// startNATSServer starts the embedded NATS server, possibly updating
// the NATS Server's clustering and/or TLS options.
327182
func (s *StanServer) startNATSServer() error {
	if err := s.configureClusterOpts(); err != nil {
		return err
	}
	if err := s.configureNATSServerTLS(); err != nil {
		return err
	}
	opts := s.natsOpts
	s.natsServer = server.New(opts)
	if s.natsServer == nil {
		return fmt.Errorf("no NATS Server object returned")
	}
	if stanLogger := s.log.GetLogger(); stanLogger != nil {
		s.natsServer.SetLogger(stanLogger, opts.Debug, opts.Trace)
	}
	// Run server in Go routine.
	go s.natsServer.Start()
	// Wait for accept loop(s) to be started
	if !s.natsServer.ReadyForConnections(10 * time.Second) {
		return fmt.Errorf("unable to start a NATS Server on %s:%d", opts.Host, opts.Port)
	}
	return nil
}
917532
func (s *SubServer) Start(listenAddr string) error {
	s.listenAddr = listenAddr

	mux := http.NewServeMux()
	mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		// Example notify response
		/*
			Method:NOTIFY URL:/ Proto:HTTP/1.1 ProtoMajor:1 ProtoMinor:1 Header:map[Nt:[upnp:event] Nts:[upnp:propchange] Sid:[uuid:054ce1c6-1dd2-11b2-864f-d1dbdfd9a2e2] Seq:[6] Content-Type:[text/xml; charset="utf-8"] Content-Length:[296]] Body:0xc4200dc300 ContentLength:296 TransferEncoding:[] Close:false Host:192.168.0.9:9000 Form:map[] PostForm:map[] MultipartForm:<nil> Trailer:map[] RemoteAddr:192.168.0.34:3663 RequestURI:/ TLS:<nil> Cancel:<nil> Response:<nil> ctx:0xc4200dc340}
		*/

		defer func() {
			w.WriteHeader(http.StatusOK)
		}()

		if r.Method != "NOTIFY" {
			return
		}

		sid, ok := r.Header["Sid"]
		if !ok {
			return
		}
		if len(sid) == 0 {
			return
		}
		sub, ok := s.subs[sid[0]]
		if !ok {
			return
		}

		// Just return a string, caller responsible for disassembling it
		body, err := ioutil.ReadAll(r.Body)
		if err != nil {
			return
		}
		sub.Subscriber.UPNPNotify(NotifyEvent{SID: sid[0], Body: string(body)})
	})

	return http.ListenAndServe(listenAddr, mux)
}
1168913
func (s *serverManager) Start(username string, password string, host string, port int) (Server, error) {
	startedCh := make(chan error)
	server := &server{
		logger: s.logger,
		logTag: "registryServer",
	}
	go func() {
		err := server.start(username, password, host, port, startedCh)
		if err != nil {
			s.logger.Debug(s.logTag, "Registry error occurred: %s", err.Error())
		}
	}()

	// block until started
	err := <-startedCh
	if err != nil {
		if stopErr := server.Stop(); stopErr != nil {
			s.logger.Warn(s.logTag, "Failed to stop server: %s", stopErr.Error())
		}
	}
	return server, err
}
1073323
func (c *ClusterManager) Start(
	clusterMaxSize int,
	nodeInitialized bool,
	gossipPort string,
	selfClusterDomain string,
) error {
	return c.StartWithConfiguration(
		clusterMaxSize,
		nodeInitialized,
		gossipPort,
		[]string{ClusterDBKey},
		selfClusterDomain,
		&cluster.ClusterServerConfiguration{})
}
24101
func (m *testRPC) StartServer(ctx context.Context, protocol string, path string, handler interface{}) error {
	if mock := m.currentMocks(nil); mock != nil && mock.StartServerMock != nil {
		return mock.StartServerMock(ctx, protocol, path, handler)
	}
	return nil
}
536647
func (s *Service) Start(server *p2p.Server) error {
	s.server = server
	go s.loop()

	log.Info("Stats daemon started")
	return nil
}
96179
func (s *GrpcServer) StartWithServer(server func() *grpc.Server) error {
	s.lock.Lock()
	defer s.lock.Unlock()

	if server == nil {
		return fmt.Errorf("Server function has not been defined")
	}

	if s.running {
		return fmt.Errorf("Server already running")
	}

	s.server = server()

	// Start listening for requests
	s.startGrpcService()
	return nil
}
639504
func StartServer(info ServerInfo, opts ...grpc.ServerOption) func() {
	opts = append(opts, grpc.WriteBufferSize(128*1024))
	opts = append(opts, grpc.ReadBufferSize(128*1024))
	s := grpc.NewServer(opts...)
	switch info.Type {
	case "protobuf":
		testpb.RegisterBenchmarkServiceServer(s, &testServer{})
	case "bytebuf":
		respSize, ok := info.Metadata.(int32)
		if !ok {
			grpclog.Fatalf("failed to StartServer, invalid metadata: %v, for Type: %v", info.Metadata, info.Type)
		}
		testpb.RegisterBenchmarkServiceServer(s, &byteBufServer{respSize: respSize})
	default:
		grpclog.Fatalf("failed to StartServer, unknown Type: %v", info.Type)
	}
	go s.Serve(info.Listener)
	return func() {
		s.Stop()
	}
}
435027
func (n *natsConsumer) Start(acc telegraf.Accumulator) error {
	n.acc = acc.WithTracking(n.MaxUndeliveredMessages)

	var connectErr error

	// set default NATS connection options
	opts := nats.DefaultOptions

	// override max reconnection tries
	opts.MaxReconnect = -1

	// override servers if any were specified
	opts.Servers = n.Servers

	opts.Secure = n.Secure

	if n.conn == nil || n.conn.IsClosed() {
		n.conn, connectErr = opts.Connect()
		if connectErr != nil {
			return connectErr
		}

		// Setup message and error channels
		n.errs = make(chan error)
		n.conn.SetErrorHandler(n.natsErrHandler)

		n.in = make(chan *nats.Msg, 1000)
		for _, subj := range n.Subjects {
			sub, err := n.conn.QueueSubscribe(subj, n.QueueGroup, func(m *nats.Msg) {
				n.in <- m
			})
			if err != nil {
				return err
			}
			// ensure that the subscription has been processed by the server
			if err = n.conn.Flush(); err != nil {
				return err
			}
			// set the subscription pending limits
			if err = sub.SetPendingLimits(n.PendingMessageLimit, n.PendingBytesLimit); err != nil {
				return err
			}
			n.subs = append(n.subs, sub)
		}
	}

	ctx, cancel := context.WithCancel(context.Background())
	n.cancel = cancel

	// Start the message reader
	n.wg.Add(1)
	go func() {
		defer n.wg.Done()
		go n.receiver(ctx)
	}()

	log.Printf("I! Started the NATS consumer service, nats: %v, subjects: %v, queue: %v\n",
		n.conn.ConnectedUrl(), n.Subjects, n.QueueGroup)

	return nil
}
451221
func StartServer(handler http.Handler) *Server {
	ch := make(chan *ReceivedRequest)
	closeSig := make(chan struct{})
	wrapper := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		u := uuid.New()
		w.Header().Add(UUIDHeaderName, u)
		handler.ServeHTTP(w, r)
		flusher := w.(http.Flusher) // TODO: what if you can't convert to a Flusher?
		flusher.Flush()
		req := &ReceivedRequest{Request: r, Time: time.Now(), UUID: u}
		select {
		case <-closeSig:
		case ch <- req:
		}
	})

	s := httptest.NewServer(wrapper)
	return &Server{
		lck:      &sync.Mutex{},
		closed:   0,
		closeSig: closeSig,
		ch:       ch,
		srv:      s,
	}
}
478628
func (s *sdkGrpcServer) Start() error {

	// Setup https if certs have been provided
	opts := make([]grpc.ServerOption, 0)
	if s.config.Net != "unix" && s.config.Security.Tls != nil {
		creds, err := credentials.NewServerTLSFromFile(
			s.config.Security.Tls.CertFile,
			s.config.Security.Tls.KeyFile)
		if err != nil {
			return fmt.Errorf("Failed to create credentials from cert files: %v", err)
		}
		opts = append(opts, grpc.Creds(creds))
		s.log.Info("SDK TLS enabled")
	} else {
		s.log.Info("SDK TLS disabled")
	}

	// Setup authentication and authorization using interceptors if auth is enabled
	if len(s.config.Security.Authenticators) != 0 {
		opts = append(opts, grpc.UnaryInterceptor(
			grpc_middleware.ChainUnaryServer(
				s.rwlockIntercepter,
				grpc_auth.UnaryServerInterceptor(s.auth),
				s.authorizationServerInterceptor,
				s.loggerServerInterceptor,
			)))
	} else {
		opts = append(opts, grpc.UnaryInterceptor(
			grpc_middleware.ChainUnaryServer(
				s.rwlockIntercepter,
				s.loggerServerInterceptor,
			)))
	}

	// Start the gRPC Server
	err := s.GrpcServer.StartWithServer(func() *grpc.Server {
		grpcServer := grpc.NewServer(opts...)

		api.RegisterOpenStorageClusterServer(grpcServer, s.clusterServer)
		api.RegisterOpenStorageNodeServer(grpcServer, s.nodeServer)
		api.RegisterOpenStorageObjectstoreServer(grpcServer, s.objectstoreServer)
		api.RegisterOpenStorageSchedulePolicyServer(grpcServer, s.schedulePolicyServer)
		api.RegisterOpenStorageIdentityServer(grpcServer, s.identityServer)
		api.RegisterOpenStorageVolumeServer(grpcServer, s.volumeServer)
		api.RegisterOpenStorageMigrateServer(grpcServer, s.volumeServer)
		api.RegisterOpenStorageCredentialsServer(grpcServer, s.credentialServer)
		api.RegisterOpenStorageCloudBackupServer(grpcServer, s.cloudBackupServer)
		api.RegisterOpenStorageMountAttachServer(grpcServer, s.volumeServer)
		api.RegisterOpenStorageAlertsServer(grpcServer, s.alertsServer)
		api.RegisterOpenStorageClusterPairServer(grpcServer, s.clusterPairServer)
		api.RegisterOpenStoragePolicyServer(grpcServer, s.policyServer)
		api.RegisterOpenStorageClusterDomainsServer(grpcServer, s.clusterDomainsServer)

		if s.config.Security.Role != nil {
			api.RegisterOpenStorageRoleServer(grpcServer, s.roleServer)
		}

		s.RegisterServerExtensions(grpcServer)

		return grpcServer
	})
	if err != nil {
		return err
	}

	return nil
}
181474
func NewNATSTarget(id string, args NATSArgs) (*NATSTarget, error) {
	var natsConn *nats.Conn
	var stanConn stan.Conn
	var clientID string
	var err error

	if args.Streaming.Enable {
		scheme := "nats"
		if args.Secure {
			scheme = "tls"
		}
		addressURL := scheme + "://" + args.Username + ":" + args.Password + "@" + args.Address.String()

		clientID, err = getNewUUID()
		if err != nil {
			return nil, err
		}

		connOpts := []stan.Option{stan.NatsURL(addressURL)}
		if args.Streaming.MaxPubAcksInflight > 0 {
			connOpts = append(connOpts, stan.MaxPubAcksInflight(args.Streaming.MaxPubAcksInflight))
		}

		stanConn, err = stan.Connect(args.Streaming.ClusterID, clientID, connOpts...)
	} else {
		options := nats.DefaultOptions
		options.Url = "nats://" + args.Address.String()
		options.User = args.Username
		options.Password = args.Password
		options.Token = args.Token
		options.Secure = args.Secure
		natsConn, err = options.Connect()
	}
	if err != nil {
		return nil, err
	}

	return &NATSTarget{
		id:       event.TargetID{ID: id, Name: "nats"},
		args:     args,
		stanConn: stanConn,
		natsConn: natsConn,
	}, nil
}
1122439
func (c *BackgroundService) StartObserving(service string) (*gcdmessage.ChromeResponse, error) {
	var v BackgroundServiceStartObservingParams
	v.Service = service
	return c.StartObservingWithParams(&v)
}
234005
func (s *NeutrinoClient) Start() error {
	s.CS.Start()
	s.clientMtx.Lock()
	defer s.clientMtx.Unlock()
	if !s.started {
		s.enqueueNotification = make(chan interface{})
		s.dequeueNotification = make(chan interface{})
		s.currentBlock = make(chan *waddrmgr.BlockStamp)
		s.quit = make(chan struct{})
		s.started = true
		s.wg.Add(1)
		go func() {
			select {
			case s.enqueueNotification <- ClientConnected{}:
			case <-s.quit:
			}
		}()
		go s.notificationHandler()
	}
	return nil
}
1320748
func (e environ) StartInstance(ctx context.ProviderCallContext, args environs.StartInstanceParams) (*environs.StartInstanceResult, error) {
	osString, err := series.GetOSFromSeries(args.Tools.OneSeries())
	if err != nil {
		return nil, errors.Trace(err)
	}
	fwmode := e.Config().FirewallMode()
	if osString == jujuos.Windows && fwmode != config.FwNone {
		return nil, errors.Errorf("rackspace provider doesn't support firewalls for windows instances")

	}
	r, err := e.Environ.StartInstance(ctx, args)
	if err != nil {
		return nil, errors.Trace(err)
	}
	if fwmode != config.FwNone {
		interrupted := make(chan os.Signal, 1)
		timeout := environs.BootstrapDialOpts{
			Timeout:        time.Minute * 5,
			RetryDelay:     time.Second * 5,
			AddressesDelay: time.Second * 20,
		}
		addr, err := waitSSH(
			ioutil.Discard,
			interrupted,
			ssh.DefaultClient,
			common.GetCheckNonceCommand(args.InstanceConfig),
			&common.RefreshableInstance{r.Instance, e},
			ctx,
			timeout,
			common.DefaultHostSSHOptions,
		)
		if err != nil {
			return nil, errors.Trace(err)
		}
		client := newInstanceConfigurator(addr)
		apiPort := 0
		if args.InstanceConfig.Controller != nil {
			apiPort = args.InstanceConfig.Controller.Config.APIPort()
		}
		err = client.DropAllPorts([]int{apiPort, 22}, addr)
		if err != nil {
			common.HandleCredentialError(IsAuthorisationFailure, err, ctx)
			return nil, errors.Trace(err)
		}
	}
	return r, nil
}
361899
func (s *Server) Start() error {
	if s.config.Listener == nil {
		s.config.DisableHTTP2 = true
		err := s.config.InitListener(func() error {
			if s.config.TLSConfig == nil {
				return nil
			}
			s.config.TLSConfig.PreferServerCipherSuites = true
			return nil
		})
		if err != nil {
			return err
		}
	}
	s.config.Print(`fast`)
	return s.Serve(s.config.Listener)

}
976123
func (c *Client) StartServer() {
	mux := http.NewServeMux()
	mux.Handle("/", c)
	srv := &http.Server{
		ReadTimeout:  5 * time.Second,
		WriteTimeout: 10 * time.Second,
		Handler:      mux,
		Addr:         c.BindAddress,
	}
	log.Printf("Listening on http://%v...\n", c.BindAddress)
	if err := srv.ListenAndServe(); err != nil {
		log.Fatal(err)
	}
}