2
0

provider.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  1. package scaleway
  2. import (
  3. "errors"
  4. "fmt"
  5. "io"
  6. "strconv"
  7. "strings"
  8. "sync"
  9. coreenv "github.com/opencost/opencost/core/pkg/env"
  10. "github.com/opencost/opencost/pkg/cloud/models"
  11. "github.com/opencost/opencost/pkg/cloud/utils"
  12. "github.com/opencost/opencost/core/pkg/clustercache"
  13. "github.com/opencost/opencost/core/pkg/opencost"
  14. "github.com/opencost/opencost/core/pkg/util"
  15. "github.com/opencost/opencost/core/pkg/util/json"
  16. "github.com/opencost/opencost/pkg/env"
  17. "github.com/opencost/opencost/core/pkg/log"
  18. "github.com/scaleway/scaleway-sdk-go/api/instance/v1"
  19. "github.com/scaleway/scaleway-sdk-go/scw"
  20. )
  21. const (
  22. InstanceAPIPricing = "Instance API Pricing"
  23. )
  24. type ScalewayPricing struct {
  25. NodesInfos map[string]*instance.ServerType
  26. PVCost float64
  27. }
  28. type Scaleway struct {
  29. Clientset clustercache.ClusterCache
  30. Config models.ProviderConfig
  31. Pricing map[string]*ScalewayPricing
  32. ClusterRegion string
  33. ClusterAccountID string
  34. DownloadPricingDataLock sync.RWMutex
  35. }
  36. // PricingSourceSummary returns the pricing source summary for the provider.
  37. // The summary represents what was _parsed_ from the pricing source, not
  38. // everything that was _available_ in the pricing source.
  39. func (c *Scaleway) PricingSourceSummary() interface{} {
  40. return c.Pricing
  41. }
  42. func (c *Scaleway) DownloadPricingData() error {
  43. c.DownloadPricingDataLock.Lock()
  44. defer c.DownloadPricingDataLock.Unlock()
  45. // TODO wait for an official Pricing API from Scaleway
  46. // Let's use a static map and an old API
  47. if len(c.Pricing) != 0 {
  48. // Already initialized
  49. return nil
  50. }
  51. // PV pricing per AZ
  52. pvPrice := map[string]float64{
  53. "fr-par-1": 0.00011,
  54. "fr-par-2": 0.00011,
  55. "fr-par-3": 0.00032,
  56. "nl-ams-1": 0.00008,
  57. "nl-ams-2": 0.00008,
  58. "nl-ams-3": 0.00008,
  59. "pl-waw-1": 0.00011,
  60. "pl-waw-2": 0.00011,
  61. "pl-waw-3": 0.00011,
  62. }
  63. c.Pricing = make(map[string]*ScalewayPricing)
  64. // The endpoint we are trying to hit does not have authentication
  65. client, err := scw.NewClient(scw.WithoutAuth())
  66. if err != nil {
  67. return err
  68. }
  69. instanceAPI := instance.NewAPI(client)
  70. for _, zone := range scw.AllZones {
  71. resp, err := instanceAPI.ListServersTypes(&instance.ListServersTypesRequest{Zone: zone})
  72. if err != nil {
  73. log.Errorf("Could not get Scaleway pricing data from instance API in zone %s: %+v", zone, err)
  74. continue
  75. }
  76. c.Pricing[zone.String()] = &ScalewayPricing{
  77. PVCost: pvPrice[zone.String()],
  78. NodesInfos: map[string]*instance.ServerType{},
  79. }
  80. for name, infos := range resp.Servers {
  81. c.Pricing[zone.String()].NodesInfos[name] = infos
  82. }
  83. }
  84. return nil
  85. }
  86. func (c *Scaleway) AllNodePricing() (interface{}, error) {
  87. c.DownloadPricingDataLock.RLock()
  88. defer c.DownloadPricingDataLock.RUnlock()
  89. return c.Pricing, nil
  90. }
  91. type scalewayKey struct {
  92. Labels map[string]string
  93. }
  94. func (k *scalewayKey) Features() string {
  95. instanceType, _ := util.GetInstanceType(k.Labels)
  96. zone, _ := util.GetZone(k.Labels)
  97. return zone + "," + instanceType
  98. }
  99. func (k *scalewayKey) GPUCount() int {
  100. return 0
  101. }
  102. func (k *scalewayKey) GPUType() string {
  103. instanceType, _ := util.GetInstanceType(k.Labels)
  104. if strings.HasPrefix(instanceType, "RENDER") || strings.HasPrefix(instanceType, "GPU") {
  105. return instanceType
  106. }
  107. return ""
  108. }
  109. func (k *scalewayKey) ID() string {
  110. return ""
  111. }
  112. func (c *Scaleway) NodePricing(key models.Key) (*models.Node, models.PricingMetadata, error) {
  113. c.DownloadPricingDataLock.RLock()
  114. defer c.DownloadPricingDataLock.RUnlock()
  115. meta := models.PricingMetadata{}
  116. // There is only the zone and the instance ID in the providerID, hence we must use the features
  117. split := strings.Split(key.Features(), ",")
  118. if pricing, ok := c.Pricing[split[0]]; ok {
  119. if info, ok := pricing.NodesInfos[split[1]]; ok {
  120. return &models.Node{
  121. Cost: fmt.Sprintf("%f", info.HourlyPrice),
  122. PricingType: models.DefaultPrices,
  123. VCPU: fmt.Sprintf("%d", info.Ncpus),
  124. RAM: fmt.Sprintf("%d", info.RAM),
  125. // This is tricky, as instances can have local volumes or not
  126. Storage: fmt.Sprintf("%d", info.PerVolumeConstraint.LSSD.MinSize),
  127. GPU: fmt.Sprintf("%d", *info.Gpu),
  128. InstanceType: split[1],
  129. Region: split[0],
  130. GPUName: key.GPUType(),
  131. }, meta, nil
  132. }
  133. }
  134. return nil, meta, fmt.Errorf("Unable to find node pricing matching thes features `%s`", key.Features())
  135. }
  136. func (c *Scaleway) LoadBalancerPricing() (*models.LoadBalancer, error) {
  137. // Different LB types, lets take the cheaper for now, we can't get the type
  138. // without a service specifying the type in the annotations
  139. return &models.LoadBalancer{
  140. Cost: 0.014,
  141. }, nil
  142. }
  143. func (c *Scaleway) NetworkPricing() (*models.Network, error) {
  144. // it's free baby!
  145. return &models.Network{
  146. ZoneNetworkEgressCost: 0,
  147. RegionNetworkEgressCost: 0,
  148. InternetNetworkEgressCost: 0,
  149. NatGatewayEgressCost: 0,
  150. NatGatewayIngressCost: 0,
  151. }, nil
  152. }
  153. func (c *Scaleway) GetKey(l map[string]string, n *clustercache.Node) models.Key {
  154. return &scalewayKey{
  155. Labels: l,
  156. }
  157. }
  158. type scalewayPVKey struct {
  159. Labels map[string]string
  160. StorageClassName string
  161. StorageClassParameters map[string]string
  162. Name string
  163. Zone string
  164. }
  165. func (key *scalewayPVKey) ID() string {
  166. return ""
  167. }
  168. func (key *scalewayPVKey) GetStorageClass() string {
  169. return key.StorageClassName
  170. }
  171. func (key *scalewayPVKey) Features() string {
  172. // Only 1 type of PV for now
  173. return key.Zone
  174. }
  175. func (c *Scaleway) GetPVKey(pv *clustercache.PersistentVolume, parameters map[string]string, defaultRegion string) models.PVKey {
  176. // the csi volume handle is the form <az>/<volume-id>
  177. zone := ""
  178. if pv.Spec.CSI != nil {
  179. zoneVolID := strings.Split(pv.Spec.CSI.VolumeHandle, "/")
  180. if len(zoneVolID) > 0 {
  181. zone = zoneVolID[0]
  182. }
  183. }
  184. return &scalewayPVKey{
  185. Labels: pv.Labels,
  186. StorageClassName: pv.Spec.StorageClassName,
  187. StorageClassParameters: parameters,
  188. Name: pv.Name,
  189. Zone: zone,
  190. }
  191. }
  192. func (c *Scaleway) GpuPricing(nodeLabels map[string]string) (string, error) {
  193. return "", nil
  194. }
  195. func (c *Scaleway) PVPricing(pvk models.PVKey) (*models.PV, error) {
  196. c.DownloadPricingDataLock.RLock()
  197. defer c.DownloadPricingDataLock.RUnlock()
  198. pricing, ok := c.Pricing[pvk.Features()]
  199. if !ok {
  200. log.Debugf("Persistent Volume pricing not found for %s: %s", pvk.GetStorageClass(), pvk.Features())
  201. return &models.PV{}, nil
  202. }
  203. return &models.PV{
  204. Cost: fmt.Sprintf("%f", pricing.PVCost),
  205. Class: pvk.GetStorageClass(),
  206. }, nil
  207. }
  208. func (c *Scaleway) ServiceAccountStatus() *models.ServiceAccountStatus {
  209. return &models.ServiceAccountStatus{
  210. Checks: []*models.ServiceAccountCheck{},
  211. }
  212. }
  213. func (*Scaleway) ClusterManagementPricing() (string, float64, error) {
  214. return "", 0.0, nil
  215. }
  216. func (c *Scaleway) CombinedDiscountForNode(instanceType string, isPreemptible bool, defaultDiscount, negotiatedDiscount float64) float64 {
  217. return 1.0 - ((1.0 - defaultDiscount) * (1.0 - negotiatedDiscount))
  218. }
  219. func (c *Scaleway) Regions() []string {
  220. regionOverrides := env.GetRegionOverrideList()
  221. if len(regionOverrides) > 0 {
  222. log.Debugf("Overriding Scaleway regions with configured region list: %+v", regionOverrides)
  223. return regionOverrides
  224. }
  225. // These are zones but hey, its 2022
  226. zones := []string{}
  227. for _, zone := range scw.AllZones {
  228. zones = append(zones, zone.String())
  229. }
  230. return zones
  231. }
  232. func (*Scaleway) ApplyReservedInstancePricing(map[string]*models.Node) {}
  233. func (*Scaleway) GetAddresses() ([]byte, error) {
  234. return nil, nil
  235. }
  236. func (*Scaleway) GetDisks() ([]byte, error) {
  237. return nil, nil
  238. }
  239. func (*Scaleway) GetOrphanedResources() ([]models.OrphanedResource, error) {
  240. return nil, errors.New("not implemented")
  241. }
  242. func (scw *Scaleway) ClusterInfo() (map[string]string, error) {
  243. remoteEnabled := env.IsRemoteEnabled()
  244. m := make(map[string]string)
  245. m["name"] = "Scaleway Cluster #1"
  246. c, err := scw.GetConfig()
  247. if err != nil {
  248. return nil, err
  249. }
  250. if c.ClusterName != "" {
  251. m["name"] = c.ClusterName
  252. }
  253. m["provider"] = opencost.ScalewayProvider
  254. m["region"] = scw.ClusterRegion
  255. m["account"] = scw.ClusterAccountID
  256. m["remoteReadEnabled"] = strconv.FormatBool(remoteEnabled)
  257. m["id"] = coreenv.GetClusterID()
  258. return m, nil
  259. }
  260. func (c *Scaleway) UpdateConfigFromConfigMap(a map[string]string) (*models.CustomPricing, error) {
  261. return c.Config.UpdateFromMap(a)
  262. }
  263. func (c *Scaleway) UpdateConfig(r io.Reader, updateType string) (*models.CustomPricing, error) {
  264. defer c.DownloadPricingData()
  265. return c.Config.Update(func(c *models.CustomPricing) error {
  266. a := make(map[string]interface{})
  267. err := json.NewDecoder(r).Decode(&a)
  268. if err != nil {
  269. return err
  270. }
  271. for k, v := range a {
  272. kUpper := utils.ToTitle.String(k) // Just so we consistently supply / receive the same values, uppercase the first letter.
  273. vstr, ok := v.(string)
  274. if ok {
  275. err := models.SetCustomPricingField(c, kUpper, vstr)
  276. if err != nil {
  277. return fmt.Errorf("error setting custom pricing field: %w", err)
  278. }
  279. } else {
  280. return fmt.Errorf("type error while updating config for %s", kUpper)
  281. }
  282. }
  283. if env.IsRemoteEnabled() {
  284. err := utils.UpdateClusterMeta(coreenv.GetClusterID(), c.ClusterName)
  285. if err != nil {
  286. return err
  287. }
  288. }
  289. return nil
  290. })
  291. }
  292. func (scw *Scaleway) GetConfig() (*models.CustomPricing, error) {
  293. c, err := scw.Config.GetCustomPricingData()
  294. if err != nil {
  295. return nil, err
  296. }
  297. if c.Discount == "" {
  298. c.Discount = "0%"
  299. }
  300. if c.NegotiatedDiscount == "" {
  301. c.NegotiatedDiscount = "0%"
  302. }
  303. if c.CurrencyCode == "" {
  304. c.CurrencyCode = "EUR"
  305. }
  306. return c, nil
  307. }
  308. func (scw *Scaleway) GetManagementPlatform() (string, error) {
  309. nodes := scw.Clientset.GetAllNodes()
  310. if len(nodes) > 0 {
  311. n := nodes[0]
  312. if _, ok := n.Labels["k8s.scaleway.com/kapsule"]; ok {
  313. return "kapsule", nil
  314. }
  315. if _, ok := n.Labels["kops.k8s.io/instancegroup"]; ok {
  316. return "kops", nil
  317. }
  318. }
  319. return "", nil
  320. }
  321. func (c *Scaleway) PricingSourceStatus() map[string]*models.PricingSource {
  322. return map[string]*models.PricingSource{
  323. InstanceAPIPricing: {
  324. Name: InstanceAPIPricing,
  325. Enabled: true,
  326. Available: true,
  327. },
  328. }
  329. }