95 lines
2.3 KiB
Go
95 lines
2.3 KiB
Go
package main
|
|
|
|
import (
|
|
"encoding/csv"
|
|
"flag"
|
|
"fmt"
|
|
"log"
|
|
"os"
|
|
"sort"
|
|
"strconv"
|
|
"time"
|
|
|
|
"code.stevenpolley.net/steven/cfcleaner/cf"
|
|
)
|
|
|
|
func init() {
|
|
|
|
}
|
|
|
|
func main() {
|
|
|
|
cfAPIKey := flag.String("cfapikey", "", "in cf, my profile -> API Tokens -> Create Token")
|
|
onlyZone := flag.String("onlyZone", "", "if specified, only the zone with this name will be processed. If omitted, all zones will be processed")
|
|
outFile := flag.String("outFile", "cfcleaner.csv", "the path of the output file")
|
|
flag.Parse()
|
|
|
|
if *cfAPIKey == "" {
|
|
fmt.Println("you must specify an API key with the -cfapikey=<key> parameter")
|
|
return
|
|
}
|
|
|
|
cfClient := cf.NewClient(*cfAPIKey)
|
|
|
|
zones, err := cfClient.GetZones()
|
|
if err != nil {
|
|
log.Fatalf("failed to get zones: %v", err)
|
|
}
|
|
|
|
outRows := make([]cf.Record, 0)
|
|
|
|
for _, zone := range zones {
|
|
if *onlyZone != "" && zone.Name != *onlyZone {
|
|
continue
|
|
}
|
|
log.Printf("processing zone '%s' with ID '%s'", zone.Name, zone.ID)
|
|
|
|
analytic, err := cfClient.GetZoneAnalytic(zone)
|
|
if err != nil {
|
|
log.Printf("failed to get zone analytic for zone '%s': %v", zone.Name, err)
|
|
}
|
|
|
|
records, err := cfClient.GetRecords(zone)
|
|
if err != nil {
|
|
log.Printf("failed to get records for zone '%s' with ID '%s': %v", zone.Name, zone.ID, err)
|
|
}
|
|
|
|
for i := range records {
|
|
for _, metric := range analytic.Result.Data {
|
|
if records[i].Name != metric.Dimensions[0] {
|
|
continue
|
|
}
|
|
records[i].NumberQueries = metric.Metrics[0]
|
|
break
|
|
}
|
|
outRows = append(outRows, records[i])
|
|
}
|
|
}
|
|
|
|
sort.Slice(outRows, func(i, j int) bool {
|
|
return outRows[i].NumberQueries < outRows[j].NumberQueries
|
|
})
|
|
|
|
f, err := os.OpenFile(*outFile, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
|
|
if err != nil {
|
|
log.Fatalf("failed to open output file '%s': %v", *outFile, err)
|
|
}
|
|
defer f.Close()
|
|
|
|
writer := csv.NewWriter(f)
|
|
defer writer.Flush()
|
|
err = writer.Write([]string{"Name", "Type", "NumberQueries", "CreatedOn", "ModifiedOn", "Comment", "Content"})
|
|
if err != nil {
|
|
log.Fatalf("failed to write to outFile: %v", err)
|
|
}
|
|
|
|
for _, row := range outRows {
|
|
err = writer.Write([]string{row.Name, row.Type, strconv.Itoa(row.NumberQueries), row.CreatedOn.Format(time.RFC3339), row.ModifiedOn.Format(time.RFC3339), row.Comment, row.Content})
|
|
if err != nil {
|
|
log.Fatalf("failed to write to outFile: %v", err)
|
|
}
|
|
}
|
|
|
|
fmt.Printf("wrote to file: %s\n", *outFile)
|
|
}
|