-
Notifications
You must be signed in to change notification settings - Fork 133
/
metrics.go
311 lines (279 loc) · 9.79 KB
/
metrics.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
package scheduler
import (
"context"
"strings"
"sync/atomic"
"time"
"github.com/google/uuid"
"github.com/prometheus/client_golang/prometheus"
log "github.com/sirupsen/logrus"
"k8s.io/apimachinery/pkg/util/clock"
commonmetrics "github.com/armadaproject/armada/internal/common/metrics"
"github.com/armadaproject/armada/internal/common/resource"
"github.com/armadaproject/armada/internal/scheduler/database"
"github.com/armadaproject/armada/internal/scheduler/jobdb"
"github.com/armadaproject/armada/internal/scheduler/schedulerobjects"
)
// Metrics Recorders associated with a queue
type queueState struct {
queuedJobRecorder *commonmetrics.JobMetricsRecorder
runningJobRecorder *commonmetrics.JobMetricsRecorder
}
// metricProvider is a simple implementation of QueueMetricProvider
type metricProvider struct {
queueStates map[string]*queueState
}
func (m metricProvider) GetQueuedJobMetrics(queueName string) []*commonmetrics.QueueMetrics {
state, ok := m.queueStates[queueName]
if ok {
return state.queuedJobRecorder.Metrics()
}
return nil
}
func (m metricProvider) GetRunningJobMetrics(queueName string) []*commonmetrics.QueueMetrics {
state, ok := m.queueStates[queueName]
if ok {
return state.runningJobRecorder.Metrics()
}
return nil
}
// MetricsCollector is a Prometheus Collector that handles scheduler metrics.
// The metrics themselves are calculated asynchronously every refreshPeriod
type MetricsCollector struct {
jobDb *jobdb.JobDb
queueRepository database.QueueRepository
executorRepository database.ExecutorRepository
poolAssigner PoolAssigner
refreshPeriod time.Duration
clock clock.Clock
state atomic.Value
}
func NewMetricsCollector(
jobDb *jobdb.JobDb,
queueRepository database.QueueRepository,
executorRepository database.ExecutorRepository,
poolAssigner PoolAssigner,
refreshPeriod time.Duration,
) *MetricsCollector {
return &MetricsCollector{
jobDb: jobDb,
queueRepository: queueRepository,
executorRepository: executorRepository,
poolAssigner: poolAssigner,
refreshPeriod: refreshPeriod,
clock: clock.RealClock{},
state: atomic.Value{},
}
}
// Run enters s a loop which updates the metrics every refreshPeriod until the supplied context is cancelled
func (c *MetricsCollector) Run(ctx context.Context) error {
ticker := c.clock.NewTicker(c.refreshPeriod)
log.Infof("Will update metrics every %s", c.refreshPeriod)
for {
select {
case <-ctx.Done():
log.Debugf("Context cancelled, returning..")
return nil
case <-ticker.C():
err := c.refresh(ctx)
if err != nil {
log.WithError(err).Warnf("error refreshing metrics state")
}
}
}
}
// Describe returns all descriptions of the collector.
func (c *MetricsCollector) Describe(out chan<- *prometheus.Desc) {
commonmetrics.Describe(out)
}
// Collect returns the current state of all metrics of the collector.
func (c *MetricsCollector) Collect(metrics chan<- prometheus.Metric) {
state, ok := c.state.Load().([]prometheus.Metric)
if ok {
for _, m := range state {
metrics <- m
}
}
}
func (c *MetricsCollector) refresh(ctx context.Context) error {
log.Debugf("Refreshing prometheus metrics")
start := time.Now()
queueMetrics, err := c.updateQueueMetrics(ctx)
if err != nil {
return err
}
clusterMetrics, err := c.updateClusterMetrics(ctx)
if err != nil {
return err
}
allMetrics := append(queueMetrics, clusterMetrics...)
c.state.Store(allMetrics)
log.Debugf("Refreshed prometheus metrics in %s", time.Since(start))
return nil
}
func (c *MetricsCollector) updateQueueMetrics(ctx context.Context) ([]prometheus.Metric, error) {
queues, err := c.queueRepository.GetAllQueues()
if err != nil {
return nil, err
}
provider := metricProvider{queueStates: make(map[string]*queueState, len(queues))}
queuedJobsCount := make(map[string]int, len(queues))
for _, queue := range queues {
provider.queueStates[queue.Name] = &queueState{
queuedJobRecorder: commonmetrics.NewJobMetricsRecorder(),
runningJobRecorder: commonmetrics.NewJobMetricsRecorder(),
}
queuedJobsCount[queue.Name] = 0
}
err = c.poolAssigner.Refresh(ctx)
if err != nil {
return nil, err
}
currentTime := c.clock.Now()
for _, job := range c.jobDb.GetAll(c.jobDb.ReadTxn()) {
// Don't calculate metrics for dead jobs
if job.InTerminalState() {
continue
}
qs, ok := provider.queueStates[job.Queue()]
if !ok {
log.Warnf("job %s is in queue %s, but this queue does not exist; skipping", job.Id(), job.Queue())
continue
}
pool, err := c.poolAssigner.AssignPool(job)
if err != nil {
return nil, err
}
priorityClass := job.JobSchedulingInfo().PriorityClassName
resourceRequirements := job.JobSchedulingInfo().GetObjectRequirements()[0].GetPodRequirements().GetResourceRequirements().Requests
jobResources := make(map[string]float64)
for key, value := range resourceRequirements {
jobResources[string(key)] = resource.QuantityAsFloat64(value)
}
var recorder *commonmetrics.JobMetricsRecorder
var timeInState time.Duration
if job.Queued() {
recorder = qs.queuedJobRecorder
timeInState = currentTime.Sub(time.Unix(0, job.Created()))
queuedJobsCount[job.Queue()]++
} else if job.HasRuns() {
run := job.LatestRun()
timeInState = currentTime.Sub(time.Unix(0, run.Created()))
recorder = qs.runningJobRecorder
} else {
log.Warnf("Job %s is marked as leased but has no runs", job.Id())
}
recorder.RecordJobRuntime(pool, priorityClass, timeInState)
recorder.RecordResources(pool, priorityClass, jobResources)
}
queueMetrics := commonmetrics.CollectQueueMetrics(queuedJobsCount, provider)
return queueMetrics, nil
}
type queueMetricKey struct {
cluster string
pool string
queueName string
nodeType string
}
type queuePhaseMetricKey struct {
cluster string
pool string
queueName string
nodeType string
phase string
}
type clusterMetricKey struct {
cluster string
pool string
nodeType string
}
func (c *MetricsCollector) updateClusterMetrics(ctx context.Context) ([]prometheus.Metric, error) {
executors, err := c.executorRepository.GetExecutors(ctx)
if err != nil {
return nil, err
}
phaseCountByQueue := map[queuePhaseMetricKey]int{}
allocatedResourceByQueue := map[queueMetricKey]schedulerobjects.ResourceList{}
usedResourceByQueue := map[queueMetricKey]schedulerobjects.ResourceList{}
availableResourceByCluster := map[clusterMetricKey]schedulerobjects.ResourceList{}
totalResourceByCluster := map[clusterMetricKey]schedulerobjects.ResourceList{}
txn := c.jobDb.ReadTxn()
for _, executor := range executors {
for _, node := range executor.Nodes {
clusterKey := clusterMetricKey{
cluster: executor.Id,
pool: executor.Pool,
nodeType: node.ReportingNodeType,
}
addToResourceListMap(availableResourceByCluster, clusterKey, node.AvailableArmadaResource())
addToResourceListMap(totalResourceByCluster, clusterKey, node.TotalResources)
for queueName, resourceUsage := range node.ResourceUsageByQueue {
queueKey := queueMetricKey{
cluster: executor.Id,
pool: executor.Pool,
queueName: queueName,
nodeType: node.ReportingNodeType,
}
addToResourceListMap(usedResourceByQueue, queueKey, *resourceUsage)
}
for runId, jobRunState := range node.StateByJobRunId {
job := c.jobDb.GetByRunId(txn, uuid.MustParse(runId))
if job != nil {
phase := schedulerobjects.JobRunState_name[int32(jobRunState)]
key := queuePhaseMetricKey{
cluster: executor.Id,
pool: executor.Pool,
queueName: job.Queue(),
nodeType: node.ReportingNodeType,
// Convert to string with first letter capitalised
phase: strings.Title(strings.ToLower(phase)),
}
phaseCountByQueue[key]++
podRequirements := job.PodRequirements()
if podRequirements != nil {
queueKey := queueMetricKey{
cluster: executor.Id,
pool: executor.Pool,
queueName: job.Queue(),
nodeType: node.ReportingNodeType,
}
addToResourceListMap(allocatedResourceByQueue, queueKey, schedulerobjects.ResourceListFromV1ResourceList(podRequirements.ResourceRequirements.Requests))
}
}
}
}
}
clusterMetrics := make([]prometheus.Metric, 0, len(phaseCountByQueue))
for k, v := range phaseCountByQueue {
clusterMetrics = append(clusterMetrics, commonmetrics.NewQueueLeasedPodCount(float64(v), k.cluster, k.pool, k.queueName, k.phase, k.nodeType))
}
for k, r := range allocatedResourceByQueue {
for resourceKey, resourceValue := range r.Resources {
clusterMetrics = append(clusterMetrics, commonmetrics.NewQueueAllocated(resource.QuantityAsFloat64(resourceValue), k.queueName, k.cluster, k.pool, resourceKey, k.nodeType))
}
}
for k, r := range usedResourceByQueue {
for resourceKey, resourceValue := range r.Resources {
clusterMetrics = append(clusterMetrics, commonmetrics.NewQueueUsed(resource.QuantityAsFloat64(resourceValue), k.queueName, k.cluster, k.pool, resourceKey, k.nodeType))
}
}
for k, r := range availableResourceByCluster {
for resourceKey, resourceValue := range r.Resources {
clusterMetrics = append(clusterMetrics, commonmetrics.NewClusterAvailableCapacity(resource.QuantityAsFloat64(resourceValue), k.cluster, k.pool, resourceKey, k.nodeType))
}
}
for k, r := range totalResourceByCluster {
for resourceKey, resourceValue := range r.Resources {
clusterMetrics = append(clusterMetrics, commonmetrics.NewClusterTotalCapacity(resource.QuantityAsFloat64(resourceValue), k.cluster, k.pool, resourceKey, k.nodeType))
}
}
return clusterMetrics, nil
}
func addToResourceListMap[K comparable](m map[K]schedulerobjects.ResourceList, key K, value schedulerobjects.ResourceList) {
if _, exists := m[key]; !exists {
m[key] = schedulerobjects.ResourceList{}
}
newValue := m[key]
newValue.Add(value)
m[key] = newValue
}