provider.go 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  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. }, nil
  150. }
  151. func (c *Scaleway) GetKey(l map[string]string, n *clustercache.Node) models.Key {
  152. return &scalewayKey{
  153. Labels: l,
  154. }
  155. }
  156. type scalewayPVKey struct {
  157. Labels map[string]string
  158. StorageClassName string
  159. StorageClassParameters map[string]string
  160. Name string
  161. Zone string
  162. }
  163. func (key *scalewayPVKey) ID() string {
  164. return ""
  165. }
  166. func (key *scalewayPVKey) GetStorageClass() string {
  167. return key.StorageClassName
  168. }
  169. func (key *scalewayPVKey) Features() string {
  170. // Only 1 type of PV for now
  171. return key.Zone
  172. }
  173. func (c *Scaleway) GetPVKey(pv *clustercache.PersistentVolume, parameters map[string]string, defaultRegion string) models.PVKey {
  174. // the csi volume handle is the form <az>/<volume-id>
  175. zone := ""
  176. if pv.Spec.CSI != nil {
  177. zoneVolID := strings.Split(pv.Spec.CSI.VolumeHandle, "/")
  178. if len(zoneVolID) > 0 {
  179. zone = zoneVolID[0]
  180. }
  181. }
  182. return &scalewayPVKey{
  183. Labels: pv.Labels,
  184. StorageClassName: pv.Spec.StorageClassName,
  185. StorageClassParameters: parameters,
  186. Name: pv.Name,
  187. Zone: zone,
  188. }
  189. }
  190. func (c *Scaleway) GpuPricing(nodeLabels map[string]string) (string, error) {
  191. return "", nil
  192. }
  193. func (c *Scaleway) PVPricing(pvk models.PVKey) (*models.PV, error) {
  194. c.DownloadPricingDataLock.RLock()
  195. defer c.DownloadPricingDataLock.RUnlock()
  196. pricing, ok := c.Pricing[pvk.Features()]
  197. if !ok {
  198. log.Debugf("Persistent Volume pricing not found for %s: %s", pvk.GetStorageClass(), pvk.Features())
  199. return &models.PV{}, nil
  200. }
  201. return &models.PV{
  202. Cost: fmt.Sprintf("%f", pricing.PVCost),
  203. Class: pvk.GetStorageClass(),
  204. }, nil
  205. }
  206. func (c *Scaleway) ServiceAccountStatus() *models.ServiceAccountStatus {
  207. return &models.ServiceAccountStatus{
  208. Checks: []*models.ServiceAccountCheck{},
  209. }
  210. }
  211. func (*Scaleway) ClusterManagementPricing() (string, float64, error) {
  212. return "", 0.0, nil
  213. }
  214. func (c *Scaleway) CombinedDiscountForNode(instanceType string, isPreemptible bool, defaultDiscount, negotiatedDiscount float64) float64 {
  215. return 1.0 - ((1.0 - defaultDiscount) * (1.0 - negotiatedDiscount))
  216. }
  217. func (c *Scaleway) Regions() []string {
  218. regionOverrides := env.GetRegionOverrideList()
  219. if len(regionOverrides) > 0 {
  220. log.Debugf("Overriding Scaleway regions with configured region list: %+v", regionOverrides)
  221. return regionOverrides
  222. }
  223. // These are zones but hey, its 2022
  224. zones := []string{}
  225. for _, zone := range scw.AllZones {
  226. zones = append(zones, zone.String())
  227. }
  228. return zones
  229. }
  230. func (*Scaleway) ApplyReservedInstancePricing(map[string]*models.Node) {}
  231. func (*Scaleway) GetAddresses() ([]byte, error) {
  232. return nil, nil
  233. }
  234. func (*Scaleway) GetDisks() ([]byte, error) {
  235. return nil, nil
  236. }
  237. func (*Scaleway) GetOrphanedResources() ([]models.OrphanedResource, error) {
  238. return nil, errors.New("not implemented")
  239. }
  240. func (scw *Scaleway) ClusterInfo() (map[string]string, error) {
  241. remoteEnabled := env.IsRemoteEnabled()
  242. m := make(map[string]string)
  243. m["name"] = "Scaleway Cluster #1"
  244. c, err := scw.GetConfig()
  245. if err != nil {
  246. return nil, err
  247. }
  248. if c.ClusterName != "" {
  249. m["name"] = c.ClusterName
  250. }
  251. m["provider"] = opencost.ScalewayProvider
  252. m["region"] = scw.ClusterRegion
  253. m["account"] = scw.ClusterAccountID
  254. m["remoteReadEnabled"] = strconv.FormatBool(remoteEnabled)
  255. m["id"] = coreenv.GetClusterID()
  256. return m, nil
  257. }
  258. func (c *Scaleway) UpdateConfigFromConfigMap(a map[string]string) (*models.CustomPricing, error) {
  259. return c.Config.UpdateFromMap(a)
  260. }
  261. func (c *Scaleway) UpdateConfig(r io.Reader, updateType string) (*models.CustomPricing, error) {
  262. defer c.DownloadPricingData()
  263. return c.Config.Update(func(c *models.CustomPricing) error {
  264. a := make(map[string]interface{})
  265. err := json.NewDecoder(r).Decode(&a)
  266. if err != nil {
  267. return err
  268. }
  269. for k, v := range a {
  270. kUpper := utils.ToTitle.String(k) // Just so we consistently supply / receive the same values, uppercase the first letter.
  271. vstr, ok := v.(string)
  272. if ok {
  273. err := models.SetCustomPricingField(c, kUpper, vstr)
  274. if err != nil {
  275. return fmt.Errorf("error setting custom pricing field: %w", err)
  276. }
  277. } else {
  278. return fmt.Errorf("type error while updating config for %s", kUpper)
  279. }
  280. }
  281. if env.IsRemoteEnabled() {
  282. err := utils.UpdateClusterMeta(coreenv.GetClusterID(), c.ClusterName)
  283. if err != nil {
  284. return err
  285. }
  286. }
  287. return nil
  288. })
  289. }
  290. func (scw *Scaleway) GetConfig() (*models.CustomPricing, error) {
  291. c, err := scw.Config.GetCustomPricingData()
  292. if err != nil {
  293. return nil, err
  294. }
  295. if c.Discount == "" {
  296. c.Discount = "0%"
  297. }
  298. if c.NegotiatedDiscount == "" {
  299. c.NegotiatedDiscount = "0%"
  300. }
  301. if c.CurrencyCode == "" {
  302. c.CurrencyCode = "EUR"
  303. }
  304. return c, nil
  305. }
  306. func (scw *Scaleway) GetManagementPlatform() (string, error) {
  307. nodes := scw.Clientset.GetAllNodes()
  308. if len(nodes) > 0 {
  309. n := nodes[0]
  310. if _, ok := n.Labels["k8s.scaleway.com/kapsule"]; ok {
  311. return "kapsule", nil
  312. }
  313. if _, ok := n.Labels["kops.k8s.io/instancegroup"]; ok {
  314. return "kops", nil
  315. }
  316. }
  317. return "", nil
  318. }
  319. func (c *Scaleway) PricingSourceStatus() map[string]*models.PricingSource {
  320. return map[string]*models.PricingSource{
  321. InstanceAPIPricing: {
  322. Name: InstanceAPIPricing,
  323. Enabled: true,
  324. Available: true,
  325. },
  326. }
  327. }