Exemple #1
0
def main():
    """
    get-bootable-blocks main
    """
    # setup logging for client. The clients should call this before doing anything else.
    client_utils.setup_logging(logging.INFO)

    # list of callback with its arguments
    callbacks = [
        # <cb function>     <cb args>
        [ cb_debug        , () ],
        [ cb_gtzero       , (True,) ], # return int
        [ cb_bgq_geo      , () ] ]

    # Get the version information
    opt_def =  __doc__.replace('__revision__',__revision__)
    opt_def =  opt_def.replace('__version__',__version__)

    parser = ArgParse(opt_def,callbacks)
    parser.parse_it() # parse the command line
    opts   = parser.options
    args   = parser.args

    if parser.no_args():
        client_utils.print_usage(parser)
        sys.exit(1)

    block_loc   = args[0]
    idle_blocks = client_utils.component_call(SYSMGR, False, 'get_idle_blocks', (block_loc, opts.query_size, opts.geo_list))
    client_utils.logger.info("\n".join(idle_blocks))
Exemple #2
0
def main():
    """
    qselect main
    """
    # setup logging for client. The clients should call this before doing anything else.
    client_utils.setup_logging(logging.INFO)

    opts = {}  # old map
    opt2spec = {}

    # list of callback with its arguments
    callbacks = [
        # <cb function>           <cb args>
        [cb_debug, ()],
        [cb_nodes, (False, )],  # return string
        [cb_time, (False, False, False)]
    ]  # no delta time, return minutes, return string

    # Get the version information
    opt_def = __doc__.replace('__revision__', __revision__)
    opt_def = opt_def.replace('__version__', __version__)

    parser = ArgParse(opt_def, callbacks)

    # Set required default for the query:
    query = {
        'tag': 'job',
        'jobid': '*',
        'nodes': '*',
        'walltime': '*',
        'mode': '*',
        'project': '*',
        'state': '*',
        'queue': '*'
    }

    parser.parse_it()  # parse the command line

    if not parser.no_args():
        client_utils.logger.error("qselect takes no arguments")
        sys.exit(1)

    client_utils.get_options(query, opts, opt2spec, parser)
    response = client_utils.component_call(QUEMGR, False, 'get_jobs',
                                           ([query], ))
    if not response:
        client_utils.logger.error("Failed to match any jobs")
    else:
        client_utils.logger.debug(response)
        client_utils.logger.info("   The following jobs matched your query:")
        for job in response:
            client_utils.logger.info("      %d" % job.get('jobid'))
Exemple #3
0
def main():
    """
    qmove main
    """
    # setup logging for client. The clients should call this before doing anything else.
    client_utils.setup_logging(logging.INFO)

    # list of callback with its arguments
    callbacks = [
        # <cb function>     <cb args>
        [ cb_debug        , () ] ]

    # Get the version information
    opt_def =  __doc__.replace('__revision__',__revision__)
    opt_def =  opt_def.replace('__version__',__version__)

    parser = ArgParse(opt_def,callbacks)

    # Set required default values: None

    parser.parse_it() # parse the command line

    if not parser.no_args():
        client_utils.logger.error("No arguments needed")
    
    impl = client_utils.component_call(SYSMGR, False, 'get_implementation', ())

    # make sure we're on a cluster-system or orcm-system
    if ("cluster_system" != impl) and ("orcm_system" != impl):
        client_utils.logger.error("nodelist is only supported on cluster and orcm systems.  Try partlist instead.")
        sys.exit(0)

    status     = client_utils.component_call(SYSMGR, False, 'get_node_status', ())
    queue_data = client_utils.component_call(SYSMGR, False, 'get_queue_assignments', ())

    header = [['Host', 'Queue', 'State']]
    #build output list
    output = []
    for t in status:
        host_name = t[0]
        status = t[1]
        queues = []
        for q in queue_data:
            if host_name in queue_data[q]:
                queues.append(q) 
        output.append([host_name, ":".join(queues), status])
        
    client_utils.printTabular(header + output)
Exemple #4
0
def main():
    """
    userres main
    """
    # setup logging for client. The clients should call this before doing anything else.
    client_utils.setup_logging(logging.INFO)

    # list of callback with its arguments
    callbacks = [( cb_debug, ())]

    # Get the version information
    opt_def =  __doc__.replace('__revision__',__revision__)
    opt_def =  opt_def.replace('__version__',__version__)

    parser = ArgParse(opt_def,callbacks)

    parser.parse_it() # parse the command line
    args = parser.args

    if parser.no_args():
        client_utils.print_usage(parser)
        sys.exit(1)

    # Check if reservation exists
    spec = [{'name': rname, 'users':"*", 'start':'*', 'cycle':'*', 'duration':'*'} for rname in args]
    result = client_utils.component_call(SCHMGR, False, 'get_reservations', (spec,))

    if len(result) and len(result) != len(args):
        client_utils.logger.error("Reservation subset matched")
    elif not result:
        client_utils.logger.error("No Reservations matched")
        sys.exit(1)

    user_name = client_utils.getuid()
    
    for spec in result:
        if not spec['users'] or user_name not in spec['users'].split(":"):
            client_utils.logger.error("You are not a user of reservation '%s' and so cannot alter it.", spec['name'])
            continue

        if spec['cycle']:
            updates = update_start_time(spec, user_name)
        else:
            client_utils.component_call(SCHMGR, False, 'del_reservations', ([{'name':spec['name']}], user_name))
            client_utils.logger.info("Releasing reservation '%s'", spec['name'])
Exemple #5
0
def main():
    """
    slpstat main
    """
    # setup logging for client. The clients should call this before doing anything else.
    client_utils.setup_logging(logging.INFO)

    # list of callback with its arguments
    callbacks = [
        # <cb function>     <cb args>
        [cb_debug, ()]
    ]

    # Get the version information
    opt_def = __doc__.replace('__revision__', __revision__)
    opt_def = opt_def.replace('__version__', __version__)

    parser = ArgParse(opt_def, callbacks)

    # Set required default values: None

    parser.parse_it()  # parse the command line

    if not parser.no_args():
        client_utils.logger.error('No arguments needed')

    services = client_utils.component_call(SLPMGR, False, 'get_services',
                                           ([{
                                               'tag': 'service',
                                               'name': '*',
                                               'stamp': '*',
                                               'location': '*'
                                           }], ))

    if services:
        header = [('Name', 'Location', 'Update Time')]
        output = [(service['name'], service['location'],
                   time.strftime("%c", time.localtime(service['stamp'])))
                  for service in services]
        client_utils.print_tabular(header + [tuple(item) for item in output])
    else:
        client_utils.logger.info("no services registered")
Exemple #6
0
def main():
    """
    releaseres main
    """
    # setup logging for client. The clients should call this before doing anything else.
    client_utils.setup_logging(logging.INFO)

    # list of callback with its arguments
    callbacks = [(cb_debug, ())]

    # Get the version information
    opt_def = __doc__.replace('__revision__', __revision__)
    opt_def = opt_def.replace('__version__', __version__)

    parser = ArgParse(opt_def, callbacks)

    parser.parse_it()  # parse the command line
    args = parser.args

    if parser.no_args():
        client_utils.print_usage(parser)
        sys.exit(1)

    # Check if reservation exists
    spec = [{'name': arg, 'partitions': '*'} for arg in args]
    result = client_utils.component_call(SCHMGR, False, 'get_reservations',
                                         (spec, ))

    if len(result) and len(result) != len(args):
        client_utils.logger.error("Reservation subset matched")
    elif not result:
        client_utils.logger.error("No Reservations matched")
        sys.exit(1)

    result = client_utils.component_call(SCHMGR, False, 'release_reservations',
                                         (spec, client_utils.getuid()))
    for resinfo in result:
        partitions = resinfo['partitions'].split(':')
        client_utils.logger.info(
            "Released reservation '%s' for partitions: %s", resinfo['name'],
            str(partitions))
def main():
    """
    qmove main
    """
    # setup logging for client. The clients should call this before doing anything else.
    client_utils.setup_logging(logging.INFO)

    # list of callback with its arguments
    callbacks = [
        # <cb function>     <cb args>
        [ cb_debug        , () ] ]

    # Get the version information
    opt_def =  __doc__.replace('__revision__',__revision__)
    opt_def =  opt_def.replace('__version__',__version__)

    parser = ArgParse(opt_def,callbacks)

    # Set required default values: None

    parser.parse_it() # parse the command line

    if not parser.no_args():
        client_utils.logger.error("No arguments needed")

    impl = client_utils.component_call(SYSMGR, False, 'get_implementation', ())

    # make sure we're on a cluster-system
    if "cluster_system" != impl:
        client_utils.logger.error("nodelist is only supported on cluster systems.  Try partlist instead.")
        sys.exit(0)


    header, output = client_utils.cluster_display_node_info()
    if parser.options.noheader is not None:
        client_utils.printTabular(header + output, with_header_info=False)
    else:
        client_utils.printTabular(header + output)
Exemple #8
0
def main():
    """
    qmove main
    """
    # setup logging for client. The clients should call this before doing anything else.
    client_utils.setup_logging(logging.INFO)

    # list of callback with its arguments
    callbacks = [
        # <cb function>     <cb args>
        [cb_debug, ()]
    ]

    # Get the version information
    opt_def = __doc__.replace("__revision__", __revision__)
    opt_def = opt_def.replace("__version__", __version__)

    parser = ArgParse(opt_def, callbacks)

    # Set required default values: None

    parser.parse_it()  # parse the command line

    if not parser.no_args():
        client_utils.logger.error("No arguments needed")

    impl = client_utils.component_call(SYSMGR, False, "get_implementation", ())

    # make sure we're on a cluster-system
    if "cluster_system" != impl:
        client_utils.logger.error("nodelist is only supported on cluster systems.  Try partlist instead.")
        sys.exit(0)

    header, output = client_utils.cluster_display_node_info()
    if parser.options.noheader is not None:
        client_utils.printTabular(header + output, with_header_info=False)
    else:
        client_utils.printTabular(header + output)
Exemple #9
0
def main():
    """
    releaseres main
    """
    # setup logging for client. The clients should call this before doing anything else.
    client_utils.setup_logging(logging.INFO)

    # list of callback with its arguments
    callbacks = [(cb_debug, ())]

    # Get the version information
    opt_def = __doc__.replace("__revision__", __revision__)
    opt_def = opt_def.replace("__version__", __version__)

    parser = ArgParse(opt_def, callbacks)

    parser.parse_it()  # parse the command line
    args = parser.args

    if parser.no_args():
        client_utils.print_usage(parser)
        sys.exit(1)

    # Check if reservation exists
    spec = [{"name": arg, "partitions": "*"} for arg in args]
    result = client_utils.component_call(SCHMGR, False, "get_reservations", (spec,))

    if len(result) and len(result) != len(args):
        client_utils.logger.error("Reservation subset matched")
    elif not result:
        client_utils.logger.error("No Reservations matched")
        sys.exit(1)

    result = client_utils.component_call(SCHMGR, False, "release_reservations", (spec, client_utils.getuid()))
    for resinfo in result:
        partitions = resinfo["partitions"].split(":")
        client_utils.logger.info("Released reservation '%s' for partitions: %s", resinfo["name"], str(partitions))
Exemple #10
0
def main():
    """
    slpstat main
    """
    # setup logging for client. The clients should call this before doing anything else.
    client_utils.setup_logging(logging.INFO)

    # list of callback with its arguments
    callbacks = [
        # <cb function>     <cb args>
        [ cb_debug        , () ] ]

    # Get the version information
    opt_def =  __doc__.replace('__revision__',__revision__)
    opt_def =  opt_def.replace('__version__',__version__)

    parser = ArgParse(opt_def,callbacks)

    # Set required default values: None

    parser.parse_it() # parse the command line

    if not parser.no_args():
        client_utils.logger.error('No arguments needed')

    services = client_utils.component_call(SLPMGR, False, 'get_services', 
                                           ([{'tag':'service', 'name':'*', 'stamp':'*', 'location':'*'}],))

    if services:
        header = [('Name', 'Location', 'Update Time')]
        output = [ (service['name'],
                    service['location'],
                    time.strftime("%c", time.localtime(service['stamp'])))
                   for service in services ]
        client_utils.print_tabular(header + [tuple(item) for item in output])
    else:
        client_utils.logger.info("no services registered")
Exemple #11
0
def main():
    """
    partlist main
    """
    # setup logging for client. The clients should call this before doing anything else.
    client_utils.setup_logging(logging.INFO)

    # list of callback with its arguments
    callbacks = [
        # <cb function>     <cb args>
        [cb_debug, ()]
    ]

    # Get the version information
    opt_def = __doc__.replace('__revision__', __revision__)
    opt_def = opt_def.replace('__version__', __version__)

    parser = ArgParse(opt_def, callbacks)

    parser.parse_it()  # parse the command line

    if not parser.no_args():
        client_utils.logger.error("No arguments required")
        sys.exit(1)

    sys_info = client_utils.system_info()

    sys_type = sys_info[0]

    if sys_type == 'bgq':
        spec = [{
            'tag': 'partition',
            'name': '*',
            'queue': '*',
            'state': '*',
            'size': '*',
            'functional': '*',
            'scheduled': '*',
            'children': '*',
            'backfill_time': "*",
            'draining': "*",
            'node_geometry': "*"
        }]
    else:
        spec = [{
            'tag': 'partition',
            'name': '*',
            'queue': '*',
            'state': '*',
            'size': '*',
            'functional': '*',
            'scheduled': '*',
            'children': '*',
            'backfill_time': "*",
            'draining': "*"
        }]

    parts = client_utils.component_call(SYSMGR, True, 'get_partitions',
                                        (spec, ))
    reservations = client_utils.component_call(SCHMGR, False,
                                               'get_reservations',
                                               ([{
                                                   'queue': '*',
                                                   'partitions': '*',
                                                   'active': True
                                               }], ))

    expanded_parts = {}
    for res in reservations:
        for res_part in res['partitions'].split(':'):
            for p in parts:
                if p['name'] == res_part:
                    if expanded_parts.has_key(res['queue']):
                        expanded_parts[res['queue']].update(p['children'])
                    else:
                        expanded_parts[res['queue']] = set(p['children'])
                    expanded_parts[res['queue']].add(p['name'])

    for res in reservations:
        for p in parts:
            if p['name'] in expanded_parts.get(res['queue'], []):
                p['queue'] += ":%s" % res['queue']

    def my_cmp(left, right):
        val = -cmp(int(left['size']), int(right['size']))
        if val == 0:
            return cmp(left['name'], right['name'])
        else:
            return val

    parts.sort(my_cmp)
    now = time.time()
    for part in parts:
        if part['draining'] and part['state'] == "idle":
            # remove a little extra, to make sure that users can just type the number
            # that is output by partlist to get their job to backfill
            remaining = max(0, part['backfill_time'] - now - 90)
            hours, seconds = divmod(remaining, 3600.0)
            minutes = seconds / 60.0
            part['backfill'] = "%d:%0.2d" % (int(hours), int(minutes))
        else:
            part['backfill'] = "-"

    if sys_type == 'bgq':
        header = [['Name', 'Queue', 'State', 'Backfill', 'node_geometry']]
        #build output list, adding
        output = [[part.get(x) for x in [y.lower() for y in header[0]]]
                  for part in parts
                  if part['functional'] and part['scheduled']]
        #Hack to make the display cleaner.
        header[0][4] = 'Geometry'
        for o in output:
            if o[4] != None:
                o[4] = 'x'.join([str(i) for i in o[4]])
    else:
        header = [['Name', 'Queue', 'State', 'Backfill']]
        #build output list, adding
        output = [[part.get(x) for x in [y.lower() for y in header[0]]]
                  for part in parts
                  if part['functional'] and part['scheduled']]
    client_utils.printTabular(header + output)
Exemple #12
0
def main():
    """
    partlist main
    """
    # setup logging for client. The clients should call this before doing anything else.
    client_utils.setup_logging(logging.INFO)

    # list of callback with its arguments
    callbacks = [
        # <cb function>     <cb args>
        [ cb_debug        , () ] ]

    # Get the version information
    opt_def =  __doc__.replace('__revision__',__revision__)
    opt_def =  opt_def.replace('__version__',__version__)

    parser = ArgParse(opt_def,callbacks)

    parser.parse_it() # parse the command line

    if not parser.no_args():
        client_utils.logger.error("No arguments required")
        sys.exit(1)
    
    sys_info = client_utils.system_info()
    
    sys_type = sys_info[0]

    if sys_type == 'bgq':
        spec = [{'tag':'partition', 'name':'*', 'queue':'*', 'state':'*',
                 'size':'*', 'functional':'*', 'scheduled':'*', 'children':'*',
                 'backfill_time':"*", 'draining':"*",'node_geometry':"*"}]
    else:
        spec = [{'tag':'partition', 'name':'*', 'queue':'*', 'state':'*',
                 'size':'*', 'functional':'*', 'scheduled':'*', 'children':'*',
                 'backfill_time':"*", 'draining':"*"}]

    parts        = client_utils.component_call(SYSMGR, True, 'get_partitions', (spec,))
    reservations = client_utils.component_call(SCHMGR, False, 'get_reservations', 
                                               ([{'queue':'*','partitions':'*','active':True}],))

    expanded_parts = {}
    for res in reservations:
        for res_part in res['partitions'].split(':'):
            for p in parts:
                if p['name'] == res_part:
                    if expanded_parts.has_key(res['queue']):
                        expanded_parts[res['queue']].update(p['children'])
                    else:
                        expanded_parts[res['queue']] = set( p['children'] )
                    expanded_parts[res['queue']].add(p['name'])    
    
    for res in reservations:
        for p in parts:
            if p['name'] in expanded_parts.get(res['queue'], []):
                p['queue'] += ":%s" % res['queue']

    def my_cmp(left, right):
        val = -cmp(int(left['size']), int(right['size']))
        if val == 0:
            return cmp(left['name'], right['name'])
        else:
            return val

    parts.sort(my_cmp)
    now = time.time()
    for part in parts:
        if part['draining'] and part['state'] == "idle":
            # remove a little extra, to make sure that users can just type the number
            # that is output by partlist to get their job to backfill
            remaining = max(0, part['backfill_time'] - now - 90)
            hours, seconds = divmod(remaining, 3600.0)
            minutes = seconds/60.0
            part['backfill'] = "%d:%0.2d" % (int(hours), int(minutes))
        else:
            part['backfill'] = "-"

    if sys_type == 'bgq':
        header = [['Name', 'Queue', 'State', 'Backfill', 'node_geometry']]
        #build output list, adding
        output = [[part.get(x) for x in [y.lower() for y in header[0]]] for part in parts 
                  if part['functional'] and part['scheduled']]
        #Hack to make the display cleaner.
        header[0][4] = 'Geometry'
        for o in output:
            if o[4] != None:
                o[4] = 'x'.join([str(i) for i in o[4]])
    else:
        header = [['Name', 'Queue', 'State', 'Backfill']]
        #build output list, adding
        output = [[part.get(x) for x in [y.lower() for y in header[0]]] for part in parts 
                  if part['functional'] and part['scheduled']]
    client_utils.printTabular(header + output)
Exemple #13
0
def main():
    """
    get-bootable-blocks main
    """
    # setup logging for client. The clients should call this before doing anything else.
    client_utils.setup_logging(logging.INFO)

    # list of callback with its arguments
    callbacks = [
        # <cb function>     <cb args>
        [cb_debug, ()],
        [cb_gtzero, (True, )]
    ]  # return int

    # Get the version information
    opt_def = __doc__.replace('__revision__', __revision__)
    opt_def = opt_def.replace('__version__', __version__)

    parser = ArgParse(opt_def, callbacks)

    user = client_utils.getuid()

    parser.parse_it()  # parse the command line
    opts = parser.options

    if not parser.no_args():
        client_utils.logger.info('No arguments needed')

    if opts.free and opts.reboot:
        client_utils.logger.error(
            "ERROR: --free may not be specified with --reboot.")
        sys.exit(BAD_OPTION_FAIL)

    block = opts.block
    if block == None:
        try:
            block = os.environ['COBALT_PARTNAME']
        except KeyError:
            pass
        try:
            block = os.environ['COBALT_BLOCKNAME']
        except KeyError:
            pass
        if block == None:
            client_utils.logger.error(
                "ERROR: block not specified as option or in environment.")
            sys.exit(BAD_OPTION_FAIL)

    jobid = opts.jobid
    if jobid == None:
        try:
            jobid = int(os.environ['COBALT_JOBID'])
        except KeyError:
            client_utils.logger.error(
                "ERROR: Cobalt jobid not specified as option or in environment."
            )
            sys.exit(BAD_OPTION_FAIL)

    if opts.reboot or opts.free:
        #Start the free on the block
        #poke cobalt to kill all jobs on the resource as well.
        success = client_utils.component_call(SYSMGR, False,
                                              'initiate_proxy_free',
                                              (block, user, jobid))
        client_utils.logger.info("Block free on %s initiated." % (block, ))
        if not success:
            client_utils.logger.error(
                "Free request for block %s failed authorization." % (block, ))
            sys.exit(AUTH_FAIL)
        while (True):
            #wait for free.  If the user still has jobs running, this won't complete.
            #the proxy free should take care of this, though.
            if client_utils.component_call(SYSMGR, False,
                                           'get_block_bgsched_status',
                                           (block, )) == 'Free':
                client_utils.logger.info("Block %s successfully freed." %
                                         (block, ))
                break

    if not opts.free:
        #This returns important error codes. Pass this back up through main.
        return client_utils.boot_block(block, user, jobid)
Exemple #14
0
def main():
    """
    get-bootable-blocks main
    """
    # setup logging for client. The clients should call this before doing anything else.
    client_utils.setup_logging(logging.INFO)

    # list of callback with its arguments
    callbacks = [
        # <cb function>     <cb args>
        [ cb_debug        , () ],
        [ cb_gtzero       , (True,) ] ] # return int

    # Get the version information
    opt_def =  __doc__.replace('__revision__',__revision__)
    opt_def =  opt_def.replace('__version__',__version__)

    parser = ArgParse(opt_def,callbacks)

    user = client_utils.getuid()

    parser.parse_it() # parse the command line
    opts   = parser.options

    if not parser.no_args():
        client_utils.logger.info('No arguments needed')

    if opts.free and opts.reboot:
        client_utils.logger.error("ERROR: --free may not be specified with --reboot.")
        sys.exit(BAD_OPTION_FAIL)

    block = opts.block
    if block == None:
        try:
            block = os.environ['COBALT_PARTNAME']
        except KeyError:
            pass
        try:
            block = os.environ['COBALT_BLOCKNAME']
        except KeyError:
            pass
        if block == None:
            client_utils.logger.error("ERROR: block not specified as option or in environment.")
            sys.exit(BAD_OPTION_FAIL)

    jobid = opts.jobid
    if jobid == None:
        try:
            jobid = int(os.environ['COBALT_JOBID'])
        except KeyError:
            client_utils.logger.error("ERROR: Cobalt jobid not specified as option or in environment.")
            sys.exit(BAD_OPTION_FAIL)

    if opts.reboot or opts.free:
        #Start the free on the block
        #poke cobalt to kill all jobs on the resource as well.
        success = client_utils.component_call(SYSMGR, False, 'initiate_proxy_free', (block, user, jobid))
        client_utils.logger.info("Block free on %s initiated." % (block,))
        if not success:
            client_utils.logger.error("Free request for block %s failed authorization." % (block, ))
            sys.exit(AUTH_FAIL)
        while (True):
            #wait for free.  If the user still has jobs running, this won't complete.
            #the proxy free should take care of this, though.
            if client_utils.component_call(SYSMGR, False, 'get_block_bgsched_status', (block,)) == 'Free':
                client_utils.logger.info("Block %s successfully freed." % (block,))
                break

    if not opts.free:
        #This returns important error codes. Pass this back up through main.
        return client_utils.boot_block(block, user, jobid)
Exemple #15
0
def main():
    """
    showres main
    """
    # setup logging for client. The clients should call this before doing anything else.
    client_utils.setup_logging(logging.INFO)

    # list of callback with its arguments
    callbacks = [
        # <cb function>     <cb args>
        [ cb_debug        , () ] ]

    # Get the version information
    opt_def =  __doc__.replace('__revision__',__revision__)
    opt_def =  opt_def.replace('__version__',__version__)

    parser = ArgParse(opt_def,callbacks)

    parser.parse_it() # parse the command line

    if not parser.no_args():
        client_utils.logger.error("No arguments needed")
    
    if parser.options.verbose != None and parser.options.really_verbose != None:
        client_utils.logger.error('Only use -l or -x not both')
        sys.exit(1)

    cluster = False
    if 'cluster' in client_utils.component_call(SYSMGR, False, 'get_implementation', ()):
        cluster = True

    reservations = client_utils.component_call(SCHMGR, False, 'get_reservations', 
                                               ([{'name':'*', 'users':'*','start':'*', 'duration':'*', 'partitions':'*', 
                                                  'cycle': '*', 'queue': '*', 'res_id': '*', 'cycle_id': '*','project':'*', 
                                                  'block_passthrough':'*'}], ))

    output = []

    verbose        = False
    really_verbose = False
    header = [('Reservation', 'Queue', 'User', 'Start', 'Duration','Passthrough', 'Partitions', 'Remaining','T-Minus')]

    if parser.options.verbose:
        verbose = True
        header = [('Reservation', 'Queue', 'User', 'Start', 'Duration',
                   'End Time', 'Cycle Time', 'Passthrough', 'Partitions', 'Remaining', 'T-Minus')]
    elif parser.options.really_verbose:
        really_verbose = True
        header = [('Reservation', 'Queue', 'User', 'Start', 'Duration','End Time', 'Cycle Time','Passthrough','Partitions', 
                   'Project', 'ResID', 'CycleID', 'Remaining', 'T-Minus' )]

    for res in reservations:

        passthrough = "Allowed"
        if res['block_passthrough']:
            passthrough = "Blocked"

        start     = float(res['start'])
        duration  = float(res['duration'])
        now       = time.time()

        deltatime = now - start
        remaining = "inactive" if deltatime < 0.0 else client_utils.get_elapsed_time(deltatime, duration, True)
        remaining = "00:00:00" if '-' in remaining else remaining
        tminus    = "active" if deltatime >= 0.0 else client_utils.get_elapsed_time(deltatime, duration, True)

        # do some crazy stuff to make reservations which cycle display the 
        # "next" start time
        if res['cycle']:
            cycle = float(res['cycle'])
            periods = math.floor((now - start)/cycle)
            # reservations can't become active until they pass the start time 
            # -- so negative periods aren't allowed
            if periods < 0:
                pass
            # if we are still inside the reservation, show when it started
            elif (now - start) % cycle < duration:
                start += periods * cycle
            # if we are in the dead time after the reservation ended, show 
            # when the next one starts
            else:
                start += (periods+1) * cycle
        if res['cycle_id'] == None:
            res['cycle_id'] = '-'

        if res['cycle']:
            cycle = float(res['cycle'])
            if cycle < (60 * 60 * 24):
                cycle = "%02d:%02d" % (cycle/3600, (cycle/60)%60)
            else:
                cycle = "%0.1f days" % (cycle / (60 * 60 * 24))
        else:
            cycle = None
        dmin = (duration/60)%60
        dhour = duration/3600

        time_fmt = "%c"
        starttime = time.strftime(time_fmt, time.localtime(start))
        endtime   = time.strftime(time_fmt, time.localtime(start + duration)) 

        if parser.options.oldts == None:
            #time_fmt += " %z (%Z)"
            starttime = client_utils.sec_to_str(start)
            endtime = client_utils.sec_to_str(start + duration)

        if really_verbose:
            output.append((res['name'], res['queue'], res['users'], 
                           starttime,"%02d:%02d" % (dhour, dmin),
                           endtime, cycle, passthrough,
                           mergelist(res['partitions'], cluster), 
                           res['project'], res['res_id'], res['cycle_id'], remaining, tminus))
        elif verbose:
            output.append((res['name'], res['queue'], res['users'], 
                           starttime,"%02d:%02d" % (dhour, dmin),
                           endtime, cycle, passthrough,
                           mergelist(res['partitions'], cluster), 
                           remaining, tminus))
        else:
            output.append((res['name'], res['queue'], res['users'], 
                           starttime,"%02d:%02d" % (dhour, dmin), passthrough,
                           mergelist(res['partitions'], cluster), 
                           remaining, tminus))

    output.sort( (lambda x,y: cmp( time.mktime(time.strptime(x[3].split('+')[0].split('-')[0].strip(), time_fmt)), 
                                   time.mktime(time.strptime(y[3].split('+')[0].split('-')[0].strip(), time_fmt))) ) )
    client_utils.print_tabular(header + output)
Exemple #16
0
def main():
    """
    showres main
    """
    # setup logging for client. The clients should call this before doing anything else.
    client_utils.setup_logging(logging.INFO)

    # list of callback with its arguments
    callbacks = [
        # <cb function>     <cb args>
        [cb_debug, ()]
    ]

    # Get the version information
    opt_def = __doc__.replace('__revision__', __revision__)
    opt_def = opt_def.replace('__version__', __version__)

    parser = ArgParse(opt_def, callbacks)

    parser.parse_it()  # parse the command line

    if not parser.no_args():
        client_utils.logger.error("No arguments needed")

    if parser.options.verbose != None and parser.options.really_verbose != None:
        client_utils.logger.error('Only use -l or -x not both')
        sys.exit(1)

    cluster = False
    if 'cluster' in client_utils.component_call(SYSMGR, False,
                                                'get_implementation', ()):
        cluster = True

    reservations = client_utils.component_call(SCHMGR, False,
                                               'get_reservations',
                                               ([{
                                                   'name': '*',
                                                   'users': '*',
                                                   'start': '*',
                                                   'duration': '*',
                                                   'partitions': '*',
                                                   'cycle': '*',
                                                   'queue': '*',
                                                   'res_id': '*',
                                                   'cycle_id': '*',
                                                   'project': '*',
                                                   'block_passthrough': '*'
                                               }], ))

    output = []

    verbose = False
    really_verbose = False
    header = [('Reservation', 'Queue', 'User', 'Start', 'Duration',
               'Passthrough', 'Partitions', 'Remaining', 'T-Minus')]

    if parser.options.verbose:
        verbose = True
        header = [
            ('Reservation', 'Queue', 'User', 'Start', 'Duration', 'End Time',
             'Cycle Time', 'Passthrough', 'Partitions', 'Remaining', 'T-Minus')
        ]
    elif parser.options.really_verbose:
        really_verbose = True
        header = [('Reservation', 'Queue', 'User', 'Start', 'Duration',
                   'End Time', 'Cycle Time', 'Passthrough', 'Partitions',
                   'Project', 'ResID', 'CycleID', 'Remaining', 'T-Minus')]

    for res in reservations:

        passthrough = "Allowed"
        if res['block_passthrough']:
            passthrough = "Blocked"

        start = float(res['start'])
        duration = float(res['duration'])
        now = time.time()

        deltatime = now - start
        remaining = "inactive" if deltatime < 0.0 else client_utils.get_elapsed_time(
            deltatime, duration, True)
        remaining = "00:00:00" if '-' in remaining else remaining
        tminus = "active" if deltatime >= 0.0 else client_utils.get_elapsed_time(
            deltatime, duration, True)

        # do some crazy stuff to make reservations which cycle display the
        # "next" start time
        if res['cycle']:
            cycle = float(res['cycle'])
            periods = math.floor((now - start) / cycle)
            # reservations can't become active until they pass the start time
            # -- so negative periods aren't allowed
            if periods < 0:
                pass
            # if we are still inside the reservation, show when it started
            elif (now - start) % cycle < duration:
                start += periods * cycle
            # if we are in the dead time after the reservation ended, show
            # when the next one starts
            else:
                start += (periods + 1) * cycle
        if res['cycle_id'] == None:
            res['cycle_id'] = '-'

        if res['cycle']:
            cycle = float(res['cycle'])
            if cycle < (60 * 60 * 24):
                cycle = "%02d:%02d" % (cycle / 3600, (cycle / 60) % 60)
            else:
                cycle = "%0.1f days" % (cycle / (60 * 60 * 24))
        else:
            cycle = None
        dmin = (duration / 60) % 60
        dhour = duration / 3600

        time_fmt = "%c"
        starttime = time.strftime(time_fmt, time.localtime(start))
        endtime = time.strftime(time_fmt, time.localtime(start + duration))

        if parser.options.oldts == None:
            #time_fmt += " %z (%Z)"
            starttime = client_utils.sec_to_str(start)
            endtime = client_utils.sec_to_str(start + duration)

        if really_verbose:
            output.append(
                (res['name'], res['queue'], res['users'], starttime,
                 "%02d:%02d" % (dhour, dmin), endtime, cycle, passthrough,
                 mergelist(res['partitions'], cluster), res['project'],
                 res['res_id'], res['cycle_id'], remaining, tminus))
        elif verbose:
            output.append(
                (res['name'], res['queue'], res['users'], starttime,
                 "%02d:%02d" % (dhour, dmin), endtime, cycle, passthrough,
                 mergelist(res['partitions'], cluster), remaining, tminus))
        else:
            output.append((res['name'], res['queue'], res['users'], starttime,
                           "%02d:%02d" % (dhour, dmin), passthrough,
                           mergelist(res['partitions'],
                                     cluster), remaining, tminus))

    output.sort((lambda x, y: cmp(
        time.mktime(
            time.strptime(x[3].split('+')[0].split('-')[0].strip(), time_fmt)),
        time.mktime(
            time.strptime(y[3].split('+')[0].split('-')[0].strip(), time_fmt)))
                 ))
    client_utils.print_tabular(header + output)