scalewayprovider.go 8.5 KB

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