Skip to content

Commit aa72e6d

Browse files
author
Jason Yellick
committed
[FAB-5274] Make WriteBlock asynchronous
In general, each consensus plugin for the ordering service has a single thread which is responsible for receiving ordered messages, and writing them into blocks. This is a good thing, because it makes the consensus implementations simpler and less error prone. However, for operations like WriteBlock which require some computations to be performed, followed by IO puts a serious synchronous block in the path of these consensus threads. While the block is being written, the thread cannot do other things like drain the queue or build the next block to write. This CR decouples the actual writing of the block from the consenting thread. It accomplishes this by acquiring a lock in WriteBlock, then spawning a go routine to go do the IO work, which releases the lock once done. While the lock is held, the consenter thread may perform other work, but, if it gets to the point where it must construct a new block, the CreateNextBlock function also acquires the lock, ensuring that the integrity of the hash chain is not broken. In non-scientific local testing with Solo, this produced an approximate 30% increase in overall orderer throughput. Change-Id: I11e2f9a716d415726c48066abe88a11a6e2fd1e0 Signed-off-by: Jason Yellick <jyellick@us.ibm.com>
1 parent 307ee2d commit aa72e6d

File tree

7 files changed

+438
-351
lines changed

7 files changed

+438
-351
lines changed
Lines changed: 209 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,209 @@
1+
/*
2+
Copyright IBM Corp. 2017 All Rights Reserved.
3+
4+
SPDX-License-Identifier: Apache-2.0
5+
*/
6+
7+
package multichannel
8+
9+
import (
10+
"sync"
11+
12+
"github.com/hyperledger/fabric/common/configtx"
13+
configtxapi "github.com/hyperledger/fabric/common/configtx/api"
14+
"github.com/hyperledger/fabric/common/crypto"
15+
"github.com/hyperledger/fabric/common/util"
16+
"github.com/hyperledger/fabric/orderer/common/ledger"
17+
cb "github.com/hyperledger/fabric/protos/common"
18+
"github.com/hyperledger/fabric/protos/utils"
19+
20+
"github.com/golang/protobuf/proto"
21+
)
22+
23+
type blockWriterSupport interface {
24+
crypto.LocalSigner
25+
ledger.ReadWriter
26+
configtxapi.Manager
27+
}
28+
29+
// BlockWriter efficiently writes the blockchain to disk.
30+
// To safely use BlockWriter, only one thread should interact with it.
31+
// BlockWriter will spawn additional committing go routines and handle locking
32+
// so that these other go routines safely interact with the calling one.
33+
type BlockWriter struct {
34+
support blockWriterSupport
35+
registrar *Registrar
36+
lastConfigBlockNum uint64
37+
lastConfigSeq uint64
38+
lastBlock *cb.Block
39+
committingBlock sync.Mutex
40+
}
41+
42+
func newBlockWriter(lastBlock *cb.Block, r *Registrar, support blockWriterSupport) *BlockWriter {
43+
bw := &BlockWriter{
44+
support: support,
45+
lastConfigSeq: support.Sequence(),
46+
lastBlock: lastBlock,
47+
registrar: r,
48+
}
49+
50+
// If this is the genesis block, the lastconfig field may be empty, and, the last config block is necessarily block 0
51+
// so no need to initialize lastConfig
52+
if lastBlock.Header.Number != 0 {
53+
var err error
54+
bw.lastConfigBlockNum, err = utils.GetLastConfigIndexFromBlock(lastBlock)
55+
if err != nil {
56+
logger.Panicf("[channel: %s] Error extracting last config block from block metadata: %s", support.ChainID(), err)
57+
}
58+
}
59+
60+
logger.Debugf("[channel: %s] Creating block writer for tip of chain (blockNumber=%d, lastConfigBlockNum=%d, lastConfigSeq=%d)", support.ChainID(), lastBlock.Header.Number, bw.lastConfigBlockNum, bw.lastConfigSeq)
61+
return bw
62+
}
63+
64+
// CreateNextBlock creates a new block with the next block number, and the given contents.
65+
func (bw *BlockWriter) CreateNextBlock(messages []*cb.Envelope) *cb.Block {
66+
previousBlockHash := bw.lastBlock.Header.Hash()
67+
68+
data := &cb.BlockData{
69+
Data: make([][]byte, len(messages)),
70+
}
71+
72+
var err error
73+
for i, msg := range messages {
74+
data.Data[i], err = proto.Marshal(msg)
75+
if err != nil {
76+
logger.Panicf("Could not marshal envelope: %s", err)
77+
}
78+
}
79+
80+
block := cb.NewBlock(bw.lastBlock.Header.Number+1, previousBlockHash)
81+
block.Header.DataHash = data.Hash()
82+
block.Data = data
83+
84+
return block
85+
}
86+
87+
// WriteConfigBlock should be invoked for blocks which contain a config transaction.
88+
// This call will block until the new config has taken effect, then will return
89+
// while the block is written asynchronously to disk.
90+
func (bw *BlockWriter) WriteConfigBlock(block *cb.Block, encodedMetadataValue []byte) {
91+
ctx, err := utils.ExtractEnvelope(block, 0)
92+
if err != nil {
93+
logger.Panicf("Told to write a config block, but could not get configtx: %s", err)
94+
}
95+
96+
payload, err := utils.UnmarshalPayload(ctx.Payload)
97+
if err != nil {
98+
logger.Panicf("Told to write a config block, but configtx payload is invalid: %s", err)
99+
}
100+
101+
if payload.Header == nil {
102+
logger.Panicf("Told to write a config block, but configtx payload header is missing")
103+
}
104+
105+
chdr, err := utils.UnmarshalChannelHeader(payload.Header.ChannelHeader)
106+
if err != nil {
107+
logger.Panicf("Told to write a config block with an invalid channel header: %s", err)
108+
}
109+
110+
switch chdr.Type {
111+
case int32(cb.HeaderType_ORDERER_TRANSACTION):
112+
newChannelConfig, err := utils.UnmarshalEnvelope(payload.Data)
113+
if err != nil {
114+
logger.Panicf("Told to write a config block with new channel, but did not have config update embedded: %s", err)
115+
}
116+
bw.registrar.newChain(newChannelConfig)
117+
case int32(cb.HeaderType_CONFIG):
118+
configEnvelope, err := configtx.UnmarshalConfigEnvelope(payload.Data)
119+
if err != nil {
120+
logger.Panicf("Told to write a config block with new channel, but did not have config envelope encoded: %s", err)
121+
}
122+
123+
err = bw.support.Apply(configEnvelope)
124+
if err != nil {
125+
logger.Panicf("Told to write a config block with new config, but could not apply it: %s", err)
126+
}
127+
default:
128+
logger.Panicf("Told to write a config block with unknown header type: %v", chdr.Type)
129+
}
130+
131+
bw.WriteBlock(block, encodedMetadataValue)
132+
}
133+
134+
// WriteBlock should be invoked for blocks which contain normal transactions.
135+
// It sets the target block as the pending next block, and returns before it is committed.
136+
// Before returning, it acquires the committing lock, and spawns a go routine which will
137+
// annotate the block with metadata and signatures, and write the block to the ledger
138+
// then release the lock. This allows the calling thread to begin assembling the next block
139+
// before the commit phase is complete.
140+
func (bw *BlockWriter) WriteBlock(block *cb.Block, encodedMetadataValue []byte) {
141+
bw.committingBlock.Lock()
142+
bw.lastBlock = block
143+
144+
go func() {
145+
defer bw.committingBlock.Unlock()
146+
bw.commitBlock(encodedMetadataValue)
147+
}()
148+
}
149+
150+
// commitBlock should only ever be invoked with the bw.committingBlock held
151+
// this ensures that the encoded config sequence numbers stay in sync
152+
func (bw *BlockWriter) commitBlock(encodedMetadataValue []byte) {
153+
// Set the orderer-related metadata field
154+
if encodedMetadataValue != nil {
155+
bw.lastBlock.Metadata.Metadata[cb.BlockMetadataIndex_ORDERER] = utils.MarshalOrPanic(&cb.Metadata{Value: encodedMetadataValue})
156+
}
157+
bw.addBlockSignature(bw.lastBlock)
158+
bw.addLastConfigSignature(bw.lastBlock)
159+
160+
err := bw.support.Append(bw.lastBlock)
161+
if err != nil {
162+
logger.Panicf("[channel: %s] Could not append block: %s", bw.support.ChainID(), err)
163+
}
164+
logger.Debugf("[channel: %s] Wrote block %d", bw.support.ChainID(), bw.lastBlock.GetHeader().Number)
165+
}
166+
167+
func (bw *BlockWriter) addBlockSignature(block *cb.Block) {
168+
blockSignature := &cb.MetadataSignature{
169+
SignatureHeader: utils.MarshalOrPanic(utils.NewSignatureHeaderOrPanic(bw.support)),
170+
}
171+
172+
// Note, this value is intentionally nil, as this metadata is only about the signature, there is no additional metadata
173+
// information required beyond the fact that the metadata item is signed.
174+
blockSignatureValue := []byte(nil)
175+
176+
blockSignature.Signature = utils.SignOrPanic(bw.support, util.ConcatenateBytes(blockSignatureValue, blockSignature.SignatureHeader, block.Header.Bytes()))
177+
178+
block.Metadata.Metadata[cb.BlockMetadataIndex_SIGNATURES] = utils.MarshalOrPanic(&cb.Metadata{
179+
Value: blockSignatureValue,
180+
Signatures: []*cb.MetadataSignature{
181+
blockSignature,
182+
},
183+
})
184+
}
185+
186+
func (bw *BlockWriter) addLastConfigSignature(block *cb.Block) {
187+
configSeq := bw.support.Sequence()
188+
if configSeq > bw.lastConfigSeq {
189+
logger.Debugf("[channel: %s] Detected lastConfigSeq transitioning from %d to %d, setting lastConfigBlockNum from %d to %d", bw.support.ChainID(), bw.lastConfigSeq, configSeq, bw.lastConfigBlockNum, block.Header.Number)
190+
bw.lastConfigBlockNum = block.Header.Number
191+
bw.lastConfigSeq = configSeq
192+
}
193+
194+
lastConfigSignature := &cb.MetadataSignature{
195+
SignatureHeader: utils.MarshalOrPanic(utils.NewSignatureHeaderOrPanic(bw.support)),
196+
}
197+
198+
lastConfigValue := utils.MarshalOrPanic(&cb.LastConfig{Index: bw.lastConfigBlockNum})
199+
logger.Debugf("[channel: %s] About to write block, setting its LAST_CONFIG to %d", bw.support.ChainID(), bw.lastConfigBlockNum)
200+
201+
lastConfigSignature.Signature = utils.SignOrPanic(bw.support, util.ConcatenateBytes(lastConfigValue, lastConfigSignature.SignatureHeader, block.Header.Bytes()))
202+
203+
block.Metadata.Metadata[cb.BlockMetadataIndex_LAST_CONFIG] = utils.MarshalOrPanic(&cb.Metadata{
204+
Value: lastConfigValue,
205+
Signatures: []*cb.MetadataSignature{
206+
lastConfigSignature,
207+
},
208+
})
209+
}
Lines changed: 188 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,188 @@
1+
/*
2+
Copyright IBM Corp. 2016 All Rights Reserved.
3+
4+
Licensed under the Apache License, Version 2.0 (the "License");
5+
you may not use this file except in compliance with the License.
6+
You may obtain a copy of the License at
7+
8+
http://www.apache.org/licenses/LICENSE-2.0
9+
10+
Unless required by applicable law or agreed to in writing, software
11+
distributed under the License is distributed on an "AS IS" BASIS,
12+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
See the License for the specific language governing permissions and
14+
limitations under the License.
15+
*/
16+
17+
package multichannel
18+
19+
import (
20+
"testing"
21+
22+
// "github.com/golang/protobuf/proto"
23+
"github.com/hyperledger/fabric/common/configtx/tool/provisional"
24+
"github.com/hyperledger/fabric/common/crypto"
25+
mockconfigtx "github.com/hyperledger/fabric/common/mocks/configtx"
26+
"github.com/hyperledger/fabric/orderer/common/ledger"
27+
cb "github.com/hyperledger/fabric/protos/common"
28+
"github.com/hyperledger/fabric/protos/utils"
29+
"github.com/stretchr/testify/assert"
30+
)
31+
32+
type mockBlockWriterSupport struct {
33+
*mockconfigtx.Manager
34+
crypto.LocalSigner
35+
ledger.ReadWriter
36+
}
37+
38+
func TestCreateBlock(t *testing.T) {
39+
seedBlock := cb.NewBlock(7, []byte("lasthash"))
40+
seedBlock.Data.Data = [][]byte{[]byte("somebytes")}
41+
42+
bw := &BlockWriter{lastBlock: seedBlock}
43+
block := bw.CreateNextBlock([]*cb.Envelope{
44+
&cb.Envelope{Payload: []byte("some other bytes")},
45+
})
46+
47+
assert.Equal(t, seedBlock.Header.Number+1, block.Header.Number)
48+
assert.Equal(t, block.Data.Hash(), block.Header.DataHash)
49+
assert.Equal(t, seedBlock.Header.Hash(), block.Header.PreviousHash)
50+
}
51+
52+
func TestBlockSignature(t *testing.T) {
53+
bw := &BlockWriter{
54+
support: &mockBlockWriterSupport{
55+
LocalSigner: mockCrypto(),
56+
},
57+
}
58+
59+
block := cb.NewBlock(7, []byte("foo"))
60+
bw.addBlockSignature(block)
61+
62+
md := utils.GetMetadataFromBlockOrPanic(block, cb.BlockMetadataIndex_SIGNATURES)
63+
assert.Nil(t, md.Value, "Value is empty in this case")
64+
assert.NotNil(t, md.Signatures, "Should have signature")
65+
}
66+
67+
func TestBlockLastConfig(t *testing.T) {
68+
lastConfigSeq := uint64(6)
69+
newConfigSeq := lastConfigSeq + 1
70+
newBlockNum := uint64(9)
71+
72+
bw := &BlockWriter{
73+
support: &mockBlockWriterSupport{
74+
LocalSigner: mockCrypto(),
75+
Manager: &mockconfigtx.Manager{
76+
SequenceVal: newConfigSeq,
77+
},
78+
},
79+
lastConfigSeq: lastConfigSeq,
80+
}
81+
82+
block := cb.NewBlock(newBlockNum, []byte("foo"))
83+
bw.addLastConfigSignature(block)
84+
85+
assert.Equal(t, newBlockNum, bw.lastConfigBlockNum)
86+
assert.Equal(t, newConfigSeq, bw.lastConfigSeq)
87+
88+
md := utils.GetMetadataFromBlockOrPanic(block, cb.BlockMetadataIndex_LAST_CONFIG)
89+
assert.NotNil(t, md.Value, "Value not be empty in this case")
90+
assert.NotNil(t, md.Signatures, "Should have signature")
91+
92+
lc := utils.GetLastConfigIndexFromBlockOrPanic(block)
93+
assert.Equal(t, newBlockNum, lc)
94+
}
95+
96+
func TestWriteConfigBlock(t *testing.T) {
97+
// TODO, use assert.PanicsWithValue once available
98+
t.Run("EmptyBlock", func(t *testing.T) {
99+
assert.Panics(t, func() { (&BlockWriter{}).WriteConfigBlock(&cb.Block{}, nil) })
100+
})
101+
t.Run("BadPayload", func(t *testing.T) {
102+
assert.Panics(t, func() {
103+
(&BlockWriter{}).WriteConfigBlock(&cb.Block{
104+
Data: &cb.BlockData{
105+
Data: [][]byte{
106+
utils.MarshalOrPanic(&cb.Envelope{Payload: []byte("bad")}),
107+
},
108+
},
109+
}, nil)
110+
})
111+
})
112+
t.Run("MissingHeader", func(t *testing.T) {
113+
assert.Panics(t, func() {
114+
(&BlockWriter{}).WriteConfigBlock(&cb.Block{
115+
Data: &cb.BlockData{
116+
Data: [][]byte{
117+
utils.MarshalOrPanic(&cb.Envelope{
118+
Payload: utils.MarshalOrPanic(&cb.Payload{}),
119+
}),
120+
},
121+
},
122+
}, nil)
123+
})
124+
})
125+
t.Run("BadChannelHeader", func(t *testing.T) {
126+
assert.Panics(t, func() {
127+
(&BlockWriter{}).WriteConfigBlock(&cb.Block{
128+
Data: &cb.BlockData{
129+
Data: [][]byte{
130+
utils.MarshalOrPanic(&cb.Envelope{
131+
Payload: utils.MarshalOrPanic(&cb.Payload{
132+
Header: &cb.Header{
133+
ChannelHeader: []byte("bad"),
134+
},
135+
}),
136+
}),
137+
},
138+
},
139+
}, nil)
140+
})
141+
})
142+
t.Run("BadChannelHeaderType", func(t *testing.T) {
143+
assert.Panics(t, func() {
144+
(&BlockWriter{}).WriteConfigBlock(&cb.Block{
145+
Data: &cb.BlockData{
146+
Data: [][]byte{
147+
utils.MarshalOrPanic(&cb.Envelope{
148+
Payload: utils.MarshalOrPanic(&cb.Payload{
149+
Header: &cb.Header{
150+
ChannelHeader: utils.MarshalOrPanic(&cb.ChannelHeader{}),
151+
},
152+
}),
153+
}),
154+
},
155+
},
156+
}, nil)
157+
})
158+
})
159+
}
160+
161+
func TestGoodWriteConfig(t *testing.T) {
162+
l := NewRAMLedger(10)
163+
164+
bw := &BlockWriter{
165+
support: &mockBlockWriterSupport{
166+
LocalSigner: mockCrypto(),
167+
ReadWriter: l,
168+
Manager: &mockconfigtx.Manager{},
169+
},
170+
}
171+
172+
ctx := makeConfigTx(provisional.TestChainID, 1)
173+
block := cb.NewBlock(1, genesisBlock.Header.Hash())
174+
block.Data.Data = [][]byte{utils.MarshalOrPanic(ctx)}
175+
consenterMetadata := []byte("foo")
176+
bw.WriteConfigBlock(block, consenterMetadata)
177+
178+
// Wait for the commit to complete
179+
bw.committingBlock.Lock()
180+
bw.committingBlock.Unlock()
181+
182+
cBlock := ledger.GetBlock(l, block.Header.Number)
183+
assert.Equal(t, block.Header, cBlock.Header)
184+
assert.Equal(t, block.Data, cBlock.Data)
185+
186+
omd := utils.GetMetadataFromBlockOrPanic(block, cb.BlockMetadataIndex_ORDERER)
187+
assert.Equal(t, consenterMetadata, omd.Value)
188+
}

0 commit comments

Comments
 (0)