INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
:param data: :type data: bytes :return: :rtype:
def receive(self, data): """ :param data: :type data: bytes :return: :rtype: """ self._incoming_segments_queue.put(data) if not self._in_handshake(): self._flush_incoming_buffer()
:rtype: YowsupEnv
def getCurrent(cls): """ :rtype: YowsupEnv """ if cls.__CURR is None: env = DEFAULT envs = cls.getRegisteredEnvs() if env not in envs: env = envs[0] logger.debug("Env not set, setting it to %s" % env) cls.setEnv(...
:param params: :type params: list :param key: :type key: ECPublicKey :return: :rtype: list
def encryptParams(self, params, key): """ :param params: :type params: list :param key: :type key: ECPublicKey :return: :rtype: list """ keypair = Curve.generateKeyPair() encodedparams = self.urlencodeParams(params) cipher = AESGCM...
:param preKeyIds: :type preKeyIds: list :return: :rtype:
def setAsSent(self, prekeyIds): """ :param preKeyIds: :type preKeyIds: list :return: :rtype: """ for prekeyId in prekeyIds: q = "UPDATE prekeys SET sent_to_server = ? WHERE prekey_id = ?" cursor = self.dbConn.cursor() cursor.exe...
:param config: :type config: dict :return: :rtype: yowsup.config.config.Config
def transform(self, config): """ :param config: :type config: dict :return: :rtype: yowsup.config.config.Config """ out = {} for prop in vars(config): out[prop] = getattr(config, prop) return out
Show system notification with duration t (ms)
def notify(msg, msg_type=0, t=None): msg = msg.replace('"', '\\"') "Show system notification with duration t (ms)" if platform.system() == "Darwin": command = notify_command_osx(msg, msg_type, t) else: command = notify_command_linux(msg, t) try: subprocess.call(command) ...
Runs the given args in subprocess.Popen, and then calls the function on_exit when the subprocess completes. on_exit is a callable object, and args is a lists/tuple of args that would give to subprocess.Popen.
def start_playing(self, on_exit, args): """ Runs the given args in subprocess.Popen, and then calls the function on_exit when the subprocess completes. on_exit is a callable object, and args is a lists/tuple of args that would give to subprocess.Popen. """ # log.d...
Expand a string containing $vars as Ninja would. Note: doesn't handle the full Ninja variable syntax, but it's enough to make configure.py's use of it work.
def expand(string, vars, local_vars={}): """Expand a string containing $vars as Ninja would. Note: doesn't handle the full Ninja variable syntax, but it's enough to make configure.py's use of it work. """ def exp(m): var = m.group(1) if var == '$': return '$' ret...
Returns the number of '$' characters right in front of s[i].
def _count_dollars_before_index(self, s, i): """Returns the number of '$' characters right in front of s[i].""" dollar_count = 0 dollar_index = i - 1 while dollar_index > 0 and s[dollar_index] == '$': dollar_count += 1 dollar_index -= 1 return dollar_count
Write 'text' word-wrapped at self.width characters.
def _line(self, text, indent=0): """Write 'text' word-wrapped at self.width characters.""" leading_space = ' ' * indent while len(leading_space) + len(text) > self.width: # The text is too wide; wrap if possible. # Find the rightmost space that would obey our width cons...
Expand $vars in an array of paths, e.g. from a 'build' block.
def _expand_paths(self, paths): """Expand $vars in an array of paths, e.g. from a 'build' block.""" paths = ninja_syntax.as_list(paths) return ' '.join(map(self._shell_escape, (map(self._expand, paths))))
Expand $vars in a string.
def _expand(self, str, local_vars={}): """Expand $vars in a string.""" return ninja_syntax.expand(str, self.vars, local_vars)
Run a subcommand, quietly. Prints the full command on error.
def _run_command(self, cmdline): """Run a subcommand, quietly. Prints the full command on error.""" try: if self.verbose: print(cmdline) subprocess.check_call(cmdline, shell=True) except subprocess.CalledProcessError: print('when running: ', c...
Returns a random integer that's avg on average, following a power law. alpha determines the shape of the power curve. alpha has to be larger than 1. The closer alpha is to 1, the higher the variation of the returned numbers.
def paretoint(avg, alpha): """Returns a random integer that's avg on average, following a power law. alpha determines the shape of the power curve. alpha has to be larger than 1. The closer alpha is to 1, the higher the variation of the returned numbers.""" return int(random.paretovariate(alpha) * a...
Writes master build.ninja file, referencing all given subninjas.
def write_master_ninja(master_ninja, targets): """Writes master build.ninja file, referencing all given subninjas.""" master_ninja.variable('cxx', 'c++') master_ninja.variable('ld', '$cxx') if sys.platform == 'darwin': master_ninja.variable('alink', 'libtool -static') else: master_ni...
Context manager for a ninja_syntax object writing to a file.
def FileWriter(path): """Context manager for a ninja_syntax object writing to a file.""" try: os.makedirs(os.path.dirname(path)) except OSError: pass f = open(path, 'w') yield ninja_syntax.Writer(f) f.close()
Load the server extension.
def load_jupyter_server_extension(nbapp): """Load the server extension. """ here = PACKAGE_DIR nbapp.log.info('nteract extension loaded from %s' % here) app_dir = here # bundle is part of the python package web_app = nbapp.web_app config = NteractConfig(parent=nbapp) # original #...
Add the appropriate handlers to the web app.
def add_handlers(web_app, config): """Add the appropriate handlers to the web app. """ base_url = web_app.settings['base_url'] url = ujoin(base_url, config.page_url) assets_dir = config.assets_dir package_file = os.path.join(assets_dir, 'package.json') with open(package_file) as fid: ...
if (!(this instanceof SemVer)) return new SemVer(version, loose);
def semver(version, loose): if isinstance(version, SemVer): if version.loose == loose: return version else: version = version.version elif not isinstance(version, string_type): # xxx: raise ValueError("Invalid Version: {}".format(version)) """ if (!(this...
read the lines from a file into a list
def get_list_from_file(file_name): """read the lines from a file into a list""" with open(file_name, mode='r', encoding='utf-8') as f1: lst = f1.readlines() return lst
append a line of text to a file
def append_to_file(file_name, line_data): """append a line of text to a file""" with open(file_name, mode='a', encoding='utf-8') as f1: f1.write(line_data) f1.write("\n")
Determine if input contains negation words
def negated(input_words, include_nt=True): """ Determine if input contains negation words """ input_words = [str(w).lower() for w in input_words] neg_words = [] neg_words.extend(NEGATE) for word in neg_words: if word in input_words: return True if include_nt: ...
Normalize the score to be between -1 and 1 using an alpha that approximates the max expected value
def normalize(score, alpha=15): """ Normalize the score to be between -1 and 1 using an alpha that approximates the max expected value """ norm_score = score / math.sqrt((score * score) + alpha) if norm_score < -1.0: return -1.0 elif norm_score > 1.0: return 1.0 else: ...
Check whether just some words in the input are ALL CAPS :param list words: The words to inspect :returns: `True` if some but not all items in `words` are ALL CAPS
def allcap_differential(words): """ Check whether just some words in the input are ALL CAPS :param list words: The words to inspect :returns: `True` if some but not all items in `words` are ALL CAPS """ is_different = False allcap_words = 0 for word in words: if word.isupper(): ...
Check if the preceding words increase, decrease, or negate/nullify the valence
def scalar_inc_dec(word, valence, is_cap_diff): """ Check if the preceding words increase, decrease, or negate/nullify the valence """ scalar = 0.0 word_lower = word.lower() if word_lower in BOOSTER_DICT: scalar = BOOSTER_DICT[word_lower] if valence < 0: scalar *=...
Returns mapping of form: { 'cat,': 'cat', ',cat': 'cat', }
def _words_plus_punc(self): """ Returns mapping of form: { 'cat,': 'cat', ',cat': 'cat', } """ no_punc_text = REGEX_REMOVE_PUNCTUATION.sub('', self.text) # removes punctuation (but loses emoticons & contractions) words_only = no_pun...
Removes leading and trailing puncutation Leaves contractions and most emoticons Does not preserve punc-plus-letter emoticons (e.g. :D)
def _words_and_emoticons(self): """ Removes leading and trailing puncutation Leaves contractions and most emoticons Does not preserve punc-plus-letter emoticons (e.g. :D) """ wes = self.text.split() words_punc_dict = self._words_plus_punc() wes = [we f...
Convert lexicon file to a dictionary
def make_lex_dict(self): """ Convert lexicon file to a dictionary """ lex_dict = {} for line in self.lexicon_full_filepath.split('\n'): (word, measure) = line.strip().split('\t')[0:2] lex_dict[word] = float(measure) return lex_dict
Convert emoji lexicon file to a dictionary
def make_emoji_dict(self): """ Convert emoji lexicon file to a dictionary """ emoji_dict = {} for line in self.emoji_full_filepath.split('\n'): (emoji, description) = line.strip().split('\t')[0:2] emoji_dict[emoji] = description return emoji_dict
Return a float for sentiment strength based on the input text. Positive values are positive valence, negative value are negative valence.
def polarity_scores(self, text): """ Return a float for sentiment strength based on the input text. Positive values are positive valence, negative value are negative valence. """ # convert emojis to their textual descriptions text_token_list = text.split() ...
Build an absolute path from *parts* and and return the contents of the resulting file. Assume UTF-8 encoding.
def read(*parts): """ Build an absolute path from *parts* and and return the contents of the resulting file. Assume UTF-8 encoding. """ with codecs.open(os.path.join(HERE, *parts), "rb", "utf-8") as f: return f.read()
Parse messages sent by the 'buildbot-cvs-mail' program.
def parse(self, m, prefix=None): """Parse messages sent by the 'buildbot-cvs-mail' program. """ # The mail is sent from the person doing the checkin. Assume that the # local username is enough to identify them (this assumes a one-server # cvs-over-rsh environment rather than the ...
Parse messages sent by the svn 'commit-email.pl' trigger.
def parse(self, m, prefix=None): """Parse messages sent by the svn 'commit-email.pl' trigger. """ # The mail is sent from the person doing the checkin. Assume that the # local username is enough to identify them (this assumes a one-server # cvs-over-rsh environment rather than t...
Called from remote worker to write L{data} to L{fp} within boundaries of L{maxsize} @type data: C{string} @param data: String of data to write
def remote_write(self, data): """ Called from remote worker to write L{data} to L{fp} within boundaries of L{maxsize} @type data: C{string} @param data: String of data to write """ data = unicode2bytes(data) if self.remaining is not None: if ...
Parse branch notification messages sent by Launchpad.
def parse(self, m, prefix=None): """Parse branch notification messages sent by Launchpad. """ subject = m["subject"] match = re.search(r"^\s*\[Branch\s+([^]]+)\]", subject) if match: repository = match.group(1) else: repository = None # P...
Called by remote worker to state that no more data will be transferred
def remote_close(self): """ Called by remote worker to state that no more data will be transferred """ self.fp.close() self.fp = None # on windows, os.rename does not automatically unlink, so do it # manually if os.path.exists(self.destfile): o...
Called by remote worker to state that no more data will be transferred
def remote_unpack(self): """ Called by remote worker to state that no more data will be transferred """ # Make sure remote_close is called, otherwise atomic rename won't happen self.remote_close() # Map configured compression to a TarFile setting if self.compress...
Called from remote worker to read at most L{maxlength} bytes of data @type maxlength: C{integer} @param maxlength: Maximum number of data bytes that can be returned @return: Data read from L{fp} @rtype: C{string} of bytes read from file
def remote_read(self, maxlength): """ Called from remote worker to read at most L{maxlength} bytes of data @type maxlength: C{integer} @param maxlength: Maximum number of data bytes that can be returned @return: Data read from L{fp} @rtype: C{string} of bytes read from...
run CMake
def run(self): """ run CMake """ command = [self.cmake] if self.generator: command.extend([ '-G', self.generator ]) if self.path: command.append(self.path) if self.definitions is not None: for item...
I am called by the worker's L{buildbot_worker.base.WorkerForBuilderBase.sendUpdate} so I can receive updates from the running remote command. @type updates: list of [object, int] @param updates: list of updates from the remote command
def remote_update(self, updates): """ I am called by the worker's L{buildbot_worker.base.WorkerForBuilderBase.sendUpdate} so I can receive updates from the running remote command. @type updates: list of [object, int] @param updates: list of updates from the remote comma...
Called by the worker's L{buildbot_worker.base.WorkerForBuilderBase.commandComplete} to notify me the remote command has finished. @type failure: L{twisted.python.failure.Failure} or None @rtype: None
def remote_complete(self, failure=None): """ Called by the worker's L{buildbot_worker.base.WorkerForBuilderBase.commandComplete} to notify me the remote command has finished. @type failure: L{twisted.python.failure.Failure} or None @rtype: None """ self...
The hasattr equivalent for attribute groups: returns whether the given member is in the attribute group.
def _hasAttrGroupMember(self, attrGroup, attr): """ The hasattr equivalent for attribute groups: returns whether the given member is in the attribute group. """ method_name = '%s_%s' % (attrGroup, attr) return hasattr(self, method_name)
The getattr equivalent for attribute groups: gets and returns the attribute group member.
def _getAttrGroupMember(self, attrGroup, attr): """ The getattr equivalent for attribute groups: gets and returns the attribute group member. """ method_name = '%s_%s' % (attrGroup, attr) return getattr(self, method_name)
Returns a list of all members in the attribute group.
def _listAttrGroupMembers(self, attrGroup): """ Returns a list of all members in the attribute group. """ from inspect import getmembers, ismethod methods = getmembers(self, ismethod) group_prefix = attrGroup + '_' group_len = len(group_prefix) group_membe...
Update a property, indexing the property by codebase if codebase is not ''. Source steps should generally use this instead of setProperty.
def updateSourceProperty(self, name, value, source=''): """ Update a property, indexing the property by codebase if codebase is not ''. Source steps should generally use this instead of setProperty. """ # pick a decent source name if source == '': source = se...
Convert Gerrit account properties to Buildbot format Take into account missing values
def _gerrit_user_to_author(props, username="unknown"): """ Convert Gerrit account properties to Buildbot format Take into account missing values """ username = props.get("username", username) username = props.get("name", username) if "email" in props: username += " <%(email)s>" % pr...
This method finds the first parent class which is within the buildbot namespace it prepends the name with as many ">" as the class is subclassed
def getName(obj): """This method finds the first parent class which is within the buildbot namespace it prepends the name with as many ">" as the class is subclassed """ # elastic search does not like '.' in dict keys, so we replace by / def sanitize(name): return name.replace(".", "/") ...
Send the actual configuration of the builders, how the steps are agenced. Note that full data will never send actual detail of what command is run, name of servers, etc.
def fullData(master): """ Send the actual configuration of the builders, how the steps are agenced. Note that full data will never send actual detail of what command is run, name of servers, etc. """ builders = [] for b in master.config.builders: steps = [] for step in b...
Generate a pair of (directory, file-list) for installation. 'd' -- A directory 'e' -- A glob pattern
def include(d, e): """Generate a pair of (directory, file-list) for installation. 'd' -- A directory 'e' -- A glob pattern""" return (d, [f for f in glob.glob('%s/%s' % (d, e)) if os.path.isfile(f)])
helper to produce lines suitable for setup.py's entry_points
def define_plugin_entry(name, module_name): """ helper to produce lines suitable for setup.py's entry_points """ if isinstance(name, tuple): entry, name = name else: entry = name return '%s = %s:%s' % (entry, module_name, name)
helper to all groups for plugins
def define_plugin_entries(groups): """ helper to all groups for plugins """ result = dict() for group, modules in groups: tempo = [] for module_name, names in modules: tempo.extend([define_plugin_entry(name, module_name) for name in names]) ...
Static method to create a filter based on constructor args change_filter, branch, and categories; use default values @code{None}, @code{NotABranch}, and @code{None}, respectively. These arguments are interpreted as documented for the L{buildbot.schedulers.basic.Scheduler} class. ...
def fromSchedulerConstructorArgs(change_filter=None, branch=NotABranch, categories=None): """ Static method to create a filter based on constructor args change_filter, branch, and categories; use default values @code{None}, @code{NotABranch}, and @cod...
Read changes since last change. - Read list of commit hashes. - Extract details from each commit. - Add changes to database.
def _process_changes(self, newRev, branch): """ Read changes since last change. - Read list of commit hashes. - Extract details from each commit. - Add changes to database. """ # initial run, don't parse all history if not self.lastRev: retur...
Shut down the entire process, once all currently-running builds are complete. quickMode will mark all builds as retry (except the ones that were triggered)
def cleanShutdown(self, quickMode=False, stopReactor=True, _reactor=reactor): """Shut down the entire process, once all currently-running builds are complete. quickMode will mark all builds as retry (except the ones that were triggered) """ if self.shuttingDown: retur...
Convert a Lock identifier into an actual Lock instance. @param lockid: a locks.MasterLock or locks.WorkerLock instance @return: a locks.RealMasterLock or locks.RealWorkerLock instance
def getLockByID(self, lockid): """Convert a Lock identifier into an actual Lock instance. @param lockid: a locks.MasterLock or locks.WorkerLock instance @return: a locks.RealMasterLock or locks.RealWorkerLock instance """ assert isinstance(lockid, (locks.MasterLock, locks.WorkerL...
Call this when something suggests that a particular worker may now be available to start a build. @param worker_name: the name of the worker
def maybeStartBuildsForWorker(self, worker_name): """ Call this when something suggests that a particular worker may now be available to start a build. @param worker_name: the name of the worker """ builders = self.getBuildersForWorker(worker_name) self.brd.maybe...
Rewrap text for output to the console. Removes common indentation and rewraps paragraphs according to the console width. Line feeds between paragraphs preserved. Formatting of paragraphs that starts with additional indentation preserved.
def rewrap(text, width=None): """ Rewrap text for output to the console. Removes common indentation and rewraps paragraphs according to the console width. Line feeds between paragraphs preserved. Formatting of paragraphs that starts with additional indentation preserved. """ if wi...
Consumes a naive build notification (the default for now) basically, set POST variables to match commit object parameters: revision, revlink, comments, branch, who, files, links files, links and properties will be de-json'd, the rest are interpreted as strings
def getChanges(self, request): """ Consumes a naive build notification (the default for now) basically, set POST variables to match commit object parameters: revision, revlink, comments, branch, who, files, links files, links and properties will be de-json'd, the rest are interp...
Create and return a L{BBRefTargetDirective} subclass.
def make_ref_target_directive(ref_type, indextemplates=None, **kwargs): """ Create and return a L{BBRefTargetDirective} subclass. """ class_vars = dict(ref_type=ref_type, indextemplates=indextemplates) class_vars.update(kwargs) return type("BB%sRefTargetDirective" % (ref_type.capitalize(),), ...
Create and return a L{BBIndex} subclass, for use in the domain's C{indices}
def make_index(name, localname): """ Create and return a L{BBIndex} subclass, for use in the domain's C{indices} """ return type("BB%sIndex" % (name.capitalize(),), (BBIndex,), dict(name=name, localname=localname))
Resolve a reference to a directive of this class
def resolve_ref(cls, domain, env, fromdocname, builder, typ, target, node, contnode): """ Resolve a reference to a directive of this class """ targets = domain.data['targets'].get(cls.ref_type, {}) try: todocname, targetname = targets[target] ...
Resolve a reference to an index to the document containing the index, using the index's C{localname} as the content of the link.
def resolve_ref(cls, domain, env, fromdocname, builder, typ, target, node, contnode): """ Resolve a reference to an index to the document containing the index, using the index's C{localname} as the content of the link. """ # indexes appear to be automatically ...
call this function after the file exists to populate properties
def load(self): """ call this function after the file exists to populate properties """ # If we are given a string, open it up else assume it's something we # can call read on. if isinstance(self.specfile, str): f = open(self.specfile, 'r') else: ...
Consumer for this (CaptureProperty) class. Gets the properties from data api and send them to the storage backends.
def consume(self, routingKey, msg): """ Consumer for this (CaptureProperty) class. Gets the properties from data api and send them to the storage backends. """ builder_info = yield self.master.data.get(("builders", msg['builderid'])) if self._builder_name_matches(builder...
Consumer for CaptureBuildStartTime. Gets the build start time.
def consume(self, routingKey, msg): """ Consumer for CaptureBuildStartTime. Gets the build start time. """ builder_info = yield self.master.data.get(("builders", msg['builderid'])) if self._builder_name_matches(builder_info): try: ret_val = self._callb...
Consumer for this (CaptureData) class. Gets the data sent from yieldMetricsValue and sends it to the storage backends.
def consume(self, routingKey, msg): """ Consumer for this (CaptureData) class. Gets the data sent from yieldMetricsValue and sends it to the storage backends. """ build_data = msg['build_data'] builder_info = yield self.master.data.get(("builders", build_data['builderid']...
:param repo_user: GitHub user or organization :param repo_name: Name of the repository :param sha: Full sha to create the status for. :param state: one of the following 'pending', 'success', 'error' or 'failure'. :param target_url: Target url to associate with this ...
def createStatus(self, repo_user, repo_name, sha, state, target_url=None, context=None, issue=None, description=None): """ :param repo_user: GitHub user or organization :param repo_name: Name of the repository :param sha: Full sha to create the s...
:param repo_user: GitHub user or organization :param repo_name: Name of the repository :param issue: Pull request number :param state: one of the following 'pending', 'success', 'error' or 'failure'. :param description: Short description of the status. :retu...
def createStatus(self, repo_user, repo_name, sha, state, target_url=None, context=None, issue=None, description=None): """ :param repo_user: GitHub user or organization :param repo_name: Name of the repository :param issue: Pull request number ...
Stop worker process by sending it a signal. Using the specified basedir path, read worker process's pid file and try to terminate that process with specified signal. @param basedir: worker's basedir path @param quite: if False, don't print any messages to stdout @param signame: signal to send to...
def stopWorker(basedir, quiet, signame="TERM"): """ Stop worker process by sending it a signal. Using the specified basedir path, read worker process's pid file and try to terminate that process with specified signal. @param basedir: worker's basedir path @param quite: if False, don't print ...
Create a new Build instance. @param requests: a list of buildrequest dictionaries describing what is to be built
def newBuild(self, requests): """Create a new Build instance. @param requests: a list of buildrequest dictionaries describing what is to be built """ b = self.buildClass(requests) b.useProgress = self.useProgress b.workdir = self.workdir b.setStepFactorie...
This method can be used to add patters of warnings that should not be counted. It takes a single argument, a list of patterns. Each pattern is a 4-tuple (FILE-RE, WARN-RE, START, END). FILE-RE is a regular expression (string or compiled regexp), or None. If None, the pattern m...
def addSuppression(self, suppressionList): """ This method can be used to add patters of warnings that should not be counted. It takes a single argument, a list of patterns. Each pattern is a 4-tuple (FILE-RE, WARN-RE, START, END). FILE-RE is a regular expression (stri...
Extract file name, line number, and warning text as groups (1,2,3) of warningPattern match.
def warnExtractFromRegexpGroups(self, line, match): """ Extract file name, line number, and warning text as groups (1,2,3) of warningPattern match.""" file = match.group(1) lineNo = match.group(2) if lineNo is not None: lineNo = int(lineNo) text = matc...
Match log lines against warningPattern. Warnings are collected into another log for this step, and the build-wide 'warnings-count' is updated.
def createSummary(self, log): """ Match log lines against warningPattern. Warnings are collected into another log for this step, and the build-wide 'warnings-count' is updated.""" # If there were any warnings, make the log if lines with warnings # available if s...
cppcheck always return 0, unless a special parameter is given
def evaluateCommand(self, cmd): """ cppcheck always return 0, unless a special parameter is given """ for msg in self.flunkingIssues: if self.counts[msg] != 0: return FAILURE if self.getProperty('cppcheck-total') != 0: return WARNINGS return SUCCES...
get the value from pass identified by 'entry'
def get(self, entry): """ get the value from pass identified by 'entry' """ try: output = yield utils.getProcessOutput( "pass", args=[entry], env=self._env ) return output.decode("utf-8", "ignore").splitl...
Patch startService and stopService so that they check the previous state first. (used for debugging only)
def patch(): """ Patch startService and stopService so that they check the previous state first. (used for debugging only) """ from twisted.application.service import Service old_startService = Service.startService old_stopService = Service.stopService def startService(self): ...
Perform any periodic database cleanup tasks. @returns: Deferred
def _doCleanup(self): """ Perform any periodic database cleanup tasks. @returns: Deferred """ # pass on this if we're not configured yet if not self.configured_url: return d = self.changes.pruneChanges(self.master.config.changeHorizon) d.addE...
Special setup for sqlite engines
def set_up(self, u, engine): """Special setup for sqlite engines""" def connect_listener_enable_fk(connection, record): # fk must be enabled for all connections if not getattr(engine, "fk_disabled", False): return # http://trac.buildbot.net/ticket/3490#ticket ...
Special setup for mysql engines
def set_up(self, u, engine): """Special setup for mysql engines""" # add the reconnecting PoolListener that will detect a # disconnected connection and automatically start a new # one. This provides a measure of additional safety over # the pool_recycle parameter, and is useful ...
For sqlite, percent-substitute %(basedir)s and use a full path to the basedir. If using a memory database, force the pool size to be 1.
def special_case_sqlite(self, u, kwargs): """For sqlite, percent-substitute %(basedir)s and use a full path to the basedir. If using a memory database, force the pool size to be 1.""" max_conns = 1 # when given a database path, stick the basedir in there if u.database: ...
For mysql, take max_idle out of the query arguments, and use its value for pool_recycle. Also, force use_unicode and charset to be True and 'utf8', failing if they were set to anything else.
def special_case_mysql(self, u, kwargs): """For mysql, take max_idle out of the query arguments, and use its value for pool_recycle. Also, force use_unicode and charset to be True and 'utf8', failing if they were set to anything else.""" kwargs['pool_recycle'] = int(u.query.pop...
Return a novaclient from the given args.
def _constructClient(client_version, username, user_domain, password, project_name, project_domain, auth_url): """Return a novaclient from the given args.""" loader = loading.get_plugin_loader('password') # These only work with v3 if user_domain is not None or p...
Parse a higher-level view of the block device mapping into something novaclient wants. This should be similar to how Horizon presents it. Required keys: device_name: The name of the device; e.g. vda or xda. source_type: image, snapshot, volume, or blank/None. destinat...
def _parseBlockDevice(self, block_device): """ Parse a higher-level view of the block device mapping into something novaclient wants. This should be similar to how Horizon presents it. Required keys: device_name: The name of the device; e.g. vda or xda. source_typ...
Render all of the block device's values.
def _renderBlockDevice(self, block_device, build): """Render all of the block device's values.""" rendered_block_device = yield build.render(block_device) if rendered_block_device['volume_size'] is None: source_type = rendered_block_device['source_type'] source_uuid = ren...
Determine the minimum size the volume needs to be for the source. Returns the size in GiB.
def _determineVolumeSize(self, source_type, source_uuid): """ Determine the minimum size the volume needs to be for the source. Returns the size in GiB. """ nova = self.novaclient if source_type == 'image': # The size returned for an image is in bytes. Round u...
Run a database transaction with dbpool.runInteraction, but retry the transaction in case of a temporary error (like connection lost). This is needed to be robust against things like database connection idle timeouts. The passed callable that implements the transaction must be retryable...
def runInteractionWithRetry(self, actionFn, *args, **kw): """ Run a database transaction with dbpool.runInteraction, but retry the transaction in case of a temporary error (like connection lost). This is needed to be robust against things like database connection idle timeouts. ...
Run a database query, like with dbpool.runQuery, but retry the query in case of a temporary error (like connection lost). This is needed to be robust against things like database connection idle timeouts.
def runQueryWithRetry(self, *args, **kw): """ Run a database query, like with dbpool.runQuery, but retry the query in case of a temporary error (like connection lost). This is needed to be robust against things like database connection idle timeouts.""" def runQuery(txn...
Decorate a do function to log before, after, and elapsed time, with the name of the calling function. This is not speedy!
def timed_do_fn(f): """Decorate a do function to log before, after, and elapsed time, with the name of the calling function. This is not speedy!""" def wrap(callable, *args, **kwargs): global _debug_id # get a description of the function that called us st = traceback.extract_stack(...
Manually stop the pool. This is only necessary from tests, as the pool will stop itself when the reactor stops under normal circumstances.
def shutdown(self): """Manually stop the pool. This is only necessary from tests, as the pool will stop itself when the reactor stops under normal circumstances.""" if not self._stop_evt: return # pool is already stopped self.reactor.removeSystemEventTrigger(self._s...
Display the data attributes of an object in a readable format
def show(x): """Display the data attributes of an object in a readable format""" print("data attributes of %r" % (x,)) names = dir(x) maxlen = max([0] + [len(n) for n in names]) for k in names: v = getattr(x, k) if isinstance(v, types.MethodType): continue if k[:2...
I lookup an existing predefined domain
def lookupByName(self, name): """ I lookup an existing predefined domain """ res = yield queue.executeInThread(self.connection.lookupByName, name) return self.DomainClass(self, res)
I take libvirt XML and start a new VM
def create(self, xml): """ I take libvirt XML and start a new VM """ res = yield queue.executeInThread(self.connection.createXML, xml, 0) return self.DomainClass(self, res)
I find existing VMs that are already running that might be orphaned instances of this worker.
def _find_existing_instance(self): """ I find existing VMs that are already running that might be orphaned instances of this worker. """ if not self.connection: return None domains = yield self.connection.all() for d in domains: name = yield d.nam...
I am a private method for creating (possibly cheap) copies of a base_image for start_instance to boot.
def _prepare_base_image(self): """ I am a private method for creating (possibly cheap) copies of a base_image for start_instance to boot. """ if not self.base_image: return defer.succeed(True) if self.cheap_copy: clone_cmd = "qemu-img" ...
I start a new instance of a VM. If a base_image is specified, I will make a clone of that otherwise i will use image directly. If i'm not given libvirt domain definition XML, I will look for my name in the list of defined virtual machines and start that.
def start_instance(self, build): """ I start a new instance of a VM. If a base_image is specified, I will make a clone of that otherwise i will use image directly. If i'm not given libvirt domain definition XML, I will look for my name in the list of defined virtual mac...
I attempt to stop a running VM. I make sure any connection to the worker is removed. If the VM was using a cloned image, I remove the clone When everything is tidied up, I ask that bbot looks for work to do
def stop_instance(self, fast=False): """ I attempt to stop a running VM. I make sure any connection to the worker is removed. If the VM was using a cloned image, I remove the clone When everything is tidied up, I ask that bbot looks for work to do """ log.msg("Att...
Splits the branchfile argument and assuming branch is the first path component in branchfile, will return branch and file else None.
def get_simple_split(branchfile): """Splits the branchfile argument and assuming branch is the first path component in branchfile, will return branch and file else None.""" index = branchfile.find('/') if index == -1: return None, None branch, file = branchfile.split('/', 1) r...
Make sure that C{builderNames} is a subset of the configured C{self.builderNames}, returning an empty list if not. If C{builderNames} is empty, use C{self.builderNames}. @returns: list of builder names to build on
def filterBuilderList(self, builderNames): """ Make sure that C{builderNames} is a subset of the configured C{self.builderNames}, returning an empty list if not. If C{builderNames} is empty, use C{self.builderNames}. @returns: list of builder names to build on """ ...
Record a reference to the argument key.
def _ref_key(self, key): """Record a reference to the argument key.""" queue = self.queue refcount = self.refcount queue.append(key) refcount[key] = refcount[key] + 1 # periodically compact the queue by eliminating duplicate keys # while preserving order of most...
Try to do a value lookup from the existing cache entries.
def _get_hit(self, key): """Try to do a value lookup from the existing cache entries.""" try: result = self.cache[key] self.hits += 1 self._ref_key(key) return result except KeyError: pass result = self.weakrefs[key] se...