-
Notifications
You must be signed in to change notification settings - Fork 402
/
bandwidthdb.go
442 lines (359 loc) · 13.1 KB
/
bandwidthdb.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
// Copyright (C) 2019 Storj Labs, Inc.
// See LICENSE for copying information.
package storagenodedb
import (
"context"
"database/sql"
"errors"
"sync"
"time"
"github.com/zeebo/errs"
"storj.io/common/pb"
"storj.io/common/storj"
"storj.io/private/dbutil"
"storj.io/storj/private/date"
"storj.io/storj/storagenode/bandwidth"
)
// ErrBandwidth represents errors from the bandwidthdb database.
var ErrBandwidth = errs.Class("bandwidthdb")
// BandwidthDBName represents the database name.
const BandwidthDBName = "bandwidth"
type bandwidthDB struct {
// Moved to top of struct to resolve alignment issue with atomic operations on ARM
usedSpace int64
usedMu sync.RWMutex
usedSince time.Time
dbContainerImpl
}
// Add adds bandwidth usage to the table.
func (db *bandwidthDB) Add(ctx context.Context, satelliteID storj.NodeID, action pb.PieceAction, amount int64, created time.Time) (err error) {
defer mon.Task()(&ctx)(&err)
_, err = db.ExecContext(ctx, `
INSERT INTO
bandwidth_usage(satellite_id, action, amount, created_at)
VALUES(?, ?, ?, datetime(?))`, satelliteID, action, amount, created.UTC())
if err == nil {
db.usedMu.Lock()
defer db.usedMu.Unlock()
beginningOfMonth := getBeginningOfMonth(created.UTC())
if beginningOfMonth.Equal(db.usedSince) {
db.usedSpace += amount
} else if beginningOfMonth.After(db.usedSince) {
usage, err := db.Summary(ctx, beginningOfMonth, time.Now())
if err != nil {
return err
}
db.usedSince = beginningOfMonth
db.usedSpace = usage.Total()
}
}
return ErrBandwidth.Wrap(err)
}
// MonthSummary returns summary of the current months bandwidth usages.
func (db *bandwidthDB) MonthSummary(ctx context.Context, now time.Time) (_ int64, err error) {
defer mon.Task()(&ctx)(&err)
db.usedMu.RLock()
beginningOfMonth := getBeginningOfMonth(now)
if beginningOfMonth.Equal(db.usedSince) {
defer db.usedMu.RUnlock()
return db.usedSpace, nil
}
db.usedMu.RUnlock()
usage, err := db.Summary(ctx, beginningOfMonth, now)
if err != nil {
return 0, err
}
// Just return the usage, don't update the cache. Let add handle updates
return usage.Total(), nil
}
// actionFilter sums bandwidth depending on piece action type.
type actionFilter func(action pb.PieceAction, amount int64, usage *bandwidth.Usage)
var (
// ingressFilter sums put and put repair.
ingressFilter actionFilter = func(action pb.PieceAction, amount int64, usage *bandwidth.Usage) {
switch action {
case pb.PieceAction_PUT, pb.PieceAction_PUT_REPAIR:
usage.Include(action, amount)
}
}
// egressFilter sums get, get audit and get repair.
egressFilter actionFilter = func(action pb.PieceAction, amount int64, usage *bandwidth.Usage) {
switch action {
case pb.PieceAction_GET, pb.PieceAction_GET_AUDIT, pb.PieceAction_GET_REPAIR:
usage.Include(action, amount)
}
}
// bandwidthFilter sums all bandwidth.
bandwidthFilter actionFilter = func(action pb.PieceAction, amount int64, usage *bandwidth.Usage) {
usage.Include(action, amount)
}
)
// Summary returns summary of bandwidth usages for all satellites.
func (db *bandwidthDB) Summary(ctx context.Context, from, to time.Time) (_ *bandwidth.Usage, err error) {
defer mon.Task()(&ctx)(&err)
return db.getSummary(ctx, from, to, bandwidthFilter)
}
// EgressSummary returns summary of egress usages for all satellites.
func (db *bandwidthDB) EgressSummary(ctx context.Context, from, to time.Time) (_ *bandwidth.Usage, err error) {
defer mon.Task()(&ctx)(&err)
return db.getSummary(ctx, from, to, egressFilter)
}
// IngressSummary returns summary of ingress usages for all satellites.
func (db *bandwidthDB) IngressSummary(ctx context.Context, from, to time.Time) (_ *bandwidth.Usage, err error) {
defer mon.Task()(&ctx)(&err)
return db.getSummary(ctx, from, to, ingressFilter)
}
// getSummary returns bandwidth data for all satellites.
func (db *bandwidthDB) getSummary(ctx context.Context, from, to time.Time, filter actionFilter) (_ *bandwidth.Usage, err error) {
defer mon.Task()(&ctx)(&err)
usage := &bandwidth.Usage{}
from, to = from.UTC(), to.UTC()
rows, err := db.QueryContext(ctx, `
SELECT action, sum(a) amount from(
SELECT action, sum(amount) a
FROM bandwidth_usage
WHERE datetime(?) <= created_at AND created_at <= datetime(?)
GROUP BY action
UNION ALL
SELECT action, sum(amount) a
FROM bandwidth_usage_rollups
WHERE datetime(?) <= interval_start AND interval_start <= datetime(?)
GROUP BY action
) GROUP BY action;
`, from, to, from, to)
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
return usage, nil
}
return nil, ErrBandwidth.Wrap(err)
}
defer func() { err = errs.Combine(err, rows.Close()) }()
for rows.Next() {
var action pb.PieceAction
var amount int64
err := rows.Scan(&action, &amount)
if err != nil {
return nil, ErrBandwidth.Wrap(err)
}
filter(action, amount, usage)
}
return usage, ErrBandwidth.Wrap(rows.Err())
}
// SatelliteSummary returns summary of bandwidth usages for a particular satellite.
func (db *bandwidthDB) SatelliteSummary(ctx context.Context, satelliteID storj.NodeID, from, to time.Time) (_ *bandwidth.Usage, err error) {
defer mon.Task()(&ctx, satelliteID, from, to)(&err)
return db.getSatelliteSummary(ctx, satelliteID, from, to, bandwidthFilter)
}
// SatelliteEgressSummary returns summary of egress usage for a particular satellite.
func (db *bandwidthDB) SatelliteEgressSummary(ctx context.Context, satelliteID storj.NodeID, from, to time.Time) (_ *bandwidth.Usage, err error) {
defer mon.Task()(&ctx, satelliteID, from, to)(&err)
return db.getSatelliteSummary(ctx, satelliteID, from, to, egressFilter)
}
// SatelliteIngressSummary returns summary of ingress usage for a particular satellite.
func (db *bandwidthDB) SatelliteIngressSummary(ctx context.Context, satelliteID storj.NodeID, from, to time.Time) (_ *bandwidth.Usage, err error) {
defer mon.Task()(&ctx, satelliteID, from, to)(&err)
return db.getSatelliteSummary(ctx, satelliteID, from, to, ingressFilter)
}
// getSummary returns bandwidth data for a particular satellite.
func (db *bandwidthDB) getSatelliteSummary(ctx context.Context, satelliteID storj.NodeID, from, to time.Time, filter actionFilter) (_ *bandwidth.Usage, err error) {
defer mon.Task()(&ctx, satelliteID, from, to)(&err)
from, to = from.UTC(), to.UTC()
query := `SELECT action, sum(a) amount from(
SELECT action, sum(amount) a
FROM bandwidth_usage
WHERE datetime(?) <= created_at AND created_at <= datetime(?)
AND satellite_id = ?
GROUP BY action
UNION ALL
SELECT action, sum(amount) a
FROM bandwidth_usage_rollups
WHERE datetime(?) <= interval_start AND interval_start <= datetime(?)
AND satellite_id = ?
GROUP BY action
) GROUP BY action;`
rows, err := db.QueryContext(ctx, query, from, to, satelliteID, from, to, satelliteID)
if err != nil {
return nil, ErrBandwidth.Wrap(err)
}
defer func() {
err = ErrBandwidth.Wrap(errs.Combine(err, rows.Close()))
}()
usage := new(bandwidth.Usage)
for rows.Next() {
var action pb.PieceAction
var amount int64
err := rows.Scan(&action, &amount)
if err != nil {
return nil, err
}
filter(action, amount, usage)
}
return usage, ErrBandwidth.Wrap(rows.Err())
}
// SummaryBySatellite returns summary of bandwidth usage grouping by satellite.
func (db *bandwidthDB) SummaryBySatellite(ctx context.Context, from, to time.Time) (_ map[storj.NodeID]*bandwidth.Usage, err error) {
defer mon.Task()(&ctx)(&err)
entries := map[storj.NodeID]*bandwidth.Usage{}
from, to = from.UTC(), to.UTC()
rows, err := db.QueryContext(ctx, `
SELECT satellite_id, action, sum(a) amount from(
SELECT satellite_id, action, sum(amount) a
FROM bandwidth_usage
WHERE datetime(?) <= created_at AND created_at <= datetime(?)
GROUP BY satellite_id, action
UNION ALL
SELECT satellite_id, action, sum(amount) a
FROM bandwidth_usage_rollups
WHERE datetime(?) <= interval_start AND interval_start <= datetime(?)
GROUP BY satellite_id, action
) GROUP BY satellite_id, action;
`, from, to, from, to)
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
return entries, nil
}
return nil, ErrBandwidth.Wrap(err)
}
defer func() { err = errs.Combine(err, rows.Close()) }()
for rows.Next() {
var satelliteID storj.NodeID
var action pb.PieceAction
var amount int64
err := rows.Scan(&satelliteID, &action, &amount)
if err != nil {
return nil, ErrBandwidth.Wrap(err)
}
entry, ok := entries[satelliteID]
if !ok {
entry = &bandwidth.Usage{}
entries[satelliteID] = entry
}
entry.Include(action, amount)
}
return entries, ErrBandwidth.Wrap(rows.Err())
}
// Rollup bandwidth_usage data earlier than the current hour, then delete the rolled up records.
func (db *bandwidthDB) Rollup(ctx context.Context) (err error) {
defer mon.Task()(&ctx)(&err)
now := time.Now().UTC()
// Go back an hour to give us room for late persists
hour := time.Date(now.Year(), now.Month(), now.Day(), now.Hour(), 0, 0, 0, now.Location()).Add(-time.Hour)
tx, err := db.BeginTx(ctx, nil)
if err != nil {
return ErrBandwidth.Wrap(err)
}
defer func() {
if err == nil {
err = tx.Commit()
} else {
err = errs.Combine(err, tx.Rollback())
}
}()
result, err := tx.ExecContext(ctx, `
INSERT INTO bandwidth_usage_rollups (interval_start, satellite_id, action, amount)
SELECT datetime(strftime('%Y-%m-%dT%H:00:00', created_at)) created_hr, satellite_id, action, SUM(amount)
FROM bandwidth_usage
WHERE created_at < datetime(?)
GROUP BY created_hr, satellite_id, action
ON CONFLICT(interval_start, satellite_id, action)
DO UPDATE SET amount = bandwidth_usage_rollups.amount + excluded.amount;
DELETE FROM bandwidth_usage WHERE created_at < datetime(?);
`, hour, hour)
if err != nil {
return ErrBandwidth.Wrap(err)
}
_, err = result.RowsAffected()
if err != nil {
return ErrBandwidth.Wrap(err)
}
return nil
}
// GetDailyRollups returns slice of daily bandwidth usage rollups for provided time range,
// sorted in ascending order.
func (db *bandwidthDB) GetDailyRollups(ctx context.Context, from, to time.Time) (_ []bandwidth.UsageRollup, err error) {
defer mon.Task()(&ctx, from, to)(&err)
since, _ := date.DayBoundary(from.UTC())
_, before := date.DayBoundary(to.UTC())
return db.getDailyUsageRollups(ctx,
"WHERE datetime(?) <= interval_start AND interval_start <= datetime(?)",
since, before)
}
// GetDailySatelliteRollups returns slice of daily bandwidth usage for provided time range,
// sorted in ascending order for a particular satellite.
func (db *bandwidthDB) GetDailySatelliteRollups(ctx context.Context, satelliteID storj.NodeID, from, to time.Time) (_ []bandwidth.UsageRollup, err error) {
defer mon.Task()(&ctx, satelliteID, from, to)(&err)
since, _ := date.DayBoundary(from.UTC())
_, before := date.DayBoundary(to.UTC())
return db.getDailyUsageRollups(ctx,
"WHERE satellite_id = ? AND datetime(?) <= interval_start AND interval_start <= datetime(?)",
satelliteID, since, before)
}
// getDailyUsageRollups returns slice of grouped by date bandwidth usage rollups
// sorted in ascending order and applied condition if any.
func (db *bandwidthDB) getDailyUsageRollups(ctx context.Context, cond string, args ...interface{}) (_ []bandwidth.UsageRollup, err error) {
defer mon.Task()(&ctx)(&err)
query := `SELECT action, sum(a) as amount, DATETIME(DATE(interval_start)) as date FROM (
SELECT action, sum(amount) as a, created_at AS interval_start
FROM bandwidth_usage
` + cond + `
GROUP BY interval_start, action
UNION ALL
SELECT action, sum(amount) as a, interval_start
FROM bandwidth_usage_rollups
` + cond + `
GROUP BY interval_start, action
) GROUP BY date, action
ORDER BY interval_start`
// duplicate args as they are used twice
args = append(args, args...)
rows, err := db.QueryContext(ctx, query, args...)
if err != nil {
return nil, ErrBandwidth.Wrap(err)
}
defer func() {
err = ErrBandwidth.Wrap(errs.Combine(err, rows.Close()))
}()
var dates []time.Time
usageRollupsByDate := make(map[time.Time]*bandwidth.UsageRollup)
for rows.Next() {
var action int32
var amount int64
var intervalStartN dbutil.NullTime
err = rows.Scan(&action, &amount, &intervalStartN)
if err != nil {
return nil, err
}
intervalStart := intervalStartN.Time
rollup, ok := usageRollupsByDate[intervalStart]
if !ok {
rollup = &bandwidth.UsageRollup{
IntervalStart: intervalStart,
}
dates = append(dates, intervalStart)
usageRollupsByDate[intervalStart] = rollup
}
switch pb.PieceAction(action) {
case pb.PieceAction_GET:
rollup.Egress.Usage = amount
case pb.PieceAction_GET_AUDIT:
rollup.Egress.Audit = amount
case pb.PieceAction_GET_REPAIR:
rollup.Egress.Repair = amount
case pb.PieceAction_PUT:
rollup.Ingress.Usage = amount
case pb.PieceAction_PUT_REPAIR:
rollup.Ingress.Repair = amount
case pb.PieceAction_DELETE:
rollup.Delete = amount
}
}
var usageRollups []bandwidth.UsageRollup
for _, d := range dates {
usageRollups = append(usageRollups, *usageRollupsByDate[d])
}
return usageRollups, ErrBandwidth.Wrap(rows.Err())
}
func getBeginningOfMonth(now time.Time) time.Time {
y, m, _ := now.UTC().Date()
return time.Date(y, m, 1, 0, 0, 0, 0, time.UTC)
}