provider.go 9.9 KB

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