-
Notifications
You must be signed in to change notification settings - Fork 8.9k
/
registrar.go
438 lines (371 loc) · 13.2 KB
/
registrar.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
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
/*
Copyright IBM Corp. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
// Package multichannel tracks the channel resources for the orderer. It initially
// loads the set of existing channels, and provides an interface for users of these
// channels to retrieve them, or create new ones.
package multichannel
import (
"fmt"
"sync"
cb "github.com/hyperledger/fabric-protos-go/common"
ab "github.com/hyperledger/fabric-protos-go/orderer"
"github.com/hyperledger/fabric/bccsp"
"github.com/hyperledger/fabric/common/channelconfig"
"github.com/hyperledger/fabric/common/configtx"
"github.com/hyperledger/fabric/common/flogging"
"github.com/hyperledger/fabric/common/ledger/blockledger"
"github.com/hyperledger/fabric/common/metrics"
"github.com/hyperledger/fabric/internal/pkg/identity"
"github.com/hyperledger/fabric/orderer/common/blockcutter"
"github.com/hyperledger/fabric/orderer/common/localconfig"
"github.com/hyperledger/fabric/orderer/common/msgprocessor"
"github.com/hyperledger/fabric/orderer/common/types"
"github.com/hyperledger/fabric/orderer/consensus"
"github.com/hyperledger/fabric/protoutil"
"github.com/pkg/errors"
)
const (
msgVersion = int32(0)
epoch = 0
)
var logger = flogging.MustGetLogger("orderer.commmon.multichannel")
// checkResources makes sure that the channel config is compatible with this binary and logs sanity checks
func checkResources(res channelconfig.Resources) error {
channelconfig.LogSanityChecks(res)
oc, ok := res.OrdererConfig()
if !ok {
return errors.New("config does not contain orderer config")
}
if err := oc.Capabilities().Supported(); err != nil {
return errors.Wrapf(err, "config requires unsupported orderer capabilities: %s", err)
}
if err := res.ChannelConfig().Capabilities().Supported(); err != nil {
return errors.Wrapf(err, "config requires unsupported channel capabilities: %s", err)
}
return nil
}
// checkResourcesOrPanic invokes checkResources and panics if an error is returned
func checkResourcesOrPanic(res channelconfig.Resources) {
if err := checkResources(res); err != nil {
logger.Panicf("[channel %s] %s", res.ConfigtxValidator().ChannelID(), err)
}
}
type mutableResources interface {
channelconfig.Resources
Update(*channelconfig.Bundle)
}
type configResources struct {
mutableResources
bccsp bccsp.BCCSP
}
func (cr *configResources) CreateBundle(channelID string, config *cb.Config) (*channelconfig.Bundle, error) {
return channelconfig.NewBundle(channelID, config, cr.bccsp)
}
func (cr *configResources) Update(bndl *channelconfig.Bundle) {
checkResourcesOrPanic(bndl)
cr.mutableResources.Update(bndl)
}
func (cr *configResources) SharedConfig() channelconfig.Orderer {
oc, ok := cr.OrdererConfig()
if !ok {
logger.Panicf("[channel %s] has no orderer configuration", cr.ConfigtxValidator().ChannelID())
}
return oc
}
type ledgerResources struct {
*configResources
blockledger.ReadWriter
}
// Registrar serves as a point of access and control for the individual channel resources.
type Registrar struct {
config localconfig.TopLevel
lock sync.RWMutex
chains map[string]*ChainSupport
consenters map[string]consensus.Consenter
ledgerFactory blockledger.Factory
signer identity.SignerSerializer
blockcutterMetrics *blockcutter.Metrics
systemChannelID string
systemChannel *ChainSupport
templator msgprocessor.ChannelConfigTemplator
callbacks []channelconfig.BundleActor
bccsp bccsp.BCCSP
}
// ConfigBlock retrieves the last configuration block from the given ledger.
// Panics on failure.
func ConfigBlock(reader blockledger.Reader) *cb.Block {
lastBlock := blockledger.GetBlock(reader, reader.Height()-1)
index, err := protoutil.GetLastConfigIndexFromBlock(lastBlock)
if err != nil {
logger.Panicf("Chain did not have appropriately encoded last config in its latest block: %s", err)
}
configBlock := blockledger.GetBlock(reader, index)
if configBlock == nil {
logger.Panicf("Config block does not exist")
}
return configBlock
}
func configTx(reader blockledger.Reader) *cb.Envelope {
return protoutil.ExtractEnvelopeOrPanic(ConfigBlock(reader), 0)
}
// NewRegistrar produces an instance of a *Registrar.
func NewRegistrar(
config localconfig.TopLevel,
ledgerFactory blockledger.Factory,
signer identity.SignerSerializer,
metricsProvider metrics.Provider,
bccsp bccsp.BCCSP,
callbacks ...channelconfig.BundleActor,
) *Registrar {
r := &Registrar{
config: config,
chains: make(map[string]*ChainSupport),
ledgerFactory: ledgerFactory,
signer: signer,
blockcutterMetrics: blockcutter.NewMetrics(metricsProvider),
callbacks: callbacks,
bccsp: bccsp,
}
return r
}
func (r *Registrar) Initialize(consenters map[string]consensus.Consenter) {
r.consenters = consenters
existingChannels := r.ledgerFactory.ChannelIDs()
for _, channelID := range existingChannels {
rl, err := r.ledgerFactory.GetOrCreate(channelID)
if err != nil {
logger.Panicf("Ledger factory reported channelID %s but could not retrieve it: %s", channelID, err)
}
configTx := configTx(rl)
if configTx == nil {
logger.Panic("Programming error, configTx should never be nil here")
}
ledgerResources := r.newLedgerResources(configTx)
channelID := ledgerResources.ConfigtxValidator().ChannelID()
if _, ok := ledgerResources.ConsortiumsConfig(); ok {
if r.systemChannelID != "" {
logger.Panicf("There appear to be two system channels %s and %s", r.systemChannelID, channelID)
}
chain := newChainSupport(
r,
ledgerResources,
r.consenters,
r.signer,
r.blockcutterMetrics,
r.bccsp,
)
r.templator = msgprocessor.NewDefaultTemplator(chain, r.bccsp)
chain.Processor = msgprocessor.NewSystemChannel(
chain,
r.templator,
msgprocessor.CreateSystemChannelFilters(r.config, r, chain, chain.MetadataValidator),
r.bccsp,
)
// Retrieve genesis block to log its hash. See FAB-5450 for the purpose
iter, pos := rl.Iterator(&ab.SeekPosition{Type: &ab.SeekPosition_Oldest{Oldest: &ab.SeekOldest{}}})
defer iter.Close()
if pos != uint64(0) {
logger.Panicf("Error iterating over system channel: '%s', expected position 0, got %d", channelID, pos)
}
genesisBlock, status := iter.Next()
if status != cb.Status_SUCCESS {
logger.Panicf("Error reading genesis block of system channel '%s'", channelID)
}
logger.Infof("Starting system channel '%s' with genesis block hash %x and orderer type %s",
channelID, protoutil.BlockHeaderHash(genesisBlock.Header), chain.SharedConfig().ConsensusType())
r.chains[channelID] = chain
r.systemChannelID = channelID
r.systemChannel = chain
// We delay starting this channel, as it might try to copy and replace the channels map via newChannel before the map is fully built
defer chain.start()
} else {
logger.Debugf("Starting channel: %s", channelID)
chain := newChainSupport(
r,
ledgerResources,
r.consenters,
r.signer,
r.blockcutterMetrics,
r.bccsp,
)
r.chains[channelID] = chain
chain.start()
}
}
if r.systemChannelID == "" {
logger.Warning("registrar initializing without a system channel")
}
}
// SystemChannelID returns the ChannelID for the system channel.
func (r *Registrar) SystemChannelID() string {
r.lock.RLock()
defer r.lock.RUnlock()
return r.systemChannelID
}
// SystemChannel returns the ChainSupport for the system channel.
func (r *Registrar) SystemChannel() *ChainSupport {
r.lock.RLock()
defer r.lock.RUnlock()
return r.systemChannel
}
// BroadcastChannelSupport returns the message channel header, whether the message is a config update
// and the channel resources for a message or an error if the message is not a message which can
// be processed directly (like CONFIG and ORDERER_TRANSACTION messages)
func (r *Registrar) BroadcastChannelSupport(msg *cb.Envelope) (*cb.ChannelHeader, bool, *ChainSupport, error) {
chdr, err := protoutil.ChannelHeader(msg)
if err != nil {
return nil, false, nil, fmt.Errorf("could not determine channel ID: %s", err)
}
cs := r.GetChain(chdr.ChannelId)
// New channel creation
if cs == nil {
sysChan := r.SystemChannel()
if sysChan == nil {
return nil, false, nil, errors.New("channel creation request not allowed because the orderer system channel is not defined")
}
cs = sysChan
}
isConfig := false
switch cs.ClassifyMsg(chdr) {
case msgprocessor.ConfigUpdateMsg:
isConfig = true
case msgprocessor.ConfigMsg:
return chdr, false, nil, errors.New("message is of type that cannot be processed directly")
default:
}
return chdr, isConfig, cs, nil
}
// GetChain retrieves the chain support for a chain if it exists.
func (r *Registrar) GetChain(chainID string) *ChainSupport {
r.lock.RLock()
defer r.lock.RUnlock()
return r.chains[chainID]
}
func (r *Registrar) newLedgerResources(configTx *cb.Envelope) *ledgerResources {
payload, err := protoutil.UnmarshalPayload(configTx.Payload)
if err != nil {
logger.Panicf("Error umarshaling envelope to payload: %s", err)
}
if payload.Header == nil {
logger.Panicf("Missing channel header: %s", err)
}
chdr, err := protoutil.UnmarshalChannelHeader(payload.Header.ChannelHeader)
if err != nil {
logger.Panicf("Error unmarshaling channel header: %s", err)
}
configEnvelope, err := configtx.UnmarshalConfigEnvelope(payload.Data)
if err != nil {
logger.Panicf("Error umarshaling config envelope from payload data: %s", err)
}
bundle, err := channelconfig.NewBundle(chdr.ChannelId, configEnvelope.Config, r.bccsp)
if err != nil {
logger.Panicf("Error creating channelconfig bundle: %s", err)
}
checkResourcesOrPanic(bundle)
ledger, err := r.ledgerFactory.GetOrCreate(chdr.ChannelId)
if err != nil {
logger.Panicf("Error getting ledger for %s", chdr.ChannelId)
}
return &ledgerResources{
configResources: &configResources{
mutableResources: channelconfig.NewBundleSource(bundle, r.callbacks...),
bccsp: r.bccsp,
},
ReadWriter: ledger,
}
}
// CreateChain makes the Registrar create a chain with the given name.
func (r *Registrar) CreateChain(chainName string) {
lf, err := r.ledgerFactory.GetOrCreate(chainName)
if err != nil {
logger.Panicf("Failed obtaining ledger factory for %s: %v", chainName, err)
}
chain := r.GetChain(chainName)
if chain != nil {
logger.Infof("A chain of type %T for channel %s already exists. "+
"Halting it.", chain.Chain, chainName)
chain.Halt()
}
r.newChain(configTx(lf))
}
func (r *Registrar) newChain(configtx *cb.Envelope) {
r.lock.Lock()
defer r.lock.Unlock()
ledgerResources := r.newLedgerResources(configtx)
// If we have no blocks, we need to create the genesis block ourselves.
if ledgerResources.Height() == 0 {
ledgerResources.Append(blockledger.CreateNextBlock(ledgerResources, []*cb.Envelope{configtx}))
}
cs := newChainSupport(r, ledgerResources, r.consenters, r.signer, r.blockcutterMetrics, r.bccsp)
chainID := ledgerResources.ConfigtxValidator().ChannelID()
r.chains[chainID] = cs
logger.Infof("Created and starting new channel %s", chainID)
cs.start()
}
// ChannelsCount returns the count of the current total number of channels.
func (r *Registrar) ChannelsCount() int {
r.lock.RLock()
defer r.lock.RUnlock()
return len(r.chains)
}
// NewChannelConfig produces a new template channel configuration based on the system channel's current config.
func (r *Registrar) NewChannelConfig(envConfigUpdate *cb.Envelope) (channelconfig.Resources, error) {
return r.templator.NewChannelConfig(envConfigUpdate)
}
// CreateBundle calls channelconfig.NewBundle
func (r *Registrar) CreateBundle(channelID string, config *cb.Config) (channelconfig.Resources, error) {
return channelconfig.NewBundle(channelID, config, r.bccsp)
}
// ChannelList returns a slice of ChannelInfoShort containing all application channels (excluding the system
// channel), and ChannelInfoShort of the system channel (nil if does not exist).
// The URL fields are empty, and are to be completed by the caller.
func (r *Registrar) ChannelList() types.ChannelList {
r.lock.RLock()
defer r.lock.RUnlock()
list := types.ChannelList{}
if len(r.chains) == 0 {
return list
}
if r.systemChannelID != "" {
list.SystemChannel = &types.ChannelInfoShort{Name: r.systemChannelID}
}
for name := range r.chains {
if name == r.systemChannelID {
continue
}
list.Channels = append(list.Channels, types.ChannelInfoShort{Name: name})
}
return list
}
func (r *Registrar) ChannelInfo(channelID string) (types.ChannelInfo, error) {
r.lock.RLock()
defer r.lock.RUnlock()
info := types.ChannelInfo{}
cs, ok := r.chains[channelID]
if !ok {
return info, types.ErrChannelNotExist
}
info.Name = channelID
info.Height = cs.Height()
info.ClusterRelation, info.Status = cs.StatusReport()
return info, nil
}
func (r *Registrar) JoinChannel(channelID string, configBlock *cb.Block) (types.ChannelInfo, error) {
r.lock.RLock()
defer r.lock.RUnlock()
if r.systemChannelID != "" {
return types.ChannelInfo{}, types.ErrSystemChannelExists
}
_, ok := r.chains[channelID]
if ok {
return types.ChannelInfo{}, types.ErrChannelAlreadyExists
}
//TODO
return types.ChannelInfo{}, errors.New("Not implemented yet")
}
func (r *Registrar) RemoveChannel(channelID string, removeStorage bool) error {
//TODO
return errors.New("Not implemented yet")
}