-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
Copy pathexecutor.go
295 lines (246 loc) · 6.31 KB
/
executor.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
/*
* Copyright 2016-2020 Dgraph Labs, Inc. and Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* 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 worker contains code for pb.worker communication to perform
// queries and mutations.
package worker
import (
"context"
"runtime"
"sync"
"sync/atomic"
"github.com/dgraph-io/badger/v2/y"
"github.com/dgraph-io/dgraph/posting"
"github.com/dgraph-io/dgraph/protos/pb"
"github.com/dgraph-io/dgraph/schema"
"github.com/dgraph-io/dgraph/x"
"github.com/golang/glog"
)
type subMutation struct {
edges []*pb.DirectedEdge
ctx context.Context
startTs uint64
index uint64
}
type executor struct {
pendingSize int64
smCount int64 // Stores count for active sub mutations.
sync.RWMutex
predChan map[string]chan *subMutation
workerChan chan *mutation
closer *y.Closer
applied *y.WaterMark
}
func newExecutor(applied *y.WaterMark) *executor {
runtime.SetBlockProfileRate(1)
ex := &executor{
predChan: make(map[string]chan *subMutation),
closer: y.NewCloser(0),
applied: applied,
workerChan: make(chan *mutation, 1000),
}
for i := 0; i < 200; i++ {
go ex.worker()
}
go ex.shutdown()
return ex
}
func generateConflictKeys(p *subMutation) []uint64 {
keys := make([]uint64, 0)
uniq := make(map[uint64]struct{})
for _, edge := range p.edges {
key := x.DataKey(edge.Attr, edge.Entity)
pk, err := x.Parse(key)
if err != nil {
continue
}
if schema.State().IsList(edge.Attr) {
uniq[1] = struct{}{}
}
uniq[posting.GetConflictKeys(pk, key, edge)] = struct{}{}
}
for key := range uniq {
keys = append(keys, key)
}
return keys
}
type mutation struct {
m *subMutation
keys []uint64
inDeg int
outEdges map[uint64]*mutation
graph *graph
}
type graph struct {
sync.RWMutex
conflicts map[uint64][]*mutation
}
func newGraph() *graph {
return &graph{conflicts: make(map[uint64][]*mutation)}
}
func (e *executor) worker() {
writer := posting.NewTxnWriter(pstore)
for mut := range e.workerChan {
payload := mut.m
var esize int64
ptxn := posting.NewTxn(payload.startTs)
for _, edge := range payload.edges {
esize += int64(edge.Size())
for {
err := runMutation(payload.ctx, edge, ptxn)
if err == nil {
break
} else if err != posting.ErrRetry {
glog.Errorf("Error while mutating: %v", err)
break
}
}
}
ptxn.Update()
if err := ptxn.CommitToDisk(writer, payload.startTs); err != nil {
glog.Errorf("Error while commiting to disk: %v", err)
}
if err := writer.Wait(); err != nil {
glog.Errorf("Error while waiting for writes: %v", err)
}
e.applied.Done(payload.index)
atomic.AddInt64(&e.pendingSize, -esize)
atomic.AddInt64(&e.smCount, -1)
mut.graph.Lock()
toRun := make([]*mutation, 0)
for _, dependent := range mut.outEdges {
dependent.inDeg -= 1
if dependent.inDeg == 0 {
toRun = append(toRun, dependent)
}
}
for _, c := range mut.keys {
i := 0
arr := mut.graph.conflicts[c]
for _, x := range arr {
if x.m.startTs != mut.m.startTs {
arr[i] = x
i++
}
}
if i == 0 {
delete(mut.graph.conflicts, c)
} else {
mut.graph.conflicts[c] = arr[:i]
}
}
mut.graph.Unlock()
for _, i := range toRun {
go func(j *mutation) {
e.workerChan <- j
}(i)
}
}
}
func (e *executor) processMutationCh(ch chan *subMutation) {
defer e.closer.Done()
g := newGraph()
for payload := range ch {
conflicts := generateConflictKeys(payload)
m := &mutation{m: payload, keys: conflicts, outEdges: make(map[uint64]*mutation), graph: g, inDeg: 0}
g.Lock()
for _, c := range conflicts {
l, ok := g.conflicts[c]
if !ok {
g.conflicts[c] = []*mutation{m}
continue
}
for _, dependent := range l {
_, ok := dependent.outEdges[m.m.startTs]
if !ok {
m.inDeg += 1
dependent.outEdges[m.m.startTs] = m
}
}
l = append(l, m)
g.conflicts[c] = l
}
g.Unlock()
if m.inDeg == 0 {
e.workerChan <- m
}
}
}
func (e *executor) shutdown() {
<-e.closer.HasBeenClosed()
e.RLock()
defer e.RUnlock()
for _, ch := range e.predChan {
close(ch)
}
}
// getChannel obtains the channel for the given pred. It must be called under e.Lock().
func (e *executor) getChannel(pred string) (ch chan *subMutation) {
ch, ok := e.predChan[pred]
if ok {
return ch
}
ch = make(chan *subMutation, 1000)
e.predChan[pred] = ch
e.closer.AddRunning(1)
go e.processMutationCh(ch)
return ch
}
const (
maxPendingEdgesSize int64 = 64 << 20
executorAddEdges = "executor.addEdges"
)
func (e *executor) addEdges(ctx context.Context, proposal *pb.Proposal) {
rampMeter(&e.pendingSize, maxPendingEdgesSize, executorAddEdges)
index := proposal.Index
startTs := proposal.Mutations.StartTs
edges := proposal.Mutations.Edges
payloadMap := make(map[string]*subMutation)
var esize int64
for _, edge := range edges {
payload, ok := payloadMap[edge.Attr]
if !ok {
payloadMap[edge.Attr] = &subMutation{
ctx: ctx,
startTs: startTs,
index: index,
}
payload = payloadMap[edge.Attr]
}
payload.edges = append(payload.edges, edge)
esize += int64(edge.Size())
}
// Lock() in case the channel gets closed from underneath us.
e.Lock()
defer e.Unlock()
select {
case <-e.closer.HasBeenClosed():
return
default:
// Closer is not closed. And we have the Lock, so sending on channel should be safe.
for attr, payload := range payloadMap {
e.applied.Begin(index)
atomic.AddInt64(&e.smCount, 1)
e.getChannel(attr) <- payload
}
}
atomic.AddInt64(&e.pendingSize, esize)
}
// waitForActiveMutations waits for all the mutations (currently active) to finish. This function
// should be called before running any schema mutation.
func (e *executor) waitForActiveMutations() {
glog.Infoln("executor: wait for active mutation to finish")
rampMeter(&e.smCount, 0, "waiting on active mutations to finish")
}