示例#1
0
def run_tasks(confs, msgs, callback=None, random=True):
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
    if random:
        shuffle(msgs)
    # print(confs, msgs)
    return Comunication.SendMul(confs, msgs, loop=loop, callback=callback)
示例#2
0
    def show_log_file(self, log_file):
        ip = AppMenu.ip
        session = AppMenu.session
        if '-' not in log_file:
            return
        app, t = log_file.split("-", 1)
        t = t.split(".")[0]

        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)
        w = json.load(open(os.path.join(SERVER_ROOT, ip)))
        msg = Task.build_json(app, date=t, op='log', line=300, session=session)
        code, tag, msg = Comunication.SendOnce(w, msg, loop=loop)
        try:
            cc = msg['reply']['log'] + "\n ===============\n" + msg[
                'reply'].get('err_log', "")
            log('err get:', cc)
        except (KeyError, TypeError) as e:
            cc = str(msg['reply'])
            log('err get:', cc)
        TextPanel.Popup(cc,
                        x=self.start_x - self.width - 3,
                        max_height=Application.height - self.px - 5,
                        width=80,
                        y=self.py + 5,
                        screen=self.screen,
                        exit_keys=[10])
        TextPanel.Cl()
        self.Redraw()
        ShowFi(self)
示例#3
0
def push_all_ini(confs, fname):
    with open(fname) as fp:
        content = fp.read()
    msg = Task.build_json('', op='sync-ini', session='config', content=content)
    msgs = [msg.copy() for i in range(len(confs))]
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
    return Comunication.SendMul(confs, msgs, loop=loop, callback=save_ini)
示例#4
0
 def vi_server_ini(self):
     w = json.load(
         open(os.path.join(SERVER_ROOT,
                           self.get_now_text().strip())))
     data = Task.build_json('', op='get-ini', session='config')
     res = Comunication.SendOnce(w, data)
     content = editor(res[2]['reply'])
     data = Task.build_json('',
                            op="sync-ini",
                            session='config',
                            content=content)
     Stack.run_background(Comunication.SendOnce, w, data)
示例#5
0
def pull_all_session(confs):
    async def _save_session(code, tag, reply):
        if code == 0:
            ip = reply['ip']
            with open(os.path.join(SERVER_SESSION, ip), 'w') as fp:
                fp.write('\n'.join(reply['reply']))
        else:
            L(reply)

    msg = Task.build_json('', op='session', session='config')
    msgs = [msg.copy() for i in range(len(confs))]
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
    return Comunication.SendMul(confs, msgs, loop=loop, callback=_save_session)
示例#6
0
 def show_log(self, ip, refresh=False):
     if refresh:
         loop = asyncio.new_event_loop()
         asyncio.set_event_loop(loop)
         w = json.load(open(os.path.join(SERVER_ROOT, ip)))
         log(w)
         msg = Task.build_json('', op='info', session='config')
         code, tag, msg = Comunication.SendOnce(w, msg, loop=loop)
         log(msg)
         sessions = msg['reply']['session']
     else:
         if ip in IpMenu.infos:
             AppMenu.apps = IpMenu.infos[ip]['app']
             sessions = IpMenu.infos[ip]['session']
         else:
             loop = asyncio.new_event_loop()
             asyncio.set_event_loop(loop)
             w = json.load(open(os.path.join(SERVER_ROOT, ip)))
             msg = Task.build_json('', op='info', session='config')
             code, tag, msg = Comunication.SendOnce(w, msg, loop=loop)
             log(msg)
             sessions = msg['reply']['session']
             AppMenu.apps = msg['reply']['app']
     AppMenu.from_res(ip, sessions)
示例#7
0
 def get_logs(cls, ip, session):
     if ip in IpMenu.infos:
         session = session[0] if isinstance(session, list) else session
         res = IpMenu.infos[ip]
         logs = []
         for log in res['ps']:
             if log.startswith(session):
                 # logs[log.split("/")[0]] = res['ps'][log]
                 logs.append(log.split("/")[1])
         return logs
     else:
         session = session[0] if isinstance(session, list) else session
         loop = asyncio.new_event_loop()
         asyncio.set_event_loop(loop)
         w = json.load(open(os.path.join(SERVER_ROOT, ip)))
         msg = Task.build_json('', op='check', session=session)
         code, tag, msg = Comunication.SendOnce(w, msg, loop=loop)
         return list(msg['reply'].keys())
示例#8
0
 def run_task(self, target, servers, apps, session, op='run', **kwargs):
     loop = asyncio.new_event_loop()
     asyncio.set_event_loop(loop)
     msgs = Task.build_jsons(apps,
                             op=op,
                             session=session,
                             ip=target,
                             option='',
                             background=True,
                             **kwargs)
     log(msgs)
     ws = []
     for s in servers:
         with open(os.path.join(SERVER_ROOT, s)) as fp:
             w = json.load(fp)
             ws.append(w)
     mul_res = Comunication.SendMul(ws, msgs, loop=loop)
     log(mul_res)
     msgs = [i[-1] for i in mul_res]
     return msgs
示例#9
0
def main():
    args = parser.parse_args()
    w = None
    conf = get_local_config()
    #if 'last_session' not in list(conf['client'].keys()):
    #    update('client','last_session', args.session)
    #    conf = get_local_config()
    #else:
    #    update('client','last_session', args.session)

    #if 'last_op' not in list(conf['client'].keys()):
    #    update('client','last_op', args.op)
    #    conf = get_local_config()
    #
    #if 'last_app' not in list(conf['client'].keys()):
    #    if not args.app:
    #        app = ''
    #    else:
    #        app = args.app[0]
    #    update('client','last_app', app)
    #    conf = get_local_config()

    #last_session = conf['client']['last_session']
    #last_app = conf['client']['last_app']
    #last_op = conf['client']['last_op']
    #if '-s' not in sys.argv:
    #    args.session = last_session
    #if '--op' not in sys.argv and '-l' not in sys.argv :
    #    args.op = last_op

    L('session: ', args.session, 'op: ', args.op)

    if args.generate_sec_conf:
        d = {}
        ip = [
            i.strip() for i in os.popen("ifconfig").read().split("\n")
            if 'inet' in i and '127.0.0.1' not in i and '::' not in i
        ][0].split()[1]
        print("server ip: %s" % ip)
        for k in ['server_port', 'password', 'method']:
            v = input(k)
            if not v:
                raise Exception("%s : must a val" % k)
            d[k] = v
        d['server'] = ip
        with open("seed-node-server.json", "w") as fp:
            json.dump(d, fp)
        sys.exit(0)
    if args.conf:
        f = args.conf
        with open(f) as fp:
            w = json.load(fp)
            assert 'server' in w
            assert 'server_port' in w
            assert 'password' in w
            assert 'method' in w

    if args.daemon:
        if args.updater:
            if args.daemon == 'start':
                assert w is not None
                daemon_exec(pid_file="/var/run/hack-updater.pid",
                            log_file="/var/log/hack-updater.log")
                w['server_port'] = str(int(w['server_port']) + 1)
                w['server'] = 'localhost'
                run_server(w)
            elif args.daemon == 'stop':

                daemon_exec(command='stop',
                            pid_file='/var/run/hack-updater.pid',
                            log_file='/var/log/hack-updater.log')
                run_server(w)
        else:
            if args.daemon == 'start':
                assert w is not None
                daemon_exec()
                run_server(w)
            elif args.daemon == 'stop':
                daemon_exec(command='stop')
                run_server(w)

    if args.push_ini and os.path.exists(args.push_ini):
        with open(args.sync_ini) as fp:
            content = fp.read()
        data = Task.build_json('',
                               op="sync-ini",
                               session=args.session,
                               content=content)
        res = Comunication.SendOnce(w, data)
        L(res[2]['reply'])
        sys.exit(0)

    if args.vi_ini:
        data = Task.build_json('',
                               op='get-ini',
                               session=args.session,
                               **{
                                   'option': args.option,
                                   'background': args.not_background,
                                   'date': args.time
                               })
        res = Comunication.SendOnce(w, data)
        L(res[2]['reply'])
        content = editor(res[2]['reply'])
        data = Task.build_json('',
                               op="sync-ini",
                               session=args.session,
                               content=content)
        res = Comunication.SendOnce(w, data)
        try:
            L(res[2]['reply'])
        except Exception:
            L(res[2])

        if os.path.exists("/tmp/tmp.ini"):
            os.remove('/tmp/tmp.ini')
        sys.exit(0)

    if w and args.app:
        # args.op = 'run'
        if len(args.app) == 1:
            target = ''
        else:
            target = args.app[1]
        app = args.app[0]
        if args.op.strip() == 'install':
            args.session = 'config'
        data = Task.build_json(app,
                               op=args.op,
                               session=args.session,
                               **{
                                   getattr(args, 'as'): target,
                                   'option': args.option,
                                   'background': args.not_background,
                                   'date': args.time
                               })
        res = Comunication.SendOnce(w, data)
        try:
            L(res[2]['reply'])
            sys.exit(0)
        except Exception as e:
            L(res[2])
            sys.exit(1)

    if args.log:
        args.op = 'log'
        args.app = args.log[0]
        app = args.log[0]
        if len(args.log) == 2:
            lines = args.log[1]
            time = args.time
        elif len(args.log) == 3:
            lines = args.log[1]
            time = args.log[2]
        else:
            lines = '50'
            time = args.time

        data = Task.build_json(app,
                               op='log',
                               session=args.session,
                               **{
                                   'option': args.option,
                                   'background': args.not_background,
                                   'date': time,
                                   'line': lines
                               })
        res = Comunication.SendOnce(w, data)
        try:
            L(res[2]['reply'])
            sys.exit(0)
        except Exception as e:
            L(res[2])
            sys.exit(1)

    if w and args.op != 'run':
        if args.app:
            app = args.app[0]
        else:
            app = ''
        if args.op.strip() == 'install':
            args.session = 'config'
        # L("session:",args.session)
        data = Task.build_json(app,
                               op=args.op,
                               session=args.session,
                               **{
                                   'option': args.option,
                                   'background': args.not_background,
                                   'date': args.time
                               })
        res = Comunication.SendOnce(w, data)
        try:
            L(res[2]['reply'])
            sys.exit(0)
        except Exception as e:
            L(res[2])
            sys.exit(1)

    if args.test:
        args.op = 'test'
    if w and args.test:

        data = Task.build_json("", session=args.session, op="test")
        res = Comunication.SendOnce(w, data)
        L(res[2]['reply'])
        sys.exit(0)

    if args.remote_help:
        data = Task.build_json('',
                               op='ls',
                               session=args.session,
                               **{
                                   'option': args.option,
                                   'background': args.not_background,
                                   'date': args.time
                               })
        res = Comunication.SendOnce(w, data)
        try:
            L(res[2]['reply'])
            sys.exit(0)
        except Exception as e:
            L(res[2])
            sys.exit(1)

    if args.init:
        init(args.init)
        sys.exit(0)

    if args.init_from_db:
        db_file = os.path.expanduser("~/.config/seed/cache.db")
        if os.path.exists(db_file):
            res = init_from_db(db_file, args.init_from_db)
            for r in res:
                L(r)

    if args.tree:
        data = Task.build_json('tree',
                               op='run',
                               session=args.session,
                               **{
                                   getattr(args, 'as'): '/tmp/tasks',
                                   'option': args.option,
                                   'background': False,
                                   'date': args.time
                               })
        res = Comunication.SendOnce(w, data)
        try:
            L(res[2]['reply'])
            sys.exit(0)
        except Exception as e:
            L(res[2])
            sys.exit(1)

    if args.conf_select:
        confs = list(select(args.conf_select))
    else:
        sys.exit(0)
        # L(confs)
    if args.sync_ini and os.path.exists(args.sync_ini):
        confs = list(select(args.conf_select))
        push_all_ini(confs, args.sync_ini)
        sys.exit(0)

    if args.pull_ini:
        confs = list(select(args.conf_select))
        pull_all_ini(confs)
        sys.exit(0)

    if args.app:
        app = [args.app[0]]
        if len(args.app) > 1:
            target = args.app[1:]
            L("targets:", target)
        else:
            target = []
    else:
        app = []
        target = []

    msgs = list(
        build_tasks(confs,
                    apps=app,
                    op=args.op,
                    targets=target,
                    option=args.option,
                    session=args.session,
                    date=args.time,
                    background=args.not_background,
                    line=50))
    for r in run_tasks(confs, msgs):
        if 'tree' in r[2]:
            L(r[2]['tree'])
        else:

            if 'reply' in r[2] and isinstance(r[2]['reply'], dict):
                L(r[2]['ip'], r[2]['reply'])
            else:
                L(r[2])
示例#10
0
def pull_all_ini(confs):
    msg = Task.build_json('', op='get-ini', session='config')
    msgs = [msg.copy() for i in range(len(confs))]
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
    return Comunication.SendMul(confs, msgs, loop=loop, callback=save_ini)