Skip to content

Commit

Permalink
[FAB-998] Add new-chain sample client
Browse files Browse the repository at this point in the history
https://jira.hyperledger.org/browse/FAB-998

This changeset introduces a sample client that sends a single envelope
via the broadcast RPC to the ordering service. This envelope contains a
configuration envelope that calls for the creation of a new chain.

The client is invoked as follows:

$ broadcast_config -cmd new-chain -chainID newChainID

As is the case with the bd_counter sample client, the user can also set
the logging level (-loglevel) and the address of the RPC server
(-server).  The user may also set the backing creation policy
(-creationPolicy).

This changeset also adds chainID support for the deliver_stdout and the
broadcast_timestamp sample clients.

Change-Id: I782eb77c45f5c8d91c75c4440e47a20ab76a560e
Signed-off-by: Kostas Christidis <kostas@christidis.io>
Signed-off-by: Jason Yellick <jyellick@us.ibm.com>
  • Loading branch information
Jason Yellick committed Dec 12, 2016
1 parent 9028424 commit 1093492
Show file tree
Hide file tree
Showing 6 changed files with 245 additions and 17 deletions.
6 changes: 4 additions & 2 deletions orderer/sample_clients/bd_counter/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@ import (
"google.golang.org/grpc"
)

const pkgName = "orderer/bd_counter"

var logger *logging.Logger

type configImpl struct {
Expand All @@ -49,7 +51,7 @@ func main() {
logging.SetBackend(backend)
formatter := logging.MustStringFormatter("[%{time:15:04:05}] %{shortfile:18s}: %{color}[%{level:-5s}]%{color:reset} %{message}")
logging.SetFormatter(formatter)
logger = logging.MustGetLogger("orderer/bd_counter")
logger = logging.MustGetLogger(pkgName)

flag.StringVar(&client.config.rpc, "rpc", "broadcast",
"The RPC that this client is requesting.")
Expand Down Expand Up @@ -78,7 +80,7 @@ func main() {

conn, err := grpc.Dial(client.config.server, grpc.WithInsecure())
if err != nil {
logger.Fatalf("Client did not connect to %s: %v\n", client.config.server, err)
logger.Fatalf("Client did not connect to %s: %v", client.config.server, err)
}
defer conn.Close()
client.rpc = ab.NewAtomicBroadcastClient(conn)
Expand Down
61 changes: 61 additions & 0 deletions orderer/sample_clients/broadcast_config/broadcast.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
/*
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 main

import (
"fmt"
"io"

cb "github.com/hyperledger/fabric/protos/common"
ab "github.com/hyperledger/fabric/protos/orderer"
context "golang.org/x/net/context"
)

func (c *clientImpl) broadcast(envelope *cb.Envelope) {
stream, err := c.rpc.Broadcast(context.Background())
if err != nil {
panic(fmt.Errorf("Failed to invoke broadcast RPC: %s", err))
}
go c.recvBroadcastReplies(stream)

if err := stream.Send(envelope); err != nil {
panic(fmt.Errorf("Failed to send broadcast message to ordering service: %s", err))
}
logger.Debugf("Sent broadcast message \"%v\" to ordering service\n", envelope)

if err := stream.CloseSend(); err != nil {
panic(fmt.Errorf("Failed to close the send direction of the broadcast stream: %v", err))
}

<-c.doneChan // Wait till we've had a chance to get back a reply (or an error)
logger.Info("Client shutting down")
}

func (c *clientImpl) recvBroadcastReplies(stream ab.AtomicBroadcast_BroadcastClient) {
defer close(c.doneChan)
for {
reply, err := stream.Recv()
if err == io.EOF {
return
}
if err != nil {
panic(fmt.Errorf("Failed to receive a broadcast reply from orderer: %v", err))
}
logger.Info("Broadcast reply from orderer:", reply.Status.String())
break
}
}
98 changes: 98 additions & 0 deletions orderer/sample_clients/broadcast_config/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
/*
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 main

import (
"flag"
"os"
"strings"

ab "github.com/hyperledger/fabric/protos/orderer"
logging "github.com/op/go-logging"
"google.golang.org/grpc"
)

const pkgName = "orderer/broadcast_config"

var logger *logging.Logger

// Include here all the possible arguments for a command
type argsImpl struct {
creationPolicy string
chainID string
}

// This holds the command and its arguments
type cmdImpl struct {
cmd string
args argsImpl
}

type configImpl struct {
logLevel logging.Level
server string
cmd cmdImpl
}

type clientImpl struct {
config configImpl
rpc ab.AtomicBroadcastClient
doneChan chan struct{}
}

func main() {
var loglevel string

client := &clientImpl{doneChan: make(chan struct{})}

backend := logging.NewLogBackend(os.Stderr, "", 0)
logging.SetBackend(backend)
formatter := logging.MustStringFormatter("[%{time:15:04:05}] %{shortfile:18s}: %{color}[%{level:-5s}]%{color:reset} %{message}")
logging.SetFormatter(formatter)
logger = logging.MustGetLogger(pkgName)

flag.StringVar(&loglevel, "loglevel", "info",
"The logging level. (Suggested values: info, debug)")
flag.StringVar(&client.config.server, "server",
"127.0.0.1:7050", "The RPC server to connect to.")
flag.StringVar(&client.config.cmd.cmd, "cmd", "new-chain",
"The action that this client is requesting via the config transaction.")
flag.StringVar(&client.config.cmd.args.creationPolicy, "creationPolicy", "AcceptAllPolicy",
"In case of a new-chain command, the chain createion policy this request should be validated against.")
flag.StringVar(&client.config.cmd.args.chainID, "chainID", "NewChainID",
"In case of a new-chain command, the chain ID to create.")
flag.Parse()

client.config.logLevel, _ = logging.LogLevel(strings.ToUpper(loglevel))
logging.SetLevel(client.config.logLevel, logger.Module)

conn, err := grpc.Dial(client.config.server, grpc.WithInsecure())
if err != nil {
logger.Fatalf("Client did not connect to %s: %v", client.config.server, err)
}
defer conn.Close()
client.rpc = ab.NewAtomicBroadcastClient(conn)

switch client.config.cmd.cmd {
case "new-chain":
envelope := newChainRequest(client.config.cmd.args.creationPolicy, client.config.cmd.args.chainID)
logger.Infof("Requesting the creation of chain \"%s\"", client.config.cmd.args.chainID)
client.broadcast(envelope)
default:
panic("Invalid cmd given")
}
}
43 changes: 43 additions & 0 deletions orderer/sample_clients/broadcast_config/newchain.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
/*
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 main

import (
"github.com/hyperledger/fabric/orderer/common/bootstrap/static"
cb "github.com/hyperledger/fabric/protos/common"
ab "github.com/hyperledger/fabric/protos/orderer"
"github.com/hyperledger/fabric/protos/utils"
)

var genesisBlock *cb.Block

func init() {
helper := static.New()
var err error
genesisBlock, err = helper.GenesisBlock()
if err != nil {
panic("Error retrieving static genesis block")
}
}

func newChainRequest(creationPolicy, newChainID string) *cb.Envelope {
oldGenesisTx := utils.ExtractEnvelopeOrPanic(genesisBlock, 0)
oldGenesisTxPayload := utils.ExtractPayloadOrPanic(oldGenesisTx)
oldConfigEnv := utils.UnmarshalConfigurationEnvelopeOrPanic(oldGenesisTxPayload.Data)

return ab.ChainCreationConfigurationTransaction(static.AcceptAllPolicyKey, newChainID, oldConfigEnv)
}
29 changes: 21 additions & 8 deletions orderer/sample_clients/broadcast_timestamp/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ limitations under the License.
package main

import (
"flag"
"fmt"
"time"

Expand All @@ -30,19 +31,20 @@ import (
)

type broadcastClient struct {
client ab.AtomicBroadcast_BroadcastClient
client ab.AtomicBroadcast_BroadcastClient
chainID string
}

// newBroadcastClient creates a simple instance of the broadcastClient interface
func newBroadcastClient(client ab.AtomicBroadcast_BroadcastClient) *broadcastClient {
return &broadcastClient{client: client}
func newBroadcastClient(client ab.AtomicBroadcast_BroadcastClient, chainID string) *broadcastClient {
return &broadcastClient{client: client, chainID: chainID}
}

func (s *broadcastClient) broadcast(transaction []byte) error {
payload, err := proto.Marshal(&cb.Payload{
Header: &cb.Header{
ChainHeader: &cb.ChainHeader{
ChainID: static.TestChainID,
ChainID: s.chainID,
},
},
Data: transaction,
Expand All @@ -66,7 +68,16 @@ func (s *broadcastClient) getAck() error {

func main() {
config := config.Load()
serverAddr := fmt.Sprintf("%s:%d", config.General.ListenAddress, config.General.ListenPort)

var chainID string
var serverAddr string
var messages uint64

flag.StringVar(&serverAddr, "server", fmt.Sprintf("%s:%d", config.General.ListenAddress, config.General.ListenPort), "The RPC server to connect to.")
flag.StringVar(&chainID, "chainID", static.TestChainID, "The chain ID to broadcast to.")
flag.Uint64Var(&messages, "messages", 1, "The number of messages to braodcast.")
flag.Parse()

conn, err := grpc.Dial(serverAddr, grpc.WithInsecure())
defer conn.Close()
if err != nil {
Expand All @@ -79,9 +90,11 @@ func main() {
return
}

s := newBroadcastClient(client)
s.broadcast([]byte(fmt.Sprintf("Testing %v", time.Now())))
err = s.getAck()
s := newBroadcastClient(client, chainID)
for i := uint64(0); i < messages; i++ {
s.broadcast([]byte(fmt.Sprintf("Testing %v", time.Now())))
err = s.getAck()
}
if err != nil {
fmt.Printf("\nError: %v\n", err)
}
Expand Down
25 changes: 18 additions & 7 deletions orderer/sample_clients/deliver_stdout/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ limitations under the License.
package main

import (
"flag"
"fmt"

"github.com/hyperledger/fabric/orderer/common/bootstrap/static"
Expand All @@ -29,12 +30,13 @@ import (

type deliverClient struct {
client ab.AtomicBroadcast_DeliverClient
chainID string
windowSize uint64
unAcknowledged uint64
}

func newDeliverClient(client ab.AtomicBroadcast_DeliverClient, windowSize uint64) *deliverClient {
return &deliverClient{client: client, windowSize: windowSize}
func newDeliverClient(client ab.AtomicBroadcast_DeliverClient, chainID string, windowSize uint64) *deliverClient {
return &deliverClient{client: client, chainID: chainID, windowSize: windowSize}
}

func (r *deliverClient) seekOldest() error {
Expand All @@ -43,7 +45,7 @@ func (r *deliverClient) seekOldest() error {
Seek: &ab.SeekInfo{
Start: ab.SeekInfo_OLDEST,
WindowSize: r.windowSize,
ChainID: static.TestChainID,
ChainID: r.chainID,
},
},
})
Expand All @@ -55,7 +57,7 @@ func (r *deliverClient) seekNewest() error {
Seek: &ab.SeekInfo{
Start: ab.SeekInfo_NEWEST,
WindowSize: r.windowSize,
ChainID: static.TestChainID,
ChainID: r.chainID,
},
},
})
Expand All @@ -68,7 +70,7 @@ func (r *deliverClient) seek(blockNumber uint64) error {
Start: ab.SeekInfo_SPECIFIED,
SpecifiedNumber: blockNumber,
WindowSize: r.windowSize,
ChainID: static.TestChainID,
ChainID: r.chainID,
},
},
})
Expand Down Expand Up @@ -109,7 +111,16 @@ func (r *deliverClient) readUntilClose() {

func main() {
config := config.Load()
serverAddr := fmt.Sprintf("%s:%d", config.General.ListenAddress, config.General.ListenPort)

var chainID string
var serverAddr string
var windowSize uint64

flag.StringVar(&serverAddr, "server", fmt.Sprintf("%s:%d", config.General.ListenAddress, config.General.ListenPort), "The RPC server to connect to.")
flag.StringVar(&chainID, "chainID", static.TestChainID, "The chain ID to deliver from.")
flag.Uint64Var(&windowSize, "windowSize", 10, "The window size for the deliver.")
flag.Parse()

conn, err := grpc.Dial(serverAddr, grpc.WithInsecure())
if err != nil {
fmt.Println("Error connecting:", err)
Expand All @@ -121,7 +132,7 @@ func main() {
return
}

s := newDeliverClient(client, 10)
s := newDeliverClient(client, chainID, windowSize)
s.seekOldest()
s.readUntilClose()

Expand Down

0 comments on commit 1093492

Please sign in to comment.