implementato la scrittura e il controllo del PID per verificare se e' gia' running
This commit is contained in:
parent
97e7801f0f
commit
b51b7e4cf9
1 changed files with 54 additions and 12 deletions
50
llmongo.go
50
llmongo.go
|
@ -8,6 +8,8 @@ import (
|
|||
"gopkg.in/mgo.v2"
|
||||
"os"
|
||||
// "gopkg.in/mgo.v2/bson"
|
||||
"bytes"
|
||||
"io/ioutil"
|
||||
"log"
|
||||
"path"
|
||||
"path/filepath"
|
||||
|
@ -23,7 +25,10 @@ type Options struct {
|
|||
mdb *mgo.Session
|
||||
ll *mgo.Collection
|
||||
RedisTTL time.Duration
|
||||
CurrentPath string
|
||||
Exe string
|
||||
LogFile string
|
||||
PIDFile string
|
||||
Version bool
|
||||
}
|
||||
|
||||
|
@ -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())
|
||||
|
|
Loading…
Add table
Reference in a new issue