/
cluster.go
508 lines (458 loc) · 16.7 KB
/
cluster.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
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
/*******************************************************************************
*
* Copyright 2017-2020 SAP SE
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You should have received a copy of the License along with this
* program. If not, 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 reports
import (
"database/sql"
"encoding/json"
"strings"
"time"
"github.com/sapcc/go-api-declarations/limes"
limesrates "github.com/sapcc/go-api-declarations/limes/rates"
limesresources "github.com/sapcc/go-api-declarations/limes/resources"
"github.com/sapcc/go-bits/sqlext"
"github.com/sapcc/limes/internal/core"
"github.com/sapcc/limes/internal/db"
)
var clusterReportQuery1 = sqlext.SimplifyWhitespace(`
WITH project_commitment_sums AS (
SELECT az_resource_id, SUM(amount) AS amount
FROM project_commitments
WHERE state = 'active'
GROUP BY az_resource_id
)
SELECT ps.type, pr.name, par.az,
SUM(par.usage), SUM(COALESCE(par.physical_usage, par.usage)), COUNT(par.physical_usage) > 0,
SUM(GREATEST(0, COALESCE(pcs.amount, 0) - par.usage)),
MIN(ps.scraped_at), MAX(ps.scraped_at)
FROM project_services ps
LEFT OUTER JOIN project_resources pr ON pr.service_id = ps.id {{AND pr.name = $resource_name}}
LEFT OUTER JOIN project_az_resources par ON par.resource_id = pr.id
LEFT OUTER JOIN project_commitment_sums pcs ON pcs.az_resource_id = par.id
WHERE TRUE {{AND ps.type = $service_type}}
GROUP BY ps.type, pr.name, par.az
`)
// This was split from clusterReportQuery1 because the quota collection and burst usage calculation requires a different `GROUP BY`.
var clusterReportQuery1B = sqlext.SimplifyWhitespace(`
WITH project_az_sums AS (
SELECT resource_id, SUM(usage) AS usage
FROM project_az_resources
GROUP BY resource_id
)
SELECT ps.type, pr.name, SUM(GREATEST(pas.usage - pr.quota, 0))
FROM project_services ps
LEFT OUTER JOIN project_resources pr ON pr.service_id = ps.id {{AND pr.name = $resource_name}}
LEFT OUTER JOIN project_az_sums pas ON pas.resource_id = pr.id
WHERE TRUE {{AND ps.type = $service_type}}
GROUP BY ps.type, pr.name
`)
var clusterReportQuery2 = sqlext.SimplifyWhitespace(`
SELECT ds.type, dr.name, SUM(dr.quota)
FROM domain_services ds
LEFT OUTER JOIN domain_resources dr ON dr.service_id = ds.id {{AND dr.name = $resource_name}}
WHERE TRUE {{AND ds.type = $service_type}}
GROUP BY ds.type, dr.name
`)
var clusterReportQuery3 = sqlext.SimplifyWhitespace(`
SELECT cs.type, cr.name, car.az, car.raw_capacity, car.usage, car.subcapacities, cc.scraped_at
FROM cluster_services cs
LEFT OUTER JOIN cluster_resources cr ON cr.service_id = cs.id {{AND cr.name = $resource_name}}
LEFT OUTER JOIN cluster_az_resources car ON car.resource_id = cr.id
LEFT OUTER JOIN cluster_capacitors cc ON cc.capacitor_id = cr.capacitor_id
WHERE TRUE {{AND cs.type = $service_type}}
ORDER BY car.az
`)
var clusterReportQuery4 = sqlext.SimplifyWhitespace(`
WITH project_commitment_sums AS (
SELECT az_resource_id, duration,
COALESCE(SUM(amount) FILTER (WHERE state = 'active'), 0) AS active,
COALESCE(SUM(amount) FILTER (WHERE state = 'pending'), 0) AS pending,
COALESCE(SUM(amount) FILTER (WHERE state = 'planned'), 0) AS planned
FROM project_commitments
GROUP BY az_resource_id, duration
)
SELECT ps.type, pr.name, par.az,
pcs.duration, SUM(pcs.active), SUM(pcs.pending), SUM(pcs.planned)
FROM project_services ps
JOIN project_resources pr ON pr.service_id = ps.id {{AND pr.name = $resource_name}}
JOIN project_az_resources par ON par.resource_id = pr.id
JOIN project_commitment_sums pcs ON pcs.az_resource_id = par.id
WHERE TRUE {{AND ps.type = $service_type}}
GROUP BY ps.type, pr.name, par.az, pcs.duration
`)
var clusterRateReportQuery1 = sqlext.SimplifyWhitespace(`
SELECT type, MIN(rates_scraped_at), MAX(rates_scraped_at)
FROM project_services
WHERE TRUE {{AND type = $service_type}}
GROUP BY type
`)
// GetClusterResources returns the resource data report for the whole cluster.
func GetClusterResources(cluster *core.Cluster, now time.Time, dbi db.Interface, filter Filter) (*limesresources.ClusterReport, error) {
report := &limesresources.ClusterReport{
ClusterInfo: limes.ClusterInfo{
ID: "current", //multi-cluster support has been removed; this value is only included for backwards-compatibility
},
Services: make(limesresources.ClusterServiceReports),
}
//first query: collect project usage data in these clusters
queryStr, joinArgs := filter.PrepareQuery(clusterReportQuery1)
err := sqlext.ForeachRow(dbi, queryStr, joinArgs, func(rows *sql.Rows) error {
var (
serviceType string
resourceName *string
availabilityZone *limes.AvailabilityZone
usage *uint64
physicalUsage *uint64
showPhysicalUsage *bool
unusedCommitments *uint64
minScrapedAt *time.Time
maxScrapedAt *time.Time
)
err := rows.Scan(&serviceType, &resourceName, &availabilityZone,
&usage, &physicalUsage, &showPhysicalUsage, &unusedCommitments,
&minScrapedAt, &maxScrapedAt)
if err != nil {
return err
}
service, resource := findInClusterReport(cluster, report, serviceType, resourceName, now)
if service != nil {
service.MaxScrapedAt = mergeMaxTime(service.MaxScrapedAt, maxScrapedAt)
service.MinScrapedAt = mergeMinTime(service.MinScrapedAt, minScrapedAt)
}
if resource == nil || availabilityZone == nil {
return nil
}
resource.Usage += *usage
if *showPhysicalUsage {
sumPhysicalUsage := *physicalUsage
if resource.PhysicalUsage != nil {
sumPhysicalUsage += *resource.PhysicalUsage
}
resource.PhysicalUsage = &sumPhysicalUsage
}
if filter.WithAZBreakdown {
if resource.PerAZ == nil {
resource.PerAZ = make(limesresources.ClusterAZResourceReports)
}
azReport := limesresources.ClusterAZResourceReport{
ProjectsUsage: *usage,
UnusedCommitments: *unusedCommitments,
}
if *showPhysicalUsage {
azReport.PhysicalUsage = physicalUsage
}
resource.PerAZ[*availabilityZone] = &azReport
}
return nil
})
if err != nil {
return nil, err
}
//first query, addendum: collect burst usage data
clusterCanBurst := cluster.Config.Bursting.MaxMultiplier > 0
if clusterCanBurst {
queryStr, joinArgs = filter.PrepareQuery(clusterReportQuery1B)
err := sqlext.ForeachRow(dbi, queryStr, joinArgs, func(rows *sql.Rows) error {
var (
serviceType string
resourceName *string
burstUsage *uint64
)
err := rows.Scan(&serviceType, &resourceName, &burstUsage)
if err != nil {
return err
}
if burstUsage != nil {
_, resource := findInClusterReport(cluster, report, serviceType, resourceName, now)
if resource != nil {
resource.BurstUsage = *burstUsage
}
}
return nil
})
if err != nil {
return nil, err
}
}
//second query: collect domain quota data in these clusters
queryStr, joinArgs = filter.PrepareQuery(clusterReportQuery2)
err = sqlext.ForeachRow(dbi, queryStr, joinArgs, func(rows *sql.Rows) error {
var (
serviceType string
resourceName *string
quota *uint64
)
err := rows.Scan(&serviceType, &resourceName, "a)
if err != nil {
return err
}
_, resource := findInClusterReport(cluster, report, serviceType, resourceName, now)
if resource != nil && quota != nil && !resource.NoQuota {
resource.DomainsQuota = quota
}
return nil
})
if err != nil {
return nil, err
}
//third query: collect capacity data for these clusters
queryStr, joinArgs = filter.PrepareQuery(clusterReportQuery3)
if !filter.WithSubcapacities {
queryStr = strings.Replace(queryStr, "car.subcapacities", "''", 1)
}
err = sqlext.ForeachRow(dbi, queryStr, joinArgs, func(rows *sql.Rows) error {
var (
serviceType string
resourceName *string
availabilityZone *limes.AvailabilityZone
rawCapacityInAZ *uint64
usageInAZ *uint64
subcapacitiesInAZ *string
scrapedAt *time.Time
)
err := rows.Scan(&serviceType, &resourceName, &availabilityZone,
&rawCapacityInAZ, &usageInAZ, &subcapacitiesInAZ, &scrapedAt)
if err != nil {
return err
}
_, resource := findInClusterReport(cluster, report, serviceType, resourceName, now)
if resource != nil {
//NOTE: resource.Capacity is computed from this below once data for all AZs was ingested
if resource.RawCapacity == nil {
resource.RawCapacity = rawCapacityInAZ
} else if rawCapacityInAZ != nil {
resource.RawCapacity = pointerTo(*resource.RawCapacity + *rawCapacityInAZ)
}
if subcapacitiesInAZ != nil && *subcapacitiesInAZ != "" && filter.IsSubcapacityAllowed(serviceType, *resourceName) {
mergeJSONListInto(&resource.Subcapacities, *subcapacitiesInAZ)
}
if availabilityZone != nil && rawCapacityInAZ != nil {
azReport := limesresources.ClusterAvailabilityZoneReport{
Name: *availabilityZone,
Usage: unwrapOrDefault(usageInAZ, 0),
}
overcommitFactor := cluster.BehaviorForResource(serviceType, *resourceName, "").OvercommitFactor
azReport.Capacity = overcommitFactor.ApplyTo(*rawCapacityInAZ)
if azReport.Capacity != *rawCapacityInAZ {
azReport.RawCapacity = *rawCapacityInAZ
}
if resource.CapacityPerAZ == nil {
resource.CapacityPerAZ = make(limesresources.ClusterAvailabilityZoneReports)
}
resource.CapacityPerAZ[*availabilityZone] = &azReport
if filter.WithAZBreakdown {
if resource.PerAZ == nil {
resource.PerAZ = make(limesresources.ClusterAZResourceReports)
}
azReportV2 := resource.PerAZ[*availabilityZone]
if azReportV2 == nil {
azReportV2 = &limesresources.ClusterAZResourceReport{}
resource.PerAZ[*availabilityZone] = azReportV2
}
azReportV2.Capacity = azReport.Capacity
azReportV2.RawCapacity = azReport.RawCapacity
azReportV2.Usage = usageInAZ
azReportV2.Subcapacities = json.RawMessage(unwrapOrDefault(subcapacitiesInAZ, ""))
}
}
}
report.MaxScrapedAt = mergeMaxTime(report.MaxScrapedAt, scrapedAt)
report.MinScrapedAt = mergeMinTime(report.MinScrapedAt, scrapedAt)
return nil
})
if err != nil {
return nil, err
}
if filter.WithAZBreakdown {
//fourth query: collect commitment data that is broken down by commitment duration
queryStr, joinArgs = filter.PrepareQuery(clusterReportQuery4)
err = sqlext.ForeachRow(dbi, queryStr, joinArgs, func(rows *sql.Rows) error {
var (
serviceType string
resourceName string
az limes.AvailabilityZone
duration limesresources.CommitmentDuration
activeAmount uint64
pendingAmount uint64
plannedAmount uint64
)
err := rows.Scan(
&serviceType, &resourceName, &az,
&duration, &activeAmount, &pendingAmount, &plannedAmount,
)
if err != nil {
return err
}
_, resource := findInClusterReport(cluster, report, serviceType, &resourceName, now)
if resource == nil || resource.PerAZ[az] == nil {
return nil
}
azReport := resource.PerAZ[az]
if activeAmount > 0 {
if azReport.Committed == nil {
azReport.Committed = make(map[string]uint64)
}
azReport.Committed[duration.String()] = activeAmount
}
if pendingAmount > 0 {
if azReport.PendingCommitments == nil {
azReport.PendingCommitments = make(map[string]uint64)
}
azReport.PendingCommitments[duration.String()] = pendingAmount
}
if plannedAmount > 0 {
if azReport.PlannedCommitments == nil {
azReport.PlannedCommitments = make(map[string]uint64)
}
azReport.PlannedCommitments[duration.String()] = plannedAmount
}
return nil
})
if err != nil {
return nil, err
}
}
//epilogue: perform some calculations that require the full sum over all AZs to be done
for serviceType, service := range report.Services {
for resourceName, resource := range service.Resources {
overcommitFactor := cluster.BehaviorForResource(serviceType, resourceName, "").OvercommitFactor
if overcommitFactor == 0 {
resource.Capacity = resource.RawCapacity
resource.RawCapacity = nil
} else if resource.RawCapacity != nil {
resource.Capacity = pointerTo(overcommitFactor.ApplyTo(*resource.RawCapacity))
}
if skipAZBreakdown(resource.CapacityPerAZ) {
resource.CapacityPerAZ = nil
}
//project_az_resources always has entries for "any", even if the resource
//is AZ-aware, because ApplyComputedProjectQuota needs somewhere to write
//the base quotas; we ignore those entries here if the "any" usage is
//zero and there are other AZs
if len(resource.PerAZ) >= 2 {
capaInAny := resource.PerAZ[limes.AvailabilityZoneAny]
if capaInAny.Capacity == 0 && capaInAny.Usage == nil && capaInAny.ProjectsUsage == 0 {
delete(resource.PerAZ, limes.AvailabilityZoneAny)
}
}
}
}
return report, nil
}
// GetClusterRates returns the rate data report for the whole cluster.
func GetClusterRates(cluster *core.Cluster, dbi db.Interface, filter Filter) (*limesrates.ClusterReport, error) {
report := &limesrates.ClusterReport{
ClusterInfo: limes.ClusterInfo{
ID: "current", //multi-cluster support has been removed; this value is only included for backwards-compatibility
},
Services: make(limesrates.ClusterServiceReports),
}
//collect scraping timestamp summaries
queryStr, joinArgs := filter.PrepareQuery(clusterRateReportQuery1)
err := sqlext.ForeachRow(dbi, queryStr, joinArgs, func(rows *sql.Rows) error {
var (
serviceType string
minRatesScrapedAt *time.Time
maxRatesScrapedAt *time.Time
)
err := rows.Scan(&serviceType, &minRatesScrapedAt, &maxRatesScrapedAt)
if err != nil {
return err
}
if !cluster.HasService(serviceType) {
return nil
}
srvReport, exists := report.Services[serviceType]
if !exists {
srvReport = &limesrates.ClusterServiceReport{
ServiceInfo: cluster.InfoForService(serviceType),
Rates: make(limesrates.ClusterRateReports),
}
report.Services[serviceType] = srvReport
}
srvReport.MaxScrapedAt = mergeMaxTime(srvReport.MaxScrapedAt, maxRatesScrapedAt)
srvReport.MinScrapedAt = mergeMinTime(srvReport.MinScrapedAt, minRatesScrapedAt)
return nil
})
if err != nil {
return nil, err
}
//include global rate limits from configuration
for _, serviceConfig := range cluster.Config.Services {
srvReport := report.Services[serviceConfig.ServiceType]
if srvReport != nil {
for _, rateCfg := range serviceConfig.RateLimits.Global {
srvReport.Rates[rateCfg.Name] = &limesrates.ClusterRateReport{
RateInfo: limesrates.RateInfo{
Name: rateCfg.Name,
Unit: rateCfg.Unit,
},
Limit: rateCfg.Limit,
Window: rateCfg.Window,
}
}
}
}
return report, nil
}
func findInClusterReport(cluster *core.Cluster, report *limesresources.ClusterReport, serviceType string, resourceName *string, now time.Time) (*limesresources.ClusterServiceReport, *limesresources.ClusterResourceReport) {
service, exists := report.Services[serviceType]
if !exists {
if !cluster.HasService(serviceType) {
return nil, nil
}
service = &limesresources.ClusterServiceReport{
ServiceInfo: cluster.InfoForService(serviceType),
Resources: make(limesresources.ClusterResourceReports),
}
report.Services[serviceType] = service
}
if resourceName == nil {
return service, nil
}
resource, exists := service.Resources[*resourceName]
if !exists {
if !cluster.HasResource(serviceType, *resourceName) {
return service, nil
}
globalBehavior := cluster.BehaviorForResource(serviceType, *resourceName, "")
resource = &limesresources.ClusterResourceReport{
ResourceInfo: cluster.InfoForResource(serviceType, *resourceName),
CommitmentConfig: globalBehavior.ToCommitmentConfig(now),
}
if !resource.ResourceInfo.NoQuota {
qdConfig := cluster.QuotaDistributionConfigForResource(serviceType, *resourceName)
resource.QuotaDistributionModel = qdConfig.Model
//We need to set a default value here. Otherwise zero values will never
//be reported when there are no `domain_resources` entries to aggregate
//over.
defaultDomainsQuota := uint64(0)
resource.DomainsQuota = &defaultDomainsQuota
}
service.Resources[*resourceName] = resource
}
return service, resource
}
func skipAZBreakdown(azReports limesresources.ClusterAvailabilityZoneReports) bool {
for az := range azReports {
if az != limes.AvailabilityZoneAny {
return false
}
}
return true
}