scalewayprovider.go 8.7 KB

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