-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
dispatcher.go
327 lines (275 loc) · 8.23 KB
/
dispatcher.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
package hraftdispatcher
import (
"context"
"crypto/tls"
"fmt"
"net"
"github.com/soheilhy/cmux"
"github.com/hashicorp/go-multierror"
"github.com/casbin/casbin/v2/persist"
"github.com/casbin/hraft-dispatcher/command"
"github.com/casbin/hraft-dispatcher/http"
"github.com/casbin/hraft-dispatcher/store"
"github.com/hashicorp/raft"
"github.com/pkg/errors"
"go.uber.org/zap"
)
var _ persist.Dispatcher = &HRaftDispatcher{}
// HRaftDispatcher implements the persist.Dispatcher interface.
type HRaftDispatcher struct {
store http.Store
tlsConfig *tls.Config
httpService *http.Service
shutdownFn func() error
logger *zap.Logger
}
// NewHRaftDispatcher returns a HRaftDispatcher.
func NewHRaftDispatcher(config *Config) (*HRaftDispatcher, error) {
return NewHRaftDispatcherWithLogger(config, zap.NewExample())
}
// NewHRaftDispatcher returns a HRaftDispatcher.
func NewHRaftDispatcherWithLogger(config *Config, logger *zap.Logger) (*HRaftDispatcher, error) {
if config == nil {
return nil, errors.New("config is not provided")
}
if config.Enforcer == nil {
return nil, errors.New("Enforcer is not provided in config")
}
if len(config.DataDir) == 0 {
return nil, errors.New("DataDir is not provided in config")
}
if len(config.ListenAddress) == 0 {
return nil, errors.New("ListenAddress is not provided in config")
}
if len(config.ServerID) == 0 {
config.ServerID = config.ListenAddress
}
if logger == nil {
return nil, errors.New("no logger provided")
}
// check ListenAddress is network address
listenAddress, err := net.ResolveTCPAddr("tcp", config.ListenAddress)
if err != nil {
return nil, err
}
if listenAddress.IP == nil {
return nil, errors.New("host is omitted in ListenAddress")
}
ip := net.ParseIP(listenAddress.IP.String())
if ip != nil && ip.IsUnspecified() {
return nil, fmt.Errorf("cannot use unspecified IP %s", ip)
}
var ln net.Listener
if config.TLSConfig == nil {
ln, err = net.Listen("tcp", config.ListenAddress)
} else {
ln, err = tls.Listen("tcp", config.ListenAddress, config.TLSConfig)
}
if err != nil {
return nil, err
}
mux := cmux.New(ln)
httpLn := mux.Match(cmux.HTTP1Fast())
raftLn := mux.Match(cmux.Any())
go mux.Serve()
streamLayer, err := store.NewTCPStreamLayer(raftLn, config.TLSConfig)
if err != nil {
return nil, err
}
storeConfig := &store.Config{
ID: config.ServerID,
Dir: config.DataDir,
NetworkTransportConfig: &raft.NetworkTransportConfig{
Stream: streamLayer,
MaxPool: 5,
Logger: nil,
},
Enforcer: config.Enforcer,
RaftConfig: config.RaftConfig,
}
s, err := store.NewStore(logger, storeConfig)
if err != nil {
logger.Error(err.Error())
return nil, err
}
isNewCluster := !s.IsInitializedCluster()
enableBootstrap := false
if isNewCluster == true {
enableBootstrap = true
}
if len(config.JoinAddress) != 0 {
enableBootstrap = false
}
if enableBootstrap {
logger.Info("bootstrapping a new cluster")
} else {
logger.Info("skip bootstrapping a new cluster")
}
err = s.Start(enableBootstrap)
if err != nil {
logger.Error("failed to start raft service", zap.Error(err))
return nil, err
}
if enableBootstrap {
err = s.WaitLeader()
if err != nil {
logger.Error(err.Error())
}
}
if isNewCluster && config.JoinAddress != config.ListenAddress && len(config.JoinAddress) != 0 {
logger.Info("start joining the current node to existing cluster")
err = http.DoJoinNodeRequest(config.JoinAddress, config.ServerID, config.ListenAddress, config.TLSConfig)
if err != nil {
logger.Error("failed to join the current node to existing cluster", zap.String("nodeID", config.ServerID), zap.String("nodeAddress", config.ListenAddress), zap.String("clusterAddress", config.JoinAddress), zap.Error(err))
return nil, err
}
logger.Info("the current node has joined to existing cluster")
}
httpService, err := http.NewService(logger, httpLn, config.TLSConfig, s)
if err != nil {
return nil, err
}
err = httpService.Start()
if err != nil {
return nil, err
}
h := &HRaftDispatcher{
store: s,
tlsConfig: config.TLSConfig,
httpService: httpService,
logger: logger,
}
h.shutdownFn = func() error {
var ret error
err := s.Stop()
if err != nil {
ret = multierror.Append(ret, err)
}
err = httpService.Stop(context.Background())
if err != nil {
ret = multierror.Append(ret, err)
}
err = ln.Close()
if err != nil {
ret = multierror.Append(ret, err)
}
return ret
}
return h, nil
}
//
//AddPolicies implements the persist.Dispatcher interface.
func (h *HRaftDispatcher) AddPolicies(sec string, pType string, rules [][]string) error {
var items []*command.StringArray
for _, rule := range rules {
var item = &command.StringArray{Items: rule}
items = append(items, item)
}
addPolicyRequest := &command.AddPoliciesRequest{
Sec: sec,
PType: pType,
Rules: items,
}
return h.httpService.DoAddPolicyRequest(addPolicyRequest)
}
// RemovePolicies implements the persist.Dispatcher interface.
func (h *HRaftDispatcher) RemovePolicies(sec string, pType string, rules [][]string) error {
var items []*command.StringArray
for _, rule := range rules {
var item = &command.StringArray{Items: rule}
items = append(items, item)
}
request := &command.RemovePoliciesRequest{
Sec: sec,
PType: pType,
Rules: items,
}
return h.httpService.DoRemovePolicyRequest(request)
}
// RemoveFilteredPolicy implements the persist.Dispatcher interface.
func (h *HRaftDispatcher) RemoveFilteredPolicy(sec string, pType string, fieldIndex int, fieldValues ...string) error {
request := &command.RemoveFilteredPolicyRequest{
Sec: sec,
PType: pType,
FieldIndex: int32(fieldIndex),
FieldValues: fieldValues,
}
return h.httpService.DoRemoveFilteredPolicyRequest(request)
}
// ClearPolicy implements the persist.Dispatcher interface.
func (h *HRaftDispatcher) ClearPolicy() error {
return h.httpService.DoClearPolicyRequest()
}
// UpdatePolicy implements the persist.Dispatcher interface.
func (h *HRaftDispatcher) UpdatePolicy(sec string, pType string, oldRule, newRule []string) error {
request := &command.UpdatePolicyRequest{
Sec: sec,
PType: pType,
OldRule: oldRule,
NewRule: newRule,
}
return h.httpService.DoUpdatePolicyRequest(request)
}
// UpdateFilteredPolicies implements the persist.Dispatcher interface.
func (h *HRaftDispatcher) UpdateFilteredPolicies(sec string, pType string, oldRules, newRules [][]string) error {
var olds []*command.StringArray
for _, rule := range oldRules {
var item = &command.StringArray{Items: rule}
olds = append(olds, item)
}
var news []*command.StringArray
for _, rule := range newRules {
var item = &command.StringArray{Items: rule}
news = append(news, item)
}
request := &command.UpdateFilteredPoliciesRequest{
Sec: sec,
PType: pType,
OldRules: olds,
NewRules: news,
}
return h.httpService.DoUpdateFilteredPoliciesRequest(request)
}
// UpdatePolicies implements the persist.Dispatcher interface.
func (h *HRaftDispatcher) UpdatePolicies(sec string, pType string, oldRules, newRules [][]string) error {
var olds []*command.StringArray
for _, rule := range oldRules {
var item = &command.StringArray{Items: rule}
olds = append(olds, item)
}
var news []*command.StringArray
for _, rule := range newRules {
var item = &command.StringArray{Items: rule}
news = append(news, item)
}
request := &command.UpdatePoliciesRequest{
Sec: sec,
PType: pType,
OldRules: olds,
NewRules: news,
}
return h.httpService.DoUpdatePoliciesRequest(request)
}
// JoinNode joins a node to the current cluster.
func (h *HRaftDispatcher) JoinNode(serverID, serverAddress string) error {
request := &command.AddNodeRequest{
Id: serverID,
Address: serverAddress,
}
return h.httpService.DoJoinNodeRequest(request)
}
// JoinNode joins a node from the current cluster.
func (h *HRaftDispatcher) RemoveNode(serverID string) error {
request := &command.RemoveNodeRequest{
Id: serverID,
}
return h.httpService.DoRemoveNodeRequest(request)
}
// Shutdown is used to close the http and raft service.
func (h *HRaftDispatcher) Shutdown() error {
return h.shutdownFn()
}
// Stats is used to get stats of currently service.
func (h *HRaftDispatcher) Stats() (map[string]interface{}, error) {
return h.store.Stats()
}