1 #!/usr/bin/env python
2 #_*_coding:utf-8_*_
3 #Author: "Edward.Liu"
4
5 #Import libary~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
6 importsubprocess7 importtime8 importsys9 importsignal10 importos11 importargparse12 importcontextlib13 importzipfile14
15
16 #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
17 classTomcat(object):18 def __init__(self, tomcat_exe):19 self.tomcat_exe =tomcat_exe20 self.Tomcat_Home = "/software/%s" %tomcat_exe21 self.Tomcat_Log_Home = "/software/%s/logs" %tomcat_exe22 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_dir31 self.static_Home = "/data/www"
32 self.static_home_link = "%s/www" %self.dest_dir33 #deploy options --->end
34
35 #Get Tomcat_PID~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
36 defget_tomcat_pid(self):37 #自定义获取程序 pid 与启动命令
38 p = subprocess.Popen(['ps', '-Ao', 'pid,command'], stdout=subprocess.PIPE)39 out, err =p.communicate()40 for line inout.splitlines():41 if 'java' inline:42 if self.tomcat_exe inline:43 pid = int(line.split(None, 1)[0])44 returnpid45 #获取 END
46
47 #Start Tomcat Process~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
48 defstart_tomcat(self):49 if self.get_tomcat_pid() is notNone:50 print "\033[32m %s Is Started \033[0m" %self.tomcat_exe51 else:52 #Start Tomcat
53 command_start_tomcat = "%s/bin/startup.sh" %self.Tomcat_Home54 p = subprocess.Popen(command_start_tomcat, stdin=subprocess.PIPE, stdout=subprocess.PIPE,55 stderr=subprocess.PIPE, shell=True)56 stdout, stderr =p.communicate()57 printstdout, stderr58
59 #Stop Tomcat process~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
60 defstop_tomcat(self):61 wait_sleep =062 if self.get_tomcat_pid() isNone: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_Home66 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 notNone):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 deftomcat_log(self):80 command_tomcat_log = "tail -f %s/catalina.out" %self.Tomcat_Log_Home81 p = subprocess.Popen(command_tomcat_log, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)82 returncode =p.poll()83 try:84 while returncode isNone:85 line =p.stdout.readline()86 returncode =p.poll()87 line =line.strip()88 printline89 printreturncode90 exceptKeyboardInterrupt:91 print 'ctrl+d or z'
92
93 #Unzip Project_name~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
94 defunzip(self):95 ret =096 try:97 with contextlib.closing(zipfile.ZipFile(self.source_files)) as zf:98 if notos.path.exists(self.dest_dir):99 print "\033[32mPath %s Is Not Exists Creating\033[0m" %self.dest_dir100 os.makedirs(self.dest_dir)101 zf.extractall(self.dest_dir)102 os.remove(self.source_files)103 ret = 2
104
105 exceptIOError:106 print "\033[31m%s Is Not Exists Please send Files\033[0m" %self.source_files107 returnret108 #Create Soft Links
109 defsoft_link(self):110 ifos.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 printself.dest_dir116 printself.dest_deploy_dir117 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 printself.dest_dir123 printself.dest_deploy_dir124 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 notNone: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_exe163 else:164 print "\033[31mYou Input parameter Is Not Exist\033[0m"
165 exceptTypeError:166 parser.print_help()