// newPluginGrpcClient returns a configured gRPC Client.
344045
func newPluginGrpcClient(ctx context.Context, address string, timeout time.Duration, security GRPCSecurity, typ plugin.PluginType) (interface{}, error) {
	address, port, err := parseAddress(address)
	if err != nil {
		return nil, err
	}
	var p *grpcClient
	var creds credentials.TransportCredentials
	if creds, err = buildCredentials(security); err != nil {
		return nil, err
	}
	p, err = newGrpcClient(ctx, address, int(port), timeout, typ, creds)
	if err != nil {
		return nil, err
	}
	return p, nil
}
1321371
func newAvailablePlugin(resp plugin.Response, emitter gomit.Emitter, ep executablePlugin, security client.GRPCSecurity) (*availablePlugin, error) {
	if security.TLSEnabled && !resp.Meta.TLSEnabled {
		return nil, errors.New(ErrMsgInsecurePlugin + "; plugin_name: " + resp.Meta.Name)
	}
	if !security.TLSEnabled && resp.Meta.TLSEnabled {
		return nil, errors.New(ErrMsgInsecureClient + "; plugin_name: " + resp.Meta.Name)
	}
	if resp.Type != plugin.CollectorPluginType && resp.Type != plugin.ProcessorPluginType && resp.Type != plugin.PublisherPluginType && resp.Type != plugin.StreamCollectorPluginType {
		return nil, strategy.ErrBadType
	}
	ap := &availablePlugin{
		meta:        resp.Meta,
		name:        resp.Meta.Name,
		version:     resp.Meta.Version,
		pluginType:  resp.Type,
		emitter:     emitter,
		healthChan:  make(chan error, 1),
		lastHitTime: time.Now(),
		ePlugin:     ep,
		pprofPort:   resp.PprofAddress,
		isRemote:    false,
	}
	ap.key = fmt.Sprintf("%s"+core.Separator+"%s"+core.Separator+"%d", ap.pluginType.String(), ap.name, ap.version)

	// Create RPC Client
	switch resp.Type {
	case plugin.CollectorPluginType:
		switch resp.Meta.RPCType {
		case plugin.NativeRPC:
			log.WithFields(log.Fields{
				"_module":     "control-aplugin",
				"_block":      "newAvailablePlugin",
				"plugin_name": ap.name,
			}).Warning("This plugin is using a deprecated RPC protocol. Find more information here: https://github.com/intelsdi-x/snap/issues/1289 ")
			c, e := client.NewCollectorNativeClient(resp.ListenAddress, DefaultClientTimeout, resp.PublicKey, !resp.Meta.Unsecure)
			if e != nil {
				return nil, errors.New("error while creating client connection: " + e.Error())
			}
			ap.client = c
		case plugin.GRPC:
			c, e := client.NewCollectorGrpcClient(resp.ListenAddress, DefaultClientTimeout, security)
			if e != nil {
				return nil, errors.New("error while creating client connection: " + e.Error())
			}
			ap.client = c
		case plugin.STREAMGRPC:
			c, e := client.NewStreamCollectorGrpcClient(
				resp.ListenAddress,
				DefaultClientTimeout,
				security)
			if e != nil {
				return nil, errors.New("error while creating client connection: " + e.Error())
			}
			ap.client = c
		default:
			return nil, errors.New("Invalid RPCTYPE")
		}
	case plugin.PublisherPluginType:
		switch resp.Meta.RPCType {
		case plugin.NativeRPC:
			c, e := client.NewPublisherNativeClient(resp.ListenAddress, DefaultClientTimeout, resp.PublicKey, !resp.Meta.Unsecure)
			if e != nil {
				return nil, errors.New("error while creating client connection: " + e.Error())
			}
			ap.client = c
		case plugin.GRPC:
			c, e := client.NewPublisherGrpcClient(resp.ListenAddress, DefaultClientTimeout, security)
			if e != nil {
				return nil, errors.New("error while creating client connection: " + e.Error())
			}
			ap.client = c
		default:
			return nil, errors.New("Invalid RPCTYPE")
		}
	case plugin.ProcessorPluginType:
		switch resp.Meta.RPCType {
		case plugin.NativeRPC:
			c, e := client.NewProcessorNativeClient(resp.ListenAddress, DefaultClientTimeout, resp.PublicKey, !resp.Meta.Unsecure)
			if e != nil {
				return nil, errors.New("error while creating client connection: " + e.Error())
			}
			ap.client = c
		case plugin.GRPC:
			c, e := client.NewProcessorGrpcClient(resp.ListenAddress, DefaultClientTimeout, security)
			if e != nil {
				return nil, errors.New("error while creating client connection: " + e.Error())
			}
			ap.client = c
		default:
			return nil, errors.New("Invalid RPCTYPE")
		}
	case plugin.StreamCollectorPluginType:
		switch resp.Meta.RPCType {
		case plugin.STREAMGRPC:
			c, e := client.NewStreamCollectorGrpcClient(
				resp.ListenAddress,
				DefaultClientTimeout,
				security)
			if e != nil {
				return nil, errors.New("error while creating client connection: " + e.Error())
			}
			ap.client = c
		default:
			return nil, errors.New("Invalid RPCTYPE")
		}
	default:
		return nil, errors.New("Cannot create a client for a plugin of the type: " + resp.Type.String())
	}

	return ap, nil
}
612911
func (m *testRPC) NewRPCClient(contextID string, channel string, secret string) error {
	if mock := m.currentMocks(nil); mock != nil && mock.NewRPCClientMock != nil {
		return mock.NewRPCClientMock(contextID, channel, secret)
	}
	return nil
}
239089
func NewGRPCServer(cfg APIConfig) http.Handler {
	authServer := &GRPCServer{
		APIConfig: cfg,
		Entry: logrus.WithFields(logrus.Fields{
			trace.Component: teleport.Component(teleport.ComponentAuth, teleport.ComponentGRPC),
		}),
		httpHandler: NewAPIServer(&cfg),
		grpcHandler: grpc.NewServer(),
	}
	proto.RegisterAuthServiceServer(authServer.grpcHandler, authServer)
	return authServer
}
630651
func NewClient(conf Config) (*Client, error) {
	if conf.Timeout == time.Duration(0) {
		conf.Timeout = defaultTimeout
	}
	sop, err := conf.ToSecureOptions(newSelfSignedTLSCert)
	if err != nil {
		return nil, errors.WithStack(err)
	}
	cl, err := comm.NewGRPCClient(comm.ClientConfig{
		SecOpts: sop,
		Timeout: conf.Timeout,
	})
	if err != nil {
		return nil, err
	}
	return &Client{GRPCClient: cl, TLSCertHash: util.ComputeSHA256(sop.Certificate)}, nil
}
725161
func NewPlugin(opts ...Option) *Plugin {
	p := &Plugin{}

	p.PluginName = "grpcsync"
	p.GRPC = &grpc.DefaultPlugin

	for _, o := range opts {
		o(p)
	}

	return p
}
783900
func NewDebugClient(cr statscollector.Collector) (DebugClient, error) {
	d := &debugClient{
		collector:     cr,
		rpchdl:        rpcwrapper.NewRPCWrapper(),
		secret:        os.Getenv(constants.EnvStatsSecret),
		debugChannel:  os.Getenv(constants.EnvStatsChannel),
		debugInterval: defaultDebugIntervalMilliseconds * time.Millisecond,
		stop:          make(chan bool),
	}

	if d.debugChannel == "" {
		return nil, errors.New("no path to debug socket provided")
	}

	if d.secret == "" {
		return nil, errors.New("no secret provided for debug channel")
	}

	return d, nil
}
627850
func (m *MockRPCClient) NewRPCClient(contextID, channel, rpcSecret string) error {
	ret := m.ctrl.Call(m, "NewRPCClient", contextID, channel, rpcSecret)
	ret0, _ := ret[0].(error)
	return ret0
}
11062
func NewMockRPCClient(ctrl *gomock.Controller) *MockRPCClient {
	mock := &MockRPCClient{ctrl: ctrl}
	mock.recorder = &MockRPCClientMockRecorder{mock}
	return mock
}
278603
func NewHTTPClient(ctx context.Context, opt ...cloud.ClientOption) (*http.Client, string, error) {
	var o opts.DialOpt
	for _, opt := range opt {
		opt.Resolve(&o)
	}
	if o.GRPCClient != nil {
		return nil, "", errors.New("unsupported GRPC base transport specified")
	}
	// TODO(djd): Wrap all http.Clients with appropriate internal version to add
	// UserAgent header and prepend correct endpoint.
	if o.HTTPClient != nil {
		return o.HTTPClient, o.Endpoint, 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)
		}
	}
	return oauth2.NewClient(ctx, o.TokenSource), o.Endpoint, nil
}
301593
func NewGRPCServerFromListener(listener net.Listener, serverConfig ServerConfig) (*GRPCServer, error) {
	grpcServer := &GRPCServer{
		address:  listener.Addr().String(),
		listener: listener,
		lock:     &sync.Mutex{},
	}

	//set up our server options
	var serverOpts []grpc.ServerOption

	//check SecOpts
	var secureConfig SecureOptions
	if serverConfig.SecOpts != nil {
		secureConfig = *serverConfig.SecOpts
	}
	if secureConfig.UseTLS {
		//both key and cert are required
		if secureConfig.Key != nil && secureConfig.Certificate != nil {
			//load server public and private keys
			cert, err := tls.X509KeyPair(secureConfig.Certificate, secureConfig.Key)
			if err != nil {
				return nil, err
			}
			grpcServer.serverCertificate.Store(cert)

			//set up our TLS config
			if len(secureConfig.CipherSuites) == 0 {
				secureConfig.CipherSuites = DefaultTLSCipherSuites
			}
			getCert := func(_ *tls.ClientHelloInfo) (*tls.Certificate, error) {
				cert := grpcServer.serverCertificate.Load().(tls.Certificate)
				return &cert, nil
			}
			//base server certificate
			grpcServer.tlsConfig = &tls.Config{
				VerifyPeerCertificate:  secureConfig.VerifyCertificate,
				GetCertificate:         getCert,
				SessionTicketsDisabled: true,
				CipherSuites:           secureConfig.CipherSuites,
			}
			grpcServer.tlsConfig.ClientAuth = tls.RequestClientCert
			//check if client authentication is required
			if secureConfig.RequireClientCert {
				//require TLS client auth
				grpcServer.tlsConfig.ClientAuth = tls.RequireAndVerifyClientCert
				//if we have client root CAs, create a certPool
				if len(secureConfig.ClientRootCAs) > 0 {
					grpcServer.clientRootCAs = make(map[string]*x509.Certificate)
					grpcServer.tlsConfig.ClientCAs = x509.NewCertPool()
					for _, clientRootCA := range secureConfig.ClientRootCAs {
						err = grpcServer.appendClientRootCA(clientRootCA)
						if err != nil {
							return nil, err
						}
					}
				}
			}

			// create credentials and add to server options
			creds := NewServerTransportCredentials(grpcServer.tlsConfig, serverConfig.Logger)
			serverOpts = append(serverOpts, grpc.Creds(creds))
		} else {
			return nil, errors.New("serverConfig.SecOpts must contain both Key and Certificate when UseTLS is true")
		}
	}
	// set max send and recv msg sizes
	serverOpts = append(serverOpts, grpc.MaxSendMsgSize(MaxSendMsgSize))
	serverOpts = append(serverOpts, grpc.MaxRecvMsgSize(MaxRecvMsgSize))
	// set the keepalive options
	serverOpts = append(serverOpts, ServerKeepaliveOptions(serverConfig.KaOpts)...)
	// set connection timeout
	if serverConfig.ConnectionTimeout <= 0 {
		serverConfig.ConnectionTimeout = DefaultConnectionTimeout
	}
	serverOpts = append(
		serverOpts,
		grpc.ConnectionTimeout(serverConfig.ConnectionTimeout))
	// set the interceptors
	if len(serverConfig.StreamInterceptors) > 0 {
		serverOpts = append(
			serverOpts,
			grpc.StreamInterceptor(grpc_middleware.ChainStreamServer(serverConfig.StreamInterceptors...)),
		)
	}
	if len(serverConfig.UnaryInterceptors) > 0 {
		serverOpts = append(
			serverOpts,
			grpc.UnaryInterceptor(grpc_middleware.ChainUnaryServer(serverConfig.UnaryInterceptors...)),
		)
	}

	if serverConfig.MetricsProvider != nil {
		sh := NewServerStatsHandler(serverConfig.MetricsProvider)
		serverOpts = append(serverOpts, grpc.StatsHandler(sh))
	}

	grpcServer.server = grpc.NewServer(serverOpts...)

	return grpcServer, nil
}
844058
func NewGRPCConnection(hostname string, port string, tlsConfig *tls.Config) (*grpc.ClientConn, error) {
	var opts []grpc.DialOption
	netAddr := net.JoinHostPort(hostname, port)
	creds := credentials.NewTLS(tlsConfig)
	opts = append(opts, grpc.WithTransportCredentials(creds))
	return grpc.Dial(netAddr, opts...)
}
123623
func NewClient() (*Client, error) {
	osdbServer := os.Getenv("OSDB_SERVER")
	if osdbServer == "" {
		osdbServer = DefaultOSDBServer
	}
	rpc, err := xmlrpc.NewClient(osdbServer, nil)
	if err != nil {
		return nil, err
	}

	c := &Client{
		UserAgent: DefaultUserAgent,
		Client:    rpc, // xmlrpc.Client
	}

	return c, nil
}
791883
func NewClient(addr string, opt *ClientOpt) (*grpc.ClientConn, error) {

	if opt == nil {
		return nil, fmt.Errorf("Empty ClientOpt")
	}

	// Load key pair
	certificate, err := tls.LoadX509KeyPair(opt.Crt, opt.Key)
	if err != nil {
		return nil, err
	}

	tlsConf := &tls.Config{
		ServerName:         opt.ServerName,
		Certificates:       []tls.Certificate{certificate},
		InsecureSkipVerify: opt.InsecureSkipVerify,
	}

	// Mutual handshake with private ca
	if opt.CaCrt != "" {
		certPool := x509.NewCertPool()
		bs, err := ioutil.ReadFile(opt.CaCrt)
		if err != nil {
			return nil, err
		}
		ok := certPool.AppendCertsFromPEM(bs)
		if !ok {
			return nil, fmt.Errorf("failed to append certs")
		}
		tlsConf.InsecureSkipVerify = false
		tlsConf.RootCAs = certPool
	}

	dailOpts := []grpc.DialOption{
		grpc.WithTransportCredentials(credentials.NewTLS(tlsConf)),
	}

	if opt.WithBlock {
		dailOpts = append(dailOpts, grpc.WithBlock(), grpc.WithTimeout(5*time.Second))
	}

	// Dail and return connection
	conn, err := grpc.Dial(addr, dailOpts...)
	if err != nil {
		return nil, err
	}

	return conn, nil

}
1052652
func NewPubControlClient(uri string) *PubControlClient {
    // This is basically the same as the default in Go 1.6, but with these changes:
    // Timeout: 30s -> 10s
    // TLSHandshakeTimeout: 10s -> 7s
    // MaxIdleConnsPerHost: 2 -> 100
    transport := &http.Transport{
        Proxy: http.ProxyFromEnvironment,
        Dial: (&net.Dialer{
            Timeout:   10 * time.Second,
            KeepAlive: 30 * time.Second,
        }).Dial,
        TLSHandshakeTimeout:   7 * time.Second,
        ExpectContinueTimeout: 1 * time.Second,
        MaxIdleConnsPerHost: 100,
    }

    newPcc := new(PubControlClient)
    newPcc.uri = uri
    newPcc.lock = &sync.Mutex{}
    newPcc.pubCall = pubCall
    newPcc.publish = publish
    newPcc.makeHttpRequest = makeHttpRequest
    newPcc.httpClient = &http.Client{Transport: transport, Timeout: 15 * time.Second}
    return newPcc
}
602842
func NewHyperClient(server string) (*HyperClient, error) {
	conn, err := grpc.Dial(server, grpc.WithInsecure(), grpc.WithTimeout(5*time.Second))
	if err != nil {
		return nil, err
	}

	return &HyperClient{
		client: types.NewPublicAPIClient(conn),
		ctx:    context.Background(),
	}, nil
}
109907
func newReconnectRPCClient(serverAddr, serviceEndpoint string) *ReconnectRPCClient {
	return &ReconnectRPCClient{
		serverAddr:      serverAddr,
		serviceEndpoint: serviceEndpoint,
	}
}