text
stringlengths
81
112k
Execute the script and save results. 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....
Return the total number of bytes of requested, unprocessed replicas. 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' ...
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). Postconditions: - The database is set up to track a new replica, wi...
Add standard arguments for DataONE utilities to a command line parser. 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.ad...
# language=rst. Args: path_list: list of str List of file- and dir paths. File paths are used directly and dirs are searched for files. ``path_list`` does not accept glob patterns, as it's more convenient to let the shell expand glob patterns to directly specified files and ...
``pid`` is the PID of a Resource Map or the PID of a member of a Resource Map. 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.a...
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 string literal. def set_with_conversion(self, variable, value_st...
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 stderr. def log_setup(is_debug=False, is_multiprocess=False...
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: String with only content type Example: ...
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: d: dict dict tha...
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 and does end up getting shuffl...
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 automatically converted to strings. ...
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 automatically converted to strings. Returns: str: norm...
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 represented in JSON. Some types, such as datetimes are aut...
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``. def format_sec_to_dhm(sec): """Format seconds to days, hours, minutes. Args: sec: float or int ...
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 the event by more than 1. def count(self, event_str...
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 of the message logged by this function. msg_str: str ...
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. def dump_to_log(self): """Write summary to logger with the name and number of times each event has been counted. ...
Clear the database. Used for testing and debugging. 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 djang...
Get query parameter uniformly for GET and POST requests. 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
Return limit parameter. 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.ma...
Return offset parameter. 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
2to3 uses AST, not Baron. 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, ...
We previously used more groups for the import statements and named each group. 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...
Add or update __all__ in __init__.py file. 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) ...
Remove any __all__ in __init__.py file. 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
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. def get_object_list_json(request): """gmn.listObjects(session[, fromDate][, toDat...
Configure logging to send log records to the master. 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, ...
Dump the record to JSON. 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 reco...
Send log message to the listener. 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), }, ...
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 or better access on the given object if it exists. asyn...
Issue a notification and request for sync for object with {pid} to the CN. 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.synchr...
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 expires: Optional date/time of expiry (defaults to None, which means that ...
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 get_secret(self, handle, contributor): """Retrieve an ex...
Return json schema for json validation. 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...
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_required` is set to ``True``) * check if ``basic:file:`` and ``list:basic:file`` fields match regex given in s...
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_values(output, output_schema, data): """Hydrate basic:file and basic:json values. Find fields with basic:...
Hydrate ``input_`` with linked data. Find fields with complex data:<...> types in ``input_``. Assign an output of corresponding data object to those fields. def hydrate_input_references(input_, input_schema, hydrate_values=True): """Hydrate ``input_`` with linked data. Find fields with complex data:<...
Hydrate input basic:upload types with upload location. Find basic:upload fields in input. Add the upload location for relative paths. 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 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. def hydrate_size(data, force=False): """Add file and di...
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` def render_descriptor(data): """Render data descriptor. The rendering is based on descriptor schema and input context. ...
Render template using the specified expression engine. 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 expre...
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 def json_path_components(path): """Convert JSON path to individual path components. :param path: JSON path, ...
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 strings def validate_process_subtype(supertype_name, supertype, subtype_name, subtype): ...
Perform process type validation. :param queryset: Optional process queryset to validate :return: A list of validation error strings def validate_process_types(queryset=None): """Perform process type validation. :param queryset: Optional process queryset to validate :return: A list of validation e...
Fill empty optional fields in input with default values. 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...
Format the internal value. def to_internal_value(self, data): """Format the internal value.""" # When setting the contributor, it may be passed as an integer. if isinstance(data, dict) and isinstance(data.get('id', None), int): data = data['id'] elif isinstance(data, int): ...
Extract data from the descriptor. def extract_descriptor(self, obj): """Extract data from the descriptor.""" descriptor = [] def flatten(current): """Flatten descriptor.""" if isinstance(current, dict): for key in current: flatten(cur...
Return serialized items or list of ids, depending on `hydrate_XXX` query param. def _serialize_items(self, serializer, kind, items): """Return serialized items or list of ids, depending on `hydrate_XXX` query param.""" if self.request and self.request.query_params.get('hydrate_{}'.format(kind), False):...
Return serialized list of entity names on data that user has `view` permission on. def get_entity_names(self, data): """Return serialized list of entity names on data that user has `view` permission on.""" entities = self._filter_queryset('view_entity', data.entity_set.all()) return list(entiti...
Return serialized list of collection objects on data that user has `view` permission on. def get_collections(self, data): """Return serialized list of collection objects on data that user has `view` permission on.""" collections = self._filter_queryset('view_collection', data.collection_set.all()) ...
Return serialized list of entity objects on data that user has `view` permission on. def get_entities(self, data): """Return serialized list of entity objects on data that user has `view` permission on.""" entities = self._filter_queryset('view_entity', data.entity_set.all()) from .entity impo...
Dynamically adapt fields based on the current request. def get_fields(self): """Dynamically adapt fields based on the current request.""" fields = super(DataSerializer, self).get_fields() # Hide collections/entities fields on list views as fetching them may be expensive. if self.parent...
Handle command list_docker_images. def handle(self, *args, **options): """Handle command list_docker_images.""" verbosity = int(options.get('verbosity')) # Check that the specified output format is valid if options['format'] != 'plain' and options['format'] != 'yaml': raise...
Create a resource. def create(self, request, *args, **kwargs): """Create a resource.""" collections = request.data.get('collections', []) # check that user has permissions on all collections that Data # object will be added to for collection_id in collections: try: ...
Get ``Data`` object if similar already exists, otherwise create it. def get_or_create(self, request, *args, **kwargs): """Get ``Data`` object if similar already exists, otherwise create it.""" kwargs['get_or_create'] = True return self.create(request, *args, **kwargs)
Perform "get_or_create" - return existing object if found. def perform_get_or_create(self, request, *args, **kwargs): """Perform "get_or_create" - return existing object if found.""" serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) process = ...
Create a resource. def perform_create(self, serializer): """Create a resource.""" process = serializer.validated_data.get('process') if not process.is_active: raise exceptions.ParseError( 'Process retired (id: {}, slug: {}/{}).'.format(process.id, process.slug, proce...
Called once per Django process instance. If the filesystem setup fails or if an error is found in settings.py, django.core.exceptions.ImproperlyConfigured is raised, causing Django not to launch the main GMN app. def ready(self): """Called once per Django process instance. If ...
Check that the dirs leading up to the given file path exist. Does not check if the file exists. def _assert_dirs_exist(self, setting_name): """Check that the dirs leading up to the given file path exist. Does not check if the file exists. """ v = self._get_setting(setting_nam...
Warn on settings that are not safe for production. def _warn_unsafe_for_prod(self): """Warn on settings that are not safe for production.""" safe_settings_list = [ ('DEBUG', False), ('DEBUG_GMN', False), ('STAND_ALONE', False), ('DATABASES.default.ATOMIC_...
Return the value of a potentially nested dict setting. E.g., 'DATABASES.default.NAME def _get_setting(self, setting_dotted_name, default=None): """Return the value of a potentially nested dict setting. E.g., 'DATABASES.default.NAME """ name_list = setting_dotted_name.split('....
Refresh connection to Elasticsearch when worker is started. File descriptors (sockets) can be shared between multiple threads. If same connection is used by multiple threads at the same time, this can cause timeouts in some of the pushes. So connection needs to be reestablished in each ...
Generate unique document id for ElasticSearch. def generate_id(self, obj): """Generate unique document id for ElasticSearch.""" object_type = type(obj).__name__.lower() return '{}_{}'.format(object_type, self.get_object_id(obj))
Process current object and push it to the ElasticSearch. def process_object(self, obj): """Process current object and push it to the ElasticSearch.""" document = self.document_class(meta={'id': self.generate_id(obj)}) for field in document._doc_type.mapping: # pylint: disable=protected-access...
Create the mappings in elasticsearch. def create_mapping(self): """Create the mappings in elasticsearch.""" try: self.document_class.init() self._mapping_created = True except IllegalOperation as error: if error.args[0].startswith('You cannot update analysis ...
Build indexes. def build(self, obj=None, queryset=None, push=True): """Build indexes.""" if obj is not None and queryset is not None: raise ValueError( "Only one of 'obj' and 'queryset' parameters can be passed to the build method." ) if obj is not None:...
Build indexes. def _build(self, obj=None, queryset=None, push=True): """Build indexes.""" logger.debug("Building '%s' Elasticsearch index...", self.__class__.__name__) if obj is not None: build_list = [obj] elif queryset is not None: build_list = self.queryset....
Push built documents to ElasticSearch. def push(self): """Push built documents to ElasticSearch.""" self._refresh_connection() # Check if we need to update mappings as this needs to be done # before we push anything to the Elasticsearch server. # This must be done even if the q...
Destroy an index. def destroy(self): """Destroy an index.""" self._refresh_connection() self.push_queue = [] index_name = self.document_class()._get_index() # pylint: disable=protected-access connections.get_connection().indices.delete(index_name, ignore=404) self._ma...
Return users and groups with ``view`` permission on the current object. Return a dict with two keys - ``users`` and ``groups`` - which contain list of ids of users/groups with ``view`` permission. def get_permissions(self, obj): """Return users and groups with ``view`` permission on the curren...
Remove current object from the ElasticSearch. def remove_object(self, obj): """Remove current object from the ElasticSearch.""" obj_id = self.generate_id(obj) es_obj = self.document_class.get(obj_id, ignore=[404]) # Object may not exist in this index. if es_obj: es_o...
Args: args: def generate_pyxb_binding(self, args): """Args: args: """ pyxbgen_args = [] pyxbgen_args.append('--schema-root=\'{}\''.format(self.schema_dir)) pyxbgen_args.append('--binding-root=\'{}\''.format(self.binding_dir)) pyxbgen_args.append( ...
Args: args: def run_pyxbgen(self, args): """Args: args: """ cmd = 'pyxbgen {}'.format(' '.join(args)) print(cmd) os.system(cmd)
Given a DataONE schema, generates a file that contains version information about the schema. def generate_version_file(self, schema_filename, binding_filename): """Given a DataONE schema, generates a file that contains version information about the schema.""" version_filename = binding_...
Args: version_file_path: tstamp: svnpath: svnrev: version: def write_version_file(self, version_file_path, tstamp, svnpath, svnrev, version): """Args: version_file_path: tstamp: svnpath: svnrev: version: """ txt = """# This file is automatically generated. Manual edits will b...
MNStorage.updateSystemMetadata(session, pid, sysmeta) → boolean http://jenkins-1.dataone.org/documentation/unstable/API-Documentation- development/apis/MN_APIs.html#MNStorage.updateSystemMetadata. Args: pid: sysmeta_pyxb: vendorSpecific: Returns: def upda...
Create DataLocation for each Data. def set_data_location(apps, schema_editor): """Create DataLocation for each Data.""" Data = apps.get_model('flow', 'Data') DataLocation = apps.get_model('flow', 'DataLocation') for data in Data.objects.all(): if os.path.isdir(os.path.join(settings.FLOW_EXECUT...
Retrieves the next page of results. def _loadMore(self, start=0, trys=0, validation=True): """Retrieves the next page of results.""" self._log.debug("Loading page starting from %d" % start) self._czero = start self._pageoffs = 0 try: pyxb.RequireValidWhenParsing(vali...
Carves up a mime-type and returns a tuple of the (type, subtype, params) where 'params' is a dictionary of all the parameters for the media range. For example, the media range 'application/xhtml;q=0.5' would get parsed into: ('application', 'xhtml', {'q', '0.5'}) def parse_mime_type(mime_type): """Car...
Takes a list of supported mime-types and finds the best match for all the media- ranges listed in header. The value of header must be a string that conforms to the format of the HTTP Accept: header. The value of 'supported' is a list of mime-types. >>> best_match(['application/xbel+xml', 'text/xml'], 'text...
Chunked delete, which should be used if deleting many objects. The reason why this method is needed is that deleting a lot of Data objects requires Django to fetch all of them into memory (fast path is not used) and this causes huge memory usage (and possibly OOM). :param chunk_size: O...
Duplicate (make a copy) ``Data`` objects. :param contributor: Duplication user def duplicate(self, contributor=None): """Duplicate (make a copy) ``Data`` objects. :param contributor: Duplication user """ bundle = [ {'original': data, 'copy': data.duplicate(contribu...
Save basic:json values to a Storage collection. def save_storage(self, instance, schema): """Save basic:json values to a Storage collection.""" for field_schema, fields in iterate_fields(instance, schema): name = field_schema['name'] value = fields[name] if field_sch...
Retrieve handles for all basic:secret: fields on input. The process must have the ``secrets`` resource requirement specified in order to access any secrets. Otherwise this method will raise a ``PermissionDenied`` exception. :return: A dictionary of secrets where key is the secret handl...
Save data: and list:data: references as parents. def save_dependencies(self, instance, schema): """Save data: and list:data: references as parents.""" def add_dependency(value): """Add parent Data dependency.""" try: DataDependency.objects.update_or_create( ...
Create entity if `flow_collection` is defined in process. Following rules applies for adding `Data` object to `Entity`: * Only add `Data object` to `Entity` if process has defined `flow_collection` field * Add object to existing `Entity`, if all parents that are part of it (but ...
Save the data model. def save(self, render_name=False, *args, **kwargs): # pylint: disable=keyword-arg-before-vararg """Save the data model.""" if self.name != self._original_name: self.named_by_user = True create = self.pk is None if create: fill_with_defaults...
Delete the data model. def delete(self, *args, **kwargs): """Delete the data model.""" # Store ids in memory as relations are also deleted with the Data object. storage_ids = list(self.storages.values_list('pk', flat=True)) # pylint: disable=no-member super().delete(*args, **kwargs) ...
Duplicate (make a copy). def duplicate(self, contributor=None): """Duplicate (make a copy).""" if self.status not in [self.STATUS_DONE, self.STATUS_ERROR]: raise ValidationError('Data object must have done or error status to be duplicated') duplicate = Data.objects.get(id=self.id) ...
Render data name. The rendering is based on name template (`process.data_name`) and input context. def _render_name(self): """Render data name. The rendering is based on name template (`process.data_name`) and input context. """ if not self.process.data_name o...
Compose data location path. def get_path(self, prefix=None, filename=None): """Compose data location path.""" prefix = prefix or settings.FLOW_EXECUTOR['DATA_DIR'] path = os.path.join(prefix, self.subpath) if filename: path = os.path.join(path, filename) return pat...
Compose data runtime location path. def get_runtime_path(self, filename=None): """Compose data runtime location path.""" return self.get_path(prefix=settings.FLOW_EXECUTOR['RUNTIME_DIR'], filename=filename)
Return serialized list of data objects on entity that user has `view` permission on. def get_data(self, entity): """Return serialized list of data objects on entity that user has `view` permission on.""" data = self._filter_queryset('view_data', entity.data.all()) return self._serialize_data(d...
Validate process descriptor. def validate(self): """Validate process descriptor.""" required_fields = ('slug', 'name', 'process_type', 'version') for field in required_fields: if getattr(self.metadata, field, None) is None: raise ValidationError("process '{}' is miss...
Return process schema for this process. def to_schema(self): """Return process schema for this process.""" process_type = self.metadata.process_type if not process_type.endswith(':'): process_type = '{}:'.format(process_type) schema = { 'slug': self.metadata.slu...
Pull Docker images needed by processes after registering. def post_register_hook(self, verbosity=1): """Pull Docker images needed by processes after registering.""" if not getattr(settings, 'FLOW_DOCKER_DONT_PULL', False): call_command('list_docker_images', pull=True, verbosity=verbosity)
Resolve data path for use with the executor. :param data: Data object instance :param filename: Filename to resolve :return: Resolved filename, which can be used to access the given data file in programs executed using this executor def resolve_data_path(self, data=None, filename=N...
Resolve upload path for use with the executor. :param filename: Filename to resolve :return: Resolved filename, which can be used to access the given uploaded file in programs executed using this executor def resolve_upload_path(self, filename=None): """Resolve upload p...
Determine if two datetimes are equal with fuzz factor. A naive datetime (no timezone information) is assumed to be in in UTC. Args: a_dt: datetime Timestamp to compare. b_dt: datetime Timestamp to compare. round_sec: int or float Round the timestamps to the closest ...