provider.go 9.9 KB

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