Path: blob/main/cmd/grafana-agent-service/main_windows.go
4094 views
package main12import (3"context"4"fmt"5"os"6"sync"78"github.com/go-kit/log"9"github.com/go-kit/log/level"10"golang.org/x/sys/windows/svc"11)1213const serviceName = "Grafana Agent Flow"1415func main() {16logger, err := newLogger()17if err != nil {18// Ideally the logger never fails to be created, since if it does, there's19// nowhere to send the failure to.20fmt.Fprintln(os.Stderr, err)21os.Exit(1)22}2324managerConfig, err := loadConfig()25if err != nil {26level.Error(logger).Log("msg", "failed to run service", "err", err)27os.Exit(1)28}2930cfg := serviceManagerConfig{31Path: managerConfig.ServicePath,32Args: managerConfig.Args,33Dir: managerConfig.WorkingDirectory,3435// Send logs directly to the event logger.36Stdout: logger,37Stderr: logger,38}3940as := &agentService{logger: logger, cfg: cfg}41if err := svc.Run(serviceName, as); err != nil {42level.Error(logger).Log("msg", "failed to run service", "err", err)43os.Exit(1)44}45}4647type agentService struct {48logger log.Logger49cfg serviceManagerConfig50}5152const cmdsAccepted = svc.AcceptStop | svc.AcceptShutdown5354func (as *agentService) Execute(args []string, r <-chan svc.ChangeRequest, s chan<- svc.Status) (svcSpecificEC bool, exitCode uint32) {55defer func() {56s <- svc.Status{State: svc.Stopped}57}()5859var workers sync.WaitGroup60defer workers.Wait()6162ctx, cancel := context.WithCancel(context.Background())63defer cancel()6465s <- svc.Status{State: svc.StartPending}6667// Run the serviceManager.68{69sm := newServiceManager(as.logger, as.cfg)7071workers.Add(1)72go func() {73// In case the service manager exits on its own, we cancel our context to74// signal to the parent goroutine to exit.75defer cancel()76defer workers.Done()77sm.Run(ctx)78}()79}8081s <- svc.Status{State: svc.Running, Accepts: cmdsAccepted}82defer func() {83s <- svc.Status{State: svc.StopPending}84}()8586for {87select {88case <-ctx.Done():89// Our managed service exited; shut down the service.90return false, 091case req := <-r:92switch req.Cmd {93case svc.Interrogate:94s <- req.CurrentStatus95case svc.Pause, svc.Continue:96// no-op97default:98// Every other command should terminate the service.99return false, 0100}101}102}103}104105106