// forwardGRPC forwards all input metrics to a downstream Veneur, over gRPC.
182740
func (s *Server) forwardGRPC(ctx context.Context, wms []WorkerMetrics) {
	span, _ := trace.StartSpanFromContext(ctx, "")
	span.SetTag("protocol", "grpc")
	defer span.ClientFinish(s.TraceClient)

	exportStart := time.Now()

	// Collect all of the forwardable metrics from the various WorkerMetrics.
	var metrics []*metricpb.Metric
	for _, wm := range wms {
		metrics = append(metrics, wm.ForwardableMetrics(s.TraceClient)...)
	}

	span.Add(
		ssf.Timing("forward.duration_ns", time.Since(exportStart),
			time.Nanosecond, map[string]string{"part": "export"}),
		ssf.Gauge("forward.metrics_total", float32(len(metrics)), nil),
		// Maintain compatibility with metrics used in HTTP-based forwarding
		ssf.Count("forward.post_metrics_total", float32(len(metrics)), nil),
	)

	if len(metrics) == 0 {
		log.Debug("Nothing to forward, skipping.")
		return
	}

	entry := log.WithFields(logrus.Fields{
		"metrics":     len(metrics),
		"destination": s.ForwardAddr,
		"protocol":    "grpc",
		"grpcstate":   s.grpcForwardConn.GetState().String(),
	})

	c := forwardrpc.NewForwardClient(s.grpcForwardConn)

	grpcStart := time.Now()
	_, err := c.SendMetrics(ctx, &forwardrpc.MetricList{Metrics: metrics})
	if err != nil {
		if ctx.Err() != nil {
			// We exceeded the deadline of the flush context.
			span.Add(ssf.Count("forward.error_total", 1, map[string]string{"cause": "deadline_exceeded"}))
		} else if statErr, ok := status.FromError(err); ok &&
			(statErr.Message() == "all SubConns are in TransientFailure" || statErr.Message() == "transport is closing") {
			// We could check statErr.Code() == codes.Unavailable, but we don't know all of the cases that
			// could return that code. These two particular cases are fairly safe and usually associated
			// with connection rebalancing or host replacement, so we don't want them going to sentry.
			span.Add(ssf.Count("forward.error_total", 1, map[string]string{"cause": "transient_unavailable"}))
		} else {
			span.Add(ssf.Count("forward.error_total", 1, map[string]string{"cause": "send"}))
			entry.WithError(err).Error("Failed to forward to an upstream Veneur")
		}
	} else {
		entry.Info("Completed forward to an upstream Veneur")
	}

	span.Add(
		ssf.Timing("forward.duration_ns", time.Since(grpcStart), time.Nanosecond,
			map[string]string{"part": "grpc"}),
		ssf.Count("forward.error_total", 0, nil),
	)
}
1318771
func ServeGRPC() error {
	var err error
	service.ServiceListener, err = net.Listen("tcp", service.Config.Address())
	if err != nil {
		return err
	}

	logrus.Infof("Serving gRPC on %s", service.Config.Address())
	return createGrpcServer().Serve(service.ServiceListener)
}
880731
func (f *FileSystem) forwardRegionStreamingRpc(conn io.ReadWriteCloser,
	encoder *codec.Encoder, args interface{}, method, allocID string, qo *structs.QueryOptions) {
	// Request the allocation from the target region
	allocReq := &structs.AllocSpecificRequest{
		AllocID:      allocID,
		QueryOptions: *qo,
	}
	var allocResp structs.SingleAllocResponse
	if err := f.srv.forwardRegion(qo.RequestRegion(), "Alloc.GetAlloc", allocReq, &allocResp); err != nil {
		f.handleStreamResultError(err, nil, encoder)
		return
	}

	if allocResp.Alloc == nil {
		f.handleStreamResultError(structs.NewErrUnknownAllocation(allocID), helper.Int64ToPtr(404), encoder)
		return
	}

	// Determine the Server that has a connection to the node.
	srv, err := f.srv.serverWithNodeConn(allocResp.Alloc.NodeID, qo.RequestRegion())
	if err != nil {
		var code *int64
		if structs.IsErrNoNodeConn(err) {
			code = helper.Int64ToPtr(404)
		}
		f.handleStreamResultError(err, code, encoder)
		return
	}

	// Get a connection to the server
	srvConn, err := f.srv.streamingRpc(srv, method)
	if err != nil {
		f.handleStreamResultError(err, nil, encoder)
		return
	}
	defer srvConn.Close()

	// Send the request.
	outEncoder := codec.NewEncoder(srvConn, structs.MsgpackHandle)
	if err := outEncoder.Encode(args); err != nil {
		f.handleStreamResultError(err, nil, encoder)
		return
	}

	structs.Bridge(conn, srvConn)
}
919666
func (bot *TgBot) ForwardFn(f func(TgBot, Message, User, int)) *TgBot {
	bot.addToConditionalFuncs(ForwardConditionalCall{f})
	return bot
}
457791
func NewGRPCServer(address string, serverConfig ServerConfig) (*GRPCServer, error) {
	if address == "" {
		return nil, errors.New("Missing address parameter")
	}
	//create our listener
	lis, err := net.Listen("tcp", address)

	if err != nil {
		return nil, err
	}
	return NewGRPCServerFromListener(lis, serverConfig)
}
467791
func (p2p *P2P) ForwardRemote(ctx context.Context, proto protocol.ID, addr ma.Multiaddr, reportRemote bool) (Listener, error) {
	listener := &remoteListener{
		p2p: p2p,

		proto: proto,
		addr:  addr,

		reportRemote: reportRemote,
	}

	if err := p2p.ListenersP2P.Register(listener); err != nil {
		return nil, err
	}

	return listener, nil
}
635769
func (cs *ConnStats) AvgRPCBytes() (send float64, recv float64) {
	return float64(cs.BytesWritten) / float64(cs.RPCCalls), float64(cs.BytesRead) / float64(cs.RPCCalls)
}
717336
func (pf *PortForwarder) ForwardPorts() error {
	defer pf.Close()

	var err error
	pf.streamConn, _, err = pf.dialer.Dial(PortForwardProtocolV1Name)
	if err != nil {
		return fmt.Errorf("error upgrading connection: %s", err)
	}
	defer pf.streamConn.Close()

	return pf.forward()
}
1369076
func (r *rpcHandler) forwardLeader(server *serverParts, method string, args interface{}, reply interface{}) error {
	// Handle a missing server
	if server == nil {
		return structs.ErrNoLeader
	}
	return r.connPool.RPC(r.config.Region, server.Addr, server.MajorVersion, method, args, reply)
}
1185188
func (la *Lattice) Forward(m TokenizeMode) {
	for i, size := 1, len(la.list); i < size; i++ {
		currentList := la.list[i]
		for index, target := range currentList {
			prevList := la.list[target.Start]
			if len(prevList) == 0 {
				la.list[i][index].Cost = maximumCost
				continue
			}
			for j, n := range prevList {
				var c int16
				if n.Class != USER && target.Class != USER {
					c = la.dic.Connection.At(int(n.Right), int(target.Left))
				}
				totalCost := int64(c) + int64(target.Weight) + int64(n.Cost)
				if m != Normal {
					totalCost += int64(additionalCost(n))
				}
				if totalCost > maximumCost {
					totalCost = maximumCost
				}
				if j == 0 || int32(totalCost) < la.list[i][index].Cost {
					la.list[i][index].Cost = int32(totalCost)
					la.list[i][index].Prev = la.list[target.Start][j]
				}
			}
		}
	}
	return
}
101142
func MakeGRPCServer(ctx context.Context, endpoints Endpoints, tracer stdopentracing.Tracer, logger log.Logger) pb.SessionManagementServer {
	opts := []grpctransport.ServerOption{
		grpctransport.ServerErrorLogger(logger),
	}
	return &grpcServer{
		createSession: grpctransport.NewServer(
			ctx,
			endpoints.CreateSessionEndpoint,
			DecodeGRPCCreateSessionRequest,
			EncodeGRPCCreateSessionResponse,
			append(
				opts,
				grpctransport.ServerBefore(kitty.FromGRPCRequest(tracer, "Create session", logger)),
				grpctransport.ServerAfter(kitty.GRPCFinish()),
			)...,
		),
		findSessionByToken: grpctransport.NewServer(
			ctx,
			endpoints.FindSessionByTokenEndpoint,
			DecodeGRPCFindSessionByTokenRequest,
			EncodeGRPCFindSessionByTokenResponse,
			append(
				opts,
				grpctransport.ServerBefore(kitty.FromGRPCRequest(tracer, "Find session by token", logger)),
				grpctransport.ServerAfter(kitty.GRPCFinish()),
			)...,
		),
		deleteSessionByToken: grpctransport.NewServer(
			ctx,
			endpoints.DeleteSessionByTokenEndpoint,
			DecodeGRPCDeleteSessionByTokenRequest,
			EncodeGRPCDeleteSessionByTokenResponse,
			append(
				opts,
				grpctransport.ServerBefore(kitty.FromGRPCRequest(tracer, "Delete session by token", logger)),
				grpctransport.ServerAfter(kitty.GRPCFinish()),
			)...,
		),
		deleteSessionsByOwnerToken: grpctransport.NewServer(
			ctx,
			endpoints.DeleteSessionsByOwnerTokenEndpoint,
			DecodeGRPCDeleteSessionsByOwnerTokenRequest,
			EncodeGRPCDeleteSessionsByOwnerTokenResponse,
			append(
				opts,
				grpctransport.ServerBefore(kitty.FromGRPCRequest(tracer, "Delete sessions by owner token", logger)),
				grpctransport.ServerAfter(kitty.GRPCFinish()),
			)...,
		),
	}
}
1120894
func SwarmFromGRPC(c swarmapi.Cluster) types.Swarm {
	swarm := types.Swarm{
		ClusterInfo: types.ClusterInfo{
			ID: c.ID,
			Spec: types.Spec{
				Orchestration: types.OrchestrationConfig{
					TaskHistoryRetentionLimit: &c.Spec.Orchestration.TaskHistoryRetentionLimit,
				},
				Raft: types.RaftConfig{
					SnapshotInterval:           c.Spec.Raft.SnapshotInterval,
					KeepOldSnapshots:           &c.Spec.Raft.KeepOldSnapshots,
					LogEntriesForSlowFollowers: c.Spec.Raft.LogEntriesForSlowFollowers,
					HeartbeatTick:              int(c.Spec.Raft.HeartbeatTick),
					ElectionTick:               int(c.Spec.Raft.ElectionTick),
				},
				EncryptionConfig: types.EncryptionConfig{
					AutoLockManagers: c.Spec.EncryptionConfig.AutoLockManagers,
				},
				CAConfig: types.CAConfig{
					// do not include the signing CA cert or key (it should already be redacted via the swarm APIs) -
					// the key because it's secret, and the cert because otherwise doing a get + update on the spec
					// can cause issues because the key would be missing and the cert wouldn't
					ForceRotate: c.Spec.CAConfig.ForceRotate,
				},
			},
			TLSInfo: types.TLSInfo{
				TrustRoot: string(c.RootCA.CACert),
			},
			RootRotationInProgress: c.RootCA.RootRotation != nil,
			DefaultAddrPool:        c.DefaultAddressPool,
			SubnetSize:             c.SubnetSize,
			DataPathPort:           c.VXLANUDPPort,
		},
		JoinTokens: types.JoinTokens{
			Worker:  c.RootCA.JoinTokens.Worker,
			Manager: c.RootCA.JoinTokens.Manager,
		},
	}

	issuerInfo, err := ca.IssuerFromAPIRootCA(&c.RootCA)
	if err == nil && issuerInfo != nil {
		swarm.TLSInfo.CertIssuerSubject = issuerInfo.Subject
		swarm.TLSInfo.CertIssuerPublicKey = issuerInfo.PublicKey
	}

	heartbeatPeriod, _ := gogotypes.DurationFromProto(c.Spec.Dispatcher.HeartbeatPeriod)
	swarm.Spec.Dispatcher.HeartbeatPeriod = heartbeatPeriod

	swarm.Spec.CAConfig.NodeCertExpiry, _ = gogotypes.DurationFromProto(c.Spec.CAConfig.NodeCertExpiry)

	for _, ca := range c.Spec.CAConfig.ExternalCAs {
		swarm.Spec.CAConfig.ExternalCAs = append(swarm.Spec.CAConfig.ExternalCAs, &types.ExternalCA{
			Protocol: types.ExternalCAProtocol(strings.ToLower(ca.Protocol.String())),
			URL:      ca.URL,
			Options:  ca.Options,
			CACert:   string(ca.CACert),
		})
	}

	// Meta
	swarm.Version.Index = c.Meta.Version.Index
	swarm.CreatedAt, _ = gogotypes.TimestampFromProto(c.Meta.CreatedAt)
	swarm.UpdatedAt, _ = gogotypes.TimestampFromProto(c.Meta.UpdatedAt)

	// Annotations
	swarm.Spec.Annotations = annotationsFromGRPC(c.Spec.Annotations)

	return swarm
}
932461
func (pm *PortMapper) AppendForwardingTableEntry(proto string, sourceIP net.IP, sourcePort int, containerIP string, containerPort int) error {
	return pm.forward(iptables.Append, proto, sourceIP, sourcePort, containerIP, containerPort)
}
730777
func (b *Backend) RegisterGRPC(s *grpc.Server) {
	if b.buildkit != nil {
		b.buildkit.RegisterGRPC(s)
	}
}
958643
func DialGRPC(ctx context.Context, opt ...cloud.ClientOption) (*grpc.ClientConn, error) {
	var o opts.DialOpt
	for _, opt := range opt {
		opt.Resolve(&o)
	}
	if o.HTTPClient != nil {
		return nil, errors.New("unsupported HTTP base transport specified")
	}
	if o.GRPCClient != nil {
		return o.GRPCClient, nil
	}
	if o.TokenSource == nil {
		var err error
		o.TokenSource, err = google.DefaultTokenSource(ctx, o.Scopes...)
		if err != nil {
			return nil, fmt.Errorf("google.DefaultTokenSource: %v", err)
		}
	}
	grpcOpts := []grpc.DialOption{
		grpc.WithPerRPCCredentials(oauth.TokenSource{o.TokenSource}),
		grpc.WithTransportCredentials(credentials.NewClientTLSFromCert(nil, "")),
	}
	if o.UserAgent != "" {
		grpcOpts = append(grpcOpts, grpc.WithUserAgent(o.UserAgent))
	}
	return grpc.Dial(o.Endpoint, grpcOpts...)
}
1162966
func GRPCServerTrace(options ...TracerOption) kitgrpc.ServerOption {
	cfg := TracerOptions{}

	for _, option := range options {
		option(&cfg)
	}

	serverBefore := kitgrpc.ServerBefore(
		func(ctx context.Context, md metadata.MD) context.Context {
			var name string

			if cfg.Name != "" {
				name = cfg.Name
			} else {
				name, _ = ctx.Value(kitgrpc.ContextKeyRequestMethod).(string)
				if name == "" {
					// we can't find the gRPC method. probably the
					// unaryInterceptor was not wired up.
					name = "unknown grpc method"
				}
			}

			var (
				parentContext trace.SpanContext
				traceContext  = md[propagationKey]
				ok            bool
			)

			if len(traceContext) > 0 {
				traceContextBinary := []byte(traceContext[0])
				parentContext, ok = propagation.FromBinary(traceContextBinary)
				if ok && !cfg.Public {
					ctx, _ = trace.StartSpanWithRemoteParent(
						ctx,
						name,
						parentContext,
						trace.WithSpanKind(trace.SpanKindServer),
						trace.WithSampler(cfg.Sampler),
					)
					return ctx
				}
			}
			ctx, span := trace.StartSpan(
				ctx,
				name,
				trace.WithSpanKind(trace.SpanKindServer),
				trace.WithSampler(cfg.Sampler),
			)
			if ok {
				span.AddLink(
					trace.Link{
						TraceID: parentContext.TraceID,
						SpanID:  parentContext.SpanID,
						Type:    trace.LinkTypeChild,
					},
				)
			}
			return ctx
		},
	)

	serverFinalizer := kitgrpc.ServerFinalizer(
		func(ctx context.Context, err error) {
			if span := trace.FromContext(ctx); span != nil {
				if s, ok := status.FromError(err); ok {
					span.SetStatus(trace.Status{Code: int32(s.Code()), Message: s.Message()})
				} else {
					span.SetStatus(trace.Status{Code: int32(codes.Internal), Message: err.Error()})
				}
				span.End()
			}
		},
	)

	return func(s *kitgrpc.Server) {
		serverBefore(s)
		serverFinalizer(s)
	}
}
626768
func (c *Core) ForwardRequest(req *http.Request) (int, http.Header, []byte, error) {
	c.requestForwardingConnectionLock.RLock()
	defer c.requestForwardingConnectionLock.RUnlock()

	if c.rpcForwardingClient == nil {
		return 0, nil, nil, ErrCannotForward
	}

	origPath := req.URL.Path
	defer func() {
		req.URL.Path = origPath
	}()

	req.URL.Path = req.Context().Value("original_request_path").(string)

	freq, err := forwarding.GenerateForwardedRequest(req)
	if err != nil {
		c.logger.Error("error creating forwarding RPC request", "error", err)
		return 0, nil, nil, fmt.Errorf("error creating forwarding RPC request")
	}
	if freq == nil {
		c.logger.Error("got nil forwarding RPC request")
		return 0, nil, nil, fmt.Errorf("got nil forwarding RPC request")
	}
	resp, err := c.rpcForwardingClient.ForwardRequest(c.rpcClientConnContext, freq)
	if err != nil {
		c.logger.Error("error during forwarded RPC request", "error", err)
		return 0, nil, nil, fmt.Errorf("error during forwarding RPC request")
	}

	var header http.Header
	if resp.HeaderEntries != nil {
		header = make(http.Header)
		for k, v := range resp.HeaderEntries {
			header[k] = v.Values
		}
	}

	// If we are a perf standby and the request was forwarded to the active node
	// we should attempt to wait for the WAL to ship to offer best effort read after
	// write guarantees
	if c.perfStandby && resp.LastRemoteWal > 0 {
		WaitUntilWALShipped(req.Context(), c, resp.LastRemoteWal)
	}

	return int(resp.StatusCode), header, resp.Body, nil
}