forked from lablabs/cloudflare-exporter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cloudflare.go
609 lines (558 loc) · 15.4 KB
/
cloudflare.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
package main
import (
"context"
"time"
"github.com/cloudflare/cloudflare-go"
"github.com/machinebox/graphql"
log "github.com/sirupsen/logrus"
)
var (
cfGraphQLEndpoint = "https://api.cloudflare.com/client/v4/graphql/"
)
type cloudflareResponse struct {
Viewer struct {
Zones []zoneResp `json:"zones"`
} `json:"viewer"`
}
type cloudflareResponseAccts struct {
Viewer struct {
Accounts []accountResp `json:"accounts"`
} `json:"viewer"`
}
type cloudflareResponseColo struct {
Viewer struct {
Zones []zoneRespColo `json:"zones"`
} `json:"viewer"`
}
type cloudflareResponseLb struct {
Viewer struct {
Zones []lbResp `json:"zones"`
} `json:"viewer"`
}
type accountResp struct {
WorkersInvocationsAdaptive []struct {
Dimensions struct {
ScriptName string `json:"scriptName"`
Status string `json:"status"`
}
Sum struct {
Requests uint64 `json:"requests"`
Errors uint64 `json:"errors"`
Duration float64 `json:"duration"`
} `json:"sum"`
Quantiles struct {
CPUTimeP50 float32 `json:"cpuTimeP50"`
CPUTimeP75 float32 `json:"cpuTimeP75"`
CPUTimeP99 float32 `json:"cpuTimeP99"`
CPUTimeP999 float32 `json:"cpuTimeP999"`
DurationP50 float32 `json:"durationP50"`
DurationP75 float32 `json:"durationP75"`
DurationP99 float32 `json:"durationP99"`
DurationP999 float32 `json:"durationP999"`
} `json:"quantiles"`
} `json:"workersInvocationsAdaptive"`
}
type zoneRespColo struct {
ColoGroups []struct {
Dimensions struct {
Datetime string `json:"datetime"`
ColoCode string `json:"coloCode"`
Host string `json:"clientRequestHTTPHost"`
} `json:"dimensions"`
Count uint64 `json:"count"`
Sum struct {
EdgeResponseBytes uint64 `json:"edgeResponseBytes"`
Visits uint64 `json:"visits"`
} `json:"sum"`
Avg struct {
SampleInterval float64 `json:"sampleInterval"`
} `json:"avg"`
} `json:"httpRequestsAdaptiveGroups"`
ZoneTag string `json:"zoneTag"`
}
type zoneResp struct {
HTTP1mGroups []struct {
Dimensions struct {
Datetime string `json:"datetime"`
} `json:"dimensions"`
Unique struct {
Uniques uint64 `json:"uniques"`
} `json:"uniq"`
Sum struct {
Bytes uint64 `json:"bytes"`
CachedBytes uint64 `json:"cachedBytes"`
CachedRequests uint64 `json:"cachedRequests"`
Requests uint64 `json:"requests"`
BrowserMap []struct {
PageViews uint64 `json:"pageViews"`
UaBrowserFamily string `json:"uaBrowserFamily"`
} `json:"browserMap"`
ClientHTTPVersion []struct {
Protocol string `json:"clientHTTPProtocol"`
Requests uint64 `json:"requests"`
} `json:"clientHTTPVersionMap"`
ClientSSL []struct {
Protocol string `json:"clientSSLProtocol"`
} `json:"clientSSLMap"`
ContentType []struct {
Bytes uint64 `json:"bytes"`
Requests uint64 `json:"requests"`
EdgeResponseContentType string `json:"edgeResponseContentTypeName"`
} `json:"contentTypeMap"`
Country []struct {
Bytes uint64 `json:"bytes"`
ClientCountryName string `json:"clientCountryName"`
Requests uint64 `json:"requests"`
Threats uint64 `json:"threats"`
} `json:"countryMap"`
EncryptedBytes uint64 `json:"encryptedBytes"`
EncryptedRequests uint64 `json:"encryptedRequests"`
IPClass []struct {
Type string `json:"ipType"`
Requests uint64 `json:"requests"`
} `json:"ipClassMap"`
PageViews uint64 `json:"pageViews"`
ResponseStatus []struct {
EdgeResponseStatus int `json:"edgeResponseStatus"`
Requests uint64 `json:"requests"`
} `json:"responseStatusMap"`
ThreatPathing []struct {
Name string `json:"threatPathingName"`
Requests uint64 `json:"requests"`
} `json:"threatPathingMap"`
Threats uint64 `json:"threats"`
} `json:"sum"`
} `json:"httpRequests1mGroups"`
FirewallEventsAdaptiveGroups []struct {
Count uint64 `json:"count"`
Dimensions struct {
Action string `json:"action"`
Source string `json:"source"`
ClientCountryName string `json:"clientCountryName"`
ClientRequestHTTPHost string `json:"clientRequestHTTPHost"`
} `json:"dimensions"`
} `json:"firewallEventsAdaptiveGroups"`
HTTPRequestsAdaptiveGroups []struct {
Count uint64 `json:"count"`
Dimensions struct {
OriginResponseStatus uint16 `json:"originResponseStatus"`
ClientCountryName string `json:"clientCountryName"`
ClientRequestHTTPHost string `json:"clientRequestHTTPHost"`
} `json:"dimensions"`
} `json:"httpRequestsAdaptiveGroups"`
HTTPRequestsEdgeCountryHost []struct {
Count uint64 `json:"count"`
Dimensions struct {
EdgeResponseStatus uint16 `json:"edgeResponseStatus"`
ClientCountryName string `json:"clientCountryName"`
ClientRequestHTTPHost string `json:"clientRequestHTTPHost"`
} `json:"dimensions"`
} `json:"httpRequestsEdgeCountryHost"`
HealthCheckEventsAdaptiveGroups []struct {
Count uint64 `json:"count"`
Dimensions struct {
HealthStatus string `json:"healthStatus"`
OriginIP string `json:"originIP"`
FailureReason string `json:"failureReason"`
Region string `json:"region"`
Fqdn string `json:"fqdn"`
} `json:"dimensions"`
} `json:"healthCheckEventsAdaptiveGroups"`
ZoneTag string `json:"zoneTag"`
}
type lbResp struct {
LoadBalancingRequestsAdaptiveGroups []struct {
Count uint64 `json:"count"`
Dimensions struct {
LbName string `json:"lbName"`
Proxied uint8 `json:"proxied"`
Region string `json:"region"`
SelectedOriginName string `json:"selectedOriginName"`
SelectedPoolAvgRttMs uint64 `json:"selectedPoolAvgRttMs"`
SelectedPoolHealthy uint8 `json:"selectedPoolHealthy"`
SelectedPoolName string `json:"selectedPoolName"`
SteeringPolicy string `json:"steeringPolicy"`
} `json:"dimensions"`
} `json:"loadBalancingRequestsAdaptiveGroups"`
LoadBalancingRequestsAdaptive []struct {
LbName string `json:"lbName"`
Proxied uint8 `json:"proxied"`
Region string `json:"region"`
SelectedPoolHealthy uint8 `json:"selectedPoolHealthy"`
SelectedPoolID string `json:"selectedPoolID"`
SelectedPoolName string `json:"selectedPoolName"`
SessionAffinityStatus string `json:"sessionAffinityStatus"`
SteeringPolicy string `json:"steeringPolicy"`
SelectedPoolAvgRttMs uint64 `json:"selectedPoolAvgRttMs"`
Pools []struct {
AvgRttMs uint64 `json:"avgRttMs"`
Healthy uint8 `json:"healthy"`
ID string `json:"id"`
PoolName string `json:"poolName"`
} `json:"pools"`
Origins []struct {
OriginName string `json:"originName"`
Health uint8 `json:"health"`
IPv4 string `json:"ipv4"`
Selected uint8 `json:"selected"`
} `json:"origins"`
} `json:"loadBalancingRequestsAdaptive"`
ZoneTag string `json:"zoneTag"`
}
func fetchZones() []cloudflare.Zone {
var api *cloudflare.API
var err error
if len(cfgCfAPIToken) > 0 {
api, err = cloudflare.NewWithAPIToken(cfgCfAPIToken)
} else {
api, err = cloudflare.New(cfgCfAPIKey, cfgCfAPIEmail)
}
if err != nil {
log.Fatal(err)
}
ctx := context.Background()
z, err := api.ListZones(ctx)
if err != nil {
log.Fatal(err)
}
return z
}
func fetchAccounts() []cloudflare.Account {
var api *cloudflare.API
var err error
if len(cfgCfAPIToken) > 0 {
api, err = cloudflare.NewWithAPIToken(cfgCfAPIToken)
} else {
api, err = cloudflare.New(cfgCfAPIKey, cfgCfAPIEmail)
}
if err != nil {
log.Fatal(err)
}
ctx := context.Background()
a, _, err := api.Accounts(ctx, cloudflare.PaginationOptions{PerPage: 100})
if err != nil {
log.Fatal(err)
}
return a
}
func fetchZoneTotals(zoneIDs []string) (*cloudflareResponse, error) {
now := time.Now().Add(-time.Duration(cfgScrapeDelay) * time.Second).UTC()
s := 60 * time.Second
now = now.Truncate(s)
now1mAgo := now.Add(-60 * time.Second)
request := graphql.NewRequest(`
query ($zoneIDs: [String!], $mintime: Time!, $maxtime: Time!, $limit: Int!) {
viewer {
zones(filter: { zoneTag_in: $zoneIDs }) {
zoneTag
httpRequests1mGroups(limit: $limit filter: { datetime: $maxtime }) {
uniq {
uniques
}
sum {
browserMap {
pageViews
uaBrowserFamily
}
bytes
cachedBytes
cachedRequests
clientHTTPVersionMap {
clientHTTPProtocol
requests
}
clientSSLMap {
clientSSLProtocol
requests
}
contentTypeMap {
bytes
requests
edgeResponseContentTypeName
}
countryMap {
bytes
clientCountryName
requests
threats
}
encryptedBytes
encryptedRequests
ipClassMap {
ipType
requests
}
pageViews
requests
responseStatusMap {
edgeResponseStatus
requests
}
threatPathingMap {
requests
threatPathingName
}
threats
}
dimensions {
datetime
}
}
firewallEventsAdaptiveGroups(limit: $limit, filter: { datetime_geq: $mintime, datetime_lt: $maxtime }) {
count
dimensions {
action
source
clientRequestHTTPHost
clientCountryName
}
}
httpRequestsAdaptiveGroups(limit: $limit, filter: { datetime_geq: $mintime, datetime_lt: $maxtime, cacheStatus_notin: ["hit"] }) {
count
dimensions {
originResponseStatus
clientCountryName
clientRequestHTTPHost
}
}
httpRequestsEdgeCountryHost: httpRequestsAdaptiveGroups(limit: $limit, filter: { datetime_geq: $mintime, datetime_lt: $maxtime }) {
count
dimensions {
edgeResponseStatus
clientCountryName
clientRequestHTTPHost
}
}
healthCheckEventsAdaptiveGroups(limit: $limit, filter: { datetime_geq: $mintime, datetime_lt: $maxtime }) {
count
dimensions {
healthStatus
originIP
region
fqdn
}
}
}
}
}
`)
if len(cfgCfAPIToken) > 0 {
request.Header.Set("Authorization", "Bearer "+cfgCfAPIToken)
} else {
request.Header.Set("X-AUTH-EMAIL", cfgCfAPIEmail)
request.Header.Set("X-AUTH-KEY", cfgCfAPIKey)
}
request.Var("limit", 9999)
request.Var("maxtime", now)
request.Var("mintime", now1mAgo)
request.Var("zoneIDs", zoneIDs)
ctx := context.Background()
graphqlClient := graphql.NewClient(cfGraphQLEndpoint)
var resp cloudflareResponse
if err := graphqlClient.Run(ctx, request, &resp); err != nil {
log.Error(err)
return nil, err
}
return &resp, nil
}
func fetchColoTotals(zoneIDs []string) (*cloudflareResponseColo, error) {
now := time.Now().Add(-time.Duration(cfgScrapeDelay) * time.Second).UTC()
s := 60 * time.Second
now = now.Truncate(s)
now1mAgo := now.Add(-60 * time.Second)
request := graphql.NewRequest(`
query ($zoneIDs: [String!], $mintime: Time!, $maxtime: Time!, $limit: Int!) {
viewer {
zones(filter: { zoneTag_in: $zoneIDs }) {
zoneTag
httpRequestsAdaptiveGroups(
limit: $limit
filter: { datetime_geq: $mintime, datetime_lt: $maxtime }
) {
count
avg {
sampleInterval
}
dimensions {
clientRequestHTTPHost
coloCode
datetime
}
sum {
edgeResponseBytes
visits
}
}
}
}
}
`)
if len(cfgCfAPIToken) > 0 {
request.Header.Set("Authorization", "Bearer "+cfgCfAPIToken)
} else {
request.Header.Set("X-AUTH-EMAIL", cfgCfAPIEmail)
request.Header.Set("X-AUTH-KEY", cfgCfAPIKey)
}
request.Var("limit", 9999)
request.Var("maxtime", now)
request.Var("mintime", now1mAgo)
request.Var("zoneIDs", zoneIDs)
ctx := context.Background()
graphqlClient := graphql.NewClient(cfGraphQLEndpoint)
var resp cloudflareResponseColo
if err := graphqlClient.Run(ctx, request, &resp); err != nil {
log.Error(err)
return nil, err
}
return &resp, nil
}
func fetchWorkerTotals(accountID string) (*cloudflareResponseAccts, error) {
now := time.Now().Add(-time.Duration(cfgScrapeDelay) * time.Second).UTC()
s := 60 * time.Second
now = now.Truncate(s)
now1mAgo := now.Add(-60 * time.Second)
request := graphql.NewRequest(`
query ($accountID: String!, $mintime: Time!, $maxtime: Time!, $limit: Int!) {
viewer {
accounts(filter: {accountTag: $accountID} ) {
workersInvocationsAdaptive(limit: $limit, filter: { datetime_geq: $mintime, datetime_lt: $maxtime}) {
dimensions {
scriptName
status
datetime
}
sum {
requests
errors
duration
}
quantiles {
cpuTimeP50
cpuTimeP75
cpuTimeP99
cpuTimeP999
durationP50
durationP75
durationP99
durationP999
}
}
}
}
}
`)
if len(cfgCfAPIToken) > 0 {
request.Header.Set("Authorization", "Bearer "+cfgCfAPIToken)
} else {
request.Header.Set("X-AUTH-EMAIL", cfgCfAPIEmail)
request.Header.Set("X-AUTH-KEY", cfgCfAPIKey)
}
request.Var("limit", 9999)
request.Var("maxtime", now)
request.Var("mintime", now1mAgo)
request.Var("accountID", accountID)
ctx := context.Background()
graphqlClient := graphql.NewClient(cfGraphQLEndpoint)
var resp cloudflareResponseAccts
if err := graphqlClient.Run(ctx, request, &resp); err != nil {
log.Error(err)
return nil, err
}
return &resp, nil
}
func fetchLoadBalancerTotals(zoneIDs []string) (*cloudflareResponseLb, error) {
now := time.Now().Add(-time.Duration(cfgScrapeDelay) * time.Second).UTC()
s := 60 * time.Second
now = now.Truncate(s)
now1mAgo := now.Add(-60 * time.Second)
request := graphql.NewRequest(`
query ($zoneIDs: [String!], $mintime: Time!, $maxtime: Time!, $limit: Int!) {
viewer {
zones(filter: { zoneTag_in: $zoneIDs }) {
zoneTag
loadBalancingRequestsAdaptiveGroups(
filter: { datetime_geq: $mintime, datetime_lt: $maxtime},
limit: $limit) {
count
dimensions {
region
lbName
selectedPoolName
proxied
selectedOriginName
selectedPoolAvgRttMs
selectedPoolHealthy
steeringPolicy
}
}
loadBalancingRequestsAdaptive(
filter: { datetime_geq: $mintime, datetime_lt: $maxtime},
limit: $limit) {
lbName
proxied
region
selectedPoolHealthy
selectedPoolId
selectedPoolName
sessionAffinityStatus
steeringPolicy
selectedPoolAvgRttMs
pools {
id
poolName
healthy
avgRttMs
}
origins {
originName
health
ipv4
selected
}
}
}
}
}
`)
if len(cfgCfAPIToken) > 0 {
request.Header.Set("Authorization", "Bearer "+cfgCfAPIToken)
} else {
request.Header.Set("X-AUTH-EMAIL", cfgCfAPIEmail)
request.Header.Set("X-AUTH-KEY", cfgCfAPIKey)
}
request.Var("limit", 9999)
request.Var("maxtime", now)
request.Var("mintime", now1mAgo)
request.Var("zoneIDs", zoneIDs)
ctx := context.Background()
graphqlClient := graphql.NewClient(cfGraphQLEndpoint)
var resp cloudflareResponseLb
if err := graphqlClient.Run(ctx, request, &resp); err != nil {
log.Error(err)
return nil, err
}
return &resp, nil
}
func findZoneName(zones []cloudflare.Zone, ID string) string {
for _, z := range zones {
if z.ID == ID {
return z.Name
}
}
return ""
}
func extractZoneIDs(zones []cloudflare.Zone) []string {
var IDs []string
for _, z := range zones {
IDs = append(IDs, z.ID)
}
return IDs
}
func filterNonFreePlanZones(zones []cloudflare.Zone) (filteredZones []cloudflare.Zone) {
for _, z := range zones {
if z.Plan.ZonePlanCommon.ID != "0feeeeeeeeeeeeeeeeeeeeeeeeeeeeee" {
filteredZones = append(filteredZones, z)
}
}
return
}