github.com/crowdsecurity/crowdsec@v1.6.1/cmd/crowdsec/run_in_svc.go (about)

     1  //go:build !windows
     2  
     3  package main
     4  
     5  import (
     6  	"fmt"
     7  	"runtime/pprof"
     8  
     9  	log "github.com/sirupsen/logrus"
    10  
    11  	"github.com/crowdsecurity/go-cs-lib/trace"
    12  	"github.com/crowdsecurity/go-cs-lib/version"
    13  
    14  	"github.com/crowdsecurity/crowdsec/pkg/csconfig"
    15  	"github.com/crowdsecurity/crowdsec/pkg/database"
    16  )
    17  
    18  func StartRunSvc() error {
    19  	var (
    20  		cConfig *csconfig.Config
    21  		err     error
    22  	)
    23  
    24  	defer trace.CatchPanic("crowdsec/StartRunSvc")
    25  
    26  	// Always try to stop CPU profiling to avoid passing flags around
    27  	// It's a noop if profiling is not enabled
    28  	defer pprof.StopCPUProfile()
    29  
    30  	if cConfig, err = LoadConfig(flags.ConfigFile, flags.DisableAgent, flags.DisableAPI, false); err != nil {
    31  		return err
    32  	}
    33  
    34  	log.Infof("Crowdsec %s", version.String())
    35  
    36  	agentReady := make(chan bool, 1)
    37  
    38  	// Enable profiling early
    39  	if cConfig.Prometheus != nil {
    40  		var dbClient *database.Client
    41  
    42  		var err error
    43  
    44  		if cConfig.DbConfig != nil {
    45  			dbClient, err = database.NewClient(cConfig.DbConfig)
    46  
    47  			if err != nil {
    48  				return fmt.Errorf("unable to create database client: %w", err)
    49  			}
    50  		}
    51  
    52  		registerPrometheus(cConfig.Prometheus)
    53  
    54  		go servePrometheus(cConfig.Prometheus, dbClient, agentReady)
    55  	} else {
    56  		// avoid leaking the channel
    57  		go func() {
    58  			<-agentReady
    59  		}()
    60  	}
    61  
    62  	return Serve(cConfig, agentReady)
    63  }