Skip to content

Commit

Permalink
feat: Add support for pidfile
Browse files Browse the repository at this point in the history
Signed-off-by: Shubharanshu Mahapatra <[email protected]>
  • Loading branch information
Shubhranshu153 committed Oct 31, 2024
1 parent 65fbf5a commit dfb9e1c
Showing 1 changed file with 27 additions and 0 deletions.
27 changes: 27 additions & 0 deletions cmd/finch-daemon/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import (
"net/http"
"os"
"os/signal"
"path/filepath"
"strings"
"sync"
"syscall"
Expand All @@ -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"
Expand All @@ -34,6 +36,7 @@ const (
defaultFinchAddr = "/run/finch.sock"
defaultNamespace = "finch"
defaultConfigPath = "/etc/finch/finch.toml"
defaultPidFile = "/run/finch.pid"
)

type DaemonOptions struct {
Expand All @@ -42,6 +45,7 @@ type DaemonOptions struct {
socketOwner int
debugAddress string
configPath string
PidFile string
}

var options = new(DaemonOptions)
Expand All @@ -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)
Expand All @@ -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), 0o644); 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 {
Expand Down

0 comments on commit dfb9e1c

Please sign in to comment.