def _cmdline_power_list(args):
    with msgid_c("cmdline"):
        target = tc.target_c.create_from_cmdline_args(args)
        state, substate, components = target.power.list()

        def _state_to_str(state):
            if state == True:
                return 'on'
            if state == False:
                return 'off'
            if state == None:
                return "n/a"
            return "BUG:unknown-state"

        if args.verbosity < 2:
            _state = _state_to_str(state)
            print "overall: %s (%s)" % (_state, substate)
            for component, data in components.iteritems():
                state = data['state']
                explicit = data.get('explicit', None)
                _state = _state_to_str(state)
                if explicit and args.verbosity == 0:
                    continue
                if not explicit:
                    explicit = ""
                else:
                    explicit = " (explicit/" + explicit + ")"
                print "  %s: %s%s" % (component, _state, explicit)
        elif args.verbosity == 2:
            r = dict(state = state, substate = substate, components = components)
            commonl.data_dump_recursive(r, prefix = target.fullid)
            
        else:  # args.verbosity >= 2:
            r = dict(state = state, substate = substate, components = components)
            print json.dumps(r, skipkeys = True, indent = 4)
Beispiel #2
0
def rest_target_print(rt, verbosity = 0):
    """
    Print information about a REST target taking into account the
    verbosity level from the logging module

    :param rt: object describing the REST target to print
    :type rt: dict

    """
    if verbosity == 0:
        print "%(fullid)s" % rt
    elif verbosity == 1:
        # Simple list, just show owner and power state
        if 'powered' in rt:
            # having that attribute means the target is powered; otherwise it
            # is either off or has no power control
            power = " ON"
        else:
            power = ""
        owner = rt.get('owner', None)
        if owner != None:
            owner_s = "[" + owner + "]"
        else:
            owner_s = ""
        print "%s %s%s" % (rt['fullid'], owner_s, power)
    elif verbosity == 2:
        print rt['fullid']
        commonl.data_dump_recursive(rt, prefix = "  ")
    elif verbosity == 3:
        pprint.pprint(rt)
    else:
        print json.dumps(rt, skipkeys = True, indent = 4)
Beispiel #3
0
def _cmdline_servers(args):
    # collect data in two structures, makes it easier to print at
    # different verbosity levels...yah, lazy
    r = []
    d = {}
    rtbs = {}

    if args.targets:
        rtb_list = {}
        for target_name in args.targets:
            try:
                target = tc.target_c.create_from_cmdline_args(
                    args, target_name, extensions_only=[])
                rtb_list[target.rtb.aka] = target.rtb
            except IndexError as e:
                logging.error("%s: invalid target" % target_name)
    else:
        rtb_list = ttb_client.rest_target_brokers

    for name, rtb in rtb_list.items():
        username = "******"
        try:
            if args.verbosity >= 0:
                # FIXME: this should be parallelized
                # we don't need this if verbosity < 0 and it takes time
                username = rtb.logged_in_username()
        # FIXME: we need a base exception for errors from the API
        except (ttb_client.requests.HTTPError, RuntimeError):
            username = "******"
        r.append((rtb.aka, str(rtb), username))
        d[rtb.aka] = dict(url=str(rtb), username=username)
        rtbs[rtb.aka] = rtb

    verbosity = args.verbosity - args.quietosity

    if verbosity < -1:
        for aka in d:
            print(aka)
    elif verbosity == -1:
        for rtb in rtbs.values():
            print(rtb.parsed_url.hostname)
    elif verbosity == 0:
        for aka, url, username in r:
            print(aka, url, username)
    elif verbosity in (1, 2):
        headers = [
            "Server",
            "URL",
            "UserID",
        ]
        print(tabulate.tabulate(r, headers=headers))
    elif verbosity == 3:
        commonl.data_dump_recursive(d)
    elif verbosity == 4:
        pprint.pprint(d)
    elif verbosity >= 5:
        print(json.dumps(d, skipkeys=True, indent=4))
def _cmdline_debug_list(args):
    with msgid_c("cmdline"):
        target = tc.target_c.create_from_cmdline_args(args, iface = "debug")
        r = target.debug.list(args.component)
        for component, value in r.iteritems():
            if value == None:
                print component + ": <debugging stopped>"
            elif value == {}:
                print component + ": <debugging started, target probably off>"
            else:
                print component + ":",
                commonl.data_dump_recursive(value)
Beispiel #5
0
def _cmdline_user_list(args):
    with msgid_c("cmdline"):
        threads = {}
        tp = ttb_client._multiprocessing_pool_c(
            processes=len(ttb_client.rest_target_brokers))
        if not ttb_client.rest_target_brokers:
            logging.error("E: no servers available, did you configure?")
            return
        for rtb in sorted(ttb_client.rest_target_brokers.values(), key=str):
            threads[rtb] = tp.apply_async(_user_list, (rtb, args.userid))
        tp.close()
        tp.join()

        result = {}
        for rtb, thread in threads.items():
            result[rtb.aka] = thread.get()

    if args.verbosity == 0:
        headers = [
            "Server",
            "UserID",
        ]
        table = []
        for rtb, r in result.items():
            for userid, data in r.items():
                table.append([rtb, userid])
        print((tabulate.tabulate(table, headers=headers)))
    elif args.verbosity == 1:
        headers = [
            "Server",
            "UserID",
            "Roles",
        ]
        table = []
        for rtb, r in result.items():
            for userid, data in r.items():
                rolel = []
                for role, state in data['roles'].items():
                    if state == False:
                        rolel.append(role + " (dropped)")
                    else:
                        rolel.append(role)
                table.append([rtb, userid, "\n".join(rolel)])
        print((tabulate.tabulate(table, headers=headers)))
    elif args.verbosity == 2:
        commonl.data_dump_recursive(result)
    elif args.verbosity == 3:
        pprint.pprint(result)
    elif args.verbosity >= 4:
        print(json.dumps(result, skipkeys=True, indent=4))
Beispiel #6
0
def _cmdline_store_list(args):
    with msgid_c("cmdline"):
        target = tc.target_c.create_from_cmdline_args(args,
                                                      extensions_only="store",
                                                      iface="store")
        if not args.filename:
            args.filename = None
        data = target.store.list2(path=args.path,
                                  filenames=args.filename,
                                  digest=args.digest)
        # this assumes v2 of the call, which if talking to a v1 server
        # will convert the data to v2 format
        if args.verbosity == 0:
            # simple one entry per line
            for file_name, file_data in sorted(data.items()):
                print(file_name,
                      ' '.join(f"{k}:{v}" for k, v in file_data.items()))
        elif args.verbosity == 1:
            headers = [
                "Name",
                "Type",
                "Aliases",
                "Hash " + (args.digest if args.digest else "(default)"),
            ]
            entries = []
            for file_name, file_data in data.items():
                entry = [file_name, file_data['type']]
                entry.append(file_data.get("aliases", ""))
                entry.append(file_data.get("digest", ""))
                bisect.insort(entries, entry)
            print(tabulate.tabulate(entries, headers=headers))
        elif args.verbosity == 2:
            commonl.data_dump_recursive(data)
        elif args.verbosity == 3:
            pprint.pprint(data)
        elif args.verbosity >= 4:
            print(json.dumps(data, skipkeys=True, indent=4))
Beispiel #7
0
def _alloc_ls(verbosity, username=None):
    allocs = {}
    tp = ttb_client._multiprocessing_pool_c(
        processes=len(ttb_client.rest_target_brokers))
    threads = {}
    for rtb in sorted(ttb_client.rest_target_brokers.itervalues()):
        threads[rtb] = tp.apply_async(_allocs_get, (rtb, username))
    tp.close()
    tp.join()
    for rtb, thread in threads.iteritems():
        allocs[rtb.aka] = thread.get()

    if verbosity < 0:
        # just print the list of alloc ids for each server, one per line
        for _, data in allocs.iteritems():
            if data:
                print "\n".join(data.keys())
        return
    elif verbosity == 3:
        pprint.pprint(allocs)
        return
    elif verbosity == 4:
        print json.dumps(allocs, skipkeys=True, indent=4)
        return

    table = []
    for rtb, r in allocs.iteritems():
        for allocid, data in r.iteritems():
            userl = []
            user = data.get('user', None)
            creator = data['creator']
            guests = data.get('guests', [])
            if 'priority' in data:
                prio = str(data['priority'])
                if data['preempt']:
                    prio += ":P"
            else:
                prio = "n/a"
            userl = [user]
            if user != creator:
                userl.append(creator + " (creator)")
            for guest in guests:
                userl.append(guest + " (guest)")
            if verbosity == 0:
                table.append([
                    allocid,
                    # put state/prio/preempt together
                    data['state'] + " " + prio,
                    "\n".join(userl),
                    len(data.get('target_group', [])),
                    data.get('reason', "n/a"),
                ])
            elif verbosity == 1:
                tgs = []
                for name, group in data.get('target_group', {}).iteritems():
                    tgs.append(name + ": " + ",".join(group))
                table.append([
                    allocid,
                    rtb,
                    data['state'],
                    prio,
                    data.get('timestamp', 'n/a'),
                    "\n".join(userl),
                    "\n".join(tgs),
                    data.get('reason', "n/a"),
                ])
            elif verbosity == 2:
                commonl.data_dump_recursive(
                    data,
                    allocid,
                )
    if verbosity == 0:
        headers0 = ["AllocID", "State", "Users", "#Groups", "Reason"]
        print(tabulate.tabulate(table, headers=headers0))
    if verbosity == 1:
        headers1 = [
            "AllocID",
            "Server",
            "State",
            "Priority",
            "Timestamp",
            "Users",
            "Groups",
            "Reason",
        ]
        print(tabulate.tabulate(table, headers=headers1))