text stringlengths 81 112k |
|---|
Args:
header_dict : CaseInsensitiveDict
Returns:
bool: ``True`` if ``header_dict`` has a Content-Type key (case insensitive) with
value that begins with 'multipart'.
def is_multipart(header_dict):
"""
Args:
header_dict : CaseInsensitiveDict
Returns:
bool: ``True`` if ``header_dict`` has... |
Return: object_tree_path, resolver, controlled_path.
def _split_path_by_reserved_name(self, path):
"""Return: object_tree_path, resolver, controlled_path."""
for i, e in enumerate(path):
if e in self._resolvers or e == self._get_readme_filename():
return path[:i], path[i], p... |
Generate a human readable description of the folder in text format.
def _generate_readme_text(self, object_tree_path):
"""Generate a human readable description of the folder in text format."""
wdef_folder = self._object_tree.get_source_tree_folder(object_tree_path)
res = StringIO()
if ... |
Return serialized data or list of ids, depending on `hydrate_data` query param.
def _serialize_data(self, data):
"""Return serialized data or list of ids, depending on `hydrate_data` query param."""
if self.request and self.request.query_params.get('hydrate_data', False):
serializer = DataS... |
Filter object objects by permissions of user in request.
def _filter_queryset(self, perms, queryset):
"""Filter object objects by permissions of user in request."""
user = self.request.user if self.request else AnonymousUser()
return get_objects_for_user(user, perms, queryset) |
Return serialized list of data objects on collection that user has `view` permission on.
def get_data(self, collection):
"""Return serialized list of data objects on collection that user has `view` permission on."""
data = self._filter_queryset('view_data', collection.data.all())
return self._... |
Dynamically adapt fields based on the current request.
def get_fields(self):
"""Dynamically adapt fields based on the current request."""
fields = super(CollectionSerializer, self).get_fields()
if self.request.method == "GET":
fields['data'] = serializers.SerializerMethodField()
... |
Load engines.
def load_engines(manager, class_name, base_module, engines, class_key='ENGINE', engine_type='engine'):
"""Load engines."""
loaded_engines = {}
for module_name_or_dict in engines:
if not isinstance(module_name_or_dict, dict):
module_name_or_dict = {
class_k... |
Args: sysmeta_pyxb: Object that may or may not be a SystemMetadata PyXB object.
Returns:
bool:
- ``True`` if ``sysmeta_pyxb`` is a SystemMetadata PyXB object.
- ``False`` if ``sysmeta_pyxb`` is not a PyXB object or is a PyXB object of a
type other than SystemMetadata.
def is_sysmet... |
Normalize SystemMetadata PyXB object in-place.
Args:
sysmeta_pyxb:
SystemMetadata PyXB object to normalize.
reset_timestamps: bool
``True``: Timestamps in the SystemMetadata are set to a standard value so that
objects that are compared after normalization register as equivalent... |
Determine if SystemMetadata PyXB objects are semantically equivalent.
Normalize then compare SystemMetadata PyXB objects for equivalency.
Args:
a_pyxb, b_pyxb : SystemMetadata PyXB objects to compare
reset_timestamps: bool
``True``: Timestamps in the SystemMetadata are set to a standard v... |
Determine if two SystemMetadata XML docs are semantically equivalent.
Normalize then compare SystemMetadata XML docs for equivalency.
Args:
a_xml, b_xml: bytes
UTF-8 encoded SystemMetadata XML docs to compare
ignore_timestamps: bool
``True``: Timestamps in the SystemMetadata are i... |
{clear_replica} causes any replica information to be removed from the object.
{clear_replica} ignores any differences in replica information, as this information
is often different between MN and CN.
def clear_elements(sysmeta_pyxb, clear_replica=True, clear_serial_version=True):
"""{clear_replica} causes... |
Copy elements specified in ``el_list`` from ``src_pyxb`` to ``dst_pyxb``
Only elements that are children of root are supported. See
SYSMETA_ROOT_CHILD_LIST.
If an element in ``el_list`` does not exist in ``src_pyxb``, it is removed from
``dst_pyxb``.
def update_elements(dst_pyxb, src_pyxb, el_list):
... |
Join action with the content type of ``obj``.
Permission is returned in the format of ``<action>_<object_type>``.
def get_full_perm(perm, obj):
"""Join action with the content type of ``obj``.
Permission is returned in the format of ``<action>_<object_type>``.
"""
ctype = ContentType.objects.get_... |
Copy permissions form ``src_obj`` to ``dest_obj``.
def copy_permissions(src_obj, dest_obj):
"""Copy permissions form ``src_obj`` to ``dest_obj``."""
def _process_permission(codename, user_or_group, dest_obj, relabel):
"""Process single permission."""
if relabel:
codename = change_pe... |
Get user by ``pk`` or ``username``. Raise error if it doesn't exist.
def fetch_user(query):
"""Get user by ``pk`` or ``username``. Raise error if it doesn't exist."""
user_filter = {'pk': query} if query.isdigit() else {'username': query}
user_model = get_user_model()
try:
return user_model.ob... |
Get group by ``pk`` or ``name``. Raise error if it doesn't exist.
def fetch_group(query):
"""Get group by ``pk`` or ``name``. Raise error if it doesn't exist."""
group_filter = {'pk': query} if query.isdigit() else {'name': query}
try:
return Group.objects.get(**group_filter)
except Group.Does... |
Raise ``PermissionDenied``if ``owner`` found in ``data``.
def check_owner_permission(payload, allow_user_owner):
"""Raise ``PermissionDenied``if ``owner`` found in ``data``."""
for entity_type in ['users', 'groups']:
for perm_type in ['add', 'remove']:
for perms in payload.get(entity_type, ... |
Raise ``PermissionDenied`` if public permissions are too open.
def check_public_permissions(payload):
"""Raise ``PermissionDenied`` if public permissions are too open."""
allowed_public_permissions = ['view', 'add', 'download']
for perm_type in ['add', 'remove']:
for perm in payload.get('public', {... |
Raise ``PermissionDenied`` if ``payload`` includes ``user_pk``.
def check_user_permissions(payload, user_pk):
"""Raise ``PermissionDenied`` if ``payload`` includes ``user_pk``."""
for perm_type in ['add', 'remove']:
user_pks = payload.get('users', {}).get(perm_type, {}).keys()
if user_pk in use... |
Remove all occurrences of ``permission`` from ``payload``.
def remove_permission(payload, permission):
"""Remove all occurrences of ``permission`` from ``payload``."""
payload = copy.deepcopy(payload)
for entity_type in ['users', 'groups']:
for perm_type in ['add', 'remove']:
for perms... |
Update object permissions.
def update_permission(obj, data):
"""Update object permissions."""
full_permissions = get_all_perms(obj)
def apply_perm(perm_func, perms, entity):
"""Apply permissions using given ``perm_func``.
``perm_func`` is intended to be ``assign_perms`` or
``remov... |
Assign all permissions to object's contributor.
def assign_contributor_permissions(obj, contributor=None):
"""Assign all permissions to object's contributor."""
for permission in get_all_perms(obj):
assign_perm(permission, contributor if contributor else obj.contributor, obj) |
Start process execution.
async def start(self):
"""Start process execution."""
# Workaround for pylint issue #1469
# (https://github.com/PyCQA/pylint/issues/1469).
self.proc = await subprocess.create_subprocess_exec( # pylint: disable=no-member
*shlex.split(self.command),
... |
Execute the script and save results.
async def run_script(self, script):
"""Execute the script and save results."""
script = os.linesep.join(['set -x', 'set +B', script, 'exit']) + os.linesep
self.proc.stdin.write(script.encode('utf-8'))
await self.proc.stdin.drain()
self.proc.s... |
Terminate a running script.
async def terminate(self):
"""Terminate a running script."""
self.proc.terminate()
await asyncio.wait_for(self.proc.wait(), self.kill_delay)
if self.proc.returncode is None:
self.proc.kill()
await self.proc.wait()
await super().t... |
Construct a connection to Redis.
async def _make_connection(self):
"""Construct a connection to Redis."""
return await aioredis.create_redis(
'redis://{}:{}'.format(
self._redis_params.get('host', 'localhost'),
self._redis_params.get('port', 6379)
... |
Perform a Redis call and handle connection dropping.
async def _call_redis(self, meth, *args, **kwargs):
"""Perform a Redis call and handle connection dropping."""
while True:
try:
if not self._redis:
self._redis = await self._make_connection()
... |
Reset the executor queue channel to an empty state.
async def clear_queue(self):
"""Reset the executor queue channel to an empty state."""
conn = await self._make_connection()
try:
script = """
local keys = redis.call('KEYS', ARGV[1])
redis.call('DEL'... |
Stop the standalone manager.
def terminate(self):
"""Stop the standalone manager."""
logger.info(__(
"Terminating Resolwe listener on channel '{}'.",
state.MANAGER_EXECUTOR_CHANNELS.queue
))
self._should_stop = True |
Generate the feedback channel name from the object's id.
:param obj: The Channels message object.
def _queue_response_channel(self, obj):
"""Generate the feedback channel name from the object's id.
:param obj: The Channels message object.
"""
return '{}.{}'.format(state.MANAGE... |
Send a reply with added standard fields back to executor.
:param obj: The original Channels message object to which we're
replying.
:param reply: The message contents dictionary. The data id is
added automatically (``reply`` is modified in place).
async def _send_reply(self, ob... |
Pop the given file's map from the exported files mapping.
:param exported_files_mapper: The dict of file mappings this
process produced.
:param filename: The filename to format and remove from the
mapping.
:param data_id: The id of the :meth:`~resolwe.flow.models.Data`
... |
Handle an incoming ``Data`` object update request.
:param obj: The Channels message object. Command object format:
.. code-block:: none
{
'command': 'update',
'data_id': [id of the :class:`~resolwe.flow.models.Data`
... |
Handle an incoming ``Data`` finished processing request.
:param obj: The Channels message object. Command object format:
.. code-block:: none
{
'command': 'finish',
'data_id': [id of the :class:`~resolwe.flow.models.Data` object
... |
Handle an incoming ``Data`` abort processing request.
.. IMPORTANT::
This only makes manager's state consistent and doesn't
affect Data object in any way. Any changes to the Data
must be applied over ``handle_update`` method.
:param obj: The Channels message object... |
Handle an incoming log processing request.
:param obj: The Channels message object. Command object format:
.. code-block:: none
{
'command': 'log',
'message': [log message]
}
def handle_log(self, obj):
"""Handle an i... |
Push current stats to Redis.
async def push_stats(self):
"""Push current stats to Redis."""
snapshot = self._make_stats()
try:
serialized = json.dumps(snapshot)
await self._call_redis(aioredis.Redis.set, state.MANAGER_LISTENER_STATS, serialized)
await self._c... |
Check for critical load and log an error if necessary.
def check_critical_load(self):
"""Check for critical load and log an error if necessary."""
if self.load_avg.intervals['1m'].value > 1:
if self.last_load_level == 1 and time.time() - self.last_load_log < 30:
return
... |
Run the main listener run loop.
Doesn't return until :meth:`terminate` is called.
async def run(self):
"""Run the main listener run loop.
Doesn't return until :meth:`terminate` is called.
"""
logger.info(__(
"Starting Resolwe listener on channel '{}'.",
... |
Issue callback to start dokan drive.
:param DokanOptions: drive options
:type DokanOptions: DOKAN_OPTIONS
:param DokanOperations: pointers implemented file system calls
:type DokanOperations: DokanOperations
:return: error code
:rtype: int
def dokanMain(self, dokanOptio... |
Creates a file.
:param fileName: name of file to create
:type fileName: ctypes.c_wchar_p
:param desiredAccess: desired access flags
:type desiredAccess: ctypes.c_ulong
:param shareMode: share mode flags
:type shareMode: ctypes.c_ulong
:param creationDisposition: ... |
Read a file.
:param fileName: name of file to read
:type fileName: ctypes.c_wchar_p
:param buffer: buffer for content read
:type buffer: ctypes.c_void_p
:param numberOfBytesToRead: number of bytes to read
:type numberOfBytesToRead: ctypes.c_ulong
:param numberOfB... |
Read a file.
:param fileName: name of file to write
:type fileName: ctypes.c_wchar_p
:param buffer: buffer to write
:type buffer: ctypes.c_void_p
:param numberOfBytesToWrite: number of bytes to write
:type numberOfBytesToWrite: ctypes.c_ulong
:param numberOfBytes... |
Find files in a certain path that match the search pattern.
:param fileName: path to search
:type fileName: ctypes.c_wchar_p
:param searchPattern: pattern to search for
:type searchPattern: ctypes.c_wchar_p
:param fillFindData: function pointer for populating search results
... |
Set time values for a file.
:param fileName: name of file to set time values for
:type fileName: ctypes.c_wchar_p
:param creationTime: creation time of file
:type creationTime: ctypes.POINTER(ctypes.wintypes.FILETIME)
:param lastAccessTime: last access time of file
:type... |
Move a file.
:param existingFileName: name of file to move
:type existingFileName: ctypes.c_wchar_p
:param newFileName: new name of file
:type newFileName: ctypes.c_wchar_p
:param replaceExisting: flag to indicate replacement of existing file
:type replaceExisting: ctype... |
Lock a file.
:param fileName: name of file to lock
:type fileName: ctypes.c_wchar_p
:param byteOffset: location to start lock
:type byteOffset: ctypes.c_longlong
:param length: number of bytes to lock
:type length: ctypes.c_longlong
:param dokanFileInfo: used by ... |
Unlock a file.
:param fileName: name of file to unlock
:type fileName: ctypes.c_wchar_p
:param byteOffset: location to start unlock
:type byteOffset: ctypes.c_longlong
:param length: number of bytes to unlock
:type length: ctypes.c_longlong
:param dokanFileInfo: ... |
Get the amount of free space on this volume.
:param freeBytesAvailable: pointer for free bytes available
:type freeBytesAvailable: ctypes.c_void_p
:param totalNumberOfBytes: pointer for total number of bytes
:type totalNumberOfBytes: ctypes.c_void_p
:param totalNumberOfFreeBytes... |
Get information about the volume.
:param volumeNameBuffer: buffer for volume name
:type volumeNameBuffer: ctypes.c_void_p
:param volumeNameSize: volume name buffer size
:type volumeNameSize: ctypes.c_ulong
:param volumeSerialNumber: buffer for volume serial number
:type ... |
Get security attributes of a file.
:param fileName: name of file to get security for
:type fileName: ctypes.c_wchar_p
:param securityInformation: buffer for security information
:type securityInformation: PSECURITY_INFORMATION
:param securityDescriptor: buffer for security descr... |
Set security attributes of a file.
:param fileName: name of file to set security for
:type fileName: ctypes.c_wchar_p
:param securityInformation: new security information
:type securityInformation: PSECURITY_INFORMATION
:param securityDescriptor: newsecurity descriptor
:... |
Create a simple resource map with one metadata document and n data objects.
def createSimpleResourceMap(ore_pid, sci_meta_pid, data_pids):
"""Create a simple resource map with one metadata document and n data objects."""
ore = ResourceMap()
ore.initialize(ore_pid)
ore.addMetadataDocument(sci_meta_pid)
... |
read pids from in_stream and generate a resource map.
first pid is the ore_pid second is the sci meta pid remainder are data pids
def pids2ore(in_stream, fmt='xml', base_url='https://cn.dataone.org/cn'):
"""read pids from in_stream and generate a resource map.
first pid is the ore_pid second is the sci m... |
Run process.
For details, see
:meth:`~resolwe.flow.managers.workload_connectors.base.BaseConnector.submit`.
def submit(self, data, runtime_dir, argv):
"""Run process.
For details, see
:meth:`~resolwe.flow.managers.workload_connectors.base.BaseConnector.submit`.
"""
... |
Synchronize the local tree of Solr records for DataONE identifiers and
queries with the reference tree.
def refresh(self):
"""Synchronize the local tree of Solr records for DataONE identifiers and
queries with the reference tree."""
if self._source_tree.cache_is_stale():
sel... |
Get an object that has already been cached in the object tree.
Caching happens when the object tree is refreshed.
def get_object_record(self, pid):
"""Get an object that has already been cached in the object tree.
Caching happens when the object tree is refreshed.
"""
try:
... |
Get an object that may not currently be in the cache.
If the object is not in the cache, an attempt is made to retrieve the record
from a CN on the fly. If the object is found, it is cached before being returned
to the user. This allows the object tree caching system to be used for objects
... |
The source tree can contain identifiers that are no longer valid (or were
never valid).
Any items for which a Solr record cannot be retrieved are silently skipped.
def _create_cache_item_for_pid(self, cache_folder, pid):
"""The source tree can contain identifiers that are no longer valid (or w... |
Return abstracted status of dependencies.
- ``STATUS_ERROR`` .. one dependency has error status or was deleted
- ``STATUS_DONE`` .. all dependencies have done status
- ``None`` .. other
def dependency_status(data):
"""Return abstracted status of dependencies.
- ``STATUS_ERROR`` .. one dependency ... |
Discover configured engines.
:param executor: Optional executor module override
def discover_engines(self, executor=None):
"""Discover configured engines.
:param executor: Optional executor module override
"""
if executor is None:
executor = getattr(settings, 'FLOW... |
Reset the shared state and drain Django Channels.
:param keep_state: If ``True``, do not reset the shared manager
state (useful in tests, where the settings overrides need to
be kept). Defaults to ``False``.
def reset(self, keep_state=False):
"""Reset the shared state and drain... |
Marshal Django settings into a serializable object.
:return: The serialized settings.
:rtype: dict
def _marshal_settings(self):
"""Marshal Django settings into a serializable object.
:return: The serialized settings.
:rtype: dict
"""
result = {}
for key... |
Define environment variables.
def _include_environment_variables(self, program, executor_vars):
"""Define environment variables."""
env_vars = {
'RESOLWE_HOST_URL': self.settings_actual.get('RESOLWE_HOST_URL', 'localhost'),
}
set_env = self.settings_actual.get('FLOW_EXECUTO... |
Select a concrete connector and run the process through it.
:param data: The :class:`~resolwe.flow.models.Data` object that
is to be run.
:param runtime_dir: The directory the executor is run from.
:param argv: The argument vector used to spawn the executor.
def run(self, data, run... |
Extend the given base directory with a per-data component.
The method creates a private path for the
:class:`~resolwe.flow.models.Data` object, such as::
./test_data/1/
if ``base_dir`` is ``'./test_data'`` and ``subpath`` is ``1``.
:param dir_base: The base path to be ext... |
Prepare destination directory where the data will live.
:param data: The :class:`~resolwe.flow.models.Data` object for
which to prepare the private execution directory.
:return: The prepared data directory path.
:rtype: str
def _prepare_data_dir(self, data):
"""Prepare dest... |
Prepare settings and constants JSONs for the executor.
Settings and constants provided by other ``resolwe`` modules and
:class:`~django.conf.settings` are all inaccessible in the
executor once it is deployed, so they need to be serialized into
the runtime directory.
:param data... |
Copy executor sources into the destination directory.
:param data: The :class:`~resolwe.flow.models.Data` object being
prepared for.
:param executor: The fully qualified name of the executor that
is to be used for this data object.
:return: Tuple containing the relative ... |
Copy the script into the destination directory.
:param dest_dir: The target directory where the script will be
saved.
:param program: The script text to be saved.
:return: The name of the script file.
:rtype: str
def _prepare_script(self, dest_dir, program):
"""Copy... |
Handle an event from the Channels layer.
Channels layer callback, do not call directly.
async def handle_control_event(self, message):
"""Handle an event from the Channels layer.
Channels layer callback, do not call directly.
"""
cmd = message[WorkerProtocol.COMMAND]
l... |
Ensure the sync counter is a valid non-dummy object.
def _ensure_counter(self):
"""Ensure the sync counter is a valid non-dummy object."""
if not isinstance(self.sync_counter, self._SynchronizationManager):
self.sync_counter = self._SynchronizationManager() |
Wait for executors to finish.
At least one must finish after this point to avoid a deadlock.
async def execution_barrier(self):
"""Wait for executors to finish.
At least one must finish after this point to avoid a deadlock.
"""
async def _barrier():
"""Enter the sy... |
Scan database for resolving Data objects and process them.
This is submitted as a task to the manager's channel workers.
:param data_id: Optional id of Data object which (+ its
children) should be processes. If it is not given, all
resolving objects are processed.
:para... |
Execute the Data object.
The activities carried out here include target directory
preparation, executor copying, setting serialization and actual
execution of the object.
:param data: The :class:`~resolwe.flow.models.Data` object to
execute.
:param program: The proc... |
Scan for new Data objects and execute them.
:param data_id: Optional id of Data object which (+ its
children) should be scanned. If it is not given, all
resolving objects are processed.
:param executor: The fully qualified name of the executor to use
for all :class:`... |
Return an expression engine instance.
def get_expression_engine(self, name):
"""Return an expression engine instance."""
try:
return self.expression_engines[name]
except KeyError:
raise InvalidEngineError("Unsupported expression engine: {}".format(name)) |
Return an execution engine instance.
def get_execution_engine(self, name):
"""Return an execution engine instance."""
try:
return self.execution_engines[name]
except KeyError:
raise InvalidEngineError("Unsupported execution engine: {}".format(name)) |
Load process executor.
def load_executor(self, executor_name):
"""Load process executor."""
executor_name = executor_name + '.prepare'
module = import_module(executor_name)
return module.FlowExecutorPreparer() |
Extract subjects from a DataONE PEM (Base64) encoded X.509 v3 certificate.
Args:
cert_pem: str or bytes
PEM (Base64) encoded X.509 v3 certificate
Returns:
2-tuple:
- The primary subject string, extracted from the certificate DN.
- A set of equivalent identities, group membe... |
Return queryset.
def get_queryset(self): # pylint: disable=method-hidden
"""Return queryset."""
if self.request and self.request.query_params.get('hydrate_data', False):
return self.queryset.prefetch_related('data__entity_set')
return self.queryset |
Check that collection exists and user has `add` permission.
def _get_collection_for_user(self, collection_id, user):
"""Check that collection exists and user has `add` permission."""
collection_query = Collection.objects.filter(pk=collection_id)
if not collection_query.exists():
rai... |
Return entities queryset based on provided entity ids.
def _get_entities(self, user, ids):
"""Return entities queryset based on provided entity ids."""
queryset = get_objects_for_user(user, 'view_entity', Entity.objects.filter(id__in=ids))
actual_ids = queryset.values_list('id', flat=True)
... |
Apply permissions to data objects in ``Entity``.
def set_content_permissions(self, user, obj, payload):
"""Apply permissions to data objects in ``Entity``."""
# Data doesn't have "ADD" permission, so it has to be removed
payload = remove_permission(payload, 'add')
for data in obj.data.... |
Destroy a model instance.
If ``delete_content`` flag is set in query parameters, also all
Data objects contained in entity will be deleted.
def destroy(self, request, *args, **kwargs):
"""Destroy a model instance.
If ``delete_content`` flag is set in query parameters, also all
... |
Add Entity to a collection.
def add_to_collection(self, request, pk=None):
"""Add Entity to a collection."""
entity = self.get_object()
# TODO use `self.get_ids` (and elsewhere). Backwards
# incompatible because raised error's response contains
# ``detail`` instead of ``error``... |
Add data to Entity and it's collection.
def add_data(self, request, pk=None):
"""Add data to Entity and it's collection."""
# add data to entity
resp = super().add_data(request, pk)
# add data to collections in which entity is
entity = self.get_object()
for collection i... |
Move samples from source to destination collection.
def move_to_collection(self, request, *args, **kwargs):
"""Move samples from source to destination collection."""
ids = self.get_ids(request.data)
src_collection_id = self.get_id(request.data, 'source_collection')
dst_collection_id = s... |
Update an entity.
Original queryset produces a temporary database table whose rows
cannot be selected for an update. As a workaround, we patch
get_queryset function to return only Entity objects without
additional data that is not needed for the update.
def update(self, request, *args,... |
Start process execution.
async def start(self):
"""Start process execution."""
# arguments passed to the Docker command
command_args = {
'command': self.command,
'container_image': self.requirements.get('image', constants.DEFAULT_CONTAINER_IMAGE),
}
# Ge... |
Execute the script and save results.
async def run_script(self, script):
"""Execute the script and save results."""
# Create a Bash command to add all the tools to PATH.
tools_paths = ':'.join([map_["dest"] for map_ in self.tools_volumes])
add_tools_path = 'export PATH=$PATH:{}'.format(... |
End process execution.
async def end(self):
"""End process execution."""
try:
await self.proc.wait()
finally:
# Cleanup temporary files.
for temporary_file in self.temporary_files:
temporary_file.close()
self.temporary_files = []
... |
Terminate a running script.
async def terminate(self):
"""Terminate a running script."""
# Workaround for pylint issue #1469
# (https://github.com/PyCQA/pylint/issues/1469).
cmd = await subprocess.create_subprocess_exec( # pylint: disable=no-member
*shlex.split('{} rm -f {}... |
Decode JSON stream.
def iterjson(text):
"""Decode JSON stream."""
decoder = json.JSONDecoder()
while text:
obj, ndx = decoder.raw_decode(text)
if not isinstance(obj, dict):
raise ValueError()
text = text[ndx:].lstrip('\r\n')
yield obj |
Send an update to manager and terminate the process if it fails.
async def _send_manager_command(self, *args, **kwargs):
"""Send an update to manager and terminate the process if it fails."""
resp = await send_manager_command(*args, **kwargs)
if resp is False:
await self.terminate(... |
Update (PATCH) Data object.
:param kwargs: The dictionary of
:class:`~resolwe.flow.models.Data` attributes to be changed.
async def update_data_status(self, **kwargs):
"""Update (PATCH) Data object.
:param kwargs: The dictionary of
:class:`~resolwe.flow.models.Data` at... |
Execute the script and save results.
async def run(self, data_id, script):
"""Execute the script and save results."""
logger.debug("Executor for Data with id {} has started.".format(data_id))
try:
finish_fields = await self._run(data_id, script)
except SystemExit as ex:
... |
Ensure a new file is created and opened for writing.
def _create_file(self, filename):
"""Ensure a new file is created and opened for writing."""
file_descriptor = os.open(filename, os.O_WRONLY | os.O_CREAT | os.O_EXCL)
return os.fdopen(file_descriptor, 'w') |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.