Esempio n. 1
0
def _run_swarm_manager(args):
    containers_config_file = _containers_config_file(args)
    containers_conf = parse_containers_config(containers_config_file)
    container_conf = _container_conf(containers_conf, args.swarm)
    swarm_manager_conf = _swarm_manager_conf(container_conf)
    _configure_logging(args, swarm_manager_conf)
    docker_interface = build_container_interfaces(containers_config_file, containers_conf=containers_conf)[args.swarm]
    pidfile = _swarm_manager_pidfile(swarm_manager_conf)

    if not args.foreground:
        _swarm_manager_daemon(pidfile, swarm_manager_conf['log_file'], swarm_manager_conf, docker_interface)
    else:
        if swarm_manager_conf['terminate_when_idle']:
            log.info('running in the foreground, disabling automatic swarm manager termination')
            swarm_manager_conf['terminate_when_idle'] = False
        else:
            log.info("running in the foreground")
        try:
            pidfile.acquire()
        except lockfile.AlreadyLocked:
            pid = pidfile.read_pid()
            try:
                os.kill(pid, 0)
                log.warning("swarm manager is already running in pid %s", pid)
                return
            except OSError:
                log.warning("removing stale lockfile: %s", pidfile.path)
                pidfile.break_lock()
                pidfile.acquire()
        try:
            _swarm_manager(swarm_manager_conf, docker_interface)
        finally:
            pidfile.release()
def _run_swarm_manager(args):
    containers_config_file = _containers_config_file(args)
    containers_conf = parse_containers_config(containers_config_file)
    container_conf = _container_conf(containers_conf, args.swarm)
    swarm_manager_conf = _swarm_manager_conf(container_conf)
    _configure_logging(args, swarm_manager_conf)
    docker_interface = build_container_interfaces(
        containers_config_file, containers_conf=containers_conf)[args.swarm]
    pidfile = _swarm_manager_pidfile(swarm_manager_conf)

    if not args.foreground:
        _swarm_manager_daemon(pidfile, swarm_manager_conf['log_file'],
                              swarm_manager_conf, docker_interface)
    else:
        if swarm_manager_conf['terminate_when_idle']:
            log.info(
                'running in the foreground, disabling automatic swarm manager termination'
            )
            swarm_manager_conf['terminate_when_idle'] = False
        else:
            log.info("running in the foreground")
        pidfile.acquire()
        try:
            _swarm_manager(swarm_manager_conf, docker_interface)
        finally:
            pidfile.release()
Esempio n. 3
0
def _run_swarm_manager(args):
    containers_config_file = _containers_config_file(args)
    containers_conf = parse_containers_config(containers_config_file)
    container_conf = _container_conf(containers_conf, args.swarm)
    swarm_manager_conf = _swarm_manager_conf(container_conf)
    _configure_logging(args, swarm_manager_conf)
    docker_interface = build_container_interfaces(containers_config_file, containers_conf=containers_conf)[args.swarm]
    pidfile = _swarm_manager_pidfile(swarm_manager_conf)

    if not args.foreground:
        _swarm_manager_daemon(pidfile, swarm_manager_conf['log_file'], swarm_manager_conf, docker_interface)
    else:
        if swarm_manager_conf['terminate_when_idle']:
            log.info('running in the foreground, disabling automatic swarm manager termination')
            swarm_manager_conf['terminate_when_idle'] = False
        else:
            log.info("running in the foreground")
        pidfile.acquire()
        try:
            _swarm_manager(swarm_manager_conf, docker_interface)
        finally:
            pidfile.release()
Esempio n. 4
0
def main():
    # Option handling
    parser = argparse.ArgumentParser(
        epilog='ELM327-emulator v' + __version__ +
        ' - ELM327 OBD-II adapter emulator')
    parser.prog = "elm"
    parser.add_argument(
        '-V',
        "--version",
        dest='version',
        action='store_true',
        help="print ELM327-emulator version and exit")
    if os.name != 'nt':
        parser.add_argument(
            '-t',
            "--terminate",
            dest='terminate',
            action='store_true',
            help="terminate the daemon process sending SIGTERM")
        parser.add_argument(
            "-d", "--daemon",
            dest = "daemon_mode",
            action='store_true',
            help = "Run ELM327-emulator in daemon mode. ")
    parser.add_argument(
        "-b", "--batch",
        dest="batch_mode",
        type=argparse.FileType('w'),
        help="Run ELM327-emulator in batch mode. "
             "Argument is the output file. "
             "The first line in that file will be the virtual serial device",
        default=0,
        nargs=1,
        metavar='FILE')
    parser.add_argument(
        '-p', '--port',
        dest = 'serial_port',
        help = "Set the com0com serial port listened by ELM327-emulator "
               "when running under windows OS. Default is COM3.",
        default = ['COM3'],
        nargs = 1,
        metavar = 'PORT'
    )
    parser.add_argument(
        '-a', '--baudrate',
        dest = 'serial_baudrate',
        type=int,
        help = "Set the serial device baud rate used by ELM327-emulator.",
        default = None,
        nargs = 1,
        metavar = 'BAUDRATE'
    )
    parser.add_argument(
        '-s', '--scenario',
        dest = 'scenario',
        help = "Set the scenario used by ELM327-emulator.",
        default = [''],
        nargs = 1,
        metavar = 'SCENARIO'
    )
    parser.add_argument(
        '-n', '--net',
        dest = 'net_port',
        type=int,
        help = "Set the INET socket port used by ELM327-emulator.",
        default = None,
        nargs = 1,
        metavar = 'INET_PORT'
    )
    parser.add_argument(
        '-H', '--forward_host',
        dest = 'forward_net_host',
        help = "Set the INET host used by ELM327-emulator."
            "when forwarding the client interaction to a remote OBD-II port.",
        default = None,
        nargs = 1,
        metavar = 'INET_FORWARD_HOST'
    )
    parser.add_argument(
        '-N', '--forward_port',
        dest = 'forward_net_port',
        type=int,
        help = "Set the INET socket port used by ELM327-emulator "
            "when forwarding the client interaction to a remote OBD-II port.",
        default = None,
        nargs = 1,
        metavar = 'INET_FORWARD_PORT'
    )
    parser.add_argument(
        '-S', '--forward_serial_port',
        dest = 'forward_serial_port',
        help = "Set the serial device port used by ELM327-emulator "
            "when forwarding the client interaction to a serial device.",
        default = None,
        nargs = 1,
        metavar = 'FORWARD_SERIAL_PORT'
    )
    parser.add_argument(
        '-B', '--forward_serial_baudrate',
        dest = 'forward_serial_baudrate',
        type=int,
        help = "Set the device baud rate used by ELM327-emulator "
            "when forwarding the client interaction to a serial device.",
        default = None,
        nargs = 1,
        metavar = 'FORWARD_SERIAL_BAUDRATE'
    )
    parser.add_argument(
        '-T', '--forward_timeout',
        dest = 'forward_timeout',
        type=float,
        help = "Set forward timeout as floating number "
            "(default is 5 seconds).",
        default = None,
        nargs = 1,
        metavar = 'FORWARD_TIMEOUT'
    )
    args = parser.parse_args()

    if args.version:
        print(f'ELM327-emulator version {__version__}.')
        sys.exit(0)

    # Redirect stdout
    if args.batch_mode and not args.batch_mode[0].isatty():
        sys.stdout = args.batch_mode[0]

    # Instantiate the class
    if os.name == 'nt':
        args.daemon_mode = False
        args.terminate = False

    emulator = Elm(
        batch_mode=args.batch_mode or args.daemon_mode,
        serial_port=args.serial_port[0],
        serial_baudrate=args.serial_baudrate[0]
            if args.serial_baudrate else None,
        net_port=args.net_port[0]
            if args.net_port else None,
        forward_net_host=args.forward_net_host[0]
            if args.forward_net_host else None,
        forward_net_port=args.forward_net_port[0]
            if args.forward_net_port else None,
        forward_serial_port=args.forward_serial_port[0]
            if args.forward_serial_port else None,
        forward_serial_baudrate = args.forward_serial_baudrate[0]
            if args.forward_serial_baudrate else None,
        forward_timeout = args.forward_timeout[0]
            if args.forward_timeout else None)

    if os.name != 'nt':
        if os.getuid() == 0:
            daemon_pid_fname = DAEMON_PIDFILE_DIR_ROOT + DAEMON_PIDFILE
        else:
            daemon_pid_fname = DAEMON_PIDFILE_DIR_NON_ROOT + DAEMON_PIDFILE
        pidfile = daemon.pidfile.PIDLockFile(daemon_pid_fname)
        pid = pidfile.read_pid()

    if args.terminate:
        if pid:
            print(f'Terminating daemon process {pid}.')
            try:
                Ret = os.kill(pid, signal.SIGTERM)
            except Exception as e:
                print(f'Error while terminating daemon process {pid}: {e}.')
                sys.exit(1)
            if Ret:
                print(f'Error while terminating daemon process {pid}.')
                sys.exit(1)
            else:
                sys.exit(0)
        else:
            print('Cannot terminate daemon process: not running.')
            sys.exit(0)

    if args.batch_mode and args.daemon_mode:
        try:
            print(emulator.get_pty())
            print('ELM327-emulator service STARTED')
            if args.scenario[0]:
                set_scenario(emulator, args.scenario[0])
            emulator.run()
        except (KeyboardInterrupt, SystemExit):
            emulator.terminate()
        print("\nELM327-emulator service ENDED")
        sys.exit(0)

    if args.daemon_mode and not args.batch_mode:
        if pid:
            try:
                pidfile.acquire()
                pidfile.release() # this might occur only in rare contention cases
            except AlreadyLocked:
                try:
                    os.kill(pid, 0)
                    print(f'Process {pid} already running. '
                        f'Check lockfile "{daemon_pid_fname}".')
                    sys.exit(1)
                except OSError:  #No process with locked PID
                    pidfile.break_lock()
                    print(f"Previous process {pid} terminated abnormally.")
            except NotLocked:
                print("Internal error: lockfile", daemon_pid_fname)
        context = daemon.DaemonContext(
            working_directory=DAEMON_DIR,
            umask=DAEMON_UMASK,
            pidfile=pidfile,
            detach_process=True,
            stdout=sys.stdout,
            stderr=sys.stderr,
            signal_map={
                signal.SIGTERM: lambda signum, frame: emulator.terminate(),
                signal.SIGINT: lambda signum, frame: emulator.terminate()
                }
            )
        try:
            with context:
                print('ELM327-emulator daemon service STARTED on ',
                    emulator.get_pty())
                if args.scenario[0]:
                    set_scenario(emulator, args.scenario[0])
                emulator.run()
                print("\nELM327-emulator daemon service ENDED")
        except LockFailed as e:
            print('Internal error: cannot start daemon', e)
            sys.exit(1)
        sys.exit(0)

    if os.name != 'nt' and pid:
        print(f'Warning: lockfile "{daemon_pid_fname}" reports pid {pid}.')

    p_elm = None
    pty_name = None
    try:
        with emulator as session:
            while session.threadState == session.THREAD.STARTING:
                time.sleep(0.1)
            if args.net_port:
                pty_name = "TCP network port " + str(args.net_port[0]) + "."
            else:
                pty_name = session.get_pty()
                if args.batch_mode:
                    print(pty_name)
                sys.stdout.flush()
            if session.threadState == session.THREAD.TERMINATED:
                print('\nELM327-emulator cannot run. Exiting.\n')
                os._exit(1)  # does not raise SystemExit
            if args.scenario[0]:
                set_scenario(session, args.scenario[0])
            if pty_name == None:
                print("\nCannot start ELM327-emulator.\n")
                os._exit(1) # does not raise SystemExit
            p_elm = Interpreter(session, args)
            if args.batch_mode:
                p_elm.cmdloop_with_keyboard_interrupt(
                    'ELM327-emulator batch mode STARTED\n'
                    'Begin batch commands.')
            else:
                p_elm.cmdloop_with_keyboard_interrupt(
                    'Welcome to the ELM327 OBD-II adapter emulator.\n'
                    'ELM327-emulator is running on %s\n'
                    'Type help or ? to list commands.\n' % pty_name)
    except (KeyboardInterrupt, SystemExit):
        if not args.batch_mode and p_elm:
            p_elm.postloop()
            print('\n\nExiting.\n')
        else:
            print("\nELM327-emulator batch mode ENDED")
        sys.exit(1)
Esempio n. 5
0
def main():
    # Option handling
    parser = argparse.ArgumentParser(
        epilog=f"hostp2pd v.{__version__} - The Wi-Fi Direct "
        " Session Manager. wpa_cli controller of Wi-Fi "
        " Direct connections handled by wpa_supplicant.")
    parser.prog = "hostp2pd"
    parser.add_argument(
        "-V",
        "--version",
        dest="version",
        action="store_true",
        help="print hostp2pd version and exit",
    )
    parser.add_argument(
        "-v",
        "--verbosity",
        dest="verbosity",
        action="store_true",
        help="print execution logging",
    )
    parser.add_argument(
        "-vv",
        "--debug",
        dest="debug",
        action="store_true",
        help="print debug logging information",
    )
    parser.add_argument(
        "-t",
        "--terminate",
        dest="terminate",
        action="store_true",
        help="terminate a daemon process sending SIGTERM",
    )
    parser.add_argument(
        "-r",
        "--reload",
        dest="reload",
        action="store_true",
        help="reload configuration of a daemon process sending SIGHUP",
    )
    parser.add_argument(
        "-c",
        "--config",
        dest="config_file",
        type=argparse.FileType("r"),
        help="Configuration file.",
        default=0,
        nargs=1,
        metavar="CONFIG_FILE",
    )
    parser.add_argument(
        "-d",
        "--daemon",
        dest="daemon_mode",
        action="store_true",
        help="Run hostp2pd in daemon mode. ",
    )
    parser.add_argument(
        "-b",
        "--batch",
        dest="batch_mode",
        type=argparse.FileType("w"),
        help="Run hostp2pd in batch mode. "
        "Argument is the output file. "
        "Use an hyphen (-) for standard output.",
        default=0,
        nargs=1,
        metavar="FILE",
    )
    parser.add_argument(
        "-i",
        "--interface",
        dest="interface",
        help="Set the interface managed by hostp2pd.",
        default=["auto"],
        nargs=1,
        metavar="INTERFACE",
    )
    parser.add_argument(
        "-p",
        "--run_program",
        dest="run_program",
        help="Name of the program to run with start and stop arguments. ",
        default=[""],
        nargs=1,
        metavar="RUN_PROGRAM",
    )
    args = parser.parse_args()

    if args.version:
        print(f"hostp2pd version {__version__}.")
        sys.exit(0)

    # Redirect stdout
    if args.batch_mode and not args.batch_mode[0].isatty():
        sys.stdout = args.batch_mode[0]

    # Configuration file
    if args.config_file and args.config_file[0].name:
        config_file = args.config_file[0].name
    else:
        config_file = None

    # Debug
    force_logging = None
    if args.verbosity:
        force_logging = logging.INFO
    if args.debug:
        force_logging = logging.DEBUG

    # Instantiate the class
    hostp2pd = HostP2pD(config_file, args.interface[0], args.run_program[0],
                        force_logging)

    if os.getuid() == 0:
        daemon_pid_fname = (DAEMON_PIDFILE_DIR_ROOT + DAEMON_PIDFILE_BASE +
                            args.interface[0] + ".pid")
    else:
        daemon_pid_fname = (DAEMON_PIDFILE_DIR_NON_ROOT + DAEMON_PIDFILE_BASE +
                            args.interface[0] + ".pid")
    pidfile = daemon.pidfile.PIDLockFile(daemon_pid_fname)
    pid = pidfile.read_pid()

    if args.terminate:
        if pid:
            print(f"Terminating daemon process {pid}.")
            try:
                Ret = os.kill(pid, signal.SIGTERM)
            except Exception as e:
                print(f"Error while terminating daemon process {pid}: {e}.")
                sys.exit(1)
            if Ret:
                print(f"Error while terminating daemon process {pid}.")
                sys.exit(1)
            else:
                sys.exit(0)
        else:
            print("Cannot terminate daemon process: not running.")
            sys.exit(0)

    if args.reload:
        if pid:
            print(f"Reloading configuration file for daemon process {pid}.")
            try:
                Ret = os.kill(pid, signal.SIGHUP)
            except Exception as e:
                print(f"Error while reloading configuration file "
                      f"for daemon process {pid}: {e}.")
                sys.exit(1)
            if Ret:
                print(f"Error while reloading configuration file "
                      f"for daemon process {pid}.")
                sys.exit(1)
            else:
                sys.exit(0)
        else:
            print("Cannot reload the configuration of the daemon process: "
                  "not running.")
            sys.exit(0)

    if args.daemon_mode and not args.batch_mode:
        if pid:
            try:
                pidfile.acquire()
                pidfile.release(
                )  # this might occur only in rare contention cases
            except AlreadyLocked:
                try:
                    os.kill(pid, 0)
                    print(f"Process {pid} already running"
                          f' on the same interface "{args.interface[0]}". '
                          f'Check lockfile "{daemon_pid_fname}".')
                    sys.exit(1)
                except OSError:  # No process with locked PID
                    pidfile.break_lock()
                    print(f"Previous process {pid} terminated abnormally.")
            except NotLocked:
                print("Internal error: lockfile", daemon_pid_fname)
        context = daemon.DaemonContext(
            working_directory=DAEMON_DIR,
            umask=DAEMON_UMASK,
            pidfile=pidfile,
            detach_process=True,
            stdin=sys.stdin if args.debug else None,
            stdout=sys.stdout if args.debug else None,
            stderr=sys.stderr if args.debug else None,
            signal_map={
                signal.SIGTERM:
                lambda signum, frame: hostp2pd.terminate(),
                signal.SIGINT:
                lambda signum, frame: hostp2pd.terminate(),
                signal.SIGHUP:
                lambda signum, frame: hostp2pd.read_configuration(
                    configuration_file=hostp2pd.config_file,
                    do_activation=True),
            },
        )
        try:
            with context:
                print("hostp2pd daemon service STARTED")
                hostp2pd.run()
                print("\nhostp2pd daemon service ENDED")
        except LockFailed as e:
            print("Internal error: cannot start daemon", e)
            sys.exit(1)
        sys.exit(0)

    if pid:
        print(f'Warning: lockfile "{daemon_pid_fname}" reports pid {pid}.')

    if args.batch_mode and args.daemon_mode:
        print("hostp2pd service STARTED")
        signal.signal(
            signal.SIGHUP,
            lambda signum, frame: hostp2pd.read_configuration(
                configuration_file=hostp2pd.config_file, do_activation=True),
        )
        try:
            hostp2pd.run()
        except (KeyboardInterrupt, SystemExit):
            hostp2pd.terminate()
        print("\nhostp2pd service ENDED")
        sys.exit(0)
    else:
        w_p2p_interpreter = None
        try:
            with hostp2pd as session:
                if hostp2pd.process == None or hostp2pd.process.pid == None:
                    print("\nCannot start hostp2pd.\n")
                    os._exit(1)  # does not raise SystemExit
                while hostp2pd.threadState == hostp2pd.THREAD.STARTING:
                    time.sleep(0.1)
                if not args.batch_mode:
                    logging.info(f"\n\nhostp2pd (v{__version__}) "
                                 "started in interactive mode.\n")
                sys.stdout.flush()
                w_p2p_interpreter = Interpreter(hostp2pd, args)
                if args.batch_mode:
                    w_p2p_interpreter.cmdloop_with_keyboard_interrupt(
                        "hostp2pd batch mode STARTED\n"
                        "Begin batch commands.")
                else:
                    w_p2p_interpreter.cmdloop_with_keyboard_interrupt(
                        "Welcome to hostp2pd - "
                        "The Wi-Fi Direct Session Manager.\n"
                        "Copyright (c) Ircama 2021 - CC BY-NC-SA 4.0.\n"
                        "https://github.com/Ircama/hostp2pd\n"
                        "hostp2pd is running in interactive mode.\n"
                        "Type help or ? to list commands.\n")
        except (KeyboardInterrupt, SystemExit):
            if not args.batch_mode and w_p2p_interpreter:
                w_p2p_interpreter.postloop()
                print("\nExiting.\n")
            else:
                print("hostp2pd batch mode ENDED.")
            sys.exit(1)