NewNetTransport returns a net transport with the given configuration. On success all the network listeners will be created and listening.
(config *NetTransportConfig)
| 64 | // NewNetTransport returns a net transport with the given configuration. On |
| 65 | // success all the network listeners will be created and listening. |
| 66 | func NewNetTransport(config *NetTransportConfig) (*NetTransport, error) { |
| 67 | // If we reject the empty list outright we can assume that there's at |
| 68 | // least one listener of each type later during operation. |
| 69 | if len(config.BindAddrs) == 0 { |
| 70 | return nil, fmt.Errorf("at least one bind address is required") |
| 71 | } |
| 72 | |
| 73 | // Build out the new transport. |
| 74 | var ok bool |
| 75 | t := NetTransport{ |
| 76 | config: config, |
| 77 | packetCh: make(chan *Packet), |
| 78 | streamCh: make(chan net.Conn), |
| 79 | logger: config.Logger, |
| 80 | metricLabels: config.MetricLabels, |
| 81 | } |
| 82 | |
| 83 | // Clean up listeners if there's an error. |
| 84 | defer func() { |
| 85 | if !ok { |
| 86 | _ = t.Shutdown() |
| 87 | } |
| 88 | }() |
| 89 | |
| 90 | // Build all the TCP and UDP listeners. |
| 91 | port := config.BindPort |
| 92 | for _, addr := range config.BindAddrs { |
| 93 | ip := net.ParseIP(addr) |
| 94 | |
| 95 | tcpAddr := &net.TCPAddr{IP: ip, Port: port} |
| 96 | tcpLn, err := net.ListenTCP("tcp", tcpAddr) |
| 97 | if err != nil { |
| 98 | return nil, fmt.Errorf("failed to start TCP listener on %q port %d: %v", addr, port, err) |
| 99 | } |
| 100 | t.tcpListeners = append(t.tcpListeners, tcpLn) |
| 101 | |
| 102 | // If the config port given was zero, use the first TCP listener |
| 103 | // to pick an available port and then apply that to everything |
| 104 | // else. |
| 105 | if port == 0 { |
| 106 | port = tcpLn.Addr().(*net.TCPAddr).Port |
| 107 | } |
| 108 | |
| 109 | udpAddr := &net.UDPAddr{IP: ip, Port: port} |
| 110 | udpLn, err := net.ListenUDP("udp", udpAddr) |
| 111 | if err != nil { |
| 112 | return nil, fmt.Errorf("failed to start UDP listener on %q port %d: %v", addr, port, err) |
| 113 | } |
| 114 | if err := setUDPRecvBuf(udpLn); err != nil { |
| 115 | return nil, fmt.Errorf("failed to resize UDP buffer: %v", err) |
| 116 | } |
| 117 | t.udpListeners = append(t.udpListeners, udpLn) |
| 118 | } |
| 119 | |
| 120 | // Fire them up now that we've been able to create them all. |
| 121 | for i := 0; i < len(config.BindAddrs); i++ { |
| 122 | t.wg.Add(2) |
| 123 | go t.tcpListen(t.tcpListeners[i]) |
no test coverage detected
searching dependent graphs…