forked from codeskyblue/gosuv
/
client.go
421 lines (348 loc) · 8.53 KB
/
client.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
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net"
"net/http"
"net/url"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"syscall"
log "github.com/cihub/seelog"
_ "github.com/shurcooL/vfsgen"
"github.com/urfave/cli"
)
type Client struct {
UnixClient bool
HTTPClient bool
Addr string
User string
Password string
Action map[string]ActionMap
ProgramFile string
UnixHTTP http.Client
}
type ActionMap struct {
Uri string
Method string
}
func NewClient() *Client {
unixServer := strings.HasPrefix(Cfg.Client.ServerURL, "unix://")
httpServer := strings.HasPrefix(Cfg.Client.ServerURL, "http://")
if !(unixServer || httpServer) {
fmt.Printf("Please check client configure, ex: unix://%s or http://ip:port\n", DefaultSockFile)
log.Criticalf("client config is error , %v\n", Cfg.Client.ServerURL)
os.Exit(-1)
}
clientAddr := strings.Split(Cfg.Client.ServerURL, "//")
addr := clientAddr[1]
cl := &Client{
UnixClient: unixServer,
HTTPClient: httpServer,
User: Cfg.Client.Username,
Password: Cfg.Client.Password,
}
if CfgDir == "" {
cl.ProgramFile = filepath.Join("./", DefaultProgramFile)
} else {
cl.ProgramFile = filepath.Join(CfgDir, DefaultProgramFile)
}
if httpServer {
addrs := strings.Split(addr, ":")
ipAddr := addrs[0]
portAddr := addrs[1]
if ipAddr == "" {
cl.Addr = "http://127.0.0.1" + ":" + portAddr
}
} else if unixServer {
//sockfile
cl.Addr = "http://unix"
sockFile := addr
if sockFile == "" {
sockFile = DefaultSockFile
}
cl.UnixHTTP = http.Client{
Transport: &http.Transport{
DialContext: func(_ context.Context, _, _ string) (net.Conn, error) {
return net.Dial("unix", sockFile)
},
},
}
} else {
fmt.Println("notice: only can use 'kill' command")
}
//注册Client的方法
// <actions> <rui> <method>
actions := make(map[string]ActionMap)
actions["shutdown"] = ActionMap{Uri: "/api/shutdown", Method: "POST"}
actions["reload"] = ActionMap{Uri: "/api/reload", Method: "POST"}
actions["status"] = ActionMap{Uri: "/api/status", Method: "GET"}
actions["addProgram"] = ActionMap{Uri: "/api/programs", Method: "POST"}
actions["getProgramStatus"] = ActionMap{Uri: "/api/programs", Method: "GET"}
actions["getProgram"] = ActionMap{Uri: "/api/programs/", Method: "GET"}
actions["delProgram"] = ActionMap{Uri: "/api/programs/", Method: "DELETE"}
actions["programs"] = ActionMap{Uri: "/api/programs/", Method: "POST"}
cl.Action = actions
return cl
}
/*
programs相关指令
*/
// server status
func actionStatus(c *cli.Context) error {
request, _ := http.NewRequest(cl.Action["status"].Method, cl.Addr+cl.Action["status"].Uri, nil)
request.SetBasicAuth(cl.User, cl.Password)
var resp *http.Response
var err error
if cl.UnixClient {
resp, err = cl.UnixHTTP.Do(request)
} else {
resp, err = http.DefaultClient.Do(request)
}
if err != nil {
return err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
var serverStatus JSONResponse
err = json.Unmarshal(body, &serverStatus)
if err != nil {
return errors.New("json loads error: " + string(body))
}
if serverStatus.Status != 0 {
return fmt.Errorf("server status is %+v,%+v\n", serverStatus.Status, serverStatus.Value)
}
fmt.Println(serverStatus.Value)
return nil
}
//programs status
func actionProgramStatus(c *cli.Context) error {
var programs = make([]struct {
Program Program `json:"program"`
Status string `json:"status"`
}, 0)
request, _ := http.NewRequest(cl.Action["getProgramStatus"].Method, cl.Addr+cl.Action["getProgramStatus"].Uri, nil)
request.SetBasicAuth(cl.User, cl.Password)
var resp *http.Response
var err error
if cl.UnixClient {
resp, err = cl.UnixHTTP.Do(request)
} else {
resp, err = http.DefaultClient.Do(request)
}
if err != nil {
return err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
err = json.Unmarshal(body, &programs)
if err != nil {
return errors.New("json loads error: " + string(body))
}
format := "%-23s\t%-8s\n"
fmt.Printf(format, "PROGRAM NAME", "STATUS")
for _, p := range programs {
fmt.Printf(format, p.Program.Name, p.Status)
}
return nil
}
func actionStart(c *cli.Context) (err error) {
name := c.Args().First()
success, err := programOperate("start", name)
if err != nil {
return
}
if success {
fmt.Println(name, "Started")
} else {
fmt.Println(name, "Start failed")
}
return nil
}
func actionStop(c *cli.Context) (err error) {
name := c.Args().First()
success, err := programOperate("stop", name)
if err != nil {
return
}
if !success {
fmt.Println(name, "Stop failed")
}
return nil
}
// cmd: <start|stop>
func programOperate(cmd, name string) (success bool, err error) {
request, _ := http.NewRequest(cl.Action["programs"].Method, cl.Addr+cl.Action["programs"].Uri+name+"/"+cmd, nil)
request.SetBasicAuth(Cfg.Server.Auth.User, Cfg.Server.Auth.Password)
var resp *http.Response
if cl.UnixClient {
resp, err = cl.UnixHTTP.Do(request)
} else {
resp, err = http.DefaultClient.Do(request)
}
if err != nil {
return false, err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return false, err
}
var v = struct {
Status int `json:"status"`
}{}
err = json.Unmarshal(body, &v)
if err != nil {
return false, errors.New("json loads error: " + string(body))
}
success = v.Status == 0
return success, nil
}
/*
gosuv server相关操作指令
*/
func actionShutdown(c *cli.Context) error {
ret, err := postForm(cl.Addr+cl.Action["shutdown"].Uri, nil)
if err != nil {
return err
}
fmt.Println(ret.Value)
return nil
}
func actionRestart(c *cli.Context) error {
fmt.Println("shutdown server...")
actionShutdown(c)
fmt.Println("start server..")
ser := NewSer()
ser.startServer(false)
return nil
}
func actionReload(c *cli.Context) error {
ret, err := postForm(cl.Addr+cl.Action["reload"].Uri, nil)
if err != nil {
return err
}
fmt.Println(ret.Value)
return nil
}
/*
命令行
*/
//查看gosuv版本
func actionVersion(c *cli.Context) error {
fmt.Printf("gosuv version %s\n", Version)
return nil
}
//测试配置文件
func actionConfigTest(c *cli.Context) error {
if _, _, err := newSupervisorHandler(); err != nil {
return err
}
fmt.Println("test is successful")
return nil
}
//编辑programs.yml配置文件
func actionEdit(c *cli.Context) error {
cmd := exec.Command("vim", cl.ProgramFile)
cmd.Stdout = os.Stdout
cmd.Stdin = os.Stdin
cmd.Stderr = os.Stderr
return cmd.Run()
}
//查看gosuv server状态 使用server的配置.
func actionServerStatus() error {
request, _ := http.NewRequest("GET", cl.Addr+"/api/status", nil)
request.SetBasicAuth(Cfg.Server.Auth.User, Cfg.Server.Auth.Password)
var resp *http.Response
var err error
if cl.UnixClient {
resp, err = cl.UnixHTTP.Do(request)
} else if cl.HTTPClient {
resp, err = http.DefaultClient.Do(request)
} else {
return fmt.Errorf("no client configure %+v\n", cl)
}
if err != nil {
return err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
var ret JSONResponse
err = json.Unmarshal(body, &ret)
if err != nil {
return errors.New("json loads error: " + string(body))
}
if ret.Status != 0 {
return fmt.Errorf("%v", ret.Value)
}
return nil
}
func postForm(urlPath string, data url.Values) (r *JSONResponse, err error) {
request, err := http.NewRequest("POST", urlPath, strings.NewReader(data.Encode()))
if err != nil {
return r, err
}
request.SetBasicAuth(cl.User, cl.Password)
var resp *http.Response
if cl.UnixClient {
resp, err = cl.UnixHTTP.Do(request)
} else {
resp, err = http.DefaultClient.Do(request)
}
if err != nil {
return r, err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return r, err
}
err = json.Unmarshal(body, &r)
if err != nil {
return r, fmt.Errorf("POST %v %v", strconv.Quote(urlPath), string(body))
}
return r, nil
}
// 从pid file读取pid进行kill操作.
func actionKill(c *cli.Context) error {
//if actionServerStatus() != nil {
// fmt.Println("server is not running.")
// return nil
//}
pidFile := Cfg.Server.PidFile
if Cfg.Server.PidFile == "" {
pidFile = DefaultPidFile
}
fi, err := os.Open(pidFile)
if err != nil {
return err
}
defer fi.Close()
fd, err := ioutil.ReadAll(fi)
if err != nil {
return err
}
pid, err := strconv.Atoi(string(fd))
if err != nil {
return err
}
if err := syscall.Kill(pid, syscall.SIGQUIT); err != nil {
return err
}
return nil
}