scalewayprovider.go 9.7 KB

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