scalewayprovider.go 9.6 KB

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