From 897675d529dd42307f2c7384c520bad321c69904 Mon Sep 17 00:00:00 2001 From: asandikci Date: Wed, 2 Aug 2023 23:07:43 +0300 Subject: [PATCH] feat: initialize a basic go daemon --- cmd/ahenkd-go/ahenkd-go.go | 78 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 cmd/ahenkd-go/ahenkd-go.go diff --git a/cmd/ahenkd-go/ahenkd-go.go b/cmd/ahenkd-go/ahenkd-go.go new file mode 100644 index 0000000..4722b3b --- /dev/null +++ b/cmd/ahenkd-go/ahenkd-go.go @@ -0,0 +1,78 @@ +package main + +import ( + "log" + "os" + "syscall" + "time" + + "github.com/sevlyar/go-daemon" + "golang.org/x/exp/slices" +) + +const PidFile = "/run/ahenkd-go.pid" +const ExecutablePath = "/usr/bin/ahenkd-go" +const ConfDir = "/etc/ahenk-go/" + +// FIXME there isn't any difference with Stop() function +// TODO There can be a Start() function in it but start function doesnt work properly right now +func Restart(pid, signal int) { + Stop(pid, signal) +} + +// Stop Ahenkd Daemon with a specific PID (running from second copy) +// do not forget to use also os.Exit() when using in ExecStop +func Stop(pid, signal int) { + log.Println("Stop Signal Caught") + + // FILLME what you want to do before stopping daemon? + + if err := syscall.Kill(pid, syscall.Signal(signal)); err == nil { + log.Printf("Ahenk Daemon with pid number %v Successfully stopped", pid) // TODO Also log to /etc/ahenk-go/ahenkd.log + } else { + log.Fatal(err) + } +} + +// Main Function that starts daemon and controls arguments +func main() { + if len(os.Args) == 2 && slices.Contains([]string{"start", "stop", "restart"}, os.Args[1]) { + switch os.Args[1] { + case "start": + cntxt := &daemon.Context{ + PidFileName: PidFile, + PidFilePerm: 0644, + LogFileName: ConfDir + "ahenkd.log", + LogFilePerm: 0640, + WorkDir: ConfDir, + Umask: 027, + Args: []string{ExecutablePath, "start"}, + } + d, err := cntxt.Reborn() + if err != nil { + log.Fatal("Daemon Reborn ERROR:", err) + } + if d != nil { + return + } + defer cntxt.Release() + log.Println("- - - - - - - - - - - - - - - - - -") + log.Print("Daemon Succesfully Started") + case "stop": + i, _ := daemon.ReadPidFile(PidFile) + Stop(i, 15) + os.Exit(0) + case "restart": + i, _ := daemon.ReadPidFile(PidFile) + Restart(i, 15) + os.Exit(0) + } + } + + for { + // NEXT Usage + log.Println("Working on it") + time.Sleep(2 * time.Second) + } + +}