github.com/braveheart12/insolar-09-08-19@v0.8.7/network/transport/tcp.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 transport 19 20 import ( 21 "context" 22 "io" 23 "net" 24 "strings" 25 26 "github.com/pkg/errors" 27 28 "github.com/insolar/insolar/instrumentation/inslogger" 29 "github.com/insolar/insolar/log" 30 "github.com/insolar/insolar/metrics" 31 "github.com/insolar/insolar/network/transport/pool" 32 "github.com/insolar/insolar/network/transport/relay" 33 "github.com/insolar/insolar/network/utils" 34 ) 35 36 type tcpTransport struct { 37 baseTransport 38 39 pool pool.ConnectionPool 40 listener net.Listener 41 address string 42 } 43 44 func newTCPTransport(listener net.Listener, proxy relay.Proxy, publicAddress string) (*tcpTransport, error) { 45 transport := &tcpTransport{ 46 baseTransport: newBaseTransport(proxy, publicAddress), 47 listener: listener, 48 pool: pool.NewConnectionPool(&tcpConnectionFactory{}), 49 } 50 51 transport.sendFunc = transport.send 52 53 return transport, nil 54 } 55 56 func (t *tcpTransport) send(address string, data []byte) error { 57 ctx := context.Background() 58 logger := inslogger.FromContext(ctx) 59 60 addr, err := net.ResolveTCPAddr("tcp", address) 61 if err != nil { 62 return errors.Wrap(err, "[ send ] Failed to resolve net address") 63 } 64 65 conn, err := t.pool.GetConnection(ctx, addr) 66 if err != nil { 67 return errors.Wrap(err, "[ send ] Failed to get connection") 68 } 69 70 logger.Debug("[ send ] len = ", len(data)) 71 72 n, err := conn.Write(data) 73 74 if err != nil { 75 t.pool.CloseConnection(ctx, addr) 76 conn, err = t.pool.GetConnection(ctx, addr) 77 if err != nil { 78 return errors.Wrap(err, "[ send ] Failed to get connection") 79 } 80 n, err = conn.Write(data) 81 } 82 83 if err == nil { 84 metrics.NetworkSentSize.Add(float64(n)) 85 return nil 86 } 87 return errors.Wrap(err, "[ send ] Failed to write data") 88 } 89 90 func (t *tcpTransport) prepareListen() (net.Listener, error) { 91 t.mutex.Lock() 92 defer t.mutex.Unlock() 93 94 t.disconnectStarted = make(chan bool, 1) 95 t.disconnectFinished = make(chan bool, 1) 96 97 if t.listener != nil { 98 t.address = t.listener.Addr().String() 99 } else { 100 var err error 101 t.listener, err = net.Listen("tcp", t.address) 102 if err != nil { 103 return nil, errors.Wrap(err, "failed to listen TCP") 104 } 105 } 106 107 return t.listener, nil 108 } 109 110 // Start starts networking. 111 func (t *tcpTransport) Listen(ctx context.Context) error { 112 logger := inslogger.FromContext(ctx) 113 logger.Info("[ Listen ] Start TCP transport") 114 115 listener, err := t.prepareListen() 116 if err != nil { 117 logger.Info("[ Listen ] Failed to prepare TCP transport: ", err.Error()) 118 return err 119 } 120 121 go func() { 122 for { 123 conn, err := listener.Accept() 124 if err != nil { 125 <-t.disconnectFinished 126 if strings.Contains(strings.ToLower(err.Error()), "use of closed network connection") { 127 logger.Info("Connection closed, quiting accept loop") 128 return 129 } 130 131 logger.Error("[ Listen ] Failed to accept connection: ", err.Error()) 132 return 133 } 134 135 logger.Debugf("[ Listen ] Accepted new connection from %s", conn.RemoteAddr()) 136 137 go t.handleAcceptedConnection(conn) 138 } 139 140 }() 141 142 return nil 143 } 144 145 // Stop stops networking. 146 func (t *tcpTransport) Stop() { 147 t.mutex.Lock() 148 defer t.mutex.Unlock() 149 150 log.Info("[ Stop ] Stop TCP transport") 151 t.prepareDisconnect() 152 153 if t.listener != nil { 154 utils.CloseVerbose(t.listener) 155 t.listener = nil 156 } 157 t.pool.Reset() 158 } 159 160 func (t *tcpTransport) handleAcceptedConnection(conn net.Conn) { 161 defer utils.CloseVerbose(conn) 162 163 for { 164 msg, err := t.serializer.DeserializePacket(conn) 165 166 if err != nil { 167 if err == io.EOF || err == io.ErrUnexpectedEOF { 168 log.Warn("[ handleAcceptedConnection ] Connection closed by peer") 169 return 170 } 171 172 log.Error("[ handleAcceptedConnection ] Failed to deserialize packet: ", err.Error()) 173 } else { 174 ctx, logger := inslogger.WithTraceField(context.Background(), msg.TraceID) 175 logger.Debug("[ handleAcceptedConnection ] Handling packet: ", msg.RequestID) 176 177 go t.packetHandler.Handle(ctx, msg) 178 } 179 } 180 } 181 182 type tcpConnectionFactory struct{} 183 184 func (*tcpConnectionFactory) CreateConnection(ctx context.Context, address net.Addr) (net.Conn, error) { 185 logger := inslogger.FromContext(ctx) 186 tcpAddress, ok := address.(*net.TCPAddr) 187 if !ok { 188 return nil, errors.New("[ createConnection ] Failed to get tcp address") 189 } 190 191 conn, err := net.DialTCP("tcp", nil, tcpAddress) 192 if err != nil { 193 logger.Errorf("[ createConnection ] Failed to open connection to %s: %s", address, err.Error()) 194 return nil, errors.Wrap(err, "[ createConnection ] Failed to open connection") 195 } 196 197 err = conn.SetKeepAlive(true) 198 if err != nil { 199 logger.Error("[ createConnection ] Failed to set keep alive") 200 } 201 202 err = conn.SetNoDelay(true) 203 if err != nil { 204 logger.Error("[ createConnection ] Failed to set connection no delay: ", err.Error()) 205 } 206 207 return conn, nil 208 }