// Start crawling the host.
979482
func (w *worker) run() {
	defer func() {
		w.logFunc(LogInfo, "worker done.")
		w.wg.Done()
	}()

	// Enter loop to process URLs until stop signal is received
	for {
		var idleChan <-chan time.Time

		w.logFunc(LogInfo, "waiting for pop...")

		// Initialize the idle timeout channel, if required
		if w.opts.WorkerIdleTTL > 0 {
			idleChan = time.After(w.opts.WorkerIdleTTL)
		}

		select {
		case <-w.stop:
			w.logFunc(LogInfo, "stop signal received.")
			return

		case <-idleChan:
			w.logFunc(LogInfo, "idle timeout received.")
			w.sendResponse(nil, false, nil, true)
			return

		case batch := <-w.pop:

			// Got a batch of urls to crawl, loop and check at each iteration if a stop
			// is received.
			for _, ctx := range batch {
				w.logFunc(LogInfo, "popped: %s", ctx.url)

				if ctx.IsRobotsURL() {
					w.requestRobotsTxt(ctx)
				} else if w.isAllowedPerRobotsPolicies(ctx.url) {
					w.requestURL(ctx, ctx.HeadBeforeGet)
				} else {
					// Must still notify Crawler that this URL was processed, although not visited
					w.opts.Extender.Disallowed(ctx)
					w.sendResponse(ctx, false, nil, false)
				}

				// No need to check for idle timeout here, no idling while looping through
				// a batch of URLs.
				select {
				case <-w.stop:
					w.logFunc(LogInfo, "stop signal received.")
					return
				default:
					// Nothing, just continue...
				}
			}
		}
	}
}
1184056
func Start(sockFile string, c *cli.Context) error {
	var err error

	if err = daemonEnvironmentSetup(c); err != nil {
		return err
	}
	defer environmentCleanup()

	root := c.String("root")
	s := &daemon{
		ConvoyDrivers: make(map[string]ConvoyDriver),
	}
	config := &daemonConfig{
		Root: root,
	}

	ignoreCfgFile := c.Bool("ignore-config-file")
	exists := false
	if !ignoreCfgFile {
		exists, err = util.ObjectExists(config)
		if err != nil {
			return err
		}
	}

	if exists {
		log.Debug("Found existing config. Ignoring command line opts, loading config from ", root)
		if err := util.ObjectLoad(config); err != nil {
			return err
		}
	} else {
		fd := c.String("mnt-ns")
		if fd != "" {
			if _, err := os.Stat(fd); err != nil {
				return fmt.Errorf("Cannot find mount namespace fd %v", fd)
			}
			config.MountNamespaceFD = fd
		}

		driverList := c.StringSlice("drivers")
		if len(driverList) == 0 {
			return fmt.Errorf("Missing or invalid parameters")
		}
		log.Debug("Creating config at ", root)

		config.DriverList = driverList
		config.DefaultDriver = driverList[0]
		config.IgnoreDockerDelete = c.Bool("ignore-docker-delete")
		config.CreateOnDockerMount = c.Bool("create-on-docker-mount")
		config.CmdTimeout = c.String("cmd-timeout")
	}

	s.daemonConfig = *config

	if err := util.InitMountNamespace(s.MountNamespaceFD); err != nil {
		return err
	}

	util.InitTimeout(config.CmdTimeout)

	// driverOpts would be ignored by Convoy Drivers if config already exists
	driverOpts := util.SliceToMap(c.StringSlice("driver-opts"))
	if err := s.initDrivers(driverOpts); err != nil {
		return err
	}
	if err := s.finializeInitialization(); err != nil {
		return err
	}
	if err := util.ObjectSave(config); err != nil {
		return err
	}

	s.Router = createRouter(s)

	if err := util.MkdirIfNotExists(filepath.Dir(sockFile)); err != nil {
		return err
	}
	// This should be safe because lock file prevent starting daemon twice
	if _, err := os.Stat(sockFile); err == nil {
		log.Warnf("Remove previous sockfile at %v", sockFile)
		if err := os.Remove(sockFile); err != nil {
			return err
		}
	}

	l, err := net.Listen("unix", sockFile)
	if err != nil {
		fmt.Println("listen err", err)
		return err
	}
	defer l.Close()

	sigs := make(chan os.Signal, 1)
	done := make(chan bool, 1)
	signal.Notify(sigs, os.Interrupt, os.Kill, syscall.SIGTERM)
	go func() {
		sig := <-sigs
		fmt.Printf("Caught signal %s: shutting down.\n", sig)
		done <- true
	}()

	go func() {
		err = http.Serve(l, s.Router)
		if err != nil {
			log.Error("http server error", err.Error())
		}
		done <- true
	}()

	<-done
	return nil
}
1322831
func (s *Server) Start(ctx context.Context) (*net.TCPAddr, error) {
	return s.srv.Start(ctx, "devshell", s.Port, s.serve)
}
39523
func (bot *TgBot) Start() {
	if bot.ID == 0 {
		fmt.Println("No ID, maybe the token is bad.")
		return
	}

	if bot.MainListener == nil {
		fmt.Println("No listener!")
		return
	}

	removedhook := false

	for {
		updatesList, err := bot.GetUpdates()
		if err != nil {
			fmt.Println(err)
			if !removedhook {
				fmt.Println("Removing webhook...")
				bot.SetWebhook("")
				removedhook = true
			}
			continue
		}
		bot.ProcessMessages(updatesList)
	}
}
1167157
func (config ManifoldConfig) start(context dependency.Context) (worker.Worker, error) {
	if err := config.Validate(); err != nil {
		return nil, errors.Trace(err)
	}

	var agent jujuagent.Agent
	if err := context.Get(config.AgentName, &agent); err != nil {
		return nil, errors.Trace(err)
	}

	var stTracker workerstate.StateTracker
	if err := context.Get(config.StateName, &stTracker); err != nil {
		return nil, errors.Trace(err)
	}
	statePool, err := stTracker.Use()
	if err != nil {
		return nil, errors.Trace(err)
	}

	agentConfig := agent.CurrentConfig()
	setStateServingInfo := func(info params.StateServingInfo) error {
		return agent.ChangeConfig(func(config jujuagent.ConfigSetter) error {
			config.SetStateServingInfo(info)
			return nil
		})
	}

	st := statePool.SystemState()
	addressWatcher, err := config.NewMachineAddressWatcher(st, agentConfig.Tag().Id())
	if err != nil {
		return nil, errors.Trace(err)
	}

	w := config.NewWorker(Config{
		AddressWatcher:         addressWatcher,
		StateServingInfoGetter: agentConfig,
		StateServingInfoSetter: setStateServingInfo,
		ControllerConfigGetter: st,
		APIHostPortsGetter:     st,
	})
	return common.NewCleanupWorker(w, func() { stTracker.Done() }), nil
}
1240279
func (fw *BarracudaNG) Start(ctx context.Context, info map[string]string, timeout int) (bool, error) {
	session, err := fw.getSshSession(ctx)

	if err != nil {
		log.LoggerWContext(ctx).Error(fmt.Sprintf("Cannot connect to BarracudaNG: %s", err))
		return false, err
	}

	cmd := "phibstest 127.0.0.1 l peer=" + info["ip"] + " origin=PacketFence service=PacketFence user=" + info["username"]
	session.Run(cmd)

	return true, nil
}
757658
func (w *Server) Start() {
	w.wg.Add(1)
	go func(w *Server) {
		w.server.ListenAndServe()
		w.wg.Done()
	}(w)
}
557834
func (config ManifoldConfig) start(context dependency.Context) (worker.Worker, error) {
	if err := config.Validate(); err != nil {
		return nil, errors.Trace(err)
	}

	var clk clock.Clock
	if err := context.Get(config.ClockName, &clk); err != nil {
		return nil, errors.Trace(err)
	}

	var agent agent.Agent
	if err := context.Get(config.AgentName, &agent); err != nil {
		return nil, errors.Trace(err)
	}
	var transport raft.Transport
	if err := context.Get(config.TransportName, &transport); err != nil {
		return nil, errors.Trace(err)
	}

	// TODO(axw) make the directory path configurable, so we can
	// potentially have multiple Rafts. The dqlite raft should go
	// in <data-dir>/dqlite.
	agentConfig := agent.CurrentConfig()
	raftDir := filepath.Join(agentConfig.DataDir(), "raft")

	return config.NewWorker(Config{
		FSM:                  config.FSM,
		Logger:               config.Logger,
		StorageDir:           raftDir,
		LocalID:              raft.ServerID(agentConfig.Tag().Id()),
		Transport:            transport,
		Clock:                clk,
		PrometheusRegisterer: config.PrometheusRegisterer,
	})
}
1341928
func (rkq *RekeyQueueStandard) start(ctx context.Context) {
	go func() {
		for {
			select {
			case id := <-rkq.queue:
				if err := rkq.limiter.Wait(ctx); err != nil {
					rkq.log.Debug("Waiting on rate limiter for tlf=%v error: %v", id, err)
					return
				}
				rkq.config.KBFSOps().RequestRekey(context.Background(), id)
				func(id tlf.ID) {
					rkq.mu.Lock()
					defer rkq.mu.Unlock()
					delete(rkq.pendings, id)
				}(id)
			case err := <-ctx.Done():
				rkq.log.Debug("Rekey queue background routine context done: %v", err)
				return
			}
		}
	}()
}
47482
func (l *ServiceListener) Start(sn *ServiceNode, instanceID int) bool {

	l.mu.Lock()
	defer l.mu.Unlock()

	logger := plog.WithFields(log.Fields{
		"serviceid":                   sn.ID,
		"servicename":                 sn.Name,
		"shouldhaveaddressassignment": sn.ShouldHaveAddressAssignment,
		"instanceid":                  instanceID,
	})

	// pick a host
	hostID, err := l.handler.SelectHost(sn)
	if err != nil {
		logger.WithError(err).Warn("Could not select host")
		return false
	}
	// CC-3656: If the strategy doesn't select a host, an invalid service state is created.
	if hostID == "" {
		// The selected strategy didn't select any hosts; we need to make this
		// obvious in the log so it can be corrected.
		strat, err := strategy.Get(string(sn.HostPolicy))
		if err == nil {
			logger = logger.WithField("strategy", strat.Name())
		}
		logger.Warn("No hosts available")
		return false
	}

	logger.WithField("hostid", hostID).Debug("Service instance scheduled to host")
	req := StateRequest{
		PoolID:     l.poolid,
		HostID:     hostID,
		ServiceID:  sn.ID,
		InstanceID: instanceID,
	}

	// make sure the state exists on neither the service nor the host
	DeleteState(l.conn, req)

	if err := CreateState(l.conn, req); err != nil {

		logger.WithError(err).Warn("Could not schedule service instance")
		return false
	}

	return true
}
770707
func (s *Server) Start() error {
	if len(s.getCommandLabels()) > 0 {
		s.updateLabels()
	}
	go s.heartbeat.Run()

	// If the server requested connections to it arrive over a reverse tunnel,
	// don't call Start() which listens on a socket, return right away.
	if s.useTunnel {
		return nil
	}
	return s.srv.Start()
}
246582
func Start() {
	connect()
	go startBatcher(commonBatchStream)

	for i := range registry {
		debug("starting", registry[i])
		go registry[i].StartLoop()
	}
}
328483
func (c *Client) Start() error {
	if err := c.Listen(); err != nil {
		return err
	}
	return c.Serve()
}
133877
func Start(httpAddress, tlsAddress string) error {
	err := StartHTTP(httpAddress)
	if err != nil {
		return err
	}
	return StartTLS(tlsAddress)
}
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
}
817374
func (r *Router) Start() {
	if browserSupportsPushState && !r.ForceHashURL {
		r.pathChanged(getPath(), true)
		r.watchHistory()
	} else {
		r.setInitialHash()
		r.watchHash()
	}
	if r.ShouldInterceptLinks {
		r.InterceptLinks()
	}
}
1352302
func Crawl(url string, depth int, fetcher Fetcher) {
	if depth <= 0 {
		fmt.Printf("<- Done with %v, depth 0.\n", url)
		return
	}

	fetched.Lock()
	if _, ok := fetched.m[url]; ok {
		fetched.Unlock()
		fmt.Printf("<- Done with %v, already fetched.\n", url)
		return
	}
	// We mark the url to be loading to avoid others reloading it at the same time.
	fetched.m[url] = loading
	fetched.Unlock()

	// We load it concurrently.
	body, urls, err := fetcher.Fetch(url)

	// And update the status in a synced zone.
	fetched.Lock()
	fetched.m[url] = err
	fetched.Unlock()

	if err != nil {
		fmt.Printf("<- Error on %v: %v\n", url, err)
		return
	}
	fmt.Printf("Found: %s %q\n", url, body)
	done := make(chan bool)
	for i, u := range urls {
		fmt.Printf("-> Crawling child %v/%v of %v : %v.\n", i, len(urls), url, u)
		go func(url string) {
			Crawl(url, depth-1, fetcher)
			done <- true
		}(u)
	}
	for i, u := range urls {
		fmt.Printf("<- [%v] %v/%v Waiting for child %v.\n", url, i, len(urls), u)
		<-done
	}
	fmt.Printf("<- Done with %v\n", url)
}