// Starts a profiler returns nil if profiler is not enabled, caller needs to handle this.
420683
func startProfiler(profilerType, dirPath string) (minioProfiler, error) {
	var err error
	if dirPath == "" {
		dirPath, err = ioutil.TempDir("", "profile")
		if err != nil {
			return nil, err
		}
	}

	var profiler interface {
		Stop()
	}

	var profilerFileName string

	// Enable profiler and set the name of the file that pkg/pprof
	// library creates to store profiling data.
	switch profilerType {
	case "cpu":
		profiler = profile.Start(profile.CPUProfile, profile.NoShutdownHook, profile.ProfilePath(dirPath))
		profilerFileName = "cpu.pprof"
	case "mem":
		profiler = profile.Start(profile.MemProfile, profile.NoShutdownHook, profile.ProfilePath(dirPath))
		profilerFileName = "mem.pprof"
	case "block":
		profiler = profile.Start(profile.BlockProfile, profile.NoShutdownHook, profile.ProfilePath(dirPath))
		profilerFileName = "block.pprof"
	case "mutex":
		profiler = profile.Start(profile.MutexProfile, profile.NoShutdownHook, profile.ProfilePath(dirPath))
		profilerFileName = "mutex.pprof"
	case "trace":
		profiler = profile.Start(profile.TraceProfile, profile.NoShutdownHook, profile.ProfilePath(dirPath))
		profilerFileName = "trace.out"
	default:
		return nil, errors.New("profiler type unknown")
	}

	return &profilerWrapper{
		stopFn: profiler.Stop,
		pathFn: func() string {
			return filepath.Join(dirPath, profilerFileName)
		},
	}, nil
}
387869
func (a adminAPIHandlers) StartProfilingHandler(w http.ResponseWriter, r *http.Request) {
	ctx := newContext(r, w, "StartProfiling")

	objectAPI := validateAdminReq(ctx, w, r)
	if objectAPI == nil {
		return
	}

	vars := mux.Vars(r)
	profiler := vars["profilerType"]

	thisAddr, err := xnet.ParseHost(GetLocalPeer(globalEndpoints))
	if err != nil {
		writeErrorResponseJSON(ctx, w, toAdminAPIErr(ctx, err), r.URL)
		return
	}

	// Start profiling on remote servers.
	hostErrs := globalNotificationSys.StartProfiling(profiler)

	// Start profiling locally as well.
	{
		if globalProfiler != nil {
			globalProfiler.Stop()
		}
		prof, err := startProfiler(profiler, "")
		if err != nil {
			hostErrs = append(hostErrs, NotificationPeerErr{
				Host: *thisAddr,
				Err:  err,
			})
		} else {
			globalProfiler = prof
			hostErrs = append(hostErrs, NotificationPeerErr{
				Host: *thisAddr,
			})
		}
	}

	var startProfilingResult []StartProfilingResult

	for _, nerr := range hostErrs {
		result := StartProfilingResult{NodeName: nerr.Host.String()}
		if nerr.Err != nil {
			result.Error = nerr.Err.Error()
		} else {
			result.Success = true
		}
		startProfilingResult = append(startProfilingResult, result)
	}

	// Create JSON result and send it to the client
	startProfilingResultInBytes, err := json.Marshal(startProfilingResult)
	if err != nil {
		writeErrorResponseJSON(ctx, w, toAdminAPIErr(ctx, err), r.URL)
		return
	}

	writeSuccessResponseJSON(w, []byte(startProfilingResultInBytes))
}
114589
func (ttles *TTLExpirationScheduler) Start() error {
	ttles.Lock()
	defer ttles.Unlock()

	err := ttles.readState()
	if err != nil {
		return err
	}

	if !ttles.stopped {
		return fmt.Errorf("scheduler already started")
	}

	dcontext.GetLogger(ttles.ctx).Infof("Starting cached object TTL expiration scheduler...")
	ttles.stopped = false

	// Start timer for each deserialized entry
	for _, entry := range ttles.entries {
		entry.timer = ttles.startTimer(entry, time.Until(entry.Expiry))
	}

	// Start a ticker to periodically save the entries index

	go func() {
		for {
			select {
			case <-ttles.saveTimer.C:
				ttles.Lock()
				if !ttles.indexDirty {
					ttles.Unlock()
					continue
				}

				err := ttles.writeState()
				if err != nil {
					dcontext.GetLogger(ttles.ctx).Errorf("Error writing scheduler state: %s", err)
				} else {
					ttles.indexDirty = false
				}
				ttles.Unlock()

			case <-ttles.doneChan:
				return
			}
		}
	}()

	return nil
}
644411
func NewProfiler() (prof *Profiler, err error) {
	p, err := basic.NewProfiler()
	if err != nil {
		return nil, err
	}
	return &Profiler{Profiler: p}, nil
}
772329
func NewProfiler() (prof *Profiler, err error) {
	// if it hasn't been set, set it.
	if atomic.LoadInt32(&CLK_TCK) == 0 {
		err = ClkTck()
		if err != nil {
			return nil, err
		}
	}
	proc, err := joe.NewProc(procFile)
	if err != nil {
		return nil, err
	}
	return &Profiler{Procer: proc, Buffer: joe.NewBuffer(), ClkTck: int16(atomic.LoadInt32(&CLK_TCK))}, nil
}
945132
func (this *MirrorMaker) Start() {
	this.initializeMessageChannels()
	this.startConsumers()
	this.startProducers()
	<-this.stopped
}
964564
func (s *StatsHandler) Start() error {
	go func() {
		s.wg.Add(1)
		defer s.wg.Done()

		for stats := range gateway.Backend().StatsPacketChan() {
			go func(stats gw.GatewayStats) {
				s.wg.Add(1)
				defer s.wg.Done()

				if err := updateGatewayState(storage.DB(), storage.RedisPool(), stats); err != nil {
					log.WithError(err).Error("update gateway state error")
				}

				if err := handleGatewayStats(storage.RedisPool(), stats); err != nil {
					log.WithError(err).Error("handle gateway stats error")
				}
			}(stats)
		}
	}()
	return nil
}
611997
func (config ManifoldConfig) start(context dependency.Context) (worker.Worker, error) {
	if err := config.Validate(); 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)
	}

	pool, err := stTracker.Use()
	if err != nil {
		return nil, errors.Trace(err)
	}

	w, err := config.NewWorker(Config{
		Logger:               config.Logger,
		WatcherFactory:       func() BackingWatcher { return pool.SystemState().WatchAllModels(pool) },
		PrometheusRegisterer: config.PrometheusRegisterer,
		Cleanup:              func() { _ = stTracker.Done() },
	})
	if err != nil {
		_ = stTracker.Done()
		return nil, errors.Trace(err)
	}
	return w, nil
}
544615
func NewProfiler() *Profiler {
	prof := cpux.NewProfiler()
	return &Profiler{Profiler: prof, Builder: fb.NewBuilder(0)}
}
724930
func NewProfiler() (prof *Profiler, err error) {
	p, err := u.NewProfiler()
	if err != nil {
		return nil, err
	}
	return &Profiler{Profiler: p}, nil
}
435201
func (l *Logger) Start() error {
	// initialize mutex on start
	l.fileMu = new(sync.RWMutex)

	var err error

selectwriter:
	switch l.Output {
	case "", "stderr":
		l.writer = os.Stderr

	case "stdout":
		l.writer = os.Stdout

	case "syslog":
		l.writer, err = gsyslog.NewLogger(gsyslog.LOG_ERR, "LOCAL0", "caddy")
		if err != nil {
			return err
		}
	default:

		if address := parseSyslogAddress(l.Output); address != nil {
			l.writer, err = gsyslog.DialLogger(address.network, address.address, gsyslog.LOG_ERR, "LOCAL0", "caddy")

			if err != nil {
				return err
			}

			break selectwriter
		}

		var file *os.File

		file, err = os.OpenFile(l.Output, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0644)
		if err != nil {
			return err
		}

		if l.Roller != nil {
			file.Close()
			l.Roller.Filename = l.Output
			l.writer = l.Roller.GetLogWriter()
		} else {
			l.writer = file
		}
	}

	l.Logger = log.New(l.writer, "", 0)

	return nil

}
798774
func (h *MPL115A2Driver) Start() (err error) {
	if err := h.initialization(); err != nil {
		return err
	}

	return
}
707924
func (m *monitor) Start(availablePlugins *availablePlugins) {
	//start a routine that will be fired every X duration looping
	//over available plugins and firing a health check routine
	ticker := time.NewTicker(m.duration)
	m.quit = make(chan struct{})
	go func() {
		for {
			select {
			case <-ticker.C:
				go func() {
					availablePlugins.RLock()
					for _, ap := range availablePlugins.all() {
						if !ap.IsRemote() {
							go ap.CheckHealth()
						}
					}
					availablePlugins.RUnlock()
				}()
			case <-m.quit:
				ticker.Stop()
				m.State = MonitorStopped
				return
			}
		}
	}()
	m.State = MonitorStarted
}
135954
func (h *Handle) Start() error {
	if err := h.watcher.registerHandle(h); err != nil {
		return err
	}
	go h.deliver()
	return nil
}
203834
func NewProfiler() (prof *Profiler, err error) {
	proc, err := joe.NewProc(procFile)
	if err != nil {
		return nil, err
	}
	cpuProf := cpux.NewProfiler()
	nodeProf := node.NewProfiler()
	return &Profiler{Procer: proc, Buffer: joe.NewBuffer(), CPUProf: cpuProf, NodeProf: nodeProf}, nil
}
1335599
func (adm *AdminClient) StartProfiling(profiler ProfilerType) ([]StartProfilingResult, error) {
	v := url.Values{}
	v.Set("profilerType", string(profiler))
	resp, err := adm.executeMethod("POST", requestData{
		relPath:     "/v1/profiling/start",
		queryValues: v,
	})
	defer closeResponse(resp)
	if err != nil {
		return nil, err
	}

	if resp.StatusCode != http.StatusOK {
		return nil, httpRespToErrorResponse(resp)
	}

	jsonResult, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}

	var startResults []StartProfilingResult
	err = json.Unmarshal(jsonResult, &startResults)
	if err != nil {
		return nil, err
	}

	return startResults, nil
}
28776
func Start(config *config.Config, handler http.Handler) {
	mu.Lock()
	defer mu.Unlock()

	cfg = config
	port := config.Choria.StatsPort

	if port == 0 {
		log.Infof("Statistics gathering disabled, set plugin.choria.stats_port")
		return
	}

	prometheus.MustRegister(buildInfo)
	buildInfo.WithLabelValues(build.Version, build.SHA).Inc()

	if !running {
		log.Infof("Starting statistic reporting Prometheus statistics on http://%s:%d/choria/", config.Choria.StatsListenAddress, port)

		if handler == nil {
			http.HandleFunc("/choria/", handleRoot)
			http.Handle("/choria/prometheus", promhttp.Handler())

			go http.ListenAndServe(fmt.Sprintf("%s:%d", config.Choria.StatsListenAddress, port), nil)
		} else {
			hh := handler.(*http.ServeMux)
			hh.HandleFunc("/choria/", handleRoot)
			hh.Handle("/choria/prometheus", promhttp.Handler())
		}

		running = true
	}
}