code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
verbosity = int(options['verbosity']) skip_mapping = options['skip_mapping'] if self.has_filter(options): self.filter_indices(options, verbosity, skip_mapping=skip_mapping) else: # Process all indices. index_builder.delete(skip_mapping=skip_m...
def handle(self, *args, **options)
Command handle.
5.695999
5.675629
1.003589
f_dict = {} for f_pyxb in sorted(node_list_pyxb.node, key=lambda x: x.identifier.value()): f_dict[f_pyxb.identifier.value()] = { 'name': f_pyxb.name, 'description': f_pyxb.description, 'base_url': f_pyxb.baseURL, 'ping': f_pyxb.ping, 'repl...
def pyxb_to_dict(node_list_pyxb)
Returns: dict : Representation of ``node_list_pyxb``, keyed on the Node identifier (``urn:node:*``). Example:: { u'urn:node:ARCTIC': { 'base_url': u'https://arcticdata.io/metacat/d1/mn', 'description': u'The US National Science Foundation...', 'name': u'Arctic Data Center...
3.079989
2.425015
1.270091
user = request.user app_label = queryset.model._meta.app_label # pylint: disable=protected-access model_name = queryset.model._meta.model_name # pylint: disable=protected-access kwargs = {} if model_name == 'storage': model_name = 'data' kwarg...
def filter_queryset(self, request, queryset, view)
Filter permissions queryset.
2.738714
2.656805
1.03083
# admins can do anything if request.user.is_superuser: return True # `share` permission is required for editing permissions if 'permissions' in view.action: self.perms_map['POST'] = ['%(app_label)s.share_%(model_name)s'] if view.action in ['add_...
def has_object_permission(self, request, view, obj)
Check object permissions.
3.179271
3.148576
1.009749
# Handle complete certificate in vendor specific extension. if django.conf.settings.DEBUG_GMN: if 'HTTP_VENDOR_INCLUDE_CERTIFICATE' in request.META: request.META[ 'SSL_CLIENT_CERT' ] = self.pem_in_http_header_to_pem_in_string( ...
def get_active_subject_set(self, request)
Get a set containing all subjects for which the current connection has been successfully authenticated.
3.936894
3.888944
1.01233
level = logging.DEBUG if debug_bool else logging.INFO logging.config.dictConfig( { "version": 1, "disable_existing_loggers": False, "formatters": { "verbose": { "format": "%(asctime)s %(levelname)-8s %(name)s %(module)s " ...
def log_setup(debug_bool)
Set up logging. We output only to stdout. Instead of also writing to a log file, redirect stdout to a log file when the script is executed from cron.
1.440384
1.499286
0.960713
self.con = psycopg2.connect(dsn) self.cur = self.con.cursor(cursor_factory=psycopg2.extras.DictCursor) # autocommit: Disable automatic transactions self.con.set_isolation_level(psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT)
def connect(self, dsn)
Connect to DB. dbname: the database name user: user name used to authenticate password: password used to authenticate host: database host address (defaults to UNIX socket if not provided) port: connection port number (defaults to 5432 if not provided)
2.12963
2.329834
0.914069
value = self.request.query_params.get(key, None) if value is None: value = self.request.data.get(key, None) if value is None: value = default return value
def get_query_param(self, key, default=None)
Get query parameter uniformly for GET and POST requests.
2.206842
1.957006
1.127662
params = self.request.query_params.copy() params.update(self.request.data) return params
def get_query_params(self)
Get combined query parameters (GET and POST).
3.738419
2.646992
1.412327
ordering = self.get_query_param('ordering', self.ordering) if not ordering: return search sort_fields = [] for raw_ordering in ordering.split(','): ordering_field = raw_ordering.lstrip('-') if ordering_field not in self.ordering_fields: ...
def order_search(self, search)
Order given search by the ordering parameter given in request. :param search: ElasticSearch query object
2.521626
2.737368
0.921186
builder = QueryBuilder( self.filtering_fields, self.filtering_map, self ) search, unmatched = builder.build(search, self.get_query_params()) # Ensure that no unsupported arguments were used. for argument in self.get_always_allowed_arg...
def filter_search(self, search)
Filter given search by the filter parameter given in request. :param search: ElasticSearch query object
5.0752
5.096961
0.995731
user = self.request.user if user.is_superuser: return search if user.is_anonymous: user = get_anonymous_user() filters = [Q('match', users_with_permissions=user.pk)] filters.extend([ Q('match', groups_with_permissions=group.pk) for gr...
def filter_permissions(self, search)
Filter given query based on permissions of the user in the request. :param search: ElasticSearch query object
3.555476
3.547081
1.002367
page = self.paginate_queryset(queryset) if page is not None: serializer = self.get_serializer(page, many=True, **serializers_kwargs) return self.get_paginated_response(serializer.data) serializer = self.get_serializer(queryset, many=True, **serializers_kwargs) ...
def paginate_response(self, queryset, serializers_kwargs={})
Optionally return paginated response. If pagination parameters are provided in the request, then paginated response is returned, otherwise response is not paginated.
1.316286
1.423489
0.924689
search = self.document_class().search() # pylint: disable=not-callable search = self.custom_filter(search) search = self.filter_search(search) search = self.order_search(search) search = self.filter_permissions(search) if search.count() > ELASTICSEARCH_SIZE: ...
def search(self)
Handle the search request.
4.044342
3.903981
1.035953
if self.is_search_request(): search = self.search() page = self.paginate_queryset(search) if page is None: items = search else: items = page try: primary_keys = [] order_map_cas...
def list_with_post(self, request)
Endpoint handler.
3.384667
3.382282
1.000705
self._raise_error_if_os_special_file(path) # log.debug(u'getattr(): {0}'.format(path)) attribute = self._get_attributes_through_cache(path) # log.debug('getattr() returned attribute: {0}'.format(attribute)) return self._stat_from_attributes(attribute)
def getattr(self, path, fh)
Called by FUSE when the attributes for a file or directory are required. Returns a dictionary with keys identical to the stat C structure of stat(2). st_atime, st_mtime and st_ctime should be floats. On OSX, st_nlink should count all files inside the directory. On Linux, only the subdirectories...
5.963531
6.032504
0.988566
log.debug('readdir(): {}'.format(path)) try: dir = self._directory_cache[path] except KeyError: dir = self._get_directory(path) self._directory_cache[path] = dir return dir
def readdir(self, path, fh)
Called by FUSE when a directory is opened. Returns a list of file and directory names for the directory.
3.176583
3.197718
0.993391
log.debug('open(): {}'.format(path)) # ONEDrive is currently read only. Anything but read access is denied. if (flags & self._READ_ONLY_ACCESS_MODE) != os.O_RDONLY: self._raise_error_permission_denied(path) # Any file in the filesystem can be opened. attribut...
def open(self, path, flags)
Called by FUSE when a file is opened. Determines if the provided path and open flags are valid.
8.456601
8.42715
1.003495
text = text.strip() if not text.startswith(self.inline_tags[0]) or not text.endswith(self.inline_tags[1]): return return text[2:-2]
def get_inline_expression(self, text)
Extract an inline expression from the given text.
3.389164
3.123178
1.085165
entities = self.request.query_params.getlist('entity') labels = self.request.query_params.getlist('label') positions = self.request.query_params.getlist('position') if labels and len(labels) != len(entities): raise exceptions.ParseError( 'If `labels`...
def _filter_queryset(self, queryset)
Filter queryset by entity, label and position. Due to a bug in django-filter these filters have to be applied manually: https://github.com/carltongibson/django-filter/issues/883
2.155315
1.928514
1.117604
instance = self.get_object() if (not request.user.has_perm('edit_collection', instance.collection) and not request.user.is_superuser): return Response(status=status.HTTP_401_UNAUTHORIZED) return super().update(request, *args, **kwargs)
def update(self, request, *args, **kwargs)
Update the ``Relation`` object. Reject the update if user doesn't have ``EDIT`` permission on the collection referenced in the ``Relation``.
2.475155
2.202041
1.124028
# XXX: Optimize: rebuild only permissions, not whole document codename = perm.permission.codename if not codename.startswith('view') and not codename.startswith('owner'): return index_builder.build(perm.content_object)
def _process_permission(perm)
Rebuild indexes affected by the given permission.
12.133217
9.431508
1.286456
return requests_toolbelt.multipart.decoder.MultipartDecoder.from_response( response, encoding ).parts
def parse_response(response, encoding='utf-8')
Parse a multipart Requests.Response into a tuple of BodyPart objects. Args: response: Requests.Response encoding: The parser will assume that any text in the HTML body is encoded with this encoding when decoding it for use in the ``text`` attribute. Returns: tuple of BodyPar...
5.925808
10.876876
0.544808
return requests_toolbelt.multipart.decoder.MultipartDecoder( mmp_bytes, content_type, encoding ).parts
def parse_str(mmp_bytes, content_type, encoding='utf-8')
Parse multipart document bytes into a tuple of BodyPart objects. Args: mmp_bytes: bytes Multipart document. content_type : str Must be on the form, ``multipart/form-data; boundary=<BOUNDARY>``, where ``<BOUNDARY>`` is the string that separates the parts of the multipart documen...
4.189357
6.408604
0.653708
return '\n\n'.join( [ '{}\n\n{}'.format( str(p.headers[b'Content-Disposition'], p.encoding), p.text ) for p in sorted( body_part_tup, key=lambda p: p.headers[b'Content-Disposition'] ) ] )
def normalize(body_part_tup,)
Normalize a tuple of BodyPart objects to a string. Normalization is done by sorting the body_parts by the Content- Disposition headers, which is typically on the form, ``form-data; name="name_of_part``.
4.295881
3.872974
1.109194
return ( {k.lower(): v for k, v in header_dict.items()} .get('content-type', '') .startswith('multipart') )
def is_multipart(header_dict)
Args: header_dict : CaseInsensitiveDict Returns: bool: ``True`` if ``header_dict`` has a Content-Type key (case insensitive) with value that begins with 'multipart'.
3.104093
3.648156
0.850866
for i, e in enumerate(path): if e in self._resolvers or e == self._get_readme_filename(): return path[:i], path[i], path[i + 1 :] raise d1_onedrive.impl.onedrive_exceptions.PathException( 'Invalid folder: %s' % str(path) )
def _split_path_by_reserved_name(self, path)
Return: object_tree_path, resolver, controlled_path.
6.409908
5.562037
1.152439
wdef_folder = self._object_tree.get_source_tree_folder(object_tree_path) res = StringIO() if len(object_tree_path): folder_name = object_tree_path[-1] else: folder_name = 'root' header = 'ObjectTree Folder "{}"'.format(folder_name) res.wr...
def _generate_readme_text(self, object_tree_path)
Generate a human readable description of the folder in text format.
2.736607
2.610177
1.048437
if self.request and self.request.query_params.get('hydrate_data', False): serializer = DataSerializer(data, many=True, read_only=True) serializer.bind('data', self) return serializer.data else: return [d.id for d in data]
def _serialize_data(self, data)
Return serialized data or list of ids, depending on `hydrate_data` query param.
4.766722
2.77506
1.7177
user = self.request.user if self.request else AnonymousUser() return get_objects_for_user(user, perms, queryset)
def _filter_queryset(self, perms, queryset)
Filter object objects by permissions of user in request.
3.598575
3.145814
1.143925
data = self._filter_queryset('view_data', collection.data.all()) return self._serialize_data(data)
def get_data(self, collection)
Return serialized list of data objects on collection that user has `view` permission on.
12.378032
6.636828
1.865052
fields = super(CollectionSerializer, self).get_fields() if self.request.method == "GET": fields['data'] = serializers.SerializerMethodField() else: fields['data'] = serializers.PrimaryKeyRelatedField(many=True, read_only=True) return fields
def get_fields(self)
Dynamically adapt fields based on the current request.
2.834142
2.510787
1.128786
loaded_engines = {} for module_name_or_dict in engines: if not isinstance(module_name_or_dict, dict): module_name_or_dict = { class_key: module_name_or_dict } try: module_name = module_name_or_dict[class_key] engine_settings ...
def load_engines(manager, class_name, base_module, engines, class_key='ENGINE', engine_type='engine')
Load engines.
2.620135
2.60964
1.004022
return ( d1_common.type_conversions.is_pyxb_d1_type(sysmeta_pyxb) and d1_common.type_conversions.pyxb_get_type_name(sysmeta_pyxb) == 'SystemMetadata' )
def is_sysmeta_pyxb(sysmeta_pyxb)
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.
2.98429
3.79315
0.786758
if sysmeta_pyxb.accessPolicy is not None: sysmeta_pyxb.accessPolicy = d1_common.wrap.access_policy.get_normalized_pyxb( sysmeta_pyxb.accessPolicy ) if getattr(sysmeta_pyxb, 'mediaType', False): d1_common.xml.sort_value_list_pyxb(sysmeta_pyxb.mediaType.property_) if g...
def normalize_in_place(sysmeta_pyxb, reset_timestamps=False)
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...
2.047671
2.141237
0.956303
normalize_in_place(a_pyxb, ignore_timestamps) normalize_in_place(b_pyxb, ignore_timestamps) a_xml = d1_common.xml.serialize_to_xml_str(a_pyxb) b_xml = d1_common.xml.serialize_to_xml_str(b_pyxb) are_equivalent = d1_common.xml.are_equivalent(a_xml, b_xml) if not are_equivalent: logger...
def are_equivalent_pyxb(a_pyxb, b_pyxb, ignore_timestamps=False)
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...
2.000092
2.426992
0.824103
return are_equivalent_pyxb( d1_common.xml.deserialize(a_xml), d1_common.xml.deserialize(b_xml), ignore_timestamps, )
def are_equivalent_xml(a_xml, b_xml, ignore_timestamps=False)
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...
3.696553
4.685364
0.788958
if clear_replica: sysmeta_pyxb.replica = None if clear_serial_version: sysmeta_pyxb.serialVersion = None sysmeta_pyxb.replicationPolicy = None
def clear_elements(sysmeta_pyxb, clear_replica=True, clear_serial_version=True)
{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.
2.435217
2.586099
0.941657
invalid_element_set = set(el_list) - set(SYSMETA_ROOT_CHILD_LIST) if invalid_element_set: raise ValueError( 'Passed one or more invalid elements. invalid="{}"'.format( ', '.join(sorted(list(invalid_element_set))) ) ) for el_str in el_list: ...
def update_elements(dst_pyxb, src_pyxb, el_list)
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``.
3.650846
3.18325
1.146893
ctype = ContentType.objects.get_for_model(obj) # Camel case class names are converted into a space-separated # content types, so spaces have to be removed. ctype = str(ctype).replace(' ', '') return '{}_{}'.format(perm.lower(), ctype)
def get_full_perm(perm, obj)
Join action with the content type of ``obj``. Permission is returned in the format of ``<action>_<object_type>``.
8.038651
6.883451
1.167823
def _process_permission(codename, user_or_group, dest_obj, relabel): if relabel: codename = change_perm_ctype(codename, dest_obj) if codename not in dest_all_perms: return # dest object doesn't have matching permission assign_perm(codename, use...
def copy_permissions(src_obj, dest_obj)
Copy permissions form ``src_obj`` to ``dest_obj``.
2.371589
2.347772
1.010145
user_filter = {'pk': query} if query.isdigit() else {'username': query} user_model = get_user_model() try: return user_model.objects.get(**user_filter) except user_model.DoesNotExist: raise exceptions.ParseError("Unknown user: {}".format(query))
def fetch_user(query)
Get user by ``pk`` or ``username``. Raise error if it doesn't exist.
2.902919
2.415551
1.201763
group_filter = {'pk': query} if query.isdigit() else {'name': query} try: return Group.objects.get(**group_filter) except Group.DoesNotExist: raise exceptions.ParseError("Unknown group: {}".format(query))
def fetch_group(query)
Get group by ``pk`` or ``name``. Raise error if it doesn't exist.
3.672935
2.795885
1.313693
for entity_type in ['users', 'groups']: for perm_type in ['add', 'remove']: for perms in payload.get(entity_type, {}).get(perm_type, {}).values(): if 'owner' in perms: if entity_type == 'users' and allow_user_owner: continue ...
def check_owner_permission(payload, allow_user_owner)
Raise ``PermissionDenied``if ``owner`` found in ``data``.
3.298263
3.281872
1.004994
allowed_public_permissions = ['view', 'add', 'download'] for perm_type in ['add', 'remove']: for perm in payload.get('public', {}).get(perm_type, []): if perm not in allowed_public_permissions: raise exceptions.PermissionDenied("Permissions for public users are too open"...
def check_public_permissions(payload)
Raise ``PermissionDenied`` if public permissions are too open.
4.572969
3.483935
1.312587
for perm_type in ['add', 'remove']: user_pks = payload.get('users', {}).get(perm_type, {}).keys() if user_pk in user_pks: raise exceptions.PermissionDenied("You cannot change your own permissions")
def check_user_permissions(payload, user_pk)
Raise ``PermissionDenied`` if ``payload`` includes ``user_pk``.
4.063682
3.683167
1.103312
payload = copy.deepcopy(payload) for entity_type in ['users', 'groups']: for perm_type in ['add', 'remove']: for perms in payload.get(entity_type, {}).get(perm_type, {}).values(): if permission in perms: perms.remove(permission) for perm_type in...
def remove_permission(payload, permission)
Remove all occurrences of ``permission`` from ``payload``.
2.365107
2.249477
1.051403
full_permissions = get_all_perms(obj) def apply_perm(perm_func, perms, entity): if perms == 'ALL': perms = full_permissions for perm in perms: perm_codename = get_full_perm(perm, obj) if perm_codename not in full_permissions: rai...
def update_permission(obj, data)
Update object permissions.
2.393208
2.375218
1.007574
for permission in get_all_perms(obj): assign_perm(permission, contributor if contributor else obj.contributor, obj)
def assign_contributor_permissions(obj, contributor=None)
Assign all permissions to object's contributor.
4.445508
3.666224
1.212558
# 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), stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=su...
async def start(self)
Start process execution.
3.361089
2.99201
1.123355
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.stdin.close()
async def run_script(self, script)
Execute the script and save results.
3.61718
3.414995
1.059205
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().terminate()
async def terminate(self)
Terminate a running script.
3.105526
2.950332
1.052602
return await aioredis.create_redis( 'redis://{}:{}'.format( self._redis_params.get('host', 'localhost'), self._redis_params.get('port', 6379) ), db=int(self._redis_params.get('db', 1)) )
async def _make_connection(self)
Construct a connection to Redis.
2.54618
2.124205
1.198651
while True: try: if not self._redis: self._redis = await self._make_connection() return await meth(self._redis, *args, **kwargs) except aioredis.RedisError: logger.exception("Redis connection error") ...
async def _call_redis(self, meth, *args, **kwargs)
Perform a Redis call and handle connection dropping.
2.196123
2.055247
1.068545
conn = await self._make_connection() try: script = await conn.eval( script, keys=[], args=['*{}*'.format(settings.FLOW_MANAGER['REDIS_PREFIX'])], ) finally: conn.close()
async def clear_queue(self)
Reset the executor queue channel to an empty state.
10.321487
9.075373
1.137307
logger.info(__( "Terminating Resolwe listener on channel '{}'.", state.MANAGER_EXECUTOR_CHANNELS.queue )) self._should_stop = True
def terminate(self)
Stop the standalone manager.
28.294529
28.765574
0.983625
return '{}.{}'.format(state.MANAGER_EXECUTOR_CHANNELS.queue_response, obj[ExecutorProtocol.DATA_ID])
def _queue_response_channel(self, obj)
Generate the feedback channel name from the object's id. :param obj: The Channels message object.
33.01582
42.485188
0.777114
reply.update({ ExecutorProtocol.DATA_ID: obj[ExecutorProtocol.DATA_ID], }) await self._call_redis(aioredis.Redis.rpush, self._queue_response_channel(obj), json.dumps(reply))
async def _send_reply(self, obj, reply)
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).
8.786455
7.34905
1.195591
# JSON only has string dictionary keys, so the Data object id # needs to be stringified first. data_id = str(data_id) if filename not in exported_files_mapper[data_id]: raise KeyError("Use 're-export' to prepare the file for spawned process: {}".format(filename)) ...
def hydrate_spawned_files(self, exported_files_mapper, filename, data_id)
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` ...
5.257701
4.91357
1.070037
data_id = obj[ExecutorProtocol.DATA_ID] changeset = obj[ExecutorProtocol.UPDATE_CHANGESET] if not internal_call: logger.debug( __("Handling update for Data with id {} (handle_update).", data_id), extra={ 'data_id': data_id,...
def handle_update(self, obj, internal_call=False)
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` ...
2.598696
2.497374
1.040571
async_to_sync(consumer.send_event)({ WorkerProtocol.COMMAND: WorkerProtocol.ABORT, WorkerProtocol.DATA_ID: obj[ExecutorProtocol.DATA_ID], WorkerProtocol.FINISH_COMMUNICATE_EXTRA: { 'executor': getattr(settings, 'FLOW_EXECUTOR', {}).get('NAME', 'resolw...
def handle_abort(self, obj)
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...
7.798306
6.59364
1.182701
record_dict = json.loads(obj[ExecutorProtocol.LOG_MESSAGE]) record_dict['msg'] = record_dict['msg'] executors_dir = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'executors') record_dict['pathname'] = os.path.join(executors_dir, record_dict['pathname']) logg...
def handle_log(self, obj)
Handle an incoming log processing request. :param obj: The Channels message object. Command object format: .. code-block:: none { 'command': 'log', 'message': [log message] }
3.61716
4.011681
0.901657
snapshot = self._make_stats() try: serialized = json.dumps(snapshot) await self._call_redis(aioredis.Redis.set, state.MANAGER_LISTENER_STATS, serialized) await self._call_redis(aioredis.Redis.expire, state.MANAGER_LISTENER_STATS, 3600) except TypeErro...
async def push_stats(self)
Push current stats to Redis.
4.102798
3.807507
1.077555
if self.load_avg.intervals['1m'].value > 1: if self.last_load_level == 1 and time.time() - self.last_load_log < 30: return self.last_load_log = time.time() self.last_load_level = 1 logger.error( "Listener load limit exceede...
def check_critical_load(self)
Check for critical load and log an error if necessary.
2.74848
2.625992
1.046645
logger.info(__( "Starting Resolwe listener on channel '{}'.", state.MANAGER_EXECUTOR_CHANNELS.queue )) while not self._should_stop: await self.push_stats() ret = await self._call_redis(aioredis.Redis.blpop, state.MANAGER_EXECUTOR_CHANNELS....
async def run(self)
Run the main listener run loop. Doesn't return until :meth:`terminate` is called.
4.270711
4.236551
1.008063
return int( self.dokanDLL.DokanMain( PDOKAN_OPTIONS(dokanOptions), PDOKAN_OPERATIONS(dokanOperations) ) )
def dokanMain(self, dokanOptions, dokanOperations)
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
6.957452
5.436053
1.279872
return self.operations('createFile', fileName)
def createFile( self, fileName, desiredAccess, shareMode, creationDisposition, flagsAndAttributes, dokanFileInfo, )
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: ...
48.674286
63.264633
0.769376
try: ret = self.operations('readFile', fileName, numberOfBytesToRead, offset) data = ctypes.create_string_buffer( ret[:numberOfBytesToRead], numberOfBytesToRead ) ctypes.memmove(buffer, data, numberOfBytesToRead) sizeRead = cty...
def readFile( self, fileName, buffer, numberOfBytesToRead, numberOfBytesRead, offset, dokanFileInfo, )
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...
3.31644
3.222758
1.029069
return self.operations( 'writeFile', fileName, buffer, numberOfBytesToWrite, offset )
def writeFile( self, fileName, buffer, numberOfBytesToWrite, numberOfBytesWritten, offset, dokanFileInfo, )
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...
8.242364
11.401729
0.722905
try: ret = self.operations('findFilesWithPattern', fileName, searchPattern) if ret is None: return d1_onedrive.impl.drivers.dokan.const.DOKAN_ERROR for r in ret: create_ft = self.python_timestamp_to_win32_filetime(r['ctime']) ...
def findFilesWithPattern( self, fileName, searchPattern, fillFindData, dokanFileInfo )
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 ...
2.736686
2.729039
1.002802
return self.operations('setFileTime', fileName)
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 creationTime: ctypes.POINTER(ctypes.wintypes.FILETIME) :param lastAccessTime: last access time of file :type...
29.369759
49.736423
0.590508
return self.operations('moveFile', existingFileName, newFileName)
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 replaceExisting: flag to indicate replacement of existing file :type replaceExisting: ctype...
14.567891
21.574448
0.675238
return self.operations('lockFile', fileName, byteOffset, length)
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 :type length: ctypes.c_longlong :param dokanFileInfo: used by ...
9.922773
16.914179
0.586654
return self.operations('unlockFile', fileName, byteOffset, length)
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 unlock :type length: ctypes.c_longlong :param dokanFileInfo: ...
9.70822
16.57312
0.585781
ret = self.operations('getDiskFreeSpace') ctypes.memmove( freeBytesAvailable, ctypes.byref(ctypes.c_longlong(ret['freeBytesAvailable'])), ctypes.sizeof(ctypes.c_longlong), ) ctypes.memmove( totalNumberOfBytes, ctypes.by...
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.c_void_p :param totalNumberOfBytes: pointer for total number of bytes :type totalNumberOfBytes: ctypes.c_void_p :param totalNumberOfFreeBytes...
2.162067
2.043266
1.058143
ret = self.operations('getVolumeInformation') # populate volume name buffer ctypes.memmove( volumeNameBuffer, ret['volumeNameBuffer'], min( ctypes.sizeof(ctypes.c_wchar) * len(ret['volumeNameBuffer']), volumeNameSize, ...
def getVolumeInformation( self, volumeNameBuffer, volumeNameSize, volumeSerialNumber, maximumComponentLength, fileSystemFlags, fileSystemNameBuffer, fileSystemNameSize, dokanFileInfo, )
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 ...
2.113305
2.074207
1.01885
return self.operations('getFileSecurity', fileName)
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 fileName: ctypes.c_wchar_p :param securityInformation: buffer for security information :type securityInformation: PSECURITY_INFORMATION :param securityDescriptor: buffer for security descr...
52.680546
63.514393
0.829427
return self.operations('setFileSecurity', fileName)
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_wchar_p :param securityInformation: new security information :type securityInformation: PSECURITY_INFORMATION :param securityDescriptor: newsecurity descriptor :...
37.407001
49.900669
0.749629
ore = ResourceMap() ore.initialize(ore_pid) ore.addMetadataDocument(sci_meta_pid) ore.addDataDocuments(data_pids, sci_meta_pid) return ore
def createSimpleResourceMap(ore_pid, sci_meta_pid, data_pids)
Create a simple resource map with one metadata document and n data objects.
3.301754
2.80907
1.175391
pids = [] for line in in_stream: pid = line.strip() if len(pid) > 0: if not pid.startswith("# "): pids.append(pid) if (len(pids)) < 2: raise ValueError("Insufficient identifiers provided.") logging.info("Read %d identifiers", len(pids)) 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
3.603657
3.291238
1.094924
queue = 'ordinary' if data.process.scheduling_class == Process.SCHEDULING_CLASS_INTERACTIVE: queue = 'hipri' logger.debug(__( "Connector '{}' running for Data with id {} ({}) in celery queue {}, EAGER is {}.", self.__class__.__module__, d...
def submit(self, data, runtime_dir, argv)
Run process. For details, see :meth:`~resolwe.flow.managers.workload_connectors.base.BaseConnector.submit`.
8.698898
7.75761
1.121337
if self._source_tree.cache_is_stale(): self._source_tree.refresh() logging.info('Refreshing object tree') self._init_cache() self.sync_cache_with_source_tree()
def refresh(self)
Synchronize the local tree of Solr records for DataONE identifiers and queries with the reference tree.
7.421217
6.282501
1.181252
try: return self._cache['records'][pid] except KeyError: raise d1_onedrive.impl.onedrive_exceptions.ONEDriveException('Unknown PID')
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.
7.150622
7.245816
0.986862
try: return self._cache['records'][pid] except KeyError: return self._get_uncached_object_record(pid)
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 object tree caching system to be used for objects ...
5.146068
5.291202
0.972571
try: record = self._solr_client.get_solr_record(pid) except d1_onedrive.impl.onedrive_exceptions.ONEDriveException: pass else: self._create_cache_item(cache_folder, record)
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.
4.526077
3.86514
1.171
parents_statuses = set( DataDependency.objects.filter( child=data, kind=DataDependency.KIND_IO ).distinct('parent__status').values_list('parent__status', flat=True) ) if not parents_statuses: return Data.STATUS_DONE if None in parents_statuses: # Some p...
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
3.33307
3.046854
1.093938
if executor is None: executor = getattr(settings, 'FLOW_EXECUTOR', {}).get('NAME', 'resolwe.flow.executors.local') self.executor = self.load_executor(executor) logger.info( __("Loaded '{}' executor.", str(self.executor.__class__.__module__).replace('.prepare', ''...
def discover_engines(self, executor=None)
Discover configured engines. :param executor: Optional executor module override
2.325356
2.420614
0.960647
if not keep_state: self.state = state.ManagerState(state.MANAGER_STATE_PREFIX) self.state.reset() async_to_sync(consumer.run_consumer)(timeout=1) async_to_sync(self.sync_counter.reset)()
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``.
7.479649
6.70958
1.114772
result = {} for key in dir(settings): if any(map(key.startswith, ['FLOW_', 'RESOLWE_', 'CELERY_'])): result[key] = getattr(settings, key) return result
def _marshal_settings(self)
Marshal Django settings into a serializable object. :return: The serialized settings. :rtype: dict
6.014287
5.75128
1.04573
env_vars = { 'RESOLWE_HOST_URL': self.settings_actual.get('RESOLWE_HOST_URL', 'localhost'), } set_env = self.settings_actual.get('FLOW_EXECUTOR', {}).get('SET_ENV', {}) env_vars.update(executor_vars) env_vars.update(set_env) export_commands = ['expo...
def _include_environment_variables(self, program, executor_vars)
Define environment variables.
3.490884
3.365532
1.037246
process_scheduling = self.scheduling_class_map[data.process.scheduling_class] if 'DISPATCHER_MAPPING' in getattr(settings, 'FLOW_MANAGER', {}): class_name = settings.FLOW_MANAGER['DISPATCHER_MAPPING'][process_scheduling] else: class_name = getattr(settings, 'FLOW...
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 used to spawn the executor.
5.713051
5.099693
1.120274
# Use Django settings here, because the state must be preserved # across events. This also implies the directory settings can't # be patched outside the manager and then just sent along in the # command packets. result = self.settings_actual.get('FLOW_EXECUTOR', {}).get(...
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`` is ``1``. :param dir_base: The base path to be ext...
19.207922
17.591778
1.091869
logger.debug(__("Preparing data directory for Data with id {}.", data.id)) with transaction.atomic(): # Create a temporary random location and then override it with data # location id since object has to be created first. # TODO Find a better solution, e.g. ...
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
5.658733
5.222428
1.083545
files = {} secrets = {} settings_dict = {} settings_dict['DATA_DIR'] = data_dir settings_dict['REDIS_CHANNEL_PAIR'] = state.MANAGER_EXECUTOR_CHANNELS files[ExecutorFiles.EXECUTOR_SETTINGS] = settings_dict django_settings = {} django_settings.upd...
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 they need to be serialized into the runtime directory. :param data...
3.247531
3.199941
1.014872
logger.debug(__("Preparing executor for Data with id {}", data.id)) # Both of these imports are here only to get the packages' paths. import resolwe.flow.executors as executor_package exec_dir = os.path.dirname(inspect.getsourcefile(executor_package)) dest_dir = self._...
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 object. :return: Tuple containing the relative ...
5.787036
5.011146
1.154833
script_name = ExecutorFiles.PROCESS_SCRIPT dest_file = os.path.join(dest_dir, script_name) with open(dest_file, 'wt') as dest_file_obj: dest_file_obj.write(program) os.chmod(dest_file, 0o700) return script_name
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
3.02877
3.209413
0.943715
cmd = message[WorkerProtocol.COMMAND] logger.debug(__("Manager worker got channel command '{}'.", cmd)) # Prepare settings for use; Django overlaid by state overlaid by # anything immediate in the current packet. immediates = {} if cmd == WorkerProtocol.COMMUNIC...
async def handle_control_event(self, message)
Handle an event from the Channels layer. Channels layer callback, do not call directly.
5.016273
4.942787
1.014867
if not isinstance(self.sync_counter, self._SynchronizationManager): self.sync_counter = self._SynchronizationManager()
def _ensure_counter(self)
Ensure the sync counter is a valid non-dummy object.
8.311042
4.515926
1.840385
async def _barrier(): async with self.sync_counter: pass await consumer.exit_consumer() self._ensure_counter() await asyncio.wait([ _barrier(), consumer.run_consumer(), ]) self.sync_counter = s...
async def execution_barrier(self)
Wait for executors to finish. At least one must finish after this point to avoid a deadlock.
12.741597
11.878089
1.072698
executor = getattr(settings, 'FLOW_EXECUTOR', {}).get('NAME', 'resolwe.flow.executors.local') logger.debug(__( "Manager sending communicate command on '{}' triggered by Data with id {}.", state.MANAGER_CONTROL_CHANNEL, data_id, )) saved_setti...
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 processes. If it is not given, all resolving objects are processed. :para...
4.921134
4.784087
1.028646