示例#1
0
    def stop(self, section_id=None):
        itemconf = self._chp.get_section_dict(section_id)
        appname = itemconf.get("appname", None)
        stop_cmd = itemconf.get("stop_cmd", None)
        self._logger.dictlog(level="info", width=20, **itemconf)

        scolor.info(u"#### [%s] 停止应用【%s】 ####" %
                    (sdate().datetime_human(), appname))
        if str(stop_cmd).strip() == None:
            scolor.warn(u"应用【%s】停止命令为空" % (appname))
            return

        c2 = cmds(stop_cmd)
        stdo = c2.stdo()
        stde = c2.stde()
        retcode = c2.code()

        #exeop = str("%s\n%s" % (stdo,stde)).strip()
        if retcode == 0 and str(stde).strip() == "":
            scolor.info(u"停止应用【%s】成功!" % (appname))
        else:
            scolor.error(u"停止应用【%s】失败!" % (appname))

        logobj = {
            u"命令": stop_cmd,
            u"标准输出": stdo,
            u"错误输出": stde,
            u"返回码": retcode,
            u"orders": [u"命令", u"标准输出", u"错误输出", u"返回码"]
        }
        self._logger.dictlog(level="info", width=12, **logobj)
示例#2
0
    def modify(self, section):
        if self.has_section(section) == False:
            scolor.info("SECTION不存在: %s" % (section))
            return
        self.list_one(section)

        try:
            #keymap = self._key_map
            val_map = dict()
            for k in self._key_order:
                old_val = self.get_section_dict(section).get(k)
                val = self._get_key_val(k, old_val=old_val)
                if not val: val = ""
                val_map[k] = val

            while True:
                resp = raw_input(u"是否确认修改? (y or n) ")
                if str(resp).strip().lower() in ["n", "no"]:
                    break
                elif str(resp).strip().lower() in ["y", "yes"]:
                    for k in self._key_order:
                        if val_map[k]: self.set(section, k, val_map[k])
                    self.save()
                    break
        except:
            print traceback.format_exc()
示例#3
0
 def list_one(self, section):
     if self.has_section(section) == False: return False
     shper = sstr()
     conf = self.get_section_dict(section)
     scolor.info("################# [ section: %s ]" % (section))
     keymap = self._key_map
     max_key_len = self._max_key_len if self._max_key_len else 12
     for k in self._key_order:
         key_cn = keymap.get(k, "None")
         val = conf.get(k, None)
         print shper.str_rpad(key_cn, width=max_key_len) + ": " + str(val)
示例#4
0
    def modify(self, section):
        if self.has_section(section) == False:
            scolor.info("SECTION不存在: %s" % (section))
            return
        self.list_one(section)

        try:
            keymap = self._key_map
            val_map = dict()
            for k in self._key_order:
                key_cn = keymap.get(k, "None")
                val_map[k] = raw_input(key_cn + ": ")
            while True:
                resp = raw_input(u"是否确认修改? (y or n) ")
                if str(resp).strip().lower() in ["n", "no"]:
                    break
                elif str(resp).strip().lower() in ["y", "yes"]:
                    for k in self._key_order:
                        if val_map[k]: self.set(section, k, val_map[k])
                    self.save()
                    break
        except:
            print traceback.format_exc()
示例#5
0
    def status(self, section_id=None):
        itemconf = self._chp.get_section_dict(section_id)
        appname = itemconf.get("appname", None)
        process_uniq_flag = itemconf.get("process_uniq_flag", None)
        process_port = itemconf.get("process_port", None)
        status_cmd = itemconf.get("status_cmd", None)
        self._logger.dictlog(level="info", width=20, **itemconf)

        scolor.info(u"#### [%s] 检测应用【%s】状态 ####" %
                    (sdate().datetime_human(), appname))
        if status_cmd and str(status_cmd).strip():
            c2 = cmds(status_cmd, timeout=10)
            stdo, stde, retcode = c2.stdo(), c2.stde(), c2.code()
            logdict = {
                "命令": status_cmd,
                "标准输出": stdo,
                "标准错误输出": stde,
                "返回码": retcode,
                "orders": ["命令", "标准输出", "标准错误输出", "返回码"],
            }
            self._logger.dictlog(level="info", width=10, **logdict)
            scolor.info(u"-> 根据用户指定的状态命令检测应用状态")
            print "    命令:%s" % (status_cmd)
            print "执行结果:"
            print "========="
            print str(str(stdo).strip() + "\n" + str(stde).strip()).strip()

        if process_uniq_flag and str(process_uniq_flag).strip():
            (flag, cmdstr, stdo, stde,
             retcode) = self.is_process_exist(process_uniq_flag)
            scolor.info(u"-> 根据应用进程唯一标识检测")
            print "    命令:%s" % (cmdstr)
            print "执行结果:"
            print "========="
            print str(str(stdo).strip() + "\n" + str(stde).strip()).strip()

        if process_port:
            (flag, cmdstr, stdo, stde,
             retcode) = self.is_port_exist(process_port)
            scolor.info(u"-> 根据应用进程端口检测")
            print "    命令:%s" % (cmdstr)
            print "执行结果:"
            print "========="
            print str(str(stdo).strip() + "\n" + str(stde).strip()).strip()
示例#6
0
    def check(self, section_id=None):
        itemconf = self._chp.get_section_dict(section_id)
        appname = itemconf.get("appname", None)
        process_uniq_flag = itemconf.get("process_uniq_flag", None)
        process_port = itemconf.get("process_port", None)
        check_cmd = itemconf.get("check_cmd", None)
        check_str = itemconf.get("check_str", None)
        self._logger.dictlog(level="info", width=20, **itemconf)

        scolor.info(u"#### [%s] 检测应用【%s】运行状态 ####" %
                    (sdate().datetime_human(), appname))

        is_ok = True
        mt_method = {"False": scolor.error, "True": scolor.info}
        if check_cmd and check_str:
            check_flag, cmdstr, stdo, stde, retcode = self.is_check_ok(
                check_cmd, check_str)
            is_ok = is_ok and check_flag
            scolor.info(u"-> 根据检测命令检测")
            mt_method[str(check_flag)](str(check_flag))

        if process_uniq_flag:
            chk_proc_flag, cmdstr, stdo, stde, retcode = self.is_process_exist(
                process_uniq_flag)
            is_ok = is_ok and chk_proc_flag
            scolor.info(u"-> 根据应用进程唯一标识检测")
            mt_method[str(chk_proc_flag)](str(chk_proc_flag))

        if process_port:
            chk_proc_port_flag, cmdstr, stdo, stde, retcode = self.is_port_exist(
                process_port)
            is_ok = is_ok and chk_proc_port_flag
            scolor.info(u"-> 根据应用进程端口检测")
            mt_method[str(chk_proc_port_flag)](str(chk_proc_port_flag))

        return is_ok
示例#7
0
def backup_one(conffile, input_section, debug=False):
    bc = conf_helper(conffile)
    itemconf = bc.get_section_dict(input_section)
    srcdir = itemconf.get("srcdir", None)
    destdir = itemconf.get("destdir", None)
    brange = itemconf.get("range", None)
    files = itemconf.get("files", None)
    logger = slog("/tmp/backup.log", debug=debug)
    if bc.has_section(input_section) == False:
        scolor.info("备份标识不存在: %s" % (input_section))
        return
    logobj = {
        u"备份标识": input_section,
        u"备份目录": srcdir,
        u"存储目录": destdir,
        u"范围(包含or不包含)": brange,
        u"文件(夹)列表": files,
        u"orders": [u"section", u"备份目录", u"存储目录", u"范围(包含or不包含)"]
    }
    logger.dictlog(level="info", width=20, **logobj)

    scolor.info(u"尝试执行备份任务,备份信息如下: ")
    scolor.info(u"===============================")
    print sstr().dictstr(width=20, **logobj)

    try:
        ## src dir
        srcdir = str(srcdir).strip()
        while '//' in str(srcdir):
            srcdir = str(srcdir).replace('//', '/')
        while str(srcdir).endswith('/'):
            srcdir = srcdir[:-1]
        pos = str(srcdir).rfind('/')
        dirroot = srcdir[:pos]  ##
        dirname = srcdir[pos + 1:]  ## relative dir name

        ## dest dir
        destdir = str(destdir).strip()
        while '//' in str(destdir):
            destdir = str(destdir).replace('//', '/')
        while str(destdir).endswith('/') and len(destdir) > 2:
            destdir = destdir[:-1]

        if os.path.exists(srcdir) == False or os.path.exists(destdir) == False:
            scolor.error(u"=> 备份任务")
            infobj = {
                u"状态": u"失败",
                u"错误": u"备份目录或存储目录不存在",
                u"备份目录": srcdir,
                u"存储目录": destdir,
                u"orders": [u"状态", u"错误", u"备份目录", u"存储目录"]
            }
            scolor.error(sstr().dictstr(width=8, **infobj))
            return

        if str(brange).lower().strip() not in ["include", "exclude"]:
            scolor.error(u"=> 备份任务")
            infobj = {
                u"状态": u"失败",
                u"错误": u"备份范围错误,只能是include或exclude",
                u"orders": [u"状态", u"错误"]
            }
            scolor.error(sstr().dictstr(width=4, **infobj))
            return

        ## include or exclude files
        files = str(files).strip()
        files_ary = re.split("[ |,|;]+", files)
        last_files = []
        if files_ary:
            for each_file in files_ary:
                if not each_file: continue
                while '//' in str(each_file):
                    each_file = str(each_file).replace('//', '/')
                while str(each_file).endswith('/'):
                    each_file = each_file[:-1]
                while str(each_file).startswith('/'):
                    each_file = each_file[1:]
                each_file = each_file.replace(" ", "")
                last_files.append(each_file)

        nowdt = sdate().datetime()
        nd = sdate().date()
        tarname = "%s_%s.tar.gz " % (dirname, nowdt)
        tmpfile = "/tmp/%s" % (tarname)
        last_destdir = "%s/%s/" % (destdir, nd)
        subffix = ""
        tar_cmdstr = ""
        if str(brange).lower().strip() == "include":
            for ef in last_files:
                subffix = subffix + dirname + "/" + ef + " "
            if str(subffix).strip() == "":  ## 备份整个目录
                tar_cmdstr = "cd %s && tar czf %s %s" % (dirroot, tmpfile,
                                                         dirname)
            else:  ## 备份指定的目录
                tar_cmdstr = "cd %s && tar czf %s %s" % (dirroot, tmpfile,
                                                         subffix)

        if str(brange).lower().strip() == "exclude":
            for ef in last_files:
                subffix = subffix + "--exclude=" + dirname + "/" + ef + " "
            tar_cmdstr = "cd %s && tar czf %s %s %s" % (dirroot, tmpfile,
                                                        dirname, subffix)

        c1 = cmds(tar_cmdstr, timeout=1800)
        stdo1 = c1.stdo()
        stde1 = c1.stde()
        retcode1 = c1.code()
        logobj = {
            u"命令": tar_cmdstr,
            u"标准输出": stdo1,
            u"错误输出": stde1,
            u"返回码": retcode1,
            u"orders": [u"命令", u"标准输出", u"错误输出", u"返回码"]
        }
        logger.dictlog(level="info", width=12, **logobj)

        ## 打包归档失败
        if retcode1 != 0:
            scolor.error(u"=> 备份任务")
            infobj = {
                u"状态": u"失败",
                u"错误": u"打包归档失败,具体:%s" % (stde1),
                u"orders": [u"状态", u"错误"]
            }
            scolor.error(sstr().dictstr(width=4, **infobj))
            return

        #cmdstr = "mkdir -p %s && mv %s %s && rm -frv %s" % (last_destdir, tmpfile, last_destdir, tmpfile)
        cmdstr = "mkdir -p %s && mv -v %s %s" % (last_destdir, tmpfile,
                                                 last_destdir)
        c2 = cmds(cmdstr)
        stdo2 = c2.stdo()
        stde2 = c2.stde()
        retcode2 = c2.code()
        logobj = {
            u"命令": cmdstr,
            u"标准输出": stdo2,
            u"错误输出": stde2,
            u"返回码": retcode2,
            u"orders": [u"命令", u"标准输出", u"错误输出", u"返回码"]
        }
        logger.dictlog(level="info", width=12, **logobj)
        if retcode2 != 0:
            scolor.error(u"=> 备份任务")
            infobj = {
                u"状态": u"失败",
                u"错误": u"创建目录或移动文件失败,具体:%s" % (stde1),
                u"orders": [u"状态", u"错误"]
            }
            scolor.error(sstr().dictstr(width=4, **infobj))
            return

        scolor.info(u"=> 备份任务")
        infobj = {
            u"状态": u"成功",
            u"原目录": srcdir,
            u"备份位置": "%s%s" % (last_destdir, tarname),
            u"orders": [u"状态", u"原目录"]
        }
        scolor.info(sstr().dictstr(width=8, **infobj))
    except:
        print traceback.format_exc()