warrend init statup properly in /var/run and close and respect only one

instance
This commit is contained in:
Dan Ballard 2015-02-04 13:05:28 -08:00
parent e8db38d869
commit cf6a9c0a97
4 changed files with 68 additions and 13 deletions

View File

@ -18,7 +18,9 @@ clean:
install:
cp cmd/warren/warren /usr/bin
cp cmd/warrend/warrend /usr/bin
mkdir /var/run/warrend
uninstall:
rm /usr/bin/warren
rm /usr/bin/warrend
rmdir /var/run/warrend

View File

@ -49,5 +49,4 @@ func main() {
}
icmd.(*warren.Command).Exec(args[1:])
}

View File

@ -11,6 +11,8 @@ import (
"syscall"
)
var cmdSock net.Listener
type SockCommand struct {
warren.Command
Run func(cmd *SockCommand, c net.Conn, args ...string)
@ -52,19 +54,64 @@ func sockCmdHandle(c net.Conn) {
return
}
icmd.(*SockCommand).Exec(c, args[1:])
warren.WriteStringz(c, "echo: "+data)
}
// determine if warrend is already running
func checkRunning() bool {
if pfile, err := os.Open(warren.WarrendPidFile()); err == nil {
// pid file exists
var pid int
n, err := fmt.Fscanf(pfile, "%d", &pid)
if n == 0 || err != nil {
// read error
return false
}
// is there a runnign process with the pid?
err = syscall.Kill(pid, 0)
return err == nil
} else {
// pid file does not exist
return false
}
}
func initRunning() {
// rm old sock
os.Remove(warren.CmdSockAddr())
// drop down pid
pidfile, err := os.Create(warren.WarrendPidFile())
if err != nil {
log.Fatal("Could not create pidfile: ", warren.WarrendPidFile(), " : ", err)
}
pid := os.Getpid()
fmt.Fprintf(pidfile, "%d", pid)
pidfile.Close()
cmdSock, err = net.Listen(warren.CmdSockType(), warren.CmdSockAddr())
if err != nil {
fmt.Println(cmdSock)
Shutdown()
log.Fatal("Listen on sock error:", err)
}
}
func Shutdown() {
os.Remove(warren.WarrendPidFile())
if cmdSock != nil {
cmdSock.Close()
}
}
func main() {
warren.RegisterCommand(statusCmd)
if checkRunning() {
log.Fatal("warrend instance already running")
}
cmdSock, err := net.Listen(warren.CmdSockType(), warren.CmdSockAddr())
if cmdSock != nil {
defer cmdSock.Close()
}
if err != nil {
log.Fatal("Listen on sock error:", err)
}
initRunning()
warren.RegisterCommand(statusCmd)
// Handle signals
c := make(chan os.Signal, 1)
@ -76,16 +123,18 @@ func main() {
)
go func() {
_ = <-c
cmdSock.Close()
Shutdown()
}()
// Listen
for {
fd, err := cmdSock.Accept()
fmt.Println("accept")
if err != nil {
Shutdown()
log.Fatal("accpet error:", err)
}
go sockCmdHandle(fd)
}
Shutdown()
}

View File

@ -11,7 +11,8 @@ import (
)
var cmdSockType string = "unix"
var cmdSockAddr string = "/tmp/warrend.sock"
var cmdSockAddr string = "/var/run/warrend/warrend.sock"
var warrendPidFile string = "/var/run/warrend/warrend.pid"
func CmdSockType() string {
return cmdSockType
@ -21,6 +22,10 @@ func CmdSockAddr() string {
return cmdSockAddr
}
func WarrendPidFile() string {
return warrendPidFile
}
func GitHash() string {
hash, err := exec.Command("git", "rev-parse", "HEAD").Output()
if err != nil {