id
stringlengths
2
7
text
stringlengths
17
51.2k
title
stringclasses
1 value
c178200
defer l.RUnlock() return l.peerHeap.Len() }
c178201
{ l.RLock() ps, ok := l.peersByHostPort[hostPort] l.RUnlock() return ps, ok }
c178202
{ return nil, 0, false } return ps, ps.score, ok }
c178203
newScore == psScore { return } l.Lock() l.updatePeer(ps, newScore) l.Unlock() }
c178204
return } ps.score = newScore l.peerHeap.updatePeer(ps) }
c178205
p.inboundConnections[i] } return p.outboundConnections[i-inboundLen] }
c178206
else got ahead of us. if activeConn, ok := p.getActiveConn(); ok { return activeConn, nil } // No active connections, make a new outgoing connection. return p.Connect(ctx) }
c178207
connect back to us and send us traffic. We hide the host:port // so that service instances on remote machines don't try to connect back // and don't try to send Hyperbahn traffic on this connection. ctx, cancel := NewContextBuilder(timeout).HideListeningOnOutbound().Build() defer cancel() return p.Connect(ctx) }
c178208
+ len(p.outboundConnections) + int(p.scCount) p.RUnlock() return count == 0 }
c178209
p.Unlock() // Inform third parties that a peer gained a connection. p.onStatusChanged(p) return nil }
c178210
last := len(conns) - 1 conns[i], conns[last] = conns[last], nil *connsPtr = conns[:last] return true } } return false }
c178211
found { p.onClosedConnRemoved(p) // Inform third parties that a peer lost a connection. p.onStatusChanged(p) } }
c178212
p.channel.Connect(ctx, p.hostPort) }
c178213
} conn, err := p.GetConnection(ctx) if err != nil { return nil, err } call, err := conn.beginCall(ctx, serviceName, methodName, callOptions) if err != nil { return nil, err } return call, err }
c178214
= len(p.outboundConnections) p.RUnlock() return inbound, outbound }
c178215
count += c.outbound.count() } for _, c := range p.inboundConnections { count += c.outbound.count() } p.RUnlock() return count }
c178216
== ephemeralHostPort || strings.HasSuffix(hostPort, ":0") }
c178217
val, ok := h.vals[key]; ok { return val, nil } return "", &keyvalue.KeyNotFound{Key: key} }
c178218
be passed via result structs. ctx.SetResponseHeaders(map[string]string{"count": fmt.Sprint(len(h.vals))}) return nil }
c178219
defer h.Unlock() h.vals = make(map[string]string) return nil }
c178220
PeerInfo: PeerInfo{ ProcessName: processName, HostPort: ephemeralHostPort, IsEphemeral: true, Version: PeerVersion{ Language: "go", LanguageVersion: strings.TrimPrefix(runtime.Version(), "go"), TChannelVersion: VersionInfo, }, }, ServiceName: serviceName, } ch.mutable.state = ChannelClient ch.mutable.conns = make(map[uint32]*Connection) ch.createCommonStats() // Register internal unless the root handler has been overridden, since // Register will panic. if opts.Handler == nil { ch.registerInternal() } registerNewChannel(ch) if opts.RelayHost != nil { opts.RelayHost.SetChannel(ch) } // Start the idle connection timer. ch.mutable.idleSweep = startIdleSweep(ch, opts) return ch, nil }
c178221
mutable.peerInfo.IsEphemeral = false ch.log = ch.log.WithFields(LogField{"hostPort", mutable.peerInfo.HostPort}) ch.log.Info("Channel is listening.") go ch.serve() return nil }
c178222
mutable.RUnlock() return errAlreadyListening } l, err := net.Listen("tcp", hostPort) if err != nil { mutable.RUnlock() return err } mutable.RUnlock() return ch.Serve(l) }
c178223
alternate root handler") } ch.GetSubChannel(ch.PeerInfo().ServiceName).Register(h, methodName) }
c178224
ch.mutable.RUnlock() return peerInfo }
c178225
added { for _, opt := range opts { opt(sub) } } return sub }
c178226
} } acceptBackoff = 0 // Perform the connection handshake in a background goroutine. go func() { // Register the connection in the peer once the channel is set up. events := connectionEvents{ OnActive: ch.inboundConnectionActive, OnCloseStateChange: ch.connectionCloseStateChange, OnExchangeUpdated: ch.exchangeUpdated, } if _, err := ch.inboundHandshake(context.Background(), netConn, events); err != nil { netConn.Close() } }() } }
c178227
peer.GetConnection(ctx) if err != nil { return err } return conn.ping(ctx) }
c178228
:= range ch.commonStatsTags { m[k] = v } return m }
c178229
ok := err.(net.Error); ok && ne.Timeout() { ch.log.WithFields( LogField{"remoteHostPort", hostPort}, LogField{"timeout", timeout}, ).Info("Outbound net.Dial timed out.") err = ErrTimeout } else if ctx.Err() == context.Canceled { ch.log.WithFields( LogField{"remoteHostPort", hostPort}, ).Info("Outbound net.Dial was cancelled.") err = GetContextError(ErrRequestCancelled) } else { ch.log.WithFields( ErrField(err), LogField{"remoteHostPort", hostPort}, ).Info("Outbound net.Dial failed.") } return nil, err } conn, err := ch.outboundHandshake(ctx, tcpConn, hostPort, events) if conn != nil { // It's possible that the connection we just created responds with a host:port // that is not what we tried to connect to. E.g., we may have connected to // 127.0.0.1:1234, but the returned host:port may be 10.0.0.1:1234. // In this case, the connection won't be added to 127.0.0.1:1234 peer // and so future calls to that peer may end up creating new connections. To // avoid this issue, and to avoid clients being aware of any TCP relays, we // add the connection to the intended peer. if hostPort != conn.remotePeerInfo.HostPort { conn.log.Debugf("Outbound connection host:port mismatch, adding to peer %v", conn.remotePeerInfo.HostPort) ch.addConnectionToPeer(hostPort, conn, outbound) } } return conn, err }
c178230
unknown until we get init resp. return } p, ok := ch.RootPeers().Get(c.remotePeerInfo.HostPort) if !ok { return } ch.updatePeer(p) }
c178231
ch.subChannels.updatePeer(p) p.callOnUpdateComplete() }
c178232
case ChannelClient, ChannelListening: break default: return false } ch.mutable.conns[c.connID] = c return true }
c178233
ch.mutable.Lock() delete(ch.mutable.conns, c.connID) ch.mutable.Unlock() }
c178234
} ch.mutable.RLock() minState := ch.getMinConnectionState() ch.mutable.RUnlock() var updateTo ChannelState if minState >= connectionClosed { updateTo = ChannelClosed } else if minState >= connectionInboundClosed && chState == ChannelStartClose { updateTo = ChannelInboundClosed } var updatedToState ChannelState if updateTo > 0 { ch.mutable.Lock() // Recheck the state as it's possible another goroutine changed the state // from what we expected, and so we might make a stale change. if ch.mutable.state == chState { ch.mutable.state = updateTo updatedToState = updateTo } ch.mutable.Unlock() chState = updateTo } c.log.Debugf("ConnectionCloseStateChange channel state = %v connection minState = %v", chState, minState) if updatedToState == ChannelClosed { ch.onClosed() } }
c178235
ch.mutable.RUnlock() return state }
c178236
r.reader = reader r.err = nil return r }
c178237
io.ReadFull(r.reader, buf) if readN < 2 { return 0 } return binary.BigEndian.Uint16(buf) }
c178238
var readN int readN, r.err = io.ReadFull(r.reader, buf) if readN < n { return "" } s := string(buf) return s }
c178239
r.ReadUint16() return r.ReadString(int(len)) }
c178240
b.registerThrift(ch) b.registerJSON(ch) }
c178241
level3 := &Downstream{ ServiceName: t.Param(server3NameParam), ServerRole: RoleS3, HostPort: fmt.Sprintf("%s:%s", b.serviceToHost(t.Param(server3NameParam)), b.ServerPort, ), Encoding: t.Param(server3EncodingParam), } level2.Downstream = level3 resp, err := b.startTrace(t, level1, sampled, baggage) if err != nil { t.Errorf("Failed to startTrace in S1(%s): %s", server1, err.Error()) return } log.Printf("Response: span=%+v, downstream=%+v", resp.Span, resp.Downstream) traceID := resp.Span.TraceID require := crossdock.Require(t) require.NotEmpty(traceID, "Trace ID should not be empty in S1(%s)", server1) if validateTrace(t, level1.Downstream, resp, server1, 1, traceID, sampled, baggage) { t.Successf("trace checks out") log.Println("PASS") } else { log.Println("FAIL") } }
c178242
then stop it so we can start it later. rt.timer = time.AfterFunc(time.Duration(math.MaxInt64), rt.OnTimer) if !rt.timer.Stop() { panic("relayTimer requires timers in stopped state, but failed to stop underlying timer") } return rt }
c178243
the timer, and instead ensure no methods are called after being released. return } tp.pool.Put(rt) }
c178244
rt.isOriginator = isOriginator if wasActive := rt.timer.Reset(d); wasActive { panic("relayTimer's underlying timer was Started multiple times without Stop") } }
c178245
be released") } rt.released = true rt.pool.Put(rt) }
c178246
&writerLogger{writer, fields} }
c178247
r.tcpRelay, err = newTCPRelay(dests, r.handleConnFrameRelay) if err != nil { return nil, err } return r, nil }
c178248
{ tallyTags["procedure"] = kt.procedure } if kt.retryCount != "" { tallyTags["retry-count"] = kt.retryCount } return tallyTags }
c178249
s.peers.SetStrategy(newLeastPendingCalculator()) s.Unlock() }
c178250
return c.topChannel.Peers() != c.peers }
c178251
SubChannel(%v) was changed to disallow method registration", c.ServiceName(), )) } handlers.register(h, methodName) }
c178252
:= make(map[string]Handler, len(handlers.handlers)) for k, v := range handlers.handlers { handlersMap[k] = v } handlers.RUnlock() return handlersMap }
c178253
:= c.topChannel.StatsTags() tags["subchannel"] = c.serviceName return tags }
c178254
nil { subChMap.subchannels = make(map[string]*SubChannel) } if sc, ok := subChMap.subchannels[serviceName]; ok { return sc, false } sc := newSubChannel(serviceName, ch) subChMap.subchannels[serviceName] = sc return sc, true }
c178255
{ subChMap.RLock() sc, ok := subChMap.subchannels[serviceName] subChMap.RUnlock() return sc, ok }
c178256
{ return sc, false } return subChMap.registerNewSubChannel(serviceName, ch) }
c178257
hostPorts []string for _, peer := range result.GetPeers() { hostPorts = append(hostPorts, servicePeerToHostPort(peer)) } return hostPorts, nil }
c178258
nil { return err } go func() { http.Serve(c.listener, c.mux) }() return nil }
c178259
mux creates problem in unit tests c.mux.Handle("/", crossdock.Handler(c.Behaviors, true)) listener, err := net.Listen("tcp", c.ClientHostPort) if err != nil { return err } c.listener = listener c.ClientHostPort = listener.Addr().String() // override in case it was ":0" return nil }
c178260
if err := arg2Writer.Close(); err != nil { return err } arg3Writer, err := call.Arg3Writer() if err != nil { return err } if req.Body != nil { if _, err = io.Copy(arg3Writer, req.Body); err != nil { return err } } return arg3Writer.Close() }
c178261
err != nil { return nil, err } readHeaders(rb, r.Header) if err := rb.Err(); err != nil { return nil, err } r.Body, err = call.Arg3Reader() return r, err }
c178262
make([]byte, size), remaining: nil} }
c178263
b := r.remaining[0] r.remaining = r.remaining[1:] return b, nil }
c178264
b := r.remaining[0:n] r.remaining = r.remaining[n:] return b }
c178265
creates a copy, which sucks return string(b) } return "" }
c178266
b != nil { return binary.BigEndian.Uint16(b) } return 0 }
c178267
b != nil { return binary.BigEndian.Uint32(b) } return 0 }
c178268
b != nil { return binary.BigEndian.Uint64(b) } return 0 }
c178269
_ := binary.ReadUvarint(r) return v }
c178270
r.ReadSingleByte() return r.ReadString(int(n)) }
c178271
r.ReadUint16() return r.ReadString(int(n)) }
c178272
n { return 0, ErrEOF } r.err = nil r.remaining = r.buffer[:n] return io.ReadFull(ior, r.remaining) }
c178273
b r.remaining = b r.err = nil }
c178274
return } w.remaining[0] = n w.remaining = w.remaining[1:] }
c178275
:= w.reserve(len(in)); b != nil { copy(b, in) } }
c178276
binary.BigEndian.PutUint16(b, n) } }
c178277
binary.BigEndian.PutUint32(b, n) } }
c178278
binary.BigEndian.PutUint64(b, n) } }
c178279
n) if b := w.reserve(varBytes); b != nil { copy(b, buf[0:varBytes]) } }
c178280
the string due to the cast if b := w.reserve(len(s)); b != nil { copy(b, s) } }
c178281
w.WriteSingleByte(byte(len(s))) w.WriteString(s) }
c178282
!= len(s) { w.setErr(errStringTooLong) } w.WriteUint16(uint16(len(s))) w.WriteString(s) }
c178283
// Always zero out references, since the caller expects the default to be 0. w.remaining[0] = 0 bufRef := ByteRef(w.remaining[0:]) w.remaining = w.remaining[1:] return bufRef }
c178284
return BytesRef(w.deferred(n)) }
c178285
:= w.buffer[0:w.BytesWritten()] return iow.Write(dirty) }
c178286
w.buffer w.err = nil }
c178287
= b w.remaining = b }
c178288
if ref != nil { binary.BigEndian.PutUint16(ref, n) } }
c178289
if ref != nil { binary.BigEndian.PutUint32(ref, n) } }
c178290
if ref != nil { binary.BigEndian.PutUint64(ref, n) } }
c178291
!= nil { copy(ref, b) } }
c178292
ref != nil { copy(ref, s) } }
c178293
{ if err := r.BeginArgument(last); err != nil { return nil, err } return r, nil }
c178294
f.flagsRef.Update(hasMoreFragmentsFlag) } else { f.checksum.Release() } }
c178295
return &writableChunk{ size: 0, sizeRef: contents.DeferUint16(), checksum: checksum, contents: contents, } }
c178296
= b[:c.contents.BytesRemaining()] } c.checksum.Add(b) c.contents.WriteBytes(b) written := len(b) c.size += uint16(written) return written }
c178297
return &fragmentingWriter{ logger: logger, sender: sender, checksum: checksum, state: fragmentingWriteStart, } }
c178298
{ if err := w.BeginArgument(last); err != nil { return nil, err } return w, nil }
c178299
happen due to an implementation error in the TChannel stack // itself if w.curFragment.contents.BytesRemaining() <= chunkHeaderSize { panic(fmt.Errorf("attempting to begin an argument in a fragment with only %d bytes available", w.curFragment.contents.BytesRemaining())) } w.curChunk = newWritableChunk(w.checksum, w.curFragment.contents) w.state = fragmentingWriteInArgument if last { w.state = fragmentingWriteInLastArgument } return nil }