forked from ug93tad/fabric
/
executor.go
242 lines (203 loc) · 7.91 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
/*
Copyright IBM Corp. 2016 All Rights Reserved.
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 executor
import (
"strconv"
"github.com/golang/protobuf/proto"
"github.com/hyperledger/fabric/consensus"
"github.com/hyperledger/fabric/consensus/pbft"
"github.com/hyperledger/fabric/core/util"
"github.com/hyperledger/fabric/consensus/util/events"
"github.com/hyperledger/fabric/core/peer/statetransfer"
pb "github.com/hyperledger/fabric/protos"
"github.com/op/go-logging"
"github.com/spf13/viper"
)
var logger *logging.Logger // package-level logger
func init() {
logger = logging.MustGetLogger("consensus/executor")
}
// PartialStack contains the ledger features required by the executor.Coordinator
type PartialStack interface {
consensus.LegacyExecutor
GetBlockchainInfo() *pb.BlockchainInfo
}
type coordinatorImpl struct {
manager events.Manager // Maintains event thread and sends events to the coordinator
rawExecutor PartialStack // Does the real interaction with the ledger
consumer consensus.ExecutionConsumer // The consumer of this coordinator which receives the callbacks
stc statetransfer.Coordinator // State transfer instance
batchInProgress bool // Are we mid execution batch
skipInProgress bool // Are we mid state transfer
statUtil *util.StatUtil
}
// NewCoordinatorImpl creates a new executor.Coordinator
func NewImpl(consumer consensus.ExecutionConsumer, rawExecutor PartialStack, stps statetransfer.PartialStack) consensus.Executor {
co := &coordinatorImpl{
rawExecutor: rawExecutor,
consumer: consumer,
stc: statetransfer.NewCoordinatorImpl(stps),
manager: events.NewManagerImpl(),
}
co.manager.SetReceiver(co)
config := viper.New()
config.SetEnvPrefix("core_execution")
config.AutomaticEnv()
interval := uint32(config.GetInt("sample_interval"))
co.statUtil = util.GetStatUtil()
co.statUtil.NewStat("execute", interval)
co.statUtil.NewStat("commitqueue", interval)
co.statUtil.NewStat("commit", interval)
return co
}
// ProcessEvent is the main event loop for the executor.Coordinator
func (co *coordinatorImpl) ProcessEvent(event events.Event) events.Event {
switch et := event.(type) {
case executeEvent:
logger.Debug("Executor is processing an executeEvent")
if co.skipInProgress {
logger.Error("FATAL programming error, attempted to execute a transaction during state transfer")
return nil
}
if !co.batchInProgress {
logger.Debug("Starting new transaction batch")
co.batchInProgress = true
err := co.rawExecutor.BeginTxBatch(co)
_ = err // TODO This should probably panic, see issue 752
}
meta := &pbft.Metadata{}
if _, ok := et.tag.([]byte); ok {
proto.Unmarshal(et.tag.([]byte), meta)
if lt, ok := co.statUtil.Stats["executionqueue"].End(strconv.FormatUint(meta.SeqNo,10)); ok {
logger.Infof("Execution queue time: %v", lt)
}
co.statUtil.Stats["execute"].Start(strconv.FormatUint(meta.SeqNo,10))
}
co.rawExecutor.ExecTxs(co, et.txs)
if lt, ok := co.statUtil.Stats["execute"].End(strconv.FormatUint(meta.SeqNo,10)); ok {
logger.Infof("Batch execution time (seqNo %v): %v, #tx: %v", meta.SeqNo, lt, len(et.txs))
}
co.statUtil.Stats["commitqueue"].Start(strconv.FormatUint(meta.SeqNo,10))
co.consumer.Executed(et.tag)
case commitEvent:
logger.Debug("Executor is processing an commitEvent")
if co.skipInProgress {
logger.Error("Likely FATAL programming error, attempted to commit a transaction batch during state transfer")
return nil
}
if !co.batchInProgress {
logger.Error("Likely FATAL programming error, attemted to commit a transaction batch when one does not exist")
return nil
}
meta := &pbft.Metadata{}
proto.Unmarshal(et.metadata, meta)
if lt, ok := co.statUtil.Stats["commitqueue"].End(strconv.FormatUint(meta.SeqNo,10)); ok {
logger.Infof("Commit queue time: %v", lt)
}
co.statUtil.Stats["commit"].Start(strconv.FormatUint(meta.SeqNo,10))
_, err := co.rawExecutor.CommitTxBatch(co, et.metadata)
_ = err // TODO This should probably panic, see issue 752
co.batchInProgress = false
info := co.rawExecutor.GetBlockchainInfo()
logger.Debugf("Committed block %d with hash %x to chain", info.Height-1, info.CurrentBlockHash)
co.consumer.Committed(et.tag, info)
if lt, ok := co.statUtil.Stats["commit"].End(strconv.FormatUint(meta.SeqNo,10)); ok {
logger.Infof("Batch commit time (seqNo %v): %v", meta.SeqNo, lt)
}
case rollbackEvent:
logger.Debug("Executor is processing an rollbackEvent")
if co.skipInProgress {
logger.Error("Programming error, attempted to rollback a transaction batch during state transfer")
return nil
}
if !co.batchInProgress {
logger.Error("Programming error, attempted to rollback a transaction batch which had not started")
return nil
}
err := co.rawExecutor.RollbackTxBatch(co)
_ = err // TODO This should probably panic, see issue 752
co.batchInProgress = false
co.consumer.RolledBack(et.tag)
case stateUpdateEvent:
logger.Debug("Executor is processing a stateUpdateEvent")
if co.batchInProgress {
err := co.rawExecutor.RollbackTxBatch(co)
_ = err // TODO This should probably panic, see issue 752
}
co.skipInProgress = true
info := et.blockchainInfo
for {
err, recoverable := co.stc.SyncToTarget(info.Height-1, info.CurrentBlockHash, et.peers)
if err == nil {
logger.Debug("State transfer sync completed, returning")
co.skipInProgress = false
co.consumer.StateUpdated(et.tag, info)
return nil
}
if !recoverable {
logger.Warningf("State transfer failed irrecoverably, calling back to consumer: %s", err)
co.consumer.StateUpdated(et.tag, nil)
return nil
}
logger.Warningf("State transfer did not complete successfully but is recoverable, trying again: %s", err)
et.peers = nil // Broaden the peers included in recover to all connected
}
default:
logger.Errorf("Unknown event type %s", et)
}
return nil
}
// Commit commits whatever outstanding requests have been executed, it is an error to call this without pending executions
func (co *coordinatorImpl) Commit(tag interface{}, metadata []byte) {
co.manager.Queue() <- commitEvent{tag, metadata}
}
// Execute adds additional executions to the current batch
func (co *coordinatorImpl) Execute(tag interface{}, txs []*pb.Transaction) {
co.manager.Queue() <- executeEvent{tag, txs}
}
// Rollback rolls back the executions from the current batch
func (co *coordinatorImpl) Rollback(tag interface{}) {
co.manager.Queue() <- rollbackEvent{tag}
}
// UpdateState uses the state transfer subsystem to attempt to progress to a target
func (co *coordinatorImpl) UpdateState(tag interface{}, info *pb.BlockchainInfo, peers []*pb.PeerID) {
co.manager.Queue() <- stateUpdateEvent{tag, info, peers}
}
// Start must be called before utilizing the Coordinator
func (co *coordinatorImpl) Start() {
co.stc.Start()
co.manager.Start()
}
// Halt should be called to clean up resources allocated by the Coordinator
func (co *coordinatorImpl) Halt() {
co.stc.Stop()
co.manager.Halt()
}
// Event types
type executeEvent struct {
tag interface{}
txs []*pb.Transaction
}
// Note, this cannot be a simple type alias, in case tag is nil
type rollbackEvent struct {
tag interface{}
}
type commitEvent struct {
tag interface{}
metadata []byte
}
type stateUpdateEvent struct {
tag interface{}
blockchainInfo *pb.BlockchainInfo
peers []*pb.PeerID
}