github.com/observiq/carbon@v0.9.11-0.20200820160507-1b872e368a5e/commands/service.go (about)

     1  package commands
     2  
     3  import (
     4  	"context"
     5  	"os"
     6  	"os/signal"
     7  	"syscall"
     8  
     9  	"github.com/kardianos/service"
    10  	"github.com/observiq/carbon/agent"
    11  	"go.uber.org/zap"
    12  )
    13  
    14  // AgentService is a service that runs the carbon agent.
    15  type AgentService struct {
    16  	cancel context.CancelFunc
    17  	agent  *agent.LogAgent
    18  }
    19  
    20  // Start will start the carbon agent.
    21  func (a *AgentService) Start(s service.Service) error {
    22  	a.agent.Info("Starting carbon agent")
    23  	if err := a.agent.Start(); err != nil {
    24  		a.agent.Errorw("Failed to start carbon agent", zap.Any("error", err))
    25  		a.cancel()
    26  	}
    27  	return nil
    28  }
    29  
    30  // Stop will stop the carbon agent.
    31  func (a *AgentService) Stop(s service.Service) error {
    32  	a.agent.Info("Stopping carbon agent")
    33  	a.agent.Stop()
    34  	a.cancel()
    35  	return nil
    36  }
    37  
    38  // newAgentService creates a new agent service with the provided agent.
    39  func newAgentService(ctx context.Context, agent *agent.LogAgent, cancel context.CancelFunc) (service.Service, error) {
    40  	agentService := &AgentService{cancel, agent}
    41  	config := &service.Config{
    42  		Name:        "carbon",
    43  		DisplayName: "Carbon Log Agent",
    44  		Description: "Monitors and processes log entries",
    45  		Option: service.KeyValue{
    46  			"RunWait": func() {
    47  				var sigChan = make(chan os.Signal, 3)
    48  				signal.Notify(sigChan, syscall.SIGTERM, os.Interrupt)
    49  				select {
    50  				case <-sigChan:
    51  				case <-ctx.Done():
    52  				}
    53  			},
    54  		},
    55  	}
    56  
    57  	service, err := service.New(agentService, config)
    58  	if err != nil {
    59  		return nil, err
    60  	}
    61  
    62  	return service, nil
    63  }