// Start should be called once all the Connections have been subscribed
// for topic consumption. An attempt to start consuming a topic after the multiplexer is started
// returns an error.
965435
func (mux *Multiplexer) Start() error {
	mux.rwlock.Lock()
	defer mux.rwlock.Unlock()
	var err error

	if mux.started {
		return fmt.Errorf("multiplexer has been started already")
	}

	// block further Consumer consumers
	mux.started = true

	var hashTopics, manTopics []string

	for _, subscription := range mux.mapping {
		if subscription.manual {
			manTopics = append(manTopics, subscription.topic)
			continue
		}
		hashTopics = append(hashTopics, subscription.topic)
	}

	mux.config.SetRecvMessageChan(make(chan *client.ConsumerMessage))
	mux.config.GroupID = mux.name
	mux.config.SetInitialOffset(sarama.OffsetOldest)
	mux.config.Topics = append(hashTopics, manTopics...)

	// create consumer
	mux.WithFields(logging.Fields{"hashTopics": hashTopics, "manualTopics": manTopics}).Debugf("Consuming started")
	mux.Consumer, err = client.NewConsumer(mux.config, nil)
	if err != nil {
		return err
	}

	if len(hashTopics) == 0 {
		mux.Debug("No topics for hash partitioner")
	} else {
		mux.WithFields(logging.Fields{"topics": hashTopics}).Debugf("Consuming (hash) started")
		mux.Consumer.StartConsumerHandlers()
	}

	if len(manTopics) == 0 {
		mux.Debug("No topics for manual partitioner")
	} else {
		mux.WithFields(logging.Fields{"topics": manTopics}).Debugf("Consuming (manual) started")
		for _, sub := range mux.mapping {
			if sub.manual {
				sConsumer := mux.Consumer.SConsumer
				if sConsumer == nil {
					return fmt.Errorf("consumer for manual partition is not available")
				}
				partitionConsumer, err := sConsumer.ConsumePartition(sub.topic, sub.partition, sub.offset)
				if err != nil {
					return err
				}
				// Store partition consumer in subscription so it can be closed lately
				sub.partitionConsumer = &partitionConsumer
				mux.Logger.WithFields(logging.Fields{"topic": sub.topic, "partition": sub.partition, "offset": sub.offset}).Info("Partition sConsumer started")
				mux.Consumer.StartConsumerManualHandlers(partitionConsumer)
			}
		}

	}

	go mux.genericConsumer()
	go mux.manualConsumer(mux.Consumer)

	return err
}
777827
func (l *Linearizer) Start() {
	for {
		// Check context error
		if l.ctx.Err() != nil {
			l.md.Lock()
			l.dispatchEvent(&event{err: l.ctx.Err()})
			return
		}

		// Get bytes from pool
		var b = l.bytesPool.Get().([]byte)

		// Read
		n, err := l.r.Read(b)
		if err != nil {
			l.md.Lock()
			l.dispatchEvent(&event{err: err})
			return
		}

		// Dispatch event in a go routine so that it doesn't block the read
		l.md.Lock()
		go l.dispatchEvent(&event{b: b, n: n})
	}
}
241186
func (n *NeutrinoNotifier) Start() error {
	// Already started?
	if atomic.AddInt32(&n.started, 1) != 1 {
		return nil
	}

	// First, we'll obtain the latest block height of the p2p node. We'll
	// start the auto-rescan from this point. Once a caller actually wishes
	// to register a chain view, the rescan state will be rewound
	// accordingly.
	startingPoint, err := n.p2pNode.BestBlock()
	if err != nil {
		return err
	}
	n.bestBlock.Hash = &startingPoint.Hash
	n.bestBlock.Height = startingPoint.Height

	n.txNotifier = chainntnfs.NewTxNotifier(
		uint32(n.bestBlock.Height), chainntnfs.ReorgSafetyLimit,
		n.confirmHintCache, n.spendHintCache,
	)

	// Next, we'll create our set of rescan options. Currently it's
	// required that a user MUST set an addr/outpoint/txid when creating a
	// rescan. To get around this, we'll add a "zero" outpoint, that won't
	// actually be matched.
	var zeroInput neutrino.InputWithScript
	rescanOptions := []neutrino.RescanOption{
		neutrino.StartBlock(startingPoint),
		neutrino.QuitChan(n.quit),
		neutrino.NotificationHandlers(
			rpcclient.NotificationHandlers{
				OnFilteredBlockConnected:    n.onFilteredBlockConnected,
				OnFilteredBlockDisconnected: n.onFilteredBlockDisconnected,
				OnRedeemingTx:               n.onRelevantTx,
			},
		),
		neutrino.WatchInputs(zeroInput),
	}

	// Finally, we'll create our rescan struct, start it, and launch all
	// the goroutines we need to operate this ChainNotifier instance.
	n.chainView = neutrino.NewRescan(
		&neutrino.RescanChainSource{
			ChainService: n.p2pNode,
		},
		rescanOptions...,
	)
	n.rescanErr = n.chainView.Start()

	n.chainUpdates.Start()
	n.txUpdates.Start()

	n.wg.Add(1)
	go n.notificationDispatcher()

	return nil
}
418991
func (cm *ConnManager) Start() {
	// Already started?
	if atomic.AddInt32(&cm.start, 1) != 1 {
		return
	}

	log.Trace("Connection manager started")
	cm.wg.Add(1)
	go cm.connHandler()

	// Start all the listeners so long as the caller requested them and
	// provided a callback to be invoked when connections are accepted.
	if cm.cfg.OnAccept != nil {
		for _, listner := range cm.cfg.Listeners {
			cm.wg.Add(1)
			go cm.listenHandler(listner)
		}
	}

	for i := atomic.LoadUint64(&cm.connReqCount); i < uint64(cm.cfg.TargetOutbound); i++ {
		go cm.NewConnReq()
	}
}
774121
func (r *rpcServer) Start() error {
	if atomic.AddInt32(&r.started, 1) != 1 {
		return nil
	}

	// First, we'll start all the sub-servers to ensure that they're ready
	// to take new requests in.
	//
	// TODO(roasbeef): some may require that the entire daemon be started
	// at that point
	for _, subServer := range r.subServers {
		rpcsLog.Debugf("Starting sub RPC server: %v", subServer.Name())

		if err := subServer.Start(); err != nil {
			return err
		}
	}

	// With all the sub-servers started, we'll spin up the listeners for
	// the main RPC server itself.
	for _, listener := range cfg.RPCListeners {
		lis, err := lncfg.ListenOnAddress(listener)
		if err != nil {
			ltndLog.Errorf(
				"RPC server unable to listen on %s", listener,
			)
			return err
		}

		r.listenerCleanUp = append(r.listenerCleanUp, func() {
			lis.Close()
		})

		go func() {
			rpcsLog.Infof("RPC server listening on %s", lis.Addr())
			r.grpcServer.Serve(lis)
		}()
	}

	// Finally, start the REST proxy for our gRPC server above. We'll ensure
	// we direct LND to connect to its loopback address rather than a
	// wildcard to prevent certificate issues when accessing the proxy
	// externally.
	//
	// TODO(roasbeef): eventually also allow the sub-servers to themselves
	// have a REST proxy.
	mux := proxy.NewServeMux()

	err := lnrpc.RegisterLightningHandlerFromEndpoint(
		context.Background(), mux, r.restProxyDest,
		r.restDialOpts,
	)
	if err != nil {
		return err
	}
	for _, restEndpoint := range cfg.RESTListeners {
		lis, err := lncfg.TLSListenOnAddress(restEndpoint, r.tlsCfg)
		if err != nil {
			ltndLog.Errorf(
				"gRPC proxy unable to listen on %s",
				restEndpoint,
			)
			return err
		}

		r.listenerCleanUp = append(r.listenerCleanUp, func() {
			lis.Close()
		})

		go func() {
			rpcsLog.Infof("gRPC proxy started at %s", lis.Addr())
			http.Serve(lis, mux)
		}()
	}

	return nil
}
788646
func (c *kvmContainer) Start(params StartParams) error {
	var bridge string
	var interfaces []libvirt.InterfaceInfo
	if params.Network != nil {
		if params.Network.NetworkType == container.BridgeNetwork {
			bridge = params.Network.Device
			for _, iface := range params.Network.Interfaces {
				interfaces = append(interfaces, interfaceInfo{config: iface})
			}
		} else {
			err := errors.New("Non-bridge network devices not yet supported")
			logger.Infof(err.Error())
			return err
		}
	}
	logger.Debugf("create the machine %s", c.name)
	if params.StatusCallback != nil {
		_ = params.StatusCallback(status.Provisioning, "Creating instance", nil)
	}
	if err := CreateMachine(CreateMachineParams{
		Hostname:          c.name,
		Series:            params.Series,
		UserDataFile:      params.UserDataFile,
		NetworkConfigData: params.NetworkConfigData,
		NetworkBridge:     bridge,
		Memory:            params.Memory,
		CpuCores:          params.CpuCores,
		RootDisk:          params.RootDisk,
		Interfaces:        interfaces,
	}); err != nil {
		return err
	}

	logger.Debugf("Set machine %s to autostart", c.name)
	if params.StatusCallback != nil {
		_ = params.StatusCallback(status.Provisioning, "Starting instance", nil)
	}
	return AutostartMachine(c)
}
169781
func (p *Daemon) Start() error {
	p.lock.Lock()
	defer p.lock.Unlock()

	// A stopped proxy cannot be restarted
	if p.stopped {
		return fmt.Errorf("stopped")
	}

	// If we're already running, that is okay
	if p.process != nil {
		return nil
	}

	// Setup our stop channel
	stopCh := make(chan struct{})
	exitedCh := make(chan struct{})
	p.stopCh = stopCh
	p.exitedCh = exitedCh

	// Start the loop.
	go p.keepAlive(stopCh, exitedCh)

	return nil
}
857704
func (s *RTMService) Start() *RTMStartCall {
	var call RTMStartCall
	call.service = s
	return &call
}
203988
func (tc *Consumer) Start() error {
	log.Info("Starting TCP consumer")
	tcpAddr, err := net.ResolveTCPAddr("tcp", tc.address)
	if err != nil {
		return err
	}

	listener, err := net.ListenTCP("tcp", tcpAddr)
	if err != nil {
		return err
	}

	log.Info("Listening TCP at %s", tc.address)
	go tc.closeListener(listener)
	go tc.listen(listener)

	return nil
}
775779
func (s *OsdCsiServer) Start() error {
	return s.GrpcServer.Start(func(grpcServer *grpc.Server) {
		csi.RegisterIdentityServer(grpcServer, s)
		csi.RegisterControllerServer(grpcServer, s)
		csi.RegisterNodeServer(grpcServer, s)
	})
}
697509
func (conn *BytesManualConnectionStr) StartPostInitConsumer(topic string, partition int32, offset int64) (*sarama.PartitionConsumer, error) {
	multiplexer := conn.multiplexer
	multiplexer.WithFields(logging.Fields{"topic": topic}).Debugf("Post-init consuming started")

	if multiplexer.Consumer == nil || multiplexer.Consumer.SConsumer == nil {
		multiplexer.Warn("Unable to start post-init Consumer, client not available in the mux")
		return nil, nil
	}

	// Consumer that reads topic/partition/offset. Throws error if offset is 'in the future' (message with offset does not exist yet)
	partitionConsumer, err := multiplexer.Consumer.SConsumer.ConsumePartition(topic, partition, offset)
	if err != nil {
		return nil, err
	}
	multiplexer.Consumer.StartConsumerManualHandlers(partitionConsumer)

	return &partitionConsumer, nil
}
281087
func (s *rpcServer) Start() {
	if atomic.AddInt32(&s.started, 1) != 1 {
		return
	}

	rpcsLog.Trace("Starting RPC server")
	rpcServeMux := http.NewServeMux()
	httpServer := &http.Server{
		Handler: rpcServeMux,

		// Timeout connections which don't complete the initial
		// handshake within the allowed timeframe.
		ReadTimeout: time.Second * rpcAuthTimeoutSeconds,
	}
	rpcServeMux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Connection", "close")
		w.Header().Set("Content-Type", "application/json")
		r.Close = true

		// Limit the number of connections to max allowed.
		if s.limitConnections(w, r.RemoteAddr) {
			return
		}

		// Keep track of the number of connected clients.
		s.incrementClients()
		defer s.decrementClients()
		_, isAdmin, err := s.checkAuth(r, true)
		if err != nil {
			jsonAuthFail(w)
			return
		}

		// Read and respond to the request.
		s.jsonRPCRead(w, r, isAdmin)
	})

	// Websocket endpoint.
	rpcServeMux.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) {
		authenticated, isAdmin, err := s.checkAuth(r, false)
		if err != nil {
			jsonAuthFail(w)
			return
		}

		// Attempt to upgrade the connection to a websocket connection
		// using the default size for read/write buffers.
		ws, err := websocket.Upgrade(w, r, nil, 0, 0)
		if err != nil {
			if _, ok := err.(websocket.HandshakeError); !ok {
				rpcsLog.Errorf("Unexpected websocket error: %v",
					err)
			}
			http.Error(w, "400 Bad Request.", http.StatusBadRequest)
			return
		}
		s.WebsocketHandler(ws, r.RemoteAddr, authenticated, isAdmin)
	})

	for _, listener := range s.cfg.Listeners {
		s.wg.Add(1)
		go func(listener net.Listener) {
			rpcsLog.Infof("RPC server listening on %s", listener.Addr())
			httpServer.Serve(listener)
			rpcsLog.Tracef("RPC listener done for %s", listener.Addr())
			s.wg.Done()
		}(listener)
	}

	s.ntfnMgr.Start()
}
768832
func (s *Server) Start() error {
	if !atomic.CompareAndSwapUint32(&s.started, 0, 1) {
		return nil
	}

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

	return nil
}
71340
func (conn *ProtoConnection) ConsumeTopic(msgClb func(messaging.ProtoMessage), topics ...string) error {
	conn.multiplexer.rwlock.Lock()
	defer conn.multiplexer.rwlock.Unlock()

	if conn.multiplexer.started {
		return fmt.Errorf("ConsumeTopic can be called only if the multiplexer has not been started yet")
	}

	byteClb := func(bm *client.ConsumerMessage) {
		pm := client.NewProtoConsumerMessage(bm, conn.serializer)
		msgClb(pm)
	}

	for _, topic := range topics {
		// check if we have already consumed the topic
		var found bool
		var subs *consumerSubscription
	LoopSubs:
		for _, subscription := range conn.multiplexer.mapping {
			if subscription.manual == true {
				// do not mix dynamic and manual mode
				continue
			}
			if subscription.topic == topic {
				found = true
				subs = subscription
				break LoopSubs
			}
		}

		if !found {
			subs = &consumerSubscription{
				manual:         false, // non-manual example
				topic:          topic,
				connectionName: conn.name,
				byteConsMsg:    byteClb,
			}
			// subscribe new topic
			conn.multiplexer.mapping = append(conn.multiplexer.mapping, subs)
		}

		// add subscription to consumerList
		subs.byteConsMsg = byteClb
	}

	return nil
}
389369
func (c *Conn) Start() error {
	if c.Rwc == nil {
		return errors.New("No connection exists")
	}

	c.RwcScanner = bufio.NewScanner(c.Rwc)

	for c.state != StateLoggedOut {
		// Always send welcome message if we are still in new connection state
		if c.state == StateNew {
			c.sendWelcome()
		}

		// Await requests from the client
		req, ok := c.ReadLine()
		if !ok {
			// The client has closed the connection
			c.state = StateLoggedOut
			break
		}
		fmt.Fprintf(c.Transcript, "C: %s\n", req)
		c.handleRequest(req)

		if c.RwcScanner.Err() != nil {
			fmt.Fprintf(c.Transcript, "Scan error: %s\n", c.RwcScanner.Err())
		}
	}

	return nil
}
85188
func (c *ChannelNotifier) Start() error {
	if !atomic.CompareAndSwapUint32(&c.started, 0, 1) {
		return nil
	}

	log.Tracef("ChannelNotifier %v starting", c)

	if err := c.ntfnServer.Start(); err != nil {
		return err
	}

	return nil
}
14737
func (s *Server) Start(ctx context.Context) {
	go func() {
		defer s.Close()
		<-ctx.Done()
		logger := log.FromContext(ctx)
		logger.Info("I have to go...")
		logger.Info("Stopping server gracefully")
		s.Stop()
	}()

	s.startTCPServers()
	s.routinesPool.Go(func(stop chan bool) {
		s.listenProviders(stop)
	})
	s.routinesPool.Go(func(stop chan bool) {
		s.listenConfigurations(stop)
	})
	s.startProvider()
	s.routinesPool.Go(func(stop chan bool) {
		s.listenSignals(stop)
	})
}