Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
# (model name, mask, search filter)
searchTable = (
('folder', parentType in ('user', 'collection', 'folder'), {
'name': token,
'parentId': parent['_id'],
'parentCollection': parentType
}),
('item', parentType == 'folder', {'name': token, 'folderId': parent['_id']}),
('file', parentType == 'item', {'name': token, 'itemId': parent['_id']}),
)
for candidateModel, mask, filterObject in searchTable:
if not mask:
continue
candidateChild = ModelImporter.model(candidateModel).findOne(filterObject)
if candidateChild is not None:
return candidateChild, candidateModel
# if no folder, item, or file matches, give up
raise NotFoundException('Child resource not found: %s(%s)->%s' % (
parentType, parent.get('name', parent.get('_id')), token))
resource = ModelImporter.model(model).load(id=resource, force=True)
except ImportError:
return None, None
if model == 'file':
model = 'item'
resource = Item().load(id=resource['itemId'], force=True)
if model in ('folder', 'item'):
if ('baseParentType' not in resource
or 'baseParentId' not in resource):
resource = ModelImporter.model(model).load(id=resource['_id'], force=True)
if ('baseParentType' not in resource
or 'baseParentId' not in resource):
return None, None
model = resource['baseParentType']
resourceId = resource['baseParentId']
resource = ModelImporter.model(model).load(id=resourceId, force=True)
if model in ('user', 'collection') and resource:
# Ensure the base resource has a quota field so we can use the
# default quota if appropriate
if QUOTA_FIELD not in resource:
resource[QUOTA_FIELD] = {}
if not resource or QUOTA_FIELD not in resource:
return None, None
return model, resource
job = event.info
if job['handler'] == 'worker_handler':
task = job.get('celeryTaskName', 'girder_worker.run')
# Set the job status to queued
ModelImporter.model('job', 'jobs').updateJob(job, status=JobStatus.QUEUED)
# Send the task to celery
asyncResult = getCeleryApp().send_task(
task, job['args'], job['kwargs'], queue=job.get('celeryQueue'), headers={
'jobInfoSpec': jobInfoSpec(job, job.get('token', None)),
'apiUrl': getWorkerApiUrl()
})
# Record the task ID from celery.
ModelImporter.model('job', 'jobs').updateJob(job, otherFields={
'celeryTaskId': asyncResult.task_id
})
# Stop event propagation since we have taken care of scheduling.
event.stopPropagation()
def run(job):
job_model = ModelImporter.model('job', 'jobs')
job_model.updateJob(job, status=JobStatus.RUNNING)
try:
kwargs = job['kwargs']
# TODO better to create a job token rather than a user token?
token = kwargs['token']
datasetId = str(kwargs['dataset']['_id'])
# connect to girder and upload the file
# TODO will probably have to change this from local to girder worker
# so that can work on worker machine
# at least need host connection info
girderPort = config.getConfig()['server.socket_port']
client = girder_client.GirderClient(port=girderPort)
client.token = token['_id']
def findNamedCollection(currentUser, name, create=False):
collections = \
[ModelImporter.model('collection').filter(c, currentUser) for c in
ModelImporter.model('collection').textSearch(name, user=currentUser)]
# collections should have len of 0 or 1, since we are looking
# for a collection with a certain name
if len(collections) == 0:
if create:
return ModelImporter.model('collection').createCollection(
name, description='', public=True, creator=currentUser)
else:
return None
else:
return collections[0]
identifier = reference['identifier']
except (ValueError, TypeError):
logger.warning('Failed to parse data.process reference: %r', reference)
if identifier is not None and identifier.endswith('AnnotationFile'):
if 'userId' not in reference or 'itemId' not in reference:
logger.error('Annotation reference does not contain required information.')
return
userId = reference['userId']
imageId = reference['itemId']
# load model classes
Item = ModelImporter.model('item')
File = ModelImporter.model('file')
User = ModelImporter.model('user')
Annotation = ModelImporter.model('annotation', plugin='large_image')
# load models from the database
user = User.load(userId, force=True)
image = File.load(imageId, level=AccessType.READ, user=user)
item = Item.load(image['itemId'], level=AccessType.READ, user=user)
file = File.load(
info.get('file', {}).get('_id'),
level=AccessType.READ, user=user
)
if not (item and user and file):
logger.error('Could not load models from the database')
return
try:
data = json.loads(b''.join(File.download(file)()).decode('utf8'))
def findNamedCollection(currentUser, name, create=False):
collections = \
[ModelImporter.model('collection').filter(c, currentUser) for c in
ModelImporter.model('collection').textSearch(name, user=currentUser)]
# collections should have len of 0 or 1, since we are looking
# for a collection with a certain name
if len(collections) == 0:
if create:
return ModelImporter.model('collection').createCollection(
name, description='', public=True, creator=currentUser)
else:
return None
else:
return collections[0]
def patch_access(self, sharer, simulation, users, groups,
level=AccessType.READ, flags=[]):
access_list = simulation.get('access', {'groups': [], 'users': []})
new_users = merge_access(access_list['users'], users, level, flags)
new_groups = merge_access(access_list['groups'], groups, level, flags)
# Share the simulation folder
simulation_folder = ModelImporter.model('folder').load(
simulation['folderId'], user=sharer)
share_folder(sharer, simulation_folder, new_users, new_groups)
# Set access on project if just this simulation is being shared
# print('gets here!', simulation)
project = ModelImporter.model('project', 'hpccloud').load(
simulation['projectId'], user=sharer)
new_proj_users = _not_in_filter(new_users,
project['access']['users'])
new_proj_groups = _not_in_filter(new_groups,
project['access']['groups'])
# print('gets here', new_proj_users, new_proj_groups)
if len(new_proj_users) or len(new_proj_groups):
ModelImporter.model('project', 'hpccloud').patch_access(
sharer, project, new_proj_users, new_proj_groups, single=True)
def _filter(self, model, resource):
"""
Filter a resource to include only the ordinary data and the quota
field.
:param model: the type of resource (e.g., user or collection)
:param resource: the resource document.
:returns: filtered field of the resource with the quota data, if any.
"""
filtered = ModelImporter.model(model).filter(resource, self.getCurrentUser())
filtered[QUOTA_FIELD] = resource.get(QUOTA_FIELD, {})
return filtered
def _save_group_girder(self, group_id, result):
from girder.utility.model_importer import ModelImporter
from girder.api.rest import getCurrentUser
from girder.constants import AccessType
folder = ModelImporter.model('folder').load(
id=self._parent_id, user=getCurrentUser(), level=AccessType.WRITE)
item_model = ModelImporter.model('item')
item = item_model.createItem(group_id, getCurrentUser(),
folder)
item_model.setMetadata(item, self._group_meta(result))
return result