forked from yuanjack/champloo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcommand.go
689 lines (611 loc) · 15.1 KB
/
command.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
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
package main
import (
"encoding/json"
"encoding/xml"
"fmt"
"path/filepath"
"strings"
"sync"
"time"
)
type ShellSession struct {
SessionId string
CommandCount int
DeployId int
ExecuteResult map[Server]ShellCommand
IsComplete bool // 是否全部执行完成
IsCancel bool // 是否已取消
Success bool
ExecutedCmdNum int // 已执行的命令数
}
func NewShellSession(servers []Server, cmd ShellCommand, deployId int) *ShellSession {
new := ShellSession{}
new.CommandCount = cmd.Count()
new.SessionId = time.Now().Format("s_20060102150405")
new.ExecuteResult = map[Server]ShellCommand{}
new.DeployId = deployId
for _, server := range servers {
new.ExecuteResult[server] = cmd.Duplicate()
}
return &new
}
func (s *ShellSession) Run() {
for i := 0; i < s.CommandCount; i++ {
allServerDisable := true
for server, shell := range s.ExecuteResult {
// 已停用服务器不处理
if server.Disable {
continue
}
allServerDisable = false
cmd := shell.cmds[i]
cmd.Run(server.Ip, server.Port)
if cmd.Halt() {
s.IsComplete = true
s.Success = false
return
}
}
if allServerDisable || s.IsCancel {
s.IsComplete = true
s.Success = false
return
}
}
s.Success = true
s.IsComplete = true
}
func (s *ShellSession) ParallelRun() {
for i := 0; i < s.CommandCount; i++ {
isHalt := false
allServerDisable := true
var wg sync.WaitGroup
for server, shell := range s.ExecuteResult {
// 已停用服务器不处理
if server.Disable {
fmt.Println(server.Ip + "已停用.")
continue
}
wg.Add(1)
allServerDisable = false
srv := server
cmd := &shell.cmds[i]
go func() {
cmd.Run(srv.Ip, srv.Port)
if cmd.Halt() {
isHalt = true
}
defer wg.Done()
}()
}
wg.Wait()
// 判断是否有命令出错,需中断执行
if isHalt || allServerDisable || s.IsCancel {
s.IsComplete = true
s.Success = false
return
}
}
s.Success = true
s.IsComplete = true
}
func (s *ShellSession) Cancel() {
s.IsCancel = true
}
func (s *ShellSession) Output() string {
output := ""
isCompelete := s.IsComplete
// 命令都执行成功时,只显示最后一台服务器的输出信息
// 命令出错时,显示所有出错服务器输出信息
for i := 0; i < s.CommandCount; i++ {
allServerSuccess := true
allServerDisable := true
cmdstr := ""
outputstr := ""
errorstr := ""
for server, shell := range s.ExecuteResult {
// 已停用服务器不处理
if server.Disable {
continue
}
allServerDisable = false
cmd := shell.cmds[i]
if !cmd.HasExecute() {
continue
}
cmdstr = cmd.cmd
if cmd.success {
outputstr = cmd.output
} else {
errorstr += fmt.Sprintf("<span class='server'>[%s]</span> <span class='error'>%s</span>\n", server.Ip, cmd.output)
allServerSuccess = false
}
}
if allServerDisable {
output = "当前没有可用服务器需要部署."
break
}
if cmdstr != "" {
output += fmt.Sprintln("<i></i><span>" + cmdstr + "</span>")
output += fmt.Sprintln(outputstr)
}
if errorstr != "" {
output += fmt.Sprintln(errorstr)
}
if !allServerSuccess {
break
}
}
if output != "" {
serverstr := "[提示] 将更新到如下服务器:\n "
for server, _ := range s.ExecuteResult {
if server.Disable {
continue
}
serverstr += server.Ip + ","
}
disablestr := ""
for server, _ := range s.ExecuteResult {
if server.Disable {
disablestr += server.Ip + ","
}
}
if disablestr != "" {
disablestr = "\n 停用不更新的服务器:\n " + disablestr
}
output = "<span class='tip'>" + serverstr + disablestr + "</span>\n\n" + output
if isCompelete {
if s.Success {
output += "\n\n<span class='success'>已成功部署更新 :)</span>"
} else {
output += "\n\n<span class='error'>部署出错 !!已中止后面步骤执行.</span>"
}
}
}
return output
}
// 失败时删除已部署的所有文件
func (s *ShellSession) ClearDeploy(dest string) {
c := command{
cmd: fmt.Sprintf("rm -rf %s", dest),
canHalt: true,
}
for server, _ := range s.ExecuteResult {
// 已停用服务器忽略
if server.Disable {
continue
}
c.Run(server.Ip, server.Port)
if c.err != nil {
fmt.Println(c.err)
}
}
}
// 取git最近5个提交日志
func (s *ShellSession) RetrieveGitCommitLog(currentDir string) (CommitLog, error) {
cmd := `
cd ` + currentDir + `
git log --pretty=format:"%h@@@@%an@@@@%s@@@@%ad" -5
`
c := command{
cmd: cmd,
canHalt: true,
}
output := ""
for server, _ := range s.ExecuteResult {
// 已停用服务器忽略
if server.Disable {
continue
}
c.Run(server.Ip, server.Port)
if c.err == nil {
output = c.output
} else {
fmt.Println(c.err)
}
break
}
var commitLog CommitLog
var err error
if output != "" {
// 返回结果是分隔格式
commitLog.LogEntries = []CommitLogEntry{}
output = strings.TrimSpace(output)
lines := strings.Split(output, "\n")
for _, line := range lines {
arr := strings.Split(line, "@@@@")
commitDate, err := time.Parse("Mon Jan 2 15:04:05 2006 -0700", arr[3])
if err == nil {
commitLog.LogEntries = append(commitLog.LogEntries, CommitLogEntry{
Revision: arr[0],
Author: arr[1],
Msg: arr[2],
Date: commitDate,
})
} else {
fmt.Println(err)
commitLog.LogEntries = append(commitLog.LogEntries, CommitLogEntry{
Revision: arr[0],
Author: arr[1],
Msg: arr[2],
})
}
}
}
return commitLog, err
}
// 取svn最近5个提交日志
func (s *ShellSession) RetrieveSvnCommitLog(currentDir string, username string, password string) (CommitLog, error) {
cmd := `
cd %s
svn log --limit 5 --xml --username %s --password %s --no-auth-cache
`
c := command{
cmd: fmt.Sprintf(cmd, currentDir, username, password),
canHalt: true,
}
output := ""
for server, _ := range s.ExecuteResult {
// 已停用服务器忽略
if server.Disable {
continue
}
c.Run(server.Ip, server.Port)
if c.err == nil {
output = c.output
} else {
fmt.Println(c.err)
}
break
}
var commitLog CommitLog
var err error
if output != "" {
xmloutput := strings.TrimSpace(output)
err = xml.Unmarshal([]byte(xmloutput), &commitLog)
if err != nil {
fmt.Println(err)
}
}
return commitLog, err
}
type ShellCommand struct {
cmds []command
}
func NewShellCommand() *ShellCommand {
new := ShellCommand{}
new.cmds = []command{}
return &new
}
func (s *ShellCommand) Count() int {
return len(s.cmds)
}
func (s *ShellCommand) Mkdir(dir string) *ShellCommand {
c := command{
cmd: fmt.Sprintf("mkdir -p %s", dir),
canHalt: true,
}
s.cmds = append(s.cmds, c)
return s
}
func (s *ShellCommand) Rm(path string) *ShellCommand {
c := command{
cmd: fmt.Sprintf("rm -rf %s", path),
canHalt: true,
}
s.cmds = append(s.cmds, c)
return s
}
func (s *ShellCommand) Copy(src string, dest string) *ShellCommand {
cmd := `
if [ -d "%s" ]; then
cp -a %s/. %s
else
echo "复制失败,源目录%s不存在."
exit 1
fi
`
c := command{
cmd: fmt.Sprintf(cmd, src, src, dest, src),
canHalt: true,
}
s.cmds = append(s.cmds, c)
return s
}
func (s *ShellCommand) CopyNoHalt(src string, dest string) *ShellCommand {
cmd := `
if [ -d "%s" ]; then
cp -a %s/. %s
fi
`
c := command{
cmd: fmt.Sprintf(cmd, src, src, dest),
canHalt: false,
}
s.cmds = append(s.cmds, c)
return s
}
func (s *ShellCommand) Git(dest string, repo string) *ShellCommand {
c := command{
cmd: fmt.Sprintf("git clone %s %s", repo, dest),
canHalt: true,
}
s.cmds = append(s.cmds, c)
return s
}
func (s *ShellCommand) GitCopyUpdate(currentDir string, dest string, repo string) *ShellCommand {
cmd := `
if [ -d "%s" ]; then
cd %s
git remote update
else
git clone %s %s
fi
`
c := command{
cmd: fmt.Sprintf(cmd, currentDir, dest, repo, dest),
canHalt: true,
}
s.cmds = append(s.cmds, c)
return s
}
func (s *ShellCommand) GitUpdate(currentDir string, dest string, repo string) *ShellCommand {
cmd := `
if [ -d "%s" ]; then
cd %s
git remote update
else
git clone %s %s
fi
`
c := command{
cmd: fmt.Sprintf(cmd, currentDir, currentDir, repo, dest),
canHalt: true,
}
s.cmds = append(s.cmds, c)
return s
}
func (s *ShellCommand) Svn(dest string, repo string, username string, password string) *ShellCommand {
c := command{
cmd: fmt.Sprintf("svn checkout --username %s --password %s --no-auth-cache %s %s", username, password, repo, dest),
canHalt: true,
}
s.cmds = append(s.cmds, c)
return s
}
func (s *ShellCommand) SvnCopyUpdate(currentDir string, dest string, repo string, username string, password string) *ShellCommand {
cmd := `
if [ -d "%s" ]; then
cd %s
svn up --username %s --password %s --no-auth-cache
else
svn checkout --username %s --password %s --no-auth-cache %s %s
fi
`
c := command{
cmd: fmt.Sprintf(cmd, currentDir, dest, username, password, username, password, repo, dest),
canHalt: true,
}
s.cmds = append(s.cmds, c)
return s
}
func (s *ShellCommand) SvnUpdate(currentDir string, dest string, repo string, username string, password string) *ShellCommand {
cmd := `
if [ -d "%s" ]; then
cd %s
svn up --username %s --password %s --no-auth-cache
else
svn checkout --username %s --password %s --no-auth-cache %s %s
fi
`
c := command{
cmd: fmt.Sprintf(cmd, currentDir, currentDir, username, password, username, password, repo, dest),
canHalt: true,
}
s.cmds = append(s.cmds, c)
return s
}
// cp -Rpn 是为了同步共享目录中新增的文件,但不覆盖已有文件
func (s *ShellCommand) Shared(srcPath string, sharedDir string) *ShellCommand {
src := strings.TrimSpace(srcPath)
shared := strings.TrimSpace(sharedDir)
name := filepath.Base(src)
dest := fmt.Sprintf("%s/%s", shared, name)
cmd := `
if [ ! -d "%s" ]; then
if [ ! -d "%s" ]; then
echo "共享的目录%s不存在."
exit 1
fi
cp -Rpf --preserve=all %s %s
else
yes n|cp -RLi --preserve=all %s %s &>/dev/null
fi
rm -rf %s
ln -s %s %s
`
c := command{
cmd: fmt.Sprintf(cmd, dest, src, src, src, shared, src, shared, src, dest, src),
canHalt: true,
}
s.cmds = append(s.cmds, c)
return s
}
func (s *ShellCommand) ClearBackup(dir string, leaveNum int) *ShellCommand {
cmd := `
i=0
for p in $(ls -dr %s/*)
do
if [ -d "$p" ]; then
i=$(($i+1))
if [ $i -gt %d ]; then
rm -rf $p
echo "$p has been removed"
fi
fi
done
`
c := command{
cmd: fmt.Sprintf(cmd, dir, leaveNum),
canHalt: true,
}
s.cmds = append(s.cmds, c)
return s
}
func (s *ShellCommand) ExistDir(dir string) *ShellCommand {
cmd := `
if [ ! -d "%s" ]; then
echo "目录%s不存在."
exit 1
fi
`
c := command{
cmd: fmt.Sprintf(cmd, dir, dir),
canHalt: true,
}
s.cmds = append(s.cmds, c)
return s
}
func (s *ShellCommand) Rollback(src string, dest string) *ShellCommand {
cmd := `
if [ ! -d "%s" ]; then
echo "版本目录%s不存在."
exit 1
fi
ln -sfn %s %s
`
c := command{
cmd: fmt.Sprintf(cmd, src, src, src, dest),
canHalt: true,
}
s.cmds = append(s.cmds, c)
return s
}
func (s *ShellCommand) Exec(cmd string, workdir string) *ShellCommand {
c := command{
cmd: cmd,
workdir: workdir,
canHalt: true,
}
s.cmds = append(s.cmds, c)
return s
}
func (s *ShellCommand) Ln(src string, dest string) *ShellCommand {
c := command{
cmd: fmt.Sprintf("ln -sfn %s %s", src, dest),
canHalt: true,
}
s.cmds = append(s.cmds, c)
return s
}
func (s *ShellCommand) Intro(intro string) *ShellCommand {
if len(s.cmds) > 0 {
s.cmds[len(s.cmds)-1].intro = intro
}
return s
}
func (s *ShellCommand) Duplicate() ShellCommand {
sh := NewShellCommand()
for _, c := range s.cmds {
sh.cmds = append(sh.cmds, command{
cmd: c.cmd,
intro: c.intro,
output: c.output,
hasExecute: c.hasExecute,
success: c.success,
canHalt: c.canHalt,
err: c.err,
workdir: c.workdir,
})
}
return *sh
}
// 对shell命令的封装
type command struct {
cmd string // 需执行的命令
intro string // 命令介绍
output string // 执行命令结果
hasExecute bool // 是否已执行
success bool // 是否执行成功
canHalt bool // 命令执行失败是否挂起后面命令执行
err error // 执行错误
workdir string // 执行目录
}
func (c *command) Introduction() string {
return c.intro
}
func (c *command) HasExecute() bool {
return c.hasExecute
}
func (c *command) Output() string {
return c.output
}
func (c *command) Success() bool {
return c.success
}
func (c *command) Halt() bool {
if c.canHalt {
return !c.success || c.err != nil
}
return false
}
func (c *command) Error() error {
return c.err
}
func (c *command) Run(ip string, port int) {
cmd := strings.Replace(c.cmd, "\r\n", "\n", -1)
// 请求接口执行命令
jsonCmd := JsonCommand{
Dir: c.workdir,
Cmd: cmd,
}
url := fmt.Sprintf("http://%s:%d/run", ip, port)
body, statusCode, err := PostJson(url, jsonCmd)
if *debug {
fmt.Println("执行脚本:" + url)
fmt.Println(cmd)
fmt.Printf("执行结果:%d %v %s \n", statusCode, err, body)
fmt.Println()
}
if err != nil {
c.hasExecute = true
c.err = err
c.output = err.Error()
c.success = false
return
}
if statusCode != 200 {
c.hasExecute = true
c.err = fmt.Errorf("执行脚本请求出错.%s 状态码:%d 内容:%s", url, statusCode, body)
c.output = c.err.Error()
c.success = false
return
}
var result ActionMessage
err = json.Unmarshal([]byte(body), &result)
if err != nil {
c.hasExecute = true
c.err = err
c.success = false
return
}
c.hasExecute = true
c.success = result.Success
c.output = result.Data.(string)
if c.output == "" {
c.output = result.Message
}
}
type JsonCommand struct {
Dir string `json:"dir"`
Cmd string `json:"cmd"`
}
type CommitLog struct {
LogEntries []CommitLogEntry `xml:"logentry"`
}
type CommitLogEntry struct {
Revision string `xml:"revision,attr"`
Author string `xml:"author"`
Date time.Time `xml:"date"`
Msg string `xml:"msg"`
}