scalewayprovider.go 8.8 KB

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