implementato la scrittura e il controllo del PID per verificare se e' gia' running

This commit is contained in:
Michele Fadda 2015-07-29 17:32:51 +02:00
parent 97e7801f0f
commit b51b7e4cf9

View file

@ -8,6 +8,8 @@ import (
"gopkg.in/mgo.v2" "gopkg.in/mgo.v2"
"os" "os"
// "gopkg.in/mgo.v2/bson" // "gopkg.in/mgo.v2/bson"
"bytes"
"io/ioutil"
"log" "log"
"path" "path"
"path/filepath" "path/filepath"
@ -17,14 +19,17 @@ import (
) )
type Options struct { type Options struct {
MongoUri string MongoUri string
RedisUri string RedisUri string
rdb *redis.Client rdb *redis.Client
mdb *mgo.Session mdb *mgo.Session
ll *mgo.Collection ll *mgo.Collection
RedisTTL time.Duration RedisTTL time.Duration
LogFile string CurrentPath string
Version bool Exe string
LogFile string
PIDFile string
Version bool
} }
type MongoLogin struct { type MongoLogin struct {
@ -60,14 +65,15 @@ func usage() {
} }
func init() { func init() {
current, err := filepath.Abs(filepath.Dir(os.Args[0])) var err error
opts.CurrentPath, err = filepath.Abs(filepath.Dir(os.Args[0]))
if err != nil { if err != nil {
log.Fatal(err) log.Fatal(err)
} }
opts.LogFile = path.Join(current, opts.LogFile) opts.LogFile = path.Join(opts.CurrentPath, opts.LogFile)
opts.PIDFile = path.Join(opts.CurrentPath, "run", path.Base(os.Args[0])+".pid")
// fmt.Println(opts.LogFile) opts.Exe = path.Base(os.Args[0])
flag.StringVar(&opts.MongoUri, "m", opts.MongoUri, "Mongodb") flag.StringVar(&opts.MongoUri, "m", opts.MongoUri, "Mongodb")
flag.StringVar(&opts.RedisUri, "r", opts.RedisUri, "Redis") flag.StringVar(&opts.RedisUri, "r", opts.RedisUri, "Redis")
@ -95,6 +101,26 @@ func connectMongo() {
opts.ll = opts.mdb.DB("dovecot").C("lastlogin") opts.ll = opts.mdb.DB("dovecot").C("lastlogin")
} }
func checkPID(bpid []byte) bool {
pid := strings.TrimRight(string(bpid), "\n")
fmt.Println("PID: ", pid)
bcmd, err := ioutil.ReadFile(path.Join("/proc", pid, "cmdline"))
if err != nil {
fmt.Println("cmdline error: ", err)
return false
}
cmd := bytes.Trim(bcmd, "\x00")
fmt.Println(string(cmd), opts.Exe)
if strings.Contains(string(cmd), opts.Exe) {
return true
}
return true
}
func writePID() {
}
func main() { func main() {
flag.Usage = usage flag.Usage = usage
flag.Parse() flag.Parse()
@ -104,6 +130,22 @@ func main() {
os.Exit(0) os.Exit(0)
} }
if bpid, err := ioutil.ReadFile(opts.PIDFile); err == nil && checkPID(bpid) {
fmt.Println("Running: ", string(bpid))
os.Exit(-6)
} else {
fpid, err := os.OpenFile(opts.PIDFile, os.O_WRONLY|os.O_CREATE, 0666)
if err != nil {
fmt.Println("PID file error: ", err.Error())
os.Exit(-5)
}
fpid.WriteString(strconv.Itoa(os.Getpid()))
fpid.Close()
}
defer os.Remove(opts.PIDFile)
fmt.Println(os.Stat(opts.PIDFile))
fs, err := os.OpenFile(opts.LogFile, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0666) fs, err := os.OpenFile(opts.LogFile, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0666)
if err != nil { if err != nil {
fmt.Println("Log file error: ", err.Error()) fmt.Println("Log file error: ", err.Error())