text
stringlengths
81
112k
Create buildbot.tac file. If buildbot.tac file already exists with different contents, create buildbot.tac.new instead. @param basedir: worker base directory relative path @param tac_file_contents: contents of buildbot.tac file to write @param quiet: if True, don't print info messages @raise Creat...
Create info/* files inside basedir. @param basedir: worker base directory relative path @param quiet: if True, don't print info messages @raise CreateWorkerError: on error making info directory or writing info files def _makeInfoFiles(basedir, quiet): """ Create inf...
Takes a git repository URL from Bitbucket and tries to determine the owner and repository name :param repourl: Bitbucket git repo in the form of git@bitbucket.com:OWNER/REPONAME.git https://bitbucket.com/OWNER/REPONAME.git ssh://git@bitbucket.com/OWNER...
Called periodically by DBConnector, this method deletes changes older than C{changeHorizon}. def pruneChanges(self, changeHorizon): """ Called periodically by DBConnector, this method deletes changes older than C{changeHorizon}. """ if not changeHorizon: ret...
mostly comes from _twistd_unix.py which is not twisted public API :-/ except it returns an exception instead of exiting def checkPidFile(pidfile): """ mostly comes from _twistd_unix.py which is not twisted public API :-/ except it returns an exception instead of exiting """ if os.path.exi...
Find the .buildbot/options file. Crawl from the current directory up towards the root, and also look in ~/.buildbot . The first directory that's owned by the user and has the file we're looking for wins. Windows skips the owned-by-user test. @rtype: dict @return: a dictionary o...
The login process failed, most likely because of an authorization failure (bad password), but it is also possible that we lost the new connection before we managed to send our credentials. def failedToGetPerspective(self, why, broker): """The login process failed, most likely because of an auth...
:param project_id: Project ID from GitLab :param branch: Branch name to create the status for. :param sha: Full sha to create the status for. :param state: one of the following 'pending', 'success', 'failed' or 'cancelled'. :param target_url: Target url to associate...
Construct a new L{BuildRequest} from a dictionary as returned by L{BuildRequestsConnectorComponent.getBuildRequest}. This method uses a cache, which may result in return of stale objects; for the most up-to-date information, use the database connector methods. @param master: cu...
Returns true if both buildrequest can be merged, via Deferred. This implements Buildbot's default collapse strategy. def canBeCollapsed(master, br1, br2): """ Returns true if both buildrequest can be merged, via Deferred. This implements Buildbot's default collapse strategy. "...
Returns one merged sourcestamp for every codebase def mergeSourceStampsWith(self, others): """ Returns one merged sourcestamp for every codebase """ # get all codebases from all requests all_codebases = set(self.sources) for other in others: all_codebases |= set(other.source...
Return a reason for the merged build request. def mergeReasons(self, others): """Return a reason for the merged build request.""" reasons = [] for req in [self] + others: if req.reason and req.reason not in reasons: reasons.append(req.reason) return ", ".join...
Convert C{bytes} to a native C{str}. On Python 3 and higher, str and bytes are not equivalent. In this case, decode the bytes, and return a native string. On Python 2 and lower, str and bytes are equivalent. In this case, just just return the native string. @param x: a string of type C{...
Convert a unicode string to C{bytes}. @param x: a unicode string, of type C{unicode} on Python 2, or C{str} on Python 3. @param encoding: an optional codec, default: 'utf-8' @param errors: error handling scheme, default 'strict' @return: a string of type C{bytes} def unicode2bytes(x, enc...
Convert a C{bytes} to a unicode string. @param x: a unicode string, of type C{unicode} on Python 2, or C{str} on Python 3. @param encoding: an optional codec, default: 'utf-8' @param errors: error handling scheme, default 'strict' @return: a unicode string of type C{unicode} on Python 2, ...
Try to remove the old mock logs first. def start(self): """ Try to remove the old mock logs first. """ if self.resultdir: for lname in self.mock_logfiles: self.logfiles[lname] = self.build.path_module.join(self.resultdir, ...
\ Input is the json representation of: {'stream': "Content\ncontent"} Output is a generator yield "Content", and then "content" def _handle_stream_line(line): """\ Input is the json representation of: {'stream': "Content\ncontent"} Output is a generator yield "Content", and then "content" """ ...
Returns True if this build should be reported for this contact (eliminating duplicates), and also records the report for later def shouldReportBuild(self, builder, buildnum): """Returns True if this build should be reported for this contact (eliminating duplicates), and also records the report ...
Returns list of arguments parsed by shlex.split() or raise UsageError if failed def splitArgs(self, args): """Returns list of arguments parsed by shlex.split() or raise UsageError if failed""" try: return shlex.split(args) except ValueError as e: raise Us...
get a Contact instance for ``user`` on ``channel`` def getContact(self, user=None, channel=None): """ get a Contact instance for ``user`` on ``channel`` """ try: return self.contacts[(channel, user)] except KeyError: new_contact = self.contactClass(self, user=user, chann...
An issue - failing, erroring etc test. def issue(self, test, err): """An issue - failing, erroring etc test.""" self.step.setProgress('tests failed', len(self.failures) + len(self.errors))
Consumes the JSON as a python object and actually starts the build. :arguments: payload Python Object that represents the JSON sent by GitLab Service Hook. def _process_change(self, payload, user, repo, repo_url, event, codebase=None): ...
Consumes the merge_request JSON as a python object and turn it into a buildbot change. :arguments: payload Python Object that represents the JSON sent by GitLab Service Hook. def _process_merge_request_change(self, payload, event, codebase=None): """ ...
Reponds only to POST events and starts the build process :arguments: request the http request object def getChanges(self, request): """ Reponds only to POST events and starts the build process :arguments: request the http request...
Set up FN to only run once within an interpreter instance def onlyOnce(fn): 'Set up FN to only run once within an interpreter instance' def wrap(*args, **kwargs): if hasattr(fn, 'called'): return fn.called = 1 return fn(*args, **kwargs) util.mergeFunctionMetadata(fn, wra...
return the full spec of the connector as a list of dicts def allEndpoints(self): """return the full spec of the connector as a list of dicts """ paths = [] for k, v in sorted(self.matcher.iterPatterns()): paths.append(dict(path="/".join(k), plur...
Validate master (-m, --master) command line option. Checks that option is a string of the 'hostname:port' form, otherwise raises an UsageError exception. @type master: string @param master: master option @raise usage.UsageError: on invalid master option def validateMasterOption(master): """...
concat a path for this name def addEnvPath(env, name, value): """ concat a path for this name """ try: oldval = env[name] if not oldval.endswith(';'): oldval = oldval + ';' except KeyError: oldval = "" if not value.endswith(';'): value = value + ';' env[n...
Ping the worker to make sure it is still there. Returns a Deferred that fires with True if it is. @param status: if you point this at a BuilderStatus, a 'pinging' event will be pushed. def ping(self, status=None): """Ping the worker to make sure it is still there. Return...
Call me at checkConfig time to properly report config error if neither txrequests or treq is installed def checkAvailable(from_module): """Call me at checkConfig time to properly report config error if neither txrequests or treq is installed """ if txrequests is None and t...
Generator for a list/tuple that potentially contains nested/lists/tuples of arbitrary nesting that returns every individual non-list/tuple element. In other words, [(5, 6, [8, 3]), 2, [2, 1, (3, 4)]] will yield 5, 6, 8, 3, 2, 2, 1, 3, 4 This is safe to call on something not a list/tuple - the original inp...
Given a list/tuple that potentially contains nested lists/tuples of arbitrary nesting, flatten into a single dimension. In other words, turn [(5, 6, [8, 3]), 2, [2, 1, (3, 4)]] into [5, 6, 8, 3, 2, 2, 1, 3, 4] This is safe to call on something not a list/tuple - the original input is returned as a list d...
Return a string of human readable time delta. def human_readable_delta(start, end): """ Return a string of human readable time delta. """ start_date = datetime.datetime.fromtimestamp(start) end_date = datetime.datetime.fromtimestamp(end) delta = end_date - start_date result = [] if del...
decorate a function by running it with maybeDeferred in a reactor def in_reactor(f): """decorate a function by running it with maybeDeferred in a reactor""" def wrap(*args, **kwargs): from twisted.internet import reactor, defer result = [] def _async(): d = defer.maybeDefer...
merges dictionary b into a Like dict.update, but recursive def dictionary_merge(a, b): """merges dictionary b into a Like dict.update, but recursive """ for key, value in b.items(): if key in a and isinstance(a[key], dict) and isinstance(value, dict): dictionary_merge(a[ke...
Create nice summary logs. @param log: log to create summary off of. def createSummary(self, log): """ Create nice summary logs. @param log: log to create summary off of. """ warnings = self.obs.warnings errors = [] if warnings: self.addCompl...
Returns the submitted_at of the oldest unclaimed build request for this builder, or None if there are no build requests. @returns: datetime instance or None, via Deferred def getOldestRequestTime(self): """Returns the submitted_at of the oldest unclaimed build request for this builder,...
Returns the complete_at of the latest completed build request for this builder, or None if there are no such build requests. @returns: datetime instance or None, via Deferred def getNewestCompleteTime(self): """Returns the complete_at of the latest completed build request for this buil...
This is invoked by the Worker when the self.workername bot registers their builder. @type worker: L{buildbot.worker.Worker} @param worker: the Worker that represents the worker as a whole @type commands: dict: string -> string, or None @param commands: provides the worker's ve...
This is called when the connection to the bot is lost. def detached(self, worker): """This is called when the connection to the bot is lost.""" for wfb in self.attaching_workers + self.workers: if wfb.worker == worker: break else: log.msg("WEIRD: Builder....
This is called when the Build has finished (either success or failure). Any exceptions during the build are reported with results=FAILURE, not with an errback. def buildFinished(self, build, wfb): """This is called when the Build has finished (either success or failure). Any exceptions ...
Helper function to determine which collapseRequests function to use from L{_collapseRequests}, or None for no merging def getCollapseRequestsFn(self): """Helper function to determine which collapseRequests function to use from L{_collapseRequests}, or None for no merging""" # first, see...
private implementation of reactor.spawnProcess, to allow use of L{ProcGroupProcess} def _spawnProcess(self, processProtocol, executable, args=(), env=None, path=None, uid=None, gid=None, usePTY=False, childFDs=None): """private implementation of reactor.spawnProcess, to allow use ...
A cheat that routes around the impedance mismatch between twisted and cmd.exe with respect to escaping quotes def _spawnAsBatch(self, processProtocol, executable, args, env, path, usePTY): """A cheat that routes around the impedance mismatch between twisted and cmd.exe wit...
limit the chunks that we send over PB to 128k, since it has a hardwired string-size limit of 640k. def _chunkForSend(self, data): """ limit the chunks that we send over PB to 128k, since it has a hardwired string-size limit of 640k. """ LIMIT = self.CHUNK_LIMIT f...
Take msg, which is a dictionary of lists of output chunks, and concatenate all the chunks into a single string def _collapseMsg(self, msg): """ Take msg, which is a dictionary of lists of output chunks, and concatenate all the chunks into a single string """ retval = {} ...
Collapse and send msg to the master def _sendMessage(self, msg): """ Collapse and send msg to the master """ if not msg: return msg = self._collapseMsg(msg) self.sendStatus(msg)
Send all the content in our buffers. def _sendBuffers(self): """ Send all the content in our buffers. """ msg = {} msg_size = 0 lastlog = None logdata = [] while self.buffered: # Grab the next bits from the buffer logname, data = s...
Add data to the buffer for logname Start a timer to send the buffers if BUFFER_TIMEOUT elapses. If adding data causes the buffer size to grow beyond BUFFER_SIZE, then the buffers will be sent. def _addToBuffers(self, logname, data): """ Add data to the buffer for logname ...
This gets invoked by L{buildbot.process.step.RemoteCommand.start}, as part of various master-side BuildSteps, to start various commands that actually do the build. I return nothing. Eventually I will call .commandComplete() to notify the master-side RemoteCommand that I'm done. def remo...
Halt the current step. def remote_interruptCommand(self, stepId, why): """Halt the current step.""" log.msg("asked to interrupt current command: {0}".format(why)) self.activity() if not self.command: # TODO: just log it, a race could result in their interrupting a ...
Make any currently-running command die, with no further status output. This is used when the worker is shutting down or the connection to the master has been lost. Interrupt the command, silence it, and then forget about it. def stopCommand(self): """Make any currently-running command d...
This sends the status update to the master-side L{buildbot.process.step.RemoteCommand} object, giving it a sequence number in the process. It adds the update to a queue, and asks the master to acknowledge the update so it can be removed from that queue. def sendUpdate(self, data): ...
This command retrieves data from the files in WORKERDIR/info/* and sends the contents to the buildmaster. These are used to describe the worker and its configuration, and should be created and maintained by the worker administrator. They will be retrieved each time the master-worker conn...
Record my hostname in twistd.hostname, for user convenience def recordHostname(self, basedir): "Record my hostname in twistd.hostname, for user convenience" log.msg("recording hostname in twistd.hostname") filename = os.path.join(basedir, "twistd.hostname") try: hostname = ...
walk upwards from the current directory until we find this topfile def getTopdir(topfile, start=None): """walk upwards from the current directory until we find this topfile""" if not start: start = os.getcwd() here = start toomany = 20 while toomany > 0: if os.path.exists(os.path.jo...
This accepts the arguments of a command, without the actual command itself. def dovc(self, cmd): """This accepts the arguments of a command, without the actual command itself.""" env = os.environ.copy() env['LC_ALL'] = "C" d = utils.getProcessOutputAndValue(self.exe, cmd...
Return a Deferred that fires with a SourceStamp instance. def get(self): """Return a Deferred that fires with a SourceStamp instance.""" d = self.getBaseRevision() d.addCallback(self.getPatch) d.addCallback(self.done) return d
Version of check_output which does not throw error def check_output(cmd): """Version of check_output which does not throw error""" popen = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE) out = popen.communicate()[0].strip() if not isinstance(out, str): out = out.decode(sys.stdout.enco...
Extract the tag if a source is from git archive. When source is exported via `git archive`, the git_archive_id init value is modified and placeholders are expanded to the "archived" revision: %ct: committer date, UNIX timestamp %d: ref names, like the --decorate option of git-l...
Return BUILDBOT_VERSION environment variable, content of VERSION file, git tag or 'latest' def getVersion(init_file): """ Return BUILDBOT_VERSION environment variable, content of VERSION file, git tag or 'latest' """ try: return os.environ['BUILDBOT_VERSION'] except KeyError: ...
Run command. def run(self): """Run command.""" if self.already_run: return package = self.distribution.packages[0] if os.path.exists("gulpfile.js") or os.path.exists("webpack.config.js"): yarn_version = check_output("yarn --version") npm_version = che...
:param repo: the repo full name, ``{owner}/{project}``. e.g. ``buildbot/buildbot`` def _get_commit_msg(self, repo, sha): ''' :param repo: the repo full name, ``{owner}/{project}``. e.g. ``buildbot/buildbot`` ''' headers = { 'User-Agent': 'Buildbot' ...
Consumes the JSON as a python object and actually starts the build. :arguments: payload Python Object that represents the JSON sent by GitHub Service Hook. def _process_change(self, payload, user, repo, repo_url, project, event, properties): ...
The message contains the skipping keyword no not. :return type: Bool def _has_skip(self, msg): ''' The message contains the skipping keyword no not. :return type: Bool ''' for skip in self.skips: if re.search(skip, msg): return True ...
Create nice summary logs. @param log: log to create summary off of. def createSummary(self, log): """ Create nice summary logs. @param log: log to create summary off of. """ warnings = self.obs.warnings errors = self.obs.errors if warnings: ...
Write a block of data to the remote writer def _writeBlock(self): """Write a block of data to the remote writer""" if self.interrupted or self.fp is None: if self.debug: log.msg('WorkerFileUploadCommand._writeBlock(): end') return True length = self.blo...
Read a block of data from the remote reader. def _readBlock(self): """Read a block of data from the remote reader.""" if self.interrupted or self.fp is None: if self.debug: log.msg('WorkerFileDownloadCommand._readBlock(): end') return True length = self...
Generate a buildbot mail message and return a dictionary containing the message body, type and subject. def formatMessageForBuildResults(self, mode, buildername, buildset, build, master, previous_results, blamelist): """Generate a buildbot mail message and return a dictionary containing t...
A full name, intended to uniquely identify a parameter def fullName(self): """A full name, intended to uniquely identify a parameter""" # join with '_' if both are set (cannot put '.', because it is used as # **kwargs) if self.parentName and self.name: return self.parentName...
Simple customization point for child classes that do not need the other parameters supplied to updateFromKwargs. Return the value for the property named 'self.name'. The default implementation converts from a list of items, validates using the optional regex field and calls ...
Primary entry point to turn 'kwargs' into 'properties def updateFromKwargs(self, properties, kwargs, collector, **unused): """Primary entry point to turn 'kwargs' into 'properties'""" properties[self.name] = self.getFromKwargs(kwargs)
Secondary customization point, called from getFromKwargs to turn a validated value into a single property value def parse_from_args(self, l): """Secondary customization point, called from getFromKwargs to turn a validated value into a single property value""" if self.multiple: ...
Collapse the child values into a dictionary. This is intended to be called by child classes to fix up the fullName->name conversions. def collectChildProperties(self, kwargs, properties, collector, **kw): """Collapse the child values into a dictionary. This is intended to be called by chi...
By default, the child values will be collapsed into a dictionary. If the parent is anonymous, this dictionary is the top-level properties. def updateFromKwargs(self, kwargs, properties, collector, **kw): """By default, the child values will be collapsed into a dictionary. If the parent is anony...
We check the parameters, and launch the build, if everything is correct def force(self, owner, builderNames=None, builderid=None, **kwargs): """ We check the parameters, and launch the build, if everything is correct """ builderNames = yield self.computeBuilderNames(builderNames, builde...
get secrets from the provider defined in the secret using args and kwargs @secrets: secrets keys @type: string @return type: SecretDetails def get(self, secret, *args, **kwargs): """ get secrets from the provider defined in the secret using args and kwargs ...
save function def save(): """ save function """ results = {} cpu_number = 0 while True: try: _file = open( CPU_PREFIX + 'cpu{}/cpufreq/scaling_governor'.format(cpu_number)) except: break governor = _file.read().strip() re...
change function def change(governor, freq=None): """ change function """ cpu_number = 0 while True: try: subprocess.check_output([ "sudo", "bash", "-c", "echo {governor} > {CPU_PREFIX}cpu{cpu_number}/cpufreq/scaling_governor" .for...
function for checking available frequency def available_freq(): """ function for checking available frequency """ _file = open(CPU_PREFIX + 'cpu0/cpufreq/scaling_available_frequencies') freq = [int(_file) for _file in _file.read().strip().split()] _file.close() return freq
dump function def dump(): """ dump function """ try: sensors = subprocess.check_output('sensors').decode('utf-8') except (FileNotFoundError, subprocess.CalledProcessError): print("Couldn't read CPU temp") else: cores = [] for line in sensors.splitlines(): ...
Pads data to the multiplies of 8 bytes. This makes x86_64 faster and prevents undefined behavior on other platforms def padto8(data): """Pads data to the multiplies of 8 bytes. This makes x86_64 faster and prevents undefined behavior on other platforms""" length = len(data) re...
Parse a ``Cookie`` HTTP header into a dict of name/value pairs. This function attempts to mimic browser cookie parsing behavior; it specifically does not follow any of the cookie-related RFCs (because browsers don't either). The algorithm used is identical to that used by Django version 1.9.10. def par...
A heuristic to find out if a function is simple enough. def is_simple(fun): """A heuristic to find out if a function is simple enough.""" seen_load_fast_0 = False seen_load_response = False seen_call_fun = False for instruction in dis.get_instructions(fun): if instruction.opname == 'LOAD_F...
Return a list of variable names being rejected for high correlation with one of remaining variables. Parameters: ---------- threshold : float Correlation value which is above the threshold are rejected Returns ------- list The lis...
Write the report to a file. By default a name is generated. Parameters: ---------- outputfile : str The name or the path of the file to generale including the extension (.html). def to_file(self, outputfile=DEFAULT_OUTPUTFILE): """Write the report to a file...
Return a jinja template ready for rendering. If needed, global variables are initialized. Parameters ---------- template_name: str, the name of the template as defined in the templates mapping Returns ------- The Jinja template ready for rendering def template(template_name): """Return a ...
Generate a HTML report from summary statistics and a given sample. Parameters ---------- sample : DataFrame the sample you want to print stats_object : dict Summary statistics. Should be generated with an appropriate describe() function Returns ------- str containin...
Compute summary statistics of a numerical (`TYPE_NUM`) variable (a Series). Also create histograms (mini an full) of its distribution. Parameters ---------- series : Series The variable to describe. Returns ------- Series The description of the variable as a Series with in...
Compute summary statistics of a date (`TYPE_DATE`) variable (a Series). Also create histograms (mini an full) of its distribution. Parameters ---------- series : Series The variable to describe. Returns ------- Series The description of the variable as a Series with index ...
Compute summary statistics of a categorical (`TYPE_CAT`) variable (a Series). Parameters ---------- series : Series The variable to describe. Returns ------- Series The description of the variable as a Series with index being stats keys. def describe_categorical_1d(series): ...
Compute summary statistics of a boolean (`TYPE_BOOL`) variable (a Series). Parameters ---------- series : Series The variable to describe. Returns ------- Series The description of the variable as a Series with index being stats keys. def describe_boolean_1d(series): """Co...
Compute summary statistics of a constant (`S_TYPE_CONST`) variable (a Series). Parameters ---------- series : Series The variable to describe. Returns ------- Series The description of the variable as a Series with index being stats keys. def describe_constant_1d(series): ...
Compute summary statistics of a unique (`S_TYPE_UNIQUE`) variable (a Series). Parameters ---------- series : Series The variable to describe. Returns ------- Series The description of the variable as a Series with index being stats keys. def describe_unique_1d(series): """...
Compute summary statistics of a supported variable (a Series). Parameters ---------- series : Series The variable to describe. Returns ------- Series The description of the variable as a Series with index being stats keys. def describe_supported(series, **kwargs): """Compu...
Compute summary statistics of a unsupported (`S_TYPE_UNSUPPORTED`) variable (a Series). Parameters ---------- series : Series The variable to describe. Returns ------- Series The description of the variable as a Series with index being stats keys. def describe_unsupported(seri...
Compute summary statistics of a variable (a Series). The description is different according to the type of the variable. However a set of common stats is also computed. Parameters ---------- series : Series The variable to describe. Returns ------- Series The descripti...
Generates a dict containing summary statistics for a given dataset stored as a pandas `DataFrame`. Used has is it will output its content as an HTML report in a Jupyter notebook. Parameters ---------- df : DataFrame Data to be analyzed bins : int Number of bins in histogram. ...
Plot an histogram from the data and return the AxesSubplot object. Parameters ---------- series : Series The data to plot figsize : tuple The size of the figure (width, height) in inches, default (6,4) facecolor : str The color code. Returns ------- matplotlib.A...
Plot an histogram of the data. Parameters ---------- series: Series The data to plot. Returns ------- str The resulting image encoded as a string. def histogram(series, **kwargs): """Plot an histogram of the data. Parameters ---------- series: Series T...