deployer.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # @Author: wushuiyong
  4. # @Created Time : 日 1/ 1 23:43:12 2017
  5. # @Description:
  6. import time
  7. from datetime import datetime
  8. import os
  9. # from fabric import context_managers, colors
  10. from flask import current_app
  11. from walle.model import deploy as TaskModel
  12. from walle.service.waller import Waller
  13. from walle.model.deploy import ProjectModel
  14. # import fabric2.exceptions.GroupException
  15. class Deployer:
  16. '''
  17. 序列号
  18. '''
  19. stage = '0'
  20. sequence = 0
  21. stage_prev_deploy = 'prev_deploy'
  22. stage_deploy = 'deploy'
  23. stage_post_deploy = 'post_deploy'
  24. stage_prev_release = 'prev_release'
  25. stage_release = 'release'
  26. stage_post_release = 'post_release'
  27. task_id = '0'
  28. user_id = '0'
  29. taskMdl = None
  30. TaskRecord = None
  31. version = datetime.now().strftime('%Y%m%d%H%M%s')
  32. project_name = 'walden'
  33. dir_codebase = '/tmp/walle/codebase/'
  34. dir_codebase_project = dir_codebase + project_name
  35. # 定义远程机器
  36. # env.hosts = ['172.16.0.231', '172.16.0.177']
  37. dir_release = None
  38. dir_webroot = None
  39. connections, success, errors = {}, {}, {}
  40. release_version_tar, release_version = None, None
  41. local, websocket = None, None
  42. def __init__(self, task_id=None, project_id=None, websocket=None):
  43. self.local = Waller(host=current_app.config.get('LOCAL_SERVER_HOST'),
  44. user=current_app.config.get('LOCAL_SERVER_USER'),
  45. port=current_app.config.get('LOCAL_SERVER_PORT'))
  46. self.TaskRecord = TaskModel.TaskRecordModel()
  47. if websocket:
  48. websocket.send_updates(__name__)
  49. self.websocket = websocket
  50. if task_id:
  51. self.task_id = task_id
  52. self.taskMdl = TaskModel.TaskModel().item(self.task_id)
  53. self.user_id = self.taskMdl.get('user_id')
  54. self.servers = self.taskMdl.get('servers_info')
  55. self.task = self.taskMdl.get('target_user')
  56. self.project_info = self.taskMdl.get('project_info')
  57. if project_id:
  58. self.project_id = project_id
  59. self.project_info = ProjectModel(id=project_id).item()
  60. def config(self):
  61. return {'task_id': self.task_id, 'user_id': self.user_id, 'stage': self.stage, 'sequence': self.sequence,
  62. 'websocket': self.websocket}
  63. # ===================== fabric ================
  64. # SocketHandler
  65. def prev_deploy(self):
  66. '''
  67. 1.代码检出前要做的基础工作
  68. - 检查 当前用户
  69. - 检查 python 版本
  70. - 检查 git 版本
  71. - 检查 目录是否存在
  72. - 用户自定义命令
  73. :return:
  74. '''
  75. self.stage = self.stage_prev_deploy
  76. self.sequence = 1
  77. # TODO remove
  78. # result = self.local.run('sleep 30', wenv=self.config())
  79. # 检查 当前用户
  80. command = 'whoami'
  81. self.websocket.send_updates(command)
  82. current_app.logger.info(command)
  83. result = self.local.run(command, wenv=self.config())
  84. # 检查 python 版本
  85. command = 'python --version'
  86. result = self.local.run(command, wenv=self.config())
  87. current_app.logger.info(command)
  88. # 检查 git 版本
  89. command = 'git --version'
  90. result = self.local.run(command, wenv=self.config())
  91. current_app.logger.info(command)
  92. # 检查 目录是否存在
  93. command = 'mkdir -p %s' % (self.dir_codebase_project)
  94. # TODO remove
  95. current_app.logger.info(command)
  96. result = self.local.run(command, wenv=self.config())
  97. # 用户自定义命令
  98. command = self.project_info['prev_deploy']
  99. current_app.logger.info(command)
  100. with self.local.cd(self.dir_codebase_project):
  101. result = self.local.run(command, wenv=self.config())
  102. # SocketHandler.send_to_all({
  103. # 'type': 'user',
  104. # 'id': 33,
  105. # 'host': env.host_string,
  106. # 'command': command,
  107. # 'message': result.stdout,
  108. # })
  109. def deploy(self):
  110. '''
  111. 2.检出代码
  112. :param project_name:
  113. :return:
  114. '''
  115. self.stage = self.stage_deploy
  116. self.sequence = 2
  117. current_app.logger.info('git dir: %s', self.dir_codebase_project + '/.git')
  118. # 如果项目底下有 .git 目录则认为项目完整,可以直接检出代码
  119. # TODO 不标准
  120. if os.path.exists(self.dir_codebase_project + '/.git'):
  121. with self.local.cd(self.dir_codebase_project):
  122. command = 'pwd && git pull'
  123. result = self.local.run(command, wenv=self.config())
  124. else:
  125. # 否则当作新项目检出完整代码
  126. with self.local.cd(self.dir_codebase_project):
  127. command = 'pwd && git clone %s .' % (self.project_info['repo_url'])
  128. current_app.logger.info('cd %s command: %s ', self.dir_codebase_project, command)
  129. result = self.local.run(command, wenv=self.config())
  130. # copy to a local version
  131. self.release_version = '%s_%s_%s' % (
  132. self.project_name, self.task_id, time.strftime('%Y%m%d_%H%M%S', time.localtime(time.time())))
  133. with self.local.cd(self.dir_codebase):
  134. command = 'cp -rf %s %s' % (self.dir_codebase_project, self.release_version)
  135. current_app.logger.info('cd %s command: %s ', self.dir_codebase_project, command)
  136. result = self.local.run(command, wenv=self.config())
  137. # 更新到指定 commit_id
  138. with self.local.cd(self.dir_codebase + self.release_version):
  139. command = 'git reset -q --hard %s' % (self.taskMdl.get('commit_id'))
  140. result = self.local.run(command, wenv=self.config())
  141. # SocketHandler.send_to_all({
  142. # 'type': 'user',
  143. # 'id': 33,
  144. # 'host': env.host_string,
  145. # 'command': command,
  146. # 'message': result.stdout,
  147. # })
  148. # 用户自定义命令
  149. # command = self.project_info['deploy']
  150. # current_app.logger.info(command)
  151. # with self.local.cd(self.dir_codebase):
  152. # result = self.local.run(command)
  153. pass
  154. def post_deploy(self):
  155. '''
  156. 3.检出代码后要做的任务
  157. - 用户自定义操作命令
  158. - 代码编译
  159. - 清除日志文件及无用文件
  160. -
  161. - 压缩打包
  162. - 传送到版本库 release
  163. :return:
  164. '''
  165. self.stage = self.stage_post_deploy
  166. self.sequence = 3
  167. # 用户自定义命令
  168. command = self.project_info['post_deploy']
  169. current_app.logger.info(command)
  170. with self.local.cd(self.dir_codebase + self.release_version):
  171. result = self.local.run(command, wenv=self.config())
  172. # 压缩打包
  173. self.release_version_tar = '%s.tgz' % (self.release_version)
  174. with self.local.cd(self.dir_codebase):
  175. command = 'tar zcvf %s %s' % (self.release_version_tar, self.release_version)
  176. result = self.local.run(command, wenv=self.config())
  177. def prev_release(self, waller):
  178. '''
  179. 4.部署代码到目标机器前做的任务
  180. - 检查 webroot 父目录是否存在
  181. :return:
  182. '''
  183. self.stage = self.stage_prev_release
  184. self.sequence = 4
  185. # 检查 target_releases 父目录是否存在
  186. command = 'mkdir -p %s' % (self.project_info['target_releases'])
  187. result = waller.run(command, wenv=self.config())
  188. # TODO 检查 webroot 父目录是否存在,是否为软链
  189. # command = 'mkdir -p %s' % (self.project_info['target_root'])
  190. # result = waller.run(command)
  191. # current_app.logger.info('command: %s', dir(result))
  192. # TODO md5
  193. # 传送到版本库 release
  194. current_app.logger.info('/tmp/walle/codebase/' + self.release_version_tar)
  195. result = waller.put('/tmp/walle/codebase/' + self.release_version_tar,
  196. remote=self.project_info['target_releases'])
  197. current_app.logger.info('command: %s', dir(result))
  198. # 解压
  199. self.release_untar(waller)
  200. def release(self, waller):
  201. '''
  202. 5.部署代码到目标机器做的任务
  203. - 打包代码 local
  204. - scp local => remote
  205. - 解压 remote
  206. :return:
  207. '''
  208. self.stage = self.stage_release
  209. self.sequence = 5
  210. with waller.cd(self.project_info['target_releases']):
  211. # 1. create a tmp link dir
  212. current_link_tmp_dir = '%s/current-tmp-%s' % (self.project_info['target_releases'], self.task_id)
  213. command = 'ln -sfn %s/%s %s' % (
  214. self.project_info['target_releases'], self.release_version, current_link_tmp_dir)
  215. result = waller.run(command, wenv=self.config())
  216. # 2. make a soft link from release to tmp link
  217. # 3. move tmp link to webroot
  218. current_link_tmp_dir = '%s/current-tmp-%s' % (self.project_info['target_releases'], self.task_id)
  219. command = 'mv -fT %s %s' % (current_link_tmp_dir, self.project_info['target_root'])
  220. result = waller.run(command, wenv=self.config())
  221. def release_untar(self, waller):
  222. '''
  223. 解压版本包
  224. :return:
  225. '''
  226. with waller.cd(self.project_info['target_releases']):
  227. command = 'tar zxf %s' % (self.release_version_tar)
  228. result = waller.run(command, wenv=self.config())
  229. def post_release(self, waller):
  230. '''
  231. 6.部署代码到目标机器后要做的任务
  232. - 切换软链
  233. - 重启 nginx
  234. :return:
  235. '''
  236. self.stage = self.stage_post_release
  237. self.sequence = 6
  238. self.post_release_service(waller)
  239. def post_release_service(self, waller):
  240. '''
  241. 代码部署完成后,服务启动工作,如: nginx重启
  242. :param connection:
  243. :return:
  244. '''
  245. with waller.cd(self.project_info['target_root']):
  246. command = 'sudo service nginx restart'
  247. result = waller.run(command, wenv=self.config())
  248. def list_tag(self):
  249. with self.local.cd(self.dir_codebase_project):
  250. command = 'git tag -l'
  251. current_app.logger.info('cd %s command: %s ', self.dir_codebase_project, command)
  252. result = self.local.run(command, wenv=self.config())
  253. current_app.logger.info(dir(result))
  254. return result
  255. return None
  256. def list_branch(self):
  257. with self.local.cd(self.dir_codebase_project):
  258. command = 'git pull'
  259. # result = self.local.run(command, wenv=self.config())
  260. current_app.logger.info(self.dir_codebase_project)
  261. command = 'git branch -r'
  262. result = self.local.run(command, wenv=self.config())
  263. # TODO 三种可能: false, error, success
  264. branches = result.stdout.strip().split('\n')
  265. # 去除 origin/HEAD -> 当前指向
  266. # 去除远端前缀
  267. branches = [branch.strip().lstrip('origin/') for branch in branches if not branch.startswith('origin/HEAD')]
  268. return branches
  269. return None
  270. def list_commit(self, branch):
  271. with self.local.cd(self.dir_codebase_project):
  272. command = 'git checkout %s && git pull' % (branch)
  273. result = self.local.run(command, wenv=self.config())
  274. # TODO 10是需要前端传的
  275. command = 'git log -10 --pretty="%h #_# %an #_# %s"'
  276. result = self.local.run(command, wenv=self.config())
  277. commit_list = result.stdout.strip().split('\n')
  278. commits = []
  279. for commit in commit_list:
  280. commit_dict = commit.split(' #_# ')
  281. commits.append({
  282. 'id': commit_dict[0],
  283. 'name': commit_dict[1],
  284. 'message': commit_dict[2],
  285. })
  286. return commits
  287. return None
  288. def walle_deploy(self):
  289. self.prev_deploy()
  290. self.deploy()
  291. self.post_deploy()
  292. server = '172.16.0.231'
  293. try:
  294. self.connections[server] = Waller(host=server, user=self.project_info['target_user'])
  295. self.prev_release(self.connections[server])
  296. self.release(self.connections[server])
  297. self.post_release(self.connections[server])
  298. except Exception, e:
  299. current_app.logger.exception(e)
  300. self.errors[server] = e.message
  301. # for server_info in self.servers:
  302. # server = server_info.host
  303. # try:
  304. # self.connections[server] = Waller(host=server, user=self.project_info['target_user'])
  305. # self.prev_release(self.connections[server])
  306. # self.release(self.connections[server])
  307. # self.post_release(self.connections[server])
  308. # except Exception, e:
  309. # self.errors[server] = e.message
  310. return {'success': self.success, 'errors': self.errors}