scalewayprovider.go 9.4 KB

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