Skip to content

Instantly share code, notes, and snippets.

@bmillemathias
Created October 16, 2024 17:00
Show Gist options
  • Select an option

  • Save bmillemathias/bd71be12e85515695ab38873b8c0d22f to your computer and use it in GitHub Desktop.

Select an option

Save bmillemathias/bd71be12e85515695ab38873b8c0d22f to your computer and use it in GitHub Desktop.
sample golang program to get Scaleway realtime consumption
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