|
| 1 | +package tcm |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "errors" |
| 6 | + "fmt" |
| 7 | + "log" |
| 8 | + "os" |
| 9 | + "os/exec" |
| 10 | + "os/signal" |
| 11 | + "path/filepath" |
| 12 | + "sync" |
| 13 | + "syscall" |
| 14 | + "time" |
| 15 | +) |
| 16 | + |
| 17 | +// Watchdog manages the lifecycle of a process. |
| 18 | +type Watchdog struct { |
| 19 | + // The command to execute and monitor. |
| 20 | + cmd *exec.Cmd |
| 21 | + // Time to wait before restarting the process. |
| 22 | + restartTimeout time.Duration |
| 23 | + // Flag to indicate if the Watchdog should stop. |
| 24 | + shouldStop bool |
| 25 | + // Mutex to protect access to shouldStop. |
| 26 | + stopMutex sync.Mutex |
| 27 | + // WaitGroup to wait for all goroutines to finish. |
| 28 | + doneBarrier sync.WaitGroup |
| 29 | + // File to store the process PID. |
| 30 | + pidFile string |
| 31 | +} |
| 32 | + |
| 33 | +// NewWatchdog creates a new Watchdog instance. |
| 34 | +func NewWatchdog(restartTimeout time.Duration) (*Watchdog, error) { |
| 35 | + return &Watchdog{ |
| 36 | + restartTimeout: restartTimeout, |
| 37 | + pidFile: "tcm/pidFile.pid", |
| 38 | + }, nil |
| 39 | +} |
| 40 | + |
| 41 | +// Start starts the process and monitors its execution. |
| 42 | +func (wd *Watchdog) Start(bin string, args ...string) error { |
| 43 | + wd.doneBarrier.Add(1) |
| 44 | + defer wd.doneBarrier.Done() |
| 45 | + |
| 46 | + signalCtx, signalCancel := context.WithCancel(context.Background()) |
| 47 | + defer signalCancel() |
| 48 | + |
| 49 | + go wd.handleSignals(signalCtx, signalCancel) |
| 50 | + |
| 51 | + for { |
| 52 | + wd.stopMutex.Lock() |
| 53 | + if wd.shouldStop { |
| 54 | + wd.stopMutex.Unlock() |
| 55 | + return nil |
| 56 | + } |
| 57 | + wd.stopMutex.Unlock() |
| 58 | + |
| 59 | + wd.cmd = exec.Command(bin, args...) |
| 60 | + wd.cmd.Stdout = os.Stdout |
| 61 | + wd.cmd.Stderr = os.Stderr |
| 62 | + |
| 63 | + log.Println("(INFO): Starting process...") |
| 64 | + if err := wd.cmd.Start(); err != nil { |
| 65 | + log.Printf("(ERROR): Failed to start process: %v\n", err) |
| 66 | + return err |
| 67 | + } |
| 68 | + |
| 69 | + if err := wd.writePIDToFile(); err != nil { |
| 70 | + log.Printf("(ERROR): Failed to write PID to file: %v\n", err) |
| 71 | + return err |
| 72 | + } |
| 73 | + |
| 74 | + err := wd.cmd.Wait() |
| 75 | + if err != nil { |
| 76 | + var exitErr *exec.ExitError |
| 77 | + if errors.As(err, &exitErr) { |
| 78 | + log.Printf("(WARN): Process exited with error: %v\n", exitErr) |
| 79 | + } else { |
| 80 | + log.Printf("(ERROR): Process failed: %v\n", err) |
| 81 | + return err |
| 82 | + } |
| 83 | + } else { |
| 84 | + log.Println("(INFO): Process completed successfully.") |
| 85 | + } |
| 86 | + |
| 87 | + wd.stopMutex.Lock() |
| 88 | + if wd.shouldStop { |
| 89 | + wd.stopMutex.Unlock() |
| 90 | + return nil |
| 91 | + } |
| 92 | + wd.stopMutex.Unlock() |
| 93 | + |
| 94 | + log.Printf("(INFO): Waiting for %s before restart...\n", wd.restartTimeout) |
| 95 | + time.Sleep(wd.restartTimeout) |
| 96 | + } |
| 97 | +} |
| 98 | + |
| 99 | +// Stop stops the process and shuts down the Watchdog. |
| 100 | +func (wd *Watchdog) Stop() { |
| 101 | + wd.stopMutex.Lock() |
| 102 | + wd.shouldStop = true |
| 103 | + if wd.cmd != nil && wd.cmd.Process != nil { |
| 104 | + log.Println("(INFO): Stopping process...") |
| 105 | + if err := wd.cmd.Process.Signal(syscall.SIGTERM); err != nil { |
| 106 | + log.Printf("(ERROR): Failed to stop process: %v\n", err) |
| 107 | + } |
| 108 | + } |
| 109 | + wd.stopMutex.Unlock() |
| 110 | + |
| 111 | + wd.doneBarrier.Wait() |
| 112 | + os.RemoveAll(filepath.Dir(wd.pidFile)) |
| 113 | + log.Println("(INFO): Watchdog stopped.") |
| 114 | +} |
| 115 | + |
| 116 | +// handleSignals listens for OS signals and stops the Watchdog gracefully. |
| 117 | +func (wd *Watchdog) handleSignals(ctx context.Context, cancel context.CancelFunc) { |
| 118 | + signalChan := make(chan os.Signal, 1) |
| 119 | + signal.Notify(signalChan, syscall.SIGINT, syscall.SIGTERM) |
| 120 | + |
| 121 | + select { |
| 122 | + case <-signalChan: |
| 123 | + log.Println("(INFO): Received stop signal.") |
| 124 | + wd.Stop() |
| 125 | + cancel() |
| 126 | + case <-ctx.Done(): |
| 127 | + return |
| 128 | + } |
| 129 | +} |
| 130 | + |
| 131 | +// writePIDToFile writes the PID of the process to a file. |
| 132 | +func (wd *Watchdog) writePIDToFile() error { |
| 133 | + if wd.cmd == nil || wd.cmd.Process == nil { |
| 134 | + return errors.New("process is not running") |
| 135 | + } |
| 136 | + |
| 137 | + pid := wd.cmd.Process.Pid |
| 138 | + pidData := fmt.Sprintf("%d", pid) |
| 139 | + |
| 140 | + dir := filepath.Dir(wd.pidFile) |
| 141 | + if err := os.MkdirAll(dir, os.ModePerm); err != nil { |
| 142 | + return err |
| 143 | + } |
| 144 | + |
| 145 | + file, err := os.Create(wd.pidFile) |
| 146 | + if err != nil { |
| 147 | + return fmt.Errorf("failed to create PID file: %v", err) |
| 148 | + } |
| 149 | + defer file.Close() |
| 150 | + |
| 151 | + _, err = file.WriteString(pidData) |
| 152 | + if err != nil { |
| 153 | + return err |
| 154 | + } |
| 155 | + |
| 156 | + log.Printf("(INFO): PID %d written to %s\n", pid, wd.pidFile) |
| 157 | + return nil |
| 158 | +} |
0 commit comments