forked from yuanjack/champloo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
deploy.go
577 lines (481 loc) · 16.1 KB
/
deploy.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
package main
import (
"fmt"
"strconv"
"strings"
"time"
"github.com/go-martini/martini"
"github.com/martini-contrib/render"
)
// 默认发布
func ExecuteDeployDefault(username string, params martini.Params, r render.Render) {
executeDeploy("", username, params, r)
}
// 发布到开发场景(Dev)
func ExecuteDeployDev(username string, params martini.Params, r render.Render) {
executeDeploy("dev", username, params, r)
}
// 发布到产品场景(Prod)
func ExecuteDeployProd(username string, params martini.Params, r render.Render) {
executeDeploy("prod", username, params, r)
}
func executeDeploy(stage string, username string, params martini.Params, r render.Render) {
id, _ := strconv.Atoi(params["id"])
var conf SystemConfig
db.First(&conf, id)
if conf.Way == "update" {
executeDeployUpdate(stage, username, params, r)
return
}
if isDeploying(id) {
sendFailMsg(r, "另一部署进程正在进行中,请稍候.", nil)
return
}
workdir := conf.Path
switch stage {
case "dev":
workdir = strings.TrimSuffix(conf.Path, "/") + "/development"
case "prod":
workdir = strings.TrimSuffix(conf.Path, "/") + "/production"
default:
}
releaseDir := fmt.Sprintf("%s/releases", workdir)
sharedDir := fmt.Sprintf("%s/shared", workdir)
currentDir := fmt.Sprintf("%s/current", workdir)
tags := conf.Tags
version := time.Now().Format("20060102150405")
deploy := Deploy{
SystemId: id,
Stage: stage,
Operator: string(username),
Version: version,
}
err := db.Save(&deploy).Error
if err != nil {
sendFailMsg(r, "创建部署记录出错."+err.Error(), nil)
return
}
cmds := NewShellCommand()
// 1.创建部署目录
cmds.Mkdir(workdir).Mkdir(releaseDir).Mkdir(sharedDir)
// 2.创建新版本目录
versionDir := fmt.Sprintf("%s/%s", releaseDir, version)
cmds.Mkdir(versionDir)
// 3.checkout代码
if strings.Contains(conf.Repo, ".git") {
switch conf.Way {
case "copy":
cmds.CopyNoHalt(currentDir, versionDir)
// 删除旧共享目录,要不很容易因为共享目录代码冲突导致update不了
if strings.TrimSpace(conf.Shared) != "" {
paths := strings.Split(conf.Shared, "\n")
for _, path := range paths {
sharePath := strings.TrimSpace(path)
sharePath = strings.Replace(sharePath, "$path", versionDir, -1)
cmds.Rm(sharePath)
}
}
cmds.GitCopyUpdate(currentDir, versionDir, conf.Repo)
default:
cmds.Git(versionDir, conf.Repo)
}
} else {
switch conf.Way {
case "copy":
cmds.CopyNoHalt(currentDir, versionDir)
// 删除旧共享目录,要不很容易因为共享目录代码冲突导致update不了
if strings.TrimSpace(conf.Shared) != "" {
paths := strings.Split(conf.Shared, "\n")
for _, path := range paths {
sharePath := strings.TrimSpace(path)
sharePath = strings.Replace(sharePath, "$path", versionDir, -1)
cmds.Rm(sharePath)
}
}
cmds.SvnCopyUpdate(currentDir, versionDir, conf.Repo, conf.UserName, conf.Password)
default:
cmds.Svn(versionDir, conf.Repo, conf.UserName, conf.Password)
}
}
// 4.处理共享目录
if strings.TrimSpace(conf.Shared) != "" {
paths := strings.Split(conf.Shared, "\n")
for _, path := range paths {
sharePath := strings.TrimSpace(path)
src := strings.Replace(sharePath, "$path", versionDir, -1)
cmds.Shared(src, sharedDir)
}
}
// 5.清理备份版本
cmds.ClearBackup(releaseDir, conf.BackupNum)
// 6.TODO:测试?
// 7.执行部署上线前命令
if strings.TrimSpace(conf.BeforeCmd) != "" {
conf.BeforeCmd = strings.Replace(conf.BeforeCmd, "$path", versionDir, -1)
conf.BeforeCmd = strings.Replace(conf.BeforeCmd, "$share", sharedDir, -1)
conf.BeforeCmd = strings.Replace(conf.BeforeCmd, "$release", releaseDir, -1)
cmds.Exec(conf.BeforeCmd, versionDir)
}
// 执行对应场景上线前命令
if stage == "dev" && strings.TrimSpace(conf.DevBeforeCmd) != "" {
conf.DevBeforeCmd = strings.Replace(conf.DevBeforeCmd, "$path", versionDir, -1)
conf.DevBeforeCmd = strings.Replace(conf.DevBeforeCmd, "$share", sharedDir, -1)
conf.DevBeforeCmd = strings.Replace(conf.DevBeforeCmd, "$release", releaseDir, -1)
cmds.Exec(conf.DevBeforeCmd, versionDir)
}
if stage == "prod" && strings.TrimSpace(conf.ProdBeforeCmd) != "" {
conf.ProdBeforeCmd = strings.Replace(conf.ProdBeforeCmd, "$path", versionDir, -1)
conf.ProdBeforeCmd = strings.Replace(conf.ProdBeforeCmd, "$share", sharedDir, -1)
conf.ProdBeforeCmd = strings.Replace(conf.ProdBeforeCmd, "$release", releaseDir, -1)
cmds.Exec(conf.ProdBeforeCmd, versionDir)
}
// 8.把current软链接指向新版本
cmds.Ln(versionDir, currentDir)
// 11.执行部署后命令
if strings.TrimSpace(conf.AfterCmd) != "" {
conf.AfterCmd = strings.Replace(conf.AfterCmd, "$path", versionDir, -1)
conf.AfterCmd = strings.Replace(conf.AfterCmd, "$share", sharedDir, -1)
conf.AfterCmd = strings.Replace(conf.AfterCmd, "$release", releaseDir, -1)
cmds.Exec(conf.AfterCmd, versionDir)
}
// 执行对应场景上线后命令
if stage == "dev" && strings.TrimSpace(conf.DevAfterCmd) != "" {
conf.DevAfterCmd = strings.Replace(conf.DevAfterCmd, "$path", versionDir, -1)
conf.DevAfterCmd = strings.Replace(conf.DevAfterCmd, "$share", sharedDir, -1)
conf.DevAfterCmd = strings.Replace(conf.DevAfterCmd, "$release", releaseDir, -1)
cmds.Exec(conf.DevAfterCmd, versionDir)
}
if stage == "prod" && strings.TrimSpace(conf.ProdAfterCmd) != "" {
conf.ProdAfterCmd = strings.Replace(conf.ProdAfterCmd, "$path", versionDir, -1)
conf.ProdAfterCmd = strings.Replace(conf.ProdAfterCmd, "$share", sharedDir, -1)
conf.ProdAfterCmd = strings.Replace(conf.ProdAfterCmd, "$release", releaseDir, -1)
cmds.Exec(conf.ProdAfterCmd, versionDir)
}
// 取对应该tag的所有服务器
servers := getTagServers(tags)
session := NewShellSession(servers, *cmds, deploy.Id)
mutex.Lock()
sessions[id] = session
mutex.Unlock()
startTime := time.Now()
session.ParallelRun()
if !session.Success {
// 删除部署的文件夹
session.ClearDeploy(versionDir)
deploy.Stage = stage
deploy.Operator = string(username)
deploy.Status = -1
deploy.Output = session.Output()
deploy.ElapsedTime = int(time.Now().Sub(startTime).Seconds())
db.Save(&deploy)
sendFailMsg(r, "部署失败.", session.Output())
return
}
// 取commit日志
revision, commitLog := getCommitLog(session, id, stage, conf, currentDir)
deploy.Revision = revision
deploy.CommitLog = commitLog
// 去掉旧的部署的启用状态
db.Model(Deploy{}).Where(Deploy{SystemId: id, Stage: stage, Enable: true}).Update(map[string]interface{}{"enable": false})
deploy.Stage = stage
deploy.Operator = string(username)
deploy.Status = 1
deploy.Output = session.Output()
deploy.Enable = true
deploy.ElapsedTime = int(time.Now().Sub(startTime).Seconds())
db.Save(&deploy)
sendSuccessMsg(r, nil)
return
}
func executeDeployUpdate(stage string, username string, params martini.Params, r render.Render) {
id, _ := strconv.Atoi(params["id"])
if isDeploying(id) {
sendFailMsg(r, "另一部署进程正在进行中,请稍候.", nil)
return
}
var conf SystemConfig
db.First(&conf, id)
workdir := conf.Path
switch stage {
case "dev":
workdir = strings.TrimSuffix(conf.Path, "/") + "/development"
case "prod":
workdir = strings.TrimSuffix(conf.Path, "/") + "/production"
default:
}
releaseDir := fmt.Sprintf("%s/releases", workdir)
sharedDir := fmt.Sprintf("%s/shared", workdir)
currentDir := fmt.Sprintf("%s/current", workdir)
tags := conf.Tags
version := time.Now().Format("20060102150405")
var deploy Deploy
db.First(&deploy, Deploy{SystemId: id, Stage: stage, Enable: true})
if deploy.Id <= 0 {
deploy = Deploy{
SystemId: id,
Stage: stage,
Operator: string(username),
Version: version,
}
err := db.Save(&deploy).Error
if err != nil {
sendFailMsg(r, "创建部署记录出错."+err.Error(), nil)
return
}
} else {
version = deploy.Version
}
cmds := NewShellCommand()
// 1.创建部署目录
cmds.Mkdir(workdir).Mkdir(releaseDir).Mkdir(sharedDir)
// 2.创建新版本目录
versionDir := fmt.Sprintf("%s/%s", releaseDir, version)
cmds.Mkdir(versionDir)
// 3.checkout代码
if strings.Contains(conf.Repo, ".git") {
cmds.GitUpdate(currentDir, versionDir, conf.Repo)
} else {
cmds.SvnUpdate(currentDir, versionDir, conf.Repo, conf.UserName, conf.Password)
}
// 4.处理共享目录
// update 不需要
// 5.清理备份版本
cmds.ClearBackup(releaseDir, conf.BackupNum)
// 6.TODO:测试?
// 7.执行部署上线前命令
if strings.TrimSpace(conf.BeforeCmd) != "" {
conf.BeforeCmd = strings.Replace(conf.BeforeCmd, "$path", versionDir, -1)
conf.BeforeCmd = strings.Replace(conf.BeforeCmd, "$share", sharedDir, -1)
conf.BeforeCmd = strings.Replace(conf.BeforeCmd, "$release", releaseDir, -1)
cmds.Exec(conf.BeforeCmd, versionDir)
}
// 执行对应场景上线前命令
if stage == "dev" && strings.TrimSpace(conf.DevBeforeCmd) != "" {
conf.DevBeforeCmd = strings.Replace(conf.DevBeforeCmd, "$path", versionDir, -1)
conf.DevBeforeCmd = strings.Replace(conf.DevBeforeCmd, "$share", sharedDir, -1)
conf.DevBeforeCmd = strings.Replace(conf.DevBeforeCmd, "$release", releaseDir, -1)
cmds.Exec(conf.DevBeforeCmd, versionDir)
}
if stage == "prod" && strings.TrimSpace(conf.ProdBeforeCmd) != "" {
conf.ProdBeforeCmd = strings.Replace(conf.ProdBeforeCmd, "$path", versionDir, -1)
conf.ProdBeforeCmd = strings.Replace(conf.ProdBeforeCmd, "$share", sharedDir, -1)
conf.ProdBeforeCmd = strings.Replace(conf.ProdBeforeCmd, "$release", releaseDir, -1)
cmds.Exec(conf.ProdBeforeCmd, versionDir)
}
// 8.把current软链接指向新版本
cmds.Ln(versionDir, currentDir)
// 11.执行部署后命令
if strings.TrimSpace(conf.AfterCmd) != "" {
conf.AfterCmd = strings.Replace(conf.AfterCmd, "$path", versionDir, -1)
conf.AfterCmd = strings.Replace(conf.AfterCmd, "$share", sharedDir, -1)
conf.AfterCmd = strings.Replace(conf.AfterCmd, "$release", releaseDir, -1)
cmds.Exec(conf.AfterCmd, versionDir)
}
// 执行对应场景上线后命令
if stage == "dev" && strings.TrimSpace(conf.DevAfterCmd) != "" {
conf.DevAfterCmd = strings.Replace(conf.DevAfterCmd, "$path", versionDir, -1)
conf.DevAfterCmd = strings.Replace(conf.DevAfterCmd, "$share", sharedDir, -1)
conf.DevAfterCmd = strings.Replace(conf.DevAfterCmd, "$release", releaseDir, -1)
cmds.Exec(conf.DevAfterCmd, versionDir)
}
if stage == "prod" && strings.TrimSpace(conf.ProdAfterCmd) != "" {
conf.ProdAfterCmd = strings.Replace(conf.ProdAfterCmd, "$path", versionDir, -1)
conf.ProdAfterCmd = strings.Replace(conf.ProdAfterCmd, "$share", sharedDir, -1)
conf.ProdAfterCmd = strings.Replace(conf.ProdAfterCmd, "$release", releaseDir, -1)
cmds.Exec(conf.ProdAfterCmd, versionDir)
}
// 取对应该tag的所有服务器
servers := getTagServers(tags)
session := NewShellSession(servers, *cmds, deploy.Id)
mutex.Lock()
sessions[id] = session
mutex.Unlock()
startTime := time.Now()
session.ParallelRun()
if !session.Success {
deploy.Stage = stage
deploy.Operator = string(username)
deploy.Status = -1
deploy.Output = session.Output()
deploy.ElapsedTime = int(time.Now().Sub(startTime).Seconds())
deploy.CreatedAt = time.Now()
db.Save(&deploy)
sendFailMsg(r, "部署失败.", session.Output())
return
}
// 取commit日志
revision, commitLog := getCommitLog(session, id, stage, conf, currentDir)
deploy.Revision = revision
deploy.CommitLog = commitLog
// 保存
deploy.Stage = stage
deploy.Operator = string(username)
deploy.Status = 1
deploy.Output = session.Output()
deploy.Enable = true
deploy.ElapsedTime = int(time.Now().Sub(startTime).Seconds())
deploy.CreatedAt = time.Now()
db.Save(&deploy)
sendSuccessMsg(r, nil)
return
}
// 回滚部署
func ExecuteRollback(username string, params martini.Params, r render.Render) {
deployId, _ := strconv.Atoi(params["id"])
var deploy Deploy
db.First(&deploy, deployId)
if deploy.Id <= 0 {
sendFailMsg(r, "该版本不存在.", nil)
return
}
id := deploy.SystemId
stage := deploy.Stage
if isDeploying(id) {
sendFailMsg(r, "另一部署进程正在进行中,请稍候.", nil)
return
}
var conf SystemConfig
db.First(&conf, id)
workdir := conf.Path
switch deploy.Stage {
case "dev":
workdir = strings.TrimSuffix(conf.Path, "/") + "/development"
case "prod":
workdir = strings.TrimSuffix(conf.Path, "/") + "/production"
default:
}
releaseDir := fmt.Sprintf("%s/releases", workdir)
versionDir := fmt.Sprintf("%s/%s", releaseDir, deploy.Version)
currentDir := fmt.Sprintf("%s/current", workdir)
tags := conf.Tags
cmds := NewShellCommand()
// 判断该版本目录是否存在,存在直接回滚
cmds.ExistDir(versionDir).Rollback(versionDir, currentDir)
// 取对应该tag的所有服务器
servers := getTagServers(tags)
session := NewShellSession(servers, *cmds, deployId)
mutex.Lock()
sessions[id] = session
mutex.Unlock()
session.ParallelRun()
if !session.Success {
sendFailMsg(r, "回滚失败.", session.Output())
return
}
// 去掉旧的部署的启用状态
db.Model(Deploy{}).Where(Deploy{SystemId: id, Stage: stage, Enable: true}).Update(map[string]interface{}{"enable": false})
deploy.Enable = true
db.Save(&deploy)
sendSuccessMsg(r, session.Output())
return
}
func DeployProgress(params martini.Params, r render.Render) {
id, _ := strconv.Atoi(params["id"])
var s *ShellSession
var found bool
mutex.Lock()
s, found = sessions[id]
mutex.Unlock()
if found {
data := map[string]interface{}{}
isComplete := false
if s.IsComplete {
output, status := getDeployLog(s.DeployId)
if status != 0 {
isComplete = true
data["output"] = output
data["complete"] = true
data["success"] = s.Success
}
}
if !isComplete {
data["output"] = s.Output()
data["complete"] = false
data["success"] = false
}
r.JSON(200, data)
} else {
data := map[string]interface{}{}
data["output"] = ""
data["complete"] = true
data["success"] = false
r.JSON(200, data)
}
}
func ShowDeployLog(params martini.Params, r render.Render) {
id, _ := strconv.Atoi(params["id"])
data := map[string]interface{}{}
data["output"], data["success"] = getDeployLog(id)
r.JSON(200, data)
}
func getDeployLog(id int) (output string, status int) {
var deploy Deploy
db.First(&deploy, id)
status = deploy.Status
if deploy.CommitLog != "" {
output += "<span class=\"tip\">[变更] 版本提交历史log:\n " +
strings.Replace(deploy.CommitLog, "\n", "\n ", -1) +
"</span>\n"
}
output = output + deploy.Output
return
}
func CancelDeploy(params martini.Params, r render.Render) {
id, _ := strconv.Atoi(params["id"])
mutex.Lock()
defer mutex.Unlock()
var deploy Deploy
err := db.First(&deploy, id).Error
if err != nil {
sendFailMsg(r, "取消部署失败."+err.Error(), "")
return
}
deploy.Status = -1
db.Save(&deploy)
s, found := sessions[deploy.SystemId]
if found && !s.IsComplete {
sessions[deploy.SystemId].Cancel()
sessions[deploy.SystemId].Success = false
sessions[deploy.SystemId].IsComplete = true
}
sendSuccessMsg(r, "取消部署成功.")
return
}
func getCommitLog(session *ShellSession, id int, stage string, conf SystemConfig, currentDir string) (revision string, commitLogStr string) {
var oldDeploy Deploy
db.First(&oldDeploy, Deploy{SystemId: id, Stage: stage, Enable: true})
var commitLog CommitLog
if strings.Contains(conf.Repo, ".git") {
commitLog, _ = session.RetrieveGitCommitLog(currentDir)
session.IsComplete = true
} else {
commitLog, _ = session.RetrieveSvnCommitLog(currentDir, conf.UserName, conf.Password)
session.IsComplete = true
}
if commitLog.LogEntries != nil {
for _, commit := range commitLog.LogEntries {
if commit.Revision == oldDeploy.Revision {
break
}
commitLogStr += "r" + commit.Revision + " " + commit.Msg + "\n"
}
if len(commitLog.LogEntries) > 0 {
revision = commitLog.LogEntries[0].Revision
if commitLogStr == "" {
commitLogStr = "r" + commitLog.LogEntries[0].Revision + " " + commitLog.LogEntries[0].Msg + "\n"
}
}
}
return
}
func isDeploying(systemid int) bool {
mutex.Lock()
defer mutex.Unlock()
s, found := sessions[systemid]
if !found || s.IsComplete {
s = &ShellSession{}
sessions[systemid] = s
return false
}
return true
}