isabl-cli 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- isabl_cli/VERSION +1 -0
- isabl_cli/__init__.py +25 -0
- isabl_cli/__main__.py +13 -0
- isabl_cli/api.py +815 -0
- isabl_cli/app.py +1926 -0
- isabl_cli/batch_systems/__init__.py +7 -0
- isabl_cli/batch_systems/local.py +44 -0
- isabl_cli/batch_systems/lsf.py +175 -0
- isabl_cli/batch_systems/sge.py +194 -0
- isabl_cli/batch_systems/slurm.py +180 -0
- isabl_cli/cli.py +91 -0
- isabl_cli/commands.py +480 -0
- isabl_cli/data/README.md +7 -0
- isabl_cli/data.py +1240 -0
- isabl_cli/exceptions.py +48 -0
- isabl_cli/factories.py +99 -0
- isabl_cli/options.py +407 -0
- isabl_cli/settings.py +315 -0
- isabl_cli/signals.py +23 -0
- isabl_cli/test/__init__.py +1 -0
- isabl_cli/test/utils.py +159 -0
- isabl_cli/utils.py +346 -0
- isabl_cli/validators.py +100 -0
- isabl_cli-0.1.0.dist-info/LICENSE.md +23 -0
- isabl_cli-0.1.0.dist-info/METADATA +40 -0
- isabl_cli-0.1.0.dist-info/RECORD +43 -0
- isabl_cli-0.1.0.dist-info/WHEEL +5 -0
- isabl_cli-0.1.0.dist-info/entry_points.txt +2 -0
- isabl_cli-0.1.0.dist-info/top_level.txt +2 -0
- tests/__init__.py +0 -0
- tests/conftest.py +26 -0
- tests/test_api.py +124 -0
- tests/test_app.py +1254 -0
- tests/test_batch_systems.py +87 -0
- tests/test_cli.py +34 -0
- tests/test_commands.py +341 -0
- tests/test_data.py +450 -0
- tests/test_options.py +28 -0
- tests/test_signals.py +59 -0
- tests/test_testutils.py +24 -0
- tests/test_utils.py +154 -0
- tests/test_validators.py +128 -0
- tests/test_version.py +8 -0
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import subprocess
|
|
2
|
+
import os
|
|
3
|
+
|
|
4
|
+
from click import progressbar
|
|
5
|
+
|
|
6
|
+
from isabl_cli import api
|
|
7
|
+
from isabl_cli import utils
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def submit_local(app, command_tuples):
|
|
11
|
+
"""Submit analyses locally and serially."""
|
|
12
|
+
# make sure analyses are in submitted status to avoid
|
|
13
|
+
# merging project level analyses in every success
|
|
14
|
+
ret = []
|
|
15
|
+
api.patch_analyses_status([i for i, _ in command_tuples], "SUBMITTED")
|
|
16
|
+
label = f"Running {len(command_tuples)} analyses..."
|
|
17
|
+
|
|
18
|
+
with progressbar(command_tuples, label=label) as bar:
|
|
19
|
+
for i, j in bar:
|
|
20
|
+
log = app.get_command_log_path(i)
|
|
21
|
+
err = app.get_command_err_path(i)
|
|
22
|
+
api.patch_analysis_status(i, "STARTED")
|
|
23
|
+
oldmask = os.umask(0o22)
|
|
24
|
+
status = app._get_after_completion_status(i)
|
|
25
|
+
|
|
26
|
+
with open(log, "w") as stdout, open(err, "w") as stderr:
|
|
27
|
+
try:
|
|
28
|
+
subprocess.check_call(
|
|
29
|
+
args=j,
|
|
30
|
+
cwd=i["storage_url"],
|
|
31
|
+
stdout=stdout,
|
|
32
|
+
stderr=stderr,
|
|
33
|
+
shell=True,
|
|
34
|
+
executable="/bin/bash"
|
|
35
|
+
)
|
|
36
|
+
|
|
37
|
+
except subprocess.CalledProcessError:
|
|
38
|
+
status = "FAILED"
|
|
39
|
+
|
|
40
|
+
os.umask(oldmask)
|
|
41
|
+
i = api.patch_analysis_status(i, status)
|
|
42
|
+
ret.append((i, i["status"]))
|
|
43
|
+
|
|
44
|
+
return ret
|
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
# pylint: disable=W9008,R0201
|
|
2
|
+
|
|
3
|
+
from collections import defaultdict
|
|
4
|
+
from datetime import datetime
|
|
5
|
+
from getpass import getuser
|
|
6
|
+
from os.path import abspath
|
|
7
|
+
from os.path import dirname
|
|
8
|
+
from os.path import join
|
|
9
|
+
import os
|
|
10
|
+
import random
|
|
11
|
+
import re
|
|
12
|
+
import shutil
|
|
13
|
+
import subprocess
|
|
14
|
+
|
|
15
|
+
import click
|
|
16
|
+
|
|
17
|
+
from isabl_cli import api
|
|
18
|
+
from isabl_cli import utils
|
|
19
|
+
from isabl_cli.settings import system_settings
|
|
20
|
+
from isabl_cli.settings import perform_import
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def submit_lsf(app, command_tuples): # pragma: no cover
|
|
24
|
+
"""Submit applications as arrays grouped by the target methods."""
|
|
25
|
+
groups = defaultdict(list)
|
|
26
|
+
|
|
27
|
+
# group analyses by the methods of its targets
|
|
28
|
+
for analysis, command in command_tuples:
|
|
29
|
+
targets = analysis["targets"]
|
|
30
|
+
key = tuple(sorted({i["technique"]["method"] for i in targets}))
|
|
31
|
+
groups[key].append((analysis, command))
|
|
32
|
+
|
|
33
|
+
# execute analyses on a methods basis
|
|
34
|
+
for methods, cmd_tuples in groups.items():
|
|
35
|
+
click.echo(f"Submitting {len(cmd_tuples)} ({', '.join(methods)}) jobs.")
|
|
36
|
+
commands, analyses, projects = [], [], set()
|
|
37
|
+
requirements = ""
|
|
38
|
+
|
|
39
|
+
# ignore command in tuple and use script instead
|
|
40
|
+
for i, _ in cmd_tuples:
|
|
41
|
+
analyses.append(i)
|
|
42
|
+
exit_cmd = app.get_patch_status_command(i["pk"], "FAILED")
|
|
43
|
+
commands.append((app.get_command_script_path(i), exit_cmd))
|
|
44
|
+
keys = [j["pk"] for k in i["targets"] for j in k["projects"]]
|
|
45
|
+
projects.update(keys)
|
|
46
|
+
|
|
47
|
+
# get requirements as a function of the app and target methods
|
|
48
|
+
get_requirements = system_settings.SUBMIT_CONFIGURATION.get("get_requirements")
|
|
49
|
+
|
|
50
|
+
if get_requirements:
|
|
51
|
+
name = "SUBMIT_CONFIGURATION.get_requirements"
|
|
52
|
+
get_requirements = perform_import(val=get_requirements, setting_name=name)
|
|
53
|
+
requirements = get_requirements(app, methods)
|
|
54
|
+
|
|
55
|
+
try:
|
|
56
|
+
api.patch_analyses_status(analyses, "SUBMITTED")
|
|
57
|
+
submit_configuration = system_settings.SUBMIT_CONFIGURATION
|
|
58
|
+
|
|
59
|
+
# LSF may not like arrays bigger thank 10K
|
|
60
|
+
for i in api.chunks(commands, 10000):
|
|
61
|
+
submit_lsf_array(
|
|
62
|
+
commands=i,
|
|
63
|
+
requirements=requirements or "",
|
|
64
|
+
extra_args=submit_configuration.get("extra_args", ""),
|
|
65
|
+
throttle_by=submit_configuration.get("throttle_by", 50),
|
|
66
|
+
unbuffer=submit_configuration.get("unbuffer", False),
|
|
67
|
+
jobname=(
|
|
68
|
+
f"application: {app} | "
|
|
69
|
+
f"methods: {', '.join(methods)} | "
|
|
70
|
+
f"projects: {', '.join(map(str, projects))}"
|
|
71
|
+
),
|
|
72
|
+
)
|
|
73
|
+
|
|
74
|
+
except Exception: # pylint: disable=broad-except
|
|
75
|
+
api.patch_analyses_status(analyses, "STAGED")
|
|
76
|
+
raise Exception("Error during submission...")
|
|
77
|
+
|
|
78
|
+
return [(i, "SUBMITTED") for i, _ in command_tuples]
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def submit_lsf_array(
|
|
82
|
+
commands,
|
|
83
|
+
requirements,
|
|
84
|
+
jobname,
|
|
85
|
+
extra_args=None,
|
|
86
|
+
throttle_by=50,
|
|
87
|
+
wait=False,
|
|
88
|
+
unbuffer=False,
|
|
89
|
+
): # pragma: no cover
|
|
90
|
+
"""
|
|
91
|
+
Submit an array of bash scripts.
|
|
92
|
+
|
|
93
|
+
Two other jobs will also be submitted:
|
|
94
|
+
|
|
95
|
+
EXIT: run exit command if failure.
|
|
96
|
+
CLEAN: clean temporary files and directories after completion.
|
|
97
|
+
|
|
98
|
+
Arguments:
|
|
99
|
+
commands (list): of (path to bash script, on exit command) tuples.
|
|
100
|
+
requirements (str): string of LSF requirements.
|
|
101
|
+
jobname (str): lsf array jobname.
|
|
102
|
+
extra_args (str): extra LSF args.
|
|
103
|
+
throttle_by (int): max number of jobs running at same time.
|
|
104
|
+
wait (bool): if true, wait until clean command finishes.
|
|
105
|
+
unbuffer (bool): if true, will unbuffer the stdout/stderr.
|
|
106
|
+
|
|
107
|
+
Returns:
|
|
108
|
+
str: jobid of clean up job.
|
|
109
|
+
"""
|
|
110
|
+
if not shutil.which("bsub"):
|
|
111
|
+
raise RuntimeError("LSF is not available.")
|
|
112
|
+
|
|
113
|
+
extra_args = extra_args or ""
|
|
114
|
+
assert system_settings.BASE_STORAGE_DIRECTORY
|
|
115
|
+
|
|
116
|
+
root = join(
|
|
117
|
+
system_settings.BASE_STORAGE_DIRECTORY,
|
|
118
|
+
".runs",
|
|
119
|
+
getuser(),
|
|
120
|
+
datetime.now(system_settings.TIME_ZONE).isoformat(),
|
|
121
|
+
)
|
|
122
|
+
|
|
123
|
+
wait_flag = "-K" if wait else ""
|
|
124
|
+
unbuffer = "unbuffer" if unbuffer and shutil.which("unbuffer") else ""
|
|
125
|
+
os.makedirs(root, exist_ok=True)
|
|
126
|
+
jobname += " | rundir: {}".format(root)
|
|
127
|
+
total = len(commands)
|
|
128
|
+
index = 0
|
|
129
|
+
|
|
130
|
+
with click.progressbar(commands, label="preparing submission...") as bar:
|
|
131
|
+
for command, exit_command in bar:
|
|
132
|
+
index += 1
|
|
133
|
+
rundir = abspath(dirname(command))
|
|
134
|
+
|
|
135
|
+
with open(join(root, "in.%s" % index), "w") as f:
|
|
136
|
+
# use random sleep to avoid parallel API hits
|
|
137
|
+
f.write(
|
|
138
|
+
f"sleep {random.uniform(0, 10):.3} && {unbuffer} bash {command}"
|
|
139
|
+
)
|
|
140
|
+
|
|
141
|
+
with open(join(root, "exit_cmd.%s" % index), "w") as f:
|
|
142
|
+
f.write(exit_command)
|
|
143
|
+
|
|
144
|
+
for j in "log", "err", "exit":
|
|
145
|
+
src = join(rundir, "head_job.{}".format(j))
|
|
146
|
+
dst = join(root, "{}.{}".format(j, index))
|
|
147
|
+
open(src, "w").close()
|
|
148
|
+
utils.force_symlink(src, dst)
|
|
149
|
+
|
|
150
|
+
# submit array of commands
|
|
151
|
+
cmd = (
|
|
152
|
+
f"bsub {requirements} {extra_args} "
|
|
153
|
+
f'-J "ISABL | {jobname}[1-{total}]%{throttle_by}" '
|
|
154
|
+
f'-oo "{root}/log.%I" -eo "{root}/err.%I" -i "{root}/in.%I" bash'
|
|
155
|
+
)
|
|
156
|
+
|
|
157
|
+
jobid = subprocess.check_output(cmd, shell=True).decode("utf-8")
|
|
158
|
+
jobid = re.findall("<(.*?)>", jobid)[0]
|
|
159
|
+
|
|
160
|
+
# submit array of exit commands
|
|
161
|
+
# -ti, or immediate termination, prevents orphan jobs when -w is not valid anymore
|
|
162
|
+
cmd = (
|
|
163
|
+
f'bsub -W 15 -J "EXIT | {jobname}[1-{total}]" -ti -o "{root}/exit.%I" '
|
|
164
|
+
f'-w "exit({jobid}[*])" -i "{root}/exit_cmd.%I" bash '
|
|
165
|
+
)
|
|
166
|
+
|
|
167
|
+
jobid = subprocess.check_output(cmd, shell=True).decode("utf-8")
|
|
168
|
+
jobid = re.findall("<(.*?)>", jobid)[0]
|
|
169
|
+
|
|
170
|
+
# clean the execution directory
|
|
171
|
+
cmd = (
|
|
172
|
+
f'bsub -J "CLEAN | {jobname}" -w "ended({jobid})" -ti {wait_flag} rm -r {root}'
|
|
173
|
+
)
|
|
174
|
+
jobid = subprocess.check_output(cmd, shell=True).decode("utf-8")
|
|
175
|
+
return re.findall("<(.*?)>", jobid)[0]
|
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
# pylint: disable=W9008,R0201
|
|
2
|
+
|
|
3
|
+
from collections import defaultdict
|
|
4
|
+
from datetime import datetime
|
|
5
|
+
from getpass import getuser
|
|
6
|
+
from os.path import abspath
|
|
7
|
+
from os.path import dirname
|
|
8
|
+
from os.path import join
|
|
9
|
+
import os
|
|
10
|
+
import random
|
|
11
|
+
import shutil
|
|
12
|
+
import subprocess
|
|
13
|
+
|
|
14
|
+
from slugify import slugify
|
|
15
|
+
import click
|
|
16
|
+
|
|
17
|
+
from isabl_cli import api
|
|
18
|
+
from isabl_cli import utils
|
|
19
|
+
from isabl_cli.settings import system_settings
|
|
20
|
+
from isabl_cli.settings import perform_import
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
# catch kill signal using -notify in qsub
|
|
24
|
+
COMMAND = """
|
|
25
|
+
#!/bin/sh
|
|
26
|
+
|
|
27
|
+
sigusr2()
|
|
28
|
+
{{
|
|
29
|
+
echo kill signal catched
|
|
30
|
+
({exit_command}) &> {exit_log}
|
|
31
|
+
}}
|
|
32
|
+
|
|
33
|
+
# catch -USR2 signal
|
|
34
|
+
trap sigusr2 USR2
|
|
35
|
+
trap sigusr2 USR1
|
|
36
|
+
|
|
37
|
+
# run the command
|
|
38
|
+
{command}
|
|
39
|
+
|
|
40
|
+
# reset to be elegant
|
|
41
|
+
trap - USR2
|
|
42
|
+
trap - USR1
|
|
43
|
+
"""
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def submit_sge(app, command_tuples): # pragma: no cover
|
|
47
|
+
"""Submit applications as arrays grouped by the target methods."""
|
|
48
|
+
groups = defaultdict(list)
|
|
49
|
+
|
|
50
|
+
# group analyses by the methods of its targets
|
|
51
|
+
for analysis, command in command_tuples:
|
|
52
|
+
targets = analysis["targets"]
|
|
53
|
+
key = tuple(sorted({i["technique"]["method"] for i in targets}))
|
|
54
|
+
groups[key].append((analysis, command))
|
|
55
|
+
|
|
56
|
+
# execute analyses on a methods basis
|
|
57
|
+
for methods, cmd_tuples in groups.items():
|
|
58
|
+
click.echo(f"Submitting {len(cmd_tuples)} ({', '.join(methods)}) jobs.")
|
|
59
|
+
commands, analyses, projects = [], [], set()
|
|
60
|
+
requirements = ""
|
|
61
|
+
|
|
62
|
+
# ignore command in tuple and use script instead
|
|
63
|
+
for i, _ in cmd_tuples:
|
|
64
|
+
analyses.append(i)
|
|
65
|
+
exit_cmd = app.get_patch_status_command(i["pk"], "FAILED")
|
|
66
|
+
commands.append((app.get_command_script_path(i), exit_cmd))
|
|
67
|
+
keys = [j["pk"] for k in i["targets"] for j in k["projects"]]
|
|
68
|
+
projects.update(keys)
|
|
69
|
+
|
|
70
|
+
# get requirements as a function of the app and target methods
|
|
71
|
+
get_requirements = system_settings.SUBMIT_CONFIGURATION.get("get_requirements")
|
|
72
|
+
|
|
73
|
+
if get_requirements:
|
|
74
|
+
name = "SUBMIT_CONFIGURATION.get_requirements"
|
|
75
|
+
get_requirements = perform_import(val=get_requirements, setting_name=name)
|
|
76
|
+
requirements = get_requirements(app, methods)
|
|
77
|
+
|
|
78
|
+
try:
|
|
79
|
+
api.patch_analyses_status(analyses, "SUBMITTED")
|
|
80
|
+
submit_configuration = system_settings.SUBMIT_CONFIGURATION
|
|
81
|
+
for i in api.chunks(commands, 10000):
|
|
82
|
+
submit_sge_array(
|
|
83
|
+
commands=i,
|
|
84
|
+
requirements=requirements or "",
|
|
85
|
+
extra_args=submit_configuration.get("extra_args", ""),
|
|
86
|
+
throttle_by=submit_configuration.get("throttle_by", 50),
|
|
87
|
+
unbuffer=submit_configuration.get("unbuffer", False),
|
|
88
|
+
jobname=(
|
|
89
|
+
f"application: {app} | "
|
|
90
|
+
f"methods: {', '.join(methods)} | "
|
|
91
|
+
f"projects: {', '.join(map(str, projects))}"
|
|
92
|
+
),
|
|
93
|
+
)
|
|
94
|
+
|
|
95
|
+
except Exception: # pylint: disable=broad-except
|
|
96
|
+
api.patch_analyses_status(analyses, "STAGED")
|
|
97
|
+
raise Exception("Error during submission...")
|
|
98
|
+
|
|
99
|
+
return [(i, "SUBMITTED") for i, _ in command_tuples]
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def submit_sge_array(
|
|
103
|
+
commands,
|
|
104
|
+
requirements,
|
|
105
|
+
jobname,
|
|
106
|
+
extra_args=None,
|
|
107
|
+
throttle_by=50,
|
|
108
|
+
wait=False,
|
|
109
|
+
unbuffer=False,
|
|
110
|
+
): # pragma: no cover
|
|
111
|
+
"""
|
|
112
|
+
Submit an array of bash scripts.
|
|
113
|
+
|
|
114
|
+
Two other jobs will also be submitted:
|
|
115
|
+
|
|
116
|
+
EXIT: run exit command if failure.
|
|
117
|
+
CLEAN: clean temporary files and directories after completion.
|
|
118
|
+
|
|
119
|
+
Arguments:
|
|
120
|
+
commands (list): of (path to bash script, on exit command) tuples.
|
|
121
|
+
requirements (str): string of LSF requirements.
|
|
122
|
+
jobname (str): sge array jobname.
|
|
123
|
+
extra_args (str): extra LSF args.
|
|
124
|
+
throttle_by (int): max number of jobs running at same time.
|
|
125
|
+
wait (bool): if true, wait until clean command finishes.
|
|
126
|
+
unbuffer (bool): if true, will unbuffer the stdout/stderr.
|
|
127
|
+
|
|
128
|
+
Returns:
|
|
129
|
+
str: jobid of clean up job.
|
|
130
|
+
"""
|
|
131
|
+
extra_args = extra_args or ""
|
|
132
|
+
assert system_settings.BASE_STORAGE_DIRECTORY
|
|
133
|
+
|
|
134
|
+
root = join(
|
|
135
|
+
system_settings.BASE_STORAGE_DIRECTORY,
|
|
136
|
+
".runs",
|
|
137
|
+
getuser(),
|
|
138
|
+
datetime.now(system_settings.TIME_ZONE).isoformat(),
|
|
139
|
+
)
|
|
140
|
+
|
|
141
|
+
wait_flag = "-sync y" if wait else ""
|
|
142
|
+
unbuffer = "unbuffer" if unbuffer and shutil.which("unbuffer") else ""
|
|
143
|
+
os.makedirs(root, exist_ok=True)
|
|
144
|
+
jobname += "-rundir: {}".format(root)
|
|
145
|
+
jobname = slugify(jobname)
|
|
146
|
+
total = len(commands)
|
|
147
|
+
index = 0
|
|
148
|
+
base_args = f"-V -b n -terse -wd {root}"
|
|
149
|
+
|
|
150
|
+
with click.progressbar(commands, label="preparing submission...") as bar:
|
|
151
|
+
for command, exit_command in bar:
|
|
152
|
+
index += 1
|
|
153
|
+
rundir = abspath(dirname(command))
|
|
154
|
+
|
|
155
|
+
with open(join(root, "in.%s" % index), "w") as f:
|
|
156
|
+
# use random sleep to avoid parallel API hits
|
|
157
|
+
sge_command = (
|
|
158
|
+
f"sleep {random.uniform(0, 10):.3} && {unbuffer} bash {command}"
|
|
159
|
+
)
|
|
160
|
+
f.write(
|
|
161
|
+
COMMAND.format(
|
|
162
|
+
exit_command=exit_command,
|
|
163
|
+
exit_log=join(rundir, "head_job.exit"),
|
|
164
|
+
command=sge_command,
|
|
165
|
+
)
|
|
166
|
+
)
|
|
167
|
+
|
|
168
|
+
for j in "log", "err", "exit":
|
|
169
|
+
src = join(rundir, f"head_job.{j}")
|
|
170
|
+
dst = join(root, f"{j}.{index}")
|
|
171
|
+
open(src, "w").close()
|
|
172
|
+
utils.force_symlink(src, dst)
|
|
173
|
+
|
|
174
|
+
with open(join(root, "in.sh"), "w") as f:
|
|
175
|
+
f.write("bash in.${SGE_TASK_ID}")
|
|
176
|
+
|
|
177
|
+
with open(join(root, "clean.sh"), "w") as f:
|
|
178
|
+
f.write(f"rm -rf {root}")
|
|
179
|
+
|
|
180
|
+
cmd = (
|
|
181
|
+
f"qsub {base_args} {requirements} {extra_args} -t 1-{total} "
|
|
182
|
+
f'-N "ISABL-{jobname}" -notify -tc {throttle_by} '
|
|
183
|
+
f"-o 'log.$TASK_ID' -e 'err.$TASK_ID' {root}/in.sh"
|
|
184
|
+
)
|
|
185
|
+
|
|
186
|
+
jobid = subprocess.check_output(cmd, shell=True).decode("utf-8")
|
|
187
|
+
jobid = jobid.strip().split(".")[0]
|
|
188
|
+
|
|
189
|
+
cmd = (
|
|
190
|
+
f'qsub {base_args} -N "CLEAN-{jobname}" -hold_jid {jobid} {wait_flag} '
|
|
191
|
+
f"-o /dev/null -e /dev/null {root}/clean.sh"
|
|
192
|
+
)
|
|
193
|
+
|
|
194
|
+
return subprocess.check_output(cmd, shell=True).decode("utf-8").strip()
|
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
# pylint: disable=W9008,R0201
|
|
2
|
+
|
|
3
|
+
from collections import defaultdict
|
|
4
|
+
from datetime import datetime
|
|
5
|
+
from getpass import getuser
|
|
6
|
+
from os.path import abspath
|
|
7
|
+
from os.path import dirname
|
|
8
|
+
from os.path import join
|
|
9
|
+
import os
|
|
10
|
+
import random
|
|
11
|
+
import shutil
|
|
12
|
+
import subprocess
|
|
13
|
+
|
|
14
|
+
from slugify import slugify
|
|
15
|
+
import click
|
|
16
|
+
|
|
17
|
+
from isabl_cli import api
|
|
18
|
+
from isabl_cli import utils
|
|
19
|
+
from isabl_cli.settings import system_settings
|
|
20
|
+
from isabl_cli.settings import perform_import
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def submit_slurm(app, command_tuples): # pragma: no cover
|
|
24
|
+
"""Submit applications as arrays grouped by the target methods."""
|
|
25
|
+
groups = defaultdict(list)
|
|
26
|
+
|
|
27
|
+
# group analyses by the methods of its targets
|
|
28
|
+
for analysis, command in command_tuples:
|
|
29
|
+
targets = analysis["targets"]
|
|
30
|
+
key = tuple(sorted({i["technique"]["method"] for i in targets}))
|
|
31
|
+
groups[key].append((analysis, command))
|
|
32
|
+
|
|
33
|
+
# execute analyses on a methods basis
|
|
34
|
+
for methods, cmd_tuples in groups.items():
|
|
35
|
+
click.echo(f"Submitting {len(cmd_tuples)} ({', '.join(methods)}) jobs.")
|
|
36
|
+
commands, analyses, projects = [], [], set()
|
|
37
|
+
requirements = ""
|
|
38
|
+
|
|
39
|
+
# ignore command in tuple and use script instead
|
|
40
|
+
for i, _ in cmd_tuples:
|
|
41
|
+
analyses.append(i)
|
|
42
|
+
exit_cmd = app.get_patch_status_command(i["pk"], "FAILED")
|
|
43
|
+
commands.append((app.get_command_script_path(i), exit_cmd))
|
|
44
|
+
keys = [j["pk"] for k in i["targets"] for j in k["projects"]]
|
|
45
|
+
projects.update(keys)
|
|
46
|
+
|
|
47
|
+
# get requirements as a function of the app and target methods
|
|
48
|
+
get_requirements = system_settings.SUBMIT_CONFIGURATION.get("get_requirements")
|
|
49
|
+
|
|
50
|
+
if get_requirements:
|
|
51
|
+
name = "SUBMIT_CONFIGURATION.get_requirements"
|
|
52
|
+
get_requirements = perform_import(val=get_requirements, setting_name=name)
|
|
53
|
+
requirements = get_requirements(app, methods)
|
|
54
|
+
|
|
55
|
+
try:
|
|
56
|
+
api.patch_analyses_status(analyses, "SUBMITTED")
|
|
57
|
+
submit_configuration = system_settings.SUBMIT_CONFIGURATION
|
|
58
|
+
for i in api.chunks(commands, 10000):
|
|
59
|
+
submit_slurm_array(
|
|
60
|
+
commands=i,
|
|
61
|
+
requirements=requirements or "",
|
|
62
|
+
extra_args=submit_configuration.get("extra_args", ""),
|
|
63
|
+
throttle_by=submit_configuration.get("throttle_by", 50),
|
|
64
|
+
unbuffer=submit_configuration.get("unbuffer", False),
|
|
65
|
+
jobname=(
|
|
66
|
+
f"application: {app} | "
|
|
67
|
+
f"methods: {', '.join(methods)} | "
|
|
68
|
+
f"projects: {', '.join(map(str, projects))}"
|
|
69
|
+
),
|
|
70
|
+
)
|
|
71
|
+
|
|
72
|
+
except Exception: # pylint: disable=broad-except
|
|
73
|
+
api.patch_analyses_status(analyses, "STAGED")
|
|
74
|
+
raise Exception("Error during submission...")
|
|
75
|
+
|
|
76
|
+
return [(i, "SUBMITTED") for i, _ in command_tuples]
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def submit_slurm_array(
|
|
80
|
+
commands,
|
|
81
|
+
requirements,
|
|
82
|
+
jobname,
|
|
83
|
+
extra_args=None,
|
|
84
|
+
throttle_by=50,
|
|
85
|
+
wait=False,
|
|
86
|
+
unbuffer=False,
|
|
87
|
+
): # pragma: no cover
|
|
88
|
+
"""
|
|
89
|
+
Submit an array of bash scripts.
|
|
90
|
+
|
|
91
|
+
Three other jobs will also be submitted:
|
|
92
|
+
|
|
93
|
+
EXIT: run exit command if failure.
|
|
94
|
+
SEFF: run slurm utility to printout job metrics.
|
|
95
|
+
CLEAN: clean temporary files and directories after completion.
|
|
96
|
+
|
|
97
|
+
Arguments:
|
|
98
|
+
commands (list): of (path to bash script, on exit command) tuples.
|
|
99
|
+
requirements (str): string of SLURM requirements.
|
|
100
|
+
jobname (str): slurm array jobname.
|
|
101
|
+
extra_args (str): extra SLURM args.
|
|
102
|
+
throttle_by (int): max number of jobs running at same time.
|
|
103
|
+
wait (bool): if true, wait until clean command finishes.
|
|
104
|
+
unbuffer (bool): if true, will unbuffer the stdout/stderr.
|
|
105
|
+
|
|
106
|
+
Returns:
|
|
107
|
+
str: jobid of clean up job.
|
|
108
|
+
"""
|
|
109
|
+
if not shutil.which("sbatch"):
|
|
110
|
+
raise RuntimeError("Slurm is not available.")
|
|
111
|
+
|
|
112
|
+
extra_args = extra_args or ""
|
|
113
|
+
assert system_settings.BASE_STORAGE_DIRECTORY
|
|
114
|
+
|
|
115
|
+
root = join(
|
|
116
|
+
system_settings.BASE_STORAGE_DIRECTORY,
|
|
117
|
+
".runs",
|
|
118
|
+
getuser(),
|
|
119
|
+
datetime.now(system_settings.TIME_ZONE).isoformat(),
|
|
120
|
+
)
|
|
121
|
+
|
|
122
|
+
wait_flag = "-W" if wait else ""
|
|
123
|
+
unbuffer = "unbuffer" if unbuffer and shutil.which("unbuffer") else ""
|
|
124
|
+
os.makedirs(root, exist_ok=True)
|
|
125
|
+
jobname += "-rundir: {}".format(root)
|
|
126
|
+
jobname = slugify(jobname)
|
|
127
|
+
total = len(commands)
|
|
128
|
+
index = 0
|
|
129
|
+
|
|
130
|
+
with click.progressbar(commands, label="preparing submission...") as bar:
|
|
131
|
+
for command, exit_command in bar:
|
|
132
|
+
index += 1
|
|
133
|
+
rundir = abspath(dirname(command))
|
|
134
|
+
|
|
135
|
+
with open(join(root, f"in.{index}"), "w") as f:
|
|
136
|
+
# submit a dependency job on failure
|
|
137
|
+
# important when the scheduler kills the head job
|
|
138
|
+
dependency = "${SLURM_ARRAY_JOB_ID}_${SLURM_ARRAY_TASK_ID}"
|
|
139
|
+
after_not_ok_job = (
|
|
140
|
+
f"sbatch {extra_args} --depend=afternotok:{dependency} --kill-on-invalid-dep=yes "
|
|
141
|
+
f'--export=ALL -o {join(rundir, "head_job.exit")} -J "EXIT: {jobname}" '
|
|
142
|
+
f"<< EOF\n#!/bin/bash\n{exit_command}\nEOF\n"
|
|
143
|
+
)
|
|
144
|
+
|
|
145
|
+
# use random sleep to avoid parallel API hits
|
|
146
|
+
f.write(
|
|
147
|
+
f"#!/bin/bash\n\n"
|
|
148
|
+
f"sleep {random.uniform(0, 10):.3f} && "
|
|
149
|
+
f"echo {dependency} >> {command.replace('head_job.sh', 'job_ids.txt')} && "
|
|
150
|
+
f"({after_not_ok_job}) && {unbuffer} bash {command}"
|
|
151
|
+
)
|
|
152
|
+
|
|
153
|
+
for j in {"log", "err", "exit"}:
|
|
154
|
+
src = join(rundir, f"head_job.{j}")
|
|
155
|
+
dst = join(root, f"{j}.{index}")
|
|
156
|
+
open(src, "w").close()
|
|
157
|
+
utils.force_symlink(src, dst)
|
|
158
|
+
|
|
159
|
+
with open(join(root, "in.sh"), "w") as f:
|
|
160
|
+
f.write(f"#!/bin/bash\nbash {root}/in.$SLURM_ARRAY_TASK_ID")
|
|
161
|
+
|
|
162
|
+
# Main job array
|
|
163
|
+
cmd = (
|
|
164
|
+
f"sbatch {extra_args} {requirements} --array 1-{total}%{throttle_by} "
|
|
165
|
+
f"-o '{root}/log.%a' -e '{root}/err.%a' "
|
|
166
|
+
f'-J "ISABL: {jobname}" --parsable {root}/in.sh'
|
|
167
|
+
)
|
|
168
|
+
jobid = subprocess.check_output(cmd, shell=True).decode("utf-8").strip()
|
|
169
|
+
|
|
170
|
+
# Job to clean job array rundir
|
|
171
|
+
with open(join(root, "clean.sh"), "w") as f:
|
|
172
|
+
f.write(f"#!/bin/bash\nrm -rf {root}")
|
|
173
|
+
|
|
174
|
+
cmd = (
|
|
175
|
+
f"sbatch {extra_args} -J 'CLEAN: {jobname}' {wait_flag} "
|
|
176
|
+
f"--kill-on-invalid-dep yes -o /dev/null -e /dev/null "
|
|
177
|
+
f"--depend=afterany:{jobid} --parsable {root}/clean.sh"
|
|
178
|
+
)
|
|
179
|
+
|
|
180
|
+
return subprocess.check_output(cmd, shell=True).decode("utf-8").strip()
|
isabl_cli/cli.py
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Module that contains the command line app.
|
|
3
|
+
|
|
4
|
+
Why does this file exist, and why not put this in __main__?
|
|
5
|
+
You might be tempted to import things from __main__ later, but that will
|
|
6
|
+
cause problems, the code will get executed twice:
|
|
7
|
+
|
|
8
|
+
- When you run `python -m isabl_cli` python will execute
|
|
9
|
+
`__main__.py` as a script. That means there won't be any
|
|
10
|
+
`isabl_cli.__main__` in `sys.modules`.
|
|
11
|
+
|
|
12
|
+
- When you import __main__ it will get executed again (as a module) because
|
|
13
|
+
there's no `isabl_cli.__main__` in `sys.modules`.
|
|
14
|
+
|
|
15
|
+
Also see (1) from http://click.pocoo.org/5/setuptools/#setuptools-integration
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
from collections import defaultdict
|
|
19
|
+
import time
|
|
20
|
+
|
|
21
|
+
from slugify import slugify
|
|
22
|
+
import click
|
|
23
|
+
|
|
24
|
+
from isabl_cli import __version__
|
|
25
|
+
from isabl_cli import exceptions
|
|
26
|
+
from isabl_cli.settings import system_settings
|
|
27
|
+
from isabl_cli.utils import send_analytics
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
@click.group()
|
|
31
|
+
@click.version_option(version=__version__)
|
|
32
|
+
def main(): # pragma: no cover
|
|
33
|
+
"""Run Isabl command line tools."""
|
|
34
|
+
pass
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def add_apps_groups(apps):
|
|
38
|
+
"""Group apps by assembly."""
|
|
39
|
+
apps_dict = defaultdict(dict)
|
|
40
|
+
|
|
41
|
+
for i in apps: # pylint: disable=W0621
|
|
42
|
+
start_time = time.time()
|
|
43
|
+
|
|
44
|
+
try:
|
|
45
|
+
command = i.as_cli_command()
|
|
46
|
+
apps_dict[i.ASSEMBLY][command.name] = command
|
|
47
|
+
except (exceptions.ConfigurationError, AttributeError) as error:
|
|
48
|
+
click.secho(f"Invalid configuration, failed to register {i}: {error}", err=True, fg="red")
|
|
49
|
+
|
|
50
|
+
if (time.time() - start_time) > 0.1: # pragma: no cover
|
|
51
|
+
click.secho(f"{i.__name__} is loading slowly...", err=True, fg="yellow")
|
|
52
|
+
|
|
53
|
+
for i, j in apps_dict.items():
|
|
54
|
+
name = f"apps-{slugify(i)}" if i else "apps"
|
|
55
|
+
help_text = f"{i} applications." if i else "data processing applications."
|
|
56
|
+
main.add_command(click.Group(name=name, commands=j, help=help_text))
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
for i in system_settings.SYSTEM_COMMANDS:
|
|
60
|
+
# Add analytics to every system command
|
|
61
|
+
i.callback = send_analytics(i.callback)
|
|
62
|
+
|
|
63
|
+
main.add_command(i)
|
|
64
|
+
|
|
65
|
+
for i in system_settings.CUSTOM_COMMANDS: # pragma: no cover
|
|
66
|
+
main.add_command(i)
|
|
67
|
+
|
|
68
|
+
try:
|
|
69
|
+
add_apps_groups(system_settings.INSTALLED_APPLICATIONS)
|
|
70
|
+
except ImportError as error:
|
|
71
|
+
click.secho(f"Failed to import applications: {error}", err=True, fg="red")
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
if system_settings.is_admin_user:
|
|
75
|
+
for i in system_settings.ADMIN_COMMANDS:
|
|
76
|
+
main.add_command(i)
|
|
77
|
+
|
|
78
|
+
if system_settings.REFERENCE_DATA_IMPORTER:
|
|
79
|
+
main.add_command(system_settings.REFERENCE_DATA_IMPORTER.as_cli_command())
|
|
80
|
+
|
|
81
|
+
if system_settings.REFERENCE_GENOME_IMPORTER:
|
|
82
|
+
main.add_command(system_settings.REFERENCE_GENOME_IMPORTER.as_cli_command())
|
|
83
|
+
|
|
84
|
+
if system_settings.DATA_IMPORTER:
|
|
85
|
+
main.add_command(system_settings.DATA_IMPORTER.as_cli_command())
|
|
86
|
+
|
|
87
|
+
if system_settings.BED_IMPORTER:
|
|
88
|
+
main.add_command(system_settings.BED_IMPORTER.as_cli_command())
|
|
89
|
+
|
|
90
|
+
if system_settings.YAML_DATA_IMPORTER:
|
|
91
|
+
main.add_command(system_settings.YAML_DATA_IMPORTER.as_cli_command())
|