diff --git a/llmongo.go b/llmongo.go index d92ff02..9c24c3b 100644 --- a/llmongo.go +++ b/llmongo.go @@ -8,6 +8,8 @@ import ( "gopkg.in/mgo.v2" "os" // "gopkg.in/mgo.v2/bson" + "bytes" + "io/ioutil" "log" "path" "path/filepath" @@ -17,14 +19,17 @@ import ( ) type Options struct { - MongoUri string - RedisUri string - rdb *redis.Client - mdb *mgo.Session - ll *mgo.Collection - RedisTTL time.Duration - LogFile string - Version bool + MongoUri string + RedisUri string + rdb *redis.Client + mdb *mgo.Session + ll *mgo.Collection + RedisTTL time.Duration + CurrentPath string + Exe string + LogFile string + PIDFile string + Version bool } type MongoLogin struct { @@ -60,14 +65,15 @@ func usage() { } 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 { log.Fatal(err) } - opts.LogFile = path.Join(current, opts.LogFile) - - // fmt.Println(opts.LogFile) + opts.LogFile = path.Join(opts.CurrentPath, opts.LogFile) + opts.PIDFile = path.Join(opts.CurrentPath, "run", path.Base(os.Args[0])+".pid") + opts.Exe = path.Base(os.Args[0]) flag.StringVar(&opts.MongoUri, "m", opts.MongoUri, "Mongodb") flag.StringVar(&opts.RedisUri, "r", opts.RedisUri, "Redis") @@ -95,6 +101,26 @@ func connectMongo() { 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() { flag.Usage = usage flag.Parse() @@ -104,6 +130,22 @@ func main() { 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) if err != nil { fmt.Println("Log file error: ", err.Error())