CraySystem.py 82.5 KB
Newer Older
1
"""Resource management for Cray ALPS based systems"""
2 3
# Copyright 2017 UChicago Argonne, LLC. All rights reserved.
# Licensed under a modified BSD 3-clause license. See LICENSE for details.
4 5 6
import logging
import threading
import time
7
import sys
8
import xmlrpclib
9
import json
10
from xml.etree.ElementTree import ParseError
11
import ConfigParser
12 13
import Cobalt.Util
import Cobalt.Components.system.AlpsBridge as ALPSBridge
14
from Cobalt.Components.system.AlpsBridge import ALPSError
15
from Cobalt.Components.base import Component, exposed, automatic, query, locking
16 17
from Cobalt.Components.system.base_system import BaseSystem
from Cobalt.Components.system.CrayNode import CrayNode
18
from Cobalt.Components.system.base_pg_manager import ProcessGroupManager
19
from Cobalt.Components.system.ALPSProcessGroup import ALPSProcessGroup
20
from Cobalt.Exceptions import ComponentLookupError
Paul Rich's avatar
Paul Rich committed
21
from Cobalt.Exceptions import JobNotInteractive
22
from Cobalt.Components.system.ALPSProcessGroup import ALPSProcessGroup
23
from Cobalt.Exceptions import JobValidationError
24
from Cobalt.DataTypes.ProcessGroup import ProcessGroup
25
from Cobalt.Util import compact_num_list, expand_num_list
26
from Cobalt.Util import init_cobalt_config, get_config_option
Paul Rich's avatar
Paul Rich committed
27
from Cobalt.Util import extract_traceback, sanitize_password, get_current_thread_identifier
28
from Queue import Queue
29

30
_logger = logging.getLogger(__name__)
31
init_cobalt_config()
32

33
DEFAULT_DEPTH = int(get_config_option('alps', 'default_depth', 72))
34 35
UPDATE_THREAD_TIMEOUT = int(get_config_option('alpssystem', 'update_thread_timeout', 10))
TEMP_RESERVATION_TIME = int(get_config_option('alpssystem', 'temp_reservation_time', 300))
36
SAVE_ME_INTERVAL = float(get_config_option('alpsssytem', 'save_me_interval', 10.0))
37
#default 20 minutes to account for boot.
38 39
# DISABLED: Not used
#PENDING_STARTUP_TIMEOUT = float(get_config_option('alpssystem', 'pending_startup_timeout', 1200))
Paul Rich's avatar
Paul Rich committed
40
APKILL_CMD = get_config_option('alps', 'apkill', '/opt/cray/alps/default/bin/apkill')
41
DRAIN_MODE = get_config_option('system', 'drain_mode', 'first-fit')
42 43
#cleanup time in seconds
CLEANUP_DRAIN_WINDOW = get_config_option('system', 'cleanup_drain_window', 300)
44 45
#SSD information
DEFAULT_MIN_SSD_SIZE = int(get_config_option('alpssystem', 'min_ssd_size', -1))
46

47 48
#Epsilon for backfilling.  This system does not do this on a per-node basis.
BACKFILL_EPSILON = int(get_config_option('system', 'backfill_epsilon', 120))
49
ELOGIN_HOSTS = [host for host in get_config_option('system', 'elogin_hosts', '').split(':')]
50 51
if ELOGIN_HOSTS == ['']:
    ELOGIN_HOSTS = []
Paul Rich's avatar
Paul Rich committed
52
DRAIN_MODES = ['first-fit', 'backfill']
53
CLEANING_ID = -1
54 55
DEFAULT_MCDRAM_MODE = get_config_option('alpssystem', 'default_mcdram_mode', 'cache')
DEFAULT_NUMA_MODE = get_config_option('alpssystem', 'default_numa_mode', 'quad')
56
MCDRAM_TO_HBMCACHEPCT = {'flat':'0', 'cache':'100', 'split':'25', 'equal':'50', '0':'0', '25':'25', '50':'50', '100':'100'}
57 58
VALID_MCDRAM_MODES = ['flat', 'cache', 'split', 'equal', '0', '25', '50', '100']
VALID_NUMA_MODES = ['a2a', 'hemi', 'quad', 'snc2', 'snc4']
59

60 61 62 63 64 65 66 67 68 69
def chain_loc_list(loc_list):
    '''Take a list of compact Cray locations,
    expand and concatenate them.

    '''
    retlist = []
    for locs in loc_list:
        retlist.extend(expand_num_list(locs))
    return retlist

70

71
class CraySystem(BaseSystem):
72 73 74
    '''Cray/ALPS-specific system component.  Behaviors should go here.  Direct
    ALPS interaction through BASIL/other APIs should go through the ALPSBridge
    (or other bridge) module as appropriate.
75

76
    '''
77 78
    name = "system"
    implementation = "alps_system"
79
    logger = _logger
80

81
    def __init__(self, *args, **kwargs):
82 83 84 85
        '''Initialize system.  Read initial states from bridge.
        Get current state

        '''
86
        start_time = time.time()
87
        super(CraySystem, self).__init__(*args, **kwargs)
88
        _logger.info('BASE SYSTEM INITIALIZED')
89 90
        self._common_init_restart()
        _logger.info('ALPS SYSTEM COMPONENT READY TO RUN')
91
        _logger.info('Initialization complete in %s sec.', (time.time() -
92 93 94
                start_time))

    def _common_init_restart(self, spec=None):
95
        '''Common routine for cold and restart initialization of the system
96 97 98
        component.

        '''
99 100 101
        try:
            self.system_size = int(get_config_option('system', 'size'))
        except (ConfigParser.NoSectionError, ConfigParser.NoOptionError):
102
            self.logger.critical('ALPS SYSTEM: ABORT STARTUP: System size must be specified in the [system] section of the cobalt configuration file.')
103
            sys.exit(1)
104 105
        if DRAIN_MODE not in DRAIN_MODES:
            #abort startup, we have a completely invalid config.
106
            self.logger.critical('ALPS SYSTEM: ABORT STARTUP: %s is not a valid drain mode.  Must be one of %s.',
107 108
                DRAIN_MODE, ", ".join(DRAIN_MODES))
            sys.exit(1)
109
        #initilaize bridge.
110 111 112 113
        bridge_pending = True
        while bridge_pending:
            # purge stale children from prior run.  Also ensure the
            # system_script_forker is currently up.
Paul Rich's avatar
Paul Rich committed
114 115
            # These attempts may fail due to system_script_forker not being up.
            # We don't want to trash the statefile in this case.
116 117 118
            try:
                ALPSBridge.init_bridge()
            except ALPSBridge.BridgeError:
119
                self.logger.error('Bridge Initialization failed.  Retrying.')
120 121
                Cobalt.Util.sleep(10)
            except ComponentLookupError:
122
                self.logger.warning('Error reaching forker.  Retrying.')
123
                Cobalt.Util.sleep(10)
124 125
            else:
                bridge_pending = False
126
                self.logger.info('BRIDGE INITIALIZED')
127
        #process manager setup
128
        if spec is None:
Paul Rich's avatar
Paul Rich committed
129
            self.process_manager = ProcessGroupManager(pgroup_type=ALPSProcessGroup)
130
        else:
131 132 133 134 135 136 137 138 139 140 141
            spec_version = spec.get('alps_system_statefile_version', 1)
            if spec_version <= 1:
                # Compat for old version of process manager information that was stored as a dict
                # rather than an actual object.  Yes, this results in a double initialize. Ugly, but
                # doesn't hurt anything, yet.
                self.process_manager = ProcessGroupManager(pgroup_type=ALPSProcessGroup).__setstate__(spec['process_manager'])
                self.logger.debug('pg type %s', self.process_manager.process_groups.item_cls)
            else:
                self.process_manager = spec['process_manager']
                self.process_manager.pgroup_type = ALPSProcessGroup
                self.logger.debug('pg type %s', self.process_manager.process_groups.item_cls)
142 143 144 145 146 147 148 149 150 151

        # DISABLED: Why are we calling this here?  It's called below in the update thread.
        # Any error in update_launchers will cause CraySystem to fail to start.
        # the below thread that has wrappers will protect it and should be used.
        #self.process_manager.update_launchers()
        self.logger.info('PROCESS MANAGER INITIALIZED')

        # DISABLED: Not used
        # self.pending_start_timeout = PENDING_STARTUP_TIMEOUT

152
        #resource management setup
153
        self.nodes = {} #cray node_id: CrayNode
154 155 156 157
        self.node_name_to_id = {} #cray node name to node_id map
        self.alps_reservations = {} #cobalt jobid : AlpsReservation object
        if spec is not None:
            self.alps_reservations = spec['alps_reservations']
158
        self._init_nodes_and_reservations()
159 160 161
        if spec is not None:
            node_info = spec.get('node_info', {})
            for nid, node in node_info.items():
162 163 164 165
                try:
                    self.nodes[nid].reset_info(node)
                except: #check the exception types later.  Carry on otherwise.
                    self.logger.warning("Node nid: %s not found in restart information.  Bringing up node in a clean configuration.", nid)
Paul Rich's avatar
Paul Rich committed
166 167 168
        #storage for pending job starts.  Allows us to handle slow starts vs
        #user deletes
        self.pending_starts = {} #jobid: time this should be cleared.
169
        self.nodes_by_queue = {} #queue:[node_ids]
170
        #populate initial state
171
        #state update thread and lock
172
        self._node_lock = threading.RLock()
173
        self._gen_node_to_queue()
174 175 176 177
        self.node_update_thread_kill_queue = Queue()
        self.node_update_thread_dead = False
        self.logger.info("_run_update_state thread starting.")
        self.node_update_thread = threading.Thread(target=self._run_update_state)
178
        self.node_update_thread.daemon = True
179 180
        self.node_update_thread.start()
        self.logger.info("_run_update_state thread started:%s", self.node_update_thread)
Paul Rich's avatar
Paul Rich committed
181
        self.killing_jobs = {}
182 183 184 185
        #hold on to the initial spec in case nodes appear out of nowhere.
        self.init_spec = None
        if spec is not None:
            self.init_spec = spec
186

187 188 189 190 191
    def __getstate__(self):
        '''Save process, alps-reservation information, along with base
        information'''
        state = {}
        state.update(super(CraySystem, self).__getstate__())
192
        state['alps_system_statefile_version'] = 2
193
        state['process_manager'] = self.process_manager
194
        state['alps_reservations'] = self.alps_reservations
195
        state['node_info'] = self.nodes
196 197 198 199
        return state

    def __setstate__(self, state):
        start_time = time.time()
200
        _logger.info('INITIALIZING FROM ALPS SYSTEM STATE FILE VERSION %s', state.get('alps_system_statefile_version', None))
201 202 203
        super(CraySystem, self).__setstate__(state)
        _logger.info('BASE SYSTEM INITIALIZED')
        self._common_init_restart(state)
204
        _logger.info('ALPS SYSTEM COMPONENT READY TO RUN')
205
        _logger.info('Reinitilaization complete in %s sec.', (time.time() -
206
                start_time))
207

208 209 210 211 212
    def save_me(self):
        '''Automatically save a copy of the state of the system component.'''
        #should we be holding the block lock as well?
        Component.save(self)
    save_me = automatic(save_me, SAVE_ME_INTERVAL)
213

214 215 216 217
    def _init_nodes_and_reservations(self):
        '''Initialize nodes from ALPS bridge data'''

        retnodes = {}
218 219 220
        pending = True
        while pending:
            try:
221 222 223 224 225
                # None of these queries has strictly degenerate data.  Inventory
                # is needed for raw reservation data.  System gets memory and a
                # much more compact representation of data.  Reservednodes gives
                # which notes are reserved.
                inventory = ALPSBridge.fetch_inventory()
Paul Rich's avatar
Paul Rich committed
226
                _logger.info('INVENTORY FETCHED')
227
                system = ALPSBridge.extract_system_node_data(ALPSBridge.system())
Paul Rich's avatar
Paul Rich committed
228
                _logger.info('SYSTEM DATA FETCHED')
229
                reservations = ALPSBridge.fetch_reservations()
Paul Rich's avatar
Paul Rich committed
230
                _logger.info('ALPS RESERVATION DATA FETCHED')
231
                # reserved_nodes = ALPSBridge.reserved_nodes()
232 233
                ssd_enabled = ALPSBridge.fetch_ssd_enable()
                _logger.info('CAPMC SSD ENABLED DATA FETCHED')
234
                ssd_info = ALPSBridge.fetch_ssd_static_data(raw=True) #2017-09-15: API doc is wrong.  Need RAW and work on cname here.
235 236 237
                _logger.info('CAPMC SSD DETAIL DATA FETCHED')
                ssd_diags = ALPSBridge.fetch_ssd_diags()
                _logger.info('CAPMC SSD DIAG DATA FETCHED')
238 239 240
            except Exception:
                #don't crash out here.  That may trash a statefile.
                _logger.error('Possible transient encountered during initialization. Retrying.',
241
                        exc_info=True)
242 243 244 245
                Cobalt.Util.sleep(10)
            else:
                pending = False

246
        self._assemble_nodes(inventory, system, ssd_enabled, ssd_info, ssd_diags)
247 248
        #Reversing the node name to id lookup is going to save a lot of cycles.
        for node in self.nodes.values():
249
            self.node_name_to_id[node.name] = node.node_id
250 251
        _logger.info('NODE INFORMATION INITIALIZED')
        _logger.info('ALPS REPORTS %s NODES', len(self.nodes))
252 253 254
        # self._assemble_reservations(reservations, reserved_nodes)
        return

255
    def _assemble_nodes(self, inventory, system, ssd_enabled, ssd_info, ssd_diags):
256 257 258
        '''merge together the INVENTORY and SYSTEM query data to form as
        complete a picture of a node as we can.

259 260 261 262 263 264 265 266 267 268 269 270 271
        Args:
            inventory - ALPS QUERY(INVENTORY) data
            system - ALPS QUERY(SYSTEM) data
            ssd_enable - CAPMC get_ssd_enable data
            ssd_info - CAPMC get_ssds data
            ssd_diags - CAPMC get_ssd_diags data

        Returns:
            None

        Side Effects:
            Populates the node dictionary

272 273 274 275 276 277 278
        '''
        nodes = {}
        for nodespec in inventory['nodes']:
            node = CrayNode(nodespec)
            node.managed = True
            nodes[node.node_id] = node
        for node_id, nodespec in system.iteritems():
279 280 281 282 283 284
            nodes[node_id].attributes.update(nodespec['attrs'])
            # Should this be a different status?
            nodes[node_id].role = nodespec['role'].upper()
            if nodes[node_id].role.upper() not in ['BATCH']:
                nodes[node_id].status = 'down'
            nodes[node_id].status = nodespec['state']
285
        self._update_ssd_data(nodes, ssd_enabled, ssd_info, ssd_diags)
286 287
        self.nodes = nodes

288 289 290 291 292 293 294 295 296
    def _update_ssd_data(self, nodes, ssd_enabled=None, ssd_info=None, ssd_diags=None):
        '''Update/add ssd data from CAPMC'''
        if ssd_enabled is not None:
            for ssd_data in ssd_enabled['nids']:
                try:
                    nodes[str(ssd_data['nid'])].attributes['ssd_enabled'] = int(ssd_data['ssd_enable'])
                except KeyError:
                    _logger.warning('ssd info present for nid %s, but not reported in ALPS.', ssd_data['nid'])
        if ssd_info is not None:
297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313
            # Cray broke this query.  Need to remap based on cray-cname.  Yes, not having the nid is a violation of their own API.
            for ssd_data_key, ssd_data_val in ssd_info.items():
                if ssd_data_key not in ['e', 'err_msg']:
                    found = False
                    for node in nodes.values():
                        if node.name == ssd_data_key:
                            node.attributes['ssd_info'] = ssd_data_val[0]
                            found = True
                            break
                    if not found:
                        _logger.warning('ssd data for %s found, but no node found.', ssd_data_key)
            #This is the corrected query where we can reconstruct the nid index.
            # for ssd_data in ssd_info['nids']:
                # try:
                    # nodes[str(ssd_data['nid'])].attributes['ssd_info'] = ssd_data
                # except KeyError:
                    # _logger.warning('ssd info present for nid %s, but not reported in ALPS.', ssd_data['nid'])
314 315 316 317 318 319 320 321 322 323 324
        if ssd_diags is not None:
            for diag_info in ssd_diags['ssd_diags']:
                try:
                    node = nodes[str(diag_info['nid'])]
                except KeyError:
                    _logger.warning('ssd diag data present for nid %s, but not reported in ALPS.', ssd_data['nid'])
                else:
                    for field in ['life_remaining', 'ts', 'firmware', 'percent_used']:
                        node.attributes['ssd_info'][field] = diag_info[field]


325 326 327
    def _assemble_reservations(self, reservations, reserved_nodes):
        # FIXME: we can recover reservations now.  Implement this.
        pass
328

329
    def _gen_node_to_queue(self):
330
        '''(Re)Generate a mapping for fast lookup of node-id's to queues.'''
331
        with self._node_lock:
332
            self.nodes_by_queue = {}
333 334 335
            for node in self.nodes.values():
                for queue in node.queues:
                    if queue in self.nodes_by_queue.keys():
336
                        self.nodes_by_queue[queue].add(node.node_id)
337
                    else:
338
                        self.nodes_by_queue[queue] = set([node.node_id])
339

340
    @exposed
341
    def get_nodes(self, as_dict=False, node_ids=None, params=None, as_json=False):
342 343
        '''fetch the node dictionary.

344 345 346 347 348 349 350
            as_dict  - Return node information as a dictionary keyed to string
                        node_id value.
            node_ids - A list of node names to return, if None, return all nodes
                       (default None).
            params   - If requesting a dict, only request this list of
                       parameters of the node.
            json     - Encode to json before sending.  Useful on large systems.
351 352 353 354 355

            returns the node dictionary.  Can reutrn underlying node data as
            dictionary for XMLRPC purposes

        '''
356 357 358 359 360 361 362 363 364
        def node_filter(node):
            if node_ids is not None:
                return (str(node[0]) in [str(nid) for nid in node_ids])
            return True

        node_info = None
        if as_dict:
            retdict = {k:v.to_dict(True, params) for k, v in self.nodes.items()}
            node_info = dict(filter(node_filter, retdict.items()))
365
        else:
366 367 368 369 370
            node_info = dict(filter(node_filter, self.nodes.items()))
        if as_json:
            return json.dumps(node_info)
        return node_info

371
    def _run_and_wrap(self, update_func):
372
        self.logger.debug('_run_and_wrap %s, tid:%s', update_func, get_current_thread_identifier())
373 374 375 376 377 378 379 380
        update_func_name = update_func.__name__
        bool_error = False
        td = -1.0
        ts = time.time()
        try:
            update_func()
        except Exception:
            te = time.time()
Paul Rich's avatar
Paul Rich committed
381
            tb_str = sanitize_password('\n'.join(extract_traceback()))
382 383 384 385 386 387 388 389 390
            td = te - ts
            self.logger.error('_run_and_wrap(%s): td:%s error:%s' % (update_func_name, td, tb_str))
            bool_error = True
        else:
            te = time.time()
            td = te - ts
            bool_error = False
        return update_func_name, bool_error, td

391 392
    def _run_update_state(self):
        '''automated node update functions on the update timer go here.'''
393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411
        try:
            self.logger.info('_run_update_state starting, tid:%s, queue:%s',
                              get_current_thread_identifier(), self.node_update_thread_kill_queue.qsize())
            while self.node_update_thread_kill_queue.empty() is True:
                self.logger.info('_run_update_state running, tid:%s', get_current_thread_identifier())
                # Each of these is wrapped in it's own log-and-preserve block.
                # The outer try is there to ensure the thread update timeout happens.
                metadata_lst = []
                metadata_lst.append(self._run_and_wrap(self.process_manager.update_launchers))
                metadata_lst.append(self._run_and_wrap(self.update_node_state))
                metadata_lst.append(self._run_and_wrap(self._get_exit_status))
                any_error = False
                for func_name, error, td in metadata_lst:
                    if error is True:
                        any_error = True
                if any_error is True:
                    self.logger.critical("_run_update_state: error occurred, timings below.")
                    for func_name, error, td in metadata_lst:
                        self.logger.critical("%s: %s", func_name, td)
412 413 414
                self.logger.info('_run_update_state sleeping for %s, tid:%s', UPDATE_THREAD_TIMEOUT,
                        get_current_thread_identifier())
                Cobalt.Util.sleep(UPDATE_THREAD_TIMEOUT)
415 416 417 418 419 420 421
            self.logger.critical('_run_update_state exiting, tid:%s', get_current_thread_identifier())
            self.node_update_thread_kill_queue.get(timeout=1.0)
            self.node_update_thread_dead = True
        finally:
            self.node_update_thread_dead = True
        self.logger.critical('_run_update_state dead, tid:%s', get_current_thread_identifier())
        return
422

423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457
    def _reconstruct_node(self, inven_node, inventory):
        '''Reconstruct a node from statefile information.  Needed whenever we
        find a new node.  If no statefile information from the orignal cobalt
        invocation exists, bring up a node in default states and mark node
        administratively down.

        This node was disabled and invisible to ALPS at the time Cobalt was
        initialized and so we have no current record of that node.

        '''
        nid = inven_node['node_id']
        new_node = None
        #construct basic node from inventory
        for node_info in inventory['nodes']:
            if int(node_info['node_id']) == int(nid):
                new_node = CrayNode(node_info)
                break
        if new_node is None:
            #we have a phantom node?
            self.logger.error('Unable to find inventory information for nid: %s', nid)
            return
        # if we have information from the statefile we need to repopulate the
        # node with the saved data.
        # Perhaps this should be how I construct all node data anyway?
        if self.init_spec is not None:
            node_info = self.init_spec.get('node_info', {})
            try:
                new_node.reset_info(node_info[str(nid)])
                self.logger.warning('Node %s reconstructed.', nid)
            except:
                self.logger.warning("Node nid: %s not found in restart information.  Bringing up node in a clean configuration.", nid, exc_info=True)
                #put into admin_down
                new_node.admin_down = True
                new_node.status = 'down'
                self.logger.warning('Node %s marked down.', nid)
Paul Rich's avatar
Paul Rich committed
458
        new_node.managed = True
459 460 461
        self.nodes[str(nid)] = new_node
        self.logger.warning('Node %s added to tracking.', nid)

462

463 464 465 466 467 468
    @exposed
    def update_node_state(self):
        '''update the state of cray nodes. Check reservation status and system
        stateus as reported by ALPS

        '''
Paul Rich's avatar
Paul Rich committed
469 470 471
        #Check clenaup progress.  Check ALPS reservations.  Check allocated
        #nodes.  If there is no resource reservation and the node is not in
        #current alps reservations, the node is ready to schedule again.
472
        now = time.time()
473 474 475 476 477 478 479 480 481 482 483 484 485 486
        # This lock doesn't need to be held for most update operations
        fetch_time_start = time.time()
        try:
            #updated for >= 1.6 interface
            inven_nodes = ALPSBridge.extract_system_node_data(ALPSBridge.system())
            reservations = ALPSBridge.fetch_reservations()
            # Fetch SSD diagnostic data and enabled flags. I would hope these change in event of dead ssd
            ssd_enabled = ALPSBridge.fetch_ssd_enable()
            ssd_diags = ALPSBridge.fetch_ssd_diags()
        except (ALPSBridge.ALPSError, ComponentLookupError):
            _logger.warning('Error contacting ALPS for state update.  Aborting this update',
                    exc_info=True)
            return
        #_logger.debug("time in ALPS fetch: %s seconds", (time.time() - fetch_time_start))
487
        with self._node_lock:
488 489 490 491 492 493 494 495 496 497 498 499 500 501 502
            # We set a pending startup timeout from the scheduler so that the queue-manager has
            # time to start the job, but will also release resources should the resource manager
            # fail to start the job in a timely fashion or errors out (like a badly timed hold)
            startup_time_to_clear = []
            #clear pending starttimes.
            for jobid, start_time in self.pending_starts.items():
                if int(now) > int(start_time):
                    startup_time_to_clear.append(jobid)
            for jobid in startup_time_to_clear:
                _logger.info("Jobid %s: Clearing pending start.", jobid)
                del self.pending_starts[jobid]

            self.check_killing_aprun()

            # ALPS reservation cleanup
503
            inven_reservations = reservations.get('reservations', [])
504
            start_time = time.time()
Paul Rich's avatar
Paul Rich committed
505
            self._detect_rereservation(inven_reservations)
506 507 508 509 510 511
            # check our reservation objects.  If a res object doesn't correspond
            # to any backend reservations, this reservation object should be
            # dropped
            alps_res_to_delete = []
            current_alps_res_ids = [int(res['reservation_id']) for res in
                    inven_reservations]
Paul Rich's avatar
Paul Rich committed
512
            res_jobid_to_delete = []
513 514 515 516
            if self.alps_reservations == {}:
                # if we have nodes in cleanup-pending but no alps reservations,
                # then the nodes in cleanup pending are considered idle (or
                # at least not in cleanup).  Hardware check can catch these
517 518
                # later. This catches leftover reservations from hard-shutdowns
                # while running.
519 520 521 522
                for node in self.nodes.values():
                    if node.status in ['cleanup', 'cleanup-pending']:
                        node.status = 'idle'
            for alps_res in self.alps_reservations.values():
523
                if int(alps_res.jobid) in [int(i) for i in self.pending_starts.keys()]:
Paul Rich's avatar
Paul Rich committed
524
                    continue #Get to this only after timeout happens
Paul Rich's avatar
Paul Rich committed
525
                #find alps_id associated reservation
526
                if int(alps_res.alps_res_id) not in current_alps_res_ids:
Paul Rich's avatar
Paul Rich committed
527
                    for node_id in alps_res.node_ids:
528
                        if not self.nodes[str(node_id)].reserved:
Paul Rich's avatar
Paul Rich committed
529
                            #pending hardware status update
530
                            self.nodes[str(node_id)].status = 'idle'
Paul Rich's avatar
Paul Rich committed
531
                    res_jobid_to_delete.append(alps_res.jobid)
Paul Rich's avatar
Paul Rich committed
532
                    _logger.info('job %s: Nodes %s cleanup complete.', alps_res.jobid, compact_num_list(alps_res.node_ids))
Paul Rich's avatar
Paul Rich committed
533
            for jobid in res_jobid_to_delete:
534
                _logger.info('%s: ALPS reservation for this job complete.', jobid)
Paul Rich's avatar
Paul Rich committed
535 536 537 538 539 540 541 542
                try:
                    del self.alps_reservations[str(jobid)]
                except KeyError:
                    _logger.warning('Job %s: Attempted to remove ALPS reservation for this job multiple times', jobid)
                if self.alps_reservations.get(int(jobid), None) is not None:
                    # in case of type leakage
                    _logger.warning('Job %s: ALPS reservation found with integer key: deleting', jobid)
                    del self.alps_reservations[jobid]
Paul Rich's avatar
Paul Rich committed
543 544
            #process group should already be on the way down since cqm released the
            #resource reservation
545
            cleanup_nodes = [node for node in self.nodes.values()
546
                             if node.status in ['cleanup-pending', 'cleanup']]
Paul Rich's avatar
Paul Rich committed
547
            #If we have a block marked for cleanup, send a release message.
Paul Rich's avatar
Paul Rich committed
548
            released_res_jobids = []
549
            cleaned_nodes = []
Paul Rich's avatar
Paul Rich committed
550
            for node in cleanup_nodes:
551
                found = False
552
                for alps_res in self.alps_reservations.values():
553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571
                    if str(node.node_id) in alps_res.node_ids:
                        found = True
                        if alps_res.jobid not in released_res_jobids:
                            #send only one release per iteration
                            apids = alps_res.release()
                            if apids is not None:
                                for apid in apids:
                                    self.signal_aprun(apid)
                            released_res_jobids.append(alps_res.jobid)
                if not found:
                    # There is no alps reservation to release, cleanup is
                    # already done.  This happens with very poorly timed
                    # qdel requests. Status will be set properly with the
                    # subsequent hardware status check.
                    _logger.info('Node %s cleanup complete.', node.node_id)
                    node.status = 'idle'
                    cleaned_nodes.append(node)
            for node in cleaned_nodes:
                cleanup_nodes.remove(node)
Paul Rich's avatar
Paul Rich committed
572 573

        #find hardware status
574 575 576
            #so we do this only once for nodes being added.
            #full inventory fetch is expensive.
            recon_inventory = None
Paul Rich's avatar
Paul Rich committed
577
            for inven_node in inven_nodes.values():
578 579
                if self.nodes.has_key(str(inven_node['node_id'])):
                    node = self.nodes[str(inven_node['node_id'])]
580
                    node.role = inven_node['role'].upper()
581
                    node.attributes.update(inven_node['attrs'])
Paul Rich's avatar
Paul Rich committed
582
                    if node.reserved:
583 584
                        #node marked as reserved.
                        if self.alps_reservations.has_key(str(node.reserved_jobid)):
Paul Rich's avatar
Paul Rich committed
585 586
                            node.status = 'busy'
                        else:
587 588 589 590 591 592
                            # check to see if the resource reservation should be
                            # released.
                            if node.reserved_until >= now:
                                node.status = 'allocated'
                            else:
                                node.release(user=None, jobid=None, force=True)
Paul Rich's avatar
Paul Rich committed
593
                    else:
594
                        node.status = inven_node['state'].upper()
595 596
                        if node.role.upper() not in ['BATCH'] and node.status is 'idle':
                            node.status = 'alps-interactive'
597
                else:
598 599 600
                    # Apparently, we CAN add nodes on the fly.  The node would
                    # have been disabled.  We need to add a new node and update
                    # it's state.
601
                    _logger.warning('Unknown node %s found. Starting reconstruction.', inven_node['node_id'])
602 603 604 605 606 607 608 609 610
                    try:
                        if recon_inventory is None:
                            recon_inventory = ALPSBridge.fetch_inventory()
                    except:
                        _logger.error('Failed to fetch inventory.  Will retry on next pass.', exc_info=True)
                    else:
                        self._reconstruct_node(inven_node, recon_inventory)
                   # _logger.error('UNS: ALPS reports node %s but not in our node list.',
                   #               inven_node['node_id'])
611 612
            # Update SSD data:
            self._update_ssd_data(self.nodes, ssd_enabled=ssd_enabled, ssd_diags=ssd_diags)
Paul Rich's avatar
Paul Rich committed
613 614 615
            #should down win over running in terms of display?
            #keep node that are marked for cleanup still in cleanup
            for node in cleanup_nodes:
616
                node.status = 'cleanup-pending'
617
        #_logger.debug("time in UNS lock: %s seconds", (time.time() - start_time))
618 619
        return

Paul Rich's avatar
Paul Rich committed
620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668
    def _detect_rereservation(self, inven_reservations):
        '''Detect and update the ALPS reservation associated with a running job.
        We are only concerned with BATCH reservations.  Others would be
        associated with running jobs, and should not be touched.

        '''
        def _construct_alps_res():
            with self._node_lock:
                job_nodes = [node.node_id for node in self.nodes.values()
                        if node.reserved_jobid == int(alps_res['batch_id'])]
            new_resspec = {'reserved_nodes': job_nodes,
                           'reservation_id': str(alps_res['reservation_id']),
                           'pagg_id': 0 #unknown.  Not used here.
                            }
            new_jobspec = {'jobid': int(alps_res['batch_id']),
                           'user' : alps_res['user_name']}

            return ALPSReservation(new_jobspec, new_resspec, self.nodes)

        replaced_reservation = None
        for alps_res in inven_reservations:
            try:
                #This traversal is terrible. May want to hide this in the API
                #somewhere
                if alps_res['ApplicationArray'][0]['Application'][0]['CommandArray'][0]['Command'][0]['cmd'] != 'BASIL':
                    # Not a reservation we're in direct control of.
                    continue
            except (KeyError, IndexError):
                #not a batch reservation
                continue
            if str(alps_res['batch_id']) in self.alps_reservations.keys():
                # This is a reservation we may already know about
                if (int(alps_res['reservation_id']) ==
                        self.alps_reservations[str(alps_res['batch_id'])].alps_res_id):
                    # Already know about this one
                    continue
                # we have a re-reservation.  If this has a batch id, we need
                # to add it to our list of tracked reservations, and inherit
                # other reservation details.  We can pull the reservation
                # information out of reserve_resources_until.

                # If this is a BATCH reservation and no hardware has that
                # reservation id, then this reservation needs to be released
                # Could happen if we have a job starting right at the RRU
                # boundary.
                new_alps_res = _construct_alps_res()
                tracked_res = self.alps_reservations.get(new_alps_res.jobid, None)
                if tracked_res is not None:
                    try:
Paul Rich's avatar
Paul Rich committed
669
                        apids = tracked_res.release()
Paul Rich's avatar
Paul Rich committed
670 671 672 673 674 675 676 677 678 679 680 681 682 683 684
                    except ALPSBridge.ALPSError:
                        # backend reservation probably is gone, which is why
                        # we are here in the first place.
                        pass
                self.alps_reservations[str(alps_res['batch_id'])] = new_alps_res
            else:
                #this is a basil reservation we don't know about already.
                new_alps_res = _construct_alps_res()
                if len(new_alps_res.node_ids) == 0:
                    # This reservation has no resources, so Cobalt's internal
                    # resource reservation tracking has no record.  This needs to
                    # be removed.
                    new_alps_res.release()
                else:
                    self.alps_reservations[str(alps_res['batch_id'])] = new_alps_res
Paul Rich's avatar
Paul Rich committed
685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710
        return

    def signal_aprun(self, aprun_id, signame='SIGINT'):
        '''Signal an aprun by aprun id (application_id).  Does not block.
        Use check_killing_aprun to determine completion/termination.  Does not
        depend on the host the aprun(s) was launched from.

        Input:
            aprun_id - integer application id number.
            signame  - string name of signal to send (default: SIGINT)
        Notes:
            Valid signals to apkill are:
            SIGHUP, SIGINT, SIGQUIT, SIGTERM, SIGABRT, SIGUSR1, SIGUSR2, SIGURG,
            and SIGWINCH (from apkill(1) man page.)  Also allowing SIGKILL.

        '''
        #Expect changes with an API updte

        #mark legal signals from docos
        if (signame not in ['SIGHUP', 'SIGINT', 'SIGQUIT', 'SIGTERM', 'SIGABRT',
            'SIGUSR1', 'SIGUSR2', 'SIGURG','SIGWINCH', 'SIGKILL']):
            raise ValueError('%s is not a legal value for signame.', signame)
        try:
            retval = Cobalt.Proxy.ComponentProxy('system_script_forker').fork(
                    [APKILL_CMD, '-%s' % signame, '%d' % int(aprun_id)],
                    'aprun_termination', '%s cleanup:'% aprun_id)
Paul Rich's avatar
Paul Rich committed
711
            _logger.info("killing backend ALPS application_id: %s", aprun_id)
Paul Rich's avatar
Paul Rich committed
712 713 714 715 716 717 718 719 720 721 722 723 724 725 726
        except xmlrpclib.Fault:
            _logger.warning("XMLRPC Error while killing backend job: %s, will retry.",
                    aprun_id, exc_info=True)
        except:
            _logger.critical("Unknown Error while killing backend job: %s, will retry.",
                    aprun_id, exc_info=True)
        else:
            self.killing_jobs[aprun_id] = retval
        return

    def check_killing_aprun(self):
        '''Check that apkill commands have completed and clean them from the
        system_script_forker.  Allows for non-blocking cleanup initiation.

        '''
727

Paul Rich's avatar
Paul Rich committed
728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743
        try:
            system_script_forker = Cobalt.Proxy.ComponentProxy('system_script_forker')
        except:
            self.logger.critical("Cannot connect to system_script_forker.",
                    exc_info=True)
            return
        complete_jobs = []
        rev_killing_jobs = dict([(v,k) for (k,v) in self.killing_jobs.iteritems()])
        removed_jobs = []
        current_killing_jobs = system_script_forker.get_children(None, self.killing_jobs.values())

        for job in current_killing_jobs:
            if job['complete']:
                del self.killing_jobs[rev_killing_jobs[int(job['id'])]]
                removed_jobs.append(job['id'])
        system_script_forker.cleanup_children(removed_jobs)
Paul Rich's avatar
Paul Rich committed
744
        return
Paul Rich's avatar
Paul Rich committed
745

746
    @exposed
747 748 749 750 751 752
    def find_queue_equivalence_classes(self, reservation_dict, active_queue_names, passthrough_blocking_res_list=[]):
        '''Given a list of reservations and a list of active queues from the queue-manager
        via the scheduler, returns a list of dictionaries containing the current active
        reservations on the machine as well as a list of active queues that have nodes
        associated with them.   From this the scheduler can determine which jobs have
        any chance at all of being eligible to run.
753 754

        Inputs:
755 756 757 758 759 760 761 762
            reservation_dict -- a mapping of active reservations to resrouces.
                                These will block any job in a normal queue.
            active_queue_names -- A list of queues that are currently enabled.
                                  Queues that are not in the 'running' state
                                  are ignored.
            passthrough_partitions -- Not used on Cray systems currently.  This is
                                      for handling hardware that supports
                                      partitioned interconnect networks.
763 764

        Output:
765
            A list containing dictionaries with reservations and active queues with associated nodes.
766 767

        Side effects:
768
            None
769 770

        Internal Data:
771 772 773 774 775 776 777 778
            This does make use of a list of current queues associated with nodes.
            This is done for speed, to prevent a lot of needless iteration.
            The nodes_by_queue association is updated any time that there is a change
            in the mapping of queues to nodes, when nodeadm --queue is invoked.

        Notes:
            This always returns a single "equivalence class" no matter what the
            current queue-node binding on the machine is.
779 780

        '''
Eric Roy Pershey's avatar
Eric Roy Pershey committed
781 782
        with self._node_lock:
            equiv_class = [{'reservations': reservation_dict.keys(),
783 784
                 'queues': [queue_name for queue_name in self.nodes_by_queue.keys()
                            if queue_name in active_queue_names]}]
Eric Roy Pershey's avatar
Eric Roy Pershey committed
785
        return equiv_class
786

787
    def _setup_special_locations(self, job):
788 789 790
        forbidden = set([str(loc) for loc in chain_loc_list(job.get('forbidden', []))])
        required = set([str(loc) for loc in chain_loc_list(job.get('required', []))])
        requested_locations = set([str(n) for n in expand_num_list(job['attrs'].get('location', ''))])
791 792 793 794 795 796 797 798 799
        # If ssds are required, add nodes without working SSDs to the forbidden list
        ssd_unavail = set([])
        if job.get('attrs', {}).get("ssds", "none").lower() == "required":
            ssd_min_size = int(job.get('attrs', {}).get("ssd_size", DEFAULT_MIN_SSD_SIZE)) * 1000000000 #convert to bytes
            ssd_unavail.update(set([str(node.node_id) for node in self.nodes.values()
                                  if (node.attributes['ssd_enabled'] == 0 or
                                      int(node.attributes.get('ssd_info', {'size': DEFAULT_MIN_SSD_SIZE})['size'])  < ssd_min_size)
                                ]))
        return (forbidden, required, requested_locations, ssd_unavail)
800

801
    def _assemble_queue_data(self, job, idle_only=True, drain_time=None):
802 803
        '''put together data for a queue, or queue-like reservation structure.

804 805 806 807 808 809 810
        Input:
            job - dictionary of job data.
            idle_only - [default: True] if True, return only idle nodes.
                        Otherwise return nodes in any non-down status.

        return count of idle resources, and a list of valid nodes to run on.
        if idle_only is set to false, returns a set of candidate draining nodes.
811 812 813


        '''
814 815 816 817
        # RESERVATION SUPPORT: Reservation queues are ephemeral, so we will
        # not find the queue normally. In the event of a reservation we'll
        # have to intersect required nodes with the idle and available
        # we also have to forbid a bunch of locations, in  this case.
818
        unavailable_nodes = []
819
        forbidden, required, requested_locations, ssd_unavail = self._setup_special_locations(job)
820 821 822 823 824 825
        requested_loc_in_forbidden = False
        for loc in requested_locations:
            if loc in forbidden:
                #don't spam the logs.
                requested_loc_in_forbidden = True
                break
826
        if job['queue'] not in self.nodes_by_queue.keys():
827 828
            # Either a new queue with no resources, or a possible
            # reservation need to do extra work for a reservation
829
            node_id_list = list(required - forbidden - ssd_unavail)
830
        else:
831
            node_id_list = list(set(self.nodes_by_queue[job['queue']]) - forbidden - ssd_unavail)
832
        if requested_locations != set([]): # handle attrs location= requests
833
            job_set = set([str(nid) for nid in requested_locations])
834
            if job['queue'] not in self.nodes_by_queue.keys():
835 836 837
                #we're in a reservation and need to further restrict nodes.
                if job_set <= set(node_id_list):
                    # We are in a reservation there are no forbidden nodes.
838
                    node_id_list = list(requested_locations - ssd_unavail)
839 840 841 842
                else:
                    # We can't run this job.  Insufficent resources in this
                    # reservation to do so.  Don't risk blocking anything.
                    node_id_list = []
843
            else:
844 845 846 847 848
                # Check to see if the job is requesting resources that are not
                # available in the queue specified and raise an exception.  This
                # results in a warning.
                if not requested_locations.issubset(set(self.nodes_by_queue[job['queue']])):
                    raise ValueError("requested locations not in queue")
849 850
                #normal queues.  Restrict to the non-reserved nodes.
                if job_set <= set([str(node_id) for node_id in
851
                                    self.nodes_by_queue[job['queue']]]):
852
                    node_id_list = list(requested_locations)
853 854 855 856
                    if not set(node_id_list).isdisjoint(forbidden):
                        # this job has requested locations that are a part of an
                        # active reservation.  Remove locaitons and drop available
                        # nodecount appropriately.
857
                        node_id_list = list(set(node_id_list) - forbidden - ssd_unavail)
858 859
                    # if not requested_loc_in_forbidden:
                        # raise ValueError("forbidden locations not in queue")
860
        with self._node_lock:
861 862 863 864 865 866 867
            if idle_only:
                unavailable_nodes = [node_id for node_id in node_id_list
                        if self.nodes[str(node_id)].status not in ['idle']]
            else:
                unavailable_nodes = [node_id for node_id in node_id_list
                        if self.nodes[str(node_id)].status in
                        self.nodes[str(node_id)].DOWN_STATUSES]
868
            if drain_time is not None:
869
                unavailable_nodes.extend([node_id for node_id in node_id_list
870
                    if (self.nodes[str(node_id)].draining and
871
                        (self.nodes[str(node_id)].drain_until - BACKFILL_EPSILON) < int(drain_time))])
872
        for node_id in set(unavailable_nodes):
873
            node_id_list.remove(node_id)
874
        return sorted(node_id_list, key=lambda nid: int(nid))
875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893

    def _select_first_nodes(self, job, node_id_list):
        '''Given a list of nids, select the first node count nodes fromt the
        list.  This is the target for alternate allocator replacement.

        Input:
            job - dictionary of job data from the scheduler
            node_id_list - a list of possible candidate nodes

        Return:
            A list of nodes.  [] if insufficient nodes for the allocation.

        Note: hold the node lock while doing this.  We really don't want a
        update to happen while doing this.

        '''
        ret_nodes = []
        with self._node_lock:
            if int(job['nodes']) <= len(node_id_list):
894 895
                node_id_list.sort(key=lambda nid: int(nid))
                ret_nodes = node_id_list[:int(job['nodes'])]
896 897
        return ret_nodes

898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913
    def _select_first_nodes_prefer_memory_match(self, job, node_id_list):
        '''Given a list of nids, select the first node count nodes fromt the
        list.  Prefer nodes that match the memory modes for a given job, then
        go in nid order.

        Input:
            job - dictionary of job data from the scheduler
            node_id_list - a list of possible candidate nodes

        Return:
            A list of nodes.  [] if insufficient nodes for the allocation.

        Note: hold the node lock while doing this.  We really don't want a
        update to happen while doing this.

        '''
914
        ssd_required = (job.get('attrs', {}).get("ssds", "none").lower() == "required")
915 916 917
        if job.get('attrs', {}).get('mcdram', None) is None or job.get('attrs', {}).get('numa', None) is None:
            # insufficient information to include a mode match
            return self._select_first_nodes(job, node_id_list)
918
        ret_nids = []
919 920 921
        with self._node_lock:
            considered_nodes = [node for node in self.nodes.values() if node.node_id in node_id_list]
            for node in considered_nodes:
922
                if (node.attributes['hbm_cache_pct'] == MCDRAM_TO_HBMCACHEPCT[job['attrs']['mcdram']] and
923
                        node.attributes['numa_cfg'] == job['attrs']['numa']):
924 925
                    ret_nids.append(int(node.node_id))
            if len(ret_nids) < int(job['nodes']):
926 927
                node_id_list.sort(key=lambda nid: int(nid))
                for nid in node_id_list:
928 929
                    if int(nid) not in ret_nids:
                        ret_nids.append(int(nid))
930 931
                        if len(ret_nids) >= int(job['nodes']):
                            break
932 933
        return ret_nids[:int(job['nodes'])]

934

935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954
    def _associate_and_run_immediate(self, job, resource_until_time, node_id_list):
        '''Given a list of idle node ids, choose a set that can run a job
        immediately, if a set exists in the node_id_list.

        Inputs:
            job - Dictionary of job data
            node_id_list - a list of string node id values

        Side Effects:
            Will reserve resources in ALPS and will set resource reservations on
            allocated nodes.

        Return:
            None if no match, otherwise the pairing of a jobid and set of nids
            that have been allocated to a job.

        '''
        compact_locs = None
        if int(job['nodes']) <= len(node_id_list):
            #this job can be run immediately
955
            to_alps_list = self._select_first_nodes_prefer_memory_match(job, node_id_list)
956 957 958 959 960
            job_locs = self._ALPS_reserve_resources(job, resource_until_time,
                    to_alps_list)
            if job_locs is not None and len(job_locs) == int(job['nodes']):
                compact_locs = compact_num_list(job_locs)
                #temporary reservation until job actually starts
961
                #FIXME: data race, self.pending_starts can be modified without locks
962 963 964
                self.pending_starts[job['jobid']] = resource_until_time
                self.reserve_resources_until(compact_locs, resource_until_time, job['jobid'])
        return compact_locs
965

966
    @locking
967 968
    @exposed
    def find_job_location(self, arg_list, end_times, pt_blocking_locations=[]):
969 970 971 972 973 974
        '''Given a list of jobs, and when jobs are ending, return a set of
        locations mapped to a jobid that can be run.  Also, set up draining
        as-needed to run top-scored jobs and backfill when possible.

        Called once per equivalence class.

975 976
        Args::
            arg_list: A list of dictionaries containning information on jobs to
977
                   cosnider.
978
            end_times: list containing a mapping of locations and the times jobs