forked from hyperledger/fabric
-
Notifications
You must be signed in to change notification settings - Fork 0
/
chain.go
358 lines (295 loc) · 8.5 KB
/
chain.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
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
/*
Copyright IBM Corp. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package etcdraft
import (
"context"
"sync"
"sync/atomic"
"time"
"github.com/hyperledger/fabric/common/flogging"
"github.com/hyperledger/fabric/orderer/consensus"
"github.com/hyperledger/fabric/protos/common"
"github.com/hyperledger/fabric/protos/orderer"
"github.com/hyperledger/fabric/protos/utils"
"code.cloudfoundry.org/clock"
"github.com/coreos/etcd/raft"
"github.com/coreos/etcd/raft/raftpb"
"github.com/pkg/errors"
)
// Storage is currently backed by etcd/raft.MemoryStorage. This interface is
// defined to expose dependencies of fsm so that it may be swapped in the
// future. TODO(jay) Add other necessary methods to this interface once we need
// them in implementation, e.g. ApplySnapshot.
type Storage interface {
raft.Storage
Append(entries []raftpb.Entry) error
}
// Options contains all the configurations relevant to the chain.
type Options struct {
RaftID uint64
Clock clock.Clock
Storage Storage
Logger *flogging.FabricLogger
TickInterval time.Duration
ElectionTick int
HeartbeatTick int
MaxSizePerMsg uint64
MaxInflightMsgs int
Peers []raft.Peer
}
// Chain implements consensus.Chain interface.
type Chain struct {
raftID uint64
submitC chan *orderer.SubmitRequest
commitC chan *common.Block
observeC chan<- uint64 // Notifies external observer on leader change
haltC chan struct{}
doneC chan struct{}
clock clock.Clock
support consensus.ConsenterSupport
leaderLock sync.RWMutex
leader uint64
appliedIndex uint64
node raft.Node
storage Storage
opts Options
logger *flogging.FabricLogger
}
// NewChain returns a new chain.
func NewChain(support consensus.ConsenterSupport, opts Options, observe chan<- uint64) (*Chain, error) {
return &Chain{
raftID: opts.RaftID,
submitC: make(chan *orderer.SubmitRequest),
commitC: make(chan *common.Block),
haltC: make(chan struct{}),
doneC: make(chan struct{}),
observeC: observe,
support: support,
clock: opts.Clock,
logger: opts.Logger.With("channel", support.ChainID()),
storage: opts.Storage,
opts: opts,
}, nil
}
// Start instructs the orderer to begin serving the chain and keep it current.
func (c *Chain) Start() {
config := &raft.Config{
ID: c.raftID,
ElectionTick: c.opts.ElectionTick,
HeartbeatTick: c.opts.HeartbeatTick,
MaxSizePerMsg: c.opts.MaxSizePerMsg,
MaxInflightMsgs: c.opts.MaxInflightMsgs,
Logger: c.logger,
Storage: c.opts.Storage,
}
c.node = raft.StartNode(config, c.opts.Peers)
go c.serveRaft()
go c.serveRequest()
}
// Order submits normal type transactions for ordering.
func (c *Chain) Order(env *common.Envelope, configSeq uint64) error {
return c.Submit(&orderer.SubmitRequest{LastValidationSeq: configSeq, Content: env}, 0)
}
// Configure submits config type transactions for ordering.
func (c *Chain) Configure(env *common.Envelope, configSeq uint64) error {
c.logger.Panicf("Configure not implemented yet")
return nil
}
// WaitReady is currently a no-op.
func (c *Chain) WaitReady() error {
return nil
}
// Errored returns a channel that closes when the chain stops.
func (c *Chain) Errored() <-chan struct{} {
return c.doneC
}
// Halt stops the chain.
func (c *Chain) Halt() {
select {
case c.haltC <- struct{}{}:
case <-c.doneC:
return
}
<-c.doneC
}
// Submit forwards the incoming request to:
// - the local serveRequest goroutine if this is leader
// - the actual leader via the transport mechanism
// The call fails if there's no leader elected yet.
func (c *Chain) Submit(req *orderer.SubmitRequest, sender uint64) error {
c.leaderLock.RLock()
defer c.leaderLock.RUnlock()
if c.leader == raft.None {
return errors.Errorf("no raft leader")
}
if c.leader == c.raftID {
select {
case c.submitC <- req:
return nil
case <-c.doneC:
return errors.Errorf("chain is stopped")
}
}
// TODO forward request to actual leader when we implement multi-node raft
return errors.Errorf("only single raft node is currently supported")
}
func (c *Chain) serveRequest() {
ticking := false
timer := c.clock.NewTimer(time.Second)
// we need a stopped timer rather than nil,
// because we will be select waiting on timer.C()
if !timer.Stop() {
<-timer.C()
}
// if timer is already started, this is a no-op
start := func() {
if !ticking {
ticking = true
timer.Reset(c.support.SharedConfig().BatchTimeout())
}
}
stop := func() {
if !timer.Stop() && ticking {
// we only need to drain the channel if the timer expired (not explicitly stopped)
<-timer.C()
}
ticking = false
}
for {
seq := c.support.Sequence()
select {
case msg := <-c.submitC:
if c.isConfig(msg.Content) {
c.logger.Panicf("Processing config envelope is not implemented yet")
}
if msg.LastValidationSeq < seq {
if _, err := c.support.ProcessNormalMsg(msg.Content); err != nil {
c.logger.Warningf("Discarding bad normal message: %s", err)
continue
}
}
batches, _ := c.support.BlockCutter().Ordered(msg.Content)
if len(batches) == 0 {
start()
continue
}
stop()
if err := c.commitBatches(batches...); err != nil {
c.logger.Errorf("Failed to commit block: %s", err)
}
case <-timer.C():
ticking = false
batch := c.support.BlockCutter().Cut()
if len(batch) == 0 {
c.logger.Warningf("Batch timer expired with no pending requests, this might indicate a bug")
continue
}
c.logger.Debugf("Batch timer expired, creating block")
if err := c.commitBatches(batch); err != nil {
c.logger.Errorf("Failed to commit block: %s", err)
}
case <-c.doneC:
c.logger.Infof("Stop serving requests")
return
}
}
}
func (c *Chain) commitBatches(batches ...[]*common.Envelope) error {
for _, batch := range batches {
b := c.support.CreateNextBlock(batch)
data := utils.MarshalOrPanic(b)
if err := c.node.Propose(context.TODO(), data); err != nil {
return errors.Errorf("failed to propose data to raft: %s", err)
}
select {
case block := <-c.commitC:
if utils.IsConfigBlock(block) {
c.logger.Panicf("Config block is not supported yet")
}
c.support.WriteBlock(block, nil)
case <-c.doneC:
return nil
}
}
return nil
}
func (c *Chain) serveRaft() {
ticker := c.clock.NewTicker(c.opts.TickInterval)
for {
select {
case <-ticker.C():
c.node.Tick()
case rd := <-c.node.Ready():
c.storage.Append(rd.Entries)
// TODO send messages to other peers when we implement multi-node raft
c.apply(c.entriesToApply(rd.CommittedEntries))
c.node.Advance()
if rd.SoftState != nil {
c.leaderLock.Lock()
newLead := atomic.LoadUint64(&rd.SoftState.Lead)
if newLead != c.leader {
c.logger.Infof("Raft leader changed on node %x: %x -> %x", c.raftID, c.leader, newLead)
c.leader = newLead
// notify external observer
select {
case c.observeC <- newLead:
default:
}
}
c.leaderLock.Unlock()
}
case <-c.haltC:
close(c.doneC)
ticker.Stop()
c.node.Stop()
c.logger.Infof("Raft node %x stopped", c.raftID)
return
}
}
}
func (c *Chain) apply(ents []raftpb.Entry) {
for i := range ents {
switch ents[i].Type {
case raftpb.EntryNormal:
if len(ents[i].Data) == 0 {
break
}
c.commitC <- utils.UnmarshalBlockOrPanic(ents[i].Data)
case raftpb.EntryConfChange:
var cc raftpb.ConfChange
if err := cc.Unmarshal(ents[i].Data); err != nil {
c.logger.Warnf("Failed to unmarshal ConfChange data: %s", err)
continue
}
c.node.ApplyConfChange(cc)
}
c.appliedIndex = ents[i].Index
}
}
// this is taken from coreos/contrib/raftexample/raft.go
func (c *Chain) entriesToApply(ents []raftpb.Entry) (nents []raftpb.Entry) {
if len(ents) == 0 {
return
}
firstIdx := ents[0].Index
if firstIdx > c.appliedIndex+1 {
c.logger.Panicf("first index of committed entry[%d] should <= progress.appliedIndex[%d]+1", firstIdx, c.appliedIndex)
}
// If we do have unapplied entries in nents.
// | applied | unapplied |
// |----------------|----------------------|
// firstIdx appliedIndex last
if c.appliedIndex-firstIdx+1 < uint64(len(ents)) {
nents = ents[c.appliedIndex-firstIdx+1:]
}
return nents
}
func (c *Chain) isConfig(env *common.Envelope) bool {
h, err := utils.ChannelHeader(env)
if err != nil {
c.logger.Panicf("programming error: failed to extract channel header from envelope")
}
return h.Type == int32(common.HeaderType_CONFIG) || h.Type == int32(common.HeaderType_ORDERER_TRANSACTION)
}