scalewayprovider.go 8.8 KB

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