hcloud-pricing-exporter/fetcher/server_traffic.go

58 lines
1.4 KiB
Go
Raw Normal View History

2021-03-05 18:47:23 +00:00
package fetcher
import (
"math"
"github.com/hetznercloud/hcloud-go/v2/hcloud"
2021-03-05 18:47:23 +00:00
)
var _ Fetcher = &serverTraffic{}
2021-03-05 18:53:37 +00:00
// NewServerTraffic creates a new fetcher that will collect pricing information on server traffic.
func NewServerTraffic(pricing *PriceProvider, additionalLabels ...string) Fetcher {
return &serverTraffic{newBase(pricing, "server_traffic", []string{"location", "type"}, additionalLabels...)}
2021-03-05 18:47:23 +00:00
}
type serverTraffic struct {
*baseFetcher
}
func (serverTraffic serverTraffic) Run(client *hcloud.Client) error {
2024-01-17 19:19:21 +00:00
servers, err := client.Server.All(ctx)
2021-03-05 18:47:23 +00:00
if err != nil {
return err
}
for _, s := range servers {
location := s.Datacenter.Location
labels := append([]string{
s.Name,
location.Name,
s.ServerType.Name,
},
parseAdditionalLabels(serverTraffic.additionalLabels, s.Labels)...,
)
2021-03-05 19:28:59 +00:00
additionalTraffic := int(s.OutgoingTraffic) - int(s.IncludedTraffic)
2021-03-05 18:47:23 +00:00
if additionalTraffic < 0 {
serverTraffic.hourly.WithLabelValues(labels...).Set(0)
serverTraffic.monthly.WithLabelValues(labels...).Set(0)
2021-03-05 18:47:23 +00:00
break
}
serverTrafficPrice, err := serverTraffic.pricing.ServerTraffic(s.ServerType, location.Name)
if err != nil {
return err
}
monthlyPrice := math.Ceil(float64(additionalTraffic)/sizeTB) * serverTrafficPrice
2021-03-05 18:47:23 +00:00
hourlyPrice := pricingPerHour(monthlyPrice)
serverTraffic.hourly.WithLabelValues(labels...).Set(hourlyPrice)
serverTraffic.monthly.WithLabelValues(labels...).Set(monthlyPrice)
2021-03-05 18:47:23 +00:00
}
return nil
}