-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathupdatePhpService.py
More file actions
369 lines (308 loc) · 10.2 KB
/
Copy pathupdatePhpService.py
File metadata and controls
369 lines (308 loc) · 10.2 KB
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
#!/usr/bin/env python
#!-*-coding:utf-8 -*-
#!@Date : 2018/11/9 0009 下午 17:08
#!@Author : Damon.guo
#!@File : updateStandard.py
import os
import sys
import time
import ConfigParser
from optparse import OptionParser
from subprocess import PIPE,Popen
import json
reload(sys)
sys.setdefaultencoding('utf-8')
serverConf = "standard.conf" # 部署配置文件路径
ansibileHostFile = "/etc/ansible/hosts" #ansible 主机文件
def getOptions():
parser = OptionParser()
parser.add_option("-n", "--serverName", action="store",
dest="serverName",
default=False,
help="serverName to do")
parser.add_option("-a", "--action", action="store",
dest="action",
default=False,
help="action -a [install,merge,update]for php project")
#
# parser.add_option("-v", "--versionId", action="store",
# dest="versionId",
# default=False,
# help="-v versionId")
parser.add_option("-b", "--branchName", action="store",
dest="branchName",
default=False,
help="-b branchName")
options, args = parser.parse_args()
return options, args
def execSh(cmd):
# 执行SH命令
try:
print "Exec ssh command %s" % cmd
p = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True)
except Exception, e:
print e,
sys.exit()
return p.communicate()
def checkMaster():
# 获取项目分支是否为master
cmd = "git branch"
stdout, stderr = execSh(cmd)
print "out:", stdout
branch_list = [i.strip() for i in stdout.split("\n") if i]
if "* master" in branch_list:
print "已经在master 分支"
return True
print "err", stderr
return False
#初始化主节点
def initProject(serverName):
# 新机器 或者新目录项目部署
print "master install:%s" % serverName
deployDir = projectDict[serverName]["deploydir"]
gitUrl = projectDict[serverName]["giturl"]
if not os.path.exists(deployDir):
os.mkdir(deployDir)
os.chdir(deployDir)
print "部署路径:",os.getcwd()
stdout, stderr = execSh("git status .")
if stdout:
print"out:\n%s" % stdout
print "当前目录:%s,已经存在git仓库请检查!" % deployDir
return True
if stderr:
print "没有git仓库,下一步"
print"out:%s" % stderr
print "初始化本地仓库"
ReturnExec("git init")
print"本地git仓库当前项目认证"
config_cmd = "git config --local credential.helper store"
ReturnExec(config_cmd)
print "拉取代码"
pull_cmd = "git pull %s" % gitUrl
ReturnExec(pull_cmd)
print "添加远程仓库地址"
add_remote_cmd = "git remote add origin %s" % gitUrl
ReturnExec(add_remote_cmd)
print "获取分支"
fetch_cmd = "git fetch"
ReturnExec(fetch_cmd)
print "关联本地master分支与远程master"
upstream_cmd = "git branch --set-upstream-to=origin/master master"
ReturnExec(upstream_cmd)
print "获取 最新master分支"
pull_m_cmd = "git pull"
ReturnExec(pull_m_cmd)
def ReturnExec(cmd):
stdout, stderr = execSh(cmd)
if stdout:
print 80*"#"
print "out:%s " % stdout
if stderr:
print 80*"#"
print "err:%s" % stderr
def readStdin():
input_str = raw_input("确认执行操作:Y/N")
return input_str.strip().lower()
# 合并分支至master
def mergeBranch(serverName,branchName):
deployDir = projectDict[serverName]["deploydir"]
fetch_cmd = "git fetch origin %s" % branchName
checkout_b_cmd = "git checkout %s" % branchName
pull_cmd = "git pull"
checkout_m_cmd = "git checkout master"
merge_cmd = "git merge origin/%s" % branchName
push_cmd = "git push origin master"
try:
print "切换工作目录"
print deployDir
os.chdir(deployDir) # 切换工做目录
print os.getcwd()
except Exception, e:
print e
sys.exit()
print "取分支"
stdout,stderr = execSh(fetch_cmd)
print stdout
if "fatal" in stderr:
print stderr
print "check branchname:%s" % branchName
sys.exit()
# 更新分支
print "更新本地 分支"
ReturnExec(pull_cmd)
# 切换至master分支
if not checkMaster():
print "切换至master分支"
ReturnExec(checkout_m_cmd)
# 更新master分支
print "更新master分支"
ReturnExec(pull_cmd)
# 合并分支至master
print "是否合并分支至master"
ReturnExec(merge_cmd)
# 提交合并的master 至源端git库
# 需要加确认 文件修改,在判断是否推送源端
print "是否提交合并的master 至源端git库"
option = readStdin()
if option != "y":
sys.exit()
ReturnExec(push_cmd)
# 更新应用节点代码
# print "是否更新应用节点代码"
# option = readStdin()
#
# if option != "y":
# sys.exit()
# updatecmd = 'ansible %s -m shell -a "cd %s;sudo git pull";' % (deployNodeName, deployDir)
# ReturnExec(updatecmd)
#检查配置文件
def confCheck(cf, section, option):
if not cf.options(section):
print "no section: %s in conf file" % section
sys.exit()
try:
options = cf.get(section, option)
except ConfigParser.NoOptionError:
print "no option in conf %s " % option
sys.exit()
if not options:
print "options:(%s) is null in section:(%s)" % (option, section)
return False
else:
return True
#读取配置文件
def readConf(serverConf):
cf = ConfigParser.ConfigParser()
try:
cf.read(serverConf)
except ConfigParser.ParsingError,e:
print e
print "please check conf %s" % serverConf
sys.exit()
serverNameDict = {}
optinsDict = {}
for serverName in cf.sections():
#print 'serverName:%s' % serverName
for optins in cf.options(serverName):
# 取服务名下的对应的配置和参数
if not confCheck(cf, serverName, optins):
sys.exit()
value = cf.get(serverName, optins)
optinsDict[optins] = value
serverNameDict[serverName] = optinsDict
optinsDict={}
return serverNameDict
#读取ansibel host 文件解析
def readConfAnsible(file):
cf = ConfigParser.ConfigParser(allow_no_value=True)
cf.read(file)
try:
cf.read(file)
except ConfigParser.ParsingError, e:
print e
print "please check conf %s" % file
sys.exit()
groupNameDict = {}
for groupName in cf.sections():
iplist = []
# print cf.options(groupName)
for ipstr in cf.options(groupName):
ip = ipstr.split(" ansible_ssh_user")[0]
iplist.append(ip)
print groupName, ip
groupNameDict[groupName] = iplist
return groupNameDict
def ansibleUpdateGit(serverName):
groupName = projectDict[serverName]["deploygroupname"]
deployDir = projectDict[serverName]["deploydir"]
UpdateDir = 'ansible %s -i %s -m shell -a "cd %s;sudo git pull"' % (groupName, ansibileHostFile, deployDir)
ReturnExec(UpdateDir)
def ansibleDirIsExists(ip,filepath):
# 判断远程 文件或者目录是否存在
cmd = "ansible %s -m stat -a 'path=%s' -o " % (ip, filepath)
stdout, stederr = execSh(cmd)
reslust = parseAnsibleOut(stdout)
if reslust:
print "%s is exists,on:%s" % (filepath,ip)
return True
elif reslust == None:
print "%s is other err on: %s " % (filepath, ip)
return None
else:
print "%s is not exists,on: %s " % (filepath, ip)
return False
# 解析 ansible 输出
def parseAnsibleOut(stdout):
try:
splitList = stdout.split("SUCCESS => ")
d = splitList[1].strip()
t = json.loads(d)
exists = t["stat"]["exists"]
return exists
except:
pass
#检查 配置文件是否存在配置项错误
def _init(serverName):
if not os.path.exists(serverConf):
print "%s is not exist" % serverConf
print """ %s like this:
[testgit22]
deployDir=/app/project/testgit22
gitUrl=git@10.0.1.131:root/testgit22.git
deployGroupName=node
deployFile=3.war""" % serverConf
if serverName != "all":
try:
projectDict[serverName]
except KeyError, e:
print "please check servername: %s" % e
sys.exit(1)
else:
return
sub_dict = projectDict[serverName]
try:
deploygroupname = sub_dict["deploygroupname"]
deploydir = sub_dict["deploydir"]
giturl = sub_dict["giturl"]
except KeyError, e:
print "please check confile:%s servername:%s conf:%s" % (serverConf, serverName, e)
sys.exit(1)
def main(serverName,branchName,action):
_init(serverName)
if action == "install":
# 新服务器部署项目
if serverName == "all":
for serName, dict_sub in projectDict.iteritems():
initProject(serName)
else:
initProject(serverName)
elif action == "merge":
# 合并分支至master
mergeBranch(serverName, branchName)
elif action == "update":
mergeBranch(serverName, branchName)
ansibleUpdateGit(serverName)
elif action == "restart":
pass
else:
print "action just [install,merge,update]"
sys.exit()
if __name__ == "__main__":
projectDict = readConf(serverConf)
# ansibleHostDict = readConfAnsible(ansibileHostFile)
options, args = getOptions()
action = options.action
# version = options.versionId
serverName = options.serverName
branchName = options.branchName
if not action:
print "please follow -a action"
sys.exit(1)
if not serverName:
print "please follow -n servename"
sys.exit(1)
if not branchName:
print "please follow -b branchname"
sys.exit(1)
main(serverName, branchName, action)