forked from juju/juju
/
txns.go
216 lines (198 loc) · 6.6 KB
/
txns.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
// Copyright 2012-2014 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package state
import (
"runtime/debug"
"strings"
"time"
"github.com/juju/errors"
"github.com/juju/mgo/v2/bson"
"github.com/juju/mgo/v2/txn"
jujutxn "github.com/juju/txn/v2"
)
func readTxnRevno(db Database, collectionName string, id interface{}) (int64, error) {
collection, closer := db.GetCollection(collectionName)
defer closer()
query := collection.FindId(id).Select(bson.D{{"txn-revno", 1}})
var result struct {
TxnRevno int64 `bson:"txn-revno"`
}
err := query.One(&result)
return result.TxnRevno, errors.Trace(err)
}
func (st *State) runRawTransaction(ops []txn.Op) error {
return st.database.RunRawTransaction(ops)
}
// ResumeTransactions resumes all pending transactions.
func (st *State) ResumeTransactions() error {
runner, closer := st.database.TransactionRunner()
defer closer()
return runner.ResumeTransactions()
}
// MaybePruneTransactions removes data for completed transactions.
func (st *State) MaybePruneTransactions() error {
runner, closer := st.database.TransactionRunner()
defer closer()
cfg, err := st.ControllerConfig()
if err != nil {
return errors.Trace(err)
}
// Prune txns when txn count has increased by 10% since last prune.
return runner.MaybePruneTransactions(jujutxn.PruneOptions{
PruneFactor: 1.1,
MinNewTransactions: 1000,
MaxNewTransactions: 100000,
MaxTime: time.Now().Add(-time.Hour),
MaxBatchTransactions: cfg.MaxPruneTxnBatchSize(),
MaxBatches: cfg.MaxPruneTxnPasses(),
SmallBatchTransactionCount: cfg.PruneTxnQueryCount(),
BatchTransactionSleepTime: cfg.PruneTxnSleepTime(),
})
}
type multiModelRunner struct {
rawRunner jujutxn.Runner
schema CollectionSchema
modelUUID string
}
func shortStack() string {
var rv []string
for _, line := range strings.Split(string(debug.Stack()), "\n") {
if len(line) > 0 && line[0] == '\t' {
rv = append(rv, strings.Split(line[1:], " ")[0])
}
}
// We definitely have at least 3 objects in rv - debug.Stack(), this function and the one that called it.
return strings.Join(rv[3:], " ")
}
var seenShortStacks = make(map[string]bool)
// RunTransaction is part of the jujutxn.Runner interface. Operations
// that affect multi-model collections will be modified to
// ensure correct interaction with these collections.
func (r *multiModelRunner) RunTransaction(tx *jujutxn.Transaction) error {
if len(tx.Ops) == 0 {
stack := shortStack()
// It is a warning that should be reported to us, but we definitely
// don't want to clutter up logs so we'll only write it once.
if !seenShortStacks[stack] {
seenShortStacks[stack] = true
logger.Warningf("Running no-op transaction - called by %s", stack)
}
}
newOps, err := r.updateOps(tx.Ops)
if err != nil {
return errors.Trace(err)
}
tx.Ops = newOps
return r.rawRunner.RunTransaction(tx)
}
// Run is part of the jujutxn.Runner interface. Operations returned by
// the given "transactions" function that affect multi-model
// collections will be modified to ensure correct interaction with
// these collections.
func (r *multiModelRunner) Run(transactions jujutxn.TransactionSource) error {
return r.rawRunner.Run(func(attempt int) ([]txn.Op, error) {
ops, err := transactions(attempt)
if err != nil {
// Don't use Trace here as jujutxn doens't use juju/errors
// and won't deal correctly with some returned errors.
return nil, err
}
newOps, err := r.updateOps(ops)
if err != nil {
return nil, errors.Trace(err)
}
return newOps, nil
})
}
// ResumeTransactions is part of the jujutxn.Runner interface.
func (r *multiModelRunner) ResumeTransactions() error {
return r.rawRunner.ResumeTransactions()
}
// MaybePruneTransactions is part of the jujutxn.Runner interface.
func (r *multiModelRunner) MaybePruneTransactions(opts jujutxn.PruneOptions) error {
return r.rawRunner.MaybePruneTransactions(opts)
}
// updateOps modifies the Insert and Update fields in a slice of
// txn.Ops to ensure they are multi-model safe where
// possible. The returned []txn.Op is a new copy of the input (with
// changes).
func (r *multiModelRunner) updateOps(ops []txn.Op) ([]txn.Op, error) {
var outOps []txn.Op
for _, op := range ops {
collInfo, found := r.schema[op.C]
if !found {
return nil, errors.Errorf("forbidden transaction: references unknown collection %q", op.C)
}
if collInfo.rawAccess {
return nil, errors.Errorf("forbidden transaction: references raw-access collection %q", op.C)
}
outOp := op
if !collInfo.global {
outOp.Id = ensureModelUUIDIfString(r.modelUUID, op.Id)
if op.Insert != nil {
newInsert, err := mungeDocForMultiModel(op.Insert, r.modelUUID, modelUUIDRequired)
if err != nil {
return nil, errors.Annotatef(err, "cannot insert into %q", op.C)
}
outOp.Insert = newInsert
}
if op.Update != nil {
newUpdate, err := r.mungeUpdate(op.Update)
if err != nil {
return nil, errors.Annotatef(err, "cannot update %q", op.C)
}
outOp.Update = newUpdate
}
}
outOps = append(outOps, outOp)
}
return outOps, nil
}
// mungeUpdate takes the value of an txn.Op Update field and modifies
// it to be multi-model safe, returning the modified document.
func (r *multiModelRunner) mungeUpdate(updateDoc interface{}) (interface{}, error) {
switch doc := updateDoc.(type) {
case bson.D:
return r.mungeBsonDUpdate(doc)
case bson.M:
return r.mungeBsonMUpdate(doc)
default:
return nil, errors.Errorf("don't know how to handle %T", updateDoc)
}
}
// mungeBsonDUpdate modifies a txn.Op's Update field values expressed
// as a bson.D and attempts to make it multi-model safe.
//
// Currently, only $set operations are munged.
func (r *multiModelRunner) mungeBsonDUpdate(updateDoc bson.D) (bson.D, error) {
outDoc := make(bson.D, 0, len(updateDoc))
for _, elem := range updateDoc {
if elem.Name == "$set" {
newSetDoc, err := mungeDocForMultiModel(elem.Value, r.modelUUID, 0)
if err != nil {
return nil, errors.Trace(err)
}
elem = bson.DocElem{elem.Name, newSetDoc}
}
outDoc = append(outDoc, elem)
}
return outDoc, nil
}
// mungeBsonMUpdate modifies a txn.Op's Update field values expressed
// as a bson.M and attempts to make it multi-model safe.
//
// Currently, only $set operations are munged.
func (r *multiModelRunner) mungeBsonMUpdate(updateDoc bson.M) (bson.M, error) {
outDoc := make(bson.M)
for name, elem := range updateDoc {
if name == "$set" {
var err error
elem, err = mungeDocForMultiModel(elem, r.modelUUID, 0)
if err != nil {
return nil, errors.Trace(err)
}
}
outDoc[name] = elem
}
return outDoc, nil
}