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 May 17, 2015
1 parent f1d86c7 commit e23b540
Showing 1 changed file with 43 additions and 0 deletions.
43 changes: 43 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 @@ -61,6 +64,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 @@ -113,6 +121,7 @@ func main() {
log.Infof("Gracefully shutting down")
srv.Stop()
srv.Purge()
removePidFile(PidFile)
os.Exit(0)
}

Expand Down Expand Up @@ -221,6 +230,40 @@ 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 {
filename := fmt.Sprintf("/proc/%d/comm", pid)
if _, err := os.Stat(filename); err == nil {
comm, err := ioutil.ReadFile(filename)

// The last char of /proc/%d/comm is '0x0A', so need trim it
if err == nil && strings.EqualFold(string(comm[0:len(comm)-1]), "fleetd") == true {
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 e23b540

Please sign in to comment.