-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathlogpull.go
85 lines (72 loc) · 1.99 KB
/
logpull.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
package main
import (
"context"
"encoding/json"
"fmt"
"time"
"github.com/cloudflare/cloudflare-go"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
)
const fileName = "lastProcessed.txt"
const maxLookBack = 360 // 6 hours in minutes
var (
logsProcessed = promauto.NewCounter(prometheus.CounterOpts{
Name: "cloudflare_audit_logs_processed_total",
Help: "The total number of processed events",
})
)
// Get audit logs and process them until no more records are returned
func getAuditLogs(apiKey, apiEmail, orgId, s3Bucket string, lookBack int) error {
api, err := cloudflare.New(apiKey, apiEmail)
if err != nil {
return fmt.Errorf("error creating Cloudflare API client: %v", err)
}
ctx := context.Background()
userDetails, err := api.UserDetails(ctx)
if err != nil {
return err
}
if len(userDetails.Email) == 0 {
return nil
}
var searchUntil time.Time
if len(s3Bucket) > 0 {
searchUntil, err = getLastProcessedTimeFromS3(lookBack, s3Bucket, fileName)
} else {
searchUntil, err = getLastProcessedTime(lookBack, fileName)
}
if err != nil {
return err
}
if err := processAuditLogs(ctx, api, orgId, searchUntil); err != nil {
return err
}
if len(s3Bucket) > 0 {
return storeLastProcessedTimeToS3(time.Now(), s3Bucket, fileName)
}
return storeLastProcessedTimeToDisk(time.Now(), fileName)
}
func processAuditLogs(ctx context.Context, api *cloudflare.API, orgId string, searchUntil time.Time) error {
pageNumber := 1
for {
filterOpts := cloudflare.AuditLogFilter{Since: searchUntil.Format(time.RFC3339), Page: pageNumber}
results, err := api.GetOrganizationAuditLogs(ctx, orgId, filterOpts)
if err != nil {
return fmt.Errorf("error getting audit logs: %v", err)
}
if len(results.Result) == 0 {
break
}
for _, record := range results.Result {
b, err := json.Marshal(record)
if err != nil {
return err
}
logsProcessed.Inc()
fmt.Println(string(b))
}
pageNumber++
}
return nil
}