/
quota.go
99 lines (83 loc) · 2.01 KB
/
quota.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
// Copyright 2018 tsuru authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package mongodb
import (
"context"
"github.com/globalsign/mgo"
"github.com/globalsign/mgo/bson"
"github.com/tsuru/tsuru/db"
"github.com/tsuru/tsuru/types/quota"
)
var _ quota.QuotaStorage = "aStorage{}
type quotaStorage struct {
collection string
query func(string) bson.M
}
type quotaObject struct {
Quota quota.Quota
}
func (s *quotaStorage) SetLimit(ctx context.Context, name string, limit int) error {
_, err := s.Get(ctx, name)
if err != nil {
return err
}
query := s.query(name)
span := newMongoDBSpan(ctx, mongoSpanUpdate, s.collection)
span.SetQueryStatement(query)
defer span.Finish()
conn, err := db.Conn()
if err != nil {
span.SetError(err)
return err
}
defer conn.Close()
err = conn.Collection(s.collection).Update(
query,
bson.M{"$set": bson.M{"quota.limit": limit}},
)
span.SetError(err)
return err
}
func (s *quotaStorage) Set(ctx context.Context, name string, inUse int) error {
_, err := s.Get(ctx, name)
if err != nil {
return err
}
query := s.query(name)
span := newMongoDBSpan(ctx, mongoSpanUpdate, s.collection)
span.SetQueryStatement(query)
defer span.Finish()
conn, err := db.Conn()
if err != nil {
return err
}
defer conn.Close()
err = conn.Collection(s.collection).Update(
query,
bson.M{"$set": bson.M{"quota.inuse": inUse}},
)
return err
}
func (s *quotaStorage) Get(ctx context.Context, name string) (*quota.Quota, error) {
query := s.query(name)
span := newMongoDBSpan(ctx, mongoSpanFind, s.collection)
span.SetQueryStatement(query)
defer span.Finish()
var obj quotaObject
conn, err := db.Conn()
if err != nil {
span.SetError(err)
return nil, err
}
defer conn.Close()
err = conn.Collection(s.collection).Find(query).One(&obj)
if err != nil {
if err == mgo.ErrNotFound {
return nil, quota.ErrQuotaNotFound
}
span.SetError(err)
return nil, err
}
return &obj.Quota, nil
}