forked from topfreegames/apm
-
Notifications
You must be signed in to change notification settings - Fork 65
/
pmgo.go
254 lines (207 loc) · 6.74 KB
/
pmgo.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
/*
PMGO is a lightweight process manager written in Golang for Golang applications. It helps you keep all of your applications alive forever, if you want to. You can also reload, start, stop, delete and query status on the fly.
PMGO also provide a way to start a process by compiling a Golang project source code.
The main PMGO module is the Master module, it's the glue that keep everything running as it should be.
If you need to use the remote version of PMGO, take a look at RemoteMaster on Master package.
To use the remote version of PMGO, use:
- remoteServer := master.StartRemoteMasterServer(dsn, configFile)
It will start a remote master and return the instance.
To make remote requests, use the Remote Client by instantiating using:
- remoteClient, err := master.StartRemoteClient(dsn, timeout)
It will start the remote client and return the instance so you can use to initiate requests, such as:
- remoteClient.StartGoBin(sourcePath, name, keepAlive, args)
*/
package main
import (
"sync"
"github.com/struCoder/pmgo/lib/cli"
"github.com/struCoder/pmgo/lib/master"
"gopkg.in/alecthomas/kingpin.v2"
"github.com/sevlyar/go-daemon"
"os"
"os/signal"
"path"
"path/filepath"
"syscall"
"fmt"
"time"
log "github.com/sirupsen/logrus"
)
var (
app = kingpin.New("pmgo", "Aguia Process Manager.")
dns = app.Flag("dns", "TCP Dns host.").Default(":9876").String()
timeout = 30 * time.Second
serveStop = app.Command("kill", "Kill daemon pmgo.")
serveStopConfigFile = serveStop.Flag("config-file", "Config file location").String()
serve = app.Command("serve", "Create pmgo daemon.")
serveConfigFile = serve.Flag("config-file", "Config file location").String()
resurrect = app.Command("resurrect", "Resurrect all previously save processes.")
start = app.Command("start", "start and daemonize an app.")
startSourcePath = start.Arg("start go file", "go file.").Required().String()
startName = start.Arg("name", "Process name.").Required().String()
binFile = start.Arg("binary", "compiled golang file").Bool()
startKeepAlive = true
startArgs = start.Flag("args", "External args.").Strings()
restart = app.Command("restart", "Restart a process.")
restartName = restart.Arg("name", "Process name.").Required().String()
stop = app.Command("stop", "Stop a process.")
stopName = stop.Arg("name", "Process name.").Required().String()
delete = app.Command("delete", "Delete a process.")
deleteName = delete.Arg("name", "Process name.").Required().String()
save = app.Command("save", "Save a list of processes onto a file.")
status = app.Command("list", "Get pmgo list.")
version = app.Command("version", "get version")
currentVersion = "0.6.1"
info = app.Command("info", "Describe importance parameters of a process id")
infoName = info.Arg("name", "process name").Required().String()
)
func main() {
switch kingpin.MustParse(app.Parse(os.Args[1:])) {
case serveStop.FullCommand():
checkRemoteMasterServer()
cli := cli.InitCli(*dns, timeout)
cli.DeleteAllProcess()
stopRemoteMasterServer()
case serve.FullCommand():
log.Warn("Server will auto start and this command will be delete")
startRemoteMasterServer()
case resurrect.FullCommand():
fmt.Println("This feature will not support. sorry")
case start.FullCommand():
checkRemoteMasterServer()
cli := cli.InitCli(*dns, timeout)
cli.StartGoBin(*startSourcePath, *startName, startKeepAlive, *startArgs, *binFile)
cli.Status()
case restart.FullCommand():
checkRemoteMasterServer()
cli := cli.InitCli(*dns, timeout)
cli.RestartProcess(*restartName)
cli.Status()
case stop.FullCommand():
checkRemoteMasterServer()
cli := cli.InitCli(*dns, timeout)
cli.StopProcess(*stopName)
cli.Status()
case delete.FullCommand():
checkRemoteMasterServer()
cli := cli.InitCli(*dns, timeout)
cli.DeleteProcess(*deleteName)
case save.FullCommand():
cli := cli.InitCli(*dns, timeout)
cli.Save()
case status.FullCommand():
checkRemoteMasterServer()
cli := cli.InitCli(*dns, timeout)
cli.Status()
case version.FullCommand():
fmt.Println(currentVersion)
case info.FullCommand():
checkRemoteMasterServer()
cli := cli.InitCli(*dns, timeout)
cli.ProcInfo(*infoName)
}
}
func isDaemonRunning(ctx *daemon.Context) (bool, *os.Process, error) {
d, err := ctx.Search()
if err != nil {
return false, d, err
}
if err := d.Signal(syscall.Signal(0)); err != nil {
return false, d, err
}
return true, d, nil
}
func getCtx() *daemon.Context {
if *serveConfigFile == "" {
folderPath := os.Getenv("HOME")
*serveConfigFile = folderPath + "/.pmgo/config.toml"
os.MkdirAll(path.Dir(*serveConfigFile), 0755)
}
ctx := &daemon.Context{
PidFileName: path.Join(filepath.Dir(*serveConfigFile), "main.pid"),
PidFilePerm: 0644,
LogFileName: path.Join(filepath.Dir(*serveConfigFile), "main.log"),
LogFilePerm: 0640,
WorkDir: "./",
Umask: 027,
}
return ctx
}
// if RemoteMasterServer not running, just run
func checkRemoteMasterServer() {
ctx := getCtx()
if ok, _, _ := isDaemonRunning(ctx); !ok {
startRemoteMasterServer()
}
}
var waitedForSignal os.Signal
func waitForChildSignal(wg *sync.WaitGroup) {
signalChan := make(chan os.Signal, 1)
signal.Notify(signalChan, syscall.SIGUSR1, syscall.SIGUSR2)
wg.Add(1)
go func() {
waitedForSignal = <-signalChan
wg.Done()
}()
}
func kill(pid int, signal os.Signal) error {
p, err := os.FindProcess(pid)
if err != nil {
return err
}
defer p.Release()
return p.Signal(signal)
}
func startRemoteMasterServer() {
var wg sync.WaitGroup
waitForChildSignal(&wg)
ctx := getCtx()
if ok, _, _ := isDaemonRunning(ctx); ok {
log.Info("pmgo daemon is already running.")
return
}
d, err := ctx.Reborn()
if err != nil {
log.Fatalf("Failed to reborn daemon due to %+v.", err)
}
if d != nil {
wg.Wait()
if waitedForSignal == syscall.SIGUSR1 {
log.Info("daemon started")
return
}
} else {
kill(os.Getpid(), syscall.SIGUSR1)
wg.Wait()
defer ctx.Release()
}
log.Info("Starting remote master server...")
remoteMaster := master.StartRemoteMasterServer(*dns, *serveConfigFile)
// send signal to parent's process to kill goroutine
kill(os.Getppid(), syscall.SIGUSR1)
sigsKill := make(chan os.Signal, 1)
signal.Notify(sigsKill,
syscall.SIGINT,
syscall.SIGTERM,
syscall.SIGQUIT)
<-sigsKill
log.Info("Received signal to stop...")
err = remoteMaster.Stop()
if err != nil {
log.Fatal(err)
}
os.Exit(0)
}
func stopRemoteMasterServer() {
log.Info("pmgo stopping...")
ctx := getCtx()
if ok, p, _ := isDaemonRunning(ctx); ok {
if err := p.Signal(syscall.Signal(syscall.SIGQUIT)); err != nil {
log.Fatalf("Failed to kill daemon %v", err)
}
} else {
ctx.Release()
log.Info("instance is not running.")
}
log.Info("pmgo daemon terminated")
}