csvprovider.go 10 KB

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