Пример #1
0
 def judge_permission(self):
     if not pub.hasAccessPermission(self.uid, self.server_type, self.server_id):
         # print('no permission')
         runlog.error("--no permission to access the config_file from web-----, Catch exception:, file: [ %s ], line: [ %s ]"
                     %(__file__,sys._getframe().f_lineno))
         return False
     return True
Пример #2
0
 def app_LogDir(self, app_id, server_type, server_id,
                logdir_id):  # 获取具体的某个日志目录
     if server_type == '2':  # 虚拟机
         sql = '''
               SELECT b.log_dir
                 from cmdb_server_app a ,  -- server—app的中间表
                             op_app_logdir b			-- app日志目录表
                 where a.app_id = %s and a.server_type = %s 
                             and a.virtual_server_id = %s and a.id = b.server_app_id and b.id = %s
               '''
     elif server_type == '1':
         sql = '''
               SELECT b.log_dir
                 from cmdb_server_app a ,  -- server—app的中间表
                             op_app_logdir b			-- app日志目录表
                 where a.app_id = %s and a.server_type = %s 
                             and a.physical_server_id = %s and a.id = b.server_app_id and b.id = %s
               '''
     try:
         res_dir = self._cursorQuery(
             sql, [app_id, server_type, server_id, logdir_id])
     except Exception as e:
         dblog.error(
             "[ERROR] Query error, Catch exception:[ %s ], file: [ %s ], line: [ %s ]"
             % (e, __file__, sys._getframe().f_lineno))
         return {}
     else:
         if len(res_dir) == 0:
             runlog.error(
                 "[ERROR] --no found the logdir-----, Catch exception:, file: [ %s ], line: [ %s ]"
                 % (__file__, sys._getframe().f_lineno))
             return {}
     return res_dir
Пример #3
0
 def whole_appLogDirs(self, app_id, server_type,
                      server_id):  # 获取这个app在这个服务器上所有的日志目录
     # print('oooooooooo',app_id,server_type,server_id)
     if server_type == '2':  # 虚拟机
         sql = '''
               SELECT b.log_dir,b.id
                 from cmdb_server_app a ,  -- server—app的中间表
                             op_app_logdir b			-- app日志目录表
                 where a.app_id = %s and a.server_type = %s 
                             and a.virtual_server_id = %s and a.id = b.server_app_id
               '''
     elif server_type == '1':
         sql = '''
               SELECT b.log_dir,b.id
                 from cmdb_server_app a ,  -- server—app的中间表
                             op_app_logdir b			-- app日志目录表
                 where a.app_id = %s and a.server_type = %s 
                             and a.physical_server_id = %s and a.id = b.server_app_id
               '''
     try:
         res_dir = self._cursorQuery(sql, [app_id, server_type, server_id])
     except Exception as e:
         dblog.error(
             "[ERROR] Query error, Catch exception:[ %s ], file: [ %s ], line: [ %s ]"
             % (e, __file__, sys._getframe().f_lineno))
         return ''
     else:
         if len(res_dir) == 0:
             runlog.error(
                 "[ERROR] --no found the logdir-----, Catch exception:, file: [ %s ], line: [ %s ]"
                 % (__file__, sys._getframe().f_lineno))
             # print('logdir is nonononononono')
             return ''
     return res_dir
Пример #4
0
 def judge_args(self):
     # 判断前端传来的参数
     if self.project_id == '' or self.env_id == '' or self.app_id == '' or self.ip == ''\
             or self.action == ''or self.server_type == '' or self.server_id == '':
         # print('p_id,e_id,a_id,ip,action,server_type,server_id,',self.project_id,self.env_id,self.app_id,self.ip,self.action,self.server_type,self.server_id)
         print('invaild action args from web...')
         runlog.error("[ERROR] --wrong action args from web-----, Catch exception:, file: [ %s ], line: [ %s ]"
                     %(__file__,sys._getframe().f_lineno))
         return False
     return True
Пример #5
0
 def AppConfigDetail(self, server_type, app_id, server_id, env_id,
                     project_id):  # 查找app的
     # 根据项目、环境、应用、ip对对应的部署在此机器上的应用信息
     if server_type == '2':
         sql = '''
             select p.code,de.install_user,
                     e.type_app,de.app_dir,
                     de.pkgname,de.server_port,e.name,
                     de.ssh_pass,de.ssh_port,de.ssh_user
             from cmdb_server_app de, -- 服务器-app中间表	
                   cmdb_env_server hd, 	-- 服务器-环境中间表
                   cmdb_env h,					-- 环境表
                   cmdb_project p,		  -- 项目表	
                   cmdb_app e					-- app表
             where de.app_id = %s and de.app_id=e.id and de.virtual_server_id = %s 
                   and hd.virtual_server_id=de.virtual_server_id 
                   and h.env_type=%s and h.id=hd.env_id and p.id=%s 
         '''
     elif server_type == '1':
         sql = '''
         select p.code,de.install_user,
                 e.type_app,de.app_dir,
                 de.pkgname,de.server_port,e.name,
                 de.ssh_pass,de.ssh_port,de.ssh_user
             from cmdb_server_app de,    -- 服务器-app中间表
                   cmdb_env_server hd, 	-- 服务器-环境中间表
                   cmdb_env h,					-- 环境表
                   cmdb_project p,		  -- 项目表	
                   cmdb_app e					-- app表
             where de.app_id = %s and de.app_id=e.id and de.physical_server_id = %s 
                   and hd.physical_server_id=de.physical_server_id 
                   and h.env_type=%s and h.id=hd.env_id and p.id=%s 
         '''
     else:
         # print('--wrong-server_type---->\033[42;1m\033[0m')
         runlog.error(
             "[ERROR] --invalid-server_type-----, Catch exception:, file: [ %s ], line: [ %s ]"
             % (__file__, sys._getframe().f_lineno))
         return ['', False]
     try:
         res = self._cursorQuery(sql,
                                 [app_id, server_id, env_id, project_id])
     except Exception as e:
         dblog.error(
             "[ERROR] Query error, Catch exception:[ %s ], file: [ %s ], line: [ %s ],sql:[%s]"
             % (e, __file__, sys._getframe().f_lineno, sql))
         return ['', False]
     if len(res) == 0:
         # print('*****wrong action args....')
         dblog.error(
             "[ERROR]--invalid-action args-----, Catch exception:, file: [ %s ], line: [ %s ]"
             % (__file__, sys._getframe().f_lineno))
         return ['', False]
     return [res, True]
Пример #6
0
    def runScript(self, ip, cmd, **r_dic):
        username, sshport, password = r_dic['sshuser'], r_dic[
            'sshport'], r_dic['pass']

        status = self.pt.execCommand(ip, username, sshport, password, cmd)
        # print 'status',status
        if status:
            runlog.info(
                "--script execute-success--:file: [ %s ], line: [ %s ]" %
                (__file__, sys._getframe().f_lineno))
            return True
        else:
            runlog.error(
                "[ERROR] --run cmd-fail------, Catch exception:, file: [ %s ], line: [ %s ]"
                % (__file__, sys._getframe().f_lineno))
            return False
Пример #7
0
 def logDir(self):
     # 返回的字典格式
     data = {
         'project_id': self.project_id,
         'env_id': self.env_id,
         'app_id': self.app_id,
         'server_type': self.server_type,
         'server_id': self.server_id,
         'ip': self.ip,
     }
     if self.app_id == '':
         runlog.error(
             "[ERROR] -getlogdir-wrong action args from web-----, Catch exception:, file: [ %s ], line: [ %s ]"
             % (__file__, sys._getframe().f_lineno))
     if not pub.hasAccessPermission(self.uid, self.server_type,
                                    self.server_id):
         return ['no permissions to view']
     # 获取app的用户名和密码
     instance = appConfigDetailClass.appConfigDetail()
     res, status = instance.AppConfigDetail(self.server_type, self.app_id,
                                            self.server_id, self.env_id,
                                            self.project_id)
     print('logapp--res', res)
     if not status:
         runlog.error("the APP Data is null, file: [ %s ], line: [ %s ]" %
                      (__file__, sys._getframe().f_lineno))
     data['user'] = res[0][1]
     res_dir = instance.whole_appLogDirs(
         self.app_id, self.server_type,
         self.server_id)  # 通过appid查找出对应的所有的日志目录
     print('whole_appLogDirs------>\033[42;1m%s\033[0m' % res_dir)
     if len(res_dir) == 0:
         print('nono is logdir...')
         return {}
     res_list = []
     for i in res_dir:
         res_dic = dict()
         res_dic['id'] = i[1]
         res_dic['dir'] = i[0]
         res_list.append(res_dic)
     data['logdirs'] = res_list
     return data
Пример #8
0
    def getlogInfo(self):  # 获取app日志目录下所有日志的详细信息,大小,拥有者,修改时间等
        logdir_id = self.request.GET.get('logdir_id', '')
        # 判断前端传来的参数
        if self.project_id == '' or self.env_id == '' or self.app_id == '' or self.ip == ''\
                or self.server_type == '' or self.server_id == '' or logdir_id == '':
            # print(self.project_id,self.env_id,self.app_id,self.ip,self.server_type,self.server_id,logdir_id)
            # print('getLogInfo-error-invaild action args from web...')
            runlog.error(
                "[ERROR] -getLogInfo-error-wrong action args from web-----, Catch exception:, file: [ %s ], line: [ %s ]"
                % (__file__, sys._getframe().f_lineno))
            return 'invaild action args from web...'
        if not pub.hasAccessPermission(self.uid, self.server_type,
                                       self.server_id):

            runlog.error(
                "[ERROR] --no permission-----, Catch exception:, file: [ %s ], line: [ %s ]"
                % (__file__, sys._getframe().f_lineno))
            return {}
        instance = appConfigDetailClass.appConfigDetail()
        res_dir = instance.app_LogDir(self.app_id, self.server_type,
                                      self.server_id, logdir_id)
        if len(res_dir) == 0:
            return {}

        # 获取app的用户名和密码
        instance = appConfigDetailClass.appConfigDetail()
        res, Status = instance.AppConfigDetail(self.server_type, self.app_id,
                                               self.server_id, self.env_id,
                                               self.project_id)
        #print('pppppppppppplogapp--res', res)
        if not Status:
            runlog.error("the APP Data is null, file: [ %s ], line: [ %s ]" %
                         (__file__, sys._getframe().f_lineno))

        pk = ParamikoTool()  # 实例化对象,调用方法后将文件大小按时间排序展示
        data_res, status = pk.getDirInfo(self.ip, res[0][8], res[0][9],
                                         res[0][7], res_dir[0][0])
        # '''data='-rw-rw-r-- 1 beehive beehive  22900 Feb  8  2017 catalina.2017-02-08.log\n
        # -rw-rw-r-- 1 beehive beehive 171910 Feb  9  2017 catalina.2017-02-09.log\n
        #print('2222data_res------>\033[31;1m%s\033[0m' % data_res)
        if not status:
            runlog.error(
                "getDirInfo is null, file: [ %s ], line: [ %s ],error:[ %s ]" %
                (__file__, sys._getframe().f_lineno, data_res))
        final_data_dic = dict()  # 将得到的结果按字典的格式返回
        final_data_dic['data'] = data_res
        return final_data_dic
Пример #9
0
    def rsyncFile(self, ip, app_path, rsyncScriptPath, **r_dic):
        username, sshport, password = r_dic['sshuser'], r_dic[
            'sshport'], r_dic['pass']
        # 利用rsync脚本将配置文件和启动脚本推送过去,rsync可以自动创建文件夹

        # self.remote_dir = '{}/{}/{}/'.format('/home', username, 'service_manage')
        chmod_cmd = [['chmod', '+x', rsyncScriptPath]]
        if pub.execShellCommand(*chmod_cmd) == False:
            runlog.error(
                "Exec chmod_cmd command error, file: [ %s ], line: [ %s ]" %
                (__file__, sys._getframe().f_lineno))
            return ['', False]
        # 寻找服务器的家目录的命令
        remote_home_dir_cmd = [[
            "grep", "^{}:".format(username),
            "/etc/passwd|awk -F ':' '{print $6}'"
        ]]
        output_lst = self.pt.execCommandInRemoteHostOutput(
            ip, username, sshport, password, *remote_home_dir_cmd)
        print('oooouuutttpputt------>\033[42;1m%s\033[0m' % output_lst)
        if output_lst[0][0] != 0:
            return ['', False]
        remote_home = output_lst[0][1][:-1]  #remot_home = /home/bqadm
        print('rrrrrrr_home', remote_home)

        # print('remote_home_dir_cmd',remote_home_dir_cmd,type(remote_home_dir_cmd),len(remote_home_dir_cmd))
        # /home/bqadm

        remote_dir = '{}/service_manage'.format(remote_home)
        connect_args = [ip, username, sshport, password, app_path, remote_dir]
        if pub.rsyncServerToClients(rsyncScriptPath, *connect_args) != True:
            runlog.error(
                "[ERROR] rsync file to client error, Catch exception:, file: [ %s ], line: [ %s ]"
                % (__file__, sys._getframe().f_lineno))
            return ['', False]
        return [remote_dir, True]
Пример #10
0
    def download(self): #
        if not self.judge_args():
            runlog.error("[ERROR] --invalid args for downloading -----, Catch exception:, file: [ %s ], line: [ %s ]"
                         % (__file__, sys._getframe().f_lineno))
            return 'invalid args from web....'

        # 验证是否有权限
        # user_permits = permissionModelClass.PermissionModelClass(self.uid)
        if not hasAccessPermission(self.uid, self.server_type, self.server_id):
            # print('no permission')
            runlog.error("--no permission to access the logfile from web-----, Catch exception:, file: [ %s ], line: [ %s ]"
                        %(__file__,sys._getframe().f_lineno))
            return False
        rsync_file = os.path.dirname(os.path.abspath(__file__)) + '/../../scripts' + '/server/bin/execRsync.exp'  # rsync 脚本
        cmd1 = [['chmod', '+x', rsync_file]]  # 增加执行权限
        # i_calss = appLogDirModelClass.appLogModelClass(self.request)
        # dirname = i_calss.app_LogDir()


        # 获取app的用户名和密码
        instance = appConfigDetailClass.appConfigDetail()
        dirname = instance.app_LogDir(self.app_id, self.server_type, self.server_id, self.logdir_id) # 获取app的日志目录
        if len(dirname) == 0:
            runlog.error("the APP dirname is null, file: [ %s ], line: [ %s ]" % (
                __file__, sys._getframe().f_lineno))
            return 'no found the logdir'
        logfile = dirname[0][0] + os.sep + self.logfilename  # 得到app的日志的绝对路径
        res, status = instance.AppConfigDetail(self.server_type, self.app_id, self.server_id, self.env_id,
                                       self.project_id)
        print('logapp-1-res', res, logfile)
        if not status:
            runlog.error("the APP Data is null, file: [ %s ], line: [ %s ]" % (
                __file__, sys._getframe().f_lineno))
        connectmessage = {'ip': self.ip,
                          'port': res[0][8],
                          'user': res[0][9],
                          'password': res[0][7],
                          'remote_file': logfile,
                          'local_dir': os.path.dirname(os.path.abspath(__file__)) + '/../static/log/'
                          }
        # print cmd1
        if execShellCommand(*cmd1) != True:
            runlog.error("exec permission shell error, file: [ %s ], line: [ %s ]" % (
                __file__, sys._getframe().f_lineno))
            return 'exec permission shell error'
            # return JsonResponse('exec command failed!', safe=False)

        connect_lst = [connectmessage['ip'], connectmessage['user'], connectmessage['port'], connectmessage['password'],
                       connectmessage['remote_file'], connectmessage['local_dir']]
        filename = connectmessage['local_dir'] + connectmessage['ip'] + logfile.replace(os.sep, '-')

        retstr = '/static/log/' + connectmessage['ip'] + logfile.replace(os.sep, '-')

        if rsyncRemoteFileToLocal(rsync_file, *connect_lst) != True:
            runlog.error("rsyncRemoteFileToLocal error, file: [ %s ], line: [ %s ]" % (
                __file__, sys._getframe().f_lineno))
            return 'rsyncRemoteFileToLocal error'
        else:

            os.chdir(connectmessage['local_dir'])   # 切换到服务器上存放的日志目录路径下,将下载的文件加上ip后,重命名
            # print filename, self.logfilename
            os.system('mv  ' + self.logfilename + '  ' + filename)
            # 记录用户访问记录
            audit_log = Operation_dbModelClass()
            audit_log.inserToLog(self.request.user.username, self.ip, self.action, self.request.path,
                                 '{}'.format(filename))
            return retstr  # 路径可以根据自己定义
Пример #11
0
    def getAppDirs(self):
        '''
        返回树形的目录结构数据
        1、同步script/functions ${HOME}/op/ 下
        2、ssh 远程调用:
            funcions/bin/get_dir_files.py  /usr/local/tomcat8080/webapps/classes/conf
            获取返回结果并返回
        :return: data
        '''
        data = [
            {
                'text': 'document1',
                'state' : {
                    'opened': 'true',
                },
                'children': [
                    {
                        'text': 'document2',
                        'state' : {
                            'opened': 'true',
                        },
                        'children': [
                            {
                                'text': 'file2.txt',
                                'type' : 'file',
                                'icon' : 'jstree-file',
                            }
                        ]
                    }
                ]
            },{
                'text': 'file1.txt',
                'type' : 'file',
                'icon' : 'jstree-file',
            }
        ]
        # 如果遇到错误默认返回的内容
        default_res = [{
                            'text': '获取文件目录结构失败',
                            'type': 'file',
                            'icon': 'jstree-file',
                         }]
        # 判断传入参数 和 权限判断
        if not self.judge_args() or not self.judge_permission():
            return default_res
        # 查找出当前app的相关信息
        app_res, app_res_status = self.AppConfigDetail(self.server_type, self.app_id, self.server_id, self.env_id, self.project_id)
        if not app_res_status:
            return default_res


        t_pt = ParamikoTool()
        cmds = [['chmod', '+x', '/home/beehive/test/script/bin'],
                ['python', '/home/beehive/test/script/bin/get_dirs_files.py', '/home/beehive/test']]

        ip, user, port, passwd = '10.83.36.86', 'beehive', '10022', 'beehive_1'  # 参数demo
        ret_data = t_pt.execCommandInRemoteHostOutput(ip, user, port, passwd, *cmds)
        # print('type of ret_data:', type(ret_data))
        # print('ret_data:', ret_data)
        cmd_len, ret_data_len = len(cmds), len(ret_data)
        try:
            if len(ret_data) < cmd_len:  # 命令未全部执行完就已经报错
                print('cmd: [ %s ], error_info: [ %s ]' %
                      (cmds[ret_data_len - 1], ret_data[ret_data_len - 1][1]))
                runlog.error("[ERROR] chmod command exec error, Catch exception:, file: [ %s ], line: [ %s ]" % (
                    __file__, sys._getframe().f_lineno))
                return [{
                            'text': '获取文件目录结构失败',
                            'type': 'file',
                            'icon': 'jstree-file',
                         }]
            ret_status = ret_data[ret_data_len - 1][0]
            if int(ret_status) != 0:  # 执行最后一条命令出错
                print('Exec cmd: [ %s ] failed, error_info: [ %s ]' %
                      (cmds[ret_data_len - 1], ret_data[ret_data_len - 1][1]))
                return [{
                    'text': '获取文件目录结构失败',
                    'type': 'file',
                    'icon': 'jstree-file',
                }]
            org_data = ret_data[ret_data_len - 1][1]
            # print('type of data: ', type(org_data))
            # print('data:', org_data)
            list_data = eval(org_data)
            # print('type of list_data: ', type(list_data))
            # print('list_data:', list_data)
        except Exception as e:
            print('Catch error: [ %s ]' % (e))  # 记录详细日志
            return [{
                'text': '获取文件目录结构失败',
                'type': 'file',
                'icon': 'jstree-file',
            }]
        else:
            return list_data
Пример #12
0
    def getLogDetail(self):
        # 判断前端传来的参数
        if self.project_id == '' or self.env_id == '' or self.app_id == '' or self.ip == ''\
                or self.action == ''or self.server_type == '' or self.server_id == '':
            # print('p_id,e_id,a_id,ip,action,server_type,server_id,',self.project_id,self.env_id,self.app_id,self.ip,self.action,self.server_type,self.server_id)
            print('invaild action args from web...')
            runlog.error(
                "[ERROR] --wrong action args from web-----, Catch exception:, file: [ %s ], line: [ %s ]"
                % (__file__, sys._getframe().f_lineno))
            return 'invaild action args from web...'

        else:
            #判断用户是否有权限,没有权限返回判断结果

            if not pub.hasAccessPermission(self.uid, self.server_type,
                                           self.server_id):
                return 'no permissions to view'
            # 获取app的用户名和密码
            instance = appConfigDetailClass.appConfigDetail()
            res, status = instance.AppConfigDetail(self.server_type,
                                                   self.app_id, self.server_id,
                                                   self.env_id,
                                                   self.project_id)
            print('logapp--res', res)
            if not status:
                runlog.error(
                    "the APP Data is null, file: [ %s ], line: [ %s ]" %
                    (__file__, sys._getframe().f_lineno))
            res_dic = dict()
            for i in res:
                res_dic['install_user'] = i[1]
                res_dic['app_type'] = i[2]
                res_dic['appdir'] = i[3]
                res_dic['app_name'] = i[6]
                res_dic['pass'] = i[7]
                res_dic['sshport'] = i[8]
                res_dic['sshuser'] = i[9]
            # 获取远程服务器日志目录指定行数的内容
            # print('dict_res',res_dic)
            if res_dic['app_type'] == '1':  # app类型是tomcat
                if self.action == 'start':
                    log_file_path = '{}/logs/catalina.out'.format(
                        res_dic['appdir'])
                # print('00---00',log_file_path)
                elif self.action == 'stop':
                    log_file_path = '/home/{}/service_manage/{}/scripts/log/stopapp.sh.log'.format(\
                        res_dic['sshuser'], res_dic['app_name'])
                elif self.action == 'log_show':
                    logdir_id = self.request.GET.get('logdir_id', '')
                    file_name = self.request.GET.get('file_name', '')
                    print('nnnnnnnnnnnn', logdir_id, file_name)
                    if logdir_id == '' or file_name == '':
                        runlog.error(
                            "the logdir_id or filename is null, file: [ %s ], line: [ %s ]"
                            % (__file__, sys._getframe().f_lineno))
                        return 'invaild logdir_id to find the logfile'
                    # 找到app对应的日志目录
                    log_dir = instance.app_LogDir(self.app_id,
                                                  self.server_type,
                                                  self.server_id, logdir_id)
                    if len(log_dir) == 0:
                        runlog.error(
                            "the logdir is null, file: [ %s ], line: [ %s ]" %
                            (__file__, sys._getframe().f_lineno))
                        return 'invaild logdir to find the logfile'
                    log_file_path = '{}/{}'.format(log_dir[0][0], file_name)
                    print('logggggggg', log_file_path)
                else:
                    runlog.error(
                        "the APP type is not tomcat, file: [ %s ], line: [ %s ]"
                        % (__file__, sys._getframe().f_lineno))
                    return 'invaild action to find the logfile'
                pt = ParamikoTool()  # 实例化对象后,获取日志默认行数
                log_res = pt.getlogrow(self.ip, res_dic['sshport'], res_dic['sshuser'], \
                                       res_dic['pass'], log_file_path, self.line_num)
                # print('-------------',log_res)
                # 记录用户访问记录
                audit_log = Operation_dbModelClass()
                audit_log.inserToLog(self.request.user.username, self.ip,
                                     'access', self.request.path,
                                     log_file_path)
                return log_res

            else:
                runlog.info(
                    "the APP type is not tomcat, file: [ %s ], line: [ %s ]" %
                    (__file__, sys._getframe().f_lineno))
                return 'just for app-type like tomcat..'
Пример #13
0
    def getAction(self):
        if self.project_id == '' or self.env_id == '' or self.app_id == '' or self.ip == ''\
                or self.action == ''or self.server_type == '' or self.server_id == '':
            print('invaild action args from web...')
            runlog.error(
                "[ERROR] --wrong action args from web-----, Catch exception:, file: [ %s ], line: [ %s ]"
                % (__file__, sys._getframe().f_lineno))
            return False
        #  根据项目、环境、应用、ip对对应的部署在此机器上的应用信息
        instance = appConfigDetailClass.appConfigDetail()
        res, res_status = instance.AppConfigDetail(self.server_type, self.app_id, self.server_id, self.env_id, \
                                                   self.project_id)
        if not res_status:
            runlog.error("the APP Data is null, file: [ %s ], line: [ %s ]" %
                         (__file__, sys._getframe().f_lineno))
            return False
        res_dic = dict()  # 字典存储结果
        for i in res:
            res_dic['projectcode'] = i[0]
            res_dic['install_user'] = i[1]
            app_type = i[2]
            res_dic['appdir'] = i[3]
            res_dic['pkgname'] = i[4]
            res_dic['port'] = i[5]
            res_dic['app_name'] = i[6]
            res_dic['pass'] = i[7]
            res_dic['sshport'] = i[8]
            res_dic['sshuser'] = i[9]
        if app_type == '1':
            res_dic['apptype'] = 'tomcat'
        elif app_type == '2':
            res_dic['apptype'] = 'weblogic'
        else:
            # print('invalid AppType..')
            runlog.error(
                "[ERROR]--invalid AppType-----, Catch exception:, file: [ %s ], line: [ %s ]"
                % (__file__, sys._getframe().f_lineno))
            return False
        # print('123123123',res_dic)
        current_dir = os.path.dirname(os.path.abspath(__file__))
        rsyncScriptPath = '{}{}'.format(
            current_dir, '/../../scripts/server/bin/execRsync.exp')
        app_path = '{}{}{}/{}'.format(current_dir,
                                      '/../../tasks/service_manage/', self.ip,
                                      res_dic['app_name'])
        config_status = self.ConfigFile(self.ip, current_dir, **res_dic)
        if config_status:  # 配置文件构建成功
            remote_dir, status = self.rsyncFile(self.ip, app_path,
                                                rsyncScriptPath,
                                                **res_dic)  # 同步文件到远程机器
            if status:
                # print('rsync-succ----->\033[31;1m\033[0m')
                runlog.info(
                    "---rsync-file to remote-success----:file: [ %s ], line: [ %s ]"
                    % (__file__, sys._getframe().f_lineno))
                exec_dir = '{}/{}/{}'.format(remote_dir, res_dic['app_name'],
                                             'scripts/bin/')  # 远程执行的目录
                # 在bqadm家目录权限设为777
                # mkdir_cmd = "chmod 777 -R {}".format(remote_home)
                # mkdir_res = self.pt.execCommand(ip, username, sshport, password, mkdir_cmd)
                if self.action == 'start':  # 判断执行动作

                    # cmd = 'cd {}&&chmod a+x *.sh&&nohup ./startapp.sh 1>/dev/null 2>&1 &&sleep 10&&ps -ef|grep {}|grep {}|grep -v grep|wc -l' \
                    #     .format(exec_dir, res_dic['appdir'], res_dic['install_user'])
                    cmd = 'chmod 777 -R {};sudo su - {} -c "cd {}&&./startapp.sh 1>/dev/null 2>&1"'\
                            .format(remote_dir, res_dic['install_user'], exec_dir)
                elif self.action == 'stop':
                    cmd = 'chmod 777 -R {};sudo su - {} -c "cd {}&&./stopapp.sh 1>/dev/null 2>&1"'\
                            .format(remote_dir, res_dic['install_user'], exec_dir)
                else:  # action参数无效时
                    runlog.error(
                        "[ERROR] --invaild-action------, Catch exception:, file: [ %s ], line: [ %s ]"
                        % (__file__, sys._getframe().f_lineno))
                    return False
                # 记录用户访问记录
                audit_log = Operation_dbModelClass()
                audit_log.inserToLog(self.request.user.username, self.ip,
                                     self.action, self.request.path,
                                     '{}'.format(res_dic['app_name']))
                return self.runScript(self.ip, cmd,
                                      **res_dic)  # 返回执行脚本后的结果 true or false
            else:  # 同步文件失败
                # print('rsync-fail----->\033[31;1m\033[0m')
                runlog.error(
                    "[ERROR] --rsync-config-file-failed------, Catch exception:, file: [ %s ], line: [ %s ]"
                    % (__file__, sys._getframe().f_lineno))
                return False
        else:  # 创建配置文件失败
            # print('configFile create error..123')
            runlog.error(
                "[ERROR] --configFile-create-failed------, Catch exception:, file: [ %s ], line: [ %s ]"
                % (__file__, sys._getframe().f_lineno))
            return False
Пример #14
0
    def ConfigFile(self, ip, current_dir, **r_dic):  # 构建配置文件
        config_dir = '{}{}{}{}{}{}'.format(current_dir,
                                           '/../../tasks/service_manage/', ip,
                                           '/', r_dic['app_name'], '/scripts')
        # app_path = '{}{}{}/{}'.format(current_dir, '/../../tasks/service_manage/', ip, r_dic['app_name'])
        print('CONFIGGGGG', config_dir)
        if not os.path.exists(config_dir):
            try:
                for i in ['/bin', '/conf']:
                    os.makedirs(config_dir + i)
            except Exception as e:
                runlog.error(
                    "[ERROR] mkdirs error, Catch exception:[ %s ], file: [ %s ], line: [ %s ]"
                    % (e, __file__, sys._getframe().f_lineno))
                return False
        # 将最新source_dir下的start,stop脚本复制到config_dir
        source_dir = '{}{}'.format(current_dir,
                                   '/../../scripts/client/service_manage/bin')
        try:
            for file in os.listdir(source_dir):  # 获取目标文件夹的文件列表信息
                source_file = os.path.join(source_dir, file)
                target_file = '{}{}{}'.format(config_dir, '/bin/', file)
                if os.path.isfile(source_file):  # 判断是否为文件,真则写入到目标文件中
                    with open(target_file, "wb") as t_f:
                        t_f.write(open(source_file, "rb").read())
                else:
                    runlog.error(
                        "[ERROR] File--type error, Catch exception:, file: [ %s ], line: [ %s ]"
                        % (__file__, sys._getframe().f_lineno))
                    return False
            print('6666,copy files to tasks is ready....')
        except Exception as e:
            runlog.error(
                "Unexected error: [ %s ], file: [ %s ], line: [ %s ]" %
                (e, __file__, sys._getframe().f_lineno))
            return False

        # 写入配置文件
        conf_file = '{}{}'.format(config_dir, '/conf')
        try:
            with open(conf_file + '/app_config.conf', 'w') as f:
                # f = open(conf_file+'/app_config.conf','w')
                #f.write('pkgfile={0}'.format(REMOTE_BASE_DIR + dir_name + '/' + appname + '/pkg/' + dic['pkgname']) + '\n')
                f.write('appnumber={0}'.format('1') + '\n')
                f.write('projectcode={0}'.format(r_dic['projectcode']) + '\n')
                f.write('ip={0}'.format(ip) + '\n')
                # f.write('projectname=%s'%r_dic['projectname'] + '\n')
                f.write('user[1]={0}'.format(r_dic['install_user']) + '\n')
                f.write('upgradetype[1]=full' + '\n')
                f.write('apptype[1]={0}'.format(r_dic['apptype']) + '\n')
                #f.write('backupdir[1]={0}'.format(REMOTE_BASE_DIR + dir_name + '/' + appname + '/backup') + '\n')
                f.write('appdir[1]={0}'.format(r_dic['appdir']) + '\n')
                f.write('appwarname={0}'.format(r_dic['pkgname']) + '\n')
                f.write('startuptime[1]=1000' + '\n')
                f.write('port[1]={0}'.format(r_dic['port']) + '\n')
        except Exception as e:
            runlog.error(
                "Write to config file error, Catch exception:[ %s ], file: [ %s ], line: [ %s ]"
                % (e, __file__, sys._getframe().f_lineno))
            return False
        return True