id
int64 0
458k
| file_name
stringlengths 4
119
| file_path
stringlengths 14
227
| content
stringlengths 24
9.96M
| size
int64 24
9.96M
| language
stringclasses 1
value | extension
stringclasses 14
values | total_lines
int64 1
219k
| avg_line_length
float64 2.52
4.63M
| max_line_length
int64 5
9.91M
| alphanum_fraction
float64 0
1
| repo_name
stringlengths 7
101
| repo_stars
int64 100
139k
| repo_forks
int64 0
26.4k
| repo_open_issues
int64 0
2.27k
| repo_license
stringclasses 12
values | repo_extraction_date
stringclasses 433
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
4,900 | __init__.py | buildbot_buildbot/master/buildbot/worker/__init__.py | # This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright Buildbot Team Members
from buildbot.worker.base import AbstractWorker
from buildbot.worker.base import Worker
from buildbot.worker.latent import AbstractLatentWorker
_hush_pyflakes = [
AbstractWorker,
Worker,
AbstractLatentWorker,
]
| 930 | Python | .py | 22 | 40.636364 | 79 | 0.798013 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
4,901 | base.py | buildbot_buildbot/master/buildbot/worker/base.py | # This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Portions Copyright Buildbot Team Members
# Portions Copyright Canonical Ltd. 2009
from __future__ import annotations
import time
from twisted.internet import defer
from twisted.internet.base import DelayedCall
from twisted.python import log
from twisted.python.reflect import namedModule
from zope.interface import implementer
from buildbot import config
from buildbot.interfaces import IWorker
from buildbot.process import metrics
from buildbot.process.properties import Properties
from buildbot.util import Notifier
from buildbot.util import bytes2unicode
from buildbot.util import deferwaiter
from buildbot.util import service
@implementer(IWorker)
class AbstractWorker(service.BuildbotService):
"""This is the master-side representative for a remote buildbot worker.
There is exactly one for each worker described in the config file (the
c['workers'] list). When buildbots connect in (.attach), they get a
reference to this instance. The BotMaster object is stashed as the
.botmaster attribute. The BotMaster is also our '.parent' Service.
I represent a worker -- a remote machine capable of
running builds. I am instantiated by the configuration file, and can be
subclassed to add extra functionality."""
# reconfig workers after builders
reconfig_priority = 64
quarantine_timer: DelayedCall | None = None
quarantine_timeout = quarantine_initial_timeout = 10
quarantine_max_timeout = 60 * 60
start_missing_on_startup = True
DEFAULT_MISSING_TIMEOUT = 3600
DEFAULT_KEEPALIVE_INTERVAL = 3600
# override to True if isCompatibleWithBuild may return False
builds_may_be_incompatible = False
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._deferwaiter = deferwaiter.DeferWaiter()
def checkConfig(
self,
name,
password,
max_builds=None,
notify_on_missing=None,
missing_timeout=None,
properties=None,
defaultProperties=None,
locks=None,
keepalive_interval=DEFAULT_KEEPALIVE_INTERVAL,
machine_name=None,
):
"""
@param name: botname this machine will supply when it connects
@param password: password this machine will supply when
it connects
@param max_builds: maximum number of simultaneous builds that will
be run concurrently on this worker (the
default is None for no limit)
@param properties: properties that will be applied to builds run on
this worker
@type properties: dictionary
@param defaultProperties: properties that will be applied to builds
run on this worker only if the property
has not been set by another source
@type defaultProperties: dictionary
@param locks: A list of locks that must be acquired before this worker
can be used
@type locks: dictionary
@param machine_name: The name of the machine to associate with the
worker.
"""
self.name = name = bytes2unicode(name)
self.machine_name = machine_name
self.password = password
# protocol registration
self.registration = None
self._graceful = False
self._paused = False
self._pause_reason = None
# these are set when the service is started
self.manager = None
self.workerid = None
self.info = Properties()
self.worker_commands = None
self.workerforbuilders = {}
self.max_builds = max_builds
self.access = []
if locks:
self.access = locks
self.lock_subscriptions = []
self.properties = Properties()
self.properties.update(properties or {}, "Worker")
self.properties.setProperty("workername", name, "Worker")
self.defaultProperties = Properties()
self.defaultProperties.update(defaultProperties or {}, "Worker")
if self.machine_name is not None:
self.properties.setProperty('machine_name', self.machine_name, 'Worker')
self.machine = None
self.lastMessageReceived = 0
if notify_on_missing is None:
notify_on_missing = []
if isinstance(notify_on_missing, str):
notify_on_missing = [notify_on_missing]
self.notify_on_missing = notify_on_missing
for i in notify_on_missing:
if not isinstance(i, str):
config.error(f'notify_on_missing arg {i!r} is not a string')
self.missing_timeout = missing_timeout
self.missing_timer = None
# a protocol connection, if we're currently connected
self.conn = None
# during disconnection self.conn will be set to None before all disconnection notifications
# are delivered. During that period _pending_conn_shutdown_notifier will be set to
# a notifier and allows interested users to wait until all disconnection notifications are
# delivered.
self._pending_conn_shutdown_notifier = None
self._old_builder_list = None
self._configured_builderid_list = None
def __repr__(self):
return f"<{self.__class__.__name__} {self.name!r}>"
@property
def workername(self):
# workername is now an alias to twisted.Service's name
return self.name
@property
def botmaster(self):
if self.master is None:
return None
return self.master.botmaster
@defer.inlineCallbacks
def updateLocks(self):
"""Convert the L{LockAccess} objects in C{self.locks} into real lock
objects, while also maintaining the subscriptions to lock releases."""
# unsubscribe from any old locks
for s in self.lock_subscriptions:
s.unsubscribe()
# convert locks into their real form
locks = yield self.botmaster.getLockFromLockAccesses(self.access, self.config_version)
self.locks = [(l.getLockForWorker(self.workername), la) for l, la in locks]
self.lock_subscriptions = [
l.subscribeToReleases(self._lockReleased) for l, la in self.locks
]
def locksAvailable(self):
"""
I am called to see if all the locks I depend on are available,
in which I return True, otherwise I return False
"""
if not self.locks:
return True
for lock, access in self.locks:
if not lock.isAvailable(self, access):
return False
return True
def acquireLocks(self):
"""
I am called when a build is preparing to run. I try to claim all
the locks that are needed for a build to happen. If I can't, then
my caller should give up the build and try to get another worker
to look at it.
"""
log.msg(f"acquireLocks(worker {self}, locks {self.locks})")
if not self.locksAvailable():
log.msg(f"worker {self} can't lock, giving up")
return False
# all locks are available, claim them all
for lock, access in self.locks:
lock.claim(self, access)
return True
def releaseLocks(self):
"""
I am called to release any locks after a build has finished
"""
log.msg(f"releaseLocks({self}): {self.locks}")
for lock, access in self.locks:
lock.release(self, access)
def _lockReleased(self):
"""One of the locks for this worker was released; try scheduling
builds."""
if not self.botmaster:
return # oh well..
self.botmaster.maybeStartBuildsForWorker(self.name)
def _applyWorkerInfo(self, info):
if not info:
return
# set defaults
self.info.setProperty("version", "(unknown)", "Worker")
# store everything as Properties
for k, v in info.items():
if k in ('environ', 'worker_commands'):
continue
self.info.setProperty(k, v, "Worker")
@defer.inlineCallbacks
def _getWorkerInfo(self):
worker = yield self.master.data.get(('workers', self.workerid))
self._paused = worker["paused"]
self._applyWorkerInfo(worker['workerinfo'])
def setServiceParent(self, parent):
# botmaster needs to set before setServiceParent which calls
# startService
self.manager = parent
return super().setServiceParent(parent)
@defer.inlineCallbacks
def startService(self):
# tracks config version for locks
self.config_version = self.master.config_version
self.updateLocks()
self.workerid = yield self.master.data.updates.findWorkerId(self.name)
self.workerActionConsumer = yield self.master.mq.startConsuming(
self.controlWorker, ("control", "worker", str(self.workerid), None)
)
yield self._getWorkerInfo()
yield super().startService()
# startMissingTimer wants the service to be running to really start
if self.start_missing_on_startup:
self.startMissingTimer()
@defer.inlineCallbacks
def reconfigService(
self,
name,
password,
max_builds=None,
notify_on_missing=None,
missing_timeout=DEFAULT_MISSING_TIMEOUT,
properties=None,
defaultProperties=None,
locks=None,
keepalive_interval=DEFAULT_KEEPALIVE_INTERVAL,
machine_name=None,
):
# Given a Worker config arguments, configure this one identically.
# Because Worker objects are remotely referenced, we can't replace them
# without disconnecting the worker, yet there's no reason to do that.
assert self.name == name
self.password = yield self.renderSecrets(password)
# adopt new instance's configuration parameters
self.max_builds = max_builds
self.access = []
if locks:
self.access = locks
if notify_on_missing is None:
notify_on_missing = []
if isinstance(notify_on_missing, str):
notify_on_missing = [notify_on_missing]
self.notify_on_missing = notify_on_missing
if self.missing_timeout != missing_timeout:
running_missing_timer = self.missing_timer
self.stopMissingTimer()
self.missing_timeout = missing_timeout
if running_missing_timer:
self.startMissingTimer()
self.properties = Properties()
self.properties.update(properties or {}, "Worker")
self.properties.setProperty("workername", name, "Worker")
self.defaultProperties = Properties()
self.defaultProperties.update(defaultProperties or {}, "Worker")
# Note that before first reconfig self.machine will always be None and
# out of sync with self.machine_name, thus more complex logic is needed.
if self.machine is not None and self.machine_name != machine_name:
self.machine.unregisterWorker(self)
self.machine = None
self.machine_name = machine_name
if self.machine is None and self.machine_name is not None:
self.machine = self.master.machine_manager.getMachineByName(self.machine_name)
if self.machine is not None:
self.machine.registerWorker(self)
self.properties.setProperty("machine_name", self.machine_name, "Worker")
else:
log.err(f"Unknown machine '{self.machine_name}' for worker '{self.name}'")
# update our records with the worker manager
if not self.registration:
self.registration = yield self.master.workers.register(self)
yield self.registration.update(self, self.master.config)
# tracks config version for locks
self.config_version = self.master.config_version
self.updateLocks()
@defer.inlineCallbacks
def reconfigServiceWithSibling(self, sibling):
# reconfigServiceWithSibling will only reconfigure the worker when it is configured
# differently.
# However, the worker configuration depends on which builder it is configured
yield super().reconfigServiceWithSibling(sibling)
# update the attached worker's notion of which builders are attached.
# This assumes that the relevant builders have already been configured,
# which is why the reconfig_priority is set low in this class.
bids = [b.getBuilderId() for b in self.botmaster.getBuildersForWorker(self.name)]
bids = yield defer.gatherResults(bids, consumeErrors=True)
if self._configured_builderid_list != bids:
yield self.master.data.updates.workerConfigured(
self.workerid, self.master.masterid, bids
)
yield self.updateWorker()
self._configured_builderid_list = bids
@defer.inlineCallbacks
def stopService(self):
if self.registration:
yield self.registration.unregister()
self.registration = None
self.workerActionConsumer.stopConsuming()
self.stopMissingTimer()
self.stopQuarantineTimer()
# mark this worker as configured for zero builders in this master
yield self.master.data.updates.workerConfigured(self.workerid, self.master.masterid, [])
# during master shutdown we need to wait until the disconnection notification deliveries
# are completed, otherwise some of the events may still be firing long after the master
# is completely shut down.
yield self.disconnect()
yield self.waitForCompleteShutdown()
yield self._deferwaiter.wait()
yield super().stopService()
def isCompatibleWithBuild(self, build_props):
# given a build properties object, determines whether the build is
# compatible with the currently running worker or not. This is most
# often useful for latent workers where it's possible to request
# different kinds of workers.
return defer.succeed(True)
def startMissingTimer(self):
if self.missing_timeout and self.parent and self.running:
self.stopMissingTimer() # in case it's already running
self.missing_timer = self.master.reactor.callLater(
self.missing_timeout, self._missing_timer_fired
)
def stopMissingTimer(self):
if self.missing_timer:
if self.missing_timer.active():
self.missing_timer.cancel()
self.missing_timer = None
def isConnected(self):
return self.conn
def _missing_timer_fired(self):
self.missing_timer = None
# notify people, but only if we're still in the config
if not self.parent:
return
last_connection = time.ctime(time.time() - self.missing_timeout)
self.master.data.updates.workerMissing(
workerid=self.workerid,
masterid=self.master.masterid,
last_connection=last_connection,
notify=self.notify_on_missing,
)
def updateWorker(self):
"""Called to add or remove builders after the worker has connected.
@return: a Deferred that indicates when an attached worker has
accepted the new builders and/or released the old ones."""
if self.conn:
return self.sendBuilderList()
# else:
return defer.succeed(None)
@defer.inlineCallbacks
def attached(self, conn):
"""This is called when the worker connects."""
if self.conn is not None:
raise AssertionError(
f"{self.name}: {conn.get_peer()} connecting, "
f"but we are already connected to: {self.conn.get_peer()}"
)
metrics.MetricCountEvent.log("AbstractWorker.attached_workers", 1)
# now we go through a sequence of calls, gathering information, then
# tell the Botmaster that it can finally give this worker to all the
# Builders that care about it.
# Reset graceful shutdown status
self._graceful = False
self.conn = conn
self._old_builder_list = None # clear builder list before proceed
self._applyWorkerInfo(conn.info)
self.worker_commands = conn.info.get("worker_commands", {})
self.worker_environ = conn.info.get("environ", {})
self.worker_basedir = conn.info.get("basedir", None)
self.worker_system = conn.info.get("system", None)
# The _detach_sub member is only ever used from tests.
self._detached_sub = self.conn.notifyOnDisconnect(self.detached)
workerinfo = {
'admin': conn.info.get('admin'),
'host': conn.info.get('host'),
'access_uri': conn.info.get('access_uri'),
'version': conn.info.get('version'),
}
yield self.master.data.updates.workerConnected(
workerid=self.workerid, masterid=self.master.masterid, workerinfo=workerinfo
)
if self.worker_system == "nt":
self.path_module = namedModule("ntpath")
else:
# most everything accepts / as separator, so posix should be a
# reasonable fallback
self.path_module = namedModule("posixpath")
log.msg("bot attached")
self.messageReceivedFromWorker()
self.stopMissingTimer()
yield self.updateWorker()
yield self.botmaster.maybeStartBuildsForWorker(self.name)
self._update_paused()
self._update_graceful()
def messageReceivedFromWorker(self):
now = time.time()
self.lastMessageReceived = now
def setupProperties(self, props):
for name in self.properties.properties:
props.setProperty(name, self.properties.getProperty(name), "Worker")
for name in self.defaultProperties.properties:
if name not in props:
props.setProperty(name, self.defaultProperties.getProperty(name), "Worker")
@defer.inlineCallbacks
def _handle_conn_shutdown_notifier(self, conn):
self._pending_conn_shutdown_notifier = Notifier()
yield conn.waitShutdown()
self._pending_conn_shutdown_notifier.notify(None)
self._pending_conn_shutdown_notifier = None
@defer.inlineCallbacks
def detached(self):
conn = self.conn
self.conn = None
self._handle_conn_shutdown_notifier(conn)
# Note that _pending_conn_shutdown_notifier will not be fired until detached()
# is complete.
metrics.MetricCountEvent.log("AbstractWorker.attached_workers", -1)
self._old_builder_list = []
log.msg(f"Worker.detached({self.name})")
self.releaseLocks()
yield self.master.data.updates.workerDisconnected(
workerid=self.workerid,
masterid=self.master.masterid,
)
def disconnect(self):
"""Forcibly disconnect the worker.
This severs the TCP connection and returns a Deferred that will fire
(with None) when the connection is probably gone.
If the worker is still alive, they will probably try to reconnect
again in a moment.
This is called in two circumstances. The first is when a worker is
removed from the config file. In this case, when they try to
reconnect, they will be rejected as an unknown worker. The second is
when we wind up with two connections for the same worker, in which
case we disconnect the older connection.
"""
if self.conn is None:
return defer.succeed(None)
log.msg(f"disconnecting old worker {self.name} now")
# When this Deferred fires, we'll be ready to accept the new worker
return self._disconnect(self.conn)
def waitForCompleteShutdown(self):
# This function waits until the disconnection to happen and the disconnection
# notifications have been delivered and acted upon.
return self._waitForCompleteShutdownImpl(self.conn)
@defer.inlineCallbacks
def _waitForCompleteShutdownImpl(self, conn):
if conn:
yield conn.wait_shutdown_started()
yield conn.waitShutdown()
elif self._pending_conn_shutdown_notifier is not None:
yield self._pending_conn_shutdown_notifier.wait()
@defer.inlineCallbacks
def _disconnect(self, conn):
# This function waits until the disconnection to happen and the disconnection
# notifications have been delivered and acted upon
d = self._waitForCompleteShutdownImpl(conn)
conn.loseConnection()
log.msg("waiting for worker to finish disconnecting")
yield d
@defer.inlineCallbacks
def sendBuilderList(self):
our_builders = self.botmaster.getBuildersForWorker(self.name)
blist = [(b.name, b.config.workerbuilddir) for b in our_builders]
if blist == self._old_builder_list:
return
slist = yield self.conn.remoteSetBuilderList(builders=blist)
self._old_builder_list = blist
# Nothing has changed, so don't need to re-attach to everything
if not slist:
return
dl = []
for name in slist:
# use get() since we might have changed our mind since then
b = self.botmaster.builders.get(name)
if b:
d1 = self.attachBuilder(b)
dl.append(d1)
yield defer.DeferredList(dl)
def attachBuilder(self, builder):
return builder.attached(self, self.worker_commands)
def controlWorker(self, key, params):
log.msg(f"worker {self.name} wants to {key[-1]}: {params}")
if key[-1] == "stop":
return self.shutdownRequested()
if key[-1] == "pause":
self.pause(params.get("reason", None))
if key[-1] == "unpause":
self.unpause()
if key[-1] == "kill":
self.shutdown()
return None
def shutdownRequested(self):
self._graceful = True
self.maybeShutdown()
self._update_graceful()
def addWorkerForBuilder(self, wfb):
self.workerforbuilders[wfb.builder_name] = wfb
def removeWorkerForBuilder(self, wfb):
try:
del self.workerforbuilders[wfb.builder_name]
except KeyError:
pass
def buildStarted(self, wfb):
pass
def buildFinished(self, wfb):
"""This is called when a build on this worker is finished."""
self.botmaster.maybeStartBuildsForWorker(self.name)
def canStartBuild(self):
"""
I am called when a build is requested to see if this worker
can start a build. This function can be used to limit overall
concurrency on the worker.
Note for subclassers: if a worker can become willing to start a build
without any action on that worker (for example, by a resource in use on
another worker becoming available), then you must arrange for
L{maybeStartBuildsForWorker} to be called at that time, or builds on
this worker will not start.
"""
# If we're waiting to shutdown gracefully, paused or quarantined then we shouldn't
# accept any new jobs.
if self._graceful or self._paused or self.quarantine_timer:
return False
if self.max_builds:
active_builders = [wfb for wfb in self.workerforbuilders.values() if wfb.isBusy()]
if len(active_builders) >= self.max_builds:
return False
if not self.locksAvailable():
return False
return True
@defer.inlineCallbacks
def shutdown(self):
"""Shutdown the worker"""
if not self.conn:
log.msg("no remote; worker is already shut down")
return
yield self.conn.remoteShutdown()
def maybeShutdown(self):
"""Shut down this worker if it has been asked to shut down gracefully,
and has no active builders."""
if not self._graceful:
return
active_builders = [wfb for wfb in self.workerforbuilders.values() if wfb.isBusy()]
if active_builders:
return
d = self.shutdown()
d.addErrback(log.err, 'error while shutting down worker')
def _update_paused(self):
self._deferwaiter.add(
self.master.data.updates.set_worker_paused(
self.workerid, self._paused, self._pause_reason
)
)
def _update_graceful(self):
self._deferwaiter.add(
self.master.data.updates.set_worker_graceful(self.workerid, self._graceful)
)
def pause(self, reason):
"""Stop running new builds on the worker."""
self._paused = True
self._pause_reason = reason
self._update_paused()
def unpause(self):
"""Restart running new builds on the worker."""
self._paused = False
self._pause_reason = None
self.stopQuarantineTimer()
self.botmaster.maybeStartBuildsForWorker(self.name)
self._update_paused()
def isPaused(self):
return self._paused
def resetQuarantine(self):
self.quarantine_timeout = self.quarantine_initial_timeout
def putInQuarantine(self):
if self.quarantine_timer: # already in quarantine
return
self.quarantine_timer = self.master.reactor.callLater(
self.quarantine_timeout, self.exitQuarantine
)
log.msg(f"{self.name} has been put in quarantine for {self.quarantine_timeout}s")
# next we will wait twice as long
self.quarantine_timeout *= 2
# unless we hit the max timeout
self.quarantine_timeout = min(self.quarantine_timeout, self.quarantine_max_timeout)
def exitQuarantine(self):
log.msg(f"{self.name} has left quarantine")
self.quarantine_timer = None
self.botmaster.maybeStartBuildsForWorker(self.name)
def stopQuarantineTimer(self):
if self.quarantine_timer is not None:
self.quarantine_timer.cancel()
self.exitQuarantine()
class Worker(AbstractWorker):
@defer.inlineCallbacks
def detached(self):
yield super().detached()
self.botmaster.workerLost(self)
self.startMissingTimer()
@defer.inlineCallbacks
def attached(self, conn):
try:
yield super().attached(conn)
except Exception as e:
log.err(e, f"worker {self.name} cannot attach")
return
def buildFinished(self, wfb):
"""This is called when a build on this worker is finished."""
super().buildFinished(wfb)
# If we're gracefully shutting down, and we have no more active
# builders, then it's safe to disconnect
self.maybeShutdown()
| 27,832 | Python | .py | 625 | 35.2336 | 99 | 0.654184 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
4,902 | kubernetes.py | buildbot_buildbot/master/buildbot/worker/kubernetes.py | # This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright Buildbot Team Members
from twisted.internet import defer
from twisted.logger import Logger
from buildbot.interfaces import LatentWorkerFailedToSubstantiate
from buildbot.util import asyncSleep
from buildbot.util import httpclientservice
from buildbot.util import kubeclientservice
from buildbot.util.latent import CompatibleLatentWorkerMixin
from buildbot.worker.docker import DockerBaseWorker
log = Logger()
class KubeError(RuntimeError):
pass
class KubeJsonError(KubeError):
def __init__(self, code, response_json):
super().__init__(response_json['message'])
self.code = code
self.json = response_json
self.reason = response_json.get('reason')
class KubeTextError(KubeError):
def __init__(self, code, response):
super().__init__(response)
self.code = code
class KubeLatentWorker(CompatibleLatentWorkerMixin, DockerBaseWorker):
instance = None
_namespace = None
_kube = None
_kube_config = None
@defer.inlineCallbacks
def getPodSpec(self, build):
image = yield build.render(self.image)
env = yield self.createEnvironment(build)
return {
"apiVersion": "v1",
"kind": "Pod",
"metadata": {"name": self.getContainerName()},
"spec": {
"affinity": (yield self.get_affinity(build)),
"containers": [
{
"name": self.getContainerName(),
"image": image,
"env": [{"name": k, "value": v} for k, v in env.items()],
"resources": (yield self.getBuildContainerResources(build)),
"volumeMounts": (yield self.get_build_container_volume_mounts(build)),
}
]
+ (yield self.getServicesContainers(build)),
"nodeSelector": (yield self.get_node_selector(build)),
"restartPolicy": "Never",
"volumes": (yield self.get_volumes(build)),
},
}
def getBuildContainerResources(self, build):
# customization point to generate Build container resources
return {}
def get_build_container_volume_mounts(self, build):
return []
def get_affinity(self, build):
return {}
def get_node_selector(self, build):
return {}
def get_volumes(self, build):
return []
def getServicesContainers(self, build):
# customization point to create services containers around the build container
# those containers will run within the same localhost as the build container (aka within
# the same pod)
return []
def renderWorkerProps(self, build_props):
return self.getPodSpec(build_props)
def checkConfig(
self,
name,
image='buildbot/buildbot-worker',
namespace=None,
masterFQDN=None,
kube_config=None,
**kwargs,
):
super().checkConfig(name, None, **kwargs)
@defer.inlineCallbacks
def reconfigService(
self,
name,
image='buildbot/buildbot-worker',
namespace=None,
masterFQDN=None,
kube_config=None,
**kwargs,
):
# Set build_wait_timeout to 0 if not explicitly set: Starting a
# container is almost immediate, we can afford doing so for each build.
if 'build_wait_timeout' not in kwargs:
kwargs['build_wait_timeout'] = 0
if masterFQDN is None:
masterFQDN = self.get_ip
if callable(masterFQDN):
masterFQDN = masterFQDN()
self._http = yield httpclientservice.HTTPSession(
self.master.httpservice, kube_config.get_master_url()
)
if self.running and self._kube is not None:
yield self._kube.unregister(self)
self._kube = yield kubeclientservice.KubeClientService.getService(self.master)
self._kube_config = kube_config
if self.running:
yield self._kube.register(self, kube_config)
self._namespace = namespace or kube_config.getConfig()['namespace']
yield super().reconfigService(name, image=image, masterFQDN=masterFQDN, **kwargs)
@defer.inlineCallbacks
def startService(self):
yield super().startService()
yield self._kube.register(self, self._kube_config)
@defer.inlineCallbacks
def stopService(self):
yield self._kube.unregister(self)
yield super().stopService()
@defer.inlineCallbacks
def start_instance(self, build):
try:
yield self.stop_instance(reportFailure=False)
pod_spec = yield self.renderWorkerPropsOnStart(build)
yield self._create_pod(self._namespace, pod_spec)
except KubeError as e:
raise LatentWorkerFailedToSubstantiate(str(e)) from e
return True
@defer.inlineCallbacks
def stop_instance(self, fast=False, reportFailure=True):
self.current_pod_spec = None
self.resetWorkerPropsOnStop()
try:
yield self._delete_pod(self._namespace, self.getContainerName())
except KubeJsonError as e:
if reportFailure and e.reason != 'NotFound':
raise
if fast:
return
yield self._wait_for_pod_deletion(
self._namespace, self.getContainerName(), timeout=self.missing_timeout
)
@defer.inlineCallbacks
def _get_request_kwargs(self):
config = self._kube_config.getConfig()
kwargs = {}
if config.get("headers"):
kwargs.setdefault("headers", {}).update(config["headers"])
auth = yield self._kube_config.getAuthorization()
if auth is not None:
kwargs.setdefault("headers", {})['Authorization'] = auth
# warning: this only works with txrequests! not treq
for arg in ['cert', 'verify']:
if arg in config:
kwargs[arg] = config[arg]
return kwargs
@defer.inlineCallbacks
def _raise_decode_failure_error(self, res):
content = yield res.content()
msg = "Failed to decode: " + content.decode("utf-8", errors="ignore")[0:200]
raise KubeTextError(res.code, msg)
@defer.inlineCallbacks
def _create_pod(self, namespace, spec):
url = f'/api/v1/namespaces/{namespace}/pods'
res = yield self._http.post(url, json=spec, **(yield self._get_request_kwargs()))
try:
res_json = yield res.json()
except Exception:
yield self._raise_decode_failure_error(res)
if res.code not in (200, 201, 202):
raise KubeJsonError(res.code, res_json)
return res_json
@defer.inlineCallbacks
def _delete_pod(self, namespace, name, graceperiod=0):
url = f'/api/v1/namespaces/{namespace}/pods/{name}'
res = yield self._http.delete(
url, params={'graceperiod': graceperiod}, **(yield self._get_request_kwargs())
)
try:
res_json = yield res.json()
except Exception:
yield self._raise_decode_failure_error(res)
if res.code != 200:
raise KubeJsonError(res.code, res_json)
return res_json
@defer.inlineCallbacks
def _wait_for_pod_deletion(self, namespace, name, timeout):
t1 = self.master.reactor.seconds()
url = f'/api/v1/namespaces/{namespace}/pods/{name}/status'
while True:
if self.master.reactor.seconds() - t1 > timeout:
raise TimeoutError(f"Did not see pod {name} terminate after {timeout}s")
res = yield self._http.get(url, **(yield self._get_request_kwargs()))
try:
res_json = yield res.json()
except Exception:
yield self._raise_decode_failure_error(res)
if res.code == 404:
break # 404 means the pod has terminated
if res.code != 200:
raise KubeJsonError(res.code, res_json)
yield asyncSleep(1, reactor=self.master.reactor)
return res_json
| 8,862 | Python | .py | 214 | 32.242991 | 96 | 0.631395 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
4,903 | openstack.py | buildbot_buildbot/master/buildbot/worker/openstack.py | # This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Portions Copyright Buildbot Team Members
# Portions Copyright 2013 Cray Inc.
import hashlib
import math
import time
from twisted.internet import defer
from twisted.internet import threads
from twisted.python import log
from buildbot import config
from buildbot.interfaces import LatentWorkerFailedToSubstantiate
from buildbot.util import unicode2bytes
from buildbot.util.latent import CompatibleLatentWorkerMixin
from buildbot.worker import AbstractLatentWorker
try:
from keystoneauth1 import loading
from keystoneauth1 import session
from novaclient import client
from novaclient.exceptions import NotFound
_hush_pyflakes = [client]
except ImportError:
NotFound = Exception
client = None
loading = None
session = None
ACTIVE = 'ACTIVE'
BUILD = 'BUILD'
DELETED = 'DELETED'
UNKNOWN = 'UNKNOWN'
class OpenStackLatentWorker(CompatibleLatentWorkerMixin, AbstractLatentWorker):
instance = None
_poll_resolution = 5 # hook point for tests
def checkConfig(
self,
name,
password,
flavor,
os_username=None,
os_password=None,
os_tenant_name=None,
os_auth_url=None,
os_user_domain=None,
os_project_domain=None,
os_auth_args=None,
block_devices=None,
region=None,
image=None,
meta=None,
# Have a nova_args parameter to allow passing things directly
# to novaclient.
nova_args=None,
client_version='2',
**kwargs,
):
if not client:
config.error(
"The python module 'novaclient' is needed "
"to use a OpenStackLatentWorker. "
"Please install 'python-novaclient' package."
)
if not loading or not session:
config.error(
"The python module 'keystoneauth1' is needed "
"to use a OpenStackLatentWorker. "
"Please install the 'keystoneauth1' package."
)
if block_devices is None and image is None:
raise ValueError('One of block_devices or image must be given')
if os_auth_args is None:
if os_auth_url is None:
config.error(
"Missing os_auth_url OpenStackLatentWorker and os_auth_args not provided."
)
if os_username is None or os_password is None:
config.error(
"Missing os_username / os_password for OpenStackLatentWorker "
"and os_auth_args not provided."
)
else:
# ensure that at least auth_url is provided
if os_auth_args.get('auth_url') is None:
config.error("Missing 'auth_url' from os_auth_args for OpenStackLatentWorker")
super().checkConfig(name, password, **kwargs)
@defer.inlineCallbacks
def reconfigService(
self,
name,
password,
flavor,
os_username=None,
os_password=None,
os_tenant_name=None,
os_auth_url=None,
os_user_domain=None,
os_project_domain=None,
os_auth_args=None,
block_devices=None,
region=None,
image=None,
meta=None,
# Have a nova_args parameter to allow passing things directly
# to novaclient.
nova_args=None,
client_version='2',
**kwargs,
):
yield super().reconfigService(name, password, **kwargs)
if os_auth_args is None:
os_auth_args = {
'auth_url': os_auth_url,
'username': os_username,
'password': os_password,
}
if os_tenant_name is not None:
os_auth_args['project_name'] = os_tenant_name
if os_user_domain is not None:
os_auth_args['user_domain_name'] = os_user_domain
if os_project_domain is not None:
os_auth_args['project_domain_name'] = os_project_domain
self.flavor = flavor
self.client_version = client_version
if client:
os_auth_args = yield self.renderSecrets(os_auth_args)
self.novaclient = self._constructClient(client_version, os_auth_args)
if region is not None:
self.novaclient.client.region_name = region
if block_devices is not None:
self.block_devices = [self._parseBlockDevice(bd) for bd in block_devices]
else:
self.block_devices = None
self.image = image
self.meta = meta
self.nova_args = nova_args if nova_args is not None else {}
masterName = unicode2bytes(self.master.name)
self.masterhash = hashlib.sha1(masterName).hexdigest()[:6]
def _constructClient(self, client_version, auth_args):
"""Return a novaclient from the given args."""
auth_plugin = auth_args.pop('auth_type', 'password')
loader = loading.get_plugin_loader(auth_plugin)
auth = loader.load_from_options(**auth_args)
sess = session.Session(auth=auth)
return client.Client(client_version, session=sess)
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_type: image, snapshot, volume, or blank/None.
destination_type: Destination of block device: volume or local.
delete_on_termination: True/False.
uuid: The image, snapshot, or volume id.
boot_index: Integer used for boot order.
volume_size: Size of the device in GiB.
"""
client_block_device = {}
client_block_device['device_name'] = block_device.get('device_name', 'vda')
client_block_device['source_type'] = block_device.get('source_type', 'image')
client_block_device['destination_type'] = block_device.get('destination_type', 'volume')
client_block_device['delete_on_termination'] = bool(
block_device.get('delete_on_termination', True)
)
client_block_device['uuid'] = block_device['uuid']
client_block_device['boot_index'] = int(block_device.get('boot_index', 0))
# Allow None here. It will be rendered later.
client_block_device['volume_size'] = block_device.get('volume_size')
return client_block_device
@defer.inlineCallbacks
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 = rendered_block_device['uuid']
volume_size = self._determineVolumeSize(source_type, source_uuid)
rendered_block_device['volume_size'] = volume_size
return rendered_block_device
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 up to the next
# integer GiB.
image = nova.glance.get(source_uuid)
if hasattr(image, 'OS-EXT-IMG-SIZE:size'):
size = getattr(image, 'OS-EXT-IMG-SIZE:size')
size_gb = int(math.ceil(size / 1024.0**3))
return size_gb
elif source_type == 'volume':
# Volumes are easy because they are already in GiB.
volume = nova.volumes.get(source_uuid)
return volume.size
elif source_type == 'snapshot':
snap = nova.volume_snapshots.get(source_uuid)
return snap.size
else:
unknown_source = (
f"The source type '{source_type}' for UUID '{source_uuid}' is " "unknown"
)
raise ValueError(unknown_source)
return None
@defer.inlineCallbacks
def _getImage(self, build):
image_name = yield build.render(self.image)
# There is images in block devices
if image_name is None:
return None
# find_image() can find by id as well
try:
image = self.novaclient.glance.find_image(image_name)
except NotFound as e:
unknown_image = f"Cannot find OpenStack image {image_name}"
raise ValueError(unknown_image) from e
return image.id
@defer.inlineCallbacks
def _getFlavor(self, build):
flavor_uuid = yield build.render(self.flavor)
# check if we got name instead of uuid
for flavor in self.novaclient.flavors.list():
if flavor.name == flavor_uuid:
flavor_uuid = flavor.id
return flavor_uuid
@defer.inlineCallbacks
def renderWorkerProps(self, build):
image = yield self._getImage(build)
flavor = yield self._getFlavor(build)
nova_args = yield build.render(self.nova_args)
meta = yield build.render(self.meta)
worker_meta = {
'BUILDBOT:instance': self.masterhash,
}
if meta is None:
meta = worker_meta
else:
meta.update(worker_meta)
if self.block_devices is not None:
block_devices = []
for bd in self.block_devices:
rendered_block_device = yield self._renderBlockDevice(bd, build)
block_devices.append(rendered_block_device)
else:
block_devices = None
return (image, flavor, block_devices, nova_args, meta)
@defer.inlineCallbacks
def start_instance(self, build):
if self.instance is not None:
raise ValueError('instance active')
image, flavor, block_devices, nova_args, meta = yield self.renderWorkerPropsOnStart(build)
res = yield threads.deferToThread(
self._start_instance, image, flavor, block_devices, nova_args, meta
)
return res
def _start_instance(self, image_uuid, flavor_uuid, block_devices, nova_args, meta):
# ensure existing, potentially duplicated, workers are stopped
self._stop_instance(None, True)
# then try to start new one
boot_args = [self.workername, image_uuid, flavor_uuid]
boot_kwargs = {"meta": meta, "block_device_mapping_v2": block_devices, **nova_args}
instance = self.novaclient.servers.create(*boot_args, **boot_kwargs)
# There is an issue when using sessions that the status is not
# available on the first try. Trying again will work fine. Fetch the
# instance to avoid that.
try:
instance = self.novaclient.servers.get(instance.id)
except NotFound as e:
log.msg(
'{class_name} {name} instance {instance.id} ({instance.name}) never found',
class_name=self.__class__.__name__,
name=self.workername,
instance=instance,
)
raise LatentWorkerFailedToSubstantiate(instance.id, BUILD) from e
self.instance = instance
log.msg(
f'{self.__class__.__name__} {self.workername} starting instance {instance.id} '
f'(image {image_uuid})'
)
duration = 0
interval = self._poll_resolution
while instance.status.startswith(BUILD):
time.sleep(interval)
duration += interval
if duration % 60 == 0:
log.msg(
f'{self.__class__.__name__} {self.workername} has waited {duration // 60} '
f'minutes for instance {instance.id}'
)
try:
instance = self.novaclient.servers.get(instance.id)
except NotFound as e:
log.msg(
f'{self.__class__.__name__} {self.workername} instance {instance.id} '
f'({instance.name}) went missing'
)
raise LatentWorkerFailedToSubstantiate(instance.id, instance.status) from e
if instance.status == ACTIVE:
minutes = duration // 60
seconds = duration % 60
log.msg(
f'{self.__class__.__name__} {self.workername} instance {instance.id} '
f'({instance.name}) started in about {minutes} minutes {seconds} seconds'
)
return [
instance.id,
image_uuid,
f'{minutes // 60:02d}:{minutes % 60:02d}:{seconds:02d}',
]
else:
self.failed_to_start(instance.id, instance.status)
return None # This is just to silence warning, above line throws an exception
def stop_instance(self, fast=False):
instance = self.instance
self.instance = None
self.resetWorkerPropsOnStop()
self._stop_instance(instance, fast)
def _stop_instance(self, instance_param, fast):
instances = []
try:
if instance_param is None:
filter_f = (
lambda instance: instance.metadata.get("BUILDBOT:instance", "")
== self.masterhash
)
instances = list(filter(filter_f, self.novaclient.servers.findall(name=self.name)))
else:
instances = [self.novaclient.servers.get(instance_param.id)]
except NotFound:
# If can't find the instance, then it's already gone.
log.msg(
f'{self.__class__.__name__} {self.workername} instance {instance_param.id} '
f'({instance_param.name}) already terminated'
)
for instance in instances:
if instance.status not in (DELETED, UNKNOWN):
instance.delete()
log.msg(
f'{self.__class__.__name__} {self.workername} terminating instance '
f'{instance.id} ({instance.name})'
)
| 15,037 | Python | .py | 354 | 32.084746 | 99 | 0.606787 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
4,904 | latent.py | buildbot_buildbot/master/buildbot/worker/latent.py | # This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Portions Copyright Buildbot Team Members
# Portions Copyright Canonical Ltd. 2009
from __future__ import annotations
import enum
import random
import string
from typing import Any
from twisted.internet import defer
from twisted.internet.base import DelayedCall
from twisted.python import failure
from twisted.python import log
from zope.interface import implementer
from buildbot.interfaces import ILatentMachine
from buildbot.interfaces import ILatentWorker
from buildbot.interfaces import LatentWorkerFailedToSubstantiate
from buildbot.interfaces import LatentWorkerSubstantiatiationCancelled
from buildbot.util import Notifier
from buildbot.worker.base import AbstractWorker
class States(enum.Enum):
# Represents the states of AbstractLatentWorker
NOT_SUBSTANTIATED = 0
# When in this state, self._substantiation_notifier is waited on. The
# notifier is notified immediately after the state transition out of
# SUBSTANTIATING.
SUBSTANTIATING = 1
# This is the same as SUBSTANTIATING, the difference is that start_instance
# has been called
SUBSTANTIATING_STARTING = 2
SUBSTANTIATED = 3
# When in this state, self._start_stop_lock is held.
INSUBSTANTIATING = 4
# This state represents the case when insubstantiation is in progress and
# we also request substantiation at the same time. Substantiation will be
# started as soon as insubstantiation completes. Note, that the opposite
# actions are not supported: insubstantiation during substantiation will
# cancel the substantiation.
#
# When in this state, self._start_stop_lock is held.
#
# When in this state self.substantiation_build is not None.
INSUBSTANTIATING_SUBSTANTIATING = 5
# This state represents a worker that is shut down. Effectively, it's NOT_SUBSTANTIATED
# plus that we will abort if anyone tries to substantiate it.
SHUT_DOWN = 6
@implementer(ILatentWorker)
class AbstractLatentWorker(AbstractWorker):
"""A worker that will start up a worker instance when needed.
To use, subclass and implement start_instance and stop_instance.
Additionally, if the instances render any kind of data affecting instance
type from the build properties, set the class variable
builds_may_be_incompatible to True and override isCompatibleWithBuild
method.
See ec2.py for a concrete example.
"""
substantiation_build: Any = None
build_wait_timer: DelayedCall | None = None
start_missing_on_startup = False
# override if the latent worker may connect without substantiate. Most
# often this will be used in workers whose lifetime is managed by
# latent machines.
starts_without_substantiate = False
# Caveats: The handling of latent workers is much more complex than it
# might seem. The code must handle at least the following conditions:
#
# - non-silent disconnection by the worker at any time which generated
# TCP resets and in the end resulted in detached() being called
#
# - silent disconnection by worker at any time by silent TCP connection
# failure which did not generate TCP resets, but on the other hand no
# response may be received. self.conn is not None is that case.
#
# - no disconnection by worker during substantiation when
# build_wait_timeout param is negative.
#
# - worker attaching before start_instance returned.
#
# The above means that the following parts of the state must be tracked separately and can
# result in various state combinations:
# - connection state of the worker (self.conn)
# - intended state of the worker (self.state)
# - whether start_instance() has been called and has not yet finished.
state = States.NOT_SUBSTANTIATED
"""
state transitions:
substantiate(): either of
NOT_SUBSTANTIATED -> SUBSTANTIATING
INSUBSTANTIATING -> INSUBSTANTIATING_SUBSTANTIATING
_substantiate():
either of:
SUBSTANTIATING -> SUBSTANTIATING_STARTING
SUBSTANTIATING -> SUBSTANTIATING_STARTING -> SUBSTANTIATED
attached():
either of:
SUBSTANTIATING -> SUBSTANTIATED
SUBSTANTIATING_STARTING -> SUBSTANTIATED
then:
self.conn -> not None
detached():
self.conn -> None
errors in any of above will call insubstantiate()
insubstantiate():
either of:
SUBSTANTIATED -> INSUBSTANTIATING
INSUBSTANTIATING_SUBSTANTIATING -> INSUBSTANTIATING (cancels substantiation request)
SUBSTANTIATING -> INSUBSTANTIATING
SUBSTANTIATING -> INSUBSTANTIATING_SUBSTANTIATING
SUBSTANTIATING_STARTING -> INSUBSTANTIATING
SUBSTANTIATING_STARTING -> INSUBSTANTIATING_SUBSTANTIATING
then:
< other state transitions may happen during this time >
then either of:
INSUBSTANTIATING_SUBSTANTIATING -> SUBSTANTIATING
INSUBSTANTIATING -> NOT_SUBSTANTIATED
stopService():
NOT_SUBSTANTIATED -> SHUT_DOWN
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._substantiation_notifier = Notifier()
self._start_stop_lock = defer.DeferredLock()
self._check_instance_timer = None
def checkConfig(
self, name, password, build_wait_timeout=60 * 10, check_instance_interval=10, **kwargs
):
super().checkConfig(name, password, **kwargs)
def reconfigService(
self, name, password, build_wait_timeout=60 * 10, check_instance_interval=10, **kwargs
):
self.build_wait_timeout = build_wait_timeout
self.check_instance_interval = check_instance_interval
return super().reconfigService(name, password, **kwargs)
def _generate_random_password(self):
return ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(20))
def getRandomPass(self):
"""
Compute a random password. Latent workers are started by the master, so master can setup
the password too. Backends should prefer to use this API as it handles edge cases.
"""
# We should return an existing password if we're reconfiguring a substantiated worker.
# Otherwise the worker may be rejected if its password was changed during substantiation.
# To simplify, we only allow changing passwords for workers that aren't substantiated.
if self.state not in [States.NOT_SUBSTANTIATED, States.SHUT_DOWN]:
if self.password is not None:
return self.password
# pragma: no cover
log.err(
'{}: could not reuse password of substantiated worker (password == None)',
repr(self),
)
return self._generate_random_password()
@property
def building(self):
# A LatentWorkerForBuilder will only be busy if it is building.
return {wfb for wfb in self.workerforbuilders.values() if wfb.isBusy()}
def failed_to_start(self, instance_id, instance_state):
log.msg(
f'{self.__class__.__name__} {self.workername} failed to start instance '
f'{instance_id} ({instance_state})'
)
raise LatentWorkerFailedToSubstantiate(instance_id, instance_state)
def _log_start_stop_locked(self, action_str):
if self._start_stop_lock.locked:
log.msg(
(
'while {} worker {}: waiting until previous '
+ 'start_instance/stop_instance finishes'
).format(action_str, self)
)
def start_instance(self, build):
# responsible for starting instance that will try to connect with this
# master. Should return deferred with either True (instance started)
# or False (instance not started, so don't run a build here). Problems
# should use an errback.
raise NotImplementedError
def stop_instance(self, fast=False):
# responsible for shutting down instance.
raise NotImplementedError
def check_instance(self):
return (True, "")
@property
def substantiated(self):
return self.state == States.SUBSTANTIATED and self.conn is not None
def substantiate(self, wfb: Any, build: Any) -> defer.Deferred[Any]:
log.msg(f"substantiating worker {wfb}")
if self.state == States.SHUT_DOWN:
return defer.succeed(False)
if self.state == States.SUBSTANTIATED and self.conn is not None:
return defer.succeed(True)
if self.state in [
States.SUBSTANTIATING,
States.SUBSTANTIATING_STARTING,
States.INSUBSTANTIATING_SUBSTANTIATING,
]:
return self._substantiation_notifier.wait()
self.startMissingTimer()
# if anything of the following fails synchronously we need to have a
# deferred ready to be notified
d = self._substantiation_notifier.wait()
if self.state == States.SUBSTANTIATED and self.conn is None:
# connection dropped while we were substantiated.
# insubstantiate to clean up and then substantiate normally.
d_ins = self.insubstantiate(force_substantiation_build=build)
d_ins.addErrback(log.err, 'while insubstantiating')
return d
assert self.state in [States.NOT_SUBSTANTIATED, States.INSUBSTANTIATING]
if self.state == States.NOT_SUBSTANTIATED:
self.state = States.SUBSTANTIATING
self._substantiate(build)
else:
self.state = States.INSUBSTANTIATING_SUBSTANTIATING
self.substantiation_build = build
return d
@defer.inlineCallbacks
def _substantiate(self, build):
assert self.state == States.SUBSTANTIATING
try:
# if build_wait_timeout is negative we don't ever disconnect the
# worker ourselves, so we don't need to wait for it to attach
# to declare it as substantiated.
dont_wait_to_attach = self.build_wait_timeout < 0 and self.conn is not None
start_success = True
if ILatentMachine.providedBy(self.machine):
start_success = yield self.machine.substantiate(self)
try:
self._log_start_stop_locked('substantiating')
yield self._start_stop_lock.acquire()
if start_success:
self.state = States.SUBSTANTIATING_STARTING
start_success = yield self.start_instance(build)
finally:
self._start_stop_lock.release()
if not start_success:
# this behaviour is kept as compatibility, but it is better
# to just errback with a workable reason
msg = "Worker does not want to substantiate at this time"
raise LatentWorkerFailedToSubstantiate(self.name, msg)
if (
dont_wait_to_attach
and self.state == States.SUBSTANTIATING_STARTING
and self.conn is not None
):
log.msg(f"Worker {self.name} substantiated (already attached)")
self.state = States.SUBSTANTIATED
self._fireSubstantiationNotifier(True)
else:
self._start_check_instance_timer()
except Exception as e:
self.stopMissingTimer()
self._substantiation_failed(failure.Failure(e))
# swallow the failure as it is notified
def _fireSubstantiationNotifier(self, result):
if not self._substantiation_notifier:
log.msg(f"No substantiation deferred for {self.name}")
return
result_msg = 'success' if result is True else 'failure'
log.msg(f"Firing {self.name} substantiation deferred with {result_msg}")
self._substantiation_notifier.notify(result)
@defer.inlineCallbacks
def attached(self, conn):
self._stop_check_instance_timer()
if self.state != States.SUBSTANTIATING_STARTING and self.build_wait_timeout >= 0:
msg = (
f'Worker {self.name} received connection while not trying to substantiate.'
'Disconnecting.'
)
log.msg(msg)
self._deferwaiter.add(self._disconnect(conn))
raise RuntimeError(msg)
try:
yield super().attached(conn)
except Exception:
self._substantiation_failed(failure.Failure())
return
log.msg(f"Worker {self.name} substantiated \\o/")
# only change state when we are actually substantiating. We could
# end up at this point in different state than SUBSTANTIATING_STARTING
# if build_wait_timeout is negative. In that case, the worker is never
# shut down, but it may reconnect if the connection drops on its side
# without master seeing this condition.
#
# When build_wait_timeout is not negative, we throw an error (see above)
if self.state in [States.SUBSTANTIATING, States.SUBSTANTIATING_STARTING]:
self.state = States.SUBSTANTIATED
self._fireSubstantiationNotifier(True)
def attachBuilder(self, builder):
wfb = self.workerforbuilders.get(builder.name)
return wfb.attached(self, self.worker_commands)
def _missing_timer_fired(self):
self.missing_timer = None
return self._substantiation_failed(defer.TimeoutError())
def _substantiation_failed(self, failure):
if self.state in [States.SUBSTANTIATING, States.SUBSTANTIATING_STARTING]:
self._fireSubstantiationNotifier(failure)
d = self.insubstantiate()
d.addErrback(log.err, 'while insubstantiating')
self._deferwaiter.add(d)
# notify people, but only if we're still in the config
if not self.parent or not self.notify_on_missing:
return None
return self.master.data.updates.workerMissing(
workerid=self.workerid,
masterid=self.master.masterid,
last_connection="Latent worker never connected",
notify=self.notify_on_missing,
)
def canStartBuild(self):
# we were disconnected, but all the builds are not yet cleaned up.
if self.conn is None and self.building:
return False
return super().canStartBuild()
def buildStarted(self, wfb):
assert wfb.isBusy()
self._clearBuildWaitTimer()
if ILatentMachine.providedBy(self.machine):
self.machine.notifyBuildStarted()
def buildFinished(self, wfb):
assert not wfb.isBusy()
if not self.building:
if self.build_wait_timeout == 0:
# we insubstantiate asynchronously to trigger more bugs with
# the fake reactor
self.master.reactor.callLater(0, self._soft_disconnect)
# insubstantiate will automatically retry to create build for
# this worker
else:
self._setBuildWaitTimer()
# AbstractWorker.buildFinished() will try to start the next build for
# that worker
super().buildFinished(wfb)
if ILatentMachine.providedBy(self.machine):
self.machine.notifyBuildFinished()
def _clearBuildWaitTimer(self):
if self.build_wait_timer is not None:
if self.build_wait_timer.active():
self.build_wait_timer.cancel()
self.build_wait_timer = None
def _setBuildWaitTimer(self):
self._clearBuildWaitTimer()
if self.build_wait_timeout <= 0:
return
self.build_wait_timer = self.master.reactor.callLater(
self.build_wait_timeout, self._soft_disconnect
)
def _stop_check_instance_timer(self):
if self._check_instance_timer is not None:
if self._check_instance_timer.active():
self._check_instance_timer.cancel()
self._check_instance_timer = None
def _start_check_instance_timer(self):
self._stop_check_instance_timer()
self._check_instance_timer = self.master.reactor.callLater(
self.check_instance_interval, self._check_instance_timer_fired
)
def _check_instance_timer_fired(self):
self._deferwaiter.add(self._check_instance_timer_fired_impl())
@defer.inlineCallbacks
def _check_instance_timer_fired_impl(self):
self._check_instance_timer = None
if self.state != States.SUBSTANTIATING_STARTING:
# The only case when we want to recheck whether the instance has not failed is
# between call to start_instance() and successful attachment of the worker.
return
if self._start_stop_lock.locked: # pragma: no cover
# This can't actually happen, because we start the timer for instance checking after
# start_instance() completed and in insubstantiation the state is changed from
# SUBSTANTIATING_STARTING as soon as the lock is acquired.
return
try:
yield self._start_stop_lock.acquire()
message = "latent worker crashed before connecting"
try:
is_good, message_append = yield self.check_instance()
message += ": " + message_append
except Exception as e:
message += ": " + str(e)
is_good = False
if not is_good:
yield self._substantiation_failed(
LatentWorkerFailedToSubstantiate(self.name, message)
)
return
finally:
self._start_stop_lock.release()
# if check passes, schedule another one until worker connects
self._start_check_instance_timer()
@defer.inlineCallbacks
def insubstantiate(self, fast=False, force_substantiation_build=None):
# If force_substantiation_build is not None, we'll try to substantiate the given build
# after insubstantiation concludes. This parameter allows to go directly to the
# SUBSTANTIATING state without going through NOT_SUBSTANTIATED state.
log.msg(f"insubstantiating worker {self}")
if self.state == States.INSUBSTANTIATING_SUBSTANTIATING:
# there's another insubstantiation ongoing. We'll wait for it to finish by waiting
# on self._start_stop_lock
self.state = States.INSUBSTANTIATING
self.substantiation_build = None
self._fireSubstantiationNotifier(
failure.Failure(LatentWorkerSubstantiatiationCancelled())
)
try:
self._log_start_stop_locked('insubstantiating')
yield self._start_stop_lock.acquire()
assert self.state not in [
States.INSUBSTANTIATING,
States.INSUBSTANTIATING_SUBSTANTIATING,
]
if self.state in [States.NOT_SUBSTANTIATED, States.SHUT_DOWN]:
return
prev_state = self.state
if force_substantiation_build is not None:
self.state = States.INSUBSTANTIATING_SUBSTANTIATING
self.substantiation_build = force_substantiation_build
else:
self.state = States.INSUBSTANTIATING
if prev_state in [States.SUBSTANTIATING, States.SUBSTANTIATING_STARTING]:
self._fireSubstantiationNotifier(
failure.Failure(LatentWorkerSubstantiatiationCancelled())
)
self._clearBuildWaitTimer()
self._stop_check_instance_timer()
if prev_state in [States.SUBSTANTIATING_STARTING, States.SUBSTANTIATED]:
try:
yield self.stop_instance(fast)
except Exception as e:
# The case of failure for insubstantiation is bad as we have a
# left-over costing resource There is not much thing to do here
# generically, so we must put the problem of stop_instance
# reliability to the backend driver
log.err(e, "while insubstantiating")
assert self.state in [States.INSUBSTANTIATING, States.INSUBSTANTIATING_SUBSTANTIATING]
if self.state == States.INSUBSTANTIATING_SUBSTANTIATING:
build = self.substantiation_build
self.substantiation_build = None
self.state = States.SUBSTANTIATING
self._substantiate(build)
else: # self.state == States.INSUBSTANTIATING:
self.state = States.NOT_SUBSTANTIATED
finally:
self._start_stop_lock.release()
self.botmaster.maybeStartBuildsForWorker(self.name)
@defer.inlineCallbacks
def _soft_disconnect(self, fast=False, stopping_service=False):
# a negative build_wait_timeout means the worker should never be shut
# down, so just disconnect.
if not stopping_service and self.build_wait_timeout < 0:
yield super().disconnect()
return
self.stopMissingTimer()
# we add the Deferreds to DeferWaiter because we don't wait for a Deferred if
# the other Deferred errbacks
yield defer.DeferredList(
[
self._deferwaiter.add(super().disconnect()),
self._deferwaiter.add(self.insubstantiate(fast)),
],
consumeErrors=True,
fireOnOneErrback=True,
)
def disconnect(self):
self._deferwaiter.add(self._soft_disconnect())
# this removes the worker from all builders. It won't come back
# without a restart (or maybe a sighup)
self.botmaster.workerLost(self)
@defer.inlineCallbacks
def stopService(self):
# stops the service. Waits for any pending substantiations, insubstantiations or builds
# that are running or about to start to complete.
while self.state not in [States.NOT_SUBSTANTIATED, States.SHUT_DOWN]:
if self.state in [
States.INSUBSTANTIATING,
States.INSUBSTANTIATING_SUBSTANTIATING,
States.SUBSTANTIATING,
States.SUBSTANTIATING_STARTING,
]:
self._log_start_stop_locked('stopService')
yield self._start_stop_lock.acquire()
self._start_stop_lock.release()
if self.conn is not None or self.state in [
States.SUBSTANTIATED,
States.SUBSTANTIATING_STARTING,
]:
yield self._soft_disconnect(stopping_service=True)
yield self._deferwaiter.wait()
# prevent any race conditions with any future builds that are in the process of
# being started.
if self.state == States.NOT_SUBSTANTIATED:
self.state = States.SHUT_DOWN
self._clearBuildWaitTimer()
self._stop_check_instance_timer()
res = yield super().stopService()
return res
def updateWorker(self):
"""Called to add or remove builders after the worker has connected.
Also called after botmaster's builders are initially set.
@return: a Deferred that indicates when an attached worker has
accepted the new builders and/or released the old ones."""
for b in self.botmaster.getBuildersForWorker(self.name):
if b.name not in self.workerforbuilders:
b.addLatentWorker(self)
return super().updateWorker()
class LocalLatentWorker(AbstractLatentWorker):
"""
A worker that can be suspended by shutting down or suspending the hardware
it runs on. It is intended to be used with LatentMachines.
"""
starts_without_substantiate = True
def checkConfig(self, name, password, **kwargs):
super().checkConfig(self, name, password, build_wait_timeout=-1, **kwargs)
def reconfigService(self, name, password, **kwargs):
return super().reconfigService(name, password, build_wait_timeout=-1, **kwargs)
| 25,030 | Python | .py | 523 | 37.835564 | 98 | 0.657644 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
4,905 | docker.py | buildbot_buildbot/master/buildbot/worker/docker.py | # This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright Buildbot Team Members
import hashlib
import json
import socket
from io import BytesIO
from packaging.version import parse as parse_version
from twisted.internet import defer
from twisted.internet import threads
from twisted.python import log
from buildbot import config
from buildbot.interfaces import LatentWorkerCannotSubstantiate
from buildbot.interfaces import LatentWorkerFailedToSubstantiate
from buildbot.util import unicode2bytes
from buildbot.util.latent import CompatibleLatentWorkerMixin
from buildbot.worker import AbstractLatentWorker
try:
import docker
from docker.errors import NotFound
docker_py_version = parse_version(docker.__version__) # type: ignore[attr-defined]
except ImportError:
docker = None # type: ignore[assignment]
docker_py_version = parse_version("0.0")
def _handle_stream_line(line):
"""\
Input is the json representation of: {'stream': "Content\ncontent"}
Output is a generator yield "Content", and then "content"
"""
# XXX This necessary processing is probably a bug from docker-py,
# hence, might break if the bug is fixed, i.e. we should get decoded JSON
# directly from the API.
line = json.loads(line)
if 'error' in line:
content = "ERROR: " + line['error']
else:
content = line.get('stream', '')
for streamline in content.split('\n'):
if streamline:
yield streamline
class DockerBaseWorker(AbstractLatentWorker):
def checkConfig(self, name, password=None, image=None, masterFQDN=None, **kwargs):
# Set build_wait_timeout to 0 if not explicitly set: Starting a
# container is almost immediate, we can afford doing so for each build.
if 'build_wait_timeout' not in kwargs:
kwargs['build_wait_timeout'] = 0
if image is not None and not isinstance(image, str):
if not hasattr(image, 'getRenderingFor'):
config.error("image must be a string")
super().checkConfig(name, password, **kwargs)
def reconfigService(self, name, password=None, image=None, masterFQDN=None, **kwargs):
# Set build_wait_timeout to 0 if not explicitly set: Starting a
# container is almost immediate, we can afford doing so for each build.
if 'build_wait_timeout' not in kwargs:
kwargs['build_wait_timeout'] = 0
if password is None:
password = self.getRandomPass()
if masterFQDN is None:
masterFQDN = socket.getfqdn()
self.masterFQDN = masterFQDN
self.image = image
masterName = unicode2bytes(self.master.name)
self.masterhash = hashlib.sha1(masterName).hexdigest()[:6]
return super().reconfigService(name, password, **kwargs)
def getContainerName(self):
return (f'buildbot-{self.workername}-{self.masterhash}').replace("_", "-")
@property
def shortid(self):
if self.instance is None:
return None
return self.instance['Id'][:6]
def createEnvironment(self, build=None):
result = {
"BUILDMASTER": self.masterFQDN,
"WORKERNAME": self.name,
"WORKERPASS": self.password,
}
if self.registration is not None:
result["BUILDMASTER_PORT"] = str(self.registration.getPBPort())
if ":" in self.masterFQDN:
result["BUILDMASTER"], result["BUILDMASTER_PORT"] = self.masterFQDN.split(":")
return result
@staticmethod
def get_fqdn():
return socket.getfqdn()
@staticmethod
def get_ip():
fqdn = socket.getfqdn()
try:
return socket.gethostbyname(fqdn)
except socket.gaierror:
return fqdn
class DockerLatentWorker(CompatibleLatentWorkerMixin, DockerBaseWorker):
instance = None
def checkConfig(
self,
name,
password,
docker_host,
image=None,
command=None,
volumes=None,
dockerfile=None,
version=None,
tls=None,
followStartupLogs=False,
masterFQDN=None,
hostconfig=None,
autopull=False,
alwaysPull=False,
custom_context=False,
encoding='gzip',
buildargs=None,
hostname=None,
**kwargs,
):
super().checkConfig(name, password, image, masterFQDN, **kwargs)
if docker_py_version < parse_version("4.0.0"):
config.error("The python module 'docker>=4.0' is needed to use a DockerLatentWorker")
if not image and not dockerfile:
config.error(
"DockerLatentWorker: You need to specify at least an image name, or a dockerfile"
)
# Following block is only for checking config errors,
# actual parsing happens in self.parse_volumes()
# Renderables can be direct volumes definition or list member
if isinstance(volumes, list):
for volume_string in volumes or []:
if not isinstance(volume_string, str):
continue
try:
# Note that here we rely on tuple unpacking raising ValueError if the number
# of elements is wrong
_, __ = volume_string.split(":", 1)
except ValueError:
config.error(
"Invalid volume definition for docker " f"{volume_string}. Skipping..."
)
continue
@defer.inlineCallbacks
def reconfigService(
self,
name,
password,
docker_host,
image=None,
command=None,
volumes=None,
dockerfile=None,
version=None,
tls=None,
followStartupLogs=False,
masterFQDN=None,
hostconfig=None,
autopull=False,
alwaysPull=False,
custom_context=False,
encoding='gzip',
target="",
buildargs=None,
hostname=None,
**kwargs,
):
yield super().reconfigService(name, password, image, masterFQDN, **kwargs)
self.docker_host = docker_host
self.volumes = volumes or []
self.followStartupLogs = followStartupLogs
self.command = command or []
self.dockerfile = dockerfile
self.hostconfig = hostconfig or {}
self.autopull = autopull
self.alwaysPull = alwaysPull
self.custom_context = custom_context
self.encoding = encoding
self.target = target
self.buildargs = buildargs
# Prepare the parameters for the Docker Client object (except docker_host which is
# renderable and will be available only when starting containers).
self.client_args = {}
if version is not None:
self.client_args['version'] = version
if tls is not None:
self.client_args['tls'] = tls
self.hostname = hostname
def _thd_parse_volumes(self, volumes):
volume_list = []
for volume_string in volumes or []:
try:
_, volume = volume_string.split(":", 1)
except ValueError:
config.error(
"Invalid volume definition for docker " f"{volume_string}. Skipping..."
)
continue
if volume.endswith(':ro') or volume.endswith(':rw'):
volume = volume[:-3]
volume_list.append(volume)
return volume_list, volumes
def _getDockerClient(self, client_args):
return docker.APIClient(**client_args)
def renderWorkerProps(self, build):
return build.render((
self.docker_host,
self.image,
self.dockerfile,
self.volumes,
self.hostconfig,
self.custom_context,
self.encoding,
self.target,
self.buildargs,
self.hostname,
))
@defer.inlineCallbacks
def start_instance(self, build):
if self.instance is not None:
raise ValueError('instance active')
(
docker_host,
image,
dockerfile,
volumes,
hostconfig,
custom_context,
encoding,
target,
buildargs,
hostname,
) = yield self.renderWorkerPropsOnStart(build)
res = yield threads.deferToThread(
self._thd_start_instance,
docker_host,
image,
dockerfile,
volumes,
hostconfig,
custom_context,
encoding,
target,
buildargs,
hostname,
)
return res
def _image_exists(self, client, name):
# Make sure the image exists
for image in client.images():
for tag in image['RepoTags'] or []:
if ':' in name and tag == name:
return True
if tag.startswith(name + ':'):
return True
return False
def _thd_start_instance(
self,
docker_host,
image,
dockerfile,
volumes,
host_config,
custom_context,
encoding,
target,
buildargs,
hostname,
):
curr_client_args = self.client_args.copy()
curr_client_args['base_url'] = docker_host
docker_client = self._getDockerClient(curr_client_args)
container_name = self.getContainerName()
# cleanup the old instances
instances = docker_client.containers(all=1, filters={"name": container_name})
container_name = f"/{container_name}"
for instance in instances:
if container_name not in instance['Names']:
continue
try:
docker_client.remove_container(instance['Id'], v=True, force=True)
except NotFound:
pass # that's a race condition
found = False
if image is not None:
found = self._image_exists(docker_client, image)
else:
image = f'{self.workername}_{id(self)}_image'
if (not found) and (dockerfile is not None):
log.msg(f"Image '{image}' not found, building it from scratch")
if custom_context:
with open(dockerfile, 'rb') as fin:
lines = docker_client.build(
fileobj=fin,
custom_context=custom_context,
encoding=encoding,
tag=image,
pull=self.alwaysPull,
target=target,
buildargs=buildargs,
)
else:
lines = docker_client.build(
fileobj=BytesIO(dockerfile.encode('utf-8')),
tag=image,
pull=self.alwaysPull,
target=target,
)
for line in lines:
for streamline in _handle_stream_line(line):
log.msg(streamline)
imageExists = self._image_exists(docker_client, image)
if ((not imageExists) or self.alwaysPull) and self.autopull:
if not imageExists:
log.msg(f"Image '{image}' not found, pulling from registry")
docker_client.pull(image)
if not self._image_exists(docker_client, image):
msg = f'Image "{image}" not found on docker host.'
log.msg(msg)
docker_client.close()
raise LatentWorkerCannotSubstantiate(msg)
volumes, binds = self._thd_parse_volumes(volumes)
host_config['binds'] = binds
if 'init' not in host_config:
host_config['init'] = True
host_config = docker_client.create_host_config(**host_config)
instance = docker_client.create_container(
image,
self.command,
name=self.getContainerName(),
volumes=volumes,
environment=self.createEnvironment(),
host_config=host_config,
hostname=hostname,
)
if instance.get('Id') is None:
log.msg('Failed to create the container')
docker_client.close()
raise LatentWorkerFailedToSubstantiate('Failed to start container')
shortid = instance['Id'][:6]
log.msg(f'Container created, Id: {shortid}...')
instance['image'] = image
self.instance = instance
self._curr_client_args = curr_client_args
try:
docker_client.start(instance)
except docker.errors.APIError as e:
docker_client.close()
# The following was noticed in certain usage of Docker on Windows
if 'The container operating system does not match the host operating system' in str(e):
msg = f'Image used for build is wrong: {e!s}'
raise LatentWorkerCannotSubstantiate(msg) from e
raise
log.msg('Container started')
if self.followStartupLogs:
logs = docker_client.attach(container=instance, stdout=True, stderr=True, stream=True)
for line in logs:
log.msg(f"docker VM {shortid}: {line.strip()}")
if self.conn:
break
del logs
docker_client.close()
return [instance['Id'], image]
def check_instance(self):
if self.instance is None:
return defer.succeed((True, ""))
return threads.deferToThread(self._thd_check_instance, self._curr_client_args)
def _thd_check_instance(self, curr_client_args):
docker_client = self._getDockerClient(curr_client_args)
container_name = self.getContainerName()
instances = docker_client.containers(all=1, filters={"name": container_name})
container_name = f"/{container_name}"
for instance in instances:
if container_name not in instance["Names"]:
continue
if instance["State"] == "exited":
logs = docker_client.logs(instance['Id'], tail=100).decode("utf-8")
return (False, "logs: \n" + logs)
return (True, "")
def stop_instance(self, fast=False):
if self.instance is None:
# be gentle. Something may just be trying to alert us that an
# instance never attached, and it's because, somehow, we never
# started.
return defer.succeed(None)
instance = self.instance
self.instance = None
curr_client_args = self._curr_client_args
self._curr_client_args = None
self.resetWorkerPropsOnStop()
return threads.deferToThread(self._thd_stop_instance, instance, curr_client_args, fast)
def _thd_stop_instance(self, instance, curr_client_args, fast):
docker_client = self._getDockerClient(curr_client_args)
log.msg(f"Stopping container {instance['Id'][:6]}...")
docker_client.stop(instance['Id'])
if not fast:
docker_client.wait(instance['Id'])
docker_client.remove_container(instance['Id'], v=True, force=True)
if self.image is None:
try:
docker_client.remove_image(image=instance['image'])
except docker.errors.APIError as e:
log.msg('Error while removing the image: %s', e)
docker_client.close()
| 16,212 | Python | .py | 411 | 29.014599 | 99 | 0.599251 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
4,906 | ec2.py | buildbot_buildbot/master/buildbot/worker/ec2.py | # This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Portions Copyright Buildbot Team Members
# Portions Copyright Canonical Ltd. 2009
"""
A latent worker that uses EC2 to instantiate the workers on demand.
Tested with Python boto 1.5c
"""
import os
import re
import time
from twisted.internet import defer
from twisted.internet import threads
from twisted.python import log
from buildbot import config
from buildbot.interfaces import LatentWorkerFailedToSubstantiate
from buildbot.worker import AbstractLatentWorker
try:
import boto3
import botocore
from botocore.client import ClientError
except ImportError:
boto3 = None
PENDING = 'pending'
RUNNING = 'running'
SHUTTINGDOWN = 'shutting-down'
TERMINATED = 'terminated'
SPOT_REQUEST_PENDING_STATES = ['pending-evaluation', 'pending-fulfillment']
FULFILLED = 'fulfilled'
PRICE_TOO_LOW = 'price-too-low'
class EC2LatentWorker(AbstractLatentWorker):
instance = image = None
_poll_resolution = 5 # hook point for tests
def __init__(
self,
name,
password,
instance_type,
ami=None,
valid_ami_owners=None,
valid_ami_location_regex=None,
elastic_ip=None,
identifier=None,
secret_identifier=None,
aws_id_file_path=None,
user_data=None,
region=None,
keypair_name=None,
security_name=None,
spot_instance=False,
max_spot_price=1.6,
volumes=None,
placement=None,
price_multiplier=1.2,
tags=None,
product_description='Linux/UNIX',
subnet_id=None,
security_group_ids=None,
instance_profile_name=None,
block_device_map=None,
session=None,
**kwargs,
):
if not boto3:
config.error("The python module 'boto3' is needed to use a EC2LatentWorker")
if keypair_name is None:
config.error("EC2LatentWorker: 'keypair_name' parameter must be specified")
if security_name is None and not subnet_id:
config.error("EC2LatentWorker: 'security_name' parameter must be specified")
if volumes is None:
volumes = []
if tags is None:
tags = {}
super().__init__(name, password, **kwargs)
if security_name and subnet_id:
raise ValueError(
'security_name (EC2 classic security groups) is not supported '
'in a VPC. Use security_group_ids instead.'
)
if not (
(ami is not None)
^ (valid_ami_owners is not None or valid_ami_location_regex is not None)
):
raise ValueError(
'You must provide either a specific ami, or one or both of '
'valid_ami_location_regex and valid_ami_owners'
)
self.ami = ami
if valid_ami_owners is not None:
if isinstance(valid_ami_owners, int):
valid_ami_owners = (valid_ami_owners,)
else:
for element in valid_ami_owners:
if not isinstance(element, int):
raise ValueError(
'valid_ami_owners should be int or iterable of ints', element
)
if valid_ami_location_regex is not None:
if not isinstance(valid_ami_location_regex, str):
raise ValueError('valid_ami_location_regex should be a string')
# pre-compile the regex
valid_ami_location_regex = re.compile(valid_ami_location_regex)
if spot_instance and price_multiplier is None and max_spot_price is None:
raise ValueError(
'You must provide either one, or both, of price_multiplier or max_spot_price'
)
self.valid_ami_owners = None
if valid_ami_owners:
self.valid_ami_owners = [str(o) for o in valid_ami_owners]
self.valid_ami_location_regex = valid_ami_location_regex
self.instance_type = instance_type
self.keypair_name = keypair_name
self.security_name = security_name
self.user_data = user_data
self.spot_instance = spot_instance
self.max_spot_price = max_spot_price
self.volumes = volumes
self.price_multiplier = price_multiplier
self.product_description = product_description
if None not in [placement, region]:
self.placement = f'{region}{placement}'
else:
self.placement = None
if identifier is None:
assert (
secret_identifier is None
), 'supply both or neither of identifier, secret_identifier'
if aws_id_file_path is None:
home = os.environ['HOME']
default_path = os.path.join(home, '.ec2', 'aws_id')
if os.path.exists(default_path):
aws_id_file_path = default_path
if aws_id_file_path:
log.msg('WARNING: EC2LatentWorker is using deprecated aws_id file')
with open(aws_id_file_path, encoding='utf-8') as aws_file:
identifier = aws_file.readline().strip()
secret_identifier = aws_file.readline().strip()
else:
assert aws_id_file_path is None, (
'if you supply the identifier and secret_identifier, '
'do not specify the aws_id_file_path'
)
assert (
secret_identifier is not None
), 'supply both or neither of identifier, secret_identifier'
region_found = None
# Make the EC2 connection.
self.session = session
if self.session is None:
if region is not None:
for r in boto3.Session(
aws_access_key_id=identifier, aws_secret_access_key=secret_identifier
).get_available_regions('ec2'):
if r == region:
region_found = r
if region_found is not None:
self.session = boto3.Session(
region_name=region,
aws_access_key_id=identifier,
aws_secret_access_key=secret_identifier,
)
else:
raise ValueError('The specified region does not exist: ' + region)
else:
# boto2 defaulted to us-east-1 when region was unset, we
# mimic this here in boto3
region = botocore.session.get_session().get_config_variable('region')
if region is None:
region = 'us-east-1'
self.session = boto3.Session(
aws_access_key_id=identifier,
aws_secret_access_key=secret_identifier,
region_name=region,
)
self.ec2 = self.session.resource('ec2')
self.ec2_client = self.session.client('ec2')
# Make a keypair
#
# We currently discard the keypair data because we don't need it.
# If we do need it in the future, we will always recreate the keypairs
# because there is no way to
# programmatically retrieve the private key component, unless we
# generate it and store it on the filesystem, which is an unnecessary
# usage requirement.
try:
self.ec2.KeyPair(self.keypair_name).load()
# key_pair.delete() # would be used to recreate
except ClientError as e:
if 'InvalidKeyPair.NotFound' not in str(e):
if 'AuthFailure' in str(e):
log.msg(
'POSSIBLE CAUSES OF ERROR:\n'
' Did you supply your AWS credentials?\n'
' Did you sign up for EC2?\n'
' Did you put a credit card number in your AWS '
'account?\n'
'Please doublecheck before reporting a problem.\n'
)
raise
# make one; we would always do this, and stash the result, if we
# needed the key (for instance, to SSH to the box). We'd then
# use paramiko to use the key to connect.
self.ec2.create_key_pair(KeyName=keypair_name)
# create security group
if security_name:
try:
self.ec2_client.describe_security_groups(GroupNames=[security_name])
except ClientError as e:
if 'InvalidGroup.NotFound' in str(e):
self.security_group = self.ec2.create_security_group(
GroupName=security_name,
Description='Authorization to access the buildbot instance.',
)
# Authorize the master as necessary
# TODO this is where we'd open the hole to do the reverse pb
# connect to the buildbot
# ip = urllib.urlopen(
# 'http://checkip.amazonaws.com').read().strip()
# self.security_group.authorize('tcp', 22, 22, '{}/32'.format(ip))
# self.security_group.authorize('tcp', 80, 80, '{}/32'.format(ip))
else:
raise
# get the image
if self.ami is not None:
self.image = self.ec2.Image(self.ami)
else:
# verify we have access to at least one acceptable image
discard = self.get_image()
assert discard
# get the specified elastic IP, if any
if elastic_ip is not None:
# Using ec2.vpc_addresses.filter(PublicIps=[elastic_ip]) throws a
# NotImplementedError("Filtering not supported in describe_address.") in moto
# https://github.com/spulec/moto/blob/100ec4e7c8aa3fde87ff6981e2139768816992e4/moto/ec2/responses/elastic_ip_addresses.py#L52
addresses = self.ec2.meta.client.describe_addresses(PublicIps=[elastic_ip])['Addresses']
if not addresses:
raise ValueError('Could not find EIP for IP: ' + elastic_ip)
allocation_id = addresses[0]['AllocationId']
elastic_ip = self.ec2.VpcAddress(allocation_id)
self.elastic_ip = elastic_ip
self.subnet_id = subnet_id
self.security_group_ids = security_group_ids
self.classic_security_groups = [self.security_name] if self.security_name else None
self.instance_profile_name = instance_profile_name
self.tags = tags
self.block_device_map = (
self.create_block_device_mapping(block_device_map) if block_device_map else None
)
def create_block_device_mapping(self, mapping_definitions):
if not isinstance(mapping_definitions, list):
config.error("EC2LatentWorker: 'block_device_map' must be a list")
for mapping_definition in mapping_definitions:
ebs = mapping_definition.get('Ebs')
if ebs:
ebs.setdefault('DeleteOnTermination', True)
return mapping_definitions
def get_image(self):
# pylint: disable=too-many-nested-blocks
if self.image is not None:
return self.image
images = self.ec2.images.all()
if self.valid_ami_owners:
images = images.filter(Owners=self.valid_ami_owners)
if self.valid_ami_location_regex:
level = 0
options = []
get_match = self.valid_ami_location_regex.match
for image in images:
# Image must be available
if image.state != 'available':
continue
# Image must match regex
match = get_match(image.image_location)
if not match:
continue
# Gather sorting information
alpha_sort = int_sort = None
if level < 2:
try:
alpha_sort = match.group(1)
except IndexError:
level = 2
else:
if level == 0:
try:
int_sort = int(alpha_sort)
except ValueError:
level = 1
options.append([int_sort, alpha_sort, image.image_location, image.id, image])
if level:
log.msg(f'sorting images at level {level}')
options = [candidate[level:] for candidate in options]
else:
options = [(image.image_location, image.id, image) for image in images]
options.sort()
images = [f'{candidate[-1].id} ({candidate[-1].image_location})' for candidate in options]
log.msg(f"sorted images (last is chosen): {', '.join(images)}")
if not options:
raise ValueError('no available images match constraints')
return options[-1][-1]
def _dns(self):
if self.instance is None:
return None
return self.instance.public_dns_name
dns = property(_dns)
def start_instance(self, build):
if self.instance is not None:
raise ValueError('instance active')
if self.spot_instance:
return threads.deferToThread(self._request_spot_instance)
return threads.deferToThread(self._start_instance)
def _remove_none_opts(self, *args, **opts):
if args:
opts = args[0]
return dict((k, v) for k, v in opts.items() if v is not None)
def _start_instance(self):
image = self.get_image()
launch_opts = {
"ImageId": image.id,
"KeyName": self.keypair_name,
"SecurityGroups": self.classic_security_groups,
"InstanceType": self.instance_type,
"UserData": self.user_data,
"Placement": self._remove_none_opts(
AvailabilityZone=self.placement,
),
"MinCount": 1,
"MaxCount": 1,
"SubnetId": self.subnet_id,
"SecurityGroupIds": self.security_group_ids,
"IamInstanceProfile": self._remove_none_opts(
Name=self.instance_profile_name,
),
"BlockDeviceMappings": self.block_device_map,
}
launch_opts = self._remove_none_opts(launch_opts)
reservations = self.ec2.create_instances(**launch_opts)
self.instance = reservations[0]
instance_id, start_time = self._wait_for_instance()
if None not in [instance_id, image.id, start_time]:
return [instance_id, image.id, start_time]
else:
self.failed_to_start(self.instance.id, self.instance.state['Name'])
return None
def stop_instance(self, fast=False):
if self.instance is None:
# be gentle. Something may just be trying to alert us that an
# instance never attached, and it's because, somehow, we never
# started.
return defer.succeed(None)
instance = self.instance
self.output = self.instance = None
return threads.deferToThread(self._stop_instance, instance, fast)
def _attach_volumes(self):
for volume_id, device_node in self.volumes:
vol = self.ec2.Volume(volume_id)
vol.attach_to_instance(InstanceId=self.instance.id, Device=device_node)
log.msg(f'Attaching EBS volume {volume_id} to {device_node}.')
def _stop_instance(self, instance, fast):
if self.elastic_ip is not None:
self.elastic_ip.association.delete()
instance.reload()
if instance.state['Name'] not in (SHUTTINGDOWN, TERMINATED):
instance.terminate()
log.msg(
f'{self.__class__.__name__} {self.workername} terminating instance '
f'{instance.id}'
)
duration = 0
interval = self._poll_resolution
if fast:
goal = (SHUTTINGDOWN, TERMINATED)
instance.reload()
else:
goal = (TERMINATED,)
while instance.state['Name'] not in goal:
time.sleep(interval)
duration += interval
if duration % 60 == 0:
log.msg(
f'{self.__class__.__name__} {self.workername} has waited {duration // 60} '
f'minutes for instance {instance.id} to end'
)
instance.reload()
log.msg(
f'{self.__class__.__name__} {self.workername} instance {instance.id} {goal} after '
f'about {duration // 60} minutes {duration % 60} seconds'
)
def _bid_price_from_spot_price_history(self):
timestamp_yesterday = time.gmtime(int(time.time() - 86400))
spot_history_starttime = time.strftime('%Y-%m-%dT%H:%M:%SZ', timestamp_yesterday)
spot_prices = self.ec2.meta.client.describe_spot_price_history(
StartTime=spot_history_starttime,
ProductDescriptions=[self.product_description],
AvailabilityZone=self.placement,
)
price_sum = 0.0
price_count = 0
for price in spot_prices['SpotPriceHistory']:
if price['InstanceType'] == self.instance_type:
price_sum += float(price['SpotPrice'])
price_count += 1
if price_count == 0:
bid_price = 0.02
else:
bid_price = (price_sum / price_count) * self.price_multiplier
return bid_price
def _request_spot_instance(self):
if self.price_multiplier is None:
bid_price = self.max_spot_price
else:
bid_price = self._bid_price_from_spot_price_history()
if self.max_spot_price is not None and bid_price > self.max_spot_price:
bid_price = self.max_spot_price
log.msg(
f'{self.__class__.__name__} {self.workername} requesting spot instance with '
f'price {bid_price:0.4f}'
)
image = self.get_image()
reservations = self.ec2.meta.client.request_spot_instances(
SpotPrice=str(bid_price),
LaunchSpecification=self._remove_none_opts(
ImageId=self.ami,
KeyName=self.keypair_name,
SecurityGroups=self.classic_security_groups,
UserData=self.user_data,
InstanceType=self.instance_type,
Placement=self._remove_none_opts(
AvailabilityZone=self.placement,
),
SubnetId=self.subnet_id,
SecurityGroupIds=self.security_group_ids,
BlockDeviceMappings=self.block_device_map,
IamInstanceProfile=self._remove_none_opts(
Name=self.instance_profile_name,
),
),
)
request, success = self._thd_wait_for_request(reservations['SpotInstanceRequests'][0])
if not success:
raise LatentWorkerFailedToSubstantiate()
instance_id = request['InstanceId']
self.instance = self.ec2.Instance(instance_id)
instance_id, start_time = self._wait_for_instance()
return instance_id, image.id, start_time
def _wait_for_instance(self):
log.msg(
f'{self.__class__.__name__} {self.workername} waiting for instance '
f'{self.instance.id} to start'
)
duration = 0
interval = self._poll_resolution
while self.instance.state['Name'] == PENDING:
time.sleep(interval)
duration += interval
if duration % 60 == 0:
log.msg(
f'{self.__class__.__name__} {self.workername} has waited {duration // 60} '
f'minutes for instance {self.instance.id}'
)
self.instance.reload()
if self.instance.state['Name'] == RUNNING:
self.properties.setProperty("instance", self.instance.id, "Worker")
self.output = self.instance.console_output().get('Output')
minutes = duration // 60
seconds = duration % 60
log.msg(
f'{self.__class__.__name__} {self.workername} instance {self.instance.id} '
f'started on {self.dns} in about {minutes} minutes {seconds} seconds '
f'({self.output})'
)
if self.elastic_ip is not None:
self.elastic_ip.associate(InstanceId=self.instance.id)
start_time = f'{minutes // 60:02d}:{minutes % 60:02d}:{seconds:02d}'
if self.volumes:
self._attach_volumes()
if self.tags:
self.instance.create_tags(
Tags=[{"Key": k, "Value": v} for k, v in self.tags.items()]
)
return self.instance.id, start_time
else:
self.failed_to_start(self.instance.id, self.instance.state['Name'])
return None # This is just to silence warning, above line throws an exception
def _thd_wait_for_request(self, reservation):
duration = 0
interval = self._poll_resolution
while True:
# Sometimes it can take a second or so for the spot request to be
# ready. If it isn't ready, you will get a "Spot instance request
# ID 'sir-abcd1234' does not exist" exception.
try:
requests = self.ec2.meta.client.describe_spot_instance_requests(
SpotInstanceRequestIds=[reservation['SpotInstanceRequestId']]
)
except ClientError as e:
if 'InvalidSpotInstanceRequestID.NotFound' in str(e):
requests = None
else:
raise
if requests is not None:
request = requests['SpotInstanceRequests'][0]
request_status = request['Status']['Code']
if request_status not in SPOT_REQUEST_PENDING_STATES:
break
time.sleep(interval)
duration += interval
if duration % 10 == 0:
log.msg(
f"{self.__class__.__name__} {self.workername} has waited {duration} "
f"seconds for spot request {reservation['SpotInstanceRequestId']}"
)
if request_status == FULFILLED:
minutes = duration // 60
seconds = duration % 60
log.msg(
f"{self.__class__.__name__} {self.workername} spot request "
f"{request['SpotInstanceRequestId']} fulfilled in about {minutes} minutes "
f"{seconds} seconds"
)
return request, True
elif request_status == PRICE_TOO_LOW:
self.ec2.meta.client.cancel_spot_instance_requests(
SpotInstanceRequestIds=[request['SpotInstanceRequestId']]
)
log.msg(
f'{self.__class__.__name__} {self.workername} spot request rejected, spot '
'price too low'
)
raise LatentWorkerFailedToSubstantiate(request['SpotInstanceRequestId'], request_status)
else:
log.msg(
f"{self.__class__.__name__} {self.workername} failed to fulfill spot request "
f"{request['SpotInstanceRequestId']} with status {request_status}"
)
# try to cancel, just for good measure
self.ec2.meta.client.cancel_spot_instance_requests(
SpotInstanceRequestIds=[request['SpotInstanceRequestId']]
)
raise LatentWorkerFailedToSubstantiate(request['SpotInstanceRequestId'], request_status)
| 24,629 | Python | .py | 551 | 32.161525 | 137 | 0.574389 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
4,907 | msgpack.py | buildbot_buildbot/master/buildbot/worker/protocols/msgpack.py | # This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright Buildbot Team Members
import stat
from typing import Any
from twisted.internet import defer
from twisted.python import log
from twisted.python.reflect import namedModule
from buildbot.pbutil import decode
from buildbot.process import remotecommand
from buildbot.util import deferwaiter
from buildbot.util import path_expand_user
from buildbot.worker.protocols import base
class Listener(base.UpdateRegistrationListener):
name = "MsgPackListener"
def __init__(self, master):
super().__init__()
self.ConnectionClass = Connection
self.master = master
def get_manager(self):
return self.master.msgmanager
def before_connection_setup(self, protocol, workerName):
log.msg(f"worker '{workerName}' attaching")
class BasicRemoteCommand:
# only has basic functions needed for remoteSetBuilderList in class Connection
# when waiting for update messages
def __init__(self, worker_name, expected_keys, error_msg):
self.worker_name = worker_name
self.update_results = {}
self.expected_keys = expected_keys
self.error_msg = error_msg
self.d = defer.Deferred()
def wait_until_complete(self):
return self.d
def remote_update_msgpack(self, args):
# args is a list of tuples
# first element of the tuple is a key, second element is a value
for key, value in args:
if key not in self.update_results:
self.update_results[key] = value
def remote_complete(self, args):
if 'rc' not in self.update_results:
self.d.errback(
Exception(
f"Worker {self.worker_name} reconfiguration or connection to "
f"master failed. {self.error_msg}. 'rc' did not arrive."
)
)
return
if self.update_results['rc'] != 0:
self.d.errback(
Exception(
f"Worker {self.worker_name} reconfiguration or connection to "
f"master failed. {self.error_msg}. Error number: "
f"{self.update_results['rc']}"
)
)
return
for key in self.expected_keys:
if key not in self.update_results:
self.d.errback(
Exception(
f"Worker {self.worker_name} reconfiguration or connection "
f"to master failed. {self.error_msg} "
f"Key '{key}' is missing."
)
)
return
self.d.callback(None)
class Connection(base.Connection):
# TODO: configure keepalive_interval in
# c['protocols']['msgpack']['keepalive_interval']
keepalive_timer: None = None
keepalive_interval = 3600
info: Any = None
def __init__(self, master, worker, protocol):
super().__init__(worker.workername)
self.master = master
self.worker = worker
self.protocol = protocol
self._keepalive_waiter = deferwaiter.DeferWaiter()
self._keepalive_action_handler = deferwaiter.RepeatedActionHandler(
master.reactor, self._keepalive_waiter, self.keepalive_interval, self._do_keepalive
)
# methods called by the BuildbotWebSocketServerProtocol
@defer.inlineCallbacks
def attached(self, protocol):
self.startKeepaliveTimer()
self.notifyOnDisconnect(self._stop_keepalive_timer)
yield self.worker.attached(self)
def detached(self, protocol):
self.stopKeepaliveTimer()
self.protocol = None
self.notifyDisconnected()
# disconnection handling
@defer.inlineCallbacks
def _stop_keepalive_timer(self):
self.stopKeepaliveTimer()
yield self._keepalive_waiter.wait()
def loseConnection(self):
self.stopKeepaliveTimer()
self.protocol.transport.abortConnection()
# keepalive handling
def _do_keepalive(self):
return self.remoteKeepalive()
def stopKeepaliveTimer(self):
self._keepalive_action_handler.stop()
def startKeepaliveTimer(self):
assert self.keepalive_interval
self._keepalive_action_handler.start()
# methods to send messages to the worker
def remoteKeepalive(self):
return self.protocol.get_message_result({'op': 'keepalive'})
def remotePrint(self, message):
return self.protocol.get_message_result({'op': 'print', 'message': message})
@defer.inlineCallbacks
def remoteGetWorkerInfo(self):
info = yield self.protocol.get_message_result({'op': 'get_worker_info'})
self.info = decode(info)
worker_system = self.info.get("system", None)
if worker_system == "nt":
self.path_module = namedModule("ntpath")
self.path_expanduser = path_expand_user.nt_expanduser
else:
# most everything accepts / as separator, so posix should be a reasonable fallback
self.path_module = namedModule("posixpath")
self.path_expanduser = path_expand_user.posix_expanduser
return self.info
def _set_worker_settings(self):
# the lookahead here (`(?=.)`) ensures that `\r` doesn't match at the end
# of the buffer
# we also convert cursor control sequence to newlines
# and ugly \b+ (use of backspace to implement progress bar)
newline_re = r'(\r\n|\r(?=.)|\033\[u|\033\[[0-9]+;[0-9]+[Hf]|\033\[2J|\x08+)'
return self.protocol.get_message_result({
'op': 'set_worker_settings',
'args': {
'newline_re': newline_re,
'max_line_length': 4096,
'buffer_timeout': 5,
'buffer_size': 64 * 1024,
},
})
def create_remote_command(self, worker_name, expected_keys, error_msg):
command_id = remotecommand.RemoteCommand.generate_new_command_id()
command = BasicRemoteCommand(worker_name, expected_keys, error_msg)
self.protocol.command_id_to_command_map[command_id] = command
return (command, command_id)
@defer.inlineCallbacks
def remoteSetBuilderList(self, builders):
yield self._set_worker_settings()
basedir = self.info['basedir']
builder_names = [name for name, _ in builders]
self.builder_basedirs = {
name: self.path_module.join(basedir, builddir) for name, builddir in builders
}
wanted_dirs = {builddir for _, builddir in builders}
wanted_dirs.add('info')
dirs_to_mkdir = set(wanted_dirs)
command, command_id = self.create_remote_command(
self.worker.workername,
['files'],
'Worker could not send a list of builder directories.',
)
yield self.protocol.get_message_result({
'op': 'start_command',
'command_id': command_id,
'command_name': 'listdir',
'args': {'path': basedir},
})
# wait until command is over to get the update request message with args['files']
yield command.wait_until_complete()
files = command.update_results['files']
paths_to_rmdir = []
for dir in files:
dirs_to_mkdir.discard(dir)
if dir not in wanted_dirs:
if self.info['delete_leftover_dirs']:
# send 'stat' start_command and wait for status information which comes from
# worker in a response message. Status information is saved in update_results
# dictionary with key 'stat'. 'stat' value is a tuple of 10 elements, where
# first element is File mode. It goes to S_ISDIR(mode) to check if path is
# a directory so that files are not deleted
path = self.path_module.join(basedir, dir)
command, command_id = self.create_remote_command(
self.worker.workername,
['stat'],
"Worker could not send status " + "information about its files.",
)
yield self.protocol.get_message_result({
'op': 'start_command',
'command_id': command_id,
'command_name': 'stat',
'args': {'path': path},
})
yield command.wait_until_complete()
mode = command.update_results['stat'][0]
if stat.S_ISDIR(mode):
paths_to_rmdir.append(path)
if paths_to_rmdir:
log.msg(
f"Deleting directory '{paths_to_rmdir}' that is not being "
"used by the buildmaster."
)
# remove leftover directories from worker
command, command_id = self.create_remote_command(
self.worker.workername, [], "Worker could not remove directories."
)
yield self.protocol.get_message_result({
'op': 'start_command',
'command_id': command_id,
'command_name': 'rmdir',
'args': {'paths': paths_to_rmdir},
})
yield command.wait_until_complete()
paths_to_mkdir = [
self.path_module.join(basedir, dir) for dir in sorted(list(dirs_to_mkdir))
]
if paths_to_mkdir:
# make wanted builder directories which do not exist in worker yet
command, command_id = self.create_remote_command(
self.worker.workername, [], "Worker could not make directories."
)
yield self.protocol.get_message_result({
'op': 'start_command',
'command_id': command_id,
'command_name': 'mkdir',
'args': {'paths': paths_to_mkdir},
})
yield command.wait_until_complete()
self.builders = builder_names
return builder_names
@defer.inlineCallbacks
def remoteStartCommand(self, remoteCommand, builderName, commandId, commandName, args):
if commandName == "mkdir":
if isinstance(args['dir'], list):
args['paths'] = [
self.path_module.join(self.builder_basedirs[builderName], dir)
for dir in args['dir']
]
else:
args['paths'] = [
self.path_module.join(self.builder_basedirs[builderName], args['dir'])
]
del args['dir']
if commandName == "rmdir":
if isinstance(args['dir'], list):
args['paths'] = [
self.path_module.join(self.builder_basedirs[builderName], dir)
for dir in args['dir']
]
else:
args['paths'] = [
self.path_module.join(self.builder_basedirs[builderName], args['dir'])
]
del args['dir']
if commandName == "cpdir":
args['from_path'] = self.path_module.join(
self.builder_basedirs[builderName], args['fromdir']
)
args['to_path'] = self.path_module.join(
self.builder_basedirs[builderName], args['todir']
)
del args['fromdir']
del args['todir']
if commandName == "stat":
args['path'] = self.path_module.join(
self.builder_basedirs[builderName], args.get('workdir', ''), args['file']
)
del args['file']
if commandName == "glob":
args['path'] = self.path_module.join(self.builder_basedirs[builderName], args['path'])
if commandName == "listdir":
args['path'] = self.path_module.join(self.builder_basedirs[builderName], args['dir'])
del args['dir']
if commandName == "rmfile":
args['path'] = self.path_module.join(
self.builder_basedirs[builderName],
self.path_expanduser(args['path'], self.info['environ']),
)
if commandName == "shell":
args['workdir'] = self.path_module.join(
self.builder_basedirs[builderName], args['workdir']
)
if commandName == "uploadFile":
commandName = "upload_file"
args['path'] = self.path_module.join(
self.builder_basedirs[builderName],
args['workdir'],
self.path_expanduser(args['workersrc'], self.info['environ']),
)
if commandName == "uploadDirectory":
commandName = "upload_directory"
args['path'] = self.path_module.join(
self.builder_basedirs[builderName],
args['workdir'],
self.path_expanduser(args['workersrc'], self.info['environ']),
)
if commandName == "downloadFile":
commandName = "download_file"
args['path'] = self.path_module.join(
self.builder_basedirs[builderName],
args['workdir'],
self.path_expanduser(args['workerdest'], self.info['environ']),
)
if "want_stdout" in args:
if args["want_stdout"] == 1:
args["want_stdout"] = True
else:
args["want_stdout"] = False
if "want_stderr" in args:
if args["want_stderr"] == 1:
args["want_stderr"] = True
else:
args["want_stderr"] = False
self.protocol.command_id_to_command_map[commandId] = remoteCommand
if 'reader' in args:
self.protocol.command_id_to_reader_map[commandId] = args['reader']
del args['reader']
if 'writer' in args:
self.protocol.command_id_to_writer_map[commandId] = args['writer']
del args['writer']
yield self.protocol.get_message_result({
'op': 'start_command',
'builder_name': builderName,
'command_id': commandId,
'command_name': commandName,
'args': args,
})
@defer.inlineCallbacks
def remoteShutdown(self):
yield self.protocol.get_message_result({'op': 'shutdown'})
def remoteStartBuild(self, builderName):
pass
@defer.inlineCallbacks
def remoteInterruptCommand(self, builderName, commandId, why):
yield self.protocol.get_message_result({
'op': 'interrupt_command',
'builder_name': builderName,
'command_id': commandId,
'why': why,
})
# perspective methods called by the worker
def perspective_keepalive(self):
self.worker.messageReceivedFromWorker()
def perspective_shutdown(self):
self.worker.messageReceivedFromWorker()
self.worker.shutdownRequested()
def get_peer(self):
p = self.protocol.transport.getPeer()
return f"{p.host}:{p.port}"
| 15,854 | Python | .py | 362 | 32.248619 | 98 | 0.584273 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
4,908 | pb.py | buildbot_buildbot/master/buildbot/worker/protocols/pb.py | # This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright Buildbot Team Members
import contextlib
from typing import Any
from twisted.internet import defer
from twisted.python import log
from twisted.spread import pb
from buildbot.pbutil import decode
from buildbot.util import deferwaiter
from buildbot.worker.protocols import base
class Listener(base.UpdateRegistrationListener):
name = "pbListener"
def __init__(self, master):
super().__init__()
self.ConnectionClass = Connection
self.master = master
def get_manager(self):
return self.master.pbmanager
def before_connection_setup(self, mind, workerName):
log.msg(f"worker '{workerName}' attaching from {mind.broker.transport.getPeer()}")
try:
mind.broker.transport.setTcpKeepAlive(1)
except Exception:
log.err("Can't set TcpKeepAlive")
class ReferenceableProxy(pb.Referenceable):
def __init__(self, impl):
assert isinstance(impl, self.ImplClass)
self.impl = impl
def __getattr__(self, name):
return getattr(self.impl, name)
# Proxy are just ReferenceableProxy to the Impl classes
class RemoteCommand(ReferenceableProxy):
ImplClass = base.RemoteCommandImpl
class FileReaderProxy(ReferenceableProxy):
ImplClass = base.FileReaderImpl
class FileWriterProxy(ReferenceableProxy):
ImplClass = base.FileWriterImpl
class _NoSuchMethod(Exception):
"""Rewrapped pb.NoSuchMethod remote exception"""
@contextlib.contextmanager
def _wrapRemoteException():
try:
yield
except pb.RemoteError as e:
if e.remoteType in (
b'twisted.spread.flavors.NoSuchMethod',
'twisted.spread.flavors.NoSuchMethod',
):
raise _NoSuchMethod(e) from e
raise
class Connection(base.Connection, pb.Avatar):
proxies = {base.FileWriterImpl: FileWriterProxy, base.FileReaderImpl: FileReaderProxy}
# TODO: configure keepalive_interval in
# c['protocols']['pb']['keepalive_interval']
keepalive_timer: None = None
keepalive_interval = 3600
info: Any = None
def __init__(self, master, worker, mind):
super().__init__(worker.workername)
self.master = master
self.worker = worker
self.mind = mind
self._keepalive_waiter = deferwaiter.DeferWaiter()
self._keepalive_action_handler = deferwaiter.RepeatedActionHandler(
master.reactor, self._keepalive_waiter, self.keepalive_interval, self._do_keepalive
)
# methods called by the PBManager
@defer.inlineCallbacks
def attached(self, mind):
self.startKeepaliveTimer()
self.notifyOnDisconnect(self._stop_keepalive_timer)
# pbmanager calls perspective.attached; pass this along to the
# worker
yield self.worker.attached(self)
# and then return a reference to the avatar
return self
def detached(self, mind):
self.stopKeepaliveTimer()
self.mind = None
self.notifyDisconnected()
# disconnection handling
@defer.inlineCallbacks
def _stop_keepalive_timer(self):
self.stopKeepaliveTimer()
yield self._keepalive_waiter.wait()
def loseConnection(self):
self.stopKeepaliveTimer()
tport = self.mind.broker.transport
# this is the polite way to request that a socket be closed
tport.loseConnection()
try:
# but really we don't want to wait for the transmit queue to
# drain. The remote end is unlikely to ACK the data, so we'd
# probably have to wait for a (20-minute) TCP timeout.
# tport._closeSocket()
# however, doing _closeSocket (whether before or after
# loseConnection) somehow prevents the notifyOnDisconnect
# handlers from being run. Bummer.
tport.offset = 0
tport.dataBuffer = b""
except Exception:
# however, these hacks are pretty internal, so don't blow up if
# they fail or are unavailable
log.msg("failed to accelerate the shutdown process")
# keepalive handling
def _do_keepalive(self):
return self.mind.callRemote('print', message="keepalive")
def stopKeepaliveTimer(self):
self._keepalive_action_handler.stop()
def startKeepaliveTimer(self):
assert self.keepalive_interval
self._keepalive_action_handler.start()
# methods to send messages to the worker
def remotePrint(self, message):
return self.mind.callRemote('print', message=message)
@defer.inlineCallbacks
def remoteGetWorkerInfo(self):
try:
with _wrapRemoteException():
# Try to call buildbot-worker method.
info = yield self.mind.callRemote('getWorkerInfo')
return decode(info)
except _NoSuchMethod:
yield self.remotePrint(
"buildbot-slave detected, failing back to deprecated buildslave API. "
"(Ignoring missing getWorkerInfo method.)"
)
info = {}
# Probably this is deprecated buildslave.
log.msg(
"Worker.getWorkerInfo is unavailable - falling back to deprecated buildslave API"
)
try:
with _wrapRemoteException():
info = yield self.mind.callRemote('getSlaveInfo')
except _NoSuchMethod:
log.msg("Worker.getSlaveInfo is unavailable - ignoring")
# newer workers send all info in one command
if "slave_commands" in info:
assert "worker_commands" not in info
info["worker_commands"] = info.pop("slave_commands")
return info
# Old version buildslave - need to retrieve list of supported
# commands and version using separate requests.
try:
with _wrapRemoteException():
info["worker_commands"] = yield self.mind.callRemote('getCommands')
except _NoSuchMethod:
log.msg("Worker.getCommands is unavailable - ignoring")
try:
with _wrapRemoteException():
info["version"] = yield self.mind.callRemote('getVersion')
except _NoSuchMethod:
log.msg("Worker.getVersion is unavailable - ignoring")
return decode(info)
@defer.inlineCallbacks
def remoteSetBuilderList(self, builders):
builders = yield self.mind.callRemote('setBuilderList', builders)
self.builders = builders
return builders
def remoteStartCommand(self, remoteCommand, builderName, commandId, commandName, args):
workerforbuilder = self.builders.get(builderName)
remoteCommand = RemoteCommand(remoteCommand)
args = self.createArgsProxies(args)
return workerforbuilder.callRemote(
'startCommand', remoteCommand, commandId, commandName, args
)
@defer.inlineCallbacks
def remoteShutdown(self):
# First, try the "new" way - calling our own remote's shutdown
# method. The method was only added in 0.8.3, so ignore NoSuchMethod
# failures.
@defer.inlineCallbacks
def new_way():
try:
with _wrapRemoteException():
yield self.mind.callRemote('shutdown')
# successful shutdown request
return True
except _NoSuchMethod:
# fall through to the old way
return False
except pb.PBConnectionLost:
# the worker is gone, so call it finished
return True
if (yield new_way()):
return # done!
# Now, the old way. Look for a builder with a remote reference to the
# client side worker. If we can find one, then call "shutdown" on the
# remote builder, which will cause the worker buildbot process to exit.
def old_way():
d = None
for b in self.worker.workerforbuilders.values():
if b.remote:
d = b.mind.callRemote("shutdown")
break
if d:
name = self.worker.workername
log.msg(f"Shutting down (old) worker: {name}")
# The remote shutdown call will not complete successfully since
# the buildbot process exits almost immediately after getting
# the shutdown request.
# Here we look at the reason why the remote call failed, and if
# it's because the connection was lost, that means the worker
# shutdown as expected.
@d.addErrback
def _errback(why):
if why.check(pb.PBConnectionLost):
log.msg(f"Lost connection to {name}")
else:
log.err(f"Unexpected error when trying to shutdown {name}")
return d
log.err("Couldn't find remote builder to shut down worker")
return defer.succeed(None)
yield old_way()
def remoteStartBuild(self, builderName):
workerforbuilder = self.builders.get(builderName)
return workerforbuilder.callRemote('startBuild')
def remoteInterruptCommand(self, builderName, commandId, why):
workerforbuilder = self.builders.get(builderName)
return defer.maybeDeferred(workerforbuilder.callRemote, "interruptCommand", commandId, why)
# perspective methods called by the worker
def perspective_keepalive(self):
self.worker.messageReceivedFromWorker()
def perspective_shutdown(self):
self.worker.messageReceivedFromWorker()
self.worker.shutdownRequested()
def get_peer(self):
p = self.mind.broker.transport.getPeer()
return f"{p.host}:{p.port}"
| 10,665 | Python | .py | 242 | 34.219008 | 99 | 0.647274 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
4,909 | null.py | buildbot_buildbot/master/buildbot/worker/protocols/null.py | # This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright Buildbot Team Members
from twisted.internet import defer
from twisted.python import log
from buildbot.util.eventual import fireEventually
from buildbot.warnings import warn_deprecated
from buildbot.worker.protocols import base
class Listener(base.Listener):
pass
class ProxyMixin:
def __init__(self, impl):
assert isinstance(impl, self.ImplClass)
self.impl = impl
self._disconnect_listeners = []
def callRemote(self, message, *args, **kw):
method = getattr(self.impl, f"remote_{message}", None)
if method is None:
raise AttributeError(f"No such method: remote_{message}")
try:
state = method(*args, **kw)
except TypeError:
log.msg(f"{method} didn't accept {args} and {kw}")
raise
# break callback recursion for large transfers by using fireEventually
return fireEventually(state)
def notifyOnDisconnect(self, cb):
pass
def dontNotifyOnDisconnect(self, cb):
pass
# just add ProxyMixin capability to the RemoteCommandProxy
# so that callers of callRemote actually directly call the proper method
class RemoteCommandProxy(ProxyMixin):
ImplClass = base.RemoteCommandImpl
class FileReaderProxy(ProxyMixin):
ImplClass = base.FileReaderImpl
class FileWriterProxy(ProxyMixin):
ImplClass = base.FileWriterImpl
class Connection(base.Connection):
proxies = {base.FileWriterImpl: FileWriterProxy, base.FileReaderImpl: FileReaderProxy}
def __init__(self, master_or_worker, worker=None):
# All the existing code passes just the name to the Connection, however we'll need to
# support an older versions of buildbot-worker using two parameter signature for some time.
if worker is None:
worker = master_or_worker
else:
warn_deprecated(
'3.2.0',
'LocalWorker: Using different version of buildbot-worker '
+ 'than buildbot is not supported',
)
super().__init__(worker.workername)
self.worker = worker
def loseConnection(self):
self.notifyDisconnected()
def remotePrint(self, message):
return defer.maybeDeferred(self.worker.bot.remote_print, message)
def remoteGetWorkerInfo(self):
return defer.maybeDeferred(self.worker.bot.remote_getWorkerInfo)
def remoteSetBuilderList(self, builders):
return defer.maybeDeferred(self.worker.bot.remote_setBuilderList, builders)
def remoteStartCommand(self, remoteCommand, builderName, commandId, commandName, args):
remoteCommand = RemoteCommandProxy(remoteCommand)
args = self.createArgsProxies(args)
workerforbuilder = self.worker.bot.builders[builderName]
return defer.maybeDeferred(
workerforbuilder.remote_startCommand, remoteCommand, commandId, commandName, args
)
def remoteShutdown(self):
return defer.maybeDeferred(self.worker.stopService)
def remoteStartBuild(self, builderName):
return defer.succeed(self.worker.bot.builders[builderName].remote_startBuild())
def remoteInterruptCommand(self, builderName, commandId, why):
workerforbuilder = self.worker.bot.builders[builderName]
return defer.maybeDeferred(workerforbuilder.remote_interruptCommand, commandId, why)
def get_peer(self):
return "local"
| 4,109 | Python | .py | 88 | 40.045455 | 99 | 0.725451 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
4,910 | base.py | buildbot_buildbot/master/buildbot/worker/protocols/base.py | # This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright Buildbot Team Members
from __future__ import annotations
from twisted.internet import defer
from buildbot.util import ComparableMixin
from buildbot.util import subscription
from buildbot.util.eventual import eventually
class Listener:
pass
class UpdateRegistrationListener(Listener):
def __init__(self):
super().__init__()
# username : (password, portstr, manager registration)
self._registrations = {}
@defer.inlineCallbacks
def updateRegistration(self, username, password, portStr):
# NOTE: this method is only present on the PB and MsgPack protocols; others do not
# use registrations
if username in self._registrations:
currentPassword, currentPortStr, currentReg = self._registrations[username]
else:
currentPassword, currentPortStr, currentReg = None, None, None
iseq = ComparableMixin.isEquivalent(
currentPassword, password
) and ComparableMixin.isEquivalent(currentPortStr, portStr)
if iseq:
return currentReg
if currentReg:
yield currentReg.unregister()
del self._registrations[username]
if portStr is not None and password:
reg = yield self.get_manager().register(
portStr, username, password, self._create_connection
)
self._registrations[username] = (password, portStr, reg)
return reg
return currentReg
@defer.inlineCallbacks
def _create_connection(self, mind, workerName):
self.before_connection_setup(mind, workerName)
worker = self.master.workers.getWorkerByName(workerName)
conn = self.ConnectionClass(self.master, worker, mind)
# inform the manager, logging any problems in the deferred
accepted = yield self.master.workers.newConnection(conn, workerName)
# return the Connection as the perspective
if accepted:
return conn
else:
# TODO: return something more useful
raise RuntimeError("rejecting duplicate worker")
class Connection:
proxies: dict[type, type] = {}
def __init__(self, name):
self._disconnectSubs = subscription.SubscriptionPoint(f"disconnections from {name}")
# This method replace all Impl args by their Proxy protocol implementation
def createArgsProxies(self, args):
newargs = {}
for k, v in args.items():
for implclass, proxyclass in self.proxies.items():
if isinstance(v, implclass):
v = proxyclass(v)
newargs[k] = v
return newargs
def get_peer(self):
raise NotImplementedError
# disconnection handling
def wait_shutdown_started(self):
d = defer.Deferred()
self.notifyOnDisconnect(lambda: eventually(d.callback, None))
return d
def waitShutdown(self):
return self._disconnectSubs.waitForDeliveriesToFinish()
def notifyOnDisconnect(self, cb):
return self._disconnectSubs.subscribe(cb)
def notifyDisconnected(self):
self._disconnectSubs.deliver()
def loseConnection(self):
raise NotImplementedError
# methods to send messages to the worker
def remotePrint(self, message):
raise NotImplementedError
def remoteGetWorkerInfo(self):
raise NotImplementedError
def remoteSetBuilderList(self, builders):
raise NotImplementedError
def remoteStartCommand(self, remoteCommand, builderName, commandId, commandName, args):
raise NotImplementedError
def remoteShutdown(self):
raise NotImplementedError
def remoteStartBuild(self, builderName):
raise NotImplementedError
def remoteInterruptCommand(self, builderName, commandId, why):
raise NotImplementedError
# RemoteCommand base implementation and base proxy
class RemoteCommandImpl:
def remote_update(self, updates):
raise NotImplementedError
def remote_complete(self, failure=None):
raise NotImplementedError
# FileWriter base implementation
class FileWriterImpl:
def remote_write(self, data):
raise NotImplementedError
def remote_utime(self, accessed_modified):
raise NotImplementedError
def remote_unpack(self):
raise NotImplementedError
def remote_close(self):
raise NotImplementedError
# FileReader base implementation
class FileReaderImpl:
def remote_read(self, maxLength):
raise NotImplementedError
def remote_close(self):
raise NotImplementedError
| 5,305 | Python | .py | 127 | 34.551181 | 92 | 0.71028 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
4,911 | msgpack.py | buildbot_buildbot/master/buildbot/worker/protocols/manager/msgpack.py | # This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright Buildbot Team Members
import base64
import msgpack
from autobahn.twisted.websocket import WebSocketServerFactory
from autobahn.twisted.websocket import WebSocketServerProtocol
from autobahn.websocket.types import ConnectionDeny
from twisted.internet import defer
from twisted.python import log
from buildbot.util import deferwaiter
from buildbot.util.eventual import eventually
from buildbot.worker.protocols.manager.base import BaseDispatcher
from buildbot.worker.protocols.manager.base import BaseManager
class ConnectioLostError(Exception):
pass
class RemoteWorkerError(Exception):
pass
def decode_http_authorization_header(value):
if value[:5] != 'Basic':
raise ValueError("Value should always start with 'Basic'")
credentials_str = base64.b64decode(value[6:]).decode()
if ':' not in credentials_str:
raise ValueError("String of credentials should always have a colon.")
username, password = credentials_str.split(':', maxsplit=1)
return (username, password)
def encode_http_authorization_header(name, password):
if b":" in name:
raise ValueError("Username is not allowed to contain a colon.")
userpass = name + b':' + password
return 'Basic ' + base64.b64encode(userpass).decode()
class BuildbotWebSocketServerProtocol(WebSocketServerProtocol):
debug = True
def __init__(self):
super().__init__()
self.seq_num_to_waiters_map = {}
self.connection = None
self.worker_name = None
self._deferwaiter = deferwaiter.DeferWaiter()
def get_dispatcher(self):
# This is an instance of class msgpack.Dispatcher set in Dispatcher.__init__().
# self.factory is set on the protocol instance when creating it in Twisted internals
return self.factory.buildbot_dispatcher
@defer.inlineCallbacks
def onOpen(self):
if self.debug:
log.msg("WebSocket connection open.")
self.seq_number = 0
self.command_id_to_command_map = {}
self.command_id_to_reader_map = {}
self.command_id_to_writer_map = {}
yield self.initialize()
def maybe_log_worker_to_master_msg(self, message):
if self.debug:
log.msg("WORKER -> MASTER message: ", message)
def maybe_log_master_to_worker_msg(self, message):
if self.debug:
log.msg("MASTER -> WORKER message: ", message)
def contains_msg_key(self, msg, keys):
for k in keys:
if k not in msg:
raise KeyError(f'message did not contain obligatory "{k}" key')
@defer.inlineCallbacks
def initialize(self):
try:
dispatcher = self.get_dispatcher()
yield dispatcher.master.initLock.acquire()
if self.worker_name in dispatcher.users:
_, afactory = dispatcher.users[self.worker_name]
self.connection = yield afactory(self, self.worker_name)
yield self.connection.attached(self)
else:
self.sendClose()
except Exception as e:
log.msg(f"Connection opening failed: {e}")
self.sendClose()
finally:
eventually(dispatcher.master.initLock.release)
@defer.inlineCallbacks
def call_update(self, msg):
result = None
is_exception = False
try:
self.contains_msg_key(msg, ('command_id', 'args'))
if msg['command_id'] not in self.command_id_to_command_map:
raise KeyError('unknown "command_id"')
command = self.command_id_to_command_map[msg['command_id']]
yield command.remote_update_msgpack(msg['args'])
except Exception as e:
is_exception = True
result = str(e)
self.send_response_msg(msg, result, is_exception)
@defer.inlineCallbacks
def call_complete(self, msg):
result = None
is_exception = False
try:
self.contains_msg_key(msg, ('command_id', 'args'))
if msg['command_id'] not in self.command_id_to_command_map:
raise KeyError('unknown "command_id"')
command = self.command_id_to_command_map[msg['command_id']]
yield command.remote_complete(msg['args'])
if msg['command_id'] in self.command_id_to_command_map:
del self.command_id_to_command_map[msg['command_id']]
if msg['command_id'] in self.command_id_to_reader_map:
del self.command_id_to_reader_map[msg['command_id']]
if msg['command_id'] in self.command_id_to_writer_map:
del self.command_id_to_writer_map[msg['command_id']]
except Exception as e:
is_exception = True
result = str(e)
self.send_response_msg(msg, result, is_exception)
@defer.inlineCallbacks
def call_update_upload_file_write(self, msg):
result = None
is_exception = False
try:
self.contains_msg_key(msg, ('command_id', 'args'))
if msg['command_id'] not in self.command_id_to_writer_map:
raise KeyError('unknown "command_id"')
file_writer = self.command_id_to_writer_map[msg['command_id']]
yield file_writer.remote_write(msg['args'])
except Exception as e:
is_exception = True
result = str(e)
self.send_response_msg(msg, result, is_exception)
@defer.inlineCallbacks
def call_update_upload_file_utime(self, msg):
result = None
is_exception = False
try:
self.contains_msg_key(msg, ('command_id', 'access_time', 'modified_time'))
if msg['command_id'] not in self.command_id_to_writer_map:
raise KeyError('unknown "command_id"')
file_writer = self.command_id_to_writer_map[msg['command_id']]
yield file_writer.remote_utime('access_time', 'modified_time')
except Exception as e:
is_exception = True
result = str(e)
self.send_response_msg(msg, result, is_exception)
@defer.inlineCallbacks
def call_update_upload_file_close(self, msg):
result = None
is_exception = False
try:
self.contains_msg_key(msg, ('command_id',))
if msg['command_id'] not in self.command_id_to_writer_map:
raise KeyError('unknown "command_id"')
file_writer = self.command_id_to_writer_map[msg['command_id']]
yield file_writer.remote_close()
except Exception as e:
is_exception = True
result = str(e)
self.send_response_msg(msg, result, is_exception)
@defer.inlineCallbacks
def call_update_read_file(self, msg):
result = None
is_exception = False
try:
self.contains_msg_key(msg, ('command_id', 'length'))
if msg['command_id'] not in self.command_id_to_reader_map:
raise KeyError('unknown "command_id"')
file_reader = self.command_id_to_reader_map[msg['command_id']]
yield file_reader.remote_read(msg['length'])
except Exception as e:
is_exception = True
result = str(e)
self.send_response_msg(msg, result, is_exception)
@defer.inlineCallbacks
def call_update_read_file_close(self, msg):
result = None
is_exception = False
try:
self.contains_msg_key(msg, ('command_id',))
if msg['command_id'] not in self.command_id_to_reader_map:
raise KeyError('unknown "command_id"')
file_reader = self.command_id_to_reader_map[msg['command_id']]
yield file_reader.remote_close()
except Exception as e:
is_exception = True
result = str(e)
self.send_response_msg(msg, result, is_exception)
@defer.inlineCallbacks
def call_update_upload_directory_unpack(self, msg):
result = None
is_exception = False
try:
self.contains_msg_key(msg, ('command_id',))
if msg['command_id'] not in self.command_id_to_writer_map:
raise KeyError('unknown "command_id"')
directory_writer = self.command_id_to_writer_map[msg['command_id']]
yield directory_writer.remote_unpack()
except Exception as e:
is_exception = True
result = str(e)
self.send_response_msg(msg, result, is_exception)
@defer.inlineCallbacks
def call_update_upload_directory_write(self, msg):
result = None
is_exception = False
try:
self.contains_msg_key(msg, ('command_id', 'args'))
if msg['command_id'] not in self.command_id_to_writer_map:
raise KeyError('unknown "command_id"')
directory_writer = self.command_id_to_writer_map[msg['command_id']]
yield directory_writer.remote_write(msg['args'])
except Exception as e:
is_exception = True
result = str(e)
self.send_response_msg(msg, result, is_exception)
def send_response_msg(self, msg, result, is_exception):
dict_output = {'op': 'response', 'seq_number': msg['seq_number'], 'result': result}
if is_exception:
dict_output['is_exception'] = True
self.maybe_log_master_to_worker_msg(dict_output)
payload = msgpack.packb(dict_output, use_bin_type=True)
self.sendMessage(payload, isBinary=True)
def onMessage(self, payload, isBinary):
if not isBinary:
name = self.worker_name if self.worker_name is not None else '<???>'
log.msg(f'Message type from worker {name} unsupported')
return
msg = msgpack.unpackb(payload, raw=False)
self.maybe_log_worker_to_master_msg(msg)
if 'seq_number' not in msg or 'op' not in msg:
log.msg(f'Invalid message from worker: {msg}')
return
if msg['op'] != "response" and self.connection is None:
self.send_response_msg(msg, "Worker not authenticated.", is_exception=True)
return
if msg['op'] == "update":
self._deferwaiter.add(self.call_update(msg))
elif msg['op'] == "update_upload_file_write":
self._deferwaiter.add(self.call_update_upload_file_write(msg))
elif msg['op'] == "update_upload_file_close":
self._deferwaiter.add(self.call_update_upload_file_close(msg))
elif msg['op'] == "update_upload_file_utime":
self._deferwaiter.add(self.call_update_upload_file_utime(msg))
elif msg['op'] == "update_read_file":
self._deferwaiter.add(self.call_update_read_file(msg))
elif msg['op'] == "update_read_file_close":
self._deferwaiter.add(self.call_update_read_file_close(msg))
elif msg['op'] == "update_upload_directory_unpack":
self._deferwaiter.add(self.call_update_upload_directory_unpack(msg))
elif msg['op'] == "update_upload_directory_write":
self._deferwaiter.add(self.call_update_upload_directory_write(msg))
elif msg['op'] == "complete":
self._deferwaiter.add(self.call_complete(msg))
elif msg['op'] == "response":
seq_number = msg['seq_number']
if "is_exception" in msg:
self.seq_num_to_waiters_map[seq_number].errback(RemoteWorkerError(msg['result']))
else:
self.seq_num_to_waiters_map[seq_number].callback(msg['result'])
# stop waiting for a response of this command
del self.seq_num_to_waiters_map[seq_number]
else:
self.send_response_msg(msg, f"Command {msg['op']} does not exist.", is_exception=True)
@defer.inlineCallbacks
def get_message_result(self, msg):
if msg['op'] != 'print' and msg['op'] != 'get_worker_info' and self.connection is None:
raise ConnectioLostError("No worker connection")
msg['seq_number'] = self.seq_number
self.maybe_log_master_to_worker_msg(msg)
object = msgpack.packb(msg, use_bin_type=True)
d = defer.Deferred()
self.seq_num_to_waiters_map[self.seq_number] = d
self.seq_number = self.seq_number + 1
self.sendMessage(object, isBinary=True)
res1 = yield d
return res1
@defer.inlineCallbacks
def onConnect(self, request):
if self.debug:
log.msg(f"Client connecting: {request.peer}")
value = request.headers.get('authorization')
if value is None:
raise ConnectionDeny(401, "Unauthorized")
try:
username, password = decode_http_authorization_header(value)
except Exception as e:
raise ConnectionDeny(400, "Bad request") from e
try:
dispatcher = self.get_dispatcher()
yield dispatcher.master.initLock.acquire()
if username in dispatcher.users:
pwd, _ = dispatcher.users[username]
if pwd == password:
self.worker_name = username
authentication = True
else:
authentication = False
else:
authentication = False
except Exception as e:
raise RuntimeError("Internal error") from e
finally:
eventually(dispatcher.master.initLock.release)
if not authentication:
raise ConnectionDeny(401, "Unauthorized")
def onClose(self, wasClean, code, reason):
if self.debug:
log.msg(f"WebSocket connection closed: {reason}")
# stop waiting for the responses of all commands
for d in self.seq_num_to_waiters_map.values():
d.errback(ConnectioLostError("Connection lost"))
self.seq_num_to_waiters_map.clear()
if self.connection is not None:
self.connection.detached(self)
class Dispatcher(BaseDispatcher):
DUMMY_PORT = 1
def __init__(self, config_portstr, portstr):
super().__init__(portstr)
try:
port = int(config_portstr)
except ValueError as e:
raise ValueError(f'portstr unsupported: {config_portstr}') from e
# Autobahn does not support zero port meaning to pick whatever port number is free, so
# we work around this by setting the port to nonzero value and resetting the value once
# the port is known. This is possible because Autobahn doesn't do anything with the port
# during the listening setup.
self._zero_port = port == 0
if self._zero_port:
port = self.DUMMY_PORT
self.serverFactory = WebSocketServerFactory(f"ws://0.0.0.0:{port}")
self.serverFactory.buildbot_dispatcher = self
self.serverFactory.protocol = BuildbotWebSocketServerProtocol
def start_listening_port(self):
port = super().start_listening_port()
if self._zero_port:
# Check that websocket port is actually stored into the port attribute, as we're
# relying on undocumented behavior.
if self.serverFactory.port != self.DUMMY_PORT:
raise RuntimeError("Expected websocket port to be set to dummy port")
self.serverFactory.port = port.getHost().port
return port
class MsgManager(BaseManager):
def __init__(self):
super().__init__('msgmanager')
dispatcher_class = Dispatcher
| 16,239 | Python | .py | 351 | 36.393162 | 98 | 0.628749 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
4,912 | pb.py | buildbot_buildbot/master/buildbot/worker/protocols/manager/pb.py | # This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright Buildbot Team Members
from __future__ import annotations
from typing import Any
from typing import Callable
from typing import Generator
from twisted.cred import checkers
from twisted.cred import credentials
from twisted.cred import error
from twisted.cred import portal
from twisted.internet import defer
from twisted.python import log
from twisted.spread import pb
from zope.interface import Interface
from zope.interface import implementer
from buildbot.process.properties import Properties
from buildbot.util import bytes2unicode
from buildbot.util import unicode2bytes
from buildbot.util.eventual import eventually
from buildbot.worker.protocols.manager.base import BaseDispatcher
from buildbot.worker.protocols.manager.base import BaseManager
@implementer(portal.IRealm, checkers.ICredentialsChecker)
class Dispatcher(BaseDispatcher):
credentialInterfaces = [credentials.IUsernamePassword, credentials.IUsernameHashedPassword]
def __init__(self, config_portstr, portstr):
super().__init__(portstr)
# there's lots of stuff to set up for a PB connection!
self.portal = portal.Portal(self)
self.portal.registerChecker(self)
self.serverFactory = pb.PBServerFactory(self.portal)
self.serverFactory.unsafeTracebacks = True
# IRealm
@defer.inlineCallbacks
def requestAvatar(
self, avatarId: bytes | tuple[()], mind: object, *interfaces: type[Interface]
) -> Generator[defer.Deferred[Any], None, tuple[type[Interface], object, Callable]]:
assert interfaces[0] == pb.IPerspective
avatarIdStr = bytes2unicode(avatarId)
persp = None
if avatarIdStr in self.users:
_, afactory = self.users.get(avatarIdStr)
persp = yield afactory(mind, avatarIdStr)
if not persp:
raise ValueError(f"no perspective for '{avatarIdStr}'")
yield persp.attached(mind)
return (pb.IPerspective, persp, lambda: persp.detached(mind))
# ICredentialsChecker
@defer.inlineCallbacks
def requestAvatarId(self, creds):
p = Properties()
p.master = self.master
username = bytes2unicode(creds.username)
try:
yield self.master.initLock.acquire()
if username in self.users:
password, _ = self.users[username]
password = yield p.render(password)
matched = creds.checkPassword(unicode2bytes(password))
if not matched:
log.msg(f"invalid login from user '{username}'")
raise error.UnauthorizedLogin()
return creds.username
log.msg(f"invalid login from unknown user '{username}'")
raise error.UnauthorizedLogin()
finally:
# brake the callback stack by returning to the reactor
# before waking up other waiters
eventually(self.master.initLock.release)
class PBManager(BaseManager):
def __init__(self):
super().__init__('pbmanager')
dispatcher_class = Dispatcher
| 3,756 | Python | .py | 84 | 38.22619 | 95 | 0.719015 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
4,913 | base.py | buildbot_buildbot/master/buildbot/worker/protocols/manager/base.py | # This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright Buildbot Team Members
from twisted.application import strports
from twisted.internet import defer
from twisted.python import log
from buildbot.util import service
class BaseManager(service.AsyncMultiService):
"""
A centralized manager for connection ports and authentication on them.
Allows various pieces of code to request a (port, username) combo, along
with a password and a connection factory.
"""
def __init__(self, name):
super().__init__()
self.setName(name)
self.dispatchers = {}
@defer.inlineCallbacks
def register(self, config_portstr, username, password, pfactory):
"""
Register a connection code to be executed after a user with its USERNAME/PASSWORD
was authenticated and a valid high level connection can be established on a PORTSTR.
Returns a Registration object which can be used to unregister later.
"""
portstr = config_portstr
# do some basic normalization of portstrs
if isinstance(portstr, int) or ':' not in portstr:
portstr = f"tcp:{portstr}".format(portstr)
reg = Registration(self, portstr, username)
if portstr not in self.dispatchers:
disp = self.dispatchers[portstr] = self.dispatcher_class(config_portstr, portstr)
yield disp.setServiceParent(self)
else:
disp = self.dispatchers[portstr]
disp.register(username, password, pfactory)
return reg
@defer.inlineCallbacks
def _unregister(self, registration):
disp = self.dispatchers[registration.portstr]
disp.unregister(registration.username)
registration.username = None
if not disp.users:
del self.dispatchers[registration.portstr]
yield disp.disownServiceParent()
class Registration:
def __init__(self, manager, portstr, username):
self.portstr = portstr
"portstr this registration is active on"
self.username = username
"username of this registration"
self.manager = manager
def __repr__(self):
return f"<base.Registration for {self.username} on {self.portstr}>"
def unregister(self):
"""
Unregister this registration, removing the username from the port, and
closing the port if there are no more users left. Returns a Deferred.
"""
return self.manager._unregister(self)
def getPort(self):
"""
Helper method for testing; returns the TCP port used for this
registration, even if it was specified as 0 and thus allocated by the
OS.
"""
disp = self.manager.dispatchers[self.portstr]
return disp.port.getHost().port
class BaseDispatcher(service.AsyncService):
debug = False
def __init__(self, portstr):
self.portstr = portstr
self.users = {}
self.port = None
def __repr__(self):
return f'<base.BaseDispatcher for {", ".join(list(self.users))} on {self.portstr}>'
def start_listening_port(self):
return strports.listen(self.portstr, self.serverFactory)
def startService(self):
assert not self.port
self.port = self.start_listening_port()
return super().startService()
@defer.inlineCallbacks
def stopService(self):
# stop listening on the port when shut down
assert self.port
port = self.port
self.port = None
yield port.stopListening()
yield super().stopService()
def register(self, username, password, pfactory):
if self.debug:
log.msg(f"registering username '{username}' on port {self.portstr}: {pfactory}")
if username in self.users:
raise KeyError(f"username '{username}' is already registered on port {self.portstr}")
self.users[username] = (password, pfactory)
def unregister(self, username):
if self.debug:
log.msg(f"unregistering username '{username}' on port {self.portstr}")
del self.users[username]
| 4,753 | Python | .py | 110 | 35.990909 | 97 | 0.68364 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
4,914 | stats_service.py | buildbot_buildbot/master/buildbot/statistics/stats_service.py | # This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright Buildbot Team Members
from twisted.internet import defer
from twisted.python import log
from buildbot.statistics.storage_backends.base import StatsStorageBase
from buildbot.util import service
class StatsService(service.BuildbotService):
"""
A middleware for passing on statistics data to all storage backends.
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.consumers = []
def checkConfig(self, storage_backends):
for wfb in storage_backends:
if not isinstance(wfb, StatsStorageBase):
raise TypeError(
f"Invalid type of stats storage service {type(StatsStorageBase)!r}."
" Should be of type StatsStorageBase, "
f"is: {type(StatsStorageBase)!r}"
)
@defer.inlineCallbacks
def reconfigService(self, storage_backends):
log.msg(f"Reconfiguring StatsService with config: {storage_backends!r}")
self.checkConfig(storage_backends)
self.registeredStorageServices = []
for svc in storage_backends:
self.registeredStorageServices.append(svc)
yield self.removeConsumers()
yield self.registerConsumers()
@defer.inlineCallbacks
def registerConsumers(self):
self.consumers = []
for svc in self.registeredStorageServices:
for cap in svc.captures:
cap.parent_svcs.append(svc)
cap.master = self.master
consumer = yield self.master.mq.startConsuming(cap.consume, cap.routingKey)
self.consumers.append(consumer)
@defer.inlineCallbacks
def stopService(self):
yield super().stopService()
yield self.removeConsumers()
@defer.inlineCallbacks
def removeConsumers(self):
for consumer in self.consumers:
yield consumer.stopConsuming()
self.consumers = []
@defer.inlineCallbacks
def yieldMetricsValue(self, data_name, post_data, buildid):
"""
A method to allow posting data that is not generated and stored as build-data in
the database. This method generates the `stats-yield-data` event to the mq layer
which is then consumed in self.postData.
@params
data_name: (str) The unique name for identifying this data.
post_data: (dict) A dictionary of key-value pairs that'll be sent for storage.
buildid: The buildid of the current Build.
"""
build_data = yield self.master.data.get(('builds', buildid))
routingKey = ("stats-yieldMetricsValue", "stats-yield-data")
msg = {'data_name': data_name, 'post_data': post_data, 'build_data': build_data}
self.master.mq.produce(routingKey, msg)
| 3,477 | Python | .py | 75 | 38.613333 | 91 | 0.68617 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
4,915 | __init__.py | buildbot_buildbot/master/buildbot/statistics/__init__.py | # This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright Buildbot Team Members
from buildbot.statistics.capture import CaptureBuildDuration
from buildbot.statistics.capture import CaptureBuildDurationAllBuilders
from buildbot.statistics.capture import CaptureBuildEndTime
from buildbot.statistics.capture import CaptureBuildEndTimeAllBuilders
from buildbot.statistics.capture import CaptureBuildStartTime
from buildbot.statistics.capture import CaptureBuildStartTimeAllBuilders
from buildbot.statistics.capture import CaptureData
from buildbot.statistics.capture import CaptureDataAllBuilders
from buildbot.statistics.capture import CaptureProperty
from buildbot.statistics.capture import CapturePropertyAllBuilders
from buildbot.statistics.stats_service import StatsService
from buildbot.statistics.storage_backends.influxdb_client import InfluxStorageService
__all__ = [
'CaptureBuildDuration',
'CaptureBuildDurationAllBuilders',
'CaptureBuildEndTime',
'CaptureBuildEndTimeAllBuilders',
'CaptureBuildStartTime',
'CaptureBuildStartTimeAllBuilders',
'CaptureData',
'CaptureDataAllBuilders',
'CaptureProperty',
'CapturePropertyAllBuilders',
'InfluxStorageService',
'StatsService',
]
| 1,858 | Python | .py | 40 | 44.2 | 85 | 0.83315 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
4,916 | capture.py | buildbot_buildbot/master/buildbot/statistics/capture.py | # This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright Buildbot Team Members
import abc
import datetime
import re
from twisted.internet import defer
from twisted.internet import threads
from buildbot import config
from buildbot.errors import CaptureCallbackError
class Capture:
"""
Base class for all Capture* classes.
"""
__metaclass__ = abc.ABCMeta
def __init__(self, routingKey, callback):
self.routingKey = routingKey
self._callback = callback
# parent service and buildmaster to be set when StatsService
# initialized
self.parent_svcs = []
self.master = None
def _defaultContext(self, msg, builder_name):
return {"builder_name": builder_name, "build_number": str(msg['number'])}
@abc.abstractmethod
def consume(self, routingKey, msg):
pass
@defer.inlineCallbacks
def _store(self, post_data, series_name, context):
for svc in self.parent_svcs:
yield threads.deferToThread(svc.thd_postStatsValue, post_data, series_name, context)
class CapturePropertyBase(Capture):
"""
A base class for CaptureProperty* classes.
"""
def __init__(self, property_name, callback=None, regex=False):
self._property_name = property_name
self._regex = regex
routingKey = ("builders", None, "builds", None, "finished")
def default_callback(props, property_name):
# index: 0 - prop_value, 1 - prop_source
return props[property_name][0]
if not callback:
callback = default_callback
super().__init__(routingKey, callback)
@defer.inlineCallbacks
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_info):
properties = yield self.master.data.get(("builds", msg['buildid'], "properties"))
if self._regex:
filtered_prop_names = [pn for pn in properties if re.match(self._property_name, pn)]
else:
filtered_prop_names = [self._property_name]
for pn in filtered_prop_names:
try:
ret_val = self._callback(properties, pn)
except KeyError as e:
raise CaptureCallbackError(
"CaptureProperty failed."
f" The property {pn} not found for build number "
f"{msg['number']} on"
f" builder {builder_info['name']}."
) from e
context = self._defaultContext(msg, builder_info['name'])
series_name = f"{builder_info['name']}-{pn}"
post_data = {"name": pn, "value": ret_val}
yield self._store(post_data, series_name, context)
else:
yield defer.succeed(None)
@abc.abstractmethod
def _builder_name_matches(self, builder_info):
pass
class CaptureProperty(CapturePropertyBase):
"""
Convenience wrapper for getting statistics for filtering.
Filters out build properties specifies in the config file.
"""
def __init__(self, builder_name, property_name, callback=None, regex=False):
self._builder_name = builder_name
super().__init__(property_name, callback, regex)
def _builder_name_matches(self, builder_info):
return self._builder_name == builder_info['name']
class CapturePropertyAllBuilders(CapturePropertyBase):
"""
Capture class for filtering out build properties for all builds.
"""
def _builder_name_matches(self, builder_info):
# Since we need to match all builders, we simply return True here.
return True
class CaptureBuildTimes(Capture):
"""
Capture methods for capturing build start times.
"""
def __init__(self, builder_name, callback, time_type):
self._builder_name = builder_name
routingKey = ("builders", None, "builds", None, "finished")
self._time_type = time_type
super().__init__(routingKey, callback)
@defer.inlineCallbacks
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._callback(*self._retValParams(msg))
except Exception as e:
# catching generic exceptions is okay here since we propagate
# it
raise CaptureCallbackError(
f"{self._err_msg(msg, builder_info['name'])} "
f"Exception raised: {type(e).__name__} "
f"with message: {e!s}"
) from e
context = self._defaultContext(msg, builder_info['name'])
post_data = {self._time_type: ret_val}
series_name = f"{builder_info['name']}-build-times"
yield self._store(post_data, series_name, context)
else:
yield defer.succeed(None)
def _err_msg(self, build_data, builder_name):
msg = (
f"{self.__class__.__name__} failed on build {build_data['number']} "
f"on builder {builder_name}."
)
return msg
@abc.abstractmethod
def _retValParams(self, msg):
pass
@abc.abstractmethod
def _builder_name_matches(self, builder_info):
pass
class CaptureBuildStartTime(CaptureBuildTimes):
"""
Capture methods for capturing build start times.
"""
def __init__(self, builder_name, callback=None):
def default_callback(start_time):
return start_time.isoformat()
if not callback:
callback = default_callback
super().__init__(builder_name, callback, "start-time")
def _retValParams(self, msg):
return [msg['started_at']]
def _builder_name_matches(self, builder_info):
return self._builder_name == builder_info['name']
class CaptureBuildStartTimeAllBuilders(CaptureBuildStartTime):
"""
Capture methods for capturing build start times for all builders.
"""
def __init__(self, callback=None):
super().__init__(None, callback)
def _builder_name_matches(self, builder_info):
# Match all builders so simply return True
return True
class CaptureBuildEndTime(CaptureBuildTimes):
"""
Capture methods for capturing build end times.
"""
def __init__(self, builder_name, callback=None):
def default_callback(end_time):
return end_time.isoformat()
if not callback:
callback = default_callback
super().__init__(builder_name, callback, "end-time")
def _retValParams(self, msg):
return [msg['complete_at']]
def _builder_name_matches(self, builder_info):
return self._builder_name == builder_info['name']
class CaptureBuildEndTimeAllBuilders(CaptureBuildEndTime):
"""
Capture methods for capturing build end times on all builders.
"""
def __init__(self, callback=None):
super().__init__(None, callback)
def _builder_name_matches(self, builder_info):
# Match all builders so simply return True
return True
class CaptureBuildDuration(CaptureBuildTimes):
"""
Capture methods for capturing build start times.
"""
def __init__(self, builder_name, report_in='seconds', callback=None):
if report_in not in ['seconds', 'minutes', 'hours']:
config.error(
f"Error during initialization of class {self.__class__.__name__}."
" `report_in` parameter must be one of 'seconds', 'minutes' or 'hours'"
)
def default_callback(start_time, end_time):
divisor = 1
# it's a closure
if report_in == 'minutes':
divisor = 60
elif report_in == 'hours':
divisor = 60 * 60
if end_time < start_time:
duration = datetime.timedelta(0)
else:
duration = end_time - start_time
return duration.total_seconds() / divisor
if not callback:
callback = default_callback
super().__init__(builder_name, callback, "duration")
def _retValParams(self, msg):
return [msg['started_at'], msg['complete_at']]
def _builder_name_matches(self, builder_info):
return self._builder_name == builder_info['name']
class CaptureBuildDurationAllBuilders(CaptureBuildDuration):
"""
Capture methods for capturing build durations on all builders.
"""
def __init__(self, report_in='seconds', callback=None):
super().__init__(None, report_in, callback)
def _builder_name_matches(self, builder_info):
# Match all builders so simply return True
return True
class CaptureDataBase(Capture):
"""
Base class for CaptureData methods.
"""
def __init__(self, data_name, callback=None):
self._data_name = data_name
def identity(x):
return x
if not callback:
callback = identity
# this is the routing key which is used to register consumers on to mq layer
# this following key created in StatsService.yieldMetricsValue and used
# here
routingKey = ("stats-yieldMetricsValue", "stats-yield-data")
super().__init__(routingKey, callback)
@defer.inlineCallbacks
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']))
if self._builder_name_matches(builder_info) and self._data_name == msg['data_name']:
try:
ret_val = self._callback(msg['post_data'])
except Exception as e:
raise CaptureCallbackError(
f"CaptureData failed for build {build_data['number']} "
f"of builder {builder_info['name']}. "
f"Exception generated: {type(e).__name__} "
f"with message {e!s}"
) from e
post_data = ret_val
series_name = f"{builder_info['name']}-{self._data_name}"
context = self._defaultContext(build_data, builder_info['name'])
yield self._store(post_data, series_name, context)
@abc.abstractmethod
def _builder_name_matches(self, builder_info):
pass
class CaptureData(CaptureDataBase):
"""
Capture methods for arbitrary data that may not be stored in the Buildbot database.
"""
def __init__(self, data_name, builder_name, callback=None):
self._builder_name = builder_name
super().__init__(data_name, callback)
def _builder_name_matches(self, builder_info):
return self._builder_name == builder_info['name']
class CaptureDataAllBuilders(CaptureDataBase):
"""
Capture methods for arbitrary data that may not be stored in the Buildbot database.
"""
def _builder_name_matches(self, builder_info):
return True
| 12,233 | Python | .py | 288 | 33.576389 | 100 | 0.626919 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
4,917 | influxdb_client.py | buildbot_buildbot/master/buildbot/statistics/storage_backends/influxdb_client.py | # This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright Buildbot Team Members
from twisted.python import log
from buildbot import config
from buildbot.statistics.storage_backends.base import StatsStorageBase
try:
from influxdb import InfluxDBClient
except ImportError:
InfluxDBClient = None
class InfluxStorageService(StatsStorageBase):
"""
Delegates data to InfluxDB
"""
def __init__(self, url, port, user, password, db, captures, name="InfluxStorageService"):
if not InfluxDBClient:
config.error("Python client for InfluxDB not installed.")
return
self.url = url
self.port = port
self.user = user
self.password = password
self.db = db
self.name = name
self.captures = captures
self.client = InfluxDBClient(self.url, self.port, self.user, self.password, self.db)
self._inited = True
def thd_postStatsValue(self, post_data, series_name, context=None):
if not self._inited:
log.err(f"Service {self.name} not initialized")
return
data = {'measurement': series_name, 'fields': post_data}
log.msg("Sending data to InfluxDB")
log.msg(f"post_data: {post_data!r}")
if context:
log.msg(f"context: {context!r}")
data['tags'] = context
self.client.write_points([data])
| 2,025 | Python | .py | 49 | 35.44898 | 93 | 0.69771 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
4,918 | __init__.py | buildbot_buildbot/master/buildbot/statistics/storage_backends/__init__.py | # This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright Buildbot Team Members
| 705 | Python | .py | 14 | 49.357143 | 79 | 0.788712 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
4,919 | base.py | buildbot_buildbot/master/buildbot/statistics/storage_backends/base.py | # This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright Buildbot Team Members
import abc
class StatsStorageBase:
"""
Base class for sub service responsible for passing on stats data to
a storage backend
"""
__metaclass__ = abc.ABCMeta
@abc.abstractmethod
def thd_postStatsValue(self, post_data, series_name, context=None):
pass
| 996 | Python | .py | 24 | 38.791667 | 79 | 0.764219 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
4,920 | manager.py | buildbot_buildbot/master/buildbot/machine/manager.py | # This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Portions Copyright Buildbot Team Members
from __future__ import annotations
from buildbot.util import service
from buildbot.worker.manager import WorkerManager
class MachineManager(service.BuildbotServiceManager):
reconfig_priority = WorkerManager.reconfig_priority + 1
name: str | None = 'MachineManager' # type: ignore[assignment]
managed_services_name = 'machines'
config_attr = 'machines'
@property
def machines(self):
return self.namedServices
def getMachineByName(self, name):
if name in self.machines:
return self.machines[name]
return None
| 1,292 | Python | .py | 29 | 41.137931 | 79 | 0.765314 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
4,921 | generic.py | buildbot_buildbot/master/buildbot/machine/generic.py | # This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright Buildbot Team Members
import os
import stat
from twisted.internet import defer
from twisted.python import log
from zope.interface import implementer
from buildbot import config
from buildbot.interfaces import IMachineAction
from buildbot.machine.latent import AbstractLatentMachine
from buildbot.util import httpclientservice
from buildbot.util import misc
from buildbot.util import private_tempdir
from buildbot.util import runprocess
from buildbot.util.git import getSshArgsForKeys
from buildbot.util.git import getSshKnownHostsContents
class GenericLatentMachine(AbstractLatentMachine):
def checkConfig(self, name, start_action, stop_action, **kwargs):
super().checkConfig(name, **kwargs)
for action, arg_name in [(start_action, 'start_action'), (stop_action, 'stop_action')]:
if not IMachineAction.providedBy(action):
msg = f"{arg_name} of {self.name} does not implement required interface"
raise RuntimeError(msg)
@defer.inlineCallbacks
def reconfigService(self, name, start_action, stop_action, **kwargs):
yield super().reconfigService(name, **kwargs)
self.start_action = start_action
self.stop_action = stop_action
def start_machine(self):
return self.start_action.perform(self)
def stop_machine(self):
return self.stop_action.perform(self)
@defer.inlineCallbacks
def runProcessLogFailures(reactor, args, expectedCode=0):
code, stdout, stderr = yield runprocess.run_process(reactor, args)
if code != expectedCode:
log.err(
f'Got unexpected return code when running {args}: '
f'code: {code}, stdout: {stdout}, stderr: {stderr}'
)
return False
return True
class _LocalMachineActionMixin:
def setupLocal(self, command):
if not isinstance(command, list):
config.error('command parameter must be a list')
self._command = command
@defer.inlineCallbacks
def perform(self, manager):
args = yield manager.renderSecrets(self._command)
return (yield runProcessLogFailures(manager.master.reactor, args))
class _SshActionMixin:
def setupSsh(self, sshBin, host, remoteCommand, sshKey=None, sshHostKey=None):
if not isinstance(sshBin, str):
config.error('sshBin parameter must be a string')
if not isinstance(host, str):
config.error('host parameter must be a string')
if not isinstance(remoteCommand, list):
config.error('remoteCommand parameter must be a list')
self._sshBin = sshBin
self._host = host
self._remoteCommand = remoteCommand
self._sshKey = sshKey
self._sshHostKey = sshHostKey
@defer.inlineCallbacks
def _performImpl(self, manager, key_path, known_hosts_path):
args = getSshArgsForKeys(key_path, known_hosts_path)
args.append((yield manager.renderSecrets(self._host)))
args.extend((yield manager.renderSecrets(self._remoteCommand)))
return (yield runProcessLogFailures(manager.master.reactor, [self._sshBin, *args]))
@defer.inlineCallbacks
def _prepareSshKeys(self, manager, temp_dir_path):
key_path = None
if self._sshKey is not None:
ssh_key_data = yield manager.renderSecrets(self._sshKey)
key_path = os.path.join(temp_dir_path, 'ssh-key')
misc.writeLocalFile(key_path, ssh_key_data, mode=stat.S_IRUSR)
known_hosts_path = None
if self._sshHostKey is not None:
ssh_host_key_data = yield manager.renderSecrets(self._sshHostKey)
ssh_host_key_data = getSshKnownHostsContents(ssh_host_key_data)
known_hosts_path = os.path.join(temp_dir_path, 'ssh-known-hosts')
misc.writeLocalFile(known_hosts_path, ssh_host_key_data)
return (key_path, known_hosts_path)
@defer.inlineCallbacks
def perform(self, manager):
if self._sshKey is not None or self._sshHostKey is not None:
with private_tempdir.PrivateTemporaryDirectory(
prefix='ssh-', dir=manager.master.basedir
) as temp_dir:
key_path, hosts_path = yield self._prepareSshKeys(manager, temp_dir)
ret = yield self._performImpl(manager, key_path, hosts_path)
else:
ret = yield self._performImpl(manager, None, None)
return ret
@implementer(IMachineAction)
class LocalWakeAction(_LocalMachineActionMixin):
def __init__(self, command):
self.setupLocal(command)
class LocalWOLAction(LocalWakeAction):
def __init__(self, wakeMac, wolBin='wakeonlan'):
LocalWakeAction.__init__(self, [wolBin, wakeMac])
@implementer(IMachineAction)
class RemoteSshWakeAction(_SshActionMixin):
def __init__(self, host, remoteCommand, sshBin='ssh', sshKey=None, sshHostKey=None):
self.setupSsh(sshBin, host, remoteCommand, sshKey=sshKey, sshHostKey=sshHostKey)
class RemoteSshWOLAction(RemoteSshWakeAction):
def __init__(
self, host, wakeMac, wolBin='wakeonlan', sshBin='ssh', sshKey=None, sshHostKey=None
):
RemoteSshWakeAction.__init__(
self, host, [wolBin, wakeMac], sshBin=sshBin, sshKey=sshKey, sshHostKey=sshHostKey
)
@implementer(IMachineAction)
class RemoteSshSuspendAction(_SshActionMixin):
def __init__(self, host, remoteCommand=None, sshBin='ssh', sshKey=None, sshHostKey=None):
if remoteCommand is None:
remoteCommand = ['systemctl', 'suspend']
self.setupSsh(sshBin, host, remoteCommand, sshKey=sshKey, sshHostKey=sshHostKey)
@implementer(IMachineAction)
class HttpAction:
def __init__(
self,
url,
method,
params=None,
data=None,
json=None,
headers=None,
cookies=None,
files=None,
auth=None,
timeout=None,
allow_redirects=None,
proxies=None,
):
self.url = url
self.method = method
self.params = params
self.data = data
self.json = json
self.headers = headers
self.cookies = cookies
self.files = files
self.auth = auth
self.timeout = timeout
self.allow_redirects = allow_redirects
self.proxies = proxies
@defer.inlineCallbacks
def perform(self, manager):
(
url,
method,
params,
data,
json,
headers,
cookies,
files,
auth,
timeout,
allow_redirects,
proxies,
) = yield manager.renderSecrets((
self.url,
self.method,
self.params,
self.data,
self.json,
self.headers,
self.cookies,
self.files,
self.auth,
self.timeout,
self.allow_redirects,
self.proxies,
))
http = httpclientservice.HTTPSession(manager.master.httpservice, base_url=url)
if method == 'get':
fn = http.get
elif method == 'put':
fn = http.put
elif method == 'delete':
fn = http.delete
elif method == 'post':
fn = http.post
else:
config.error(f'Invalid method {method}')
yield fn(
ep='',
params=params,
data=data,
json=json,
headers=headers,
cookies=cookies,
files=files,
auth=auth,
timeout=timeout,
allow_redirects=allow_redirects,
proxies=proxies,
)
| 8,389 | Python | .py | 213 | 31.042254 | 95 | 0.652901 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
4,922 | __init__.py | buildbot_buildbot/master/buildbot/machine/__init__.py | # This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright Buildbot Team Members
| 705 | Python | .py | 14 | 49.357143 | 79 | 0.788712 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
4,923 | base.py | buildbot_buildbot/master/buildbot/machine/base.py | # This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Portions Copyright Buildbot Team Members
from twisted.internet import defer
from zope.interface import implementer
from buildbot import interfaces
from buildbot.util import service
@implementer(interfaces.IMachine)
class Machine(service.BuildbotService):
def checkConfig(self, name, **kwargs):
super().checkConfig(**kwargs)
self.name = name
self.workers = []
@defer.inlineCallbacks
def reconfigService(self, name, **kwargs):
yield super().reconfigService(**kwargs)
assert self.name == name
def registerWorker(self, worker):
assert worker.machine_name == self.name
self.workers.append(worker)
def unregisterWorker(self, worker):
assert worker in self.workers
self.workers.remove(worker)
def __repr__(self):
return f"<Machine '{self.name}' at {id(self)}>"
| 1,539 | Python | .py | 36 | 38.638889 | 79 | 0.742475 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
4,924 | latent.py | buildbot_buildbot/master/buildbot/machine/latent.py | # This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright Buildbot Team Members
import enum
from twisted.internet import defer
from twisted.python import log
from zope.interface import implementer
from buildbot import interfaces
from buildbot.machine.base import Machine
from buildbot.util import Notifier
class States(enum.Enum):
# Represents the state of LatentMachine
STOPPED = 0
STARTING = 1
STARTED = 2
STOPPING = 3
@implementer(interfaces.ILatentMachine)
class AbstractLatentMachine(Machine):
DEFAULT_MISSING_TIMEOUT = 20 * 60
def checkConfig(
self, name, build_wait_timeout=0, missing_timeout=DEFAULT_MISSING_TIMEOUT, **kwargs
):
super().checkConfig(name, **kwargs)
self.state = States.STOPPED
self.latent_workers = []
@defer.inlineCallbacks
def reconfigService(
self, name, build_wait_timeout=0, missing_timeout=DEFAULT_MISSING_TIMEOUT, **kwargs
):
yield super().reconfigService(name, **kwargs)
self.build_wait_timeout = build_wait_timeout
self.missing_timeout = missing_timeout
for worker in self.workers:
if not interfaces.ILatentWorker.providedBy(worker):
raise RuntimeError(f'Worker is not latent {worker.name}')
self.state = States.STOPPED
self._start_notifier = Notifier()
self._stop_notifier = Notifier()
self._build_wait_timer = None
self._missing_timer = None
def start_machine(self):
# Responsible for starting the machine. The function should return a
# deferred which should result in True if the startup has been
# successful, or False otherwise.
raise NotImplementedError
def stop_machine(self):
# Responsible for shutting down the machine
raise NotImplementedError
@defer.inlineCallbacks
def substantiate(self, starting_worker):
if self.state == States.STOPPING:
# wait until stop action finishes
yield self._stop_notifier.wait()
if self.state == States.STARTED:
# may happen if we waited for stop to complete and in the mean
# time the machine was successfully woken.
return True
# wait for already proceeding startup to finish, if any
if self.state == States.STARTING:
return (yield self._start_notifier.wait())
self.state = States.STARTING
# substantiate all workers that will start if we wake the machine. We
# do so before waking the machine to guarantee that we're already
# waiting for worker connection as waking may take time confirming
# machine came online. We'll call substantiate on the worker that
# invoked this function again, but that's okay as that function is
# reentrant. Note that we substantiate without gathering results
# because the original call to substantiate will get them anyway and
# we don't want to be slowed down by other workers on the machine.
for worker in self.workers:
if worker.starts_without_substantiate:
worker.substantiate(None, None)
# Start the machine. We don't need to wait for any workers to actually
# come online as that's handled in their substantiate() functions.
try:
ret = yield self.start_machine()
except Exception as e:
log.err(e, f'while starting latent machine {self.name}')
ret = False
if not ret:
yield defer.DeferredList(
[worker.insubstantiate() for worker in self.workers], consumeErrors=True
)
else:
self._setMissingTimer()
self.state = States.STARTED if ret else States.STOPPED
self._start_notifier.notify(ret)
return ret
@defer.inlineCallbacks
def _stop(self):
if any(worker.building for worker in self.workers) or self.state == States.STARTING:
return None
if self.state == States.STOPPING:
yield self._stop_notifier.wait()
return None
self.state = States.STOPPING
# wait until workers insubstantiate, then stop
yield defer.DeferredList(
[worker.insubstantiate() for worker in self.workers], consumeErrors=True
)
try:
yield self.stop_machine()
except Exception as e:
log.err(e, f'while stopping latent machine {self.name}')
self.state = States.STOPPED
self._stop_notifier.notify(None)
return None
def notifyBuildStarted(self):
self._clearMissingTimer()
def notifyBuildFinished(self):
if any(worker.building for worker in self.workers):
self._clearBuildWaitTimer()
else:
self._setBuildWaitTimer()
def _clearMissingTimer(self):
if self._missing_timer is not None:
if self._missing_timer.active():
self._missing_timer.cancel()
self._missing_timer = None
def _setMissingTimer(self):
self._clearMissingTimer()
self._missing_timer = self.master.reactor.callLater(self.missing_timeout, self._stop)
def _clearBuildWaitTimer(self):
if self._build_wait_timer is not None:
if self._build_wait_timer.active():
self._build_wait_timer.cancel()
self._build_wait_timer = None
def _setBuildWaitTimer(self):
self._clearBuildWaitTimer()
self._build_wait_timer = self.master.reactor.callLater(self.build_wait_timeout, self._stop)
def __repr__(self):
return f"<AbstractLatentMachine '{self.name}' at {id(self)}>"
| 6,344 | Python | .py | 143 | 36.125874 | 99 | 0.674019 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
4,925 | state.py | buildbot_buildbot/master/buildbot/util/state.py | # This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright Buildbot Team Members
from twisted.internet import defer
class StateMixin:
# state management
_objectid = None
@defer.inlineCallbacks
def getState(self, *args, **kwargs):
# get the objectid, if not known
if self._objectid is None:
self._objectid = yield self.master.db.state.getObjectId(
self.name, self.__class__.__name__
)
rv = yield self.master.db.state.getState(self._objectid, *args, **kwargs)
return rv
@defer.inlineCallbacks
def setState(self, key, value):
# get the objectid, if not known
if self._objectid is None:
self._objectid = yield self.master.db.state.getObjectId(
self.name, self.__class__.__name__
)
yield self.master.db.state.setState(self._objectid, key, value)
| 1,534 | Python | .py | 35 | 38 | 81 | 0.695973 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
4,926 | ssfilter.py | buildbot_buildbot/master/buildbot/util/ssfilter.py | # This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright Buildbot Team Members
import re
from typing import ClassVar
from typing import Sequence
from buildbot.util import ComparableMixin
from buildbot.util import NotABranch
def extract_filter_values(values, filter_name):
if not isinstance(values, (list, str)):
raise ValueError(f"Values of filter {filter_name} must be list of strings or a string")
if isinstance(values, str):
values = [values]
else:
for value in values:
if not isinstance(value, str):
raise ValueError(f"Value of filter {filter_name} must be string")
return values
def extract_filter_values_branch(values, filter_name):
if not isinstance(values, (list, str, type(None))):
raise ValueError(
f"Values of filter {filter_name} must be list of strings, " "a string or None"
)
if isinstance(values, (str, type(None))):
values = [values]
else:
for value in values:
if not isinstance(value, (str, type(None))):
raise ValueError(f"Value of filter {filter_name} must be string or None")
return values
def extract_filter_values_regex(values, filter_name):
if not isinstance(values, (list, str, re.Pattern)):
raise ValueError(
f"Values of filter {filter_name} must be list of strings, " "a string or regex"
)
if isinstance(values, (str, re.Pattern)):
values = [values]
else:
for value in values:
if not isinstance(value, (str, re.Pattern)):
raise ValueError(f"Value of filter {filter_name} must be string or regex")
return values
def extract_filter_values_dict(values, filter_name):
if not isinstance(values, dict):
raise ValueError(f"Value of filter {filter_name} must be dict")
return {k: extract_filter_values(v, filter_name) for k, v in values.items()}
def extract_filter_values_dict_regex(values, filter_name):
if not isinstance(values, dict):
raise ValueError(f"Value of filter {filter_name} must be dict")
return {k: extract_filter_values_regex(v, filter_name) for k, v in values.items()}
class _FilterExactMatch(ComparableMixin):
compare_attrs: ClassVar[Sequence[str]] = ('prop', 'values')
def __init__(self, prop, values):
self.prop = prop
self.values = values
def is_matched(self, value):
return value in self.values
def describe(self):
return f'{self.prop} in {self.values}'
class _FilterExactMatchInverse(ComparableMixin):
compare_attrs: ClassVar[Sequence[str]] = ('prop', 'values')
def __init__(self, prop, values):
self.prop = prop
self.values = values
def is_matched(self, value):
return value not in self.values
def describe(self):
return f'{self.prop} not in {self.values}'
class _FilterRegex(ComparableMixin):
compare_attrs: ClassVar[Sequence[str]] = ('prop', 'regexes')
def __init__(self, prop, regexes):
self.prop = prop
self.regexes = [self._compile(regex) for regex in regexes]
def _compile(self, regex):
if isinstance(regex, re.Pattern):
return regex
return re.compile(regex)
def is_matched(self, value):
if value is None:
return False
for regex in self.regexes:
if regex.match(value) is not None:
return True
return False
def describe(self):
return f'{self.prop} matches {self.regexes}'
class _FilterRegexInverse(ComparableMixin):
compare_attrs: ClassVar[Sequence[str]] = ('prop', 'regexes')
def __init__(self, prop, regexes):
self.prop = prop
self.regexes = [self._compile(regex) for regex in regexes]
def _compile(self, regex):
if isinstance(regex, re.Pattern):
return regex
return re.compile(regex)
def is_matched(self, value):
if value is None:
return True
for regex in self.regexes:
if regex.match(value) is not None:
return False
return True
def describe(self):
return f'{self.prop} does not match {self.regexes}'
def _create_branch_filters(eq, not_eq, regex, not_regex, prop):
filters = []
if eq is not NotABranch:
values = extract_filter_values_branch(eq, prop + '_eq')
filters.append(_FilterExactMatch(prop, values))
if not_eq is not NotABranch:
values = extract_filter_values_branch(not_eq, prop + '_not_eq')
filters.append(_FilterExactMatchInverse(prop, values))
if regex is not None:
values = extract_filter_values_regex(regex, prop + '_re')
filters.append(_FilterRegex(prop, values))
if not_regex is not None:
values = extract_filter_values_regex(not_regex, prop + '_not_re')
filters.append(_FilterRegexInverse(prop, values))
return filters
def _create_filters(eq, not_eq, regex, not_regex, prop):
filters = []
if eq is not None:
values = extract_filter_values(eq, prop + '_eq')
filters.append(_FilterExactMatch(prop, values))
if not_eq is not None:
values = extract_filter_values(not_eq, prop + '_not_eq')
filters.append(_FilterExactMatchInverse(prop, values))
if regex is not None:
values = extract_filter_values_regex(regex, prop + '_re')
filters.append(_FilterRegex(prop, values))
if not_regex is not None:
values = extract_filter_values_regex(not_regex, prop + '_not_re')
filters.append(_FilterRegexInverse(prop, values))
return filters
def _create_property_filters(eq, not_eq, regex, not_regex, arg_prefix):
filters = []
if eq is not None:
values_dict = extract_filter_values_dict(eq, arg_prefix + '_eq')
filters += [_FilterExactMatch(prop, values) for prop, values in values_dict.items()]
if not_eq is not None:
values_dict = extract_filter_values_dict(not_eq, arg_prefix + '_not_eq')
filters += [_FilterExactMatchInverse(prop, values) for prop, values in values_dict.items()]
if regex is not None:
values_dict = extract_filter_values_dict_regex(regex, arg_prefix + '_re')
filters += [_FilterRegex(prop, values) for prop, values in values_dict.items()]
if not_regex is not None:
values_dict = extract_filter_values_dict_regex(not_regex, arg_prefix + '_not_re')
filters += [_FilterRegexInverse(prop, values) for prop, values in values_dict.items()]
return filters
class SourceStampFilter(ComparableMixin):
compare_attrs: ClassVar[Sequence[str]] = (
'filter_fn',
'filters',
)
def __init__(
self,
# gets a SourceStamp dictionary, returns boolean
filter_fn=None,
project_eq=None,
project_not_eq=None,
project_re=None,
project_not_re=None,
repository_eq=None,
repository_not_eq=None,
repository_re=None,
repository_not_re=None,
branch_eq=NotABranch,
branch_not_eq=NotABranch,
branch_re=None,
branch_not_re=None,
codebase_eq=None,
codebase_not_eq=None,
codebase_re=None,
codebase_not_re=None,
):
self.filter_fn = filter_fn
self.filters = _create_filters(
project_eq,
project_not_eq,
project_re,
project_not_re,
'project',
)
self.filters += _create_filters(
codebase_eq,
codebase_not_eq,
codebase_re,
codebase_not_re,
'codebase',
)
self.filters += _create_filters(
repository_eq,
repository_not_eq,
repository_re,
repository_not_re,
'repository',
)
self.filters += _create_branch_filters(
branch_eq,
branch_not_eq,
branch_re,
branch_not_re,
'branch',
)
def is_matched(self, ss):
if self.filter_fn is not None and not self.filter_fn(ss):
return False
for filter in self.filters:
value = ss.get(filter.prop, '')
if not filter.is_matched(value):
return False
return True
def __repr__(self):
filters = []
if self.filter_fn is not None:
filters.append(f'{self.filter_fn.__name__}()')
filters += [filter.describe() for filter in self.filters]
return f"<{self.__class__.__name__} on {' and '.join(filters)}>"
| 9,261 | Python | .py | 229 | 32.502183 | 99 | 0.636992 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
4,927 | ssl.py | buildbot_buildbot/master/buildbot/util/ssl.py | # This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright Buildbot Team Members
"""
This modules acts the same as twisted.internet.ssl except it does not raise ImportError
Modules using this should call ensureHasSSL in order to make sure that the user installed
buildbot[tls]
"""
import unittest
from buildbot.config import error
try:
from twisted.internet.ssl import * # noqa: F403
ssl_import_error = None
has_ssl = True
except ImportError as e:
ssl_import_error = str(e)
has_ssl = False
def ensureHasSSL(module):
if not has_ssl:
error(
f"TLS dependencies required for {module} are not installed : "
f"{ssl_import_error}\n pip install 'buildbot[tls]'"
)
def skipUnless(f):
return unittest.skipUnless(has_ssl, "TLS dependencies required")(f)
| 1,446 | Python | .py | 36 | 37 | 89 | 0.752143 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
4,928 | queue.py | buildbot_buildbot/master/buildbot/util/queue.py | # This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Portions Copyright Buildbot Team Members
import queue
import threading
from twisted.internet import defer
from twisted.internet import reactor
from twisted.python import log
from buildbot.util import backoff
class UndoableQueue(queue.Queue):
def unget(self, x):
with self.mutex:
self.queue.appendleft(x)
class _TerminateRequest:
pass
class ConnectableThreadQueue(threading.Thread):
"""
This provides worker thread that is processing work given via execute_in_thread() method.
The return value of the function submitted to execute_in_thread() is returned via Deferred.
All work is performed in a "connection", which is established in create_connection() which
is intended to be overridden by user. The user is expected to return an opaque connection
object from create_connection(). create_connection() must not throw exceptions.
The connection is from the user-side closed by calling close_connection().
The connection is passed as the first argument to the functions submitted to
execute_in_thread().
When the thread is joined, it will execute all currently pending items and call
on_close_connection() if needed to close the connection. Any work submitted after join() is
called will be ignored.
"""
def __init__(
self,
connect_backoff_start_seconds=1,
connect_backoff_multiplier=1.1,
connect_backoff_max_wait_seconds=3600,
):
self._queue = UndoableQueue()
self._conn = None
self._backoff_engine = backoff.ExponentialBackoffEngineSync(
start_seconds=connect_backoff_start_seconds,
multiplier=connect_backoff_multiplier,
max_wait_seconds=connect_backoff_max_wait_seconds,
)
super().__init__(daemon=True)
self.connecting = False
self.start()
def join(self, *args, **kwargs):
self.execute_in_thread(_TerminateRequest())
super().join(*args, **kwargs)
def execute_in_thread(self, cb, *args, **kwargs):
d = defer.Deferred()
self._queue.put((d, cb, args, kwargs))
return d
@property
def conn(self):
return self._conn
def close_connection(self):
self._conn = None
self.connecting = False
def on_close_connection(self, conn):
# override to perform any additional connection closing tasks
self.close_connection()
def create_connection(self):
# override to create a new connection
raise NotImplementedError()
def _handle_backoff(self, msg):
# returns True if termination has been requested
log.err(msg)
try:
self._backoff_engine.wait_on_failure()
except backoff.BackoffTimeoutExceededError:
self._backoff_engine.on_success() # reset the timers
if self._drain_queue_with_exception(backoff.BackoffTimeoutExceededError(msg)):
return True
return False
def _drain_queue_with_exception(self, e):
# returns True if termination has been requested
try:
while True:
result_d, next_operation, _, __ = self._queue.get(block=False)
if isinstance(next_operation, _TerminateRequest):
self._queue.task_done()
reactor.callFromThread(result_d.callback, None)
return True
else:
self._queue.task_done()
reactor.callFromThread(result_d.errback, e)
except queue.Empty:
return False
def run(self):
while True:
result_d, next_operation, args, kwargs = self._queue.get()
if isinstance(next_operation, _TerminateRequest):
self._queue.task_done()
reactor.callFromThread(result_d.callback, None)
break
if not self._conn:
self.connecting = True
self._queue.unget((result_d, next_operation, args, kwargs))
try:
self._conn = self.create_connection()
self.connecting = False
if self._conn is not None:
self._backoff_engine.on_success()
elif self._handle_backoff('Did not receive connection'):
break
except Exception as e:
self.connecting = False
if self._handle_backoff(f'Exception received: {e}'):
break
continue
try:
result = next_operation(self._conn, *args, **kwargs)
reactor.callFromThread(result_d.callback, result)
except Exception as e:
reactor.callFromThread(result_d.errback, e)
self._queue.task_done()
if self._conn is not None:
self.on_close_connection(self._conn)
| 5,641 | Python | .py | 129 | 33.96124 | 95 | 0.639745 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
4,929 | httpclientservice.py | buildbot_buildbot/master/buildbot/util/httpclientservice.py | # This file is part of Buildbot. Buildbot is free software: you can)
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright Buildbot Team Members
import json as jsonmodule
from twisted.internet import defer
from twisted.logger import Logger
from twisted.python import deprecate
from twisted.python import versions
from twisted.python.threadpool import ThreadPool
from twisted.web.client import Agent
from twisted.web.client import HTTPConnectionPool
from zope.interface import implementer
from buildbot.interfaces import IHttpResponse
from buildbot.util import service
from buildbot.util import toJson
from buildbot.util import unicode2bytes
try:
import txrequests
except ImportError:
txrequests = None
import treq
log = Logger()
@implementer(IHttpResponse)
class TxRequestsResponseWrapper:
def __init__(self, res):
self._res = res
def content(self):
return defer.succeed(self._res.content)
def json(self):
return defer.succeed(self._res.json())
@property
def code(self):
return self._res.status_code
@property
def url(self):
return self._res.url
@implementer(IHttpResponse)
class TreqResponseWrapper:
def __init__(self, res):
self._res = res
def content(self):
return self._res.content()
def json(self):
return self._res.json()
@property
def code(self):
return self._res.code
@property
def url(self):
return self._res.request.absoluteURI.decode()
class HTTPClientService(service.SharedService):
"""A SharedService class that can make http requests to remote services.
I provide minimal get/post/put/delete API with automatic baseurl joining, and json data encoding
that is suitable for use from buildbot services.
"""
# Those could be in theory be overridden in master.cfg by using
# import buildbot.util.httpclientservice.HTTPClientService.PREFER_TREQ = True
# We prefer at the moment keeping it simple
PREFER_TREQ = False
MAX_THREADS = 20
def __init__(
self, base_url, auth=None, headers=None, verify=None, debug=False, skipEncoding=False
):
super().__init__()
self._session = HTTPSession(
self,
base_url,
auth=auth,
headers=headers,
verify=verify,
debug=debug,
skip_encoding=skipEncoding,
)
self._pool = None
self._txrequests_sessions = []
def updateHeaders(self, headers):
self._session.update_headers(headers)
@staticmethod
@deprecate.deprecated(versions.Version("buildbot", 4, 1, 0))
def checkAvailable(from_module):
pass
def startService(self):
if txrequests is not None:
self._txrequests_pool = ThreadPool(minthreads=1, maxthreads=self.MAX_THREADS)
# unclosed ThreadPool leads to reactor hangs at shutdown
# this is a problem in many situation, so better enforce pool stop here
self.master.reactor.addSystemEventTrigger(
"after",
"shutdown",
lambda: self._txrequests_pool.stop() if self._txrequests_pool.started else None,
)
self._txrequests_pool.start()
self._pool = HTTPConnectionPool(self.master.reactor)
self._pool.maxPersistentPerHost = self.MAX_THREADS
return super().startService()
@defer.inlineCallbacks
def stopService(self):
if txrequests is not None:
sessions = self._txrequests_sessions
self._txrequests_sessions = []
for session in sessions:
session.close()
self._txrequests_pool.stop()
if self._pool:
yield self._pool.closeCachedConnections()
yield super().stopService()
def _do_request(self, session, method, ep, **kwargs):
prefer_treq = self.PREFER_TREQ
if session.auth is not None and not isinstance(session.auth, tuple):
prefer_treq = False
if prefer_treq or txrequests is None:
return self._do_treq(session, method, ep, **kwargs)
else:
return self._do_txrequest(session, method, ep, **kwargs)
def _prepare_request(self, session, ep, kwargs):
if ep.startswith('http://') or ep.startswith('https://'):
url = ep
else:
assert ep == "" or ep.startswith("/"), "ep should start with /: " + ep
url = session.base_url + ep
if session.auth is not None and 'auth' not in kwargs:
kwargs['auth'] = session.auth
headers = kwargs.get('headers', {})
if session.headers is not None:
headers.update(session.headers)
kwargs['headers'] = headers
# we manually do the json encoding in order to automatically convert timestamps
# for txrequests and treq
json = kwargs.pop('json', None)
if isinstance(json, (dict, list)):
jsonStr = jsonmodule.dumps(json, default=toJson)
kwargs['headers']['Content-Type'] = 'application/json'
if session.skip_encoding:
kwargs['data'] = jsonStr
else:
jsonBytes = unicode2bytes(jsonStr)
kwargs['data'] = jsonBytes
return url, kwargs
@defer.inlineCallbacks
def _do_txrequest(self, session, method, ep, **kwargs):
url, kwargs = yield self._prepare_request(session, ep, kwargs)
if session.debug:
log.debug("http {url} {kwargs}", url=url, kwargs=kwargs)
def readContent(txrequests_session, res):
# this forces reading of the content inside the thread
_ = res.content
if session.debug:
log.debug("==> {code}: {content}", code=res.status_code, content=res.content)
return res
# read the whole content in the thread
kwargs['background_callback'] = readContent
if session.verify is False:
kwargs['verify'] = False
if session._txrequests_session is None:
session._txrequests_session = txrequests.Session(
pool=self._txrequests_pool, maxthreads=self.MAX_THREADS
)
# FIXME: remove items from the list as HTTPSession objects are destroyed
self._txrequests_sessions.append(session._txrequests_session)
res = yield session._txrequests_session.request(method, url, **kwargs)
return IHttpResponse(TxRequestsResponseWrapper(res))
@defer.inlineCallbacks
def _do_treq(self, session, method, ep, **kwargs):
url, kwargs = yield self._prepare_request(session, ep, kwargs)
# treq requires header values to be an array
if "headers" in kwargs:
kwargs['headers'] = {k: [v] for k, v in kwargs["headers"].items()}
if session._treq_agent is None:
session._trex_agent = Agent(self.master.reactor, pool=self._pool)
kwargs['agent'] = session._trex_agent
res = yield getattr(treq, method)(url, **kwargs)
return IHttpResponse(TreqResponseWrapper(res))
@deprecate.deprecated(versions.Version("buildbot", 4, 1, 0), "Use HTTPSession.get()")
def get(self, ep, **kwargs):
return self._do_request(self._session, 'get', ep, **kwargs)
@deprecate.deprecated(versions.Version("buildbot", 4, 1, 0), "Use HTTPSession.put()")
def put(self, ep, **kwargs):
return self._do_request(self._session, 'put', ep, **kwargs)
@deprecate.deprecated(versions.Version("buildbot", 4, 1, 0), "Use HTTPSession.delete()")
def delete(self, ep, **kwargs):
return self._do_request(self._session, 'delete', ep, **kwargs)
@deprecate.deprecated(versions.Version("buildbot", 4, 1, 0), "Use HTTPSession.post()")
def post(self, ep, **kwargs):
return self._do_request(self._session, 'post', ep, **kwargs)
class HTTPSession:
def __init__(
self, http, base_url, auth=None, headers=None, verify=None, debug=False, skip_encoding=False
):
assert not base_url.endswith("/"), "baseurl should not end with /: " + base_url
self.http = http
self.base_url = base_url
self.auth = auth
self.headers = headers
self.pool = None
self.verify = verify
self.debug = debug
self.skip_encoding = skip_encoding
self._treq_agent = None
self._txrequests_session = None
def update_headers(self, headers):
if self.headers is None:
self.headers = {}
self.headers.update(headers)
def get(self, ep, **kwargs):
return self.http._do_request(self, 'get', ep, **kwargs)
def put(self, ep, **kwargs):
return self.http._do_request(self, 'put', ep, **kwargs)
def delete(self, ep, **kwargs):
return self.http._do_request(self, 'delete', ep, **kwargs)
def post(self, ep, **kwargs):
return self.http._do_request(self, 'post', ep, **kwargs)
| 9,573 | Python | .py | 222 | 35.117117 | 100 | 0.651828 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
4,930 | config.py | buildbot_buildbot/master/buildbot/util/config.py | # This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright Buildbot Team Members
import re
from twisted.cred.checkers import FilePasswordDB
from twisted.python.components import registerAdapter
from zope.interface import implementer
from buildbot.interfaces import IConfigured
@implementer(IConfigured)
class _DefaultConfigured:
def __init__(self, value):
self.value = value
def getConfigDict(self):
return self.value
registerAdapter(_DefaultConfigured, object, IConfigured)
@implementer(IConfigured)
class _ListConfigured:
def __init__(self, value):
self.value = value
def getConfigDict(self):
return [IConfigured(e).getConfigDict() for e in self.value]
registerAdapter(_ListConfigured, list, IConfigured)
@implementer(IConfigured)
class _DictConfigured:
def __init__(self, value):
self.value = value
def getConfigDict(self):
return {k: IConfigured(v).getConfigDict() for k, v in self.value.items()}
registerAdapter(_DictConfigured, dict, IConfigured)
@implementer(IConfigured)
class _SREPatternConfigured:
def __init__(self, value):
self.value = value
def getConfigDict(self):
return {"name": 're', "pattern": self.value.pattern}
registerAdapter(_SREPatternConfigured, type(re.compile("")), IConfigured)
@implementer(IConfigured)
class ConfiguredMixin:
def getConfigDict(self):
return {'name': self.name}
@implementer(IConfigured)
class _FilePasswordDBConfigured:
def __init__(self, value):
pass
def getConfigDict(self):
return {'type': 'file'}
registerAdapter(_FilePasswordDBConfigured, FilePasswordDB, IConfigured)
| 2,305 | Python | .py | 58 | 35.948276 | 81 | 0.759585 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
4,931 | test_result_submitter.py | buildbot_buildbot/master/buildbot/util/test_result_submitter.py | # This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright Buildbot Team Members
from twisted.internet import defer
from twisted.python import log
from buildbot.util import deferwaiter
class TestResultSubmitter:
def __init__(self, batch_n=3000):
self._batch_n = batch_n
self._curr_batch = []
self._pending_batches = []
self._waiter = deferwaiter.DeferWaiter()
self._master = None
self._builderid = None
self._add_pass_fail_result = None # will be set to a callable if enabled
self._tests_passed = None
self._tests_failed = None
@defer.inlineCallbacks
def setup(self, step, description, category, value_unit):
builderid = yield step.build.getBuilderId()
yield self.setup_by_ids(
step.master,
builderid,
step.build.buildid,
step.stepid,
description,
category,
value_unit,
)
@defer.inlineCallbacks
def setup_by_ids(self, master, builderid, buildid, stepid, description, category, value_unit):
self._master = master
self._category = category
self._value_unit = value_unit
self._initialize_pass_fail_recording_if_needed()
self._builderid = builderid
self._setid = yield self._master.data.updates.addTestResultSet(
builderid, buildid, stepid, description, category, value_unit
)
@defer.inlineCallbacks
def finish(self):
self._submit_batch()
yield self._waiter.wait()
yield self._master.data.updates.completeTestResultSet(
self._setid, tests_passed=self._tests_passed, tests_failed=self._tests_failed
)
def get_test_result_set_id(self):
return self._setid
def _submit_batch(self):
batch = self._curr_batch
self._curr_batch = []
if not batch:
return
self._pending_batches.append(batch)
if self._waiter.has_waited():
return
self._waiter.add(self._process_batches())
@defer.inlineCallbacks
def _process_batches(self):
# at most one instance of this function may be running at the same time
while self._pending_batches:
batch = self._pending_batches.pop(0)
yield self._master.data.updates.addTestResults(self._builderid, self._setid, batch)
def _initialize_pass_fail_recording(self, function):
self._add_pass_fail_result = function
self._compute_pass_fail = True
self._tests_passed = 0
self._tests_failed = 0
def _initialize_pass_fail_recording_if_needed(self):
if self._category == 'pass_fail' and self._value_unit == 'boolean':
self._initialize_pass_fail_recording(self._add_pass_fail_result_category_pass_fail)
return
if self._category == 'pass_only':
self._initialize_pass_fail_recording(self._add_pass_fail_result_category_pass_only)
return
if self._category in ('fail_only', 'code_issue'):
self._initialize_pass_fail_recording(self._add_pass_fail_result_category_fail_only)
return
def _add_pass_fail_result_category_fail_only(self, value):
self._tests_failed += 1
def _add_pass_fail_result_category_pass_only(self, value):
self._tests_passed += 1
def _add_pass_fail_result_category_pass_fail(self, value):
try:
is_success = bool(int(value))
if is_success:
self._tests_passed += 1
else:
self._tests_failed += 1
except Exception as e:
log.err(e, 'When parsing test result success status')
def add_test_result(
self, value, test_name=None, test_code_path=None, line=None, duration_ns=None
):
if not isinstance(value, str):
raise TypeError('value must be a string')
result = {'value': value}
if test_name is not None:
if not isinstance(test_name, str):
raise TypeError('test_name must be a string')
result['test_name'] = test_name
if test_code_path is not None:
if not isinstance(test_code_path, str):
raise TypeError('test_code_path must be a string')
result['test_code_path'] = test_code_path
if line is not None:
if not isinstance(line, int):
raise TypeError('line must be an integer')
result['line'] = line
if duration_ns is not None:
if not isinstance(duration_ns, int):
raise TypeError('duration_ns must be an integer')
result['duration_ns'] = duration_ns
if self._add_pass_fail_result is not None:
self._add_pass_fail_result(value)
self._curr_batch.append(result)
if len(self._curr_batch) >= self._batch_n:
self._submit_batch()
| 5,580 | Python | .py | 129 | 34.27907 | 98 | 0.635743 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
4,932 | protocol.py | buildbot_buildbot/master/buildbot/util/protocol.py | # This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Portions Copyright Buildbot Team Members
from twisted.internet import protocol
class LineBuffer:
def __init__(self):
self._buffer = b''
def add_data(self, data):
# returns lines that have been processed, if any
lines = (self._buffer + data).split(b'\n')
self._buffer = lines.pop(-1)
for l in lines:
yield l.rstrip(b'\r')
def get_trailing_line(self):
if self._buffer:
ret = [self._buffer]
self._buffer = b''
return ret
return []
class LineProcessProtocol(protocol.ProcessProtocol):
def __init__(self):
self._out_buffer = LineBuffer()
self._err_buffer = LineBuffer()
def outReceived(self, data):
"""
Translates bytes into lines, and calls outLineReceived.
"""
for line in self._out_buffer.add_data(data):
self.outLineReceived(line)
def errReceived(self, data):
"""
Translates bytes into lines, and calls errLineReceived.
"""
for line in self._err_buffer.add_data(data):
self.errLineReceived(line)
def processEnded(self, reason):
for line in self._out_buffer.get_trailing_line():
self.outLineReceived(line)
for line in self._err_buffer.get_trailing_line():
self.errLineReceived(line)
def outLineReceived(self, line):
"""
Callback to which stdout lines will be sent.
Any line that is not terminated by a newline will be processed once the next line comes,
or when processEnded is called.
"""
raise NotImplementedError
def errLineReceived(self, line):
"""
Callback to which stdout lines will be sent.
Any line that is not terminated by a newline will be processed once the next line comes,
or when processEnded is called.
"""
raise NotImplementedError
| 2,613 | Python | .py | 65 | 33.153846 | 96 | 0.665483 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
4,933 | twisted.py | buildbot_buildbot/master/buildbot/util/twisted.py | # This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright Buildbot Team Members
from __future__ import annotations
from functools import wraps
from typing import TYPE_CHECKING
from twisted.internet import defer
if TYPE_CHECKING:
from typing import Any
from typing import Callable
from typing import Coroutine
from typing import TypeVar
from typing_extensions import ParamSpec
_T = TypeVar('_T')
_P = ParamSpec('_P')
def async_to_deferred(fn: Callable[_P, Coroutine[Any, Any, _T]]):
@wraps(fn)
def wrapper(*args: _P.args, **kwargs: _P.kwargs) -> defer.Deferred[_T]:
try:
return defer.ensureDeferred(fn(*args, **kwargs))
except Exception as e:
return defer.fail(e)
return wrapper
| 1,392 | Python | .py | 34 | 37.323529 | 79 | 0.740549 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
4,934 | kubeclientservice.py | buildbot_buildbot/master/buildbot/util/kubeclientservice.py | # This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright Buildbot Team Members
from __future__ import annotations
import abc
import base64
import os
from twisted.internet import defer
from twisted.internet import reactor
from twisted.internet.error import ProcessExitedAlready
from twisted.logger import Logger
from twisted.python.failure import Failure
from buildbot import config
from buildbot.util import service
from buildbot.util.protocol import LineProcessProtocol
log = Logger()
# this is a BuildbotService, so that it can be started and destroyed.
# this is needed to implement kubectl proxy lifecycle
class KubeConfigLoaderBase(service.BuildbotService):
name = "KubeConfig"
@abc.abstractmethod
def getConfig(self):
"""
@return dictionary with optional params
{
'master_url': 'https://kube_master.url',
'namespace': 'default_namespace',
'headers' {
'Authentication': XXX
}
# todo (quite hard to implement with treq):
'cert': 'optional client certificate used to connect to ssl'
'verify': 'kube master certificate authority to use to connect'
}
"""
def get_master_url(self):
# This function may be called before reconfigService() is called.
# The function must be overridden in case getConfig() is not fully setup in such situation.
return self.getConfig()["master_url"]
def getAuthorization(self):
return None
def __str__(self):
"""return unique str for SharedService"""
# hash is implemented from ComparableMixin
return f"{self.__class__.__name__}({hash(self)})"
class KubeHardcodedConfig(KubeConfigLoaderBase):
def reconfigService(
self,
master_url=None,
bearerToken=None,
basicAuth=None,
headers=None,
cert=None,
verify=None,
namespace="default",
):
self.config = {'master_url': master_url, 'namespace': namespace, 'headers': {}}
if headers is not None:
self.config['headers'] = headers
if basicAuth and bearerToken:
raise RuntimeError("set one of basicAuth and bearerToken, not both")
self.basicAuth = basicAuth
self.bearerToken = bearerToken
if cert is not None:
self.config['cert'] = cert
if verify is not None:
self.config['verify'] = verify
checkConfig = reconfigService
@defer.inlineCallbacks
def getAuthorization(self):
if self.basicAuth is not None:
basicAuth = yield self.renderSecrets(self.basicAuth)
authstring = f"{basicAuth['user']}:{basicAuth['password']}".encode()
encoded = base64.b64encode(authstring)
return f"Basic {encoded}"
if self.bearerToken is not None:
bearerToken = yield self.renderSecrets(self.bearerToken)
return f"Bearer {bearerToken}"
return None
def getConfig(self):
return self.config
class KubeCtlProxyConfigLoader(KubeConfigLoaderBase):
"""We use kubectl proxy to connect to kube master.
Parsing the config and setting up SSL is complex.
So for now, we use kubectl proxy to load the config and connect to master.
This will run the kube proxy as a subprocess, and return configuration with
http://localhost:PORT
"""
kube_ctl_proxy_cmd = ['kubectl', 'proxy'] # for tests override
class LocalPP(LineProcessProtocol):
def __init__(self):
super().__init__()
self.got_output_deferred = defer.Deferred()
self.terminated_deferred = defer.Deferred()
self.first_line = b""
def outLineReceived(self, line):
if not self.got_output_deferred.called:
self.got_output_deferred.callback(line)
def errLineReceived(self, line):
if not self.got_output_deferred.called:
self.got_output_deferred.errback(Failure(RuntimeError(line)))
def processEnded(self, status):
super().processEnded(status)
self.terminated_deferred.callback(None)
def checkConfig(self, proxy_port=8001, namespace="default"):
self.proxy_port = proxy_port
self.namespace = namespace
self.pp = None
self.process = None
@defer.inlineCallbacks
def ensure_subprocess_killed(self):
if self.pp is not None:
try:
self.process.signalProcess("TERM")
except ProcessExitedAlready:
pass # oh well
yield self.pp.terminated_deferred
@defer.inlineCallbacks
def reconfigService(self, proxy_port=8001, namespace="default"):
self.proxy_port = proxy_port
self.namespace = namespace
if self.running:
yield self.ensure_subprocess_killed()
yield self.start_subprocess()
@defer.inlineCallbacks
def start_subprocess(self):
self.pp = self.LocalPP()
self.process = reactor.spawnProcess(
self.pp,
self.kube_ctl_proxy_cmd[0],
[*self.kube_ctl_proxy_cmd, "-p", str(self.proxy_port)],
env=os.environ,
)
self.kube_proxy_output = yield self.pp.got_output_deferred
@defer.inlineCallbacks
def startService(self):
try:
yield self.start_subprocess()
except Exception:
yield self.ensure_subprocess_killed()
raise
yield super().startService()
@defer.inlineCallbacks
def stopService(self):
yield self.ensure_subprocess_killed()
yield super().stopService()
def getConfig(self):
return {'master_url': f"http://localhost:{self.proxy_port}", 'namespace': self.namespace}
class KubeInClusterConfigLoader(KubeConfigLoaderBase):
kube_dir = '/var/run/secrets/kubernetes.io/serviceaccount/'
kube_namespace_file = os.path.join(kube_dir, 'namespace')
kube_token_file = os.path.join(kube_dir, 'token')
kube_cert_file = os.path.join(kube_dir, 'ca.crt')
def checkConfig(self):
if not os.path.exists(self.kube_dir):
config.error(f"Not in kubernetes cluster (kube_dir not found: {self.kube_dir})")
def reconfigService(self):
self.config = {}
self.config['master_url'] = self.get_master_url()
self.config['verify'] = self.kube_cert_file
with open(self.kube_token_file, encoding="utf-8") as token_content:
token = token_content.read().strip()
self.config['headers'] = {'Authorization': f'Bearer {token}'.format(token)}
with open(self.kube_namespace_file, encoding="utf-8") as namespace_content:
self.config['namespace'] = namespace_content.read().strip()
def getConfig(self):
return self.config
def get_master_url(self):
return os.environ["KUBERNETES_PORT"].replace("tcp", "https")
class KubeClientService(service.SharedService):
name: str | None = "KubeClientService" # type: ignore[assignment]
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._config_id_to_workers = {}
self._worker_to_config = {}
self._lock = defer.DeferredLock()
@defer.inlineCallbacks
def register(self, worker, config):
yield self._lock.acquire()
try:
if worker.name in self._worker_to_config:
raise ValueError(f"Worker {worker.name} registered multiple times")
self._worker_to_config[worker.name] = config
config_id = id(config)
if config_id in self._config_id_to_workers:
self._config_id_to_workers[config_id].append(worker.name)
else:
self._config_id_to_workers[config_id] = [worker.name]
yield config.setServiceParent(self)
finally:
self._lock.release()
@defer.inlineCallbacks
def unregister(self, worker):
yield self._lock.acquire()
try:
if worker.name not in self._worker_to_config:
raise ValueError(f"Worker {worker.name} was not registered")
config = self._worker_to_config.pop(worker.name)
config_id = id(config)
worker_list = self._config_id_to_workers[config_id]
worker_list.remove(worker.name)
if not worker_list:
del self._config_id_to_workers[config_id]
yield config.disownServiceParent()
finally:
self._lock.release()
@defer.inlineCallbacks
def startService(self):
yield self._lock.acquire()
try:
yield super().startService()
finally:
self._lock.release()
@defer.inlineCallbacks
def stopService(self):
yield self._lock.acquire()
try:
yield super().stopService()
finally:
self._lock.release()
| 9,618 | Python | .py | 231 | 33.060606 | 99 | 0.647361 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
4,935 | debounce.py | buildbot_buildbot/master/buildbot/util/debounce.py | # This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright Buildbot Team Members
import functools
from twisted.internet import defer
from twisted.python import log
# debounce phases
PH_IDLE = 0
PH_WAITING = 1
PH_RUNNING = 2
PH_RUNNING_QUEUED = 3
class Debouncer:
__slots__ = [
'phase',
'timer',
'wait',
'function',
'stopped',
'completeDeferreds',
'get_reactor',
]
def __init__(self, wait, function, get_reactor):
# time to wait
self.wait = wait
# zero-argument callable to invoke
self.function = function
# current phase
self.phase = PH_IDLE
# Twisted timer for waiting
self.timer = None
# true if this instance is stopped
self.stopped = False
# deferreds to fire when the call is complete
self.completeDeferreds = []
# for tests
self.get_reactor = get_reactor
def __call__(self):
if self.stopped:
return
phase = self.phase
if phase == PH_IDLE:
self.timer = self.get_reactor().callLater(self.wait, self.invoke)
self.phase = PH_WAITING
elif phase == PH_RUNNING:
self.phase = PH_RUNNING_QUEUED
else: # phase == PH_WAITING or phase == PH_RUNNING_QUEUED:
pass
def __repr__(self):
return f"<debounced {self.function!r}, wait={self.wait!r}, phase={self.phase}>"
def invoke(self):
self.phase = PH_RUNNING
d = defer.maybeDeferred(self.function)
d.addErrback(log.err, 'from debounced function:')
@d.addCallback
def retry(_):
queued = self.phase == PH_RUNNING_QUEUED
self.phase = PH_IDLE
if queued and self.stopped:
# If stop() is called when debouncer is running with additional run queued,
# the queued run must still be invoked because the current run may be stale.
self.invoke()
return
while self.completeDeferreds:
self.completeDeferreds.pop(0).callback(None)
if queued:
self()
def start(self):
self.stopped = False
def stop(self):
self.stopped = True
if self.phase == PH_WAITING:
self.timer.cancel()
self.invoke()
# fall through with PH_RUNNING
if self.phase in (PH_RUNNING, PH_RUNNING_QUEUED):
d = defer.Deferred()
self.completeDeferreds.append(d)
return d
return defer.succeed(None)
class _Descriptor:
def __init__(self, fn, wait, attrName, get_reactor):
self.fn = fn
self.wait = wait
self.attrName = attrName
self.get_reactor = get_reactor
def __get__(self, instance, cls):
try:
db = getattr(instance, self.attrName)
except AttributeError:
db = Debouncer(
self.wait,
functools.partial(self.fn, instance),
functools.partial(self.get_reactor, instance),
)
setattr(instance, self.attrName, db)
return db
def _get_reactor_from_master(o):
return o.master.reactor
def method(wait, get_reactor=_get_reactor_from_master):
def wrap(fn):
stateName = "__debounce_" + fn.__name__ + "__"
return _Descriptor(fn, wait, stateName, get_reactor)
return wrap
| 4,090 | Python | .py | 114 | 27.631579 | 92 | 0.615073 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
4,936 | lineboundaries.py | buildbot_buildbot/master/buildbot/util/lineboundaries.py | # This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright Buildbot Team Members
import re
from twisted.logger import Logger
log = Logger()
class LineBoundaryFinder:
__slots__ = ['partialLine', 'warned']
# split at reasonable line length.
# too big lines will fill master's memory, and slow down the UI too much.
MAX_LINELENGTH = 4096
# the lookahead here (`(?=.)`) ensures that `\r` doesn't match at the end
# of the buffer
# we also convert cursor control sequence to newlines
# and ugly \b+ (use of backspace to implement progress bar)
newline_re = re.compile(r'(\r\n|\r(?=.)|\033\[u|\033\[[0-9]+;[0-9]+[Hf]|\033\[2J|\x08+)')
def __init__(self, callback=None):
self.partialLine = None
self.warned = False
def adjust_line(self, text):
if self.partialLine:
if len(self.partialLine) > self.MAX_LINELENGTH:
if not self.warned:
# Unfortunately we cannot give more hint as per which log that is
log.warn(
"Splitting long line: {line_start} {length} "
"(not warning anymore for this log)",
line_start=self.partialLine[:30],
length=len(self.partialLine),
)
self.warned = True
# switch the variables, and return previous _partialLine_,
# split every MAX_LINELENGTH plus a trailing \n
self.partialLine, text = text, self.partialLine
ret = []
while len(text) > self.MAX_LINELENGTH:
ret.append(text[: self.MAX_LINELENGTH])
text = text[self.MAX_LINELENGTH :]
ret.append(text)
result = "\n".join(ret) + "\n"
return result
text = self.partialLine + text
self.partialLine = None
text = self.newline_re.sub('\n', text)
if text:
if text[-1] != '\n':
i = text.rfind('\n')
if i >= 0:
i = i + 1
self.partialLine = text[i:]
text = text[:i]
else:
self.partialLine = text
return None
return text
return None
def append(self, text):
return self.adjust_line(text)
def flush(self):
if self.partialLine is not None:
return self.append('\n')
return None
| 3,166 | Python | .py | 73 | 32.589041 | 93 | 0.579955 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
4,937 | watchdog.py | buildbot_buildbot/master/buildbot/util/watchdog.py | # This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright Buildbot Team Members
class Watchdog:
def __init__(self, reactor, fn, timeout):
self._reactor = reactor
self._fn = fn
self._timeout = timeout
self._delayed_call = None
def _timed_out(self):
self._delayed_call = None
self._fn()
def start(self):
if self._delayed_call is None:
self._delayed_call = self._reactor.callLater(self._timeout, self._timed_out)
def stop(self):
if self._delayed_call is not None:
self._delayed_call.cancel()
def notify(self):
if self._delayed_call is None:
return
self._delayed_call.reset(self._timeout)
| 1,353 | Python | .py | 33 | 35.666667 | 88 | 0.694593 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
4,938 | backoff.py | buildbot_buildbot/master/buildbot/util/backoff.py | # This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright Buildbot Team Members
import time
from twisted.internet import defer
from buildbot.util import asyncSleep
class BackoffTimeoutExceededError(Exception):
pass
class ExponentialBackoffEngine:
def __init__(self, start_seconds, multiplier, max_wait_seconds):
if start_seconds < 0:
raise ValueError('start_seconds cannot be negative')
if multiplier < 0:
raise ValueError('multiplier cannot be negative')
if max_wait_seconds < 0:
raise ValueError('max_wait_seconds cannot be negative')
self.start_seconds = start_seconds
self.multiplier = multiplier
self.max_wait_seconds = max_wait_seconds
self.on_success()
def on_success(self):
self.current_total_wait_seconds = 0
self.current_wait_seconds = self.start_seconds
def wait_on_failure(self):
raise NotImplementedError()
def calculate_wait_on_failure_seconds(self):
if self.current_total_wait_seconds >= self.max_wait_seconds:
raise BackoffTimeoutExceededError()
seconds = self.current_wait_seconds
self.current_wait_seconds *= self.multiplier
if self.current_total_wait_seconds + seconds < self.max_wait_seconds:
self.current_total_wait_seconds += seconds
else:
seconds = self.max_wait_seconds - self.current_total_wait_seconds
self.current_total_wait_seconds = self.max_wait_seconds
return seconds
class ExponentialBackoffEngineSync(ExponentialBackoffEngine):
def wait_on_failure(self):
seconds = self.calculate_wait_on_failure_seconds()
time.sleep(seconds)
class ExponentialBackoffEngineAsync(ExponentialBackoffEngine):
def __init__(self, reactor, *args, **kwargs):
super().__init__(*args, **kwargs)
self.reactor = reactor
@defer.inlineCallbacks
def wait_on_failure(self):
seconds = self.calculate_wait_on_failure_seconds()
yield asyncSleep(seconds, reactor=self.reactor)
| 2,713 | Python | .py | 59 | 39.661017 | 79 | 0.718134 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
4,939 | codebase.py | buildbot_buildbot/master/buildbot/util/codebase.py | # This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright Buildbot Team Members
from twisted.internet import defer
class AbsoluteSourceStampsMixin:
# record changes and revisions per codebase
_lastCodebases = None
@defer.inlineCallbacks
def getCodebaseDict(self, codebase):
assert self.codebases
if self._lastCodebases is None:
self._lastCodebases = yield self.getState('lastCodebases', {})
# may fail with KeyError
return self._lastCodebases.get(codebase, self.codebases[codebase])
@defer.inlineCallbacks
def recordChange(self, change):
codebase = yield self.getCodebaseDict(change.codebase)
lastChange = codebase.get('lastChange', -1)
if change.number > lastChange:
self._lastCodebases[change.codebase] = {
'repository': change.repository,
'branch': change.branch,
'revision': change.revision,
'lastChange': change.number,
}
yield self.setState('lastCodebases', self._lastCodebases)
| 1,712 | Python | .py | 37 | 39.810811 | 79 | 0.712312 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
4,940 | bbcollections.py | buildbot_buildbot/master/buildbot/util/bbcollections.py | # This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright Buildbot Team Members
# this is here for compatibility
from collections import defaultdict # noqa: F401
class KeyedSets:
def __init__(self):
self.d = {}
def add(self, key, value):
if key not in self.d:
self.d[key] = set()
self.d[key].add(value)
def discard(self, key, value):
if key in self.d:
self.d[key].discard(value)
if not self.d[key]:
del self.d[key]
def __contains__(self, key):
return key in self.d
def __getitem__(self, key):
return self.d.get(key, set())
def pop(self, key):
if key in self.d:
return self.d.pop(key)
return set()
| 1,384 | Python | .py | 36 | 32.972222 | 79 | 0.67289 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
4,941 | render_description.py | buildbot_buildbot/master/buildbot/util/render_description.py | # This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright Buildbot Team Members
def render_description(description, format):
if format is None:
return None
if format == "markdown":
import markdown
return markdown.markdown(description)
raise RuntimeError(f"Unsupported description format {format}")
| 962 | Python | .py | 21 | 42.952381 | 79 | 0.768657 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
4,942 | git.py | buildbot_buildbot/master/buildbot/util/git.py | # This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright Buildbot Team Members
from __future__ import annotations
import os
import re
import stat
from pathlib import Path
from typing import TYPE_CHECKING
from typing import ClassVar
from typing import Sequence
from packaging.version import parse as parse_version
from twisted.internet import defer
from twisted.python import log
from buildbot import config
from buildbot.process import buildstep
from buildbot.process import remotecommand
from buildbot.process.properties import Properties
from buildbot.steps.worker import CompositeStepMixin
from buildbot.util import ComparableMixin
from buildbot.util import bytes2unicode
from buildbot.util.git_credential import GitCredentialOptions
from buildbot.util.misc import writeLocalFile
from buildbot.util.twisted import async_to_deferred
if TYPE_CHECKING:
from buildbot.changes.gitpoller import GitPoller
from buildbot.interfaces import IRenderable
RC_SUCCESS = 0
def getSshArgsForKeys(keyPath, knownHostsPath):
args = ['-o', 'BatchMode=yes']
if keyPath is not None:
args += ['-i', keyPath]
if knownHostsPath is not None:
args += ['-o', f'UserKnownHostsFile={knownHostsPath}']
return args
def escapeShellArgIfNeeded(arg):
if re.match(r"^[a-zA-Z0-9_-]+$", arg):
return arg
return f'"{arg}"'
def getSshCommand(keyPath, knownHostsPath):
command = ['ssh', *getSshArgsForKeys(keyPath, knownHostsPath)]
command = [escapeShellArgIfNeeded(arg) for arg in command]
return ' '.join(command)
def check_ssh_config(
logname: str,
ssh_private_key: IRenderable | None,
ssh_host_key: IRenderable | None,
ssh_known_hosts: IRenderable | None,
):
if ssh_host_key is not None and ssh_private_key is None:
config.error(f'{logname}: sshPrivateKey must be provided in order use sshHostKey')
if ssh_known_hosts is not None and ssh_private_key is None:
config.error(f'{logname}: sshPrivateKey must be provided in order use sshKnownHosts')
if ssh_host_key is not None and ssh_known_hosts is not None:
config.error(f'{logname}: only one of sshKnownHosts and sshHostKey can be provided')
class GitMixin:
def setupGit(self):
self.gitInstalled = False
self.supportsBranch = False
self.supportsProgress = False
self.supportsSubmoduleForce = False
self.supportsSubmoduleCheckout = False
self.supportsSshPrivateKeyAsEnvOption = False
self.supportsSshPrivateKeyAsConfigOption = False
self.supportsFilters = False
self.supports_lsremote_symref = False
self.supports_credential_store = False
def parseGitFeatures(self, version_stdout):
match = re.match(r"^git version (\d+(\.\d+)*)", version_stdout)
if not match:
return
version = parse_version(match.group(1))
self.gitInstalled = True
if version >= parse_version("1.6.5"):
self.supportsBranch = True
if version >= parse_version("1.7.2"):
self.supportsProgress = True
if version >= parse_version("1.7.6"):
self.supportsSubmoduleForce = True
if version >= parse_version("1.7.8"):
self.supportsSubmoduleCheckout = True
if version >= parse_version("1.7.9"):
self.supports_credential_store = True
if version >= parse_version("2.3.0"):
self.supportsSshPrivateKeyAsEnvOption = True
if version >= parse_version("2.8.0"):
# https://github.com/git/git/blob/v2.8.0/Documentation/RelNotes/2.8.0.txt#L72-L73
self.supports_lsremote_symref = True
if version >= parse_version("2.10.0"):
self.supportsSshPrivateKeyAsConfigOption = True
if version >= parse_version("2.27.0"):
self.supportsFilters = True
def adjustCommandParamsForSshPrivateKey(
self, command, env, keyPath, sshWrapperPath=None, knownHostsPath=None
):
ssh_command = getSshCommand(keyPath, knownHostsPath)
if self.supportsSshPrivateKeyAsConfigOption:
command.append('-c')
command.append(f'core.sshCommand={ssh_command}')
elif self.supportsSshPrivateKeyAsEnvOption:
env['GIT_SSH_COMMAND'] = ssh_command
else:
if sshWrapperPath is None:
raise RuntimeError('Only SSH wrapper script is supported but path not given')
env['GIT_SSH'] = sshWrapperPath
def getSshWrapperScriptContents(keyPath, knownHostsPath=None):
ssh_command = getSshCommand(keyPath, knownHostsPath)
# note that this works on windows if using git with MINGW embedded.
return f'#!/bin/sh\n{ssh_command} "$@"\n'
def getSshKnownHostsContents(hostKey: str) -> str:
host_name = '*'
return f'{host_name} {hostKey}'
def ensureSshKeyNewline(privateKey: str) -> str:
"""Ensure key has trailing newline
Providers can be configured to strip newlines from secrets. This feature
breaks SSH key use within the Git module. This helper function ensures that
when an ssh key is provided for a git step that is contains the trailing
newline.
"""
if privateKey.endswith("\n") or privateKey.endswith("\r") or privateKey.endswith("\r\n"):
return privateKey
return privateKey + "\n"
class GitStepMixin(GitMixin):
_git_auth: GitStepAuth
def setupGitStep(self):
self.setupGit()
if not self.repourl:
config.error("Git: must provide repourl.")
if not hasattr(self, '_git_auth'):
self._git_auth = GitStepAuth(self)
def setup_git_auth(
self,
ssh_private_key: IRenderable | None,
ssh_host_key: IRenderable | None,
ssh_known_hosts: IRenderable | None,
git_credential_options: GitCredentialOptions | None = None,
) -> None:
self._git_auth = GitStepAuth(
self,
ssh_private_key,
ssh_host_key,
ssh_known_hosts,
git_credential_options=git_credential_options,
)
def _get_auth_data_workdir(self) -> str:
raise NotImplementedError()
@defer.inlineCallbacks
def _dovccmd(self, command, abandonOnFailure=True, collectStdout=False, initialStdin=None):
full_command = ['git']
full_env = self.env.copy() if self.env else {}
if self.config is not None:
for name, value in self.config.items():
full_command.append('-c')
full_command.append(f'{name}={value}')
if command and self._git_auth.is_auth_needed_for_git_command(command[0]):
self._git_auth.adjust_git_command_params_for_auth(
full_command,
full_env,
self._get_auth_data_workdir(),
self,
)
full_command.extend(command)
# check for the interruptSignal flag
sigtermTime = None
interruptSignal = None
# If possible prefer to send a SIGTERM to git before we send a SIGKILL.
# If we send a SIGKILL, git is prone to leaving around stale lockfiles.
# By priming it with a SIGTERM first we can ensure that it has a chance to shut-down
# gracefully before getting terminated
if not self.workerVersionIsOlderThan("shell", "2.16"):
# git should shut-down quickly on SIGTERM. If it doesn't don't let it
# stick around for too long because this is on top of any timeout
# we have hit.
sigtermTime = 1
else:
# Since sigtermTime is unavailable try to just use SIGTERM by itself instead of
# killing. This should be safe.
if self.workerVersionIsOlderThan("shell", "2.15"):
log.msg(
"NOTE: worker does not allow master to specify "
"interruptSignal. This may leave a stale lockfile around "
"if the command is interrupted/times out\n"
)
else:
interruptSignal = 'TERM'
cmd = remotecommand.RemoteShellCommand(
self.workdir,
full_command,
env=full_env,
logEnviron=self.logEnviron,
timeout=self.timeout,
sigtermTime=sigtermTime,
interruptSignal=interruptSignal,
collectStdout=collectStdout,
initialStdin=initialStdin,
)
cmd.useLog(self.stdio_log, False)
yield self.runCommand(cmd)
if abandonOnFailure and cmd.didFail():
log.msg(f"Source step failed while running command {cmd}")
raise buildstep.BuildStepFailed()
if collectStdout:
return cmd.stdout
return cmd.rc
@defer.inlineCallbacks
def checkFeatureSupport(self):
stdout = yield self._dovccmd(['--version'], collectStdout=True)
self.parseGitFeatures(stdout)
return self.gitInstalled
class AbstractGitAuth(ComparableMixin):
compare_attrs: ClassVar[Sequence[str]] = (
"ssh_private_key",
"ssh_host_key",
"ssh_known_hosts",
"git_credential_options",
)
def __init__(
self,
ssh_private_key: IRenderable | None = None,
ssh_host_key: IRenderable | None = None,
ssh_known_hosts: IRenderable | None = None,
git_credential_options: GitCredentialOptions | None = None,
) -> None:
self.did_download_auth_files = False
self.ssh_private_key = ssh_private_key
self.ssh_host_key = ssh_host_key
self.ssh_known_hosts = ssh_known_hosts
self.git_credential_options = git_credential_options
check_ssh_config('Git', self.ssh_private_key, self.ssh_host_key, self.ssh_known_hosts)
@property
def is_auth_needed(self) -> bool:
return self.ssh_private_key is not None or self.git_credential_options is not None
def is_auth_needed_for_git_command(self, git_command: str) -> bool:
if not git_command:
return False
if not self.is_auth_needed:
return False
git_commands_that_need_auth = [
'clone',
'credential',
'fetch',
'ls-remote',
'push',
'submodule',
]
if git_command in git_commands_that_need_auth:
return True
return False
@property
def _path_module(self):
raise NotImplementedError()
@property
def _master(self):
raise NotImplementedError()
def _get_ssh_private_key_path(self, ssh_data_path: str) -> str:
return self._path_module.join(ssh_data_path, 'ssh-key')
def _get_ssh_host_key_path(self, ssh_data_path: str) -> str:
return self._path_module.join(ssh_data_path, 'ssh-known-hosts')
def _get_ssh_wrapper_script_path(self, ssh_data_path: str) -> str:
return self._path_module.join(ssh_data_path, 'ssh-wrapper.sh')
def _get_credential_store_file_path(self, ssh_data_path):
return self._path_module.join(ssh_data_path, '.git-credentials')
def _adjust_command_params_for_ssh_private_key(
self,
full_command: list[str],
full_env: dict[str, str],
workdir: str,
git_mixin: GitMixin,
) -> None:
if self.ssh_private_key is None:
return
key_path = self._get_ssh_private_key_path(workdir)
host_key_path = None
if self.ssh_host_key is not None or self.ssh_known_hosts is not None:
host_key_path = self._get_ssh_host_key_path(workdir)
ssh_wrapper_path = self._get_ssh_wrapper_script_path(workdir)
git_mixin.adjustCommandParamsForSshPrivateKey(
full_command,
full_env,
key_path,
ssh_wrapper_path,
host_key_path,
)
def _adjust_command_params_for_credential_store(
self,
full_command: list[str],
workdir: str,
git_mixin: GitMixin,
):
if self.git_credential_options is None:
return
if not git_mixin.supports_credential_store:
raise RuntimeError('git credential-store is not supported')
credentials_path = self._get_credential_store_file_path(workdir)
# This will unset the `credential.helper` config for this command
# so that system/global credential store is not used
# NOTE: This could be optional allowing credential retrieval from system sources
# However, it would need the store process (`credential approve`) to pass it
# as `credential approve` will store the credential in ALL credential helpers
full_command.extend([
'-c',
'credential.helper=',
])
full_command.extend([
'-c',
f'credential.helper=store "--file={credentials_path}"',
])
if self.git_credential_options.use_http_path is not None:
# Whether or not to only use domain for credential lookup
value = 'true' if self.git_credential_options.use_http_path else 'false'
full_command.extend([
'-c',
f'credential.useHttpPath={value}',
])
def adjust_git_command_params_for_auth(
self,
full_command: list[str],
full_env: dict[str, str],
workdir: str,
git_mixin: GitMixin,
) -> None:
self._adjust_command_params_for_ssh_private_key(
full_command,
full_env,
workdir=workdir,
git_mixin=git_mixin,
)
self._adjust_command_params_for_credential_store(
full_command,
workdir=workdir,
git_mixin=git_mixin,
)
@async_to_deferred
async def _dovccmd(
self,
command: list[str],
initial_stdin: str | None = None,
workdir: str | None = None,
) -> None:
raise NotImplementedError()
async def _download_file(
self,
path: str,
content: str,
mode: int,
workdir: str | None = None,
) -> None:
raise NotImplementedError()
@async_to_deferred
async def _download_ssh_files(
self,
private_key: str,
host_key: str | None,
known_hosts: str | None,
workdir: str,
download_wrapper_script: bool = False,
) -> None:
private_key_path = self._get_ssh_private_key_path(workdir)
private_key = ensureSshKeyNewline(private_key)
await self._download_file(
private_key_path,
private_key,
mode=stat.S_IRUSR,
workdir=workdir,
)
known_hosts_path = self._get_ssh_host_key_path(workdir)
known_hosts_contents = None
if known_hosts is not None:
known_hosts_contents = known_hosts
elif host_key is not None:
known_hosts_contents = getSshKnownHostsContents(host_key)
if known_hosts_contents is not None:
await self._download_file(
known_hosts_path,
known_hosts_contents,
mode=stat.S_IRUSR,
workdir=workdir,
)
if download_wrapper_script:
script_path = self._get_ssh_wrapper_script_path(workdir)
script_contents = getSshWrapperScriptContents(
private_key_path,
(known_hosts_path if known_hosts_contents is not None else None),
)
await self._download_file(
script_path,
script_contents,
mode=stat.S_IRWXU,
workdir=workdir,
)
@async_to_deferred
async def _download_credentials(
self,
credentials: list[str],
workdir: str,
) -> None:
for creds in credentials:
# Using credential approve here instead of directly writing to the file
# as recommended by Git doc (https://git-scm.com/docs/git-credential-store#_storage_format)
# "Do not view or edit the file with editors."
await self._dovccmd(
['credential', 'approve'],
initial_stdin=creds,
workdir=workdir,
)
@async_to_deferred
async def download_auth_files_if_needed(
self,
workdir: str,
download_wrapper_script: bool = False,
) -> int:
p = Properties()
p.master = self._master
private_key: str | None = await p.render(self.ssh_private_key)
host_key: str | None = await p.render(self.ssh_host_key)
known_hosts: str | None = await p.render(self.ssh_known_hosts)
if private_key is not None:
await self._download_ssh_files(
private_key,
host_key,
known_hosts,
workdir,
download_wrapper_script,
)
self.did_download_auth_files = True
if self.git_credential_options is not None:
credentials: list[str] = []
for creds in self.git_credential_options.credentials:
rendered: str | None = await p.render(creds)
if rendered:
credentials.append(rendered)
if credentials:
await self._download_credentials(credentials, workdir)
self.did_download_auth_files = True
return RC_SUCCESS
@async_to_deferred
async def remove_auth_files_if_needed(self, workdir: str) -> int:
raise NotImplementedError()
class GitStepAuth(AbstractGitAuth):
def __init__(
self,
# step must implement all these types
step: buildstep.BuildStep | GitStepMixin | CompositeStepMixin,
ssh_private_key: IRenderable | None = None,
ssh_host_key: IRenderable | None = None,
ssh_known_hosts: IRenderable | None = None,
git_credential_options: GitCredentialOptions | None = None,
) -> None:
self.step = step
super().__init__(ssh_private_key, ssh_host_key, ssh_known_hosts, git_credential_options)
def _get_auth_data_path(self, data_workdir: str) -> str:
# we can't use the workdir for temporary ssh-related files, because
# it's needed when cloning repositories and git does not like the
# destination directory being non-empty. We have to use separate
# temporary directory for that data to ensure the confidentiality of it.
# So instead of
# '{path}/{to}/{workerbuilddir}/{workdir}/.buildbot-ssh-key'
# we put the key in
# '{path}/{to}/.{workerbuilddir}.{workdir}.buildbot/ssh-key'.
# basename and dirname interpret the last element being empty for paths
# ending with a slash
assert (
isinstance(self.step, buildstep.BuildStep)
and self.step.build is not None
and self.step.build.builder.config is not None
)
workerbuilddir = bytes2unicode(self.step.build.builder.config.workerbuilddir)
workdir = data_workdir.rstrip('/\\')
if self._path_module.isabs(workdir):
parent_path = self._path_module.dirname(workdir)
else:
assert self.step.worker is not None
parent_path = self._path_module.join(
self.step.worker.worker_basedir, self._path_module.dirname(workdir)
)
basename = f'.{workerbuilddir}.{self._path_module.basename(workdir)}.buildbot'
return self._path_module.join(parent_path, basename)
def adjust_git_command_params_for_auth(
self,
full_command: list[str],
full_env: dict[str, str],
workdir: str,
git_mixin: GitMixin,
) -> None:
auth_data_path = self._get_auth_data_path(workdir)
super().adjust_git_command_params_for_auth(
full_command,
full_env,
workdir=auth_data_path,
git_mixin=git_mixin,
)
@property
def _path_module(self):
assert isinstance(self.step, buildstep.BuildStep) and self.step.build is not None
return self.step.build.path_module
@property
def _master(self):
assert isinstance(self.step, buildstep.BuildStep) and self.step.master is not None
return self.step.master
@async_to_deferred
async def _download_file(
self,
path: str,
content: str,
mode: int,
workdir: str | None = None,
) -> None:
assert isinstance(self.step, CompositeStepMixin)
await self.step.downloadFileContentToWorker(
path,
content,
mode=mode,
workdir=workdir,
)
@async_to_deferred
async def _dovccmd(
self,
command: list[str],
initial_stdin: str | None = None,
workdir: str | None = None,
) -> None:
assert isinstance(self.step, GitStepMixin)
await self.step._dovccmd(
command=command,
initialStdin=initial_stdin,
)
@async_to_deferred
async def download_auth_files_if_needed(
self,
workdir: str,
download_wrapper_script: bool = False,
) -> int:
if self.ssh_private_key is None and self.git_credential_options is None:
return RC_SUCCESS
assert isinstance(self.step, CompositeStepMixin) and isinstance(self.step, GitMixin)
workdir = self._get_auth_data_path(workdir)
await self.step.runMkdir(workdir)
return_code = await super().download_auth_files_if_needed(
workdir=workdir,
download_wrapper_script=(
download_wrapper_script or not self.step.supportsSshPrivateKeyAsEnvOption
),
)
return return_code
@async_to_deferred
async def remove_auth_files_if_needed(self, workdir: str) -> int:
if not self.did_download_auth_files:
return RC_SUCCESS
assert isinstance(self.step, CompositeStepMixin)
await self.step.runRmdir(self._get_auth_data_path(workdir))
return RC_SUCCESS
class GitServiceAuth(AbstractGitAuth):
def __init__(
self,
service: GitPoller,
ssh_private_key: IRenderable | None = None,
ssh_host_key: IRenderable | None = None,
ssh_known_hosts: IRenderable | None = None,
git_credential_options: GitCredentialOptions | None = None,
) -> None:
self._service = service
super().__init__(ssh_private_key, ssh_host_key, ssh_known_hosts, git_credential_options)
@property
def _path_module(self):
return os.path
@property
def _master(self):
assert self._service.master is not None
return self._service.master
@async_to_deferred
async def _dovccmd(
self,
command: list[str],
initial_stdin: str | None = None,
workdir: str | None = None,
) -> None:
await self._service._dovccmd(
command=command[0],
args=command[1:],
initial_stdin=initial_stdin,
path=workdir,
auth_files_path=workdir, # this is ... not great
)
@async_to_deferred
async def _download_file(
self,
path: str,
content: str,
mode: int,
workdir: str | None = None,
) -> None:
writeLocalFile(path, content, mode=mode)
@async_to_deferred
async def remove_auth_files_if_needed(self, workdir: str) -> int:
if not self.did_download_auth_files:
return RC_SUCCESS
Path(self._get_ssh_private_key_path(workdir)).unlink(missing_ok=True)
Path(self._get_ssh_host_key_path(workdir)).unlink(missing_ok=True)
return RC_SUCCESS
| 24,519 | Python | .py | 610 | 30.998361 | 103 | 0.627769 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
4,943 | raml.py | buildbot_buildbot/master/buildbot/util/raml.py | # This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright Buildbot Team Members
import copy
import json
import os
from collections import OrderedDict
import yaml
# minimalistic raml loader. Support !include tags, and mapping as OrderedDict
class RamlLoader(yaml.SafeLoader):
pass
def construct_include(loader, node):
path = os.path.join(os.path.dirname(loader.stream.name), node.value)
with open(path, encoding='utf-8') as f:
return yaml.load(f, Loader=RamlLoader)
def construct_mapping(loader, node):
loader.flatten_mapping(node)
return OrderedDict(loader.construct_pairs(node))
RamlLoader.add_constructor(yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, construct_mapping)
RamlLoader.add_constructor('!include', construct_include)
class RamlSpec:
"""
This class loads the raml specification, and expose useful
aspects of the spec
Main usage for now is for the doc, but it can be extended to make sure
raml spec matches other spec implemented in the tests
"""
def __init__(self):
fn = os.path.join(os.path.dirname(__file__), os.pardir, 'spec', 'api.raml')
with open(fn, encoding='utf-8') as f:
self.api = yaml.load(f, Loader=RamlLoader)
with open(fn, encoding='utf-8') as f:
self.rawraml = f.read()
endpoints = {}
self.endpoints_by_type = {}
self.rawendpoints = {}
self.endpoints = self.parse_endpoints(endpoints, "", self.api)
self.types = self.parse_types()
def parse_endpoints(self, endpoints, base, api, uriParameters=None):
if uriParameters is None:
uriParameters = OrderedDict()
for k, v in api.items():
if k.startswith("/"):
ep = base + k
p = copy.deepcopy(uriParameters)
if v is not None:
p.update(v.get("uriParameters", {}))
v["uriParameters"] = p
endpoints[ep] = v
self.parse_endpoints(endpoints, ep, v, p)
elif k in ['get', 'post']:
if 'is' not in v:
continue
for _is in v['is']:
if not isinstance(_is, dict):
raise RuntimeError(f'Unexpected "is" target {type(_is)}: {_is}')
if 'bbget' in _is:
try:
v['eptype'] = _is['bbget']['bbtype']
except TypeError as e:
raise RuntimeError(f"Unexpected 'is' target {_is['bbget']}") from e
self.endpoints_by_type.setdefault(v['eptype'], {})
self.endpoints_by_type[v['eptype']][base] = api
if 'bbgetraw' in _is:
self.rawendpoints.setdefault(base, {})
self.rawendpoints[base] = api
return endpoints
def reindent(self, s, indent):
return s.replace("\n", "\n" + " " * indent)
def format_json(self, j, indent):
j = json.dumps(j, indent=4).replace(", \n", ",\n")
return self.reindent(j, indent)
def parse_types(self):
types = self.api['types']
return types
def iter_actions(self, endpoint):
ACTIONS_MAGIC = '/actions/'
for k, v in endpoint.items():
if k.startswith(ACTIONS_MAGIC):
k = k[len(ACTIONS_MAGIC) :]
v = v['post']
# simplify the raml tree for easier processing
v['body'] = v['body']['application/json'].get('properties', {})
yield (k, v)
| 4,272 | Python | .py | 95 | 34.936842 | 95 | 0.600578 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
4,944 | eventual.py | buildbot_buildbot/master/buildbot/util/eventual.py | # This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright Buildbot Team Members
#
# copied from foolscap
from twisted.internet import defer
from twisted.internet import reactor
from twisted.python import log
class _SimpleCallQueue:
_reactor = reactor
def __init__(self):
self._events = []
self._flushObservers = []
self._timer = None
self._in_turn = False
def append(self, cb, args, kwargs):
self._events.append((cb, args, kwargs))
if not self._timer:
self._timer = self._reactor.callLater(0, self._turn)
def _turn(self):
self._timer = None
self._in_turn = True
# flush all the messages that are currently in the queue. If anything
# gets added to the queue while we're doing this, those events will
# be put off until the next turn.
events = self._events
self._events = []
for cb, args, kwargs in events:
try:
cb(*args, **kwargs)
except Exception:
log.err()
self._in_turn = False
if self._events and not self._timer:
self._timer = self._reactor.callLater(0, self._turn)
if not self._events:
observers = self._flushObservers
self._flushObservers = []
for o in observers:
o.callback(None)
def flush(self):
if not self._events and not self._in_turn:
return defer.succeed(None)
d = defer.Deferred()
self._flushObservers.append(d)
return d
_theSimpleQueue = _SimpleCallQueue()
def eventually(cb, *args, **kwargs):
_theSimpleQueue.append(cb, args, kwargs)
def fireEventually(value=None):
d = defer.Deferred()
eventually(d.callback, value)
return d
def flushEventualQueue(_ignored=None):
return _theSimpleQueue.flush()
def _setReactor(r=None):
# This sets the reactor used to schedule future events to r. If r is None
# (the default), the reactor is reset to its default value.
# This should only be used for unit tests.
if r is None:
r = reactor
_theSimpleQueue._reactor = r
| 2,794 | Python | .py | 73 | 31.821918 | 79 | 0.663337 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
4,945 | pullrequest.py | buildbot_buildbot/master/buildbot/util/pullrequest.py | # This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright Buildbot Team Members
from __future__ import annotations
from fnmatch import fnmatch
class PullRequestMixin:
external_property_whitelist: list[str] = []
external_property_denylist: list[str] = []
def extractProperties(self, payload):
def flatten(properties, base, info_dict):
for k, v in info_dict.items():
name = ".".join([base, k])
if name in self.external_property_denylist:
continue
if isinstance(v, dict):
flatten(properties, name, v)
elif any(fnmatch(name, expr) for expr in self.external_property_whitelist):
properties[name] = v
properties = {}
flatten(properties, self.property_basename, payload)
return properties
| 1,492 | Python | .py | 32 | 39.84375 | 91 | 0.690034 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
4,946 | maildir.py | buildbot_buildbot/master/buildbot/util/maildir.py | # This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright Buildbot Team Members
"""
This is a class which watches a maildir for new messages. It uses the
linux dirwatcher API (if available) to look for new files. The
.messageReceived method is invoked with the filename of the new message,
relative to the top of the maildir (so it will look like "new/blahblah").
"""
from __future__ import annotations
import os
from twisted.application import internet
from twisted.internet import defer
from twisted.internet import reactor
# We have to put it here, since we use it to provide feedback
from twisted.python import log
from twisted.python import runtime
from buildbot.util import service
dnotify = None
try:
import dnotify # type: ignore[no-redef]
except ImportError:
log.msg("unable to import dnotify, so Maildir will use polling instead")
class NoSuchMaildir(Exception):
pass
class MaildirService(service.BuildbotService):
pollInterval = 10 # only used if we don't have DNotify
name: str | None = 'MaildirService' # type: ignore
def __init__(self, basedir=None):
super().__init__()
if basedir:
self.setBasedir(basedir)
self.files = []
self.dnotify = None
self.timerService = None
def setBasedir(self, basedir):
# some users of MaildirService (scheduler.Try_Jobdir, in particular)
# don't know their basedir until setServiceParent, since it is
# relative to the buildmaster's basedir. So let them set it late. We
# don't actually need it until our own startService.
self.basedir = basedir
self.newdir = os.path.join(self.basedir, "new")
self.curdir = os.path.join(self.basedir, "cur")
@defer.inlineCallbacks
def startService(self):
if not os.path.isdir(self.newdir) or not os.path.isdir(self.curdir):
raise NoSuchMaildir(f"invalid maildir '{self.basedir}'")
try:
if dnotify:
# we must hold an fd open on the directory, so we can get
# notified when it changes.
self.dnotify = dnotify.DNotify(
self.newdir, self.dnotify_callback, [dnotify.DNotify.DN_CREATE]
)
except (OSError, OverflowError):
# IOError is probably linux<2.4.19, which doesn't support
# dnotify. OverflowError will occur on some 64-bit machines
# because of a python bug
log.msg("DNotify failed, falling back to polling")
if not self.dnotify:
self.timerService = internet.TimerService(self.pollInterval, self.poll)
yield self.timerService.setServiceParent(self)
self.poll()
yield super().startService()
def dnotify_callback(self):
log.msg("dnotify noticed something, now polling")
# give it a moment. I found that qmail had problems when the message
# was removed from the maildir instantly. It shouldn't, that's what
# maildirs are made for. I wasn't able to eyeball any reason for the
# problem, and safecat didn't behave the same way, but qmail reports
# "Temporary_error_on_maildir_delivery" (qmail-local.c:165,
# maildir_child() process exited with rc not in 0,2,3,4). Not sure
# why, and I'd have to hack qmail to investigate further, so it's
# easier to just wait a second before yanking the message out of new/
reactor.callLater(0.1, self.poll)
def stopService(self):
if self.dnotify:
self.dnotify.remove()
self.dnotify = None
if self.timerService is not None:
self.timerService.disownServiceParent()
self.timerService = None
return super().stopService()
@defer.inlineCallbacks
def poll(self):
try:
assert self.basedir
# see what's new
for f in self.files:
if not os.path.isfile(os.path.join(self.newdir, f)):
self.files.remove(f)
newfiles = []
for f in os.listdir(self.newdir):
if f not in self.files:
newfiles.append(f)
self.files.extend(newfiles)
for n in newfiles:
try:
yield self.messageReceived(n)
except Exception:
log.err(None, f"while reading '{n}' from maildir '{self.basedir}':")
except Exception:
log.err(None, f"while polling maildir '{self.basedir}':")
def moveToCurDir(self, filename):
f = None
if runtime.platformType == "posix":
# open the file before moving it, because I'm afraid that once
# it's in cur/, someone might delete it at any moment
path = os.path.join(self.newdir, filename)
f = open(path, encoding='utf-8')
os.rename(os.path.join(self.newdir, filename), os.path.join(self.curdir, filename))
elif runtime.platformType == "win32":
# do this backwards under windows, because you can't move a file
# that somebody is holding open. This was causing a Permission
# Denied error on bear's win32-twisted1.3 worker.
os.rename(os.path.join(self.newdir, filename), os.path.join(self.curdir, filename))
path = os.path.join(self.curdir, filename)
f = open(path, encoding='utf-8')
return f
def messageReceived(self, filename):
raise NotImplementedError
| 6,170 | Python | .py | 132 | 38.189394 | 95 | 0.657803 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
4,947 | netstrings.py | buildbot_buildbot/master/buildbot/util/netstrings.py | # This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright Buildbot Team Members
from twisted.internet.interfaces import IAddress
from twisted.internet.interfaces import ITransport
from twisted.protocols import basic
from zope.interface import implementer
from buildbot.util import unicode2bytes
@implementer(IAddress)
class NullAddress:
"an address for NullTransport"
@implementer(ITransport)
class NullTransport:
"a do-nothing transport to make NetstringReceiver happy"
def write(self, data):
raise NotImplementedError
def writeSequence(self, data):
raise NotImplementedError
def loseConnection(self):
pass
def getPeer(self):
return NullAddress
def getHost(self):
return NullAddress
class NetstringParser(basic.NetstringReceiver):
"""
Adapts the Twisted netstring support (which assumes it is on a socket) to
work on simple strings, too. Call the C{feed} method with arbitrary blocks
of data, and override the C{stringReceived} method to get called for each
embedded netstring. The default implementation collects the netstrings in
the list C{self.strings}.
"""
def __init__(self):
# most of the complexity here is stubbing out the transport code so
# that Twisted-10.2.0 and higher believes that this is a valid protocol
self.makeConnection(NullTransport())
self.strings = []
def feed(self, data):
data = unicode2bytes(data)
self.dataReceived(data)
# dataReceived handles errors unusually quietly!
if self.brokenPeer:
raise basic.NetstringParseError
def stringReceived(self, string):
self.strings.append(string)
| 2,350 | Python | .py | 56 | 37.232143 | 79 | 0.751427 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
4,948 | pathmatch.py | buildbot_buildbot/master/buildbot/util/pathmatch.py | # This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright Buildbot Team Members
import re
_ident_re = re.compile('^[a-zA-Z_-][.a-zA-Z0-9_-]*$')
def ident(x):
if _ident_re.match(x):
return x
raise TypeError
class Matcher:
def __init__(self):
self._patterns = {}
self._dirty = True
def __setitem__(self, path, value):
assert path not in self._patterns, f"duplicate path {path}"
self._patterns[path] = value
self._dirty = True
def __repr__(self):
return f'<Matcher {self._patterns!r}>'
path_elt_re = re.compile('^(.?):([a-z0-9_.]+)$')
type_fns = {"n": int, "i": ident, "s": str}
def __getitem__(self, path):
if self._dirty:
self._compile()
patterns = self._by_length.get(len(path), {})
for pattern in patterns:
kwargs = {}
for pattern_elt, path_elt in zip(pattern, path):
mo = self.path_elt_re.match(pattern_elt)
if mo:
type_flag, arg_name = mo.groups()
if type_flag:
try:
type_fn = self.type_fns[type_flag]
except Exception:
assert type_flag in self.type_fns, f"no such type flag {type_flag}"
try:
path_elt = type_fn(path_elt)
except Exception:
break
kwargs[arg_name] = path_elt
else:
if pattern_elt != path_elt:
break
else:
# complete match
return patterns[pattern], kwargs
raise KeyError(f'No match for {path!r}')
def iterPatterns(self):
return list(self._patterns.items())
def _compile(self):
self._by_length = {}
for k, v in self.iterPatterns():
length = len(k)
self._by_length.setdefault(length, {})[k] = v
| 2,664 | Python | .py | 66 | 29.833333 | 95 | 0.559381 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
4,949 | poll.py | buildbot_buildbot/master/buildbot/util/poll.py | # This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright Buildbot Team Members
from random import randint
from twisted.internet import defer
from twisted.python import log
_poller_instances = None
class Poller:
def __init__(self, fn, instance, reactor):
self.fn = fn
self.instance = instance
self.running = False
self.pending = False
# Invariants:
# - If self._call is not None or self._currently_executing then it is guaranteed that
# self.pending and self._run_complete_deferreds will be handled at some point in the
# future.
# - If self._call is not None then _run will be executed at some point, but it's not being
# executed now.
self._currently_executing = False
self._call = None
self._next_call_time = None # valid when self._call is not None
self._start_time = 0
self._interval = 0
self._random_delay_min = 0
self._random_delay_max = 0
self._run_complete_deferreds = []
self._reactor = reactor
@defer.inlineCallbacks
def _run(self):
self._call = None
self._currently_executing = True
try:
yield self.fn(self.instance)
except Exception as e:
log.err(e, f'while executing {self.fn}')
finally:
self._currently_executing = False
was_pending = self.pending
self.pending = False
if self.running:
self._schedule(force_now=was_pending)
while self._run_complete_deferreds:
self._run_complete_deferreds.pop(0).callback(None)
def _get_wait_time(self, curr_time, force_now=False, force_initial_now=False):
if force_now:
return 0
extra_wait = randint(self._random_delay_min, self._random_delay_max)
if force_initial_now or self._interval == 0:
return extra_wait
# note that differently from twisted.internet.task.LoopingCall, we don't care about
# floating-point precision issues as we don't have the withCount feature.
running_time = curr_time - self._start_time
return self._interval - (running_time % self._interval) + extra_wait
def _schedule(self, force_now=False, force_initial_now=False):
curr_time = self._reactor.seconds()
wait_time = self._get_wait_time(
curr_time, force_now=force_now, force_initial_now=force_initial_now
)
next_call_time = curr_time + wait_time
if self._call is not None:
# Note that self._call can ever be moved to earlier time, so we can always cancel it.
self._call.cancel()
self._next_call_time = next_call_time
self._call = self._reactor.callLater(wait_time, self._run)
def __call__(self):
if not self.running:
return
if self._currently_executing:
self.pending = True
else:
self._schedule(force_now=True)
def start(self, interval, now=False, random_delay_min=0, random_delay_max=0):
assert not self.running
self._interval = interval
self._random_delay_min = random_delay_min
self._random_delay_max = random_delay_max
self._start_time = self._reactor.seconds()
self.running = True
self._schedule(force_initial_now=now)
@defer.inlineCallbacks
def stop(self):
self.running = False
if self._call is not None:
self._call.cancel()
self._call = None
if self._currently_executing:
d = defer.Deferred()
self._run_complete_deferreds.append(d)
yield d
class _Descriptor:
def __init__(self, fn, attrName):
self.fn = fn
self.attrName = attrName
def __get__(self, instance, cls):
try:
poller = getattr(instance, self.attrName)
except AttributeError:
poller = Poller(self.fn, instance, instance.master.reactor)
setattr(instance, self.attrName, poller)
# track instances when testing
if _poller_instances is not None:
_poller_instances.append((instance, self.attrName))
return poller
def method(fn):
stateName = "__poll_" + fn.__name__ + "__"
return _Descriptor(fn, stateName)
def track_poll_methods():
global _poller_instances
_poller_instances = []
def reset_poll_methods():
global _poller_instances
for instance, attrname in _poller_instances: # pylint: disable=not-an-iterable
delattr(instance, attrname)
_poller_instances = None
| 5,280 | Python | .py | 126 | 33.865079 | 100 | 0.644266 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
4,950 | __init__.py | buildbot_buildbot/master/buildbot/util/__init__.py | # This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright Buildbot Team Members
from __future__ import annotations
import calendar
import datetime
import itertools
import json
import locale
import re
import sys
import textwrap
import time
from typing import TYPE_CHECKING
from typing import ClassVar
from typing import Sequence
from urllib.parse import urlsplit
from urllib.parse import urlunsplit
import dateutil.tz
from twisted.python import reflect
from zope.interface import implementer
from buildbot.interfaces import IConfigured
from buildbot.util.giturlparse import giturlparse
from buildbot.util.misc import deferredLocked
from ._notifier import Notifier
if TYPE_CHECKING:
from typing import ClassVar
from typing import Sequence
def naturalSort(array):
array = array[:]
def try_int(s):
try:
return int(s)
except ValueError:
return s
def key_func(item):
return [try_int(s) for s in re.split(r'(\d+)', item)]
# prepend integer keys to each element, sort them, then strip the keys
keyed_array = sorted([(key_func(i), i) for i in array])
array = [i[1] for i in keyed_array]
return array
def flattened_iterator(l, types=(list, tuple)):
"""
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 input is yielded.
"""
if not isinstance(l, types):
yield l
return
for element in l:
yield from flattened_iterator(element, types)
def flatten(l, types=(list,)):
"""
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
"""
# For backwards compatibility, this returned a list, not an iterable.
# Changing to return an iterable could break things.
if not isinstance(l, types):
return l
return list(flattened_iterator(l, types))
def now(_reactor=None):
if _reactor and hasattr(_reactor, "seconds"):
return _reactor.seconds()
return time.time()
def formatInterval(eta):
eta_parts = []
if eta > 3600:
eta_parts.append(f"{eta // 3600} hrs")
eta %= 3600
if eta > 60:
eta_parts.append(f"{eta // 60} mins")
eta %= 60
eta_parts.append(f"{eta} secs")
return ", ".join(eta_parts)
def fuzzyInterval(seconds):
"""
Convert time interval specified in seconds into fuzzy, human-readable form
"""
if seconds <= 1:
return "a moment"
if seconds < 20:
return f"{seconds} seconds".format(seconds)
if seconds < 55:
return f"{round(seconds / 10.0) * 10} seconds"
minutes = round(seconds / 60.0)
if minutes == 1:
return "a minute"
if minutes < 20:
return f"{minutes} minutes"
if minutes < 55:
return f"{round(minutes / 10.0) * 10} minutes"
hours = round(minutes / 60.0)
if hours == 1:
return "an hour"
if hours < 24:
return f"{hours} hours"
days = (hours + 6) // 24
if days == 1:
return "a day"
if days < 30:
return f"{days} days"
months = int((days + 10) / 30.5)
if months == 1:
return "a month"
if months < 12:
return f"{months} months"
years = round(days / 365.25)
if years == 1:
return "a year"
return f"{years} years"
@implementer(IConfigured)
class ComparableMixin:
compare_attrs: ClassVar[Sequence[str]] = ()
class _None:
pass
def __hash__(self):
compare_attrs = []
reflect.accumulateClassList(self.__class__, 'compare_attrs', compare_attrs)
alist = [self.__class__] + [getattr(self, name, self._None) for name in compare_attrs]
return hash(tuple(map(str, alist)))
def _cmp_common(self, them):
if type(self) != type(them):
return (False, None, None)
if self.__class__ != them.__class__:
return (False, None, None)
compare_attrs = []
reflect.accumulateClassList(self.__class__, 'compare_attrs', compare_attrs)
self_list = [getattr(self, name, self._None) for name in compare_attrs]
them_list = [getattr(them, name, self._None) for name in compare_attrs]
return (True, self_list, them_list)
def __eq__(self, them):
(isComparable, self_list, them_list) = self._cmp_common(them)
if not isComparable:
return False
return self_list == them_list
@staticmethod
def isEquivalent(us, them):
if isinstance(them, ComparableMixin):
them, us = us, them
if isinstance(us, ComparableMixin):
(isComparable, us_list, them_list) = us._cmp_common(them)
if not isComparable:
return False
return all(ComparableMixin.isEquivalent(v, them_list[i]) for i, v in enumerate(us_list))
return us == them
def __ne__(self, them):
(isComparable, self_list, them_list) = self._cmp_common(them)
if not isComparable:
return True
return self_list != them_list
def __lt__(self, them):
(isComparable, self_list, them_list) = self._cmp_common(them)
if not isComparable:
return False
return self_list < them_list
def __le__(self, them):
(isComparable, self_list, them_list) = self._cmp_common(them)
if not isComparable:
return False
return self_list <= them_list
def __gt__(self, them):
(isComparable, self_list, them_list) = self._cmp_common(them)
if not isComparable:
return False
return self_list > them_list
def __ge__(self, them):
(isComparable, self_list, them_list) = self._cmp_common(them)
if not isComparable:
return False
return self_list >= them_list
def getConfigDict(self):
compare_attrs = []
reflect.accumulateClassList(self.__class__, 'compare_attrs', compare_attrs)
return {
k: getattr(self, k)
for k in compare_attrs
if hasattr(self, k) and k not in ("passwd", "password")
}
def diffSets(old, new):
if not isinstance(old, set):
old = set(old)
if not isinstance(new, set):
new = set(new)
return old - new, new - old
# Remove potentially harmful characters from builder name if it is to be
# used as the build dir.
badchars_map = bytes.maketrans(
b"\t !#$%&'()*+,./:;<=>?@[\\]^{|}~", b"______________________________"
)
def safeTranslate(s):
if isinstance(s, str):
s = s.encode('utf8')
return s.translate(badchars_map)
def none_or_str(x):
if x is not None and not isinstance(x, str):
return str(x)
return x
def unicode2bytes(x, encoding='utf-8', errors='strict'):
if isinstance(x, str):
x = x.encode(encoding, errors)
return x
def bytes2unicode(x, encoding='utf-8', errors='strict'):
if isinstance(x, (str, type(None))):
return x
return str(x, encoding, errors)
_hush_pyflakes = [json]
def toJson(obj):
if isinstance(obj, datetime.datetime):
return datetime2epoch(obj)
return None
# changes and schedulers consider None to be a legitimate name for a branch,
# which makes default function keyword arguments hard to handle. This value
# is always false.
class _NotABranch:
def __bool__(self):
return False
NotABranch = _NotABranch()
# time-handling methods
# this used to be a custom class; now it's just an instance of dateutil's class
UTC = dateutil.tz.tzutc()
def epoch2datetime(epoch):
"""Convert a UNIX epoch time to a datetime object, in the UTC timezone"""
if epoch is not None:
return datetime.datetime.fromtimestamp(epoch, tz=UTC)
return None
def datetime2epoch(dt):
"""Convert a non-naive datetime object to a UNIX epoch timestamp"""
if dt is not None:
return calendar.timegm(dt.utctimetuple())
return None
# TODO: maybe "merge" with formatInterval?
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 delta.days > 0:
result.append(f'{delta.days} days')
if delta.seconds > 0:
hours = int(delta.seconds / 3600)
if hours > 0:
result.append(f'{hours} hours')
minutes = int((delta.seconds - hours * 3600) / 60)
if minutes:
result.append(f'{minutes} minutes')
seconds = delta.seconds % 60
if seconds > 0:
result.append(f'{seconds} seconds')
if result:
return ', '.join(result)
return 'super fast'
def makeList(input):
if isinstance(input, str):
return [input]
elif input is None:
return []
return list(input)
def in_reactor(f):
"""decorate a function by running it with maybeDeferred in a reactor"""
def wrap(*args, **kwargs):
from twisted.internet import defer
from twisted.internet import reactor
result = []
def _async():
d = defer.maybeDeferred(f, *args, **kwargs)
@d.addErrback
def eb(f):
f.printTraceback(file=sys.stderr)
@d.addBoth
def do_stop(r):
result.append(r)
reactor.stop()
reactor.callWhenRunning(_async)
reactor.run()
return result[0]
wrap.__doc__ = f.__doc__
wrap.__name__ = f.__name__
wrap._orig = f # for tests
return wrap
def string2boolean(str):
return {
b'on': True,
b'true': True,
b'yes': True,
b'1': True,
b'off': False,
b'false': False,
b'no': False,
b'0': False,
}[str.lower()]
def asyncSleep(delay, reactor=None):
from twisted.internet import defer
from twisted.internet import reactor as internet_reactor
if reactor is None:
reactor = internet_reactor
d = defer.Deferred()
reactor.callLater(delay, d.callback, None)
return d
def check_functional_environment(config):
try:
if sys.version_info >= (3, 11, 0):
locale.getencoding()
else:
locale.getdefaultlocale()
except (KeyError, ValueError) as e:
config.error(
"\n".join([
"Your environment has incorrect locale settings. This means python cannot handle "
"strings safely.",
" Please check 'LANG', 'LC_CTYPE', 'LC_ALL' and 'LANGUAGE'"
" are either unset or set to a valid locale.",
str(e),
])
)
_netloc_url_re = re.compile(r':[^@]*@')
def stripUrlPassword(url):
parts = list(urlsplit(url))
parts[1] = _netloc_url_re.sub(':xxxx@', parts[1])
return urlunsplit(parts)
def join_list(maybeList):
if isinstance(maybeList, (list, tuple)):
return ' '.join(bytes2unicode(s) for s in maybeList)
return bytes2unicode(maybeList)
def command_to_string(command):
words = command
if isinstance(words, (bytes, str)):
words = words.split()
try:
len(words)
except (AttributeError, TypeError):
# WithProperties and Property don't have __len__
# For old-style classes instances AttributeError raised,
# for new-style classes instances - TypeError.
return None
# flatten any nested lists
words = flatten(words, (list, tuple))
stringWords = []
for w in words:
if isinstance(w, (bytes, str)):
# If command was bytes, be gentle in
# trying to covert it.
w = bytes2unicode(w, errors="replace")
stringWords.append(w)
else:
stringWords.append(repr(w))
words = stringWords
if not words:
return None
if len(words) < 3:
rv = f"'{' '.join(words)}'"
else:
rv = f"'{' '.join(words[:2])} ...'"
return rv
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 width is None:
width = 80
# Remove common indentation.
text = textwrap.dedent(text)
def needs_wrapping(line):
# Line always non-empty.
return not line[0].isspace()
# Split text by lines and group lines that comprise paragraphs.
wrapped_text = ""
for do_wrap, lines in itertools.groupby(text.splitlines(True), key=needs_wrapping):
paragraph = ''.join(lines)
if do_wrap:
paragraph = textwrap.fill(paragraph, width)
wrapped_text += paragraph
return wrapped_text
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[key], b[key])
continue
a[key] = b[key]
return a
__all__ = [
'naturalSort',
'now',
'formatInterval',
'ComparableMixin',
'safeTranslate',
'none_or_str',
'NotABranch',
'deferredLocked',
'UTC',
'diffSets',
'makeList',
'in_reactor',
'string2boolean',
'check_functional_environment',
'human_readable_delta',
'rewrap',
'Notifier',
"giturlparse",
]
| 14,701 | Python | .py | 426 | 27.894366 | 100 | 0.630731 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
4,951 | path_expand_user.py | buildbot_buildbot/master/buildbot/util/path_expand_user.py | # This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright Buildbot Team Members
#
# This code has originally been copied from cpython project.
#
# Copyright Python Software Foundation and contributors
# Licensed under Python Software Foundation License Version 2
import ntpath
import os
import posixpath
def posix_expanduser(path, worker_environ):
"""Expand ~ and ~user constructions. If user or $HOME is unknown,
do nothing."""
path = os.fspath(path)
tilde = '~'
if not path.startswith(tilde):
return path
sep = posixpath._get_sep(path)
i = path.find(sep, 1)
if i < 0:
i = len(path)
if i == 1:
if 'HOME' not in worker_environ:
try:
import pwd
except ImportError:
# pwd module unavailable, return path unchanged
return path
try:
userhome = pwd.getpwuid(os.getuid()).pw_dir
except KeyError:
# bpo-10496: if the current user identifier doesn't exist in the
# password database, return the path unchanged
return path
else:
userhome = worker_environ['HOME']
else:
try:
import pwd
except ImportError:
# pwd module unavailable, return path unchanged
return path
name = path[1:i]
try:
pwent = pwd.getpwnam(name)
except KeyError:
# bpo-10496: if the user name from the path doesn't exist in the
# password database, return the path unchanged
return path
userhome = pwent.pw_dir
root = '/'
userhome = userhome.rstrip(root)
return (userhome + path[i:]) or root
def nt_expanduser(path, worker_environ):
"""Expand ~ and ~user constructs.
If user or $HOME is unknown, do nothing."""
path = os.fspath(path)
tilde = '~'
if not path.startswith(tilde):
return path
i = 1
n = len(path)
while i < n and path[i] not in ntpath._get_bothseps(path):
i += 1
if 'USERPROFILE' in worker_environ:
userhome = worker_environ['USERPROFILE']
elif 'HOMEPATH' not in worker_environ:
return path
else:
try:
drive = worker_environ['HOMEDRIVE']
except KeyError:
drive = ''
userhome = ntpath.join(drive, worker_environ['HOMEPATH'])
if i != 1: # ~user
target_user = path[1:i]
current_user = worker_environ.get('USERNAME')
if target_user != current_user:
# Try to guess user home directory. By default all user
# profile directories are located in the same place and are
# named by corresponding usernames. If userhome isn't a
# normal profile directory, this guess is likely wrong,
# so we bail out.
if current_user != ntpath.basename(userhome):
return path
userhome = ntpath.join(ntpath.dirname(userhome), target_user)
return userhome + path[i:]
| 3,691 | Python | .py | 99 | 29.686869 | 80 | 0.635501 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
4,952 | subscription.py | buildbot_buildbot/master/buildbot/util/subscription.py | # This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright Buildbot Team Members
from twisted.internet import defer
from twisted.python import log
from buildbot.util import Notifier
class SubscriptionPoint:
def __init__(self, name):
self.name = name
self.subscriptions = set()
self._unfinished_deliveries = []
self._unfinished_notifier = Notifier()
self._got_exceptions = []
def __str__(self):
return f"<SubscriptionPoint '{self.name}'>"
def subscribe(self, callback):
sub = Subscription(self, callback)
self.subscriptions.add(sub)
return sub
def deliver(self, *args, **kwargs):
self._unfinished_deliveries.append(self)
for sub in list(self.subscriptions):
try:
d = sub.callback(*args, **kwargs)
if isinstance(d, defer.Deferred):
self._unfinished_deliveries.append(d)
d.addErrback(self._notify_delivery_exception, sub)
d.addBoth(self._notify_delivery_finished, d)
except Exception as e:
self._notify_delivery_exception(e, sub)
self._notify_delivery_finished(None, self)
def waitForDeliveriesToFinish(self):
# returns a deferred
if not self._unfinished_deliveries:
return defer.succeed(None)
return self._unfinished_notifier.wait()
def pop_exceptions(self):
exceptions = self._got_exceptions
self._got_exceptions = None # we no longer expect any exceptions
return exceptions
def _unsubscribe(self, subscription):
self.subscriptions.remove(subscription)
def _notify_delivery_exception(self, e, sub):
log.err(e, f'while invoking callback {sub.callback} to {self}')
if self._got_exceptions is None:
log.err(
e,
'exceptions have already been collected. '
'This is serious error, please submit a bug report',
)
return
self._got_exceptions.append(e)
def _notify_delivery_finished(self, _, d):
self._unfinished_deliveries.remove(d)
if not self._unfinished_deliveries:
self._unfinished_notifier.notify(None)
class Subscription:
def __init__(self, subpt, callback):
self.subpt = subpt
self.callback = callback
def unsubscribe(self):
self.subpt._unsubscribe(self)
| 3,096 | Python | .py | 73 | 34.315068 | 79 | 0.661564 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
4,953 | sautils.py | buildbot_buildbot/master/buildbot/util/sautils.py | # This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright Buildbot Team Members
from __future__ import annotations
import hashlib
from contextlib import contextmanager
from typing import TYPE_CHECKING
import sqlalchemy as sa
from sqlalchemy.ext import compiler
from sqlalchemy.sql.elements import BooleanClauseList
from sqlalchemy.sql.elements import ColumnElement
from sqlalchemy.sql.expression import ClauseElement
from sqlalchemy.sql.expression import Executable
if TYPE_CHECKING:
from typing import Any
from typing import Callable
from typing import Sequence
from sqlalchemy.future.engine import Connection
from sqlalchemy.future.engine import Engine
# from http:
# www.sqlalchemy.org/docs/core/compiler.html#compiling-sub-elements-of-a-custom-expression-construct
# _execution_options per
# http://docs.sqlalchemy.org/en/rel_0_7/core/compiler.html#enabling-compiled-autocommit
# (UpdateBase requires sqlalchemy 0.7.0)
class InsertFromSelect(Executable, ClauseElement):
_execution_options = Executable._execution_options.union({'autocommit': True})
def __init__(self, table, select):
self.table = table
self.select = select
@compiler.compiles(InsertFromSelect)
def _visit_insert_from_select(element, compiler, **kw):
return (
f"INSERT INTO {compiler.process(element.table, asfrom=True)} "
f"{compiler.process(element.select)}"
)
def sa_version():
if hasattr(sa, '__version__'):
def tryint(s):
try:
return int(s)
except (ValueError, TypeError):
return -1
return tuple(map(tryint, sa.__version__.split('.')))
return (0, 0, 0) # "it's old"
def Table(*args, **kwargs):
"""Wrap table creation to add any necessary dialect-specific options"""
# work around the case where a database was created for us with
# a non-utf8 character set (mysql's default)
kwargs['mysql_character_set'] = 'utf8'
return sa.Table(*args, **kwargs)
@contextmanager
def withoutSqliteForeignKeys(connection: Connection):
if connection.engine.dialect.name != 'sqlite':
yield
return
# This context is not re-entrant. Ensure it.
assert not getattr(connection.engine, 'fk_disabled', False)
connection.fk_disabled = True # type: ignore[attr-defined]
connection.exec_driver_sql('pragma foreign_keys=OFF')
try:
yield
finally:
connection.fk_disabled = False # type: ignore[attr-defined]
connection.exec_driver_sql('pragma foreign_keys=ON')
def get_sqlite_version():
import sqlite3
return sqlite3.sqlite_version_info
def get_upsert_method(engine: Engine | None):
if engine is None:
return _upsert_default
# https://sqlite.org/lang_upsert.html
if engine.dialect.name == 'sqlite' and get_sqlite_version() > (3, 24, 0):
return _upsert_sqlite
if engine.dialect.name == 'postgresql':
return _upsert_postgresql
if engine.dialect.name == 'mysql':
return _upsert_mysql
return _upsert_default
def _upsert_sqlite(
connection: Connection,
table: sa.Table,
*,
where_values: Sequence[tuple[sa.Column, Any]],
update_values: Sequence[tuple[sa.Column, Any]],
_race_hook: Callable[[Connection], None] | None = None,
):
from sqlalchemy.dialects.sqlite import insert # pylint: disable=import-outside-toplevel
_upsert_on_conflict_do_update(
insert,
connection,
table,
where_values=where_values,
update_values=update_values,
_race_hook=_race_hook,
)
def _upsert_postgresql(
connection: Connection,
table: sa.Table,
*,
where_values: Sequence[tuple[sa.Column, Any]],
update_values: Sequence[tuple[sa.Column, Any]],
_race_hook: Callable[[Connection], None] | None = None,
):
from sqlalchemy.dialects.postgresql import insert # pylint: disable=import-outside-toplevel
_upsert_on_conflict_do_update(
insert,
connection,
table,
where_values=where_values,
update_values=update_values,
_race_hook=_race_hook,
)
def _upsert_on_conflict_do_update(
insert: Any,
connection: Connection,
table: sa.Table,
*,
where_values: Sequence[tuple[sa.Column, Any]],
update_values: Sequence[tuple[sa.Column, Any]],
_race_hook: Callable[[Connection], None] | None = None,
):
if _race_hook is not None:
_race_hook(connection)
insert_stmt = insert(table).values(
**_column_value_kwargs(where_values),
**_column_value_kwargs(update_values),
)
do_update_stmt = insert_stmt.on_conflict_do_update(
index_elements=[c for (c, _) in where_values],
index_where=_column_values_where_clause(where_values),
set_=dict(update_values),
)
connection.execute(do_update_stmt)
def _upsert_mysql(
connection: Connection,
table: sa.Table,
*,
where_values: Sequence[tuple[sa.Column, Any]],
update_values: Sequence[tuple[sa.Column, Any]],
_race_hook: Callable[[Connection], None] | None = None,
):
from sqlalchemy.dialects.mysql import insert # pylint: disable=import-outside-toplevel
if _race_hook is not None:
_race_hook(connection)
update_kwargs = _column_value_kwargs(update_values)
insert_stmt = insert(table).values(
**_column_value_kwargs(where_values),
**update_kwargs,
)
on_duplicate_key_stmt = insert_stmt.on_duplicate_key_update(
**update_kwargs,
)
connection.execute(on_duplicate_key_stmt)
def _upsert_default(
connection: Connection,
table: sa.Table,
*,
where_values: Sequence[tuple[sa.Column, Any]],
update_values: Sequence[tuple[sa.Column, Any]],
_race_hook: Callable[[Connection], None] | None = None,
):
q = table.update()
if where_values:
q = q.where(_column_values_where_clause(where_values))
res = connection.execute(q.values(*update_values))
if res.rowcount > 0:
return
# the update hit 0 rows, so try inserting a new one
if _race_hook is not None:
_race_hook(connection)
connection.execute(
table.insert().values(
**_column_value_kwargs(where_values),
**_column_value_kwargs(update_values),
)
)
def _column_value_kwargs(values: Sequence[tuple[sa.Column, Any]]) -> dict[str, Any]:
return {c.name: v for (c, v) in values}
def _column_values_where_clause(values: Sequence[tuple[sa.Column, Any]]) -> ColumnElement[bool]:
return BooleanClauseList.and_(*[c == v for (c, v) in values])
def hash_columns(*args):
def encode(x):
if x is None:
return b'\xf5'
elif isinstance(x, str):
return x.encode('utf-8')
return str(x).encode('utf-8')
return hashlib.sha1(b'\0'.join(map(encode, args))).hexdigest()
| 7,526 | Python | .py | 199 | 32.341709 | 100 | 0.690352 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
4,954 | identifiers.py | buildbot_buildbot/master/buildbot/util/identifiers.py | # This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright Buildbot Team Members
import re
from buildbot import util
ident_re = re.compile(
'^[a-zA-Z\u00a0-\U0010ffff_-][a-zA-Z0-9\u00a0-\U0010ffff_-]*$', flags=re.UNICODE
)
initial_re = re.compile('^[^a-zA-Z_-]')
subsequent_re = re.compile('[^a-zA-Z0-9_-]')
trailing_digits_re = re.compile('_([0-9]+)$')
def isIdentifier(maxLength, obj):
if not isinstance(obj, str):
return False
elif not ident_re.match(obj):
return False
elif not obj or len(obj) > maxLength:
return False
return True
def forceIdentifier(maxLength, s):
if not isinstance(s, str):
raise TypeError(f"{str!r} cannot be coerced to an identifier")
# usually bytes2unicode can handle it
s = util.bytes2unicode(s)
if isIdentifier(maxLength, s):
return s
# trim to length and substitute out invalid characters
s = s[:maxLength]
s = initial_re.sub('_', s)
s = subsequent_re.subn('_', s)[0]
return s
def incrementIdentifier(maxLength, ident):
num = 1
mo = trailing_digits_re.search(ident)
if mo:
ident = ident[: mo.start(1) - 1]
num = int(mo.group(1))
num = f'_{num + 1}'
if len(num) > maxLength:
raise ValueError("cannot generate a larger identifier")
ident = ident[: maxLength - len(num)] + num
return ident
| 2,001 | Python | .py | 53 | 33.754717 | 84 | 0.695405 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
4,955 | runprocess.py | buildbot_buildbot/master/buildbot/util/runprocess.py | # This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright Buildbot Team Members
import io
import os
import subprocess
from twisted.internet import defer
from twisted.internet import error
from twisted.internet import protocol
from twisted.python import failure
from twisted.python import log
from twisted.python import runtime
from buildbot.util import unicode2bytes
class RunProcessPP(protocol.ProcessProtocol):
def __init__(self, run_process, initial_stdin=None):
self.run_process = run_process
self.initial_stdin = initial_stdin
def connectionMade(self):
if self.initial_stdin:
self.transport.write(self.initial_stdin)
self.transport.closeStdin()
def outReceived(self, data):
self.run_process.add_stdout(data)
def errReceived(self, data):
self.run_process.add_stderr(data)
def processEnded(self, reason):
self.run_process.process_ended(reason.value.signal, reason.value.exitCode)
class RunProcess:
TIMEOUT_KILL = 5
interrupt_signal = "KILL"
def __init__(
self,
reactor,
command,
workdir=None,
env=None,
collect_stdout=True,
collect_stderr=True,
stderr_is_error=False,
io_timeout=300,
runtime_timeout=3600,
sigterm_timeout=5,
initial_stdin=None,
use_pty=False,
):
self._reactor = reactor
self.command = command
self.workdir = workdir
self.process = None
self.environ = env
self.initial_stdin = initial_stdin
self.output_stdout = None
self.consumer_stdout = None
if collect_stdout is True:
self.output_stdout = io.BytesIO()
self.consumer_stdout = self.output_stdout.write
elif callable(collect_stdout):
self.consumer_stdout = collect_stdout
self.output_stderr = None
self.consumer_stderr = None
if collect_stderr is True:
self.output_stderr = io.BytesIO()
self.consumer_stderr = self.output_stderr.write
elif callable(collect_stderr):
self.consumer_stderr = collect_stderr
self.stderr_is_error = stderr_is_error
self.io_timeout = io_timeout
self.io_timer = None
self.sigterm_timeout = sigterm_timeout
self.sigterm_timer = None
self.runtime_timeout = runtime_timeout
self.runtime_timer = None
self.killed = False
self.kill_timer = None
self.use_pty = use_pty
self.result_signal = None
self.result_rc = None
def __repr__(self):
return f"<{self.__class__.__name__} '{self.command}'>"
def get_os_env(self):
return os.environ
def resolve_environment(self, env):
os_env = self.get_os_env()
if env is None:
return os_env.copy()
new_env = {}
for key, value in os_env.items():
if key not in env or env[key] is not None:
new_env[key] = value
for key, value in env.items():
if value is not None:
new_env[key] = value
return new_env
def start(self):
self.deferred = defer.Deferred()
try:
self._start_command()
except Exception as e:
self.deferred.errback(failure.Failure(e))
return self.deferred
def _start_command(self):
self.pp = RunProcessPP(self, initial_stdin=self.initial_stdin)
environ = self.resolve_environment(self.environ)
# $PWD usually indicates the current directory; spawnProcess may not
# update this value, though, so we set it explicitly here. This causes
# weird problems (bug #456) on msys
if not environ.get('MACHTYPE', None) == 'i686-pc-msys' and self.workdir is not None:
environ['PWD'] = os.path.abspath(self.workdir)
argv = unicode2bytes(self.command)
self.process = self._reactor.spawnProcess(
self.pp, argv[0], argv, environ, self.workdir, usePTY=self.use_pty
)
if self.io_timeout:
self.io_timer = self._reactor.callLater(self.io_timeout, self.io_timed_out)
if self.runtime_timeout:
self.runtime_timer = self._reactor.callLater(
self.runtime_timeout, self.runtime_timed_out
)
def add_stdout(self, data):
if self.consumer_stdout is not None:
self.consumer_stdout(data)
if self.io_timer:
self.io_timer.reset(self.io_timeout)
def add_stderr(self, data):
if self.consumer_stderr is not None:
self.consumer_stderr(data)
if self.stderr_is_error:
self.kill('command produced stderr which is interpreted as error')
if self.io_timer:
self.io_timer.reset(self.io_timeout)
def _build_result(self, rc):
if self.output_stdout is not None and self.output_stderr is not None:
return (rc, self.output_stdout.getvalue(), self.output_stderr.getvalue())
if self.output_stdout is not None:
return (rc, self.output_stdout.getvalue())
if self.output_stderr is not None:
return (rc, self.output_stderr.getvalue())
return rc
def process_ended(self, sig, rc):
self.result_signal = sig
self.result_rc = rc
if self.killed and rc == 0:
log.msg("process was killed, but exited with status 0; faking a failure")
# windows returns '1' even for signalled failures, while POSIX returns -1
if runtime.platformType == 'win32':
rc = 1
else:
rc = -1
if sig is not None:
rc = -1
self._cancel_timers()
d = self.deferred
self.deferred = None
if d:
d.callback(self._build_result(rc))
else:
log.err(f"{self}: command finished twice")
def failed(self, why):
self._cancel_timers()
d = self.deferred
self.deferred = None
if d:
d.errback(why)
else:
log.err(f"{self}: command finished twice")
def io_timed_out(self):
self.io_timer = None
msg = f"{self}: command timed out: {self.io_timeout} seconds without output"
self.kill(msg)
def runtime_timed_out(self):
self.runtime_timer = None
msg = f"{self}: command timed out: {self.runtime_timeout} seconds elapsed"
self.kill(msg)
def is_dead(self):
if self.process.pid is None:
return True
pid = int(self.process.pid)
try:
os.kill(pid, 0)
except OSError:
return True
return False
def check_process_was_killed(self):
self.sigterm_timer = None
if not self.is_dead():
if not self.send_signal(self.interrupt_signal):
log.msg(f"{self}: failed to kill process again")
self.cleanup_killed_process()
def cleanup_killed_process(self):
if runtime.platformType == "posix":
# we only do this under posix because the win32eventreactor
# blocks here until the process has terminated, while closing
# stderr. This is weird.
self.pp.transport.loseConnection()
if self.deferred:
# finished ought to be called momentarily. Just in case it doesn't,
# set a timer which will abandon the command.
self.kill_timer = self._reactor.callLater(self.TIMEOUT_KILL, self.kill_timed_out)
def send_signal(self, interrupt_signal):
success = False
log.msg(f'{self}: killing process using {interrupt_signal}')
if runtime.platformType == "win32":
pid = self.process.pid
if interrupt_signal is not None and pid is not None:
try:
if interrupt_signal == "TERM":
# TODO: blocks
subprocess.check_call(f"TASKKILL /PID {pid} /T")
success = True
elif interrupt_signal == "KILL":
# TODO: blocks
subprocess.check_call(f"TASKKILL /F /PID {pid} /T")
success = True
except subprocess.CalledProcessError as e:
# taskkill may return 128 or 255 as exit code when the child has already exited.
# We can't handle this race condition in any other way than just interpreting
# the kill action as successful
if e.returncode in (128, 255):
log.msg(f"{self} taskkill didn't find pid {pid} to kill")
success = True
else:
raise
# try signalling the process itself (works on Windows too, sorta)
if not success:
try:
self.process.signalProcess(interrupt_signal)
success = True
except OSError as e:
log.err(f"{self}: from process.signalProcess: {e}")
# could be no-such-process, because they finished very recently
except error.ProcessExitedAlready:
log.msg(f"{self}: process exited already - can't kill")
# the process has already exited, and likely finished() has
# been called already or will be called shortly
return success
def kill(self, msg):
log.msg(f'{self}: killing process because {msg}')
self._cancel_timers()
self.killed = True
if self.sigterm_timeout is not None:
self.send_signal("TERM")
self.sigterm_timer = self._reactor.callLater(
self.sigterm_timeout, self.check_process_was_killed
)
else:
if not self.send_signal(self.interrupt_signal):
log.msg(f"{self}: failed to kill process")
self.cleanup_killed_process()
def kill_timed_out(self):
self.kill_timer = None
log.msg(f"{self}: attempted to kill process, but it wouldn't die")
self.failed(RuntimeError(f"SIG{self.interrupt_signal} failed to kill process"))
def _cancel_timers(self):
for name in ('io_timer', 'kill_timer', 'runtime_timer', 'sigterm_timer'):
timer = getattr(self, name, None)
if timer:
timer.cancel()
setattr(self, name, None)
def create_process(*args, **kwargs):
return RunProcess(*args, **kwargs)
def run_process(*args, **kwargs):
process = create_process(*args, **kwargs)
return process.start()
| 11,383 | Python | .py | 274 | 31.332117 | 100 | 0.608136 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
4,956 | service.py | buildbot_buildbot/master/buildbot/util/service.py | # This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright Buildbot Team Members
from __future__ import annotations
import hashlib
from typing import ClassVar
from typing import Sequence
from twisted.application import service
from twisted.internet import defer
from twisted.internet import task
from twisted.python import log
from twisted.python import reflect
from twisted.python.reflect import accumulateClassList
import buildbot.config
from buildbot import util
from buildbot.process.properties import Properties
from buildbot.util import bytes2unicode
from buildbot.util import config
from buildbot.util import unicode2bytes
class ReconfigurableServiceMixin:
reconfig_priority = 128
@defer.inlineCallbacks
def reconfigServiceWithBuildbotConfig(self, new_config):
if not service.IServiceCollection.providedBy(self):
return
# get a list of child services to reconfigure
reconfigurable_services = [
svc for svc in self if isinstance(svc, ReconfigurableServiceMixin)
]
# sort by priority
reconfigurable_services.sort(key=lambda svc: -svc.reconfig_priority)
for svc in reconfigurable_services:
yield svc.reconfigServiceWithBuildbotConfig(new_config)
# twisted 16's Service is now an new style class, better put everybody new style
# to catch issues even on twisted < 16
class AsyncService(service.Service):
name: str | None # type: ignore[assignment]
# service.Service.setServiceParent does not wait for neither disownServiceParent nor addService
# to complete
@defer.inlineCallbacks
def setServiceParent(self, parent):
if self.parent is not None:
yield self.disownServiceParent()
parent = service.IServiceCollection(parent, parent)
self.parent = parent
yield self.parent.addService(self)
# service.Service.disownServiceParent does not wait for removeService to complete before
# setting parent to None
@defer.inlineCallbacks
def disownServiceParent(self):
yield self.parent.removeService(self)
self.parent = None
# We recurse over the parent services until we find a MasterService
@property
def master(self):
if self.parent is None:
return None
return self.parent.master
class AsyncMultiService(AsyncService, service.MultiService):
def startService(self):
# Do NOT use super() here.
# The method resolution order would cause MultiService.startService() to
# be called which we explicitly want to override with this method.
service.Service.startService(self)
dl = []
# if a service attaches another service during the reconfiguration
# then the service will be started twice, so we don't use iter, but rather
# copy in a list
for svc in list(self):
# handle any deferreds, passing up errors and success
dl.append(defer.maybeDeferred(svc.startService))
return defer.gatherResults(dl, consumeErrors=True)
@defer.inlineCallbacks
def stopService(self):
# Do NOT use super() here.
# The method resolution order would cause MultiService.stopService() to
# be called which we explicitly want to override with this method.
service.Service.stopService(self)
services = list(self)
services.reverse()
dl = []
for svc in services:
if not isinstance(svc, SharedService):
dl.append(defer.maybeDeferred(svc.stopService))
# unlike MultiService, consume errors in each individual deferred, and
# pass the first error in a child service up to our caller
yield defer.gatherResults(dl, consumeErrors=True)
for svc in services:
if isinstance(svc, SharedService):
yield svc.stopService()
def addService(self, service):
if service.name is not None:
if service.name in self.namedServices:
raise RuntimeError("cannot have two services with same name" f" '{service.name}'")
self.namedServices[service.name] = service
self.services.append(service)
if self.running:
# It may be too late for that, but we will do our best
service.privilegedStartService()
return service.startService()
return defer.succeed(None)
class MasterService(AsyncMultiService):
# master service is the service that stops the master property recursion
@property
def master(self):
return self
def get_db_url(self, new_config) -> defer.Deferred:
p = Properties()
p.master = self
return p.render(new_config.db['db_url'])
class SharedService(AsyncMultiService):
"""a service that is created only once per parameter set in a parent service"""
@classmethod
@defer.inlineCallbacks
def getService(cls, parent, *args, **kwargs):
name = cls.getName(*args, **kwargs)
if name in parent.namedServices:
return parent.namedServices[name]
instance = cls(*args, **kwargs)
# The class is not required to initialized its name
# but we use the name to identify the instance in the parent service
# so we force it with the name we used
instance.name = name
yield instance.setServiceParent(parent)
# we put the service on top of the list, so that it is stopped the last
# This make sense as the shared service is used as a dependency
# for other service
parent.services.remove(instance)
parent.services.insert(0, instance)
# hook the return value to the instance object
return instance
@classmethod
def getName(cls, *args, **kwargs):
_hash = hashlib.sha1()
for arg in args:
arg = unicode2bytes(str(arg))
_hash.update(arg)
for k, v in sorted(kwargs.items()):
k = unicode2bytes(str(k))
v = unicode2bytes(str(v))
_hash.update(k)
_hash.update(v)
return cls.__name__ + "_" + _hash.hexdigest()
class BuildbotService(
AsyncMultiService, config.ConfiguredMixin, util.ComparableMixin, ReconfigurableServiceMixin
):
compare_attrs: ClassVar[Sequence[str]] = ('name', '_config_args', '_config_kwargs')
name: str | None = None # type: ignore[assignment]
configured = False
objectid: int | None = None
def __init__(self, *args, **kwargs):
name = kwargs.pop("name", None)
if name is not None:
self.name = bytes2unicode(name)
self.checkConfig(*args, **kwargs)
if self.name is None:
raise ValueError(f"{type(self)}: must pass a name to constructor")
self._config_args = args
self._config_kwargs = kwargs
self.rendered = False
super().__init__()
def getConfigDict(self):
_type = type(self)
return {
'name': self.name,
'class': _type.__module__ + "." + _type.__name__,
'args': self._config_args,
'kwargs': self._config_kwargs,
}
@defer.inlineCallbacks
def reconfigServiceWithSibling(self, sibling):
# only reconfigure if sibling is configured differently.
# sibling == self is using ComparableMixin's implementation
# only compare compare_attrs
if self.configured and util.ComparableMixin.isEquivalent(sibling, self):
return None
self.configured = True
# render renderables in parallel
p = Properties()
p.master = self.master
# render renderables in parallel
secrets = []
kwargs = {}
accumulateClassList(self.__class__, 'secrets', secrets)
for k, v in sibling._config_kwargs.items():
if k in secrets:
# for non reconfigurable services, we force the attribute
v = yield p.render(v)
setattr(sibling, k, v)
setattr(self, k, v)
kwargs[k] = v
d = yield self.reconfigService(*sibling._config_args, **kwargs)
return d
def canReconfigWithSibling(self, sibling):
return reflect.qual(self.__class__) == reflect.qual(sibling.__class__)
def configureService(self):
# reconfigServiceWithSibling with self, means first configuration
return self.reconfigServiceWithSibling(self)
@defer.inlineCallbacks
def startService(self):
if not self.configured:
try:
yield self.configureService()
except NotImplementedError:
pass
yield super().startService()
def checkConfig(self, *args, **kwargs):
return defer.succeed(True)
def reconfigService(self, name=None, *args, **kwargs):
return defer.succeed(None)
def renderSecrets(self, *args):
p = Properties()
p.master = self.master
if len(args) == 1:
return p.render(args[0])
return defer.gatherResults([p.render(s) for s in args], consumeErrors=True)
class ClusteredBuildbotService(BuildbotService):
"""
ClusteredBuildbotService-es are meant to be executed on a single
master only. When starting such a service, by means of "yield startService",
it will first try to claim it on the current master and:
- return without actually starting it
if it was already claimed by another master (self.active == False).
It will however keep trying to claim it, in case another master
stops, and takes the job back.
- return after it starts else.
"""
compare_attrs: ClassVar[Sequence[str]] = ('name',)
POLL_INTERVAL_SEC = 5 * 60 # 5 minutes
serviceid: int | None = None
active = False
def __init__(self, *args, **kwargs):
self.serviceid = None
self.active = False
self._activityPollCall = None
self._activityPollDeferred = None
super().__init__(*args, **kwargs)
# activity handling
def isActive(self):
return self.active
def activate(self):
# will run when this instance becomes THE CHOSEN ONE for the cluster
return defer.succeed(None)
def deactivate(self):
# to be overridden by subclasses
# will run when this instance loses its chosen status
return defer.succeed(None)
# service arbitration hooks
def _getServiceId(self):
# retrieve the id for this service; we assume that, once we have a valid id,
# the id doesn't change. This may return a Deferred.
raise NotImplementedError
def _claimService(self):
# Attempt to claim the service for this master. Should return True or False
# (optionally via a Deferred) to indicate whether this master now owns the
# service.
raise NotImplementedError
def _unclaimService(self):
# Release the service from this master. This will only be called by a claimed
# service, and this really should be robust and release the claim. May return
# a Deferred.
raise NotImplementedError
# default implementation to delegate to the above methods
@defer.inlineCallbacks
def startService(self):
# subclasses should override startService only to perform actions that should
# run on all instances, even if they never get activated on this
# master.
yield super().startService()
self._startServiceDeferred = defer.Deferred()
self._startActivityPolling()
yield self._startServiceDeferred
@defer.inlineCallbacks
def stopService(self):
# subclasses should override stopService only to perform actions that should
# run on all instances, even if they never get activated on this
# master.
self._stopActivityPolling()
# need to wait for prior activations to finish
if self._activityPollDeferred:
yield self._activityPollDeferred
if self.active:
self.active = False
try:
yield self.deactivate()
yield self._unclaimService()
except Exception as e:
msg = f"Caught exception while deactivating ClusteredService({self.name})"
log.err(e, _why=msg)
yield super().stopService()
def _startActivityPolling(self):
self._activityPollCall = task.LoopingCall(self._activityPoll)
self._activityPollCall.clock = self.master.reactor
d = self._activityPollCall.start(self.POLL_INTERVAL_SEC, now=True)
self._activityPollDeferred = d
# this should never happen, but just in case:
d.addErrback(log.err, 'while polling for service activity:')
def _stopActivityPolling(self):
if self._activityPollCall:
self._activityPollCall.stop()
self._activityPollCall = None
return self._activityPollDeferred
return None
def _callbackStartServiceDeferred(self):
if self._startServiceDeferred is not None:
self._startServiceDeferred.callback(None)
self._startServiceDeferred = None
@defer.inlineCallbacks
def _activityPoll(self):
try:
# just in case..
if self.active:
return
if self.serviceid is None:
self.serviceid = yield self._getServiceId()
try:
claimed = yield self._claimService()
except Exception:
msg = f'WARNING: ClusteredService({self.name}) got exception while trying to claim'
log.err(_why=msg)
return
if not claimed:
# this master is not responsible
# for this service, we callback for StartService
# if it was not callback-ed already,
# and keep polling to take back the service
# if another one lost it
self._callbackStartServiceDeferred()
return
try:
# this master is responsible for this service
# we activate it
self.active = True
yield self.activate()
except Exception:
# this service is half-active, and noted as such in the db..
msg = f'WARNING: ClusteredService({self.name}) is only partially active'
log.err(_why=msg)
finally:
# cannot wait for its deactivation
# with yield self._stopActivityPolling
# as we're currently executing the
# _activityPollCall callback
# we just call it without waiting its stop
# (that may open race conditions)
self._stopActivityPolling()
self._callbackStartServiceDeferred()
except Exception:
# don't pass exceptions into LoopingCall, which can cause it to
# fail
msg = f'WARNING: ClusteredService({self.name}) failed during activity poll'
log.err(_why=msg)
class BuildbotServiceManager(AsyncMultiService, config.ConfiguredMixin, ReconfigurableServiceMixin):
config_attr = "services"
name: str | None = "services" # type: ignore[assignment]
def getConfigDict(self):
return {
'name': self.name,
'childs': [v.getConfigDict() for v in self.namedServices.values()],
}
def get_service_config(self, new_config) -> dict[str, AsyncService]:
new_config_attr = getattr(new_config, self.config_attr)
if isinstance(new_config_attr, list):
service_dict = {}
for s in new_config_attr:
if s.name in service_dict:
buildbot.config.error(
f"Two services share the same name '{s.name}'."
"This will result in only one service being configured."
)
service_dict[s.name] = s
return service_dict
if isinstance(new_config_attr, dict):
return new_config_attr
raise TypeError(f"config.{self.config_attr} should be a list or dictionary")
@defer.inlineCallbacks
def reconfigServiceWithBuildbotConfig(self, new_config):
# arrange childs by name
old_by_name = self.namedServices
old_set = set(old_by_name)
new_by_name = self.get_service_config(new_config)
new_set = set(new_by_name)
# calculate new childs, by name, and removed childs
removed_names, added_names = util.diffSets(old_set, new_set)
# find any children for which the old instance is not
# able to do a reconfig with the new sibling
# and add them to both removed and added, so that we
# run the new version
for n in old_set & new_set:
old = old_by_name[n]
new = new_by_name[n]
# check if we are able to reconfig service
if not old.canReconfigWithSibling(new):
removed_names.add(n)
added_names.add(n)
if removed_names or added_names:
log.msg(
f"adding {len(added_names)} new {self.config_attr}, "
f"removing {len(removed_names)}"
)
for n in removed_names:
child = old_by_name[n]
# disownServiceParent calls stopService after removing the relationship
# as child might use self.master.data to stop itself, its better to stop it first
# (this is related to the fact that self.master is found by recursively looking at
# self.parent for a master)
yield child.stopService()
# it has already called, so do not call it again
child.stopService = lambda: None
yield child.disownServiceParent()
for n in added_names:
child = new_by_name[n]
# setup service's objectid
if hasattr(child, 'objectid'):
class_name = f'{child.__class__.__module__}.{child.__class__.__name__}'
objectid = yield self.master.db.state.getObjectId(child.name, class_name)
child.objectid = objectid
yield child.setServiceParent(self)
# As the services that were just added got
# reconfigServiceWithSibling called by
# setServiceParent->startService,
# we avoid calling it again by selecting
# in reconfigurable_services, services
# that were not added just now
reconfigurable_services = [svc for svc in self if svc.name not in added_names]
# sort by priority
reconfigurable_services.sort(key=lambda svc: -svc.reconfig_priority)
for svc in reconfigurable_services:
if not svc.name:
raise ValueError(f"{self}: child {svc} should have a defined name attribute")
config_sibling = new_by_name.get(svc.name)
try:
yield svc.reconfigServiceWithSibling(config_sibling)
except NotImplementedError:
# legacy support. Its too painful to transition old code to new Service life cycle
# so we implement switch of child when the service raises NotImplementedError
# Note this means that self will stop, and sibling will take ownership
# means that we have a small time where the service is unavailable.
yield svc.disownServiceParent()
config_sibling.objectid = svc.objectid
yield config_sibling.setServiceParent(self)
except Exception as e: # pragma: no cover
log.err(
e,
f'Got exception while reconfiguring {self} child service {svc.name}:\n'
f'current config dict:\n{svc.getConfigDict()}\n'
f'new config dict:\n{config_sibling.getConfigDict()}',
)
raise
| 20,842 | Python | .py | 460 | 35.341304 | 100 | 0.640974 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
4,957 | giturlparse.py | buildbot_buildbot/master/buildbot/util/giturlparse.py | # This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright Buildbot Team Members
from __future__ import annotations
import re
from typing import NamedTuple
# The regex is matching more than it should and is not intended to be an url validator.
# It is intended to efficiently and reliably extract information from the various examples
# that are described in the unit tests.
_giturlmatcher = re.compile(
r'(?P<proto>(https?://|ssh://|git://|))'
r'((?P<user>[^:@]*)(:(?P<password>.*))?@)?'
r'(?P<domain>[^\/:]+)(:((?P<port>[0-9]+)/)?|/)'
r'((?P<owner>.+)/)?(?P<repo>[^/]+?)(\.git)?$'
)
class GitUrl(NamedTuple):
proto: str
user: str | None
password: str | None
domain: str
port: int | None
owner: str | None
repo: str
def giturlparse(url: str) -> GitUrl | None:
res = _giturlmatcher.match(url)
if res is None:
return None
port = res.group("port")
if port is not None:
port = int(port)
proto = res.group("proto")
if proto:
proto = proto[:-3]
else:
proto = 'ssh' # implicit proto is ssh
return GitUrl(
proto=proto,
user=res.group('user'),
password=res.group('password'),
domain=res.group("domain"),
port=port,
owner=res.group('owner'),
repo=res.group('repo'),
)
| 1,961 | Python | .py | 55 | 31.436364 | 90 | 0.66737 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
4,958 | latent.py | buildbot_buildbot/master/buildbot/util/latent.py | # This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright Buildbot Team Members
import copy
from twisted.internet import defer
class CompatibleLatentWorkerMixin:
builds_may_be_incompatible = True
_actual_build_props = None
def renderWorkerProps(self, build):
# Deriving classes should implement this method to render and return
# a Deferred that will have all properties that are needed to start a
# worker as its result. The Deferred should result in data that can
# be copied via copy.deepcopy
#
# During actual startup, renderWorkerPropsOnStart should be called
# which will invoke renderWorkerProps, store a copy of the results for
# later comparison and return them.
raise NotImplementedError()
@defer.inlineCallbacks
def renderWorkerPropsOnStart(self, build):
props = yield self.renderWorkerProps(build)
self._actual_build_props = copy.deepcopy(props)
return props
def resetWorkerPropsOnStop(self):
self._actual_build_props = None
@defer.inlineCallbacks
def isCompatibleWithBuild(self, build):
if self._actual_build_props is None:
return True
requested_props = yield self.renderWorkerProps(build)
return requested_props == self._actual_build_props
| 1,961 | Python | .py | 42 | 41.357143 | 79 | 0.74175 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
4,959 | git_credential.py | buildbot_buildbot/master/buildbot/util/git_credential.py | # This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright Buildbot Team Members
from __future__ import annotations
from typing import ClassVar
from typing import NamedTuple
from typing import Sequence
from zope.interface import implementer
from buildbot.interfaces import IRenderable
from buildbot.util import ComparableMixin
from buildbot.util.twisted import async_to_deferred
@implementer(IRenderable)
class GitCredentialInputRenderer(ComparableMixin):
compare_attrs: ClassVar[Sequence[str]] = ('_credential_attributes',)
def __init__(self, **credential_attributes) -> None:
self._credential_attributes: dict[str, IRenderable | str] = credential_attributes
@async_to_deferred
async def getRenderingFor(self, build):
props = build.getProperties()
rendered_attributes = []
attributes = list(self._credential_attributes.items())
# git-credential-approve parsing of the `url` attribute
# will reset all other fields
# So make sure it's the first attribute in the form
if 'url' in self._credential_attributes:
attributes.sort(key=lambda e: e[0] != "url")
for key, value in attributes:
rendered_value = await props.render(value)
if rendered_value is not None:
rendered_attributes.append(f"{key}={rendered_value}\n")
return "".join(rendered_attributes)
class GitCredentialOptions(NamedTuple):
# Each element of `credentials` should be a `str` which is a input format for git-credential
# ref: https://git-scm.com/docs/git-credential#IOFMT
credentials: list[IRenderable | str]
# value to set the git config `credential.useHttpPath` to.
# ref: https://git-scm.com/docs/gitcredentials#Documentation/gitcredentials.txt-useHttpPath
use_http_path: bool | None = None
def add_user_password_to_credentials(
auth_credentials: tuple[IRenderable | str, IRenderable | str],
url: IRenderable | str | None,
credential_options: GitCredentialOptions | None,
) -> GitCredentialOptions:
if credential_options is None:
credential_options = GitCredentialOptions(credentials=[])
else:
# create a new instance to avoid side-effects
credential_options = GitCredentialOptions(
credentials=credential_options.credentials[:],
use_http_path=credential_options.use_http_path,
)
username, password = auth_credentials
credential_options.credentials.insert(
0,
IRenderable( # placate typing
GitCredentialInputRenderer(
url=url,
username=username,
password=password,
)
),
)
return credential_options
| 3,368 | Python | .py | 74 | 39.391892 | 96 | 0.717863 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
4,960 | private_tempdir.py | buildbot_buildbot/master/buildbot/util/private_tempdir.py | # This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright Buildbot Team Members
import os
import shutil
import stat
import sys
import tempfile
class PrivateTemporaryDirectory:
"""Works similarly to python 3.2+ TemporaryDirectory except the
also sets the permissions of the created directory and
Note, that Windows ignores the permissions.
"""
def __init__(self, suffix=None, prefix=None, dir=None, mode=0o700):
self.name = tempfile.mkdtemp(suffix, prefix, dir)
self.mode = mode
self._cleanup_needed = True
def __enter__(self):
return self.name
def __exit__(self, exc, value, tb):
self.cleanup()
def cleanup(self):
if self._cleanup_needed:
def remove_readonly(func, path, _):
"""Workaround Permission Error on Windows if any files in path are read-only.
See https://docs.python.org/3/library/shutil.html#rmtree-example
"""
os.chmod(path, stat.S_IWRITE)
func(path)
if sys.version_info >= (3, 12):
shutil.rmtree(self.name, onexc=remove_readonly)
else:
shutil.rmtree(self.name, onerror=remove_readonly)
self._cleanup_needed = False
| 1,904 | Python | .py | 45 | 35.733333 | 93 | 0.683442 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
4,961 | tuplematch.py | buildbot_buildbot/master/buildbot/util/tuplematch.py | # This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright Buildbot Team Members
def matchTuple(routingKey, filter):
if len(filter) != len(routingKey):
return False
for k, f in zip(routingKey, filter):
if f is not None and f != k:
return False
return True
| 922 | Python | .py | 21 | 40.904762 | 79 | 0.74861 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
4,962 | misc.py | buildbot_buildbot/master/buildbot/util/misc.py | # This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright Buildbot Team Members
"""
Miscellaneous utilities; these should be imported from C{buildbot.util}, not
directly from this module.
"""
import os
from twisted.internet import reactor
def deferredLocked(lock_or_attr):
def decorator(fn):
def wrapper(*args, **kwargs):
lock = lock_or_attr
if isinstance(lock, str):
lock = getattr(args[0], lock)
return lock.run(fn, *args, **kwargs)
return wrapper
return decorator
def cancelAfter(seconds, deferred, _reactor=reactor):
delayedCall = _reactor.callLater(seconds, deferred.cancel)
# cancel the delayedCall when the underlying deferred fires
@deferred.addBoth
def cancelTimer(x):
if delayedCall.active():
delayedCall.cancel()
return x
return deferred
def writeLocalFile(path, contents, mode=None): # pragma: no cover
with open(path, 'w', encoding='utf-8') as file:
if mode is not None:
os.chmod(path, mode)
file.write(contents)
def chunkify_list(l, chunk_size):
chunk_size = max(1, chunk_size)
return (l[i : i + chunk_size] for i in range(0, len(l), chunk_size))
| 1,865 | Python | .py | 46 | 35.673913 | 79 | 0.710803 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
4,963 | async_sort.py | buildbot_buildbot/master/buildbot/util/async_sort.py | # Copyright Buildbot Team Members
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
from twisted.internet import defer
@defer.inlineCallbacks
def async_sort(l, key, max_parallel=10):
"""perform an asynchronous sort with parallel run of the key algorithm"""
sem = defer.DeferredSemaphore(max_parallel)
try:
keys = yield defer.gatherResults([sem.run(key, i) for i in l], consumeErrors=True)
except defer.FirstError as e:
raise e.subFailure.value from e
# Index the keys by the id of the original item in list
keys = {id(l[i]): v for i, v in enumerate(keys)}
# now we can sort the list in place
l.sort(key=lambda x: keys[id(x)])
| 1,690 | Python | .py | 33 | 48.545455 | 90 | 0.76303 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
4,964 | _notifier.py | buildbot_buildbot/master/buildbot/util/_notifier.py | # Copyright Buildbot Team Members
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
from twisted.internet.defer import Deferred
class Notifier:
def __init__(self):
self._waiters = []
def wait(self):
d = Deferred()
self._waiters.append(d)
return d
def notify(self, result):
if self._waiters:
waiters = self._waiters
self._waiters = []
for waiter in waiters:
waiter.callback(result)
def __bool__(self):
return bool(self._waiters)
| 1,560 | Python | .py | 36 | 38.916667 | 72 | 0.727093 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
4,965 | lru.py | buildbot_buildbot/master/buildbot/util/lru.py | # This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright Buildbot Team Members
from collections import defaultdict
from collections import deque
from itertools import filterfalse
from weakref import WeakValueDictionary
from twisted.internet import defer
from twisted.python import log
class LRUCache:
"""
A least-recently-used cache, with a fixed maximum size.
See buildbot manual for more information.
"""
__slots__ = (
'max_size max_queue miss_fn queue cache weakrefs refcount hits refhits misses'.split()
)
sentinel = object()
QUEUE_SIZE_FACTOR = 10
def __init__(self, miss_fn, max_size=50):
self.max_size = max_size
self.max_queue = max_size * self.QUEUE_SIZE_FACTOR
self.queue = deque()
self.cache = {}
self.weakrefs = WeakValueDictionary()
self.hits = self.misses = self.refhits = 0
self.refcount = defaultdict(lambda: 0)
self.miss_fn = miss_fn
def put(self, key, value):
cached = key in self.cache or key in self.weakrefs
self.cache[key] = value
self.weakrefs[key] = value
self._ref_key(key)
if not cached:
self._purge()
def get(self, key, **miss_fn_kwargs):
try:
return self._get_hit(key)
except KeyError:
pass
self.misses += 1
result = self.miss_fn(key, **miss_fn_kwargs)
if result is not None:
self.cache[key] = result
self.weakrefs[key] = result
self._ref_key(key)
self._purge()
return result
def keys(self):
return list(self.cache)
def set_max_size(self, max_size):
if self.max_size == max_size:
return
self.max_size = max_size
self.max_queue = max_size * self.QUEUE_SIZE_FACTOR
self._purge()
def inv(self):
global inv_failed
# the keys of the queue and cache should be identical
cache_keys = set(self.cache.keys())
queue_keys = set(self.queue)
if queue_keys - cache_keys:
log.msg("INV: uncached keys in queue:", queue_keys - cache_keys)
inv_failed = True
if cache_keys - queue_keys:
log.msg("INV: unqueued keys in cache:", cache_keys - queue_keys)
inv_failed = True
# refcount should always represent the number of times each key appears
# in the queue
exp_refcount = {}
for k in self.queue:
exp_refcount[k] = exp_refcount.get(k, 0) + 1
if exp_refcount != self.refcount:
log.msg("INV: refcounts differ:")
log.msg(" expected:", sorted(exp_refcount.items()))
log.msg(" got:", sorted(self.refcount.items()))
inv_failed = True
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 recent access. Note that this
# is only required when the cache does not exceed its maximum
# size
if len(queue) > self.max_queue:
refcount.clear()
queue_appendleft = queue.appendleft
queue_appendleft(self.sentinel)
for k in filterfalse(refcount.__contains__, iter(queue.pop, self.sentinel)):
queue_appendleft(k)
refcount[k] = 1
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]
self.refhits += 1
self.cache[key] = result
self._ref_key(key)
return result
def _purge(self):
"""
Trim the cache down to max_size by evicting the
least-recently-used entries.
"""
if len(self.cache) <= self.max_size:
return
cache = self.cache
refcount = self.refcount
queue = self.queue
max_size = self.max_size
# purge least recently used entries, using refcount to count entries
# that appear multiple times in the queue
while len(cache) > max_size:
refc = 1
while refc:
k = queue.popleft()
refc = refcount[k] = refcount[k] - 1
del cache[k]
del refcount[k]
class AsyncLRUCache(LRUCache):
"""
An LRU cache with asynchronous locking to ensure that in the common case of
multiple concurrent requests for the same key, only one fetch is performed.
"""
__slots__ = ['concurrent']
def __init__(self, miss_fn, max_size=50):
super().__init__(miss_fn, max_size=max_size)
self.concurrent = {}
def get(self, key, **miss_fn_kwargs):
try:
result = self._get_hit(key)
return defer.succeed(result)
except KeyError:
pass
concurrent = self.concurrent
conc = concurrent.get(key)
if conc:
self.hits += 1
d = defer.Deferred()
conc.append(d)
return d
# if we're here, we've missed and need to fetch
self.misses += 1
# create a list of waiting deferreds for this key
d = defer.Deferred()
assert key not in concurrent
concurrent[key] = [d]
miss_d = self.miss_fn(key, **miss_fn_kwargs)
def handle_result(result):
if result is not None:
self.cache[key] = result
self.weakrefs[key] = result
# reference the key once, possibly standing in for multiple
# concurrent accesses
self._ref_key(key)
self._purge()
# and fire all of the waiting Deferreds
dlist = concurrent.pop(key)
for d in dlist:
d.callback(result)
def handle_failure(f):
# errback all of the waiting Deferreds
dlist = concurrent.pop(key)
for d in dlist:
d.errback(f)
miss_d.addCallbacks(handle_result, handle_failure)
miss_d.addErrback(log.err)
return d
# for tests
inv_failed = False
| 7,150 | Python | .py | 190 | 28.463158 | 94 | 0.59919 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
4,966 | deferwaiter.py | buildbot_buildbot/master/buildbot/util/deferwaiter.py | # This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright Buildbot Team Members
from twisted.internet import defer
from twisted.python import failure
from twisted.python import log
from buildbot.util import Notifier
class DeferWaiter:
"""This class manages a set of Deferred objects and allows waiting for their completion"""
def __init__(self):
self._waited_count = 0
self._finish_notifier = Notifier()
def _finished(self, result, d):
# most likely nothing is consuming the errors, so do it here
if isinstance(result, failure.Failure):
log.err(result)
self._waited_count -= 1
if self._waited_count == 0:
self._finish_notifier.notify(None)
return result
def add(self, d):
if not isinstance(d, defer.Deferred):
return None
self._waited_count += 1
d.addBoth(self._finished, d)
return d
def has_waited(self):
return self._waited_count > 0
@defer.inlineCallbacks
def wait(self):
if self._waited_count == 0:
return
yield self._finish_notifier.wait()
class RepeatedActionHandler:
"""This class handles a repeated action such as submitting keepalive requests. It integrates
with DeferWaiter to correctly control shutdown of such process.
"""
def __init__(self, reactor, waiter, interval, action, start_timer_after_action_completes=False):
self._reactor = reactor
self._waiter = waiter
self._interval = interval
self._action = action
self._enabled = False
self._timer = None
self._start_timer_after_action_completes = start_timer_after_action_completes
self._running = False
def set_interval(self, interval):
self._interval = interval
def start(self):
if self._enabled:
return
self._enabled = True
self._start_timer()
def stop(self):
if not self._enabled:
return
self._enabled = False
if self._timer:
self._timer.cancel()
self._timer = None
def delay(self):
if not self._enabled or not self._timer:
# If self._timer is None, then the action is running and timer will be started once
# it's done.
return
self._timer.reset(self._interval)
def force(self):
if not self._enabled or self._running:
return
self._timer.cancel()
self._waiter.add(self._handle_action())
def _start_timer(self):
self._timer = self._reactor.callLater(self._interval, self._handle_timeout)
@defer.inlineCallbacks
def _do_action(self):
try:
self._running = True
yield self._action()
except Exception as e:
log.err(e, 'Got exception in RepeatedActionHandler')
finally:
self._running = False
def _handle_timeout(self):
self._waiter.add(self._handle_action())
@defer.inlineCallbacks
def _handle_action(self):
self._timer = None
if self._start_timer_after_action_completes:
yield self._do_action()
if self._enabled:
self._start_timer()
if not self._start_timer_after_action_completes:
yield self._do_action()
class NonRepeatedActionHandler:
"""This class handles a single action that can be issued on demand. It ensures that multiple
invocations of an action do not overlap.
"""
def __init__(self, reactor, waiter, action):
self._reactor = reactor
self._waiter = waiter
self._action = action
self._timer = None
self._running = False
self._repeat_after_finished = False
def force(self, invoke_again_if_running=False):
if self._running:
if not invoke_again_if_running:
return
self._repeat_after_finished = True
return
if self._timer is not None:
self._timer.cancel()
self._timer = None
self._waiter.add(self._do_action())
def schedule(self, seconds_from_now, invoke_again_if_running=False):
if self._running and not invoke_again_if_running:
return
if self._timer is None:
self._timer = self._reactor.callLater(seconds_from_now, self._handle_timeout)
return
target_time = self._reactor.seconds() + seconds_from_now
if target_time > self._timer.getTime():
return
self._timer.reset(seconds_from_now)
def stop(self):
if self._timer:
self._timer.cancel()
self._timer = None
@defer.inlineCallbacks
def _do_action(self):
try:
self._running = True
yield self._action()
except Exception as e:
log.err(e, 'Got exception in NonRepeatedActionHandler')
finally:
self._running = False
if self._repeat_after_finished:
self._repeat_after_finished = False
self._waiter.add(self._do_action())
def _handle_timeout(self):
self._timer = None
self._waiter.add(self._do_action())
| 5,866 | Python | .py | 154 | 29.766234 | 100 | 0.632581 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
4,967 | importlib_compat.py | buildbot_buildbot/master/buildbot/util/importlib_compat.py | # This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright Buildbot Team Members
# This module is for backward compatibility of importlib.
def entry_points_get(entry_points, group):
"""Since Python 3.12 dictionary access is removed and replaced by new interface.
see: https://github.com/python/cpython/issues/97781
"""
if hasattr(entry_points, "select"):
return entry_points.select(group=group)
else:
if isinstance(entry_points, list):
filtered_entry_points = []
for ep in entry_points:
if ep.group == group:
filtered_entry_points.append(ep)
return filtered_entry_points
else:
return entry_points.get(group, [])
| 1,367 | Python | .py | 30 | 40.2 | 84 | 0.713643 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
4,968 | db.py | buildbot_buildbot/master/buildbot/plugins/db.py | # This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright Buildbot Team Members
#
# pylint: disable=C0111
import traceback
import warnings
from importlib.metadata import distributions
from importlib.metadata import entry_points
from zope.interface import Invalid
from zope.interface.verify import verifyClass
from buildbot.errors import PluginDBError
from buildbot.interfaces import IPlugin
from buildbot.util.importlib_compat import entry_points_get
# Base namespace for Buildbot specific plugins
_NAMESPACE_BASE = 'buildbot'
def find_distribution_info(entry_point_name, entry_point_group):
for distribution in distributions():
# each distribution can have many entry points
try:
for ep in entry_points_get(distribution.entry_points, entry_point_group):
if ep.name == entry_point_name:
return (distribution.metadata['Name'], distribution.metadata['Version'])
except KeyError as exc:
raise PluginDBError("Plugin info was found, but it is invalid.") from exc
raise PluginDBError("Plugin info not found.")
class _PluginEntry:
def __init__(self, group, entry, loader):
self._group = group
self._entry = entry
self._value = None
self._loader = loader
self._load_warnings = []
self._info = None
def load(self):
if self._value is None:
with warnings.catch_warnings(record=True) as all_warnings:
warnings.simplefilter("always")
self._value = self._loader(self._entry)
self._load_warnings = list(all_warnings)
@property
def group(self):
return self._group
@property
def name(self):
return self._entry.name
@property
def info(self):
if self._info is None:
self._info = find_distribution_info(self._entry.name, self._group)
return self._info
def __eq__(self, other):
return self.info == other.info
def __ne__(self, other):
return not self.__eq__(other)
@property
def value(self):
self.load()
for w in self._load_warnings:
warnings.warn_explicit(w.message, w.category, w.filename, w.lineno)
return self._value
class _PluginEntryProxy(_PluginEntry):
"""Proxy for specific entry with custom group name.
Used to provided access to the same entry from different namespaces.
"""
def __init__(self, group, plugin_entry):
assert isinstance(plugin_entry, _PluginEntry)
self._plugin_entry = plugin_entry
self._group = group
def load(self):
self._plugin_entry.load()
@property
def group(self):
return self._group
@property
def name(self):
return self._plugin_entry.name
@property
def info(self):
return self._plugin_entry.info
@property
def value(self):
return self._plugin_entry.value
class _NSNode:
# pylint: disable=W0212
def __init__(self):
self._children = {}
def load(self):
for child in self._children.values():
child.load()
def add(self, name, entry):
assert isinstance(name, str) and isinstance(entry, _PluginEntry)
self._add(name, entry)
def _add(self, name, entry):
path = name.split('.', 1)
key = path.pop(0)
is_leaf = not path
child = self._children.get(key)
if is_leaf:
if child is not None:
assert isinstance(child, _PluginEntry)
if child != entry:
raise PluginDBError(
f'Duplicate entry point for "{child.group}:{child.name}".\n'
f' Previous definition {child.info}\n'
f' This definition {entry.info}'
)
else:
self._children[key] = entry
else:
if child is None:
child = _NSNode()
assert isinstance(child, _NSNode)
child._add(path[0], entry)
self._children[key] = child
def __getattr__(self, name):
child = self._children.get(name)
if child is None:
raise PluginDBError(f'Unknown component name: {name}')
if isinstance(child, _PluginEntry):
return child.value
return child
def info(self, name):
assert isinstance(name, str)
return self._get(name).info
def get(self, name):
assert isinstance(name, str)
return self._get(name).value
def _get(self, name):
path = name.split('.', 1)
key = path.pop(0)
is_leaf = not path
child = self._children.get(key)
if isinstance(child, _PluginEntry):
if not is_leaf:
raise PluginDBError(f'Excessive namespace specification: {path[0]}')
return child
elif child is None:
raise PluginDBError(f'Unknown component name: {name}')
else:
return child._get(path[0])
def _info_all(self):
result = []
for key, child in self._children.items():
if isinstance(child, _PluginEntry):
result.append((key, child.info))
else:
result.extend([
(f'{key}.{name}', value) for name, value in child.info_all().items()
])
return result
def info_all(self):
return dict(self._info_all())
class _Plugins:
"""
represent plugins within a namespace
"""
def __init__(self, namespace, interface=None):
if interface is not None:
assert interface.isOrExtends(IPlugin)
self._group = f'{_NAMESPACE_BASE}.{namespace}'
self._interface = interface
self._real_tree = None
def _load_entry(self, entry):
# pylint: disable=W0703
try:
result = entry.load()
except Exception as e:
# log full traceback of the bad entry to help support
traceback.print_exc()
raise PluginDBError(f'Unable to load {self._group}:{entry.name}: {e!s}') from e
if self._interface:
try:
verifyClass(self._interface, result)
except Invalid as e:
raise PluginDBError(
f'Plugin {self._group}:{entry.name} does not implement '
f'{self._interface.__name__}: {e!s}'
) from e
return result
@property
def _tree(self):
if self._real_tree is None:
self._real_tree = _NSNode()
entries = entry_points_get(entry_points(), self._group)
for entry in entries:
self._real_tree.add(entry.name, _PluginEntry(self._group, entry, self._load_entry))
return self._real_tree
def load(self):
self._tree.load()
def info_all(self):
return self._tree.info_all()
@property
def names(self):
# Expensive operation
return list(self.info_all())
def info(self, name):
"""
get information about a particular plugin if known in this namespace
"""
return self._tree.info(name)
def __contains__(self, name):
"""
check if the given name is available as a plugin
"""
try:
return not isinstance(self._tree.get(name), _NSNode)
except PluginDBError:
return False
def get(self, name):
"""
get an instance of the plugin with the given name
"""
return self._tree.get(name)
def _get_entry(self, name):
return self._tree._get(name)
def __getattr__(self, name):
try:
return getattr(self._tree, name)
except PluginDBError as e:
raise AttributeError(str(e)) from e
class _PluginDB:
"""
Plugin infrastructure support for Buildbot
"""
def __init__(self):
self._namespaces = {}
def add_namespace(self, namespace, interface=None, load_now=False):
"""
register given namespace in global database of plugins
in case it's already registered, return the registration
"""
tempo = self._namespaces.get(namespace)
if tempo is None:
tempo = _Plugins(namespace, interface)
self._namespaces[namespace] = tempo
if load_now:
tempo.load()
return tempo
@property
def namespaces(self):
"""
get a list of registered namespaces
"""
return list(self._namespaces)
def info(self):
"""
get information about all plugins in registered namespaces
"""
result = {}
for name, namespace in self._namespaces.items():
result[name] = namespace.info_all()
return result
_DB = _PluginDB()
def namespaces():
"""
provide information about known namespaces
"""
return _DB.namespaces
def info():
"""
provide information about all known plugins
format of the output:
{<namespace>, {
{<plugin-name>: (<package-name>, <package-version),
...},
...
}
"""
return _DB.info()
def get_plugins(namespace, interface=None, load_now=False):
"""
helper to get a direct interface to _Plugins
"""
return _DB.add_namespace(namespace, interface, load_now)
| 10,089 | Python | .py | 286 | 26.72028 | 99 | 0.60512 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
4,969 | __init__.py | buildbot_buildbot/master/buildbot/plugins/__init__.py | # This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright Buildbot Team Members
"""
Buildbot plugin infrastructure
"""
from buildbot import statistics
from buildbot.interfaces import IBuildStep
from buildbot.interfaces import IChangeSource
from buildbot.interfaces import IScheduler
from buildbot.interfaces import IWorker
from buildbot.plugins.db import get_plugins
__all__ = [
'changes',
'schedulers',
'steps',
'util',
'reporters',
'statistics',
'worker',
'secrets',
'webhooks',
]
# Names here match the names of the corresponding Buildbot module, hence
# 'changes', 'schedulers', but 'buildslave'
changes = get_plugins('changes', IChangeSource)
schedulers = get_plugins('schedulers', IScheduler)
steps = get_plugins('steps', IBuildStep)
util = get_plugins('util', None)
reporters = get_plugins('reporters', None)
secrets = get_plugins('secrets', None)
webhooks = get_plugins('webhooks', None)
# Worker entry point for new/updated plugins.
worker = get_plugins('worker', IWorker)
| 1,649 | Python | .py | 45 | 34.711111 | 79 | 0.770964 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
4,970 | cleanupdb.py | buildbot_buildbot/master/buildbot/scripts/cleanupdb.py | # This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright Buildbot Team Members
from __future__ import annotations
import os
from typing import TYPE_CHECKING
from twisted.internet import defer
from buildbot import config as config_module
from buildbot.master import BuildMaster
from buildbot.scripts import base
from buildbot.util import in_reactor
if TYPE_CHECKING:
from sqlalchemy.engine import Connection
async def doCleanupDatabase(config, master_cfg) -> None:
if not config['quiet']:
print(f"cleaning database ({master_cfg.db['db_url']})")
master = BuildMaster(config['basedir'])
master.config = master_cfg
db = master.db
await db.setup(check_version=False, verbose=not config['quiet'])
res = await db.logs.getLogs()
percent = 0
saved = 0
for i, log in enumerate(res, start=1):
saved += await db.logs.compressLog(log.id, force=config['force'])
if not config['quiet'] and percent != int(i * 100 / len(res)):
percent = int(i * 100 / len(res))
print(f" {percent}% {saved} saved", flush=True)
saved = 0
assert master.db._engine is not None
vacuum_stmt = {
# https://www.postgresql.org/docs/current/sql-vacuum.html
'postgresql': f'VACUUM FULL {master.db.model.logchunks.name};',
# https://dev.mysql.com/doc/refman/5.7/en/optimize-table.html
'mysql': f'OPTIMIZE TABLE {master.db.model.logchunks.name};',
# https://www.sqlite.org/lang_vacuum.html
'sqlite': 'vacuum;',
}.get(master.db._engine.dialect.name)
if vacuum_stmt is not None:
def thd(conn: Connection) -> None:
if not config['quiet']:
print(f"executing vacuum operation '{vacuum_stmt}'...", flush=True)
# vacuum operation cannot be done in a transaction
# https://github.com/sqlalchemy/sqlalchemy/discussions/6959#discussioncomment-1251681
with conn.execution_options(isolation_level='AUTOCOMMIT'):
conn.exec_driver_sql(vacuum_stmt).close()
conn.commit()
await db.pool.do(thd)
@in_reactor
async def cleanupDatabase(config): # pragma: no cover
# we separate the actual implementation to protect unit tests
# from @in_reactor which stops the reactor
return defer.Deferred.fromCoroutine(_cleanupDatabase(config))
async def _cleanupDatabase(config) -> int:
if not base.checkBasedir(config):
return 1
config['basedir'] = os.path.abspath(config['basedir'])
orig_cwd = os.getcwd()
try:
os.chdir(config['basedir'])
with base.captureErrors(
(SyntaxError, ImportError), f"Unable to load 'buildbot.tac' from '{config['basedir']}':"
):
configFile = base.getConfigFileFromTac(config['basedir'])
with base.captureErrors(
config_module.ConfigErrors, f"Unable to load '{configFile}' from '{config['basedir']}':"
):
master_cfg = base.loadConfig(config, configFile)
if not master_cfg:
return 1
await doCleanupDatabase(config, master_cfg)
if not config['quiet']:
print("cleanup complete")
finally:
os.chdir(orig_cwd)
return 0
| 3,877 | Python | .py | 87 | 37.965517 | 100 | 0.682434 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
4,971 | sendchange.py | buildbot_buildbot/master/buildbot/scripts/sendchange.py | # This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright Buildbot Team Members
import sys
import traceback
from twisted.internet import defer
from buildbot.clients import sendchange as sendchange_client
from buildbot.util import in_reactor
@in_reactor
@defer.inlineCallbacks
def sendchange(config):
encoding = config.get('encoding', 'utf8')
who = config.get('who')
auth = config.get('auth')
master = config.get('master')
branch = config.get('branch')
category = config.get('category')
revision = config.get('revision')
properties = config.get('properties', {})
repository = config.get('repository', '')
vc = config.get('vc', None)
project = config.get('project', '')
revlink = config.get('revlink', '')
when = config.get('when')
comments = config.get('comments')
files = config.get('files', ())
codebase = config.get('codebase', None)
s = sendchange_client.Sender(master, auth, encoding=encoding)
try:
yield s.send(
branch,
revision,
comments,
files,
who=who,
category=category,
when=when,
properties=properties,
repository=repository,
vc=vc,
project=project,
revlink=revlink,
codebase=codebase,
)
except Exception:
print("change not sent:")
traceback.print_exc(file=sys.stdout)
return 1
else:
print("change sent successfully")
return 0
| 2,162 | Python | .py | 62 | 29.048387 | 79 | 0.673674 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
4,972 | user.py | buildbot_buildbot/master/buildbot/scripts/user.py | # This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright Buildbot Team Members
from twisted.internet import defer
from buildbot.clients import usersclient
from buildbot.process.users import users
from buildbot.util import in_reactor
@in_reactor
@defer.inlineCallbacks
def user(config):
master = config.get('master')
op = config.get('op')
username = config.get('username')
passwd = config.get('passwd')
master, port = master.split(":")
port = int(port)
bb_username = config.get('bb_username')
bb_password = config.get('bb_password')
if bb_username or bb_password:
bb_password = users.encrypt(bb_password)
info = config.get('info')
ids = config.get('ids')
# find identifier if op == add
if info and op == 'add':
for user in info:
user['identifier'] = sorted(user.values())[0]
uc = usersclient.UsersClient(master, username, passwd, port)
output = yield uc.send(op, bb_username, bb_password, ids, info)
if output:
print(output)
return 0
| 1,671 | Python | .py | 42 | 36.119048 | 79 | 0.725478 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
4,973 | upgrade_master.py | buildbot_buildbot/master/buildbot/scripts/upgrade_master.py | # This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright Buildbot Team Members
import os
import signal
import sys
import traceback
from twisted.internet import defer
from twisted.python import util
from buildbot.db import connector
from buildbot.interfaces import IRenderable
from buildbot.master import BuildMaster
from buildbot.scripts import base
from buildbot.util import in_reactor
from buildbot.util import stripUrlPassword
def installFile(config, target, source, overwrite=False):
with open(source, encoding='utf-8') as f:
new_contents = f.read()
if os.path.exists(target):
with open(target, encoding='utf-8') as f:
old_contents = f.read()
if old_contents != new_contents:
if overwrite:
if not config['quiet']:
print(f"{target} has old/modified contents")
print(" overwriting it with new contents")
with open(target, "w", encoding='utf-8') as f:
f.write(new_contents)
else:
if not config['quiet']:
print(f"{target} has old/modified contents")
print(f" writing new contents to {target}.new")
with open(target + ".new", "w", encoding='utf-8') as f:
f.write(new_contents)
# otherwise, it's up to date
else:
if not config['quiet']:
print(f"creating {target}")
with open(target, "w", encoding='utf-8') as f:
f.write(new_contents)
def upgradeFiles(config):
if not config['quiet']:
print("upgrading basedir")
webdir = os.path.join(config['basedir'], "public_html")
if os.path.exists(webdir):
print("Notice: public_html is not used starting from Buildbot 0.9.0")
print(" consider using third party HTTP server for serving static files")
installFile(
config,
os.path.join(config['basedir'], "master.cfg.sample"),
util.sibpath(__file__, "sample.cfg"),
overwrite=True,
)
@defer.inlineCallbacks
def upgradeDatabase(config, master_cfg):
if not config['quiet']:
db_url_cfg = master_cfg.db['db_url']
if IRenderable.providedBy(db_url_cfg):
# if it's a renderable, assume the password is rendered
# so no need to try and strip it.
# Doesn't really make sense for it to be renderable with clear password
db_url = repr(db_url_cfg)
else:
db_url = stripUrlPassword(db_url_cfg)
print(f"upgrading database ({db_url})")
print("Warning: Stopping this process might cause data loss")
def sighandler(signum, frame):
msg = " ".join(
"""
WARNING: ignoring signal {}.
This process should not be interrupted to avoid database corruption.
If you really need to terminate it, use SIGKILL.
""".split()
)
print(msg.format(signum))
prev_handlers = {}
try:
for signame in ("SIGTERM", "SIGINT", "SIGQUIT", "SIGHUP", "SIGUSR1", "SIGUSR2", "SIGBREAK"):
if hasattr(signal, signame):
signum = getattr(signal, signame)
prev_handlers[signum] = signal.signal(signum, sighandler)
master = BuildMaster(config['basedir'])
master.config = master_cfg
master.db.disownServiceParent()
db = connector.DBConnector(basedir=config['basedir'])
yield db.setServiceParent(master)
yield master.secrets_manager.setup()
yield db.setup(check_version=False, verbose=not config['quiet'])
yield db.model.upgrade()
yield db.masters.setAllMastersActiveLongTimeAgo()
finally:
# restore previous signal handlers
for signum, handler in prev_handlers.items():
signal.signal(signum, handler)
@in_reactor
def upgradeMaster(config):
if not base.checkBasedir(config):
return defer.succeed(1)
os.chdir(config['basedir'])
try:
configFile = base.getConfigFileFromTac(config['basedir'])
except (SyntaxError, ImportError):
print(f"Unable to load 'buildbot.tac' from '{config['basedir']}':", file=sys.stderr)
e = traceback.format_exc()
print(e, file=sys.stderr)
return defer.succeed(1)
master_cfg = base.loadConfig(config, configFile)
if not master_cfg:
return defer.succeed(1)
return _upgradeMaster(config, master_cfg)
@defer.inlineCallbacks
def _upgradeMaster(config, master_cfg):
try:
upgradeFiles(config)
yield upgradeDatabase(config, master_cfg)
except Exception:
e = traceback.format_exc()
print("problem while upgrading!:\n" + e, file=sys.stderr)
return 1
else:
if not config['quiet']:
print("upgrade complete")
return 0
| 5,490 | Python | .py | 134 | 33.223881 | 100 | 0.651163 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
4,974 | start.py | buildbot_buildbot/master/buildbot/scripts/start.py | # This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright Buildbot Team Members
import os
import sys
from twisted.internet import protocol
from twisted.internet import reactor
from twisted.python.runtime import platformType
from buildbot.scripts import base
from buildbot.scripts.logwatcher import BuildmasterStartupError
from buildbot.scripts.logwatcher import BuildmasterTimeoutError
from buildbot.scripts.logwatcher import LogWatcher
from buildbot.scripts.logwatcher import ReconfigError
from buildbot.util import rewrap
class Follower:
def follow(self, basedir, timeout=None):
self.rc = 0
self._timeout = timeout if timeout else 10.0
print("Following twistd.log until startup finished..")
lw = LogWatcher(os.path.join(basedir, "twistd.log"), timeout=self._timeout)
d = lw.start()
d.addCallbacks(self._success, self._failure)
reactor.run()
return self.rc
def _success(self, _):
print("The buildmaster appears to have (re)started correctly.")
self.rc = 0
reactor.stop()
def _failure(self, why):
if why.check(BuildmasterTimeoutError):
print(
rewrap(f"""\
The buildmaster took more than {self._timeout} seconds to start, so we were
unable to confirm that it started correctly.
Please 'tail twistd.log' and look for a line that says
'BuildMaster is running' to verify correct startup.
""")
)
elif why.check(ReconfigError):
print(
rewrap("""\
The buildmaster appears to have encountered an error in the
master.cfg config file during startup.
Please inspect and fix master.cfg, then restart the
buildmaster.
""")
)
elif why.check(BuildmasterStartupError):
print(
rewrap("""\
The buildmaster startup failed. Please see 'twistd.log' for
possible reason.
""")
)
else:
print(
rewrap("""\
Unable to confirm that the buildmaster started correctly.
You may need to stop it, fix the config file, and restart.
""")
)
print(why)
self.rc = 1
reactor.stop()
def launchNoDaemon(config):
os.chdir(config['basedir'])
sys.path.insert(0, os.path.abspath(config['basedir']))
argv = [
"twistd",
"--no_save",
"--nodaemon",
"--logfile=twistd.log", # windows doesn't use the same default
"--python=buildbot.tac",
]
if platformType != 'win32':
# windows doesn't use pidfile option.
argv.extend(["--pidfile="])
sys.argv = argv
# this is copied from bin/twistd. twisted-2.0.0 through 2.4.0 use
# _twistw.run . Twisted-2.5.0 and later use twistd.run, even for
# windows.
from twisted.scripts import twistd
twistd.run()
def launch(config):
os.chdir(config['basedir'])
sys.path.insert(0, os.path.abspath(config['basedir']))
# see if we can launch the application without actually having to
# spawn twistd, since spawning processes correctly is a real hassle
# on windows.
argv = [
sys.executable,
"-c",
# this is copied from bin/twistd. twisted-2.0.0 through 2.4.0 use
# _twistw.run . Twisted-2.5.0 and later use twistd.run, even for
# windows.
"from twisted.scripts import twistd; twistd.run()",
"--no_save",
"--logfile=twistd.log", # windows doesn't use the same default
"--python=buildbot.tac",
]
# ProcessProtocol just ignores all output
proc = reactor.spawnProcess(protocol.ProcessProtocol(), sys.executable, argv, env=os.environ)
if platformType == "win32":
with open("twistd.pid", "w", encoding='utf-8') as pidfile:
pidfile.write(f"{proc.pid}")
def start(config):
if not base.isBuildmasterDir(config['basedir']):
return 1
if config['nodaemon']:
launchNoDaemon(config)
return 0
launch(config)
# We don't have tail on windows
if platformType == "win32" or config['quiet']:
return 0
# this is the parent
timeout = config.get('start_timeout', None)
if timeout is None:
timeout = os.getenv('START_TIMEOUT', None)
if timeout is not None:
try:
timeout = float(timeout)
except ValueError:
print('Start timeout must be a number')
return 1
rc = Follower().follow(config['basedir'], timeout=timeout)
return rc
| 5,373 | Python | .py | 138 | 30.898551 | 97 | 0.638825 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
4,975 | dataspec.py | buildbot_buildbot/master/buildbot/scripts/dataspec.py | # This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright Buildbot Team Members
import json
import os
import sys
from twisted.internet import defer
from buildbot.data import connector
from buildbot.test.fake import fakemaster
from buildbot.util import in_reactor
@in_reactor
@defer.inlineCallbacks
def dataspec(config):
master = yield fakemaster.make_master(None, wantRealReactor=True)
data = connector.DataConnector()
yield data.setServiceParent(master)
if config['out'] != '--':
dirs = os.path.dirname(config['out'])
if dirs and not os.path.exists(dirs):
os.makedirs(dirs)
f = open(config['out'], "w", encoding='utf-8')
else:
f = sys.stdout
if config['global'] is not None:
f.write("window." + config['global'] + '=')
f.write(json.dumps(data.allEndpoints(), indent=2))
f.close()
return 0
| 1,509 | Python | .py | 39 | 35.282051 | 79 | 0.73429 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
4,976 | logwatcher.py | buildbot_buildbot/master/buildbot/scripts/logwatcher.py | # This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright Buildbot Team Members
import os
import platform
from twisted.internet import defer
from twisted.internet import error
from twisted.internet import protocol
from twisted.internet import reactor
from twisted.python.failure import Failure
from buildbot.util import unicode2bytes
class FakeTransport:
disconnecting = False
class BuildmasterTimeoutError(Exception):
pass
class BuildmasterStartupError(Exception):
pass
class ReconfigError(Exception):
pass
class TailProcess(protocol.ProcessProtocol):
def outReceived(self, data):
self.lw.dataReceived(data)
def errReceived(self, data):
self.lw.print_output(f"ERR: '{data}'")
class LineOnlyLongLineReceiver(protocol.Protocol):
"""
This is almost the same as Twisted's LineOnlyReceiver except that long lines are handled
appropriately.
"""
_buffer = b''
delimiter = b'\r\n'
MAX_LENGTH = 16384
def dataReceived(self, data):
lines = (self._buffer + data).split(self.delimiter)
self._buffer = lines.pop(-1)
for line in lines:
if self.transport.disconnecting:
# this is necessary because the transport may be told to lose
# the connection by a line within a larger packet, and it is
# important to disregard all the lines in that packet following
# the one that told it to close.
return
if len(line) > self.MAX_LENGTH:
self.lineLengthExceeded(line)
else:
self.lineReceived(line)
def lineReceived(self, line):
raise NotImplementedError
def lineLengthExceeded(self, line):
raise NotImplementedError
class LogWatcher(LineOnlyLongLineReceiver):
POLL_INTERVAL = 0.1
TIMEOUT_DELAY = 10.0
delimiter = unicode2bytes(os.linesep)
def __init__(self, logfile, timeout=None, _reactor=reactor):
self.logfile = logfile
self.in_reconfig = False
self.transport = FakeTransport()
self.pp = TailProcess()
self.pp.lw = self
self.timer = None
self._reactor = _reactor
self._timeout_delay = timeout or self.TIMEOUT_DELAY
def start(self):
# If the log file doesn't exist, create it now.
self.create_logfile(self.logfile)
# return a Deferred that fires when the reconfig process has
# finished. It errbacks with TimeoutError if the startup has not
# progressed for 10 seconds, and with ReconfigError if the error
# line was seen. If the logfile could not be opened, it errbacks with
# an IOError.
if platform.system().lower() == 'sunos' and os.path.exists('/usr/xpg4/bin/tail'):
tailBin = "/usr/xpg4/bin/tail"
elif platform.system().lower() == 'haiku' and os.path.exists('/bin/tail'):
tailBin = "/bin/tail"
else:
tailBin = "/usr/bin/tail"
args = ("tail", "-F", "-n", "0", self.logfile)
self.p = self._reactor.spawnProcess(self.pp, tailBin, args, env=os.environ)
self.running = True
d = defer.maybeDeferred(self._start)
return d
def _start(self):
self.d = defer.Deferred()
self.startTimer()
return self.d
def startTimer(self):
self.timer = self._reactor.callLater(self._timeout_delay, self.timeout)
def timeout(self):
# was the timeout set to be ignored? if so, restart it
if not self.timer:
self.startTimer()
return
self.timer = None
e = BuildmasterTimeoutError()
self.finished(Failure(e))
def finished(self, results):
try:
self.p.signalProcess("KILL")
except error.ProcessExitedAlready:
pass
if self.timer:
self.timer.cancel()
self.timer = None
self.running = False
self.in_reconfig = False
self.d.callback(results)
def create_logfile(self, path): # pragma: no cover
if not os.path.exists(path):
with open(path, 'a', encoding='utf-8'):
pass
def print_output(self, output): # pragma: no cover
print(output)
def lineLengthExceeded(self, line):
msg = f'Got an a very long line in the log (length {len(line)} bytes), ignoring'
self.print_output(msg)
def lineReceived(self, line):
if not self.running:
return None
if b"Log opened." in line:
self.in_reconfig = True
if b"beginning configuration update" in line:
self.in_reconfig = True
if self.in_reconfig:
self.print_output(line.decode())
# certain lines indicate progress, so we "cancel" the timeout
# and it will get re-added when it fires
PROGRESS_TEXT = [
b'Starting BuildMaster',
b'Loading configuration from',
b'added builder',
b'adding scheduler',
b'Loading builder',
b'Starting factory',
]
for progressText in PROGRESS_TEXT:
if progressText in line:
self.timer = None
break
if b"message from master: attached" in line:
return self.finished("worker")
if (
b"configuration update aborted" in line
or b'configuration update partially applied' in line
):
return self.finished(Failure(ReconfigError()))
if b"Server Shut Down" in line:
return self.finished(Failure(ReconfigError()))
if b"configuration update complete" in line:
return self.finished("buildmaster")
if b"BuildMaster is running" in line:
return self.finished("buildmaster")
if b"BuildMaster startup failed" in line:
return self.finished(Failure(BuildmasterStartupError()))
return None
| 6,623 | Python | .py | 166 | 31.506024 | 92 | 0.645372 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
4,977 | windows_service.py | buildbot_buildbot/master/buildbot/scripts/windows_service.py | # pylint: disable=import-outside-toplevel
# # Runs the build-bot as a Windows service.
# To use:
# * Install and configure buildbot as per normal (ie, running
# 'setup.py install' from the source directory).
#
# * Configure any number of build-bot directories (workers or masters), as
# per the buildbot instructions. Test these directories normally by
# using the (possibly modified) "buildbot.bat" file and ensure everything
# is working as expected.
#
# * Install the buildbot service. Execute the command:
# % buildbot_windows_service
# To see installation options. You probably want to specify:
# + --username and --password options to specify the user to run the
# + --startup auto to have the service start at boot time.
#
# For example:
# % buildbot_windows_service --user mark --password secret \
# --startup auto install
# Alternatively, you could execute:
# % buildbot_windows_service install
# to install the service with default options, then use Control Panel
# to configure it.
#
# * Start the service specifying the name of all buildbot directories as
# service args. This can be done one of 2 ways:
# - Execute the command:
# % buildbot_windows_service start "dir_name1" "dir_name2"
# or:
# - Start Control Panel->Administrative Tools->Services
# - Locate the previously installed buildbot service.
# - Open the "properties" for the service.
# - Enter the directory names into the "Start Parameters" textbox. The
# directory names must be fully qualified, and surrounded in quotes if
# they include spaces.
# - Press the "Start"button.
# Note that the service will automatically use the previously specified
# directories if no arguments are specified. This means the directories
# need only be specified when the directories to use have changed (and
# therefore also the first time buildbot is configured)
#
# * The service should now be running. You should check the Windows
# event log. If all goes well, you should see some information messages
# telling you the buildbot has successfully started.
#
# * If you change the buildbot configuration, you must restart the service.
# There is currently no way to ask a running buildbot to reload the
# config. You can restart by executing:
# % buildbot_windows_service restart
#
# Troubleshooting:
# * Check the Windows event log for any errors.
# * Check the "twistd.log" file in your buildbot directories - once each
# bot has been started it just writes to this log as normal.
# * Try executing:
# % python buildbot_service.py debug
# This will execute the buildbot service in "debug" mode, and allow you to
# see all messages etc generated. If the service works in debug mode but
# not as a real service, the error probably relates to the environment or
# permissions of the user configured to run the service (debug mode runs as
# the currently logged in user, not the service user)
# * Ensure you have the latest pywin32 build available, at least version 206.
# Written by Mark Hammond, 2006.
import os
import sys
import threading
import pywintypes
import servicemanager
import win32api
import win32con
import win32event
import win32file
import win32pipe
import win32process
import win32security
import win32service
import win32serviceutil
import winerror
# Are we running in a py2exe environment?
is_frozen = hasattr(sys, "frozen")
# Taken from the Zope service support - each "child" is run as a sub-process
# (trying to run multiple twisted apps in the same process is likely to screw
# stdout redirection etc).
# Note that unlike the Zope service, we do *not* attempt to detect a failed
# client and perform restarts - buildbot itself does a good job
# at reconnecting, and Windows itself provides restart semantics should
# everything go pear-shaped.
# We execute a new thread that captures the tail of the output from our child
# process. If the child fails, it is written to the event log.
# This process is unconditional, and the output is never written to disk
# (except obviously via the event log entry)
# Size of the blocks we read from the child process's output.
CHILDCAPTURE_BLOCK_SIZE = 80
# The number of BLOCKSIZE blocks we keep as process output.
CHILDCAPTURE_MAX_BLOCKS = 200
class BBService(win32serviceutil.ServiceFramework):
_svc_name_ = 'BuildBot'
_svc_display_name_ = _svc_name_
_svc_description_ = 'Manages local buildbot workers and masters - see http://buildbot.net'
def __init__(self, args):
super().__init__(args)
# Create an event which we will use to wait on. The "service stop"
# request will set this event.
# * We must make it inheritable so we can pass it to the child
# process via the cmd-line
# * Must be manual reset so each child process and our service
# all get woken from a single set of the event.
sa = win32security.SECURITY_ATTRIBUTES()
sa.bInheritHandle = True
self.hWaitStop = win32event.CreateEvent(sa, True, False, None)
self.args = args
self.dirs = None
self.runner_prefix = None
# Patch up the service messages file in a frozen exe.
# (We use the py2exe option that magically bundles the .pyd files
# into the .zip file - so servicemanager.pyd doesn't exist.)
if is_frozen and servicemanager.RunningAsService():
msg_file = os.path.join(os.path.dirname(sys.executable), "buildbot.msg")
if os.path.isfile(msg_file):
servicemanager.Initialize("BuildBot", msg_file)
else:
self.warning(f"Strange - '{msg_file}' does not exist")
def _checkConfig(self):
# Locate our child process runner (but only when run from source)
if not is_frozen:
# Running from source
python_exe = os.path.join(sys.prefix, "python.exe")
if not os.path.isfile(python_exe):
# for ppl who build Python itself from source.
python_exe = os.path.join(sys.prefix, "PCBuild", "python.exe")
if not os.path.isfile(python_exe):
# virtualenv support
python_exe = os.path.join(sys.prefix, "Scripts", "python.exe")
if not os.path.isfile(python_exe):
self.error("Can not find python.exe to spawn subprocess")
return False
me = __file__
if me.endswith(".pyc") or me.endswith(".pyo"):
me = me[:-1]
self.runner_prefix = f'"{python_exe}" "{me}"'
else:
# Running from a py2exe built executable - our child process is
# us (but with the funky cmdline args!)
self.runner_prefix = '"' + sys.executable + '"'
# Now our arg processing - this may be better handled by a
# twisted/buildbot style config file - but as of time of writing,
# MarkH is clueless about such things!
# Note that the "arguments" you type into Control Panel for the
# service do *not* persist - they apply only when you click "start"
# on the service. When started by Windows, args are never presented.
# Thus, it is the responsibility of the service to persist any args.
# so, when args are presented, we save them as a "custom option". If
# they are not presented, we load them from the option.
self.dirs = []
if len(self.args) > 1:
dir_string = os.pathsep.join(self.args[1:])
save_dirs = True
else:
dir_string = win32serviceutil.GetServiceCustomOption(self, "directories")
save_dirs = False
if not dir_string:
self.error(
"You must specify the buildbot directories as "
"parameters to the service.\nStopping the service."
)
return False
dirs = dir_string.split(os.pathsep)
for d in dirs:
d = os.path.abspath(d)
sentinal = os.path.join(d, "buildbot.tac")
if os.path.isfile(sentinal):
self.dirs.append(d)
else:
msg = f"Directory '{d}' is not a buildbot dir - ignoring"
self.warning(msg)
if not self.dirs:
self.error("No valid buildbot directories were specified.\nStopping the service.")
return False
if save_dirs:
dir_string = os.pathsep.join(self.dirs)
win32serviceutil.SetServiceCustomOption(self, "directories", dir_string)
return True
def SvcStop(self):
# Tell the SCM we are starting the stop process.
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
# Set the stop event - the main loop takes care of termination.
win32event.SetEvent(self.hWaitStop)
# SvcStop only gets triggered when the user explicitly stops (or restarts)
# the service. To shut the service down cleanly when Windows is shutting
# down, we also need to hook SvcShutdown.
SvcShutdown = SvcStop
def SvcDoRun(self):
if not self._checkConfig():
# stopped status set by caller.
return
self.logmsg(servicemanager.PYS_SERVICE_STARTED)
child_infos = []
for bbdir in self.dirs:
self.info(f"Starting BuildBot in directory '{bbdir}'")
# hWaitStop is a Handle but the command needs the int associated
# to that Handle
hstop = int(self.hWaitStop)
cmd = f'{self.runner_prefix} --spawn {hstop} start --nodaemon {bbdir}'
h, t, output = self.createProcess(cmd)
child_infos.append((bbdir, h, t, output))
while child_infos:
handles = [self.hWaitStop] + [i[1] for i in child_infos]
rc = win32event.WaitForMultipleObjects(
handles,
0, # bWaitAll
win32event.INFINITE,
)
if rc == win32event.WAIT_OBJECT_0:
# user sent a stop service request
break
# A child process died. For now, just log the output
# and forget the process.
index = rc - win32event.WAIT_OBJECT_0 - 1
bbdir, dead_handle, _, output_blocks = child_infos[index]
status = win32process.GetExitCodeProcess(dead_handle)
output = "".join(output_blocks)
if not output:
output = (
"The child process generated no output. "
"Please check the twistd.log file in the "
"indicated directory."
)
self.warning(
f"BuildBot for directory {bbdir!r} terminated with "
f"exit code {status}.\n{output}"
)
del child_infos[index]
if not child_infos:
self.warning("All BuildBot child processes have terminated. Service stopping.")
# Either no child processes left, or stop event set.
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
# The child processes should have also seen our stop signal
# so wait for them to terminate.
for bbdir, h, t, output in child_infos:
for _ in range(10): # 30 seconds to shutdown...
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
rc = win32event.WaitForSingleObject(h, 3000)
if rc == win32event.WAIT_OBJECT_0:
break
# Process terminated - no need to try harder.
if rc == win32event.WAIT_OBJECT_0:
break
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
# If necessary, kill it
if win32process.GetExitCodeProcess(h) == win32con.STILL_ACTIVE:
self.warning(f"BuildBot process at {bbdir!r} failed to terminate - " "killing it")
win32api.TerminateProcess(h, 3)
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
# Wait for the redirect thread - it should have died as the remote
# process terminated.
# As we are shutting down, we do the join with a little more care,
# reporting progress as we wait (even though we never will <wink>)
for _ in range(5):
t.join(1)
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
if not t.is_alive():
break
else:
self.warning("Redirect thread did not stop!")
# All done.
self.logmsg(servicemanager.PYS_SERVICE_STOPPED)
#
# Error reporting/logging functions.
#
def logmsg(self, event):
# log a service event using servicemanager.LogMsg
try:
servicemanager.LogMsg(
servicemanager.EVENTLOG_INFORMATION_TYPE,
event,
(self._svc_name_, f" ({self._svc_display_name_})"),
)
except win32api.error as details:
# Failed to write a log entry - most likely problem is
# that the event log is full. We don't want this to kill us
try:
print("FAILED to write INFO event", event, ":", details)
except OSError:
# No valid stdout! Ignore it.
pass
def _dolog(self, func, msg):
try:
func(msg)
except win32api.error as details:
# Failed to write a log entry - most likely problem is
# that the event log is full. We don't want this to kill us
try:
print("FAILED to write event log entry:", details)
print(msg)
except OSError:
pass
def info(self, s):
self._dolog(servicemanager.LogInfoMsg, s)
def warning(self, s):
self._dolog(servicemanager.LogWarningMsg, s)
def error(self, s):
self._dolog(servicemanager.LogErrorMsg, s)
# Functions that spawn a child process, redirecting any output.
# Although buildbot itself does this, it is very handy to debug issues
# such as ImportErrors that happen before buildbot has redirected.
def createProcess(self, cmd):
hInputRead, hInputWriteTemp = self.newPipe()
hOutReadTemp, hOutWrite = self.newPipe()
pid = win32api.GetCurrentProcess()
# This one is duplicated as inheritable.
hErrWrite = win32api.DuplicateHandle(
pid, hOutWrite, pid, 0, 1, win32con.DUPLICATE_SAME_ACCESS
)
# These are non-inheritable duplicates.
hOutRead = self.dup(hOutReadTemp)
hInputWrite = self.dup(hInputWriteTemp)
# dup() closed hOutReadTemp, hInputWriteTemp
si = win32process.STARTUPINFO()
si.hStdInput = hInputRead
si.hStdOutput = hOutWrite
si.hStdError = hErrWrite
si.dwFlags = win32process.STARTF_USESTDHANDLES | win32process.STARTF_USESHOWWINDOW
si.wShowWindow = win32con.SW_HIDE
# pass True to allow handles to be inherited. Inheritance is
# problematic in general, but should work in the controlled
# circumstances of a service process.
create_flags = win32process.CREATE_NEW_CONSOLE
# info is (hProcess, hThread, pid, tid)
info = win32process.CreateProcess(None, cmd, None, None, True, create_flags, None, None, si)
# (NOTE: these really aren't necessary for Python - they are closed
# as soon as they are collected)
hOutWrite.Close()
hErrWrite.Close()
hInputRead.Close()
# We don't use stdin
hInputWrite.Close()
# start a thread collecting output
blocks = []
t = threading.Thread(target=self.redirectCaptureThread, args=(hOutRead, blocks))
t.start()
return info[0], t, blocks
def redirectCaptureThread(self, handle, captured_blocks):
# One of these running per child process we are watching. It
# handles both stdout and stderr on a single handle. The read data is
# never referenced until the thread dies - so no need for locks
# around self.captured_blocks.
# self.info("Redirect thread starting")
while True:
try:
_, data = win32file.ReadFile(handle, CHILDCAPTURE_BLOCK_SIZE)
except pywintypes.error as err:
# ERROR_BROKEN_PIPE means the child process closed the
# handle - ie, it terminated.
if err[0] != winerror.ERROR_BROKEN_PIPE:
self.warning(f"Error reading output from process: {err}")
break
captured_blocks.append(data)
del captured_blocks[CHILDCAPTURE_MAX_BLOCKS:]
handle.Close()
# self.info("Redirect capture thread terminating")
def newPipe(self):
sa = win32security.SECURITY_ATTRIBUTES()
sa.bInheritHandle = True
return win32pipe.CreatePipe(sa, 0)
def dup(self, pipe):
# create a duplicate handle that is not inherited, so that
# it can be closed in the parent. close the original pipe in
# the process.
pid = win32api.GetCurrentProcess()
dup = win32api.DuplicateHandle(pid, pipe, pid, 0, 0, win32con.DUPLICATE_SAME_ACCESS)
pipe.Close()
return dup
# Service registration and startup
def RegisterWithFirewall(exe_name, description):
# Register our executable as an exception with Windows Firewall.
# taken from http://msdn.microsoft.com/library/default.asp?url=\
# /library/en-us/ics/ics/wf_adding_an_application.asp
from win32com.client import Dispatch
# Scope
NET_FW_SCOPE_ALL = 0
# IP Version - ANY is the only allowable setting for now
NET_FW_IP_VERSION_ANY = 2
fwMgr = Dispatch("HNetCfg.FwMgr")
# Get the current profile for the local firewall policy.
profile = fwMgr.LocalPolicy.CurrentProfile
app = Dispatch("HNetCfg.FwAuthorizedApplication")
app.ProcessImageFileName = exe_name
app.Name = description
app.Scope = NET_FW_SCOPE_ALL
# Use either Scope or RemoteAddresses, but not both
# app.RemoteAddresses = "*"
app.IpVersion = NET_FW_IP_VERSION_ANY
app.Enabled = True
# Use this line if you want to add the app, but disabled.
# app.Enabled = False
profile.AuthorizedApplications.Add(app)
# A custom install function.
def CustomInstall(opts):
# Register this process with the Windows Firewall
import pythoncom
try:
RegisterWithFirewall(sys.executable, "BuildBot")
except pythoncom.com_error as why:
print("FAILED to register with the Windows firewall")
print(why)
# Magic code to allow shutdown. Note that this code is executed in
# the *child* process, by way of the service process executing us with
# special cmdline args (which includes the service stop handle!)
def _RunChild(runfn):
del sys.argv[1] # The --spawn arg.
# Create a new thread that just waits for the event to be signalled.
t = threading.Thread(target=_WaitForShutdown, args=(int(sys.argv[1]),))
del sys.argv[1] # The stop handle
# This child process will be sent a console handler notification as
# users log off, or as the system shuts down. We want to ignore these
# signals as the service parent is responsible for our shutdown.
def ConsoleHandler(what):
# We can ignore *everything* - ctrl+c will never be sent as this
# process is never attached to a console the user can press the
# key in!
return True
win32api.SetConsoleCtrlHandler(ConsoleHandler, True)
t.setDaemon(True) # we don't want to wait for this to stop!
t.start()
if hasattr(sys, "frozen"):
# py2exe sets this env vars that may screw our child process - reset
del os.environ["PYTHONPATH"]
# Start the buildbot/worker app
runfn()
print("Service child process terminating normally.")
def _WaitForShutdown(h):
win32event.WaitForSingleObject(h, win32event.INFINITE)
print("Shutdown requested")
from twisted.internet import reactor
reactor.callLater(0, reactor.stop)
def DetermineRunner(bbdir):
"""Checks if the given directory is a worker or a master and returns the
appropriate run function."""
tacfile = os.path.join(bbdir, 'buildbot.tac')
if not os.path.exists(tacfile):
# No tac-file - use master runner by default.
import buildbot.scripts.runner
return buildbot.scripts.runner.run
with open(tacfile, encoding='utf-8') as f:
contents = f.read()
try:
if 'import Worker' in contents:
import buildbot_worker.scripts.runner
return buildbot_worker.scripts.runner.run
except ImportError:
# Not a worker.
pass
try:
if 'import BuildSlave' in contents:
import buildslave.scripts.runner # type: ignore[import-not-found]
return buildslave.scripts.runner.run
except ImportError:
# Not an old buildslave.
pass
# Treat as master by default.
import buildbot.scripts.runner
return buildbot.scripts.runner.run
# This function is also called by the py2exe startup code.
def HandleCommandLine():
if len(sys.argv) > 1 and sys.argv[1] == "--spawn":
# Special command-line created by the service to execute the
# child-process.
# First arg is the handle to wait on
# Fourth arg is the config directory to use for the buildbot/worker
_RunChild(DetermineRunner(sys.argv[5]))
else:
win32serviceutil.HandleCommandLine(BBService, customOptionHandler=CustomInstall)
if __name__ == '__main__':
HandleCommandLine()
| 21,896 | Python | .py | 475 | 37.783158 | 100 | 0.656334 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
4,978 | reconfig.py | buildbot_buildbot/master/buildbot/scripts/reconfig.py | # This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright Buildbot Team Members
import os
import platform
import signal
from twisted.internet import defer
from twisted.internet import reactor
from buildbot.scripts.logwatcher import BuildmasterTimeoutError
from buildbot.scripts.logwatcher import LogWatcher
from buildbot.scripts.logwatcher import ReconfigError
from buildbot.util import in_reactor
from buildbot.util import rewrap
class Reconfigurator:
@defer.inlineCallbacks
def run(self, basedir, quiet, timeout=None):
# Returns "Microsoft" for Vista and "Windows" for other versions
if platform.system() in ("Windows", "Microsoft"):
print("Reconfig (through SIGHUP) is not supported on Windows.")
return None
with open(os.path.join(basedir, "twistd.pid"), encoding='utf-8') as f:
self.pid = int(f.read().strip())
if quiet:
os.kill(self.pid, signal.SIGHUP)
return None
# keep reading twistd.log. Display all messages between "loading
# configuration from ..." and "configuration update complete" or
# "I will keep using the previous config file instead.", or until
# `timeout` seconds have elapsed.
self.sent_signal = False
reactor.callLater(0.2, self.sighup)
lw = LogWatcher(os.path.join(basedir, "twistd.log"), timeout=timeout)
try:
yield lw.start()
print("Reconfiguration appears to have completed successfully")
return 0
except BuildmasterTimeoutError:
print("Never saw reconfiguration finish.")
except ReconfigError:
print(
rewrap("""\
Reconfiguration failed. Please inspect the master.cfg file for
errors, correct them, then try 'buildbot reconfig' again.
""")
)
except OSError:
# we were probably unable to open the file in the first place
self.sighup()
except Exception as e:
print(f"Error while following twistd.log: {e}")
return 1
def sighup(self):
if self.sent_signal:
return
print(f"sending SIGHUP to process {self.pid}")
self.sent_signal = True
os.kill(self.pid, signal.SIGHUP)
@in_reactor
def reconfig(config):
basedir = config['basedir']
quiet = config['quiet']
timeout = config.get('progress_timeout', None)
if timeout is not None:
try:
timeout = float(timeout)
except ValueError:
print('Progress timeout must be a number')
return 1
r = Reconfigurator()
return r.run(basedir, quiet, timeout=timeout)
| 3,360 | Python | .py | 81 | 34.098765 | 79 | 0.676272 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
4,979 | create_master.py | buildbot_buildbot/master/buildbot/scripts/create_master.py | # This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright Buildbot Team Members
import os
import jinja2
from twisted.internet import defer
from twisted.python import util
from buildbot.config import master as config_master
from buildbot.master import BuildMaster
from buildbot.util import in_reactor
def makeBasedir(config):
if os.path.exists(config['basedir']):
if not config['quiet']:
print("updating existing installation")
return
if not config['quiet']:
print("mkdir", config['basedir'])
os.mkdir(config['basedir'])
def makeTAC(config):
# render buildbot_tac.tmpl using the config
loader = jinja2.FileSystemLoader(os.path.dirname(__file__))
env = jinja2.Environment(loader=loader, undefined=jinja2.StrictUndefined)
env.filters['repr'] = repr
tpl = env.get_template('buildbot_tac.tmpl')
cxt = dict((k.replace('-', '_'), v) for k, v in config.items())
contents = tpl.render(cxt)
tacfile = os.path.join(config['basedir'], "buildbot.tac")
if os.path.exists(tacfile):
with open(tacfile, encoding='utf-8') as f:
oldcontents = f.read()
if oldcontents == contents:
if not config['quiet']:
print("buildbot.tac already exists and is correct")
return
if not config['quiet']:
print("not touching existing buildbot.tac")
print("creating buildbot.tac.new instead")
tacfile += ".new"
with open(tacfile, "w", encoding='utf-8') as f:
f.write(contents)
def makeSampleConfig(config):
source = util.sibpath(__file__, "sample.cfg")
target = os.path.join(config['basedir'], "master.cfg.sample")
if not config['quiet']:
print(f"creating {target}")
with open(source, encoding='utf-8') as f:
config_sample = f.read()
if config['db']:
config_sample = config_sample.replace('sqlite:///state.sqlite', config['db'])
with open(target, "w", encoding='utf-8') as f:
f.write(config_sample)
os.chmod(target, 0o600)
@defer.inlineCallbacks
def createDB(config):
# create a master with the default configuration, but with db_url
# overridden
master_cfg = config_master.MasterConfig()
master_cfg.db['db_url'] = config['db']
master = BuildMaster(config['basedir'])
master.config = master_cfg
db = master.db
yield db.setup(check_version=False, verbose=not config['quiet'])
if not config['quiet']:
print(f"creating database ({master_cfg.db['db_url']})")
yield db.model.upgrade()
@in_reactor
@defer.inlineCallbacks
def createMaster(config):
makeBasedir(config)
makeTAC(config)
makeSampleConfig(config)
yield createDB(config)
if not config['quiet']:
print(f"buildmaster configured in {config['basedir']}")
return 0
| 3,461 | Python | .py | 86 | 35.05814 | 85 | 0.692468 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
4,980 | runner.py | buildbot_buildbot/master/buildbot/scripts/runner.py | # This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright Buildbot Team Members
#
# N.B.: don't import anything that might pull in a reactor yet. Some of our
# subcommands want to load modules that need the gtk reactor.
#
# Also don't forget to mirror your changes on command-line options in manual
# pages and reStructuredText documentation.
from __future__ import annotations
import getpass
import sys
import textwrap
from typing import Any
import sqlalchemy as sa
from twisted.python import reflect
from twisted.python import usage
import buildbot
from buildbot.scripts import base
from buildbot.util import check_functional_environment
# Note that the terms 'options' and 'config' are used interchangeably here - in
# fact, they are interchanged several times. Caveat legator.
def validateMasterOption(master):
"""
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
"""
try:
_, port = master.split(":")
port = int(port)
except (TypeError, ValueError) as e:
raise usage.UsageError("master must have the form 'hostname:port'") from e
class UpgradeMasterOptions(base.BasedirMixin, base.SubcommandOptions):
subcommandFunction = "buildbot.scripts.upgrade_master.upgradeMaster"
optFlags = [
["quiet", "q", "Do not emit the commands being run"],
[
"develop",
"d",
"link to buildbot dir rather than copy, with no JS optimization (UNIX only)",
],
["replace", "r", "Replace any modified files without confirmation."],
]
optParameters: list[tuple[str, str | None, Any, str]] = []
def getSynopsis(self):
return "Usage: buildbot upgrade-master [options] [<basedir>]"
longdesc = textwrap.dedent("""
This command takes an existing buildmaster working directory and
adds/modifies the files there to work with the current version of
buildbot. When this command is finished, the buildmaster directory should
look much like a brand-new one created by the 'create-master' command.
Use this after you've upgraded your buildbot installation and before you
restart the buildmaster to use the new version.
If you have modified the files in your working directory, this command
will leave them untouched, but will put the new recommended contents in a
.new file (for example, if index.html has been modified, this command
will create index.html.new). You can then look at the new version and
decide how to merge its contents into your modified file.
When upgrading the database, this command uses the database specified in
the master configuration file. If you wish to use a database other than
the default (sqlite), be sure to set that parameter before upgrading.
""")
class CreateMasterOptions(base.BasedirMixin, base.SubcommandOptions):
subcommandFunction = "buildbot.scripts.create_master.createMaster"
optFlags = [
["quiet", "q", "Do not emit the commands being run"],
["force", "f", "Re-use an existing directory (will not overwrite master.cfg file)"],
["relocatable", "r", "Create a relocatable buildbot.tac"],
[
"develop",
"d",
"link to buildbot dir rather than copy, with no JS optimization (UNIX only)",
],
["no-logrotate", "n", "Do not permit buildmaster rotate logs by itself"],
]
optParameters = [
["config", "c", "master.cfg", "name of the buildmaster config file"],
["log-size", "s", 10000000, "size at which to rotate twisted log files", int],
["log-count", "l", 10, "limit the number of kept old twisted log files"],
[
"db",
None,
"sqlite:///state.sqlite",
"which DB to use for scheduler/status state. See below for syntax.",
],
]
def getSynopsis(self):
return "Usage: buildbot create-master [options] [<basedir>]"
longdesc = textwrap.dedent("""
This command creates a buildmaster working directory and buildbot.tac file.
The master will live in <basedir> (defaults to the current directory)
and create various files there.
If --relocatable is given, then the resulting buildbot.tac file will be
written such that its containing directory is assumed to be the basedir.
This is generally a good idea.
At runtime, the master will read a configuration file (named
'master.cfg' by default) in its basedir. This file should contain python
code which eventually defines a dictionary named 'BuildmasterConfig'.
The elements of this dictionary are used to configure the Buildmaster.
See doc/config.xhtml for details about what can be controlled through
this interface.
The --db string is evaluated to build the DB object, which specifies
which database the buildmaster should use to hold scheduler state and
status information. The default (which creates an SQLite database in
BASEDIR/state.sqlite) is equivalent to:
--db='sqlite:///state.sqlite'
To use a remote MySQL database instead, use something like:
--db='mysql://bbuser:bbpasswd@dbhost/bbdb'
The --db string is stored verbatim in the master.cfg.sample file, and
evaluated at 'buildbot start' time to pass a DBConnector instance into
the newly-created BuildMaster object.
""")
def postOptions(self):
super().postOptions()
# validate 'log-count' parameter
if self['log-count'] == 'None':
self['log-count'] = None
else:
try:
self['log-count'] = int(self['log-count'])
except ValueError as e:
raise usage.UsageError("log-count parameter needs to be an int or None") from e
# validate 'db' parameter
try:
# check if sqlalchemy will be able to parse specified URL
sa.engine.url.make_url(self['db'])
except sa.exc.ArgumentError as e:
raise usage.UsageError(f"could not parse database URL '{self['db']}'") from e
class StopOptions(base.BasedirMixin, base.SubcommandOptions):
subcommandFunction = "buildbot.scripts.stop.stop"
optFlags = [
["quiet", "q", "Do not emit the commands being run"],
["clean", "c", "Clean shutdown master"],
["no-wait", None, "Don't wait for complete master shutdown"],
]
def getSynopsis(self):
return "Usage: buildbot stop [<basedir>]"
class RestartOptions(base.BasedirMixin, base.SubcommandOptions):
subcommandFunction = "buildbot.scripts.restart.restart"
optFlags = [
['quiet', 'q', "Don't display startup log messages"],
['nodaemon', None, "Don't daemonize (stay in foreground)"],
["clean", "c", "Clean shutdown master"],
]
optParameters = [
[
'start_timeout',
None,
None,
'The amount of time the script waits for the master to restart until '
'it declares the operation as failure',
],
]
def getSynopsis(self):
return "Usage: buildbot restart [<basedir>]"
class StartOptions(base.BasedirMixin, base.SubcommandOptions):
subcommandFunction = "buildbot.scripts.start.start"
optFlags = [
['quiet', 'q', "Don't display startup log messages"],
['nodaemon', None, "Don't daemonize (stay in foreground)"],
]
optParameters = [
[
'start_timeout',
None,
None,
'The amount of time the script waits for the master to start until it '
'declares the operation as failure',
],
]
def getSynopsis(self):
return "Usage: buildbot start [<basedir>]"
class ReconfigOptions(base.BasedirMixin, base.SubcommandOptions):
subcommandFunction = "buildbot.scripts.reconfig.reconfig"
optFlags = [
['quiet', 'q', "Don't display log messages about reconfiguration"],
]
optParameters = [
[
'progress_timeout',
None,
None,
'The amount of time the script waits for messages in the logs that indicate progress.',
],
]
def getSynopsis(self):
return "Usage: buildbot reconfig [<basedir>]"
class SendChangeOptions(base.SubcommandOptions):
subcommandFunction = "buildbot.scripts.sendchange.sendchange"
def __init__(self):
super().__init__()
self['properties'] = {}
optParameters = [
("master", "m", None, "Location of the buildmaster's PBChangeSource (host:port)"),
# deprecated in 0.8.3; remove in 0.8.5 (bug #1711)
(
"auth",
"a",
'change:changepw',
"Authentication token - username:password, or prompt for password",
),
("who", "W", None, "Author of the commit"),
("repository", "R", '', "Repository specifier"),
(
"vc",
"s",
None,
"The VC system in use, one of: cvs, svn, darcs, hg, bzr, git, mtn, p4",
),
("project", "P", '', "Project specifier"),
("branch", "b", None, "Branch specifier"),
("category", "C", None, "Category of repository"),
("codebase", None, None, "Codebase this change is in (requires 0.8.7 master or later)"),
("revision", "r", None, "Revision specifier"),
("revision_file", None, None, "Filename containing revision spec"),
("property", "p", None, "A property for the change, in the format: name:value"),
("comments", "c", None, "log message"),
("logfile", "F", None, "Read the log messages from this file (- for stdin)"),
("when", "w", None, "timestamp to use as the change time"),
("revlink", "l", '', "Revision link (revlink)"),
("encoding", "e", 'utf8', "Encoding of other parameters"),
]
buildbotOptions = [
['master', 'master'],
['who', 'who'],
['branch', 'branch'],
['category', 'category'],
['vc', 'vc'],
]
requiredOptions = ['who', 'master']
def getSynopsis(self):
return "Usage: buildbot sendchange [options] filenames.."
def parseArgs(self, *args):
self['files'] = args
def opt_property(self, property):
name, value = property.split(':', 1)
self['properties'][name] = value
def postOptions(self):
super().postOptions()
if self.get("revision_file"):
with open(self["revision_file"], encoding='utf-8') as f:
self['revision'] = f.read()
if self.get('when'):
try:
self['when'] = float(self['when'])
except (TypeError, ValueError) as e:
raise usage.UsageError(f"invalid 'when' value {self['when']}") from e
else:
self['when'] = None
if not self.get('comments') and self.get('logfile'):
if self['logfile'] == "-":
self['comments'] = sys.stdin.read()
else:
with open(self['logfile'], encoding='utf-8') as f:
self['comments'] = f.read()
if self.get('comments') is None:
self['comments'] = ""
# fix up the auth with a password if none was given
auth = self.get('auth')
if ':' not in auth:
pw = getpass.getpass(f"Enter password for '{auth}': ")
auth = f"{auth}:{pw}"
self['auth'] = tuple(auth.split(':', 1))
vcs = ['cvs', 'svn', 'darcs', 'hg', 'bzr', 'git', 'mtn', 'p4']
if self.get('vc') and self.get('vc') not in vcs:
raise usage.UsageError(f"vc must be one of {', '.join(vcs)}")
validateMasterOption(self.get('master'))
class TryOptions(base.SubcommandOptions):
subcommandFunction = "buildbot.scripts.trycmd.trycmd"
optParameters = [
["connect", "c", None, "How to reach the buildmaster, either 'ssh' or 'pb'"],
# for ssh, use --host, --username, --jobdir and optionally
# --ssh
["host", None, None, "Hostname (used by ssh) for the buildmaster"],
["port", None, None, "Port (used by ssh) for the buildmaster"],
["jobdir", None, None, "Directory (on the buildmaster host) where try jobs are deposited"],
["ssh", None, None, "Command to use instead of the default \"ssh\""],
["username", "u", None, "Username performing the try build"],
# for PB, use --master, --username, and --passwd
["master", "m", None, "Location of the buildmaster's Try server (host:port)"],
["passwd", None, None, "Password for PB authentication"],
["who", "w", None, "Who is responsible for the try build"],
["comment", "C", None, "A comment which can be used in notifications for this build"],
# for ssh to accommodate running in a virtualenv on the buildmaster
["buildbotbin", None, "buildbot", "buildbot binary to use on the buildmaster host"],
[
"diff",
None,
None,
"Filename of a patch to use instead of scanning a local tree. Use '-' for stdin.",
],
[
"patchlevel",
"p",
0,
"Number of slashes to remove from patch pathnames, like the -p option to 'patch'",
],
["baserev", None, None, "Base revision to use instead of scanning a local tree."],
[
"vc",
None,
None,
"The VC system in use, one of: bzr, cvs, darcs, git, hg, mtn, p4, svn",
],
[
"branch",
None,
None,
"The branch in use, for VC systems that can't figure it out themselves",
],
["repository", None, None, "Repository to use, instead of path to working directory."],
["builder", "b", None, "Run the trial build on this Builder. Can be used multiple times."],
[
"properties",
None,
None,
"A set of properties made available in the build environment, "
"format is --properties=prop1=value1,prop2=value2,.. "
"option can be specified multiple times.",
],
[
"property",
None,
None,
"A property made available in the build environment, "
"format:prop=value. Can be used multiple times.",
],
[
"topfile",
None,
None,
"Name of a file at the top of the tree, used to find the top. "
"Only needed for SVN and CVS.",
],
["topdir", None, None, "Path to the top of the working copy. Only needed for SVN and CVS."],
]
optFlags = [
["wait", None, "wait until the builds have finished"],
["dryrun", 'n', "Gather info, but don't actually submit."],
[
"get-builder-names",
None,
"Get the names of available builders. Doesn't submit anything. "
"Only supported for 'pb' connections.",
],
["quiet", "q", "Don't print status of current builds while waiting."],
]
# Mapping of .buildbot/options names to command-line options
buildbotOptions = [
['try_connect', 'connect'],
# [ 'try_builders', 'builders' ], <-- handled in postOptions
['try_vc', 'vc'],
['try_branch', 'branch'],
['try_repository', 'repository'],
['try_topdir', 'topdir'],
['try_topfile', 'topfile'],
['try_host', 'host'],
['try_username', 'username'],
['try_jobdir', 'jobdir'],
['try_ssh', 'ssh'],
['try_buildbotbin', 'buildbotbin'],
['try_passwd', 'passwd'],
['try_master', 'master'],
['try_who', 'who'],
['try_comment', 'comment'],
# [ 'try_wait', 'wait' ], <-- handled in postOptions
# [ 'try_quiet', 'quiet' ], <-- handled in postOptions
# Deprecated command mappings from the quirky old days:
['try_masterstatus', 'master'],
['try_dir', 'jobdir'],
['try_password', 'passwd'],
]
def __init__(self):
super().__init__()
self['builders'] = []
self['properties'] = {}
def opt_builder(self, option):
self['builders'].append(option)
def opt_properties(self, option):
# We need to split the value of this option
# into a dictionary of properties
propertylist = option.split(",")
for prop in propertylist:
splitproperty = prop.split("=", 1)
self['properties'][splitproperty[0]] = splitproperty[1]
def opt_property(self, option):
name, _, value = option.partition("=")
self['properties'][name] = value
def opt_patchlevel(self, option):
self['patchlevel'] = int(option)
def getSynopsis(self):
return "Usage: buildbot try [options]"
def postOptions(self):
super().postOptions()
opts = self.optionsFile
if not self['builders']:
self['builders'] = opts.get('try_builders', [])
if opts.get('try_wait', False):
self['wait'] = True
if opts.get('try_quiet', False):
self['quiet'] = True
# get the global 'masterstatus' option if it's set and no master
# was specified otherwise
if not self['master']:
self['master'] = opts.get('masterstatus', None)
if self['connect'] == 'pb':
if not self['master']:
raise usage.UsageError("master location must be specified for 'pb' connections")
validateMasterOption(self['master'])
class TryServerOptions(base.SubcommandOptions):
subcommandFunction = "buildbot.scripts.tryserver.tryserver"
optParameters = [
["jobdir", None, None, "the jobdir (maildir) for submitting jobs"],
]
requiredOptions = ['jobdir']
def getSynopsis(self):
return "Usage: buildbot tryserver [options]"
def postOptions(self):
if not self['jobdir']:
raise usage.UsageError('jobdir is required')
class CheckConfigOptions(base.SubcommandOptions):
subcommandFunction = "buildbot.scripts.checkconfig.checkconfig"
optFlags = [
['quiet', 'q', "Don't display error messages or tracebacks"],
]
# on tab completion, suggest files as first argument
if hasattr(usage, 'Completions'):
# only set completion suggestion if running with
# twisted version (>=11.1.0) that supports it
compData = usage.Completions(extraActions=[usage.CompleteFiles()])
def getSynopsis(self):
return (
"Usage:\t\tbuildbot checkconfig [configFile]\n"
+ "\t\tIf not specified, the config file specified in "
+ "'buildbot.tac' from the current directory will be used"
)
def parseArgs(self, *args):
if len(args) >= 1:
self['configFile'] = args[0]
class UserOptions(base.SubcommandOptions):
subcommandFunction = "buildbot.scripts.user.user"
optParameters = [
["master", "m", None, "Location of the buildmaster's user service (host:port)"],
["username", "u", None, "Username for PB authentication"],
["passwd", "p", None, "Password for PB authentication"],
["op", None, None, "User management operation: add, remove, update, get"],
[
"bb_username",
None,
None,
"Username to set for a given user. Only available on 'update', "
"and bb_password must be given as well.",
],
[
"bb_password",
None,
None,
"Password to set for a given user. Only available on 'update', "
"and bb_username must be given as well.",
],
[
"ids",
None,
None,
"User's identifiers, used to find users in 'remove' and 'get' "
"Can be specified multiple times (--ids=id1,id2,id3)",
],
[
"info",
None,
None,
"User information in the form: --info=type=value,type=value,.. "
"Used in 'add' and 'update', can be specified multiple times. "
"Note that 'update' requires --info=id:type=value...",
],
]
buildbotOptions = [
['master', 'master'],
['user_master', 'master'],
['user_username', 'username'],
['user_passwd', 'passwd'],
]
requiredOptions = ['master']
longdesc = textwrap.dedent("""
Currently implemented types for --info= are:\n
git, svn, hg, cvs, darcs, bzr, email
""")
def __init__(self):
super().__init__()
self['ids'] = []
self['info'] = []
def opt_ids(self, option):
id_list = option.split(",")
self['ids'].extend(id_list)
def opt_info(self, option):
# splits info into type/value dictionary, appends to info
info_list = option.split(",")
info_elem = {}
if len(info_list) == 1 and '=' not in info_list[0]:
info_elem["identifier"] = info_list[0]
self['info'].append(info_elem)
else:
for info_item in info_list:
split_info = info_item.split("=", 1)
# pull identifier from update --info
if ":" in split_info[0]:
split_id = split_info[0].split(":")
info_elem["identifier"] = split_id[0]
split_info[0] = split_id[1]
info_elem[split_info[0]] = split_info[1]
self['info'].append(info_elem)
def getSynopsis(self):
return "Usage: buildbot user [options]"
def _checkValidTypes(self, info):
from buildbot.process.users import users
valid = set(["identifier", "email", *users.srcs])
for user in info:
for attr_type in user:
if attr_type not in valid:
raise usage.UsageError(
"Type not a valid attr_type, must be in: " f"{', '.join(valid)}"
)
def postOptions(self):
super().postOptions()
validateMasterOption(self.get('master'))
op = self.get('op')
if not op:
raise usage.UsageError("you must specify an operation: add, remove, update, get")
if op not in ['add', 'remove', 'update', 'get']:
raise usage.UsageError(f"bad op {op!r}, use 'add', 'remove', 'update', " "or 'get'")
if not self.get('username') or not self.get('passwd'):
raise usage.UsageError("A username and password must be given")
bb_username = self.get('bb_username')
bb_password = self.get('bb_password')
if bb_username or bb_password:
if op != 'update':
raise usage.UsageError("bb_username and bb_password only work with update")
if not bb_username or not bb_password:
raise usage.UsageError("Must specify both bb_username and bb_password or neither.")
info = self.get('info')
ids = self.get('ids')
# check for erroneous args
if not info and not ids:
raise usage.UsageError("must specify either --ids or --info")
if op in ('add', 'update'):
if ids:
raise usage.UsageError("cannot use --ids with 'add' or 'update'")
self._checkValidTypes(info)
if op == 'update':
for user in info:
if 'identifier' not in user:
raise usage.UsageError(
"no ids found in update info; "
"use: --info=id:type=value,type=value,.."
)
if op == 'add':
for user in info:
if 'identifier' in user:
raise usage.UsageError(
"identifier found in add info, use: --info=type=value,type=value,.."
)
if op in ('remove', 'get'):
if info:
raise usage.UsageError("cannot use --info with 'remove' or 'get'")
class DataSpecOption(base.BasedirMixin, base.SubcommandOptions):
subcommandFunction = "buildbot.scripts.dataspec.dataspec"
optParameters = [
['out', 'o', "dataspec.json", "output to specified path"],
['global', 'g', None, "output a js script, that sets a global, for inclusion in testsuite"],
]
def getSynopsis(self):
return "Usage: buildbot dataspec [options]"
class GenGraphQLOption(base.BasedirMixin, base.SubcommandOptions):
subcommandFunction = "buildbot.scripts.gengraphql.gengraphql"
optParameters = [
['out', 'o', "graphql.schema", "output to specified path"],
]
def getSynopsis(self):
return "Usage: buildbot graphql-schema [options]"
class DevProxyOptions(base.BasedirMixin, base.SubcommandOptions):
"""Run a fake web server serving the local ui frontend and a distant rest and websocket api.
This command required aiohttp to be installed in the virtualenv"""
subcommandFunction = "buildbot.scripts.devproxy.devproxy"
optFlags = [
["unsafe_ssl", None, "Bypass ssl certificate validation"],
]
optParameters = [
["port", "p", 8011, "http port to use"],
[
"plugins",
None,
None,
"plugin config to use. As json string e.g: "
"--plugins='{\"custom_plugin\": {\"option1\": true}}'",
],
[
"auth_cookie",
None,
None,
"TWISTED_SESSION cookie to be used for auth "
"(taken in developer console: in document.cookie variable)",
],
[
"buildbot_url",
"b",
"https://buildbot.buildbot.net",
"real buildbot url to proxy to (can be http or https)",
],
]
class CleanupDBOptions(base.BasedirMixin, base.SubcommandOptions):
subcommandFunction = "buildbot.scripts.cleanupdb.cleanupDatabase"
optFlags = [
["quiet", "q", "Do not emit the commands being run"],
["force", "f", "Force log recompression (useful when changing compression algorithm)"],
# when this command has several maintenance jobs, we should make
# them optional here. For now there is only one.
]
optParameters: list[tuple[str, str | None, Any, str]] = []
def getSynopsis(self):
return "Usage: buildbot cleanupdb [options] [<basedir>]"
longdesc = textwrap.dedent("""
This command takes an existing buildmaster working directory and
do some optimization on the database.
This command is frontend for various database maintenance jobs:
- optimiselogs: This optimization groups logs into bigger chunks
to apply higher level of compression.
This command uses the database specified in
the master configuration file. If you wish to use a database other than
the default (sqlite), be sure to set that parameter before upgrading.
""")
class CopyDBOptions(base.BasedirMixin, base.SubcommandOptions):
subcommandFunction = "buildbot.scripts.copydb.copy_database"
optFlags = [
('quiet', 'q', "Don't display error messages or tracebacks"),
]
def getSynopsis(self):
return "Usage: buildbot copydb <destination_url> [<basedir>]"
def parseArgs(self, *args):
if len(args) == 0:
raise usage.UsageError("incorrect number of arguments")
self['destination_url'] = args[0]
args = args[1:]
super().parseArgs(*args)
longdesc = textwrap.dedent("""
This command copies all buildbot data from source database configured in the buildbot
configuration file to the destination database. The URL of the destination database is
specified on the command line.
The destination database must be empty. The script will initialize it in the same way as if
a new Buildbot installation was created.
Source database must be already upgraded to the current Buildbot version by the "buildbot
upgrade-master" command.
""")
class Options(usage.Options):
synopsis = "Usage: buildbot <command> [command options]"
subCommands = [
[
'create-master',
None,
CreateMasterOptions,
"Create and populate a directory for a new buildmaster",
],
[
'upgrade-master',
None,
UpgradeMasterOptions,
"Upgrade an existing buildmaster directory for the current version",
],
['start', None, StartOptions, "Start a buildmaster"],
['stop', None, StopOptions, "Stop a buildmaster"],
['restart', None, RestartOptions, "Restart a buildmaster"],
[
'reconfig',
None,
ReconfigOptions,
"SIGHUP a buildmaster to make it re-read the config file",
],
[
'sighup',
None,
ReconfigOptions,
"SIGHUP a buildmaster to make it re-read the config file",
],
['sendchange', None, SendChangeOptions, "Send a change to the buildmaster"],
['try', None, TryOptions, "Run a build with your local changes"],
[
'tryserver',
None,
TryServerOptions,
"buildmaster-side 'try' support function, not for users",
],
['checkconfig', None, CheckConfigOptions, "test the validity of a master.cfg config file"],
['user', None, UserOptions, "Manage users in buildbot's database"],
['dataspec', None, DataSpecOption, "Output data api spec"],
[
'dev-proxy',
None,
DevProxyOptions,
"Run a fake web server serving the local ui frontend and a distant rest and websocket api.",
],
['graphql-schema', None, GenGraphQLOption, "Output graphql api schema"],
['cleanupdb', None, CleanupDBOptions, "cleanup the database"],
["copy-db", None, CopyDBOptions, "copy the database"],
]
def opt_version(self):
print(f"Buildbot version: {buildbot.version}")
super().opt_version()
def opt_verbose(self):
from twisted.python import log
log.startLogging(sys.stderr)
def postOptions(self):
if not hasattr(self, 'subOptions'):
raise usage.UsageError("must specify a command")
def run():
config = Options()
check_functional_environment(buildbot.config)
try:
config.parseOptions(sys.argv[1:])
except usage.error as e:
print(f"{sys.argv[0]}: {e}")
print()
c = getattr(config, 'subOptions', config)
print(str(c))
sys.exit(1)
subconfig = config.subOptions
subcommandFunction = reflect.namedObject(subconfig.subcommandFunction)
sys.exit(subcommandFunction(subconfig))
| 31,904 | Python | .py | 741 | 34.020243 | 104 | 0.603539 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
4,981 | devproxy.py | buildbot_buildbot/master/buildbot/scripts/devproxy.py | # This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright Buildbot Team Members
import asyncio
import json
import logging
import aiohttp # dev-proxy command requires aiohttp! run 'pip install aiohttp'
import aiohttp.web
import jinja2
from buildbot.plugins.db import get_plugins
log = logging.getLogger(__name__)
class DevProxy:
MAX_CONNECTIONS = 10
def __init__(self, port, next_url, plugins, unsafe_ssl, auth_cookie):
while next_url.endswith('/'):
next_url = next_url[:-1]
self.next_url = next_url
self.app = app = aiohttp.web.Application()
self.apps = get_plugins('www', None, load_now=True)
self.unsafe_ssl = unsafe_ssl
cookies = {}
if auth_cookie:
if "TWISTED_SESSION" in auth_cookie: # user pasted the whole document.cookie part!
cookies = dict(c.split("=") for c in auth_cookie.split(";"))
auth_cookie = cookies["TWISTED_SESSION"]
cookies = {'TWISTED_SESSION': auth_cookie}
logging.basicConfig(level=logging.DEBUG)
if plugins is None:
plugins = {}
else:
plugins = json.loads(plugins)
self.plugins = plugins
app.router.add_route('*', '/ws', self.ws_handler)
for path in ['/api', '/auth', '/sse', '/avatar']:
app.router.add_route('*', path + '{path:.*}', self.proxy_handler)
app.router.add_route('*', '/', self.index_handler)
for plugin in self.apps.names:
if plugin != 'base':
staticdir = self.apps.get(plugin).static_dir
app.router.add_static('/' + plugin, staticdir)
staticdir = self.staticdir = self.apps.get('base').static_dir
loader = jinja2.FileSystemLoader(staticdir)
self.jinja = jinja2.Environment(loader=loader, undefined=jinja2.StrictUndefined)
app.router.add_static('/', staticdir)
conn = aiohttp.TCPConnector(limit=self.MAX_CONNECTIONS, verify_ssl=not self.unsafe_ssl)
self.session = aiohttp.ClientSession(connector=conn, trust_env=True, cookies=cookies)
self.config = None
self.buildbotURL = f"http://localhost:{port}/"
app.on_startup.append(self.on_startup)
app.on_cleanup.append(self.on_cleanup)
aiohttp.web.run_app(app, host="localhost", port=port)
async def on_startup(self, app):
try:
await self.fetch_config_from_upstream()
except aiohttp.ClientConnectionError as e:
raise RuntimeError("Unable to connect to buildbot master" + str(e)) from e
async def on_cleanup(self, app):
await self.session.close()
async def ws_handler(self, req):
# based on https://github.com/oetiker/aio-reverse-proxy/blob/master/paraview-proxy.py
ws_server = aiohttp.web.WebSocketResponse()
await ws_server.prepare(req)
async with self.session.ws_connect(self.next_url + "/ws", headers=req.headers) as ws_client:
async def ws_forward(ws_from, ws_to):
async for msg in ws_from:
if ws_to.closed:
await ws_to.close(code=ws_to.close_code, message=msg.extra)
return
if msg.type == aiohttp.WSMsgType.TEXT:
await ws_to.send_str(msg.data)
elif msg.type == aiohttp.WSMsgType.BINARY:
await ws_to.send_bytes(msg.data)
elif msg.type == aiohttp.WSMsgType.PING:
await ws_to.ping()
elif msg.type == aiohttp.WSMsgType.PONG:
await ws_to.pong()
else:
raise ValueError(f'unexpected message type: {msg}')
# keep forwarding websocket data in both directions
await asyncio.wait(
[ws_forward(ws_server, ws_client), ws_forward(ws_client, ws_server)],
return_when=asyncio.FIRST_COMPLETED,
)
return ws_server
async def proxy_handler(self, req):
method = getattr(self.session, req.method.lower())
upstream_url = self.next_url + req.path
headers = req.headers.copy()
query = req.query
try:
# note that req.content is a StreamReader, so the data is streamed
# and not fully loaded in memory (unlike with python-requests)
async with method(
upstream_url, headers=headers, params=query, allow_redirects=False, data=req.content
) as request:
response = aiohttp.web.StreamResponse(
status=request.status, headers=request.headers
)
writer = await response.prepare(req)
while True:
chunk = await request.content.readany()
if not chunk:
break
# using writer.write instead of response.write saves a few checks
await writer.write(chunk)
return response
except aiohttp.ClientConnectionError as e:
return self.connection_error(e)
def connection_error(self, error):
return aiohttp.web.Response(
text=f'Unable to connect to upstream server {self.next_url} ({error!s})', status=502
)
async def fetch_config_from_upstream(self):
async with self.session.get(self.next_url) as request:
index = await request.content.read()
if request.status != 200:
raise RuntimeError("Unable to fetch buildbot config: " + index.decode())
# hack to parse the configjson from upstream buildbot config
start_delimiter = b'angular.module("buildbot_config", []).constant("config", '
start_index = index.index(start_delimiter)
last_index = index.index(b')</script></html>')
self.config = json.loads(index[start_index + len(start_delimiter) : last_index].decode())
# keep the original config, but remove the plugins that we don't know
for plugin in list(self.config['plugins'].keys()):
if plugin not in self.apps:
del self.config['plugins'][plugin]
log.warn("warning: Missing plugin compared to original buildbot: %s", plugin)
# add the plugins configs passed in cmdline
for k, v in self.plugins.items():
self.config['plugins'][k] = v
self.config['buildbotURL'] = self.buildbotURL
self.config['buildbotURLs'] = [self.buildbotURL, self.next_url + "/"]
async def index_handler(self, req):
tpl = self.jinja.get_template('index.html')
index = tpl.render(
configjson=json.dumps(self.config), custom_templates={}, config=self.config
)
return aiohttp.web.Response(body=index, content_type='text/html')
def devproxy(config):
DevProxy(
config['port'],
config['buildbot_url'],
config['plugins'],
config['unsafe_ssl'],
config['auth_cookie'],
)
| 7,719 | Python | .py | 157 | 38.426752 | 100 | 0.618416 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
4,982 | tryserver.py | buildbot_buildbot/master/buildbot/scripts/tryserver.py | # This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright Buildbot Team Members
import os
import sys
import time
from hashlib import md5
from buildbot.util import unicode2bytes
def tryserver(config):
jobdir = os.path.expanduser(config["jobdir"])
job = sys.stdin.read()
# now do a 'safecat'-style write to jobdir/tmp, then move atomically to
# jobdir/new . Rather than come up with a unique name randomly, I'm just
# going to MD5 the contents and prepend a timestamp.
timestring = f"{time.time()}"
m = md5()
job = unicode2bytes(job)
m.update(job)
jobhash = m.hexdigest()
fn = f"{timestring}-{jobhash}"
tmpfile = os.path.join(jobdir, "tmp", fn)
newfile = os.path.join(jobdir, "new", fn)
with open(tmpfile, "wb") as f:
f.write(job)
os.rename(tmpfile, newfile)
return 0
| 1,469 | Python | .py | 37 | 36.594595 | 79 | 0.73352 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
4,983 | copydb.py | buildbot_buildbot/master/buildbot/scripts/copydb.py | # This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright Buildbot Team Members
import os
import queue
import sqlalchemy as sa
from twisted.internet import defer
from buildbot import config as config_module
from buildbot.db import connector
from buildbot.db import exceptions
from buildbot.db import model
from buildbot.master import BuildMaster
from buildbot.scripts import base
from buildbot.util import in_reactor
from buildbot.util import misc
@in_reactor
def copy_database(config): # pragma: no cover
# we separate the actual implementation to protect unit tests
# from @in_reactor which stops the reactor
return _copy_database_in_reactor(config)
@defer.inlineCallbacks
def _copy_database_in_reactor(config):
if not base.checkBasedir(config):
return 1
print_debug = not config["quiet"]
def print_log(*args, **kwargs):
if print_debug:
print(*args, **kwargs)
config['basedir'] = os.path.abspath(config['basedir'])
with base.captureErrors(
(SyntaxError, ImportError), f"Unable to load 'buildbot.tac' from '{config['basedir']}':"
):
config_file = base.getConfigFileFromTac(config['basedir'])
with base.captureErrors(
config_module.ConfigErrors, f"Unable to load '{config_file}' from '{config['basedir']}':"
):
master_src_cfg = base.loadConfig(config, config_file)
master_dst_cfg = base.loadConfig(config, config_file)
master_dst_cfg.db["db_url"] = config["destination_url"]
print_log(f"Copying database ({master_src_cfg.db['db_url']}) to ({config['destination_url']})")
if not master_src_cfg or not master_dst_cfg:
return 1
master_src = BuildMaster(config['basedir'])
master_src.config = master_src_cfg
try:
yield master_src.db.setup(check_version=True, verbose=not config["quiet"])
except exceptions.DatabaseNotReadyError:
for l in connector.upgrade_message.format(basedir=config['basedir']).split('\n'):
print(l)
return 1
master_dst = BuildMaster(config['basedir'])
master_dst.config = master_dst_cfg
yield master_dst.db.setup(check_version=False, verbose=not config["quiet"])
yield master_dst.db.model.upgrade()
yield _copy_database_with_db(master_src.db, master_dst.db, print_log)
return 0
@defer.inlineCallbacks
def _copy_single_table(src_db, dst_db, table, table_name, buildset_to_parent_buildid, print_log):
column_keys = table.columns.keys()
rows_queue = queue.Queue(32)
written_count = [0]
total_count = [0]
autoincrement_foreign_key_column = None
for column_name, column in table.columns.items():
if not column.foreign_keys and column.primary_key and isinstance(column.type, sa.Integer):
autoincrement_foreign_key_column = column_name
def thd_write(conn):
max_column_id = 0
while True:
try:
rows = rows_queue.get(timeout=1)
if rows is None:
if autoincrement_foreign_key_column is not None and max_column_id != 0:
if dst_db.pool.engine.dialect.name == 'postgresql':
# Explicitly inserting primary row IDs does not bump the primary key
# sequence on Postgres
seq_name = f"{table_name}_{autoincrement_foreign_key_column}_seq"
transaction = conn.begin()
conn.execute(
f"ALTER SEQUENCE {seq_name} RESTART WITH {max_column_id + 1}"
)
transaction.commit()
rows_queue.task_done()
return
row_dicts = [{k: getattr(row, k) for k in column_keys} for row in rows]
if autoincrement_foreign_key_column is not None:
for row in row_dicts:
max_column_id = max(max_column_id, row[autoincrement_foreign_key_column])
if table_name == "buildsets":
for row_dict in row_dicts:
if row_dict["parent_buildid"] is not None:
buildset_to_parent_buildid.append((
row_dict["id"],
row_dict["parent_buildid"],
))
row_dict["parent_buildid"] = None
except queue.Empty:
continue
try:
written_count[0] += len(rows)
print_log(
f"Copying {len(rows)} items ({written_count[0]}/{total_count[0]}) "
f"for {table_name} table"
)
if len(row_dicts) > 0:
conn.execute(table.insert(), row_dicts)
finally:
rows_queue.task_done()
def thd_read(conn):
q = sa.select([sa.sql.func.count()]).select_from(table)
total_count[0] = conn.execute(q).scalar()
result = conn.execute(sa.select(table))
while True:
chunk = result.fetchmany(10000)
if not chunk:
break
rows_queue.put(chunk)
rows_queue.put(None)
tasks = [src_db.pool.do(thd_read), dst_db.pool.do(thd_write)]
yield defer.gatherResults(tasks)
rows_queue.join()
@defer.inlineCallbacks
def _copy_database_with_db(src_db, dst_db, print_log):
# Tables need to be specified in correct order so that tables that other tables depend on are
# copied first.
table_names = [
# Note that buildsets.parent_buildid introduces circular dependency.
# It is handled separately
"buildsets",
"buildset_properties",
"projects",
"builders",
"changesources",
"buildrequests",
"workers",
"masters",
"buildrequest_claims",
"changesource_masters",
"builder_masters",
"configured_workers",
"connected_workers",
"patches",
"sourcestamps",
"buildset_sourcestamps",
"changes",
"change_files",
"change_properties",
"users",
"users_info",
"change_users",
"builds",
"build_properties",
"build_data",
"steps",
"logs",
"logchunks",
"schedulers",
"scheduler_masters",
"scheduler_changes",
"tags",
"builders_tags",
"test_result_sets",
"test_names",
"test_code_paths",
"test_results",
"objects",
"object_state",
]
metadata = model.Model.metadata
assert len(set(table_names)) == len(set(metadata.tables.keys()))
# Not a dict so that the values are inserted back in predictable order
buildset_to_parent_buildid = []
for table_name in table_names:
table = metadata.tables[table_name]
yield _copy_single_table(
src_db, dst_db, table, table_name, buildset_to_parent_buildid, print_log
)
def thd_write_buildset_parent_buildid(conn):
written_count = 0
for rows in misc.chunkify_list(buildset_to_parent_buildid, 10000):
q = model.Model.buildsets.update()
q = q.where(model.Model.buildsets.c.id == sa.bindparam('_id'))
q = q.values({'parent_buildid': sa.bindparam('parent_buildid')})
written_count += len(rows)
print_log(
f"Copying {len(rows)} items ({written_count}/{len(buildset_to_parent_buildid)}) "
f"for buildset.parent_buildid field"
)
conn.execute(
q,
[
{'_id': buildset_id, 'parent_buildid': parent_buildid}
for buildset_id, parent_buildid in rows
],
)
yield dst_db.pool.do(thd_write_buildset_parent_buildid)
print_log("Copy complete")
| 8,634 | Python | .py | 208 | 31.370192 | 99 | 0.602434 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
4,984 | base.py | buildbot_buildbot/master/buildbot/scripts/base.py | # This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright Buildbot Team Members
from __future__ import annotations
import copy
import errno
import os
import stat
import sys
import traceback
from contextlib import contextmanager
from twisted.python import runtime
from twisted.python import usage
from buildbot.config.errors import ConfigErrors
from buildbot.config.master import FileLoader
@contextmanager
def captureErrors(errors, msg):
try:
yield
except errors as e:
print(msg)
print(e)
return 1
return None
class BusyError(RuntimeError):
pass
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.exists(pidfile):
try:
with open(pidfile, encoding='utf-8') as f:
pid = int(f.read())
except ValueError as e:
raise ValueError(f'Pidfile {pidfile} contains non-numeric value') from e
try:
os.kill(pid, 0)
except OSError as why:
if why.errno == errno.ESRCH:
# The pid doesn't exist.
print(f'Removing stale pidfile {pidfile}')
os.remove(pidfile)
else:
raise OSError(
f"Can't check status of PID {pid} from pidfile {pidfile}: {why}"
) from why
else:
raise BusyError(f"'{pidfile}' exists - is this master still running?")
def checkBasedir(config):
if not config['quiet']:
print("checking basedir")
if not isBuildmasterDir(config['basedir']):
return False
if runtime.platformType != 'win32': # no pids on win32
if not config['quiet']:
print("checking for running master")
pidfile = os.path.join(config['basedir'], 'twistd.pid')
try:
checkPidFile(pidfile)
except Exception as e:
print(str(e))
return False
tac = getConfigFromTac(config['basedir'])
if tac:
if isinstance(tac.get('rotateLength', 0), str):
print("ERROR: rotateLength is a string, it should be a number")
print("ERROR: Please, edit your buildbot.tac file and run again")
print("ERROR: See http://trac.buildbot.net/ticket/2588 for more details")
return False
if isinstance(tac.get('maxRotatedFiles', 0), str):
print("ERROR: maxRotatedFiles is a string, it should be a number")
print("ERROR: Please, edit your buildbot.tac file and run again")
print("ERROR: See http://trac.buildbot.net/ticket/2588 for more details")
return False
return True
def loadConfig(config, configFileName='master.cfg'):
if not config['quiet']:
print(f"checking {configFileName}")
try:
master_cfg = FileLoader(config['basedir'], configFileName).loadConfig()
except ConfigErrors as e:
print("Errors loading configuration:")
for msg in e.errors:
print(" " + msg)
return None
except Exception:
print("Errors loading configuration:")
traceback.print_exc(file=sys.stdout)
return None
return master_cfg
def isBuildmasterDir(dir):
def print_error(error_message):
print(f"{error_message}\ninvalid buildmaster directory '{dir}'")
buildbot_tac = os.path.join(dir, "buildbot.tac")
try:
with open(buildbot_tac, encoding='utf-8') as f:
contents = f.read()
except OSError as exception:
print_error(f"error reading '{buildbot_tac}': {exception.strerror}")
return False
if "Application('buildmaster')" not in contents:
print_error(f"unexpected content in '{buildbot_tac}'")
return False
return True
def getConfigFromTac(basedir, quiet=False):
tacFile = os.path.join(basedir, 'buildbot.tac')
if os.path.exists(tacFile):
# don't mess with the global namespace, but set __file__ for
# relocatable buildmasters
tacGlobals = {'__file__': tacFile}
try:
with open(tacFile, encoding='utf-8') as f:
exec(f.read(), tacGlobals) # pylint: disable=exec-used
except Exception:
if not quiet:
traceback.print_exc()
raise
return tacGlobals
return None
def getConfigFileFromTac(basedir, quiet=False):
# execute the .tac file to see if its configfile location exists
config = getConfigFromTac(basedir, quiet=quiet)
if config:
return config.get("configfile", "master.cfg")
return "master.cfg"
class SubcommandOptions(usage.Options):
# subclasses should set this to a list-of-lists in order to source the
# .buildbot/options file. Note that this *only* works with optParameters,
# not optFlags. Example:
# buildbotOptions = [ [ 'optfile-name', 'parameter-name' ], .. ]
buildbotOptions: list[list[str]] | None = None
# set this to options that must have non-None values
requiredOptions: list[str] = []
def __init__(self, *args):
# for options in self.buildbotOptions, optParameters, and the options
# file, change the default in optParameters to the value in the options
# file, call through to the constructor, and then change it back.
# Options uses reflect.accumulateClassList, so this *must* be a class
# attribute; however, we do not want to permanently change the class.
# So we patch it temporarily and restore it after.
cls = self.__class__
if hasattr(cls, 'optParameters'):
old_optParameters = cls.optParameters
cls.optParameters = op = copy.deepcopy(cls.optParameters)
if self.buildbotOptions:
optfile = self.optionsFile = self.loadOptionsFile()
# pylint: disable=not-an-iterable
for optfile_name, option_name in self.buildbotOptions:
for i, val in enumerate(op):
if val[0] == option_name and optfile_name in optfile:
op[i] = list(val)
op[i][2] = optfile[optfile_name]
super().__init__(*args)
if hasattr(cls, 'optParameters'):
cls.optParameters = old_optParameters
def loadOptionsFile(self, _here=None):
"""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 of names defined in the options file. If no
options file was found, return an empty dict.
"""
here = _here or os.path.abspath(os.getcwd())
if runtime.platformType == 'win32':
# never trust env-vars, use the proper API
from win32com.shell import shell
from win32com.shell import shellcon
appdata = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, 0, 0)
home = os.path.join(appdata, "buildbot")
else:
home = os.path.expanduser("~/.buildbot")
searchpath = []
toomany = 20
while True:
searchpath.append(os.path.join(here, ".buildbot"))
next = os.path.dirname(here)
if next == here:
break # we've hit the root
here = next
toomany -= 1 # just in case
if toomany == 0:
print("I seem to have wandered up into the infinite glories of the heavens. Oops.")
break
searchpath.append(home)
localDict = {}
for d in searchpath:
if os.path.isdir(d):
if runtime.platformType != 'win32':
if os.stat(d)[stat.ST_UID] != os.getuid():
print(f"skipping {d} because you don't own it")
continue # security, skip other people's directories
optfile = os.path.join(d, "options")
if os.path.exists(optfile):
try:
with open(optfile, encoding='utf-8') as f:
options = f.read()
exec(options, localDict) # pylint: disable=exec-used
except Exception:
print(f"error while reading {optfile}")
raise
break
for k in list(localDict.keys()): # pylint: disable=consider-iterating-dictionary
if k.startswith("__"):
del localDict[k]
return localDict
def postOptions(self):
missing = [k for k in self.requiredOptions if self[k] is None]
if missing:
if len(missing) > 1:
msg = 'Required arguments missing: ' + ', '.join(missing)
else:
msg = 'Required argument missing: ' + missing[0]
raise usage.UsageError(msg)
class BasedirMixin:
"""SubcommandOptions Mixin to handle subcommands that take a basedir
argument"""
# on tab completion, suggest directories as first argument
if hasattr(usage, 'Completions'):
# only set completion suggestion if running with
# twisted version (>=11.1.0) that supports it
compData = usage.Completions(
extraActions=[usage.CompleteDirs(descr="buildbot base directory")]
)
def parseArgs(self, *args):
if args:
self['basedir'] = args[0]
else:
# Use the current directory if no basedir was specified.
self['basedir'] = os.getcwd()
if len(args) > 1:
raise usage.UsageError("I wasn't expecting so many arguments")
def postOptions(self):
# get an unambiguous, expanded basedir, including expanding '~', which
# may be useful in a .buildbot/config file
self['basedir'] = os.path.abspath(os.path.expanduser(self['basedir']))
| 10,790 | Python | .py | 249 | 33.658635 | 99 | 0.619792 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
4,985 | gengraphql.py | buildbot_buildbot/master/buildbot/scripts/gengraphql.py | # This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright Buildbot Team Members
import os
import sys
from twisted.internet import defer
from buildbot.data import connector
from buildbot.data.graphql import GraphQLConnector
from buildbot.test.fake import fakemaster
from buildbot.util import in_reactor
@in_reactor
@defer.inlineCallbacks
def gengraphql(config):
master = yield fakemaster.make_master(None, wantRealReactor=True)
data = connector.DataConnector()
yield data.setServiceParent(master)
graphql = GraphQLConnector()
yield graphql.setServiceParent(master)
graphql.data = data
master.config.www = {"graphql": {'debug': True}}
graphql.reconfigServiceWithBuildbotConfig(master.config)
yield master.startService()
if config['out'] != '--':
dirs = os.path.dirname(config['out'])
if dirs and not os.path.exists(dirs):
os.makedirs(dirs)
f = open(config['out'], "w", encoding='utf-8')
else:
f = sys.stdout
schema = graphql.get_schema()
f.write(schema)
f.close()
yield master.stopService()
return 0
| 1,737 | Python | .py | 45 | 35.066667 | 79 | 0.747924 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
4,986 | restart.py | buildbot_buildbot/master/buildbot/scripts/restart.py | # This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright Buildbot Team Members
from buildbot.scripts import base
from buildbot.scripts import start
from buildbot.scripts import stop
def restart(config):
basedir = config['basedir']
quiet = config['quiet']
if not base.isBuildmasterDir(basedir):
return 1
if stop.stop(config, wait=True) != 0:
return 1
if not quiet:
print("now restarting buildbot process..")
return start.start(config)
| 1,114 | Python | .py | 27 | 38.259259 | 79 | 0.759482 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
4,987 | trycmd.py | buildbot_buildbot/master/buildbot/scripts/trycmd.py | # This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright Buildbot Team Members
def trycmd(config):
from buildbot.clients import tryclient
t = tryclient.Try(config)
t.run()
return 0
| 826 | Python | .py | 19 | 41.473684 | 79 | 0.776119 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
4,988 | checkconfig.py | buildbot_buildbot/master/buildbot/scripts/checkconfig.py | # This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright Buildbot Team Members
import os
import sys
from buildbot.config.errors import ConfigErrors
from buildbot.config.master import FileLoader
from buildbot.scripts.base import getConfigFileFromTac
from buildbot.util import in_reactor
def _loadConfig(basedir, configFile, quiet):
try:
FileLoader(basedir, configFile).loadConfig()
except ConfigErrors as err:
if not quiet:
print("Configuration Errors:", file=sys.stderr)
for e in err.errors:
print(" " + e, file=sys.stderr)
return 1
if not quiet:
print("Config file is good!")
return 0
@in_reactor
def checkconfig(config):
quiet = config.get('quiet')
configFile = config.get('configFile', os.getcwd())
if os.path.isdir(configFile):
basedir = configFile
try:
configFile = getConfigFileFromTac(basedir, quiet=quiet)
except Exception:
if not quiet:
# the exception is already printed in base.py
print(f"Unable to load 'buildbot.tac' from '{basedir}':")
return 1
else:
basedir = os.getcwd()
return _loadConfig(basedir=basedir, configFile=configFile, quiet=quiet)
__all__ = ['checkconfig']
| 1,932 | Python | .py | 49 | 33.938776 | 79 | 0.707643 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
4,989 | stop.py | buildbot_buildbot/master/buildbot/scripts/stop.py | # This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright Buildbot Team Members
import errno
import os
import signal
import time
from twisted.python.runtime import platformType
from buildbot.scripts import base
def stop(config, signame="TERM", wait=None):
basedir = config['basedir']
quiet = config['quiet']
if wait is None:
wait = not config['no-wait']
if config['clean']:
signame = 'USR1'
if not base.isBuildmasterDir(config['basedir']):
return 1
pidfile = os.path.join(basedir, 'twistd.pid')
try:
with open(pidfile, encoding='utf-8') as f:
pid = int(f.read().strip())
except Exception:
if not config['quiet']:
print("buildmaster not running")
return 0
signum = getattr(signal, "SIG" + signame)
try:
os.kill(pid, signum)
except OSError as e:
if e.errno != errno.ESRCH and platformType != "win32":
raise
if not config['quiet']:
print("buildmaster not running")
try:
os.unlink(pidfile)
except OSError:
pass
return 0
if not wait:
if not quiet:
print(f"sent SIG{signame} to process")
return 0
time.sleep(0.1)
# poll once per second until twistd.pid goes away, up to 10 seconds,
# unless we're doing a clean stop, in which case wait forever
count = 0
while count < 10 or config['clean']:
try:
os.kill(pid, 0)
except OSError:
if not quiet:
print(f"buildbot process {pid} is dead")
return 0
time.sleep(1)
count += 1
if not quiet:
print("never saw process go away")
return 1
| 2,373 | Python | .py | 70 | 27.485714 | 79 | 0.650787 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
4,990 | janitor.py | buildbot_buildbot/master/buildbot/configurators/janitor.py | # This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright Buildbot Team Members
#
import datetime
from twisted.internet import defer
from buildbot.config import BuilderConfig
from buildbot.configurators import ConfiguratorBase
from buildbot.process.buildstep import BuildStep
from buildbot.process.factory import BuildFactory
from buildbot.process.results import SUCCESS
from buildbot.schedulers.forcesched import ForceScheduler
from buildbot.schedulers.timed import Nightly
from buildbot.util import datetime2epoch
from buildbot.worker.local import LocalWorker
JANITOR_NAME = "__Janitor" # If you read this code, you may want to patch this name.
def now():
"""patchable now (datetime is not patchable as builtin)"""
return datetime.datetime.now(datetime.timezone.utc)
class LogChunksJanitor(BuildStep):
name = 'LogChunksJanitor'
renderables = ["logHorizon"]
def __init__(self, logHorizon):
super().__init__()
self.logHorizon = logHorizon
@defer.inlineCallbacks
def run(self):
older_than_timestamp = datetime2epoch(now() - self.logHorizon)
deleted = yield self.master.db.logs.deleteOldLogChunks(older_than_timestamp)
self.descriptionDone = ["deleted", str(deleted), "logchunks"]
return SUCCESS
class BuildDataJanitor(BuildStep):
name = 'BuildDataJanitor'
renderables = ["build_data_horizon"]
def __init__(self, build_data_horizon):
super().__init__()
self.build_data_horizon = build_data_horizon
@defer.inlineCallbacks
def run(self):
older_than_timestamp = datetime2epoch(now() - self.build_data_horizon)
deleted = yield self.master.db.build_data.deleteOldBuildData(older_than_timestamp)
self.descriptionDone = ["deleted", str(deleted), "build data key-value pairs"]
return SUCCESS
class JanitorConfigurator(ConfiguratorBase):
"""Janitor is a configurator which create a Janitor Builder with all needed Janitor steps"""
def __init__(self, logHorizon=None, hour=0, build_data_horizon=None, **kwargs):
super().__init__()
self.logHorizon = logHorizon
self.build_data_horizon = build_data_horizon
self.hour = hour
self.kwargs = kwargs
def configure(self, config_dict):
steps = []
if self.logHorizon is not None:
steps.append(LogChunksJanitor(logHorizon=self.logHorizon))
if self.build_data_horizon is not None:
steps.append(BuildDataJanitor(build_data_horizon=self.build_data_horizon))
if not steps:
return
hour = self.hour
kwargs = self.kwargs
super().configure(config_dict)
nightly_kwargs = {}
# we take the defaults of Nightly, except for hour
for arg in ('minute', 'dayOfMonth', 'month', 'dayOfWeek'):
if arg in kwargs:
nightly_kwargs[arg] = kwargs[arg]
self.schedulers.append(
Nightly(name=JANITOR_NAME, builderNames=[JANITOR_NAME], hour=hour, **nightly_kwargs)
)
self.schedulers.append(
ForceScheduler(name=JANITOR_NAME + "_force", builderNames=[JANITOR_NAME])
)
self.builders.append(
BuilderConfig(
name=JANITOR_NAME, workername=JANITOR_NAME, factory=BuildFactory(steps=steps)
)
)
self.protocols.setdefault('null', {})
self.workers.append(LocalWorker(JANITOR_NAME))
| 4,087 | Python | .py | 91 | 38.505495 | 96 | 0.706949 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
4,991 | __init__.py | buildbot_buildbot/master/buildbot/configurators/__init__.py | # This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright Buildbot Team Members
#
"""This module holds configurators, which helps setup schedulers, builders, steps,
for a very specific purpose.
Higher level interfaces to buildbot configurations components.
"""
from zope.interface import implementer
from buildbot.interfaces import IConfigurator
@implementer(IConfigurator)
class ConfiguratorBase:
"""
I provide base helper methods for configurators
"""
def __init__(self):
pass
def configure(self, config_dict):
self.config_dict = c = config_dict
self.schedulers = c.setdefault('schedulers', [])
self.protocols = c.setdefault('protocols', {})
self.builders = c.setdefault('builders', [])
self.workers = c.setdefault('workers', [])
self.projects = c.setdefault('projects', [])
self.secretsProviders = c.setdefault('secretsProviders', [])
self.www = c.setdefault('www', {})
| 1,597 | Python | .py | 37 | 39.486486 | 82 | 0.735995 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
4,992 | timed.py | buildbot_buildbot/master/buildbot/schedulers/timed.py | # This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright Buildbot Team Members
import datetime
from typing import ClassVar
from typing import Sequence
import croniter
from twisted.internet import defer
from twisted.internet import reactor
from twisted.python import log
from zope.interface import implementer
from buildbot import config
from buildbot import util
from buildbot.changes.filter import ChangeFilter
from buildbot.interfaces import ITriggerableScheduler
from buildbot.process import buildstep
from buildbot.process import properties
from buildbot.schedulers import base
from buildbot.util.codebase import AbsoluteSourceStampsMixin
# States of objects which have to be observed are registered in the data base table `object_state`.
# `objectid` in the `object_state` refers to the object from the `object` table.
# Schedulers use the following state keys:
# - `last_only_if_changed` - bool, setting of `onlyIfChanged` when the scheduler checked whether to
# run build the last time. Does not exist if there was no build before.
# - `last_build` - timestamp, time when the last build was scheduled to run. If `onlyIfChanged` is
# set to True, only when there are designated changes build will be started. If the build was not
# started,
# `last_build` means on what time build was scheduled to run ignoring the fact if it actually ran or
# not.
# Value of these state keys affects the decision whether to run a build.
#
# When deciding whether to run the build or to skip it, several factors and their interactions are
# evaluated:
# - the value of `onlyIfChanged` (default is False);
# - has the state of `onlyIfChanged` changed;
# - whether this would be first build (True if `last_build` value was not detected). If there
# already were builds in the past, it indicates that the scheduler is existing;
# - were there any important changes after the last build.
#
# If `onlyIfChanged` is not set or its setting changes to False, builds will always run on the time
# set, ignoring the status of `last_only_if_changed` and `last_build` regardless of what the state
# is or anything else.
#
# If `onlyIfChanged` is True, then builds will be run when there are relevant changes.
#
# If `onlyIfChanged` is True and even when there were no relevant changes, builds will run for the
# the first time on specified time as well when the following condition holds:
# - `last_only_if_changed` was set to False on previous build. This ensures that any changes that
# happened while `onlyIfChanged` was still False are not missed. This may result in a single build
# done unnecessarily, but it is accepted as a good compromise because it only happens when
# `onlyIfChanged` is adjusted;
# - `last_build` does not have a value yet meaning that it is a new scheduler and we should have
# initial build to set a baseline.
#
# There is an edge case, when upgrading to v3.5.0 and new object status variable
# `last_only_if_changed` is introduced. If scheduler exists and had builds before
# (`last_build` has a value), build should only be started if there are relevant changes.
# Thus upgrading the version does not start unnecessary builds.
class Timed(AbsoluteSourceStampsMixin, base.BaseScheduler):
"""
Parent class for timed schedulers. This takes care of the (surprisingly
subtle) mechanics of ensuring that each timed actuation runs to completion
before the service stops.
"""
compare_attrs: ClassVar[Sequence[str]] = (
'reason',
'createAbsoluteSourceStamps',
'onlyIfChanged',
'branch',
'fileIsImportant',
'change_filter',
'onlyImportant',
)
reason = ''
class NoBranch:
pass
def __init__(
self,
name,
builderNames,
reason='',
createAbsoluteSourceStamps=False,
onlyIfChanged=False,
branch=NoBranch,
change_filter=None,
fileIsImportant=None,
onlyImportant=False,
**kwargs,
):
super().__init__(name, builderNames, **kwargs)
# tracking for when to start the next build
self.lastActuated = None
# A lock to make sure that each actuation occurs without interruption.
# This lock governs actuateAt, actuateAtTimer, and actuateOk
self.actuationLock = defer.DeferredLock()
self.actuateOk = False
self.actuateAt = None
self.actuateAtTimer = None
self.reason = util.bytes2unicode(reason % {'name': name})
self.branch = branch
self.change_filter = ChangeFilter.fromSchedulerConstructorArgs(change_filter=change_filter)
self.createAbsoluteSourceStamps = createAbsoluteSourceStamps
self.onlyIfChanged = onlyIfChanged
if fileIsImportant and not callable(fileIsImportant):
config.error("fileIsImportant must be a callable")
self.fileIsImportant = fileIsImportant
# If True, only important changes will be added to the buildset.
self.onlyImportant = onlyImportant
self._reactor = reactor # patched by tests
self.is_first_build = None
@defer.inlineCallbacks
def activate(self):
yield super().activate()
if not self.enabled:
return None
# no need to lock this
# nothing else can run before the service is started
self.actuateOk = True
# get the scheduler's last_build time (note: only done at startup)
self.lastActuated = yield self.getState('last_build', None)
if self.lastActuated is None:
self.is_first_build = True
else:
self.is_first_build = False
# schedule the next build
yield self.scheduleNextBuild()
if self.onlyIfChanged or self.createAbsoluteSourceStamps:
yield self.startConsumingChanges(
fileIsImportant=self.fileIsImportant,
change_filter=self.change_filter,
onlyImportant=self.onlyImportant,
)
else:
yield self.master.db.schedulers.flushChangeClassifications(self.serviceid)
return None
@defer.inlineCallbacks
def deactivate(self):
yield super().deactivate()
if not self.enabled:
return None
# shut down any pending actuation, and ensure that we wait for any
# current actuation to complete by acquiring the lock. This ensures
# that no build will be scheduled after deactivate is complete.
def stop_actuating():
self.actuateOk = False
self.actuateAt = None
if self.actuateAtTimer:
self.actuateAtTimer.cancel()
self.actuateAtTimer = None
yield self.actuationLock.run(stop_actuating)
return None
# Scheduler methods
def gotChange(self, change, important):
# both important and unimportant changes on our branch are recorded, as
# we will include all such changes in any buildsets we start. Note
# that we must check the branch here because it is not included in the
# change filter.
if self.branch is not Timed.NoBranch and change.branch != self.branch:
return defer.succeed(None) # don't care about this change
d = self.master.db.schedulers.classifyChanges(self.serviceid, {change.number: important})
if self.createAbsoluteSourceStamps:
d.addCallback(lambda _: self.recordChange(change))
return d
@defer.inlineCallbacks
def startBuild(self):
if not self.enabled:
log.msg(
format='ignoring build from %(name)s because scheduler '
'has been disabled by the user',
name=self.name,
)
return
# use the collected changes to start a build
scheds = self.master.db.schedulers
classifications = yield scheds.getChangeClassifications(self.serviceid)
# if onlyIfChanged is True, then we will skip this build if no important changes have
# occurred since the last invocation. Note that when the scheduler has just been started
# there may not be any important changes yet and we should start the build for the
# current state of the code whatever it is.
#
# Note that last_only_if_changed will always be set to the value of onlyIfChanged
# at the point when startBuild finishes (it is not obvious, that all code paths lead
# to this outcome)
last_only_if_changed = yield self.getState('last_only_if_changed', True)
if (
last_only_if_changed
and self.onlyIfChanged
and not any(classifications.values())
and not self.is_first_build
and not self.maybe_force_build_on_unimportant_changes(self.lastActuated)
):
log.msg(
("{} scheduler <{}>: skipping build " + "- No important changes").format(
self.__class__.__name__, self.name
)
)
self.is_first_build = False
return
if last_only_if_changed != self.onlyIfChanged:
yield self.setState('last_only_if_changed', self.onlyIfChanged)
changeids = sorted(classifications.keys())
if changeids:
max_changeid = changeids[-1] # (changeids are sorted)
yield self.addBuildsetForChanges(
reason=self.reason, changeids=changeids, priority=self.priority
)
yield scheds.flushChangeClassifications(self.serviceid, less_than=max_changeid + 1)
else:
# There are no changes, but onlyIfChanged is False, so start
# a build of the latest revision, whatever that is
sourcestamps = [{"codebase": cb} for cb in self.codebases]
yield self.addBuildsetForSourceStampsWithDefaults(
reason=self.reason, sourcestamps=sourcestamps, priority=self.priority
)
self.is_first_build = False
def getCodebaseDict(self, codebase):
if self.createAbsoluteSourceStamps:
return super().getCodebaseDict(codebase)
return self.codebases[codebase]
# Timed methods
def getNextBuildTime(self, lastActuation):
"""
Called by to calculate the next time to actuate a BuildSet. Override
in subclasses. To trigger a fresh call to this method, use
L{rescheduleNextBuild}.
@param lastActuation: the time of the last actuation, or None for never
@returns: a Deferred firing with the next time a build should occur (in
the future), or None for never.
"""
raise NotImplementedError
def scheduleNextBuild(self):
"""
Schedule the next build, re-invoking L{getNextBuildTime}. This can be
called at any time, and it will avoid contention with builds being
started concurrently.
@returns: Deferred
"""
return self.actuationLock.run(self._scheduleNextBuild_locked)
def maybe_force_build_on_unimportant_changes(self, current_actuation_time):
"""
Allows forcing a build in cases when there are no important changes and onlyIfChanged is
enabled.
"""
return False
# utilities
def now(self):
"Similar to util.now, but patchable by tests"
return util.now(self._reactor)
def current_utc_offset(self, tm):
return (
datetime.datetime.fromtimestamp(tm).replace(tzinfo=datetime.timezone.utc)
- datetime.datetime.fromtimestamp(tm, datetime.timezone.utc)
).total_seconds()
@defer.inlineCallbacks
def _scheduleNextBuild_locked(self):
# clear out the existing timer
if self.actuateAtTimer:
self.actuateAtTimer.cancel()
self.actuateAtTimer = None
# calculate the new time
actuateAt = yield self.getNextBuildTime(self.lastActuated)
if actuateAt is None:
self.actuateAt = None
else:
# set up the new timer
now = self.now()
self.actuateAt = max(actuateAt, now)
untilNext = self.actuateAt - now
if untilNext == 0:
log.msg(
f"{self.__class__.__name__} scheduler <{self.name}>: "
"missed scheduled build time - building immediately"
)
self.actuateAtTimer = self._reactor.callLater(untilNext, self._actuate)
@defer.inlineCallbacks
def _actuate(self):
# called from the timer when it's time to start a build
self.actuateAtTimer = None
self.lastActuated = self.actuateAt
@defer.inlineCallbacks
def set_state_and_start():
# bail out if we shouldn't be actuating anymore
if not self.actuateOk:
return
# mark the last build time
self.actuateAt = None
yield self.setState('last_build', self.lastActuated)
try:
# start the build
yield self.startBuild()
except Exception as e:
log.err(e, 'while actuating')
finally:
# schedule the next build (noting the lock is already held)
yield self._scheduleNextBuild_locked()
yield self.actuationLock.run(set_state_and_start)
class Periodic(Timed):
compare_attrs: ClassVar[Sequence[str]] = ('periodicBuildTimer',)
def __init__(
self,
name,
builderNames,
periodicBuildTimer,
reason="The Periodic scheduler named '%(name)s' triggered this build",
**kwargs,
):
super().__init__(name, builderNames, reason=reason, **kwargs)
if periodicBuildTimer <= 0:
config.error("periodicBuildTimer must be positive")
self.periodicBuildTimer = periodicBuildTimer
def getNextBuildTime(self, lastActuated):
if lastActuated is None:
return defer.succeed(self.now()) # meaning "ASAP"
return defer.succeed(lastActuated + self.periodicBuildTimer)
class NightlyBase(Timed):
compare_attrs: ClassVar[Sequence[str]] = (
"minute",
"hour",
"dayOfMonth",
"month",
"dayOfWeek",
"force_at_minute",
"force_at_hour",
"force_at_day_of_month",
"force_at_month",
"force_at_day_of_week",
)
def __init__(
self,
name,
builderNames,
minute=0,
hour='*',
dayOfMonth='*',
month='*',
dayOfWeek='*',
force_at_minute=None,
force_at_hour=None,
force_at_day_of_month=None,
force_at_month=None,
force_at_day_of_week=None,
**kwargs,
):
super().__init__(name, builderNames, **kwargs)
self.minute = minute
self.hour = hour
self.dayOfMonth = dayOfMonth
self.month = month
self.dayOfWeek = dayOfWeek
self.force_at_enabled = (
force_at_minute is not None
or force_at_hour is not None
or force_at_day_of_month is not None
or force_at_month is not None
or force_at_day_of_week is not None
)
def default_if_none(value, default):
if value is None:
return default
return value
self.force_at_minute = default_if_none(force_at_minute, 0)
self.force_at_hour = default_if_none(force_at_hour, "*")
self.force_at_day_of_month = default_if_none(force_at_day_of_month, "*")
self.force_at_month = default_if_none(force_at_month, "*")
self.force_at_day_of_week = default_if_none(force_at_day_of_week, "*")
def _timeToCron(self, time, isDayOfWeek=False):
if isinstance(time, int):
if isDayOfWeek:
# Convert from Mon = 0 format to Sun = 0 format for use in
# croniter
time = (time + 1) % 7
return time
if isinstance(time, str):
if isDayOfWeek:
# time could be a comma separated list of values, e.g. "5,sun"
time_array = str(time).split(',')
for i, time_val in enumerate(time_array):
try:
# try to convert value in place
# Conversion for croniter (see above)
time_array[i] = (int(time_val) + 1) % 7
except ValueError:
# all non-int values are kept
pass
# Convert the list to a string
return ','.join([str(s) for s in time_array])
return time
if isDayOfWeek:
# Conversion for croniter (see above)
time = [(t + 1) % 7 for t in time]
return ','.join([str(s) for s in time]) # Convert the list to a string
def _times_to_cron_line(self, minute, hour, day_of_month, month, day_of_week):
return " ".join([
str(self._timeToCron(minute)),
str(self._timeToCron(hour)),
str(self._timeToCron(day_of_month)),
str(self._timeToCron(month)),
str(self._timeToCron(day_of_week, True)),
])
def _time_to_croniter_tz_time(self, ts):
# By default croniter interprets input timestamp in UTC timezone. However, the scheduler
# works in local timezone, so appropriate timezone information needs to be passed
tz = datetime.timezone(datetime.timedelta(seconds=self.current_utc_offset(ts)))
return datetime.datetime.fromtimestamp(ts, tz)
def getNextBuildTime(self, lastActuated):
ts = lastActuated or self.now()
sched = self._times_to_cron_line(
self.minute,
self.hour,
self.dayOfMonth,
self.month,
self.dayOfWeek,
)
cron = croniter.croniter(sched, self._time_to_croniter_tz_time(ts))
nextdate = cron.get_next(float)
return defer.succeed(nextdate)
def maybe_force_build_on_unimportant_changes(self, current_actuation_time):
if not self.force_at_enabled:
return False
cron_string = self._times_to_cron_line(
self.force_at_minute,
self.force_at_hour,
self.force_at_day_of_month,
self.force_at_month,
self.force_at_day_of_week,
)
return croniter.croniter.match(
cron_string, self._time_to_croniter_tz_time(current_actuation_time)
)
class Nightly(NightlyBase):
def __init__(
self,
name,
builderNames,
minute=0,
hour='*',
dayOfMonth='*',
month='*',
dayOfWeek='*',
reason="The Nightly scheduler named '%(name)s' triggered this build",
force_at_minute=None,
force_at_hour=None,
force_at_day_of_month=None,
force_at_month=None,
force_at_day_of_week=None,
**kwargs,
):
super().__init__(
name=name,
builderNames=builderNames,
minute=minute,
hour=hour,
dayOfMonth=dayOfMonth,
month=month,
dayOfWeek=dayOfWeek,
reason=reason,
force_at_minute=force_at_minute,
force_at_hour=force_at_hour,
force_at_day_of_month=force_at_day_of_month,
force_at_month=force_at_month,
force_at_day_of_week=force_at_day_of_week,
**kwargs,
)
@implementer(ITriggerableScheduler)
class NightlyTriggerable(NightlyBase):
def __init__(
self,
name,
builderNames,
minute=0,
hour='*',
dayOfMonth='*',
month='*',
dayOfWeek='*',
reason="The NightlyTriggerable scheduler named '%(name)s' triggered this build",
force_at_minute=None,
force_at_hour=None,
force_at_day_of_month=None,
force_at_month=None,
force_at_day_of_week=None,
**kwargs,
):
super().__init__(
name=name,
builderNames=builderNames,
minute=minute,
hour=hour,
dayOfMonth=dayOfMonth,
month=month,
dayOfWeek=dayOfWeek,
reason=reason,
force_at_minute=force_at_minute,
force_at_hour=force_at_hour,
force_at_day_of_month=force_at_day_of_month,
force_at_month=force_at_month,
force_at_day_of_week=force_at_day_of_week,
**kwargs,
)
self._lastTrigger = None
@defer.inlineCallbacks
def activate(self):
yield super().activate()
if not self.enabled:
return
lastTrigger = yield self.getState('lastTrigger', None)
self._lastTrigger = None
if lastTrigger:
try:
if isinstance(lastTrigger[0], list):
self._lastTrigger = (
lastTrigger[0],
properties.Properties.fromDict(lastTrigger[1]),
lastTrigger[2],
lastTrigger[3],
)
# handle state from before Buildbot-0.9.0
elif isinstance(lastTrigger[0], dict):
self._lastTrigger = (
list(lastTrigger[0].values()),
properties.Properties.fromDict(lastTrigger[1]),
None,
None,
)
except Exception:
pass
# If the lastTrigger isn't of the right format, ignore it
if not self._lastTrigger:
log.msg(
format="NightlyTriggerable Scheduler <%(scheduler)s>: "
"could not load previous state; starting fresh",
scheduler=self.name,
)
def trigger(
self,
waited_for,
sourcestamps=None,
set_props=None,
parent_buildid=None,
parent_relationship=None,
):
"""Trigger this scheduler with the given sourcestamp ID. Returns a
deferred that will fire when the buildset is finished."""
assert isinstance(sourcestamps, list), "trigger requires a list of sourcestamps"
self._lastTrigger = (sourcestamps, set_props, parent_buildid, parent_relationship)
if set_props:
propsDict = set_props.asDict()
else:
propsDict = {}
# record the trigger in the db
d = self.setState(
'lastTrigger', (sourcestamps, propsDict, parent_buildid, parent_relationship)
)
# Trigger expects a callback with the success of the triggered
# build, if waitForFinish is True.
# Just return SUCCESS, to indicate that the trigger was successful,
# don't wait for the nightly to run.
return (defer.succeed((None, {})), d.addCallback(lambda _: buildstep.SUCCESS))
@defer.inlineCallbacks
def startBuild(self):
if not self.enabled:
log.msg(
format='ignoring build from %(name)s because scheduler '
'has been disabled by the user',
name=self.name,
)
return
if self._lastTrigger is None:
return
(sourcestamps, set_props, parent_buildid, parent_relationship) = self._lastTrigger
self._lastTrigger = None
yield self.setState('lastTrigger', None)
# properties for this buildset are composed of our own properties,
# potentially overridden by anything from the triggering build
props = properties.Properties()
props.updateFromProperties(self.properties)
if set_props:
props.updateFromProperties(set_props)
yield self.addBuildsetForSourceStampsWithDefaults(
reason=self.reason,
sourcestamps=sourcestamps,
properties=props,
parent_buildid=parent_buildid,
parent_relationship=parent_relationship,
priority=self.priority,
)
| 24,926 | Python | .py | 596 | 32.04698 | 100 | 0.626506 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
4,993 | canceller_buildset.py | buildbot_buildbot/master/buildbot/schedulers/canceller_buildset.py | # This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright Buildbot Team Members
from typing import ClassVar
from typing import Sequence
from twisted.internet import defer
from buildbot import config
from buildbot.data import resultspec
from buildbot.process.results import FAILURE
from buildbot.util.service import BuildbotService
from buildbot.util.ssfilter import SourceStampFilter
from buildbot.util.ssfilter import extract_filter_values
class _FailingSingleBuilderConfig:
def __init__(self, builders_to_cancel, filter):
self.builders_to_cancel = builders_to_cancel
self.filter = filter
class _FailingBuilderConfig:
def __init__(self):
self._by_builder = {}
def add_config(self, builders, builders_to_cancel, filter):
assert builders is not None
config = _FailingSingleBuilderConfig(builders_to_cancel, filter)
for builder in builders:
self._by_builder.setdefault(builder, []).append(config)
def get_all_matched(self, builder_name, props):
assert builder_name is not None
configs = self._by_builder.get(builder_name, [])
return [c for c in configs if c.filter.is_matched(props)]
class FailingBuildsetCanceller(BuildbotService):
compare_attrs: ClassVar[Sequence[str]] = (*BuildbotService.compare_attrs, 'filters')
def checkConfig(self, name, filters):
FailingBuildsetCanceller.check_filters(filters)
self.name = name
self._build_finished_consumer = None
def reconfigService(self, name, filters):
self.filters = FailingBuildsetCanceller.filter_tuples_to_filter_set_object(filters)
@defer.inlineCallbacks
def startService(self):
yield super().startService()
self._build_finished_consumer = yield self.master.mq.startConsuming(
self._on_build_finished, ('builds', None, 'finished')
)
@defer.inlineCallbacks
def stopService(self):
yield self._build_finished_consumer.stopConsuming()
@classmethod
def check_filters(cls, filters):
if not isinstance(filters, list):
config.error(f'{cls.__name__}: The filters argument must be a list of tuples')
for filter in filters:
if (
not isinstance(filter, tuple)
or len(filter) != 3
or not isinstance(filter[2], SourceStampFilter)
):
config.error(
(
'{}: The filters argument must be a list of tuples each of which '
+ 'contains builders to track as the first item, builders to cancel '
+ 'as the second and SourceStampFilter as the third'
).format(cls.__name__)
)
builders, builders_to_cancel, _ = filter
try:
extract_filter_values(builders, 'builders')
if builders_to_cancel is not None:
extract_filter_values(builders_to_cancel, 'builders_to_cancel')
except Exception as e:
config.error(f'{cls.__name__}: When processing filter builders: {e!s}')
@classmethod
def filter_tuples_to_filter_set_object(cls, filters):
filter_set = _FailingBuilderConfig()
for filter in filters:
builders, builders_to_cancel, ss_filter = filter
extract_filter_values(builders, 'builders')
if builders_to_cancel is not None:
builders_to_cancel = extract_filter_values(builders_to_cancel, 'builders_to_cancel')
filter_set.add_config(builders, builders_to_cancel, ss_filter)
return filter_set
@defer.inlineCallbacks
def _on_build_finished(self, key, build):
if build['results'] != FAILURE:
return
buildrequest = yield self.master.data.get(('buildrequests', build['buildrequestid']))
builder = yield self.master.data.get(("builders", build['builderid']))
buildset = yield self.master.data.get(('buildsets', buildrequest['buildsetid']))
sourcestamps = buildset['sourcestamps']
builders_to_cancel = set()
for ss in sourcestamps:
configs = self.filters.get_all_matched(builder['name'], ss)
for c in configs:
if builders_to_cancel is not None:
if c.builders_to_cancel is None:
builders_to_cancel = None
else:
builders_to_cancel.update(c.builders_to_cancel)
all_bs_buildrequests = yield self.master.data.get(
('buildrequests',),
filters=[
resultspec.Filter('buildsetid', 'eq', [buildset['bsid']]),
resultspec.Filter('complete', 'eq', [False]),
],
)
all_bs_buildrequests = [
br
for br in all_bs_buildrequests
if br['buildrequestid'] != buildrequest['buildrequestid']
]
for br in all_bs_buildrequests:
brid = br['buildrequestid']
if brid == buildrequest['buildrequestid']:
continue # this one has just failed
br_builder = yield self.master.data.get(("builders", br['builderid']))
if builders_to_cancel is not None and br_builder['name'] not in builders_to_cancel:
continue
reason = 'Build has been cancelled because another build in the same buildset failed'
self.master.data.control('cancel', {'reason': reason}, ('buildrequests', str(brid)))
| 6,223 | Python | .py | 128 | 38.640625 | 100 | 0.644863 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
4,994 | forcesched.py | buildbot_buildbot/master/buildbot/schedulers/forcesched.py | # This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright Buildbot Team Members
from __future__ import annotations
import re
import traceback
from typing import Any
from typing import ClassVar
from typing import Sequence
from twisted.internet import defer
from twisted.python.reflect import accumulateClassList
from buildbot import config
from buildbot.process.properties import Properties
from buildbot.reporters.mail import VALID_EMAIL_ADDR
from buildbot.schedulers import base
from buildbot.util import identifiers
class ValidationError(ValueError):
pass
class CollectedValidationError(ValueError):
def __init__(self, errors):
self.errors = errors
super().__init__("\n".join([k + ":" + v for k, v in errors.items()]))
class ValidationErrorCollector:
def __init__(self):
self.errors = {}
@defer.inlineCallbacks
def collectValidationErrors(self, name, fn, *args, **kwargs):
res = None
try:
res = yield fn(*args, **kwargs)
except CollectedValidationError as err:
for error_name, e in err.errors.items():
self.errors[error_name] = e
except ValueError as e:
self.errors[name] = str(e)
return res
def maybeRaiseCollectedErrors(self):
errors = self.errors
if errors:
raise CollectedValidationError(errors)
DefaultField = object() # sentinel object to signal default behavior
class BaseParameter:
"""
BaseParameter provides a base implementation for property customization
"""
spec_attributes = [
"name",
"fullName",
"label",
"tablabel",
"type",
"default",
"required",
"multiple",
"regex",
"hide",
"maxsize",
"autopopulate",
"tooltip",
]
name = ""
parentName = None
label = ""
tablabel = ""
type: str = ""
default: Any = ""
required = False
multiple = False
regex = None
debug = True
hide = False
maxsize: int | None = None
autopopulate = None
tooltip = ""
@property
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 + '_' + self.name
# otherwise just use the one that is set
# (this allows empty name for "anonymous nests")
return self.name or self.parentName
def setParent(self, parent):
self.parentName = parent.fullName if parent else None
def __init__(self, name, label=None, tablabel=None, regex=None, **kw):
"""
@param name: the name of the field, used during posting values
back to the scheduler. This is not necessarily a UI value,
and there may be restrictions on the characters allowed for
this value. For example, HTML would require this field to
avoid spaces and other punctuation ('-', '.', and '_' allowed)
@type name: unicode
@param label: (optional) the name of the field, used for UI display.
@type label: unicode or None (to use 'name')
@param regex: (optional) regex to validate the value with. Not used by
all subclasses
@type regex: unicode or regex
"""
if name in ["owner", "builderNames", "builderid"]:
config.error(f"{name} cannot be used as a parameter name, because it is reserved")
self.name = name
self.label = name if label is None else label
self.tablabel = self.label if tablabel is None else tablabel
if regex:
self.regex = re.compile(regex)
if 'value' in kw:
config.error(
f"Use default='{kw['value']}' instead of value=... to give a "
"default Parameter value"
)
# all other properties are generically passed via **kw
self.__dict__.update(kw)
def getFromKwargs(self, kwargs):
"""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 'parse_from_args' for the final conversion.
"""
args = kwargs.get(self.fullName, [])
# delete white space for args
for arg in args:
if isinstance(arg, str) and not arg.strip():
args.remove(arg)
if not args:
if self.required:
raise ValidationError(f"'{self.label}' needs to be specified")
if self.multiple:
args = self.default
else:
args = [self.default]
if self.regex:
for arg in args:
if not self.regex.match(arg):
raise ValidationError(
f"{self.label}:'{arg}' does not match pattern '{self.regex.pattern}'"
)
if self.maxsize is not None:
for arg in args:
if len(arg) > self.maxsize:
raise ValidationError(f"{self.label}: is too large {len(arg)} > {self.maxsize}")
try:
arg = self.parse_from_args(args)
except Exception as e:
# an exception will just display an alert in the web UI
# also log the exception
if self.debug:
traceback.print_exc()
raise e
if arg is None:
raise ValidationError(f"need {self.fullName}: no default provided by config")
return arg
def updateFromKwargs(self, properties, kwargs, collector, **unused):
"""Primary entry point to turn 'kwargs' into 'properties'"""
properties[self.name] = self.getFromKwargs(kwargs)
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:
return [self.parse_from_arg(arg) for arg in l]
return self.parse_from_arg(l[0])
def parse_from_arg(self, s):
return s
def getSpec(self):
spec_attributes = []
accumulateClassList(self.__class__, 'spec_attributes', spec_attributes)
ret = {}
for i in spec_attributes:
ret[i] = getattr(self, i)
return ret
class FixedParameter(BaseParameter):
"""A fixed parameter that cannot be modified by the user."""
type = "fixed"
hide = True
default = ""
def parse_from_args(self, l):
return self.default
class StringParameter(BaseParameter):
"""A simple string parameter"""
spec_attributes = ["size"]
type = "text"
size = 10
def parse_from_arg(self, s):
return s
class TextParameter(StringParameter):
"""A generic string parameter that may span multiple lines"""
spec_attributes = ["cols", "rows"]
type = "textarea"
cols = 80
rows = 20
def value_to_text(self, value):
return str(value)
class IntParameter(StringParameter):
"""An integer parameter"""
type = "int"
default = 0
parse_from_arg = int # will throw an exception if parse fail
class BooleanParameter(BaseParameter):
"""A boolean parameter"""
type = "bool"
def getFromKwargs(self, kwargs):
return kwargs.get(self.fullName, [self.default]) == [True]
class UserNameParameter(StringParameter):
"""A username parameter to supply the 'owner' of a build"""
spec_attributes = ["need_email"]
type = "username"
default = ""
size = 30
need_email = True
def __init__(self, name="username", label="Your name:", **kw):
super().__init__(name, label, **kw)
def parse_from_arg(self, s):
if not s and not self.required:
return s
if self.need_email:
res = VALID_EMAIL_ADDR.search(s)
if res is None:
raise ValidationError(
f"{self.name}: please fill in email address in the "
"form 'User <[email protected]>'"
)
return s
class ChoiceStringParameter(BaseParameter):
"""A list of strings, allowing the selection of one of the predefined values.
The 'strict' parameter controls whether values outside the predefined list
of choices are allowed"""
spec_attributes = ["choices", "strict"]
type = "list"
choices: list[str] = []
strict = True
def parse_from_arg(self, s):
if self.strict and s not in self.choices:
raise ValidationError(
f"'{s}' does not belong to list of available choices '{self.choices}'"
)
return s
def getChoices(self, master, scheduler, buildername):
return self.choices
class InheritBuildParameter(ChoiceStringParameter):
"""A parameter that takes its values from another build"""
type = ChoiceStringParameter.type
name = "inherit"
compatible_builds = None
def getChoices(self, master, scheduler, buildername):
return self.compatible_builds(master, buildername)
def getFromKwargs(self, kwargs):
raise ValidationError("InheritBuildParameter can only be used by properties")
def updateFromKwargs(self, master, properties, changes, kwargs, **unused):
arg = kwargs.get(self.fullName, [""])[0]
split_arg = arg.split(" ")[0].split("/")
if len(split_arg) != 2:
raise ValidationError(f"bad build: {arg}")
builder_name, build_num = split_arg
builder_dict = master.data.get(('builders', builder_name))
if builder_dict is None:
raise ValidationError(f"unknown builder: {builder_name} in {arg}")
build_dict = master.data.get(
('builders', builder_name, 'builds', build_num), fields=['properties']
)
if build_dict is None:
raise ValidationError(f"unknown build: {builder_name} in {arg}")
props = {self.name: (arg.split(" ")[0])}
for name, (value, source) in build_dict['properties']:
if source == "Force Build Form":
if name == "owner":
name = "orig_owner"
props[name] = value
properties.update(props)
# FIXME: this does not do what we expect, but updateFromKwargs is not used either.
# This needs revisiting when the build parameters are fixed:
# changes.extend(b.changes)
class WorkerChoiceParameter(ChoiceStringParameter):
"""A parameter that lets the worker name be explicitly chosen.
This parameter works in conjunction with 'buildbot.process.builder.enforceChosenWorker',
which should be added as the 'canStartBuild' parameter to the Builder.
The "anySentinel" parameter represents the sentinel value to specify that
there is no worker preference.
"""
anySentinel = '-any-'
label = 'Worker'
required = False
strict = False
def __init__(self, name='workername', **kwargs):
super().__init__(name, **kwargs)
def updateFromKwargs(self, kwargs, **unused):
workername = self.getFromKwargs(kwargs)
if workername == self.anySentinel:
# no preference, so don't set a parameter at all
return
super().updateFromKwargs(kwargs=kwargs, **unused)
@defer.inlineCallbacks
def getChoices(self, master, scheduler, buildername):
if buildername is None:
# this is the "Force All Builds" page
workers = yield self.master.data.get(('workers',))
else:
builder = yield self.master.data.get(('builders', buildername))
workers = yield self.master.data.get(('builders', builder['builderid'], 'workers'))
workernames = [worker['name'] for worker in workers]
workernames.sort()
workernames.insert(0, self.anySentinel)
return workernames
class FileParameter(BaseParameter):
"""A parameter which allows to download a whole file and store it as a property or patch"""
type = 'file'
maxsize = 1024 * 1024 * 10 # 10M
class NestedParameter(BaseParameter):
"""A 'parent' parameter for a set of related parameters. This provides a
logical grouping for the child parameters.
Typically, the 'fullName' of the child parameters mix in the parent's
'fullName'. This allows for a field to appear multiple times in a form
(for example, two codebases each have a 'branch' field).
If the 'name' of the parent is the empty string, then the parent's name
does not mix in with the child 'fullName'. This is useful when a field
will not appear multiple time in a scheduler but the logical grouping is
helpful.
The result of a NestedParameter is typically a dictionary, with the key/value
being the name/value of the children.
"""
spec_attributes = [
"layout",
"columns",
] # field is recursive, and thus managed in custom getSpec
type = 'nested'
layout = 'vertical'
fields = None
columns: int | None = None
def __init__(self, name, fields, **kwargs):
super().__init__(fields=fields, name=name, **kwargs)
# reasonable defaults for the number of columns
if self.columns is None:
num_visible_fields = len([field for field in fields if not field.hide])
if num_visible_fields >= 4:
self.columns = 2
else:
self.columns = 1
if self.columns > 4:
config.error("UI only support up to 4 columns in nested parameters")
# fix up the child nodes with the parent (use None for now):
self.setParent(None)
def setParent(self, parent):
super().setParent(parent)
for field in self.fields: # pylint: disable=not-an-iterable
field.setParent(self)
@defer.inlineCallbacks
def collectChildProperties(self, kwargs, properties, collector, **kw):
"""Collapse the child values into a dictionary. This is intended to be
called by child classes to fix up the fullName->name conversions."""
childProperties = {}
for field in self.fields: # pylint: disable=not-an-iterable
yield collector.collectValidationErrors(
field.fullName,
field.updateFromKwargs,
kwargs=kwargs,
properties=childProperties,
collector=collector,
**kw,
)
kwargs[self.fullName] = childProperties
@defer.inlineCallbacks
def updateFromKwargs(self, kwargs, properties, collector, **kw):
"""By default, the child values will be collapsed into a dictionary. If
the parent is anonymous, this dictionary is the top-level properties."""
yield self.collectChildProperties(
kwargs=kwargs, properties=properties, collector=collector, **kw
)
# default behavior is to set a property
# -- use setdefault+update in order to collapse 'anonymous' nested
# parameters correctly
if self.name:
d = properties.setdefault(self.name, {})
else:
# if there's no name, collapse this nest all the way
d = properties
d.update(kwargs[self.fullName])
def getSpec(self):
ret = super().getSpec()
# pylint: disable=not-an-iterable
ret['fields'] = [field.getSpec() for field in self.fields]
return ret
ParameterGroup = NestedParameter
class AnyPropertyParameter(NestedParameter):
"""A generic property parameter, where both the name and value of the property
must be given."""
type = NestedParameter.type
def __init__(self, name, **kw):
fields = [
StringParameter(name='name', label="Name:"),
StringParameter(name='value', label="Value:"),
]
super().__init__(name, label='', fields=fields, **kw)
def getFromKwargs(self, kwargs):
raise ValidationError("AnyPropertyParameter can only be used by properties")
@defer.inlineCallbacks
def updateFromKwargs(self, master, properties, kwargs, collector, **kw):
yield self.collectChildProperties(
master=master, properties=properties, kwargs=kwargs, collector=collector, **kw
)
pname = kwargs[self.fullName].get("name", "")
pvalue = kwargs[self.fullName].get("value", "")
if not pname:
return
validation = master.config.validation
pname_validate = validation['property_name']
pval_validate = validation['property_value']
if not pname_validate.match(pname) or not pval_validate.match(pvalue):
raise ValidationError(f"bad property name='{pname}', value='{pvalue}'")
properties[pname] = pvalue
class CodebaseParameter(NestedParameter):
"""A parameter whose result is a codebase specification instead of a property"""
type = NestedParameter.type
codebase = ''
def __init__(
self,
codebase,
name=None,
label=None,
branch=DefaultField,
revision=DefaultField,
repository=DefaultField,
project=DefaultField,
patch=None,
**kwargs,
):
"""
A set of properties that will be used to generate a codebase dictionary.
The branch/revision/repository/project should each be a parameter that
will map to the corresponding value in the sourcestamp. Use None to disable
the field.
@param codebase: name of the codebase; used as key for the sourcestamp set
@type codebase: unicode
@param name: optional override for the name-currying for the subfields
@type codebase: unicode
@param label: optional override for the label for this set of parameters
@type codebase: unicode
"""
name = name or codebase
if label is None and codebase:
label = "Codebase: " + codebase
fields_dict = {
"branch": branch,
"revision": revision,
"repository": repository,
"project": project,
}
for k, v in fields_dict.items():
if v is DefaultField:
v = StringParameter(name=k, label=k.capitalize() + ":")
elif isinstance(v, str):
v = FixedParameter(name=k, default=v)
fields_dict[k] = v
fields = [val for k, val in sorted(fields_dict.items(), key=lambda x: x[0]) if val]
if patch is not None:
if patch.name != "patch":
config.error("patch parameter of a codebase must be named 'patch'")
fields.append(patch)
if self.columns is None and 'columns' not in kwargs:
self.columns = 1
super().__init__(name=name, label=label, codebase=codebase, fields=fields, **kwargs)
def createSourcestamp(self, properties, kwargs):
# default, just return the things we put together
return kwargs.get(self.fullName, {})
@defer.inlineCallbacks
def updateFromKwargs(self, sourcestamps, kwargs, properties, collector, **kw):
yield self.collectChildProperties(
sourcestamps=sourcestamps,
properties=properties,
kwargs=kwargs,
collector=collector,
**kw,
)
# convert the "property" to a sourcestamp
ss = self.createSourcestamp(properties, kwargs)
if ss is not None:
patch = ss.pop('patch', None)
if patch is not None:
for k, v in patch.items():
ss['patch_' + k] = v
sourcestamps[self.codebase] = ss
def oneCodebase(**kw):
return [CodebaseParameter('', **kw)]
class PatchParameter(NestedParameter):
"""A patch parameter contains pre-configure UI for all the needed components for a
sourcestamp patch
"""
columns = 1
def __init__(self, **kwargs):
name = kwargs.pop('name', 'patch')
default_fields = [
FileParameter('body'),
IntParameter('level', default=1),
StringParameter('author', default=""),
StringParameter('comment', default=""),
StringParameter('subdir', default="."),
]
fields = [kwargs.pop(field.name, field) for field in default_fields]
super().__init__(name, fields=fields, **kwargs)
class ForceScheduler(base.BaseScheduler):
"""
ForceScheduler implements the backend for a UI to allow customization of
builds. For example, a web form be populated to trigger a build.
"""
compare_attrs: ClassVar[Sequence[str]] = (
*base.BaseScheduler.compare_attrs,
"builderNames",
"reason",
"username",
"forcedProperties",
)
def __init__(
self,
name,
builderNames,
username: UserNameParameter | None = None,
reason: StringParameter | None = None,
reasonString="A build was forced by '%(owner)s': %(reason)s",
buttonName=None,
codebases=None,
label=None,
properties=None,
priority: IntParameter | None = None,
):
"""
Initialize a ForceScheduler.
The UI will provide a set of fields to the user; these fields are
driven by a corresponding child class of BaseParameter.
Use NestedParameter to provide logical groupings for parameters.
The branch/revision/repository/project fields are deprecated and
provided only for backwards compatibility. Using a Codebase(name='')
will give the equivalent behavior.
@param name: name of this scheduler (used as a key for state)
@type name: unicode
@param builderNames: list of builders this scheduler may start
@type builderNames: list of unicode
@param username: the "owner" for a build (may not be shown depending
on the Auth configuration for the master)
@type username: BaseParameter
@param reason: the "reason" for a build
@type reason: BaseParameter
@param codebases: the codebases for a build
@type codebases: list of string's or CodebaseParameter's;
None will generate a default, but
CodebaseParameter(codebase='', hide=True)
will remove all codebases
@param properties: extra properties to configure the build
@type properties: list of BaseParameter's
"""
if not self.checkIfType(name, str):
config.error(f"ForceScheduler name must be a unicode string: {name!r}")
if not name:
config.error(f"ForceScheduler name must not be empty: {name!r}")
if not identifiers.ident_re.match(name):
config.error(f"ForceScheduler name must be an identifier: {name!r}")
if not self.checkIfListOfType(builderNames, (str,)):
config.error(
f"ForceScheduler '{name}': builderNames must be a list of strings: "
f"{builderNames!r}"
)
if reason is None:
reason = StringParameter(name="reason", default="force build", size=20)
if self.checkIfType(reason, BaseParameter):
self.reason = reason
else:
config.error(f"ForceScheduler '{name}': reason must be a StringParameter: {reason!r}")
if properties is None:
properties = []
if not self.checkIfListOfType(properties, BaseParameter):
config.error(
f"ForceScheduler '{name}': properties must be "
f"a list of BaseParameters: {properties!r}"
)
if username is None:
username = UserNameParameter()
if self.checkIfType(username, BaseParameter):
self.username = username
else:
config.error(
f"ForceScheduler '{name}': username must be a StringParameter: {username!r}"
)
self.forcedProperties = []
self.label = name if label is None else label
# Use the default single codebase form if none are provided
if codebases is None:
codebases = [CodebaseParameter(codebase='')]
elif not codebases:
config.error(
f"ForceScheduler '{name}': 'codebases' cannot be empty;"
f" use [CodebaseParameter(codebase='', hide=True)] if needed: "
f"{codebases!r} "
)
elif not isinstance(codebases, list):
config.error(
f"ForceScheduler '{name}': 'codebases' should be a list of strings "
f"or CodebaseParameter, not {type(codebases)}"
)
codebase_dict = {}
for codebase in codebases:
if isinstance(codebase, str):
codebase = CodebaseParameter(codebase=codebase)
elif not isinstance(codebase, CodebaseParameter):
config.error(
f"ForceScheduler '{name}': 'codebases' must be a list of strings "
f"or CodebaseParameter objects: {codebases!r}"
)
self.forcedProperties.append(codebase)
codebase_dict[codebase.codebase] = {"branch": '', "repository": '', "revision": ''}
super().__init__(
name=name, builderNames=builderNames, properties={}, codebases=codebase_dict
)
if priority is None:
priority = IntParameter(name="priority", default=0)
if self.checkIfType(priority, IntParameter):
self.priority = priority
else:
config.error(f"ForceScheduler '{name}': priority must be a IntParameter: {priority!r}")
if properties:
self.forcedProperties.extend(properties)
# this is used to simplify the template
self.all_fields = [NestedParameter(name='', fields=[username, reason, priority])]
self.all_fields.extend(self.forcedProperties)
self.reasonString = reasonString
self.buttonName = buttonName or name
def checkIfType(self, obj, chkType):
return isinstance(obj, chkType)
def checkIfListOfType(self, obj, chkType):
isListOfType = True
if self.checkIfType(obj, list):
for item in obj:
if not self.checkIfType(item, chkType):
isListOfType = False
break
else:
isListOfType = False
return isListOfType
@defer.inlineCallbacks
def gatherPropertiesAndChanges(self, collector, **kwargs):
properties = {}
changeids = []
sourcestamps = {}
for param in self.forcedProperties:
yield collector.collectValidationErrors(
param.fullName,
param.updateFromKwargs,
master=self.master,
properties=properties,
changes=changeids,
sourcestamps=sourcestamps,
collector=collector,
kwargs=kwargs,
)
changeids = [type(a) == int and a or a.number for a in changeids]
real_properties = Properties()
for pname, pvalue in properties.items():
real_properties.setProperty(pname, pvalue, "Force Build Form")
return (real_properties, changeids, sourcestamps)
@defer.inlineCallbacks
def computeBuilderNames(self, builderNames=None, builderid=None):
if builderNames is None:
if builderid is not None:
builder = yield self.master.data.get(('builders', str(builderid)))
builderNames = [builder['name']]
else:
builderNames = self.builderNames
else:
builderNames = sorted(set(builderNames).intersection(self.builderNames))
return builderNames
@defer.inlineCallbacks
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, builderid)
if not builderNames:
raise KeyError("builderNames not specified or not supported")
# Currently the validation code expects all kwargs to be lists
# I don't want to refactor that now so much sure we comply...
kwargs = dict((k, [v]) if not isinstance(v, list) else (k, v) for k, v in kwargs.items())
# probably need to clean that out later as the IProperty is already a
# validation mechanism
collector = ValidationErrorCollector()
reason = yield collector.collectValidationErrors(
self.reason.fullName, self.reason.getFromKwargs, kwargs
)
if owner is None or owner == "anonymous":
owner = yield collector.collectValidationErrors(
self.username.fullName, self.username.getFromKwargs, kwargs
)
priority = yield collector.collectValidationErrors(
self.priority.fullName, self.priority.getFromKwargs, kwargs
)
properties, _, sourcestamps = yield self.gatherPropertiesAndChanges(collector, **kwargs)
collector.maybeRaiseCollectedErrors()
properties.setProperty("reason", reason, "Force Build Form")
properties.setProperty("owner", owner, "Force Build Form")
r = self.reasonString % {'owner': owner, 'reason': reason}
# turn sourcestamps into a list
for cb, ss in sourcestamps.items():
ss['codebase'] = cb
sourcestamps = list(sourcestamps.values())
# everything is validated, we can create our source stamp, and
# buildrequest
res = yield self.addBuildsetForSourceStampsWithDefaults(
reason=r,
sourcestamps=sourcestamps,
properties=properties,
builderNames=builderNames,
priority=priority,
)
return res
| 31,056 | Python | .py | 722 | 33.5 | 100 | 0.626671 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
4,995 | filter.py | buildbot_buildbot/master/buildbot/schedulers/filter.py | # This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright Buildbot Team Members
# old (pre-0.8.4) location for ChangeFilter
from buildbot.changes.filter import ChangeFilter
_hush_pyflakes = ChangeFilter # keep pyflakes happy
| 854 | Python | .py | 17 | 49.058824 | 79 | 0.792566 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
4,996 | basic.py | buildbot_buildbot/master/buildbot/schedulers/basic.py | # This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright Buildbot Team Members
from collections import defaultdict
from typing import ClassVar
from typing import Sequence
from twisted.internet import defer
from twisted.internet import reactor
from twisted.python import log
from buildbot import config
from buildbot import util
from buildbot.changes import changes
from buildbot.changes.filter import ChangeFilter
from buildbot.schedulers import base
from buildbot.schedulers import dependent
from buildbot.util import NotABranch
from buildbot.util.codebase import AbsoluteSourceStampsMixin
class BaseBasicScheduler(base.BaseScheduler):
"""
@param onlyImportant: If True, only important changes will be added to the
buildset.
@type onlyImportant: boolean
"""
compare_attrs: ClassVar[Sequence[str]] = (
'treeStableTimer',
'change_filter',
'fileIsImportant',
'onlyImportant',
'reason',
)
_reactor = reactor # for tests
fileIsImportant = None
reason = ''
class NotSet:
pass
def __init__(
self,
name,
shouldntBeSet=NotSet,
treeStableTimer=None,
builderNames=None,
branch=NotABranch,
branches=NotABranch,
fileIsImportant=None,
categories=None,
reason="The %(classname)s scheduler named '%(name)s' triggered this build",
change_filter=None,
onlyImportant=False,
**kwargs,
):
if shouldntBeSet is not self.NotSet:
config.error("pass arguments to schedulers using keyword arguments")
if fileIsImportant and not callable(fileIsImportant):
config.error("fileIsImportant must be a callable")
# initialize parent classes
super().__init__(name, builderNames, **kwargs)
self.treeStableTimer = treeStableTimer
if fileIsImportant is not None:
self.fileIsImportant = fileIsImportant
self.onlyImportant = onlyImportant
self.change_filter = self.getChangeFilter(
branch=branch, branches=branches, change_filter=change_filter, categories=categories
)
# the IDelayedCall used to wake up when this scheduler's
# treeStableTimer expires.
self._stable_timers = defaultdict(lambda: None)
self._stable_timers_lock = defer.DeferredLock()
self.reason = util.bytes2unicode(
reason % {'name': name, 'classname': self.__class__.__name__}
)
def getChangeFilter(self, branch, branches, change_filter, categories):
raise NotImplementedError
@defer.inlineCallbacks
def activate(self):
yield super().activate()
if not self.enabled:
return
yield self.startConsumingChanges(
fileIsImportant=self.fileIsImportant,
change_filter=self.change_filter,
onlyImportant=self.onlyImportant,
)
# if we have a treeStableTimer, if there are classified changes
# out there, start their timers again
if self.treeStableTimer:
yield self.scanExistingClassifiedChanges()
# otherwise, we don't care about classified
# changes, so get rid of any hanging around from previous
# configurations
else:
yield self.master.db.schedulers.flushChangeClassifications(self.serviceid)
@defer.inlineCallbacks
def deactivate(self):
# the base deactivate will unsubscribe from new changes
yield super().deactivate()
if not self.enabled:
return
@util.deferredLocked(self._stable_timers_lock)
def cancel_timers():
for timer in self._stable_timers.values():
if timer:
timer.cancel()
self._stable_timers.clear()
yield cancel_timers()
@util.deferredLocked('_stable_timers_lock')
def gotChange(self, change, important):
if not self.treeStableTimer:
# if there's no treeStableTimer, we can completely ignore
# unimportant changes
if not important:
return defer.succeed(None)
# otherwise, we'll build it right away
return self.addBuildsetForChanges(
reason=self.reason, changeids=[change.number], priority=self.priority
)
timer_name = self.getTimerNameForChange(change)
# if we have a treeStableTimer
# - for an important change, start the timer
# - for an unimportant change, reset the timer if it is running
if important or self._stable_timers[timer_name]:
if self._stable_timers[timer_name]:
self._stable_timers[timer_name].cancel()
def fire_timer():
d = self.stableTimerFired(timer_name)
d.addErrback(log.err, "while firing stable timer")
self._stable_timers[timer_name] = self._reactor.callLater(
self.treeStableTimer, fire_timer
)
# record the change's importance
return self.master.db.schedulers.classifyChanges(self.serviceid, {change.number: important})
@defer.inlineCallbacks
def scanExistingClassifiedChanges(self):
# call gotChange for each classified change. This is called at startup
# and is intended to re-start the treeStableTimer for any changes that
# had not yet been built when the scheduler was stopped.
# NOTE: this may double-call gotChange for changes that arrive just as
# the scheduler starts up. In practice, this doesn't hurt anything.
classifications = yield self.master.db.schedulers.getChangeClassifications(self.serviceid)
# call gotChange for each change, after first fetching it from the db
for changeid, important in classifications.items():
chdict = yield self.master.db.changes.getChange(changeid)
if not chdict:
continue
change = yield changes.Change.fromChdict(self.master, chdict)
yield self.gotChange(change, important)
def getTimerNameForChange(self, change):
raise NotImplementedError # see subclasses
def getChangeClassificationsForTimer(self, sched_id, timer_name):
"""similar to db.schedulers.getChangeClassifications, but given timer
name"""
raise NotImplementedError # see subclasses
@util.deferredLocked('_stable_timers_lock')
@defer.inlineCallbacks
def stableTimerFired(self, timer_name):
# delete this now-fired timer, if the service has already been stopped
# then just bail out
if not self._stable_timers.pop(timer_name, None):
return
classifications = yield self.getChangeClassificationsForTimer(self.serviceid, timer_name)
# just in case: databases do weird things sometimes!
if not classifications: # pragma: no cover
return
changeids = sorted(classifications.keys())
yield self.addBuildsetForChanges(
reason=self.reason, changeids=changeids, priority=self.priority
)
max_changeid = changeids[-1] # (changeids are sorted)
yield self.master.db.schedulers.flushChangeClassifications(
self.serviceid, less_than=max_changeid + 1
)
class SingleBranchScheduler(AbsoluteSourceStampsMixin, BaseBasicScheduler):
def __init__(self, name, createAbsoluteSourceStamps=False, **kwargs):
self.createAbsoluteSourceStamps = createAbsoluteSourceStamps
super().__init__(name, **kwargs)
@defer.inlineCallbacks
def gotChange(self, change, important):
if self.createAbsoluteSourceStamps:
yield self.recordChange(change)
yield super().gotChange(change, important)
def getCodebaseDict(self, codebase):
if self.createAbsoluteSourceStamps:
return super().getCodebaseDict(codebase)
return self.codebases[codebase]
def getChangeFilter(self, branch, branches, change_filter, categories):
if branch is NotABranch and not change_filter:
config.error(
"the 'branch' argument to SingleBranchScheduler is "
+ "mandatory unless change_filter is provided"
)
elif branches is not NotABranch:
config.error("the 'branches' argument is not allowed for " + "SingleBranchScheduler")
return ChangeFilter.fromSchedulerConstructorArgs(
change_filter=change_filter, branch=branch, categories=categories
)
def getTimerNameForChange(self, change):
return "only" # this class only uses one timer
def getChangeClassificationsForTimer(self, sched_id, timer_name):
return self.master.db.schedulers.getChangeClassifications(sched_id)
class Scheduler(SingleBranchScheduler):
"alias for SingleBranchScheduler"
def __init__(self, *args, **kwargs):
log.msg(
"WARNING: the name 'Scheduler' is deprecated; use "
+ "buildbot.schedulers.basic.SingleBranchScheduler instead "
+ "(note that this may require you to change your import "
+ "statement)"
)
super().__init__(*args, **kwargs)
class AnyBranchScheduler(BaseBasicScheduler):
def getChangeFilter(self, branch, branches, change_filter, categories):
assert branch is NotABranch
return ChangeFilter.fromSchedulerConstructorArgs(
change_filter=change_filter, branch=branches, categories=categories
)
def getTimerNameForChange(self, change):
# Py2.6+: could be a namedtuple
return (change.codebase, change.project, change.repository, change.branch)
def getChangeClassificationsForTimer(self, sched_id, timer_name):
# set in getTimerNameForChange
codebase, project, repository, branch = timer_name
return self.master.db.schedulers.getChangeClassifications(
sched_id, branch=branch, repository=repository, codebase=codebase, project=project
)
# now at buildbot.schedulers.dependent, but keep the old name alive
Dependent = dependent.Dependent
| 10,851 | Python | .py | 236 | 37.300847 | 100 | 0.686061 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
4,997 | triggerable.py | buildbot_buildbot/master/buildbot/schedulers/triggerable.py | # This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright Buildbot Team Members
from typing import ClassVar
from typing import Sequence
from twisted.internet import defer
from twisted.python import failure
from zope.interface import implementer
from buildbot.interfaces import ITriggerableScheduler
from buildbot.process.properties import Properties
from buildbot.schedulers import base
from buildbot.util import debounce
@implementer(ITriggerableScheduler)
class Triggerable(base.BaseScheduler):
compare_attrs: ClassVar[Sequence[str]] = (*base.BaseScheduler.compare_attrs, 'reason')
def __init__(self, name, builderNames, reason=None, **kwargs):
super().__init__(name, builderNames, **kwargs)
self._waiters = {}
self._buildset_complete_consumer = None
self.reason = reason
def trigger(
self,
waited_for,
sourcestamps=None,
set_props=None,
parent_buildid=None,
parent_relationship=None,
):
"""Trigger this scheduler with the optional given list of sourcestamps
Returns two deferreds:
idsDeferred -- yields the ids of the buildset and buildrequest, as soon as they are
available.
resultsDeferred -- yields the build result(s), when they finish."""
# properties for this buildset are composed of our own properties,
# potentially overridden by anything from the triggering build
props = Properties()
props.updateFromProperties(self.properties)
reason = self.reason
if set_props:
props.updateFromProperties(set_props)
reason = set_props.getProperty('reason')
if reason is None:
reason = f"The Triggerable scheduler named '{self.name}' triggered this build"
# note that this does not use the buildset subscriptions mechanism, as
# the duration of interest to the caller is bounded by the lifetime of
# this process.
idsDeferred = self.addBuildsetForSourceStampsWithDefaults(
reason,
sourcestamps,
waited_for,
priority=self.priority,
properties=props,
parent_buildid=parent_buildid,
parent_relationship=parent_relationship,
)
resultsDeferred = defer.Deferred()
@idsDeferred.addCallback
def setup_waiter(ids):
bsid, brids = ids
self._waiters[bsid] = (resultsDeferred, brids)
self._updateWaiters()
return ids
return idsDeferred, resultsDeferred
@defer.inlineCallbacks
def startService(self):
yield super().startService()
self._updateWaiters.start()
@defer.inlineCallbacks
def stopService(self):
# finish any _updateWaiters calls
yield self._updateWaiters.stop()
# cancel any outstanding subscription
if self._buildset_complete_consumer:
self._buildset_complete_consumer.stopConsuming()
self._buildset_complete_consumer = None
# and errback any outstanding deferreds
if self._waiters:
msg = 'Triggerable scheduler stopped before build was complete'
for d, _ in self._waiters.values():
d.errback(failure.Failure(RuntimeError(msg)))
self._waiters = {}
yield super().stopService()
@debounce.method(wait=0)
@defer.inlineCallbacks
def _updateWaiters(self):
if self._waiters and not self._buildset_complete_consumer:
startConsuming = self.master.mq.startConsuming
self._buildset_complete_consumer = yield startConsuming(
self._buildset_complete_cb, ('buildsets', None, 'complete')
)
elif not self._waiters and self._buildset_complete_consumer:
self._buildset_complete_consumer.stopConsuming()
self._buildset_complete_consumer = None
def _buildset_complete_cb(self, key, msg):
if msg['bsid'] not in self._waiters:
return
# pop this bsid from the waiters list,
d, brids = self._waiters.pop(msg['bsid'])
# ..and potentially stop consuming buildset completion notifications
self._updateWaiters()
# fire the callback to indicate that the triggered build is complete
d.callback((msg['results'], brids))
| 5,014 | Python | .py | 113 | 36.238938 | 95 | 0.682107 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
4,998 | manager.py | buildbot_buildbot/master/buildbot/schedulers/manager.py | # This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright Buildbot Team Members
from __future__ import annotations
from buildbot.process.measured_service import MeasuredBuildbotServiceManager
class SchedulerManager(MeasuredBuildbotServiceManager):
name: str | None = "SchedulerManager" # type: ignore[assignment]
managed_services_name = "schedulers"
config_attr = "schedulers"
| 1,019 | Python | .py | 20 | 49.15 | 79 | 0.792965 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
4,999 | base.py | buildbot_buildbot/master/buildbot/schedulers/base.py | # This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright Buildbot Team Members
from __future__ import annotations
from typing import ClassVar
from typing import Sequence
from twisted.internet import defer
from twisted.python import failure
from twisted.python import log
from zope.interface import implementer
from buildbot import config
from buildbot import interfaces
from buildbot.changes import changes
from buildbot.process.properties import Properties
from buildbot.util.service import ClusteredBuildbotService
from buildbot.util.state import StateMixin
@implementer(interfaces.IScheduler)
class BaseScheduler(ClusteredBuildbotService, StateMixin):
DEFAULT_CODEBASES: dict[str, dict[str, str]] = {'': {}}
compare_attrs: ClassVar[Sequence[str]] = (
*ClusteredBuildbotService.compare_attrs,
'builderNames',
'properties',
'codebases',
)
def __init__(self, name, builderNames, properties=None, codebases=None, priority=None):
super().__init__(name=name)
if codebases is None:
codebases = self.DEFAULT_CODEBASES.copy()
ok = True
if interfaces.IRenderable.providedBy(builderNames):
pass
elif isinstance(builderNames, (list, tuple)):
for b in builderNames:
if not isinstance(b, str) and not interfaces.IRenderable.providedBy(b):
ok = False
else:
ok = False
if not ok:
config.error(
"The builderNames argument to a scheduler must be a list "
"of Builder names or an IRenderable object that will render"
"to a list of builder names."
)
self.builderNames = builderNames
if properties is None:
properties = {}
self.properties = Properties()
self.properties.update(properties, "Scheduler")
self.properties.setProperty("scheduler", name, "Scheduler")
self.objectid = None
# Set the codebases that are necessary to process the changes
# These codebases will always result in a sourcestamp with or without
# changes
known_keys = set(['branch', 'repository', 'revision'])
if codebases is None:
config.error("Codebases cannot be None")
elif isinstance(codebases, list):
codebases = dict((codebase, {}) for codebase in codebases)
elif not isinstance(codebases, dict):
config.error("Codebases must be a dict of dicts, or list of strings")
else:
for codebase, attrs in codebases.items():
if not isinstance(attrs, dict):
config.error("Codebases must be a dict of dicts")
else:
unk = set(attrs) - known_keys
if unk:
config.error(
f"Unknown codebase keys {', '.join(unk)} for codebase {codebase}"
)
self.codebases = codebases
# internal variables
self._change_consumer = None
self._enable_consumer = None
self._change_consumption_lock = defer.DeferredLock()
self.enabled = True
if priority and not isinstance(priority, int) and not callable(priority):
config.error(
f"Invalid type for priority: {type(priority)}. "
"It must either be an integer or a function"
)
self.priority = priority
def __repr__(self):
"""
Provide a meaningful string representation of scheduler.
"""
return (
f'<{self.__class__.__name__}({self.name}, {self.builderNames}, enabled={self.enabled})>'
)
def reconfigService(self, *args, **kwargs):
raise NotImplementedError()
# activity handling
@defer.inlineCallbacks
def activate(self):
if not self.enabled:
return None
# even if we aren't called via _activityPoll(), at this point we
# need to ensure the service id is set correctly
if self.serviceid is None:
self.serviceid = yield self._getServiceId()
assert self.serviceid is not None
schedulerData = yield self._getScheduler(self.serviceid)
if schedulerData:
self.enabled = schedulerData.enabled
if not self._enable_consumer:
yield self.startConsumingEnableEvents()
return None
def _enabledCallback(self, key, msg):
if msg['enabled']:
self.enabled = True
d = self.activate()
else:
d = self.deactivate()
def fn(x):
self.enabled = False
d.addCallback(fn)
return d
@defer.inlineCallbacks
def deactivate(self):
if not self.enabled:
return None
yield self._stopConsumingChanges()
return None
# service handling
def _getServiceId(self):
return self.master.data.updates.findSchedulerId(self.name)
def _getScheduler(self, sid):
return self.master.db.schedulers.getScheduler(sid)
def _claimService(self):
return self.master.data.updates.trySetSchedulerMaster(self.serviceid, self.master.masterid)
def _unclaimService(self):
return self.master.data.updates.trySetSchedulerMaster(self.serviceid, None)
# status queries
# deprecated: these aren't compatible with distributed schedulers
def listBuilderNames(self):
return self.builderNames
# change handling
@defer.inlineCallbacks
def startConsumingChanges(self, fileIsImportant=None, change_filter=None, onlyImportant=False):
assert fileIsImportant is None or callable(fileIsImportant)
# register for changes with the data API
assert not self._change_consumer
self._change_consumer = yield self.master.mq.startConsuming(
lambda k, m: self._changeCallback(k, m, fileIsImportant, change_filter, onlyImportant),
('changes', None, 'new'),
)
@defer.inlineCallbacks
def startConsumingEnableEvents(self):
assert not self._enable_consumer
self._enable_consumer = yield self.master.mq.startConsuming(
self._enabledCallback, ('schedulers', str(self.serviceid), 'updated')
)
@defer.inlineCallbacks
def _changeCallback(self, key, msg, fileIsImportant, change_filter, onlyImportant):
# ignore changes delivered while we're not running
if not self._change_consumer:
return
# get a change object, since the API requires it
chdict = yield self.master.db.changes.getChange(msg['changeid'])
change = yield changes.Change.fromChdict(self.master, chdict)
# filter it
if change_filter and not change_filter.filter_change(change):
return
if change.codebase not in self.codebases:
log.msg(
format='change contains codebase %(codebase)s that is '
'not processed by scheduler %(name)s',
codebase=change.codebase,
name=self.name,
)
return
if fileIsImportant:
try:
important = fileIsImportant(change)
if not important and onlyImportant:
return
except Exception:
log.err(failure.Failure(), f'in fileIsImportant check for {change}')
return
else:
important = True
# use change_consumption_lock to ensure the service does not stop
# while this change is being processed
d = self._change_consumption_lock.run(self.gotChange, change, important)
d.addErrback(log.err, 'while processing change')
def _stopConsumingChanges(self):
# (note: called automatically in deactivate)
# acquire the lock change consumption lock to ensure that any change
# consumption is complete before we are done stopping consumption
def stop():
if self._change_consumer:
self._change_consumer.stopConsuming()
self._change_consumer = None
return self._change_consumption_lock.run(stop)
def gotChange(self, change, important):
raise NotImplementedError
# starting builds
@defer.inlineCallbacks
def addBuildsetForSourceStampsWithDefaults(
self,
reason,
sourcestamps=None,
waited_for=False,
properties=None,
builderNames=None,
priority=None,
**kw,
):
if sourcestamps is None:
sourcestamps = []
# convert sourcestamps to a dictionary keyed by codebase
stampsByCodebase = {}
for ss in sourcestamps:
cb = ss['codebase']
if cb in stampsByCodebase:
raise RuntimeError("multiple sourcestamps with same codebase")
stampsByCodebase[cb] = ss
# Merge codebases with the passed list of sourcestamps
# This results in a new sourcestamp for each codebase
stampsWithDefaults = []
for codebase in self.codebases:
cb = yield self.getCodebaseDict(codebase)
ss = {
'codebase': codebase,
'repository': cb.get('repository', ''),
'branch': cb.get('branch', None),
'revision': cb.get('revision', None),
'project': '',
}
# apply info from passed sourcestamps onto the configured default
# sourcestamp attributes for this codebase.
ss.update(stampsByCodebase.get(codebase, {}))
stampsWithDefaults.append(ss)
# fill in any supplied sourcestamps that aren't for a codebase in the
# scheduler's codebase dictionary
for codebase in set(stampsByCodebase) - set(self.codebases):
cb = stampsByCodebase[codebase]
ss = {
'codebase': codebase,
'repository': cb.get('repository', ''),
'branch': cb.get('branch', None),
'revision': cb.get('revision', None),
'project': '',
}
stampsWithDefaults.append(ss)
rv = yield self.addBuildsetForSourceStamps(
sourcestamps=stampsWithDefaults,
reason=reason,
waited_for=waited_for,
properties=properties,
builderNames=builderNames,
priority=priority,
**kw,
)
return rv
def getCodebaseDict(self, codebase):
# Hook for subclasses to change codebase parameters when a codebase does
# not have a change associated with it.
try:
return defer.succeed(self.codebases[codebase])
except KeyError:
return defer.fail()
@defer.inlineCallbacks
def addBuildsetForChanges(
self,
waited_for=False,
reason='',
external_idstring=None,
changeids=None,
builderNames=None,
properties=None,
priority=None,
**kw,
):
if changeids is None:
changeids = []
changesByCodebase = {}
def get_last_change_for_codebase(codebase):
return max(changesByCodebase[codebase], key=lambda change: change.changeid)
# Changes are retrieved from database and grouped by their codebase
for changeid in changeids:
chdict = yield self.master.db.changes.getChange(changeid)
changesByCodebase.setdefault(chdict.codebase, []).append(chdict)
sourcestamps = []
for codebase in sorted(self.codebases):
if codebase not in changesByCodebase:
# codebase has no changes
# create a sourcestamp that has no changes
cb = yield self.getCodebaseDict(codebase)
ss = {
'codebase': codebase,
'repository': cb.get('repository', ''),
'branch': cb.get('branch', None),
'revision': cb.get('revision', None),
'project': '',
}
else:
lastChange = get_last_change_for_codebase(codebase)
ss = lastChange.sourcestampid
sourcestamps.append(ss)
if priority is None:
priority = self.priority
if callable(priority):
priority = priority(builderNames or self.builderNames, changesByCodebase)
elif priority is None:
priority = 0
# add one buildset, using the calculated sourcestamps
bsid, brids = yield self.addBuildsetForSourceStamps(
waited_for,
sourcestamps=sourcestamps,
reason=reason,
external_idstring=external_idstring,
builderNames=builderNames,
properties=properties,
priority=priority,
**kw,
)
return (bsid, brids)
@defer.inlineCallbacks
def addBuildsetForSourceStamps(
self,
waited_for=False,
sourcestamps=None,
reason='',
external_idstring=None,
properties=None,
builderNames=None,
priority=None,
**kw,
):
if sourcestamps is None:
sourcestamps = []
# combine properties
if properties:
properties.updateFromProperties(self.properties)
else:
properties = self.properties
# make a fresh copy that we actually can modify safely
properties = Properties.fromDict(properties.asDict())
# make extra info available from properties.render()
properties.master = self.master
properties.sourcestamps = []
properties.changes = []
for ss in sourcestamps:
if isinstance(ss, int):
# fetch actual sourcestamp and changes from data API
properties.sourcestamps.append((yield self.master.data.get(('sourcestamps', ss))))
properties.changes.extend(
(yield self.master.data.get(('sourcestamps', ss, 'changes')))
)
else:
# sourcestamp with no change, see addBuildsetForChanges
properties.sourcestamps.append(ss)
for c in properties.changes:
properties.updateFromProperties(Properties.fromDict(c['properties']))
# apply the default builderNames
if not builderNames:
builderNames = self.builderNames
# dynamically get the builder list to schedule
builderNames = yield properties.render(builderNames)
# Get the builder ids
# Note that there is a data.updates.findBuilderId(name)
# but that would merely only optimize the single builder case, while
# probably the multiple builder case will be severely impacted by the
# several db requests needed.
builderids = []
for bldr in (yield self.master.data.get(('builders',))):
if bldr['name'] in builderNames:
builderids.append(bldr['builderid'])
# translate properties object into a dict as required by the
# addBuildset method
properties_dict = yield properties.render(properties.asDict())
if priority is None:
priority = 0
bsid, brids = yield self.master.data.updates.addBuildset(
scheduler=self.name,
sourcestamps=sourcestamps,
reason=reason,
waited_for=waited_for,
properties=properties_dict,
builderids=builderids,
external_idstring=external_idstring,
priority=priority,
**kw,
)
return (bsid, brids)
| 16,503 | Python | .py | 398 | 30.944724 | 100 | 0.620883 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.