comm.go 21.1 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
/*
Copyright IBM Corp. 2017 All Rights Reserved.

SPDX-License-Identifier: Apache-2.0
*/

package cluster

import (
	"bytes"
11
	"context"
12
13
	"fmt"
	"sync"
14
	"sync/atomic"
15
16
17
	"time"

	"github.com/golang/protobuf/proto"
18
	"github.com/hyperledger/fabric/common/flogging"
19
20
21
	"github.com/hyperledger/fabric/core/comm"
	"github.com/hyperledger/fabric/protos/orderer"
	"github.com/pkg/errors"
22
	"go.uber.org/zap"
23
24
	"google.golang.org/grpc"
	"google.golang.org/grpc/connectivity"
25
26
)

27
28
29
30
31
32
var (
	errOverflow = errors.New("send queue overflown")
	errAborted  = errors.New("aborted")
	errTimeout  = errors.New("rpc timeout expired")
)

33
34
35
36
37
38
39
40
41
42
// ChannelExtractor extracts the channel of a given message,
// or returns an empty string if that's not possible
type ChannelExtractor interface {
	TargetChannel(message proto.Message) string
}

//go:generate mockery -dir . -name Handler -case underscore -output ./mocks/

// Handler handles Step() and Submit() requests and returns a corresponding response
type Handler interface {
43
44
	OnConsensus(channel string, sender uint64, req *orderer.ConsensusRequest) error
	OnSubmit(channel string, sender uint64, req *orderer.SubmitRequest) error
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
}

// RemoteNode represents a cluster member
type RemoteNode struct {
	// ID is unique among all members, and cannot be 0.
	ID uint64
	// Endpoint is the endpoint of the node, denoted in %s:%d format
	Endpoint string
	// ServerTLSCert is the DER encoded TLS server certificate of the node
	ServerTLSCert []byte
	// ClientTLSCert is the DER encoded TLS client certificate of the node
	ClientTLSCert []byte
}

// String returns a string representation of this RemoteNode
func (rm RemoteNode) String() string {
61
	return fmt.Sprintf("ID: %d,\nEndpoint: %s,\nServerTLSCert:%s, ClientTLSCert:%s",
62
63
64
		rm.ID, rm.Endpoint, DERtoPEM(rm.ServerTLSCert), DERtoPEM(rm.ClientTLSCert))
}

yacovm's avatar
yacovm committed
65
66
//go:generate mockery -dir . -name Communicator -case underscore -output ./mocks/

67
68
69
70
71
72
73
74
75
// Communicator defines communication for a consenter
type Communicator interface {
	// Remote returns a RemoteContext for the given RemoteNode ID in the context
	// of the given channel, or error if connection cannot be established, or
	// the channel wasn't configured
	Remote(channel string, id uint64) (*RemoteContext, error)
	// Configure configures the communication to connect to all
	// given members, and disconnect from any members not among the given
	// members.
yacovm's avatar
yacovm committed
76
	Configure(channel string, members []RemoteNode)
77
78
79
80
81
82
83
84
85
86
	// Shutdown shuts down the communicator
	Shutdown()
}

// MembersByChannel is a mapping from channel name
// to MemberMapping
type MembersByChannel map[string]MemberMapping

// Comm implements Communicator
type Comm struct {
87
88
89
90
91
92
93
94
95
	shutdownSignal chan struct{}
	shutdown       bool
	SendBufferSize int
	Lock           sync.RWMutex
	Logger         *flogging.FabricLogger
	ChanExt        ChannelExtractor
	H              Handler
	Connections    *ConnectionStore
	Chan2Members   MembersByChannel
yacovm's avatar
yacovm committed
96
	Metrics        *Metrics
97
98
99
100
101
102
103
104
105
}

type requestContext struct {
	channel string
	sender  uint64
}

// DispatchSubmit identifies the channel and sender of the submit request and passes it
// to the underlying Handler
106
func (c *Comm) DispatchSubmit(ctx context.Context, request *orderer.SubmitRequest) error {
107
108
	reqCtx, err := c.requestContext(ctx, request)
	if err != nil {
109
		return err
110
111
112
113
	}
	return c.H.OnSubmit(reqCtx.channel, reqCtx.sender, request)
}

114
// DispatchConsensus identifies the channel and sender of the step request and passes it
115
// to the underlying Handler
116
func (c *Comm) DispatchConsensus(ctx context.Context, request *orderer.ConsensusRequest) error {
117
118
	reqCtx, err := c.requestContext(ctx, request)
	if err != nil {
119
		return err
120
	}
121
	return c.H.OnConsensus(reqCtx.channel, reqCtx.sender, request)
122
123
124
125
126
127
128
129
130
}

// classifyRequest identifies the sender and channel of the request and returns
// it wrapped in a requestContext
func (c *Comm) requestContext(ctx context.Context, msg proto.Message) (*requestContext, error) {
	channel := c.ChanExt.TargetChannel(msg)
	if channel == "" {
		return nil, errors.Errorf("badly formatted message, cannot extract channel")
	}
131

132
133
134
135
136
137
138
139
	c.Lock.RLock()
	mapping, exists := c.Chan2Members[channel]
	c.Lock.RUnlock()

	if !exists {
		return nil, errors.Errorf("channel %s doesn't exist", channel)
	}

140
	cert := comm.ExtractRawCertificateFromContext(ctx)
141
142
143
	if len(cert) == 0 {
		return nil, errors.Errorf("no TLS certificate sent")
	}
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
	stub := mapping.LookupByClientCert(cert)
	if stub == nil {
		return nil, errors.Errorf("certificate extracted from TLS connection isn't authorized")
	}
	return &requestContext{
		channel: channel,
		sender:  stub.ID,
	}, nil
}

// Remote obtains a RemoteContext linked to the destination node on the context
// of a given channel
func (c *Comm) Remote(channel string, id uint64) (*RemoteContext, error) {
	c.Lock.RLock()
	defer c.Lock.RUnlock()

	if c.shutdown {
		return nil, errors.New("communication has been shut down")
	}

	mapping, exists := c.Chan2Members[channel]
	if !exists {
		return nil, errors.Errorf("channel %s doesn't exist", channel)
	}
	stub := mapping.ByID(id)
	if stub == nil {
		return nil, errors.Errorf("node %d doesn't exist in channel %s's membership", id, channel)
	}

	if stub.Active() {
		return stub.RemoteContext, nil
	}

178
	err := stub.Activate(c.createRemoteContext(stub, channel))
179
180
181
182
183
184
185
186
187
188
189
190
191
192
	if err != nil {
		return nil, errors.WithStack(err)
	}
	return stub.RemoteContext, nil
}

// Configure configures the channel with the given RemoteNodes
func (c *Comm) Configure(channel string, newNodes []RemoteNode) {
	c.Logger.Infof("Entering, channel: %s, nodes: %v", channel, newNodes)
	defer c.Logger.Infof("Exiting")

	c.Lock.Lock()
	defer c.Lock.Unlock()

193
194
	c.createShutdownSignalIfNeeded()

195
196
197
198
199
200
201
202
203
204
205
	if c.shutdown {
		return
	}

	beforeConfigChange := c.serverCertsInUse()
	// Update the channel-scoped mapping with the new nodes
	c.applyMembershipConfig(channel, newNodes)
	// Close connections to nodes that are not present in the new membership
	c.cleanUnusedConnections(beforeConfigChange)
}

206
207
208
209
210
211
func (c *Comm) createShutdownSignalIfNeeded() {
	if c.shutdownSignal == nil {
		c.shutdownSignal = make(chan struct{})
	}
}

212
213
214
215
216
// Shutdown shuts down the instance
func (c *Comm) Shutdown() {
	c.Lock.Lock()
	defer c.Lock.Unlock()

217
218
219
220
221
	c.createShutdownSignalIfNeeded()
	if !c.shutdown {
		close(c.shutdownSignal)
	}

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
	c.shutdown = true
	for _, members := range c.Chan2Members {
		for _, member := range members {
			c.Connections.Disconnect(member.ServerTLSCert)
		}
	}
}

// cleanUnusedConnections disconnects all connections that are un-used
// at the moment of the invocation
func (c *Comm) cleanUnusedConnections(serverCertsBeforeConfig StringSet) {
	// Scan all nodes after the reconfiguration
	serverCertsAfterConfig := c.serverCertsInUse()
	// Filter out the certificates that remained after the reconfiguration
	serverCertsBeforeConfig.subtract(serverCertsAfterConfig)
	// Close the connections to all these nodes as they shouldn't be in use now
	for serverCertificate := range serverCertsBeforeConfig {
		c.Connections.Disconnect([]byte(serverCertificate))
	}
}

// serverCertsInUse returns the server certificates that are in use
// represented as strings.
func (c *Comm) serverCertsInUse() StringSet {
	endpointsInUse := make(StringSet)
	for _, mapping := range c.Chan2Members {
		endpointsInUse.union(mapping.ServerCertificates())
	}
	return endpointsInUse
}

// applyMembershipConfig sets the given RemoteNodes for the given channel
func (c *Comm) applyMembershipConfig(channel string, newNodes []RemoteNode) {
	mapping := c.getOrCreateMapping(channel)
	newNodeIDs := make(map[uint64]struct{})

	for _, node := range newNodes {
		newNodeIDs[node.ID] = struct{}{}
260
		c.updateStubInMapping(channel, mapping, node)
261
262
263
264
265
266
	}

	// Remove all stubs without a corresponding node
	// in the new nodes
	for id, stub := range mapping {
		if _, exists := newNodeIDs[id]; exists {
267
			c.Logger.Info(id, "exists in both old and new membership for channel", channel, ", skipping its deactivation")
268
269
270
271
272
273
274
275
276
			continue
		}
		c.Logger.Info("Deactivated node", id, "who's endpoint is", stub.Endpoint, "as it's removed from membership")
		delete(mapping, id)
		stub.Deactivate()
	}
}

// updateStubInMapping updates the given RemoteNode and adds it to the MemberMapping
277
func (c *Comm) updateStubInMapping(channel string, mapping MemberMapping, node RemoteNode) {
278
279
	stub := mapping.ByID(node.ID)
	if stub == nil {
280
		c.Logger.Info("Allocating a new stub for node", node.ID, "with endpoint of", node.Endpoint, "for channel", channel)
281
282
283
284
285
286
287
		stub = &Stub{}
	}

	// Check if the TLS server certificate of the node is replaced
	// and if so - then deactivate the stub, to trigger
	// a re-creation of its gRPC connection
	if !bytes.Equal(stub.ServerTLSCert, node.ServerTLSCert) {
288
289
		c.Logger.Info("Deactivating node", node.ID, "in channel", channel,
			"with endpoint of", node.Endpoint, "due to TLS certificate change")
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
		stub.Deactivate()
	}

	// Overwrite the stub Node data with the new data
	stub.RemoteNode = node

	// Put the stub into the mapping
	mapping.Put(stub)

	// Check if the stub needs activation.
	if stub.Active() {
		return
	}

	// Activate the stub
305
	stub.Activate(c.createRemoteContext(stub, channel))
306
307
308
309
310
}

// createRemoteStub returns a function that creates a RemoteContext.
// It is used as a parameter to Stub.Activate() in order to activate
// a stub atomically.
311
func (c *Comm) createRemoteContext(stub *Stub, channel string) func() (*RemoteContext, error) {
312
	return func() (*RemoteContext, error) {
313
		c.Logger.Debug("Connecting to", stub.RemoteNode, "for channel", channel)
314
315
316

		conn, err := c.Connections.Connection(stub.Endpoint, stub.ServerTLSCert)
		if err != nil {
317
			c.Logger.Warningf("Unable to obtain connection to %d(%s) (channel %s): %v", stub.ID, stub.Endpoint, channel, err)
318
319
320
			return nil, err
		}

321
322
323
324
325
326
327
328
		probeConnection := func(conn *grpc.ClientConn) error {
			connState := conn.GetState()
			if connState == connectivity.Connecting {
				return errors.Errorf("connection to %d(%s) is in state %s", stub.ID, stub.Endpoint, connState)
			}
			return nil
		}

329
330
		clusterClient := orderer.NewClusterClient(conn)

yacovm's avatar
yacovm committed
331
332
333
334
		workerCountReporter := workerCountReporter{
			channel: channel,
		}

335
		rc := &RemoteContext{
yacovm's avatar
yacovm committed
336
337
338
339
340
341
342
343
344
345
			workerCountReporter: workerCountReporter,
			Channel:             channel,
			Metrics:             c.Metrics,
			SendBuffSize:        c.SendBufferSize,
			shutdownSignal:      c.shutdownSignal,
			endpoint:            stub.Endpoint,
			Logger:              c.Logger,
			ProbeConn:           probeConnection,
			conn:                conn,
			Client:              clusterClient,
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
		}
		return rc, nil
	}
}

// getOrCreateMapping creates a MemberMapping for the given channel
// or returns the existing one.
func (c *Comm) getOrCreateMapping(channel string) MemberMapping {
	// Lazily create a mapping if it doesn't already exist
	mapping, exists := c.Chan2Members[channel]
	if !exists {
		mapping = make(MemberMapping)
		c.Chan2Members[channel] = mapping
	}
	return mapping
}

// Stub holds all information about the remote node,
// including the RemoteContext for it, and serializes
// some operations on it.
type Stub struct {
	lock sync.RWMutex
	RemoteNode
	*RemoteContext
}

// Active returns whether the Stub
// is active or not
func (stub *Stub) Active() bool {
	stub.lock.RLock()
	defer stub.lock.RUnlock()
	return stub.isActive()
}

// Active returns whether the Stub
// is active or not.
func (stub *Stub) isActive() bool {
	return stub.RemoteContext != nil
}

// Deactivate deactivates the Stub and
// ceases all communication operations
// invoked on it.
func (stub *Stub) Deactivate() {
	stub.lock.Lock()
	defer stub.lock.Unlock()
	if !stub.isActive() {
		return
	}
	stub.RemoteContext.Abort()
	stub.RemoteContext = nil
}

// Activate creates a remote context with the given function callback
// in an atomic manner - if two parallel invocations are invoked on this Stub,
// only a single invocation of createRemoteStub takes place.
func (stub *Stub) Activate(createRemoteContext func() (*RemoteContext, error)) error {
	stub.lock.Lock()
	defer stub.lock.Unlock()
	// Check if the stub has already been activated while we were waiting for the lock
	if stub.isActive() {
		return nil
	}
	remoteStub, err := createRemoteContext()
	if err != nil {
		return errors.WithStack(err)
	}

	stub.RemoteContext = remoteStub
	return nil
}

// RemoteContext interacts with remote cluster
// nodes. Every call can be aborted via call to Abort()
type RemoteContext struct {
yacovm's avatar
yacovm committed
421
422
423
424
425
426
427
428
429
430
431
432
	Metrics             *Metrics
	Channel             string
	SendBuffSize        int
	shutdownSignal      chan struct{}
	Logger              *flogging.FabricLogger
	endpoint            string
	Client              orderer.ClusterClient
	ProbeConn           func(conn *grpc.ClientConn) error
	conn                *grpc.ClientConn
	nextStreamID        uint64
	streamsByID         streamsMapperReporter
	workerCountReporter workerCountReporter
433
}
434

435
436
// Stream is used to send/receive messages to/from the remote cluster member.
type Stream struct {
437
438
439
440
	abortChan    <-chan struct{}
	sendBuff     chan *orderer.StepRequest
	commShutdown chan struct{}
	abortReason  *atomic.Value
yacovm's avatar
yacovm committed
441
	metrics      *Metrics
442
	ID           uint64
yacovm's avatar
yacovm committed
443
	Channel      string
444
445
446
447
	NodeName     string
	Endpoint     string
	Logger       *flogging.FabricLogger
	Timeout      time.Duration
448
	orderer.Cluster_StepClient
449
	Cancel   func(error)
450
451
452
453
454
455
456
457
458
459
460
461
462
	canceled *uint32
}

// StreamOperation denotes an operation done by a stream, such a Send or Receive.
type StreamOperation func() (*orderer.StepResponse, error)

// Canceled returns whether the stream was canceled.
func (stream *Stream) Canceled() bool {
	return atomic.LoadUint32(stream.canceled) == uint32(1)
}

// Send sends the given request to the remote cluster member.
func (stream *Stream) Send(request *orderer.StepRequest) error {
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
	if stream.Canceled() {
		return errors.New(stream.abortReason.Load().(string))
	}
	var allowDrop bool
	// We want to drop consensus transactions if the remote node cannot keep up with us,
	// otherwise we'll slow down the entire FSM.
	if request.GetConsensusRequest() != nil {
		allowDrop = true
	}

	return stream.sendOrDrop(request, allowDrop)
}

// sendOrDrop sends the given request to the remote cluster member, or drops it
// if it is a consensus request and the queue is full.
func (stream *Stream) sendOrDrop(request *orderer.StepRequest, allowDrop bool) error {
yacovm's avatar
yacovm committed
479
480
481
482
483
484
485
	msgType := "transaction"
	if allowDrop {
		msgType = "consensus"
	}

	stream.metrics.reportQueueOccupancy(stream.Endpoint, msgType, stream.Channel, len(stream.sendBuff), cap(stream.sendBuff))

486
487
	if allowDrop && len(stream.sendBuff) == cap(stream.sendBuff) {
		stream.Cancel(errOverflow)
yacovm's avatar
yacovm committed
488
		stream.metrics.reportMessagesDropped(stream.Endpoint, stream.Channel)
489
490
491
492
493
		return errOverflow
	}

	select {
	case <-stream.abortChan:
yacovm's avatar
yacovm committed
494
		return errors.Errorf("stream %d aborted", stream.ID)
495
496
497
498
499
500
501
502
503
	case stream.sendBuff <- request:
		return nil
	case <-stream.commShutdown:
		return nil
	}
}

// sendMessage sends the request down the stream
func (stream *Stream) sendMessage(request *orderer.StepRequest) {
504
	start := time.Now()
505
	var err error
506
507
508
509
	defer func() {
		if !stream.Logger.IsEnabledFor(zap.DebugLevel) {
			return
		}
510
511
512
513
514
515
		var result string
		if err != nil {
			result = fmt.Sprintf("but failed due to %s", err.Error())
		}
		stream.Logger.Debugf("Send of %s to %s(%s) took %v %s", requestAsString(request),
			stream.NodeName, stream.Endpoint, time.Since(start), result)
516
517
518
	}()

	f := func() (*orderer.StepResponse, error) {
yacovm's avatar
yacovm committed
519
		startSend := time.Now()
520
		err := stream.Cluster_StepClient.Send(request)
yacovm's avatar
yacovm committed
521
		stream.metrics.reportMsgSendTime(stream.Endpoint, stream.Channel, time.Since(startSend))
522
523
524
		return nil, err
	}

525
526
527
	_, err = stream.operateWithTimeout(f)
}

yacovm's avatar
yacovm committed
528
func (stream *Stream) serviceStream() {
529
530
531
532
533
534
535
536
537
538
539
540
	defer stream.Cancel(errAborted)

	for {
		select {
		case msg := <-stream.sendBuff:
			stream.sendMessage(msg)
		case <-stream.abortChan:
			return
		case <-stream.commShutdown:
			return
		}
	}
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
}

// Recv receives a message from a remote cluster member.
func (stream *Stream) Recv() (*orderer.StepResponse, error) {
	start := time.Now()
	defer func() {
		if !stream.Logger.IsEnabledFor(zap.DebugLevel) {
			return
		}
		stream.Logger.Debugf("Receive from %s(%s) took %v", stream.NodeName, stream.Endpoint, time.Since(start))
	}()

	f := func() (*orderer.StepResponse, error) {
		return stream.Cluster_StepClient.Recv()
	}

	return stream.operateWithTimeout(f)
}

// operateWithTimeout performs the given operation on the stream, and blocks until the timeout expires.
func (stream *Stream) operateWithTimeout(invoke StreamOperation) (*orderer.StepResponse, error) {
	timer := time.NewTimer(stream.Timeout)
	defer timer.Stop()

	var operationEnded sync.WaitGroup
	operationEnded.Add(1)

	responseChan := make(chan struct {
		res *orderer.StepResponse
		err error
	}, 1)

	go func() {
		defer operationEnded.Done()
		res, err := invoke()
		responseChan <- struct {
			res *orderer.StepResponse
			err error
		}{res: res, err: err}
	}()

	select {
	case r := <-responseChan:
		if r.err != nil {
585
			stream.Cancel(r.err)
586
587
588
		}
		return r.res, r.err
	case <-timer.C:
yacovm's avatar
yacovm committed
589
590
		stream.Logger.Warningf("Stream %d to %s(%s) was forcibly terminated because timeout (%v) expired",
			stream.ID, stream.NodeName, stream.Endpoint, stream.Timeout)
591
		stream.Cancel(errTimeout)
592
593
		// Wait for the operation goroutine to end
		operationEnded.Wait()
594
		return nil, errTimeout
595
596
597
	}
}

598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
func requestAsString(request *orderer.StepRequest) string {
	switch t := request.GetPayload().(type) {
	case *orderer.StepRequest_SubmitRequest:
		if t.SubmitRequest == nil || t.SubmitRequest.Payload == nil {
			return fmt.Sprintf("Empty SubmitRequest: %v", t.SubmitRequest)
		}
		return fmt.Sprintf("SubmitRequest for channel %s with payload of size %d",
			t.SubmitRequest.Channel, len(t.SubmitRequest.Payload.Payload))
	case *orderer.StepRequest_ConsensusRequest:
		return fmt.Sprintf("ConsensusRequest for channel %s with payload of size %d",
			t.ConsensusRequest.Channel, len(t.ConsensusRequest.Payload))
	default:
		return fmt.Sprintf("unknown type: %v", request)
	}
}

// NewStream creates a new stream.
// It is not thread safe, and Send() or Recv() block only until the timeout expires.
func (rc *RemoteContext) NewStream(timeout time.Duration) (*Stream, error) {
617
618
619
	if err := rc.ProbeConn(rc.conn); err != nil {
		return nil, err
	}
620

621
622
623
624
625
626
	ctx, cancel := context.WithCancel(context.TODO())
	stream, err := rc.Client.Step(ctx)
	if err != nil {
		cancel()
		return nil, errors.WithStack(err)
	}
627

628
629
	streamID := atomic.AddUint64(&rc.nextStreamID, 1)
	nodeName := commonNameFromContext(stream.Context())
630

631
	var canceled uint32
632

633
634
	abortChan := make(chan struct{})

635
636
637
	abort := func() {
		cancel()
		rc.streamsByID.Delete(streamID)
yacovm's avatar
yacovm committed
638
		rc.Metrics.reportEgressStreamCount(rc.Channel, atomic.LoadUint32(&rc.streamsByID.size))
639
640
		rc.Logger.Debugf("Stream %d to %s(%s) is aborted", streamID, nodeName, rc.endpoint)
		atomic.StoreUint32(&canceled, 1)
641
642
643
644
645
646
647
648
		close(abortChan)
	}

	once := &sync.Once{}
	abortReason := &atomic.Value{}
	cancelWithReason := func(err error) {
		abortReason.Store(err.Error())
		once.Do(abort)
649
	}
650

651
652
653
654
	logger := flogging.MustGetLogger("orderer.common.cluster.step")
	stepLogger := logger.WithOptions(zap.AddCallerSkip(1))

	s := &Stream{
yacovm's avatar
yacovm committed
655
656
		Channel:            rc.Channel,
		metrics:            rc.Metrics,
657
658
659
660
		abortReason:        abortReason,
		abortChan:          abortChan,
		sendBuff:           make(chan *orderer.StepRequest, rc.SendBuffSize),
		commShutdown:       rc.shutdownSignal,
661
662
663
664
665
666
		NodeName:           nodeName,
		Logger:             stepLogger,
		ID:                 streamID,
		Endpoint:           rc.endpoint,
		Timeout:            timeout,
		Cluster_StepClient: stream,
667
		Cancel:             cancelWithReason,
668
		canceled:           &canceled,
669
670
	}

671
672
	rc.Logger.Debugf("Created new stream to %s with ID of %d and buffer size of %d",
		rc.endpoint, streamID, cap(s.sendBuff))
673
674

	rc.streamsByID.Store(streamID, s)
yacovm's avatar
yacovm committed
675
	rc.Metrics.reportEgressStreamCount(rc.Channel, atomic.LoadUint32(&rc.streamsByID.size))
676

yacovm's avatar
yacovm committed
677
678
679
680
681
	go func() {
		rc.workerCountReporter.increment(s.metrics)
		s.serviceStream()
		rc.workerCountReporter.decrement(s.metrics)
	}()
682

683
	return s, nil
684
685
}

686
687
688
689
// Abort aborts the contexts the RemoteContext uses, thus effectively
// causes all operations that use this RemoteContext to terminate.
func (rc *RemoteContext) Abort() {
	rc.streamsByID.Range(func(_, value interface{}) bool {
690
		value.(*Stream).Cancel(errAborted)
691
692
693
		return false
	})
}
694

695
696
697
698
func commonNameFromContext(ctx context.Context) string {
	cert := comm.ExtractCertificateFromContext(ctx)
	if cert == nil {
		return "unidentified node"
699
	}
700
	return cert.Subject.CommonName
701
}
yacovm's avatar
yacovm committed
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736

type streamsMapperReporter struct {
	size uint32
	sync.Map
}

func (smr *streamsMapperReporter) Delete(key interface{}) {
	smr.Map.Delete(key)
	atomic.AddUint32(&smr.size, ^uint32(0))
}

func (smr *streamsMapperReporter) Store(key, value interface{}) {
	smr.Map.Store(key, value)
	atomic.AddUint32(&smr.size, 1)
}

type workerCountReporter struct {
	channel     string
	workerCount uint32
}

func (wcr *workerCountReporter) increment(m *Metrics) {
	count := atomic.AddUint32(&wcr.workerCount, 1)
	m.reportWorkerCount(wcr.channel, count)
}

func (wcr *workerCountReporter) decrement(m *Metrics) {
	// ^0 flips all zeros to ones, which means
	// 2^32 - 1, and then we add this number wcr.workerCount.
	// It follows from commutativity of the unsigned integers group
	// that wcr.workerCount + 2^32 - 1 = wcr.workerCount - 1 + 2^32
	// which is just wcr.workerCount - 1.
	count := atomic.AddUint32(&wcr.workerCount, ^uint32(0))
	m.reportWorkerCount(wcr.channel, count)
}