Skip to content

Commit

Permalink
fleetd: prevent to run more than one fleetd deamon
Browse files Browse the repository at this point in the history
Add /var/run/fleet.pid to prevent running more than
one fleetd deamon

Fixes coreos#1220
  • Loading branch information
wuqixuan committed Mar 4, 2015
1 parent 7b9a90d commit 50ead54
Showing 1 changed file with 36 additions and 0 deletions.
36 changes: 36 additions & 0 deletions fleetd/fleet.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,10 @@ import (
"encoding/json"
"flag"
"fmt"
"io/ioutil"
"os"
"os/signal"
"strconv"
"strings"
"syscall"

Expand All @@ -35,6 +37,7 @@ import (

const (
DefaultConfigFile = "/etc/fleet/fleet.conf"
PidFile = "/var/run/fleet.pid"
)

func main() {
Expand All @@ -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)
Expand Down Expand Up @@ -105,6 +113,7 @@ func main() {
log.Infof("Gracefully shutting down")
srv.Stop()
srv.Purge()
removePidFile(PidFile)
os.Exit(0)
}

Expand Down Expand Up @@ -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 {
Expand Down

0 comments on commit 50ead54

Please sign in to comment.