Created
October 16, 2024 17:00
-
-
Save bmillemathias/bd71be12e85515695ab38873b8c0d22f to your computer and use it in GitHub Desktop.
sample golang program to get Scaleway realtime consumption
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package main | |
| import ( | |
| "fmt" | |
| "log" | |
| "net/http" | |
| "os" | |
| "time" | |
| "github.com/prometheus/client_golang/prometheus" | |
| "github.com/prometheus/client_golang/prometheus/promhttp" | |
| billing "github.com/scaleway/scaleway-sdk-go/api/billing/v2beta1" | |
| "github.com/scaleway/scaleway-sdk-go/scw" | |
| "github.com/davecgh/go-spew/spew" | |
| ) | |
| var ( | |
| // Define your Prometheus metrics | |
| billingUsage = prometheus.NewGaugeVec( | |
| prometheus.GaugeOpts{ | |
| Name: "scaleway_billing_usage", | |
| Help: "Current Scaleway billing usage in EUR", | |
| }, | |
| []string{"resource", "organization"}, | |
| ) | |
| ) | |
| func init() { | |
| // Register the metric with Prometheus's default registry. | |
| prometheus.MustRegister(billingUsage) | |
| } | |
| // fetchBillingData fetches the current consumption from Scaleway Billing API | |
| func fetchBillingData(client *scw.Client) { | |
| // Create a new instance of the billing API | |
| billingApi := billing.NewAPI(client) | |
| // Fetch current consumption | |
| response, err := billingApi.ListConsumptions(&billing.ListConsumptionsRequest{}) | |
| if err != nil { | |
| log.Printf("Error fetching billing data: %v\n", err) | |
| return | |
| } | |
| // Extract and set the metrics | |
| for _, consumption := range response.Consumptions { | |
| spew.Dump(consumption) | |
| // Set the gauge for the current resource's usage | |
| // billingUsage.WithLabelValues(resourceName, response.OrganizationID).Set(amount) | |
| } | |
| log.Println("=========================================================================") | |
| } | |
| func main() { | |
| // Initialize Scaleway SDK client | |
| client, err := scw.NewClient( | |
| scw.WithDefaultOrganizationID(os.Getenv("SCW_DEFAULT_ORGANIZATION_ID")), | |
| scw.WithAuth(os.Getenv("SCW_ACCESS_KEY"), os.Getenv("SCW_SECRET_KEY")), | |
| ) | |
| if err != nil { | |
| log.Fatalf("Failed to create Scaleway client: %v", err) | |
| } | |
| // Start a loop to fetch billing data periodically | |
| go func() { | |
| for { | |
| fetchBillingData(client) | |
| time.Sleep(3 * time.Minute) | |
| } | |
| }() | |
| // Expose the registered metrics via HTTP | |
| http.Handle("/metrics", promhttp.Handler()) | |
| fmt.Println("Starting server at :8080") | |
| log.Fatal(http.ListenAndServe(":8080", nil)) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment