// Start starts the Server, making it ready to accept subscriptions and
// updates.
768832
func (s *Server) Start() error {
	if !atomic.CompareAndSwapUint32(&s.started, 0, 1) {
		return nil
	}

	s.wg.Add(1)
	go s.subscriptionHandler()

	return nil
}
938289
func (mr *MockServerManagerMockRecorder) Start(arg0, arg1, arg2, arg3 interface{}) *gomock.Call {
	return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Start", reflect.TypeOf((*MockServerManager)(nil).Start), arg0, arg1, arg2, arg3)
}
1295198
func (s *OutboundServer) Start() error {
	Notice("Starting Freeswitch Outbound Server @ (address: %s) ...", s.Addr)

	var err error

	s.Listener, err = net.Listen(s.Proto, s.Addr)

	if err != nil {
		Error(ECouldNotStartListener, err)
		return err
	}

	quit := make(chan bool)

	go func() {
		for {
			Warning("Waiting for incoming connections ...")

			c, err := s.Accept()

			if err != nil {
				Error(EListenerConnection, err)
				quit <- true
				break
			}

			conn := SocketConnection{
				Conn: c,
				err:  make(chan error),
				m:    make(chan *Message),
			}

			Notice("Got new connection from: %s", conn.OriginatorAddr())

			go conn.Handle()

			s.Conns <- conn
		}
	}()

	<-quit

	// Stopping server itself ...
	s.Stop()

	return err
}
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
}
384397
func (m *Monitor) Start(c *exec.Cmd) (chan runc.Exit, error) {
	ec := m.Subscribe()
	if err := c.Start(); err != nil {
		m.Unsubscribe(ec)
		return nil, err
	}
	return ec, nil
}
986806
func (srv *Server) Start() (err error) {
	// Take a copy of server fields.
	var tlsConfig *tls.Config
	if srv.TLSConfig != nil {
		tlsConfig = srv.TLSConfig.Clone()
	}
	readTimeout := srv.ReadTimeout
	writeTimeout := srv.WriteTimeout
	handler := srv.Handler // if srv.Handler holds non-synced state -> possible data race

	addrs := set.CreateStringSet(srv.Addrs...).ToSlice() // copy and remove duplicates
	tcpKeepAliveTimeout := srv.TCPKeepAliveTimeout

	// Create new HTTP listener.
	var listener *httpListener
	listener, err = newHTTPListener(
		addrs,
		tcpKeepAliveTimeout,
		readTimeout,
		writeTimeout,
		srv.UpdateBytesReadFunc,
		srv.UpdateBytesWrittenFunc,
	)
	if err != nil {
		return err
	}

	// Wrap given handler to do additional
	// * return 503 (service unavailable) if the server in shutdown.
	wrappedHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		atomic.AddInt32(&srv.requestCount, 1)
		defer atomic.AddInt32(&srv.requestCount, -1)

		// If server is in shutdown, return 503 (service unavailable)
		if atomic.LoadUint32(&srv.inShutdown) != 0 {
			w.WriteHeader(http.StatusServiceUnavailable)
			return
		}

		// Handle request using passed handler.
		handler.ServeHTTP(w, r)
	})

	srv.listenerMutex.Lock()
	srv.Handler = wrappedHandler
	srv.listener = listener
	srv.listenerMutex.Unlock()

	// Start servicing with listener.
	if tlsConfig != nil {
		if err = http2.ConfigureServer(&srv.Server, &http2.Server{
			MaxConcurrentStreams: DefaultHTTP2MaxConcurrentStreams,
		}); err != nil {
			return err
		}
		return srv.Server.Serve(tls.NewListener(listener, tlsConfig))
	}
	return srv.Server.Serve(listener)
}
34621
func (s *VolumeServer) Start(
	ctx context.Context,
	req *api.SdkCloudMigrateStartRequest,
) (*api.SdkCloudMigrateStartResponse, error) {
	if s.cluster() == nil || s.driver(ctx) == nil {
		return nil, status.Error(codes.Unavailable, "Resource has not been initialized")
	}

	if volume := req.GetVolume(); volume != nil {
		// Check ownership
		if err := checkAccessFromDriverForVolumeId(ctx, s.driver(ctx), volume.GetVolumeId(), api.Ownership_Read); err != nil {
			return nil, err
		}

		//migrate volume
		return s.volumeMigrate(ctx, req, volume)
	} else if volumeGroup := req.GetVolumeGroup(); volumeGroup != nil {
		if !s.haveOwnership(ctx, nil, &api.VolumeLocator{
			Group: &api.Group{
				Id: volumeGroup.GetGroupId(),
			},
		}) {
			return nil, status.Error(codes.PermissionDenied, "Volume Operation not Permitted.")
		}
		//migrate volume groups
		return s.volumeGroupMigrate(ctx, req, volumeGroup)
	} else if allVolumes := req.GetAllVolumes(); allVolumes != nil {
		// migrate all volumes
		if !s.haveOwnership(ctx, nil, nil) {
			return nil, status.Error(codes.PermissionDenied, "Volume Operation not Permitted.")
		}
		return s.allVolumesMigrate(ctx, req, allVolumes)
	}
	return nil, status.Error(codes.InvalidArgument, "Unknown operation request")
}
151761
func (lb *LogBroker) Start(ctx context.Context) error {
	lb.mu.Lock()
	defer lb.mu.Unlock()

	if lb.cancelAll != nil {
		return errAlreadyRunning
	}

	lb.pctx, lb.cancelAll = context.WithCancel(ctx)
	lb.logQueue = watch.NewQueue()
	lb.subscriptionQueue = watch.NewQueue()
	lb.registeredSubscriptions = make(map[string]*subscription)
	lb.subscriptionsByNode = make(map[string]map[*subscription]struct{})
	return nil
}
778741
func (m *SubscriptionManager) Start() {
	if atomic.AddInt32(&m.started, 1) != 1 {
		return
	}

	log.Debug("Starting block notifications subscription manager")

	m.wg.Add(1)
	go m.subscriptionHandler()
}
580747
func (s *Server) Start() {
	log.WithField("version", VERSION).Info("Starting server")

	// Set up the processors for spans:

	// Use the pre-allocated Workers slice to know how many to start.
	s.SpanWorker = NewSpanWorker(s.spanSinks, s.TraceClient, s.Statsd, s.SpanChan, s.TagsAsMap)

	go func() {
		log.Info("Starting Event worker")
		defer func() {
			ConsumePanic(s.Sentry, s.TraceClient, s.Hostname, recover())
		}()
		s.EventWorker.Work()
	}()

	log.WithField("n", s.SpanWorkerGoroutines).Info("Starting span workers")
	for i := 0; i < s.SpanWorkerGoroutines; i++ {
		go func() {
			defer func() {
				ConsumePanic(s.Sentry, s.TraceClient, s.Hostname, recover())
			}()
			s.SpanWorker.Work()
		}()
	}

	statsdPool := &sync.Pool{
		// We +1 this so we an "detect" when someone sends us too long of a metric!
		New: func() interface{} {
			return make([]byte, s.metricMaxLength+1)
		},
	}

	tracePool := &sync.Pool{
		New: func() interface{} {
			return make([]byte, s.traceMaxLengthBytes)
		},
	}

	for _, sink := range s.spanSinks {
		logrus.WithField("sink", sink.Name()).Info("Starting span sink")
		if err := sink.Start(s.TraceClient); err != nil {
			logrus.WithError(err).WithField("sink", sink).Panic("Error starting span sink")
		}
	}

	for _, sink := range s.metricSinks {
		logrus.WithField("sink", sink.Name()).Info("Starting metric sink")
		if err := sink.Start(s.TraceClient); err != nil {
			logrus.WithError(err).WithField("sink", sink).Fatal("Error starting metric sink")
		}
	}

	// Read Metrics Forever!
	concreteAddrs := make([]net.Addr, 0, len(s.StatsdListenAddrs))
	for _, addr := range s.StatsdListenAddrs {
		concreteAddrs = append(concreteAddrs, StartStatsd(s, addr, statsdPool))
	}
	s.StatsdListenAddrs = concreteAddrs

	// Read Traces Forever!
	if len(s.SSFListenAddrs) > 0 {
		concreteAddrs := make([]net.Addr, 0, len(s.StatsdListenAddrs))
		for _, addr := range s.SSFListenAddrs {
			concreteAddrs = append(concreteAddrs, StartSSF(s, addr, tracePool))
		}
		s.SSFListenAddrs = concreteAddrs
	} else {
		logrus.Info("Tracing sockets are not configured - not reading trace socket")
	}

	// Initialize a gRPC connection for forwarding
	if s.forwardUseGRPC {
		var err error
		s.grpcForwardConn, err = grpc.Dial(s.ForwardAddr, grpc.WithInsecure())
		if err != nil {
			log.WithError(err).WithFields(logrus.Fields{
				"forwardAddr": s.ForwardAddr,
			}).Fatal("Failed to initialize a gRPC connection for forwarding")
		}
	}

	// Flush every Interval forever!
	go func() {
		defer func() {
			ConsumePanic(s.Sentry, s.TraceClient, s.Hostname, recover())
		}()

		ctx, cancel := context.WithCancel(context.Background())
		go func() {
			// If the server is shutting down, cancel any in-flight flush:
			<-s.shutdown
			cancel()
		}()

		if s.synchronizeInterval {
			// We want to align our ticker to a multiple of its duration for
			// convenience of bucketing.
			<-time.After(CalculateTickDelay(s.interval, time.Now()))
		}

		// We aligned the ticker to our interval above. It's worth noting that just
		// because we aligned once we're not guaranteed to be perfect on each
		// subsequent tick. This code is small, however, and should service the
		// incoming tick signal fast enough that the amount we are "off" is
		// negligible.
		ticker := time.NewTicker(s.interval)
		for {
			select {
			case <-s.shutdown:
				// stop flushing on graceful shutdown
				ticker.Stop()
				return
			case triggered := <-ticker.C:
				ctx, cancel := context.WithDeadline(ctx, triggered.Add(s.interval))
				s.Flush(ctx)
				cancel()
			}
		}
	}()
}
1064399
func (s *T) Start(hostCfgs map[engine.HostKey]engine.Host) error {
	log.Infof("%s start", s)
	switch s.state {
	case srvStateInit:
		lsn, err := net.Listen(s.lsnCfg.Address.Network, s.lsnCfg.Address.Address)
		if err != nil {
			return err
		}

		lsn = &graceful.TCPKeepAliveListener{TCPListener: lsn.(*net.TCPListener)}

		if s.isProxyProto() {
			lsn = &proxyproto.Listener{
				Listener:           lsn,
				ProxyHeaderTimeout: s.options.ReadTimeout,
			}
		}

		if s.isTLS() {
			config, err := s.newTLSCfg(hostCfgs)
			if err != nil {
				return err
			}
			lsn = graceful.NewTLSListener(lsn, config)
		}
		s.srv = graceful.NewWithOptions(
			graceful.Options{
				Server:       s.newHTTPServer(),
				Listener:     lsn,
				StateHandler: s.connTck.RegisterStateChange,
			})
		s.state = srvStateActive
		s.serveWg.Add(1)
		go s.serve(s.srv)
		return nil
	case srvStateHijacked:
		s.state = srvStateActive
		s.serveWg.Add(1)
		go s.serve(s.srv)
		return nil
	}
	return errors.Errorf("%v Calling start in unsupported state", s)
}
37789
func (s *SSHServer) Start() {
	s.config.Logger.Info("Starting SSH server", "addr", s.config.Bind)
	s.reaper.SpawnFunc(s.listen)
}
13514
func (s Service) Start() error {
	running, err := s.Running()
	if err != nil {
		return errors.Trace(err)
	}
	if running {
		return nil
	}

	commands, err := s.StartCommands()
	if err != nil {
		return errors.Trace(err)
	}
	for _, command := range commands {
		commandParts := strings.Fields(command)
		out, err := utils.RunCommand(commandParts[0], commandParts[1:]...)
		if err != nil {
			if strings.Contains(out, "has no services") {
				continue
			}
			return errors.Annotatef(err, "%v -> %v", command, out)
		}
	}

	return nil
}
369072
func (m *MockServerManager) Start(arg0, arg1, arg2 string, arg3 int) (registry.Server, error) {
	ret := m.ctrl.Call(m, "Start", arg0, arg1, arg2, arg3)
	ret0, _ := ret[0].(registry.Server)
	ret1, _ := ret[1].(error)
	return ret0, ret1
}
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)
}
800612
func (sv *Service) Start(t *testing.T) <-chan error {
	srv, err := embed.StartEtcd(sv.cfg)
	if err != nil {
		t.Fatal(err)
	}
	select {
	case <-srv.Server.ReadyNotify():
		err = nil
	case err = <-srv.Err():
	case <-srv.Server.StopNotify():
		err = fmt.Errorf("received from etcdserver.Server.StopNotify")
	}
	if err != nil {
		t.Fatal(err)
	}
	sv.etcd = srv

	// issue linearized read to ensure leader election
	cli := v3client.New(srv.Server)
	_, err = cli.Get(context.Background(), "foo")

	go func() {
		defer close(sv.httpErrc)
		if err := sv.httpServer.ListenAndServe(); err != nil && err != http.ErrServerClosed {
			sv.httpErrc <- err
			return
		}
		sv.httpErrc <- nil
	}()
	return sv.httpErrc
}
1369194
func (s *ExtensionManagerServer) Start() error {
	var server thrift.TServer
	err := func() error {
		s.mutex.Lock()
		defer s.mutex.Unlock()
		registry := s.genRegistry()

		stat, err := s.serverClient.RegisterExtension(
			&osquery.InternalExtensionInfo{
				Name: s.name,
			},
			registry,
		)

		if err != nil {
			return errors.Wrap(err, "registering extension")
		}
		if stat.Code != 0 {
			return errors.Errorf("status %d registering extension: %s", stat.Code, stat.Message)
		}

		listenPath := fmt.Sprintf("%s.%d", s.sockPath, stat.UUID)

		processor := osquery.NewExtensionProcessor(s)

		s.transport, err = transport.OpenServer(listenPath, s.timeout)
		if err != nil {
			return errors.Wrapf(err, "opening server socket (%s)", listenPath)
		}

		s.server = thrift.NewTSimpleServer2(processor, s.transport)
		server = s.server

		s.started = true

		return nil
	}()

	if err != nil {
		return err
	}

	return server.Serve()
}