Exemplo n.º 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)
Exemplo n.º 2
0
 def _get_key_val(self, k, old_val=None):
     keymap = self._key_map
     key_cn = keymap.get(k, "Not_Assign")
     is_continue = True
     while is_continue == True:
         val = raw_input(key_cn + ": ")
         if val == "":
             val = old_val  ## 如果不输入任何值,则用旧值作为默认值,适用于修改数据的情况,避免校验失败
         check_func = self._key_check.get(k, None)
         if not check_func:
             return val
         if check_func and type(check_func) == types.FunctionType:
             (is_check_ok, msg) = check_func(val)
             if is_check_ok == True:
                 return val
             else:
                 scolor.error("参数校验失败,信息:%s" % (msg))
                 while True:
                     resp = raw_input(u"是否继续? (y or n) ")
                     if str(resp).strip().lower() in ["n", "no"]:
                         is_continue = False
                         break
                     elif str(resp).strip().lower() in ["y", "yes"]:
                         break
     return None
Exemplo n.º 3
0
    def add(self):
        try:
            while True:
                section = raw_input(u"SECTION名(英文唯一标识): ")
                if section and str(section).strip() != "": break

            if self.has_section(section) == True:
                scolor.error("SECTION名已存在: %s" % (section))
                self.list_one(section)
                return False

            val_map = dict()
            for k in self._key_order:
                val = self._get_key_val(k)
                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
                if str(resp).strip().lower() in ["y", "yes"]:
                    self.add_section(section)
                    for k in self._key_order:
                        self.set(section, k, val_map[k])
                    self.save()
                    break
        except:
            print traceback.format_exc()
Exemplo n.º 4
0
    def add(self):
        try:
            section = raw_input(u"SECTION名(英文唯一标识): ")

            if self.has_section(section) == True:
                scolor.error("SECTION名已存在: %s" % (section))
                self.list_one(section)
                return False

            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
                if str(resp).strip().lower() in ["y", "yes"]:
                    self.add_section(section)
                    for k in self._key_order:
                        self.set(section, k, val_map[k])
                    self.save()
                    break
        except:
            print traceback.format_exc()
Exemplo n.º 5
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()
Exemplo n.º 6
0
def main():
    try:
        parser = OptionParser()
        parser.add_option("-c",
                          "--conf",
                          action="store",
                          dest="conf",
                          default=None,
                          help="configure file",
                          metavar="${backup_conf_file}")
        parser.add_option("-l",
                          "--list",
                          dest="list",
                          default=False,
                          action="store_true",
                          help="list all the configure")
        parser.add_option("-a",
                          "--add",
                          dest="add",
                          default=False,
                          action="store_true",
                          help="add configure to config file")
        parser.add_option("-m",
                          "--modify",
                          dest="modify",
                          default=False,
                          action="store_true",
                          help="modify backup configure to config file")
        parser.add_option("-d",
                          "--delete",
                          dest="delete",
                          default=False,
                          action="store_true",
                          help="delete backup configure from config file")
        parser.add_option("-D",
                          "--debug",
                          dest="debug",
                          default=False,
                          action="store_true",
                          help="if open debug module")
        parser.add_option("-i",
                          "--id",
                          action="store",
                          dest="id",
                          default=None,
                          help="which id's configure to be loaded to execute",
                          metavar="${id}")
        parser.add_option(
            "-s",
            "--signal",
            action="store",
            dest="signal",
            default=None,
            help="signal like: start, stop, restart, status, monitor",
            metavar="${signal}")

        (options, args) = parser.parse_args()
        list_flag = options.list
        conffile = options.conf
        add_flag = options.add
        modify_flag = options.modify
        delete_flag = options.delete
        debug_flag = options.debug
        section_id = options.id
        signal = options.signal

        if not conffile:
            conffile = get_realpath() + "/etc/opsctl.conf"

        if os.path.exists(conffile) == False:
            conffile = "/etc/opsctl.conf"
            if os.path.exists(conffile) == False:
                parser.print_help()
                sys.exit(1)

        tmp_list = [list_flag, add_flag, modify_flag, delete_flag]
        cnt = 0
        for a in tmp_list:
            if a == True: cnt += 1

        if cnt > 1:
            parser.print_help()
            sys.exit(1)

        key_map = {
            "appname": u"应用名称",
            "process_uniq_flag": u"进程唯一标识",
            "process_port": u"进程端口",
            "start_cmd": u"启动命令",
            "stop_cmd": u"停止命令",
            "status_cmd": u"状态命令",
            "check_cmd": u"检测命令",
            "check_str": u"检测字符串",
        }
        key_order = [
            "appname", "process_uniq_flag", "process_port", "start_cmd",
            "stop_cmd", "status_cmd", "check_cmd", "check_str"
        ]
        chp = conf_helper(conffile,
                          key_map=key_map,
                          key_order=key_order,
                          max_key_len=12)

        wk = Work(chp=chp, debug=debug_flag)
        ## backup the input section
        method_map = {
            "start": wk.start,
            "stop": wk.stop,
            "restart": wk.restart,
            "status": wk.status,
            "monitor": wk.monitor,
        }

        if signal and signal not in method_map.keys():
            parser.print_help()
            sys.exit(1)

        ## action
        if signal and section_id:
            if chp.has_section(section_id) == False:
                scolor.error(u"不存在Section: %s" % (section_id))
                return
            method_map[signal](section_id)
            return

        ## list all
        if list_flag == True and not section_id:
            chp.list()
            return

        ## list one
        if list_flag == True and section_id and not signal:
            chp.list_one(section_id)
            return

        ## delete one
        if delete_flag and section_id and not signal:
            chp.delete(section_id)
            return

        ## modify one
        if modify_flag and section_id and not signal:
            chp.modify(section_id)
            return

        ## add one
        if add_flag and not section_id and not signal:
            chp.add()
            return

        ## monitor all
        if signal == "monitor" and not section_id:
            secs = chp.sections()
            for sid in secs:
                method_map["monitor"](sid)
            return

        parser.print_help()

    except Exception as expt:
        print traceback.format_exc()