def test_slurmenv_api_submit_exceed_total_cores(): if not in_slurm_allocation() or get_num_slurm_nodes() < 2: pytest.skip('test not run in slurm allocation or allocation is smaller than 2 nodes') resources, allocation = get_slurm_resources_binded() set_pythonpath_to_qcg_module() tmpdir = str(tempfile.mkdtemp(dir=SHARED_PATH)) try: m = LocalManager(['--log', 'debug', '--wd', tmpdir, '--report-format', 'json'], {'wdir': str(tmpdir)}) jobs = Jobs(). \ add_std({ 'name': 'date', 'execution': { 'exec': '/bin/date' }, 'resources': { 'numCores': { 'exact': resources.total_cores + 1 } }}) with pytest.raises(ConnectionError, match=r".*Not enough resources.*"): m.submit(jobs) assert len(m.list()) == 0 jobs = Jobs(). \ add_std({ 'name': 'date', 'execution': { 'exec': '/bin/date' }, 'resources': { 'numNodes': { 'exact': resources.total_nodes + 1 } }}) with pytest.raises(ConnectionError, match=r".*Not enough resources.*"): ids = m.submit(jobs) assert len(m.list()) == 0 jobs = Jobs(). \ add_std({ 'name': 'date', 'execution': { 'exec': '/bin/date', 'stdout': 'std.out', }, 'resources': { 'numCores': { 'exact': resources.total_cores } } }) jinfos = submit_2_manager_and_wait_4_info(m, jobs, 'SUCCEED') assert jinfos['date'].total_cores == resources.total_cores finally: if m: m.finish() # m.stopManager() m.cleanup() rmtree(tmpdir)
def test_slurmenv_api_cancel_kill_nl(): if not in_slurm_allocation() or get_num_slurm_nodes() < 2: pytest.skip('test not run in slurm allocation or allocation is smaller than 2 nodes') resources, allocation = get_slurm_resources_binded() set_pythonpath_to_qcg_module() tmpdir = str(tempfile.mkdtemp(dir=SHARED_PATH)) print(f'tmpdir: {tmpdir}') try: m = LocalManager(['--log', 'debug', '--wd', tmpdir, '--report-format', 'json'], {'wdir': str(tmpdir)}) iters=10 ids = m.submit(Jobs(). add(script='trap "" SIGTERM; sleep 30s', iteration=iters, stdout='sleep.out.${it}', stderr='sleep.err.${it}', numCores=1) ) jid = ids[0] assert len(m.list()) == 1 list_jid = list(m.list().keys())[0] assert list_jid == jid # wait for job to start executing sleep(2) m.cancel([jid]) # wait for SIGTERM job cancel sleep(2) jinfos = m.info_parsed(ids) assert all((len(jinfos) == 1, jid in jinfos, jinfos[jid].status == 'QUEUED')) # wait for SIGKILL job cancel (~ExecutionJob.SIG_KILL_TIMEOUT) sleep(ExecutionJob.SIG_KILL_TIMEOUT) jinfos = m.info_parsed(ids, withChilds=True) assert all((len(jinfos) == 1, jid in jinfos, jinfos[jid].status == 'CANCELED')) # the canceled iterations are included in 'failed' entry in job statistics # the cancel status is presented in 'childs/state' entry assert all((jinfos[jid].iterations, jinfos[jid].iterations.get('start', -1) == 0, jinfos[jid].iterations.get('stop', 0) == iters, jinfos[jid].iterations.get('total', 0) == iters, jinfos[jid].iterations.get('finished', 0) == iters, jinfos[jid].iterations.get('failed', -1) == iters)) assert len(jinfos[jid].childs) == iters for iteration in range(iters): job_it = jinfos[jid].childs[iteration] assert all((job_it.iteration == iteration, job_it.name == '{}:{}'.format(jid, iteration), job_it.status == 'CANCELED')), str(job_it) m.remove(jid) finally: m.finish() m.cleanup()
def test_local_manager_submit_simple(tmpdir): cores = 4 # switch on debugging (by default in api.log file) m = LocalManager(['--wd', str(tmpdir), '--nodes', str(cores)], {'wdir': str(tmpdir)}) try: res = m.resources() assert all( ('total_nodes' in res, 'total_cores' in res, res['total_nodes'] == 1, res['total_cores'] == cores)) ids = m.submit(Jobs().add(name='host', exec='/bin/hostname', args=['--fqdn'], stdout='host.stdout').add( name='date', exec='/bin/date', stdout='date.stdout', numCores={'exact': 2})) assert len(m.list()) == 2 m.wait4(ids) jinfos = m.info(ids) assert all( ('jobs' in jinfos, len(jinfos['jobs'].keys()) == 2, 'host' in jinfos['jobs'], 'date' in jinfos['jobs'], jinfos['jobs']['host'].get('data', {}).get('status', '') == 'SUCCEED', jinfos['jobs']['date'].get('data', {}).get('status', '') == 'SUCCEED')) aux_dir = find_single_aux_dir(str(tmpdir)) assert all( (exists(tmpdir.join('.qcgpjm-client', 'api.log')), exists(join(aux_dir, 'service.log')), exists(tmpdir.join('host.stdout')), exists(tmpdir.join('date.stdout')))) finally: m.finish() # m.stopManager() m.cleanup()
class QCGPJExecutor(Executor): """QCG-PilotJob Executor. It provides simplified interface for common uses of QCG-PilotJob Parameters ---------- wd : str, optional Working directory where QCG-PilotJob manager should be started, by default it is a current directory resources : str, optional The resources to use. If specified forces usage of Local mode of QCG-PilotJob Manager. The format is compliant with the NODES format of QCG-PilotJob, i.e.: [node_name:]cores_on_node[,node_name2:cores_on_node][,...]. Eg. to define 4 cores on an unnamed node use `resources="4"`, to define 2 nodes: node_1 with 2 cores and node_2 with 3 cores, use `resources="node_1:2,node_2:3"` reserve_core : bool, optional If True reserves a core for QCG-PilotJob Manager instance, by default QCG-PilotJob Manager shares a core with computing tasks Parameters. enable_rt_stats : bool, optional If True, QCG-PilotJob Manager will collect its runtime statistics wrapper_rt_stats : str, optional The path to the QCG-PilotJob Manager tasks wrapper program used for collection of statistics log_level : str, optional Logging level for QCG-PilotJob Manager (for both service and client part). other_args : optional Optional list of additional arguments for initialisation of QCG-PilotJob Manager Returns ------- None """ def __init__(self, wd=".", resources=None, reserve_core=False, enable_rt_stats=False, wrapper_rt_stats=None, log_level='info', *other_args): self.finished = False # ---- QCG PILOT JOB INITIALISATION --- # Establish logging levels service_log_level, client_log_level = self._setup_qcgpj_logging( log_level) # Prepare input arguments for QCG-PJM args = ['--log', service_log_level, '--wd', wd] if resources: args.append('--nodes') args.append(str(resources)) if reserve_core: args.append('--system-core') if enable_rt_stats: args.append('--enable-rt-stats') if wrapper_rt_stats: args.append('--wrapper-rt-stats') args.append(wrapper_rt_stats) if other_args: args.append(other_args) client_conf = { 'log_file': wd + '/api.log', 'log_level': client_log_level } _logger.info(f'Starting QCG-PJ Manager with arguments: {args}') # create QCGPJ Manager (service part) self._qcgpjm = LocalManager(args, client_conf) def __enter__(self): return self def __exit__(self, exc_type, exc_value, traceback): self.shutdown() def shutdown(self, wait=True): """Shutdowns the QCG-PJ manager service. If it is already closed, the method has no effect. """ if not self.finished: self._qcgpjm.finish() self.finished = True else: pass def submit(self, fn: Callable[..., Union[str, Tuple[str, Dict[str, Any]]]], *args, **kwargs): """Submits a specific task to the QCG-PJ manager using template-based, executor-like interface. Parameters ---------- fn : Callable A callable that returns a tuple representing a task's template. The first element of the tuple should be a string containing a QCG-PilotJob task's description with placeholders (identifiers preceded by $ symbol) and the second a dictionary that assigns default values for selected placeholders. *args: variable length list with dicts, optional A set of dicts which contain parameters that will be used to substitute placeholders defined in the template. Note: *args overwrite defaults, but they are overwritten by **kwargs **kwargs: arbitrary keyword arguments A set of keyword arguments that will be used to substitute placeholders defined in the template. Note: **kwargs overwrite *args and defaults. Returns ------- QCGPJFuture The QCGPJFuture object assigned with the submitted task """ template = fn() if isinstance(template, tuple): template_str = template[0] defaults = template[1] else: template_str = template defaults = {} t = Template(textwrap.dedent(template_str)) substitutions = {} for a in args: if a is not None: substitutions.update(a) substitutions.update(kwargs) td_str = t.substitute(defaults, **substitutions) td = ast.literal_eval(td_str) if 'env' not in td['execution']: td['execution']['env'] = {} td['execution']['env']['QCG_PM_EXEC_API_JOB_ID'] = '${jname}' jobs = Jobs() jobs.add_std(td) jobs_ids = self._qcgpjm.submit(jobs) return QCGPJFuture(jobs_ids, self._qcgpjm) @property def qcgpj_manager(self): """Returns current QCG-PilotJob manager instance """ return self._qcgpjm @staticmethod def _setup_qcgpj_logging(log_level): log_level = log_level.upper() try: service_log_level = ServiceLogLevel[log_level].value except KeyError: service_log_level = ServiceLogLevel.DEBUG.value try: client_log_level = ClientLogLevel[log_level].value except KeyError: client_log_level = ClientLogLevel.DEBUG.value return service_log_level, client_log_level
def test_resume_simple(tmpdir): try: ncores = 4 m = LocalManager(['--log', 'debug', '--wd', tmpdir, '--report-format', 'json', '--nodes', str(ncores)], {'wdir': str(tmpdir)}) its = 10 job_req = { 'name': 'sleep', 'execution': { 'exec': '/bin/sleep', 'args': [ '4s' ], 'stdout': 'out', }, 'iteration': { 'stop': its }, 'resources': { 'numCores': { 'exact': 1 } } } jobs = Jobs().add_std(job_req) job_ids = m.submit(jobs) # because job iterations executes in order, after finish of 4th iteration, the three previous should also finish m.wait4('sleep:3') jinfos = m.info_parsed(job_ids, withChilds=True) assert jinfos jinfo = jinfos['sleep'] assert all((jinfo.iterations, jinfo.iterations.get('start', -1) == 0, jinfo.iterations.get('stop', 0) == its, jinfo.iterations.get('total', 0) == its, jinfo.iterations.get('finished', 0) == ncores, jinfo.iterations.get('failed', -1) == 0)), str(jinfo) assert len(jinfo.childs) == its for iteration in range(its): job_it = jinfo.childs[iteration] exp_status = ['SUCCEED'] if iteration > 3: exp_status = ['EXECUTING', 'SCHEDULED', 'QUEUED'] assert all((job_it.iteration == iteration, job_it.name == '{}:{}'.format('sleep', iteration), job_it.status in exp_status)),\ f"{job_it.iteration} != {iteration}, {job_it.name} != {'{}:{}'.format('sleep', iteration)}, {job_it.status} != {exp_status}" # kill process m.kill_manager_process() m.cleanup() ncores = 4 m = LocalManager(['--log', 'debug', '--wd', tmpdir, '--report-format', 'json', '--nodes', str(ncores), '--resume', tmpdir], {'wdir': str(tmpdir)}) m.wait4all() jinfos = m.info_parsed(job_ids, withChilds=True) assert jinfos jinfo = jinfos['sleep'] assert all((jinfo.iterations, jinfo.iterations.get('start', -1) == 0, jinfo.iterations.get('stop', 0) == its, jinfo.iterations.get('total', 0) == its, jinfo.iterations.get('finished', 0) == its, jinfo.iterations.get('failed', -1) == 0)), str(jinfo) assert len(jinfo.childs) == its for iteration in range(its): job_it = jinfo.childs[iteration] assert all((job_it.iteration == iteration, job_it.name == '{}:{}'.format('sleep', iteration), job_it.status == 'SUCCEED')), \ f"{job_it.iteration} != {iteration}, {job_it.name} != {'{}:{}'.format('sleep', iteration)}, {job_it.status} != SUCCEED" finally: if m: m.finish() m.cleanup()
cmd = '%s run_mscale.py --submodel %s --data_dir=%s --instance_index %d --coupling_type %s --num_instances %d --weather_coupling %s' % ( PYTHON_CMD, SUBMODEL, DATA_DIR, INSTANCE_INDEX, COUPLING_TYPE, NUM_INSTANCES, WEATHER_COUPLING) print("\tAdd job with cmd = %s" % (cmd)) TaskID = 'TaskID%d_%s' % (INSTANCE_INDEX + 1, SUBMODEL) stderr = 'log_task/%s_${jname}__${uniq}.stderr' % (TaskID) stdout = 'log_task/%s_${jname}__${uniq}.stdout' % (TaskID) jobs.add(name=TaskID, exec='bash', args=['-c', cmd], stdout=stdout, stderr=stderr, numCores={'exact': INSTANCE_CORES}, model='default') INSTANCE_INDEX = INSTANCE_INDEX + 1 ids = m.submit(jobs) # wait until submited jobs finish m.wait4(ids) # get detailed information about submited and finished jobs print("jobs details:\n%s\n" % str(m.info(ids))) m.finish() m.kill_manager_process() m.cleanup()