From eda0654d2ab71c4481b9071e1516c71ea27b7ebd Mon Sep 17 00:00:00 2001 From: Shubharanshu Mahapatra Date: Thu, 10 Oct 2024 09:19:50 -0700 Subject: [PATCH] feat: Add support for pidfile Signed-off-by: Shubharanshu Mahapatra --- cmd/finch-daemon/main.go | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/cmd/finch-daemon/main.go b/cmd/finch-daemon/main.go index a9a6932..a2cb509 100644 --- a/cmd/finch-daemon/main.go +++ b/cmd/finch-daemon/main.go @@ -12,6 +12,7 @@ import ( "net/http" "os" "os/signal" + "path/filepath" "strings" "sync" "syscall" @@ -22,6 +23,7 @@ import ( _ "net/http/pprof" "github.com/coreos/go-systemd/v22/daemon" + "github.com/moby/moby/pkg/pidfile" "github.com/runfinch/finch-daemon/api/router" "github.com/runfinch/finch-daemon/pkg/flog" "github.com/runfinch/finch-daemon/version" @@ -34,6 +36,7 @@ const ( defaultFinchAddr = "/run/finch.sock" defaultNamespace = "finch" defaultConfigPath = "/etc/finch/finch.toml" + defaultPidFile = "/run/finch.pid" ) type DaemonOptions struct { @@ -42,6 +45,7 @@ type DaemonOptions struct { socketOwner int debugAddress string configPath string + pidFile string } var options = new(DaemonOptions) @@ -59,6 +63,7 @@ func main() { rootCmd.Flags().IntVar(&options.socketOwner, "socket-owner", -1, "Uid and Gid of the server socket") rootCmd.Flags().StringVar(&options.debugAddress, "debug-addr", "", "") rootCmd.Flags().StringVar(&options.configPath, "config-file", defaultConfigPath, "Daemon Config Path") + rootCmd.Flags().StringVar(&options.pidFile, "pidfile", defaultPidFile, "Pid file location") if err := rootCmd.Execute(); err != nil { log.Printf("got error: %v", err) log.Fatal(err) @@ -69,12 +74,34 @@ func runAdapter(cmd *cobra.Command, _ []string) error { return run(options) } +func handlePidFileOptions(options *DaemonOptions) error { + if options.pidFile != "" { + if err := os.MkdirAll(filepath.Dir(options.pidFile), 0o640); err != nil { + return fmt.Errorf("failed to create pidfile directory %s", err) + } + if err := pidfile.Write(options.pidFile, os.Getpid()); err != nil { + return fmt.Errorf("failed to start daemon, ensure finch daemon is not running or delete %s %s", options.pidFile, err) + } + } + return nil +} + func run(options *DaemonOptions) error { // This sets the log level of the dependencies that use logrus (e.g., containerd library). if options.debug { logrus.SetLevel(logrus.DebugLevel) } + defer func() { + if err := os.Remove(options.pidFile); err != nil { + logrus.Errorf("failed to remove pidfile %s", options.pidFile) + } + }() + + if err := handlePidFileOptions(options); err != nil { + return err + } + logger := flog.NewLogrus() r, err := newRouter(options, logger) if err != nil {