#! /opt/cloud_sdk/bin/python

import asyncio
import logging
import subprocess
import sys
import citc_cloud



def handle_exception(exc_type, exc_value, exc_traceback):
    if issubclass(exc_type, KeyboardInterrupt):
        sys.__excepthook__(exc_type, exc_value, exc_traceback)
        return

    log.critical("Uncaught exception", exc_info=(exc_type, exc_value, exc_traceback))


async def main() -> None:
    nodespace = citc_cloud.get_nodespace()

    keys_file = "/home/slurm/opc_authorized_keys"

    with open(keys_file) as kf:
        ssh_keys = kf.read()

    hosts = subprocess.run(["scontrol", "show", "hostnames", sys.argv[1]], stdout=subprocess.PIPE).stdout.decode().split()

    await asyncio.gather(*(
        citc_cloud.start_node( log, host, nodespace, ssh_keys)
        for host in hosts
    ))

sys.excepthook = handle_exception

if __name__ == "__main__":
    log = logging.getLogger("startnode")
    log.setLevel(logging.INFO)
    handler = logging.FileHandler('/var/log/slurm/elastic.log')
    formatter = logging.Formatter('%(asctime)s %(name)-10s %(levelname)-8s %(message)s')
    handler.setFormatter(formatter)
    log.addHandler(handler)

    loop = asyncio.get_event_loop()
    try:
        loop.run_until_complete(main())
    finally:
        loop.close()

[((20, 16, 20, 42), 'citc_cloud.get_nodespace', 'citc_cloud.get_nodespace', ({}, {}), '()', False, 'import citc_cloud\n'), ((37, 10, 37, 40), 'logging.getLogger', 'logging.getLogger', ({(37, 28, 37, 39): '"""startnode"""'}, {}), "('startnode')", False, 'import logging\n'), ((39, 14, 39, 63), 'logging.FileHandler', 'logging.FileHandler', ({(39, 34, 39, 62): '"""/var/log/slurm/elastic.log"""'}, {}), "('/var/log/slurm/elastic.log')", False, 'import logging\n'), ((40, 16, 40, 88), 'logging.Formatter', 'logging.Formatter', ({(40, 34, 40, 87): '"""%(asctime)s %(name)-10s %(levelname)-8s %(message)s"""'}, {}), "('%(asctime)s %(name)-10s %(levelname)-8s %(message)s')", False, 'import logging\n'), ((44, 11, 44, 35), 'asyncio.get_event_loop', 'asyncio.get_event_loop', ({}, {}), '()', False, 'import asyncio\n'), ((13, 8, 13, 62), 'sys.__excepthook__', 'sys.__excepthook__', ({(13, 27, 13, 35): 'exc_type', (13, 37, 13, 46): 'exc_value', (13, 48, 13, 61): 'exc_traceback'}, {}), '(exc_type, exc_value, exc_traceback)', False, 'import sys\n'), ((30, 8, 30, 62), 'citc_cloud.start_node', 'citc_cloud.start_node', ({(30, 31, 30, 34): 'log', (30, 36, 30, 40): 'host', (30, 42, 30, 51): 'nodespace', (30, 53, 30, 61): 'ssh_keys'}, {}), '(log, host, nodespace, ssh_keys)', False, 'import citc_cloud\n'), ((27, 12, 27, 98), 'subprocess.run', 'subprocess.run', (), '', False, 'import subprocess\n')]