text
stringlengths
18
773k
def setFileTime( self, fileName, creationTime, lastAccessTime, lastWriteTime, dokanFileInfo ): """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 creati...
def moveFile(self, existingFileName, newFileName, replaceExisiting, dokanFileInfo): """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 repl...
def lockFile(self, fileName, byteOffset, length, dokanFileInfo): """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 ...
def unlockFile(self, fileName, byteOffset, length, dokanFileInfo): """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...
def getDiskFreeSpace( self, freeBytesAvailable, totalNumberOfBytes, totalNumberOfFreeBytes, dokanFileInfo, ): """Get the amount of free space on this volume. :param freeBytesAvailable: pointer for free bytes available :type freeBytesAvailable: ctypes....
def getVolumeInformation( self, volumeNameBuffer, volumeNameSize, volumeSerialNumber, maximumComponentLength, fileSystemFlags, fileSystemNameBuffer, fileSystemNameSize, dokanFileInfo, ): """Get information about the volume. :pa...
def getFileSecurity( self, fileName, securityInformation, securityDescriptor, lengthSecurityDescriptorBuffer, lengthNeeded, dokanFileInfo, ): """Get security attributes of a file. :param fileName: name of file to get security for :type...
def setFileSecurity( self, fileName, securityInformation, securityDescriptor, lengthSecurityDescriptorBuffer, dokanFileInfo, ): """Set security attributes of a file. :param fileName: name of file to set security for :type fileName: ctypes.c_wc...
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) ore.addDataDocuments(data_pids, sci_meta_pid) return ore
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 meta pid remainder are data pids """ pids = [] for line in in_stream: pid = line.strip() if len(pid) > 0: ...
def submit(self, data, runtime_dir, argv): """Run process. For details, see :meth:`~resolwe.flow.managers.workload_connectors.base.BaseConnector.submit`. """ queue = 'ordinary' if data.process.scheduling_class == Process.SCHEDULING_CLASS_INTERACTIVE: queue = ...
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(): self._source_tree.refresh() logging.info('Refreshing object tree') self._init_cache() ...
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: return self._cache['records'][pid] except KeyError: raise d1_onedrive.impl.onedrive_exceptions...
def get_object_record_with_sync(self, pid): """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...
def _create_cache_item_for_pid(self, cache_folder, pid): """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. """ try: record = self._solr_client.get_so...
def dependency_status(data): """Return abstracted status of dependencies. - ``STATUS_ERROR`` .. one dependency has error status or was deleted - ``STATUS_DONE`` .. all dependencies have done status - ``None`` .. other """ parents_statuses = set( DataDependency.objects.filter( ...
def discover_engines(self, executor=None): """Discover configured engines. :param executor: Optional executor module override """ if executor is None: executor = getattr(settings, 'FLOW_EXECUTOR', {}).get('NAME', 'resolwe.flow.executors.local') self.executor = self.l...
def reset(self, keep_state=False): """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``. """ if not keep_s...
def _marshal_settings(self): """Marshal Django settings into a serializable object. :return: The serialized settings. :rtype: dict """ result = {} for key in dir(settings): if any(map(key.startswith, ['FLOW_', 'RESOLWE_', 'CELERY_'])): result[...
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_EXECUTOR', {}).get('SET_ENV', {}) ...
def run(self, data, runtime_dir, argv): """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 u...
def _get_per_data_dir(self, dir_base, subpath): """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`` ...
def _prepare_data_dir(self, data): """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_context(self, data_id, data_dir, runtime_dir, **kwargs): """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 th...
def _prepare_executor(self, data, executor): """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...
def _prepare_script(self, dest_dir, program): """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 ...
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] logger.debug(__("Manager worker got channel command '{}'.", cmd)) # Prepare settings for u...
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()
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 sync block and exit the app afterwards.""" async with self.sync_counter: pass...
async def communicate(self, data_id=None, run_sync=False, save_settings=True): """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 pro...
def _data_execute(self, data, program, executor): """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` ob...
def _data_scan(self, data_id=None, executor='resolwe.flow.executors.local', **kwargs): """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. ...
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))
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))
def load_executor(self, executor_name): """Load process executor.""" executor_name = executor_name + '.prepare' module = import_module(executor_name) return module.FlowExecutorPreparer()
def extract_subjects(cert_pem): """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 se...
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
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(): raise exceptions.ValidationError('Collection id does not exist')...
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) missing_ids = list(set(ids) - set(actual_ids)) ...
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.all(): if user.has_perm('share_data', ...
def destroy(self, request, *args, **kwargs): """Destroy a model instance. If ``delete_content`` flag is set in query parameters, also all Data objects contained in entity will be deleted. """ obj = self.get_object() user = request.user if strtobool(request.query...
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``). if 'ids' not in re...
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 in entity.collections.all(): c...
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 = self.get_id(request.data, 'destination_collection') ...
def update(self, request, *args, **kwargs): """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 n...
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), } # Get limit defaults. ...
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(tools_paths) # Spawn another c...
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 = [] return self.proc...
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 {}'.format(self.command, self._...
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
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()
async def update_data_status(self, **kwargs): """Update (PATCH) Data object. :param kwargs: The dictionary of :class:`~resolwe.flow.models.Data` attributes to be changed. """ await self._send_manager_command(ExecutorProtocol.UPDATE, extra_fields={ ExecutorProtoco...
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: raise ex except Except...
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')
async def _run(self, data_id, script): """Execute the script and save results.""" self.data_id = data_id # Fetch data instance to get any executor requirements. self.process = PROCESS requirements = self.process['requirements'] self.requirements = requirements.get('execu...
def get_total_size_of_queued_replicas(): """Return the total number of bytes of requested, unprocessed replicas.""" return ( d1_gmn.app.models.ReplicationQueue.objects.filter( local_replica__info__status__status='queued' ).aggregate(Sum('size'))['size__sum'] or 0 )
def add_to_replication_queue(source_node_urn, sysmeta_pyxb): """Add a replication request issued by a CN to a queue that is processed asynchronously. Preconditions: - sysmeta_pyxb.identifier is verified to be available for create. E.g., with d1_gmn.app.views.is_valid_pid_for_create(pid). Pos...
def add_arguments(parser, doc_str, add_base_url=True): """Add standard arguments for DataONE utilities to a command line parser.""" parser.description = doc_str parser.formatter_class = argparse.RawDescriptionHelpFormatter parser.add_argument("--debug", action="store_true", help="Debug level logging") ...
def path_generator( path_list, include_glob_list=None, exclude_glob_list=None, recursive=True, ignore_invalid=False, default_excludes=True, return_dir_paths=False, ): """# language=rst. Args: path_list: list of str List of file- and dir paths. File paths are used dire...
def get_resource_map_members(pid): """``pid`` is the PID of a Resource Map or the PID of a member of a Resource Map.""" if d1_gmn.app.did.is_resource_map_db(pid): return get_resource_map_members_by_map(pid) elif d1_gmn.app.did.is_resource_map_member(pid): return get_resource_map_members_by_m...
def set_with_conversion(self, variable, value_string): """Convert user supplied string to Python type. Lets user use values such as True, False and integers. All variables can be set to None, regardless of type. Handle the case where a string is typed by the user and is not quoted, as a...
def log_setup(is_debug=False, is_multiprocess=False): """Set up a standardized log format for the DataONE Python stack. All Python components should use this function. If ``is_multiprocess`` is True, include process ID in the log so that logs can be separated for each process. Output only to stdout and...
def get_content_type(content_type): """Extract the MIME type value from a content type string. Removes any subtype and parameter values that may be present in the string. Args: content_type: str String with content type and optional subtype and parameter fields. Returns: str: Stri...
def nested_update(d, u): """Merge two nested dicts. Nested dicts are sometimes used for representing various recursive structures. When updating such a structure, it may be convenient to present the updated data as a corresponding recursive structure. This function will then apply the update. Args...
def print_logging(): """Context manager to temporarily suppress additional information such as timestamps when writing to loggers. This makes logging look like ``print()``. The main use case is in scripts that mix logging and ``print()``, as Python uses separate streams for those, and output can an...
def save_json(py_obj, json_path): """Serialize a native object to JSON and save it normalized, pretty printed to a file. The JSON string is normalized by sorting any dictionary keys. Args: py_obj: object Any object that can be represented in JSON. Some types, such as datetimes are ...
def serialize_to_normalized_pretty_json(py_obj): """Serialize a native object to normalized, pretty printed JSON. The JSON string is normalized by sorting any dictionary keys. Args: py_obj: object Any object that can be represented in JSON. Some types, such as datetimes are automatic...
def serialize_to_normalized_compact_json(py_obj): """Serialize a native object to normalized, compact JSON. The JSON string is normalized by sorting any dictionary keys. It will be on a single line without whitespace between elements. Args: py_obj: object Any object that can be represent...
def format_sec_to_dhm(sec): """Format seconds to days, hours, minutes. Args: sec: float or int Number of seconds in a period of time Returns: Period of time represented as a string on the form ``0d:00h:00m``. """ rem_int, s_int = divmod(int(sec), 60) rem_int, m_int, = divm...
def count(self, event_str, inc_int=1): """Count an event. Args: event_str: The name of an event to count. Used as a key in the event dict. The same name will also be used in the summary. inc_int: int Optional argument to increase the count for th...
def log_and_count(self, event_str, msg_str=None, inc_int=None): """Count an event and write a message to a logger. Args: event_str: str The name of an event to count. Used as a key in the event dict. The same name will be used in the summary. This also becomes a part o...
def dump_to_log(self): """Write summary to logger with the name and number of times each event has been counted. This function may be called at any point in the process. Counts are not zeroed. """ if self._event_dict: logger.info('Events:') for event_str...
def delete_all_from_db(): """Clear the database. Used for testing and debugging. """ # The models.CASCADE property is set on all ForeignKey fields, so tables can # be deleted in any order without breaking constraints. for model in django.apps.apps.get_models(): model.objects.all().dele...
def get_query_param(request, key): """Get query parameter uniformly for GET and POST requests.""" value = request.query_params.get(key) or request.data.get(key) if value is None: raise KeyError() return value
def get_limit(self, request): """Return limit parameter.""" if self.limit_query_param: try: return _positive_int( get_query_param(request, self.limit_query_param), strict=True, cutoff=self.max_limit )...
def get_offset(self, request): """Return offset parameter.""" try: return _positive_int( get_query_param(request, self.offset_query_param), ) except (KeyError, ValueError): return 0
def futurize_module(module_path, show_diff, write_update): """2to3 uses AST, not Baron.""" logging.info('Futurizing module... path="{}"'.format(module_path)) ast_tree = back_to_the_futurize(module_path) return d1_dev.util.update_module_file_ast( ast_tree, module_path, show_diff, write_update ...
def _remove_single_line_import_comments(r): """We previously used more groups for the import statements and named each group.""" logging.info('Removing single line import comments') import_r, remaining_r = split_by_last_import(r) new_import_r = redbaron.NodeList() for i, v in enumerate(import_r): ...
def _update_init_all(module_path, r): """Add or update __all__ in __init__.py file.""" module_dir_path = os.path.split(module_path)[0] module_list = [] for item_name in os.listdir(module_dir_path): item_path = os.path.join(module_dir_path, item_name) if os.path.isfile(item_path) and item...
def _remove_init_all(r): """Remove any __all__ in __init__.py file.""" new_r = redbaron.NodeList() for n in r.node_list: if n.type == 'assignment' and n.target.value == '__all__': pass else: new_r.append(n) return new_r
def get_object_list_json(request): """gmn.listObjects(session[, fromDate][, toDate][, formatId] [, identifier][, replicaStatus][, start=0][, count=1000] [, f=sysmetaField ...]) → ObjectListJson GMN specific API for fast retrieval of object sysmeta elements. """ # TODO: Add to documentation ...
def configure_logging(emit_list): """Configure logging to send log records to the master.""" if 'sphinx' in sys.modules: module_base = 'resolwe.flow.executors' else: module_base = 'executors' logging_config = dict( version=1, formatters={ 'json_formatter': { ...
def format(self, record): """Dump the record to JSON.""" data = record.__dict__.copy() data['data_id'] = DATA['id'] data['data_location_id'] = DATA_LOCATION['id'] data['hostname'] = socket.gethostname() # Get relative path, so listener can reconstruct the path to the ac...
def emit(self, record): """Send log message to the listener.""" future = asyncio.ensure_future(send_manager_command( ExecutorProtocol.LOG, extra_fields={ ExecutorProtocol.LOG_MESSAGE: self.format(record), }, expect_reply=False )) ...
async def is_object_synced_to_cn(self, client, pid): """Check if object with {pid} has successfully synced to the CN. CNRead.describe() is used as it's a light-weight HTTP HEAD request. This assumes that the call is being made over a connection that has been authenticated and has read ...
async def send_synchronization_request(self, client, pid): """Issue a notification and request for sync for object with {pid} to the CN.""" # Skip CN call for debugging # status = 200 status = await client.synchronize(pid) if status == 200: self.progress_logger.event(...
def create_secret(self, value, contributor, metadata=None, expires=None): """Create a new secret, returning its handle. :param value: Secret value to store :param contributor: User owning the secret :param metadata: Optional metadata dictionary (must be JSON serializable) :param...
def get_secret(self, handle, contributor): """Retrieve an existing secret's value. :param handle: Secret handle :param contributor: User instance to perform contributor validation, which means that only secrets for the given contributor will be looked up. """ ...
def validation_schema(name): """Return json schema for json validation.""" schemas = { 'processor': 'processSchema.json', 'descriptor': 'descriptorSchema.json', 'field': 'fieldSchema.json', 'type': 'typeSchema.json', } if name not in schemas: raise ValueError() ...
def validate_schema(instance, schema, test_required=True, data_location=None, skip_missing_data=False): """Check if DictField values are consistent with our data types. Perform basic JSON schema validation and our custom validations: * check that required fields are given (if `test_r...
def _hydrate_values(output, output_schema, data): """Hydrate basic:file and basic:json values. Find fields with basic:file type and assign a full path to the file. Find fields with basic:json type and assign a JSON object from storage. """ def hydrate_path(file_name): """Hydrate file paths...
def hydrate_input_references(input_, input_schema, hydrate_values=True): """Hydrate ``input_`` with linked data. Find fields with complex data:<...> types in ``input_``. Assign an output of corresponding data object to those fields. """ from .data import Data # prevent circular import for fi...
def hydrate_input_uploads(input_, input_schema, hydrate_values=True): """Hydrate input basic:upload types with upload location. Find basic:upload fields in input. Add the upload location for relative paths. """ from resolwe.flow.managers import manager files = [] for field_schema, fields ...
def hydrate_size(data, force=False): """Add file and dir sizes. Add sizes to ``basic:file:``, ``list:basic:file``, ``basic:dir:`` and ``list:basic:dir:`` fields. ``force`` parameter is used to recompute file sizes also on objects that already have these values, e.g. in migrations. """ from...
def render_descriptor(data): """Render data descriptor. The rendering is based on descriptor schema and input context. :param data: data instance :type data: :class:`resolwe.flow.models.Data` or :class:`dict` """ if not data.descriptor_schema: return # Set default values for ...
def render_template(process, template_string, context): """Render template using the specified expression engine.""" from resolwe.flow.managers import manager # Get the appropriate expression engine. If none is defined, do not evaluate # any expressions. expression_engine = process.requirements.get...
def json_path_components(path): """Convert JSON path to individual path components. :param path: JSON path, which can be either an iterable of path components or a dot-separated string :return: A list of path components """ if isinstance(path, str): path = path.split('.') retur...
def validate_process_subtype(supertype_name, supertype, subtype_name, subtype): """Perform process subtype validation. :param supertype_name: Supertype name :param supertype: Supertype schema :param subtype_name: Subtype name :param subtype: Subtype schema :return: A list of validation error st...
def validate_process_types(queryset=None): """Perform process type validation. :param queryset: Optional process queryset to validate :return: A list of validation error strings """ if not queryset: from .process import Process queryset = Process.objects.all() processes = {} ...
def fill_with_defaults(process_input, input_schema): """Fill empty optional fields in input with default values.""" for field_schema, fields, path in iterate_schema(process_input, input_schema): if 'default' in field_schema and field_schema['name'] not in fields: dict_dot(process_input, path...