| 30 | type windowsService struct{} |
| 31 | |
| 32 | func (m *windowsService) Execute(_ []string, r <-chan svc.ChangeRequest, changes chan<- svc.Status) (bool, uint32) { |
| 33 | // start the service |
| 34 | changes <- svc.Status{State: svc.StartPending} |
| 35 | |
| 36 | // set up the log file |
| 37 | exePath, err := os.Executable() |
| 38 | if err != nil { |
| 39 | changes <- svc.Status{State: svc.StopPending} |
| 40 | return true, 101 // service specific exit code=101 |
| 41 | } |
| 42 | |
| 43 | logFolder := filepath.Join(filepath.Dir(exePath), "logs") |
| 44 | os.Mkdir(logFolder, 0644) // ignore all errors |
| 45 | |
| 46 | logFile := &lumberjack.Logger{ |
| 47 | Filename: filepath.Join(logFolder, "cloud-sql-proxy.log"), |
| 48 | MaxSize: 50, // megabytes |
| 49 | MaxBackups: 10, |
| 50 | MaxAge: 30, //days |
| 51 | } |
| 52 | |
| 53 | logger := log.NewStdLogger(logFile, logFile) |
| 54 | logger.Infof("Starting...") |
| 55 | |
| 56 | // start the main command |
| 57 | ctx, cancel := context.WithCancel(context.Background()) |
| 58 | defer cancel() |
| 59 | |
| 60 | app := cmd.NewCommand(cmd.WithLogger(logger)) |
| 61 | |
| 62 | cmdErrCh := make(chan error, 1) |
| 63 | go func() { |
| 64 | cmdErrCh <- app.ExecuteContext(ctx) |
| 65 | }() |
| 66 | |
| 67 | // now running |
| 68 | changes <- svc.Status{State: svc.Running, Accepts: svc.AcceptStop | svc.AcceptShutdown} |
| 69 | |
| 70 | var cmdErr error |
| 71 | |
| 72 | loop: |
| 73 | for { |
| 74 | select { |
| 75 | case err := <-cmdErrCh: |
| 76 | cmdErr = err |
| 77 | break loop |
| 78 | |
| 79 | case c := <-r: |
| 80 | switch c.Cmd { |
| 81 | case svc.Interrogate: |
| 82 | changes <- c.CurrentStatus |
| 83 | // testing deadlock from https://code.google.com/archive/p/winsvc/issues/4 |
| 84 | time.Sleep(100 * time.Millisecond) |
| 85 | changes <- c.CurrentStatus |
| 86 | |
| 87 | case svc.Stop, svc.Shutdown: |
| 88 | cancel() |
| 89 | |