scalewayprovider.go 9.0 KB

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