scalewayprovider.go 8.6 KB

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