diff --git a/fleetd/fleet.go b/fleetd/fleet.go index 794fed53d..7a4e670f8 100644 --- a/fleetd/fleet.go +++ b/fleetd/fleet.go @@ -18,8 +18,10 @@ import ( "encoding/json" "flag" "fmt" + "io/ioutil" "os" "os/signal" + "strconv" "strings" "syscall" @@ -35,6 +37,7 @@ import ( const ( DefaultConfigFile = "/etc/fleet/fleet.conf" + PidFile = "/var/run/fleet.pid" ) func main() { @@ -53,6 +56,11 @@ func main() { os.Exit(0) } + if err := createPidFile(PidFile); err != nil { + fmt.Println(err) + os.Exit(1) + } + log.Infof("Starting fleetd version %v", version.Version) cfgset := flag.NewFlagSet("fleet", flag.ExitOnError) @@ -105,6 +113,7 @@ func main() { log.Infof("Gracefully shutting down") srv.Stop() srv.Purge() + removePidFile(PidFile) os.Exit(0) } @@ -213,6 +222,33 @@ func listenForSignals(sigmap map[os.Signal]func()) { } } +func createPidFile(pidfile string) error { + if pidstring, err := ioutil.ReadFile(pidfile); err == nil { + pid, err := strconv.Atoi(string(pidstring)) + if err == nil { + if _, err := os.Stat(fmt.Sprintf("/proc/%d/", pid)); err == nil { + return fmt.Errorf("pid file found, ensure fleetd is not running or delete %s", pidfile) + } + } + } + + file, err := os.Create(pidfile) + if err != nil { + return err + } + + defer file.Close() + + _, err = fmt.Fprintf(file, "%d", os.Getpid()) + return err +} + +func removePidFile(pidfile string) { + if err := os.Remove(pidfile); err != nil { + log.Error("Error removing %s: %s", pidfile, err) + } +} + type stringSlice []string func (f *stringSlice) Set(value string) error {