cluster_helpers.go 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961
  1. package costmodel
  2. import (
  3. "fmt"
  4. "math"
  5. "strconv"
  6. "time"
  7. coreenv "github.com/opencost/opencost/core/pkg/env"
  8. "github.com/opencost/opencost/pkg/cloud/models"
  9. "github.com/opencost/opencost/pkg/cloud/provider"
  10. "github.com/opencost/opencost/core/pkg/log"
  11. "github.com/opencost/opencost/core/pkg/opencost"
  12. "github.com/opencost/opencost/core/pkg/source"
  13. "github.com/opencost/opencost/core/pkg/util"
  14. )
  15. // mergeTypeMaps takes two maps of (cluster name, node name) -> node type
  16. // and combines them into a single map, preferring the k/v pairs in
  17. // the first map.
  18. func mergeTypeMaps(clusterAndNameToType1, clusterAndNameToType2 map[nodeIdentifierNoProviderID]string) map[nodeIdentifierNoProviderID]string {
  19. merged := map[nodeIdentifierNoProviderID]string{}
  20. for k, v := range clusterAndNameToType2 {
  21. merged[k] = v
  22. }
  23. // This ordering ensures the mappings in the first arg are preferred.
  24. for k, v := range clusterAndNameToType1 {
  25. merged[k] = v
  26. }
  27. return merged
  28. }
  29. func buildCPUCostMap(
  30. resNodeCPUCost []*source.NodeCPUPricePerHrResult,
  31. cp models.Provider,
  32. preemptible map[NodeIdentifier]bool,
  33. ) (map[NodeIdentifier]float64, map[nodeIdentifierNoProviderID]string) {
  34. cpuCostMap := make(map[NodeIdentifier]float64)
  35. clusterAndNameToType := make(map[nodeIdentifierNoProviderID]string)
  36. customPricingEnabled := provider.CustomPricesEnabled(cp)
  37. customPricingConfig, err := cp.GetConfig()
  38. if err != nil {
  39. log.Warnf("ClusterNodes: failed to load custom pricing: %s", err)
  40. }
  41. for _, result := range resNodeCPUCost {
  42. cluster := result.Cluster
  43. if cluster == "" {
  44. cluster = coreenv.GetClusterID()
  45. }
  46. name := result.Node
  47. if name == "" {
  48. log.Warnf("ClusterNodes: CPU cost data missing node")
  49. continue
  50. }
  51. nodeType := result.InstanceType
  52. providerID := result.ProviderID
  53. key := NodeIdentifier{
  54. Cluster: cluster,
  55. Name: name,
  56. ProviderID: provider.ParseID(providerID),
  57. }
  58. keyNon := nodeIdentifierNoProviderID{
  59. Cluster: cluster,
  60. Name: name,
  61. }
  62. var cpuCost float64
  63. // Start with the value from the data source (e.g., collector or Prometheus)
  64. cpuCost = result.Data[0].Value
  65. // If custom pricing is enabled or the data source value is invalid, use custom pricing
  66. if (customPricingEnabled && customPricingConfig != nil) || cpuCost == 0 || math.IsNaN(cpuCost) {
  67. if customPricingConfig != nil {
  68. var customCPUStr string
  69. if spot, ok := preemptible[key]; ok && spot {
  70. customCPUStr = customPricingConfig.SpotCPU
  71. } else {
  72. customCPUStr = customPricingConfig.CPU
  73. }
  74. customCPUCost, err := strconv.ParseFloat(customCPUStr, 64)
  75. if err != nil {
  76. log.Warnf("ClusterNodes: error parsing custom CPU price: %s", customCPUStr)
  77. } else {
  78. // Log the reason for using custom pricing
  79. if cpuCost == 0 {
  80. log.DedupedInfof(10, "ClusterNodes: node %s has invalid CPU cost (0) from data source; falling back to custom pricing: %f", name, customCPUCost)
  81. } else if math.IsNaN(cpuCost) {
  82. log.DedupedInfof(10, "ClusterNodes: node %s has invalid CPU cost (NaN) from data source; falling back to custom pricing: %f", name, customCPUCost)
  83. } else {
  84. log.DedupedInfof(10, "ClusterNodes: node %s using custom pricing: %f", name, customCPUCost)
  85. }
  86. cpuCost = customCPUCost
  87. }
  88. } else {
  89. // custom pricing config is nil, but we needed it because cpuCost was invalid
  90. if cpuCost == 0 || math.IsNaN(cpuCost) {
  91. log.Warnf("ClusterNodes: node %s has invalid CPU cost (0 or NaN), but was unable to fall back to custom pricing because it was nil", name)
  92. }
  93. }
  94. }
  95. clusterAndNameToType[keyNon] = nodeType
  96. cpuCostMap[key] = cpuCost
  97. }
  98. return cpuCostMap, clusterAndNameToType
  99. }
  100. func buildRAMCostMap(
  101. resNodeRAMCost []*source.NodeRAMPricePerGiBHrResult,
  102. cp models.Provider,
  103. preemptible map[NodeIdentifier]bool,
  104. ) (map[NodeIdentifier]float64, map[nodeIdentifierNoProviderID]string) {
  105. ramCostMap := make(map[NodeIdentifier]float64)
  106. clusterAndNameToType := make(map[nodeIdentifierNoProviderID]string)
  107. customPricingEnabled := provider.CustomPricesEnabled(cp)
  108. customPricingConfig, err := cp.GetConfig()
  109. if err != nil {
  110. log.Warnf("ClusterNodes: failed to load custom pricing: %s", err)
  111. }
  112. for _, result := range resNodeRAMCost {
  113. cluster := result.Cluster
  114. if cluster == "" {
  115. cluster = coreenv.GetClusterID()
  116. }
  117. name := result.Node
  118. if name == "" {
  119. log.Warnf("ClusterNodes: RAM cost data missing node")
  120. continue
  121. }
  122. nodeType := result.InstanceType
  123. providerID := result.ProviderID
  124. key := NodeIdentifier{
  125. Cluster: cluster,
  126. Name: name,
  127. ProviderID: provider.ParseID(providerID),
  128. }
  129. keyNon := nodeIdentifierNoProviderID{
  130. Cluster: cluster,
  131. Name: name,
  132. }
  133. var ramCost float64
  134. // Start with the value from the data source (e.g., collector or Prometheus)
  135. ramCost = result.Data[0].Value
  136. // If custom pricing is enabled or the data source value is invalid, use custom pricing
  137. if (customPricingEnabled && customPricingConfig != nil) || ramCost == 0 || math.IsNaN(ramCost) {
  138. if customPricingConfig != nil {
  139. var customRAMStr string
  140. if spot, ok := preemptible[key]; ok && spot {
  141. customRAMStr = customPricingConfig.SpotRAM
  142. } else {
  143. customRAMStr = customPricingConfig.RAM
  144. }
  145. customRAMCost, err := strconv.ParseFloat(customRAMStr, 64)
  146. if err != nil {
  147. log.Warnf("ClusterNodes: error parsing custom RAM price: %s", customRAMStr)
  148. } else {
  149. // Log the reason for using custom pricing
  150. if ramCost == 0 {
  151. log.DedupedInfof(10, "ClusterNodes: node %s has invalid RAM cost (0) from data source; falling back to custom pricing: %f", name, customRAMCost)
  152. } else if math.IsNaN(ramCost) {
  153. log.DedupedInfof(10, "ClusterNodes: node %s has invalid RAM cost (NaN) from data source; falling back to custom pricing: %f", name, customRAMCost)
  154. } else {
  155. log.DedupedInfof(10, "ClusterNodes: node %s using custom pricing: %f", name, customRAMCost)
  156. }
  157. ramCost = customRAMCost
  158. }
  159. } else {
  160. if ramCost == 0 || math.IsNaN(ramCost) {
  161. log.Warnf("ClusterNodes: node %s has invalid RAM cost (0 or NaN), but was unable to fall back to custom pricing because it was nil", name)
  162. }
  163. }
  164. }
  165. clusterAndNameToType[keyNon] = nodeType
  166. // covert to price per byte/hr
  167. ramCostMap[key] = ramCost / 1024.0 / 1024.0 / 1024.0
  168. }
  169. return ramCostMap, clusterAndNameToType
  170. }
  171. func buildGPUCostMap(
  172. resNodeGPUCost []*source.NodeGPUPricePerHrResult,
  173. gpuCountMap map[NodeIdentifier]float64,
  174. cp models.Provider,
  175. preemptible map[NodeIdentifier]bool,
  176. ) (map[NodeIdentifier]float64, map[nodeIdentifierNoProviderID]string) {
  177. gpuCostMap := make(map[NodeIdentifier]float64)
  178. clusterAndNameToType := make(map[nodeIdentifierNoProviderID]string)
  179. customPricingEnabled := provider.CustomPricesEnabled(cp)
  180. customPricingConfig, err := cp.GetConfig()
  181. if err != nil {
  182. log.Warnf("ClusterNodes: failed to load custom pricing: %s", err)
  183. }
  184. for _, result := range resNodeGPUCost {
  185. cluster := result.Cluster
  186. if cluster == "" {
  187. cluster = coreenv.GetClusterID()
  188. }
  189. name := result.Node
  190. if name == "" {
  191. log.Warnf("ClusterNodes: GPU cost data missing node")
  192. continue
  193. }
  194. nodeType := result.InstanceType
  195. providerID := result.ProviderID
  196. key := NodeIdentifier{
  197. Cluster: cluster,
  198. Name: name,
  199. ProviderID: provider.ParseID(providerID),
  200. }
  201. keyNon := nodeIdentifierNoProviderID{
  202. Cluster: cluster,
  203. Name: name,
  204. }
  205. var gpuCost float64
  206. if customPricingEnabled && customPricingConfig != nil {
  207. var customGPUStr string
  208. if spot, ok := preemptible[key]; ok && spot {
  209. customGPUStr = customPricingConfig.SpotGPU
  210. } else {
  211. customGPUStr = customPricingConfig.GPU
  212. }
  213. customGPUCost, err := strconv.ParseFloat(customGPUStr, 64)
  214. if err != nil {
  215. log.Warnf("ClusterNodes: error parsing custom GPU price: %s", customGPUStr)
  216. }
  217. gpuCost = customGPUCost
  218. } else {
  219. gpuCost = result.Data[0].Value
  220. }
  221. clusterAndNameToType[keyNon] = nodeType
  222. // If gpu count is available use it to multiply gpu cost
  223. if value, ok := gpuCountMap[key]; ok {
  224. gpuCostMap[key] = gpuCost * value
  225. } else {
  226. gpuCostMap[key] = 0
  227. }
  228. }
  229. return gpuCostMap, clusterAndNameToType
  230. }
  231. func buildGPUCountMap(resNodeGPUCount []*source.NodeGPUCountResult) map[NodeIdentifier]float64 {
  232. gpuCountMap := make(map[NodeIdentifier]float64)
  233. for _, result := range resNodeGPUCount {
  234. cluster := result.Cluster
  235. if cluster == "" {
  236. cluster = coreenv.GetClusterID()
  237. }
  238. name := result.Node
  239. if name == "" {
  240. log.Warnf("ClusterNodes: GPU count data missing node")
  241. continue
  242. }
  243. gpuCount := result.GPUCount
  244. providerID := result.ProviderID
  245. key := NodeIdentifier{
  246. Cluster: cluster,
  247. Name: name,
  248. ProviderID: provider.ParseID(providerID),
  249. }
  250. gpuCountMap[key] = gpuCount
  251. }
  252. return gpuCountMap
  253. }
  254. func buildCPUCoresMap(resNodeCPUCores []*source.NodeCPUCoresCapacityResult) map[nodeIdentifierNoProviderID]float64 {
  255. m := make(map[nodeIdentifierNoProviderID]float64)
  256. for _, result := range resNodeCPUCores {
  257. cluster := result.Cluster
  258. if cluster == "" {
  259. cluster = coreenv.GetClusterID()
  260. }
  261. name := result.Node
  262. if name == "" {
  263. log.Warnf("ClusterNodes: CPU cores data missing node")
  264. continue
  265. }
  266. key := nodeIdentifierNoProviderID{
  267. Cluster: cluster,
  268. Name: name,
  269. }
  270. m[key] = result.CPUCores
  271. }
  272. return m
  273. }
  274. func buildRAMBytesMap(resNodeRAMBytes []*source.NodeRAMBytesCapacityResult) map[nodeIdentifierNoProviderID]float64 {
  275. m := make(map[nodeIdentifierNoProviderID]float64)
  276. for _, result := range resNodeRAMBytes {
  277. cluster := result.Cluster
  278. if cluster == "" {
  279. cluster = coreenv.GetClusterID()
  280. }
  281. name := result.Node
  282. if name == "" {
  283. log.Warnf("ClusterNodes: RAM bytes data missing node")
  284. continue
  285. }
  286. key := nodeIdentifierNoProviderID{
  287. Cluster: cluster,
  288. Name: name,
  289. }
  290. m[key] = result.RAMBytes
  291. }
  292. return m
  293. }
  294. // Mapping of cluster/node=cpu for computing resource efficiency
  295. func buildCPUBreakdownMap(resNodeCPUModeTotal []*source.NodeCPUModeTotalResult) map[nodeIdentifierNoProviderID]*ClusterCostsBreakdown {
  296. cpuBreakdownMap := make(map[nodeIdentifierNoProviderID]*ClusterCostsBreakdown)
  297. // Mapping of cluster/node=cpu for computing resource efficiency
  298. clusterNodeCPUTotal := map[nodeIdentifierNoProviderID]float64{}
  299. // Mapping of cluster/node:mode=cpu for computing resource efficiency
  300. clusterNodeModeCPUTotal := map[nodeIdentifierNoProviderID]map[string]float64{}
  301. // Build intermediate structures for CPU usage by (cluster, node) and by
  302. // (cluster, node, mode) for computing resouce efficiency
  303. for _, result := range resNodeCPUModeTotal {
  304. cluster := result.Cluster
  305. if cluster == "" {
  306. cluster = coreenv.GetClusterID()
  307. }
  308. node := result.Node
  309. if node == "" {
  310. log.DedupedWarningf(5, "ClusterNodes: CPU mode data missing node")
  311. continue
  312. }
  313. mode := result.Mode
  314. if mode == "" {
  315. log.DedupedWarningf(10, "ClusterNodes: unable to read CPU mode data for node %s.", node)
  316. mode = "other"
  317. }
  318. key := nodeIdentifierNoProviderID{
  319. Cluster: cluster,
  320. Name: node,
  321. }
  322. total := result.Data[0].Value
  323. // Increment total
  324. clusterNodeCPUTotal[key] += total
  325. // Increment mode
  326. if _, ok := clusterNodeModeCPUTotal[key]; !ok {
  327. clusterNodeModeCPUTotal[key] = map[string]float64{}
  328. }
  329. clusterNodeModeCPUTotal[key][mode] += total
  330. }
  331. // Compute resource efficiency from intermediate structures
  332. for key, total := range clusterNodeCPUTotal {
  333. if modeTotals, ok := clusterNodeModeCPUTotal[key]; ok {
  334. for mode, subtotal := range modeTotals {
  335. // Compute percentage for the current cluster, node, mode
  336. pct := 0.0
  337. if total > 0 {
  338. pct = subtotal / total
  339. }
  340. if _, ok := cpuBreakdownMap[key]; !ok {
  341. cpuBreakdownMap[key] = &ClusterCostsBreakdown{}
  342. }
  343. switch mode {
  344. case "idle":
  345. cpuBreakdownMap[key].Idle += pct
  346. case "system":
  347. cpuBreakdownMap[key].System += pct
  348. case "user":
  349. cpuBreakdownMap[key].User += pct
  350. default:
  351. cpuBreakdownMap[key].Other += pct
  352. }
  353. }
  354. }
  355. }
  356. return cpuBreakdownMap
  357. }
  358. func buildOverheadMap(capRam, allocRam, capCPU, allocCPU map[nodeIdentifierNoProviderID]float64) map[nodeIdentifierNoProviderID]*NodeOverhead {
  359. m := make(map[nodeIdentifierNoProviderID]*NodeOverhead, len(capRam))
  360. for identifier, ramCapacity := range capRam {
  361. allocatableRam, ok := allocRam[identifier]
  362. if !ok {
  363. log.Warnf("Could not find allocatable ram for node %s", identifier.Name)
  364. continue
  365. }
  366. overheadBytes := ramCapacity - allocatableRam
  367. m[identifier] = &NodeOverhead{
  368. RamOverheadFraction: overheadBytes / ramCapacity,
  369. }
  370. }
  371. for identifier, cpuCapacity := range capCPU {
  372. allocatableCPU, ok := allocCPU[identifier]
  373. if !ok {
  374. log.Warnf("Could not find allocatable cpu for node %s", identifier.Name)
  375. continue
  376. }
  377. overhead := cpuCapacity - allocatableCPU
  378. if _, found := m[identifier]; found {
  379. m[identifier].CpuOverheadFraction = overhead / cpuCapacity
  380. } else {
  381. m[identifier] = &NodeOverhead{
  382. CpuOverheadFraction: overhead / cpuCapacity,
  383. }
  384. }
  385. }
  386. return m
  387. }
  388. func buildRAMUserPctMap(resNodeRAMUserPct []*source.NodeRAMUserPercentResult) map[nodeIdentifierNoProviderID]float64 {
  389. m := make(map[nodeIdentifierNoProviderID]float64)
  390. for _, result := range resNodeRAMUserPct {
  391. cluster := result.Cluster
  392. if cluster == "" {
  393. cluster = coreenv.GetClusterID()
  394. }
  395. name := result.Instance
  396. if name == "" {
  397. log.Warnf("ClusterNodes: RAM user percent missing node")
  398. continue
  399. }
  400. pct := result.Data[0].Value
  401. key := nodeIdentifierNoProviderID{
  402. Cluster: cluster,
  403. Name: name,
  404. }
  405. m[key] = pct
  406. }
  407. return m
  408. }
  409. func buildRAMSystemPctMap(resNodeRAMSystemPct []*source.NodeRAMSystemPercentResult) map[nodeIdentifierNoProviderID]float64 {
  410. m := make(map[nodeIdentifierNoProviderID]float64)
  411. for _, result := range resNodeRAMSystemPct {
  412. cluster := result.Cluster
  413. if cluster == "" {
  414. cluster = coreenv.GetClusterID()
  415. }
  416. name := result.Instance
  417. if name == "" {
  418. log.Warnf("ClusterNodes: RAM system percent missing node")
  419. continue
  420. }
  421. pct := result.Data[0].Value
  422. key := nodeIdentifierNoProviderID{
  423. Cluster: cluster,
  424. Name: name,
  425. }
  426. m[key] = pct
  427. }
  428. return m
  429. }
  430. type activeData struct {
  431. start time.Time
  432. end time.Time
  433. minutes float64
  434. }
  435. // cluster management key gen
  436. func clusterManagementKeyGen(result *source.ClusterManagementDurationResult) (ClusterManagementIdentifier, bool) {
  437. cluster := result.Cluster
  438. if cluster == "" {
  439. cluster = coreenv.GetClusterID()
  440. }
  441. provisionerName := result.Provisioner
  442. return ClusterManagementIdentifier{
  443. Cluster: cluster,
  444. Provisioner: provisionerName,
  445. }, true
  446. }
  447. func clusterManagementValues(result *source.ClusterManagementDurationResult) []*util.Vector {
  448. return result.Data
  449. }
  450. // node key gen
  451. func nodeKeyGen(result *source.NodeActiveMinutesResult) (NodeIdentifier, bool) {
  452. cluster := result.Cluster
  453. if cluster == "" {
  454. cluster = coreenv.GetClusterID()
  455. }
  456. name := result.Node
  457. if name == "" {
  458. log.Warnf("ClusterNodes: active mins missing node")
  459. return NodeIdentifier{}, false
  460. }
  461. providerID := result.ProviderID
  462. return NodeIdentifier{
  463. Cluster: cluster,
  464. Name: name,
  465. ProviderID: provider.ParseID(providerID),
  466. }, true
  467. }
  468. func nodeValues(result *source.NodeActiveMinutesResult) []*util.Vector {
  469. return result.Data
  470. }
  471. func loadBalancerKeyGen(result *source.LBActiveMinutesResult) (LoadBalancerIdentifier, bool) {
  472. cluster := result.Cluster
  473. if cluster == "" {
  474. cluster = coreenv.GetClusterID()
  475. }
  476. namespace := result.Namespace
  477. if namespace == "" {
  478. log.Warnf("ClusterLoadBalancers: LB cost data missing namespace")
  479. return LoadBalancerIdentifier{}, false
  480. }
  481. name := result.Service
  482. if name == "" {
  483. log.Warnf("ClusterLoadBalancers: LB cost data missing service_name")
  484. return LoadBalancerIdentifier{}, false
  485. }
  486. ingressIp := result.IngressIP
  487. if ingressIp == "" {
  488. log.DedupedWarningf(5, "ClusterLoadBalancers: LB cost data missing ingress_ip")
  489. // only update asset cost when an actual IP was returned
  490. return LoadBalancerIdentifier{}, false
  491. }
  492. return LoadBalancerIdentifier{
  493. Cluster: cluster,
  494. Namespace: namespace,
  495. Name: fmt.Sprintf("%s/%s", namespace, name), // TODO: this is kept for backwards-compatibility, but not good,
  496. IngressIP: ingressIp,
  497. }, true
  498. }
  499. func lbValues(result *source.LBActiveMinutesResult) []*util.Vector {
  500. return result.Data
  501. }
  502. func buildActiveDataMap[T comparable, U any](
  503. results []*U,
  504. keyGen func(*U) (T, bool),
  505. valuesFunc func(*U) []*util.Vector,
  506. resolution time.Duration,
  507. window opencost.Window,
  508. ) map[T]activeData {
  509. m := make(map[T]activeData)
  510. for _, result := range results {
  511. key, ok := keyGen(result)
  512. values := valuesFunc(result)
  513. if !ok || len(values) == 0 {
  514. continue
  515. }
  516. s, e := calculateStartAndEnd(values, resolution, window)
  517. mins := e.Sub(s).Minutes()
  518. m[key] = activeData{
  519. start: s,
  520. end: e,
  521. minutes: mins,
  522. }
  523. }
  524. return m
  525. }
  526. // Determine preemptibility with node labels
  527. // node id -> is preemptible?
  528. func buildPreemptibleMap(
  529. resIsSpot []*source.NodeIsSpotResult,
  530. ) map[NodeIdentifier]bool {
  531. m := make(map[NodeIdentifier]bool)
  532. for _, result := range resIsSpot {
  533. cluster := result.Cluster
  534. if cluster == "" {
  535. cluster = coreenv.GetClusterID()
  536. }
  537. name := result.Node
  538. if name == "" {
  539. log.Warnf("ClusterNodes: active mins missing node")
  540. continue
  541. }
  542. providerID := result.ProviderID
  543. key := NodeIdentifier{
  544. Cluster: cluster,
  545. Name: name,
  546. ProviderID: provider.ParseID(providerID),
  547. }
  548. // GCP preemptible label
  549. pre := result.Data[0].Value
  550. // TODO(michaelmdresser): check this condition at merge time?
  551. // if node, ok := nodeMap[key]; pre > 0.0 && ok {
  552. // node.Preemptible = true
  553. // }
  554. m[key] = pre > 0.0
  555. // TODO AWS preemptible
  556. // TODO Azure preemptible
  557. }
  558. return m
  559. }
  560. func buildAssetsPVCMap(resPVCInfo []*source.PVCInfoResult) map[DiskIdentifier]*Disk {
  561. diskMap := map[DiskIdentifier]*Disk{}
  562. for _, result := range resPVCInfo {
  563. cluster := result.Cluster
  564. if cluster == "" {
  565. cluster = coreenv.GetClusterID()
  566. }
  567. volumeName := result.VolumeName
  568. if volumeName == "" {
  569. log.Debugf("ClusterDisks: pv claim data missing volumename")
  570. continue
  571. }
  572. claimName := result.PersistentVolumeClaim
  573. if claimName == "" {
  574. log.Debugf("ClusterDisks: pv claim data missing persistentvolumeclaim")
  575. continue
  576. }
  577. claimNamespace := result.Namespace
  578. if claimNamespace == "" {
  579. log.Debugf("ClusterDisks: pv claim data missing namespace")
  580. continue
  581. }
  582. key := DiskIdentifier{
  583. Cluster: cluster,
  584. Name: volumeName,
  585. }
  586. if _, ok := diskMap[key]; !ok {
  587. diskMap[key] = &Disk{
  588. Cluster: cluster,
  589. Name: volumeName,
  590. Breakdown: &ClusterCostsBreakdown{},
  591. }
  592. }
  593. diskMap[key].VolumeName = volumeName
  594. diskMap[key].ClaimName = claimName
  595. diskMap[key].ClaimNamespace = claimNamespace
  596. }
  597. return diskMap
  598. }
  599. func buildLabelsMap(
  600. resLabels []*source.NodeLabelsResult,
  601. ) map[nodeIdentifierNoProviderID]map[string]string {
  602. m := make(map[nodeIdentifierNoProviderID]map[string]string)
  603. // Copy labels into node
  604. for _, result := range resLabels {
  605. cluster := result.Cluster
  606. if cluster == "" {
  607. cluster = coreenv.GetClusterID()
  608. }
  609. node := result.Node
  610. if node == "" {
  611. log.DedupedWarningf(5, "ClusterNodes: label data missing node")
  612. continue
  613. }
  614. key := nodeIdentifierNoProviderID{
  615. Cluster: cluster,
  616. Name: node,
  617. }
  618. // The QueryResult.GetLabels function needs to be called to sanitize the
  619. // ingested label data. This removes the label_ prefix that prometheus
  620. // adds to emitted labels. It also keeps from ingesting prometheus labels
  621. // that aren't a part of the asset.
  622. if _, ok := m[key]; !ok {
  623. m[key] = map[string]string{}
  624. }
  625. for k, l := range result.Labels {
  626. m[key][k] = l
  627. }
  628. }
  629. return m
  630. }
  631. // checkForKeyAndInitIfMissing inits a key in the provided nodemap if
  632. // it does not exist. Intended to be called ONLY by buildNodeMap
  633. func checkForKeyAndInitIfMissing(
  634. nodeMap map[NodeIdentifier]*Node,
  635. key NodeIdentifier,
  636. clusterAndNameToType map[nodeIdentifierNoProviderID]string,
  637. ) {
  638. if _, ok := nodeMap[key]; !ok {
  639. // default nodeType in case we don't have the mapping
  640. var nodeType string
  641. if t, ok := clusterAndNameToType[nodeIdentifierNoProviderID{
  642. Cluster: key.Cluster,
  643. Name: key.Name,
  644. }]; ok {
  645. nodeType = t
  646. } else {
  647. log.Warnf("ClusterNodes: Type does not exist for node identifier %s", key)
  648. }
  649. nodeMap[key] = &Node{
  650. Cluster: key.Cluster,
  651. Name: key.Name,
  652. NodeType: nodeType,
  653. ProviderID: key.ProviderID,
  654. CPUBreakdown: &ClusterCostsBreakdown{},
  655. RAMBreakdown: &ClusterCostsBreakdown{},
  656. }
  657. }
  658. }
  659. // buildNodeMap creates the main set of node data for ClusterNodes from
  660. // the data maps built from Prometheus queries. Some of the Prometheus
  661. // data has access to the provider_id field and some does not. To get
  662. // around this problem, we use the data that includes provider_id
  663. // to build up the definitive set of nodes and then use the data
  664. // with less-specific identifiers (i.e. without provider_id) to fill
  665. // in the remaining fields.
  666. //
  667. // For example, let's say we have nodes identified like so:
  668. // cluster name/node name/provider_id. For the sake of the example,
  669. // we will also limit data to CPU cost, CPU cores, and preemptibility.
  670. //
  671. // We have CPU cost data that looks like this:
  672. // cluster1/node1/prov_node1_A: $10
  673. // cluster1/node1/prov_node1_B: $8
  674. // cluster1/node2/prov_node2: $15
  675. //
  676. // We have Preemptible data that looks like this:
  677. // cluster1/node1/prov_node1_A: true
  678. // cluster1/node1/prov_node1_B: false
  679. // cluster1/node2/prov_node2_B: false
  680. //
  681. // We have CPU cores data that looks like this:
  682. // cluster1/node1: 4
  683. // cluster1/node2: 6
  684. //
  685. // This function first combines the data that is fully identified,
  686. // creating the following:
  687. // cluster1/node1/prov_node1_A: CPUCost($10), Preemptible(true)
  688. // cluster1/node1/prov_node1_B: CPUCost($8), Preemptible(false)
  689. // cluster1/node2/prov_node2: CPUCost($15), Preemptible(false)
  690. //
  691. // It then uses the less-specific data to extend the specific data,
  692. // making the following:
  693. // cluster1/node1/prov_node1_A: CPUCost($10), Preemptible(true), Cores(4)
  694. // cluster1/node1/prov_node1_B: CPUCost($8), Preemptible(false), Cores(4)
  695. // cluster1/node2/prov_node2: CPUCost($15), Preemptible(false), Cores(6)
  696. //
  697. // In the situation where provider_id doesn't exist for any metrics,
  698. // that is the same as all provider_ids being empty strings. If
  699. // provider_id doesn't exist at all, then we (without having to do
  700. // extra work) easily fall back on identifying nodes only by cluster name
  701. // and node name because the provider_id part of the key will always
  702. // be the empty string.
  703. //
  704. // It is worth nothing that, in this approach, if a node is not present
  705. // in the more specific data but is present in the less-specific data,
  706. // that data is never processed into the final node map. For example,
  707. // let's say the CPU cores map has the following entry:
  708. // cluster1/node8: 6
  709. // But none of the maps with provider_id (CPU cost, RAM cost, etc.)
  710. // have an identifier for cluster1/node8 (regardless of provider_id).
  711. // In this situation, the final node map will not have a cluster1/node8
  712. // entry. This could be fixed by iterating over all of the less specific
  713. // identifiers and, inside that iteration, all of the identifiers in
  714. // the node map, but this would introduce a roughly quadratic time
  715. // complexity.
  716. func buildNodeMap(
  717. cpuCostMap, ramCostMap, gpuCostMap, gpuCountMap map[NodeIdentifier]float64,
  718. cpuCoresMap, ramBytesMap, ramUserPctMap,
  719. ramSystemPctMap map[nodeIdentifierNoProviderID]float64,
  720. cpuBreakdownMap map[nodeIdentifierNoProviderID]*ClusterCostsBreakdown,
  721. activeDataMap map[NodeIdentifier]activeData,
  722. preemptibleMap map[NodeIdentifier]bool,
  723. labelsMap map[nodeIdentifierNoProviderID]map[string]string,
  724. clusterAndNameToType map[nodeIdentifierNoProviderID]string,
  725. overheadMap map[nodeIdentifierNoProviderID]*NodeOverhead,
  726. ) map[NodeIdentifier]*Node {
  727. nodeMap := make(map[NodeIdentifier]*Node)
  728. // Initialize the map with the most-specific data:
  729. for id, cost := range cpuCostMap {
  730. checkForKeyAndInitIfMissing(nodeMap, id, clusterAndNameToType)
  731. nodeMap[id].CPUCost = cost
  732. }
  733. for id, cost := range ramCostMap {
  734. checkForKeyAndInitIfMissing(nodeMap, id, clusterAndNameToType)
  735. nodeMap[id].RAMCost = cost
  736. }
  737. for id, cost := range gpuCostMap {
  738. checkForKeyAndInitIfMissing(nodeMap, id, clusterAndNameToType)
  739. nodeMap[id].GPUCost = cost
  740. }
  741. for id, count := range gpuCountMap {
  742. checkForKeyAndInitIfMissing(nodeMap, id, clusterAndNameToType)
  743. nodeMap[id].GPUCount = count
  744. }
  745. for id, preemptible := range preemptibleMap {
  746. checkForKeyAndInitIfMissing(nodeMap, id, clusterAndNameToType)
  747. nodeMap[id].Preemptible = preemptible
  748. }
  749. for id, activeData := range activeDataMap {
  750. checkForKeyAndInitIfMissing(nodeMap, id, clusterAndNameToType)
  751. nodeMap[id].Start = activeData.start
  752. nodeMap[id].End = activeData.end
  753. nodeMap[id].Minutes = nodeMap[id].End.Sub(nodeMap[id].Start).Minutes()
  754. }
  755. // We now merge in data that doesn't have a provider id by looping over
  756. // all keys already added and inserting data according to their
  757. // cluster name/node name combos.
  758. for id, nodePtr := range nodeMap {
  759. clusterAndNameID := nodeIdentifierNoProviderID{
  760. Cluster: id.Cluster,
  761. Name: id.Name,
  762. }
  763. if cores, ok := cpuCoresMap[clusterAndNameID]; ok {
  764. nodePtr.CPUCores = cores
  765. if v, ok := partialCPUMap[nodePtr.NodeType]; ok {
  766. if cores > 0 {
  767. nodePtr.CPUCores = v
  768. adjustmentFactor := v / cores
  769. nodePtr.CPUCost = nodePtr.CPUCost * adjustmentFactor
  770. }
  771. }
  772. }
  773. if ramBytes, ok := ramBytesMap[clusterAndNameID]; ok {
  774. nodePtr.RAMBytes = ramBytes
  775. }
  776. if ramUserPct, ok := ramUserPctMap[clusterAndNameID]; ok {
  777. nodePtr.RAMBreakdown.User = ramUserPct
  778. }
  779. if ramSystemPct, ok := ramSystemPctMap[clusterAndNameID]; ok {
  780. nodePtr.RAMBreakdown.System = ramSystemPct
  781. }
  782. if cpuBreakdown, ok := cpuBreakdownMap[clusterAndNameID]; ok {
  783. nodePtr.CPUBreakdown = cpuBreakdown
  784. }
  785. if labels, ok := labelsMap[clusterAndNameID]; ok {
  786. nodePtr.Labels = labels
  787. }
  788. if overhead, ok := overheadMap[clusterAndNameID]; ok {
  789. nodePtr.Overhead = overhead
  790. } else {
  791. // we were unable to compute overhead for this node
  792. // assume default case of no overhead
  793. nodePtr.Overhead = &NodeOverhead{}
  794. log.Warnf("unable to compute overhead for node %s - defaulting to no overhead", clusterAndNameID.Name)
  795. }
  796. }
  797. return nodeMap
  798. }