Merge pull request #80 from shunfei/feature/pid

Write pid to file, resolve #79
pull/81/head
Doflatango 2018-05-05 10:42:30 +08:00 committed by GitHub
commit 455025c5bb
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 48 additions and 1 deletions

View File

@ -55,6 +55,7 @@ type Conf struct {
Group string // 节点分组
Noticer string // 通知
PIDFile string
UUIDFile string
Ttl int64 // 节点超时时间,单位秒

View File

@ -21,5 +21,8 @@
"Mgo": "@extend:db.json",
"Mail": "@extend:mail.json",
"Security": "@extend:security.json",
"#comment": "PIDFile and UUIDFile just work for cronnode"
"#PIDFile": "Given a none-empty string to write a pid file to the specialed path, or leave it empty to do nothing"
"PIDFile": "/tmp/cronsun/cronnode_pid",
"UUIDFile": "/etc/cronsun/CRONSUN_UUID"
}

View File

@ -25,7 +25,8 @@ const (
type Node struct {
ID string `bson:"_id" json:"id"` // machine id
PID string `bson:"pid" json:"pid"` // 进程 pid
IP string `bson:"ip" json:"ip"` // node ip
PIDFile string `bson:"-" json:"-"`
IP string `bson:"ip" json:"ip"` // node ip
Hostname string `bson:"hostname" json:"hostname"`
Version string `bson:"version" json:"version"`

View File

@ -2,8 +2,11 @@ package node
import (
"fmt"
"io/ioutil"
"os"
"path"
"strconv"
"strings"
"time"
client "github.com/coreos/etcd/clientv3"
@ -56,6 +59,7 @@ func NewNode(cfg *conf.Conf) (n *Node, err error) {
Node: &cronsun.Node{
ID: uuid,
PID: strconv.Itoa(os.Getpid()),
PIDFile: strings.TrimSpace(cfg.PIDFile),
IP: ip.String(),
Hostname: hostname,
},
@ -101,9 +105,46 @@ func (n *Node) set() error {
}
n.lID = resp.ID
n.writePIDFile()
return nil
}
func (n *Node) writePIDFile() {
if len(n.PIDFile) == 0 {
return
}
filename := "cronnode_pid"
if !strings.HasSuffix(n.PIDFile, "/") {
filename = path.Base(n.PIDFile)
}
dir := path.Dir(n.PIDFile)
err := os.MkdirAll(dir, 0755)
if err != nil {
log.Errorf("Failed to write pid file: %s", err)
return
}
n.PIDFile = path.Join(dir, filename)
err = ioutil.WriteFile(n.PIDFile, []byte(n.PID), 0644)
if err != nil {
log.Errorf("Failed to write pid file: %s", err)
return
}
}
func (n *Node) removePIDFile() {
if len(n.PIDFile) == 0 {
return
}
if err := os.Remove(n.PIDFile); err != nil {
log.Warnf("Failed to remove pid file: %s", err)
}
}
// 断网掉线重新注册
func (n *Node) keepAlive() {
duration := time.Duration(n.ttl) * time.Second
@ -494,4 +535,5 @@ func (n *Node) Stop(i interface{}) {
n.Node.Del()
n.Client.Close()
n.Cron.Stop()
n.removePIDFile()
}