/
cron.go
402 lines (341 loc) · 13.2 KB
/
cron.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
/*
Copyright 2022 Cortex Labs, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package operator
import (
"context"
"github.com/cortexlabs/cortex/pkg/config"
"github.com/cortexlabs/cortex/pkg/consts"
"github.com/cortexlabs/cortex/pkg/lib/aws"
"github.com/cortexlabs/cortex/pkg/lib/errors"
"github.com/cortexlabs/cortex/pkg/lib/k8s"
"github.com/cortexlabs/cortex/pkg/lib/logging"
libmath "github.com/cortexlabs/cortex/pkg/lib/math"
"github.com/cortexlabs/cortex/pkg/lib/sets/strset"
"github.com/cortexlabs/cortex/pkg/lib/telemetry"
"github.com/cortexlabs/cortex/pkg/types/clusterconfig"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
v1 "k8s.io/api/core/v1"
kmeta "k8s.io/apimachinery/pkg/apis/meta/v1"
"sigs.k8s.io/controller-runtime/pkg/client"
)
var operatorLogger = logging.GetLogger()
var previousListOfEvictedPods = strset.New()
func DeleteEvictedPods() error {
failedPods, err := config.K8s.ListPods(&kmeta.ListOptions{
FieldSelector: "status.phase=Failed",
})
if err != nil {
return err
}
var errs []error
currentEvictedPods := strset.New()
for _, pod := range failedPods {
if pod.Status.Reason != k8s.ReasonEvicted {
continue
}
if previousListOfEvictedPods.Has(pod.Name) {
_, err := config.K8s.DeletePod(pod.Name)
if err != nil {
errs = append(errs, err)
}
continue
}
currentEvictedPods.Add(pod.Name)
}
previousListOfEvictedPods = currentEvictedPods
if errors.HasError(errs) {
return errors.FirstError(errs...)
}
return nil
}
type instanceInfo struct {
InstanceType string `json:"instance_type" yaml:"instance_type"`
IsSpot bool `json:"is_spot" yaml:"is_spot"`
Price float64 `json:"price" yaml:"price"`
OnDemandPrice float64 `json:"on_demand_price" yaml:"on_demand_price"`
Count int32 `json:"count" yaml:"count"`
Memory int64 `json:"memory" yaml:"memory"`
CPU float64 `json:"cpu" yaml:"cpu"`
GPU int64 `json:"gpu" yaml:"gpu"`
Inf int64 `json:"inf" yaml:"inf"`
}
func ClusterTelemetry() error {
properties, err := clusterTelemetryProperties()
if err != nil {
return err
}
telemetry.Event("operator.cron", properties,
config.ClusterConfig.CoreConfig.TelemetryEvent(),
)
return nil
}
func clusterTelemetryProperties() (map[string]interface{}, error) {
ctx := context.Background()
var nodeList v1.NodeList
err := config.K8s.List(ctx, &nodeList)
if err != nil {
return nil, err
}
nodes := nodeList.Items
instanceInfos := make(map[string]*instanceInfo)
var numOperatorInstances int
var totalInstances int
var totalInstancePrice float64
var totalInstancePriceIfOnDemand float64
spotPriceCache := make(map[string]float64) // instance type -> spot price
for _, node := range nodes {
if node.Labels["workload"] != "true" {
if node.Labels["alpha.eksctl.io/nodegroup-name"] == "cx-operator" {
numOperatorInstances++
}
continue
}
instanceType := node.Labels["node.kubernetes.io/instance-type"]
if instanceType == "" {
instanceType = "unknown"
}
isSpot := false
if node.Labels["node-lifecycle"] == "spot" {
isSpot = true
}
totalInstances++
instanceInfosKey := instanceType + "_ondemand"
if isSpot {
instanceInfosKey = instanceType + "_spot"
}
if info, ok := instanceInfos[instanceInfosKey]; ok {
info.Count++
continue
}
onDemandPrice := aws.InstanceMetadatas[config.ClusterConfig.Region][instanceType].Price
price := onDemandPrice
if isSpot {
if spotPrice, ok := spotPriceCache[instanceType]; ok {
price = spotPrice
} else {
spotPrice, err := config.AWS.SpotInstancePrice(instanceType)
if err == nil && spotPrice != 0 {
price = spotPrice
spotPriceCache[instanceType] = spotPrice
} else {
spotPriceCache[instanceType] = price // the request failed, so no need to try again in the future
}
}
}
ngName := node.Labels["alpha.eksctl.io/nodegroup-name"]
ebsPricePerVolume := getEBSPriceForNodeGroupInstance(config.ClusterConfig.NodeGroups, ngName)
onDemandPrice += ebsPricePerVolume
price += ebsPricePerVolume
gpuQty := node.Status.Capacity["nvidia.com/gpu"]
infQty := node.Status.Capacity["aws.amazon.com/neuron"]
info := instanceInfo{
InstanceType: instanceType,
IsSpot: isSpot,
Price: price,
OnDemandPrice: onDemandPrice,
Count: 1,
Memory: node.Status.Capacity.Memory().Value(),
CPU: float64(node.Status.Capacity.Cpu().MilliValue()) / 1000,
GPU: gpuQty.Value(),
Inf: infQty.Value(),
}
instanceInfos[instanceInfosKey] = &info
totalInstancePrice += info.Price
totalInstancePriceIfOnDemand += info.OnDemandPrice
}
fixedPrice := cortexSystemPrice(numOperatorInstances, 1)
return map[string]interface{}{
"region": config.ClusterConfig.Region,
"instance_count": totalInstances,
"instances": instanceInfos,
"fixed_price": fixedPrice,
"workload_price": totalInstancePrice,
"workload_price_if_on_demand": totalInstancePriceIfOnDemand,
"total_price": totalInstancePrice + fixedPrice,
"total_price_if_on_demand": totalInstancePriceIfOnDemand + fixedPrice,
}, nil
}
func getEBSPriceForNodeGroupInstance(ngs []*clusterconfig.NodeGroup, ngName string) float64 {
var ebsPrice float64
for _, ng := range ngs {
var ngNamePrefix string
if ng.Spot {
ngNamePrefix = "cx-ws-"
} else {
ngNamePrefix = "cx-wd-"
}
if ng.Name == ngNamePrefix+ngName {
ebsPrice = aws.EBSMetadatas[config.ClusterConfig.Region][ng.InstanceVolumeType.String()].PriceGB * float64(ng.InstanceVolumeSize) / 30 / 24
if ng.InstanceVolumeType == clusterconfig.IO1VolumeType && ng.InstanceVolumeIOPS != nil {
ebsPrice += aws.EBSMetadatas[config.ClusterConfig.Region][ng.InstanceVolumeType.String()].PriceIOPS * float64(*ng.InstanceVolumeIOPS) / 30 / 24
}
if ng.InstanceVolumeType == clusterconfig.GP3VolumeType && ng.InstanceVolumeIOPS != nil && ng.InstanceVolumeThroughput != nil {
ebsPrice += libmath.MaxFloat64(0, (aws.EBSMetadatas[config.ClusterConfig.Region][ng.InstanceVolumeType.String()].PriceIOPS-3000)*float64(*ng.InstanceVolumeIOPS)/30/24)
ebsPrice += libmath.MaxFloat64(0, (aws.EBSMetadatas[config.ClusterConfig.Region][ng.InstanceVolumeType.String()].PriceThroughput-125)*float64(*ng.InstanceVolumeThroughput)/30/24)
}
break
}
}
if ebsPrice == 0 && (ngName == "cx-operator" || ngName == "cx-prometheus") {
return aws.EBSMetadatas[config.ClusterConfig.Region]["gp3"].PriceGB * 20 / 30 / 24
}
return ebsPrice
}
func cortexSystemPrice(numOperatorInstances, numPrometheusInstances int) float64 {
eksPrice := aws.EKSPrices[config.ClusterConfig.Region]
metricsEBSPrice := aws.EBSMetadatas[config.ClusterConfig.Region]["gp2"].PriceGB * (40 + 2) / 30 / 24
nlbPrice := aws.NLBMetadatas[config.ClusterConfig.Region].Price
natUnitPrice := aws.NATMetadatas[config.ClusterConfig.Region].Price
var natTotalPrice float64
if config.ClusterConfig.NATGateway == clusterconfig.SingleNATGateway {
natTotalPrice = natUnitPrice
} else if config.ClusterConfig.NATGateway == clusterconfig.HighlyAvailableNATGateway {
natTotalPrice = natUnitPrice * float64(len(config.ClusterConfig.AvailabilityZones))
}
operatorInstancePrice := aws.InstanceMetadatas[config.ClusterConfig.Region]["t3.medium"].Price
operatorEBSPrice := aws.EBSMetadatas[config.ClusterConfig.Region]["gp3"].PriceGB * 20 / 30 / 24
prometheusInstancePrice := aws.InstanceMetadatas[config.ClusterConfig.Region][config.ClusterConfig.PrometheusInstanceType].Price
prometheusEBSPrice := aws.EBSMetadatas[config.ClusterConfig.Region]["gp3"].PriceGB * 20 / 30 / 24
fixedCosts := eksPrice + metricsEBSPrice + 2*nlbPrice + natTotalPrice +
float64(numOperatorInstances)*(operatorInstancePrice+operatorEBSPrice) +
float64(numPrometheusInstances)*(prometheusInstancePrice+prometheusEBSPrice)
return fixedCosts
}
var clusterGauge = promauto.NewGaugeVec(
prometheus.GaugeOpts{
Name: "cortex_cluster_cost",
Help: "The cost breakdown of the cortex cluster",
}, []string{"api", "kind", "component"},
)
func CostBreakdown() error {
ctx := context.Background()
var nodeList v1.NodeList
err := config.K8s.List(ctx, &nodeList)
if err != nil {
return err
}
nodes := nodeList.Items
var podList v1.PodList
err = config.K8s.List(ctx, &podList,
client.InNamespace(consts.DefaultNamespace),
client.HasLabels{"apiName", "apiKind"},
)
if err != nil {
return err
}
pods := podList.Items
spotPriceCache := make(map[string]float64) // instance type -> spot price
// Total cluster costs = cortex system + cortex workloads
var totalClusterCosts float64 = cortexSystemPrice(0, 0)
// Total cortex system costs = operator + prometheus node groups + workload daemonsets
var totalCortexSystemCosts float64 = cortexSystemPrice(0, 0)
// Total workload compute costs by api name
totalWorkloadComputeCostsByAPIName := make(map[string]float64, 0)
// Total workload compute costs by kind
totalWorkloadComputeCostsByAPIKind := make(map[string]float64, 0)
for _, node := range nodes {
instanceType := node.Labels["node.kubernetes.io/instance-type"]
if instanceType == "" {
continue
}
workloadNode := false
if node.Labels["workload"] == "true" {
workloadNode = true
}
isSpot := false
if node.Labels["node-lifecycle"] == "spot" {
isSpot = true
}
var instanceComputePrice float64
if isSpot {
if spotPrice, ok := spotPriceCache[instanceType]; ok {
instanceComputePrice = spotPrice
} else {
spotPrice, err := config.AWS.SpotInstancePrice(instanceType)
if err == nil && spotPrice != 0 {
instanceComputePrice = spotPrice
spotPriceCache[instanceType] = spotPrice
} else {
instanceComputePrice = aws.InstanceMetadatas[config.ClusterConfig.Region][instanceType].Price // the request failed, so no need to try again in the future
spotPriceCache[instanceType] = instanceComputePrice
}
}
} else {
instanceComputePrice = aws.InstanceMetadatas[config.ClusterConfig.Region][instanceType].Price
}
ngName := node.Labels["alpha.eksctl.io/nodegroup-name"]
instanceEBSPrice := getEBSPriceForNodeGroupInstance(config.ClusterConfig.NodeGroups, ngName)
instancePrice := instanceComputePrice + instanceEBSPrice
totalClusterCosts += instancePrice
if !workloadNode {
totalCortexSystemCosts += instancePrice
continue
}
for _, pod := range pods {
if pod.Spec.NodeName != node.Name {
continue
}
maxPods := k8s.HowManyPodsFitOnNode(pod.Spec, node, consts.CortexCPUPodReserved, consts.CortexMemPodReserved)
costPerPod := instancePrice / float64(maxPods)
if apiName, ok := pod.Labels["apiName"]; ok {
if _, okMap := totalWorkloadComputeCostsByAPIName[apiName]; okMap {
totalWorkloadComputeCostsByAPIName[apiName] += costPerPod
} else {
totalWorkloadComputeCostsByAPIName[apiName] = costPerPod
}
}
if apiKind, ok := pod.Labels["apiKind"]; ok {
if _, okMap := totalWorkloadComputeCostsByAPIName[apiKind]; okMap {
totalWorkloadComputeCostsByAPIKind[apiKind] += costPerPod
} else {
totalWorkloadComputeCostsByAPIKind[apiKind] = costPerPod
}
}
}
}
totalWorkloadComputeCosts := totalClusterCosts - totalCortexSystemCosts
var totalWorkloadComputeCostsFromAPIName float64
var totalWorkloadComputeCostsFromAPIKind float64
apiNameRenormalizationRatio := float64(1)
apiKindRenormalizationRatio := float64(1)
for apiName := range totalWorkloadComputeCostsByAPIName {
totalWorkloadComputeCostsFromAPIName += totalWorkloadComputeCostsByAPIName[apiName]
}
if totalWorkloadComputeCostsFromAPIName > 0 {
apiNameRenormalizationRatio = totalWorkloadComputeCosts / totalWorkloadComputeCostsFromAPIName
}
for apiKind := range totalWorkloadComputeCostsByAPIKind {
totalWorkloadComputeCostsFromAPIKind += totalWorkloadComputeCostsByAPIKind[apiKind]
}
if totalWorkloadComputeCostsFromAPIKind > 0 {
apiKindRenormalizationRatio = totalWorkloadComputeCosts / totalWorkloadComputeCostsFromAPIKind
}
clusterGauge.Reset()
clusterGauge.WithLabelValues("false", "false", "cluster-costs").Set(totalClusterCosts)
clusterGauge.WithLabelValues("false", "false", "cortex-system-costs").Set(totalCortexSystemCosts)
for apiName := range totalWorkloadComputeCostsByAPIName {
clusterGauge.WithLabelValues("true", "false", apiName).Set(totalWorkloadComputeCostsByAPIName[apiName] * apiNameRenormalizationRatio)
}
for apiKind := range totalWorkloadComputeCostsByAPIKind {
clusterGauge.WithLabelValues("false", "true", apiKind).Set(totalWorkloadComputeCostsByAPIKind[apiKind] * apiKindRenormalizationRatio)
}
return nil
}
func ErrorHandler(cronName string) func(error) {
return func(err error) {
err = errors.Wrap(err, cronName+" cron failed")
telemetry.Error(err)
operatorLogger.Error(err)
}
}