github.com/braveheart12/insolar-09-08-19@v0.8.7/network/hostnetwork/transport_base.go (about)

     1  /*
     2   * The Clear BSD License
     3   *
     4   * Copyright (c) 2019 Insolar Technologies
     5   *
     6   * All rights reserved.
     7   *
     8   * Redistribution and use in source and binary forms, with or without modification, are permitted (subject to the limitations in the disclaimer below) provided that the following conditions are met:
     9   *
    10   *  Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
    11   *  Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
    12   *  Neither the name of Insolar Technologies nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
    13   *
    14   * NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
    15   *
    16   */
    17  
    18  package hostnetwork
    19  
    20  import (
    21  	"context"
    22  	"sync/atomic"
    23  
    24  	"github.com/insolar/insolar/core"
    25  	"github.com/insolar/insolar/instrumentation/inslogger"
    26  	"github.com/insolar/insolar/log"
    27  	"github.com/insolar/insolar/network"
    28  	"github.com/insolar/insolar/network/sequence"
    29  	"github.com/insolar/insolar/network/transport"
    30  	"github.com/insolar/insolar/network/transport/host"
    31  	"github.com/insolar/insolar/network/transport/packet"
    32  	"github.com/pkg/errors"
    33  )
    34  
    35  type transportBase struct {
    36  	started           uint32
    37  	transport         transport.Transport
    38  	origin            *host.Host
    39  	messageProcessor  func(msg *packet.Packet)
    40  	sequenceGenerator sequence.Generator
    41  }
    42  
    43  // Listen start listening to network requests, should be started in goroutine.
    44  func (h *transportBase) Start(ctx context.Context) {
    45  	if !atomic.CompareAndSwapUint32(&h.started, 0, 1) {
    46  		inslogger.FromContext(ctx).Warn("double listen initiated")
    47  		return
    48  	}
    49  	if err := h.transport.Listen(ctx); err != nil {
    50  		inslogger.FromContext(ctx).Error("Failed to start transport: listen syscall failed:", err)
    51  	}
    52  
    53  	go h.listen(ctx)
    54  }
    55  
    56  func (h *transportBase) listen(ctx context.Context) {
    57  	for {
    58  		select {
    59  		case msg := <-h.transport.Packets():
    60  			if msg == nil {
    61  				log.Error("HostNetwork receiving channel is closed")
    62  				break
    63  			}
    64  			if msg.Error != nil {
    65  				log.Warnf("Received error response: %s", msg.Error.Error())
    66  			}
    67  			go h.messageProcessor(msg)
    68  		case <-h.transport.Stopped():
    69  			return
    70  		}
    71  	}
    72  }
    73  
    74  // Disconnect stop listening to network requests.
    75  func (h *transportBase) Stop() {
    76  	if atomic.CompareAndSwapUint32(&h.started, 1, 0) {
    77  		go h.transport.Stop()
    78  		<-h.transport.Stopped()
    79  		h.transport.Close()
    80  	}
    81  }
    82  
    83  func (h *transportBase) buildRequest(ctx context.Context, request network.Request, receiver *host.Host) *packet.Packet {
    84  	return packet.NewBuilder(h.origin).Receiver(receiver).Type(request.GetType()).RequestID(request.GetRequestID()).
    85  		Request(request.GetData()).TraceID(inslogger.TraceID(ctx)).Build()
    86  }
    87  
    88  // PublicAddress returns public address that can be published for all nodes.
    89  func (h *transportBase) PublicAddress() string {
    90  	return h.origin.Address.String()
    91  }
    92  
    93  // GetNodeID get current node ID.
    94  func (h *transportBase) GetNodeID() core.RecordRef {
    95  	return h.origin.NodeID
    96  }
    97  
    98  // NewRequestBuilder create packet Builder for an outgoing request with sender set to current node.
    99  func (h *transportBase) NewRequestBuilder() network.RequestBuilder {
   100  	return &Builder{sender: h.origin, id: network.RequestID(h.sequenceGenerator.Generate())}
   101  }
   102  
   103  func getOrigin(tp transport.Transport, id string) (*host.Host, error) {
   104  	address, err := host.NewAddress(tp.PublicAddress())
   105  	if err != nil {
   106  		return nil, errors.Wrap(err, "error resolving address")
   107  	}
   108  	nodeID, err := core.NewRefFromBase58(id)
   109  	if err != nil {
   110  		return nil, errors.Wrap(err, "error parsing NodeID from string")
   111  	}
   112  	origin := &host.Host{NodeID: *nodeID, Address: address}
   113  	return origin, nil
   114  }