docstring
stringlengths
52
499
function
stringlengths
67
35.2k
__index_level_0__
int64
52.6k
1.16M
Execute an specific method for each class instance located in path Args: path (str): Absolute path which contains the .py files method (str): Method to execute into class instance Returns: dict: Dictionary which contains the response for every class instance. The dictionary keys are the value of 'N...
def _executeMassiveMethod(path, method, args=None, classArgs = None): response = {} if args is None: args = {} if classArgs is None: classArgs = {} sys.path.append(path) exclude = ["__init__.py", "base.py"] for f in AtomShieldsScanner._getFiles(path, "*.py", exclude=exclude): try: instanc...
651,767
Setter for 'potential' property Args: value (bool): True if a potential is required. False else
def potential(self, value): if value: self._potential = True else: self._potential = False
651,783
Generate transcripts from sjson to SubRip (*.srt). Arguments: srt_subs(SubRip): "SRT" subs object Returns: Subs converted to "SJSON" format.
def generate_sjson_from_srt(srt_subs): sub_starts = [] sub_ends = [] sub_texts = [] for sub in srt_subs: sub_starts.append(sub.start.ordinal) sub_ends.append(sub.end.ordinal) sub_texts.append(sub.text.replace('\n', ' ')) sjson_subs = ...
651,787
Generate transcripts from sjson to SubRip (*.srt). Arguments: sjson_subs (dict): `sjson` subs. Returns: Subtitles in SRT format.
def generate_srt_from_sjson(sjson_subs): output = '' equal_len = len(sjson_subs['start']) == len(sjson_subs['end']) == len(sjson_subs['text']) if not equal_len: return output for i in range(len(sjson_subs['start'])): item = SubRipItem( ...
651,788
Convert transcript `content` from `input_format` to `output_format`. Arguments: content: Transcript content byte-stream. input_format: Input transcript format. output_format: Output transcript format. Accepted input formats: sjson, srt. Accepted output forma...
def convert(cls, content, input_format, output_format): assert input_format in ('srt', 'sjson') assert output_format in ('srt', 'sjson') # Decode the content with utf-8-sig which will also # skip byte order mark(BOM) character if found. content = content.decode('utf-8-s...
651,789
Writes file in specific file system. Arguments: file_data (str): Data to store into the file. file_name (str): File name of the file to be created. file_system (OSFS): Import file system. static_dir (str): The Directory to retrieve transcript file.
def create_file_in_fs(file_data, file_name, file_system, static_dir): with file_system.open(combine(static_dir, file_name), 'wb') as f: f.write(file_data.encode('utf-8'))
651,802
Returns transcript format. Arguments: transcript_content (str): Transcript file content.
def get_transcript_format(transcript_content): try: sjson_obj = json.loads(transcript_content) except ValueError: # With error handling (set to 'ERROR_RAISE'), we will be getting # the exception if something went wrong in parsing the transcript. srt_subs = SubRipFile.from_st...
651,803
Creates a video transcript instance with the given information. Arguments: request: A WSGI request.
def post(self, request): attrs = ('video_id', 'name', 'language_code', 'provider', 'file_format') missing = [attr for attr in attrs if attr not in request.data] if missing: LOGGER.warn( '[VAL] Required transcript params are missing. %s', ' and '.join(missing)...
651,806
Returns a data model object if found or none otherwise. Arguments: video_id(unicode): video id to which transcript may be associated language_code(unicode): language of the requested transcript
def get_or_none(cls, video_id, language_code): try: transcript = cls.objects.get(video__edx_video_id=video_id, language_code=language_code) except cls.DoesNotExist: transcript = None return transcript
651,825
Create a Video Transcript. Arguments: video(Video): Video data model object language_code(unicode): A language code. file_format(unicode): Transcript file format. content(InMemoryUploadedFile): Transcript content. provider(unicode): Transcript provide...
def create(cls, video, language_code, file_format, content, provider): video_transcript = cls(video=video, language_code=language_code, file_format=file_format, provider=provider) with closing(content) as transcript_content: try: file_name = '{uuid}.{ext}'.format(uui...
651,826
Create or update Transcript object. Arguments: video (Video): Video for which transcript is going to be saved. language_code (str): language code for (to be created/updated) transcript metadata (dict): A dict containing (to be overwritten) properties file_data (I...
def create_or_update(cls, video, language_code, metadata, file_data=None): try: video_transcript = cls.objects.get(video=video, language_code=language_code) retrieved = True except cls.DoesNotExist: video_transcript = cls(video=video, language_code=language_c...
651,827
Update status for an existing video. Args: edx_video_id: ID of the video status: video status Raises: Raises ValVideoNotFoundError if the video cannot be retrieved.
def update_video_status(edx_video_id, status): try: video = _get_video(edx_video_id) except Video.DoesNotExist: error_message = u"Video not found when trying to update video status with edx_video_id: {0}".format( edx_video_id ) raise ValVideoNotFoundError(error_...
651,834
Returns transcript credentials state for an org Arguments: org (unicode): course organization provider (unicode): transcript provider Returns: dict: provider name and their credential existance map { u'Cielo24': True } { u'3PlayMedia': F...
def get_transcript_credentials_state_for_org(org, provider=None): query_filter = {'org': org} if provider: query_filter['provider'] = provider return { credential.provider: credential.exists for credential in ThirdPartyTranscriptCredentialsState.objects.filter(**query_filter) ...
651,835
Returns whether the transcripts are available for a video. Arguments: video_id: it can be an edx_video_id or an external_id extracted from external sources in a video component. language_code: it will the language code of the requested transcript.
def is_transcript_available(video_id, language_code=None): filter_attrs = {'video__edx_video_id': video_id} if language_code: filter_attrs['language_code'] = language_code transcript_set = VideoTranscript.objects.filter(**filter_attrs) return transcript_set.exists()
651,836
Get video transcript info Arguments: video_id(unicode): A video id, it can be an edx_video_id or an external video id extracted from external sources of a video component. language_code(unicode): it will be the language code of the requested transcript.
def get_video_transcript(video_id, language_code): transcript = VideoTranscript.get_or_none(video_id=video_id, language_code=language_code) return TranscriptSerializer(transcript).data if transcript else None
651,837
Get video transcript data Arguments: video_id(unicode): An id identifying the Video. language_code(unicode): it will be the language code of the requested transcript. Returns: A dict containing transcript file name and its content.
def get_video_transcript_data(video_id, language_code): video_transcript = VideoTranscript.get_or_none(video_id, language_code) if video_transcript: try: return dict(file_name=video_transcript.filename, content=video_transcript.transcript.file.read()) except Exception: ...
651,838
Get available transcript languages Arguments: video_id(unicode): An id identifying the Video. Returns: A list containing transcript language codes for the Video.
def get_available_transcript_languages(video_id): available_languages = VideoTranscript.objects.filter( video__edx_video_id=video_id ).values_list( 'language_code', flat=True ) return list(available_languages)
651,839
Returns course video transcript url or None if no transcript Arguments: video_id: it can be an edx_video_id or an external_id extracted from external sources in a video component. language_code: language code of a video transcript
def get_video_transcript_url(video_id, language_code): video_transcript = VideoTranscript.get_or_none(video_id, language_code) if video_transcript: return video_transcript.url()
651,840
Create a video transcript. Arguments: video_id(unicode): An Id identifying the Video data model object. language_code(unicode): A language code. file_format(unicode): Transcript file format. content(InMemoryUploadedFile): Transcript content. provider(unicode): Transcript pro...
def create_video_transcript(video_id, language_code, file_format, content, provider=TranscriptProviderType.CUSTOM): transcript_serializer = TranscriptSerializer( data=dict(provider=provider, language_code=language_code, file_format=file_format), context=dict(video_id=video_id), ) if tra...
651,841
Create or Update video transcript for an existing video. Arguments: video_id: it can be an edx_video_id or an external_id extracted from external sources in a video component. language_code: language code of a video transcript metadata (dict): A dict containing (to be overwritten) propertie...
def create_or_update_video_transcript(video_id, language_code, metadata, file_data=None): # Filter wanted properties metadata = { prop: value for prop, value in six.iteritems(metadata) if prop in ['provider', 'language_code', 'file_name', 'file_format'] and value } file_for...
651,842
Delete transcript for an existing video. Arguments: video_id: id identifying the video to which the transcript is associated. language_code: language code of a video transcript.
def delete_video_transcript(video_id, language_code): video_transcript = VideoTranscript.get_or_none(video_id, language_code) if video_transcript: # delete the transcript content from storage. video_transcript.transcript.delete() # delete the transcript metadata from db. vid...
651,843
Retrieves course wide transcript preferences Arguments: course_id (str): course id
def get_transcript_preferences(course_id): try: transcript_preference = TranscriptPreference.objects.get(course_id=course_id) except TranscriptPreference.DoesNotExist: return return TranscriptPreferenceSerializer(transcript_preference).data
651,844
Creates or updates course-wide transcript preferences Arguments: course_id(str): course id Keyword Arguments: preferences(dict): keyword arguments
def create_or_update_transcript_preferences(course_id, **preferences): transcript_preference, __ = TranscriptPreference.objects.update_or_create( course_id=course_id, defaults=preferences ) return TranscriptPreferenceSerializer(transcript_preference).data
651,845
Deletes course-wide transcript preferences. Arguments: course_id(str): course id
def remove_transcript_preferences(course_id): try: transcript_preference = TranscriptPreference.objects.get(course_id=course_id) transcript_preference.delete() except TranscriptPreference.DoesNotExist: pass
651,846
Used to create Profile objects in the database A profile needs to exists before an EncodedVideo object can be created. Args: profile_name (str): ID of the profile Raises: ValCannotCreateError: Raised if the profile name is invalid or exists
def create_profile(profile_name): try: profile = Profile(profile_name=profile_name) profile.full_clean() profile.save() except ValidationError as err: raise ValCannotCreateError(err.message_dict)
651,849
Returns a dict mapping profiles to URLs. If the profiles or video is not found, urls will be blank. Args: edx_video_id (str): id of the video profiles (list): list of profiles we want to search for Returns: (dict): A dict containing the profile to url pair
def get_urls_for_profiles(edx_video_id, profiles): profiles_to_urls = {profile: None for profile in profiles} try: video_info = get_video_info(edx_video_id) except ValVideoNotFoundError: return profiles_to_urls for encoded_video in video_info["encoded_videos"]: if encoded_v...
651,851
Returns a list that contains all the course ids and video ids with the youtube profile Args: course_ids (list): valid course ids limit (int): batch records limit offset (int): an offset for selecting a batch Returns: (list): Tuples of course_id, edx_video_id and youtube vide...
def get_course_video_ids_with_youtube_profile(course_ids=None, offset=None, limit=None): course_videos = (CourseVideo.objects.select_related('video') .prefetch_related('video__encoded_videos', 'video__encoded_videos__profile') .filter(video__encoded_videos__profile__pr...
651,853
Returns an iterator of videos for the given course id. Args: course_id (String) sort_field (VideoSortField) sort_dir (SortDirection) Returns: A generator expression that contains the videos found, sorted by the given field and direction, with ties broken by edx_video_id...
def get_videos_for_course(course_id, sort_field=None, sort_dir=SortDirection.asc, pagination_conf=None): return _get_videos_for_filter( {'courses__course_id': six.text_type(course_id), 'courses__is_hidden': False}, sort_field, sort_dir, pagination_conf, )
651,854
Soft deletes video for particular course. Arguments: course_id (str): id of the course edx_video_id (str): id of the video to be hidden
def remove_video_for_course(course_id, edx_video_id): course_video = CourseVideo.objects.get(course_id=course_id, video__edx_video_id=edx_video_id) course_video.is_hidden = True course_video.save()
651,855
Returns an iterator of videos that match the given list of ids. Args: edx_video_ids (list) sort_field (VideoSortField) sort_dir (SortDirection) Returns: A generator expression that contains the videos found, sorted by the given field and direction, with ties broken by e...
def get_videos_for_ids( edx_video_ids, sort_field=None, sort_dir=SortDirection.asc ): videos, __ = _get_videos_for_filter( {"edx_video_id__in":edx_video_ids}, sort_field, sort_dir, ) return videos
651,856
Adds the destination_course_id to the videos taken from the source_course_id Args: source_course_id: The original course_id destination_course_id: The new course_id where the videos will be copied
def copy_course_videos(source_course_id, destination_course_id): if source_course_id == destination_course_id: return course_videos = CourseVideo.objects.select_related('video', 'video_image').filter( course_id=six.text_type(source_course_id) ) for course_video in course_videos: ...
651,858
Writes transcript file to file system. Arguments: video_id (str): Video id of the video transcript file is attached. language_code (str): Language code of the transcript. file_format (str): File format of the transcript file. static_dir (str): The Directory to store transcript file....
def create_transcript_file(video_id, language_code, file_format, resource_fs, static_dir): transcript_filename = '{video_id}-{language_code}.srt'.format( video_id=video_id, language_code=language_code ) transcript_data = get_video_transcript_data(video_id, language_code) if transcri...
651,860
Creates xml for transcripts. For each transcript element, an associated transcript file is also created in course OLX. Arguments: video_id (str): Video id of the video. video_el (Element): lxml Element object static_dir (str): The Directory to store transcript file. resource_fs ...
def create_transcripts_xml(video_id, video_el, resource_fs, static_dir): video_transcripts = VideoTranscript.objects.filter(video__edx_video_id=video_id).order_by('language_code') # create transcripts node only when we have transcripts for a video if video_transcripts.exists(): transcripts_el =...
651,861
Imports transcript file from file system and creates transcript record in DS. Arguments: edx_video_id (str): Video id of the video. language_code (unicode): Language code of the requested transcript. file_name (unicode): File name of the transcript file. provider (unicode): Transcri...
def import_transcript_from_fs(edx_video_id, language_code, file_name, provider, resource_fs, static_dir): file_format = None transcript_data = get_video_transcript_data(edx_video_id, language_code) # First check if transcript record does not exist. if not transcript_data: # Read file from ...
651,863
Makes an image from gridded visibilities and saves it to a FITS file. Args: imager (oskar.Imager): Handle to configured imager. grid_data (numpy.ndarray): Final visibility grid. grid_norm (float): Grid normalisation to apply. output_file (str): ...
def save_image(imager, grid_data, grid_norm, output_file): # Make the image (take the FFT, normalise, and apply grid correction). imager.finalise_plane(grid_data, grid_norm) grid_data = numpy.real(grid_data) # Trim the image if required. border = (imager.plane_size - imager.image_size) // 2 ...
651,919
Add a Scheduling Block to the Configuration Database. The configuration dictionary must match the schema defined in in the schema_path variable at the top of the function. Args: config (dict): Scheduling Block instance request configuration. schema_path (str): Path to schema file used to v...
def add_scheduling_block(config, schema_path=None): if schema_path is None: schema_path = os.path.join(os.path.dirname(__file__), 'sbi_post.json') schema = load_schema(schema_path) jsonschema.validate(config, schema) # Add the scheduling block to the dat...
651,925
Subscribe to the specified object type. Returns an EventQueue object which can be used to query events associated with the object type for this subscriber. Args: object_type (str): Object type subscriber (str): Subscriber name callback_handler (function, optional): Callback handler...
def subscribe(object_type: str, subscriber: str, callback_handler: Callable = None) -> EventQueue: key = _keys.subscribers(object_type) DB.remove_from_list(key, subscriber) DB.append_to_list(key, subscriber) return EventQueue(object_type, subscriber, callback_handler)
651,934
Get the list of subscribers to events of the object type. Args: object_type (str): Type of object. Returns: List[str], list of subscriber names.
def get_subscribers(object_type: str) -> List[str]: return DB.get_list(_keys.subscribers(object_type))
651,935
Get list of event ids for the object with the specified key. Args: object_key (str): Key of an object in the database.
def _get_events_list(object_key: str) -> List[str]: return DB.get_list(_keys.events_list(object_key))
651,937
Get the list of event data for the object with the specified key. Args: object_key (str): Key of an object in the database.
def _get_events_data(object_key: str) -> List[dict]: events_data = [] key = _keys.events_data(object_key) for event_id in _get_events_list(object_key): event_dict = literal_eval(DB.get_hash_value(key, event_id)) events_data.append(event_dict) return events_data
651,938
Publish and event to all subscribers. - Adds the event id to the published event list for all subscribers. - Adds the event data to the published event data for all subscribers. - Publishes the event id notification to all subscribers. Args: event (Event): Event object to publish.
def _publish_to_subscribers(event: Event): subscribers = get_subscribers(event.object_type) # Add the event to each subscribers published list for sub in subscribers: DB.prepend_to_list(_keys.published(event.object_type, sub), event.id, pipeline=True) event_d...
651,940
Update the events list and events data for the object. - Adds the event Id to the list of events for the object. - Adds the event data to the hash of object event data keyed by event id. Args: object_key (str): Key of the object being updated. event (Event): Event object
def _update_object(object_key: str, event: Event): events_list_key = _keys.events_list(object_key) events_data_key = _keys.events_data(object_key) event_dict = deepcopy(event.config) event_dict.pop('id') DB.append_to_list(events_list_key, event.id, pipeline=True) DB.set_hash_value(events_da...
651,941
Return an event key for the event on the object type. This must be a unique event id for the object. Args: object_type (str): Type of object Returns: str, event id
def _get_event_id(object_type: str) -> str: key = _keys.event_counter(object_type) DB.watch(key, pipeline=True) count = DB.get_value(key) DB.increment(key) DB.execute() if count is None: count = 0 return '{}_event_{:08d}'.format(object_type, int(count))
651,942
Initialise a state object. Args: allowed_states (List[str]): List of allowed states. allowed_transitions (dict): Dict of allowed state transitions allowed_target_states (dict): Dict of allowed target states
def __init__(self, object_id: str, allowed_states: List[str], allowed_transitions: dict, allowed_target_states: dict): self._id = object_id self._type = STATES_KEY # object type self._key = '{}:{}'.format(STATES_KEY, self._id) self._allowed_states = [state.lowe...
651,946
Set the target state. Args: value (str): New value for target state force (bool): If true, ignore allowed transitions Returns: datetime, update timestamp Raises: RuntimeError, if it is not possible to currently set the target state. ...
def update_target_state(self, value: str, force: bool = True) -> datetime: value = value.lower() if not force: current_state = self.current_state if current_state == 'unknown': raise RuntimeError("Unable to set target state when current " ...
651,949
Update the current state. Args: value (str): New value for sdp state force (bool): If true, ignore allowed transitions Returns: datetime, update timestamp Raises: ValueError: If the specified current state is not allowed.
def update_current_state(self, value: str, force: bool = False) -> datetime: value = value.lower() if not force: current_state = self.current_state # IF the current state is unknown, it can be set to any of the # allowed states, o...
651,950
Return a dictionary used to initialise a state object. This method is used to obtain a dictionary/hash describing the initial state of SDP or a service in SDP. Args: initial_state (str): Initial state. Returns: dict, Initial state configuration
def _initialise(self, initial_state: str = 'unknown') -> dict: initial_state = initial_state.lower() if initial_state != 'unknown' and \ initial_state not in self._allowed_states: raise ValueError('Invalid initial state: {}'.format(initial_state)) _initial_st...
651,951
Update the state of type specified (current or target). Args: state_type(str): Type of state to update, current or target. value (str): New state value. Returns: timestamp, current time
def _update_state(self, state_type: str, value: str) -> datetime: timestamp = datetime.utcnow() field = '{}_state'.format(state_type) old_state = DB.get_hash_value(self._key, field) DB.set_hash_value(self._key, field, value, pipeline=True) DB.set_hash_value(self._key, '{...
651,952
Add Scheduling Block to the database. Args: config_dict (dict): SBI configuration
def add_sched_block_instance(self, config_dict): # Get schema for validation schema = self._get_schema() LOG.debug('Adding SBI with config: %s', config_dict) # Validates the schema validate(config_dict, schema) # Add status field and value to the data u...
651,954
Get details of scheduling or processing block Args: block_ids (list): List of block IDs
def get_block_details(self, block_ids): # Convert input to list if needed if not hasattr(block_ids, "__iter__"): block_ids = [block_ids] for _id in block_ids: block_key = self._db.get_block(_id)[0] block_data = self._db.get_all_field_value(block_key)...
651,959
Send the pulsar data to the ftp server Args: config (dict): Dictionary of settings log (logging.Logger): Python logging object obs_id: observation id beam_id: beam id
def send(self, config, log, obs_id, beam_id): log.info('Starting Pulsar Data Transfer...') socket = self._ftp.transfercmd('STOR {0}_{1}'.format(obs_id, beam_id)) socket.send(json.dumps(config).encode()) socket.send(bytearray(1000 * 1000)) # Overwrites the metadata name ...
651,974
Configure an SBI for this subarray. Args: sbi_config (str): SBI configuration JSON Returns: str,
def configure(self, sbi_config: str): # print(sbi_config) config_dict = json.loads(sbi_config) self.debug_stream('SBI configuration:\n%s', json.dumps(config_dict, indent=2)) try: sbi = Subarray(self.get_name()).configure_sbi(config_dict) ...
651,978
Return a datetime object from an isoformat string. Args: value (str): Datetime string in isoformat.
def datetime_from_isoformat(value: str): if sys.version_info >= (3, 7): return datetime.fromisoformat(value) return datetime.strptime(value, '%Y-%m-%dT%H:%M:%S.%f')
651,980
Add any missing SBI workflow definitions as placeholders. This is a utility function used in testing and adds mock / test workflow definitions to the database for workflows defined in the specified SBI config. Args: sbi_config (dict): SBI configuration dictionary.
def add_workflow_definitions(sbi_config: dict): registered_workflows = [] for i in range(len(sbi_config['processing_blocks'])): workflow_config = sbi_config['processing_blocks'][i]['workflow'] workflow_name = '{}:{}'.format(workflow_config['id'], workf...
651,995
Select a random version. Args: max_major (int, optional) maximum major version max_minor (int, optional) maximum minor version max_patch (int, optional) maximum patch version Returns: str, Version String
def generate_version(max_major: int = 1, max_minor: int = 7, max_patch: int = 15) -> str: major = randint(0, max_major) minor = randint(0, max_minor) patch = randint(0, max_patch) return '{:d}.{:d}.{:d}'.format(major, minor, patch)
651,996
Generate a Scheduling Block data object. Args: date (datetime.datetime): UTC date of the SBI project (str): Project Name programme_block (str): Programme Returns: str, Scheduling Block Instance (SBI) ID.
def generate_sb(date: datetime.datetime, project: str, programme_block: str) -> dict: date = date.strftime('%Y%m%d') instance_id = randint(0, 9999) sb_id = 'SB-{}-{}-{:04d}'.format(date, project, instance_id) return dict(id=sb_id, project=project, programme_block=programme_block)
651,997
Generate a PB configuration dictionary. Args: pb_id (str): Processing Block Id pb_config (dict, optional) PB configuration. workflow_config (dict, optional): Workflow configuration Returns: dict, PB configuration dictionary.
def generate_pb_config(pb_id: str, pb_config: dict = None, workflow_config: dict = None) -> dict: if workflow_config is None: workflow_config = dict() if pb_config is None: pb_config = dict() pb_type = pb_config.get('type', choice(PB_TYPES))...
651,998
Create a PB object. Args: pb_id (str): Processing Block Identifier Raises: KeyError, if the specified PB does not exist
def __init__(self, pb_id): SchedulingObject.__init__(self, PB_KEY, pb_id) self._check_object_exists()
652,010
Generate a Processing Block (PB) Instance ID. Args: date (datetime.datetime): UTC date of the PB Returns: str, Processing Block ID
def get_id(date: datetime.datetime) -> str: date = date.strftime('%Y%m%d') return 'PB-{}-{}-{:03d}'.format(date, 'sip', randint(0, 100))
652,011
Add assigned resource to the processing block. Args: resource_type (str): Resource type value: Resource value parameters (dict, optional): Parameters specific to the resource
def add_assigned_resource(self, resource_type: str, value: Union[str, int, float, bool], parameters: dict = None): if parameters is None: parameters = dict() resources = DB.get_hash_value(self.key, 'resources_assigned') ...
652,015
Remove assigned resources from the processing block. All matching resources will be removed. If only type is specified all resources of the specified type will be removed. If value and/or parameters are specified they will be used for matching the resource to remove. Args: ...
def remove_assigned_resource(self, resource_type: str, value: Union[str, int, float, bool] = None, parameters: dict = None): resources = DB.get_hash_value(self.key, 'resources_assigned') resources = ast.literal_eval(resources) ...
652,016
Set the subarray parameters. Args: parameters_dict (dict): Dictionary of Subarray parameters
def set_parameters(self, parameters_dict): DB.set_hash_value(self._key, 'parameters', parameters_dict) self.publish("parameters_updated")
652,022
Add a new SBI to the database associated with this subarray. Args: sbi_config (dict): SBI configuration. schema_path (str, optional): Path to the SBI config schema.
def configure_sbi(self, sbi_config: dict, schema_path: str = None): if not self.active: raise RuntimeError("Unable to add SBIs to inactive subarray!") sbi_config['subarray_id'] = self._id sbi = SchedulingBlockInstance.from_config(sbi_config, schema_path) self._add_sb...
652,024
Initialise the event queue. Subscribes to Redis pub/sub events of the given object type. Args: object_type (str): Object type subscriber (str): Subscriber name
def __init__(self, object_type: str, subscriber: str, callback_handler: Callable = None): self._queue = DB.pub_sub() if callback_handler is None: self._queue.subscribe(object_type) else: self._queue.subscribe(**{object_type: callback_handler}) ...
652,029
Add a workflow definition to the Configuration Database. Templates are expected to be found in a directory tree with the following structure: - workflow_id: |- workflow_version |- stage_id |- stage_version |- <templates> Args...
def add(workflow_definition: dict, templates_root: str): schema_path = join(dirname(__file__), 'schema', 'workflow_definition.json') with open(schema_path, 'r') as file: schema = json.loads(file.read()) jsonschema.validate(workflow_definition, schema) _id = workflow_definition['id'] _...
652,034
Delete workflow definitions. Args: workflow_id (str, optional): Optional workflow identifier workflow_version (str, optional): Optional workflow identifier version If workflow_id and workflow_version are None, delete all workflow definitions.
def delete(workflow_id: str = None, workflow_version: str = None): if workflow_id is None and workflow_version is None: keys = DB.get_keys("workflow_definitions:*") DB.delete(*keys) elif workflow_id is not None and workflow_version is None: keys = DB.get_keys("workflow_definitions:{...
652,036
Get a workflow definition from the Configuration Database. Args: workflow_id (str): Workflow identifier workflow_version (str): Workflow version Returns: dict, Workflow definition dictionary
def get_workflow(workflow_id: str, workflow_version: str) -> dict: name = "workflow_definitions:{}:{}".format(workflow_id, workflow_version) workflow = DB.get_hash_dict(name) workflow['stages'] = ast.literal_eval(workflow['stages']) return workflow
652,037
Publish a scheduling object event. Args: object_id (str): ID of the scheduling object event_type (str): Type of event. event_data (dict, optional): Event data.
def publish(self, object_id: str, event_type: str, event_data: dict = None): object_key = SchedulingObject.get_key(self.type, object_id) publish(event_type=event_type, event_data=event_data, object_type=self.type, object_id=object_...
652,047
Abort the workflow. TODO(BMo): This function currently does nothing as the abort flag is hardcoded to False! This function is used by `execute_processing_block`. Args: pb (ProcessingBlock): Configuration database Processing block object. workflow_stage_dict (dict): Workflow stage ...
def _abort_workflow(pb: ProcessingBlock, workflow_stage_dict: dict, docker: DockerSwarmClient): # TODO(BMo) Ask the database if the abort flag on the PB is set. _abort_flag = False if _abort_flag: for workflow_stage in pb.workflow_stages: for service_id, _ in \ ...
652,050
Check if the workflow is complete. This function checks if the entire workflow is complete. This function is used by `execute_processing_block`. Args: workflow_stage_dict (dict): Workflow metadata dictionary. Returns: bool, True if the workflow is complete, otherwise False.
def _workflow_complete(workflow_stage_dict: dict): # Check if all stages are complete, if so end the PBC by breaking # out of the while loop complete_stages = [] for _, stage_config in workflow_stage_dict.items(): complete_stages.append((stage_config['status'] == 'complete')) if all(com...
652,051
Execute a processing block. Celery tasks that executes a workflow defined in a Configuration database Processing Block data object. Args: pb_id (str): The PB id for the PBC log_level (str): Python logging level.
def execute_processing_block(pb_id: str, log_level='DEBUG'): init_logger('sip', show_log_origin=True, propagate=False, log_level=log_level) LOG.info('+' * 40) LOG.info('+ Executing Processing block: %s!', pb_id) LOG.info('+' * 40) LOG.info('Processing Block Controller version: %...
652,052
Add a Processing Block to the queue. When a new entry it added, the queue is (re-)sorted by priority followed by insertion order (older blocks with equal priority are first). Args: block_id (str): Processing Block Identifier priority (int): Processing Block sche...
def put(self, block_id, priority, pb_type='offline'): if pb_type not in ('offline', 'realtime'): raise ValueError('Invalid PB type.') with self._mutex: added_time = datetime.datetime.utcnow().isoformat() entry = (priority, sys.maxsize-self._index, block_id, ...
652,054
Remove a Processing Block from the queue. Args: block_id (str):
def remove(self, block_id): with self._mutex: entry = self._block_map[block_id] self._queue.remove(entry)
652,056
Initialise variables. Args: object_type (str): Type of object. object_id (str): ID of the object.
def __init__(self, object_type: str, object_id: str = None): if object_type not in [PB_KEY, SBI_KEY]: raise RuntimeError('Invalid object type') self._type = object_type self._id = object_id self._key = self.get_key(object_type, object_id) self._check_object_e...
652,062
Publish an event associated with the scheduling object. Note: Ideally publish should not be used directly but by other methods which perform actions on the object. Args: event_type (str): Type of event. event_data (dict, optional): Event data.
def publish(self, event_type: str, event_data: dict = None): import inspect import os.path _stack = inspect.stack() _origin = os.path.basename(_stack[3][1]) + '::' + \ _stack[3][3]+'::L{}'.format(_stack[3][2]) publish(event_type=event_type, e...
652,066
Return service state data object key. Args: subsystem (str): Subsystem the service belongs to name (str): Name of the Service version (str): Version of the Service Returns: str, Key used to store the service state data object
def get_service_state_object_id(subsystem: str, name: str, version: str) -> str: return '{}:{}:{}'.format(subsystem, name, version)
652,070
Create new docker services. Args: compose_str (string): Docker compose 'file' string Return: service_names, list
def create_services(self, compose_str: str) -> list: # Raise an exception if we are not a manager if not self._manager: raise RuntimeError('Services can only be run on ' 'swarm manager nodes') # Initialise empty list services_ids = [] ...
652,072
Create new docker volumes. Only the manager nodes can create a volume Args: volume_name (string): Name for the new docker volume driver_spec (string): Driver for the docker volume
def create_volume(self, volume_name: str, driver_spec: str = None): # Default values if driver_spec: driver = driver_spec else: driver = 'local' # Raise an exception if we are not a manager if not self._manager: raise RuntimeError('Se...
652,073
Removes/stops a docker service. Only the manager nodes can delete a service Args: service (string): Service name or ID
def delete_service(self, service: str): # Raise an exception if we are not a manager if not self._manager: raise RuntimeError('Services can only be deleted ' 'on swarm manager nodes') # Remove service self._api_client.remove_service(se...
652,074
Removes/stops a docker volume. Only the manager nodes can delete a volume Args: volume_name (string): Name of the volume
def delete_volume(self, volume_name: str): # Raise an exception if we are not a manager if not self._manager: raise RuntimeError('Volumes can only be deleted ' 'on swarm manager nodes') # Remove volume self._api_client.remove_volume(vo...
652,076
Get the name of the docker service. Only the manager nodes can retrieve service name Args: service_id (string): List of service ID Returns: string, name of the docker service
def get_service_name(self, service_id: str) -> str: # Raise an exception if we are not a manager if not self._manager: raise RuntimeError('Only the Swarm manager node can retrieve all' ' the services details.') service = self._client.services....
652,079
Get details of a service. Only the manager nodes can retrieve service details Args: service_id (string): List of service id Returns: dict, details of the service
def get_service_details(self, service_id: str) -> dict: # Raise an exception if we are not a manager if not self._manager: raise RuntimeError('Only the Swarm manager node can retrieve all' ' the services details.') service = self._client.servi...
652,080
Get the state of the service. Only the manager nodes can retrieve service state Args: service_id (str): Service id Returns: str, state of the service
def get_service_state(self, service_id: str) -> str: # Get service service = self._client.services.get(service_id) # Get the state of the service for service_task in service.tasks(): service_state = service_task['DesiredState'] return service_state
652,081
Get details of a node. Only the manager nodes can retrieve details of a node Args: node_id (list): List of node ID Returns: dict, details of the node
def get_node_details(self, node_id: list) -> dict: # Raise an exception if we are not a manager if not self._manager: raise RuntimeError('Only the Swarm manager node can ' 'retrieve node details.') node = self._client.nodes.get(node_id) ...
652,083
Get details of a container. Args: container_id_or_name (string): docker container id or name Returns: dict, details of the container
def get_container_details(self, container_id_or_name: str) -> dict: container = self._client.containers.get(container_id_or_name) return container.attrs
652,085
Get details of the volume. Args: volume_name (str): Name of the volume Returns: dict, details of the volume
def get_volume_details(self, volume_name: str) -> dict: if volume_name not in self.volumes: raise RuntimeError('No such volume found: ', volume_name) volume = self._client.volumes.get(volume_name) return volume.attrs
652,087
Get the actual replica level of a service. Args: service_id (str): docker swarm service id Returns: str, replicated level of the service
def get_actual_replica(self, service_id: str) -> str: # Raise an exception if we are not a manager if not self._manager: raise RuntimeError('Only the Swarm manager node can retrieve ' 'replication level of the service') service_details = self....
652,088
Get the replication level of a service. Args: service_id (str): docker swarm service id Returns: str, replication level of the service
def get_replicas(self, service_id: str) -> str: # Initialising empty list replicas = [] # Raise an exception if we are not a manager if not self._manager: raise RuntimeError('Only the Swarm manager node can retrieve ' 'replication leve...
652,089
Update label of a node. Args: node_name (string): Name of the node. labels (dict): Label to add to the node
def update_labels(self, node_name: str, labels: dict): # Raise an exception if we are not a manager if not self._manager: raise RuntimeError('Only the Swarm manager node can update ' 'node details.') # Node specification node_spec = {'...
652,090
Parse the docker compose file. Args: service_config (dict): Service configurations from the compose file service_name (string): Name of the services service_list (dict): Service configuration list Returns: dict, service specifications extracted from the ...
def _parse_services(self, service_config: dict, service_name: str, service_list: dict) -> dict: for key, value in service_list['services'][service_name].items(): service_config[key] = value if 'command' in key: key = "args" ...
652,091
Parse deploy key. Args: deploy_values (dict): deploy configuration values service_config (dict): Service configuration
def _parse_deploy(self, deploy_values: dict, service_config: dict): # Initialising empty dictionary mode = {} for d_value in deploy_values: if 'restart_policy' in d_value: restart_spec = docker.types.RestartPolicy( **deploy_values[d_value...
652,092
Parse ports key. Args: port_values (dict): ports configuration values Returns: dict, Ports specification which contains exposed ports
def _parse_ports(port_values: dict) -> dict: # Initialising empty dictionary endpoints = {} for port_element in port_values: target_port = port_element.split(':') for port in target_port: endpoints[int(port)] = int(port) # Setting the ty...
652,093
Parse volumes key. Args: volume_values (dict): volume configuration values Returns: string, volume specification with mount source and container path
def _parse_volumes(volume_values: dict) -> str: for v_values in volume_values: for v_key, v_value in v_values.items(): if v_key == 'source': if v_value == '.': source = os.path.dirname( os.path.abspath(_...
652,094
Parse resources key. Args: resource_values (dict): resource configurations values resource_name (string): Resource name Returns: dict, resources specification
def _parse_resources(resource_values: dict, resource_name: str) -> dict: # Initialising empty dictionary resources = {} for r_values in resource_values[resource_name]: if 'limits' in r_values: for r_key, r_value in \ resource_values[r...
652,095
Parse network key. Args: service_list (dict): Service configurations Returns: list, List of networks
def _parse_networks(service_list: dict) -> list: # Initialising empty list networks = [] for n_values in service_list['networks'].values(): for n_key, n_value in n_values.items(): if 'name' in n_key: networks.append(n_value) retur...
652,096
Parse log key. Args: log_values (dict): logging configuration values service_config (dict): Service specification
def _parse_logging(log_values: dict, service_config: dict): for log_key, log_value in log_values.items(): if 'driver' in log_key: service_config['log_driver'] = log_value if 'options' in log_key: service_config['log_driver_options'] = log_value
652,097
Initialise the Scheduler. Args: report_interval (float): Minimum interval between reports, in s max_pbcs (int): Maximum number of concurrent PBCs (and therefore PBs) that can be running.
def __init__(self, report_interval: float = 5.0, max_pbcs: int = 4): LOG.info('Starting Processing Block Scheduler.') self._queue = self._init_queue() self._pb_events = ProcessingBlockList().subscribe(__service_name__) self._report_interval = report_interval self._num_pb...
652,098
Update the current state of a service. Updates the current state of services after their target state has changed. Args: service (ServiceState): Service state object to update
def _update_service_current_state(service: ServiceState): LOG.debug("Setting current state from target state for %s", service.id) service.update_current_state(service.target_state)
652,106
Update the target states of services based on SDP target state. When we get a new target state this function is called to ensure components receive the target state(s) and/or act on them. Args: sdp_target_state (str): Target state of SDP
def _update_services_target_state(sdp_target_state: str): service_states = get_service_state_list() # Set the target state of services for service in service_states: if service.current_state != sdp_target_state: LOG.debug('Setting the target state of %s to be %s', service.id, ...
652,108
Create an event object from an event dictionary object. Args: config (dict): Event Configuration dictionary.
def from_config(cls, config: dict): timestamp = config.get('timestamp', None) return cls(config.get('id'), config.get('type'), config.get('data', dict()), config.get('origin', None), timestamp, config...
652,117