github.com/anjalikarhana/fabric@v2.1.1+incompatible/orderer/common/broadcast/broadcast.go (about)

     1  /*
     2  Copyright IBM Corp. All Rights Reserved.
     3  
     4  SPDX-License-Identifier: Apache-2.0
     5  */
     6  
     7  package broadcast
     8  
     9  import (
    10  	"io"
    11  	"time"
    12  
    13  	cb "github.com/hyperledger/fabric-protos-go/common"
    14  	ab "github.com/hyperledger/fabric-protos-go/orderer"
    15  	"github.com/hyperledger/fabric/common/flogging"
    16  	"github.com/hyperledger/fabric/common/util"
    17  	"github.com/hyperledger/fabric/orderer/common/msgprocessor"
    18  	"github.com/pkg/errors"
    19  )
    20  
    21  var logger = flogging.MustGetLogger("orderer.common.broadcast")
    22  
    23  //go:generate counterfeiter -o mock/channel_support_registrar.go --fake-name ChannelSupportRegistrar . ChannelSupportRegistrar
    24  
    25  // ChannelSupportRegistrar provides a way for the Handler to look up the Support for a channel
    26  type ChannelSupportRegistrar interface {
    27  	// BroadcastChannelSupport returns the message channel header, whether the message is a config update
    28  	// and the channel resources for a message or an error if the message is not a message which can
    29  	// be processed directly (like CONFIG and ORDERER_TRANSACTION messages)
    30  	BroadcastChannelSupport(msg *cb.Envelope) (*cb.ChannelHeader, bool, ChannelSupport, error)
    31  }
    32  
    33  //go:generate counterfeiter -o mock/channel_support.go --fake-name ChannelSupport . ChannelSupport
    34  
    35  // ChannelSupport provides the backing resources needed to support broadcast on a channel
    36  type ChannelSupport interface {
    37  	msgprocessor.Processor
    38  	Consenter
    39  }
    40  
    41  // Consenter provides methods to send messages through consensus
    42  type Consenter interface {
    43  	// Order accepts a message or returns an error indicating the cause of failure
    44  	// It ultimately passes through to the consensus.Chain interface
    45  	Order(env *cb.Envelope, configSeq uint64) error
    46  
    47  	// Configure accepts a reconfiguration or returns an error indicating the cause of failure
    48  	// It ultimately passes through to the consensus.Chain interface
    49  	Configure(config *cb.Envelope, configSeq uint64) error
    50  
    51  	// WaitReady blocks waiting for consenter to be ready for accepting new messages.
    52  	// This is useful when consenter needs to temporarily block ingress messages so
    53  	// that in-flight messages can be consumed. It could return error if consenter is
    54  	// in erroneous states. If this blocking behavior is not desired, consenter could
    55  	// simply return nil.
    56  	WaitReady() error
    57  }
    58  
    59  // Handler is designed to handle connections from Broadcast AB gRPC service
    60  type Handler struct {
    61  	SupportRegistrar ChannelSupportRegistrar
    62  	Metrics          *Metrics
    63  }
    64  
    65  // Handle reads requests from a Broadcast stream, processes them, and returns the responses to the stream
    66  func (bh *Handler) Handle(srv ab.AtomicBroadcast_BroadcastServer) error {
    67  	addr := util.ExtractRemoteAddress(srv.Context())
    68  	logger.Debugf("Starting new broadcast loop for %s", addr)
    69  	for {
    70  		msg, err := srv.Recv()
    71  		if err == io.EOF {
    72  			logger.Debugf("Received EOF from %s, hangup", addr)
    73  			return nil
    74  		}
    75  		if err != nil {
    76  			logger.Warningf("Error reading from %s: %s", addr, err)
    77  			return err
    78  		}
    79  
    80  		resp := bh.ProcessMessage(msg, addr)
    81  		err = srv.Send(resp)
    82  		if resp.Status != cb.Status_SUCCESS {
    83  			return err
    84  		}
    85  
    86  		if err != nil {
    87  			logger.Warningf("Error sending to %s: %s", addr, err)
    88  			return err
    89  		}
    90  	}
    91  
    92  }
    93  
    94  type MetricsTracker struct {
    95  	ValidateStartTime time.Time
    96  	EnqueueStartTime  time.Time
    97  	ValidateDuration  time.Duration
    98  	ChannelID         string
    99  	TxType            string
   100  	Metrics           *Metrics
   101  }
   102  
   103  func (mt *MetricsTracker) Record(resp *ab.BroadcastResponse) {
   104  	labels := []string{
   105  		"status", resp.Status.String(),
   106  		"channel", mt.ChannelID,
   107  		"type", mt.TxType,
   108  	}
   109  
   110  	if mt.ValidateDuration == 0 {
   111  		mt.EndValidate()
   112  	}
   113  	mt.Metrics.ValidateDuration.With(labels...).Observe(mt.ValidateDuration.Seconds())
   114  
   115  	if mt.EnqueueStartTime != (time.Time{}) {
   116  		enqueueDuration := time.Since(mt.EnqueueStartTime)
   117  		mt.Metrics.EnqueueDuration.With(labels...).Observe(enqueueDuration.Seconds())
   118  	}
   119  
   120  	mt.Metrics.ProcessedCount.With(labels...).Add(1)
   121  }
   122  
   123  func (mt *MetricsTracker) BeginValidate() {
   124  	mt.ValidateStartTime = time.Now()
   125  }
   126  
   127  func (mt *MetricsTracker) EndValidate() {
   128  	mt.ValidateDuration = time.Since(mt.ValidateStartTime)
   129  }
   130  
   131  func (mt *MetricsTracker) BeginEnqueue() {
   132  	mt.EnqueueStartTime = time.Now()
   133  }
   134  
   135  // ProcessMessage validates and enqueues a single message
   136  func (bh *Handler) ProcessMessage(msg *cb.Envelope, addr string) (resp *ab.BroadcastResponse) {
   137  	tracker := &MetricsTracker{
   138  		ChannelID: "unknown",
   139  		TxType:    "unknown",
   140  		Metrics:   bh.Metrics,
   141  	}
   142  	defer func() {
   143  		// This looks a little unnecessary, but if done directly as
   144  		// a defer, resp gets the (always nil) current state of resp
   145  		// and not the return value
   146  		tracker.Record(resp)
   147  	}()
   148  	tracker.BeginValidate()
   149  
   150  	chdr, isConfig, processor, err := bh.SupportRegistrar.BroadcastChannelSupport(msg)
   151  	if chdr != nil {
   152  		tracker.ChannelID = chdr.ChannelId
   153  		tracker.TxType = cb.HeaderType(chdr.Type).String()
   154  	}
   155  	if err != nil {
   156  		logger.Warningf("[channel: %s] Could not get message processor for serving %s: %s", tracker.ChannelID, addr, err)
   157  		return &ab.BroadcastResponse{Status: cb.Status_BAD_REQUEST, Info: err.Error()}
   158  	}
   159  
   160  	if !isConfig {
   161  		logger.Debugf("[channel: %s] Broadcast is processing normal message from %s with txid '%s' of type %s", chdr.ChannelId, addr, chdr.TxId, cb.HeaderType_name[chdr.Type])
   162  
   163  		configSeq, err := processor.ProcessNormalMsg(msg)
   164  		if err != nil {
   165  			logger.Warningf("[channel: %s] Rejecting broadcast of normal message from %s because of error: %s", chdr.ChannelId, addr, err)
   166  			return &ab.BroadcastResponse{Status: ClassifyError(err), Info: err.Error()}
   167  		}
   168  		tracker.EndValidate()
   169  
   170  		tracker.BeginEnqueue()
   171  		if err = processor.WaitReady(); err != nil {
   172  			logger.Warningf("[channel: %s] Rejecting broadcast of message from %s with SERVICE_UNAVAILABLE: rejected by Consenter: %s", chdr.ChannelId, addr, err)
   173  			return &ab.BroadcastResponse{Status: cb.Status_SERVICE_UNAVAILABLE, Info: err.Error()}
   174  		}
   175  
   176  		err = processor.Order(msg, configSeq)
   177  		if err != nil {
   178  			logger.Warningf("[channel: %s] Rejecting broadcast of normal message from %s with SERVICE_UNAVAILABLE: rejected by Order: %s", chdr.ChannelId, addr, err)
   179  			return &ab.BroadcastResponse{Status: cb.Status_SERVICE_UNAVAILABLE, Info: err.Error()}
   180  		}
   181  	} else { // isConfig
   182  		logger.Debugf("[channel: %s] Broadcast is processing config update message from %s", chdr.ChannelId, addr)
   183  
   184  		config, configSeq, err := processor.ProcessConfigUpdateMsg(msg)
   185  		if err != nil {
   186  			logger.Warningf("[channel: %s] Rejecting broadcast of config message from %s because of error: %s", chdr.ChannelId, addr, err)
   187  			return &ab.BroadcastResponse{Status: ClassifyError(err), Info: err.Error()}
   188  		}
   189  		tracker.EndValidate()
   190  
   191  		tracker.BeginEnqueue()
   192  		if err = processor.WaitReady(); err != nil {
   193  			logger.Warningf("[channel: %s] Rejecting broadcast of message from %s with SERVICE_UNAVAILABLE: rejected by Consenter: %s", chdr.ChannelId, addr, err)
   194  			return &ab.BroadcastResponse{Status: cb.Status_SERVICE_UNAVAILABLE, Info: err.Error()}
   195  		}
   196  
   197  		err = processor.Configure(config, configSeq)
   198  		if err != nil {
   199  			logger.Warningf("[channel: %s] Rejecting broadcast of config message from %s with SERVICE_UNAVAILABLE: rejected by Configure: %s", chdr.ChannelId, addr, err)
   200  			return &ab.BroadcastResponse{Status: cb.Status_SERVICE_UNAVAILABLE, Info: err.Error()}
   201  		}
   202  	}
   203  
   204  	logger.Debugf("[channel: %s] Broadcast has successfully enqueued message of type %s from %s", chdr.ChannelId, cb.HeaderType_name[chdr.Type], addr)
   205  
   206  	return &ab.BroadcastResponse{Status: cb.Status_SUCCESS}
   207  }
   208  
   209  // ClassifyError converts an error type into a status code.
   210  func ClassifyError(err error) cb.Status {
   211  	switch errors.Cause(err) {
   212  	case msgprocessor.ErrChannelDoesNotExist:
   213  		return cb.Status_NOT_FOUND
   214  	case msgprocessor.ErrPermissionDenied:
   215  		return cb.Status_FORBIDDEN
   216  	case msgprocessor.ErrMaintenanceMode:
   217  		return cb.Status_SERVICE_UNAVAILABLE
   218  	default:
   219  		return cb.Status_BAD_REQUEST
   220  	}
   221  }