Exemple #1
0
def main():
    """Parse args, check if everything is ok and start encarne."""
    args = parser.parse_args()

    # Check if mediainfo is available
    mediainfo_exists = shutil.which('mediainfo')
    if not mediainfo_exists:
        print("Mediainfo needs to be installed on this system.")
        sys.exit(1)

    # Check if pueue is available:
    command_factory('status')({}, root_dir=os.path.expanduser('~'))

    try:
        if hasattr(args, 'func'):
            args.func(vars(args))
        else:
            encoder = Encoder(vars(args))
            encoder.run()

    except KeyboardInterrupt:
        print('Keyboard interrupt. Shutting down')
        sys.exit(0)
def main():
    try:
        status = command_factory('status')({},
                                           root_dir=os.path.expanduser('~'))
        if type(status['data']) == str:
            print(status['data'])
        else:
            # get last 4 keys from status list
            data = status['data']
            keys = sorted(data.keys())
            keys.reverse()
            status_list = []
            for key in keys[:4]:
                entry_status = status['data'][key]['status']
                status_list.append(("{}: {}".format(key, entry_status)))
            print(', '.join(status_list))
    except KeyboardInterrupt:
        sys.exit(0)
Exemple #3
0
def execute_show(args, root_dir):
    """Print stderr and stdout of the current running process.

    Args:
        args['watch'] (bool): If True, we open a curses session and tail
                              the output live in the console.
        root_dir (string): The path to the root directory the daemon is running in.
    """
    key = None
    if args.get('key'):
        key = args['key']
        status = command_factory('status')({}, root_dir=root_dir)
        if status['data'][key]['status'] != 'running':
            print(
                'No running process with this key, use `log` to show finished processes.'
            )
            return

    # In case no key provided, we take the oldest running process
    else:
        status = command_factory('status')({}, root_dir=root_dir)
        for k in sorted(status['data'].keys()):
            if status['data'][k]['status'] == 'running':
                key = k
                break
        if key is None:
            print('No running process, use `log` to show finished processes.')
            return

    config_dir = os.path.join(root_dir, '.config/pueue')
    # Get current pueueSTDout file from tmp
    stdoutFile = os.path.join(config_dir,
                              'pueue_process_{}.stdout'.format(key))
    stderrFile = os.path.join(config_dir,
                              'pueue_process_{}.stderr'.format(key))
    stdoutDescriptor = open(stdoutFile, 'r')
    stderrDescriptor = open(stderrFile, 'r')
    running = True
    # Continually print output with curses or just print once
    if args['watch']:
        # Initialize curses
        stdscr = curses.initscr()
        curses.noecho()
        curses.cbreak()
        curses.curs_set(2)
        stdscr.keypad(True)
        stdscr.refresh()

        try:
            # Update output every two seconds
            while running:
                stdscr.clear()
                stdoutDescriptor.seek(0)
                message = stdoutDescriptor.read()
                stdscr.addstr(0, 0, message)
                stdscr.refresh()
                time.sleep(2)
        except:
            # Curses cleanup
            curses.nocbreak()
            stdscr.keypad(False)
            curses.echo()
            curses.endwin()
    else:
        print('Stdout output:\n')
        stdoutDescriptor.seek(0)
        print(stdoutDescriptor.read())
        print('\n\nStderr output:\n')
        stderrDescriptor.seek(0)
        print(stderrDescriptor.read())
Exemple #4
0
def execute_status(args, root_dir=None):
    """Print the status of the daemon.

    This function displays the current status of the daemon as well
    as the whole queue and all available information about every entry
    in the queue.
    `terminaltables` is used to format and display the queue contents.
    `colorclass` is used to color format the various items in the queue.

    Args:
        root_dir (string): The path to the root directory the daemon is running in.
    """

    status = command_factory('status')({}, root_dir=root_dir)
    # First rows, showing daemon status
    if status['status'] == 'running':
        status['status'] = Color('{autogreen}' +
                                 '{}'.format(status['status']) +
                                 '{/autogreen}')
    elif status['status'] in ['paused']:
        status['status'] = Color('{autoyellow}' +
                                 '{}'.format(status['status']) +
                                 '{/autoyellow}')

    print('Daemon: {}\n'.format(status['status']))

    # Handle queue data
    data = status['data']
    if isinstance(data, str):
        print(data)
    elif isinstance(data, dict):
        # Format incomming data to be compatible with Terminaltables
        formatted_data = []
        formatted_data.append(
            ['Index', 'Status', 'Code', 'Command', 'Path', 'Start', 'End'])
        for key, entry in sorted(data.items(), key=operator.itemgetter(0)):
            formatted_data.append([
                '#{}'.format(key), entry['status'],
                '{}'.format(entry['returncode']), entry['command'],
                entry['path'], entry['start'], entry['end']
            ])

        # Create AsciiTable instance and define style
        table = AsciiTable(formatted_data)
        table.outer_border = False
        table.inner_column_border = False

        terminal_width = terminal_size()
        customWidth = table.column_widths
        # If the text is wider than the actual terminal size, we
        # compute a new size for the Command and Path column.
        if (reduce(lambda a, b: a + b, table.column_widths) +
                10) > terminal_width[0]:
            # We have to subtract 14 because of table paddings
            left_space = math.floor(
                (terminal_width[0] - customWidth[0] - customWidth[1] -
                 customWidth[2] - customWidth[5] - customWidth[6] - 14) / 2)

            if customWidth[3] < left_space:
                customWidth[4] = 2 * left_space - customWidth[3]
            elif customWidth[4] < left_space:
                customWidth[3] = 2 * left_space - customWidth[4]
            else:
                customWidth[3] = left_space
                customWidth[4] = left_space

        # Format long strings to match the console width
        for i, entry in enumerate(table.table_data):
            for j, string in enumerate(entry):
                max_width = customWidth[j]
                wrapped_string = '\n'.join(wrap(string, max_width))
                if j == 1:
                    if wrapped_string == 'done' or wrapped_string == 'running' or wrapped_string == 'paused':
                        wrapped_string = Color('{autogreen}' +
                                               '{}'.format(wrapped_string) +
                                               '{/autogreen}')
                    elif wrapped_string in ['queued', 'stashed']:
                        wrapped_string = Color('{autoyellow}' +
                                               '{}'.format(wrapped_string) +
                                               '{/autoyellow}')
                    elif wrapped_string in ['failed', 'stopping', 'killing']:
                        wrapped_string = Color('{autored}' +
                                               '{}'.format(wrapped_string) +
                                               '{/autored}')
                elif j == 2:
                    if wrapped_string == '0' and wrapped_string != 'Code':
                        wrapped_string = Color('{autogreen}' +
                                               '{}'.format(wrapped_string) +
                                               '{/autogreen}')
                    elif wrapped_string != '0' and wrapped_string != 'Code':
                        wrapped_string = Color('{autored}' +
                                               '{}'.format(wrapped_string) +
                                               '{/autored}')

                table.table_data[i][j] = wrapped_string

        print(table.table)
    print('')
Exemple #5
0
 def receive_pueue_status(self):
     self.pueue_status = command_factory('status')(
         {}, root_dir=os.path.expanduser('~'))
Exemple #6
0
def main():
    # Specifying commands
    parser = argparse.ArgumentParser(description="Pueue client/daemon")
    parser.add_argument("--daemon", action="store_true", help="Starts the pueue daemon")
    parser.add_argument(
        "--no-daemon", action="store_true", help="Starts the pueue daemon in the current terminal", dest="nodaemon"
    )
    parser.add_argument(
        "--stop-daemon",
        action="store_true",
        help="Daemon will shut down instantly. All running processes die",
        dest="stopdaemon",
    )

    # Initialze supbparser
    subparsers = parser.add_subparsers(title="Subcommands", description="Various client")

    # Add
    add_Subcommand = subparsers.add_parser("add", help="Adds a command to the queue")
    add_Subcommand.add_argument("command", type=str, help="The command to be added")
    add_Subcommand.set_defaults(func=execute_add)

    # Remove
    remove_Subcommand = subparsers.add_parser("remove", help="Removes a specific command from the queue")
    remove_Subcommand.add_argument("key", help="The index of the command to be deleted", type=int)
    remove_Subcommand.set_defaults(func=execute_remove)

    # Switch
    switch_Subcommand = subparsers.add_parser("switch", help="Switches two command in the queue")
    switch_Subcommand.add_argument("first", help="The first command", type=int)
    switch_Subcommand.add_argument("second", help="The second command", type=int)
    switch_Subcommand.set_defaults(func=execute_switch)

    # Send
    switch_Subcommand = subparsers.add_parser("send", help="Send any input to the current running process.")
    switch_Subcommand.add_argument("input", help="The input string", type=str)
    switch_Subcommand.set_defaults(func=execute_send)

    # Status
    status_Subcommand = subparsers.add_parser(
        "status",
        help="Lists all commands in the queue, " "daemon state and state/returncode of the current/last process",
    )
    status_Subcommand.set_defaults(func=execute_status)

    # Show
    show_Subcommand = subparsers.add_parser("show", help="Shows the output of the currently running process")
    show_Subcommand.add_argument(
        "-w", "--watch", action="store_true", help="Starts the pueue daemon in the current terminal"
    )
    show_Subcommand.set_defaults(func=execute_show)

    # Logs
    logs_Subcommand = subparsers.add_parser("log", help="Prints the current log file to the command line")
    logs_Subcommand.set_defaults(func=execute_log)

    # Reset
    reset_Subcommand = subparsers.add_parser(
        "reset", help="Daemon will kill the current command, reset queue and rotate logs."
    )
    reset_Subcommand.set_defaults(func=command_factory("reset"))

    # Pause
    pause_Subcommand = subparsers.add_parser(
        "pause", help="Daemon will pause the current process and stops processing the queue."
    )
    pause_Subcommand.add_argument(
        "-w", "--wait", action="store_true", help="Stops the daemon, but waits for the current process to finish."
    )
    pause_Subcommand.set_defaults(func=execute_pause)

    # Start
    start_Subcommand = subparsers.add_parser(
        "start", help="Daemon will start a paused process and continue processing the queue."
    )
    start_Subcommand.set_defaults(func=command_factory("start"))

    # Restart
    restart_Subcommand = subparsers.add_parser("restart", help="Daemon will enqueue a finished process.")
    restart_Subcommand.add_argument("key", help="The index of the command to be restart", type=int)
    restart_Subcommand.set_defaults(func=execute_restart)

    # Kills the current running process and starts the next
    kill_Subcommand = subparsers.add_parser("kill", help="Kills the current running process and starts the next one")
    kill_Subcommand.add_argument(
        "-r",
        "--remove",
        action="store_true",
        help="If this flag is set, the current entry will be removed from the queue.",
    )
    kill_Subcommand.set_defaults(func=execute_kill)

    # Terminate the current running process and starts the next
    stop_Subcommand = subparsers.add_parser("stop", help="Daemon will stop the current command and pauses afterwards.")
    stop_Subcommand.add_argument(
        "-r",
        "--remove",
        action="store_true",
        help="If this flag is set, the current entry will be removed from the queue.",
    )
    stop_Subcommand.set_defaults(func=execute_stop)

    args = parser.parse_args()

    def startDaemon():
        try:
            daemon = Daemon()
            daemon.main()
        except KeyboardInterrupt:
            print("Keyboard interrupt. Shutting down")
            remove_daemon_socket()
            sys.exit(0)

    if args.stopdaemon:
        command_factory("STOPDAEMON")(vars(args))
    elif args.nodaemon:
        startDaemon()
    elif args.daemon:
        daemon = Daemonize(app="pueue", pid="/tmp/pueue.pid", action=startDaemon)
        daemon.start()
    elif hasattr(args, "func"):
        args.func(vars(args))
    else:
        print("Invalid Command. Please check -h")