INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Build and return an ExtractedLicense or None. Note that this function adds the license to the document.
def handle_extracted_license(self, extr_lic): """ Build and return an ExtractedLicense or None. Note that this function adds the license to the document. """ lic = self.parse_only_extr_license(extr_lic) if lic is not None: self.doc.add_extr_lic(lic) re...
Return a license representing a cls object ( LicenseConjunction or LicenseDisjunction ) from a list of license resources or None.
def _handle_license_list(self, lics_set, cls=None): """ Return a license representing a `cls` object (LicenseConjunction or LicenseDisjunction) from a list of license resources or None. """ licenses = [] for _, _, lics_member in self.graph.triples( (lics_set, ...
Parses package fields.
def parse_package(self, p_term): """Parses package fields.""" # Check there is a pacakge name if not (p_term, self.spdx_namespace['name'], None) in self.graph: self.error = True self.logger.log('Package must have a name.') # Create dummy package so that we may...
Handles package lics concluded or declared.
def handle_pkg_lic(self, p_term, predicate, builder_func): """Handles package lics concluded or declared.""" try: for _, _, licenses in self.graph.triples((p_term, predicate, None)): if (licenses, RDF.type, self.spdx_namespace['ConjunctiveLicenseSet']) in self.graph: ...
Returns first found fileName property or None if not found.
def get_file_name(self, f_term): """Returns first found fileName property or None if not found.""" for _, _, name in self.graph.triples((f_term, self.spdx_namespace['fileName'], None)): return name return
Sets file dependencies.
def p_file_depends(self, f_term, predicate): """Sets file dependencies.""" for _, _, other_file in self.graph.triples((f_term, predicate, None)): name = self.get_file_name(other_file) if name is not None: self.builder.add_file_dep(six.text_type(name)) ...
Parse all file contributors and adds them to the model.
def p_file_contributor(self, f_term, predicate): """ Parse all file contributors and adds them to the model. """ for _, _, contributor in self.graph.triples((f_term, predicate, None)): self.builder.add_file_contribution(self.doc, six.text_type(contributor))
Sets file notice text.
def p_file_notice(self, f_term, predicate): """Sets file notice text.""" try: for _, _, notice in self.graph.triples((f_term, predicate, None)): self.builder.set_file_notice(self.doc, six.text_type(notice)) except CardinalityError: self.more_than_one_error...
Sets file comment text.
def p_file_comment(self, f_term, predicate): """Sets file comment text.""" try: for _, _, comment in self.graph.triples((f_term, predicate, None)): self.builder.set_file_comment(self.doc, six.text_type(comment)) except CardinalityError: self.more_than_one_...
Handles file artifactOf. Note: does not handle artifact of project URI.
def p_file_artifact(self, f_term, predicate): """Handles file artifactOf. Note: does not handle artifact of project URI. """ for _, _, project in self.graph.triples((f_term, predicate, None)): if (project, RDF.type, self.doap_namespace['Project']): self.p_file...
Helper function for parsing doap: project name and homepage. and setting them using the file builder.
def p_file_project(self, project): """Helper function for parsing doap:project name and homepage. and setting them using the file builder. """ for _, _, name in self.graph.triples((project, self.doap_namespace['name'], None)): self.builder.set_file_atrificat_of_project(self.d...
Sets file copyright text.
def p_file_cr_text(self, f_term, predicate): """Sets file copyright text.""" try: for _, _, cr_text in self.graph.triples((f_term, predicate, None)): self.builder.set_file_copyright(self.doc, six.text_type(cr_text)) except CardinalityError: self.more_than_...
Sets file license comment.
def p_file_comments_on_lics(self, f_term, predicate): """Sets file license comment.""" try: for _, _, comment in self.graph.triples((f_term, predicate, None)): self.builder.set_file_license_comment(self.doc, six.text_type(comment)) except CardinalityError: ...
Sets file license information.
def p_file_lic_info(self, f_term, predicate): """Sets file license information.""" for _, _, info in self.graph.triples((f_term, predicate, None)): lic = self.handle_lics(info) if lic is not None: self.builder.set_file_license_in_file(self.doc, lic)
Sets file type.
def p_file_type(self, f_term, predicate): """Sets file type.""" try: for _, _, ftype in self.graph.triples((f_term, predicate, None)): try: if ftype.endswith('binary'): ftype = 'BINARY' elif ftype.endswith('sourc...
Sets file checksum. Assumes SHA1 algorithm without checking.
def p_file_chk_sum(self, f_term, predicate): """Sets file checksum. Assumes SHA1 algorithm without checking.""" try: for _s, _p, checksum in self.graph.triples((f_term, predicate, None)): for _, _, value in self.graph.triples((checksum, self.spdx_namespace['checksumValue'], N...
Sets file licenses concluded.
def p_file_lic_conc(self, f_term, predicate): """Sets file licenses concluded.""" try: for _, _, licenses in self.graph.triples((f_term, predicate, None)): if (licenses, RDF.type, self.spdx_namespace['ConjunctiveLicenseSet']) in self.graph: lics = self.han...
Returns review date or None if not found. Reports error on failure. Note does not check value format.
def get_review_date(self, r_term): """Returns review date or None if not found. Reports error on failure. Note does not check value format. """ reviewed_list = list(self.graph.triples((r_term, self.spdx_namespace['reviewDate'], None))) if len(reviewed_list) != 1: ...
Returns reviewer as creator object or None if failed. Reports errors on failure.
def get_reviewer(self, r_term): """Returns reviewer as creator object or None if failed. Reports errors on failure. """ reviewer_list = list(self.graph.triples((r_term, self.spdx_namespace['reviewer'], None))) if len(reviewer_list) != 1: self.error = True ...
Returns annotation type or None if found none or more than one. Reports errors on failure.
def get_annotation_type(self, r_term): """Returns annotation type or None if found none or more than one. Reports errors on failure.""" for _, _, typ in self.graph.triples(( r_term, self.spdx_namespace['annotationType'], None)): if typ is not None: ret...
Returns annotation comment or None if found none or more than one. Reports errors.
def get_annotation_comment(self, r_term): """Returns annotation comment or None if found none or more than one. Reports errors. """ comment_list = list(self.graph.triples((r_term, RDFS.comment, None))) if len(comment_list) > 1: self.error = True msg = 'Ann...
Returns annotation date or None if not found. Reports error on failure. Note does not check value format.
def get_annotation_date(self, r_term): """Returns annotation date or None if not found. Reports error on failure. Note does not check value format. """ annotation_date_list = list(self.graph.triples((r_term, self.spdx_namespace['annotationDate'], None))) if len(annotation...
Parses a file and returns a document object. File a file like object.
def parse(self, fil): """Parses a file and returns a document object. File, a file like object. """ self.error = False self.graph = Graph() self.graph.parse(file=fil, format='xml') self.doc = document.Document() for s, _p, o in self.graph.triples((None, R...
Parse creators created and comment.
def parse_creation_info(self, ci_term): """ Parse creators, created and comment. """ for _s, _p, o in self.graph.triples((ci_term, self.spdx_namespace['creator'], None)): try: ent = self.builder.create_entity(self.doc, six.text_type(o)) self.bu...
Parses the version data license name SPDX Identifier namespace and comment.
def parse_doc_fields(self, doc_term): """Parses the version, data license, name, SPDX Identifier, namespace, and comment.""" try: self.builder.set_doc_spdx_id(self.doc, doc_term) except SPDXValueError: self.value_error('DOC_SPDX_ID_VALUE', doc_term) try: ...
Parses the External Document ID SPDX Document URI and Checksum.
def parse_ext_doc_ref(self, ext_doc_ref_term): """ Parses the External Document ID, SPDX Document URI and Checksum. """ for _s, _p, o in self.graph.triples( (ext_doc_ref_term, self.spdx_namespace['externalDocumentId'], None)): ...
Validate the package fields. Append user friendly error messages to the messages list.
def validate(self, messages): """ Validate the package fields. Append user friendly error messages to the `messages` list. """ messages = self.validate_checksum(messages) messages = self.validate_optional_str_fields(messages) messages = self.validate_mandatory_str...
Fields marked as optional and of type string in class docstring must be of a type that provides __str__ method.
def validate_optional_str_fields(self, messages): """Fields marked as optional and of type string in class docstring must be of a type that provides __str__ method. """ FIELDS = [ 'file_name', 'version', 'homepage', 'source_info', ...
Fields marked as Mandatory and of type string in class docstring must be of a type that provides __str__ method.
def validate_mandatory_str_fields(self, messages): """Fields marked as Mandatory and of type string in class docstring must be of a type that provides __str__ method. """ FIELDS = ['name', 'download_location', 'verif_code', 'cr_text'] messages = self.validate_str_fields(FIELDS, F...
Helper for validate_mandatory_str_field and validate_optional_str_fields
def validate_str_fields(self, fields, optional, messages): """Helper for validate_mandatory_str_field and validate_optional_str_fields""" for field_str in fields: field = getattr(self, field_str) if field is not None: # FIXME: this does not make sense??? ...
Set the document data license. Raise exceptions: - SPDXValueError if malformed value - CardinalityError if already defined.
def set_doc_data_lic(self, doc, res): """ Set the document data license. Raise exceptions: - SPDXValueError if malformed value, - CardinalityError if already defined. """ if not self.doc_data_lics_set: self.doc_data_lics_set = True # TODO: ...
Sets document comment Raises CardinalityError if comment already set.
def set_doc_comment(self, doc, comment): """Sets document comment, Raises CardinalityError if comment already set. """ if not self.doc_comment_set: self.doc_comment_set = True doc.comment = comment else: raise CardinalityError('Document::Commen...
Sets the external document reference s check sum if not already set. chk_sum - The checksum value in the form of a string.
def set_chksum(self, doc, chk_sum): """ Sets the external document reference's check sum, if not already set. chk_sum - The checksum value in the form of a string. """ if chk_sum: doc.ext_document_references[-1].check_sum = checksum.Algorithm( 'SHA1', ...
Sets creation comment Raises CardinalityError if comment already set. Raises SPDXValueError if not free form text.
def set_creation_comment(self, doc, comment): """Sets creation comment, Raises CardinalityError if comment already set. Raises SPDXValueError if not free form text. """ if not self.creation_comment_set: self.creation_comment_set = True doc.creation_info.co...
Sets the package check sum if not already set. chk_sum - A string Raises CardinalityError if already defined. Raises OrderError if no package previously defined.
def set_pkg_chk_sum(self, doc, chk_sum): """Sets the package check sum, if not already set. chk_sum - A string Raises CardinalityError if already defined. Raises OrderError if no package previously defined. """ self.assert_package_exists() if not self.package_chk_...
Sets the package s source information if not already set. text - Free form text. Raises CardinalityError if already defined. Raises OrderError if no package previously defined.
def set_pkg_source_info(self, doc, text): """Sets the package's source information, if not already set. text - Free form text. Raises CardinalityError if already defined. Raises OrderError if no package previously defined. """ self.assert_package_exists() if not s...
Sets the package verification code if not already set. code - A string. Raises CardinalityError if already defined. Raises OrderError if no package previously defined.
def set_pkg_verif_code(self, doc, code): """Sets the package verification code, if not already set. code - A string. Raises CardinalityError if already defined. Raises OrderError if no package previously defined. """ self.assert_package_exists() if not self.packag...
Sets the package s verification code excluded file. Raises OrderError if no package previously defined.
def set_pkg_excl_file(self, doc, filename): """Sets the package's verification code excluded file. Raises OrderError if no package previously defined. """ self.assert_package_exists() doc.package.add_exc_file(filename)
Sets the package s license comment. Raises OrderError if no package previously defined. Raises CardinalityError if already set.
def set_pkg_license_comment(self, doc, text): """Sets the package's license comment. Raises OrderError if no package previously defined. Raises CardinalityError if already set. """ self.assert_package_exists() if not self.package_license_comment_set: self.pack...
Sets the package s license comment. Raises OrderError if no package previously defined. Raises CardinalityError if already set.
def set_pkg_cr_text(self, doc, text): """Sets the package's license comment. Raises OrderError if no package previously defined. Raises CardinalityError if already set. """ self.assert_package_exists() if not self.package_cr_text_set: self.package_cr_text_set ...
Set s the package summary. Raises CardinalityError if summary already set. Raises OrderError if no package previously defined.
def set_pkg_summary(self, doc, text): """Set's the package summary. Raises CardinalityError if summary already set. Raises OrderError if no package previously defined. """ self.assert_package_exists() if not self.package_summary_set: self.package_summary_set =...
Set s the package s description. Raises CardinalityError if description already set. Raises OrderError if no package previously defined.
def set_pkg_desc(self, doc, text): """Set's the package's description. Raises CardinalityError if description already set. Raises OrderError if no package previously defined. """ self.assert_package_exists() if not self.package_desc_set: self.package_desc_set ...
Sets the file check sum if not already set. chk_sum - A string Raises CardinalityError if already defined. Raises OrderError if no package previously defined.
def set_file_chksum(self, doc, chk_sum): """Sets the file check sum, if not already set. chk_sum - A string Raises CardinalityError if already defined. Raises OrderError if no package previously defined. """ if self.has_package(doc) and self.has_file(doc): if ...
Raises OrderError if no package or file defined. Raises CardinalityError if more than one per file.
def set_file_license_comment(self, doc, text): """ Raises OrderError if no package or file defined. Raises CardinalityError if more than one per file. """ if self.has_package(doc) and self.has_file(doc): if not self.file_license_comment_set: self.file_...
Raises OrderError if no package or file defined. Raises CardinalityError if more than one.
def set_file_copyright(self, doc, text): """Raises OrderError if no package or file defined. Raises CardinalityError if more than one. """ if self.has_package(doc) and self.has_file(doc): if not self.file_copytext_set: self.file_copytext_set = True ...
Raises OrderError if no package or no file defined. Raises CardinalityError if more than one comment set.
def set_file_comment(self, doc, text): """Raises OrderError if no package or no file defined. Raises CardinalityError if more than one comment set. """ if self.has_package(doc) and self.has_file(doc): if not self.file_comment_set: self.file_comment_set = True ...
Raises OrderError if no package or file defined. Raises CardinalityError if more than one.
def set_file_notice(self, doc, text): """Raises OrderError if no package or file defined. Raises CardinalityError if more than one. """ if self.has_package(doc) and self.has_file(doc): if not self.file_notice_set: self.file_notice_set = True se...
Sets the review comment. Raises CardinalityError if already set. OrderError if no reviewer defined before.
def add_review_comment(self, doc, comment): """Sets the review comment. Raises CardinalityError if already set. OrderError if no reviewer defined before. """ if len(doc.reviews) != 0: if not self.review_comment_set: self.review_comment_set = True ...
Sets the annotation comment. Raises CardinalityError if already set. OrderError if no annotator defined before.
def add_annotation_comment(self, doc, comment): """Sets the annotation comment. Raises CardinalityError if already set. OrderError if no annotator defined before. """ if len(doc.annotations) != 0: if not self.annotation_comment_set: self.annotation_comment_set...
Sets the annotation type. Raises CardinalityError if already set. OrderError if no annotator defined before.
def add_annotation_type(self, doc, annotation_type): """Sets the annotation type. Raises CardinalityError if already set. OrderError if no annotator defined before. """ if len(doc.annotations) != 0: if not self.annotation_type_set: if annotation_type.endswith(...
Validate all fields of the document and update the messages list with user friendly error messages for display.
def validate(self, messages): """ Validate all fields of the document and update the messages list with user friendly error messages for display. """ messages = self.validate_version(messages) messages = self.validate_data_lics(messages) messages = self.validate_n...
includes the contents of a file on disk. takes a filename
def include(f): ''' includes the contents of a file on disk. takes a filename ''' fl = open(f, 'r') data = fl.read() fl.close() return raw(data)
pipes the output of a program
def system(cmd, data=None): ''' pipes the output of a program ''' import subprocess s = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stdin=subprocess.PIPE) out, err = s.communicate(data) return out.decode('utf8')
Escapes special characters into their html entities Replace special characters & < and > to HTML - safe sequences. If the optional flag quote is true the quotation mark character ( ) is also translated.
def escape(data, quote=True): # stoled from std lib cgi ''' Escapes special characters into their html entities Replace special characters "&", "<" and ">" to HTML-safe sequences. If the optional flag quote is true, the quotation mark character (") is also translated. This is used to escape content that a...
unescapes html entities. the opposite of escape.
def unescape(data): ''' unescapes html entities. the opposite of escape. ''' cc = re.compile(r'&(?:(?:#(\d+))|([^;]+));') result = [] m = cc.search(data) while m: result.append(data[0:m.start()]) d = m.group(1) if d: d = int(d) result.append(unichr(d)) else: d = _unescap...
Set attributes on the current active tag context
def attr(*args, **kwargs): ''' Set attributes on the current active tag context ''' ctx = dom_tag._with_contexts[_get_thread_context()] if ctx and ctx[-1]: dicts = args + (kwargs,) for d in dicts: for attr, value in d.items(): ctx[-1].tag.set_attribute(*dom_tag.clean_pair(attr, value)) ...
Add or update the value of an attribute.
def set_attribute(self, key, value): ''' Add or update the value of an attribute. ''' if isinstance(key, int): self.children[key] = value elif isinstance(key, basestring): self.attributes[key] = value else: raise TypeError('Only integer and string types are valid for assigning ...
Creates a reference to the parent document to allow for partial - tree validation.
def setdocument(self, doc): ''' Creates a reference to the parent document to allow for partial-tree validation. ''' # assume that a document is correct in the subtree if self.document != doc: self.document = doc for i in self.children: if not isinstance(i, dom_tag): return ...
Add new child tags.
def add(self, *args): ''' Add new child tags. ''' for obj in args: if isinstance(obj, numbers.Number): # Convert to string so we fall into next if block obj = str(obj) if isinstance(obj, basestring): obj = escape(obj) self.children.append(obj) elif isi...
Recursively searches children for tags of a certain type with matching attributes.
def get(self, tag=None, **kwargs): ''' Recursively searches children for tags of a certain type with matching attributes. ''' # Stupid workaround since we can not use dom_tag in the method declaration if tag is None: tag = dom_tag attrs = [(dom_tag.clean_attribute(attr), value) for ...
Normalize attribute names for shorthand and work arounds for limitations in Python s syntax
def clean_attribute(attribute): ''' Normalize attribute names for shorthand and work arounds for limitations in Python's syntax ''' # Shorthand attribute = { 'cls': 'class', 'className': 'class', 'class_name': 'class', 'fr': 'for', 'html_for': 'for', 'htmlFor...
This will call clean_attribute on the attribute and also allows for the creation of boolean attributes.
def clean_pair(cls, attribute, value): ''' This will call `clean_attribute` on the attribute and also allows for the creation of boolean attributes. Ex. input(selected=True) is equivalent to input(selected="selected") ''' attribute = cls.clean_attribute(attribute) # Check for boolean attri...
Creates a <title > tag if not present and renders the DOCTYPE and tag tree.
def render(self, *args, **kwargs): ''' Creates a <title> tag if not present and renders the DOCTYPE and tag tree. ''' r = [] #Validates the tag tree and adds the doctype if one was set if self.doctype: r.append(self.doctype) r.append('\n') r.append(super(document, self).render(*...
DOM API: Returns single element with matching id value.
def getElementById(self, id): ''' DOM API: Returns single element with matching id value. ''' results = self.get(id=id) if len(results) > 1: raise ValueError('Multiple tags with id "%s".' % id) elif results: return results[0] else: return None
DOM API: Returns all tags that match name.
def getElementsByTagName(self, name): ''' DOM API: Returns all tags that match name. ''' if isinstance(name, basestring): return self.get(name.lower()) else: return None
Create the Interchange process and connect to it.
def start(self): """Create the Interchange process and connect to it. """ self.outgoing_q = zmq_pipes.TasksOutgoing( "127.0.0.1", self.interchange_port_range) self.incoming_q = zmq_pipes.ResultsIncoming( "127.0.0.1", self.interchange_port_range) self.is_a...
TODO: docstring
def _start_local_queue_process(self): """ TODO: docstring """ comm_q = Queue(maxsize=10) self.queue_proc = Process(target=interchange.starter, args=(comm_q,), kwargs={"client_ports": (self.outgoing_q.port, ...
TODO: docstring
def _start_queue_management_thread(self): """ TODO: docstring """ if self._queue_management_thread is None: logger.debug("Starting queue management thread") self._queue_management_thread = threading.Thread( target=self._queue_management_worker) self._q...
TODO: docstring
def _queue_management_worker(self): """ TODO: docstring """ logger.debug("[MTHREAD] queue management worker starting") while True: task_id, buf = self.incoming_q.get() # TODO: why does this hang? msg = deserialize_object(buf)[0] # TODO: handle exceptions ...
Scale in the number of active blocks by specified amount.
def scale_in(self, blocks): """Scale in the number of active blocks by specified amount. The scale in method here is very rude. It doesn't give the workers the opportunity to finish current tasks or cleanup. This is tracked in issue #530 Raises: NotImplementedError...
Creates a registration message to identify the worker to the interchange
def create_reg_message(self): """ Creates a registration message to identify the worker to the interchange """ msg = {'parsl_v': PARSL_VERSION, 'python_v': "{}.{}.{}".format(sys.version_info.major, sys.version_info.minor, ...
Send heartbeat to the incoming task queue
def heartbeat(self): """ Send heartbeat to the incoming task queue """ heartbeat = (HEARTBEAT_CODE).to_bytes(4, "little") r = self.task_incoming.send(heartbeat) logger.debug("Return from heartbeat : {}".format(r))
Receives a results from the MPI worker pool and send it out via 0mq
def recv_result_from_workers(self): """ Receives a results from the MPI worker pool and send it out via 0mq Returns: -------- result: task result from the workers """ info = MPI.Status() result = self.comm.recv(source=MPI.ANY_SOURCE, tag=RESULT_TAG, status=in...
Receives 1 task request from MPI comm
def recv_task_request_from_workers(self): """ Receives 1 task request from MPI comm Returns: -------- worker_rank: worker_rank id """ info = MPI.Status() comm.recv(source=MPI.ANY_SOURCE, tag=TASK_REQUEST_TAG, status=info) worker_rank = info.Get_source...
Pulls tasks from the incoming tasks 0mq pipe onto the internal pending task queue
def pull_tasks(self, kill_event): """ Pulls tasks from the incoming tasks 0mq pipe onto the internal pending task queue Parameters: ----------- kill_event : threading.Event Event to let the thread know when it is time to die. """ logger.info("[TASK ...
Listens on the pending_result_queue and sends out results via 0mq
def push_results(self, kill_event): """ Listens on the pending_result_queue and sends out results via 0mq Parameters: ----------- kill_event : threading.Event Event to let the thread know when it is time to die. """ # We set this timeout so that the thread...
Start the Manager process.
def start(self): """ Start the Manager process. The worker loops on this: 1. If the last message sent was older than heartbeat period we send a heartbeat 2. TODO: Move task receiving to a thread """ self.comm.Barrier() logger.debug("Manager synced wit...
Decorator function to launch a function as a separate process
def async_process(fn): """ Decorator function to launch a function as a separate process """ def run(*args, **kwargs): proc = mp.Process(target=fn, args=args, kwargs=kwargs) proc.start() return proc return run
Send UDP messages to usage tracker asynchronously
def udp_messenger(domain_name, UDP_IP, UDP_PORT, sock_timeout, message): """Send UDP messages to usage tracker asynchronously This multiprocessing based messenger was written to overcome the limitations of signalling/terminating a thread that is blocked on a system call. This messenger is created as a ...
By default tracking is enabled.
def check_tracking_enabled(self): """By default tracking is enabled. If Test mode is set via env variable PARSL_TESTING, a test flag is set Tracking is disabled if : 1. config["globals"]["usageTracking"] is set to False (Bool) 2. Environment variable PARSL_TRACKING is s...
Collect preliminary run info at the start of the DFK.
def construct_start_message(self): """Collect preliminary run info at the start of the DFK. Returns : - Message dict dumped as json string, ready for UDP """ uname = getpass.getuser().encode('latin1') hashed_username = hashlib.sha256(uname).hexdigest()[0:10] ...
Collect the final run information at the time of DFK cleanup.
def construct_end_message(self): """Collect the final run information at the time of DFK cleanup. Returns: - Message dict dumped as json string, ready for UDP """ app_count = self.dfk.task_count site_count = len([x for x in self.dfk.config.executors if x.managed]) ...
Send UDP message.
def send_UDP_message(self, message): """Send UDP message.""" x = 0 if self.tracking_enabled: try: proc = udp_messenger(self.domain_name, self.UDP_IP, self.UDP_PORT, self.sock_timeout, message) self.procs.append(proc) except Exception as e: ...
Send message over UDP.
def send_message(self): """Send message over UDP. If tracking is disables, the bytes_sent will always be set to -1 Returns: (bytes_sent, time_taken) """ start = time.time() message = None if not self.initialized: message = self.construct_...
Add a stream log handler.
def set_file_logger(filename: str, name: str = 'parsl', level: int = logging.DEBUG, format_string: Optional[str] = None): """Add a stream log handler. Args: - filename (string): Name of the file to write logs to - name (string): Logger name - level (logging.LEVEL): Set the logging level...
Add a stream log handler. Parameters --------- filename: string Name of the file to write logs to. Required. name: string Logger name. Default = parsl. executors. interchange level: logging. LEVEL Set the logging level. Default = logging. DEBUG - format_string ( string ): Set the format string format_string: string For...
def start_file_logger(filename, name='database_manager', level=logging.DEBUG, format_string=None): """Add a stream log handler. Parameters --------- filename: string Name of the file to write logs to. Required. name: string Logger name. Default="parsl.executors.interchange" level...
Start the database manager process
def dbm_starter(priority_msgs, resource_msgs, *args, **kwargs): """Start the database manager process The DFK should start this function. The args, kwargs match that of the monitoring config """ dbm = DatabaseManager(*args, **kwargs) dbm.start(priority_msgs, resource_msgs)
maintain a set to track the tasks that are already INSERTED into database to prevent race condition that the first resource message ( indicate running state ) arrives before the first task message. If race condition happens add to left_messages and operate them later
def start(self, priority_queue, resource_queue): self._kill_event = threading.Event() self._priority_queue_pull_thread = threading.Thread(target=self._migrate_logs_to_internal, args=( ...
Create the dictionary that will be included in the log.
def _create_task_log_info(self, task_id, fail_mode=None): """ Create the dictionary that will be included in the log. """ info_to_monitor = ['func_name', 'fn_hash', 'memoize', 'checkpoint', 'fail_count', 'fail_history', 'status', 'id', 'time_submitted', 'time_...
Internal.
def _count_deps(self, depends): """Internal. Count the number of unresolved futures in the list depends. """ count = 0 for dep in depends: if isinstance(dep, Future): if not dep.done(): count += 1 return count
This function is called only as a callback from an execution attempt reaching a final state ( either successfully or failing ).
def handle_exec_update(self, task_id, future): """This function is called only as a callback from an execution attempt reaching a final state (either successfully or failing). It will launch retries if necessary, and update the task structure. Args: task_id (string...
This function is called as a callback when an AppFuture is in its final state.
def handle_app_update(self, task_id, future, memo_cbk=False): """This function is called as a callback when an AppFuture is in its final state. It will trigger post-app processing such as checkpointing and stageout. Args: task_id (string) : Task id fut...
launch_if_ready will launch the specified task if it is ready to run ( for example without dependencies and in pending state ).
def launch_if_ready(self, task_id): """ launch_if_ready will launch the specified task, if it is ready to run (for example, without dependencies, and in pending state). This should be called by any piece of the DataFlowKernel that thinks a task may have become ready to run. ...
Handle the actual submission of the task to the executor layer.
def launch_task(self, task_id, executable, *args, **kwargs): """Handle the actual submission of the task to the executor layer. If the app task has the executors attributes not set (default=='all') the task is launched on a randomly selected executor from the list of executors. This beh...
Look for inputs of the app that are remote files. Submit stage_in apps for such files and replace the file objects in the inputs list with corresponding DataFuture objects.
def _add_input_deps(self, executor, args, kwargs): """Look for inputs of the app that are remote files. Submit stage_in apps for such files and replace the file objects in the inputs list with corresponding DataFuture objects. Args: - executor (str) : executor where the app ...
Count the number of unresolved futures on which a task depends.
def _gather_all_deps(self, args, kwargs): """Count the number of unresolved futures on which a task depends. Args: - args (List[args]) : The list of args list to the fn - kwargs (Dict{kwargs}) : The dict of all kwargs passed to the fn Returns: - count, [list...
This function should be called ** ONLY ** when all the futures we track have been resolved.
def sanitize_and_wrap(self, task_id, args, kwargs): """This function should be called **ONLY** when all the futures we track have been resolved. If the user hid futures a level below, we will not catch it, and will (most likely) result in a type error. Args: task_id (uuid ...
Add task to the dataflow system.
def submit(self, func, *args, executors='all', fn_hash=None, cache=False, **kwargs): """Add task to the dataflow system. If the app task has the executors attributes not set (default=='all') the task will be launched on a randomly selected executor from the list of executors. If the app...
Waits for all tasks in the task list to be completed by waiting for their AppFuture to be completed. This method will not necessarily wait for any tasks added after cleanup has started ( such as data stageout? )
def wait_for_current_tasks(self): """Waits for all tasks in the task list to be completed, by waiting for their AppFuture to be completed. This method will not necessarily wait for any tasks added after cleanup has started (such as data stageout?) """ logger.info("Waiting for al...
DataFlowKernel cleanup.
def cleanup(self): """DataFlowKernel cleanup. This involves killing resources explicitly and sending die messages to IPP workers. If the executors are managed (created by the DFK), then we call scale_in on each of the executors and call executor.shutdown. Otherwise, we do nothing, and ...