idx int64 0 63k | question stringlengths 53 5.28k | target stringlengths 5 805 |
|---|---|---|
45,200 | def terminate ( self ) : logger . info ( __ ( "Terminating Resolwe listener on channel '{}'." , state . MANAGER_EXECUTOR_CHANNELS . queue ) ) self . _should_stop = True | Stop the standalone manager . |
45,201 | def _queue_response_channel ( self , obj ) : return '{}.{}' . format ( state . MANAGER_EXECUTOR_CHANNELS . queue_response , obj [ ExecutorProtocol . DATA_ID ] ) | Generate the feedback channel name from the object s id . |
45,202 | async def _send_reply ( self , obj , reply ) : reply . update ( { ExecutorProtocol . DATA_ID : obj [ ExecutorProtocol . DATA_ID ] , } ) await self . _call_redis ( aioredis . Redis . rpush , self . _queue_response_channel ( obj ) , json . dumps ( reply ) ) | Send a reply with added standard fields back to executor . |
45,203 | def hydrate_spawned_files ( self , exported_files_mapper , filename , data_id ) : 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 ) ) export_fn = exported_files_mapper [ data_id ] . pop ( filename ) if exported_files_mapper [ data_id ] == { } : exported_files_mapper . pop ( data_id ) return { 'file_temp' : export_fn , 'file' : filename } | Pop the given file s map from the exported files mapping . |
45,204 | def handle_abort ( self , obj ) : 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' , 'resolwe.flow.executors.local' ) , } , } ) | Handle an incoming Data abort processing request . |
45,205 | def handle_log ( self , obj ) : 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' ] ) logger . handle ( logging . makeLogRecord ( record_dict ) ) | Handle an incoming log processing request . |
45,206 | async def push_stats ( self ) : 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 TypeError : logger . error ( __ ( "Listener can't serialize statistics:\n\n{}" , traceback . format_exc ( ) ) ) except aioredis . RedisError : logger . error ( __ ( "Listener can't store updated statistics:\n\n{}" , traceback . format_exc ( ) ) ) | Push current stats to Redis . |
45,207 | def check_critical_load ( self ) : 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 exceeded, the system can't handle this!" , extra = self . _make_stats ( ) ) elif self . load_avg . intervals [ '1m' ] . value > 0.8 : if self . last_load_level == 0.8 and time . time ( ) - self . last_load_log < 30 : return self . last_load_log = time . time ( ) self . last_load_level = 0.8 logger . warning ( "Listener load approaching critical!" , extra = self . _make_stats ( ) ) else : self . last_load_log = - math . inf self . last_load_level = 0 | Check for critical load and log an error if necessary . |
45,208 | async def run ( self ) : 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 . queue , timeout = 1 ) if ret is None : self . load_avg . add ( 0 ) continue remaining = await self . _call_redis ( aioredis . Redis . llen , state . MANAGER_EXECUTOR_CHANNELS . queue ) self . load_avg . add ( remaining + 1 ) self . check_critical_load ( ) _ , item = ret try : item = item . decode ( 'utf-8' ) logger . debug ( __ ( "Got command from executor: {}" , item ) ) obj = json . loads ( item ) except json . JSONDecodeError : logger . error ( __ ( "Undecodable command packet:\n\n{}" ) , traceback . format_exc ( ) ) continue command = obj . get ( ExecutorProtocol . COMMAND , None ) if command is None : continue service_start = time . perf_counter ( ) handler = getattr ( self , 'handle_' + command , None ) if handler : try : with PrioritizedBatcher . global_instance ( ) : await database_sync_to_async ( handler ) ( obj ) except Exception : logger . error ( __ ( "Executor command handling error:\n\n{}" , traceback . format_exc ( ) ) ) else : logger . error ( __ ( "Unknown executor command '{}'." , command ) , extra = { 'decoded_packet' : obj } ) service_end = time . perf_counter ( ) self . service_time . update ( service_end - service_start ) logger . info ( __ ( "Stopping Resolwe listener on channel '{}'." , state . MANAGER_EXECUTOR_CHANNELS . queue ) ) | Run the main listener run loop . |
45,209 | def dokanMain ( self , dokanOptions , dokanOperations ) : return int ( self . dokanDLL . DokanMain ( PDOKAN_OPTIONS ( dokanOptions ) , PDOKAN_OPERATIONS ( dokanOperations ) ) ) | Issue callback to start dokan drive . |
45,210 | def findFilesWithPattern ( self , fileName , searchPattern , fillFindData , dokanFileInfo ) : 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' ] ) last_access_ft = self . python_timestamp_to_win32_filetime ( r [ 'atime' ] ) last_write_ft = self . python_timestamp_to_win32_filetime ( r [ 'wtime' ] ) cft = ctypes . wintypes . FILETIME ( create_ft [ 0 ] , create_ft [ 1 ] ) laft = ctypes . wintypes . FILETIME ( last_access_ft [ 0 ] , last_access_ft [ 1 ] ) lwft = ctypes . wintypes . FILETIME ( last_write_ft [ 0 ] , last_write_ft [ 1 ] ) size = self . pyint_to_double_dwords ( r [ 'size' ] ) File = ctypes . wintypes . WIN32_FIND_DATAW ( ctypes . c_ulong ( r [ 'attr' ] ) , cft , laft , lwft , size [ 1 ] , size [ 0 ] , ctypes . c_ulong ( 0 ) , ctypes . c_ulong ( 0 ) , r [ 'name' ] , '' , ) pFile = ctypes . wintypes . PWIN32_FIND_DATAW ( File ) fillFindData ( pFile , dokanFileInfo ) return d1_onedrive . impl . drivers . dokan . const . DOKAN_SUCCESS except Exception as e : logging . error ( '%s' , e ) return d1_onedrive . impl . drivers . dokan . const . DOKAN_ERROR | Find files in a certain path that match the search pattern . |
45,211 | def setFileTime ( self , fileName , creationTime , lastAccessTime , lastWriteTime , dokanFileInfo ) : return self . operations ( 'setFileTime' , fileName ) | Set time values for a file . |
45,212 | def lockFile ( self , fileName , byteOffset , length , dokanFileInfo ) : return self . operations ( 'lockFile' , fileName , byteOffset , length ) | Lock a file . |
45,213 | def unlockFile ( self , fileName , byteOffset , length , dokanFileInfo ) : return self . operations ( 'unlockFile' , fileName , byteOffset , length ) | Unlock a file . |
45,214 | def getDiskFreeSpace ( self , freeBytesAvailable , totalNumberOfBytes , totalNumberOfFreeBytes , dokanFileInfo , ) : ret = self . operations ( 'getDiskFreeSpace' ) ctypes . memmove ( freeBytesAvailable , ctypes . byref ( ctypes . c_longlong ( ret [ 'freeBytesAvailable' ] ) ) , ctypes . sizeof ( ctypes . c_longlong ) , ) ctypes . memmove ( totalNumberOfBytes , ctypes . byref ( ctypes . c_longlong ( ret [ 'totalNumberOfBytes' ] ) ) , ctypes . sizeof ( ctypes . c_longlong ) , ) ctypes . memmove ( totalNumberOfFreeBytes , ctypes . byref ( ctypes . c_longlong ( ret [ 'totalNumberOfFreeBytes' ] ) ) , ctypes . sizeof ( ctypes . c_longlong ) , ) return d1_onedrive . impl . drivers . dokan . const . DOKAN_SUCCESS | Get the amount of free space on this volume . |
45,215 | def getVolumeInformation ( self , volumeNameBuffer , volumeNameSize , volumeSerialNumber , maximumComponentLength , fileSystemFlags , fileSystemNameBuffer , fileSystemNameSize , dokanFileInfo , ) : ret = self . operations ( 'getVolumeInformation' ) ctypes . memmove ( volumeNameBuffer , ret [ 'volumeNameBuffer' ] , min ( ctypes . sizeof ( ctypes . c_wchar ) * len ( ret [ 'volumeNameBuffer' ] ) , volumeNameSize , ) , ) serialNum = ctypes . c_ulong ( self . serialNumber ) ctypes . memmove ( volumeSerialNumber , ctypes . byref ( serialNum ) , ctypes . sizeof ( ctypes . c_ulong ) ) maxCompLen = ctypes . c_ulong ( ret [ 'maximumComponentLength' ] ) ctypes . memmove ( maximumComponentLength , ctypes . byref ( maxCompLen ) , ctypes . sizeof ( ctypes . c_ulong ) , ) fsFlags = ctypes . c_ulong ( ret [ 'fileSystemFlags' ] ) ctypes . memmove ( fileSystemFlags , ctypes . byref ( fsFlags ) , ctypes . sizeof ( ctypes . c_ulong ) ) ctypes . memmove ( fileSystemNameBuffer , ret [ 'fileSystemNameBuffer' ] , min ( ctypes . sizeof ( ctypes . c_wchar ) * len ( ret [ 'fileSystemNameBuffer' ] ) , fileSystemNameSize , ) , ) return d1_onedrive . impl . drivers . dokan . const . DOKAN_SUCCESS | Get information about the volume . |
45,216 | def getFileSecurity ( self , fileName , securityInformation , securityDescriptor , lengthSecurityDescriptorBuffer , lengthNeeded , dokanFileInfo , ) : return self . operations ( 'getFileSecurity' , fileName ) | Get security attributes of a file . |
45,217 | def setFileSecurity ( self , fileName , securityInformation , securityDescriptor , lengthSecurityDescriptorBuffer , dokanFileInfo , ) : return self . operations ( 'setFileSecurity' , fileName ) | Set security attributes of a file . |
45,218 | def createSimpleResourceMap ( ore_pid , sci_meta_pid , data_pids ) : ore = ResourceMap ( ) ore . initialize ( ore_pid ) ore . addMetadataDocument ( sci_meta_pid ) ore . addDataDocuments ( data_pids , sci_meta_pid ) return ore | Create a simple resource map with one metadata document and n data objects . |
45,219 | def pids2ore ( in_stream , fmt = 'xml' , base_url = 'https://cn.dataone.org/cn' ) : 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 = ResourceMap ( base_url = base_url ) logging . info ( "ORE PID = %s" , pids [ 0 ] ) ore . initialize ( pids [ 0 ] ) logging . info ( "Metadata PID = %s" , pids [ 1 ] ) ore . addMetadataDocument ( pids [ 1 ] ) ore . addDataDocuments ( pids [ 2 : ] , pids [ 1 ] ) return ore . serialize_to_display ( doc_format = fmt ) | read pids from in_stream and generate a resource map . |
45,220 | def submit ( self , data , runtime_dir , argv ) : 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__ , data . id , repr ( argv ) , queue , getattr ( settings , 'CELERY_ALWAYS_EAGER' , None ) ) ) celery_run . apply_async ( ( data . id , runtime_dir , argv ) , queue = queue ) | Run process . |
45,221 | def refresh ( self ) : 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 ( ) | Synchronize the local tree of Solr records for DataONE identifiers and queries with the reference tree . |
45,222 | def get_object_record ( self , pid ) : try : return self . _cache [ 'records' ] [ pid ] except KeyError : raise d1_onedrive . impl . onedrive_exceptions . ONEDriveException ( 'Unknown PID' ) | Get an object that has already been cached in the object tree . |
45,223 | def get_object_record_with_sync ( self , pid ) : try : return self . _cache [ 'records' ] [ pid ] except KeyError : return self . _get_uncached_object_record ( pid ) | Get an object that may not currently be in the cache . |
45,224 | def dependency_status ( data ) : 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 : return Data . STATUS_ERROR if Data . STATUS_ERROR in parents_statuses : return Data . STATUS_ERROR if len ( parents_statuses ) == 1 and Data . STATUS_DONE in parents_statuses : return Data . STATUS_DONE return None | Return abstracted status of dependencies . |
45,225 | def discover_engines ( self , executor = None ) : 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' , '' ) ) ) expression_engines = getattr ( settings , 'FLOW_EXPRESSION_ENGINES' , [ 'resolwe.flow.expression_engines.jinja' ] ) self . expression_engines = self . load_expression_engines ( expression_engines ) logger . info ( __ ( "Found {} expression engines: {}" , len ( self . expression_engines ) , ', ' . join ( self . expression_engines . keys ( ) ) ) ) execution_engines = getattr ( settings , 'FLOW_EXECUTION_ENGINES' , [ 'resolwe.flow.execution_engines.bash' ] ) self . execution_engines = self . load_execution_engines ( execution_engines ) logger . info ( __ ( "Found {} execution engines: {}" , len ( self . execution_engines ) , ', ' . join ( self . execution_engines . keys ( ) ) ) ) | Discover configured engines . |
45,226 | def reset ( self , keep_state = False ) : 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 ) ( ) | Reset the shared state and drain Django Channels . |
45,227 | def _marshal_settings ( self ) : result = { } for key in dir ( settings ) : if any ( map ( key . startswith , [ 'FLOW_' , 'RESOLWE_' , 'CELERY_' ] ) ) : result [ key ] = getattr ( settings , key ) return result | Marshal Django settings into a serializable object . |
45,228 | def _include_environment_variables ( self , program , executor_vars ) : 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 = [ 'export {}={}' . format ( key , shlex . quote ( value ) ) for key , value in env_vars . items ( ) ] return os . linesep . join ( export_commands ) + os . linesep + program | Define environment variables . |
45,229 | def run ( self , data , runtime_dir , argv ) : 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_MANAGER' , { } ) . get ( 'NAME' , DEFAULT_CONNECTOR ) data . scheduled = now ( ) data . save ( update_fields = [ 'scheduled' ] ) async_to_sync ( self . sync_counter . inc ) ( 'executor' ) return self . connectors [ class_name ] . submit ( data , runtime_dir , argv ) | Select a concrete connector and run the process through it . |
45,230 | def _get_per_data_dir ( self , dir_base , subpath ) : result = self . settings_actual . get ( 'FLOW_EXECUTOR' , { } ) . get ( dir_base , '' ) return os . path . join ( result , subpath ) | Extend the given base directory with a per - data component . |
45,231 | def _prepare_data_dir ( self , data ) : logger . debug ( __ ( "Preparing data directory for Data with id {}." , data . id ) ) with transaction . atomic ( ) : temporary_location_string = uuid . uuid4 ( ) . hex [ : 10 ] data_location = DataLocation . objects . create ( subpath = temporary_location_string ) data_location . subpath = str ( data_location . id ) data_location . save ( ) data_location . data . add ( data ) output_path = self . _get_per_data_dir ( 'DATA_DIR' , data_location . subpath ) dir_mode = self . settings_actual . get ( 'FLOW_EXECUTOR' , { } ) . get ( 'DATA_DIR_MODE' , 0o755 ) os . mkdir ( output_path , mode = dir_mode ) os . chmod ( output_path , dir_mode ) return output_path | Prepare destination directory where the data will live . |
45,232 | def _prepare_context ( self , data_id , data_dir , runtime_dir , ** kwargs ) : 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 . update ( self . settings_actual ) django_settings . update ( kwargs ) files [ ExecutorFiles . DJANGO_SETTINGS ] = django_settings files [ ExecutorFiles . PROCESS_META ] = { k : getattr ( Process , k ) for k in dir ( Process ) if k . startswith ( 'SCHEDULING_CLASS_' ) and isinstance ( getattr ( Process , k ) , str ) } files [ ExecutorFiles . DATA_META ] = { k : getattr ( Data , k ) for k in dir ( Data ) if k . startswith ( 'STATUS_' ) and isinstance ( getattr ( Data , k ) , str ) } self . executor . extend_settings ( data_id , files , secrets ) settings_dict [ ExecutorFiles . FILE_LIST_KEY ] = list ( files . keys ( ) ) for file_name in files : file_path = os . path . join ( runtime_dir , file_name ) with open ( file_path , 'wt' ) as json_file : json . dump ( files [ file_name ] , json_file , cls = SettingsJSONifier ) secrets_dir = os . path . join ( runtime_dir , ExecutorFiles . SECRETS_DIR ) os . makedirs ( secrets_dir , mode = 0o300 ) for file_name , value in secrets . items ( ) : file_path = os . path . join ( secrets_dir , file_name ) old_umask = os . umask ( 0 ) try : file_descriptor = os . open ( file_path , os . O_WRONLY | os . O_CREAT , mode = 0o600 ) with os . fdopen ( file_descriptor , 'w' ) as raw_file : raw_file . write ( value ) finally : os . umask ( old_umask ) | Prepare settings and constants JSONs for the executor . |
45,233 | def _prepare_executor ( self , data , executor ) : logger . debug ( __ ( "Preparing executor for Data with id {}" , data . id ) ) import resolwe . flow . executors as executor_package exec_dir = os . path . dirname ( inspect . getsourcefile ( executor_package ) ) dest_dir = self . _get_per_data_dir ( 'RUNTIME_DIR' , data . location . subpath ) dest_package_dir = os . path . join ( dest_dir , 'executors' ) shutil . copytree ( exec_dir , dest_package_dir ) dir_mode = self . settings_actual . get ( 'FLOW_EXECUTOR' , { } ) . get ( 'RUNTIME_DIR_MODE' , 0o755 ) os . chmod ( dest_dir , dir_mode ) class_name = executor . rpartition ( '.executors.' ) [ - 1 ] return '.{}' . format ( class_name ) , dest_dir | Copy executor sources into the destination directory . |
45,234 | def _prepare_script ( self , dest_dir , program ) : 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 | Copy the script into the destination directory . |
45,235 | async def handle_control_event ( self , message ) : cmd = message [ WorkerProtocol . COMMAND ] logger . debug ( __ ( "Manager worker got channel command '{}'." , cmd ) ) immediates = { } if cmd == WorkerProtocol . COMMUNICATE : immediates = message . get ( WorkerProtocol . COMMUNICATE_SETTINGS , { } ) or { } override = self . state . settings_override or { } override . update ( immediates ) self . settings_actual = self . _marshal_settings ( ) self . settings_actual . update ( override ) if cmd == WorkerProtocol . COMMUNICATE : try : await database_sync_to_async ( self . _data_scan ) ( ** message [ WorkerProtocol . COMMUNICATE_EXTRA ] ) except Exception : logger . exception ( "Unknown error occured while processing communicate control command." ) raise finally : await self . sync_counter . dec ( 'communicate' ) elif cmd == WorkerProtocol . FINISH : try : data_id = message [ WorkerProtocol . DATA_ID ] data_location = DataLocation . objects . get ( data__id = data_id ) if not getattr ( settings , 'FLOW_MANAGER_KEEP_DATA' , False ) : try : def handle_error ( func , path , exc_info ) : if isinstance ( exc_info [ 1 ] , PermissionError ) : os . chmod ( path , 0o700 ) shutil . rmtree ( path ) secrets_dir = os . path . join ( self . _get_per_data_dir ( 'RUNTIME_DIR' , data_location . subpath ) , ExecutorFiles . SECRETS_DIR ) shutil . rmtree ( secrets_dir , onerror = handle_error ) except OSError : logger . exception ( "Manager exception while removing data runtime directory." ) if message [ WorkerProtocol . FINISH_SPAWNED ] : await database_sync_to_async ( self . _data_scan ) ( ** message [ WorkerProtocol . FINISH_COMMUNICATE_EXTRA ] ) except Exception : logger . exception ( "Unknown error occured while processing finish control command." , extra = { 'data_id' : data_id } ) raise finally : await self . sync_counter . dec ( 'executor' ) elif cmd == WorkerProtocol . ABORT : await self . sync_counter . dec ( 'executor' ) else : logger . error ( __ ( "Ignoring unknown manager control command '{}'." , cmd ) ) | Handle an event from the Channels layer . |
45,236 | def _ensure_counter ( self ) : if not isinstance ( self . sync_counter , self . _SynchronizationManager ) : self . sync_counter = self . _SynchronizationManager ( ) | Ensure the sync counter is a valid non - dummy object . |
45,237 | async def execution_barrier ( self ) : 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 = self . _SynchronizationManagerDummy ( ) | Wait for executors to finish . |
45,238 | async def communicate ( self , data_id = None , run_sync = False , save_settings = True ) : 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_settings = self . state . settings_override if save_settings : saved_settings = self . _marshal_settings ( ) self . state . settings_override = saved_settings if run_sync : self . _ensure_counter ( ) await self . sync_counter . inc ( 'communicate' ) try : await consumer . send_event ( { WorkerProtocol . COMMAND : WorkerProtocol . COMMUNICATE , WorkerProtocol . COMMUNICATE_SETTINGS : saved_settings , WorkerProtocol . COMMUNICATE_EXTRA : { 'data_id' : data_id , 'executor' : executor , } , } ) except ChannelFull : logger . exception ( "ChannelFull error occurred while sending communicate message." ) await self . sync_counter . dec ( 'communicate' ) if run_sync and not self . sync_counter . active : logger . debug ( __ ( "Manager on channel '{}' entering synchronization block." , state . MANAGER_CONTROL_CHANNEL ) ) await self . execution_barrier ( ) logger . debug ( __ ( "Manager on channel '{}' exiting synchronization block." , state . MANAGER_CONTROL_CHANNEL ) ) | Scan database for resolving Data objects and process them . |
45,239 | def _data_execute ( self , data , program , executor ) : if not program : return logger . debug ( __ ( "Manager preparing Data with id {} for processing." , data . id ) ) try : executor_env_vars = self . get_executor ( ) . get_environment_variables ( ) program = self . _include_environment_variables ( program , executor_env_vars ) data_dir = self . _prepare_data_dir ( data ) executor_module , runtime_dir = self . _prepare_executor ( data , executor ) execution_engine = data . process . run . get ( 'language' , None ) volume_maps = self . get_execution_engine ( execution_engine ) . prepare_runtime ( runtime_dir , data ) self . _prepare_context ( data . id , data_dir , runtime_dir , RUNTIME_VOLUME_MAPS = volume_maps ) self . _prepare_script ( runtime_dir , program ) argv = [ '/bin/bash' , '-c' , self . settings_actual . get ( 'FLOW_EXECUTOR' , { } ) . get ( 'PYTHON' , '/usr/bin/env python' ) + ' -m executors ' + executor_module ] except PermissionDenied as error : data . status = Data . STATUS_ERROR data . process_error . append ( "Permission denied for process: {}" . format ( error ) ) data . save ( ) return except OSError as err : logger . error ( __ ( "OSError occurred while preparing data {} (will skip): {}" , data . id , err ) ) return logger . info ( __ ( "Running {}" , runtime_dir ) ) self . run ( data , runtime_dir , argv ) | Execute the Data object . |
45,240 | def get_expression_engine ( self , name ) : try : return self . expression_engines [ name ] except KeyError : raise InvalidEngineError ( "Unsupported expression engine: {}" . format ( name ) ) | Return an expression engine instance . |
45,241 | def get_execution_engine ( self , name ) : try : return self . execution_engines [ name ] except KeyError : raise InvalidEngineError ( "Unsupported execution engine: {}" . format ( name ) ) | Return an execution engine instance . |
45,242 | def load_executor ( self , executor_name ) : executor_name = executor_name + '.prepare' module = import_module ( executor_name ) return module . FlowExecutorPreparer ( ) | Load process executor . |
45,243 | def get_queryset ( self ) : if self . request and self . request . query_params . get ( 'hydrate_data' , False ) : return self . queryset . prefetch_related ( 'data__entity_set' ) return self . queryset | Return queryset . |
45,244 | def _get_collection_for_user ( self , collection_id , user ) : collection_query = Collection . objects . filter ( pk = collection_id ) if not collection_query . exists ( ) : raise exceptions . ValidationError ( 'Collection id does not exist' ) collection = collection_query . first ( ) if not user . has_perm ( 'add_collection' , obj = collection ) : if user . is_authenticated : raise exceptions . PermissionDenied ( ) else : raise exceptions . NotFound ( ) return collection | Check that collection exists and user has add permission . |
45,245 | def _get_entities ( self , user , 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 ) ) if missing_ids : raise exceptions . ParseError ( "Entities with the following ids not found: {}" . format ( ', ' . join ( map ( str , missing_ids ) ) ) ) return queryset | Return entities queryset based on provided entity ids . |
45,246 | def set_content_permissions ( self , user , obj , payload ) : payload = remove_permission ( payload , 'add' ) for data in obj . data . all ( ) : if user . has_perm ( 'share_data' , data ) : update_permission ( data , payload ) | Apply permissions to data objects in Entity . |
45,247 | def add_to_collection ( self , request , pk = None ) : entity = self . get_object ( ) if 'ids' not in request . data : return Response ( { "error" : "`ids` parameter is required" } , status = status . HTTP_400_BAD_REQUEST ) for collection_id in request . data [ 'ids' ] : self . _get_collection_for_user ( collection_id , request . user ) for collection_id in request . data [ 'ids' ] : entity . collections . add ( collection_id ) collection = Collection . objects . get ( pk = collection_id ) for data in entity . data . all ( ) : collection . data . add ( data ) return Response ( ) | Add Entity to a collection . |
45,248 | def add_data ( self , request , pk = None ) : resp = super ( ) . add_data ( request , pk ) entity = self . get_object ( ) for collection in entity . collections . all ( ) : collection . data . add ( * request . data [ 'ids' ] ) return resp | Add data to Entity and it s collection . |
45,249 | def move_to_collection ( self , request , * args , ** kwargs ) : 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' ) src_collection = self . _get_collection_for_user ( src_collection_id , request . user ) dst_collection = self . _get_collection_for_user ( dst_collection_id , request . user ) entity_qs = self . _get_entities ( request . user , ids ) entity_qs . move_to_collection ( src_collection , dst_collection ) return Response ( ) | Move samples from source to destination collection . |
45,250 | def update ( self , request , * args , ** kwargs ) : orig_get_queryset = self . get_queryset def patched_get_queryset ( ) : entity_ids = orig_get_queryset ( ) . values_list ( 'id' , flat = True ) return Entity . objects . filter ( id__in = entity_ids ) self . get_queryset = patched_get_queryset resp = super ( ) . update ( request , * args , ** kwargs ) self . get_queryset = orig_get_queryset return resp | Update an entity . |
45,251 | async def end ( self ) : try : await self . proc . wait ( ) finally : for temporary_file in self . temporary_files : temporary_file . close ( ) self . temporary_files = [ ] return self . proc . returncode | End process execution . |
45,252 | def iterjson ( text ) : 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 | Decode JSON stream . |
45,253 | async def _send_manager_command ( self , * args , ** kwargs ) : resp = await send_manager_command ( * args , ** kwargs ) if resp is False : await self . terminate ( ) | Send an update to manager and terminate the process if it fails . |
45,254 | def _create_file ( self , filename ) : file_descriptor = os . open ( filename , os . O_WRONLY | os . O_CREAT | os . O_EXCL ) return os . fdopen ( file_descriptor , 'w' ) | Ensure a new file is created and opened for writing . |
45,255 | def get_total_size_of_queued_replicas ( ) : return ( d1_gmn . app . models . ReplicationQueue . objects . filter ( local_replica__info__status__status = 'queued' ) . aggregate ( Sum ( 'size' ) ) [ 'size__sum' ] or 0 ) | Return the total number of bytes of requested unprocessed replicas . |
45,256 | def add_to_replication_queue ( source_node_urn , sysmeta_pyxb ) : replica_info_model = d1_gmn . app . models . replica_info ( status_str = 'queued' , source_node_urn = source_node_urn ) local_replica_model = d1_gmn . app . models . local_replica ( pid = d1_common . xml . get_req_val ( sysmeta_pyxb . identifier ) , replica_info_model = replica_info_model , ) d1_gmn . app . models . replication_queue ( local_replica_model = local_replica_model , size = sysmeta_pyxb . size ) | Add a replication request issued by a CN to a queue that is processed asynchronously . |
45,257 | def add_arguments ( parser , doc_str , add_base_url = True ) : parser . description = doc_str parser . formatter_class = argparse . RawDescriptionHelpFormatter parser . add_argument ( "--debug" , action = "store_true" , help = "Debug level logging" ) parser . add_argument ( "--cert-pub" , dest = "cert_pem_path" , action = "store" , default = django . conf . settings . CLIENT_CERT_PATH , help = "Path to PEM formatted public key of certificate" , ) parser . add_argument ( "--cert-key" , dest = "cert_key_path" , action = "store" , default = django . conf . settings . CLIENT_CERT_PRIVATE_KEY_PATH , help = "Path to PEM formatted private key of certificate" , ) parser . add_argument ( "--public" , action = "store_true" , help = "Do not use certificate even if available" ) parser . add_argument ( "--disable-server-cert-validation" , action = "store_true" , help = "Do not validate the TLS/SSL server side certificate of the source node (insecure)" , ) parser . add_argument ( "--timeout" , type = float , action = "store" , default = DEFAULT_TIMEOUT_SEC , help = "Timeout for DataONE API calls to the source MN" , ) parser . add_argument ( "--retries" , type = int , action = "store" , default = DEFAULT_RETRY_COUNT , help = "Retry DataONE API calls that raise HTTP level exceptions" , ) parser . add_argument ( "--page-size" , type = int , action = "store" , default = DEFAULT_PAGE_SIZE , help = "Number of objects to retrieve in each list method API call to source MN" , ) parser . add_argument ( "--major" , type = int , action = "store" , help = "Skip automatic detection of API major version and use the provided version" , ) parser . add_argument ( "--max-concurrent" , type = int , action = "store" , default = DEFAULT_MAX_CONCURRENT_TASK_COUNT , help = "Max number of concurrent DataONE API" , ) if not add_base_url : parser . add_argument ( "--baseurl" , action = "store" , default = django . conf . settings . DATAONE_ROOT , help = "Remote MN or CN BaseURL" , ) else : parser . add_argument ( "baseurl" , help = "Remote MN or CN BaseURL" ) | Add standard arguments for DataONE utilities to a command line parser . |
45,258 | def get_resource_map_members ( pid ) : 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_member ( pid ) else : raise d1_common . types . exceptions . InvalidRequest ( 0 , 'Not a Resource Map or Resource Map member. pid="{}"' . format ( pid ) ) | pid is the PID of a Resource Map or the PID of a member of a Resource Map . |
45,259 | def set_with_conversion ( self , variable , value_string ) : self . _assert_valid_variable ( variable ) try : v = ast . literal_eval ( value_string ) except ( ValueError , SyntaxError ) : v = value_string if v is None or v == "none" : self . _variables [ variable ] = None else : try : type_converter = variable_type_map [ variable ] value_string = self . _validate_variable_type ( value_string , type_converter ) value = type_converter ( value_string ) self . _variables [ variable ] = value except ValueError : raise d1_cli . impl . exceptions . InvalidArguments ( "Invalid value for {}: {}" . format ( variable , value_string ) ) | Convert user supplied string to Python type . |
45,260 | def log_setup ( is_debug = False , is_multiprocess = False ) : format_str = ( '%(asctime)s %(name)s %(module)s:%(lineno)d %(process)4d %(levelname)-8s %(message)s' if is_multiprocess else '%(asctime)s %(name)s %(module)s:%(lineno)d %(levelname)-8s %(message)s' ) formatter = logging . Formatter ( format_str , '%Y-%m-%d %H:%M:%S' ) console_logger = logging . StreamHandler ( sys . stdout ) console_logger . setFormatter ( formatter ) logging . getLogger ( '' ) . addHandler ( console_logger ) if is_debug : logging . getLogger ( '' ) . setLevel ( logging . DEBUG ) else : logging . getLogger ( '' ) . setLevel ( logging . INFO ) | 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 . |
45,261 | def get_content_type ( content_type ) : m = email . message . Message ( ) m [ 'Content-Type' ] = content_type return m . get_content_type ( ) | Extract the MIME type value from a content type string . |
45,262 | def nested_update ( d , u ) : for k , v in list ( u . items ( ) ) : if isinstance ( v , collections . Mapping ) : r = nested_update ( d . get ( k , { } ) , v ) d [ k ] = r else : d [ k ] = u [ k ] return d | Merge two nested dicts . |
45,263 | def print_logging ( ) : root_logger = logging . getLogger ( ) old_level_list = [ h . level for h in root_logger . handlers ] for h in root_logger . handlers : h . setLevel ( logging . WARN ) log_format = logging . Formatter ( '%(message)s' ) stream_handler = logging . StreamHandler ( sys . stdout ) stream_handler . setFormatter ( log_format ) stream_handler . setLevel ( logging . DEBUG ) root_logger . addHandler ( stream_handler ) yield root_logger . removeHandler ( stream_handler ) for h , level in zip ( root_logger . handlers , old_level_list ) : h . setLevel ( level ) | Context manager to temporarily suppress additional information such as timestamps when writing to loggers . |
45,264 | def save_json ( py_obj , json_path ) : with open ( json_path , 'w' , encoding = 'utf-8' ) as f : f . write ( serialize_to_normalized_pretty_json ( py_obj ) ) | Serialize a native object to JSON and save it normalized pretty printed to a file . |
45,265 | def serialize_to_normalized_pretty_json ( py_obj ) : return json . dumps ( py_obj , sort_keys = True , indent = 2 , cls = ToJsonCompatibleTypes ) | Serialize a native object to normalized pretty printed JSON . |
45,266 | def serialize_to_normalized_compact_json ( py_obj ) : return json . dumps ( py_obj , sort_keys = True , separators = ( ',' , ':' ) , cls = ToJsonCompatibleTypes ) | Serialize a native object to normalized compact JSON . |
45,267 | def format_sec_to_dhm ( sec ) : rem_int , s_int = divmod ( int ( sec ) , 60 ) rem_int , m_int , = divmod ( rem_int , 60 ) d_int , h_int , = divmod ( rem_int , 24 ) return '{}d{:02d}h{:02d}m' . format ( d_int , h_int , m_int ) | Format seconds to days hours minutes . |
45,268 | def count ( self , event_str , inc_int = 1 ) : self . _event_dict . setdefault ( event_str , 0 ) self . _event_dict [ event_str ] += inc_int | Count an event . |
45,269 | def log_and_count ( self , event_str , msg_str = None , inc_int = None ) : logger . info ( ' - ' . join ( map ( str , [ v for v in ( event_str , msg_str , inc_int ) if v ] ) ) ) self . count ( event_str , inc_int or 1 ) | Count an event and write a message to a logger . |
45,270 | def dump_to_log ( self ) : if self . _event_dict : logger . info ( 'Events:' ) for event_str , count_int in sorted ( self . _event_dict . items ( ) ) : logger . info ( ' {}: {}' . format ( event_str , count_int ) ) else : logger . info ( 'No Events' ) | Write summary to logger with the name and number of times each event has been counted . |
45,271 | def delete_all_from_db ( ) : for model in django . apps . apps . get_models ( ) : model . objects . all ( ) . delete ( ) | Clear the database . |
45,272 | def get_limit ( self , request ) : if self . limit_query_param : try : return _positive_int ( get_query_param ( request , self . limit_query_param ) , strict = True , cutoff = self . max_limit ) except ( KeyError , ValueError ) : pass return self . default_limit | Return limit parameter . |
45,273 | def get_offset ( self , request ) : try : return _positive_int ( get_query_param ( request , self . offset_query_param ) , ) except ( KeyError , ValueError ) : return 0 | Return offset parameter . |
45,274 | def futurize_module ( module_path , show_diff , write_update ) : 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 ) | 2to3 uses AST not Baron . |
45,275 | def _remove_single_line_import_comments ( r ) : 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 ) : if 1 < i < len ( import_r ) - 2 : if not ( import_r [ i - 2 ] . type != 'comment' and v . type == 'comment' and import_r [ i + 2 ] . type != 'comment' ) or _is_keep_comment ( v ) : new_import_r . append ( v ) else : new_import_r . append ( v ) return new_import_r + remaining_r | We previously used more groups for the import statements and named each group . |
45,276 | def configure_logging ( emit_list ) : if 'sphinx' in sys . modules : module_base = 'resolwe.flow.executors' else : module_base = 'executors' logging_config = dict ( version = 1 , formatters = { 'json_formatter' : { '()' : JSONFormatter } , } , handlers = { 'redis' : { 'class' : module_base + '.logger.RedisHandler' , 'formatter' : 'json_formatter' , 'level' : logging . INFO , 'emit_list' : emit_list } , 'console' : { 'class' : 'logging.StreamHandler' , 'level' : logging . WARNING } , } , root = { 'handlers' : [ 'redis' , 'console' ] , 'level' : logging . DEBUG , } , loggers = { module_base + '.manager_comm' : { 'level' : 'INFO' , 'handlers' : [ 'console' ] , 'propagate' : False , } , } , ) dictConfig ( logging_config ) | Configure logging to send log records to the master . |
45,277 | def format ( self , record ) : data = record . __dict__ . copy ( ) data [ 'data_id' ] = DATA [ 'id' ] data [ 'data_location_id' ] = DATA_LOCATION [ 'id' ] data [ 'hostname' ] = socket . gethostname ( ) data [ 'pathname' ] = os . path . relpath ( data [ 'pathname' ] , os . path . dirname ( __file__ ) ) data [ 'exc_info' ] = None data [ 'msg' ] = str ( data [ 'msg' ] ) return json . dumps ( data ) | Dump the record to JSON . |
45,278 | def emit ( self , record ) : future = asyncio . ensure_future ( send_manager_command ( ExecutorProtocol . LOG , extra_fields = { ExecutorProtocol . LOG_MESSAGE : self . format ( record ) , } , expect_reply = False ) ) self . emit_list . append ( future ) | Send log message to the listener . |
45,279 | def create_secret ( self , value , contributor , metadata = None , expires = None ) : if metadata is None : metadata = { } secret = self . create ( value = value , contributor = contributor , metadata = metadata , expires = expires , ) return str ( secret . handle ) | Create a new secret returning its handle . |
45,280 | def get_secret ( self , handle , contributor ) : queryset = self . all ( ) if contributor is not None : queryset = queryset . filter ( contributor = contributor ) secret = queryset . get ( handle = handle ) return secret . value | Retrieve an existing secret s value . |
45,281 | def validation_schema ( name ) : schemas = { 'processor' : 'processSchema.json' , 'descriptor' : 'descriptorSchema.json' , 'field' : 'fieldSchema.json' , 'type' : 'typeSchema.json' , } if name not in schemas : raise ValueError ( ) field_schema_file = finders . find ( 'flow/{}' . format ( schemas [ 'field' ] ) , all = True ) [ 0 ] with open ( field_schema_file , 'r' ) as fn : field_schema = fn . read ( ) if name == 'field' : return json . loads ( field_schema . replace ( '{{PARENT}}' , '' ) ) schema_file = finders . find ( 'flow/{}' . format ( schemas [ name ] ) , all = True ) [ 0 ] with open ( schema_file , 'r' ) as fn : schema = fn . read ( ) return json . loads ( schema . replace ( '{{FIELD}}' , field_schema ) . replace ( '{{PARENT}}' , '/field' ) ) | Return json schema for json validation . |
45,282 | def hydrate_input_references ( input_ , input_schema , hydrate_values = True ) : from . data import Data for field_schema , fields in iterate_fields ( input_ , input_schema ) : name = field_schema [ 'name' ] value = fields [ name ] if 'type' in field_schema : if field_schema [ 'type' ] . startswith ( 'data:' ) : if value is None : continue try : data = Data . objects . get ( id = value ) except Data . DoesNotExist : fields [ name ] = { } continue output = copy . deepcopy ( data . output ) if hydrate_values : _hydrate_values ( output , data . process . output_schema , data ) output [ "__id" ] = data . id output [ "__type" ] = data . process . type output [ "__descriptor" ] = data . descriptor output [ "__entity_name" ] = None output [ "__output_schema" ] = data . process . output_schema entity = data . entity_set . values ( 'name' ) . first ( ) if entity : output [ "__entity_name" ] = entity [ 'name' ] fields [ name ] = output elif field_schema [ 'type' ] . startswith ( 'list:data:' ) : outputs = [ ] for val in value : if val is None : continue try : data = Data . objects . get ( id = val ) except Data . DoesNotExist : outputs . append ( { } ) continue output = copy . deepcopy ( data . output ) if hydrate_values : _hydrate_values ( output , data . process . output_schema , data ) output [ "__id" ] = data . id output [ "__type" ] = data . process . type output [ "__descriptor" ] = data . descriptor output [ "__output_schema" ] = data . process . output_schema entity = data . entity_set . values ( 'name' ) . first ( ) if entity : output [ "__entity_name" ] = entity [ 'name' ] outputs . append ( output ) fields [ name ] = outputs | Hydrate input_ with linked data . |
45,283 | def hydrate_size ( data , force = False ) : from . data import Data def get_dir_size ( path ) : total_size = 0 for dirpath , _ , filenames in os . walk ( path ) : for file_name in filenames : file_path = os . path . join ( dirpath , file_name ) if not os . path . isfile ( file_path ) : continue total_size += os . path . getsize ( file_path ) return total_size def get_refs_size ( obj , obj_path ) : total_size = 0 for ref in obj . get ( 'refs' , [ ] ) : ref_path = data . location . get_path ( filename = ref ) if ref_path in obj_path : continue if os . path . isfile ( ref_path ) : total_size += os . path . getsize ( ref_path ) elif os . path . isdir ( ref_path ) : total_size += get_dir_size ( ref_path ) return total_size def add_file_size ( obj ) : if data . status in [ Data . STATUS_DONE , Data . STATUS_ERROR ] and 'size' in obj and not force : return path = data . location . get_path ( filename = obj [ 'file' ] ) if not os . path . isfile ( path ) : raise ValidationError ( "Referenced file does not exist ({})" . format ( path ) ) obj [ 'size' ] = os . path . getsize ( path ) obj [ 'total_size' ] = obj [ 'size' ] + get_refs_size ( obj , path ) def add_dir_size ( obj ) : if data . status in [ Data . STATUS_DONE , Data . STATUS_ERROR ] and 'size' in obj and not force : return path = data . location . get_path ( filename = obj [ 'dir' ] ) if not os . path . isdir ( path ) : raise ValidationError ( "Referenced dir does not exist ({})" . format ( path ) ) obj [ 'size' ] = get_dir_size ( path ) obj [ 'total_size' ] = obj [ 'size' ] + get_refs_size ( obj , path ) data_size = 0 for field_schema , fields in iterate_fields ( data . output , data . process . output_schema ) : name = field_schema [ 'name' ] value = fields [ name ] if 'type' in field_schema : if field_schema [ 'type' ] . startswith ( 'basic:file:' ) : add_file_size ( value ) data_size += value . get ( 'total_size' , 0 ) elif field_schema [ 'type' ] . startswith ( 'list:basic:file:' ) : for obj in value : add_file_size ( obj ) data_size += obj . get ( 'total_size' , 0 ) elif field_schema [ 'type' ] . startswith ( 'basic:dir:' ) : add_dir_size ( value ) data_size += value . get ( 'total_size' , 0 ) elif field_schema [ 'type' ] . startswith ( 'list:basic:dir:' ) : for obj in value : add_dir_size ( obj ) data_size += obj . get ( 'total_size' , 0 ) data . size = data_size | Add file and dir sizes . |
45,284 | def render_descriptor ( data ) : if not data . descriptor_schema : return for field_schema , field , path in iterate_schema ( data . descriptor , data . descriptor_schema . schema , 'descriptor' ) : if 'default' in field_schema and field_schema [ 'name' ] not in field : dict_dot ( data , path , field_schema [ 'default' ] ) | Render data descriptor . |
45,285 | def render_template ( process , template_string , context ) : from resolwe . flow . managers import manager expression_engine = process . requirements . get ( 'expression-engine' , None ) if not expression_engine : return template_string return manager . get_expression_engine ( expression_engine ) . evaluate_block ( template_string , context ) | Render template using the specified expression engine . |
45,286 | def json_path_components ( path ) : if isinstance ( path , str ) : path = path . split ( '.' ) return list ( path ) | Convert JSON path to individual path components . |
45,287 | def validate_process_subtype ( supertype_name , supertype , subtype_name , subtype ) : errors = [ ] for item in supertype : for subitem in subtype : if item [ 'name' ] != subitem [ 'name' ] : continue for key in set ( item . keys ( ) ) | set ( subitem . keys ( ) ) : if key in ( 'label' , 'description' ) : continue elif key == 'required' : item_required = item . get ( 'required' , True ) subitem_required = subitem . get ( 'required' , False ) if item_required and not subitem_required : errors . append ( "Field '{}' is marked as required in '{}' and optional in '{}'." . format ( item [ 'name' ] , supertype_name , subtype_name , ) ) elif item . get ( key , None ) != subitem . get ( key , None ) : errors . append ( "Schema for field '{}' in type '{}' does not match supertype '{}'." . format ( item [ 'name' ] , subtype_name , supertype_name ) ) break else : errors . append ( "Schema for type '{}' is missing supertype '{}' field '{}'." . format ( subtype_name , supertype_name , item [ 'name' ] ) ) return errors | Perform process subtype validation . |
45,288 | def validate_process_types ( queryset = None ) : if not queryset : from . process import Process queryset = Process . objects . all ( ) processes = { } for process in queryset : dict_dot ( processes , process . type . replace ( ':' , '.' ) + '__schema__' , process . output_schema ) errors = [ ] for path , key , value in iterate_dict ( processes , exclude = lambda key , value : key == '__schema__' ) : if '__schema__' not in value : continue for length in range ( len ( path ) , 0 , - 1 ) : parent_type = '.' . join ( path [ : length ] + [ '__schema__' ] ) try : parent_schema = dict_dot ( processes , parent_type ) except KeyError : continue errors += validate_process_subtype ( supertype_name = ':' . join ( path [ : length ] ) , supertype = parent_schema , subtype_name = ':' . join ( path + [ key ] ) , subtype = value [ '__schema__' ] ) return errors | Perform process type validation . |
45,289 | def fill_with_defaults ( process_input , input_schema ) : 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 , field_schema [ 'default' ] ) | Fill empty optional fields in input with default values . |
45,290 | def to_internal_value ( self , data ) : if isinstance ( data , dict ) and isinstance ( data . get ( 'id' , None ) , int ) : data = data [ 'id' ] elif isinstance ( data , int ) : pass else : raise ValidationError ( "Contributor must be an integer or a dictionary with key 'id'" ) return self . Meta . model . objects . get ( pk = data ) | Format the internal value . |
45,291 | def extract_descriptor ( self , obj ) : descriptor = [ ] def flatten ( current ) : if isinstance ( current , dict ) : for key in current : flatten ( current [ key ] ) elif isinstance ( current , list ) : for val in current : flatten ( val ) elif isinstance ( current , ( int , bool , float , str ) ) : descriptor . append ( str ( current ) ) flatten ( obj . descriptor ) return descriptor | Extract data from the descriptor . |
45,292 | def _serialize_items ( self , serializer , kind , items ) : if self . request and self . request . query_params . get ( 'hydrate_{}' . format ( kind ) , False ) : serializer = serializer ( items , many = True , read_only = True ) serializer . bind ( kind , self ) return serializer . data else : return [ item . id for item in items ] | Return serialized items or list of ids depending on hydrate_XXX query param . |
45,293 | def get_entity_names ( self , data ) : entities = self . _filter_queryset ( 'view_entity' , data . entity_set . all ( ) ) return list ( entities . values_list ( 'name' , flat = True ) ) | Return serialized list of entity names on data that user has view permission on . |
45,294 | def get_collections ( self , data ) : collections = self . _filter_queryset ( 'view_collection' , data . collection_set . all ( ) ) from . collection import CollectionSerializer class CollectionWithoutDataSerializer ( WithoutDataSerializerMixin , CollectionSerializer ) : return self . _serialize_items ( CollectionWithoutDataSerializer , 'collections' , collections ) | Return serialized list of collection objects on data that user has view permission on . |
45,295 | def get_entities ( self , data ) : entities = self . _filter_queryset ( 'view_entity' , data . entity_set . all ( ) ) from . entity import EntitySerializer class EntityWithoutDataSerializer ( WithoutDataSerializerMixin , EntitySerializer ) : return self . _serialize_items ( EntityWithoutDataSerializer , 'entities' , entities ) | Return serialized list of entity objects on data that user has view permission on . |
45,296 | def handle ( self , * args , ** options ) : verbosity = int ( options . get ( 'verbosity' ) ) if options [ 'format' ] != 'plain' and options [ 'format' ] != 'yaml' : raise CommandError ( "Unknown output format: %s" % options [ 'format' ] ) unique_docker_images = set ( p . requirements [ 'executor' ] [ 'docker' ] [ 'image' ] for p in Process . objects . filter ( is_active = True ) . order_by ( 'slug' , '-version' ) . distinct ( 'slug' ) . only ( 'requirements' ) . filter ( requirements__icontains = 'docker' ) if 'image' in p . requirements . get ( 'executor' , { } ) . get ( 'docker' , { } ) ) unique_docker_images . add ( DEFAULT_CONTAINER_IMAGE ) if options [ 'pull' ] : with PULLED_IMAGES_LOCK : unique_docker_images . difference_update ( PULLED_IMAGES ) docker = getattr ( settings , 'FLOW_DOCKER_COMMAND' , 'docker' ) for img in unique_docker_images : ret = subprocess . call ( shlex . split ( '{} pull {}' . format ( docker , img ) ) , stdout = None if verbosity > 0 else subprocess . DEVNULL , stderr = None if verbosity > 0 else subprocess . DEVNULL , ) with PULLED_IMAGES_LOCK : PULLED_IMAGES . add ( img ) if ret != 0 : errmsg = "Failed to pull Docker image '{}'!" . format ( img ) if not options [ 'ignore_pull_errors' ] : raise CommandError ( errmsg ) else : logger . error ( errmsg ) if verbosity > 0 : self . stderr . write ( errmsg ) else : msg = "Docker image '{}' pulled successfully!" . format ( img ) logger . info ( msg ) if verbosity > 0 : self . stdout . write ( msg ) else : unique_docker_images = sorted ( unique_docker_images ) imgs = [ dict ( name = s [ 0 ] , tag = s [ 1 ] if len ( s ) == 2 else 'latest' ) for s in ( img . split ( ':' ) for img in unique_docker_images ) ] if options [ 'format' ] == 'yaml' : out = yaml . safe_dump ( imgs , default_flow_style = True , default_style = "'" ) else : out = functools . reduce ( operator . add , ( '{name}:{tag}\n' . format ( ** i ) for i in imgs ) , '' ) self . stdout . write ( out , ending = '' ) | Handle command list_docker_images . |
45,297 | def get_or_create ( self , request , * args , ** kwargs ) : kwargs [ 'get_or_create' ] = True return self . create ( request , * args , ** kwargs ) | Get Data object if similar already exists otherwise create it . |
45,298 | def perform_get_or_create ( self , request , * args , ** kwargs ) : serializer = self . get_serializer ( data = request . data ) serializer . is_valid ( raise_exception = True ) process = serializer . validated_data . get ( 'process' ) process_input = request . data . get ( 'input' , { } ) fill_with_defaults ( process_input , process . input_schema ) checksum = get_data_checksum ( process_input , process . slug , process . version ) data_qs = Data . objects . filter ( checksum = checksum , process__persistence__in = [ Process . PERSISTENCE_CACHED , Process . PERSISTENCE_TEMP ] , ) data_qs = get_objects_for_user ( request . user , 'view_data' , data_qs ) if data_qs . exists ( ) : data = data_qs . order_by ( 'created' ) . last ( ) serializer = self . get_serializer ( data ) return Response ( serializer . data ) | Perform get_or_create - return existing object if found . |
45,299 | def ready ( self ) : self . _assert_readable_file_if_set ( 'CLIENT_CERT_PATH' ) self . _assert_readable_file_if_set ( 'CLIENT_CERT_PRIVATE_KEY_PATH' ) self . _assert_dirs_exist ( 'OBJECT_FORMAT_CACHE_PATH' ) self . _assert_is_type ( 'SCIMETA_VALIDATION_ENABLED' , bool ) self . _assert_is_type ( 'SCIMETA_VALIDATION_MAX_SIZE' , int ) self . _assert_is_in ( 'SCIMETA_VALIDATION_OVER_SIZE_ACTION' , ( 'reject' , 'accept' ) ) self . _warn_unsafe_for_prod ( ) self . _check_resource_map_create ( ) if not d1_gmn . app . sciobj_store . is_existing_store ( ) : self . _create_sciobj_store_root ( ) self . _add_xslt_mimetype ( ) | Called once per Django process instance . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.