Skip to content

Commit

Permalink
adds tests for reload
Browse files Browse the repository at this point in the history
  • Loading branch information
shubhang93 committed May 14, 2024
1 parent f8297f6 commit 8b302a6
Show file tree
Hide file tree
Showing 3 changed files with 61 additions and 5 deletions.
9 changes: 4 additions & 5 deletions cmd/agent.go
Original file line number Diff line number Diff line change
Expand Up @@ -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))
}()
Expand Down Expand Up @@ -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)
}
29 changes: 29 additions & 0 deletions cmd/cli.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,12 @@ import (
"fmt"
"github.com/shubhang93/tplagent/internal/config"
"io"
"os"
"path/filepath"
"runtime"
"strconv"
"strings"
"syscall"
)

const usage = `usage:
Expand Down Expand Up @@ -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
}
28 changes: 28 additions & 0 deletions cmd/cli_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,9 @@ import (
"github.com/shubhang93/tplagent/internal/fatal"
"log/slog"
"os"
"os/signal"
"strings"
"syscall"
"testing"
"time"
)
Expand Down Expand Up @@ -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")
}
})
}

0 comments on commit 8b302a6

Please sign in to comment.