csvprovider.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449
  1. package provider
  2. import (
  3. "encoding/csv"
  4. "fmt"
  5. "io"
  6. "os"
  7. "regexp"
  8. "strconv"
  9. "strings"
  10. "sync"
  11. "time"
  12. "github.com/opencost/opencost/core/pkg/util"
  13. "github.com/opencost/opencost/pkg/cloud/models"
  14. "github.com/opencost/opencost/pkg/env"
  15. "github.com/aws/aws-sdk-go/aws"
  16. "github.com/aws/aws-sdk-go/aws/session"
  17. "github.com/aws/aws-sdk-go/service/s3"
  18. "github.com/opencost/opencost/core/pkg/log"
  19. v1 "k8s.io/api/core/v1"
  20. "github.com/jszwec/csvutil"
  21. )
  22. const refreshMinutes = 60
  23. var (
  24. provIdRx = regexp.MustCompile("aws:///([^/]+)/([^/]+)")
  25. )
  26. type CSVProvider struct {
  27. *CustomProvider
  28. CSVLocation string
  29. Pricing map[string]*price
  30. NodeClassPricing map[string]float64
  31. NodeClassCount map[string]float64
  32. NodeMapField string
  33. PricingPV map[string]*price
  34. PVMapField string
  35. GPUClassPricing map[string]*price
  36. GPUMapFields []string // Fields in a node's labels that represent the GPU class.
  37. UsesRegion bool
  38. DownloadPricingDataLock sync.RWMutex
  39. }
  40. type price struct {
  41. EndTimestamp string `csv:"EndTimestamp"`
  42. InstanceID string `csv:"InstanceID"`
  43. Region string `csv:"Region"`
  44. AssetClass string `csv:"AssetClass"`
  45. InstanceIDField string `csv:"InstanceIDField"`
  46. InstanceType string `csv:"InstanceType"`
  47. MarketPriceHourly string `csv:"MarketPriceHourly"`
  48. Version string `csv:"Version"`
  49. }
  50. func GetCsv(location string) (io.Reader, error) {
  51. return os.Open(location)
  52. }
  53. func (c *CSVProvider) DownloadPricingData() error {
  54. c.DownloadPricingDataLock.Lock()
  55. defer time.AfterFunc(refreshMinutes*time.Minute, func() { c.DownloadPricingData() })
  56. defer c.DownloadPricingDataLock.Unlock()
  57. pricing := make(map[string]*price)
  58. nodeclasspricing := make(map[string]float64)
  59. nodeclasscount := make(map[string]float64)
  60. pvpricing := make(map[string]*price)
  61. gpupricing := make(map[string]*price)
  62. c.GPUMapFields = make([]string, 0, 1)
  63. header, err := csvutil.Header(price{}, "csv")
  64. if err != nil {
  65. return err
  66. }
  67. fieldsPerRecord := len(header)
  68. var csvr io.Reader
  69. var csverr error
  70. if strings.HasPrefix(c.CSVLocation, "s3://") {
  71. region := env.GetCSVRegion()
  72. conf := aws.NewConfig().WithRegion(region).WithCredentialsChainVerboseErrors(true)
  73. endpoint := env.GetCSVEndpoint()
  74. if endpoint != "" {
  75. conf = conf.WithEndpoint(endpoint)
  76. }
  77. s3Client := s3.New(session.New(conf))
  78. bucketAndKey := strings.Split(strings.TrimPrefix(c.CSVLocation, "s3://"), "/")
  79. if len(bucketAndKey) == 2 {
  80. out, err := s3Client.GetObject(&s3.GetObjectInput{
  81. Bucket: aws.String(bucketAndKey[0]),
  82. Key: aws.String(bucketAndKey[1]),
  83. })
  84. csverr = err
  85. csvr = out.Body
  86. } else {
  87. c.Pricing = pricing
  88. c.NodeClassPricing = nodeclasspricing
  89. c.NodeClassCount = nodeclasscount
  90. c.PricingPV = pvpricing
  91. c.GPUClassPricing = gpupricing
  92. return fmt.Errorf("Invalid s3 URI: %s", c.CSVLocation)
  93. }
  94. } else {
  95. csvr, csverr = GetCsv(c.CSVLocation)
  96. }
  97. if csverr != nil {
  98. log.Infof("Error reading csv at %s: %s", c.CSVLocation, csverr)
  99. c.Pricing = pricing
  100. c.NodeClassPricing = nodeclasspricing
  101. c.NodeClassCount = nodeclasscount
  102. c.PricingPV = pvpricing
  103. c.GPUClassPricing = gpupricing
  104. return nil
  105. }
  106. csvReader := csv.NewReader(csvr)
  107. csvReader.Comma = ','
  108. csvReader.FieldsPerRecord = fieldsPerRecord
  109. dec, err := csvutil.NewDecoder(csvReader, header...)
  110. if err != nil {
  111. c.Pricing = pricing
  112. c.NodeClassPricing = nodeclasspricing
  113. c.NodeClassCount = nodeclasscount
  114. c.PricingPV = pvpricing
  115. c.GPUClassPricing = gpupricing
  116. return err
  117. }
  118. for {
  119. p := price{}
  120. err := dec.Decode(&p)
  121. csvParseErr, isCsvParseErr := err.(*csv.ParseError)
  122. if err == io.EOF {
  123. break
  124. } else if err == csvutil.ErrFieldCount || (isCsvParseErr && csvParseErr.Err == csv.ErrFieldCount) {
  125. rec := dec.Record()
  126. if len(rec) != 1 {
  127. log.Infof("Expected %d price info fields but received %d: %s", fieldsPerRecord, len(rec), rec)
  128. continue
  129. }
  130. if strings.Index(rec[0], "#") == 0 {
  131. continue
  132. } else {
  133. log.Infof("skipping non-CSV line: %s", rec)
  134. continue
  135. }
  136. } else if err != nil {
  137. log.Infof("Error during spot info decode: %+v", err)
  138. continue
  139. }
  140. log.Infof("Found price info %+v", p)
  141. key := strings.ToLower(p.InstanceID)
  142. if p.Region != "" { // strip the casing from region and add to key.
  143. key = fmt.Sprintf("%s,%s", strings.ToLower(p.Region), strings.ToLower(p.InstanceID))
  144. c.UsesRegion = true
  145. }
  146. if p.AssetClass == "pv" {
  147. pvpricing[key] = &p
  148. c.PVMapField = p.InstanceIDField
  149. } else if p.AssetClass == "node" {
  150. pricing[key] = &p
  151. classKey := p.Region + "," + p.InstanceType + "," + p.AssetClass
  152. cost, err := strconv.ParseFloat(p.MarketPriceHourly, 64)
  153. if err != nil {
  154. } else {
  155. if _, ok := nodeclasspricing[classKey]; ok {
  156. oldPrice := nodeclasspricing[classKey]
  157. oldCount := nodeclasscount[classKey]
  158. newPrice := ((oldPrice * oldCount) + cost) / (oldCount + 1.0)
  159. nodeclasscount[classKey] = newPrice
  160. nodeclasscount[classKey]++
  161. } else {
  162. nodeclasspricing[classKey] = cost
  163. nodeclasscount[classKey] = 1
  164. }
  165. }
  166. c.NodeMapField = p.InstanceIDField
  167. } else if p.AssetClass == "gpu" {
  168. gpupricing[key] = &p
  169. c.GPUMapFields = append(c.GPUMapFields, strings.ToLower(p.InstanceIDField))
  170. } else {
  171. log.Infof("Unrecognized asset class %s, defaulting to node", p.AssetClass)
  172. pricing[key] = &p
  173. c.NodeMapField = p.InstanceIDField
  174. }
  175. }
  176. if len(pricing) > 0 {
  177. c.Pricing = pricing
  178. c.NodeClassPricing = nodeclasspricing
  179. c.NodeClassCount = nodeclasscount
  180. c.PricingPV = pvpricing
  181. c.GPUClassPricing = gpupricing
  182. } else {
  183. log.DedupedWarningf(5, "No data received from csv at %s", c.CSVLocation)
  184. }
  185. return nil
  186. }
  187. type csvKey struct {
  188. Labels map[string]string
  189. ProviderID string
  190. GPULabel []string
  191. GPU int64
  192. }
  193. func (k *csvKey) Features() string {
  194. instanceType, _ := util.GetInstanceType(k.Labels)
  195. region, _ := util.GetRegion(k.Labels)
  196. class := "node"
  197. return region + "," + instanceType + "," + class
  198. }
  199. func (k *csvKey) GPUCount() int {
  200. return int(k.GPU)
  201. }
  202. func (k *csvKey) GPUType() string {
  203. for _, label := range k.GPULabel {
  204. if val, ok := k.Labels[label]; ok {
  205. return val
  206. }
  207. }
  208. return ""
  209. }
  210. func (k *csvKey) ID() string {
  211. return k.ProviderID
  212. }
  213. func (c *CSVProvider) nodePricing(key models.Key) *models.Node {
  214. if p, ok := c.Pricing[key.ID()]; ok {
  215. return &models.Node{
  216. Cost: p.MarketPriceHourly,
  217. PricingType: models.CsvExact,
  218. }
  219. }
  220. s := strings.Split(key.ID(), ",") // Try without a region to be sure
  221. if len(s) == 2 {
  222. if p, ok := c.Pricing[s[1]]; ok {
  223. return &models.Node{
  224. Cost: p.MarketPriceHourly,
  225. PricingType: models.CsvExact,
  226. }
  227. }
  228. }
  229. classKey := key.Features() // Use node attributes to try and do a class match
  230. if cost, ok := c.NodeClassPricing[classKey]; ok {
  231. log.Infof("Unable to find provider ID `%s`, using features:`%s`", key.ID(), key.Features())
  232. return &models.Node{
  233. Cost: fmt.Sprintf("%f", cost),
  234. PricingType: models.CsvClass,
  235. }
  236. }
  237. return nil
  238. }
  239. func (c *CSVProvider) NodePricing(key models.Key) (*models.Node, models.PricingMetadata, error) {
  240. c.DownloadPricingDataLock.RLock()
  241. defer c.DownloadPricingDataLock.RUnlock()
  242. node := c.nodePricing(key)
  243. if node == nil {
  244. return nil, models.PricingMetadata{}, fmt.Errorf("Unable to find Node matching `%s`:`%s`", key.ID(), key.Features())
  245. }
  246. if t := key.GPUType(); t != "" {
  247. t = strings.ToLower(t)
  248. count := key.GPUCount()
  249. node.GPU = strconv.Itoa(count)
  250. hourly := 0.0
  251. if p, ok := c.GPUClassPricing[t]; ok {
  252. var err error
  253. hourly, err = strconv.ParseFloat(p.MarketPriceHourly, 64)
  254. if err != nil {
  255. log.Errorf("Unable to parse %s as float", p.MarketPriceHourly)
  256. }
  257. }
  258. totalCost := hourly * float64(count)
  259. node.GPUCost = fmt.Sprintf("%f", hourly)
  260. nc, err := strconv.ParseFloat(node.Cost, 64)
  261. if err != nil {
  262. log.Errorf("Unable to parse %s as float", node.Cost)
  263. }
  264. node.Cost = fmt.Sprintf("%f", nc+totalCost)
  265. }
  266. return node, models.PricingMetadata{}, nil
  267. }
  268. func NodeValueFromMapField(m string, n *v1.Node, useRegion bool) string {
  269. mf := strings.Split(m, ".")
  270. toReturn := ""
  271. if useRegion {
  272. if region, ok := util.GetRegion(n.Labels); ok {
  273. toReturn = region + ","
  274. } else {
  275. log.Errorf("Getting region based on labels failed")
  276. }
  277. }
  278. if len(mf) == 2 && mf[0] == "spec" && mf[1] == "providerID" {
  279. for matchNum, group := range provIdRx.FindStringSubmatch(n.Spec.ProviderID) {
  280. if matchNum == 2 {
  281. return toReturn + group
  282. }
  283. }
  284. if strings.HasPrefix(n.Spec.ProviderID, "azure://") {
  285. vmOrScaleSet := strings.ToLower(strings.TrimPrefix(n.Spec.ProviderID, "azure://"))
  286. return toReturn + vmOrScaleSet
  287. }
  288. return toReturn + n.Spec.ProviderID
  289. } else if len(mf) > 1 && mf[0] == "metadata" {
  290. if mf[1] == "name" {
  291. return toReturn + n.Name
  292. } else if mf[1] == "labels" {
  293. lkey := strings.Join(mf[2:len(mf)], ".")
  294. return toReturn + n.Labels[lkey]
  295. } else if mf[1] == "annotations" {
  296. akey := strings.Join(mf[2:len(mf)], ".")
  297. return toReturn + n.Annotations[akey]
  298. } else {
  299. log.DedupedInfof(10, "Unsupported InstanceIDField %s in CSV For Node", m)
  300. return ""
  301. }
  302. } else {
  303. log.DedupedInfof(10, "Unsupported InstanceIDField %s in CSV For Node", m)
  304. return ""
  305. }
  306. }
  307. func PVValueFromMapField(m string, n *v1.PersistentVolume) string {
  308. mf := strings.Split(m, ".")
  309. if len(mf) > 1 && mf[0] == "metadata" {
  310. if mf[1] == "name" {
  311. return n.Name
  312. } else if mf[1] == "labels" {
  313. lkey := strings.Join(mf[2:len(mf)], "")
  314. return n.Labels[lkey]
  315. } else if mf[1] == "annotations" {
  316. akey := strings.Join(mf[2:len(mf)], "")
  317. return n.Annotations[akey]
  318. } else {
  319. log.Errorf("Unsupported InstanceIDField %s in CSV For PV", m)
  320. return ""
  321. }
  322. } else if len(mf) > 2 && mf[0] == "spec" {
  323. if mf[1] == "capacity" && mf[2] == "storage" {
  324. skey := n.Spec.Capacity["storage"]
  325. return skey.String()
  326. } else {
  327. log.Infof("[ERROR] Unsupported InstanceIDField %s in CSV For PV", m)
  328. return ""
  329. }
  330. } else if len(mf) > 1 && mf[0] == "spec" {
  331. if mf[1] == "storageClassName" {
  332. return n.Spec.StorageClassName
  333. } else {
  334. log.Infof("[ERROR] Unsupported InstanceIDField %s in CSV For PV", m)
  335. return ""
  336. }
  337. } else {
  338. log.Errorf("Unsupported InstanceIDField %s in CSV For PV", m)
  339. return ""
  340. }
  341. }
  342. func (c *CSVProvider) GetKey(l map[string]string, n *v1.Node) models.Key {
  343. id := NodeValueFromMapField(c.NodeMapField, n, c.UsesRegion)
  344. var gpuCount int64
  345. gpuCount = 0
  346. if gpuc, ok := n.Status.Capacity["nvidia.com/gpu"]; ok { // TODO: support non-nvidia GPUs
  347. gpuCount = gpuc.Value()
  348. }
  349. return &csvKey{
  350. ProviderID: strings.ToLower(id),
  351. Labels: l,
  352. GPULabel: c.GPUMapFields,
  353. GPU: gpuCount,
  354. }
  355. }
  356. type csvPVKey struct {
  357. Labels map[string]string
  358. ProviderID string
  359. StorageClassName string
  360. StorageClassParameters map[string]string
  361. Name string
  362. DefaultRegion string
  363. }
  364. func (key *csvPVKey) ID() string {
  365. return ""
  366. }
  367. func (key *csvPVKey) GetStorageClass() string {
  368. return key.StorageClassName
  369. }
  370. func (key *csvPVKey) Features() string {
  371. return key.ProviderID
  372. }
  373. func (c *CSVProvider) GetPVKey(pv *v1.PersistentVolume, parameters map[string]string, defaultRegion string) models.PVKey {
  374. id := PVValueFromMapField(c.PVMapField, pv)
  375. return &csvPVKey{
  376. Labels: pv.Labels,
  377. ProviderID: id,
  378. StorageClassName: pv.Spec.StorageClassName,
  379. StorageClassParameters: parameters,
  380. Name: pv.Name,
  381. DefaultRegion: defaultRegion,
  382. }
  383. }
  384. func (c *CSVProvider) PVPricing(pvk models.PVKey) (*models.PV, error) {
  385. c.DownloadPricingDataLock.RLock()
  386. defer c.DownloadPricingDataLock.RUnlock()
  387. pricing, ok := c.PricingPV[pvk.Features()]
  388. if !ok {
  389. log.Debugf("Persistent Volume pricing not found for %s: %s", pvk.GetStorageClass(), pvk.Features())
  390. return &models.PV{}, nil
  391. }
  392. return &models.PV{
  393. Cost: pricing.MarketPriceHourly,
  394. }, nil
  395. }
  396. func (c *CSVProvider) ServiceAccountStatus() *models.ServiceAccountStatus {
  397. return &models.ServiceAccountStatus{
  398. Checks: []*models.ServiceAccountCheck{},
  399. }
  400. }
  401. func (*CSVProvider) ClusterManagementPricing() (string, float64, error) {
  402. return "", 0.0, nil
  403. }
  404. func (c *CSVProvider) CombinedDiscountForNode(instanceType string, isPreemptible bool, defaultDiscount, negotiatedDiscount float64) float64 {
  405. return 1.0 - ((1.0 - defaultDiscount) * (1.0 - negotiatedDiscount))
  406. }
  407. func (c *CSVProvider) Regions() []string {
  408. return []string{}
  409. }
  410. func (c *CSVProvider) PricingSourceSummary() interface{} {
  411. return c.Pricing
  412. }