scalewayprovider.go 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  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. 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. regionOverrides := env.GetRegionOverrideList()
  203. if len(regionOverrides) > 0 {
  204. log.Debugf("Overriding Scaleway regions with configured region list: %+v", regionOverrides)
  205. return regionOverrides
  206. }
  207. // These are zones but hey, its 2022
  208. zones := []string{}
  209. for _, zone := range scw.AllZones {
  210. zones = append(zones, zone.String())
  211. }
  212. return zones
  213. }
  214. func (*Scaleway) ApplyReservedInstancePricing(map[string]*Node) {}
  215. func (*Scaleway) GetAddresses() ([]byte, error) {
  216. return nil, nil
  217. }
  218. func (*Scaleway) GetDisks() ([]byte, error) {
  219. return nil, nil
  220. }
  221. func (*Scaleway) GetOrphanedResources() ([]OrphanedResource, error) {
  222. return nil, errors.New("not implemented")
  223. }
  224. func (scw *Scaleway) ClusterInfo() (map[string]string, error) {
  225. remoteEnabled := env.IsRemoteEnabled()
  226. m := make(map[string]string)
  227. m["name"] = "Scaleway Cluster #1"
  228. c, err := scw.GetConfig()
  229. if err != nil {
  230. return nil, err
  231. }
  232. if c.ClusterName != "" {
  233. m["name"] = c.ClusterName
  234. }
  235. m["provider"] = kubecost.ScalewayProvider
  236. m["remoteReadEnabled"] = strconv.FormatBool(remoteEnabled)
  237. m["id"] = env.GetClusterID()
  238. return m, nil
  239. }
  240. func (c *Scaleway) UpdateConfigFromConfigMap(a map[string]string) (*CustomPricing, error) {
  241. return c.Config.UpdateFromMap(a)
  242. }
  243. func (c *Scaleway) UpdateConfig(r io.Reader, updateType string) (*CustomPricing, error) {
  244. defer c.DownloadPricingData()
  245. return c.Config.Update(func(c *CustomPricing) error {
  246. a := make(map[string]interface{})
  247. err := json.NewDecoder(r).Decode(&a)
  248. if err != nil {
  249. return err
  250. }
  251. for k, v := range a {
  252. kUpper := toTitle.String(k) // Just so we consistently supply / receive the same values, uppercase the first letter.
  253. vstr, ok := v.(string)
  254. if ok {
  255. err := SetCustomPricingField(c, kUpper, vstr)
  256. if err != nil {
  257. return err
  258. }
  259. } else {
  260. return fmt.Errorf("type error while updating config for %s", kUpper)
  261. }
  262. }
  263. if env.IsRemoteEnabled() {
  264. err := UpdateClusterMeta(env.GetClusterID(), c.ClusterName)
  265. if err != nil {
  266. return err
  267. }
  268. }
  269. return nil
  270. })
  271. }
  272. func (scw *Scaleway) GetConfig() (*CustomPricing, error) {
  273. c, err := scw.Config.GetCustomPricingData()
  274. if err != nil {
  275. return nil, err
  276. }
  277. if c.Discount == "" {
  278. c.Discount = "0%"
  279. }
  280. if c.NegotiatedDiscount == "" {
  281. c.NegotiatedDiscount = "0%"
  282. }
  283. if c.CurrencyCode == "" {
  284. c.CurrencyCode = "EUR"
  285. }
  286. return c, nil
  287. }
  288. func (*Scaleway) GetLocalStorageQuery(window, offset time.Duration, rate bool, used bool) string {
  289. return ""
  290. }
  291. func (scw *Scaleway) GetManagementPlatform() (string, error) {
  292. nodes := scw.Clientset.GetAllNodes()
  293. if len(nodes) > 0 {
  294. n := nodes[0]
  295. if _, ok := n.Labels["k8s.scaleway.com/kapsule"]; ok {
  296. return "kapsule", nil
  297. }
  298. if _, ok := n.Labels["kops.k8s.io/instancegroup"]; ok {
  299. return "kops", nil
  300. }
  301. }
  302. return "", nil
  303. }
  304. func (c *Scaleway) PricingSourceStatus() map[string]*PricingSource {
  305. return map[string]*PricingSource{
  306. InstanceAPIPricing: &PricingSource{
  307. Name: InstanceAPIPricing,
  308. Enabled: true,
  309. Available: true,
  310. },
  311. }
  312. }