~rootmos/action

0096ee468c4609a343c71fc003b05819c735d6ad — Gustav Behm 7 months ago 4fe14ab
Restructure main()
1 files changed, 39 insertions(+), 31 deletions(-)

M src/action/cli.py
M src/action/cli.py => src/action/cli.py +39 -31
@@ 84,49 84,57 @@ class Action:
            logger.info(f"action {self.action.name} triggered: {j}")
            self.action.trigger()

def main():
    args = parse_args()
    if args.log_file is not None:
        sys.stderr = sys.stdout = open(args.log_file, "a")
    util.setup_logger(args.log)
    logger.debug(f"args: {args}")

def mk_socket_path(args):
    socket_path = args.socket
    if socket_path is None:
        socket_path = os.path.join(args.socket_root, args.action)
    return socket_path

    if args.cmd == "bind":
        stop = asyncio.Event()
        async def act():
def bind(args):
    stop = asyncio.Event()
    async def act():
        stop.set()

    class Exit:
        def __init__(self):
            self.status = 0

        def interrupt(self):
            self.status = 1
            stop.set()
    ec = Exit()

        class Exit:
            def __init__(self):
                self.status = 0
    action = Action(name=args.action, coro=act)

            def interrupt(self):
                self.status = 1
                stop.set()
        ec = Exit()
    async def main():
        loop = asyncio.get_running_loop()

        action = Action(name=args.action, coro=act)
        loop.add_signal_handler(signal.SIGINT, ec.interrupt)

        async def main():
            loop = asyncio.get_running_loop()
        await action.bind(mk_socket_path(args))
        await stop.wait()

            loop.add_signal_handler(signal.SIGINT, ec.interrupt)
    asyncio.run(main())
    sys.exit(ec.status)

            await action.bind(socket_path)
            await stop.wait()
def trigger(args):
    msg = {
        "action": args.action,
        "timestamp": datetime.datetime.utcnow().astimezone().isoformat(timespec='seconds'),
    }
    s = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
    s.sendto(json.dumps(msg).encode("UTF-8"), mk_socket_path(args))
    s.close()

        asyncio.run(main())
        sys.exit(ec.status)
def main():
    args = parse_args()
    if args.log_file is not None:
        sys.stderr = sys.stdout = open(args.log_file, "a")
    util.setup_logger(args.log)
    logger.debug(f"args: {args}")

    if args.cmd == "bind":
        bind(args)
    elif args.cmd == "trigger":
        msg = {
            "action": args.action,
            "timestamp": datetime.datetime.utcnow().astimezone().isoformat(timespec='seconds'),
        }
        s = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
        s.sendto(json.dumps(msg).encode("UTF-8"), socket_path)
        s.close()
        trigger(args)