-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
worker.go
188 lines (160 loc) · 5.51 KB
/
worker.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
/*
* Copyright 2016-2023 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 (
"fmt"
"log"
"math"
"net"
"sync"
"sync/atomic"
"github.com/golang/glog"
"github.com/pkg/errors"
"go.opencensus.io/plugin/ocgrpc"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
"github.com/dgraph-io/badger/v4"
badgerpb "github.com/dgraph-io/badger/v4/pb"
"github.com/dgraph-io/dgraph/conn"
"github.com/dgraph-io/dgraph/posting"
"github.com/dgraph-io/dgraph/protos/pb"
"github.com/dgraph-io/dgraph/x"
)
var (
pstore *badger.DB
workerServer *grpc.Server
raftServer conn.RaftServer
// In case of flaky network connectivity we would try to keep upto maxPendingEntries in wal
// so that the nodes which have lagged behind leader can just replay entries instead of
// fetching snapshot if network disconnectivity is greater than the interval at which snapshots
// are taken
)
func workerPort() int {
return x.Config.PortOffset + x.PortInternal
}
// Init initializes this package.
func Init(ps *badger.DB) {
pstore = ps
// needs to be initialized after group config
limiter = rateLimiter{c: sync.NewCond(&sync.Mutex{}), max: int(x.WorkerConfig.Raft.GetInt64("pending-proposals"))}
go limiter.bleed()
grpcOpts := []grpc.ServerOption{
grpc.MaxRecvMsgSize(x.GrpcMaxSize),
grpc.MaxSendMsgSize(x.GrpcMaxSize),
grpc.MaxConcurrentStreams(math.MaxInt32),
grpc.StatsHandler(&ocgrpc.ServerHandler{}),
}
if x.WorkerConfig.TLSServerConfig != nil {
grpcOpts = append(grpcOpts, grpc.Creds(credentials.NewTLS(x.WorkerConfig.TLSServerConfig)))
}
workerServer = grpc.NewServer(grpcOpts...)
}
// grpcWorker struct implements the gRPC server interface.
type grpcWorker struct {
sync.Mutex
}
// grpcWorker implements pb.WorkerServer.
var _ pb.WorkerServer = (*grpcWorker)(nil)
func (w *grpcWorker) Subscribe(
req *pb.SubscriptionRequest, stream pb.Worker_SubscribeServer) error {
// Subscribe on given prefixes.
var matches []badgerpb.Match
for _, p := range req.GetPrefixes() {
matches = append(matches, badgerpb.Match{
Prefix: p,
})
}
for _, m := range req.GetMatches() {
matches = append(matches, *m)
}
return pstore.Subscribe(stream.Context(), func(kvs *badgerpb.KVList) error {
return stream.Send(kvs)
}, matches)
}
// RunServer initializes a tcp server on port which listens to requests from
// other workers for pb.communication.
func RunServer(bindall bool) {
laddr := "localhost"
if bindall {
laddr = "0.0.0.0"
}
ln, err := net.Listen("tcp", fmt.Sprintf("%s:%d", laddr, workerPort()))
if err != nil {
log.Fatalf("While running server: %v", err)
}
glog.Infof("Worker listening at address: %v", ln.Addr())
pb.RegisterWorkerServer(workerServer, &grpcWorker{})
pb.RegisterRaftServer(workerServer, &raftServer)
if err := workerServer.Serve(ln); err != nil {
glog.Errorf("Error while calling Serve: %+v", err)
}
}
// StoreStats returns stats for data store.
func StoreStats() string {
return "Currently no stats for badger"
}
// BlockingStop stops all the nodes, server between other workers and syncs all marks.
func BlockingStop() {
glog.Infof("Stopping group...")
groups().closer.SignalAndWait()
// Update checkpoint so that proposals are not replayed after the server restarts.
glog.Infof("Updating RAFT state before shutting down...")
if err := groups().Node.updateRaftProgress(); err != nil {
glog.Warningf("Error while updating RAFT progress before shutdown: %v", err)
}
glog.Infof("Stopping node...")
groups().Node.closer.SignalAndWait()
glog.Infof("Stopping worker server...")
workerServer.Stop()
groups().Node.cdcTracker.Close()
}
// UpdateCacheMb updates the value of cache_mb and updates the corresponding cache sizes.
func UpdateCacheMb(memoryMB int64) error {
glog.Infof("Updating cacheMb to %d", memoryMB)
if memoryMB < 0 {
return errors.Errorf("cache_mb must be non-negative")
}
cachePercent, err := x.GetCachePercentages(Config.CachePercentage, 3)
if err != nil {
return err
}
plCacheSize := (cachePercent[0] * (memoryMB << 20)) / 100
blockCacheSize := (cachePercent[1] * (memoryMB << 20)) / 100
indexCacheSize := (cachePercent[2] * (memoryMB << 20)) / 100
posting.UpdateMaxCost(plCacheSize)
if _, err := pstore.CacheMaxCost(badger.BlockCache, blockCacheSize); err != nil {
return errors.Wrapf(err, "cannot update block cache size")
}
if _, err := pstore.CacheMaxCost(badger.IndexCache, indexCacheSize); err != nil {
return errors.Wrapf(err, "cannot update index cache size")
}
Config.CacheMb = memoryMB
return nil
}
// UpdateLogDQLRequest updates value of x.WorkerConfig.LogDQLRequest.
func UpdateLogDQLRequest(val bool) {
if val {
atomic.StoreInt32(&x.WorkerConfig.LogDQLRequest, 1)
return
}
atomic.StoreInt32(&x.WorkerConfig.LogDQLRequest, 0)
}
// LogDQLRequestEnabled returns true if logging of requests is enabled otherwise false.
func LogDQLRequestEnabled() bool {
return atomic.LoadInt32(&x.WorkerConfig.LogDQLRequest) > 0
}