code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
_logT = self._devProxy.get_logging_target() if 'device::sip_sdp_logger' not in _logT: try: self._devProxy.add_logging_target('device::sip_sdp/elt/logger') self.info_stream("Test of Tango logging from " "'tc_tango_maste...
def always_executed_hook(self)
Run for each command.
17.971531
17.404758
1.032564
# Only accept new SBIs if the SDP is on. if self._sdp_state.current_state != 'on': raise RuntimeWarning('Unable to configure SBIs unless SDP is ' '\'on\'.') # Check that the new SBI is not already registered. sbi_config_dict = json....
def configure(self, value)
Schedule an offline only SBI with SDP.
4.049398
3.759782
1.07703
LOG.debug('Getting state of service %s', service_id) services = get_service_id_list() service_ids = [s for s in services if service_id in s] if len(service_ids) != 1: return 'Service not found! services = {}'.format(str(services)) subsystem, name, version = s...
def _get_service_state(service_id: str)
Get the Service state object for the specified id.
4.274694
3.800432
1.124792
state = self._get_service_state(service_id) return state.current_state
def get_current_service_state(self, service_id: str)
Get the state of a SDP service.
5.877756
4.271073
1.376178
state = self._get_service_state(service_id) return state.target_state
def get_target_service_state(self, service_id: str)
Get the state of a SDP service.
5.85834
4.484889
1.30624
_current_state = self._sdp_state.current_state _allowed_target_states = self._sdp_state.allowed_target_states[ _current_state] return json.dumps(dict(allowed_target_sdp_states= _allowed_target_states))
def allowed_target_sdp_states(self)
Return a list of allowed target states for the current state.
4.341751
3.985035
1.089514
LOG.info('Setting SDP target state to %s', state) if self._sdp_state.current_state == state: LOG.info('Target state ignored, SDP is already "%s"!', state) if state == 'on': self.set_state(DevState.ON) if state == 'off': self.set_state(DevState...
def target_sdp_state(self, state)
Update the target state of SDP.
2.710578
2.603169
1.041261
return json.dumps(dict(uptime='{:.3f}s' .format((time.time() - self._start_time))))
def health(self)
Health check method, returns the up-time of the device.
7.808577
6.188267
1.261836
# TODO(BMo) change this to a pipe? sbi_list = SchedulingBlockInstanceList() return json.dumps(dict(active=sbi_list.active, completed=sbi_list.completed, aborted=sbi_list.aborted))
def scheduling_block_instances(self)
Return the a JSON dict encoding the SBIs known to SDP.
7.731175
6.157853
1.255499
pb_list = ProcessingBlockList() # TODO(BMo) realtime, offline etc. return json.dumps(dict(active=pb_list.active, completed=pb_list.completed, aborted=pb_list.aborted))
def processing_blocks(self)
Return the a JSON dict encoding the PBs known to SDP.
11.068303
8.619407
1.284114
# Get the list and number of Tango PB devices tango_db = Database() pb_device_class = "ProcessingBlockDevice" pb_device_server_instance = "processing_block_ds/1" pb_devices = tango_db.get_device_name(pb_device_server_instance, ...
def processing_block_devices(self)
Get list of processing block devices.
3.885194
3.754627
1.034775
if state == 'init': self._service_state.update_current_state('init', force=True) self.set_state(DevState.INIT) elif state == 'on': self.set_state(DevState.ON) self._service_state.update_current_state('on')
def _set_master_state(self, state)
Set the state of the SDPMaster.
3.788255
3.671178
1.031891
tango_db = Database() LOG.info("Registering Subarray devices:") device_info = DbDevInfo() # pylint: disable=protected-access device_info._class = "SubarrayDevice" device_info.server = "subarray_ds/1" for index in range(16): device_info.name = "sip_sdp/elt/subarray_{:02d}".forma...
def register_subarray_devices()
Register subarray devices.
4.696356
4.529972
1.03673
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'], workflow_config['version']) if workflow_name ...
def add_workflow_definitions(sbi_config: dict)
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.
2.987426
3.115995
0.958739
major = randint(0, max_major) minor = randint(0, max_minor) patch = randint(0, max_patch) return '{:d}.{:d}.{:d}'.format(major, minor, patch)
def generate_version(max_major: int = 1, max_minor: int = 7, max_patch: int = 15) -> str
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
2.102667
2.08704
1.007488
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)
def generate_sb(date: datetime.datetime, project: str, programme_block: str) -> dict
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.
3.108602
3.20681
0.969375
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)) workflow_id = workflow_config.get('id') if workflow_id is None: if pb_type == 'offline': workflow_id = choice(OFFLI...
def generate_pb_config(pb_id: str, pb_config: dict = None, workflow_config: dict = None) -> dict
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.
2.241325
2.24395
0.99883
Union[dict, List[dict]] = None, register_workflows=False) -> dict: if isinstance(workflow_config, dict): workflow_config = [workflow_config] if isinstance(pb_config, dict): pb_config = [pb_config] utc_now = datetime.datetime.utcnow() p...
def generate_sbi_config(num_pbs: int = 3, project: str = 'sip', programme_block: str = 'sip_demos', pb_config: Union[dict, List[dict]] = None, workflow_config
Generate a SBI configuration dictionary. Args: num_pbs (int, optional): Number of Processing Blocks (default = 3) project (str, optional): Project to associate the SBI with. programme_block (str, optional): SBI programme block pb_config (dict, List[dict], optional): PB configuration...
2.44785
2.559039
0.956551
Union[dict, List[dict]] = None, register_workflows=True) -> str: return json.dumps(generate_sbi_config(num_pbs, project, programme_block, pb_config, workflow_config, register_workflow...
def generate_sbi_json(num_pbs: int = 3, project: str = 'sip', programme_block: str = 'sip_demos', pb_config: Union[dict, List[dict]] = None, workflow_config
Return a JSON string used to configure an SBI.
4.158797
3.760178
1.106011
# # Tango Manual Appendix 9 gives the format # argin[0] = millisecond Unix timestamp # argin[1] = log level # argin[2] = the source log device name # argin[3] = the log message # argin[4] = Not used - reserved # argin[5] = thread identifier of ori...
def log(self, argin)
Log a command for the SDP STango ubsystem devices.
4.642043
4.68275
0.991307
try: sbi_details = DB.get_block_details([block_id]).__next__() sbi_details['processing_blocks'] = [] pb_ids = sbi_details['processing_block_ids'] for pb_details in DB.get_block_details(pb_ids): sbi_details['processing_blocks'].append(pb_details) del sbi_detai...
def get(block_id)
Scheduling block detail resource.
3.739199
3.631879
1.02955
_url = get_root_url() LOG.debug('Requested delete of SBI %s', block_id) try: DB.delete_sched_block_instance(block_id) response = dict(message='Deleted block: _id = {}'.format(block_id)) response['_links'] = { 'list': '{}/scheduling-blocks'.format(_url) } ...
def delete(block_id)
Scheduling block detail resource.
5.505509
5.338934
1.0312
for i in range(num_blocks): _root = '{}-{}'.format(strftime("%Y%m%d", gmtime()), project) yield '{}-sb{:03d}'.format(_root, i + start_id), \ '{}-sbi{:03d}'.format(_root, i + start_id)
def _scheduling_block_ids(num_blocks, start_id, project)
Generate Scheduling Block instance ID
3.964534
3.833845
1.034088
processing_blocks = [] num_blocks = random.randint(min_blocks, max_blocks) for i in range(start_id, start_id + num_blocks): _id = 'sip-pb{:03d}'.format(i) block = dict(id=_id, resources_requirement={}, workflow={}) processing_blocks.append(block) return processing_blocks
def _generate_processing_blocks(start_id, min_blocks=0, max_blocks=4)
Generate a number of Processing Blocks
3.604536
3.455447
1.043146
pb_id = start_pb_id for sb_id, sbi_id in _scheduling_block_ids(num_blocks, start_sbi_id, project): sub_array_id = 'subarray-{:02d}'.format(random.choice(range(5))) config = dict(id=sbi_id, sched_block_id=sb_id, ...
def _scheduling_block_config(num_blocks=5, start_sbi_id=0, start_pb_id=0, project='sip')
Return a Scheduling Block Configuration dictionary
3.124202
3.149296
0.992032
db_client = ConfigDb() if clear: LOG.info('Resetting database ...') db_client.clear() start_sbi_id = 0 start_pb_id = 0 else: start_sbi_id = len(db_client.get_sched_block_instance_ids()) start_pb_id = len(db_client.get_processing_block_ids()) LOG.info...
def add_scheduling_blocks(num_blocks, clear=True)
Add a number of scheduling blocks to the db.
3.560584
3.47775
1.023818
# Configure the logger log = logging.getLogger('SIP.EC.PCI.DB') handler = logging.StreamHandler() handler.setFormatter(logging.Formatter( '%(name)-20s | %(filename)-15s | %(levelname)-5s | %(message)s')) log.addHandler(handler) log.setLevel(os.getenv('SIP_PCI_LOG_LEVEL', 'INFO')) ...
def main()
Main function
4.040732
4.034034
1.00166
LOG.info('Starting SDP PB devices.') return run([ProcessingBlockDevice], verbose=True, msg_stream=sys.stdout, args=args, **kwargs)
def main(args=None, **kwargs)
Start the Processing Block device server.
25.229055
16.333445
1.544626
date = date.strftime('%Y%m%d') return 'PB-{}-{}-{:03d}'.format(date, 'sip', randint(0, 100))
def get_id(date: datetime.datetime) -> str
Generate a Processing Block (PB) Instance ID. Args: date (datetime.datetime): UTC date of the PB Returns: str, Processing Block ID
7.405091
6.149051
1.204266
dependencies_str = DB.get_hash_value(self.key, 'dependencies') dependencies = [] for dependency in ast.literal_eval(dependencies_str): dependencies.append(Dependency(dependency)) return dependencies
def dependencies(self) -> List[Dependency]
Return the PB dependencies.
4.319799
4.150638
1.040755
resources_str = DB.get_hash_value(self.key, 'resources_assigned') resources_assigned = [] for resource in ast.literal_eval(resources_str): resources_assigned.append(Resource(resource)) return resources_assigned
def resources_assigned(self) -> List[Resource]
Return list of resources assigned to the PB.
3.696578
3.475971
1.063466
workflow_stages = [] stages = DB.get_hash_value(self.key, 'workflow_stages') for index in range(len(ast.literal_eval(stages))): workflow_stages.append(WorkflowStage(self.id, index)) return workflow_stages
def workflow_stages(self) -> List[WorkflowStage]
Return list of workflow stages. Returns: dict, resources of a specified pb
4.278245
5.604655
0.763338
if parameters is None: parameters = dict() resources = DB.get_hash_value(self.key, 'resources_assigned') resources = ast.literal_eval(resources) resources.append(dict(type=resource_type, value=value, parameters=parameters)) DB.se...
def add_assigned_resource(self, resource_type: str, value: Union[str, int, float, bool], parameters: dict = None)
Add assigned resource to the processing block. Args: resource_type (str): Resource type value: Resource value parameters (dict, optional): Parameters specific to the resource
3.118109
3.531799
0.882867
resources = DB.get_hash_value(self.key, 'resources_assigned') resources = ast.literal_eval(resources) new_resources = [] for resource in resources: if resource['type'] != resource_type: new_resources.append(resource) elif value is not None...
def remove_assigned_resource(self, resource_type: str, value: Union[str, int, float, bool] = None, parameters: dict = None)
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: ...
2.213204
2.417356
0.915548
LOG.debug('Aborting PB %s', self._id) self.set_status('aborted') pb_type = DB.get_hash_value(self.key, 'type') key = '{}:active'.format(self._type) DB.remove_from_list(key, self._id) key = '{}:active:{}'.format(self._type, pb_type) DB.remove_from_list(key...
def abort(self)
Abort the processing_block.
2.92181
2.757916
1.059427
timestamp = datetime.datetime.utcnow().isoformat() DB.set_hash_value(self.key, 'updated', timestamp)
def _mark_updated(self)
Update the updated timestamp.
7.963903
5.796149
1.373999
_url = get_root_url() LOG.debug('GET Sub array list') sub_array_ids = sorted(DB.get_sub_array_ids()) response = dict(sub_arrays=[]) for array_id in sub_array_ids: array_summary = dict(sub_arrary_id=array_id) block_ids = DB.get_sub_array_sbi_ids(array_id) LOG.debug('Sub...
def get()
Subarray list. This method will list all sub-arrays known to SDP.
3.831147
3.713282
1.031741
_url = get_root_url() LOG.debug("POST subarray SBI.") # TODO(BM) generate sbi_config .. see report ... # ... will need to add this as a util function on the db... sbi_config = {} DB.add_sbi(sbi_config) response = dict() return response, status.HTTP_200_OK
def post()
Generate a SBI.
18.665506
15.367127
1.214639
DB.set_hash_value(self._key, 'parameters', parameters_dict) self.publish("parameters_updated")
def set_parameters(self, parameters_dict)
Set the subarray parameters. Args: parameters_dict (dict): Dictionary of Subarray parameters
11.747906
19.511852
0.602091
return ast.literal_eval(DB.get_hash_value(self._key, 'sbi_ids'))
def sbi_ids(self) -> List[str]
Get the list of SBI Ids. Returns: list, list of SBI ids associated with this subarray.
10.210757
17.406168
0.586617
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_sbi_id(sbi_config['id']) return sbi
def configure_sbi(self, sbi_config: dict, schema_path: str = None)
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.
5.654173
4.935269
1.145667
for sbi_id in self.sbi_ids: sbi = SchedulingBlockInstance(sbi_id) sbi.abort() self.set_state('ABORTED')
def abort(self)
Abort all SBIs associated with the subarray.
5.422658
4.161509
1.303051
DB.set_hash_value(self._key, 'active', 'False') # Remove the subarray from each of the SBIs for sbi_id in self.sbi_ids: SchedulingBlockInstance(sbi_id).clear_subarray() DB.set_hash_value(self._key, 'sbi_ids', []) self.publish('subarray_deactivated')
def deactivate(self)
Deactivate the subarray.
6.828214
6.005342
1.137023
sbi_ids = self.sbi_ids sbi_ids.remove(sbi_id) DB.set_hash_value(self._key, 'sbi_ids', sbi_ids)
def remove_sbi_id(self, sbi_id)
Remove an SBI Identifier.
3.594414
3.464118
1.037613
sbi_ids = self.sbi_ids sbi_ids.append(sbi_id) DB.set_hash_value(self._key, 'sbi_ids', sbi_ids)
def _add_sbi_id(self, sbi_id)
Add a SBI Identifier.
3.521442
3.194925
1.102199
message = self._queue.get_message() if message and message['type'] == 'message': event_id = DB.get_event(self._pub_key, self._processed_key) event_data_str = DB.get_hash_value(self._data_key, event_id) event_dict = ast.literal_eval(event_data_str) ...
def get(self) -> Union[Event, None]
Get the latest event from the queue. Call this method to query the queue for the latest event. If no event has been published None is returned. Returns: Event or None
4.335317
4.522855
0.958536
LOG.debug('Getting published events (%s)', self._pub_key) if process: LOG.debug('Marking returned published events as processed.') DB.watch(self._pub_key, pipeline=True) event_ids = DB.get_list(self._pub_key, pipeline=True) if event_ids: ...
def get_published_events(self, process=True) -> List[Event]
Get a list of published (pending) events. Return a list of Event objects which have been published and are therefore pending to be processed. If the process argument is set to true, any events returned from this method will also be marked as processed by moving them to the processed eve...
3.039553
2.949241
1.030622
event_ids = DB.get_list(self._processed_key) events = [] for event_id in event_ids: event_str = DB.get_hash_value(self._data_key, event_id) event_dict = ast.literal_eval(event_str) event_dict['id'] = event_id event_dict['subscriber'] = sel...
def get_processed_events(self) -> List[Event]
Get all processed events. This method is intended to be used to recover events stuck in the processed state which could happen if an event handling processing an processed event goes down before completing the event processing. Returns: list[Events], list of event objects.
3.180316
3.587653
0.886461
event_ids = DB.get_list(self._processed_key) if event_id not in event_ids: raise KeyError('Unable to complete event. Event {} has not been ' 'processed (ie. it is not in the processed ' 'list).'.format(event_id)) DB.remov...
def complete_event(self, event_id: str)
Complete the specified event.
5.110884
4.744025
1.077331
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'] _version = workflow_definition['version'] _load_templa...
def add(workflow_definition: dict, templates_root: str)
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...
3.26995
3.450819
0.947587
name = "workflow_definitions:{}:{}".format(workflow_id, workflow_version) workflow_definition = dict(id=workflow_id, version=workflow_version, stages=[]) # DB.set_hash_values(name, workflow_definition) DB.save_dict(name, workflow_definition, hierarchical=False)
def register(workflow_id, workflow_version)
Register an (empty) workflow definition in the database.
5.271928
4.930244
1.069304
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:{}:*".format(workflow_id)) DB.delete(*keys) elif workflo...
def delete(workflow_id: str = None, workflow_version: str = None)
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.
2.09649
1.983495
1.056968
name = "workflow_definitions:{}:{}".format(workflow_id, workflow_version) workflow = DB.get_hash_dict(name) workflow['stages'] = ast.literal_eval(workflow['stages']) return workflow
def get_workflow(workflow_id: str, workflow_version: str) -> dict
Get a workflow definition from the Configuration Database. Args: workflow_id (str): Workflow identifier workflow_version (str): Workflow version Returns: dict, Workflow definition dictionary
6.928269
6.484854
1.068377
keys = DB.get_keys("workflow_definitions:*") known_workflows = dict() for key in keys: values = key.split(':') if values[1] not in known_workflows: known_workflows[values[1]] = list() known_workflows[values[1]].append(values[2]) return known_workflows
def get_workflows() -> dict
Get dict of ALL known workflow definitions. Returns list[dict]
3.55213
3.411962
1.041081
workflow_template_path = join(templates_root, workflow['id'], workflow['version']) for i, stage_config in enumerate(workflow['stages']): stage_template_path = join(workflow_template_path, stage_config['id'], ...
def _load_templates(workflow: dict, templates_root: str)
Load templates keys.
2.583313
2.408952
1.072381
parser = argparse.ArgumentParser(description='Register PB devices.') parser.add_argument('num_pb', type=int, help='Number of PBs devices to register.') args = parser.parse_args() log = logging.getLogger('sip.tango_control.subarray') tango_db = Database() log.info("D...
def delete_pb_devices()
Delete PBs devices from the Tango database.
4.257525
3.785743
1.124621
# Check command line arguments. if len(sys.argv) != 2: raise RuntimeError('Usage: python3 async_send.py <json config>') # Set up logging. sip_logging.init_logger(show_thread=False) # Load SPEAD configuration from JSON file. # _path = os.path.dirname(os.path.abspath(__file__)) ...
def main()
Main function for SPEAD sender module.
3.055065
2.841749
1.075065
# Calculate the time count and fraction. now = datetime.datetime.utcnow() time_full = now.timestamp() time_count = int(time_full) time_fraction = int((time_full - time_count) * (2**32 - 1)) diff = now - (now.replace(hour=0, minute=0, second=0, microsecond=0)) ...
def fill_buffer(heap_data, i_chan)
Blocking function to populate data in the heap. This is run in an executor.
3.893898
3.839473
1.014175
# Create the thread pool. executor = concurrent.futures.ThreadPoolExecutor( max_workers=self._config['num_workers']) # Wait to ensure multiple senders can be synchronised. now = int(datetime.datetime.utcnow().timestamp()) start_time = ((now + 29) // 30) * 30...
def run(self)
Starts the sender.
3.544042
3.457094
1.025151
if object_id in self.active: DB.remove_from_list('{}:active'.format(self.type), object_id) DB.append_to_list('{}:completed'.format(self.type), object_id)
def set_complete(self, object_id: str)
Mark the specified object as completed.
4.904727
4.025621
1.218378
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_id, object_key=object_key, origin=None)
def publish(self, object_id: str, event_type: str, event_data: dict = None)
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.
3.788383
3.675525
1.030705
# FIXME(BMo) replace pb_id argument, get this from the pb instead! stage_data = workflow_stage_dict[workflow_stage.id] stage_data['start'] = False # Determine if the stage can be started. if stage_data['status'] == 'none': if not workflow_stage.dependencies: stage_data['sta...
def _start_workflow_stages(pb: ProcessingBlock, pb_id: str, workflow_stage_dict: dict, workflow_stage: WorkflowStage, docker: DockerSwarmClient)
Start a workflow stage by starting a number of docker services. This function first assesses if the specified workflow stage can be started based on its dependencies. If this is found to be the case, the workflow stage is stared by first resolving and template arguments in the workflow stage configurat...
3.350489
3.132833
1.069476
service_status_complete = [] # FIXME(BMo) is not "complete" -> is "running" if stage_data["status"] != "complete": for service_id, service_dict in stage_data['services'].items(): service_state = docker.get_service_state(service_id) if service_state == 'shutdown': ...
def _update_workflow_stages(stage_data: dict, workflow_stage: WorkflowStage, docker: DockerSwarmClient)
Check and update the status of a workflow stage. This function checks and updates the status of a workflow stage specified by the parameters in the specified stage_data dictionary. If the workflow stage is not marked as complete, this function will check with the Docker Swarm API on the status of Dock...
3.932778
3.413751
1.15204
# 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 \ workflow_stage_dict[workflow_stage.id]['services'].items(): docker.delete_service...
def _abort_workflow(pb: ProcessingBlock, workflow_stage_dict: dict, docker: DockerSwarmClient)
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 ...
5.817819
4.558893
1.276147
# 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(complete_stages): LOG.info('PB workflow comple...
def _workflow_complete(workflow_stage_dict: dict)
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.
5.466808
6.251076
0.874539
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: %s', __version__) LOG.info('Docker Swarm API version: %s',...
def execute_processing_block(pb_id: str, log_level='DEBUG')
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.
3.875313
3.72543
1.040232
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, pb_type, added_time) ...
def put(self, block_id, priority, pb_type='offline')
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...
3.944923
3.689332
1.069279
with self._mutex: entry = self._queue.pop() del self._block_map[entry[2]] return entry[2]
def get(self)
Get the highest priority Processing Block from the queue.
8.003171
5.05011
1.584752
with self._mutex: entry = self._block_map[block_id] self._queue.remove(entry)
def remove(self, block_id)
Remove a Processing Block from the queue. Args: block_id (str):
5.412171
6.580186
0.822495
keys = DB.get_keys('states*') LOG.debug('Loading list of known services.') services = [] for key in keys: values = key.split(':') if len(values) == 4: services.append(ServiceState(*values[1:4])) return services
def get_service_state_list() -> List[ServiceState]
Return a list of ServiceState objects known to SDP.
5.025016
4.481514
1.121277
keys = DB.get_keys('states*') services = [] for key in keys: values = key.split(':') if len(values) == 4: services.append(':'.join(values[1:])) return services
def get_service_id_list() -> List[tuple]
Return list of Services.
4.488447
4.18398
1.07277
LOG.debug('GET Processing Block list') _url = get_root_url() # Get list of Processing block Ids block_ids = sorted(DB.get_processing_block_ids()) LOG.debug('Processing Block IDs: %s', block_ids) # Construct response object response = dict(num_processing_blocks=len(block_ids), ...
def get()
Return the list of Processing Blocks known to SDP.
4.065417
3.665858
1.108995
# Check that the key exists self._check_object_exists() config_dict = DB.get_hash_dict(self.key) for _, value in config_dict.items(): for char in ['[', '{']: if char in value: value = ast.literal_eval(value) return config_d...
def config(self) -> dict
Get the scheduling object config.
6.635449
6.015689
1.103024
self._check_object_exists() return DB.get_hash_value(self.key, property_key)
def get_property(self, property_key: str) -> str
Get a scheduling object property.
12.298249
8.58578
1.432397
self._check_object_exists() DB.set_hash_value(self.key, 'status', value) self.publish('status_changed', event_data=dict(status=value))
def set_status(self, value)
Set the status of the scheduling object.
7.602145
7.378803
1.030268
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, event_data=event_data, object_type=self._type,...
def publish(self, event_type: str, event_data: dict = None)
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.
4.195935
4.190438
1.001312
LOG.debug('Getting events for %s', self.key) return get_events(self.key)
def get_events(self) -> List[Event]
Get events associated with the scheduling object. Returns: list of Event objects
6.348311
6.849923
0.926771
if not DB.get_keys(self.key): raise KeyError("Object with key '{}' not exist".format(self.key))
def _check_object_exists(self)
Raise a KeyError if the scheduling object doesnt exist. Raise: KeyError, if the object doesnt exist in the database.
9.069003
9.011951
1.006331
return '{}:{}:{}'.format(subsystem, name, version)
def get_service_state_object_id(subsystem: str, name: str, version: str) -> str
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
9.948955
15.946421
0.623899
# 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 = [] try: service_config = yaml.load(...
def create_services(self, compose_str: str) -> list
Create new docker services. Args: compose_str (string): Docker compose 'file' string Return: service_names, list
3.388158
3.40896
0.993898
# 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('Services can only be deleted ' 'on swar...
def create_volume(self, volume_name: str, driver_spec: str = None)
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
6.054828
5.371966
1.127116
# 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(service)
def delete_service(self, service: str)
Removes/stops a docker service. Only the manager nodes can delete a service Args: service (string): Service name or ID
8.854811
7.15815
1.237025
# Raise an exception if we are not a manager if not self._manager: raise RuntimeError('Services can only be deleted ' 'on swarm manager nodes') service_list = self.get_service_list() for services in service_list: # Remove a...
def delete_all_services(self)
Removes/stops a service. Only the manager nodes can delete a service
5.923842
5.593444
1.059069
# 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(volume_name)
def delete_volume(self, volume_name: str)
Removes/stops a docker volume. Only the manager nodes can delete a volume Args: volume_name (string): Name of the volume
7.998164
6.573779
1.216677
# Raise an exception if we are not a manager if not self._manager: raise RuntimeError('Volumes can only be deleted ' 'on swarm manager nodes') volume_list = self.get_volume_list() for volumes in volume_list: # Remove all th...
def delete_all_volumes(self)
Remove all the volumes. Only the manager nodes can delete a volume
6.594475
5.79117
1.138712
# Initialising empty list services = [] # 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.') service_list = self._client.service...
def get_service_list(self) -> list
Get a list of docker services. Only the manager nodes can retrieve all the services Returns: list, all the ids of the services in swarm
7.011305
4.83542
1.449989
# 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.get(service_id) return service.name
def get_service_name(self, service_id: str) -> str
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
9.912774
6.937103
1.42895
# 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.get(service_id) return service.attrs
def get_service_details(self, service_id: str) -> dict
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
10.409398
7.306457
1.424685
# 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
def get_service_state(self, service_id: str) -> str
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
5.657954
5.717749
0.989542
# Initialising empty list nodes = [] # Raise an exception if we are not a manager if not self._manager: raise RuntimeError('Only the Swarm manager node ' 'can retrieve all the nodes.') node_list = self._client.nodes.list() ...
def get_node_list(self) -> list
Get a list of nodes. Only the manager nodes can retrieve all the nodes Returns: list, all the ids of the nodes in swarm
6.764979
4.798131
1.40992
# 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) return node.attrs
def get_node_details(self, node_id: list) -> dict
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
8.430559
6.117727
1.378054
# Initialising empty list containers = [] containers_list = self._client.containers.list() for c_list in containers_list: containers.append(c_list.short_id) return containers
def get_container_list(self) -> list
Get list of containers. Returns: list, all the ids of containers
4.694739
5.154024
0.910888
container = self._client.containers.get(container_id_or_name) return container.attrs
def get_container_details(self, container_id_or_name: str) -> dict
Get details of a container. Args: container_id_or_name (string): docker container id or name Returns: dict, details of the container
4.333879
5.808616
0.746112
# Initialising empty list volumes = [] # 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.') volume_list = self._client.volumes.l...
def get_volume_list(self) -> list
Get a list of docker volumes. Only the manager nodes can retrieve all the volumes Returns: list, all the names of the volumes in swarm
7.334585
5.18417
1.414804
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
def get_volume_details(self, volume_name: str) -> dict
Get details of the volume. Args: volume_name (str): Name of the volume Returns: dict, details of the volume
4.679417
4.909992
0.95304
# 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.get_service_details(service_id) actual_replica...
def get_actual_replica(self, service_id: str) -> str
Get the actual replica level of a service. Args: service_id (str): docker swarm service id Returns: str, replicated level of the service
6.667836
5.436408
1.226515
# 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 level of the service') service_tasks = self...
def get_replicas(self, service_id: str) -> str
Get the replication level of a service. Args: service_id (str): docker swarm service id Returns: str, replication level of the service
6.280065
5.314929
1.18159
# 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 = {'Availability': 'active', 'Name': n...
def update_labels(self, node_name: str, labels: dict)
Update label of a node. Args: node_name (string): Name of the node. labels (dict): Label to add to the node
5.939285
5.923011
1.002748
for key, value in service_list['services'][service_name].items(): service_config[key] = value if 'command' in key: key = "args" service_config['args'] = value service_config.pop('command') if 'ports' in key: ...
def _parse_services(self, service_config: dict, service_name: str, service_list: dict) -> dict
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 ...
2.187806
2.053353
1.06548
# 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]) service_config['restart_policy'] = restart_spec ...
def _parse_deploy(self, deploy_values: dict, service_config: dict)
Parse deploy key. Args: deploy_values (dict): deploy configuration values service_config (dict): Service configuration
2.684977
2.656419
1.01075