csvprovider.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443
  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/pkg/cloud/models"
  13. "github.com/opencost/opencost/pkg/env"
  14. "github.com/opencost/opencost/pkg/util"
  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/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, error) {
  214. c.DownloadPricingDataLock.RLock()
  215. defer c.DownloadPricingDataLock.RUnlock()
  216. var node *models.Node
  217. if p, ok := c.Pricing[key.ID()]; ok {
  218. node = &models.Node{
  219. Cost: p.MarketPriceHourly,
  220. PricingType: models.CsvExact,
  221. }
  222. }
  223. s := strings.Split(key.ID(), ",") // Try without a region to be sure
  224. if len(s) == 2 {
  225. if p, ok := c.Pricing[s[1]]; ok {
  226. node = &models.Node{
  227. Cost: p.MarketPriceHourly,
  228. PricingType: models.CsvExact,
  229. }
  230. }
  231. }
  232. classKey := key.Features() // Use node attributes to try and do a class match
  233. if cost, ok := c.NodeClassPricing[classKey]; ok {
  234. log.Infof("Unable to find provider ID `%s`, using features:`%s`", key.ID(), key.Features())
  235. node = &models.Node{
  236. Cost: fmt.Sprintf("%f", cost),
  237. PricingType: models.CsvClass,
  238. }
  239. }
  240. if node != nil {
  241. if t := key.GPUType(); t != "" {
  242. t = strings.ToLower(t)
  243. count := key.GPUCount()
  244. node.GPU = strconv.Itoa(count)
  245. hourly := 0.0
  246. if p, ok := c.GPUClassPricing[t]; ok {
  247. var err error
  248. hourly, err = strconv.ParseFloat(p.MarketPriceHourly, 64)
  249. if err != nil {
  250. log.Errorf("Unable to parse %s as float", p.MarketPriceHourly)
  251. }
  252. }
  253. totalCost := hourly * float64(count)
  254. node.GPUCost = fmt.Sprintf("%f", totalCost)
  255. nc, err := strconv.ParseFloat(node.Cost, 64)
  256. if err != nil {
  257. log.Errorf("Unable to parse %s as float", node.Cost)
  258. }
  259. node.Cost = fmt.Sprintf("%f", nc+totalCost)
  260. }
  261. return node, nil
  262. } else {
  263. return nil, fmt.Errorf("Unable to find Node matching `%s`:`%s`", key.ID(), key.Features())
  264. }
  265. }
  266. func NodeValueFromMapField(m string, n *v1.Node, useRegion bool) string {
  267. mf := strings.Split(m, ".")
  268. toReturn := ""
  269. if useRegion {
  270. if region, ok := util.GetRegion(n.Labels); ok {
  271. toReturn = region + ","
  272. } else {
  273. log.Errorf("Getting region based on labels failed")
  274. }
  275. }
  276. if len(mf) == 2 && mf[0] == "spec" && mf[1] == "providerID" {
  277. for matchNum, group := range provIdRx.FindStringSubmatch(n.Spec.ProviderID) {
  278. if matchNum == 2 {
  279. return toReturn + group
  280. }
  281. }
  282. if strings.HasPrefix(n.Spec.ProviderID, "azure://") {
  283. vmOrScaleSet := strings.ToLower(strings.TrimPrefix(n.Spec.ProviderID, "azure://"))
  284. return toReturn + vmOrScaleSet
  285. }
  286. return toReturn + n.Spec.ProviderID
  287. } else if len(mf) > 1 && mf[0] == "metadata" {
  288. if mf[1] == "name" {
  289. return toReturn + n.Name
  290. } else if mf[1] == "labels" {
  291. lkey := strings.Join(mf[2:len(mf)], ".")
  292. return toReturn + n.Labels[lkey]
  293. } else if mf[1] == "annotations" {
  294. akey := strings.Join(mf[2:len(mf)], ".")
  295. return toReturn + n.Annotations[akey]
  296. } else {
  297. log.Errorf("Unsupported InstanceIDField %s in CSV For Node", m)
  298. return ""
  299. }
  300. } else {
  301. log.Errorf("Unsupported InstanceIDField %s in CSV For Node", m)
  302. return ""
  303. }
  304. }
  305. func PVValueFromMapField(m string, n *v1.PersistentVolume) string {
  306. mf := strings.Split(m, ".")
  307. if len(mf) > 1 && mf[0] == "metadata" {
  308. if mf[1] == "name" {
  309. return n.Name
  310. } else if mf[1] == "labels" {
  311. lkey := strings.Join(mf[2:len(mf)], "")
  312. return n.Labels[lkey]
  313. } else if mf[1] == "annotations" {
  314. akey := strings.Join(mf[2:len(mf)], "")
  315. return n.Annotations[akey]
  316. } else {
  317. log.Errorf("Unsupported InstanceIDField %s in CSV For PV", m)
  318. return ""
  319. }
  320. } else if len(mf) > 2 && mf[0] == "spec" {
  321. if mf[1] == "capacity" && mf[2] == "storage" {
  322. skey := n.Spec.Capacity["storage"]
  323. return skey.String()
  324. } else {
  325. log.Infof("[ERROR] Unsupported InstanceIDField %s in CSV For PV", m)
  326. return ""
  327. }
  328. } else if len(mf) > 1 && mf[0] == "spec" {
  329. if mf[1] == "storageClassName" {
  330. return n.Spec.StorageClassName
  331. } else {
  332. log.Infof("[ERROR] Unsupported InstanceIDField %s in CSV For PV", m)
  333. return ""
  334. }
  335. } else {
  336. log.Errorf("Unsupported InstanceIDField %s in CSV For PV", m)
  337. return ""
  338. }
  339. }
  340. func (c *CSVProvider) GetKey(l map[string]string, n *v1.Node) models.Key {
  341. id := NodeValueFromMapField(c.NodeMapField, n, c.UsesRegion)
  342. var gpuCount int64
  343. gpuCount = 0
  344. if gpuc, ok := n.Status.Capacity["nvidia.com/gpu"]; ok { // TODO: support non-nvidia GPUs
  345. gpuCount = gpuc.Value()
  346. }
  347. return &csvKey{
  348. ProviderID: id,
  349. Labels: l,
  350. GPULabel: c.GPUMapFields,
  351. GPU: gpuCount,
  352. }
  353. }
  354. type csvPVKey struct {
  355. Labels map[string]string
  356. ProviderID string
  357. StorageClassName string
  358. StorageClassParameters map[string]string
  359. Name string
  360. DefaultRegion string
  361. }
  362. func (key *csvPVKey) ID() string {
  363. return ""
  364. }
  365. func (key *csvPVKey) GetStorageClass() string {
  366. return key.StorageClassName
  367. }
  368. func (key *csvPVKey) Features() string {
  369. return key.ProviderID
  370. }
  371. func (c *CSVProvider) GetPVKey(pv *v1.PersistentVolume, parameters map[string]string, defaultRegion string) models.PVKey {
  372. id := PVValueFromMapField(c.PVMapField, pv)
  373. return &csvPVKey{
  374. Labels: pv.Labels,
  375. ProviderID: id,
  376. StorageClassName: pv.Spec.StorageClassName,
  377. StorageClassParameters: parameters,
  378. Name: pv.Name,
  379. DefaultRegion: defaultRegion,
  380. }
  381. }
  382. func (c *CSVProvider) PVPricing(pvk models.PVKey) (*models.PV, error) {
  383. c.DownloadPricingDataLock.RLock()
  384. defer c.DownloadPricingDataLock.RUnlock()
  385. pricing, ok := c.PricingPV[pvk.Features()]
  386. if !ok {
  387. log.Infof("Persistent Volume pricing not found for %s: %s", pvk.GetStorageClass(), pvk.Features())
  388. return &models.PV{}, nil
  389. }
  390. return &models.PV{
  391. Cost: pricing.MarketPriceHourly,
  392. }, nil
  393. }
  394. func (c *CSVProvider) ServiceAccountStatus() *models.ServiceAccountStatus {
  395. return &models.ServiceAccountStatus{
  396. Checks: []*models.ServiceAccountCheck{},
  397. }
  398. }
  399. func (*CSVProvider) ClusterManagementPricing() (string, float64, error) {
  400. return "", 0.0, nil
  401. }
  402. func (c *CSVProvider) CombinedDiscountForNode(instanceType string, isPreemptible bool, defaultDiscount, negotiatedDiscount float64) float64 {
  403. return 1.0 - ((1.0 - defaultDiscount) * (1.0 - negotiatedDiscount))
  404. }
  405. func (c *CSVProvider) Regions() []string {
  406. return []string{}
  407. }
  408. func (c *CSVProvider) PricingSourceSummary() interface{} {
  409. return c.Pricing
  410. }