-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathjob_submitter.py
412 lines (304 loc) · 12.7 KB
/
job_submitter.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
"""
Job Submitter
-------------
The ``job_submitter`` allows to execute a parametric study using a script mask and a `dictionary` of parameters to replace in this mask, from the command line.
These parameters must be present in the given mask in the ``%(PARAMETER)s`` format (other types apart from string are also allowed).
The type of script and executable is freely choosable, but defaults to ``madx``, for which this submitter was originally written.
When submitting to ``HTCondor``, data to be transferred back to the working directory must be written in a sub-folder defined by ``job_output_directory`` which defaults to **Outputdata**.
This script also allows to check if all ``HTCondor`` jobs finished successfully, for resubmissions with a different parameter grid, and for local execution.
A **Jobs.tfs** file is created in the working directory containing the Job Id, parameter per job
and job directory for further post processing.
For additional information and guides, see the `Job Submitter page
<https://pylhc.github.io/packages/pylhcsubmitter/job_submitter.html>`_ in the ``OMC`` documentation site.
*--Required--*
- **mask** *(PathOrStr)*:
Program mask to use
- **replace_dict** *(DictAsString)*:
Dict containing the str to replace as keys and values a list of
parameters to replace
- **working_directory** *(PathOrStr)*:
Directory where data should be put
*--Optional--*
- **append_jobs**:
Flag to rerun job with finer/wider grid, already existing points will
not be reexecuted.
action: ``store_true``
- **check_files** *(str)*:
List of files/file-name-masks expected to be in the 'job_output_dir'
after a successful job (for appending/resuming). Uses the 'glob'
function, so unix-wildcards (*) are allowed. If not given, only the
presence of the folder itself is checked.
- **dryrun**:
Flag to only prepare folders and scripts, but does not start/submit
jobs. Together with `resume_jobs` this can be use to check which jobs
succeeded and which failed.
action: ``store_true``
- **executable** *(PathOrStr)*:
Path to executable or job-type (of ['madx', 'python3', 'python2']) to
use.
default: ``madx``
- **htc_arguments** *(DictAsString)*:
Additional arguments for htcondor, as Dict-String. For AccountingGroup
please use 'accounting_group'. 'max_retries' and 'notification' have
defaults (if not given). Others are just passed on.
default: ``{}``
- **job_output_dir** *(str)*:
The name of the output dir of the job. (Make sure your script puts its
data there!)
default: ``Outputdata``
- **jobflavour** *(str)*:
Jobflavour to give rough estimate of runtime of one job
choices: ``('espresso', 'microcentury', 'longlunch', 'workday', 'tomorrow', 'testmatch', 'nextweek')``
default: ``workday``
- **jobid_mask** *(str)*:
Mask to name jobs from replace_dict
- **num_processes** *(int)*:
Number of processes to be used if run locally
default: ``4``
- **output_destination** *(PathOrStr)*:
Directory to copy the output of the jobs to, sorted into folders per job.
Can be on EOS, preferrably via EOS-URI format ('root://eosuser.cern.ch//eos/...').
- **resume_jobs**:
Only do jobs that did not work.
action: ``store_true``
- **run_local**:
Flag to run the jobs on the local machine. Not suggested.
action: ``store_true``
- **script_arguments** *(DictAsString)*:
Additional arguments to pass to the script, as dict in key-value pairs
('--' need to be included in the keys).
default: ``{}``
- **script_extension** *(str)*:
New extension for the scripts created from the masks. This is inferred
automatically for ['madx', 'python3', 'python2']. Otherwise not
changed.
- **ssh** *(str)*:
Run htcondor from this machine via ssh (needs access to the
`working_directory`)
"""
import logging
import sys
from dataclasses import fields
from pathlib import Path
from generic_parser import EntryPointParameters, entrypoint
from generic_parser.entry_datatypes import DictAsString
from generic_parser.tools import print_dict_tree
from pylhc_submitter.constants.htcondor import JOBFLAVOURS
from pylhc_submitter.constants.job_submitter import EXECUTEABLEPATH, SCRIPT_EXTENSIONS
from pylhc_submitter.submitter.iotools import CreationOpts, create_jobs, is_eos_uri, print_stats
from pylhc_submitter.submitter.mask import (check_percentage_signs_in_mask,
find_named_variables_in_mask, is_mask_file)
from pylhc_submitter.submitter.runners import RunnerOpts, run_jobs
from pylhc_submitter.utils.iotools import (PathOrStr, keys_to_path, make_replace_entries_iterable,
save_config)
from pylhc_submitter.utils.logging_tools import log_setup
LOG = logging.getLogger(__name__)
try:
import htcondor
except ImportError:
platform = "macOS" if sys.platform == "darwin" else "windows"
LOG.warning(
f"htcondor python bindings are linux-only. You can still use job_submitter on {platform}, "
"but only for local runs."
)
htcondor = None
def get_params():
params = EntryPointParameters()
params.add_parameter(
name="mask",
type=PathOrStr,
required=True,
help="Program mask to use",
)
params.add_parameter(
name="working_directory",
type=PathOrStr,
required=True,
help="Directory where data should be put",
)
params.add_parameter(
name="executable",
default="madx",
type=PathOrStr,
help=(
"Path to executable or job-type " f"(of {str(list(EXECUTEABLEPATH.keys()))}) to use."
),
)
params.add_parameter(
name="jobflavour",
type=str,
choices=JOBFLAVOURS,
default="workday",
help="Jobflavour to give rough estimate of runtime of one job ",
)
params.add_parameter(
name="run_local",
action="store_true",
help="Flag to run the jobs on the local machine. Not suggested.",
)
params.add_parameter(
name="resume_jobs",
action="store_true",
help="Only do jobs that did not work.",
)
params.add_parameter(
name="append_jobs",
action="store_true",
help=(
"Flag to rerun job with finer/wider grid, already existing points will not be "
"reexecuted."
),
)
params.add_parameter(
name="dryrun",
action="store_true",
help=(
"Flag to only prepare folders and scripts, but does not start/submit jobs. "
"Together with `resume_jobs` this can be use to check which jobs "
"succeeded and which failed."
),
)
params.add_parameter(
name="replace_dict",
help=(
"Dict containing the str to replace as keys and values a list of parameters to "
"replace"
),
type=DictAsString,
required=True,
)
params.add_parameter(
name="script_arguments",
help=(
"Additional arguments to pass to the script, as dict in key-value pairs "
"('--' need to be included in the keys)."
),
type=DictAsString,
default={},
)
params.add_parameter(
name="script_extension",
help=(
"New extension for the scripts created from the masks. This is inferred "
f"automatically for {str(list(SCRIPT_EXTENSIONS.keys()))}. Otherwise not changed."
),
type=str,
)
params.add_parameter(
name="num_processes",
help="Number of processes to be used if run locally",
type=int,
default=4,
)
params.add_parameter(
name="check_files",
help=(
"List of files/file-name-masks expected to be in the "
"'job_output_dir' after a successful job "
"(for appending/resuming). Uses the 'glob' function, so "
"unix-wildcards (*) are allowed. If not given, only the "
"presence of the folder itself is checked."
),
type=str,
nargs="+",
)
params.add_parameter(
name="jobid_mask",
help="Mask to name jobs from replace_dict",
type=str,
)
params.add_parameter(
name="job_output_dir",
help="The name of the output dir of the job. (Make sure your script puts its data there!)",
type=str,
default="Outputdata",
)
params.add_parameter(
name="output_destination",
help="Directory to copy the output of the jobs to, sorted into folders per job. "
"Can be on EOS, preferrably via EOS-URI format ('root://eosuser.cern.ch//eos/...').",
type=PathOrStr,
)
params.add_parameter(
name="htc_arguments",
help=(
"Additional arguments for htcondor, as Dict-String. "
"For AccountingGroup please use 'accounting_group'. "
"'max_retries' and 'notification' have defaults (if not given). "
"Others are just passed on. "
),
type=DictAsString,
default={},
)
params.add_parameter(
name="ssh",
help="Run htcondor from this machine via ssh (needs access to the `working_directory`)",
type=str,
)
return params
@entrypoint(get_params(), strict=True)
def main(opt):
if not opt.run_local:
LOG.info("Starting HTCondor Job-submitter.")
_check_htcondor_presence()
else:
LOG.info("Starting Job-submitter.")
save_config(Path(opt.working_directory), opt, "job_submitter")
creation_opt, runner_opt = check_opts(opt)
job_df, dropped_jobs = create_jobs(creation_opt)
run_jobs(job_df, runner_opt)
print_stats(job_df.index, dropped_jobs)
def check_opts(opt):
""" Checks options and sorts them into job-creation and running parameters. """
LOG.debug("Checking options.")
if opt.resume_jobs and opt.append_jobs:
raise ValueError("Select either Resume jobs or Append jobs")
# Paths ---
opt = keys_to_path(opt, "working_directory", "executable")
if str(opt.executable) in EXECUTEABLEPATH.keys():
opt.executable = str(opt.executable)
if is_mask_file(opt.mask):
mask_content = Path(opt.mask).read_text() # checks that mask and dir are there
opt.mask = Path(opt.mask)
else:
mask_content = opt.mask
if is_eos_uri(opt.output_destination) and not ("://" in opt.output_destination and "//eos/" in opt.output_destination):
raise ValueError(
"The 'output_destination' is an EOS-URI but missing '://' or '//eos' (double slashes?). "
)
# Replace dict ---
dict_keys = set(opt.replace_dict.keys())
mask_keys = find_named_variables_in_mask(mask_content)
not_in_mask = dict_keys - mask_keys
not_in_dict = mask_keys - dict_keys
if len(not_in_dict):
raise KeyError(
"The following keys in the mask were not found in the given replace_dict: "
f"{str(not_in_dict).strip('{}')}"
)
if len(not_in_mask):
LOG.warning(
"The following replace_dict keys were not found in the given mask: "
f"{str(not_in_mask).strip('{}')}"
)
# remove all keys which are not present in mask (otherwise unnecessary jobs)
[opt.replace_dict.pop(key) for key in not_in_mask]
if len(opt.replace_dict) == 0:
raise KeyError("Empty replace-dictionary")
check_percentage_signs_in_mask(mask_content)
print_dict_tree(opt, name="Input parameter", print_fun=LOG.debug)
opt.replace_dict = make_replace_entries_iterable(opt.replace_dict)
# Create new classes
opt.output_dir = opt.job_output_dir # renaming
creation = CreationOpts(**{f.name: opt[f.name] for f in fields(CreationOpts)})
runner = RunnerOpts(**{f.name: opt[f.name] for f in fields(RunnerOpts)})
runner.output_dir = '""' if opt.output_destination else opt.output_dir # empty string stops htc transfer of files
return creation, runner
def _check_htcondor_presence() -> None:
""" Raises an error if htcondor is not installed. """
if htcondor is None:
raise EnvironmentError("htcondor bindings are necessary to run this module.")
# Script Mode ------------------------------------------------------------------
if __name__ == "__main__":
log_setup()
main()