// StartMonitoring starts the HTTP or HTTPs server if needed.
430291
func (s *Server) StartMonitoring() error {
	// Snapshot server options.
	opts := s.getOpts()

	// Specifying both HTTP and HTTPS ports is a misconfiguration
	if opts.HTTPPort != 0 && opts.HTTPSPort != 0 {
		return fmt.Errorf("can't specify both HTTP (%v) and HTTPs (%v) ports", opts.HTTPPort, opts.HTTPSPort)
	}
	var err error
	if opts.HTTPPort != 0 {
		err = s.startMonitoring(false)
	} else if opts.HTTPSPort != 0 {
		if opts.TLSConfig == nil {
			return fmt.Errorf("TLS cert and key required for HTTPS")
		}
		err = s.startMonitoring(true)
	}
	return err
}
902793
func (c *CheckHTTP) Start() {
	c.stopLock.Lock()
	defer c.stopLock.Unlock()

	if c.httpClient == nil {
		// Create the transport. We disable HTTP Keep-Alive's to prevent
		// failing checks due to the keepalive interval.
		trans := cleanhttp.DefaultTransport()
		trans.DisableKeepAlives = true

		// Take on the supplied TLS client config.
		trans.TLSClientConfig = c.TLSClientConfig

		// Create the HTTP client.
		c.httpClient = &http.Client{
			Timeout:   10 * time.Second,
			Transport: trans,
		}

		// For long (>10s) interval checks the http timeout is 10s, otherwise the
		// timeout is the interval. This means that a check *should* return
		// before the next check begins.
		if c.Timeout > 0 && c.Timeout < c.Interval {
			c.httpClient.Timeout = c.Timeout
		} else if c.Interval < 10*time.Second {
			c.httpClient.Timeout = c.Interval
		}
	}

	c.stop = false
	c.stopCh = make(chan struct{})
	go c.run()
}
794127
func (e *Echo) StartServer(s *http.Server) (err error) {
	// Setup
	e.colorer.SetOutput(e.Logger.Output())
	s.ErrorLog = e.StdLogger
	s.Handler = e
	if e.Debug {
		e.Logger.SetLevel(log.DEBUG)
	}

	if !e.HideBanner {
		e.colorer.Printf(banner, e.colorer.Red("v"+Version), e.colorer.Blue(website))
	}

	if s.TLSConfig == nil {
		if e.Listener == nil {
			e.Listener, err = newListener(s.Addr)
			if err != nil {
				return err
			}
		}
		if !e.HidePort {
			e.colorer.Printf("⇨ http server started on %s\n", e.colorer.Green(e.Listener.Addr()))
		}
		return s.Serve(e.Listener)
	}
	if e.TLSListener == nil {
		l, err := newListener(s.Addr)
		if err != nil {
			return err
		}
		e.TLSListener = tls.NewListener(l, s.TLSConfig)
	}
	if !e.HidePort {
		e.colorer.Printf("⇨ https server started on %s\n", e.colorer.Green(e.TLSListener.Addr()))
	}
	return s.Serve(e.TLSListener)
}
1282097
func (w *Monitor) Start() {
	var certTime <-chan time.Time
	if !w.DisconnectExpiredCert.IsZero() {
		t := time.NewTimer(w.DisconnectExpiredCert.Sub(w.Clock.Now().UTC()))
		defer t.Stop()
		certTime = t.C
	}

	var idleTimer *time.Timer
	var idleTime <-chan time.Time
	if w.ClientIdleTimeout != 0 {
		idleTimer = time.NewTimer(w.ClientIdleTimeout)
		idleTime = idleTimer.C
	}

	for {
		select {
		// certificate has expired, disconnect
		case <-certTime:
			event := events.EventFields{
				events.EventType:       events.ClientDisconnectEvent,
				events.EventLogin:      w.Login,
				events.EventUser:       w.TeleportUser,
				events.LocalAddr:       w.Conn.LocalAddr().String(),
				events.RemoteAddr:      w.Conn.RemoteAddr().String(),
				events.SessionServerID: w.ServerID,
				events.Reason:          fmt.Sprintf("client certificate expired at %v", w.Clock.Now().UTC()),
			}
			w.Audit.EmitAuditEvent(events.ClientDisconnect, event)
			w.Entry.Debugf("Disconnecting client: %v", event[events.Reason])
			w.Conn.Close()
			return
		case <-idleTime:
			now := w.Clock.Now().UTC()
			clientLastActive := w.Tracker.GetClientLastActive()
			if now.Sub(clientLastActive) >= w.ClientIdleTimeout {
				event := events.EventFields{
					events.EventLogin:      w.Login,
					events.EventUser:       w.TeleportUser,
					events.LocalAddr:       w.Conn.LocalAddr().String(),
					events.RemoteAddr:      w.Conn.RemoteAddr().String(),
					events.SessionServerID: w.ServerID,
				}
				if clientLastActive.IsZero() {
					event[events.Reason] = "client reported no activity"
				} else {
					event[events.Reason] = fmt.Sprintf("client is idle for %v, exceeded idle timeout of %v",
						now.Sub(clientLastActive), w.ClientIdleTimeout)
				}
				w.Entry.Debugf("Disconnecting client: %v", event[events.Reason])
				w.Audit.EmitAuditEvent(events.ClientDisconnect, event)
				w.Conn.Close()
				return
			}
			w.Entry.Debugf("Next check in %v", w.ClientIdleTimeout-now.Sub(clientLastActive))
			idleTimer = time.NewTimer(w.ClientIdleTimeout - now.Sub(clientLastActive))
			idleTime = idleTimer.C
		case <-w.Context.Done():
			w.Entry.Debugf("Releasing associated resources - context has been closed.")
			return
		}
	}
}
601473
func (m *Metrics) OnStartup() error {
	ln, err := net.Listen("tcp", m.Addr)
	if err != nil {
		log.Errorf("Failed to start metrics handler: %s", err)
		return err
	}

	m.ln = ln
	m.lnSetup = true
	ListenAddr = m.ln.Addr().String() // For tests

	m.mux = http.NewServeMux()
	m.mux.Handle("/metrics", promhttp.HandlerFor(m.Reg, promhttp.HandlerOpts{}))
	m.srv = &http.Server{Handler: m.mux}
	go func() {
		m.srv.Serve(m.ln)
	}()
	return nil
}
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()
			}
		}
	}()
}
622094
func (s *Server) Start() {
	if s.URL != "" {
		panic("Server already started")
	}
	if s.client == nil {
		s.client = &http.Client{Transport: &http.Transport{}}
	}
	s.URL = "http://" + s.Listener.Addr().String()
	s.wrap()
	s.goServe()
}
1236823
func (s *Service) Start() error {
	server := http.Server{
		Handler: s,
	}

	var ln net.Listener
	var err error
	if s.CertFile == "" || s.KeyFile == "" {
		ln, err = net.Listen("tcp", s.addr)
		if err != nil {
			return err
		}
	} else {
		config, err := createTLSConfig(s.CertFile, s.KeyFile)
		if err != nil {
			return err
		}
		ln, err = tls.Listen("tcp", s.addr, config)
		if err != nil {
			return err
		}
		s.logger.Printf("secure HTTPS server enabled with cert %s, key %s", s.CertFile, s.KeyFile)
	}
	s.ln = ln

	go func() {
		err := server.Serve(s.ln)
		if err != nil {
			s.logger.Println("HTTP service Serve() returned:", err.Error())
		}
	}()
	s.logger.Println("service listening on", s.addr)

	return nil
}
822900
func (m *martiniServer) Start() {
	err := http.ListenAndServe(":8001", m.svr)
	if err != nil {
		log.Fatal(err)
	}
}
1274377
func (s *Server) Start() {

	http.HandleFunc("/", index)
	http.Handle("/stats/app", &statsHandler{
		stats:  s.Stats,
		logger: s.Logger,
	})
	http.HandleFunc("/stats/runtime", stats_api.Handler)

	port := DefaultPort
	if p := os.Getenv(EnvPort); p != "" {
		port = p
	}

	s.Logger.Printf("[INFO] Start server listening on :%s", port)
	if err := http.ListenAndServe(":"+port, nil); err != nil {
		s.Logger.Printf("[ERROR] Failed to start varz-server: %s", err)
	}
}
1339276
func Start(behaviors Behaviors) {
	http.Handle("/", Handler(behaviors, false))
	log.Fatal(http.ListenAndServe(":8080", nil))
}
227633
func (s *GrpcServer) startGrpcService() {
	// Start listening for requests
	reflection.Register(s.server)
	logrus.Infof("%s gRPC Server ready on %s", s.name, s.Address())
	waitForServer := make(chan bool)
	s.goServe(waitForServer)
	<-waitForServer
	s.running = true
}
696358
func (o *Observer) Start() {
	for {
		select {
		case evt := <-o.notify: // We have an event to observe
			if len(o.observers) == 0 {
				log.Printf("Ignoring event due to no observers: %s", evt.ID)
				continue
			}

			evtb, err := json.Marshal(evt)
			if err != nil {
				log.Printf("Error marshaling event: %s", err)
				continue
			}

			sse := []byte("event: " + evt.Type + "\ndata: ")
			sse = append(sse, append(evtb, []byte("\n\n")...)...)

			for n := range o.observers {
				n <- sse
			}

		case n := <-o.newObservers:
			o.observers[n] = true
		case n := <-o.closedObservers:
			delete(o.observers, n)

		case <-o.closed: // The Observer has been closed.
			return
		}
	}
}
52688
func StartTracing(serviceName string) io.Closer {
	factory, ok := tracingBackendFactories[*tracingServer]
	if !ok {
		return fail(serviceName)
	}

	tracer, closer, err := factory(serviceName)
	if err != nil {
		log.Error(vterrors.Wrapf(err, "failed to create a %s tracer", *tracingServer))
		return &nilCloser{}
	}

	spanFactory = tracer

	log.Infof("successfully started tracing with [%s]", *tracingServer)

	return closer
}
2814
func (c *Client) Start() {
	u := c.url
	if c.LoggingEnabled {
		log.Println("Now observing changes on", u.String())
	}

	atomic.AddUint64(&(c.runID), 1)
	currentRunID := atomic.LoadUint64(&(c.runID))

	go func(runID uint64, u *url.URL) {
		since := time.Now().Unix() * 1000
		for {
			pr, err := c.fetchEvents(since)

			if err != nil {
				if c.LoggingEnabled {
					log.Println(err)
					log.Printf("Reattempting to connect to %s in %d seconds", u.String(), c.Reattempt)
				}
				time.Sleep(c.Reattempt)
				continue
			}

			// We check that its still the same runID as when this goroutine was started
			clientRunID := atomic.LoadUint64(&(c.runID))
			if clientRunID != runID {
				if c.LoggingEnabled {
					log.Printf("Client on URL %s has been stopped, not sending events", u.String())
				}
				return
			}

			if len(pr.Events) > 0 {
				if c.LoggingEnabled {
					log.Println("Got", len(pr.Events), "event(s) from URL", u.String())
				}
				for _, event := range pr.Events {
					since = event.Timestamp
					c.EventsChan <- event
				}
			} else {
				// Only push timestamp forward if its greater than the last we checked
				if pr.Timestamp > since {
					since = pr.Timestamp
				}
			}
		}
	}(currentRunID, u)
}
670916
func (s *Server) startServer(server *http.Server, errs chan error) {
	var (
		network string
		err     error
		ln      net.Listener
	)

	network, server.Addr = s.parseAddress(server.Addr)
	if network == "unix" {
		// TODO: handle error
		os.Remove(server.Addr)
	}
	ln, err = net.Listen(network, server.Addr)

	if err == nil {
		ln = tcpKeepAliveListener{ln.(*net.TCPListener)}
		if server.TLSConfig == nil {
			s.Logger.Infof("web > Server started on %s", server.Addr)
			err = server.Serve(ln)
		} else {
			s.Logger.Infof("web > Server started on %s(tls)", server.Addr)
			err = server.ServeTLS(ln, "", "")
		}
	}
	errs <- err
}
990692
func (m *Monitor) StartSampling(ctx context.Context) {
	if m.interval == 0 {
		return
	}
	go func() {
		ticker := time.NewTicker(m.interval)
		defer ticker.Stop()
		for {
			select {
			case <-ticker.C:
			case <-ctx.Done():
				m.sample()
				return
			}
			m.sample()
		}
	}()
}