Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

backfill missed data due to error from querying analytics #88

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
70 changes: 34 additions & 36 deletions cloudflare.go
Original file line number Diff line number Diff line change
Expand Up @@ -221,6 +221,11 @@ type lbResp struct {
ZoneTag string `json:"zoneTag"`
}

func getTruncatedNow() time.Time {
// truncate datetime down to YYYY-mm-dd HH:MM:00.000
return time.Now().Add(-time.Duration(cfgScrapeDelay) * time.Second).Truncate(time.Minute).UTC()
}

func fetchZones() []cloudflare.Zone {
var api *cloudflare.API
var err error
Expand Down Expand Up @@ -263,18 +268,15 @@ func fetchAccounts() []cloudflare.Account {
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)
func fetchZoneTotals(zoneIDs []string, lastSuccessfulTime *time.Time) (*cloudflareResponse, error) {
truncatedNow := getTruncatedNow()

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 }) {
httpRequests1mGroups(limit: $limit filter: { datetime_geq: $mintime, datetime_lt: $maxtime }) {
uniq {
uniques
}
Expand Down Expand Up @@ -372,27 +374,25 @@ query ($zoneIDs: [String!], $mintime: Time!, $maxtime: Time!, $limit: Int!) {
request.Header.Set("X-AUTH-KEY", cfgCfAPIKey)
}
request.Var("limit", 9999)
request.Var("maxtime", now)
request.Var("mintime", now1mAgo)
request.Var("maxtime", truncatedNow)
request.Var("mintime", *lastSuccessfulTime)
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)
log.Errorf("%s: from %s to %s", err, *lastSuccessfulTime, truncatedNow)
return nil, err
}

log.Debugf("successful from %s to %s", *lastSuccessfulTime, truncatedNow)
*lastSuccessfulTime = truncatedNow
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)
func fetchColoTotals(zoneIDs []string, lastSuccessfulTime *time.Time) (*cloudflareResponseColo, error) {
truncatedNow := getTruncatedNow()

request := graphql.NewRequest(`
query ($zoneIDs: [String!], $mintime: Time!, $maxtime: Time!, $limit: Int!) {
Expand Down Expand Up @@ -428,26 +428,24 @@ func fetchColoTotals(zoneIDs []string) (*cloudflareResponseColo, error) {
request.Header.Set("X-AUTH-KEY", cfgCfAPIKey)
}
request.Var("limit", 9999)
request.Var("maxtime", now)
request.Var("mintime", now1mAgo)
request.Var("maxtime", truncatedNow)
request.Var("mintime", *lastSuccessfulTime)
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)
log.Errorf("%s: from %s to %s", err, *lastSuccessfulTime, truncatedNow)
return nil, err
}

log.Debugf("successful from %s to %s", *lastSuccessfulTime, truncatedNow)
*lastSuccessfulTime = truncatedNow
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)
func fetchWorkerTotals(accountID string, lastSuccessfulTime *time.Time) (*cloudflareResponseAccts, error) {
truncatedNow := getTruncatedNow()

request := graphql.NewRequest(`
query ($accountID: String!, $mintime: Time!, $maxtime: Time!, $limit: Int!) {
Expand Down Expand Up @@ -488,26 +486,24 @@ func fetchWorkerTotals(accountID string) (*cloudflareResponseAccts, error) {
request.Header.Set("X-AUTH-KEY", cfgCfAPIKey)
}
request.Var("limit", 9999)
request.Var("maxtime", now)
request.Var("mintime", now1mAgo)
request.Var("maxtime", truncatedNow)
request.Var("mintime", *lastSuccessfulTime)
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)
log.Errorf("%s: from %s to %s", err, *lastSuccessfulTime, truncatedNow)
return nil, err
}

log.Debugf("successful from %s to %s", *lastSuccessfulTime, truncatedNow)
*lastSuccessfulTime = truncatedNow
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)
func fetchLoadBalancerTotals(zoneIDs []string, lastSuccessfulTime *time.Time) (*cloudflareResponseLb, error) {
truncatedNow := getTruncatedNow()

request := graphql.NewRequest(`
query ($zoneIDs: [String!], $mintime: Time!, $maxtime: Time!, $limit: Int!) {
Expand Down Expand Up @@ -565,17 +561,19 @@ func fetchLoadBalancerTotals(zoneIDs []string) (*cloudflareResponseLb, error) {
request.Header.Set("X-AUTH-KEY", cfgCfAPIKey)
}
request.Var("limit", 9999)
request.Var("maxtime", now)
request.Var("mintime", now1mAgo)
request.Var("maxtime", truncatedNow)
request.Var("mintime", *lastSuccessfulTime)
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)
log.Errorf("%s: from %s to %s", err, *lastSuccessfulTime, truncatedNow)
return nil, err
}
log.Debugf("successful from %s to %s", *lastSuccessfulTime, truncatedNow)
*lastSuccessfulTime = truncatedNow
return &resp, nil
}

Expand Down
92 changes: 74 additions & 18 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,22 @@ var (
cfgFreeTier = false
cfgBatchSize = 10
cfgMetricsDenylist = ""
cfgLogLevel = "info"
)

type AccountJob struct {
Account cloudflare.Account
LastSuccessfulTime time.Time
}

type BatchedZonesJob struct {
Zones []cloudflare.Zone
LastSuccessfulTime time.Time
}

var (
cfAccounts []cloudflare.Account
cfFilteredZones []cloudflare.Zone
)

func getTargetZones() []string {
Expand Down Expand Up @@ -100,33 +116,62 @@ func filterExcludedZones(all []cloudflare.Zone, exclude []string) []cloudflare.Z
return filtered
}

func fetchMetrics() {
func fetchMetrics(fetchWorkerAnalyticsJobs []AccountJob, fetchZoneAnalyticsJobs []BatchedZonesJob, fetchZoneColocationAnalyticsJobs []BatchedZonesJob, fetchLoadBalancerAnalyticsJobs []BatchedZonesJob) {
var wg sync.WaitGroup
zones := fetchZones()
accounts := fetchAccounts()
filteredZones := filterExcludedZones(filterZones(zones, getTargetZones()), getExcludedZones())

for _, a := range accounts {
go fetchWorkerAnalytics(a, &wg)
for i := range fetchWorkerAnalyticsJobs {
job := &fetchWorkerAnalyticsJobs[i]
go fetchWorkerAnalytics(job.Account, &wg, &job.LastSuccessfulTime)
}

for i := range fetchZoneAnalyticsJobs {
job := &fetchZoneAnalyticsJobs[i]
go fetchZoneAnalytics(job.Zones, &wg, &job.LastSuccessfulTime)
}
for i := range fetchZoneColocationAnalyticsJobs {
job := &fetchZoneColocationAnalyticsJobs[i]
go fetchZoneColocationAnalytics(job.Zones, &wg, &job.LastSuccessfulTime)
}
for i := range fetchLoadBalancerAnalyticsJobs {
job := &fetchLoadBalancerAnalyticsJobs[i]
go fetchLoadBalancerAnalytics(job.Zones, &wg, &job.LastSuccessfulTime)
}

wg.Wait()
}

func prepareExporterBatchJobs() []BatchedZonesJob {
jobs := []BatchedZonesJob{}
filteredZones := cfFilteredZones
lastNow := getTruncatedNow().Add(-time.Minute)
// Make requests in groups of cfgBatchSize to avoid rate limit
// 10 is the maximum amount of zones you can request at once
for len(filteredZones) > 0 {
sliceLength := cfgBatchSize
if len(filteredZones) < cfgBatchSize {
sliceLength = len(filteredZones)
}

targetZones := filteredZones[:sliceLength]
filteredZones = filteredZones[len(targetZones):]

go fetchZoneAnalytics(targetZones, &wg)
go fetchZoneColocationAnalytics(targetZones, &wg)
go fetchLoadBalancerAnalytics(targetZones, &wg)
jobs = append(jobs, BatchedZonesJob{
Zones: targetZones,
LastSuccessfulTime: lastNow,
})
filteredZones = filteredZones[sliceLength:]
}
return jobs
}

wg.Wait()
func prepareAccountJobs() []AccountJob {
jobs := []AccountJob{}
lastSuccessfulTime := getTruncatedNow().Add(-time.Minute)
for i := range cfAccounts {
cfAccount := &cfAccounts[i]
jobs = append(jobs, AccountJob{
Account: *cfAccount,
LastSuccessfulTime: lastSuccessfulTime,
})
}
return jobs
}

func main() {
Expand All @@ -141,17 +186,21 @@ func main() {
flag.IntVar(&cfgBatchSize, "cf_batch_size", cfgBatchSize, "cloudflare zones batch size (1-10), defaults to 10")
flag.BoolVar(&cfgFreeTier, "free_tier", cfgFreeTier, "scrape only metrics included in free plan")
flag.StringVar(&cfgMetricsDenylist, "metrics_denylist", cfgMetricsDenylist, "metrics to not expose, comma delimited list")
flag.StringVar(&cfgLogLevel, "log_level", cfgLogLevel, "log level, default to warning")
flag.Parse()
if !(len(cfgCfAPIToken) > 0 || (len(cfgCfAPIEmail) > 0 && len(cfgCfAPIKey) > 0)) {
log.Fatal("Please provide CF_API_KEY+CF_API_EMAIL or CF_API_TOKEN")
}
if cfgBatchSize < 1 || cfgBatchSize > 10 {
log.Fatal("CF_BATCH_SIZE must be between 1 and 10")
}
customFormatter := new(log.TextFormatter)
customFormatter.TimestampFormat = "2006-01-02 15:04:05"
customFormatter := new(log.JSONFormatter)
customFormatter.TimestampFormat = "2006-01-02 15:04:05.000"
log.SetFormatter(customFormatter)
customFormatter.FullTimestamp = true
log.SetReportCaller(true)
if parsedLogLevel, err := log.ParseLevel(cfgLogLevel); err == nil {
log.SetLevel(parsedLogLevel)
}

metricsDenylist := []string{}
if len(cfgMetricsDenylist) > 0 {
Expand All @@ -163,9 +212,16 @@ func main() {
}
mustRegisterMetrics(deniedMetricsSet)

cfAccounts = fetchAccounts()
cfFilteredZones = filterExcludedZones(filterZones(fetchZones(), getTargetZones()), getExcludedZones())
go func() {
for ; true; <-time.NewTicker(60 * time.Second).C {
go fetchMetrics()
fetchWorkerAnalyticsJobs := prepareAccountJobs()
fetchZoneAnalyticsJobs := prepareExporterBatchJobs()
fetchZoneColocationAnalyticsJobs := prepareExporterBatchJobs()
fetchLoadBalancerAnalyticsJobs := prepareExporterBatchJobs()

for ; true; <-time.NewTicker(time.Minute).C {
go fetchMetrics(fetchWorkerAnalyticsJobs, fetchZoneAnalyticsJobs, fetchZoneColocationAnalyticsJobs, fetchLoadBalancerAnalyticsJobs)
}
}()

Expand Down
Loading