provider.go 9.9 KB

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