diff --git a/cmd/agent.go b/cmd/agent.go index 94b206a..bc0aa07 100644 --- a/cmd/agent.go +++ b/cmd/agent.go @@ -20,8 +20,7 @@ const pidDir = "/tmp/tplagent" const pidFilename = "agent.pid" func startAgent(ctx context.Context, configFilePath string) error { - pid := os.Getpid() - writePID(pid) + writePID(filepath.Join(pidDir, pidFilename)) defer func() { _ = os.Remove(fmt.Sprintf("%s/%s", pidDir, pidFilename)) }() @@ -78,11 +77,11 @@ func newLogger(fmt string, level slog.Level) *slog.Logger { } -func writePID(pid int) { +func writePID(path string) { + pid := os.Getpid() if err := os.MkdirAll(pidDir, 0755); err != nil { return } - fullPath := filepath.Join(pidDir, pidFilename) bs := []byte(strconv.Itoa(pid)) - _ = os.WriteFile(fullPath, bs, 0755) + _ = os.WriteFile(path, bs, 0755) } diff --git a/cmd/cli.go b/cmd/cli.go index f7f5228..174d7cc 100644 --- a/cmd/cli.go +++ b/cmd/cli.go @@ -7,8 +7,12 @@ import ( "fmt" "github.com/shubhang93/tplagent/internal/config" "io" + "os" + "path/filepath" "runtime" + "strconv" "strings" + "syscall" ) const usage = `usage: @@ -69,9 +73,34 @@ Go Runtime: %s` if err != nil { return err } + case "reload": + pidFilePath := filepath.Join(pidDir, pidFilename) + return reload(pidFilePath) default: return errors.New(usage) } return nil +} + +func reload(pidFilePath string) error { + contents, err := os.ReadFile(pidFilePath) + if err != nil { + return err + } + + pid, err := strconv.Atoi(string(contents)) + if err != nil { + return fmt.Errorf("error converting PID:%w", err) + } + proc, err := os.FindProcess(pid) + if err != nil { + return fmt.Errorf("proc find err:%w", err) + } + + err = proc.Signal(syscall.SIGHUP) + if err != nil { + return fmt.Errorf("sig send err:%w", err) + } + return nil } diff --git a/cmd/cli_test.go b/cmd/cli_test.go index eda57fc..7f007a1 100644 --- a/cmd/cli_test.go +++ b/cmd/cli_test.go @@ -12,7 +12,9 @@ import ( "github.com/shubhang93/tplagent/internal/fatal" "log/slog" "os" + "os/signal" "strings" + "syscall" "testing" "time" ) @@ -206,4 +208,30 @@ written from exec } }) + + t.Run("test reload", func(t *testing.T) { + tmp := t.TempDir() + sighup, cancel := signal.NotifyContext(context.Background(), syscall.SIGHUP) + defer cancel() + + sighupReceived := make(chan bool, 1) + go func() { + <-sighup.Done() + sighupReceived <- true + }() + + pidPath := tmp + "/agent.pid" + + writePID(pidPath) + + err := reload(pidPath) + if err != nil { + t.Error(err) + return + } + + if rcvd := <-sighupReceived; !rcvd { + t.Errorf("SIGHUP not received") + } + }) }