Python 部署项目(Tomcat 容器)

此前书写了多实例的 Tomcat 启动等操作的脚本,今天完善 Tomcat 多实例部署(本脚本只提供思路)

脚本内容:

  1 #!/usr/bin/env python
  2 # _*_coding:utf-8_*_
  3 # Author: "Edward.Liu"
  4 
  5 # Import libary~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  6 import subprocess
  7 import time
  8 import sys
  9 import signal
 10 import os
 11 import argparse
 12 import contextlib
 13 import zipfile
 14 
 15 
 16 # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 17 class Tomcat(object):
 18     def __init__(self, tomcat_exe):
 19         self.tomcat_exe = tomcat_exe
 20         self.Tomcat_Home = "/software/%s" % tomcat_exe
 21         self.Tomcat_Log_Home = "/software/%s/logs" % tomcat_exe
 22         self.counnt = 10
 23         # deploy options
 24         self.timeStr = time.strftime("%Y-%m-%d-%H:%M")
 25         self.source_files = "/software/cybershop-front-0.0.1-SNAPSHOT.war"
 26         self.dest_dir = "/software/upload_project/%s-%s" % (
 27             self.timeStr, self.source_files.split('/')[2].split('.war')[0])
 28         self.dest_deploy_dir = "/software/deploy-front/%s" % self.source_files.split('/')[2].split('.war')[0]
 29         self.images_Home = "/software/newupload1"
 30         self.static_images_lins = "%s/assets/upload" % self.dest_dir
 31         self.static_Home = "/data/www"
 32         self.static_home_link = "%s/www" % self.dest_dir
 33         # deploy options --->end
 34 
 35     # Get Tomcat_PID~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 36     def get_tomcat_pid(self):
 37         # 自定义获取程序 pid 与启动命令
 38         p = subprocess.Popen(['ps', '-Ao', 'pid,command'], stdout=subprocess.PIPE)
 39         out, err = p.communicate()
 40         for line in out.splitlines():
 41             if 'java' in line:
 42                 if self.tomcat_exe in line:
 43                     pid = int(line.split(None, 1)[0])
 44                     return pid
 45                     # 获取 END
 46 
 47     # Start Tomcat Process~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 48     def start_tomcat(self):
 49         if self.get_tomcat_pid() is not None:
 50             print "\033[32m %s Is Started \033[0m" % self.tomcat_exe
 51         else:
 52             # Start Tomcat
 53             command_start_tomcat = "%s/bin/startup.sh" % self.Tomcat_Home
 54             p = subprocess.Popen(command_start_tomcat, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
 55                                  stderr=subprocess.PIPE, shell=True)
 56             stdout, stderr = p.communicate()
 57             print stdout, stderr
 58 
 59     # Stop Tomcat process~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 60     def stop_tomcat(self):
 61         wait_sleep = 0
 62         if self.get_tomcat_pid() is None:
 63             print "\033[32m %s is Not Running\033[0m" % self.tomcat_exe + "~" * 20
 64         else:
 65             command_stop_tomcat = "%s/bin/shutdown.sh" % self.Tomcat_Home
 66             p = subprocess.Popen(command_stop_tomcat, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
 67                                  stderr=subprocess.PIPE, shell=True)
 68             stdout, stderr = p.communicate()
 69             while (self.get_tomcat_pid() is not None):
 70                 print "waiting for processes to exit\n"
 71                 wait_sleep += 1
 72                 time.sleep(1)
 73                 if wait_sleep == self.counnt:
 74                     os.kill(self.get_tomcat_pid(), signal.SIGKILL)
 75                     print "\033[32m Stop Tomcat is sucessful \033[0m"
 76                     break
 77 
 78     # View TomcatLogs~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 79     def tomcat_log(self):
 80         command_tomcat_log = "tail -f %s/catalina.out " % self.Tomcat_Log_Home
 81         p = subprocess.Popen(command_tomcat_log, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
 82         returncode = p.poll()
 83         try:
 84             while returncode is None:
 85                 line = p.stdout.readline()
 86                 returncode = p.poll()
 87                 line = line.strip()
 88                 print line
 89             print returncode
 90         except KeyboardInterrupt:
 91             print 'ctrl+d or z'
 92 
 93     # Unzip Project_name~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 94     def unzip(self):
 95         ret = 0
 96         try:
 97             with contextlib.closing(zipfile.ZipFile(self.source_files)) as zf:
 98                 if not os.path.exists(self.dest_dir):
 99                     print "\033[32mPath %s Is Not Exists Creating\033[0m" % self.dest_dir
100                     os.makedirs(self.dest_dir)
101                     zf.extractall(self.dest_dir)
102                     os.remove(self.source_files)
103                     ret = 2
104 
105         except IOError:
106             print "\033[31m%s Is Not Exists Please send Files\033[0m" % self.source_files
107         return ret
108     # Create Soft Links
109     def soft_link(self):
110         if os.path.islink(self.dest_deploy_dir):
111             os.unlink(self.dest_deploy_dir)
112             print "\033[32mCreating Static Files/Images Link\033[0m "
113             os.symlink(self.images_Home, self.static_images_lins)
114             os.symlink(self.static_Home, self.static_home_link)
115             print self.dest_dir
116             print self.dest_deploy_dir
117             os.symlink(self.dest_dir, self.dest_deploy_dir)
118         else:
119             print "\033[32mCreating Static Files/Images Link\033[0m "
120             os.symlink(self.images_Home, self.static_images_lins)
121             os.symlink(self.static_Home, self.static_home_link)
122             print self.dest_dir
123             print self.dest_deploy_dir
124             os.symlink(self.dest_dir, self.dest_deploy_dir)
125 
126 
127 if __name__ == '__main__':
128     parser = argparse.ArgumentParser(
129             description="eg: '%(prog)s' -c tomcat-front|tomcat -d {start|stop|status|restart|log|deploy}")
130     # ADD Tomcat Apps ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
131     parser.add_argument('-c', '--app_name', nargs='+', dest='choices',
132                         choices=('tomcat-front', 'tomcat-mobile'))  # choices 规定只能书写此处标出的, nargs='+' 至少有一个参数
133     parser.add_argument('-d', '--Handle', action='store', nargs='?', dest='handle', default='log',
134                         help='Input One of the {start|stop|status|restart|log|deploy}')  # nargs='?' 有一个货没有参数都可以
135     parser.add_argument('-v', '--version', action='version', version='%(prog)s 1.0')
136 
137     args = parser.parse_args()
138     if len(sys.argv) <= 4:
139         parser.print_help()
140     else:
141         try:
142             Handle = Tomcat(args.choices[0])
143             if args.handle == 'log':
144                 Handle.tomcat_log()
145             elif args.handle == 'start':
146                 Handle.start_tomcat()
147             elif args.handle == 'stop':
148                 Handle.stop_tomcat()
149             elif args.handle == 'restart':
150                 Handle.stop_tomcat()
151                 time.sleep(5)
152                 Handle.start_tomcat()
153             elif args.handle == 'deploy':
154                 Handle.stop_tomcat()
155                 if Handle.unzip() != 0:
156                     Handle.soft_link()
157                 Handle.start_tomcat()
158             elif args.handle == 'status':
159                 if Handle.get_tomcat_pid() is not None:
160                     print "\033[32m %s Is Running is PID:\033[0m" % Handle.tomcat_exe + "\033[31m %s \033[0m" % Handle.get_tomcat_pid()
161                 else:
162                     print "\033[32m %s Not Running Or Not Exist \033[0m" % Handle.tomcat_exe
163             else:
164                 print "\033[31mYou Input parameter Is Not Exist\033[0m"
165         except TypeError:
166             parser.print_help()
View Code

 

转载于:https://www.cnblogs.com/edwardlogs/p/5070529.html

你可能感兴趣的:(java,python,shell)