provider.go 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  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/opencost"
  12. "github.com/opencost/opencost/core/pkg/util"
  13. "github.com/opencost/opencost/core/pkg/util/json"
  14. "github.com/opencost/opencost/pkg/clustercache"
  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) PVPricing(pvk models.PVKey) (*models.PV, error) {
  190. c.DownloadPricingDataLock.RLock()
  191. defer c.DownloadPricingDataLock.RUnlock()
  192. pricing, ok := c.Pricing[pvk.Features()]
  193. if !ok {
  194. log.Debugf("Persistent Volume pricing not found for %s: %s", pvk.GetStorageClass(), pvk.Features())
  195. return &models.PV{}, nil
  196. }
  197. return &models.PV{
  198. Cost: fmt.Sprintf("%f", pricing.PVCost),
  199. Class: pvk.GetStorageClass(),
  200. }, nil
  201. }
  202. func (c *Scaleway) ServiceAccountStatus() *models.ServiceAccountStatus {
  203. return &models.ServiceAccountStatus{
  204. Checks: []*models.ServiceAccountCheck{},
  205. }
  206. }
  207. func (*Scaleway) ClusterManagementPricing() (string, float64, error) {
  208. return "", 0.0, nil
  209. }
  210. func (c *Scaleway) CombinedDiscountForNode(instanceType string, isPreemptible bool, defaultDiscount, negotiatedDiscount float64) float64 {
  211. return 1.0 - ((1.0 - defaultDiscount) * (1.0 - negotiatedDiscount))
  212. }
  213. func (c *Scaleway) Regions() []string {
  214. regionOverrides := env.GetRegionOverrideList()
  215. if len(regionOverrides) > 0 {
  216. log.Debugf("Overriding Scaleway regions with configured region list: %+v", regionOverrides)
  217. return regionOverrides
  218. }
  219. // These are zones but hey, its 2022
  220. zones := []string{}
  221. for _, zone := range scw.AllZones {
  222. zones = append(zones, zone.String())
  223. }
  224. return zones
  225. }
  226. func (*Scaleway) ApplyReservedInstancePricing(map[string]*models.Node) {}
  227. func (*Scaleway) GetAddresses() ([]byte, error) {
  228. return nil, nil
  229. }
  230. func (*Scaleway) GetDisks() ([]byte, error) {
  231. return nil, nil
  232. }
  233. func (*Scaleway) GetOrphanedResources() ([]models.OrphanedResource, error) {
  234. return nil, errors.New("not implemented")
  235. }
  236. func (scw *Scaleway) ClusterInfo() (map[string]string, error) {
  237. remoteEnabled := env.IsRemoteEnabled()
  238. m := make(map[string]string)
  239. m["name"] = "Scaleway Cluster #1"
  240. c, err := scw.GetConfig()
  241. if err != nil {
  242. return nil, err
  243. }
  244. if c.ClusterName != "" {
  245. m["name"] = c.ClusterName
  246. }
  247. m["provider"] = opencost.ScalewayProvider
  248. m["region"] = scw.ClusterRegion
  249. m["account"] = scw.ClusterAccountID
  250. m["remoteReadEnabled"] = strconv.FormatBool(remoteEnabled)
  251. m["id"] = env.GetClusterID()
  252. return m, nil
  253. }
  254. func (c *Scaleway) UpdateConfigFromConfigMap(a map[string]string) (*models.CustomPricing, error) {
  255. return c.Config.UpdateFromMap(a)
  256. }
  257. func (c *Scaleway) UpdateConfig(r io.Reader, updateType string) (*models.CustomPricing, error) {
  258. defer c.DownloadPricingData()
  259. return c.Config.Update(func(c *models.CustomPricing) error {
  260. a := make(map[string]interface{})
  261. err := json.NewDecoder(r).Decode(&a)
  262. if err != nil {
  263. return err
  264. }
  265. for k, v := range a {
  266. kUpper := utils.ToTitle.String(k) // Just so we consistently supply / receive the same values, uppercase the first letter.
  267. vstr, ok := v.(string)
  268. if ok {
  269. err := models.SetCustomPricingField(c, kUpper, vstr)
  270. if err != nil {
  271. return fmt.Errorf("error setting custom pricing field: %w", err)
  272. }
  273. } else {
  274. return fmt.Errorf("type error while updating config for %s", kUpper)
  275. }
  276. }
  277. if env.IsRemoteEnabled() {
  278. err := utils.UpdateClusterMeta(env.GetClusterID(), c.ClusterName)
  279. if err != nil {
  280. return err
  281. }
  282. }
  283. return nil
  284. })
  285. }
  286. func (scw *Scaleway) GetConfig() (*models.CustomPricing, error) {
  287. c, err := scw.Config.GetCustomPricingData()
  288. if err != nil {
  289. return nil, err
  290. }
  291. if c.Discount == "" {
  292. c.Discount = "0%"
  293. }
  294. if c.NegotiatedDiscount == "" {
  295. c.NegotiatedDiscount = "0%"
  296. }
  297. if c.CurrencyCode == "" {
  298. c.CurrencyCode = "EUR"
  299. }
  300. return c, nil
  301. }
  302. func (scw *Scaleway) GetManagementPlatform() (string, error) {
  303. nodes := scw.Clientset.GetAllNodes()
  304. if len(nodes) > 0 {
  305. n := nodes[0]
  306. if _, ok := n.Labels["k8s.scaleway.com/kapsule"]; ok {
  307. return "kapsule", nil
  308. }
  309. if _, ok := n.Labels["kops.k8s.io/instancegroup"]; ok {
  310. return "kops", nil
  311. }
  312. }
  313. return "", nil
  314. }
  315. func (c *Scaleway) PricingSourceStatus() map[string]*models.PricingSource {
  316. return map[string]*models.PricingSource{
  317. InstanceAPIPricing: {
  318. Name: InstanceAPIPricing,
  319. Enabled: true,
  320. Available: true,
  321. },
  322. }
  323. }