#!/usr/bin/env python from torque_utils import pbsnodes # this config allows mcore to run up to full ATLAS allocation (27.02.2015) MAXDRAIN = 32 # max num of nodes allowed to drain MAXFREE = 49 # max num of free slots to tolerate MAXFREEPERNODE = 3 NODESPERGRAB = 3 # number of nodes to grab each time around CANDIDATE_NODES = [ 'wn-car-0%02d.farm.nikhef.nl' % (n) for n in range(1,97) ] + \ [ 'wn-knal-0%02d.farm.nikhef.nl' % (n) for n in range(1,19) ] MCQUEUE = 'atlasmc' # settings below appropriate for knal nodes (32 cores) # ... want to keep num of draining nodes # to MAXFREE / 3 since giving back a node could be expensive. # it might already be running several mc jobs # MAXDRAIN = 16 # max num of nodes allowed to drain # MAXFREE = 49 # max num of free slots to tolerate # MAXFREEPERNODE = 3 # NODESPERGRAB = 1 # CANDIDATE_NODES = [ 'wn-knal-0%02d.farm.nikhef.nl' % (n) for n in range(1,19) ] # MCQUEUE = 'atlasmc' # settings below more appropriate for smrt nodes (8 core) # here giving a node back doesn't really matter, it wasn't # running any mc jobs yet anyway. better to grab lots # of nodes and give back the ones that drain the slowest if # too many slots are free. # MAXDRAIN = 16 # max num of nodes allowed to drain # MAXFREE = 49 # max num of free slots to tolerate # CANDIDATE_NODES = [ 'wn-smrt-0%02d.farm.nikhef.nl' % (n) for n in range(1,73) ] UNDERPOP_NODES_FILE = ".nodes_with_too_few_jobs" TORQUE = "stro.nikhef.nl" import os import pickle import sys import subprocess def getmcjobinfo(nodes): # input is the list of nodes for which to get info # function returns tuple (jobs_waiting, node_info) # jobs_waiting boolean value : are there MC jobs waiting to be run (state Q)? (independent of nodes!) # node_info: list of tuples (wn_name, wn, num_running_mc, num_free_slots) # where wn is the node object for the machine with name wn_name, num_running_mc is the number of # mc jobs running on that node, and num_free_slots is the number of unused job slots on that node usedkeys = ['egroup', 'jobid', 'queue', 'job_state', 'euser', 'exec_host' ] import torqueJobs import torqueAttMappers as tam import tempfile qsfname = tempfile.mktemp(".txt","qsmf",os.environ['HOME']+"/tmp") import time os.system('/usr/bin/qstat -f @' + TORQUE + ' > ' + qsfname) now = time.mktime(time.localtime()) jlist = torqueJobs.qs_parsefile(qsfname) os.system('mv ' + qsfname + ' ' + os.environ['HOME'] + '/tmp/qstat.last.txt') def mapatts(indict,inkeys): sdict = tam.sub_dict(indict,inkeys) odict = dict() for k in sdict.keys(): if k in tam.tfl and sdict[k]: secs = tam.hms(sdict[k]) sdict[k] = secs/3600. if k in tam.mfl and sdict[k]: mebi = tam.memconvert(sdict[k]) sdict[k] = mebi if k in tam.tfl2 and sdict[k]: secs = tam.tconv(sdict[k]) sdict[k] = secs elif k == 'job_state': statelett = sdict[k] if statelett in ['Q','W']: sdict[k] = 'queued' elif statelett in ['R','E']: sdict[k] = 'running' elif k == 'exec_host' and sdict[k]: termpos = sdict[k].find('/') wnstring = sdict[k][:termpos] sdict[k] = wnstring if sdict[k]: odict[k] = sdict[k] return odict mcjoblist = list() waitingJobs = False for j in jlist: if j['queue'] == MCQUEUE: newj = mapatts(j,usedkeys) mcjoblist.append(newj) if newj['job_state'] == 'queued': waitingJobs = True # find out how many running mc jobs each node has running_mc = dict() for n in nodes: running_mc[n.name] = 0 for j in mcjoblist: if j['job_state'] =='running': wn = j['exec_host'] if wn in running_mc.keys(): running_mc[wn] += 1 rawlist = list() for n in nodes: rawlist.append( (n.name, n, running_mc[n.name], n.freeCpu) ) from operator import itemgetter def srtrunningfree(item): # sort optimal for dropping nodes; for nodes with zero running mc jobs, want to # drop least-drained nodes (fewer free slots first in list); for nodes with # running mc jobs, want to shed as few nodes as possible so pick the more-drained # nodes first. this probably also works for shedding nodes when queue dries up. mcrun = item[2] emptyslots = item[3] if mcrun == 0: rank = emptyslots else: rank = 32*mcrun - emptyslots # 32 just a number bigger than expected emptyslots value return rank slist = sorted(rawlist, key=srtrunningfree) return waitingJobs, slist def remove_from_mc_pool(node): # print "adding el6 tag back to node", node.name if "el6" not in node.properties : proc = subprocess.Popen(['/usr/bin/qmgr'], stdin=subprocess.PIPE, stdout=subprocess.PIPE,) proc.stdin.write( 'set node ' + node.name + \ ' properties += el6\n' ) proc.stdin.write( 'print node ' + node.name + \ ' properties\n' ) out = proc.communicate()[0] # print out if "mc" in node.properties : proc = subprocess.Popen(['/usr/bin/qmgr'], stdin=subprocess.PIPE, stdout=subprocess.PIPE,) proc.stdin.write( 'set node ' + node.name + \ ' properties -= mc\n' ) proc.stdin.write( 'print node ' + node.name + \ ' properties\n' ) out = proc.communicate()[0] # print out def add_to_mc_pool(node): # print "node props b4:", grabbed_node.properties if "el6" in node.properties : proc = subprocess.Popen(['/usr/bin/qmgr'], stdin=subprocess.PIPE, stdout=subprocess.PIPE,) proc.stdin.write( 'set node ' + node.name + \ ' properties -= el6\n' ) proc.stdin.write( 'print node ' + node.name + \ ' properties\n' ) out = proc.communicate()[0] if "mc" not in node.properties : proc = subprocess.Popen(['/usr/bin/qmgr'], stdin=subprocess.PIPE, stdout=subprocess.PIPE,) proc.stdin.write( 'set node ' + node.name + \ ' properties += mc\n' ) proc.stdin.write( 'print node ' + node.name + \ ' properties\n' ) out = proc.communicate()[0] import optparse usage = "usage: %prog [-d debug_level] [-n]" p = optparse.OptionParser(description="Monitor state of multicore pool and adjust size as needed", usage=usage) p.add_option("-n",action="store_true",dest="noopt",default=False, help="don't do anything, just print what would have been done") p.add_option("-l",action="store",dest="logfile",default=None, help="log actions and information to LOGFILE (default stdout)") p.add_option("-L",action="store",dest="loglevel",default="INFO", help="print messages of LOGLEVEL (DEBUG, INFO, WARNING, ..., default INFO") import logging opts, args = p.parse_args() # assuming loglevel is bound to the string value obtained from the # command line argument. Convert to upper case to allow the user to # specify --log=DEBUG or --log=debug numeric_level = getattr(logging, opts.loglevel.upper(), None) if not isinstance(numeric_level, int): raise ValueError('Invalid log level: %s' % loglevel) if opts.logfile: logging.basicConfig(format='%(asctime)s %(levelname)s %(message)s', level=numeric_level,filename=opts.logfile) else: logging.basicConfig(format='%(asctime)s %(levelname)s %(message)s', level=numeric_level) if os.path.isfile(UNDERPOP_NODES_FILE): pkl_file = open(UNDERPOP_NODES_FILE,'rb') nodes_too_few_jobs_last_run = pickle.load(pkl_file) pkl_file.close() else: nodes_too_few_jobs_last_run = list() logging.debug("nodes from pickle file, marked from last run: " + \ repr(nodes_too_few_jobs_last_run) ) wnodes = pbsnodes() mcnodes = list() waiting = None node_tuples = None for node in wnodes: if node.name in CANDIDATE_NODES and node.state.count('offline') == 0: mcnodes.append(node) draining_slots = 0 mcdedicated = list() draining_nodes = 0 for node in mcnodes: if 'el6' not in node.properties and 'mc' in node.properties : mcdedicated.append(node) draining_slots += node.freeCpu if node.freeCpu > 0 : draining_nodes += 1 # check for dedicated nodes with too few jobs nodes_with_too_few_jobs = list() for node in mcdedicated: logging.debug(node.name + " has " + repr(node.freeCpu) + " free slots") if node.freeCpu > MAXFREEPERNODE: nodes_with_too_few_jobs.append(node) logging.debug("there are " + repr(len(nodes_with_too_few_jobs)) + \ " nodes with too few jobs") nodes_consistently_underpopulated = list() for n in nodes_with_too_few_jobs: if n.name in nodes_too_few_jobs_last_run: nodes_consistently_underpopulated.append(n) undcount = len(nodes_consistently_underpopulated) if undcount > 0: logging.debug("there are " + repr(undcount) + \ " nodes with too few jobs that were also marked last run" ) import random removed_a_node = False if undcount > 0: logging.info("nodes consistently underpopulated:") for n in nodes_consistently_underpopulated: logging.info(" " + n.name) if undcount > 1: remcount = undcount / 2 # number to remove logging.info("going to remove " + repr(remcount) + " from mc pool") else: remcount = 1 # find out how many running mc jobs each node has waiting, node_tuples = getmcjobinfo(nodes_consistently_underpopulated) for node_t in node_tuples[:remcount]: nname, nnode, running_mc, unused_slots = node_t logging.info("dumped %d empty slots, %d mc jobs on %s" % \ (unused_slots, running_mc, nname) ) if not opts.noopt : remove_from_mc_pool(nnode) nodes_with_too_few_jobs.remove(nnode) nodes_consistently_underpopulated.remove(nnode) removed_a_node = True namelist = list() if len(nodes_with_too_few_jobs) > 0: logging.debug("placing %d nodes " % (len(nodes_with_too_few_jobs)) + \ "with too few jobs on list for next run:") for n in nodes_with_too_few_jobs: logging.debug(n.name) namelist.append(n.name) if not opts.noopt: pkl_file = open(UNDERPOP_NODES_FILE,'wb') pickle.dump(namelist,pkl_file) pkl_file.close() if len(nodes_with_too_few_jobs) > 0 or removed_a_node : sys.exit(0) # if we survive to this point, all nodes 'dedicated' are being efficiently # used. are we draining less than the configured max? logging.debug("There are " + repr(len(mcdedicated)) + " dedicated nodes and " + \ repr(draining_slots) + " unused slots") if (MAXFREE - draining_slots) >= MAXFREEPERNODE: logging.debug("%d unused slots are permitted, so %d more" % (MAXFREE, MAXFREE - draining_slots)) logging.debug("headroom of more than %d+ slots means we can try to grab another node" % (MAXFREEPERNODE) ) if draining_nodes < MAXDRAIN : # first check if there are actually any waiting jobs to run; if not makes no sense to grab a node. waiting, node_tuples = getmcjobinfo(mcdedicated) if not waiting: logging.debug("No waiting jobs found, nothing to do") sys.exit(0) logging.debug("max %d node(s) with unused slots permitted, %d seen" % \ (MAXDRAIN, draining_nodes)) logging.debug("there are also waiting jobs: try to grab another node") # build a list of candidates to grab candidate_nodes = list() for n in mcnodes: if n not in mcdedicated: candidate_nodes.append(n) logging.debug("found %d candidate nodes to dedicate to mc" % len(candidate_nodes)) if len(candidate_nodes) < 1: logging.debug("no more nodes, bailing out, nothing more I can do") sys.exit(0) for nn in range(min(NODESPERGRAB,len(candidate_nodes))): # logging.debug("found %d candidate nodes to dedicate to mc" % len(candidate_nodes)) grabbed_node=random.choice(candidate_nodes) logging.info("%s added to mc node pool" % (grabbed_node.name)) candidate_nodes.remove(grabbed_node) if not opts.noopt: add_to_mc_pool(grabbed_node) else: logging.debug("There are %d nodes with unused slots (draining)" % (draining_nodes)) logging.debug("This equals or exceeds the configured max of %d" % (MAXDRAIN)) logging.debug("Doing nothing now") elif draining_slots > MAXFREE: # find out how many running mc jobs each node has waiting, node_tuples = getmcjobinfo(mcdedicated) slots_to_recover = draining_slots - MAXFREE logging.info("unused slot limit (%d) exceeded by %d " \ % (MAXFREE, slots_to_recover) + ": remove node(s) from mc pool") slots_recovered = 0 while slots_recovered < slots_to_recover: node_t = node_tuples.pop(0) nname, nnode, running_mc, unused_slots = node_t if unused_slots > 0: logging.info("dumped %d empty slots, %d mc jobs on %s" % \ (unused_slots, running_mc, nname) ) if not opts.noopt : remove_from_mc_pool(nnode) slots_recovered += unused_slots else: logging.debug("%d unused slots of allowed %d" % (draining_slots, MAXFREE)) logging.debug("difference is %d which is less than %d" % \ (MAXFREE - draining_slots, MAXFREEPERNODE) ) logging.debug("so: doing nothing now.")