-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathmartian.py
More file actions
366 lines (286 loc) · 10.1 KB
/
martian.py
File metadata and controls
366 lines (286 loc) · 10.1 KB
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
#!/usr/bin/env python3
#
# Copyright (c) 2014 10X Genomics, Inc. All rights reserved.
#
"""Martian stage code API and common utility methods.
This module contains an API for python stage code to use to interact
with the higher-level martian logic, plus common utility methods.
"""
from __future__ import absolute_import, division, print_function
import json
import math
import os
import resource
import subprocess
import sys
from pathlib import PurePath
from typing import ( # pylint: disable=import-error, unused-import
Any,
Dict,
NoReturn,
Union,
)
# Singleton instance object.
if not "_INSTANCE" in globals():
_INSTANCE = None
class StageException(Exception):
"""Base exception type for stage code."""
class Record:
"""An object with a set of attributes generated from a dictioanry."""
def __init__(self, f_dict):
# type: (Dict[str, Any]) -> None
"""Initializes the object from a dictionary."""
self.slots = f_dict.keys()
for field_name in self.slots:
setattr(self, field_name, f_dict[field_name])
def items(self):
"""Returns the a dictionary with the elements which were in the keys in
dictionary used to initialize the record."""
return {
field_name: getattr(self, field_name) for field_name in self.slots
}
def __str__(self):
"""Formats the object as a string."""
return str(self.items())
def __iter__(self):
"""Iterate through the values of the object corresponding to keys in
the dictionary used to initialize the object."""
for field_name in self.slots:
yield getattr(self, field_name)
def __getitem__(self, index):
# type: (int) -> Any
"""Get the value associated with the Nth key in the source
dictionary."""
return getattr(self, self.slots[index])
def coerce_strings(self):
"""This exists only for backwards compatibility."""
def clear(outs):
# type: (Record) -> None
"""Set all of the outs to None."""
for field_name in outs.slots:
setattr(outs, field_name, None)
def json_sanitize(data):
"""Converts NaN values into None values, and decode raw bytes."""
retval = data
if isinstance(data, float):
# Handle exceptional floats.
if math.isnan(data) or data == float("+Inf") or data == float("-Inf"):
retval = None
elif isinstance(data, dict):
# Recurse on dictionaries.
retval = {}
for k in data.keys():
retval[k] = json_sanitize(data[k])
elif isinstance(data, str):
# This branch is required to prevent the __iter__ branch from
# processing strings.
pass
elif isinstance(data, bytes):
retval = data.decode("utf-8", errors="ignore")
elif isinstance(data, PurePath):
retval = str(data)
elif hasattr(data, "__iter__"):
# Recurse on lists.
retval = [json_sanitize(d) for d in data]
return retval
def json_dumps_safe(data, indent=None):
"""Returns a formatted json string of the data, with NaN values converted
to None."""
return json.dumps(json_sanitize(data), indent=indent)
def get_mem_kb():
# type: () -> int
"""Get the current max rss memory for this process and completed child
processes."""
return max(
resource.getrusage(resource.RUSAGE_SELF).ru_maxrss,
resource.getrusage(resource.RUSAGE_CHILDREN).ru_maxrss,
)
def convert_gb_to_kb(mem_gb):
# type: (float) -> float
"""Convert from gb to kb."""
return mem_gb * 1024 * 1024
def padded_print(field_name, value):
# type: (str, ...) -> str
"""Pad a string with leading spaces to be the same length as field_name."""
offset = len(field_name) - len(str(value))
if offset > 0:
return (" " * offset) + str(value)
return str(value)
def profile(func):
"""Add a function to the set of functions to be covered by the line profiler."""
assert _INSTANCE is not None
_INSTANCE.funcs.append(func)
return func
# On linux, provide a method to set PDEATHSIG on child processes.
if sys.platform.startswith("linux"):
import ctypes
import ctypes.util
from signal import SIGKILL
_LIBC = ctypes.CDLL(ctypes.util.find_library("c"))
_PR_SET_PDEATHSIG = ctypes.c_int(1) # <sys/prctl.h>
def child_preexec_set_pdeathsig():
"""When used as the preexec_fn argument for subprocess.Popen etc,
causes the subprocess to receive SIGKILL if the parent process
terminates."""
zero = ctypes.c_ulong(0)
_LIBC.prctl(
_PR_SET_PDEATHSIG, ctypes.c_ulong(SIGKILL), zero, zero, zero
)
else:
child_preexec_set_pdeathsig = None # pylint: disable=invalid-name
# pylint: disable=invalid-name,too-many-arguments,too-many-positional-arguments
def Popen(
args,
bufsize=0,
executable=None,
stdin=None,
stdout=None,
stderr=None,
preexec_fn=child_preexec_set_pdeathsig,
close_fds=False,
shell=False,
cwd=None,
env=None,
universal_newlines=False,
startupinfo=None,
creationflags=0,
):
# type: (...) -> subprocess.Popen
"""Log opening of a subprocess."""
assert _INSTANCE is not None
_INSTANCE.metadata.log("exec", " ".join(args))
# pylint: disable=bad-option-value, subprocess-popen-preexec-fn, consider-using-with
return subprocess.Popen(
args,
bufsize=bufsize,
executable=executable,
stdin=stdin,
stdout=stdout,
stderr=stderr,
preexec_fn=preexec_fn,
close_fds=close_fds,
shell=shell,
cwd=cwd,
env=env,
universal_newlines=universal_newlines,
startupinfo=startupinfo,
creationflags=creationflags,
)
def check_call(args, stdin=None, stdout=None, stderr=None, shell=False):
"""Log running a given subprocess."""
assert _INSTANCE is not None
_INSTANCE.metadata.log("exec", " ".join(args))
return subprocess.check_call(
args,
shell=shell,
stdin=stdin,
stdout=stdout,
stderr=stderr,
preexec_fn=child_preexec_set_pdeathsig,
)
def make_path(filename):
# type: (Union[str, bytes]) -> bytes
"""Get the file path for a named file."""
if isinstance(filename, str):
filename = filename.encode("utf-8")
assert _INSTANCE is not None
return os.path.join(_INSTANCE.metadata.files_path, filename)
def get_invocation_args():
# type: () -> Dict[str, Any]
"""Get the args from the invocation."""
assert _INSTANCE is not None
assert _INSTANCE.jobinfo is not None
return _INSTANCE.jobinfo.invocation["args"]
def get_invocation_call():
# type: () -> str
"""Get the call information from the invocation."""
assert _INSTANCE is not None
assert _INSTANCE.jobinfo is not None
return _INSTANCE.jobinfo.invocation["call"]
def get_martian_version():
# type: () -> str
"""Get the martian version from the jobinfo."""
assert _INSTANCE is not None
assert _INSTANCE.jobinfo is not None
return _INSTANCE.jobinfo.version["martian"]
def get_pipelines_version():
# type: () -> str
"""Get the pipelines version from the jobinfo."""
assert _INSTANCE is not None
assert _INSTANCE.jobinfo is not None
return _INSTANCE.jobinfo.version["pipelines"]
def get_threads_allocation():
# type: () -> float
"""Get the number of threads allocated to this job by the runtime."""
assert _INSTANCE is not None
assert _INSTANCE.jobinfo is not None
return _INSTANCE.jobinfo.threads
def get_memory_allocation():
# type: () -> float
"""Get the amount of memory in GB allocated to this job by the runtime."""
assert _INSTANCE is not None
assert _INSTANCE.jobinfo is not None
return _INSTANCE.jobinfo.mem_gb
def get_pipestance_uuid():
# type: () -> str
"""Get the UUID of the top-level pipeline instance.
Returns an empty string if the UUID is not available.
"""
return os.getenv("MRO_UUID") or os.getenv("MRO_FORCE_UUID") or ""
def update_progress(message):
# type: (Union[str, bytes]) -> None
"""Updates the current progress of the stage, which will be displayed to
the user (in the mrp log) next time mrp reads the file."""
assert _INSTANCE is not None
_INSTANCE.metadata.progress(message)
def log_info(message):
# type: (Union[str, bytes]) -> None
"""Log a message."""
assert _INSTANCE is not None
_INSTANCE.metadata.log("info", message)
def log_warn(message):
# type: (Union[str, bytes]) -> None
"""Log a warning."""
assert _INSTANCE is not None
_INSTANCE.metadata.log("warn", message)
def log_time(message):
# type: (Union[str, bytes]) -> None
"""Log a timestamp for an action."""
assert _INSTANCE is not None
_INSTANCE.metadata.log("time", message)
def log_json(label, obj):
# type: (Union[str, bytes], Any) -> None
"""Log an object in json format."""
assert _INSTANCE is not None
_INSTANCE.metadata.log(
"json", json_dumps_safe({"label": label, "object": obj})
)
def throw(message):
# type: (object) -> NoReturn
"""Raise a stage exception."""
raise StageException(message)
def exit(message): # pylint: disable=redefined-builtin
# type: (Union[str, bytes]) -> NoReturn
"""Fail the pipeline with an assertion."""
assert _INSTANCE is not None
_INSTANCE.metadata.write_assert(message)
_INSTANCE.done()
def alarm(message):
# type: (Union[str, bytes]) -> None
"""Add a message to the alarms."""
assert _INSTANCE is not None
_INSTANCE.metadata.alarm(message)
#################################################
# Initialization #
#################################################
def test_initialize(path):
# type: (Union[str, bytes]) -> Any
"""Initialize with a fake test metadata."""
# pylint: disable=bad-option-value, import-outside-toplevel
import martian_shell as mr_shell
# pylint: disable=global-statement
global _INSTANCE
_INSTANCE = mr_shell.StageWrapper(
[None, None, "main", path, path, ""], True
)
return _INSTANCE