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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
5,000 | canceller.py | buildbot_buildbot/master/buildbot/schedulers/canceller.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 twisted.internet import defer
from buildbot import config
from buildbot.data import resultspec
from buildbot.util.service import BuildbotService
from buildbot.util.ssfilter import SourceStampFilter
from buildbot.util.ssfilter import extract_filter_values
class _OldBuildFilterSet:
def __init__(self):
self._by_builder = {}
def add_filter(self, builders, filter):
assert builders is not None
for builder in builders:
self._by_builder.setdefault(builder, []).append(filter)
def is_matched(self, builder_name, props):
assert builder_name is not None
filters = self._by_builder.get(builder_name, [])
for filter in filters:
if filter.is_matched(props):
return True
return False
class _TrackedBuildRequest:
def __init__(self, brid, builder_name, start_time, ss_tuples):
self.start_time = start_time
self.builder_name = builder_name
self.brid = brid
self.ss_tuples = ss_tuples
def __str__(self):
return (
f'_TrackedBuildRequest({self.brid}, {self.builder_name} '
f'{self.start_time}, {self.ss_tuples})'
)
__repr__ = __str__
class _OldBuildrequestTracker:
def __init__(self, reactor, filter, branch_key, on_cancel):
self.reactor = reactor
self.filter = filter
self.branch_key = branch_key
self.on_cancel = on_cancel
# We need to track build requests by IDs so that when such build request finishes we know
# what we no longer need to track. We also need to track build requests by source code
# branch, so that we can cancel build requests when branch sees new commits. Branch is
# identified by a tuple of project, codebase, repository and branch.
#
# Note that a single branch may run multiple builds. Also, changes are not a source for
# build request cancelling because a change may not result in builds being started due to
# user scheduler configuration. In such case it makes sense to let the build finish.
# (is_build, id) -> _TrackedBuildRequest
self.br_by_id = {}
self.br_by_ss = {}
self.change_time_by_ss = {}
self._change_count_since_clean = 0
def reconfig(self, filter, branch_key):
self.filter = filter
self.branch_key = branch_key
def is_buildrequest_tracked(self, br_id):
return br_id in self.br_by_id
def on_new_buildrequest(self, brid, builder_name, sourcestamps):
self._maybe_cancel_new_obsoleted_buildrequest(builder_name, sourcestamps)
self._add_new_buildrequest(brid, builder_name, sourcestamps)
def _add_new_buildrequest(self, brid, builder_name, sourcestamps):
now = self.reactor.seconds()
matched_ss = []
for ss in sourcestamps:
if ss['branch'] is None:
return
# Note that it's enough to match build by a single branch from a single codebase
if self.filter.is_matched(builder_name, ss):
matched_ss.append(ss)
if not matched_ss:
return
ss_tuples = [
(ss['project'], ss['codebase'], ss['repository'], self.branch_key(ss))
for ss in matched_ss
]
tracked_br = _TrackedBuildRequest(brid, builder_name, now, ss_tuples)
self.br_by_id[brid] = tracked_br
for ss_tuple in ss_tuples:
br_dict = self.br_by_ss.setdefault(ss_tuple, {})
br_dict[tracked_br.brid] = tracked_br
def _maybe_cancel_new_obsoleted_buildrequest(self, builder_name, sourcestamps):
for sourcestamp in sourcestamps:
ss_tuple = (
sourcestamp['project'],
sourcestamp['codebase'],
sourcestamp['repository'],
self.branch_key(sourcestamp),
)
newest_change_time = self.change_time_by_ss.get(ss_tuple, None)
if newest_change_time is None:
# Don't cancel any buildrequests if the cancelling buildrequest does not come from
# a change.
continue
br_dict = self.br_by_ss.get(ss_tuple, None)
if br_dict is None:
continue
brids_to_cancel = []
for tracked_br in list(br_dict.values()):
if tracked_br.builder_name != builder_name:
continue
if newest_change_time <= tracked_br.start_time:
# The existing build request is newer than the change, thus change should not
# be a reason to cancel it.
continue
del self.br_by_id[tracked_br.brid]
# Clear the canceled buildrequest from self.br_by_ss
for i_ss_tuple in tracked_br.ss_tuples:
other_br_dict = self.br_by_ss.get(i_ss_tuple, None)
if other_br_dict is None:
raise KeyError(
f'{self.__class__.__name__}: Could not find running builds '
f'by tuple {i_ss_tuple}'
)
del other_br_dict[tracked_br.brid]
if not other_br_dict:
del self.br_by_ss[i_ss_tuple]
brids_to_cancel.append(tracked_br.brid)
for brid in brids_to_cancel:
self.on_cancel(brid)
def on_complete_buildrequest(self, brid):
tracked_br = self.br_by_id.pop(brid, None)
if tracked_br is None:
return
for ss_tuple in tracked_br.ss_tuples:
br_dict = self.br_by_ss.get(ss_tuple, None)
if br_dict is None:
raise KeyError(
f'{self.__class__.__name__}: Could not find finished builds '
f'by tuple {ss_tuple}'
)
del br_dict[tracked_br.brid]
if not br_dict:
del self.br_by_ss[ss_tuple]
def on_change(self, change):
now = self.reactor.seconds()
ss_tuple = (
change['project'],
change['codebase'],
change['repository'],
self.branch_key(change),
)
# Note that now is monotonically increasing
self.change_time_by_ss[ss_tuple] = now
self._change_count_since_clean += 1
if self._change_count_since_clean >= 1000:
self.change_time_by_ss = {
ss_tuple: ss_now
for ss_tuple, ss_now in self.change_time_by_ss.items()
if now - ss_now < 60 * 10
}
self._change_count_since_clean = 0
class OldBuildCanceller(BuildbotService):
compare_attrs: ClassVar[Sequence[str]] = (*BuildbotService.compare_attrs, 'filters')
def checkConfig(self, name, filters, branch_key=None):
OldBuildCanceller.check_filters(filters)
self.name = name
self._buildrequest_new_consumer = None
self._buildrequest_complete_consumer = None
self._build_tracker = None
self._reconfiguring = False
self._completed_buildrequests_while_reconfiguring = []
@defer.inlineCallbacks
def reconfigService(self, name, filters, branch_key=None):
# While reconfiguring we acquire a list of currently pending build
# requests and seed the build tracker with these. We need to ensure that even if some
# builds or build requests finish during this process, the tracker gets to know about
# the changes in correct order. In order to do that, we defer all build request completion
# notifications to after the reconfig finishes.
#
# Note that old builds are cancelled according to the configuration that was live when they
# were created, so for already tracked builds we don't need to do anything.
self._reconfiguring = True
if branch_key is None:
branch_key = self._default_branch_key
filter_set_object = OldBuildCanceller.filter_tuples_to_filter_set_object(filters)
if self._build_tracker is None:
self._build_tracker = _OldBuildrequestTracker(
self.master.reactor, filter_set_object, branch_key, self._cancel_buildrequest
)
else:
self._build_tracker.reconfig(filter_set_object, branch_key)
all_running_buildrequests = yield self.master.data.get(
('buildrequests',), filters=[resultspec.Filter('complete', 'eq', [False])]
)
for breq in all_running_buildrequests:
if self._build_tracker.is_buildrequest_tracked(breq['buildrequestid']):
continue
yield self._on_buildrequest_new(None, breq)
self._reconfiguring = False
completed_breqs = self._completed_buildrequests_while_reconfiguring
self._completed_buildrequests_while_reconfiguring = []
for breq in completed_breqs:
self._build_tracker.on_complete_buildrequest(breq['buildrequestid'])
@defer.inlineCallbacks
def startService(self):
yield super().startService()
self._change_consumer = yield self.master.mq.startConsuming(
self._on_change, ('changes', None, 'new')
)
self._buildrequest_new_consumer = yield self.master.mq.startConsuming(
self._on_buildrequest_new, ('buildrequests', None, 'new')
)
self._buildrequest_complete_consumer = yield self.master.mq.startConsuming(
self._on_buildrequest_complete, ('buildrequests', None, 'complete')
)
@defer.inlineCallbacks
def stopService(self):
yield self._change_consumer.stopConsuming()
yield self._buildrequest_new_consumer.stopConsuming()
yield self._buildrequest_complete_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) != 2
or not isinstance(filter[1], SourceStampFilter)
):
config.error(
(
'{}: The filters argument must be a list of tuples each of which '
+ 'contains builders as the first item and SourceStampFilter as '
+ 'the second'
).format(cls.__name__)
)
builders, _ = filter
try:
extract_filter_values(builders, 'builders')
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 = _OldBuildFilterSet()
for filter in filters:
builders, ss_filter = filter
filter_set.add_filter(extract_filter_values(builders, 'builders'), ss_filter)
return filter_set
def _default_branch_key(self, ss_or_change):
branch = ss_or_change['branch']
if branch is None:
return None
# On some VCS systems each iteration of a PR gets its own branch. We want to track all
# iterations of the PR as a single unit.
if branch.startswith('refs/changes/'):
m = re.match(r'refs/changes/(\d+)/(\d+)/\d+', branch)
if m is not None:
return f'refs/changes/{m.group(1)}/{m.group(2)}'
return branch
def _on_change(self, key, change):
self._build_tracker.on_change(change)
@defer.inlineCallbacks
def _on_buildrequest_new(self, key, breq):
builder = yield self.master.data.get(("builders", breq['builderid']))
buildset = yield self.master.data.get(('buildsets', breq['buildsetid']))
self._build_tracker.on_new_buildrequest(
breq['buildrequestid'], builder['name'], buildset['sourcestamps']
)
def _on_buildrequest_complete(self, key, breq):
if self._reconfiguring:
self._completed_buildrequests_while_reconfiguring.append(breq)
return
self._build_tracker.on_complete_buildrequest(breq['buildrequestid'])
def _cancel_buildrequest(self, brid):
self.master.data.control(
'cancel',
{'reason': 'Build request has been obsoleted by a newer commit'},
('buildrequests', str(brid)),
)
| 13,458 | Python | .py | 286 | 36.206294 | 99 | 0.616037 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
5,001 | dependent.py | buildbot_buildbot/master/buildbot/schedulers/dependent.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 import interfaces
from buildbot import util
from buildbot.process.results import SUCCESS
from buildbot.process.results import WARNINGS
from buildbot.schedulers import base
class Dependent(base.BaseScheduler):
compare_attrs: ClassVar[Sequence[str]] = ('upstream_name',)
def __init__(self, name, upstream, builderNames, **kwargs):
super().__init__(name, builderNames, **kwargs)
if not interfaces.IScheduler.providedBy(upstream):
config.error("upstream must be another Scheduler instance")
self.upstream_name = upstream.name
self._buildset_new_consumer = None
self._buildset_complete_consumer = None
self._cached_upstream_bsids = None
# the subscription lock makes sure that we're done inserting a
# subscription into the DB before registering that the buildset is
# complete.
self._subscription_lock = defer.DeferredLock()
@defer.inlineCallbacks
def activate(self):
yield super().activate()
if not self.enabled:
return
self._buildset_new_consumer = yield self.master.mq.startConsuming(
self._buildset_new_cb, ('buildsets', None, 'new')
)
# TODO: refactor to subscribe only to interesting buildsets, and
# subscribe to them directly, via the data API
self._buildset_complete_consumer = yield self.master.mq.startConsuming(
self._buildset_complete_cb, ('buildsets', None, 'complete')
)
# check for any buildsets completed before we started
yield self._checkCompletedBuildsets(
None,
)
@defer.inlineCallbacks
def deactivate(self):
# the base deactivate will unsubscribe from new changes
yield super().deactivate()
if not self.enabled:
return
if self._buildset_new_consumer:
self._buildset_new_consumer.stopConsuming()
if self._buildset_complete_consumer:
self._buildset_complete_consumer.stopConsuming()
self._cached_upstream_bsids = None
@util.deferredLocked('_subscription_lock')
def _buildset_new_cb(self, key, msg):
# check if this was submitted by our upstream
if msg['scheduler'] != self.upstream_name:
return None
# record our interest in this buildset
return self._addUpstreamBuildset(msg['bsid'])
def _buildset_complete_cb(self, key, msg):
return self._checkCompletedBuildsets(msg['bsid'])
@util.deferredLocked('_subscription_lock')
@defer.inlineCallbacks
def _checkCompletedBuildsets(self, bsid):
subs = yield self._getUpstreamBuildsets()
sub_bsids = []
for sub_bsid, sub_ssids, sub_complete, sub_results in subs:
# skip incomplete builds, handling the case where the 'complete'
# column has not been updated yet
if not sub_complete and sub_bsid != bsid:
continue
# build a dependent build if the status is appropriate. Note that
# this uses the sourcestamps from the buildset, not from any of the
# builds performed to complete the buildset (since those might
# differ from one another)
if sub_results in (SUCCESS, WARNINGS):
yield self.addBuildsetForSourceStamps(
sourcestamps=sub_ssids.copy(), reason='downstream', priority=self.priority
)
sub_bsids.append(sub_bsid)
# and regardless of status, remove the subscriptions
yield self._removeUpstreamBuildsets(sub_bsids)
@defer.inlineCallbacks
def _updateCachedUpstreamBuilds(self):
if self._cached_upstream_bsids is None:
bsids = yield self.master.db.state.getState(self.objectid, 'upstream_bsids', [])
self._cached_upstream_bsids = bsids
@defer.inlineCallbacks
def _getUpstreamBuildsets(self):
# get a list of (bsid, ssids, complete, results) for all
# upstream buildsets
yield self._updateCachedUpstreamBuilds()
changed = False
rv = []
for bsid in self._cached_upstream_bsids[:]:
buildset = yield self.master.data.get(('buildsets', str(bsid)))
if not buildset:
self._cached_upstream_bsids.remove(bsid)
changed = True
continue
ssids = [ss['ssid'] for ss in buildset['sourcestamps']]
rv.append((bsid, ssids, buildset['complete'], buildset['results']))
if changed:
yield self.master.db.state.setState(
self.objectid, 'upstream_bsids', self._cached_upstream_bsids
)
return rv
@defer.inlineCallbacks
def _addUpstreamBuildset(self, bsid):
yield self._updateCachedUpstreamBuilds()
if bsid not in self._cached_upstream_bsids:
self._cached_upstream_bsids.append(bsid)
yield self.master.db.state.setState(
self.objectid, 'upstream_bsids', self._cached_upstream_bsids
)
@defer.inlineCallbacks
def _removeUpstreamBuildsets(self, bsids):
yield self._updateCachedUpstreamBuilds()
old = set(self._cached_upstream_bsids)
self._cached_upstream_bsids = list(old - set(bsids))
yield self.master.db.state.setState(
self.objectid, 'upstream_bsids', self._cached_upstream_bsids
)
| 6,300 | Python | .py | 136 | 37.632353 | 94 | 0.669984 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
5,002 | trysched.py | buildbot_buildbot/master/buildbot/schedulers/trysched.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 json
import os
from typing import ClassVar
from typing import Sequence
from twisted.internet import defer
from twisted.protocols import basic
from twisted.python import log
from twisted.spread import pb
from buildbot import pbutil
from buildbot.process.properties import Properties
from buildbot.schedulers import base
from buildbot.util import bytes2unicode
from buildbot.util import netstrings
from buildbot.util import unicode2bytes
from buildbot.util.maildir import MaildirService
class TryBase(base.BaseScheduler):
def filterBuilderList(self, builderNames):
"""
Make sure that C{builderNames} is a subset of the configured
C{self.builderNames}, returning an empty list if not. If
C{builderNames} is empty, use C{self.builderNames}.
@returns: list of builder names to build on
"""
# self.builderNames is the configured list of builders
# available for try. If the user supplies a list of builders,
# it must be restricted to the configured list. If not, build
# on all of the configured builders.
if builderNames:
for b in builderNames:
if b not in self.builderNames:
log.msg(f"{self} got with builder {b}")
log.msg(f" but that wasn't in our list: {self.builderNames}")
return []
else:
builderNames = self.builderNames
return builderNames
class BadJobfile(Exception):
pass
class JobdirService(MaildirService):
# NOTE: tightly coupled with Try_Jobdir, below. We used to track it as a "parent"
# via the MultiService API, but now we just track it as the member
# "self.scheduler"
name = 'JobdirService'
def __init__(self, scheduler, basedir=None):
self.scheduler = scheduler
super().__init__(basedir)
def messageReceived(self, filename):
with self.moveToCurDir(filename) as f:
rv = self.scheduler.handleJobFile(filename, f)
return rv
class Try_Jobdir(TryBase):
compare_attrs: ClassVar[Sequence[str]] = ('jobdir',)
def __init__(self, name, builderNames, jobdir, **kwargs):
super().__init__(name, builderNames, **kwargs)
self.jobdir = jobdir
self.watcher = JobdirService(scheduler=self)
# TryBase used to be a MultiService and managed the JobdirService via a parent/child
# relationship. We stub out the addService/removeService and just keep track of
# JobdirService as self.watcher. We'll refactor these things later and remove
# the need for this.
def addService(self, child):
pass
def removeService(self, child):
pass
# activation handlers
@defer.inlineCallbacks
def activate(self):
yield super().activate()
if not self.enabled:
return
# set the watcher's basedir now that we have a master
jobdir = os.path.join(self.master.basedir, self.jobdir)
self.watcher.setBasedir(jobdir)
for subdir in "cur new tmp".split():
if not os.path.exists(os.path.join(jobdir, subdir)):
os.mkdir(os.path.join(jobdir, subdir))
# bridge the activate/deactivate to a startService/stopService on the
# child service
self.watcher.startService()
@defer.inlineCallbacks
def deactivate(self):
yield super().deactivate()
if not self.enabled:
return
# bridge the activate/deactivate to a startService/stopService on the
# child service
self.watcher.stopService()
def parseJob(self, f):
# jobfiles are serialized build requests. Each is a list of
# serialized netstrings, in the following order:
# format version number:
# "1" the original
# "2" introduces project and repository
# "3" introduces who
# "4" introduces comment
# "5" introduces properties and JSON serialization of values after
# version
# "6" sends patch_body as base64-encoded string in the patch_body_base64 attribute
# jobid: arbitrary string, used to find the buildSet later
# branch: branch name, "" for default-branch
# baserev: revision, "" for HEAD
# patch_level: usually "1"
# patch_body: patch to be applied for build (as string)
# patch_body_base64: patch to be applied for build (as base64-encoded bytes)
# repository
# project
# who: user requesting build
# comment: comment from user about diff and/or build
# builderNames: list of builder names
# properties: dict of build properties
p = netstrings.NetstringParser()
f.seek(0, 2)
if f.tell() > basic.NetstringReceiver.MAX_LENGTH:
raise BadJobfile(
"The patch size is greater that NetStringReceiver.MAX_LENGTH. "
"Please Set this higher in the master.cfg"
)
f.seek(0, 0)
try:
p.feed(f.read())
except basic.NetstringParseError as e:
raise BadJobfile("unable to parse netstrings") from e
if not p.strings:
raise BadJobfile("could not find any complete netstrings")
ver = bytes2unicode(p.strings.pop(0))
v1_keys = ['jobid', 'branch', 'baserev', 'patch_level', 'patch_body']
v2_keys = [*v1_keys, "repository", "project"]
v3_keys = [*v2_keys, "who"]
v4_keys = [*v3_keys, "comment"]
keys = [v1_keys, v2_keys, v3_keys, v4_keys]
# v5 introduces properties and uses JSON serialization
parsed_job = {}
def extract_netstrings(p, keys):
for i, key in enumerate(keys):
if key == 'patch_body':
parsed_job[key] = p.strings[i]
else:
parsed_job[key] = bytes2unicode(p.strings[i])
def postprocess_parsed_job():
# apply defaults and handle type casting
parsed_job['branch'] = parsed_job['branch'] or None
parsed_job['baserev'] = parsed_job['baserev'] or None
parsed_job['patch_level'] = int(parsed_job['patch_level'])
for key in 'repository project who comment'.split():
parsed_job[key] = parsed_job.get(key, '')
parsed_job['properties'] = parsed_job.get('properties', {})
if ver <= "4":
i = int(ver) - 1
extract_netstrings(p, keys[i])
parsed_job['builderNames'] = [bytes2unicode(s) for s in p.strings[len(keys[i]) :]]
postprocess_parsed_job()
elif ver == "5":
try:
data = bytes2unicode(p.strings[0])
parsed_job = json.loads(data)
parsed_job['patch_body'] = unicode2bytes(parsed_job['patch_body'])
except ValueError as e:
raise BadJobfile("unable to parse JSON") from e
postprocess_parsed_job()
elif ver == "6":
try:
data = bytes2unicode(p.strings[0])
parsed_job = json.loads(data)
parsed_job['patch_body'] = base64.b64decode(parsed_job['patch_body_base64'])
del parsed_job['patch_body_base64']
except ValueError as e:
raise BadJobfile("unable to parse JSON") from e
postprocess_parsed_job()
else:
raise BadJobfile(f"unknown version '{ver}'")
return parsed_job
def handleJobFile(self, filename, f):
try:
parsed_job = self.parseJob(f)
builderNames = parsed_job['builderNames']
except BadJobfile:
log.msg(f"{self} reports a bad jobfile in {filename}")
log.err()
return defer.succeed(None)
# Validate/fixup the builder names.
builderNames = self.filterBuilderList(builderNames)
if not builderNames:
log.msg("incoming Try job did not specify any allowed builder names")
return defer.succeed(None)
who = ""
if parsed_job['who']:
who = parsed_job['who']
comment = ""
if parsed_job['comment']:
comment = parsed_job['comment']
sourcestamp = {
"branch": parsed_job['branch'],
"codebase": '',
"revision": parsed_job['baserev'],
"patch_body": parsed_job['patch_body'],
"patch_level": parsed_job['patch_level'],
"patch_author": who,
"patch_comment": comment,
# TODO: can't set this remotely - #1769
"patch_subdir": '',
"project": parsed_job['project'],
"repository": parsed_job['repository'],
}
reason = "'try' job"
if parsed_job['who']:
reason += f" by user {bytes2unicode(parsed_job['who'])}"
properties = parsed_job['properties']
requested_props = Properties()
requested_props.update(properties, "try build")
return self.addBuildsetForSourceStamps(
sourcestamps=[sourcestamp],
reason=reason,
external_idstring=bytes2unicode(parsed_job['jobid']),
builderNames=builderNames,
priority=self.priority,
properties=requested_props,
)
class RemoteBuildSetStatus(pb.Referenceable):
def __init__(self, master, bsid, brids):
self.master = master
self.bsid = bsid
self.brids = brids
@defer.inlineCallbacks
def remote_getBuildRequests(self):
brids = {}
for builderid, brid in self.brids.items():
builderDict = yield self.master.data.get(('builders', builderid))
brids[builderDict['name']] = brid
return [(n, RemoteBuildRequest(self.master, n, brid)) for n, brid in brids.items()]
class RemoteBuildRequest(pb.Referenceable):
def __init__(self, master, builderName, brid):
self.master = master
self.builderName = builderName
self.brid = brid
self.consumer = None
@defer.inlineCallbacks
def remote_subscribe(self, subscriber):
brdict = yield self.master.data.get(('buildrequests', self.brid))
if not brdict:
return
builderId = brdict['builderid']
# make sure we aren't double-reporting any builds
reportedBuilds = set([])
# subscribe to any new builds..
def gotBuild(key, msg):
if msg['buildrequestid'] != self.brid or key[-1] != 'new':
return None
if msg['buildid'] in reportedBuilds:
return None
reportedBuilds.add(msg['buildid'])
return subscriber.callRemote(
'newbuild', RemoteBuild(self.master, msg, self.builderName), self.builderName
)
self.consumer = yield self.master.mq.startConsuming(
gotBuild, ('builders', str(builderId), 'builds', None, None)
)
subscriber.notifyOnDisconnect(lambda _: self.remote_unsubscribe(subscriber))
# and get any existing builds
builds = yield self.master.data.get(('buildrequests', self.brid, 'builds'))
for build in builds:
if build['buildid'] in reportedBuilds:
continue
reportedBuilds.add(build['buildid'])
yield subscriber.callRemote(
'newbuild', RemoteBuild(self.master, build, self.builderName), self.builderName
)
def remote_unsubscribe(self, subscriber):
if self.consumer:
self.consumer.stopConsuming()
self.consumer = None
class RemoteBuild(pb.Referenceable):
def __init__(self, master, builddict, builderName):
self.master = master
self.builddict = builddict
self.builderName = builderName
self.consumer = None
@defer.inlineCallbacks
def remote_subscribe(self, subscriber, interval):
# subscribe to any new steps..
def stepChanged(key, msg):
if key[-1] == 'started':
return subscriber.callRemote(
'stepStarted', self.builderName, self, msg['name'], None
)
elif key[-1] == 'finished':
return subscriber.callRemote(
'stepFinished', self.builderName, self, msg['name'], None, msg['results']
)
return None
self.consumer = yield self.master.mq.startConsuming(
stepChanged, ('builds', str(self.builddict['buildid']), 'steps', None, None)
)
subscriber.notifyOnDisconnect(lambda _: self.remote_unsubscribe(subscriber))
def remote_unsubscribe(self, subscriber):
if self.consumer:
self.consumer.stopConsuming()
self.consumer = None
@defer.inlineCallbacks
def remote_waitUntilFinished(self):
d = defer.Deferred()
def buildEvent(key, msg):
if key[-1] == 'finished':
d.callback(None)
buildid = self.builddict['buildid']
consumer = yield self.master.mq.startConsuming(buildEvent, ('builds', str(buildid), None))
builddict = yield self.master.data.get(('builds', buildid))
# build might have finished before we called startConsuming
if not builddict.get('complete', False):
yield d # wait for event
consumer.stopConsuming()
return self # callers expect result=self
@defer.inlineCallbacks
def remote_getResults(self):
buildid = self.builddict['buildid']
builddict = yield self.master.data.get(('builds', buildid))
return builddict['results']
@defer.inlineCallbacks
def remote_getText(self):
buildid = self.builddict['buildid']
builddict = yield self.master.data.get(('builds', buildid))
return [builddict['state_string']]
class Try_Userpass_Perspective(pbutil.NewCredPerspective):
def __init__(self, scheduler, username):
self.scheduler = scheduler
self.username = username
@defer.inlineCallbacks
def perspective_try(
self,
branch,
revision,
patch,
repository,
project,
builderNames,
who="",
comment="",
properties=None,
):
log.msg(f"user {self.username} requesting build on builders {builderNames}")
if properties is None:
properties = {}
# build the intersection of the request and our configured list
builderNames = self.scheduler.filterBuilderList(builderNames)
if not builderNames:
return None
branch = bytes2unicode(branch)
revision = bytes2unicode(revision)
patch_level = patch[0]
patch_body = unicode2bytes(patch[1])
repository = bytes2unicode(repository)
project = bytes2unicode(project)
who = bytes2unicode(who)
comment = bytes2unicode(comment)
reason = "'try' job"
if who:
reason += f" by user {bytes2unicode(who)}"
if comment:
reason += f" ({bytes2unicode(comment)})"
sourcestamp = {
"branch": branch,
"revision": revision,
"repository": repository,
"project": project,
"patch_level": patch_level,
"patch_body": patch_body,
"patch_subdir": '',
"patch_author": who or '',
"patch_comment": comment or '',
"codebase": '',
} # note: no way to specify patch subdir - #1769
requested_props = Properties()
requested_props.update(properties, "try build")
(bsid, brids) = yield self.scheduler.addBuildsetForSourceStamps(
sourcestamps=[sourcestamp],
reason=reason,
properties=requested_props,
builderNames=builderNames,
)
# return a remotely-usable BuildSetStatus object
bss = RemoteBuildSetStatus(self.scheduler.master, bsid, brids)
return bss
def perspective_getAvailableBuilderNames(self):
# Return a list of builder names that are configured
# for the try service
# This is mostly intended for integrating try services
# into other applications
return self.scheduler.listBuilderNames()
class Try_Userpass(TryBase):
compare_attrs: ClassVar[Sequence[str]] = (
'name',
'builderNames',
'port',
'userpass',
'properties',
)
def __init__(self, name, builderNames, port, userpass, **kwargs):
super().__init__(name, builderNames, **kwargs)
self.port = port
self.userpass = userpass
self.registrations = []
@defer.inlineCallbacks
def activate(self):
yield super().activate()
if not self.enabled:
return
# register each user/passwd with the pbmanager
def factory(mind, username):
return Try_Userpass_Perspective(self, username)
for user, passwd in self.userpass:
reg = yield self.master.pbmanager.register(self.port, user, passwd, factory)
self.registrations.append(reg)
@defer.inlineCallbacks
def deactivate(self):
yield super().deactivate()
if not self.enabled:
return
yield defer.gatherResults([reg.unregister() for reg in self.registrations])
| 18,206 | Python | .py | 432 | 32.541667 | 98 | 0.620267 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
5,003 | connector.py | buildbot_buildbot/master/buildbot/wamp/connector.py | # This file is part of . 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 Team Members
from __future__ import annotations
import txaio
from autobahn.twisted.wamp import ApplicationSession
from autobahn.twisted.wamp import Service
from autobahn.wamp.exception import TransportLost
from twisted.internet import defer
from twisted.python import failure
from twisted.python import log
from buildbot.util import bytes2unicode
from buildbot.util import service
class MasterService(ApplicationSession, service.AsyncMultiService):
"""
concatenation of all the wamp services of buildbot
"""
def __init__(self, config):
# Cannot use super() here.
# We must explicitly call both parent constructors.
ApplicationSession.__init__(self, config)
service.AsyncMultiService.__init__(self)
self.leaving = False
self.setServiceParent(config.extra['parent'])
@defer.inlineCallbacks
def onJoin(self, details):
log.msg("Wamp connection succeed!")
for handler in [self, *self.services]:
yield self.register(handler)
yield self.subscribe(handler)
yield self.publish(f"org.buildbot.{self.master.masterid}.connected")
self.parent.service = self
self.parent.serviceDeferred.callback(self)
@defer.inlineCallbacks
def onLeave(self, details):
if self.leaving:
return
# XXX We don't handle crossbar reboot, or any other disconnection well.
# this is a tricky problem, as we would have to reconnect with exponential backoff
# re-subscribe to subscriptions, queue messages until reconnection.
# This is quite complicated, and I believe much better handled in autobahn
# It is possible that such failure is practically non-existent
# so for now, we just crash the master
log.msg("Guru meditation! We have been disconnected from wamp server")
log.msg("We don't know how to recover this without restarting the whole system")
log.msg(str(details))
yield self.master.stopService()
def onUserError(self, e, msg):
log.err(e, msg)
def make(config):
if config:
return MasterService(config)
# if no config given, return a description of this WAMPlet ..
return {
'label': 'Buildbot master wamplet',
'description': 'This contains all the wamp methods provided by a buildbot master',
}
class WampConnector(service.ReconfigurableServiceMixin, service.AsyncMultiService):
serviceClass = Service
name: str | None = "wamp" # type: ignore[assignment]
def __init__(self):
super().__init__()
self.app = None
self.router_url = None
self.realm = None
self.wamp_debug_level = None
self.serviceDeferred = defer.Deferred()
self.service = None
def getService(self):
if self.service is not None:
return defer.succeed(self.service)
d = defer.Deferred()
@self.serviceDeferred.addCallback
def gotService(service):
d.callback(service)
return service
return d
def stopService(self):
if self.service is not None:
self.service.leaving = True
super().stopService()
@defer.inlineCallbacks
def publish(self, topic, data, options=None):
service = yield self.getService()
try:
ret = yield service.publish(topic, data, options=options)
except TransportLost:
log.err(failure.Failure(), "while publishing event " + topic)
return None
return ret
@defer.inlineCallbacks
def subscribe(self, callback, topic=None, options=None):
service = yield self.getService()
ret = yield service.subscribe(callback, topic, options)
return ret
@defer.inlineCallbacks
def reconfigServiceWithBuildbotConfig(self, new_config):
if new_config.mq.get('type', 'simple') != "wamp":
if self.app is not None:
raise ValueError("Cannot use different wamp settings when reconfiguring")
return
wamp = new_config.mq
log.msg("Starting wamp with config: %r", wamp)
router_url = wamp.get('router_url', None)
realm = bytes2unicode(wamp.get('realm', 'buildbot'))
wamp_debug_level = wamp.get('wamp_debug_level', 'error')
# MQ router can be reconfigured only once. Changes to configuration are not supported.
# We can't switch realm nor the URL as that would leave transactions in inconsistent state.
# Implementing reconfiguration just for wamp_debug_level does not seem like a good
# investment.
if self.app is not None:
if (
self.router_url != router_url
or self.realm != realm
or self.wamp_debug_level != wamp_debug_level
):
raise ValueError("Cannot use different wamp settings when reconfiguring")
return
if router_url is None:
return
self.router_url = router_url
self.realm = realm
self.wamp_debug_level = wamp_debug_level
self.app = self.serviceClass(
url=self.router_url,
extra={"master": self.master, "parent": self},
realm=realm,
make=make,
)
txaio.set_global_log_level(wamp_debug_level)
yield self.app.setServiceParent(self)
yield super().reconfigServiceWithBuildbotConfig(new_config)
| 6,163 | Python | .py | 143 | 35.251748 | 99 | 0.673452 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
5,004 | conf.py | buildbot_buildbot/master/docs/conf.py | #
# Buildbot documentation build configuration file, created by
# sphinx-quickstart on Tue Aug 10 15:13:31 2010.
#
# This file is exec()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import importlib.metadata
import os
import sys
import textwrap
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
sys.path.insert(1, os.path.dirname(os.path.abspath(__file__)))
try:
from buildbot.reporters.telegram import TelegramContact
from buildbot.util.raml import RamlSpec
except ImportError:
sys.path.insert(2, os.path.join(os.path.dirname(os.path.abspath(__file__)), os.pardir))
from buildbot.reporters.telegram import TelegramContact
from buildbot.util.raml import RamlSpec
# -- General configuration -----------------------------------------------
try:
importlib.metadata.distribution('docutils')
except importlib.metadata.PackageNotFoundError as e:
raise RuntimeError(
"docutils is not installed. "
"Please install documentation dependencies with `pip "
"install buildbot[docs]`"
) from e
# If your documentation needs a minimal Sphinx version, state it here.
needs_sphinx = '4.0'
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.todo',
'sphinx.ext.extlinks',
'bbdocs.ext',
'bbdocs.api_index',
'sphinx_jinja',
'sphinx_rtd_theme',
]
todo_include_todos = True
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
# source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = 'Buildbot'
copyright = 'Buildbot Team Members'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
if 'VERSION' in os.environ:
version = os.environ['VERSION']
else:
gl = {'__file__': '../buildbot/__init__.py'}
with open('../buildbot/__init__.py') as f:
exec(f.read(), gl) # pylint: disable=exec-used
version = gl['version']
# The full version, including alpha/beta/rc tags.
release = version
rst_prolog = ""
# add a loud note for anyone looking at the latest docs
if release == 'latest':
rst_prolog += textwrap.dedent("""\
.. caution:: This page documents the latest, unreleased version of
Buildbot. For documentation for released versions, see
http://docs.buildbot.net/current/.
""")
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
# language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
# today = ''
# Else, today_fmt is used as the format for a strftime call.
# today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build', 'release-notes/*.rst']
# The reST default role (used for this markup: `text`) to use for all documents.
# default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
add_function_parentheses = False
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
# add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
# show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'trac'
# A list of ignored prefixes for module index sorting.
# modindex_common_prefix = []
intersphinx_mapping = {
'python': ('https://python.readthedocs.io/en/latest/', None),
'sqlalchemy': ('https://sqlalchemy.readthedocs.io/en/latest/', None),
}
extlinks = {
'pull': ('https://github.com/buildbot/buildbot/pull/%s', 'pull request %s'),
'issue': ('https://github.com/buildbot/buildbot/issues/%s', 'issue #%s'),
# deprecated. Use issue instead, and point to Github
'bug': ('http://trac.buildbot.net/ticket/%s', 'bug #%s'),
# Renders as link with whole url, e.g.
# :src-link:`master`
# renders as
# "https://github.com/buildbot/buildbot/blob/master/master".
# Explicit title can be used for customizing how link looks like:
# :src-link:`master's directory <master>`
'src-link': ('https://github.com/buildbot/buildbot/tree/master/%s', None),
# "pretty" reference that looks like relative path in Buildbot source tree
# by default.
'src': ('https://github.com/buildbot/buildbot/tree/master/%s', '%s'),
}
# Sphinx' link checker.
linkcheck_ignore = [
# Local URLs:
r'^http://localhost.*',
# Available only to logged-in users:
r'^https://github\.com/settings/applications$',
# Sites which uses SSL that Python 2 can't handle:
r'^https://opensource\.org/licenses/gpl-2.0\.php$',
r'^https://docs\.docker\.com/engine/installation/$',
# Looks like server doesn't like user agent:
r'^https://www\.microsoft\.com/en-us/download/details\.aspx\?id=17657$',
# Example domain.
r'^https?://(.+\.)?example\.org',
# Anchor check fails on rendered user files on GitHub, since GitHub uses
# custom prefix for anchors in user generated content.
r'https://github\.com/buildbot/guanlecoja-ui/tree/master#changelog',
r'http://mesosphere.github.io/marathon/docs/rest-api.html#post-v2-apps',
]
linkcheck_timeout = 10
linkcheck_retries = 3
linkcheck_workers = 20
# -- Options for HTML output ---------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = 'sphinx_rtd_theme'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
# html_theme_options = {'stickysidebar': 'true'}
# Add any paths that contain custom themes here, relative to this directory.
html_theme_path = ['_themes']
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
# html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
# html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
html_logo = os.path.join('_images', 'full_logo.png')
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large or a png.
html_favicon = os.path.join('_static', 'icon.png')
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# We customize the rtd theme slightly
html_css_files = ['buildbot_rtd.css']
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
# html_last_updated_fmt = '%b %d, %Y'
# Custom sidebar templates, maps document names to template names.
html_sidebars = {'**': ['searchbox.html', 'localtoc.html', 'relations.html', 'sourcelink.html']}
# Additional templates that should be rendered to pages, maps page names to
# template names.
# html_additional_pages = {}
# If false, no module index is generated.
# html_domain_indices = True
html_use_index = True
html_use_modindex = False
# If true, the index is split into individual pages for each letter.
# html_split_index = False
# If true, links to the reST sources are added to the pages.
# html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
# html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
# html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
# html_use_opensearch = ''
# If nonempty, this is the file name suffix for HTML files (e.g. ".xhtml").
# html_file_suffix = ''
# Output file base name for HTML help builder.
htmlhelp_basename = 'Buildbotdoc'
# -- Options for LaTeX output --------------------------------------------
latex_elements = {}
# The paper size ('letter' or 'a4').
latex_elements['papersize'] = 'a4'
# The font size ('10pt', '11pt' or '12pt').
# latex_font_size = '11pt'
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
('index', 'Buildbot.tex', 'Buildbot Documentation', 'Brian Warner', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
latex_logo = os.path.join('_images', 'header-text-transparent.png')
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
# latex_use_parts = False
# If true, show page references after internal links.
# latex_show_pagerefs = False
# Three possible values for this option (see sphinx config manual) are:
# 1. 'no' - do not display URLs (default)
# 2. 'footnote' - display URLs in footnotes
# 3. 'inline' - display URLs inline in parentheses
latex_show_urls = 'inline'
# Additional stuff for the LaTeX preamble.
# latex_preamble = ''
# Documents to append as an appendix to all manuals.
# latex_appendices = []
# If false, no module index is generated.
# latex_domain_indices = True
# -- Options for manual page output --------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [('index', 'buildbot', 'Buildbot Documentation', ['Brian Warner'], 1)]
jinja_contexts = {
"data_api": {'raml': RamlSpec()},
"telegram": {'commands': TelegramContact.describe_commands()},
}
raml_spec = RamlSpec()
for raml_typename, raml_type in sorted(raml_spec.types.items()):
jinja_contexts['data_api_' + raml_typename] = {
'raml': raml_spec,
'name': raml_typename,
'type': raml_type,
}
doc_path = f'developer/raml/{raml_typename}.rst'
if not os.path.exists(doc_path):
raise RuntimeError(f'File {doc_path} for RAML type {raml_typename} does not exist')
# Spell checker.
try:
import enchant # noqa: F401
except ImportError as ex:
print("enchant module import failed:\n" f"{ex}\n" "Spell checking disabled.", file=sys.stderr)
else:
extensions.append('sphinxcontrib.spelling')
spelling_show_suggestions = True
| 11,445 | Python | .py | 260 | 41.453846 | 98 | 0.713425 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
5,005 | remove_pycs.rst | buildbot_buildbot/master/docs/manual/configuration/steps/remove_pycs.rst | .. bb:step:: RemovePYCs
.. _Step-RemovePYCs:
RemovePYCs
++++++++++
.. py:class:: buildbot.steps.python_twisted.RemovePYCs
This is a simple built-in step that will remove ``.pyc`` files from the workdir.
This is useful in builds that update their source (and thus do not automatically delete ``.pyc`` files) but where some part of the build process is dynamically searching for Python modules.
Notably, trial has a bad habit of finding old test modules.
.. code-block:: python
from buildbot.plugins import steps
f.addStep(steps.RemovePYCs())
| 556 | Python | .py | 11 | 48.181818 | 189 | 0.760223 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
5,006 | robocopy.rst | buildbot_buildbot/master/docs/manual/configuration/steps/robocopy.rst | .. bb:step:: Robocopy
.. _Step-Robocopy:
Robocopy
++++++++
.. py:class:: buildbot.steps.mswin.Robocopy
This step runs ``robocopy`` on Windows.
`Robocopy <https://technet.microsoft.com/en-us/library/cc733145.aspx>`_ is available in versions of Windows starting with Windows Vista and Windows Server 2008.
For previous versions of Windows, it's available as part of the `Windows Server 2003 Resource Kit Tools <https://www.microsoft.com/en-us/download/details.aspx?id=17657>`_.
.. code-block:: python
from buildbot.plugins import steps, util
f.addStep(
steps.Robocopy(
name='deploy_binaries',
description='Deploying binaries...',
descriptionDone='Deployed binaries.',
source=util.Interpolate('Build\\Bin\\%(prop:configuration)s'),
destination=util.Interpolate('%(prop:deploy_dir)\\Bin\\%(prop:configuration)s'),
mirror=True
)
)
Available constructor arguments are:
``source``
The path to the source directory (mandatory).
``destination``
The path to the destination directory (mandatory).
``files``
An array of file names or patterns to copy.
``recursive``
Copy files and directories recursively (``/E`` parameter).
``mirror``
Mirror the source directory in the destination directory, including removing files that don't exist anymore (``/MIR`` parameter).
``move``
Delete the source directory after the copy is complete (``/MOVE`` parameter).
``exclude_files``
An array of file names or patterns to exclude from the copy (``/XF`` parameter).
``exclude_dirs``
An array of directory names or patterns to exclude from the copy (``/XD`` parameter).
``custom_opts``
An array of custom parameters to pass directly to the ``robocopy`` command.
``verbose``
Whether to output verbose information (``/V /TS /FP`` parameters).
Note that parameters ``/TEE /NP`` will always be appended to the command to signify, respectively, to output logging to the console, use Unicode logging, and not print any percentage progress information for each file.
| 2,094 | Python | .py | 42 | 45.047619 | 218 | 0.717028 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
5,007 | build_epydoc.rst | buildbot_buildbot/master/docs/manual/configuration/steps/build_epydoc.rst | .. bb:step:: BuildEPYDoc
.. _Step-BuildEPYDoc:
BuildEPYDoc
+++++++++++
.. py:class:: buildbot.steps.python.BuildEPYDoc
`epydoc <http://epydoc.sourceforge.net/>`_ is a tool for generating
API documentation for Python modules from their docstrings.
It reads all the :file:`.py` files from your source tree, processes the docstrings therein, and creates a large tree of :file:`.html` files (or a single :file:`.pdf` file).
The :bb:step:`BuildEPYDoc` step will run :command:`epydoc` to produce this API documentation, and will count the errors and warnings from its output.
You must supply the command line to be used.
The default is ``make epydocs``, which assumes that your project has a :file:`Makefile` with an `epydocs` target.
You might wish to use something like :samp:`epydoc -o apiref source/{PKGNAME}` instead.
You might also want to add option `--pdf` to generate a PDF file instead of a large tree of HTML files.
The API docs are generated in-place in the build tree (under the workdir, in the subdirectory controlled by the option `-o` argument).
To make them useful, you will probably have to copy them to somewhere they can be read.
For example if you have server with configured nginx web server, you can place generated docs to it's public folder with command like ``rsync -ad apiref/ dev.example.com:~/usr/share/nginx/www/current-apiref/``.
You might instead want to bundle them into a tarball and publish it in the same place where the generated install tarball is placed.
.. code-block:: python
from buildbot.plugins import steps
f.addStep(steps.BuildEPYDoc(command=["epydoc", "-o", "apiref", "source/mypkg"]))
| 1,645 | Python | .py | 20 | 80.35 | 210 | 0.765325 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
5,008 | ext.py | buildbot_buildbot/master/docs/bbdocs/ext.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 docutils import nodes
from docutils.parsers.rst import Directive
from sphinx import addnodes
from sphinx.domains import Domain
from sphinx.domains import Index
from sphinx.domains import ObjType
from sphinx.roles import XRefRole
from sphinx.util import logging
from sphinx.util import ws_re
from sphinx.util.docfields import DocFieldTransformer
from sphinx.util.docfields import Field
from sphinx.util.docfields import TypedField
from sphinx.util.nodes import make_refnode
logger = logging.getLogger(__name__)
class BBRefTargetDirective(Directive):
"""
A directive that can be a target for references. Attributes:
@cvar ref_type: same as directive name
@cvar indextemplates: templates for main index entries, if any
"""
has_content = False
name_annotation = None
required_arguments = 1
optional_arguments = 0
final_argument_whitespace = True
option_spec = {}
domain = 'bb'
doc_field_types = []
def get_field_type_map(self):
# This is the same as DocFieldTransformer.preprocess_fieldtype which got removed in
# Sphinx 4.0
typemap = {}
for fieldtype in self.doc_field_types:
for name in fieldtype.names:
typemap[name] = fieldtype, False
if fieldtype.is_typed:
for name in fieldtype.typenames:
typemap[name] = fieldtype, True
return typemap
def run(self):
self.env = env = self.state.document.settings.env
# normalize whitespace in fullname like XRefRole does
fullname = ws_re.sub(' ', self.arguments[0].strip())
targetname = f'{self.ref_type}-{fullname}'
# keep the target; this may be used to generate a BBIndex later
targets = env.domaindata['bb']['targets'].setdefault(self.ref_type, {})
targets[fullname] = env.docname, targetname
# make up the descriptor: a target and potentially an index descriptor
node = nodes.target('', '', ids=[targetname])
ret = [node]
# add the target to the document
self.state.document.note_explicit_target(node)
# append the index node if necessary
entries = []
for tpl in self.indextemplates:
colon = tpl.find(':')
if colon != -1:
indextype = tpl[:colon].strip()
indexentry = tpl[colon + 1 :].strip() % (fullname,)
else:
indextype = 'single'
indexentry = tpl % (fullname,)
entries.append((indextype, indexentry, targetname, targetname, None))
if entries:
inode = addnodes.index(entries=entries)
ret.insert(0, inode)
# if the node has content, set up a signature and parse the content
if self.has_content:
descnode = addnodes.desc()
descnode['domain'] = 'bb'
descnode['objtype'] = self.ref_type
descnode['noindex'] = True
signode = addnodes.desc_signature(fullname, '')
if self.name_annotation:
annotation = f"{self.name_annotation} "
signode += addnodes.desc_annotation(annotation, annotation)
signode += addnodes.desc_name(fullname, fullname)
descnode += signode
contentnode = addnodes.desc_content()
self.state.nested_parse(self.content, 0, contentnode)
DocFieldTransformer(self).transform_all(contentnode)
descnode += contentnode
ret.append(descnode)
return ret
@classmethod
def resolve_ref(cls, domain, env, fromdocname, builder, typ, target, node, contnode):
"""
Resolve a reference to a directive of this class
"""
targets = domain.data['targets'].get(cls.ref_type, {})
try:
todocname, targetname = targets[target]
except KeyError:
logger.warning(
f"{fromdocname}:{node.line}: Missing BB reference: bb:{cls.ref_type}:{target}"
)
return None
return make_refnode(builder, fromdocname, todocname, targetname, contnode, target)
def make_ref_target_directive(ref_type, indextemplates=None, **kwargs):
"""
Create and return a L{BBRefTargetDirective} subclass.
"""
class_vars = dict(ref_type=ref_type, indextemplates=indextemplates)
class_vars.update(kwargs)
return type(f"BB{ref_type.capitalize()}RefTargetDirective", (BBRefTargetDirective,), class_vars)
class BBIndex(Index):
"""
A Buildbot-specific index.
@cvar name: same name as the directive and xref role
@cvar localname: name of the index document
"""
def generate(self, docnames=None):
content = {}
idx_targets = self.domain.data['targets'].get(self.name, {})
for name, (docname, targetname) in idx_targets.items():
letter = name[0].upper()
content.setdefault(letter, []).append((name, 0, docname, targetname, '', '', ''))
content = [
(l, sorted(content[l], key=lambda tup: tup[0].lower())) for l in sorted(content.keys())
]
return (content, False)
@classmethod
def resolve_ref(cls, domain, env, fromdocname, builder, typ, target, node, contnode):
"""
Resolve a reference to an index to the document containing the index,
using the index's C{localname} as the content of the link.
"""
# indexes appear to be automatically generated at doc DOMAIN-NAME
todocname = f"bb-{target}"
node = nodes.reference('', '', internal=True)
node['refuri'] = builder.get_relative_uri(fromdocname, todocname)
node['reftitle'] = cls.localname
node.append(nodes.emphasis(cls.localname, cls.localname))
return node
def make_index(name, localname):
"""
Create and return a L{BBIndex} subclass, for use in the domain's C{indices}
"""
return type(f"BB{name.capitalize()}Index", (BBIndex,), dict(name=name, localname=localname))
class BBDomain(Domain):
name = 'bb'
label = 'Buildbot'
object_types = {
'cfg': ObjType('cfg', 'cfg'),
'sched': ObjType('sched', 'sched'),
'chsrc': ObjType('chsrc', 'chsrc'),
'step': ObjType('step', 'step'),
'reportgen': ObjType('reportgen', 'reportgen'),
'reporter': ObjType('reporter', 'reporter'),
'configurator': ObjType('configurator', 'configurator'),
'worker': ObjType('worker', 'worker'),
'cmdline': ObjType('cmdline', 'cmdline'),
'msg': ObjType('msg', 'msg'),
'event': ObjType('event', 'event'),
'rtype': ObjType('rtype', 'rtype'),
'rpath': ObjType('rpath', 'rpath'),
'raction': ObjType('raction', 'raction'),
}
directives = {
'cfg': make_ref_target_directive(
'cfg',
indextemplates=[
'single: Buildmaster Config; %s',
'single: %s (Buildmaster Config)',
],
),
'sched': make_ref_target_directive(
'sched',
indextemplates=[
'single: Schedulers; %s',
'single: %s Scheduler',
],
),
'chsrc': make_ref_target_directive(
'chsrc',
indextemplates=[
'single: Change Sources; %s',
'single: %s Change Source',
],
),
'step': make_ref_target_directive(
'step',
indextemplates=[
'single: Build Steps; %s',
'single: %s Build Step',
],
),
'reportgen': make_ref_target_directive(
'reportgen',
indextemplates=[
'single: Report Generators; %s',
'single: %s Report Generator',
],
),
'reporter': make_ref_target_directive(
'reporter',
indextemplates=[
'single: Reporter Targets; %s',
'single: %s Reporter Target',
],
),
'configurator': make_ref_target_directive(
'configurator',
indextemplates=[
'single: Configurators; %s',
'single: %s Configurators',
],
),
'worker': make_ref_target_directive(
'worker',
indextemplates=[
'single: Build Workers; %s',
'single: %s Build Worker',
],
),
'cmdline': make_ref_target_directive(
'cmdline',
indextemplates=[
'single: Command Line Subcommands; %s',
'single: %s Command Line Subcommand',
],
),
'msg': make_ref_target_directive(
'msg',
indextemplates=[
'single: Message Schema; %s',
],
has_content=True,
name_annotation='routing key:',
doc_field_types=[
TypedField(
'key', label='Keys', names=('key',), typenames=('type',), can_collapse=True
),
Field('var', label='Variable', names=('var',)),
],
),
'event': make_ref_target_directive(
'event',
indextemplates=[
'single: event; %s',
],
has_content=True,
name_annotation='event:',
doc_field_types=[],
),
'rtype': make_ref_target_directive(
'rtype',
indextemplates=[
'single: Resource Type; %s',
],
has_content=True,
name_annotation='resource type:',
doc_field_types=[
TypedField(
'attr',
label='Attributes',
names=('attr',),
typenames=('type',),
can_collapse=True,
),
],
),
'rpath': make_ref_target_directive(
'rpath',
indextemplates=[
'single: Resource Path; %s',
],
name_annotation='path:',
has_content=True,
doc_field_types=[
TypedField(
'pathkey',
label='Path Keys',
names=('pathkey',),
typenames=('type',),
can_collapse=True,
),
],
),
'raction': make_ref_target_directive(
'raction',
indextemplates=[
'single: Resource Action; %s',
],
name_annotation='POST with method:',
has_content=True,
doc_field_types=[
TypedField(
'body',
label='Body keys',
names=('body',),
typenames=('type',),
can_collapse=True,
),
],
),
}
roles = {
'cfg': XRefRole(),
'sched': XRefRole(),
'chsrc': XRefRole(),
'step': XRefRole(),
'reportgen': XRefRole(),
'reporter': XRefRole(),
'configurator': XRefRole(),
'worker': XRefRole(),
'cmdline': XRefRole(),
'msg': XRefRole(),
'event': XRefRole(),
'rtype': XRefRole(),
'rpath': XRefRole(),
'index': XRefRole(),
}
initial_data = {
'targets': {}, # type -> target -> (docname, targetname)
}
indices = [
make_index("cfg", "Buildmaster Configuration Index"),
make_index("sched", "Scheduler Index"),
make_index("chsrc", "Change Source Index"),
make_index("step", "Build Step Index"),
make_index("reportgen", "Reporter Generator Index"),
make_index("reporter", "Reporter Target Index"),
make_index("configurator", "Configurator Target Index"),
make_index("worker", "Build Worker Index"),
make_index("cmdline", "Command Line Index"),
make_index("msg", "MQ Routing Key Index"),
make_index("event", "Data API Event Index"),
make_index("rtype", "REST/Data API Resource Type Index"),
make_index("rpath", "REST/Data API Path Index"),
make_index("raction", "REST/Data API Actions Index"),
]
def resolve_xref(self, env, fromdocname, builder, typ, target, node, contnode):
if typ == 'index':
for idx in self.indices:
if idx.name == target:
break
else:
raise KeyError(f"no index named '{target}'")
return idx.resolve_ref(self, env, fromdocname, builder, typ, target, node, contnode)
elif typ in self.directives:
dir = self.directives[typ]
return dir.resolve_ref(self, env, fromdocname, builder, typ, target, node, contnode)
def merge_domaindata(self, docnames, otherdata):
for typ in self.object_types:
if typ not in otherdata['targets']:
continue
if typ not in self.data['targets']:
self.data['targets'][typ] = otherdata['targets'][typ]
continue
self_data = self.data['targets'][typ]
other_data = otherdata['targets'][typ]
for target_name, target_data in other_data.items():
if target_name in self_data:
# for some reason we end up with multiple references to the same things in
# multiple domains. If both instances point to the same location, ignore it,
# otherwise issue a warning.
if other_data[target_name] == self_data[target_name]:
continue
self_path = f'{self.env.doc2path(self_data[target_name][0])}#{self_data[target_name][1]}'
other_path = f'{self.env.doc2path(other_data[target_name][0])}#{other_data[target_name][1]}'
logger.warning(
f'Duplicate index {typ} reference {target_name} in {self_path}, other instance in {other_path}'
)
else:
self_data[target_name] = target_data
def setup(app):
app.add_domain(BBDomain)
return {'parallel_read_safe': True, 'parallel_write_safe': True}
| 15,154 | Python | .py | 383 | 28.720627 | 119 | 0.56031 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
5,009 | api_index.py | buildbot_buildbot/master/docs/bbdocs/api_index.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 sphinx.domains import Index
from sphinx.domains.std import StandardDomain
class PythonAPIIndex(Index):
objecttype = 'class'
name = 'apiindex'
localname = 'Public API Index'
shortname = 'classes'
def generate(self, docnames=None):
unsorted_objects = [
(refname, entry.docname, entry.objtype)
for (refname, entry) in self.domain.data['objects'].items()
if entry.objtype in ['class', 'function']
]
objects = sorted(unsorted_objects, key=lambda x: x[0].lower())
entries = []
for refname, docname, objtype in objects:
if docnames and docname not in docnames:
continue
extra_info = objtype
display_name = refname
if objtype == 'function':
display_name += '()'
entries.append([display_name, 0, docname, refname, extra_info, '', ''])
return [('', entries)], False
def setup(app):
app.add_index_to_domain('py', PythonAPIIndex)
StandardDomain.initial_data['labels']['apiindex'] = ('py-apiindex', '', 'Public API Index')
StandardDomain.initial_data['anonlabels']['apiindex'] = ('py-apiindex', '')
return {'parallel_read_safe': True, 'parallel_write_safe': True}
| 1,983 | Python | .py | 43 | 39.953488 | 95 | 0.679275 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
5,010 | post_build_request.py | buildbot_buildbot/master/contrib/post_build_request.py | #!/usr/bin/env python
# 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 OpenGamma Inc. and the OpenGamma group of companies
import getpass
import optparse
import os
import textwrap
import urllib
import httplib
# Find a working json module. Code is from
# Paul Wise <[email protected]>:
# http://lists.debian.org/debian-python/2010/02/msg00016.html
try:
import json # python 2.6
assert json # silence pyflakes
except ImportError:
import simplejson as json # python 2.4 to 2.5
try:
_tmp = json.loads
except AttributeError:
import sys
import warnings
warnings.warn(
"Use simplejson, not the old json module.", category=DeprecationWarning, stacklevel=1
)
sys.modules.pop('json') # get rid of the bad json module
import simplejson as json
# Make a dictionary with options from command line
def buildURL(options):
urlDict = {}
if options.author:
author = options.author
else:
author = getpass.getuser()
urlDict['author'] = author
if options.files:
urlDict['files'] = json.dumps(options.files)
if options.comments:
urlDict['comments'] = options.comments
else:
# A comment is required by the buildbot DB
urlDict['comments'] = 'post_build_request submission'
if options.revision:
urlDict['revision'] = options.revision
if options.when:
urlDict['when'] = options.when
if options.branch:
urlDict['branch'] = options.branch
if options.category:
urlDict['category'] = options.category
if options.revlink:
urlDict['revlink'] = options.revlink
if options.properties:
urlDict['properties'] = json.dumps(options.properties)
if options.repository:
urlDict['repository'] = options.repository
if options.project:
urlDict['project'] = options.project
return urlDict
def propertyCB(option, opt, value, parser):
pdict = eval(value)
for key in pdict.keys():
parser.values.properties[key] = pdict[key]
__version__ = '0.1'
description = ""
usage = """%prog [options]
This script is used to submit a change to the buildbot master using the
/change_hook web interface. Options are url encoded and submitted
using a HTTP POST. The repository and project must be specified.
This can be used to force a build. For example, create a scheduler that
listens for changes on a category 'release':
releaseFilt = ChangeFilter(category="release")
s=Scheduler(name="Release", change_filter=releaseFilt,
treeStableTimer=10,
builderNames=["UB10.4 x86_64 Release"]))
c['schedulers'].append(s)
Then run this script with the options:
--repository <REPOSTORY> --project <PROJECT> --category release
"""
parser = optparse.OptionParser(
description=description, usage=usage, add_help_option=True, version=__version__
)
parser.add_option(
"-w",
"--who",
dest='author',
metavar="AUTHOR",
help=textwrap.dedent("""\
Who is submitting this request.
This becomes the Change.author attribute.
This defaults to the name of the user running this script
"""),
)
parser.add_option(
"-f",
"--file",
dest='files',
action="append",
metavar="FILE",
help=textwrap.dedent("""\
Add a file to the change request.
This is added to the Change.files attribute.
NOTE: Setting the file URL is not supported
"""),
)
parser.add_option(
"-c",
"--comments",
dest='comments',
metavar="COMMENTS",
help=textwrap.dedent("""\
Comments for the change. This becomes the Change.comments attribute
"""),
)
parser.add_option(
"-R",
"--revision",
dest='revision',
metavar="REVISION",
help=textwrap.dedent("""\
This is the revision of the change.
This becomes the Change.revision attribute.
"""),
)
parser.add_option(
"-W",
"--when",
dest='when',
metavar="WHEN",
help=textwrap.dedent("""\
This this the date of the change.
This becomes the Change.when attribute.
"""),
)
parser.add_option(
"-b",
"--branch",
dest='branch',
metavar="BRANCH",
help=textwrap.dedent("""\
This this the branch of the change.
This becomes the Change.branch attribute.
"""),
)
parser.add_option(
"-C",
"--category",
dest='category',
metavar="CAT",
help=textwrap.dedent("""\
Category for change. This becomes the Change.category attribute, which
can be used within the buildmaster to filter changes.
"""),
)
parser.add_option(
"--revlink",
dest='revlink',
metavar="REVLINK",
help=textwrap.dedent("""\
This this the revlink of the change.
This becomes the Change.revlink.
"""),
)
parser.add_option(
"-p",
"--property",
dest='properties',
action="callback",
callback=propertyCB,
type="string",
metavar="PROP",
help=textwrap.dedent("""\
This adds a single property. This can be specified multiple times.
The argument is a string representing python dictionary. For example,
{'foo' : [ 'bar', 'baz' ]}
This becomes the Change.properties attribute.
"""),
)
parser.add_option(
"-r",
"--repository",
dest='repository',
metavar="PATH",
help=textwrap.dedent("""\
Repository for use by buildbot workers to checkout code.
This becomes the Change.repository attribute.
Exmaple: :ext:myhost:/cvsroot
"""),
)
parser.add_option(
"-P",
"--project",
dest='project',
metavar="PROJ",
help=textwrap.dedent("""\
The project for the source. Often set to the CVS module being modified. This becomes
the Change.project attribute.
"""),
)
parser.add_option(
"-v",
"--verbose",
dest='verbosity',
action="count",
help=textwrap.dedent("""\
Print more detail. Shows the response status and reason received from the master. If
specified twice, it also shows the raw response.
"""),
)
parser.add_option(
"-H",
"--host",
dest='host',
metavar="HOST",
default='localhost:8010',
help=textwrap.dedent("""\
Host and optional port of buildbot. For example, bbhost:8010
Defaults to %default
"""),
)
parser.add_option(
"-u",
"--urlpath",
dest='urlpath',
metavar="URLPATH",
default='/change_hook/base',
help=textwrap.dedent("""\
Path portion of URL. Defaults to %default
"""),
)
parser.add_option(
"-t",
"--testing",
action="store_true",
dest="amTesting",
default=False,
help=textwrap.dedent("""\
Just print values and exit.
"""),
)
parser.set_defaults(properties={})
(options, args) = parser.parse_args()
if options.repository is None:
print("repository must be specified")
parser.print_usage()
os._exit(2)
if options.project is None:
print("project must be specified")
parser.print_usage()
os._exit(2)
urlDict = buildURL(options)
params = urllib.urlencode(urlDict)
headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain"}
if options.amTesting:
print(f"params: {params}")
print(f"host: {options.host}")
print(f"urlpath: {options.urlpath}")
else:
conn = httplib.HTTPConnection(options.host)
conn.request("POST", options.urlpath, params, headers)
response = conn.getresponse()
data = response.read()
exitCode = 0
if response.status != 202:
exitCode = 1
if options.verbosity >= 1:
print(response.status, response.reason)
if options.verbosity >= 2:
print(f"Raw response: {data}")
conn.close()
os._exit(exitCode)
| 8,688 | Python | .py | 284 | 25 | 96 | 0.651363 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
5,011 | svn_buildbot.py | buildbot_buildbot/master/contrib/svn_buildbot.py | #!/usr/bin/python
# this requires python >=2.3 for the 'sets' module.
# The sets.py from python-2.3 appears to work fine under python2.2 . To
# install this script on a host with only python2.2, copy
# /usr/lib/python2.3/sets.py from a newer python into somewhere on your
# PYTHONPATH, then edit the #! line above to invoke python2.2
# python2.1 is right out
# If you run this program as part of your SVN post-commit hooks, it will
# deliver Change notices to a buildmaster that is running a PBChangeSource
# instance.
# edit your svn-repository/hooks/post-commit file, and add lines that look
# like this:
import os
import re
import subprocess
import sys
import sets
from future.utils import text_type
from twisted.cred import credentials
from twisted.internet import defer
from twisted.internet import reactor
from twisted.python import usage
from twisted.spread import pb
'''
# set up PYTHONPATH to contain Twisted/buildbot perhaps, if not already
# installed site-wide
. ~/.environment
/path/to/svn_buildbot.py --repository "$REPOS" --revision "$REV" \
--bbserver localhost --bbport 9989 --username myuser --auth passwd
'''
# We have hackish "-d" handling here rather than in the Options
# subclass below because a common error will be to not have twisted in
# PYTHONPATH; we want to be able to print that error to the log if
# debug mode is on, so we set it up before the imports.
DEBUG = None
if '-d' in sys.argv:
i = sys.argv.index('-d')
DEBUG = sys.argv[i + 1]
del sys.argv[i]
del sys.argv[i]
if DEBUG:
f = open(DEBUG, 'a')
sys.stderr = f
sys.stdout = f
class Options(usage.Options):
optParameters = [
['repository', 'r', None, "The repository that was changed."],
['worker-repo', 'c', None, "In case the repository differs for the workers."],
['revision', 'v', None, "The revision that we want to examine (default: latest)"],
['bbserver', 's', 'localhost', "The hostname of the server that buildbot is running on"],
['bbport', 'p', 8007, "The port that buildbot is listening on"],
['username', 'u', 'change', "Username used in PB connection auth"],
['auth', 'a', 'changepw', "Password used in PB connection auth"],
[
'include',
'f',
None,
'''\
Search the list of changed files for this regular expression, and if there is
at least one match notify buildbot; otherwise buildbot will not do a build.
You may provide more than one -f argument to try multiple
patterns. If no filter is given, buildbot will always be notified.''',
],
['filter', 'f', None, "Same as --include. (Deprecated)"],
[
'exclude',
'F',
None,
'''\
The inverse of --filter. Changed files matching this expression will never
be considered for a build.
You may provide more than one -F argument to try multiple
patterns. Excludes override includes, that is, patterns that match both an
include and an exclude will be excluded.''',
],
['encoding', 'e', "utf8", "The encoding of the strings from subversion (default: utf8)"],
['project', 'P', None, "The project for the source."],
]
optFlags = [
['dryrun', 'n', "Do not actually send changes"],
]
def __init__(self):
usage.Options.__init__(self)
self._includes = []
self._excludes = []
self['includes'] = None
self['excludes'] = None
def opt_include(self, arg):
self._includes.append(f'.*{arg}.*')
opt_filter = opt_include
def opt_exclude(self, arg):
self._excludes.append(f'.*{arg}.*')
def postOptions(self):
if self['repository'] is None:
raise usage.error("You must pass --repository")
if self._includes:
self['includes'] = '({})'.format('|'.join(self._includes))
if self._excludes:
self['excludes'] = '({})'.format('|'.join(self._excludes))
def split_file_dummy(changed_file):
"""Split the repository-relative filename into a tuple of (branchname,
branch_relative_filename). If you have no branches, this should just
return (None, changed_file).
"""
return (None, changed_file)
# this version handles repository layouts that look like:
# trunk/files.. -> trunk
# branches/branch1/files.. -> branches/branch1
# branches/branch2/files.. -> branches/branch2
#
def split_file_branches(changed_file):
pieces = changed_file.split(os.sep)
if pieces[0] == 'branches':
return (os.path.join(*pieces[:2]), os.path.join(*pieces[2:]))
if pieces[0] == 'trunk':
return (pieces[0], os.path.join(*pieces[1:]))
# there are other sibilings of 'trunk' and 'branches'. Pretend they are
# all just funny-named branches, and let the Schedulers ignore them.
# return (pieces[0], os.path.join(*pieces[1:]))
raise RuntimeError(f"cannot determine branch for '{changed_file}'")
split_file = split_file_dummy
class ChangeSender:
def getChanges(self, opts):
"""Generate and stash a list of Change dictionaries, ready to be sent
to the buildmaster's PBChangeSource."""
# first we extract information about the files that were changed
repo = opts['repository']
worker_repo = opts['worker-repo'] or repo
print("Repo:", repo)
rev_arg = ''
if opts['revision']:
rev_arg = '-r {}'.format(opts['revision'])
changed = subprocess.check_output(f'svnlook changed {rev_arg} "{repo}"', shell=True)
changed = changed.decode(sys.stdout.encoding)
changed = changed.split('\n')
# the first 4 columns can contain status information
changed = [x[4:] for x in changed]
message = subprocess.check_output(f'svnlook log {rev_arg} "{repo}"', shell=True)
message = message.decode(sys.stdout.encoding)
who = subprocess.check_output(f'svnlook author {rev_arg} "{repo}"', shell=True)
who = who.decode(sys.stdout.encoding)
revision = opts.get('revision')
if revision is not None:
revision = str(int(revision))
# see if we even need to notify buildbot by looking at filters first
changestring = '\n'.join(changed)
fltpat = opts['includes']
if fltpat:
included = sets.Set(re.findall(fltpat, changestring))
else:
included = sets.Set(changed)
expat = opts['excludes']
if expat:
excluded = sets.Set(re.findall(expat, changestring))
else:
excluded = sets.Set([])
if len(included.difference(excluded)) == 0:
print(changestring)
print(
f"""\
Buildbot was not interested, no changes matched any of these filters:\n {fltpat}
or all the changes matched these exclusions:\n {expat}\
"""
)
sys.exit(0)
# now see which branches are involved
files_per_branch = {}
for f in changed:
branch, filename = split_file(f)
if branch in files_per_branch.keys():
files_per_branch[branch].append(filename)
else:
files_per_branch[branch] = [filename]
# now create the Change dictionaries
changes = []
encoding = opts['encoding']
for branch in files_per_branch.keys():
d = {
'who': text_type(who, encoding=encoding),
'repository': text_type(worker_repo, encoding=encoding),
'comments': text_type(message, encoding=encoding),
'revision': revision,
'project': text_type(opts['project'] or "", encoding=encoding),
'src': 'svn',
}
if branch:
d['branch'] = text_type(branch, encoding=encoding)
else:
d['branch'] = branch
files = []
for file in files_per_branch[branch]:
files.append(text_type(file, encoding=encoding))
d['files'] = files
changes.append(d)
return changes
def sendChanges(self, opts, changes):
pbcf = pb.PBClientFactory()
reactor.connectTCP(opts['bbserver'], int(opts['bbport']), pbcf)
creds = credentials.UsernamePassword(opts['username'], opts['auth'])
d = pbcf.login(creds)
d.addCallback(self.sendAllChanges, changes)
return d
def sendAllChanges(self, remote, changes):
dl = [remote.callRemote('addChange', change) for change in changes]
return defer.gatherResults(dl, consumeErrors=True)
def run(self):
opts = Options()
try:
opts.parseOptions()
except usage.error as ue:
print(opts)
print(f"{sys.argv[0]}: {ue}")
sys.exit()
changes = self.getChanges(opts)
if opts['dryrun']:
for i, c in enumerate(changes):
print("CHANGE #%d" % (i + 1))
keys = sorted(c.keys())
for k in keys:
print("[%10s]: %s" % (k, c[k]))
print("*NOT* sending any changes")
return
d = self.sendChanges(opts, changes)
def quit(*why):
print("quitting! because", why)
reactor.stop()
d.addCallback(quit, "SUCCESS")
@d.addErrback
def failed(f):
print("FAILURE")
print(f)
reactor.stop()
reactor.callLater(60, quit, "TIMEOUT")
reactor.run()
if __name__ == '__main__':
s = ChangeSender()
s.run()
| 9,698 | Python | .py | 237 | 32.949367 | 97 | 0.612818 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
5,012 | check_smtp.py | buildbot_buildbot/master/contrib/check_smtp.py | #! /usr/bin/python -tt
from getpass import getpass
from smtplib import SMTP
"""
This script helps to check that the SMTP_HOST (see below) would accept STARTTLS
command, and if LOCAL_HOST is acceptable for it, would check the requested user
name and password would allow to send e-mail through it.
"""
SMTP_HOST = 'the host you want to send e-mail through'
LOCAL_HOST = 'hostname that the SMTP_HOST would accept'
def main():
"""
entry point
"""
server = SMTP(SMTP_HOST)
server.starttls()
print(server.ehlo(LOCAL_HOST))
user = input('user: ')
password = getpass('password: ')
print(server.login(user, password))
server.close()
if __name__ == '__main__':
main()
# vim:ts=4:sw=4:et:tw=80
| 743 | Python | .py | 24 | 27.5 | 79 | 0.698864 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
5,013 | svn_watcher.py | buildbot_buildbot/master/contrib/svn_watcher.py | #!/usr/bin/python
# This is a program which will poll a (remote) SVN repository, looking for
# new revisions. It then uses the 'buildbot sendchange' command to deliver
# information about the Change to a (remote) buildmaster. It can be run from
# a cron job on a periodic basis, or can be told (with the 'watch' option) to
# automatically repeat its check every 10 minutes.
# This script does not store any state information, so to avoid spurious
# changes you must use the 'watch' option and let it run forever.
# You will need to provide it with the location of the buildmaster's
# PBChangeSource port (in the form hostname:portnum), and the svnurl of the
# repository to watch.
import subprocess
import sys
import time
import xml.dom.minidom
from optparse import OptionParser
from xml.parsers.expat import ExpatError
if sys.platform == 'win32':
import win32pipe
def getoutput(cmd):
timeout = 120
maxtries = 3
if sys.platform == 'win32':
f = win32pipe.popen(cmd)
stdout = ''.join(f.readlines())
f.close()
else:
currentry = 1
while True: # retry loop
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
waited = 0
while True: # wait loop
if p.poll() != None:
break # process ended.
if waited > timeout:
print(
"WARNING: Timeout of {} seconds reached while trying to run: {}".format(
timeout, ' '.join(cmd)
)
)
break
waited += 1
time.sleep(1)
if p.returncode != None: # process has endend
stdout = p.stdout.read()
if p.returncode == 0:
break # ok: exit retry loop
else:
print(
'WARNING: "{}" returned status code: {}'.format(' '.join(cmd), p.returncode)
)
if stdout is not None:
print(stdout)
else:
p.kill()
if currentry > maxtries:
print(
"ERROR: Reached maximum number of tries ({}) to run: {}".format(
maxtries, ' '.join(cmd)
)
)
sys.exit(1)
currentry += 1
return stdout
def sendchange_cmd(master, revisionData):
cmd = [
"buildbot",
"sendchange",
f"--master={master}",
"--revision={}".format(revisionData['revision']),
"--who={}".format(revisionData['author']),
"--comments={}".format(revisionData['comments']),
"--vc={}".format('svn'),
]
if opts.revlink:
cmd.append("--revlink={}/{}".format(opts.revlink, revisionData['revision']))
if opts.category:
cmd.append(f"--category={opts.category}")
if opts.branch:
cmd.append(f"--branch={opts.branch}")
if opts.auth:
cmd.append(f"--auth={opts.auth}")
for path in revisionData['paths']:
cmd.append(path)
if opts.verbose:
print(cmd)
return cmd
def parseChangeXML(raw_xml):
"""Parse the raw xml and return a dict with key pairs set.
Commmand we're parsing:
svn log --non-interactive --xml --verbose --limit=1 <repo url>
With an output that looks like this:
<?xml version="1.0"?>
<log>
<logentry revision="757">
<author>mwiggins</author>
<date>2009-11-11T17:16:48.012357Z</date>
<paths>
<path kind="" copyfrom-path="/trunk" copyfrom-rev="756" action="A">/tags/Latest</path>
</paths>
<msg>Updates/latest</msg>
</logentry>
</log>
"""
data = dict()
# parse the xml string and grab the first log entry.
try:
doc = xml.dom.minidom.parseString(raw_xml)
except ExpatError:
print("\nError: Got an empty response with an empty changeset.\n")
raise
log_entry = doc.getElementsByTagName("logentry")[0]
# grab the appropriate meta data we need
data['revision'] = log_entry.getAttribute("revision")
data['author'] = "".join([
t.data for t in log_entry.getElementsByTagName("author")[0].childNodes
])
data['comments'] = "".join([
t.data for t in log_entry.getElementsByTagName("msg")[0].childNodes
])
# grab the appropriate file paths that changed.
pathlist = log_entry.getElementsByTagName("paths")[0]
paths = []
if opts.branch:
branchtoken = "/" + opts.branch.strip("/") + "/"
for path in pathlist.getElementsByTagName("path"):
filename = "".join([t.data for t in path.childNodes])
if opts.branch:
filename = filename.split(branchtoken, 1)[1]
paths.append(filename)
data['paths'] = paths
return data
# FIXME: instead of just picking the last svn change each $interval minutes,
# we should be querying the svn server for all the changes between our
# last check and now, and notify the buildmaster about all of them.
# This is an example of a svn query we could do to get allo those changes:
# svn log --xml --non-interactive -r ${lastrevchecked}:HEAD https://repo.url/branch
def checkChanges(repo, master, oldRevision=-1):
cmd = ["svn", "log", "--non-interactive", "--xml", "--verbose", "--limit=1", repo]
if opts.verbose:
print("Getting last revision of repository: " + repo)
xml1 = getoutput(cmd)
pretty_time = time.strftime("%F %T ")
if opts.verbose:
print("XML\n-----------\n" + xml1 + "\n\n")
revisionData = parseChangeXML(xml1)
if opts.verbose:
print("PATHS")
print(revisionData['paths'])
if revisionData['revision'] != oldRevision:
cmd = sendchange_cmd(master, revisionData)
status = getoutput(cmd)
print("{} Revision {}: {}".format(pretty_time, revisionData['revision'], status))
else:
print(
"{} nothing has changed since revision {}".format(pretty_time, revisionData['revision'])
)
return revisionData['revision']
def build_parser():
usagestr = "%prog [options] <repo url> <buildbot master:port>"
parser = OptionParser(usage=usagestr)
parser.add_option(
"-c",
"--category",
dest="category",
action="store",
default="",
help="""Store a category name to be associated with sendchange msg.""",
)
parser.add_option(
"-i",
"--interval",
dest="interval",
action="store",
default=0,
help="Implies watch option and changes the time in minutes to the value specified.",
)
parser.add_option(
"-v",
"--verbose",
dest="verbose",
action="store_true",
default=False,
help="Enables more information to be presented on the command line.",
)
parser.add_option(
"-b",
"--branch",
dest="branch",
action="store",
default=None,
help="Watch only changes for this branch and send the branch info.",
)
parser.add_option(
"-a",
"--auth",
dest="auth",
action="store",
default=None,
help="Authentication token - username:password.",
)
parser.add_option(
"-l",
"--link",
dest="revlink",
action="store",
default=None,
help="A base URL for the revision links.",
)
parser.add_option(
"",
"--watch",
dest="watch",
action="store_true",
default=False,
help="Automatically check the repo url every 10 minutes.",
)
return parser
def validate_args(args):
"""Validate our arguments and exit if we don't have what we want."""
if not args:
print("\nError: No arguments were specified.\n")
parser.print_help()
sys.exit(1)
elif len(args) > 2:
print("\nToo many arguments specified.\n")
parser.print_help()
sys.exit(2)
if __name__ == '__main__':
# build our parser and validate our args
parser = build_parser()
(opts, args) = parser.parse_args()
validate_args(args)
if opts.interval:
try:
int(opts.interval)
except ValueError:
print("\nError: Value of the interval option must be a number.")
parser.print_help()
sys.exit(3)
# grab what we need
repo_url = args[0]
bbmaster = args[1]
if opts.branch:
repo_url = repo_url.rstrip("/") + "/" + opts.branch.lstrip("/")
# if watch is specified, run until stopped
if opts.watch or opts.interval:
oldRevision = -1
print(f"Watching for changes in repo {repo_url} for master {bbmaster}.")
while True:
try:
oldRevision = checkChanges(repo_url, bbmaster, oldRevision)
except ExpatError:
# had an empty changeset. Trapping the exception and moving
# on.
pass
try:
if opts.interval:
# Check the repository every interval in minutes the user
# specified.
time.sleep(int(opts.interval) * 60)
else:
# Check the repository every 10 minutes
time.sleep(10 * 60)
except KeyboardInterrupt:
print("\nReceived interrupt via keyboard. Shutting Down.")
sys.exit(0)
# default action if watch isn't specified
checkChanges(repo_url, bbmaster)
| 9,716 | Python | .py | 269 | 27.219331 | 100 | 0.580236 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
5,014 | svnpoller.py | buildbot_buildbot/master/contrib/svnpoller.py | #!/usr/bin/python
"""
svn.py
Script for BuildBot to monitor a remote Subversion repository.
Copyright (C) 2006 John Pye
"""
# This script is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library 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
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
# USA
import os.path
import subprocess
import sys
import xml.dom.minidom
import ConfigParser
# change these settings to match your project
svnurl = "https://pse.cheme.cmu.edu/svn/ascend/code/trunk"
statefilename = "~/changemonitor/config.ini"
buildmaster = "buildbot.example.org:9989" # connects to a PBChangeSource
xml1 = subprocess.check_output(
"svn log --non-interactive --verbose --xml --limit=1 " + svnurl, shell=True
)
xml1 = xml1.decode(sys.stdout.encoding)
# print "XML\n-----------\n"+xml1+"\n\n"
try:
doc = xml.dom.minidom.parseString(xml1)
el = doc.getElementsByTagName("logentry")[0]
revision = el.getAttribute("revision")
author = "".join([t.data for t in el.getElementsByTagName("author")[0].childNodes])
comments = "".join([t.data for t in el.getElementsByTagName("msg")[0].childNodes])
pathlist = el.getElementsByTagName("paths")[0]
paths = []
for p in pathlist.getElementsByTagName("path"):
paths.append("".join([t.data for t in p.childNodes]))
# print "PATHS"
# print paths
except xml.parsers.expat.ExpatError as e:
print("FAILED TO PARSE 'svn log' XML:")
print(str(e))
print("----")
print("RECEIVED TEXT:")
print(xml1)
import sys
sys.exit(1)
fname = statefilename
fname = os.path.expanduser(fname)
ini = ConfigParser.SafeConfigParser()
try:
ini.read(fname)
except Exception:
print("Creating changemonitor config.ini:", fname)
ini.add_section("CurrentRevision")
ini.set("CurrentRevision", -1)
try:
lastrevision = ini.get("CurrentRevision", "changeset")
except ConfigParser.NoOptionError:
print("NO OPTION FOUND")
lastrevision = -1
except ConfigParser.NoSectionError:
print("NO SECTION FOUND")
lastrevision = -1
if lastrevision != revision:
# comments = codecs.encodings.unicode_escape.encode(comments)
cmd = (
"buildbot sendchange --master="
+ buildmaster
+ " --branch=trunk \
--revision=\""
+ revision
+ "\" --who=\""
+ author
+ "\" --vc=\"svn\" \
--comments=\""
+ comments
+ "\" "
+ " ".join(paths)
)
# print cmd
res = subprocess.check_output(cmd)
res = res.decode(sys.stdout.encoding)
print("SUBMITTING NEW REVISION", revision)
if not ini.has_section("CurrentRevision"):
ini.add_section("CurrentRevision")
try:
ini.set("CurrentRevision", "changeset", revision)
f = open(fname, "w")
ini.write(f)
# print "WROTE CHANGES TO",fname
except Exception:
print("FAILED TO RECORD INI FILE")
| 3,441 | Python | .py | 100 | 30.44 | 87 | 0.695613 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
5,015 | darcs_buildbot.py | buildbot_buildbot/master/contrib/darcs_buildbot.py | #! /usr/bin/python
# This is a script which delivers Change events from Darcs to the buildmaster
# each time a patch is pushed into a repository. Add it to the 'apply' hook
# on your canonical "central" repository, by putting something like the
# following in the _darcs/prefs/defaults file of that repository:
#
# apply posthook /PATH/TO/darcs_buildbot.py BUILDMASTER:PORT
# apply run-posthook
#
# (the second command is necessary to avoid the usual "do you really want to
# run this hook" prompt. Note that you cannot have multiple 'apply posthook'
# lines: if you need this, you must create a shell script to run all your
# desired commands, then point the posthook at that shell script.)
#
# Note that both Buildbot and Darcs must be installed on the repository
# machine. You will also need the Python/XML distribution installed (the
# "python2.3-xml" package under debian).
import os
import subprocess
import sys
import xml
from xml.dom import minidom
from twisted.internet import defer
from twisted.internet import reactor
from buildbot.clients import sendchange
def getText(node):
return "".join([cn.data for cn in node.childNodes if cn.nodeType == cn.TEXT_NODE])
def getTextFromChild(parent, childtype):
children = parent.getElementsByTagName(childtype)
if not children:
return ""
return getText(children[0])
def makeChange(p):
author = p.getAttribute("author")
revision = p.getAttribute("hash")
comments = getTextFromChild(p, "name") + "\n" + getTextFromChild(p, "comment")
summary = p.getElementsByTagName("summary")[0]
files = []
for filenode in summary.childNodes:
if filenode.nodeName in ("add_file", "modify_file", "remove_file"):
filename = getText(filenode).strip()
files.append(filename)
elif filenode.nodeName == "move":
to_name = filenode.getAttribute("to")
files.append(to_name)
# note that these are all unicode. Because PB can't handle unicode, we
# encode them into ascii, which will blow up early if there's anything we
# can't get to the far side. When we move to something that *can* handle
# unicode (like newpb), remove this.
author = author.encode("ascii", "replace")
comments = comments.encode("ascii", "replace")
files = [f.encode("ascii", "replace") for f in files]
revision = revision.encode("ascii", "replace")
change = {
# note: this is more likely to be a full email address, which would
# make the left-hand "Changes" column kind of wide. The buildmaster
# should probably be improved to display an abbreviation of the
# username.
'username': author,
'revision': revision,
'comments': comments,
'files': files,
}
return change
def getChangesFromCommand(cmd, count):
out = subprocess.check_output(cmd, shell=True)
out = out.decode(sys.stdout.encoding)
try:
doc = minidom.parseString(out)
except xml.parsers.expat.ExpatError as e:
print("failed to parse XML")
print(str(e))
print("purported XML is:")
print("--BEGIN--")
print(out)
print("--END--")
sys.exit(1)
c = doc.getElementsByTagName("changelog")[0]
changes = []
for i, p in enumerate(c.getElementsByTagName("patch")):
if i >= count:
break
changes.append(makeChange(p))
return changes
def getSomeChanges(count):
cmd = "darcs changes --last=%d --xml-output --summary" % count
return getChangesFromCommand(cmd, count)
LASTCHANGEFILE = ".darcs_buildbot-lastchange"
def findNewChanges():
if os.path.exists(LASTCHANGEFILE):
f = open(LASTCHANGEFILE)
lastchange = f.read()
f.close()
else:
return getSomeChanges(1)
lookback = 10
while True:
changes = getSomeChanges(lookback)
# getSomeChanges returns newest-first, so changes[0] is the newest.
# we want to scan the newest first until we find the changes we sent
# last time, then deliver everything newer than that (and send them
# oldest-first).
for i, c in enumerate(changes):
if c['revision'] == lastchange:
newchanges = changes[:i]
newchanges.reverse()
return newchanges
if 2 * lookback > 100:
raise RuntimeError(
"unable to find our most recent change "
"(%s) in the last %d changes" % (lastchange, lookback)
)
lookback = 2 * lookback
def sendChanges(master):
changes = findNewChanges()
s = sendchange.Sender(master)
d = defer.Deferred()
reactor.callLater(0, d.callback, None)
if not changes:
print("darcs_buildbot.py: weird, no changes to send")
return
elif len(changes) == 1:
print("sending 1 change to buildmaster:")
else:
print("sending %d changes to buildmaster:" % len(changes))
# the Darcs Source class expects revision to be a context, not a
# hash of a patch (which is what we have in c['revision']). For
# the moment, we send None for everything but the most recent, because getting
# contexts is Hard.
# get the context for the most recent change
latestcontext = subprocess.check_output("darcs changes --context", shell=True)
latestcontext = latestcontext.decode(sys.stdout.encoding)
changes[-1]['context'] = latestcontext
def _send(res, c):
branch = None
print(" {}".format(c['revision']))
return s.send(
branch, c.get('context'), c['comments'], c['files'], c['username'], vc='darcs'
)
for c in changes:
d.addCallback(_send, c)
def printSuccess(res):
num_changes = len(changes)
if num_changes > 1:
print("%d changes sent successfully" % num_changes)
elif num_changes == 1:
print("change sent successfully")
else:
print("no changes to send")
def printFailure(why):
print("change(s) NOT sent, something went wrong: " + str(why))
d.addCallbacks(printSuccess, printFailure)
d.addBoth(lambda _: reactor.stop)
reactor.run()
if changes:
lastchange = changes[-1]['revision']
f = open(LASTCHANGEFILE, "w")
f.write(lastchange)
f.close()
if __name__ == '__main__':
MASTER = sys.argv[1]
sendChanges(MASTER)
| 6,458 | Python | .py | 162 | 33.253086 | 90 | 0.659371 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
5,016 | git_buildbot.py | buildbot_buildbot/master/contrib/git_buildbot.py | #!/usr/bin/env python
# This script expects one line for each new revision on the form
# <oldrev> <newrev> <refname>
#
# For example:
# aa453216d1b3e49e7f6f98441fa56946ddcd6a20
# 68f7abf4e6f922807889f52bc043ecd31b79f814 refs/heads/master
#
# Each of these changes will be passed to the buildbot server along
# with any other change information we manage to extract from the
# repository.
#
# This script is meant to be run from hooks/post-receive in the git
# repository. It can also be run at client side with hooks/post-merge
# after using this wrapper:
# !/bin/sh
# PRE=$(git rev-parse 'HEAD@{1}')
# POST=$(git rev-parse HEAD)
# SYMNAME=$(git rev-parse --symbolic-full-name HEAD)
# echo "$PRE $POST $SYMNAME" | git_buildbot.py
#
# Largely based on contrib/hooks/post-receive-email from git.
from future.utils import iteritems
try:
from future.utils import text_type
except ImportError:
from six import text_type
import logging
import re
import shlex
import subprocess
import sys
from optparse import OptionParser
from twisted.cred import credentials
from twisted.internet import defer
from twisted.internet import reactor
try:
from twisted.spread import pb
except ImportError as e:
raise ImportError(
'Twisted version conflicts.\
Upgrade to latest version may solve this problem.\
try: pip install --upgrade twisted'
) from e
# Modify this to fit your setup, or pass in --master server:port on the
# command line
master = "localhost:9989"
# When sending the notification, send this category if (and only if)
# it's set (via --category)
category = None
# When sending the notification, send this repository if (and only if)
# it's set (via --repository)
repository = None
# When sending the notification, send this project if (and only if)
# it's set (via --project)
project = None
# When sending the notification, send this codebase. If this is None, no
# codebase will be sent. This can also be set via --codebase
codebase = None
# Username portion of PB login credentials to send the changes to the master
username = "change"
# Password portion of PB login credentials to send the changes to the master
auth = "changepw"
# When converting strings to unicode, assume this encoding.
# (set with --encoding)
encoding = sys.stdout.encoding or 'utf-8'
# If true, takes only the first parent commits. This controls if we want to
# trigger builds for merged in commits (when False).
first_parent = False
# The GIT_DIR environment variable must have been set up so that any
# git commands that are executed will operate on the repository we're
# installed in.
changes = []
def connectFailed(error):
logging.error("Could not connect to %s: %s", master, error.getErrorMessage())
return error
def addChanges(remote, changei, src='git'):
logging.debug("addChanges %s, %s", repr(remote), repr(changei))
def addChange(c):
logging.info("New revision: %s", c['revision'][:8])
for key, value in iteritems(c):
logging.debug(" %s: %s", key, value)
c['src'] = src
d = remote.callRemote('addChange', c)
return d
finished_d = defer.Deferred()
def iter():
try:
c = next(changei)
logging.info("CHANGE: %s", c)
d = addChange(c)
# handle successful completion by re-iterating, but not immediately
# as that will blow out the Python stack
def cb(_):
reactor.callLater(0, iter)
d.addCallback(cb)
# and pass errors along to the outer deferred
d.addErrback(finished_d.errback)
except StopIteration:
remote.broker.transport.loseConnection()
finished_d.callback(None)
except Exception as e:
logging.error(e)
iter()
return finished_d
def connected(remote):
return addChanges(remote, changes.__iter__())
def grab_commit_info(c, rev):
# Extract information about committer and files using git show
options = "--raw --pretty=full"
if first_parent:
# Show the full diff for merges to avoid losing changes
# when builds are not triggered for merged in commits
options += " --diff-merges=first-parent"
f = subprocess.Popen(shlex.split(f"git show {options} {rev}"), stdout=subprocess.PIPE)
files = []
comments = []
while True:
line = f.stdout.readline().decode(encoding)
if not line:
break
if line.startswith(4 * ' '):
comments.append(line[4:])
m = re.match(r"^:.*[MAD]\s+(.+)$", line)
if m:
logging.debug("Got file: %s", m.group(1))
files.append(text_type(m.group(1)))
continue
m = re.match(r"^Author:\s+(.+)$", line)
if m:
logging.debug("Got author: %s", m.group(1))
c['who'] = text_type(m.group(1))
# Retain default behavior if all commits trigger builds
if not first_parent and re.match(r"^Merge: .*$", line):
files.append('merge')
c['comments'] = ''.join(comments)
c['files'] = files
status = f.wait()
if status:
logging.warning("git show exited with status %d", status)
def gen_changes(input, branch):
while True:
line = input.stdout.readline().decode(encoding)
if not line:
break
logging.debug("Change: %s", line)
m = re.match(r"^([0-9a-f]+) (.*)$", line.strip())
c = {
'revision': m.group(1),
'branch': text_type(branch),
}
if category:
c['category'] = text_type(category)
if repository:
c['repository'] = text_type(repository)
if project:
c['project'] = text_type(project)
if codebase:
c['codebase'] = text_type(codebase)
grab_commit_info(c, m.group(1))
changes.append(c)
def gen_create_branch_changes(newrev, refname, branch):
# A new branch has been created. Generate changes for everything
# up to `newrev' which does not exist in any branch but `refname'.
#
# Note that this may be inaccurate if two new branches are created
# at the same time, pointing to the same commit, or if there are
# commits that only exists in a common subset of the new branches.
logging.info("Branch `%s' created", branch)
p = subprocess.Popen(shlex.split(f"git rev-parse {refname}"), stdout=subprocess.PIPE)
branchref = p.communicate()[0].strip().decode(encoding)
f = subprocess.Popen(shlex.split("git rev-parse --not --branches"), stdout=subprocess.PIPE)
f2 = subprocess.Popen(
shlex.split(f"grep -v {branchref}"), stdin=f.stdout, stdout=subprocess.PIPE
)
options = "--reverse --pretty=oneline --stdin"
if first_parent:
# Don't add merged commits to avoid running builds twice for the same
# changes, as they should only be done for first parent commits
options += " --first-parent"
f3 = subprocess.Popen(
shlex.split(f"git rev-list {options} {newrev}"),
stdin=f2.stdout,
stdout=subprocess.PIPE,
)
gen_changes(f3, branch)
status = f3.wait()
if status:
logging.warning("git rev-list exited with status %d", status)
def gen_create_tag_changes(newrev, refname, tag):
# A new tag has been created. Generate one change for the commit
# a tag may or may not coincide with the head of a branch, so
# the "branch" attribute will hold the tag name.
logging.info("Tag `%s' created", tag)
f = subprocess.Popen(
shlex.split(f"git log -n 1 --pretty=oneline {newrev}"), stdout=subprocess.PIPE
)
gen_changes(f, tag)
status = f.wait()
if status:
logging.warning("git log exited with status %d", status)
def gen_update_branch_changes(oldrev, newrev, refname, branch):
# A branch has been updated. If it was a fast-forward update,
# generate Change events for everything between oldrev and newrev.
#
# In case of a forced update, first generate a "fake" Change event
# rewinding the branch to the common ancestor of oldrev and
# newrev. Then, generate Change events for each commit between the
# common ancestor and newrev.
logging.info("Branch `%s' updated %s .. %s", branch, oldrev[:8], newrev[:8])
mergebasecommand = subprocess.Popen(
["git", "merge-base", oldrev, newrev], stdout=subprocess.PIPE
)
(baserev, err) = mergebasecommand.communicate()
baserev = baserev.strip() # remove newline
baserev = baserev.decode(encoding)
logging.debug("oldrev=%s newrev=%s baserev=%s", oldrev, newrev, baserev)
if baserev != oldrev:
c = {
'revision': baserev,
'comments': "Rewind branch",
'branch': text_type(branch),
'who': "dummy",
}
logging.info("Branch %s was rewound to %s", branch, baserev[:8])
files = []
f = subprocess.Popen(
shlex.split(f"git diff --raw {oldrev}..{baserev}"),
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
)
while True:
line = f.stdout.readline().decode(encoding)
if not line:
break
file = re.match(r"^:.*[MAD]\s+(.+)$", line).group(1)
logging.debug(" Rewound file: %s", file)
files.append(text_type(file))
status = f.wait()
if status:
logging.warning("git diff exited with status %d", status)
if category:
c['category'] = text_type(category)
if repository:
c['repository'] = text_type(repository)
if project:
c['project'] = text_type(project)
if codebase:
c['codebase'] = text_type(codebase)
if files:
c['files'] = files
changes.append(c)
if newrev != baserev:
# Not a pure rewind
options = "--reverse --pretty=oneline"
if first_parent:
# Add the --first-parent to avoid adding the merge commits which
# have already been tested.
options += ' --first-parent'
f = subprocess.Popen(
shlex.split(f"git rev-list {options} {baserev}..{newrev}"),
stdout=subprocess.PIPE,
)
gen_changes(f, branch)
status = f.wait()
if status:
logging.warning("git rev-list exited with status %d", status)
def cleanup(res):
reactor.stop()
def process_branch_change(oldrev, newrev, refname, branch):
# Find out if the branch was created, deleted or updated.
if re.match(r"^0*$", newrev):
logging.info("Branch `%s' deleted, ignoring", branch)
elif re.match(r"^0*$", oldrev):
gen_create_branch_changes(newrev, refname, branch)
else:
gen_update_branch_changes(oldrev, newrev, refname, branch)
def process_tag_change(oldrev, newrev, refname, tag):
# Process a new tag, or ignore a deleted tag
if re.match(r"^0*$", newrev):
logging.info("Tag `%s' deleted, ignoring", tag)
elif re.match(r"^0*$", oldrev):
gen_create_tag_changes(newrev, refname, tag)
def process_change(oldrev, newrev, refname):
# Identify the change as a branch, tag or other, and process it
m = re.match(r"^refs/(heads|tags)/(.+)$", refname)
if not m:
logging.info("Ignoring refname `%s': Not a branch or tag", refname)
return
if m.group(1) == 'heads':
branch = m.group(2)
process_branch_change(oldrev, newrev, refname, branch)
elif m.group(1) == 'tags':
tag = m.group(2)
process_tag_change(oldrev, newrev, refname, tag)
def process_changes():
# Read branch updates from stdin and generate Change events
while True:
line = sys.stdin.readline()
line = line.rstrip()
if not line:
break
args = line.split(None, 2)
[oldrev, newrev, refname] = args
process_change(oldrev, newrev, refname)
def send_changes():
# Submit the changes, if any
if not changes:
logging.info("No changes found")
return
host, port = master.split(':')
port = int(port)
f = pb.PBClientFactory()
d = f.login(credentials.UsernamePassword(username.encode('utf-8'), auth.encode('utf-8')))
reactor.connectTCP(host, port, f)
d.addErrback(connectFailed)
d.addCallback(connected)
d.addBoth(cleanup)
reactor.run()
def parse_options():
parser = OptionParser()
parser.add_option(
"-l", "--logfile", action="store", type="string", help="Log to the specified file"
)
parser.add_option(
"-v", "--verbose", action="count", help="Be more verbose. Ignored if -l is not specified."
)
master_help = f"Build master to push to. Default is {master}"
parser.add_option("-m", "--master", action="store", type="string", help=master_help)
parser.add_option(
"-c", "--category", action="store", type="string", help="Scheduler category to notify."
)
parser.add_option(
"-r", "--repository", action="store", type="string", help="Git repository URL to send."
)
parser.add_option("-p", "--project", action="store", type="string", help="Project to send.")
parser.add_option("--codebase", action="store", type="string", help="Codebase to send.")
encoding_help = "Encoding to use when converting strings to " f"unicode. Default is {encoding}."
parser.add_option("-e", "--encoding", action="store", type="string", help=encoding_help)
username_help = "Username used in PB connection auth, defaults to " f"{username}."
parser.add_option("-u", "--username", action="store", type="string", help=username_help)
auth_help = "Password used in PB connection auth, defaults to " f"{auth}."
# 'a' instead of 'p' due to collisions with the project short option
parser.add_option("-a", "--auth", action="store", type="string", help=auth_help)
first_parent_help = "If set, don't trigger builds for merged in commits"
parser.add_option("--first-parent", action="store_true", help=first_parent_help)
options, args = parser.parse_args()
return options
# Log errors and critical messages to stderr. Optionally log
# information to a file as well (we'll set that up later.)
stderr = logging.StreamHandler(sys.stderr)
fmt = logging.Formatter("git_buildbot: %(levelname)s: %(message)s")
stderr.setLevel(logging.WARNING)
stderr.setFormatter(fmt)
logging.getLogger().addHandler(stderr)
logging.getLogger().setLevel(logging.NOTSET)
try:
options = parse_options()
level = logging.WARNING
if options.verbose:
level -= 10 * options.verbose
level = max(level, 0)
if options.logfile:
logfile = logging.FileHandler(options.logfile)
logfile.setLevel(level)
fmt = logging.Formatter("%(asctime)s %(levelname)s: %(message)s")
logfile.setFormatter(fmt)
logging.getLogger().addHandler(logfile)
if options.master:
master = options.master
if options.category:
category = options.category
if options.repository:
repository = options.repository
if options.project:
project = options.project
if options.codebase:
codebase = options.codebase
if options.username:
username = options.username
if options.auth:
auth = options.auth
if options.encoding:
encoding = options.encoding
if options.first_parent:
first_parent = options.first_parent
process_changes()
send_changes()
except Exception:
logging.exception("Unhandled exception")
sys.exit(1)
| 15,772 | Python | .py | 391 | 33.626598 | 100 | 0.648873 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
5,017 | bitbucket_buildbot.py | buildbot_buildbot/master/contrib/bitbucket_buildbot.py | #!/usr/bin/env python
"""Change source forwarder for bitbucket.org POST service.
bitbucket_buildbot.py will determine the repository information from
the JSON HTTP POST it receives from bitbucket.org and build the
appropriate repository.
If your bitbucket repository is private, you must add a ssh key to the
bitbucket repository for the user who initiated bitbucket_buildbot.py
bitbucket_buildbot.py is based on github_buildbot.py
"""
import logging
import sys
import tempfile
import traceback
from optparse import OptionParser
from future.utils import iteritems
from twisted.cred import credentials
from twisted.internet import reactor
from twisted.spread import pb
from twisted.web import resource
from twisted.web import server
try:
import json
except ImportError:
import simplejson as json
class BitBucketBuildBot(resource.Resource):
"""
BitBucketBuildBot creates the webserver that responds to the
BitBucket POST Service Hook.
"""
isLeaf = True
bitbucket = None
master = None
port = None
private = False
def render_POST(self, request):
"""
Responds only to POST events and starts the build process
:arguments:
request
the http request object
"""
try:
payload = json.loads(request.args['payload'][0])
logging.debug("Payload: " + str(payload))
self.process_change(payload)
except Exception:
logging.error("Encountered an exception:")
for msg in traceback.format_exception(*sys.exc_info()):
logging.error(msg.strip())
def process_change(self, payload):
"""
Consumes the JSON as a python object and actually starts the build.
:arguments:
payload
Python Object that represents the JSON sent by Bitbucket POST
Service Hook.
"""
if self.private:
repo_url = 'ssh://hg@{}{}'.format(
self.bitbucket,
payload['repository']['absolute_url'],
)
else:
repo_url = 'http://{}{}'.format(
self.bitbucket,
payload['repository']['absolute_url'],
)
changes = []
for commit in payload['commits']:
files = [file_info['file'] for file_info in commit['files']]
revlink = 'http://{}{}/changeset/{}/'.format(
self.bitbucket,
payload['repository']['absolute_url'],
commit['node'],
)
change = {
'revision': commit['node'],
'revlink': revlink,
'comments': commit['message'],
'who': commit['author'],
'files': files,
'repository': repo_url,
'properties': dict(),
}
changes.append(change)
# Submit the changes, if any
if not changes:
logging.warning("No changes found")
return
host, port = self.master.split(':')
port = int(port)
factory = pb.PBClientFactory()
deferred = factory.login(credentials.UsernamePassword("change", "changepw"))
logging.debug('Trying to connect to: %s:%d', host, port)
reactor.connectTCP(host, port, factory)
deferred.addErrback(self.connectFailed)
deferred.addCallback(self.connected, changes)
def connectFailed(self, error):
"""
If connection is failed. Logs the error.
"""
logging.error("Could not connect to master: %s", error.getErrorMessage())
return error
def addChange(self, dummy, remote, changei, src='hg'):
"""
Sends changes from the commit to the buildmaster.
"""
logging.debug("addChange %s, %s", repr(remote), repr(changei))
try:
change = changei.next()
except StopIteration:
remote.broker.transport.loseConnection()
return None
logging.info("New revision: %s", change['revision'][:8])
for key, value in iteritems(change):
logging.debug(" %s: %s", key, value)
change['src'] = src
deferred = remote.callRemote('addChange', change)
deferred.addCallback(self.addChange, remote, changei, src)
return deferred
def connected(self, remote, changes):
"""
Responds to the connected event.
"""
return self.addChange(None, remote, changes.__iter__())
def main():
"""
The main event loop that starts the server and configures it.
"""
usage = "usage: %prog [options]"
parser = OptionParser(usage)
parser.add_option(
"-p",
"--port",
help="Port the HTTP server listens to for the Bitbucket Service Hook"
" [default: %default]",
default=4000,
type=int,
dest="port",
)
parser.add_option(
"-m",
"--buildmaster",
help="Buildbot Master host and port. ie: localhost:9989 [default:" + " %default]",
default="localhost:9989",
dest="buildmaster",
)
parser.add_option(
"-l",
"--log",
help="The absolute path, including filename, to save the log to" " [default: %default]",
default=tempfile.gettempdir() + "/bitbucket_buildbot.log",
dest="log",
)
parser.add_option(
"-L",
"--level",
help="The logging level: debug, info, warn, error, fatal [default:" " %default]",
default='warn',
dest="level",
)
parser.add_option(
"-g",
"--bitbucket",
help="The bitbucket serve [default: %default]",
default='bitbucket.org',
dest="bitbucket",
)
parser.add_option(
'-P',
'--private',
help='Use SSH to connect, for private repositories.',
dest='private',
default=False,
action='store_true',
)
(options, _) = parser.parse_args()
# Set up logging.
levels = {
'debug': logging.DEBUG,
'info': logging.INFO,
'warn': logging.WARNING,
'error': logging.ERROR,
'fatal': logging.FATAL,
}
filename = options.log
log_format = "%(asctime)s - %(levelname)s - %(message)s"
logging.basicConfig(filename=filename, format=log_format, level=levels[options.level])
# Start listener.
bitbucket_bot = BitBucketBuildBot()
bitbucket_bot.bitbucket = options.bitbucket
bitbucket_bot.master = options.buildmaster
bitbucket_bot.private = options.private
site = server.Site(bitbucket_bot)
reactor.listenTCP(options.port, site)
reactor.run()
if __name__ == '__main__':
main()
| 6,764 | Python | .py | 198 | 25.858586 | 96 | 0.598869 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
5,018 | bzr_buildbot.py | buildbot_buildbot/master/contrib/bzr_buildbot.py | # Copyright (C) 2008-2009 Canonical
#
# This program 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, either version 2 of the License, or
# (at your option) any later version.
#
# 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, see <http://www.gnu.org/licenses/>.
"""\
bzr buildbot integration
========================
This file contains both bzr commit/change hooks and a bzr poller.
------------
Requirements
------------
This has been tested with buildbot 0.7.9, bzr 1.10, and Twisted 8.1.0. It
should work in subsequent releases.
For the hook to work, Twisted must be installed in the same Python that bzr
uses.
-----
Hooks
-----
To install, put this file in a bzr plugins directory (e.g.,
~/.bazaar/plugins). Then, in one of your bazaar conf files (e.g.,
~/.bazaar/locations.conf), set the location you want to connect with buildbot
with these keys:
- buildbot_on: one of 'commit', 'push, or 'change'. Turns the plugin on to
report changes via commit, changes via push, or any changes to the trunk.
'change' is recommended.
- buildbot_server: (required to send to a buildbot master) the URL of the
buildbot master to which you will connect (as of this writing, the same
server and port to which workers connect).
- buildbot_port: (optional, defaults to 9989) the port of the buildbot master
to which you will connect (as of this writing, the same server and port to
which workers connect)
- buildbot_auth: (optional, defaults to change:changepw) the credentials
expected by the change source configuration in the master. Takes the
"user:password" form.
- buildbot_pqm: (optional, defaults to not pqm) Normally, the user that
commits the revision is the user that is responsible for the change. When
run in a pqm (Patch Queue Manager, see https://launchpad.net/pqm)
environment, the user that commits is the Patch Queue Manager, and the user
that committed the *parent* revision is responsible for the change. To turn
on the pqm mode, set this value to any of (case-insensitive) "Yes", "Y",
"True", or "T".
- buildbot_dry_run: (optional, defaults to not a dry run) Normally, the
post-commit hook will attempt to communicate with the configured buildbot
server and port. If this parameter is included and any of (case-insensitive)
"Yes", "Y", "True", or "T", then the hook will simply print what it would
have sent, but not attempt to contact the buildbot master.
- buildbot_send_branch_name: (optional, defaults to not sending the branch
name) If your buildbot's bzr source build step uses a repourl, do
*not* turn this on. If your buildbot's bzr build step uses a baseURL, then
you may set this value to any of (case-insensitive) "Yes", "Y", "True", or
"T" to have the buildbot master append the branch name to the baseURL.
Note: The bzr smart server (as of version 2.2.2) doesn't know how to resolve
bzr:// urls into absolute paths so any paths in locations.conf won't match,
hence no change notifications will be sent to Buildbot. Setting configuration
parameters globally or in-branch might still work.
When buildbot no longer has a hardcoded password, it will be a configuration
option here as well.
------
Poller
------
See the Buildbot manual.
-------------------
Contact Information
-------------------
Maintainer/author: [email protected]
"""
# Work around Twisted bug.
# See http://twistedmatrix.com/trac/ticket/3591
import socket
from typing import ClassVar
from typing import Sequence
import bzrlib.branch
import bzrlib.errors
import bzrlib.trace
import twisted.cred.credentials
import twisted.internet.base
import twisted.internet.reactor
import twisted.internet.selectreactor
import twisted.internet.task
import twisted.internet.threads
import twisted.python.log
import twisted.spread.pb
from twisted.internet import defer
from twisted.python import failure
try:
import buildbot.changes.base
import buildbot.changes.changes
import buildbot.util
except ImportError:
DEFINE_POLLER = False
else:
DEFINE_POLLER = True
#
# This is the code that the poller and the hooks share.
def generate_change(
branch, old_revno=None, old_revid=None, new_revno=None, new_revid=None, blame_merge_author=False
):
"""Return a dict of information about a change to the branch.
Dict has keys of "files", "who", "comments", and "revision", as used by
the buildbot Change (and the PBChangeSource).
If only the branch is given, the most recent change is returned.
If only the new_revno is given, the comparison is expected to be between
it and the previous revno (new_revno -1) in the branch.
Passing old_revid and new_revid is only an optimization, included because
bzr hooks usually provide this information.
blame_merge_author means that the author of the merged branch is
identified as the "who", not the person who committed the branch itself.
This is typically used for PQM.
"""
change = {} # files, who, comments, revision; NOT branch (= branch.nick)
if new_revno is None:
new_revno = branch.revno()
if new_revid is None:
new_revid = branch.get_rev_id(new_revno)
# TODO: This falls over if this is the very first revision
if old_revno is None:
old_revno = new_revno - 1
if old_revid is None:
old_revid = branch.get_rev_id(old_revno)
repository = branch.repository
new_rev = repository.get_revision(new_revid)
if blame_merge_author:
# this is a pqm commit or something like it
change['who'] = repository.get_revision(new_rev.parent_ids[-1]).get_apparent_authors()[0]
else:
change['who'] = new_rev.get_apparent_authors()[0]
# maybe useful to know:
# name, email = bzrtools.config.parse_username(change['who'])
change['comments'] = new_rev.message
change['revision'] = new_revno
files = change['files'] = []
changes = repository.revision_tree(new_revid).changes_from(repository.revision_tree(old_revid))
for collection, name in (
(changes.added, 'ADDED'),
(changes.removed, 'REMOVED'),
(changes.modified, 'MODIFIED'),
):
for info in collection:
path = info[0]
kind = info[2]
files.append(' '.join([path, kind, name]))
for info in changes.renamed:
oldpath, newpath, id, kind, text_modified, meta_modified = info
elements = [oldpath, kind, 'RENAMED', newpath]
if text_modified or meta_modified:
elements.append('MODIFIED')
files.append(' '.join(elements))
return change
#
# poller
# We don't want to make the hooks unnecessarily depend on buildbot being
# installed locally, so we conditionally create the BzrPoller class.
if DEFINE_POLLER:
FULL = object()
SHORT = object()
class BzrPoller(buildbot.changes.base.PollingChangeSource, buildbot.util.ComparableMixin):
compare_attrs: ClassVar[Sequence[str]] = 'url'
def __init__(
self,
url,
poll_interval=10 * 60,
blame_merge_author=False,
branch_name=None,
category=None,
):
# poll_interval is in seconds, so default poll_interval is 10
# minutes.
# bzr+ssh://bazaar.launchpad.net/~launchpad-pqm/launchpad/devel/
# works, lp:~launchpad-pqm/launchpad/devel/ doesn't without help.
if url.startswith('lp:'):
url = 'bzr+ssh://bazaar.launchpad.net/' + url[3:]
self.url = url
self.poll_interval = poll_interval
self.loop = twisted.internet.task.LoopingCall(self.poll)
self.blame_merge_author = blame_merge_author
self.branch_name = branch_name
self.category = category
def startService(self):
twisted.python.log.msg(f"BzrPoller({self.url}) starting")
if self.branch_name is FULL:
ourbranch = self.url
elif self.branch_name is SHORT:
# We are in a bit of trouble, as we cannot really know what our
# branch is until we have polled new changes.
# Seems we would have to wait until we polled the first time,
# and only then do the filtering, grabbing the branch name from
# whatever we polled.
# For now, leave it as it was previously (compare against
# self.url); at least now things work when specifying the
# branch name explicitly.
ourbranch = self.url
else:
ourbranch = self.branch_name
for change in reversed(self.parent.changes):
if change.branch == ourbranch:
self.last_revision = change.revision
break
else:
self.last_revision = None
buildbot.changes.base.PollingChangeSource.startService(self)
def stopService(self):
twisted.python.log.msg(f"BzrPoller({self.url}) shutting down")
return buildbot.changes.base.PollingChangeSource.stopService(self)
def describe(self):
return f"BzrPoller watching {self.url}"
@defer.inlineCallbacks
def poll(self):
# On a big tree, even individual elements of the bzr commands
# can take awhile. So we just push the bzr work off to a
# thread.
try:
changes = yield twisted.internet.threads.deferToThread(self.getRawChanges)
except (SystemExit, KeyboardInterrupt):
raise
except Exception:
# we'll try again next poll. Meanwhile, let's report.
twisted.python.log.err()
else:
for change_kwargs in changes:
yield self.addChange(change_kwargs)
self.last_revision = change_kwargs['revision']
def getRawChanges(self):
branch = bzrlib.branch.Branch.open_containing(self.url)[0]
if self.branch_name is FULL:
branch_name = self.url
elif self.branch_name is SHORT:
branch_name = branch.nick
else: # presumably a string or maybe None
branch_name = self.branch_name
changes = []
change = generate_change(branch, blame_merge_author=self.blame_merge_author)
if self.last_revision is None or change['revision'] > self.last_revision:
change['branch'] = branch_name
change['category'] = self.category
changes.append(change)
if self.last_revision is not None:
while self.last_revision + 1 < change['revision']:
change = generate_change(
branch,
new_revno=change['revision'] - 1,
blame_merge_author=self.blame_merge_author,
)
change['branch'] = branch_name
changes.append(change)
changes.reverse()
return changes
def addChange(self, change_kwargs):
d = defer.Deferred()
def _add_change():
d.callback(self.master.data.updates.addChange(src='bzr', **change_kwargs))
twisted.internet.reactor.callLater(0, _add_change)
return d
#
# hooks
HOOK_KEY = 'buildbot_on'
SERVER_KEY = 'buildbot_server'
PORT_KEY = 'buildbot_port'
AUTH_KEY = 'buildbot_auth'
DRYRUN_KEY = 'buildbot_dry_run'
PQM_KEY = 'buildbot_pqm'
SEND_BRANCHNAME_KEY = 'buildbot_send_branch_name'
PUSH_VALUE = 'push'
COMMIT_VALUE = 'commit'
CHANGE_VALUE = 'change'
def _is_true(config, key):
val = config.get_user_option(key)
return val is not None and val.lower().strip() in ('y', 'yes', 't', 'true')
def _installed_hook(branch):
value = branch.get_config().get_user_option(HOOK_KEY)
if value is not None:
value = value.strip().lower()
if value not in (PUSH_VALUE, COMMIT_VALUE, CHANGE_VALUE):
raise bzrlib.errors.BzrError(
f'{HOOK_KEY}, if set, must be one of {PUSH_VALUE}, {COMMIT_VALUE}, or {CHANGE_VALUE}'
)
return value
# replaces twisted.internet.thread equivalent
def _putResultInDeferred(reactor, deferred, f, args, kwargs):
"""
Run a function and give results to a Deferred.
"""
try:
result = f(*args, **kwargs)
except Exception:
f = failure.Failure()
reactor.callFromThread(deferred.errback, f)
else:
reactor.callFromThread(deferred.callback, result)
# would be a proposed addition. deferToThread could use it
def deferToThreadInReactor(reactor, f, *args, **kwargs):
"""
Run function in thread and return result as Deferred.
"""
d = defer.Deferred()
reactor.callInThread(_putResultInDeferred, reactor, d, f, args, kwargs)
return d
# uses its own reactor for the threaded calls, unlike Twisted's
class ThreadedResolver(twisted.internet.base.ThreadedResolver):
def getHostByName(self, name, timeout=(1, 3, 11, 45)):
if timeout:
timeoutDelay = sum(timeout)
else:
timeoutDelay = 60
userDeferred = defer.Deferred()
lookupDeferred = deferToThreadInReactor(self.reactor, socket.gethostbyname, name)
cancelCall = self.reactor.callLater(timeoutDelay, self._cleanup, name, lookupDeferred)
self._runningQueries[lookupDeferred] = (userDeferred, cancelCall)
lookupDeferred.addBoth(self._checkTimeout, name, lookupDeferred)
return userDeferred
def send_change(branch, old_revno, old_revid, new_revno, new_revid, hook):
config = branch.get_config()
server = config.get_user_option(SERVER_KEY)
if not server:
bzrlib.trace.warning(
'bzr_buildbot: ERROR. If %s is set, %s must be set', HOOK_KEY, SERVER_KEY
)
return
change = generate_change(
branch,
old_revno,
old_revid,
new_revno,
new_revid,
blame_merge_author=_is_true(config, PQM_KEY),
)
if _is_true(config, SEND_BRANCHNAME_KEY):
change['branch'] = branch.nick
# as of this writing (in Buildbot 0.7.9), 9989 is the default port when
# you make a buildbot master.
port = int(config.get_user_option(PORT_KEY) or 9989)
# if dry run, stop.
if _is_true(config, DRYRUN_KEY):
bzrlib.trace.note(
"bzr_buildbot DRY RUN " "(*not* sending changes to %s:%d on %s)", server, port, hook
)
keys = sorted(change.keys())
for k in keys:
bzrlib.trace.note("[%10s]: %s", k, change[k])
return
# We instantiate our own reactor so that this can run within a server.
reactor = twisted.internet.selectreactor.SelectReactor()
# See other reference to http://twistedmatrix.com/trac/ticket/3591
# above. This line can go away with a release of Twisted that addresses
# this issue.
reactor.resolver = ThreadedResolver(reactor)
pbcf = twisted.spread.pb.PBClientFactory()
reactor.connectTCP(server, port, pbcf)
auth = config.get_user_option(AUTH_KEY)
if auth:
user, passwd = [s.strip() for s in auth.split(':', 1)]
else:
user, passwd = ('change', 'changepw')
deferred = pbcf.login(twisted.cred.credentials.UsernamePassword(user, passwd))
@deferred.addCallback
def sendChanges(remote):
"""Send changes to buildbot."""
bzrlib.trace.mutter("bzrbuildout sending changes: %s", change)
change['src'] = 'bzr'
return remote.callRemote('addChange', change)
def quit(ignore, msg):
bzrlib.trace.note("bzrbuildout: %s", msg)
reactor.stop()
deferred.addCallback(quit, "SUCCESS")
@deferred.addErrback
def failed(failure):
bzrlib.trace.warning("bzrbuildout: FAILURE\n %s", failure)
reactor.stop()
reactor.callLater(60, quit, None, "TIMEOUT")
bzrlib.trace.note(
"bzr_buildbot: SENDING CHANGES to buildbot master %s:%d on %s", server, port, hook
)
reactor.run(installSignalHandlers=False) # run in a thread when in server
def post_commit(
local_branch,
master_branch, # branch is the master_branch
old_revno,
old_revid,
new_revno,
new_revid,
):
if _installed_hook(master_branch) == COMMIT_VALUE:
send_change(master_branch, old_revid, old_revid, new_revno, new_revid, COMMIT_VALUE)
def post_push(result):
if _installed_hook(result.target_branch) == PUSH_VALUE:
send_change(
result.target_branch,
result.old_revid,
result.old_revid,
result.new_revno,
result.new_revid,
PUSH_VALUE,
)
def post_change_branch_tip(result):
if _installed_hook(result.branch) == CHANGE_VALUE:
send_change(
result.branch,
result.old_revid,
result.old_revid,
result.new_revno,
result.new_revid,
CHANGE_VALUE,
)
bzrlib.branch.Branch.hooks.install_named_hook(
'post_commit', post_commit, 'send change to buildbot master'
)
bzrlib.branch.Branch.hooks.install_named_hook(
'post_push', post_push, 'send change to buildbot master'
)
bzrlib.branch.Branch.hooks.install_named_hook(
'post_change_branch_tip', post_change_branch_tip, 'send change to buildbot master'
)
| 17,933 | Python | .py | 421 | 35.261283 | 101 | 0.660529 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
5,019 | bk_buildbot.py | buildbot_buildbot/master/contrib/bk_buildbot.py | #!/usr/local/bin/python
#
# BitKeeper hook script.
#
# svn_buildbot.py was used as a base for this file, if you find any bugs or
# errors please email me.
#
# Amar Takhar <[email protected]>
import subprocess
import sys
from twisted.cred import credentials
from twisted.internet import reactor
from twisted.python import usage
from twisted.spread import pb
'''
/path/to/bk_buildbot.py --repository "$REPOS" --revision "$REV" --branch \
"<branch>" --bbserver localhost --bbport 9989
'''
# We have hackish "-d" handling here rather than in the Options
# subclass below because a common error will be to not have twisted in
# PYTHONPATH; we want to be able to print that error to the log if
# debug mode is on, so we set it up before the imports.
DEBUG = None
if '-d' in sys.argv:
i = sys.argv.index('-d')
DEBUG = sys.argv[i + 1]
del sys.argv[i]
del sys.argv[i]
if DEBUG:
f = open(DEBUG, 'a')
sys.stderr = f
sys.stdout = f
class Options(usage.Options):
optParameters = [
['repository', 'r', None, "The repository that was changed."],
['revision', 'v', None, "The revision that we want to examine (default: latest)"],
['branch', 'b', None, "Name of the branch to insert into the branch field. (REQUIRED)"],
['category', 'c', None, "Schedular category."],
['bbserver', 's', 'localhost', "The hostname of the server that buildbot is running on"],
['bbport', 'p', 8007, "The port that buildbot is listening on"],
]
optFlags = [
['dryrun', 'n', "Do not actually send changes"],
]
def __init__(self):
usage.Options.__init__(self)
def postOptions(self):
if self['repository'] is None:
raise usage.error("You must pass --repository")
class ChangeSender:
def getChanges(self, opts):
"""Generate and stash a list of Change dictionaries, ready to be sent
to the buildmaster's PBChangeSource."""
# first we extract information about the files that were changed
repo = opts['repository']
print("Repo:", repo)
rev_arg = ''
if opts['revision']:
rev_arg = '-r"{}"'.format(opts['revision'])
changed = subprocess.check_output(
f"bk changes -v {rev_arg} -d':GFILE:\\n' '{repo}'", shell=True
)
changed = changed.decode(sys.stdout.encoding)
changed = changed.split('\n')
# Remove the first line, it's an info message you can't remove
# (annoying)
del changed[0]
change_info = subprocess.check_output(
f"bk changes {rev_arg} -d':USER:\\n$each(:C:){{(:C:)\\n}}' '{repo}'", shell=True
)
change_info = change_info.decode(sys.stdout.encoding)
change_info = change_info.split('\n')
# Remove the first line, it's an info message you can't remove
# (annoying)
del change_info[0]
who = change_info.pop(0)
branch = opts['branch']
message = '\n'.join(change_info)
revision = opts.get('revision')
changes = {
'who': who,
'branch': branch,
'files': changed,
'comments': message,
'revision': revision,
}
if opts.get('category'):
changes['category'] = opts.get('category')
return changes
def sendChanges(self, opts, changes):
pbcf = pb.PBClientFactory()
reactor.connectTCP(opts['bbserver'], int(opts['bbport']), pbcf)
d = pbcf.login(credentials.UsernamePassword('change', 'changepw'))
d.addCallback(self.sendAllChanges, changes)
return d
def sendAllChanges(self, remote, changes):
dl = remote.callRemote('addChange', changes)
return dl
def run(self):
opts = Options()
try:
opts.parseOptions()
if not opts['branch']:
print("You must supply a branch with -b or --branch.")
sys.exit(1)
except usage.error as ue:
print(opts)
print(f"{sys.argv[0]}: {ue}")
sys.exit()
changes = self.getChanges(opts)
if opts['dryrun']:
for k in changes.keys():
print("[%10s]: %s" % (k, changes[k]))
print("*NOT* sending any changes")
return
d = self.sendChanges(opts, changes)
def quit(*why):
print("quitting! because", why)
reactor.stop()
@d.addErrback
def failed(f):
print(f"FAILURE: {f}")
reactor.stop()
d.addCallback(quit, "SUCCESS")
reactor.callLater(60, quit, "TIMEOUT")
reactor.run()
if __name__ == '__main__':
s = ChangeSender()
s.run()
| 4,757 | Python | .py | 129 | 29.062016 | 97 | 0.592641 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
5,020 | buildbot_cvs_mail.py | buildbot_buildbot/master/contrib/buildbot_cvs_mail.py | #!/usr/bin/env python
#
# Buildbot CVS Mail
#
# This script was derrived from syncmail,
# Copyright (c) 2002-2006 Barry Warsaw, Fred Drake, and contributors
#
# http://cvs-syncmail.cvs.sourceforge.net
#
# The script was re-written with the sole pupose of providing updates to
# Buildbot master by Andy Howell
#
# Options handling done right by djmitche
import optparse
import os
import re
import smtplib
import socket
import sys
import textwrap
import time
from email.utils import formataddr
from io import StringIO
"""
-t
--testing
Construct message and send to stdout for testing
The rest of the command line arguments are:
%%{sVv}
CVS %%{sVv} loginfo expansion. When invoked by CVS, this will be a single
string containing the files that are changing.
"""
__version__ = '$Revision: 1.3 $'
try:
import pwd
except ImportError:
# pwd is not available on Windows..
pwd = None
COMMASPACE = ', '
PROGRAM = sys.argv[0]
class SmtplibMock:
"""I stand in for smtplib for testing purposes."""
class SMTP:
"""I stand in for smtplib.SMTP connection for testing purposes.
I copy the message to stdout.
"""
def close(self):
pass
def connect(self, mailhost, mailport):
pass
def sendmail(self, address, email, msg):
sys.stdout.write(msg)
rfc822_specials_re = re.compile(r'[\(\)<>@,;:\\\"\.\[\]]')
def quotename(name):
if name and rfc822_specials_re.search(name):
return '"{}"'.format(name.replace('"', '\\"'))
else:
return name
def send_mail(options):
# Create the smtp connection to the localhost
conn = options.smtplib.SMTP()
conn.connect(options.mailhost, options.mailport)
if pwd:
pwinfo = pwd.getpwuid(os.getuid())
user = pwinfo[0]
name = pwinfo[4]
else:
user = 'cvs'
name = 'CVS'
domain = options.fromhost
if not domain:
# getfqdn is not good for use in unit tests
if options.amTesting:
domain = 'testing.com'
else:
domain = socket.getfqdn()
address = f'{user}@{domain}'
s = StringIO()
datestamp = time.strftime('%a, %d %b %Y %H:%M:%S +0000', time.gmtime(time.time()))
fileList = ' '.join(map(str, options.files))
vars = {
'author': formataddr((name, address)),
'email': options.email,
'subject': f'cvs update for project {options.project}',
'version': __version__,
'date': datestamp,
}
print(
'''\
From: {author}
To: {email}'''.format(**vars),
file=s,
)
if options.replyto:
print(f'Reply-To: {options.replyto}', file=s)
print(
'''\
Subject: {subject}
Date: {date}
X-Mailer: Python buildbot-cvs-mail {version}
'''.format(**vars),
file=s,
)
print(f'Cvsmode: {options.cvsmode}', file=s)
print(f'Category: {options.category}', file=s)
print(f'CVSROOT: {options.cvsroot}', file=s)
print(f'Files: {fileList}', file=s)
if options.path:
print(f'Path: {options.path}', file=s)
print(f'Project: {options.project}', file=s)
cvs_input = sys.stdin.read()
# On Python 2, sys.stdin.read() returns bytes, but
# on Python 3, it returns unicode str.
if isinstance(cvs_input, bytes):
cvs_input = cvs_input.decode("utf-8")
s.write(cvs_input)
print('', file=s)
conn.sendmail(address, options.email, s.getvalue())
conn.close()
def fork_and_send_mail(options):
# cannot wait for child process or that will cause parent to retain cvs
# lock for too long. Urg!
if not os.fork():
# in the child
# give up the lock you cvs thang!
time.sleep(2)
send_mail(options)
os._exit(0)
description = """
This script is used to provide email notifications of changes to the CVS
repository to a buildbot master. It is invoked via a CVS loginfo file (see
$CVSROOT/CVSROOT/loginfo). See the Buildbot manual for more information.
"""
usage = "%prog [options] %{sVv}"
parser = optparse.OptionParser(
description=description, usage=usage, add_help_option=True, version=__version__
)
parser.add_option(
"-C",
"--category",
dest='category',
metavar="CAT",
help=textwrap.dedent("""\
Category for change. This becomes the Change.category attribute, which
can be used within the buildmaster to filter changes.
"""),
)
parser.add_option(
"-c",
"--cvsroot",
dest='cvsroot',
metavar="PATH",
help=textwrap.dedent("""\
CVSROOT for use by buildbot workers to checkout code.
This becomes the Change.repository attribute.
Exmaple: :ext:myhost:/cvsroot
"""),
)
parser.add_option(
"-e",
"--email",
dest='email',
metavar="EMAIL",
help=textwrap.dedent("""\
Email address of the buildbot.
"""),
)
parser.add_option(
"-f",
"--fromhost",
dest='fromhost',
metavar="HOST",
help=textwrap.dedent("""\
The hostname that email messages appear to be coming from. The From:
header of the outgoing message will look like user@hostname. By
default, hostname is the machine's fully qualified domain name.
"""),
)
parser.add_option(
"-m",
"--mailhost",
dest='mailhost',
metavar="HOST",
default="localhost",
help=textwrap.dedent("""\
The hostname of an available SMTP server. The default is
'localhost'.
"""),
)
parser.add_option(
"--mailport",
dest='mailport',
metavar="PORT",
default=25,
type="int",
help=textwrap.dedent("""\
The port number of SMTP server. The default is '25'.
"""),
)
parser.add_option(
"-q",
"--quiet",
dest='verbose',
action="store_false",
default=True,
help=textwrap.dedent("""\
Don't print as much status to stdout.
"""),
)
parser.add_option(
"-p",
"--path",
dest='path',
metavar="PATH",
help=textwrap.dedent("""\
The path for the files in this update. This comes from the %p parameter
in loginfo for CVS version 1.12.x. Do not use this for CVS version 1.11.x
"""),
)
parser.add_option(
"-P",
"--project",
dest='project',
metavar="PROJ",
help=textwrap.dedent("""\
The project for the source. Often set to the CVS module being modified. This becomes
the Change.project attribute.
"""),
)
parser.add_option(
"-R",
"--reply-to",
dest='replyto',
metavar="ADDR",
help=textwrap.dedent("""\
Add a "Reply-To: ADDR" header to the email message.
"""),
)
parser.add_option("-t", "--testing", action="store_true", dest="amTesting", default=False)
parser.set_defaults(smtplib=smtplib)
def get_options():
options, args = parser.parse_args()
# rest of command line are the files.
options.files = args
if options.path is None:
options.cvsmode = '1.11'
else:
options.cvsmode = '1.12'
if options.cvsroot is None:
parser.error('--cvsroot is required')
if options.email is None:
parser.error('--email is required')
# set up for unit tests
if options.amTesting:
options.verbose = 0
options.smtplib = SmtplibMock
return options
# scan args for options
def main():
options = get_options()
if options.verbose:
print(f'Mailing {options.email}...')
print('Generating notification message...')
if options.amTesting:
send_mail(options)
else:
fork_and_send_mail(options)
if options.verbose:
print('Generating notification message... done.')
return 0
if __name__ == '__main__':
ret = main()
sys.exit(ret)
| 7,929 | Python | .py | 273 | 23.344322 | 96 | 0.619629 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
5,021 | check_buildbot.py | buildbot_buildbot/master/contrib/check_buildbot.py | #!/usr/bin/env python
import sys
import urllib
from future.utils import lrange
"""check_buildbot.py -H hostname -p httpport [options]
nagios check for buildbot.
requires that both metrics and web status enabled.
Both hostname and httpport must be set, or alternatively use url which
should be the full url to the metrics json resource"""
try:
import simplejson as json
except ImportError:
import json
OK, WARNING, CRITICAL, UNKNOWN = lrange(4)
STATUS_TEXT = ["OK", "Warning", "Critical", "Unknown"]
STATUS_CODES = dict(OK=OK, WARNING=WARNING, CRIT=CRITICAL)
def exit(level, msg):
print(f"{STATUS_TEXT[level]}: {msg}")
sys.exit(level)
def main():
from optparse import OptionParser
parser = OptionParser(__doc__)
parser.set_defaults(hostname=None, httpport=None, url=None, verbosity=0)
parser.add_option("-H", "--host", dest="hostname", help="Hostname")
parser.add_option("-p", "--port", dest="httpport", type="int", help="WebStatus port")
parser.add_option("-u", "--url", dest="url", help="Metrics url")
parser.add_option(
"-v", "--verbose", dest="verbosity", action="count", help="Increase verbosity"
)
options, args = parser.parse_args()
if options.hostname and options.httpport:
url = f"http://{options.hostname}:{options.httpport}/json/metrics"
elif options.url:
url = options.url
else:
exit(UNKNOWN, "You must specify both hostname and httpport, or just url")
try:
data = urllib.urlopen(url).read()
except Exception:
exit(CRITICAL, f"Error connecting to {url}")
try:
data = json.loads(data)
except ValueError:
exit(CRITICAL, f"Could not parse output of {url} as json")
if not data:
exit(WARNING, f"{url} returned null; are metrics disabled?")
alarms = data['alarms']
status = OK
messages = []
for alarm_name, alarm_state in alarms.items():
if options.verbosity >= 2:
messages.append(f"{alarm_name}: {alarm_state}")
try:
alarm_code = STATUS_CODES[alarm_state[0]]
except (KeyError, IndexError):
status = UNKNOWN
messages.append(f"{alarm_name} has unknown alarm state {alarm_state}")
continue
status = max(status, alarm_code)
if alarm_code > OK and options.verbosity < 2:
messages.append(f"{alarm_name}: {alarm_state}")
if not messages and status == OK:
messages.append("no problems")
exit(status, ";".join(messages))
if __name__ == '__main__':
main()
| 2,580 | Python | .py | 66 | 33.136364 | 89 | 0.657567 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
5,022 | run_maxq.py | buildbot_buildbot/master/contrib/run_maxq.py | #!/usr/bin/env jython
import glob
import sys
testdir = sys.argv[1]
orderfiles = glob.glob(testdir + '/*.tests')
# wee. just be glad I didn't make this one gigantic nested listcomp.
# anyway, this builds a once-nested list of files to test.
# open!
files = [open(fn) for fn in orderfiles]
# create prelim list of lists of files!
files = [f.readlines() for f in files]
# shwack newlines and filter out empties!
files = [filter(None, [fn.strip() for fn in fs]) for fs in files]
# prefix with testdir
files = [[testdir + '/' + fn.strip() for fn in fs] for fs in files]
print("Will run these tests:", files)
i = 0
for testlist in files:
print("===========================")
print("running tests from testlist", orderfiles[i])
print("---------------------------")
i = i + 1
for test in testlist:
print("running test", test)
try:
with open(test) as f:
exec(f.read(), globals().copy())
except Exception:
ei = sys.exc_info()
print("TEST FAILURE:", ei[1])
else:
print("SUCCESS")
| 1,101 | Python | .py | 32 | 29.28125 | 68 | 0.60114 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
5,023 | hgbuildbot.py | buildbot_buildbot/master/contrib/hgbuildbot.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 2007 Frederic Leroy <[email protected]>
# Portions Copyright 2016 Louis Opter <[email protected]>
#
#
# Documentation
# =============
#
# Mercurial "changegroup" hook that notifies Buildbot when a number of
# changsets is brought into the repository from elsewhere.
#
# Your Buildmaster needs to define a base ChangeHook, you should configure it
# behind a reverse proxy that does TLS and authentication for you and/or keep
# it behind a firewall. See the docs for more details:
#
# http://docs.buildbot.net/latest/manual/cfg-wwwhooks.html
#
# Copy this file to ".hg/hgbuildbot.py" in the repository that should notify
# Buildbot.
#
# Add it to the "[hooks]" section of ".hg/hgrc". Also add a "[hgbuildbot]"
# section with additional parameters, for example:
#
# [hooks]
# changegroup.buildbot = python:.hg/hgbuiltbot.py:hook
#
# [hgbuildbot]
# venv = /home/buildbot/.virtualenvs/builtbot/lib/python2.7/site-packages
# master = http://localhost:8020/change_hook/base
#
#
# Available parmeters
# -------------------
#
# venv
# The hook needs the Python package "requests". You can optionally point to
# virtualenv if it is not installed globally:
#
# Optional; default: None
#
# Example:
#
# venv = /path/to/venv/lib/pythonX.Y/site-packages
#
# master
# URLs of the Buildmaster(s) to notify.
# Can be a single entry or a comma-separated list.
#
# Mandatory.
#
# Examples:
#
# master = localhost:8020/change_hook/base
# master = bm1.example.org:8020/change_hook/base,bm2.example.org:8020/change_hook/base
#
# user
# User for connecting to the Buildmaster. (Basic auth will be used).
#
# Optional.
#
# passwd
# Password for connecting to the Buildmaster.
#
# Optional.
#
# branchtype
# The branchmodel you use: "inrepo" for named branches (managed by
# "hg branch") or "dirname" for directory based branches (the last component
# of the repository's directory will then be used as branch name).
#
# Optional; default: inrepo
#
# branch
# Explicitly specify a branchname instead of using the repo's basename when
# using "branchtype = dirname".
#
# Optional.
#
# baseurl
# Prefix for the repository URL sent to the Buildmaster. See below for
# details.
#
# Optional. The hook will also check the [web] section for this parameter.
#
# strip
# Strip as many slashes from the repo dir before appending it to baseurl.
# See below for details.
#
# Optional; default: 0; The hook will also check the [notify] section for
# this parameter.
#
# category
# Category to assign to all change sets.
#
# Optional.
#
# project
# Project that the repo belongs to.
#
# Optional.
#
# codebase
# Codebase name for the repo.
#
# Optional.
#
#
# Repository URLs
# ---------------
#
# The hook sends a repository URL to the Buildmasters. It can be used by
# schedulers (e.g., for filtering) and is also used in the webview to create
# a link to the corresponding changeset.
#
# By default, the absolute repository path (e.g., "/home/hg/repos/myrepo") will
# be used. The webview will in this case simply append the path to its own
# hostname in order to create a link to that change (e.g.,
# "http://localhost:8010/home/hg/repos/myrepo").
#
# You can alternatively strip some of the repo path's components and prepend
# a custom base URL instead. For example, if you want to create an URL like
# "https://code.company.com/myrepo", you must specify the following parameters:
#
# baseurl = https://code.company.com/
# strip = 4
#
# This would strip everything until (and including) the 4th "/" in the repo's
# path leaving only "myrepo" left. This would then be append to the base URL.
import json
import os
import os.path
import requests
from future.builtins import range
from mercurial.encoding import fromlocal
from mercurial.node import hex
from mercurial.node import nullid
def hook(ui, repo, hooktype, node=None, source=None, **kwargs):
if hooktype != 'changegroup':
ui.status(f'hgbuildbot: hooktype {hooktype} not supported.\n')
return
# Read config parameters
masters = ui.configlist('hgbuildbot', 'master')
if not masters:
ui.write(
'* You must add a [hgbuildbot] section to .hg/hgrc in '
'order to use the Buildbot hook\n'
)
return
# - virtualenv
venv = ui.config('hgbuildbot', 'venv', None)
if venv is not None:
if not os.path.isdir(venv):
ui.write(f'* Virtualenv "{venv}" does not exist.\n')
else:
activate_this = os.path.join(venv, "bin/activate_this.py")
with open(activate_this) as f:
activateThisScript = f.read()
exec(activateThisScript, dict(__file__=activate_this))
# - auth
username = ui.config('hgbuildbot', 'user')
password = ui.config('hgbuildbot', 'passwd')
if username is not None and password is not None:
auth = requests.auth.HTTPBasicAuth(username, password)
else:
auth = None
# - branch
branchtype = ui.config('hgbuildbot', 'branchtype', 'inrepo')
branch = ui.config('hgbuildbot', 'branch', None)
# - repo URL
baseurl = ui.config('hgbuildbot', 'baseurl', ui.config('web', 'baseurl', ''))
stripcount = int(ui.config('hgbuildbot', 'strip', ui.config('notify', 'strip', 0)))
# - category, project and codebase
category = ui.config('hgbuildbot', 'category', None)
project = ui.config('hgbuildbot', 'project', '')
codebase = ui.config('hgbuildbot', 'codebase', None)
# Process changesets
if branch is None and branchtype == 'dirname':
branch = os.path.basename(repo.root)
# If branchtype == 'inrepo', update "branch" for each commit later.
repository = strip(repo.root, stripcount)
repository = baseurl + repository
start = repo[node].rev()
end = len(repo)
for rev in range(start, end):
# send changeset
node = repo.changelog.node(rev)
log = repo.changelog.read(node)
manifest, user, (time, timezone), files, desc, extra = log
parents = [p for p in repo.changelog.parents(node) if p != nullid]
if branchtype == 'inrepo':
branch = extra['branch']
if branch:
branch = fromlocal(branch)
is_merge = len(parents) > 1
# merges don't always contain files, but at least one file is
# required by buildbot
if is_merge and not files:
files = ["merge"]
properties = {'is_merge': is_merge}
change = {
# 'master': master,
'branch': branch,
'revision': hex(node),
'comments': fromlocal(desc),
'files': json.dumps(files),
'author': fromlocal(user),
'category': category,
'when': time,
'properties': json.dumps(properties),
'repository': repository,
'project': project,
'codebase': codebase,
}
for master in masters:
response = requests.post(
master,
auth=auth,
params=change,
headers={"Content-Type": "application/x-www-form-urlencoded"},
)
if not response.ok:
ui.warn(
f"couldn't notify buildbot about {hex(node)[:12]}: {response.status_code} {response.reason}"
)
else:
ui.status(f"notified buildbot about {hex(node)[:12]}")
def strip(path, count):
"""Strip the count first slash of the path"""
# First normalize it
path = '/'.join(path.split(os.sep))
# and strip the *count* first slash
return path.split('/', count)[-1]
| 8,467 | Python | .py | 245 | 30.265306 | 112 | 0.667683 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
5,024 | viewcvspoll.py | buildbot_buildbot/master/contrib/viewcvspoll.py | #! /usr/bin/python
import os.path
import time
import MySQLdb # @UnresolvedImport
from twisted.cred import credentials
from twisted.internet import reactor
from twisted.python import log
from twisted.spread import pb
"""Based on the fakechanges.py contrib script"""
class ViewCvsPoller:
def __init__(self):
def _load_rc():
import user
ret = {}
for line in open(os.path.join(user.home, ".cvsblamerc")).readlines():
if line.find("=") != -1:
key, val = line.split("=")
ret[key.strip()] = val.strip()
return ret
# maybe add your own keys here db=xxx, user=xxx, passwd=xxx
self.cvsdb = MySQLdb.connect("cvs", **_load_rc())
# self.last_checkin = "2005-05-11" # for testing
self.last_checkin = time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime())
def get_changes(self):
changes = []
def empty_change():
return {'who': None, 'files': [], 'comments': None}
change = empty_change()
cursor = self.cvsdb.cursor()
cursor.execute(
f"""SELECT whoid, descid, fileid, dirid, branchid, \
ci_when FROM checkins WHERE ci_when>='{self.last_checkin}'"""
)
last_checkin = None
for whoid, descid, fileid, dirid, branchid, ci_when in cursor.fetchall():
if branchid != 1: # only head
continue
cursor.execute(f"""SELECT who from people where id={whoid}""")
who = cursor.fetchone()[0]
cursor.execute(f"""SELECT description from descs where id={descid}""")
desc = cursor.fetchone()[0]
cursor.execute(f"""SELECT file from files where id={fileid}""")
filename = cursor.fetchone()[0]
cursor.execute(f"""SELECT dir from dirs where id={dirid}""")
dirname = cursor.fetchone()[0]
if who == change["who"] and desc == change["comments"]:
change["files"].append(f"{dirname}/{filename}")
elif change["who"]:
changes.append(change)
change = empty_change()
else:
change["who"] = who
change["files"].append(f"{dirname}/{filename}")
change["comments"] = desc
if last_checkin is None or ci_when > last_checkin:
last_checkin = ci_when
if last_checkin:
self.last_checkin = last_checkin
return changes
poller = ViewCvsPoller()
def error(*args):
log.err()
reactor.stop()
def poll_changes(remote):
print("GET CHANGES SINCE", poller.last_checkin, end=' ')
changes = poller.get_changes()
for change in changes:
print(change["who"], "\n *", "\n * ".join(change["files"]))
change['src'] = 'cvs'
remote.callRemote('addChange', change).addErrback(error)
print()
reactor.callLater(60, poll_changes, remote)
factory = pb.PBClientFactory()
reactor.connectTCP("localhost", 9999, factory)
deferred = factory.login(credentials.UsernamePassword("change", "changepw"))
deferred.addCallback(poll_changes).addErrback(error)
reactor.run()
| 3,195 | Python | .py | 77 | 32.376623 | 82 | 0.591863 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
5,025 | coverage2text.py | buildbot_buildbot/master/contrib/coverage2text.py | #!/usr/bin/env python
import sys
from coverage import coverage
from coverage.results import Numbers
from coverage.summary import SummaryReporter
from twisted.python import usage
# this is an adaptation of the code behind "coverage report", modified to
# display+sortby "lines uncovered", which (IMHO) is more important of a
# metric than lines covered or percentage covered. Concentrating on the files
# with the most uncovered lines encourages getting the tree and test suite
# into a state that provides full line-coverage on all files.
# much of this code was adapted from coverage/summary.py in the 'coverage'
# distribution, and is used under their BSD license.
class Options(usage.Options):
optParameters = [
("sortby", "s", "uncovered", "how to sort: uncovered, covered, name"),
]
class MyReporter(SummaryReporter):
def report(self, outfile=None, sortby="uncovered"):
self.find_code_units(
None, ["/System", "/Library", "/usr/lib", "buildbot/test", "simplejson"]
)
# Prepare the formatting strings
max_name = max([len(cu.name) for cu in self.code_units] + [5])
fmt_name = "%%- %ds " % max_name
fmt_err = "%s %s: %s\n"
header1 = (fmt_name % "") + " Statements "
header2 = (fmt_name % "Name") + " Uncovered Covered"
fmt_coverage = fmt_name + "%9d %7d "
if self.branches:
header1 += " Branches "
header2 += " Found Excutd"
fmt_coverage += " %6d %6d"
header1 += " Percent"
header2 += " Covered"
fmt_coverage += " %7d%%"
if self.show_missing:
header1 += " "
header2 += " Missing"
fmt_coverage += " %s"
rule = "-" * len(header1) + "\n"
header1 += "\n"
header2 += "\n"
fmt_coverage += "\n"
if not outfile:
outfile = sys.stdout
# Write the header
outfile.write(header1)
outfile.write(header2)
outfile.write(rule)
total = Numbers()
total_uncovered = 0
lines = []
for cu in self.code_units:
try:
analysis = self.coverage._analyze(cu)
nums = analysis.numbers
uncovered = nums.n_statements - nums.n_executed
total_uncovered += uncovered
args = (cu.name, uncovered, nums.n_executed)
if self.branches:
args += (nums.n_branches, nums.n_executed_branches)
args += (nums.pc_covered,)
if self.show_missing:
args += (analysis.missing_formatted(),)
if sortby == "covered":
sortkey = nums.pc_covered
elif sortby == "uncovered":
sortkey = uncovered
else:
sortkey = cu.name
lines.append((sortkey, fmt_coverage % args))
total += nums
except Exception:
if not self.ignore_errors:
typ, msg = sys.exc_info()[:2]
outfile.write(fmt_err % (cu.name, typ.__name__, msg))
lines.sort()
if sortby in ("uncovered", "covered"):
lines.reverse()
for sortkey, line in lines:
outfile.write(line)
if total.n_files > 1:
outfile.write(rule)
args = ("TOTAL", total_uncovered, total.n_executed)
if self.branches:
args += (total.n_branches, total.n_executed_branches)
args += (total.pc_covered,)
if self.show_missing:
args += ("",)
outfile.write(fmt_coverage % args)
def report(o):
c = coverage()
c.load()
r = MyReporter(c, show_missing=False, ignore_errors=False)
r.report(sortby=o['sortby'])
if __name__ == '__main__':
o = Options()
o.parseOptions()
report(o)
| 3,981 | Python | .py | 100 | 29.54 | 84 | 0.552563 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
5,026 | github_buildbot.py | buildbot_buildbot/master/contrib/github_buildbot.py | #!/usr/bin/env python
"""
github_buildbot.py is based on git_buildbot.py. Last revised on 2014-02-20.
github_buildbot.py will determine the repository information from the JSON
HTTP POST it receives from github.com and build the appropriate repository.
If your github repository is private, you must add a ssh key to the github
repository for the user who initiated the build on the worker.
This version of github_buildbot.py parses v3 of the github webhook api, with the
"application.vnd.github.v3+json" payload. Configure *only* "push" and/or
"pull_request" events to trigger this webhook.
"""
import hmac
import logging
import os
import re
import sys
from hashlib import sha1
from optparse import OptionParser
from future.utils import iteritems
from twisted.cred import credentials
from twisted.internet import reactor
from twisted.spread import pb
from twisted.web import resource
from twisted.web import server
try:
import json
except ImportError:
import simplejson as json
ACCEPTED = 202
BAD_REQUEST = 400
INTERNAL_SERVER_ERROR = 500
OK = 200
class GitHubBuildBot(resource.Resource):
"""
GitHubBuildBot creates the webserver that responds to the GitHub Service
Hook.
"""
isLeaf = True
master = None
port = None
def render_POST(self, request):
"""
Responds only to POST events and starts the build process
:arguments:
request
the http request object
"""
# All responses are application/json
request.setHeader(b"Content-Type", b"application/json")
content = request.content.read()
# Verify the message if a secret was provided
#
# NOTE: We always respond with '400 BAD REQUEST' if we can't
# validate the message. This is done to prevent malicious
# requests from learning about why they failed to POST data
# to us.
if self.secret is not None:
signature = request.getHeader(b"X-Hub-Signature")
if signature is None:
logging.error("Rejecting request. Signature is missing.")
request.setResponseCode(BAD_REQUEST)
return json.dumps({"error": "Bad Request."})
try:
hash_type, hexdigest = signature.split(b"=")
except ValueError:
logging.error("Rejecting request. Bad signature format.")
request.setResponseCode(BAD_REQUEST)
return json.dumps({"error": "Bad Request."})
else:
# sha1 is hard coded into github's source code so it's
# unlikely this will ever change.
if hash_type != b"sha1":
logging.error("Rejecting request. Unexpected hash type.")
request.setResponseCode(BAD_REQUEST)
return json.dumps({"error": "Bad Request."})
mac = hmac.new(self.secret, msg=content, digestmod=sha1)
if mac.hexdigest() != hexdigest:
logging.error("Rejecting request. Hash mismatch.")
request.setResponseCode(BAD_REQUEST)
return json.dumps({"error": "Bad Request."})
event_type = request.getHeader(b"X-GitHub-Event")
logging.debug(b"X-GitHub-Event: " + event_type)
handler = getattr(self, 'handle_' + event_type.decode("ascii"), None)
if handler is None:
logging.info("Rejecting request. Received unsupported event %r.", event_type)
request.setResponseCode(BAD_REQUEST)
return json.dumps({"error": "Bad Request."})
try:
content_type = request.getHeader(b"Content-Type")
if content_type == b"application/json":
payload = json.loads(content)
elif content_type == b"application/x-www-form-urlencoded":
payload = json.loads(request.args["payload"][0])
else:
logging.info(
"Rejecting request. Unknown 'Content-Type', received %r", content_type
)
request.setResponseCode(BAD_REQUEST)
return json.dumps({"error": "Bad Request."})
logging.debug("Payload: " + payload)
repo = payload['repository']['full_name']
repo_url = payload['repository']['html_url']
changes = handler(payload, repo, repo_url)
self.send_changes(changes, request)
return server.NOT_DONE_YET
except Exception as e:
logging.exception(e)
request.setResponseCode(INTERNAL_SERVER_ERROR)
return json.dumps({"error": str(e)})
def process_change(self, change, branch, repo, repo_url):
files = change['added'] + change['removed'] + change['modified']
who = ""
if 'username' in change['author']:
who = change['author']['username']
else:
who = change['author']['name']
if 'email' in change['author']:
who = "{} <{}>".format(who, change['author']['email'])
comments = change['message']
if len(comments) > 1024:
trim = " ... (trimmed, commit message exceeds 1024 characters)"
comments = comments[: 1024 - len(trim)] + trim
info_change = {
'revision': change['id'],
'revlink': change['url'],
'who': who,
'comments': comments,
'repository': repo_url,
'files': files,
'project': repo,
'branch': branch,
}
if self.category:
info_change['category'] = self.category
return info_change
def handle_ping(self, *_):
return None
def handle_push(self, payload, repo, repo_url):
"""
Consumes the JSON as a python object and actually starts the build.
:arguments:
payload
Python Object that represents the JSON sent by GitHub Service
Hook.
"""
changes = None
refname = payload['ref']
if self.filter_push_branch:
if refname != f"refs/heads/{self.filter_push_branch}":
logging.info(
f"Ignoring refname '{refname}': Not a push to branch '{self.filter_push_branch}'"
)
return changes
m = re.match(r"^refs/(heads|tags)/(.+)$", refname)
if not m:
logging.info("Ignoring refname '%s': Not a branch or a tag", refname)
return changes
refname = m.group(2)
if payload['deleted'] is True:
logging.info("%r deleted, ignoring", refname)
else:
changes = []
for change in payload['commits']:
if (self.head_commit or m.group(1) == 'tags') and change['id'] != payload[
'head_commit'
]['id']:
continue
changes.append(self.process_change(change, refname, repo, repo_url))
return changes
def handle_pull_request(self, payload, repo, repo_url):
"""
Consumes the JSON as a python object and actually starts the build.
:arguments:
payload
Python Object that represents the JSON sent by GitHub Service
Hook.
"""
changes = None
branch = "refs/pull/{}/head".format(payload['number'])
if payload['action'] not in ("opened", "synchronize"):
logging.info("PR %r %r, ignoring", payload['number'], payload['action'])
return None
else:
changes = []
# Create a synthetic change
change = {
'id': payload['pull_request']['head']['sha'],
'message': payload['pull_request']['body'],
'timestamp': payload['pull_request']['updated_at'],
'url': payload['pull_request']['html_url'],
'author': {
'username': payload['pull_request']['user']['login'],
},
'added': [],
'removed': [],
'modified': [],
}
changes.append(self.process_change(change, branch, repo, repo_url))
return changes
def send_changes(self, changes, request):
"""
Submit the changes, if any
"""
if not changes:
logging.warning("No changes found")
request.setResponseCode(OK)
request.write(json.dumps({"result": "No changes found."}))
request.finish()
return
host, port = self.master.split(':')
port = int(port)
if self.auth is not None:
auth = credentials.UsernamePassword(*self.auth.split(":"))
else:
auth = credentials.Anonymous()
factory = pb.PBClientFactory()
deferred = factory.login(auth)
reactor.connectTCP(host, port, factory)
deferred.addErrback(self.connectFailed, request)
deferred.addCallback(self.connected, changes, request)
def connectFailed(self, error, request):
"""
If connection is failed. Logs the error.
"""
logging.error("Could not connect to master: %s", error.getErrorMessage())
request.setResponseCode(INTERNAL_SERVER_ERROR)
request.write(json.dumps({"error": "Failed to connect to buildbot master."}))
request.finish()
return error
def addChange(self, _, remote, changei, src='git'):
"""
Sends changes from the commit to the buildmaster.
"""
logging.debug("addChange %r, %r", remote, changei)
try:
change = changei.next()
except StopIteration:
remote.broker.transport.loseConnection()
return None
logging.info("New revision: %s", change['revision'][:8])
for key, value in iteritems(change):
logging.debug(" %s: %s", key, value)
change['src'] = src
deferred = remote.callRemote('addChange', change)
deferred.addCallback(self.addChange, remote, changei, src)
return deferred
def connected(self, remote, changes, request):
"""
Responds to the connected event.
"""
# By this point we've connected to buildbot so
# we don't really need to keep github waiting any
# longer
request.setResponseCode(ACCEPTED)
request.write(json.dumps({"result": "Submitting changes."}))
request.finish()
return self.addChange(None, remote, changes.__iter__())
def setup_options():
"""
The main event loop that starts the server and configures it.
"""
usage = "usage: %prog [options]"
parser = OptionParser(usage)
parser.add_option(
"-p",
"--port",
help="Port the HTTP server listens to for the GitHub " "Service Hook [default: %default]",
default=9001,
type=int,
dest="port",
)
parser.add_option(
"-m",
"--buildmaster",
help="Buildbot Master host and port. ie: localhost:9989 " "[default: %default]",
default="localhost:9989",
dest="buildmaster",
)
parser.add_option(
"--auth",
help="The username and password, separated by a colon, "
"to use when connecting to buildbot over the "
"perspective broker.",
default="change:changepw",
dest="auth",
)
parser.add_option(
"--head-commit", action="store_true", help="If set, only trigger builds for commits at head"
)
parser.add_option(
"--secret",
help="If provided then use the X-Hub-Signature header "
"to verify that the request is coming from "
"github. [default: %default]",
default=None,
dest="secret",
)
parser.add_option(
"-l",
"--log",
help="The absolute path, including filename, to save the "
"log to [default: %default]. This may also be "
"'stdout' indicating logs should output directly to "
"standard output instead.",
default="github_buildbot.log",
dest="log",
)
parser.add_option(
"-L",
"--level",
help="The logging level: debug, info, warn, error, " "fatal [default: %default]",
default='warn',
dest="level",
choices=("debug", "info", "warn", "error", "fatal"),
)
parser.add_option(
"-g",
"--github",
help="The github server. Changing this is useful if"
" you've specified a specific HOST handle in "
"~/.ssh/config for github [default: %default]",
default='github.com',
dest="github",
)
parser.add_option(
"--pidfile",
help="Write the process identifier (PID) to this "
"file on start. The file is removed on clean "
"exit. [default: %default]",
default=None,
dest="pidfile",
)
parser.add_option(
"--category", help="Category for the build change", default=None, dest="category"
)
parser.add_option(
"--filter-push-branch",
help="Only trigger builds for pushes to a given " "branch name.",
default=None,
dest="filter_push_branch",
)
(options, _) = parser.parse_args()
if options.auth is not None and ":" not in options.auth:
parser.error("--auth did not contain ':'")
if options.pidfile:
with open(options.pidfile, 'w') as f:
f.write(str(os.getpid()))
filename = options.log
log_format = "%(asctime)s - %(levelname)s - %(message)s"
if options.log != "stdout":
logging.basicConfig(
filename=filename, format=log_format, level=logging._levelNames[options.level.upper()]
)
else:
logging.basicConfig(
format=log_format,
handlers=[logging.StreamHandler(stream=sys.stdout)],
level=logging._levelNames[options.level.upper()],
)
return options
def run_hook(options):
github_bot = GitHubBuildBot()
github_bot.github = options.github
github_bot.master = options.buildmaster
github_bot.secret = options.secret
github_bot.auth = options.auth
github_bot.head_commit = options.head_commit
github_bot.category = options.category
github_bot.filter_push_branch = options.filter_push_branch
site = server.Site(github_bot)
reactor.listenTCP(options.port, site)
reactor.run()
def main():
options = setup_options()
run_hook(options)
if __name__ == '__main__':
main()
| 14,718 | Python | .py | 377 | 29.405836 | 101 | 0.588933 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
5,027 | generate_changelog.py | buildbot_buildbot/master/contrib/generate_changelog.py | #!/usr/bin/env python
#
# Copyright 2008
# Steve 'Ashcrow' Milner <[email protected]>
#
# This software may be freely redistributed under the terms of the GNU
# general public license.
#
# 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., 675 Mass Ave, Cambridge, MA 02139, USA.
import os
import sys
"""
Generates changelog information using git.
"""
__docformat__ = 'restructuredtext'
def print_err(msg):
"""
Wrapper to make printing to stderr nicer.
:Parameters:
- `msg`: the message to print.
"""
sys.stderr.write(msg)
sys.stderr.write('\n')
def usage():
"""
Prints out usage information to stderr.
"""
print_err(f'Usage: {sys.argv[0]} git-binary since')
print_err(f'Example: {sys.argv[0]} /usr/bin/git f5067523dfae9c7cdefc82' '8721ec593ac7be62db')
def main(args):
"""
Main entry point.
:Parameters:
- `args`: same as sys.argv[1:]
"""
# Make sure we have the arguments we need, else show usage
try:
git_bin = args[0]
since = args[1]
except IndexError:
usage()
return 1
if not os.access(git_bin, os.X_OK):
print_err(f'Can not access {git_bin}')
return 1
# Open a pipe and force the format
pipe = os.popen(git_bin + ' log --pretty="format:%ad %ae%n' ' * %s" ' + since + '..')
print(pipe.read())
pipe.close()
return 0
if __name__ == '__main__':
raise SystemExit(main(sys.argv[1:]))
| 1,570 | Python | .py | 54 | 24.777778 | 97 | 0.648 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
5,028 | fakechange.py | buildbot_buildbot/master/contrib/fakechange.py | #! /usr/bin/python
import os.path
import random
import subprocess
import sys
from twisted.cred import credentials
from twisted.internet import reactor
from twisted.python import log
from twisted.spread import pb
"""
This is an example of how to use the remote ChangeMaster interface, which is
a port that allows a remote program to inject Changes into the buildmaster.
The buildmaster can either pull changes in from external sources (see
buildbot.changes.changes.ChangeMaster.addSource for an example), or those
changes can be pushed in from outside. This script shows how to do the
pushing.
Changes are just dictionaries with three keys:
'who': a simple string with a username. Responsibility for this change will
be assigned to the named user (if something goes wrong with the build, they
will be blamed for it).
'files': a list of strings, each with a filename relative to the top of the
source tree.
'comments': a (multiline) string with checkin comments.
Each call to .addChange injects a single Change object: each Change
represents multiple files, all changed by the same person, and all with the
same checkin comments.
The port that this script connects to is the same 'workerPort' that the
workers and other debug tools use. The ChangeMaster service will only be
available on that port if 'change' is in the list of services passed to
buildbot.master.makeApp (this service is turned ON by default).
"""
def done(*args):
reactor.stop()
users = ('zaphod', 'arthur', 'trillian', 'marvin', 'sbfast')
dirs = ('src', 'doc', 'tests')
sources = ('foo.c', 'bar.c', 'baz.c', 'Makefile')
docs = ('Makefile', 'index.html', 'manual.texinfo')
def makeFilename():
d = random.choice(dirs)
if d in ('src', 'tests'):
f = random.choice(sources)
else:
f = random.choice(docs)
return os.path.join(d, f)
def send_change(remote):
who = random.choice(users)
if len(sys.argv) > 1:
files = sys.argv[1:]
else:
files = [makeFilename()]
comments = subprocess.check_output(["fortune"])
comments = comments.decode(sys.stdout.encoding)
change = {'who': who, 'files': files, 'comments': comments}
d = remote.callRemote('addChange', change)
d.addCallback(done)
print("{}: {}".format(who, " ".join(files)))
f = pb.PBClientFactory()
d = f.login(credentials.UsernamePassword("change", "changepw"))
reactor.connectTCP("10.0.24.125", 9989, f)
err = lambda f: (log.err(), reactor.stop())
d.addCallback(send_change).addErrback(err)
reactor.run()
| 2,531 | Python | .py | 62 | 37.951613 | 76 | 0.737638 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
5,029 | setup.py | buildbot_buildbot/worker/setup.py | #!/usr/bin/env python
#
# 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
"""
Standard setup script.
"""
import os
import sys
from setuptools import Command
from setuptools import setup
from setuptools.command.sdist import sdist
from buildbot_worker import version
BUILDING_WHEEL = bool("bdist_wheel" in sys.argv)
class our_install_data(Command):
def initialize_options(self):
self.install_dir = None
def finalize_options(self):
self.set_undefined_options(
'install',
('install_lib', 'install_dir'),
)
def run(self):
# ensure there's a buildbot_worker/VERSION file
fn = os.path.join(self.install_dir, 'buildbot_worker', 'VERSION')
with open(fn, 'w') as f:
f.write(version)
class our_sdist(sdist):
def make_release_tree(self, base_dir, files):
sdist.make_release_tree(self, base_dir, files)
# ensure there's a buildbot_worker/VERSION file
fn = os.path.join(base_dir, 'buildbot_worker', 'VERSION')
open(fn, 'w').write(version)
# ensure that NEWS has a copy of the latest release notes, copied from
# the master tree, with the proper version substituted
src_fn = os.path.join('..', 'master', 'docs', 'relnotes/index.rst')
with open(src_fn) as f:
src = f.read()
src = src.replace('|version|', version)
dst_fn = os.path.join(base_dir, 'NEWS')
with open(dst_fn, 'w') as f:
f.write(src)
setup_args = {
'name': "buildbot-worker",
'version': version,
'description': "Buildbot Worker Daemon",
'long_description': "See the 'buildbot' package for details",
'author': "Brian Warner",
'author_email': "[email protected]",
'maintainer': "Dustin J. Mitchell",
'maintainer_email': "[email protected]",
'url': "http://buildbot.net/",
'classifiers': [
'Development Status :: 5 - Production/Stable',
'Environment :: No Input/Output (Daemon)',
'Intended Audience :: Developers',
'License :: OSI Approved :: GNU General Public License v2 (GPLv2)',
'Topic :: Software Development :: Build Tools',
'Topic :: Software Development :: Testing',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
'Programming Language :: Python :: 3.9',
'Programming Language :: Python :: 3.10',
'Programming Language :: Python :: 3.11',
'Programming Language :: Python :: 3.12',
],
'packages': [
"buildbot_worker",
"buildbot_worker.util",
"buildbot_worker.commands",
"buildbot_worker.scripts",
"buildbot_worker.monkeypatches",
]
+ (
[]
if BUILDING_WHEEL
else [ # skip tests for wheels (save 40% of the archive)
"buildbot_worker.test",
"buildbot_worker.test.fake",
"buildbot_worker.test.unit",
"buildbot_worker.test.util",
]
),
# mention data_files, even if empty, so install_data is called and
# VERSION gets copied
'data_files': [("buildbot_worker", [])],
'package_data': {
'': [
'VERSION',
]
},
'cmdclass': {'install_data': our_install_data, 'sdist': our_sdist},
'entry_points': {
'console_scripts': [
'buildbot-worker=buildbot_worker.scripts.runner:run',
# this will also be shipped on non windows :-(
'buildbot_worker_windows_service=buildbot_worker.scripts.windows_service:HandleCommandLine',
]
},
}
# set zip_safe to false to force Windows installs to always unpack eggs
# into directories, which seems to work better --
# see http://buildbot.net/trac/ticket/907
if sys.platform == "win32":
setup_args['zip_safe'] = False
twisted_ver = ">= 21.2.0"
setup_args['install_requires'] = [
'twisted ' + twisted_ver,
]
setup_args['install_requires'] += [
'autobahn >= 0.16.0',
'msgpack >= 0.6.0',
]
# buildbot_worker_windows_service needs pywin32
if sys.platform == "win32":
setup_args['install_requires'].append('pywin32')
# Unit test hard dependencies.
test_deps = [
'psutil',
]
setup_args['tests_require'] = test_deps
setup_args['extras_require'] = {
'test': test_deps,
}
if '--help-commands' in sys.argv or 'trial' in sys.argv or 'test' in sys.argv:
setup_args['setup_requires'] = [
'setuptools_trial',
]
if os.getenv('NO_INSTALL_REQS'):
setup_args['install_requires'] = None
setup_args['extras_require'] = None
setup(**setup_args)
| 5,311 | Python | .py | 145 | 30.903448 | 104 | 0.645205 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
5,030 | pbutil.py | buildbot_buildbot/worker/buildbot_worker/pbutil.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
"""Base classes handy for use with PB clients."""
from twisted.application.internet import backoffPolicy
from twisted.cred import error
from twisted.internet import defer
from twisted.internet import reactor
from twisted.internet import task
from twisted.python import log
from twisted.spread import pb
from twisted.spread.pb import PBClientFactory
from buildbot_worker.compat import bytes2unicode
class AutoLoginPBFactory(PBClientFactory):
"""Factory for PB brokers that are managed through a ClientService.
Upon reconnect issued by ClientService this factory will re-login.
Instead of using f.getRootObject (which gives a Deferred that can only
be fired once), override the gotRootObject method. GR -> yes in case a user
would use that to be notified of root object appearances, it wouldn't
work. But getRootObject() can itself be used as much as one wants.
Instead of using the f.login (which is also one-shot), call
f.startLogin() with the credentials and client, and override the
gotPerspective method.
gotRootObject and gotPerspective will be called each time the object is
received (once per successful connection attempt).
If an authorization error occurs, failedToGetPerspective() will be
invoked.
"""
def __init__( # pylint: disable=wrong-spelling-in-docstring
self, retryPolicy=None, **kwargs
):
"""
@param retryPolicy: A policy configuring how long L{AutoLoginPBFactory} will
wait between attempts to connect to C{endpoint}.
@type retryPolicy: callable taking (the number of failed connection
attempts made in a row (L{int})) and returning the number of
seconds to wait before making another attempt.
"""
PBClientFactory.__init__(self, **kwargs)
self._timeoutForAttempt = backoffPolicy() if retryPolicy is None else retryPolicy
self._failedAttempts = 0
self._login_d = None
def clientConnectionMade(self, broker, retryPolicy=None):
PBClientFactory.clientConnectionMade(self, broker)
self._login_d = self.doLogin(self._root, broker)
self.gotRootObject(self._root)
def login(self, *args):
raise RuntimeError("login is one-shot: use startLogin instead")
def startLogin(self, credentials, client=None):
self._credentials = credentials
self._client = client
def doLogin(self, root, broker):
d = self._cbSendUsername(
root, self._credentials.username, self._credentials.password, self._client
)
d.addCallbacks(self.gotPerspective, self.failedToGetPerspective, errbackArgs=(broker,))
return d
def stopFactory(self):
if self._login_d:
self._login_d.cancel()
PBClientFactory.stopFactory(self)
# methods to override
def gotPerspective(self, perspective):
"""The remote avatar or perspective (obtained each time this factory
connects) is now available."""
def gotRootObject(self, root):
"""The remote root object (obtained each time this factory connects)
is now available. This method will be called each time the connection
is established and the object reference is retrieved."""
@defer.inlineCallbacks
def failedToGetPerspective(self, why, broker):
"""The login process failed, most likely because of an authorization
failure (bad password), but it is also possible that we lost the new
connection before we managed to send our credentials.
"""
log.msg("ReconnectingPBClientFactory.failedToGetPerspective")
# put something useful in the logs
if why.check(pb.PBConnectionLost):
log.msg("we lost the brand-new connection")
# fall through
elif why.check(error.UnauthorizedLogin):
log.msg("unauthorized login; check worker name and password")
# fall through
else:
log.err(why, 'While trying to connect:')
reactor.stop()
return
self._failedAttempts += 1
delay = self._timeoutForAttempt(self._failedAttempts)
log.msg(f"Scheduling retry {self._failedAttempts} to getPerspective in {delay} seconds.")
# Delay the retry according to the backoff policy
try:
yield task.deferLater(reactor, delay, lambda: None)
except defer.CancelledError:
pass
# lose the current connection, which will trigger a retry
broker.transport.loseConnection()
def decode(data, encoding='utf-8', errors='strict'):
"""We need to convert a dictionary where keys and values
are bytes, to unicode strings. This happens when a
Python 2 master sends a dictionary back to a Python 3 worker.
"""
data_type = type(data)
if data_type == bytes:
return bytes2unicode(data, encoding, errors)
if data_type in (dict, list, tuple):
if data_type == dict:
data = data.items()
return data_type(map(decode, data))
return data
| 5,794 | Python | .py | 121 | 41.008264 | 97 | 0.708112 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
5,031 | bot.py | buildbot_buildbot/worker/buildbot_worker/bot.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.null import LocalWorker
from buildbot_worker.pb import Worker
__all__ = ['Worker', 'LocalWorker']
| 826 | Python | .py | 17 | 47.470588 | 79 | 0.788104 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
5,032 | msgpack.py | buildbot_buildbot/worker/buildbot_worker/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 WebSocketClientFactory
from autobahn.twisted.websocket import WebSocketClientProtocol
from autobahn.websocket.types import ConnectingRequest
from twisted.internet import defer
from twisted.python import log
from buildbot_worker.base import ProtocolCommandBase
from buildbot_worker.util import deferwaiter
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()
def remote_print(self, message):
log.msg(f"WorkerForBuilder.remote_print({self.name}): message from master: {message}")
class ProtocolCommandMsgpack(ProtocolCommandBase):
def __init__(
self,
unicode_encoding,
worker_basedir,
buffer_size,
buffer_timeout,
max_line_length,
newline_re,
builder_is_running,
on_command_complete,
protocol,
command_id,
command,
args,
):
ProtocolCommandBase.__init__(
self,
unicode_encoding,
worker_basedir,
buffer_size,
buffer_timeout,
max_line_length,
newline_re,
builder_is_running,
on_command_complete,
None,
command,
command_id,
args,
)
self.protocol = protocol
def protocol_args_setup(self, command, args):
if "want_stdout" in args:
if args["want_stdout"]:
args["want_stdout"] = 1
else:
args["want_stdout"] = 0
if "want_stderr" in args:
if args["want_stderr"]:
args["want_stderr"] = 1
else:
args["want_stderr"] = 0
# to silence the ValueError in class Command() init
if (command in ("upload_directory", "upload_file")) and 'writer' not in args:
args['writer'] = None
if command == "download_file" and 'reader' not in args:
args['reader'] = None
def protocol_send_update_message(self, message):
d = self.protocol.get_message_result({
'op': 'update',
'args': message,
'command_id': self.command_id,
})
d.addErrback(self._ack_failed, "ProtocolCommandBase.send_update")
def protocol_notify_on_disconnect(self):
pass
@defer.inlineCallbacks
def protocol_complete(self, failure):
d_update = self.flush_command_output()
if failure is not None:
failure = str(failure)
d_complete = self.protocol.get_message_result({
'op': 'complete',
'args': failure,
'command_id': self.command_id,
})
yield d_update
yield d_complete
# Returns a Deferred
def protocol_update_upload_file_close(self, writer):
return self.protocol.get_message_result({
'op': 'update_upload_file_close',
'command_id': self.command_id,
})
# Returns a Deferred
def protocol_update_upload_file_utime(self, writer, access_time, modified_time):
return self.protocol.get_message_result({
'op': 'update_upload_file_utime',
'access_time': access_time,
'modified_time': modified_time,
'command_id': self.command_id,
})
# Returns a Deferred
def protocol_update_upload_file_write(self, writer, data):
return self.protocol.get_message_result({
'op': 'update_upload_file_write',
'args': data,
'command_id': self.command_id,
})
# Returns a Deferred
def protocol_update_upload_directory(self, writer):
return self.protocol.get_message_result({
'op': 'update_upload_directory_unpack',
'command_id': self.command_id,
})
# Returns a Deferred
def protocol_update_upload_directory_write(self, writer, data):
return self.protocol.get_message_result({
'op': 'update_upload_directory_write',
'args': data,
'command_id': self.command_id,
})
# Returns a Deferred
def protocol_update_read_file_close(self, reader):
return self.protocol.get_message_result({
'op': 'update_read_file_close',
'command_id': self.command_id,
})
# Returns a Deferred
def protocol_update_read_file(self, reader, length):
return self.protocol.get_message_result({
'op': 'update_read_file',
'length': length,
'command_id': self.command_id,
})
class ConnectionLostError(Exception):
pass
class BuildbotWebSocketClientProtocol(WebSocketClientProtocol):
debug = True
def __init__(self):
super().__init__()
self.seq_num_to_waiters_map = {}
self._deferwaiter = deferwaiter.DeferWaiter()
def onConnect(self, response):
if self.debug:
log.msg(f"Server connected: {response.peer}")
def onConnecting(self, transport_details):
if self.debug:
log.msg(f"Connecting; transport details: {transport_details}")
auth_header = encode_http_authorization_header(self.factory.name, self.factory.password)
return ConnectingRequest(
host=self.factory.host,
port=self.factory.port,
resource=self.factory.resource,
headers={"Authorization": auth_header},
useragent=self.factory.useragent,
origin=self.factory.origin,
protocols=self.factory.protocols,
)
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')
def onOpen(self):
if self.debug:
log.msg("WebSocket connection open.")
self.seq_number = 0
def call_print(self, msg):
is_exception = False
try:
self.contains_msg_key(msg, ('message',))
self.factory.buildbot_bot.remote_print(msg['message'])
result = None
except Exception as e:
is_exception = True
result = str(e)
self.send_response_msg(msg, result, is_exception)
def call_keepalive(self, msg):
result = None
is_exception = False
try:
if self.debug:
log.msg("Connection keepalive confirmed.")
except Exception:
pass
self.send_response_msg(msg, result, is_exception)
@defer.inlineCallbacks
def call_get_worker_info(self, msg):
is_exception = False
try:
result = yield self.factory.buildbot_bot.remote_getWorkerInfo()
except Exception as e:
is_exception = True
result = str(e)
self.send_response_msg(msg, result, is_exception)
def call_set_worker_settings(self, msg):
is_exception = False
try:
self.contains_msg_key(msg, ('args',))
for setting in ["buffer_size", "buffer_timeout", "newline_re", "max_line_length"]:
if setting not in msg["args"]:
raise KeyError('message did not contain obligatory settings for worker')
self.factory.buildbot_bot.buffer_size = msg["args"]["buffer_size"]
self.factory.buildbot_bot.buffer_timeout = msg["args"]["buffer_timeout"]
self.factory.buildbot_bot.newline_re = msg["args"]["newline_re"]
self.factory.buildbot_bot.max_line_length = msg["args"]["max_line_length"]
result = None
except Exception as e:
is_exception = True
result = str(e)
self.send_response_msg(msg, result, is_exception)
@defer.inlineCallbacks
def call_start_command(self, msg):
is_exception = False
try:
self.contains_msg_key(msg, ('command_id', 'command_name', 'args'))
# send an instance, on which get_message_result will be called
yield self.factory.buildbot_bot.start_command(
self, msg['command_id'], msg['command_name'], msg['args']
)
result = None
except Exception as e:
is_exception = True
result = str(e)
self.send_response_msg(msg, result, is_exception)
@defer.inlineCallbacks
def call_shutdown(self, msg):
is_exception = False
try:
yield self.factory.buildbot_bot.remote_shutdown()
result = None
except Exception as e:
is_exception = True
result = str(e)
self.send_response_msg(msg, result, is_exception)
@defer.inlineCallbacks
def call_interrupt_command(self, msg):
is_exception = False
try:
self.contains_msg_key(msg, ('command_id', 'why'))
# send an instance, on which get_message_result will be called
yield self.factory.buildbot_bot.interrupt_command(msg['command_id'], msg['why'])
result = None
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_worker_to_master_msg(dict_output)
payload = msgpack.packb(dict_output)
self.sendMessage(payload, isBinary=True)
def onMessage(self, payload, isBinary):
if not isBinary:
log.msg('Message type form master unsupported')
return
msg = msgpack.unpackb(payload, raw=False)
self.maybe_log_master_to_worker_msg(msg)
if 'seq_number' not in msg or 'op' not in msg:
log.msg(f'Invalid message from master: {msg}')
return
if msg['op'] == "print":
self._deferwaiter.add(self.call_print(msg))
elif msg['op'] == "keepalive":
self._deferwaiter.add(self.call_keepalive(msg))
elif msg['op'] == "set_worker_settings":
self._deferwaiter.add(self.call_set_worker_settings(msg))
elif msg['op'] == "get_worker_info":
self._deferwaiter.add(self.call_get_worker_info(msg))
elif msg['op'] == "start_command":
self._deferwaiter.add(self.call_start_command(msg))
elif msg['op'] == "shutdown":
self._deferwaiter.add(self.call_shutdown(msg))
elif msg['op'] == "interrupt_command":
self._deferwaiter.add(self.call_interrupt_command(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, "Command {} does not exist.".format(msg['op']), is_exception=True
)
@defer.inlineCallbacks
def get_message_result(self, msg):
msg['seq_number'] = self.seq_number
self.maybe_log_worker_to_master_msg(msg)
msg = msgpack.packb(msg)
d = defer.Deferred()
self.seq_num_to_waiters_map[self.seq_number] = d
self.seq_number = self.seq_number + 1
self.sendMessage(msg, isBinary=True)
res1 = yield d
return res1
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 seq_number in self.seq_num_to_waiters_map:
self.seq_num_to_waiters_map[seq_number].errback(ConnectionLostError("Connection lost"))
self.seq_num_to_waiters_map.clear()
class BuildbotWebSocketClientFactory(WebSocketClientFactory):
def waitForCompleteShutdown(self):
pass
| 13,806 | Python | .py | 337 | 31.531157 | 99 | 0.615844 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
5,033 | pb.py | buildbot_buildbot/worker/buildbot_worker/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
import os.path
import shutil
import signal
from typing import TYPE_CHECKING
from twisted.application import service
from twisted.application.internet import ClientService
from twisted.application.internet import backoffPolicy
from twisted.cred import credentials
from twisted.internet import defer
from twisted.internet import reactor
from twisted.internet import task
from twisted.internet.base import DelayedCall
from twisted.internet.endpoints import clientFromString
from twisted.python import log
from twisted.spread import pb
from buildbot_worker import util
from buildbot_worker.base import BotBase
from buildbot_worker.base import ProtocolCommandBase
from buildbot_worker.base import WorkerBase
from buildbot_worker.base import WorkerForBuilderBase
from buildbot_worker.compat import bytes2unicode
from buildbot_worker.compat import unicode2bytes
from buildbot_worker.msgpack import BuildbotWebSocketClientFactory
from buildbot_worker.msgpack import BuildbotWebSocketClientProtocol
from buildbot_worker.msgpack import ProtocolCommandMsgpack
from buildbot_worker.pbutil import AutoLoginPBFactory
from buildbot_worker.pbutil import decode
from buildbot_worker.tunnel import HTTPTunnelEndpoint
if TYPE_CHECKING:
from buildbot.master import BuildMaster
class UnknownCommand(pb.Error):
pass
class ProtocolCommandPb(ProtocolCommandBase):
def __init__(
self,
unicode_encoding,
worker_basedir,
basedir,
buffer_size,
buffer_timeout,
max_line_length,
newline_re,
builder_is_running,
on_command_complete,
on_lost_remote_step,
command,
command_id,
args,
command_ref,
):
self.basedir = basedir
self.command_ref = command_ref
ProtocolCommandBase.__init__(
self,
unicode_encoding,
worker_basedir,
buffer_size,
buffer_timeout,
max_line_length,
newline_re,
builder_is_running,
on_command_complete,
on_lost_remote_step,
command,
command_id,
args,
)
def protocol_args_setup(self, command, args):
if command == "mkdir":
args['paths'] = [os.path.join(self.basedir, args['dir'])]
del args['dir']
if command == "rmdir":
args['paths'] = []
if isinstance(args['dir'], list):
args['paths'] = [os.path.join(self.basedir, dir) for dir in args['dir']]
else:
args['paths'] = [os.path.join(self.basedir, args['dir'])]
del args['dir']
if command == "cpdir":
args['from_path'] = os.path.join(self.basedir, args['fromdir'])
args['to_path'] = os.path.join(self.basedir, args['todir'])
del args['fromdir']
del args['todir']
if command == "stat":
args['path'] = os.path.join(self.basedir, args.get('workdir', ''), args['file'])
del args['file']
if command == "glob":
args['path'] = os.path.join(self.basedir, args['path'])
if command == "listdir":
args['path'] = os.path.join(self.basedir, args['dir'])
del args['dir']
if command == "rmfile":
args['path'] = os.path.join(self.basedir, os.path.expanduser(args['path']))
if command == "shell":
args['workdir'] = os.path.join(self.basedir, args['workdir'])
if command == "uploadFile":
args["path"] = os.path.join(
self.basedir, args['workdir'], os.path.expanduser(args['workersrc'])
)
del args['workdir']
del args['workersrc']
if command == "uploadDirectory":
args['path'] = os.path.join(
self.basedir, args['workdir'], os.path.expanduser(args['workersrc'])
)
del args['workdir']
del args['workersrc']
if command == "downloadFile":
args['path'] = os.path.join(
self.basedir, args['workdir'], os.path.expanduser(args['workerdest'])
)
del args['workdir']
del args['workerdest']
def protocol_send_update_message(self, message):
# after self.buffer.append log message is of type:
# (key, (text, newline_indexes, line_times))
# only key and text is sent to master in PB protocol
# if message is not log, simply sends the value (e.g.[("rc", 0)])
for key, value in message:
if key in ['stdout', 'stderr', 'header']:
# the update[1]=0 comes from the leftover 'updateNum', which the
# master still expects to receive. Provide it to avoid significant
# interoperability issues between new workers and old masters.
update = [{key: value[0]}, 0]
elif key == "log":
logname, data = value
update = [{key: (logname, data[0])}, 0]
else:
update = [{key: value}, 0]
updates = [update]
d = self.command_ref.callRemote("update", updates)
d.addErrback(self._ack_failed, "ProtocolCommandBase.send_update")
def protocol_notify_on_disconnect(self):
self.command_ref.notifyOnDisconnect(self.on_lost_remote_step)
@defer.inlineCallbacks
def protocol_complete(self, failure):
d_update = self.flush_command_output()
self.command_ref.dontNotifyOnDisconnect(self.on_lost_remote_step)
d_complete = self.command_ref.callRemote("complete", failure)
yield d_update
yield d_complete
# Returns a Deferred
def protocol_update_upload_file_close(self, writer):
return writer.callRemote("close")
# Returns a Deferred
def protocol_update_upload_file_utime(self, writer, access_time, modified_time):
return writer.callRemote("utime", (access_time, modified_time))
# Returns a Deferred
def protocol_update_upload_file_write(self, writer, data):
return writer.callRemote('write', data)
# Returns a Deferred
def protocol_update_upload_directory(self, writer):
return writer.callRemote("unpack")
# Returns a Deferred
def protocol_update_upload_directory_write(self, writer, data):
return writer.callRemote('write', data)
# Returns a Deferred
def protocol_update_read_file_close(self, reader):
return reader.callRemote('close')
# Returns a Deferred
def protocol_update_read_file(self, reader, length):
return reader.callRemote('read', length)
class WorkerForBuilderPbLike(WorkerForBuilderBase):
ProtocolCommand = ProtocolCommandPb
"""This is the local representation of a single Builder: it handles a
single kind of build (like an all-warnings build). It has a name and a
home directory. The rest of its behavior is determined by the master.
"""
stopCommandOnShutdown = True
# remote is a ref to the Builder object on the master side, and is set
# when they attach. We use it to detect when the connection to the master
# is severed.
remote: BuildMaster | None = None
def __init__(
self, name, unicode_encoding, buffer_size, buffer_timeout, max_line_length, newline_re
):
# service.Service.__init__(self) # Service has no __init__ method
self.setName(name)
self.unicode_encoding = unicode_encoding
self.buffer_size = buffer_size
self.buffer_timeout = buffer_timeout
self.max_line_length = max_line_length
self.newline_re = newline_re
self.protocol_command = None
def __repr__(self):
return f"<WorkerForBuilder '{self.name}' at {id(self)}>"
@defer.inlineCallbacks
def setServiceParent(self, parent):
yield service.Service.setServiceParent(self, parent)
self.bot = self.parent
# note that self.parent will go away when the buildmaster's config
# file changes and this Builder is removed (possibly because it has
# been changed, so the Builder will be re-added again in a moment).
# This may occur during a build, while a step is running.
def setBuilddir(self, builddir):
assert self.parent
self.builddir = builddir
self.basedir = os.path.join(bytes2unicode(self.bot.basedir), bytes2unicode(self.builddir))
if not os.path.isdir(self.basedir):
os.makedirs(self.basedir)
def startService(self):
service.Service.startService(self)
if self.protocol_command:
self.protocol_command.builder_is_running = True
def stopService(self):
service.Service.stopService(self)
if self.protocol_command:
self.protocol_command.builder_is_running = False
if self.stopCommandOnShutdown:
self.stopCommand()
def remote_setMaster(self, remote):
self.remote = remote
self.remote.notifyOnDisconnect(self.lostRemote)
def remote_print(self, message):
log.msg(f"WorkerForBuilder.remote_print({self.name}): message from master: {message}")
def lostRemote(self, remote):
log.msg("lost remote")
self.remote = None
def lostRemoteStep(self, remotestep):
log.msg("lost remote step")
self.protocol_command.command_ref = None
if self.stopCommandOnShutdown:
self.stopCommand()
# the following are Commands that can be invoked by the master-side
# Builder
def remote_startBuild(self):
"""This is invoked before the first step of any new build is run. It
doesn't do much, but masters call it so it's still here."""
def remote_startCommand(self, command_ref, command_id, command, args):
"""
This gets invoked by L{buildbot.process.step.RemoteCommand.start}, as
part of various master-side BuildSteps, to start various commands
that actually do the build. I return nothing. Eventually I will call
.commandComplete() to notify the master-side RemoteCommand that I'm
done.
"""
command_id = decode(command_id)
command = decode(command)
args = decode(args)
if self.protocol_command:
log.msg("leftover command, dropping it")
self.stopCommand()
def on_command_complete():
self.protocol_command = None
self.protocol_command = self.ProtocolCommand(
self.unicode_encoding,
self.bot.basedir,
self.basedir,
self.buffer_size,
self.buffer_timeout,
self.max_line_length,
self.newline_re,
self.running,
on_command_complete,
self.lostRemoteStep,
command,
command_id,
args,
command_ref,
)
log.msg(f"(command {command_id}): startCommand:{command}")
self.protocol_command.protocol_notify_on_disconnect()
d = self.protocol_command.command.doStart()
d.addCallback(lambda res: None)
d.addBoth(self.protocol_command.command_complete)
return None
def remote_interruptCommand(self, command_id, why):
"""Halt the current step."""
log.msg(f"(command {command_id}): asked to interrupt: reason {why}")
if not self.protocol_command:
# TODO: just log it, a race could result in their interrupting a
# command that wasn't actually running
log.msg(" .. but none was running")
return
self.protocol_command.command.doInterrupt()
def stopCommand(self):
"""Make any currently-running command die, with no further status
output. This is used when the worker is shutting down or the
connection to the master has been lost. Interrupt the command,
silence it, and then forget about it."""
if not self.protocol_command:
return
log.msg(f"stopCommand: halting current command {self.protocol_command.command}")
self.protocol_command.command.doInterrupt()
self.protocol_command = None
class WorkerForBuilderPb(WorkerForBuilderPbLike, pb.Referenceable):
pass
class BotPbLike(BotBase):
WorkerForBuilder = WorkerForBuilderPbLike
@defer.inlineCallbacks
def remote_setBuilderList(self, wanted):
retval = {}
wanted_names = {name for (name, builddir) in wanted}
wanted_dirs = {builddir for (name, builddir) in wanted}
wanted_dirs.add('info')
for name, builddir in wanted:
b = self.builders.get(name, None)
if b:
if b.builddir != builddir:
log.msg(f"changing builddir for builder {name} from {b.builddir} to {builddir}")
b.setBuilddir(builddir)
else:
b = self.WorkerForBuilder(
name,
self.unicode_encoding,
self.buffer_size,
self.buffer_timeout,
self.max_line_length,
self.newline_re,
)
b.setServiceParent(self)
b.setBuilddir(builddir)
self.builders[name] = b
retval[name] = b
# disown any builders no longer desired
to_remove = list(set(self.builders.keys()) - wanted_names)
if to_remove:
yield defer.gatherResults([
defer.maybeDeferred(self.builders[name].disownServiceParent) for name in to_remove
])
# and *then* remove them from the builder list
for name in to_remove:
del self.builders[name]
# finally warn about any leftover dirs
for dir in os.listdir(self.basedir):
if os.path.isdir(os.path.join(self.basedir, dir)):
if dir not in wanted_dirs:
if self.delete_leftover_dirs:
log.msg(
f"Deleting directory '{dir}' that is not being "
"used by the buildmaster"
)
try:
shutil.rmtree(dir)
except OSError as e:
log.msg(f"Cannot remove directory '{dir}': {e}")
else:
log.msg(
f"I have a leftover directory '{dir}' that is not "
"being used by the buildmaster: you can delete "
"it now"
)
return retval
class BotPb(BotPbLike, pb.Referenceable):
WorkerForBuilder = WorkerForBuilderPb
class BotMsgpack(BotBase):
def __init__(self, basedir, unicode_encoding=None, delete_leftover_dirs=False):
BotBase.__init__(
self,
basedir,
unicode_encoding=unicode_encoding,
delete_leftover_dirs=delete_leftover_dirs,
)
self.protocol_commands = {}
@defer.inlineCallbacks
def startService(self):
yield BotBase.startService(self)
@defer.inlineCallbacks
def stopService(self):
yield BotBase.stopService(self)
# Make any currently-running command die, with no further status
# output. This is used when the worker is shutting down or the
# connection to the master has been lost.
for protocol_command in self.protocol_commands:
protocol_command.builder_is_running = False
log.msg(f"stopCommand: halting current command {protocol_command.command}")
protocol_command.command.doInterrupt()
self.protocol_commands = {}
def calculate_basedir(self, builddir):
return os.path.join(bytes2unicode(self.basedir), bytes2unicode(builddir))
def create_dirs(self, basedir):
if not os.path.isdir(basedir):
os.makedirs(basedir)
def start_command(self, protocol, command_id, command, args):
"""
This gets invoked by L{buildbot.process.step.RemoteCommand.start}, as
part of various master-side BuildSteps, to start various commands
that actually do the build. I return nothing. Eventually I will call
.commandComplete() to notify the master-side RemoteCommand that I'm
done.
"""
command = decode(command)
args = decode(args)
def on_command_complete():
del self.protocol_commands[command_id]
protocol_command = ProtocolCommandMsgpack(
self.unicode_encoding,
self.basedir,
self.buffer_size,
self.buffer_timeout,
self.max_line_length,
self.newline_re,
self.running,
on_command_complete,
protocol,
command_id,
command,
args,
)
self.protocol_commands[command_id] = protocol_command
log.msg(f" startCommand:{command} [id {command_id}]")
protocol_command.protocol_notify_on_disconnect()
d = protocol_command.command.doStart()
d.addCallback(lambda res: None)
d.addBoth(protocol_command.command_complete)
return None
def interrupt_command(self, command_id, why):
"""Halt the current step."""
log.msg(f"asked to interrupt current command: {why}")
if command_id not in self.protocol_commands:
# TODO: just log it, a race could result in their interrupting a
# command that wasn't actually running
log.msg(" .. but none was running")
return
d = self.protocol_commands[command_id].flush_command_output()
d.addErrback(
self.protocol_commands[command_id]._ack_failed,
"ProtocolCommandMsgpack.flush_command_output",
)
self.protocol_commands[command_id].command.doInterrupt()
class BotFactory(AutoLoginPBFactory):
"""The protocol factory for the worker.
This class implements the optional applicative keepalives, on top of
AutoLoginPBFactory.
'keepaliveInterval' serves two purposes. The first is to keep the
connection alive: it guarantees that there will be at least some
traffic once every 'keepaliveInterval' seconds, which may help keep an
interposed NAT gateway from dropping the address mapping because it
thinks the connection has been abandoned. This also gives the operating
system a chance to notice that the master has gone away, and inform us
of such (although this could take several minutes).
buildmaster host, port and maxDelay are accepted for backwards
compatibility only.
"""
keepaliveInterval: int | None = None # None = do not use keepalives
keepaliveTimer: DelayedCall | None = None
perspective: pb.Avatar | None = None
_reactor = reactor
def __init__(self, buildmaster_host, port, keepaliveInterval, maxDelay, retryPolicy=None):
AutoLoginPBFactory.__init__(self, retryPolicy=retryPolicy)
self.keepaliveInterval = keepaliveInterval
self.keepalive_lock = defer.DeferredLock()
self._shutting_down = False
# notified when shutdown is complete.
self._shutdown_notifier = util.Notifier()
self._active_keepalives = 0
def gotPerspective(self, perspective):
log.msg("Connected to buildmaster; worker is ready")
AutoLoginPBFactory.gotPerspective(self, perspective)
self.perspective = perspective
try:
perspective.broker.transport.setTcpKeepAlive(1)
except Exception:
log.msg("unable to set SO_KEEPALIVE")
if not self.keepaliveInterval:
self.keepaliveInterval = 10 * 60
if self.keepaliveInterval:
log.msg(f"sending application-level keepalives every {self.keepaliveInterval} seconds")
self.startTimers()
def startTimers(self):
assert self.keepaliveInterval
assert not self.keepaliveTimer
@defer.inlineCallbacks
def doKeepalive():
self._active_keepalives += 1
self.keepaliveTimer = None
self.startTimers()
yield self.keepalive_lock.acquire()
self.currentKeepaliveWaiter = defer.Deferred()
# Send the keepalive request. If an error occurs
# was already dropped, so just log and ignore.
log.msg("sending app-level keepalive")
try:
details = yield self.perspective.callRemote("keepalive")
log.msg("Master replied to keepalive, everything's fine")
self.currentKeepaliveWaiter.callback(details)
self.currentKeepaliveWaiter = None
except (pb.PBConnectionLost, pb.DeadReferenceError):
log.msg("connection already shut down when attempting keepalive")
except Exception as e:
log.err(e, "error sending keepalive")
finally:
self.keepalive_lock.release()
self._active_keepalives -= 1
self._checkNotifyShutdown()
self.keepaliveTimer = self._reactor.callLater(self.keepaliveInterval, doKeepalive)
def _checkNotifyShutdown(self):
if (
self._active_keepalives == 0
and self._shutting_down
and self._shutdown_notifier is not None
):
self._shutdown_notifier.notify(None)
self._shutdown_notifier = None
def stopTimers(self):
self._shutting_down = True
if self.keepaliveTimer:
# by cancelling the timer we are guaranteed that doKeepalive() won't be called again,
# as there's no interruption point between doKeepalive() beginning and call to
# startTimers()
self.keepaliveTimer.cancel()
self.keepaliveTimer = None
self._checkNotifyShutdown()
def stopFactory(self):
self.stopTimers()
AutoLoginPBFactory.stopFactory(self)
@defer.inlineCallbacks
def waitForCompleteShutdown(self):
# This function waits for a complete shutdown to happen. It's fired when all keepalives
# have been finished and there are no pending ones.
if self._shutdown_notifier is not None:
yield self._shutdown_notifier.wait()
class Worker(WorkerBase):
"""The service class to be instantiated from buildbot.tac
to just pass a connection string, set buildmaster_host and
port to None, and use connection_string.
maxdelay is deprecated in favor of using twisted's backoffPolicy.
"""
def __init__(
self,
buildmaster_host,
port,
name,
passwd,
basedir,
keepalive,
usePTY=None,
keepaliveTimeout=None,
umask=None,
maxdelay=None,
numcpus=None,
unicode_encoding=None,
protocol='pb',
useTls=None,
allow_shutdown=None,
maxRetries=None,
connection_string=None,
delete_leftover_dirs=False,
proxy_connection_string=None,
):
assert usePTY is None, "worker-side usePTY is not supported anymore"
assert connection_string is None or (buildmaster_host, port) == (
None,
None,
), "If you want to supply a connection string, then set host and port to None"
if protocol == 'pb':
bot_class = BotPb
elif protocol == 'msgpack_experimental_v7':
bot_class = BotMsgpack
else:
raise ValueError(f'Unknown protocol {protocol}')
WorkerBase.__init__(
self,
name,
basedir,
bot_class,
umask=umask,
unicode_encoding=unicode_encoding,
delete_leftover_dirs=delete_leftover_dirs,
)
if keepalive == 0:
keepalive = None
name = unicode2bytes(name, self.bot.unicode_encoding)
passwd = unicode2bytes(passwd, self.bot.unicode_encoding)
self.numcpus = numcpus
self.shutdown_loop = None
if allow_shutdown == 'signal':
if not hasattr(signal, 'SIGHUP'):
raise ValueError("Can't install signal handler")
elif allow_shutdown == 'file':
self.shutdown_file = os.path.join(basedir, 'shutdown.stamp')
self.shutdown_mtime = 0
self.allow_shutdown = allow_shutdown
def policy(attempt):
if maxRetries and attempt >= maxRetries:
reactor.stop()
return backoffPolicy()(attempt)
if protocol == 'pb':
bf = self.bf = BotFactory(
buildmaster_host, port, keepalive, maxdelay, retryPolicy=policy
)
bf.startLogin(credentials.UsernamePassword(name, passwd), client=self.bot)
elif protocol == 'msgpack_experimental_v7':
if connection_string is None:
ws_conn_string = f"ws://{buildmaster_host}:{port}"
else:
from urllib.parse import urlparse
parsed_url = urlparse(connection_string)
ws_conn_string = f"ws://{parsed_url.hostname}:{parsed_url.port}"
bf = self.bf = BuildbotWebSocketClientFactory(ws_conn_string)
bf.protocol = BuildbotWebSocketClientProtocol
self.bf.buildbot_bot = self.bot
self.bf.name = name
self.bf.password = passwd
else:
raise ValueError(f'Unknown protocol {protocol}')
def get_connection_string(host, port):
if useTls:
connection_type = 'tls'
else:
connection_type = 'tcp'
return '{}:host={}:port={}'.format(
connection_type,
host.replace(':', r'\:'), # escape ipv6 addresses
port,
)
assert not (proxy_connection_string and connection_string), (
"If you want to use HTTP tunneling, then supply build master "
"host and port rather than a connection string"
)
if proxy_connection_string:
log.msg("Using HTTP tunnel to connect through proxy")
proxy_endpoint = clientFromString(reactor, proxy_connection_string)
endpoint = HTTPTunnelEndpoint(buildmaster_host, port, proxy_endpoint)
if useTls:
from twisted.internet.endpoints import wrapClientTLS
from twisted.internet.ssl import optionsForClientTLS
contextFactory = optionsForClientTLS(hostname=buildmaster_host)
endpoint = wrapClientTLS(contextFactory, endpoint)
else:
if connection_string is None:
connection_string = get_connection_string(buildmaster_host, port)
endpoint = clientFromString(reactor, connection_string)
pb_service = ClientService(endpoint, bf, retryPolicy=policy)
self.addService(pb_service)
def startService(self):
WorkerBase.startService(self)
if self.allow_shutdown == 'signal':
log.msg("Setting up SIGHUP handler to initiate shutdown")
signal.signal(signal.SIGHUP, self._handleSIGHUP)
elif self.allow_shutdown == 'file':
log.msg(f"Watching {self.shutdown_file}'s mtime to initiate shutdown")
if os.path.exists(self.shutdown_file):
self.shutdown_mtime = os.path.getmtime(self.shutdown_file)
self.shutdown_loop = loop = task.LoopingCall(self._checkShutdownFile)
loop.start(interval=10)
@defer.inlineCallbacks
def stopService(self):
if self.shutdown_loop:
self.shutdown_loop.stop()
self.shutdown_loop = None
yield WorkerBase.stopService(self)
yield self.bf.waitForCompleteShutdown()
def _handleSIGHUP(self, *args):
log.msg("Initiating shutdown because we got SIGHUP")
return self.gracefulShutdown()
def _checkShutdownFile(self):
if (
os.path.exists(self.shutdown_file)
and os.path.getmtime(self.shutdown_file) > self.shutdown_mtime
):
log.msg(f"Initiating shutdown because {self.shutdown_file} was touched")
self.gracefulShutdown()
# In case the shutdown fails, update our mtime so we don't keep
# trying to shutdown over and over again.
# We do want to be able to try again later if the master is
# restarted, so we'll keep monitoring the mtime.
self.shutdown_mtime = os.path.getmtime(self.shutdown_file)
def gracefulShutdown(self):
"""Start shutting down"""
if not self.bf.perspective:
log.msg("No active connection, shutting down NOW")
reactor.stop()
return None
log.msg("Telling the master we want to shutdown after any running builds are finished")
d = self.bf.perspective.callRemote("shutdown")
def _shutdownfailed(err):
if err.check(AttributeError):
log.msg(
"Master does not support worker initiated shutdown. Upgrade master to 0.8.3"
"or later to use this feature."
)
else:
log.msg('callRemote("shutdown") failed')
log.err(err)
d.addErrback(_shutdownfailed)
return d
| 30,341 | Python | .py | 692 | 33.553468 | 100 | 0.629256 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
5,034 | interfaces.py | buildbot_buildbot/worker/buildbot_worker/interfaces.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
# disable pylint warnings triggered by interface definitions
# pylint: disable=no-self-argument
# pylint: disable=no-method-argument
# pylint: disable=inherit-non-class
from zope.interface import Interface
class IWorkerCommand(Interface):
"""This interface is implemented by all of the worker's Command
subclasses. It specifies how the worker can start, interrupt, and
query the various Commands running on behalf of the buildmaster."""
def __init__(builder, command_id, args):
"""Create the Command. 'builder' is a reference to the parent
buildbot_worker.base.WorkerForBuilderBase instance, which will be
used to send status updates (by calling builder.sendStatus).
'command_id' is a random string which helps correlate worker logs with
the master. 'args' is a dict of arguments that comes from the
master-side BuildStep, with contents that are specific to the
individual Command subclass.
This method is not intended to be subclassed."""
def setup(args):
"""This method is provided for subclasses to override, to extract
parameters from the 'args' dictionary. The default implementation does
nothing. It will be called from __init__"""
def start():
"""Begin the command, and return a Deferred.
While the command runs, it should send status updates to the
master-side BuildStep by calling self.sendStatus(status). The
'status' argument is typically a dict with keys like 'stdout',
'stderr', and 'rc'.
When the step completes, it should fire the Deferred (the results are
not used). If an exception occurs during execution, it may also
errback the deferred, however any reasonable errors should be trapped
and indicated with a non-zero 'rc' status rather than raising an
exception. Exceptions should indicate problems within the buildbot
itself, not problems in the project being tested.
"""
def interrupt():
"""This is called to tell the Command that the build is being stopped
and therefore the command should be terminated as quickly as
possible. The command may continue to send status updates, up to and
including an 'rc' end-of-command update (which should indicate an
error condition). The Command's deferred should still be fired when
the command has finally completed.
If the build is being stopped because the worker it shutting down or
because the connection to the buildmaster has been lost, the status
updates will simply be discarded. The Command does not need to be
aware of this.
Child shell processes should be killed. Simple ShellCommand classes
can just insert a header line indicating that the process will be
killed, then os.kill() the child."""
| 3,602 | Python | .py | 63 | 50.936508 | 79 | 0.731915 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
5,035 | null.py | buildbot_buildbot/worker/buildbot_worker/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 buildbot_worker.base import WorkerBase
from buildbot_worker.pb import BotPbLike
from buildbot_worker.pb import WorkerForBuilderPbLike
class WorkerForBuilderNull(WorkerForBuilderPbLike):
pass
class BotNull(BotPbLike):
WorkerForBuilder = WorkerForBuilderNull
class LocalWorker(WorkerBase):
def __init__(
self, name, basedir, umask=None, unicode_encoding=None, delete_leftover_dirs=False
):
super().__init__(
name,
basedir,
BotNull,
umask=umask,
unicode_encoding=unicode_encoding,
delete_leftover_dirs=delete_leftover_dirs,
)
@defer.inlineCallbacks
def startService(self):
# importing here to avoid dependency on buildbot master package
from buildbot.worker.protocols.null import Connection
yield WorkerBase.startService(self)
self.workername = self.name
conn = Connection(self)
# I don't have a master property, but my parent has.
master = self.parent.master
res = yield master.workers.newConnection(conn, self.name)
if res:
yield self.parent.attached(conn)
# detached() will be called automatically on connection disconnection which is
# invoked from the master side when the AbstarctWorker.stopService() is called.
| 2,098 | Python | .py | 48 | 37.75 | 91 | 0.726961 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
5,036 | __init__.py | buildbot_buildbot/worker/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
#
# Keep in sync with master/buildbot/__init__.py
#
# We can't put this method in utility modules, because they import dependency packages
#
import datetime
import os
import re
from subprocess import PIPE
from subprocess import STDOUT
from subprocess import Popen
def gitDescribeToPep440(version):
# git describe produce version in the form: v0.9.8-20-gf0f45ca
# where 20 is the number of commit since last release, and gf0f45ca is the short commit id
# preceded by 'g'
# we parse this a transform into a pep440 release version 0.9.9.dev20 (increment last digit
# band add dev before 20)
VERSION_MATCH = re.compile(
r'(?P<major>\d+)\.(?P<minor>\d+)\.(?P<patch>\d+)(\.post(?P<post>\d+))?(-(?P<dev>\d+))?(-g(?P<commit>.+))?'
)
v = VERSION_MATCH.search(version)
if v:
major = int(v.group('major'))
minor = int(v.group('minor'))
patch = int(v.group('patch'))
if v.group('dev'):
patch += 1
dev = int(v.group('dev'))
return f"{major}.{minor}.{patch}.dev{dev}"
if v.group('post'):
return "{}.{}.{}.post{}".format(major, minor, patch, v.group('post'))
return f"{major}.{minor}.{patch}"
return v
def mTimeVersion(init_file):
cwd = os.path.dirname(os.path.abspath(init_file))
m = 0
for root, _, files in os.walk(cwd):
for f in files:
m = max(os.path.getmtime(os.path.join(root, f)), m)
d = datetime.datetime.fromtimestamp(m, datetime.timezone.utc)
return d.strftime("%Y.%m.%d")
def getVersionFromArchiveId(git_archive_id='$Format:%ct %(describe:abbrev=10)$'):
"""Extract the tag if a source is from git archive.
When source is exported via `git archive`, the git_archive_id init value is modified
and placeholders are expanded to the "archived" revision:
%ct: committer date, UNIX timestamp
%(describe:abbrev=10): git-describe output, always abbreviating to 10 characters of commit ID.
e.g. v3.10.0-850-g5bf957f89
See man gitattributes(5) and git-log(1) (PRETTY FORMATS) for more details.
"""
# mangle the magic string to make sure it is not replaced by git archive
if not git_archive_id.startswith('$For' + 'mat:'):
# source was modified by git archive, try to parse the version from
# the value of git_archive_id
tstamp, _, describe_output = git_archive_id.strip().partition(' ')
if describe_output:
# archived revision is tagged, use the tag
return gitDescribeToPep440(describe_output)
# archived revision is not tagged, use the commit date
d = datetime.datetime.fromtimestamp(int(tstamp), datetime.timezone.utc)
return d.strftime('%Y.%m.%d')
return None
def getVersion(init_file):
"""
Return BUILDBOT_VERSION environment variable, content of VERSION file, git
tag or '0.0.0' meaning we could not find the version, but the output still has to be valid
"""
try:
return os.environ['BUILDBOT_VERSION']
except KeyError:
pass
try:
cwd = os.path.dirname(os.path.abspath(init_file))
fn = os.path.join(cwd, 'VERSION')
with open(fn) as f:
return f.read().strip()
except OSError:
pass
version = getVersionFromArchiveId()
if version is not None:
return version
try:
p = Popen(['git', 'describe', '--tags', '--always'], stdout=PIPE, stderr=STDOUT, cwd=cwd)
out = p.communicate()[0]
if (not p.returncode) and out:
v = gitDescribeToPep440(str(out))
if v:
return v
except OSError:
pass
try:
# if we really can't find the version, we use the date of modification of the most
# recent file
# docker hub builds cannot use git describe
return mTimeVersion(init_file)
except Exception:
# bummer. lets report something
return "0.0.0"
version = getVersion(__file__)
__version__ = version
| 4,777 | Python | .py | 114 | 35.526316 | 114 | 0.659694 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
5,037 | base.py | buildbot_buildbot/worker/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.
#
# Copyright Buildbot Team Members
from __future__ import annotations
import multiprocessing
import os.path
import socket
import sys
import time
from twisted.application import service
from twisted.internet import defer
from twisted.internet import reactor
from twisted.python import failure
from twisted.python import log
from twisted.spread import pb
import buildbot_worker
from buildbot_worker.commands import base
from buildbot_worker.commands import registry
from buildbot_worker.compat import bytes2unicode
from buildbot_worker.util import buffer_manager
from buildbot_worker.util import lineboundaries
class UnknownCommand(pb.Error):
pass
class ProtocolCommandBase:
def __init__(
self,
unicode_encoding,
worker_basedir,
buffer_size,
buffer_timeout,
max_line_length,
newline_re,
builder_is_running,
on_command_complete,
on_lost_remote_step,
command,
command_id,
args,
):
self.unicode_encoding = unicode_encoding
self.worker_basedir = worker_basedir
self.buffer_size = buffer_size
self.buffer_timeout = buffer_timeout
self.max_line_length = max_line_length
self.newline_re = newline_re
self.builder_is_running = builder_is_running
self.on_command_complete = on_command_complete
self.on_lost_remote_step = on_lost_remote_step
self.command_id = command_id
self.protocol_args_setup(command, args)
try:
factory = registry.getFactory(command)
except KeyError as e:
raise UnknownCommand(
f"(command {command_id}): unrecognized WorkerCommand '{command}'"
) from e
# .command points to a WorkerCommand instance, and is set while the step is running.
self.command = factory(self, command_id, args)
self._lbfs = {}
self.buffer = buffer_manager.BufferManager(
reactor, self.protocol_send_update_message, self.buffer_size, self.buffer_timeout
)
self.is_complete = False
def log_msg(self, msg):
log.msg(f"(command {self.command_id}): {msg}")
def split_lines(self, stream, text, text_time):
try:
return self._lbfs[stream].append(text, text_time)
except KeyError:
lbf = self._lbfs[stream] = lineboundaries.LineBoundaryFinder(
self.max_line_length, self.newline_re
)
return lbf.append(text, text_time)
def flush_command_output(self):
for key in sorted(list(self._lbfs)):
lbf = self._lbfs[key]
if key in ['stdout', 'stderr', 'header']:
whole_line = lbf.flush()
if whole_line is not None:
self.buffer.append(key, whole_line)
else: # custom logfile
logname = key
whole_line = lbf.flush()
if whole_line is not None:
self.buffer.append('log', (logname, whole_line))
self.buffer.flush()
return defer.succeed(None)
# sendUpdate is invoked by the Commands we spawn
def send_update(self, data):
if not self.builder_is_running:
# if builder is not running, do not send any status messages
return
if not self.is_complete:
# first element of the tuple is dictionary key, second element is value
data_time = time.time()
for key, value in data:
if key in ['stdout', 'stderr', 'header']:
whole_line = self.split_lines(key, value, data_time)
if whole_line is not None:
self.buffer.append(key, whole_line)
elif key == 'log':
logname, data = value
whole_line = self.split_lines(logname, data, data_time)
if whole_line is not None:
self.buffer.append('log', (logname, whole_line))
else:
self.buffer.append(key, value)
def _ack_failed(self, why, where):
self.log_msg(f"ProtocolCommandBase._ack_failed: {where}")
log.err(why) # we don't really care
# this is fired by the Deferred attached to each Command
def command_complete(self, failure):
if failure:
self.log_msg(f"ProtocolCommandBase.command_complete (failure) {self.command}")
log.err(failure)
# failure, if present, is a failure.Failure. To send it across
# the wire, we must turn it into a pb.CopyableFailure.
failure = pb.CopyableFailure(failure)
failure.unsafeTracebacks = True
else:
# failure is None
self.log_msg(f"ProtocolCommandBase.command_complete (success) {self.command}")
self.on_command_complete()
if not self.builder_is_running:
self.log_msg(" but we weren't running, quitting silently")
return
if not self.is_complete:
d = self.protocol_complete(failure)
d.addErrback(self._ack_failed, "ProtocolCommandBase.command_complete")
self.is_complete = True
class WorkerForBuilderBase(service.Service):
ProtocolCommand: type[ProtocolCommandBase] = ProtocolCommandBase
class BotBase(service.MultiService):
"""I represent the worker-side bot."""
name: str | None = "bot" # type: ignore[assignment]
WorkerForBuilder: type[WorkerForBuilderBase] = WorkerForBuilderBase
os_release_file = "/etc/os-release"
def __init__(self, basedir, unicode_encoding=None, delete_leftover_dirs=False):
service.MultiService.__init__(self)
self.basedir = basedir
self.numcpus = None
self.unicode_encoding = unicode_encoding or sys.getfilesystemencoding() or 'ascii'
self.delete_leftover_dirs = delete_leftover_dirs
self.builders = {}
# Don't send any data until at least buffer_size bytes have been collected
# or buffer_timeout elapsed
self.buffer_size = 64 * 1024
self.buffer_timeout = 5
self.max_line_length = 4096
self.newline_re = r'(\r\n|\r(?=.)|\033\[u|\033\[[0-9]+;[0-9]+[Hf]|\033\[2J|\x08+)'
# for testing purposes
def setOsReleaseFile(self, os_release_file):
self.os_release_file = os_release_file
def startService(self):
assert os.path.isdir(self.basedir)
service.MultiService.startService(self)
def remote_getCommands(self):
commands = {n: base.command_version for n in registry.getAllCommandNames()}
return commands
def remote_print(self, message):
log.msg("message from master:", message)
@staticmethod
def _read_os_release(os_release_file, props):
if not os.path.exists(os_release_file):
return
with open(os_release_file) as fin:
for line in fin:
line = line.strip("\r\n")
# as per man page: Lines beginning with "#" shall be ignored as comments.
if len(line) == 0 or line.startswith('#'):
continue
# parse key-values
key, value = line.split("=", 1)
if value:
key = f'os_{key.lower()}'
props[key] = value.strip('"')
def remote_getWorkerInfo(self):
"""This command retrieves data from the files in WORKERDIR/info/* and
sends the contents to the buildmaster. These are used to describe
the worker and its configuration, and should be created and
maintained by the worker administrator. They will be retrieved each
time the master-worker connection is established.
"""
files = {}
basedir = os.path.join(self.basedir, "info")
if os.path.isdir(basedir):
for f in os.listdir(basedir):
filename = os.path.join(basedir, f)
if os.path.isfile(filename):
with open(filename) as fin:
try:
files[f] = bytes2unicode(fin.read())
except UnicodeDecodeError:
log.err(failure.Failure(), f'error while reading file: {filename}')
self._read_os_release(self.os_release_file, files)
if not self.numcpus:
try:
self.numcpus = multiprocessing.cpu_count()
except NotImplementedError:
log.msg(
"warning: could not detect the number of CPUs for "
"this worker. Assuming 1 CPU."
)
self.numcpus = 1
files['environ'] = os.environ.copy()
files['system'] = os.name
files['basedir'] = self.basedir
files['numcpus'] = self.numcpus
files['version'] = self.remote_getVersion()
files['worker_commands'] = self.remote_getCommands()
files['delete_leftover_dirs'] = self.delete_leftover_dirs
return files
def remote_getVersion(self):
"""Send our version back to the Master"""
return buildbot_worker.version
def remote_shutdown(self):
log.msg("worker shutting down on command from master")
# there's no good way to learn that the PB response has been delivered,
# so we'll just wait a bit, in hopes the master hears back. Masters are
# resilient to workers dropping their connections, so there is no harm
# if this timeout is too short.
reactor.callLater(0.2, reactor.stop)
class WorkerBase(service.MultiService):
def __init__(
self,
name,
basedir,
bot_class,
umask=None,
unicode_encoding=None,
delete_leftover_dirs=False,
):
service.MultiService.__init__(self)
self.name = name
bot = bot_class(
basedir, unicode_encoding=unicode_encoding, delete_leftover_dirs=delete_leftover_dirs
)
bot.setServiceParent(self)
self.bot = bot
self.umask = umask
self.basedir = basedir
def startService(self):
log.msg(f"Starting Worker -- version: {buildbot_worker.version}")
if self.umask is not None:
os.umask(self.umask)
self.recordHostname(self.basedir)
service.MultiService.startService(self)
def recordHostname(self, basedir):
"Record my hostname in twistd.hostname, for user convenience"
log.msg("recording hostname in twistd.hostname")
filename = os.path.join(basedir, "twistd.hostname")
try:
hostname = os.uname()[1] # only on unix
except AttributeError:
# this tends to fail on non-connected hosts, e.g., laptops
# on planes
hostname = socket.getfqdn()
try:
with open(filename, "w") as f:
f.write(f"{hostname}\n")
except Exception:
log.msg("failed - ignoring")
| 11,747 | Python | .py | 273 | 33.098901 | 97 | 0.621586 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
5,038 | runprocess.py | buildbot_buildbot/worker/buildbot_worker/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
"""
Support for running 'shell commands'
"""
from __future__ import annotations
import datetime
import os
import pprint
import re
import shlex
import signal
import stat
import subprocess
import sys
import traceback
from codecs import getincrementaldecoder
from tempfile import NamedTemporaryFile
from twisted.internet import defer
from twisted.internet import error
from twisted.internet import protocol
from twisted.internet import reactor
from twisted.internet import task
from twisted.python import failure
from twisted.python import log
from twisted.python import runtime
from twisted.python.win32 import quoteArguments
from buildbot_worker import util
from buildbot_worker.compat import bytes2NativeString
from buildbot_worker.compat import bytes2unicode
from buildbot_worker.compat import unicode2bytes
from buildbot_worker.exceptions import AbandonChain
if runtime.platformType == 'posix':
from twisted.internet.process import Process
if runtime.platformType == 'win32':
import win32api
import win32con
import win32job
def win32_batch_quote(cmd_list, unicode_encoding='utf-8'):
# Quote cmd_list to a string that is suitable for inclusion in a
# Windows batch file. This is not quite the same as quoting it for the
# shell, as cmd.exe doesn't support the %% escape in interactive mode.
def escape_arg(arg):
arg = bytes2NativeString(arg, unicode_encoding)
arg = quoteArguments([arg])
# escape shell special characters
arg = re.sub(r'[@()^"<>&|]', r'^\g<0>', arg)
# prevent variable expansion
return arg.replace('%', '%%')
return ' '.join(map(escape_arg, cmd_list))
def shell_quote(cmd_list, unicode_encoding='utf-8'):
# attempt to quote cmd_list such that a shell will properly re-interpret
# it. The shlex module is only designed for UNIX;
#
# So:
# - use shlex.quote on UNIX, handling '' as a special case
# - use our own custom function on Windows
if isinstance(cmd_list, bytes):
cmd_list = bytes2unicode(cmd_list, unicode_encoding)
if runtime.platformType == 'win32':
return win32_batch_quote(cmd_list, unicode_encoding)
def quote(e):
if not e:
return '""'
e = bytes2unicode(e, unicode_encoding)
return shlex.quote(e)
return " ".join(quote(e) for e in cmd_list)
class LogFileWatcher:
POLL_INTERVAL = 2
def __init__(self, command, name, logfile, follow=False, poll=True):
self.command = command
self.name = name
self.logfile = logfile
decoderFactory = getincrementaldecoder(self.command.unicode_encoding)
self.logDecode = decoderFactory(errors='replace')
self.command.log_msg(f"LogFileWatcher created to watch {logfile}")
# we are created before the ShellCommand starts. If the logfile we're
# supposed to be watching already exists, record its size and
# ctime/mtime so we can tell when it starts to change.
self.old_logfile_stats = self.statFile()
self.started = False
# follow the file, only sending back lines
# added since we started watching
self.follow = follow
# every 2 seconds we check on the file again
self.poller = task.LoopingCall(self.poll) if poll else None
def start(self):
self.poller.start(self.POLL_INTERVAL).addErrback(self._cleanupPoll)
def _cleanupPoll(self, err):
log.err(err, msg="Polling error")
self.poller = None
def stop(self):
self.poll()
if self.poller is not None:
self.poller.stop()
if self.started:
self.f.close()
def statFile(self):
if os.path.exists(self.logfile):
s = os.stat(self.logfile)
return (s[stat.ST_CTIME], s[stat.ST_MTIME], s[stat.ST_SIZE])
return None
def poll(self):
if not self.started:
s = self.statFile()
if s == self.old_logfile_stats:
return # not started yet
if not s:
# the file was there, but now it's deleted. Forget about the
# initial state, clearly the process has deleted the logfile
# in preparation for creating a new one.
self.old_logfile_stats = None
return # no file to work with
self.f = open(self.logfile, "rb")
# if we only want new lines, seek to
# where we stat'd so we only find new
# lines
if self.follow:
self.f.seek(s[2], 0)
self.started = True
# Mac OS X and Linux differ in behaviour when reading from a file that has previously
# reached EOF. On Linux, any new data that has been appended to the file will be returned.
# On Mac OS X, the empty string will always be returned. Seeking to the current position
# in the file resets the EOF flag on Mac OS X and will allow future reads to work as
# intended.
self.f.seek(self.f.tell(), 0)
while True:
data = self.f.read(10000)
if not data:
return
decodedData = self.logDecode.decode(data)
self.command.addLogfile(self.name, decodedData)
if runtime.platformType == 'posix':
class ProcGroupProcess(Process):
"""Simple subclass of Process to also make the spawned process a process
group leader, so we can kill all members of the process group."""
def _setupChild(self, *args, **kwargs):
Process._setupChild(self, *args, **kwargs)
# this will cause the child to be the leader of its own process group;
# it's also spelled setpgrp() on BSD, but this spelling seems to work
# everywhere
os.setpgid(0, 0)
class RunProcessPP(protocol.ProcessProtocol):
debug = False
def __init__(self, command):
self.command = command
self.pending_stdin = b""
self.stdin_finished = False
self.killed = False
decoderFactory = getincrementaldecoder(self.command.unicode_encoding)
self.stdoutDecode = decoderFactory(errors='replace')
self.stderrDecode = decoderFactory(errors='replace')
def setStdin(self, data):
assert not self.connected
self.pending_stdin = data
def connectionMade(self):
if self.debug:
self.command.log_msg("RunProcessPP.connectionMade")
if self.command.useProcGroup:
if self.debug:
self.command.log_msg(f"pid {self.transport.pid} set as subprocess pgid")
self.transport.pgid = self.transport.pid
if self.pending_stdin:
if self.debug:
self.command.log_msg("writing to stdin")
self.transport.write(self.pending_stdin)
if self.debug:
self.command.log_msg("closing stdin")
self.transport.closeStdin()
def outReceived(self, data):
if self.debug:
self.command.log_msg("RunProcessPP.outReceived")
decodedData = self.stdoutDecode.decode(data)
self.command.addStdout(decodedData)
def errReceived(self, data):
if self.debug:
self.command.log_msg("RunProcessPP.errReceived")
decodedData = self.stderrDecode.decode(data)
self.command.addStderr(decodedData)
def processEnded(self, status_object):
if self.debug:
self.command.log_msg(f"RunProcessPP.processEnded {status_object}")
# status_object is a Failure wrapped around an
# error.ProcessTerminated or and error.ProcessDone.
# requires twisted >= 1.0.4 to overcome a bug in process.py
sig = status_object.value.signal
rc = status_object.value.exitCode
# sometimes, even when we kill a process, GetExitCodeProcess will still return
# a zero exit status. So we force it. See
# http://stackoverflow.com/questions/2061735/42-passed-to-terminateprocess-sometimes-getexitcodeprocess-returns-0
if self.killed and rc == 0:
self.command.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
self.command.finished(sig, rc)
class RunProcess:
"""
This is a helper class, used by worker commands to run programs in a child
shell.
"""
BACKUP_TIMEOUT = 5
interruptSignal = "KILL"
# For sending elapsed time:
startTime: datetime.datetime | None = None
elapsedTime: datetime.timedelta | None = None
# For scheduling future events
_reactor = reactor
# I wish we had easy access to CLOCK_MONOTONIC in Python:
# http://www.opengroup.org/onlinepubs/000095399/functions/clock_getres.html
# Then changes to the system clock during a run wouldn't effect the "elapsed
# time" results.
def __init__(
self,
command_id,
command,
workdir,
unicode_encoding,
send_update,
environ=None,
sendStdout=True,
sendStderr=True,
sendRC=True,
timeout=None,
maxTime=None,
max_lines=None,
sigtermTime=None,
initialStdin=None,
keepStdout=False,
keepStderr=False,
logEnviron=True,
logfiles=None,
usePTY=False,
useProcGroup=True,
):
"""
@param keepStdout: if True, we keep a copy of all the stdout text
that we've seen. This copy is available in
self.stdout, which can be read after the command
has finished.
@param keepStderr: same, for stderr
@param usePTY: true to use a PTY, false to not use a PTY.
@param useProcGroup: (default True) use a process group for non-PTY
process invocations
"""
if logfiles is None:
logfiles = {}
if isinstance(command, list):
def obfus(w):
if isinstance(w, tuple) and len(w) == 3 and w[0] == 'obfuscated':
return util.Obfuscated(w[1], w[2])
return w
command = [obfus(w) for w in command]
self.command_id = command
# We need to take unicode commands and arguments and encode them using
# the appropriate encoding for the worker. This is mostly platform
# specific, but can be overridden in the worker's buildbot.tac file.
#
# Encoding the command line here ensures that the called executables
# receive arguments as bytestrings encoded with an appropriate
# platform-specific encoding. It also plays nicely with twisted's
# spawnProcess which checks that arguments are regular strings or
# unicode strings that can be encoded as ascii (which generates a
# warning).
def to_bytes(cmd):
if isinstance(cmd, (tuple, list)):
for i, a in enumerate(cmd):
if isinstance(a, str):
cmd[i] = a.encode(unicode_encoding)
elif isinstance(cmd, str):
cmd = cmd.encode(unicode_encoding)
return cmd
self.command = to_bytes(util.Obfuscated.get_real(command))
self.fake_command = to_bytes(util.Obfuscated.get_fake(command))
self.sendStdout = sendStdout
self.sendStderr = sendStderr
self.sendRC = sendRC
self.logfiles = logfiles
self.workdir = workdir
self.unicode_encoding = unicode_encoding
self.send_update = send_update
self.process = None
self.line_count = 0
self.max_line_kill = False
if not os.path.exists(workdir):
os.makedirs(workdir)
if environ:
for key, v in environ.items():
if isinstance(v, list):
# Need to do os.pathsep translation. We could either do that
# by replacing all incoming ':'s with os.pathsep, or by
# accepting lists. I like lists better.
# If it's not a string, treat it as a sequence to be
# turned in to a string.
environ[key] = os.pathsep.join(environ[key])
if "PYTHONPATH" in environ:
environ['PYTHONPATH'] += os.pathsep + "${PYTHONPATH}"
# do substitution on variable values matching pattern: ${name}
p = re.compile(r'\${([0-9a-zA-Z_]*)}')
def subst(match):
return os.environ.get(match.group(1), "")
newenv = {}
for key in os.environ:
# setting a key to None will delete it from the worker
# environment
if key not in environ or environ[key] is not None:
newenv[key] = os.environ[key]
for key, v in environ.items():
if v is not None:
if not isinstance(v, str):
raise RuntimeError(
"'env' values must be strings or " f"lists; key '{key}' is incorrect"
)
newenv[key] = p.sub(subst, v)
self.environ = newenv
else: # not environ
self.environ = os.environ.copy()
self.initialStdin = to_bytes(initialStdin)
self.logEnviron = logEnviron
self.timeout = timeout
self.ioTimeoutTimer = None
self.sigtermTime = sigtermTime
self.maxTime = maxTime
self.max_lines = max_lines
self.maxTimeoutTimer = None
self.killTimer = None
self.keepStdout = keepStdout
self.keepStderr = keepStderr
self.job_object = None
assert usePTY in (
True,
False,
), f"Unexpected usePTY argument value: {usePTY!r}. Expected boolean."
self.usePTY = usePTY
# usePTY=True is a convenience for cleaning up all children and
# grandchildren of a hung command. Fall back to usePTY=False on systems
# and in situations where ptys cause problems. PTYs are posix-only,
# and for .closeStdin to matter, we must use a pipe, not a PTY
if runtime.platformType != "posix" or initialStdin is not None:
if self.usePTY:
self.send_update([('header', "WARNING: disabling usePTY for this command")])
self.usePTY = False
# use an explicit process group on POSIX, noting that usePTY always implies
# a process group.
if runtime.platformType != 'posix':
useProcGroup = False
elif self.usePTY:
useProcGroup = True
self.useProcGroup = useProcGroup
self.logFileWatchers = []
for name, filevalue in self.logfiles.items():
filename = filevalue
follow = False
# check for a dictionary of options
# filename is required, others are optional
if isinstance(filevalue, dict):
filename = filevalue['filename']
follow = filevalue.get('follow', False)
w = LogFileWatcher(self, name, os.path.join(self.workdir, filename), follow=follow)
self.logFileWatchers.append(w)
def log_msg(self, msg):
log.msg(f"(command {self.command_id}): {msg}")
def __repr__(self):
return f"<{self.__class__.__name__} '{self.fake_command}'>"
def start(self):
# return a Deferred which fires (with the exit code) when the command
# completes
if self.keepStdout:
self.stdout = ""
if self.keepStderr:
self.stderr = ""
self.deferred = defer.Deferred()
try:
self._startCommand()
except Exception as e:
log.err(failure.Failure(), "error in RunProcess._startCommand")
self.send_update([('stderr', f"error in RunProcess._startCommand ({e!s})\n")])
self.send_update([('stderr', traceback.format_exc())])
# pretend it was a shell error
self.deferred.errback(AbandonChain(-1, f'Got exception ({e!s})'))
return self.deferred
def _startCommand(self):
# ensure workdir exists
if not os.path.isdir(self.workdir):
os.makedirs(self.workdir)
self.log_msg("RunProcess._startCommand")
self.pp = RunProcessPP(self)
self.using_comspec = False
self.command = unicode2bytes(self.command, encoding=self.unicode_encoding)
if isinstance(self.command, bytes):
if runtime.platformType == 'win32':
# allow %COMSPEC% to have args
argv = os.environ['COMSPEC'].split()
if '/c' not in argv:
argv += ['/c']
argv += [self.command]
self.using_comspec = True
else:
# for posix, use /bin/sh. for other non-posix, well, doesn't
# hurt to try
argv = [b'/bin/sh', b'-c', self.command]
display = self.fake_command
else:
# On windows, CreateProcess requires an absolute path to the executable.
# When we call spawnProcess below, we pass argv[0] as the executable.
# So, for .exe's that we have absolute paths to, we can call directly
# Otherwise, we should run under COMSPEC (usually cmd.exe) to
# handle path searching, etc.
if runtime.platformType == 'win32' and not (
bytes2unicode(self.command[0], self.unicode_encoding).lower().endswith(".exe")
and os.path.isabs(self.command[0])
):
# allow %COMSPEC% to have args
argv = os.environ['COMSPEC'].split()
if '/c' not in argv:
argv += ['/c']
argv += list(self.command)
self.using_comspec = True
else:
argv = self.command
# Attempt to format this for use by a shell, although the process
# isn't perfect
display = shell_quote(self.fake_command, self.unicode_encoding)
display = bytes2unicode(display, self.unicode_encoding)
# $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, though..
if not self.environ.get('MACHTYPE', None) == 'i686-pc-msys':
self.environ['PWD'] = os.path.abspath(self.workdir)
# self.stdin is handled in RunProcessPP.connectionMade
self.log_msg(" " + display)
self.send_update([('header', display + "\n")])
# then comes the secondary information
msg = f" in dir {self.workdir}"
if self.timeout:
if self.timeout == 1:
unit = "sec"
else:
unit = "secs"
msg += f" (timeout {self.timeout} {unit})"
if self.maxTime:
if self.maxTime == 1:
unit = "sec"
else:
unit = "secs"
msg += f" (maxTime {self.maxTime} {unit})"
self.log_msg(" " + msg)
self.send_update([('header', msg + "\n")])
msg = f" watching logfiles {self.logfiles}"
self.log_msg(" " + msg)
self.send_update([('header', msg + "\n")])
# then the obfuscated command array for resolving unambiguity
msg = f" argv: {self.fake_command}"
self.log_msg(" " + msg)
self.send_update([('header', msg + "\n")])
# then the environment, since it sometimes causes problems
if self.logEnviron:
msg = " environment:\n"
env_names = sorted(self.environ.keys())
for name in env_names:
msg += f" {bytes2unicode(name, encoding=self.unicode_encoding)}={bytes2unicode(self.environ[name], encoding=self.unicode_encoding)}\n"
self.log_msg(f" environment:\n{pprint.pformat(self.environ)}")
self.send_update([('header', msg)])
if self.initialStdin:
msg = f" writing {len(self.initialStdin)} bytes to stdin"
self.log_msg(" " + msg)
self.send_update([('header', msg + "\n")])
msg = f" using PTY: {bool(self.usePTY)}"
self.log_msg(" " + msg)
self.send_update([('header', msg + "\n")])
# put data into stdin and close it, if necessary. This will be
# buffered until connectionMade is called
if self.initialStdin:
self.pp.setStdin(self.initialStdin)
self.startTime = util.now(self._reactor)
# start the process
self.process = self._spawnProcess(
self.pp, argv[0], argv, self.environ, self.workdir, usePTY=self.usePTY
)
# set up timeouts
if self.timeout:
self.ioTimeoutTimer = self._reactor.callLater(self.timeout, self.doTimeout)
if self.maxTime:
self.maxTimeoutTimer = self._reactor.callLater(self.maxTime, self.doMaxTimeout)
for w in self.logFileWatchers:
w.start()
def _create_job_object(self):
job = win32job.CreateJobObject(None, "")
extented_info = win32job.QueryInformationJobObject(
job, win32job.JobObjectExtendedLimitInformation
)
extented_info['BasicLimitInformation']['LimitFlags'] = (
win32job.JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE
| win32job.JOB_OBJECT_TERMINATE_AT_END_OF_JOB
)
win32job.SetInformationJobObject(
job, win32job.JobObjectExtendedLimitInformation, extented_info
)
return job
def _spawnProcess(
self,
processProtocol,
executable,
args=(),
env=None,
path=None,
uid=None,
gid=None,
usePTY=False,
childFDs=None,
):
"""private implementation of reactor.spawnProcess, to allow use of
L{ProcGroupProcess}"""
if env is None:
env = {}
if runtime.platformType == 'win32':
if self.using_comspec:
process = self._spawnAsBatch(
processProtocol, executable, args, env, path, usePTY=usePTY
)
else:
process = reactor.spawnProcess(
processProtocol, executable, args, env, path, usePTY=usePTY
)
pHandle = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, False, int(process.pid))
# use JobObject to group subprocesses
self.job_object = self._create_job_object()
win32job.AssignProcessToJobObject(self.job_object, pHandle)
return process
# use the ProcGroupProcess class, if available
elif runtime.platformType == 'posix':
if self.useProcGroup and not usePTY:
return ProcGroupProcess(
reactor, executable, args, env, path, processProtocol, uid, gid, childFDs
)
# fall back
return reactor.spawnProcess(processProtocol, executable, args, env, path, usePTY=usePTY)
def _spawnAsBatch(self, processProtocol, executable, args, env, path, usePTY):
"""A cheat that routes around the impedance mismatch between
twisted and cmd.exe with respect to escaping quotes"""
tf = NamedTemporaryFile(
mode='w+', dir='.', suffix=".bat", delete=False, encoding=self.unicode_encoding
)
# echo off hides this cheat from the log files.
tf.write("@echo off\n")
if isinstance(self.command, (str, bytes)):
tf.write(bytes2NativeString(self.command, self.unicode_encoding))
else:
tf.write(win32_batch_quote(self.command, self.unicode_encoding))
tf.close()
argv = os.environ['COMSPEC'].split() # allow %COMSPEC% to have args
if '/c' not in argv:
argv += ['/c']
argv += [tf.name]
def unlink_temp(result):
os.unlink(tf.name)
return result
self.deferred.addBoth(unlink_temp)
return reactor.spawnProcess(processProtocol, executable, argv, env, path, usePTY=usePTY)
def addStdout(self, data):
if self.sendStdout:
self._check_max_lines(data)
self.send_update([('stdout', data)])
if self.keepStdout:
self.stdout += data
if self.ioTimeoutTimer:
self.ioTimeoutTimer.reset(self.timeout)
def addStderr(self, data):
if self.sendStderr:
self._check_max_lines(data)
self.send_update([('stderr', data)])
if self.keepStderr:
self.stderr += data
if self.ioTimeoutTimer:
self.ioTimeoutTimer.reset(self.timeout)
def addLogfile(self, name, data):
self.send_update([('log', (name, data))])
if self.ioTimeoutTimer:
self.ioTimeoutTimer.reset(self.timeout)
def finished(self, sig, rc):
self.elapsedTime = util.now(self._reactor) - self.startTime
self.log_msg(
("command finished with signal {0}, exit code {1}, " + "elapsedTime: {2:0.6f}").format(
sig, rc, self.elapsedTime
)
)
for w in self.logFileWatchers:
# this will send the final updates
w.stop()
if sig is not None:
rc = -1
if self.sendRC:
if sig is not None:
self.send_update([('header', f"process killed by signal {sig}\n")])
self.send_update([('rc', rc)])
self.send_update([('header', f"elapsedTime={self.elapsedTime:0.6f}\n")])
self._cancelTimers()
d = self.deferred
self.deferred = None
if d:
d.callback(rc)
else:
self.log_msg(f"Hey, command {self} finished twice")
def failed(self, why):
self.log_msg(f"RunProcess.failed: command failed: {why}")
self._cancelTimers()
d = self.deferred
self.deferred = None
if d:
d.errback(why)
else:
self.log_msg(f"Hey, command {self} finished twice")
def doTimeout(self):
self.ioTimeoutTimer = None
msg = (
f"command timed out: {self.timeout} seconds without output running {self.fake_command}"
)
self.send_update([("failure_reason", "timeout_without_output")])
self.kill(msg)
def doMaxTimeout(self):
self.maxTimeoutTimer = None
msg = f"command timed out: {self.maxTime} seconds elapsed running {self.fake_command}"
self.send_update([("failure_reason", "timeout")])
self.kill(msg)
def _check_max_lines(self, data):
if self.max_lines is not None:
self.line_count += len(re.findall(r"\r\n|\r|\n", data))
if self.line_count > self.max_lines and not self.max_line_kill:
self.pp.transport.closeStdout()
self.max_line_kill = True
self.do_max_lines()
def do_max_lines(self):
msg = (
f"command exceeds max lines: {self.line_count}/{self.max_lines} "
f"written/allowed running {self.fake_command}"
)
self.send_update([("failure_reason", "max_lines_failure")])
self.kill(msg)
def isDead(self):
if self.process.pid is None:
return True
pid = int(self.process.pid)
try:
os.kill(pid, 0)
except OSError:
return True # dead
return False # alive
def checkProcess(self):
self.sigtermTimer = None
if not self.isDead():
hit = self.sendSig(self.interruptSignal)
else:
hit = 1
self.cleanUp(hit)
def cleanUp(self, hit):
if not hit:
self.log_msg("signalProcess/os.kill failed both times")
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()
elif runtime.platformType == 'win32':
if self.job_object is not None:
win32job.TerminateJobObject(self.job_object, 0)
self.job_object.Close()
if self.deferred:
# finished ought to be called momentarily. Just in case it doesn't,
# set a timer which will abandon the command.
self.killTimer = self._reactor.callLater(self.BACKUP_TIMEOUT, self.doBackupTimeout)
def sendSig(self, interruptSignal):
hit = 0
# try signalling the process group
if not hit and self.useProcGroup and runtime.platformType == "posix":
sig = getattr(signal, "SIG" + interruptSignal, None)
if sig is None:
self.log_msg(f"signal module is missing SIG{interruptSignal}")
elif not hasattr(os, "kill"):
self.log_msg("os module is missing the 'kill' function")
elif self.process.pgid is None:
self.log_msg("self.process has no pgid")
else:
self.log_msg(f"trying to kill process group {self.process.pgid}")
try:
os.killpg(self.process.pgid, sig)
self.log_msg(f" signal {sig} sent successfully")
self.process.pgid = None
hit = 1
except OSError:
self.log_msg(f'failed to kill process group (ignored): {sys.exc_info()[1]}')
# probably no-such-process, maybe because there is no process
# group
elif runtime.platformType == "win32":
if interruptSignal is None:
self.log_msg("interruptSignal==None, only pretending to kill child")
elif self.process.pid is not None or self.job_object is not None:
if interruptSignal == "TERM":
self._win32_taskkill(self.process.pid, force=False)
hit = 1
elif interruptSignal == "KILL":
self._win32_taskkill(self.process.pid, force=True)
hit = 1
# try signalling the process itself (works on Windows too, sorta)
if not hit:
try:
self.log_msg(f"trying process.signalProcess('{interruptSignal}')")
self.process.signalProcess(interruptSignal)
self.log_msg(f" signal {interruptSignal} sent successfully")
hit = 1
except OSError:
log.err("from process.signalProcess:")
# could be no-such-process, because they finished very recently
except error.ProcessExitedAlready:
self.log_msg("Process exited already - can't kill")
# the process has already exited, and likely finished() has
# been called already or will be called shortly
return hit
def _win32_taskkill(self, pid, force):
try:
if force:
cmd = f"TASKKILL /F /PID {pid} /T"
else:
cmd = f"TASKKILL /PID {pid} /T"
if self.job_object is not None:
pr_info = win32job.QueryInformationJobObject(
self.job_object, win32job.JobObjectBasicProcessIdList
)
if force or len(pr_info) < 2:
win32job.TerminateJobObject(self.job_object, 1)
self.log_msg(f"terminating job object with pids {pr_info!s}")
if pid is None:
return
self.log_msg(f"using {cmd} to kill pid {pid}")
subprocess.check_call(cmd)
self.log_msg(f"taskkill'd pid {pid}")
except win32job.error:
self.log_msg("failed to terminate job object")
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):
self.log_msg(f"taskkill didn't find pid {pid} to kill")
else:
self.log_msg(f"taskkill failed to kill process {pid}: {e}")
def kill(self, msg):
# This may be called by the timeout, or when the user has decided to
# abort this build.
self._cancelTimers()
msg += ", attempting to kill"
self.log_msg(msg)
self.send_update([('header', "\n" + msg + "\n")])
# let the PP know that we are killing it, so that it can ensure that
# the exit status comes out right
self.pp.killed = True
sendSigterm = self.sigtermTime is not None
if sendSigterm:
self.sendSig("TERM")
self.sigtermTimer = self._reactor.callLater(self.sigtermTime, self.checkProcess)
else:
hit = self.sendSig(self.interruptSignal)
self.cleanUp(hit)
def doBackupTimeout(self):
self.log_msg("we tried to kill the process, and it wouldn't die.. finish anyway")
self.killTimer = None
signalName = "SIG" + self.interruptSignal
self.send_update([('header', signalName + " failed to kill process\n")])
if self.sendRC:
self.send_update([('header', "using fake rc=-1\n"), ('rc', -1)])
self.failed(RuntimeError(signalName + " failed to kill process"))
def _cancelTimers(self):
for timerName in ('ioTimeoutTimer', 'killTimer', 'maxTimeoutTimer', 'sigtermTimer'):
timer = getattr(self, timerName, None)
if timer:
timer.cancel()
setattr(self, timerName, None)
| 34,965 | Python | .py | 791 | 33.439949 | 151 | 0.60151 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
5,039 | compat.py | buildbot_buildbot/worker/buildbot_worker/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
"""
Helpers for handling compatibility differences
between Python 2 and Python 3.
"""
from io import StringIO as NativeStringIO
def bytes2NativeString(x, encoding='utf-8'):
"""
Convert C{bytes} to a native C{str}.
On Python 3 and higher, str and bytes
are not equivalent. In this case, decode
the bytes, and return a native string.
On Python 2 and lower, str and bytes
are equivalent. In this case, just
just return the native string.
@param x: a string of type C{bytes}
@param encoding: an optional codec, default: 'utf-8'
@return: a string of type C{str}
"""
if isinstance(x, bytes) and str != bytes:
return x.decode(encoding)
return x
def unicode2bytes(x, encoding='utf-8', errors='strict'):
"""
Convert a unicode string to C{bytes}.
@param x: a unicode string, of type C{str}.
@param encoding: an optional codec, default: 'utf-8'
@param errors: error handling scheme, default 'strict'
@return: a string of type C{bytes}
"""
if isinstance(x, str):
x = x.encode(encoding, errors)
return x
def bytes2unicode(x, encoding='utf-8', errors='strict'):
"""
Convert a C{bytes} to a unicode string.
@param x: a unicode string, of type C{str}.
@param encoding: an optional codec, default: 'utf-8'
@param errors: error handling scheme, default 'strict'
@return: a unicode string of type C{unicode} on Python 2, or
C{str} on Python 3.
"""
if isinstance(x, (str, type(None))):
return x
return str(x, encoding, errors)
__all__ = ["NativeStringIO", "bytes2NativeString", "bytes2unicode", "unicode2bytes"]
| 2,379 | Python | .py | 59 | 36.271186 | 84 | 0.707592 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
5,040 | exceptions.py | buildbot_buildbot/worker/buildbot_worker/exceptions.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 AbandonChain(Exception):
"""A series of chained steps can raise this exception to indicate that
one of the intermediate RunProcesses has failed, such that there is no
point in running the remainder. The first argument to the exception
is the 'rc' - the non-zero exit code of the failing ShellCommand.
The second is an optional error message."""
def __repr__(self):
return f"<AbandonChain rc={self.args[0]}>"
| 1,154 | Python | .py | 22 | 49.863636 | 79 | 0.765279 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
5,041 | tunnel.py | buildbot_buildbot/worker/buildbot_worker/tunnel.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
#
# Parts of this code were copied from Twisted Python.
# Copyright (c) Twisted Matrix Laboratories.
#
from twisted.internet import defer
from twisted.internet import interfaces
from twisted.internet import protocol
from zope.interface import implementer
class HTTPTunnelClient(protocol.Protocol):
"""
This protocol handles the HTTP communication with the proxy server
and subsequent creation of the tunnel.
Once the tunnel is established, all incoming communication is forwarded
directly to the wrapped protocol.
"""
def __init__(self, connectedDeferred):
# this gets set once the tunnel is ready
self._proxyWrappedProtocol = None
self._connectedDeferred = connectedDeferred
def connectionMade(self):
request = f"CONNECT {self.factory.host}:{self.factory.port} HTTP/1.1\r\n\r\n"
self.transport.write(request.encode())
def connectionLost(self, reason):
if self._proxyWrappedProtocol:
# Proxy connectionLost to the wrapped protocol
self._proxyWrappedProtocol.connectionLost(reason)
def dataReceived(self, data):
if self._proxyWrappedProtocol is not None:
# If tunnel is already established, proxy dataReceived()
# calls to the wrapped protocol
return self._proxyWrappedProtocol.dataReceived(data)
# process data from the proxy server
_, status, _ = data.split(b"\r\n")[0].split(b" ", 2)
if status != b"200":
return self.transport.loseConnection()
self._proxyWrappedProtocol = self.factory._proxyWrappedFactory.buildProtocol(
self.transport.getPeer()
)
self._proxyWrappedProtocol.makeConnection(self.transport)
self._connectedDeferred.callback(self._proxyWrappedProtocol)
# forward all traffic directly to the wrapped protocol
self.transport.protocol = self._proxyWrappedProtocol
# In case the server sent some data together with its response,
# forward those to the wrapped protocol.
remaining_data = data.split(b"\r\n\r\n", 2)[1]
if remaining_data:
return self._proxyWrappedProtocol.dataReceived(remaining_data)
return None
class HTTPTunnelFactory(protocol.ClientFactory):
"""The protocol factory for the HTTP tunnel.
It is used as a wrapper for BotFactory, which can hence be shielded
from all the proxy business.
"""
protocol = HTTPTunnelClient # type: ignore[assignment]
def __init__(self, host, port, wrappedFactory):
self.host = host
self.port = port
self._proxyWrappedFactory = wrappedFactory
self._onConnection = defer.Deferred()
def doStart(self):
super().doStart()
# forward start notifications through to the wrapped factory.
self._proxyWrappedFactory.doStart()
def doStop(self):
# forward stop notifications through to the wrapped factory.
self._proxyWrappedFactory.doStop()
super().doStop()
def buildProtocol(self, addr):
proto = self.protocol(self._onConnection)
proto.factory = self
return proto
def clientConnectionFailed(self, connector, reason):
if not self._onConnection.called:
self._onConnection.errback(reason)
@implementer(interfaces.IStreamClientEndpoint)
class HTTPTunnelEndpoint:
"""This handles the connection to buildbot master on given 'host'
and 'port' through the proxy server given as 'proxyEndpoint'.
"""
def __init__(self, host, port, proxyEndpoint):
self.host = host
self.port = port
self.proxyEndpoint = proxyEndpoint
def connect(self, protocolFactory):
"""Connect to remote server through an HTTP tunnel."""
tunnel = HTTPTunnelFactory(self.host, self.port, protocolFactory)
d = self.proxyEndpoint.connect(tunnel)
# once tunnel connection is established,
# defer the subsequent server connection
d.addCallback(lambda result: tunnel._onConnection)
return d
| 4,793 | Python | .py | 105 | 38.971429 | 85 | 0.712017 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
5,042 | __init__.py | buildbot_buildbot/worker/buildbot_worker/test/__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 sys
from typing import Any
import twisted
from twisted.trial import unittest
from buildbot_worker import monkeypatches
# apply the same patches the worker does when it starts
monkeypatches.patch_all()
def add_debugging_monkeypatches():
"""
DO NOT CALL THIS DIRECTLY
This adds a few "harmless" monkeypatches which make it easier to debug
failing tests.
"""
from twisted.application.service import Service
old_startService = Service.startService
old_stopService = Service.stopService
def startService(self):
assert not self.running
return old_startService(self)
def stopService(self):
assert self.running
return old_stopService(self)
Service.startService = startService
Service.stopService = stopService
# versions of Twisted before 9.0.0 did not have a UnitTest.patch that worked
# on Python-2.7
if twisted.version.major <= 9 and sys.version_info[:2] == (2, 7):
def nopatch(self, *args):
raise unittest.SkipTest('unittest.TestCase.patch is not available')
unittest.TestCase.patch = nopatch
add_debugging_monkeypatches()
__all__: list[Any] = []
# import mock so we bail out early if it's not installed
try:
from unittest import mock
_ = mock
except ImportError:
try:
from unittest import mock
except ImportError as e:
raise ImportError("Buildbot tests require the 'mock' module; try 'pip install mock'") from e
| 2,228 | Python | .py | 56 | 35.714286 | 100 | 0.747212 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
5,043 | test_util_hangcheck.py | buildbot_buildbot/worker/buildbot_worker/test/test_util_hangcheck.py | """
Tests for `buildbot_worker.util._hangcheck`.
"""
from twisted.internet import defer
from twisted.internet import reactor
from twisted.internet.endpoints import TCP4ClientEndpoint
from twisted.internet.endpoints import TCP4ServerEndpoint
from twisted.internet.error import ConnectionDone
from twisted.internet.protocol import Protocol
from twisted.internet.task import Clock
from twisted.python.failure import Failure
from twisted.spread.pb import PBClientFactory
from twisted.trial.unittest import TestCase
from twisted.web.static import Data
from buildbot_worker.test.util.site import SiteWithClose
from ..util import HangCheckFactory
from ..util._hangcheck import HangCheckProtocol
try:
from twisted.internet.testing import AccumulatingProtocol
from twisted.internet.testing import StringTransport
except ImportError:
from twisted.test.proto_helpers import AccumulatingProtocol
from twisted.test.proto_helpers import StringTransport
def assert_clock_idle(case, clock):
"""
Assert that the given clock doesn't have any pending delayed
calls.
"""
case.assertEqual(
clock.getDelayedCalls(),
[],
)
class HangCheckTests(TestCase):
"""
Tests for HangCheckProtocol.
"""
# On slower machines with high CPU oversubscription this test may take longer to run than
# the default timeout.
timeout = 20
def test_disconnects(self):
"""
When connecting to a server that doesn't send any data,
the protocol disconnects after the timeout.
"""
clock = Clock()
protocol = HangCheckProtocol(Protocol(), reactor=clock)
transport = StringTransport()
transport.protocol = protocol
protocol.makeConnection(transport)
clock.advance(120)
self.assertTrue(transport.disconnecting)
assert_clock_idle(self, clock)
def test_transport(self):
"""
The transport passed to the underlying protocol is
the underlying transport.
"""
clock = Clock()
wrapped_protocol = Protocol()
protocol = HangCheckProtocol(wrapped_protocol, reactor=clock)
transport = StringTransport()
transport.protocol = protocol
protocol.makeConnection(transport)
self.assertIdentical(wrapped_protocol.transport, transport)
def test_forwards_data(self):
"""
Data received by the protocol gets passed to the wrapped
protocol.
"""
clock = Clock()
wrapped_protocol = AccumulatingProtocol()
protocol = HangCheckProtocol(wrapped_protocol, reactor=clock)
transport = StringTransport()
transport.protocol = protocol
protocol.makeConnection(transport)
protocol.dataReceived(b'some-data')
self.assertEqual(wrapped_protocol.data, b"some-data")
def test_data_cancels_timeout(self):
"""
When data is received, the timeout is canceled
"""
clock = Clock()
protocol = HangCheckProtocol(Protocol(), reactor=clock)
transport = StringTransport()
transport.protocol = protocol
protocol.makeConnection(transport)
protocol.dataReceived(b'some-data')
assert_clock_idle(self, clock)
def test_calls_callback(self):
"""
When connecting to a server that doesn't send any data,
the protocol calls the hung callback.
"""
results = []
clock = Clock()
protocol = HangCheckProtocol(
Protocol(),
hung_callback=lambda: results.append(True),
reactor=clock,
)
transport = StringTransport()
transport.protocol = protocol
protocol.makeConnection(transport)
clock.advance(120)
self.assertEqual(results, [True])
assert_clock_idle(self, clock)
def test_disconnect_forwarded(self):
"""
If the connection is closed, the underlying protocol is informed.
"""
clock = Clock()
wrapped_protocol = AccumulatingProtocol()
protocol = HangCheckProtocol(wrapped_protocol, reactor=clock)
transport = StringTransport()
transport.protocol = protocol
protocol.makeConnection(transport)
reason = ConnectionDone("Bye.")
protocol.connectionLost(Failure(reason))
self.assertTrue(wrapped_protocol.closed)
self.assertEqual(
wrapped_protocol.closedReason.value,
reason,
)
def test_disconnect_cancels_timeout(self):
"""
If the connection is closed, the hang check is cancelled.
"""
clock = Clock()
protocol = HangCheckProtocol(
Protocol(),
reactor=clock,
)
transport = StringTransport()
transport.protocol = protocol
protocol.makeConnection(transport)
protocol.connectionLost(Failure(ConnectionDone("Bye.")))
assert_clock_idle(self, clock)
def test_data_and_disconnect(self):
"""
If the connection receives data and then is closed, no error results.
"""
clock = Clock()
protocol = HangCheckProtocol(
Protocol(),
reactor=clock,
)
transport = StringTransport()
transport.protocol = protocol
protocol.makeConnection(transport)
protocol.dataReceived(b"some-data")
protocol.connectionLost(Failure(ConnectionDone("Bye.")))
assert_clock_idle(self, clock)
@defer.inlineCallbacks
def connected_server_and_client(case, server_factory, client_factory):
"""
Create a server and client connected to that server.
:param case: The test case that will handle cleanup.
:param IProtocolFactory server_factory: The factory for the server protocol.
:param IProtocolFactory client_factory: The factory for the client protocol.
:return: A deferred that fires when the client has connected.
.. todo:
Figure out what a sensible value to return is. The existing caller doesn't
use the return value.
"""
try:
listening_port = yield TCP4ServerEndpoint(reactor, 0).listen(server_factory)
case.addCleanup(listening_port.stopListening)
endpoint = TCP4ClientEndpoint(reactor, '127.0.0.1', listening_port.getHost().port)
yield endpoint.connect(client_factory)
except Exception as e:
f = Failure(e) # we can't use `e` from the lambda itself
case.addCleanup(lambda: f)
class EndToEndHangCheckTests(TestCase):
# On slower machines with high CPU oversubscription this test may take longer to run than
# the default timeout.
timeout = 20
@defer.inlineCallbacks
def test_http(self):
"""
When connecting to a HTTP server, a PB connection times
out.
"""
result = defer.Deferred()
site = SiteWithClose(Data("", "text/plain"))
client = HangCheckFactory(PBClientFactory(), lambda: result.callback(None))
self.patch(HangCheckProtocol, '_HUNG_CONNECTION_TIMEOUT', 0.1)
d_connected = connected_server_and_client(
self,
site,
client,
)
def cancel_all():
result.cancel()
d_connected.cancel()
timer = reactor.callLater(2, cancel_all)
try:
yield result
except defer.CancelledError as e:
raise RuntimeError('Timeout did not happen') from e
finally:
d_connected.cancel()
timer.cancel()
yield site.close_connections()
| 7,637 | Python | .py | 203 | 29.743842 | 93 | 0.671181 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
5,044 | reactor.py | buildbot_buildbot/worker/buildbot_worker/test/reactor.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 threads
from twisted.python import threadpool
from buildbot_worker.test.fake.reactor import NonThreadPool
from buildbot_worker.test.fake.reactor import TestReactor
class TestReactorMixin:
"""
Mix this in to get TestReactor as self.reactor which is correctly cleaned up
at the end
"""
def setup_test_reactor(self):
self.patch(threadpool, 'ThreadPool', NonThreadPool)
self.reactor = TestReactor()
def deferToThread(f, *args, **kwargs):
return threads.deferToThreadPool(
self.reactor, self.reactor.getThreadPool(), f, *args, **kwargs
)
self.patch(threads, 'deferToThread', deferToThread)
self.addCleanup(self.reactor.stop)
| 1,463 | Python | .py | 32 | 41.3125 | 80 | 0.748945 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
5,045 | test_extra_coverage.py | buildbot_buildbot/worker/buildbot_worker/test/test_extra_coverage.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 file imports a number of source files that are not
# included in the coverage because none of the tests import
# them; this results in a more accurate total coverage percent.
from buildbot_worker.scripts import logwatcher
modules = [] # for the benefit of pyflakes
modules.extend([logwatcher])
| 1,010 | Python | .py | 20 | 49.35 | 79 | 0.7923 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
5,046 | test_bot_Worker.py | buildbot_buildbot/worker/buildbot_worker/test/unit/test_bot_Worker.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 socket
from twisted.cred import checkers
from twisted.cred import portal
from twisted.internet import defer
from twisted.internet import reactor
from twisted.spread import pb
from twisted.trial import unittest
from zope.interface import implementer
from buildbot_worker import bot
from buildbot_worker.test.util import misc
try:
from unittest.mock import Mock
except ImportError:
from unittest.mock import Mock
# I don't see any simple way to test the PB equipment without actually setting
# up a TCP connection. This just tests that the PB code will connect and can
# execute a basic ping. The rest is done without TCP (or PB) in other
# test modules.
class MasterPerspective(pb.Avatar):
def __init__(self, on_keepalive=None):
self.on_keepalive = on_keepalive
def perspective_keepalive(self):
if self.on_keepalive:
on_keepalive = self.on_keepalive
self.on_keepalive = None
on_keepalive()
@implementer(portal.IRealm)
class MasterRealm:
def __init__(self, perspective, on_attachment):
self.perspective = perspective
self.on_attachment = on_attachment
@defer.inlineCallbacks
def requestAvatar(self, avatarId, mind, *interfaces):
assert pb.IPerspective in interfaces
self.mind = mind
self.perspective.mind = mind
if self.on_attachment:
yield self.on_attachment(mind)
return pb.IPerspective, self.perspective, lambda: None
def shutdown(self):
return self.mind.broker.transport.loseConnection()
class TestWorker(misc.PatcherMixin, unittest.TestCase):
def setUp(self):
self.realm = None
self.worker = None
self.listeningport = None
self.basedir = os.path.abspath("basedir")
if os.path.exists(self.basedir):
shutil.rmtree(self.basedir)
os.makedirs(self.basedir)
@defer.inlineCallbacks
def tearDown(self):
if self.realm:
yield self.realm.shutdown()
if self.worker and self.worker.running:
yield self.worker.stopService()
if self.listeningport:
yield self.listeningport.stopListening()
if os.path.exists(self.basedir):
shutil.rmtree(self.basedir)
def start_master(self, perspective, on_attachment=None):
self.realm = MasterRealm(perspective, on_attachment)
p = portal.Portal(self.realm)
p.registerChecker(checkers.InMemoryUsernamePasswordDatabaseDontUse(testy=b"westy"))
self.listeningport = reactor.listenTCP(0, pb.PBServerFactory(p), interface='127.0.0.1')
# return the dynamically allocated port number
return self.listeningport.getHost().port
def test_constructor_minimal(self):
# only required arguments
bot.Worker('mstr', 9010, 'me', 'pwd', '/s', 10, protocol='pb')
def test_constructor_083_tac(self):
"""invocation as made from default 0.8.3 tac files"""
bot.Worker('mstr', 9010, 'me', 'pwd', '/s', 10, umask=0o123, protocol='pb', maxdelay=10)
def test_constructor_091_tac(self):
# invocation as made from default 0.9.1 tac files
bot.Worker(
None,
None,
'me',
'pwd',
'/s',
10,
connection_string="tcp:host=localhost:port=9010",
umask=0o123,
protocol='pb',
maxdelay=10,
)
def test_constructor_invalid_both_styles(self):
"""Can't instantiate with both host/port and connection string."""
# assertRaises as a context manager appears in Python 2.7
self.assertRaises(
AssertionError,
bot.Worker,
'mstr',
9010,
'me',
'pwd',
'/s',
10,
connection_string="tcp:anything",
)
def test_constructor_invalid_both_styles_partial(self):
# assertRaises as a context manager appears in Python 2.7
self.assertRaises(
AssertionError,
bot.Worker,
'mstr',
None,
'me',
'pwd',
'/s',
10,
connection_string="tcp:anything",
)
def test_constructor_invalid_both_styles_partial2(self):
"""Can't instantiate with both host/port and connection string."""
# assertRaises as a context manager appears in Python 2.7
self.assertRaises(
AssertionError,
bot.Worker,
None,
9010,
None,
'me',
'pwd',
'/s',
10,
connection_string="tcp:anything",
)
def test_constructor_full(self):
# invocation with all args
bot.Worker(
'mstr',
9010,
'me',
'pwd',
'/s',
10,
umask=0o123,
maxdelay=10,
keepaliveTimeout=10,
unicode_encoding='utf8',
protocol='pb',
allow_shutdown=True,
)
def test_worker_print(self):
d = defer.Deferred()
# set up to call print when we are attached, and chain the results onto
# the deferred for the whole test
def call_print(mind):
print_d = mind.callRemote("print", "Hi, worker.")
print_d.addCallbacks(d.callback, d.errback)
# start up the master and worker
persp = MasterPerspective()
port = self.start_master(persp, on_attachment=call_print)
self.worker = bot.Worker(
"127.0.0.1",
port,
"testy",
"westy",
self.basedir,
keepalive=0,
umask=0o22,
protocol='pb',
)
self.worker.startService()
# and wait for the result of the print
return d
def test_recordHostname_uname(self):
self.patch_os_uname(lambda: [0, 'test-hostname.domain.com'])
self.worker = bot.Worker(
"127.0.0.1",
9999,
"testy",
"westy",
self.basedir,
keepalive=0,
umask=0o22,
protocol='pb',
)
self.worker.recordHostname(self.basedir)
with open(os.path.join(self.basedir, "twistd.hostname")) as f:
twistdHostname = f.read().strip()
self.assertEqual(twistdHostname, 'test-hostname.domain.com')
def test_recordHostname_getfqdn(self):
def missing():
raise AttributeError
self.patch_os_uname(missing)
self.patch(socket, "getfqdn", lambda: 'test-hostname.domain.com')
self.worker = bot.Worker(
"127.0.0.1",
9999,
"testy",
"westy",
self.basedir,
keepalive=0,
umask=0o22,
protocol='pb',
)
self.worker.recordHostname(self.basedir)
with open(os.path.join(self.basedir, "twistd.hostname")) as f:
twistdHostname = f.read().strip()
self.assertEqual(twistdHostname, 'test-hostname.domain.com')
def test_worker_graceful_shutdown(self):
"""Test that running the build worker's gracefulShutdown method results
in a call to the master's shutdown method"""
d = defer.Deferred()
fakepersp = Mock()
called = []
def fakeCallRemote(*args):
called.append(args)
d1 = defer.succeed(None)
return d1
fakepersp.callRemote = fakeCallRemote
# set up to call shutdown when we are attached, and chain the results onto
# the deferred for the whole test
def call_shutdown(mind):
self.worker.bf.perspective = fakepersp
shutdown_d = self.worker.gracefulShutdown()
shutdown_d.addCallbacks(d.callback, d.errback)
persp = MasterPerspective()
port = self.start_master(persp, on_attachment=call_shutdown)
self.worker = bot.Worker(
"127.0.0.1",
port,
"testy",
"westy",
self.basedir,
keepalive=0,
umask=0o22,
protocol='pb',
)
self.worker.startService()
def check(ign):
self.assertEqual(called, [('shutdown',)])
d.addCallback(check)
return d
def test_worker_shutdown(self):
"""Test watching an existing shutdown_file results in gracefulShutdown
being called."""
worker = bot.Worker(
"127.0.0.1",
1234,
"testy",
"westy",
self.basedir,
keepalive=0,
umask=0o22,
protocol='pb',
allow_shutdown='file',
)
# Mock out gracefulShutdown
worker.gracefulShutdown = Mock()
# Mock out os.path methods
exists = Mock()
mtime = Mock()
self.patch(os.path, 'exists', exists)
self.patch(os.path, 'getmtime', mtime)
# Pretend that the shutdown file doesn't exist
mtime.return_value = 0
exists.return_value = False
worker._checkShutdownFile()
# We shouldn't have called gracefulShutdown
self.assertEqual(worker.gracefulShutdown.call_count, 0)
# Pretend that the file exists now, with an mtime of 2
exists.return_value = True
mtime.return_value = 2
worker._checkShutdownFile()
# Now we should have changed gracefulShutdown
self.assertEqual(worker.gracefulShutdown.call_count, 1)
# Bump the mtime again, and make sure we call shutdown again
mtime.return_value = 3
worker._checkShutdownFile()
self.assertEqual(worker.gracefulShutdown.call_count, 2)
# Try again, we shouldn't call shutdown another time
worker._checkShutdownFile()
self.assertEqual(worker.gracefulShutdown.call_count, 2)
| 10,749 | Python | .py | 293 | 27.269625 | 96 | 0.609156 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
5,047 | test_msgpack.py | buildbot_buildbot/worker/buildbot_worker/test/unit/test_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 os
import time
from parameterized import parameterized
from twisted.application import service
from twisted.internet import defer
from twisted.internet import reactor
from twisted.trial import unittest
from buildbot_worker import base
from buildbot_worker import pb
from buildbot_worker import util
from buildbot_worker.test.fake.runprocess import Expect
from buildbot_worker.test.util import command
try:
from unittest import mock
except ImportError:
from unittest import mock
import msgpack
# pylint: disable=ungrouped-imports
from buildbot_worker.msgpack import BuildbotWebSocketClientProtocol
from buildbot_worker.msgpack import decode_http_authorization_header
from buildbot_worker.msgpack import encode_http_authorization_header
from buildbot_worker.pb import BotMsgpack
class TestHttpAuthorization(unittest.TestCase):
maxDiff = None
def test_encode(self):
result = encode_http_authorization_header(b'name', b'pass')
self.assertEqual(result, 'Basic bmFtZTpwYXNz')
result = encode_http_authorization_header(b'name2', b'pass2')
self.assertEqual(result, 'Basic bmFtZTI6cGFzczI=')
def test_encode_username_contains_colon(self):
with self.assertRaises(ValueError):
encode_http_authorization_header(b'na:me', b'pass')
def test_decode(self):
result = decode_http_authorization_header(
encode_http_authorization_header(b'name', b'pass')
)
self.assertEqual(result, ('name', 'pass'))
# password can contain a colon
result = decode_http_authorization_header(
encode_http_authorization_header(b'name', b'pa:ss')
)
self.assertEqual(result, ('name', 'pa:ss'))
def test_contains_no__basic(self):
with self.assertRaises(ValueError):
decode_http_authorization_header('Test bmFtZTpwYXNzOjI=')
with self.assertRaises(ValueError):
decode_http_authorization_header('TestTest bmFtZTpwYXNzOjI=')
def test_contains_forbidden_character(self):
with self.assertRaises(ValueError):
decode_http_authorization_header('Basic test%test')
def test_credentials_do_not_contain_colon(self):
value = 'Basic ' + base64.b64encode(b'TestTestTest').decode()
with self.assertRaises(ValueError):
decode_http_authorization_header(value)
class TestException(Exception):
pass
class FakeStep:
"A fake master-side BuildStep that records its activities."
def __init__(self):
self.finished_d = defer.Deferred()
self.actions = []
def wait_for_finish(self):
return self.finished_d
def remote_update(self, updates):
for update in updates:
if 'elapsed' in update[0]:
update[0]['elapsed'] = 1
self.actions.append(["update", updates])
def remote_complete(self, f):
self.actions.append(["complete", f])
self.finished_d.callback(None)
class FakeBot(base.BotBase):
WorkerForBuilder = pb.WorkerForBuilderPbLike
class TestBuildbotWebSocketClientProtocol(command.CommandTestMixin, unittest.TestCase):
maxDiff = None
def setUp(self):
self.protocol = BuildbotWebSocketClientProtocol()
self.protocol.sendMessage = mock.Mock()
self.protocol.factory = mock.Mock()
self.protocol.factory.password = b'test_password'
self.protocol.factory.name = b'test_username'
self.protocol.factory.buildbot_bot.builders = {'test_builder': mock.Mock()}
self.protocol.dict_def = {}
self.protocol.sendClose = mock.Mock()
def mock_util_now(_reactor=None):
return 0
# patch util.now function to never let tests access the time module of the code
self.patch(util, 'now', mock_util_now)
self.list_send_message_args = []
def send_message_test(payload, isBinary):
msg = msgpack.unpackb(payload, raw=False)
self.list_send_message_args.append(msg)
self.protocol.sendMessage = send_message_test
def assert_sent_messages(self, msgs_expected):
# checks, what messages has been called in sendMessage
self.assertEqual(msgs_expected, self.list_send_message_args)
self.list_send_message_args[:] = []
def setup_with_worker_for_builder(self):
self.protocol.onOpen()
# we are not interested in list_send_message_args before onMessage was called by test
self.list_send_message_args[:] = []
self.protocol.factory.buildbot_bot = BotMsgpack('test/dir')
service.MultiService.startService(self.protocol.factory.buildbot_bot)
self.protocol.factory.buildbot_bot.builder_protocol_command = {'test_builder': None}
self.protocol.factory.buildbot_bot.builder_basedirs = {'test_builder': 'basedir'}
@defer.inlineCallbacks
def test_call_get_worker_info_success(self):
self.protocol.factory.buildbot_bot.remote_getWorkerInfo = mock.Mock()
self.protocol.factory.buildbot_bot.remote_getWorkerInfo.return_value = {
'test': 'data_about_worker'
}
msg = {'op': 'get_worker_info', 'seq_number': 0}
self.protocol.onMessage(msgpack.packb(msg), True)
yield self.protocol._deferwaiter.wait()
self.protocol.factory.buildbot_bot.remote_getWorkerInfo.assert_called()
msgs_expected = {'op': 'response', 'seq_number': 0, 'result': {'test': 'data_about_worker'}}
self.assertEqual(self.list_send_message_args, [msgs_expected])
@defer.inlineCallbacks
def send_message(self, message):
self.protocol.onMessage(msgpack.packb(message), True)
yield self.protocol._deferwaiter.wait()
@parameterized.expand([
('print_op', {'seq_number': 1, 'message': 'test'}),
('print_seq_number', {'op': 'print', 'message': 'test'}),
('keepalive_op', {'seq_number': 1}),
('keepalive_seq_number', {'op': 'keepalive'}),
('get_worker_info_op', {'seq_number': 1}),
('get_worker_info_seq_number', {'op': 'get_worker_info'}),
('start_command_op', {'seq_number': 1}),
('start_command_seq_number', {'op': 'start_command'}),
('shutdown_op', {'seq_number': 1}),
('shutdown_seq_number', {'op': 'shutdown'}),
('interrupt_command_op', {'seq_number': 1}),
('interrupt_command_seq_number', {'op': 'interrupt_command'}),
('response_op', {'seq_number': 1}),
('response_seq_number', {'op': 'response'}),
])
@defer.inlineCallbacks
def test_msg(self, name, msg):
# if msg does not have 'sep_number' or 'op', response sendMessage should not be called
with mock.patch('twisted.python.log.msg') as mock_log:
yield self.send_message(msg)
mock_log.assert_any_call(f'Invalid message from master: {msg}')
self.assert_sent_messages([])
@parameterized.expand([
(
'start_command',
{
'op': 'start_command',
'seq_number': 1,
'command_name': 'test_command',
'args': 'args',
},
'command_id',
),
(
'start_command',
{
'op': 'start_command',
'seq_number': 1,
'command_id': '123',
'command_name': 'test_command',
},
'args',
),
(
'start_command',
{'op': 'start_command', 'seq_number': 1, 'command_id': '123', 'args': 'args'},
'command_name',
),
(
'interrupt_command',
{'op': 'interrupt_command', 'seq_number': 1, 'why': 'test_why'},
'command_id',
),
('call_print', {'op': 'print', 'seq_number': 1}, 'message'),
(
'call_interrupt_command',
{'op': 'interrupt_command', 'seq_number': 1, 'command_id': '123'},
'why',
),
(
'call_interrupt_command',
{'op': 'interrupt_command', 'seq_number': 1, 'why': 'test_reason'},
'command_id',
),
])
@defer.inlineCallbacks
def test_missing_parameter(self, command, msg, missing_parameter):
self.protocol.onOpen()
# we are not interested in list_send_message_args before onMessage was called by test
self.list_send_message_args[:] = []
yield self.send_message(msg)
self.assert_sent_messages([
{
'op': 'response',
'seq_number': 1,
'result': f'\'message did not contain obligatory "{missing_parameter}" key\'',
'is_exception': True,
}
])
@defer.inlineCallbacks
def test_on_message_unrecognized_command(self):
self.protocol.onOpen()
# we are not interested in list_send_message_args before onMessage was called by test
self.list_send_message_args[:] = []
yield self.send_message({'op': 'test', 'seq_number': 0})
self.assert_sent_messages([
{
'is_exception': True,
'op': 'response',
'result': 'Command test does not exist.',
'seq_number': 0,
}
])
def test_authorization_header(self):
result = self.protocol.onConnecting('test')
self.assertEqual(
result.headers,
{"Authorization": encode_http_authorization_header(b'test_username', b'test_password')},
)
@defer.inlineCallbacks
def test_call_print_success(self):
self.protocol.factory.buildbot_bot = BotMsgpack('test/dir')
with mock.patch('twisted.python.log.msg') as mock_log:
yield self.send_message({'op': 'print', 'seq_number': 0, 'message': 'test_message'})
mock_log.assert_any_call("message from master:", 'test_message')
self.assert_sent_messages([{'op': 'response', 'seq_number': 0, 'result': None}])
@defer.inlineCallbacks
def test_call_keepalive(self):
with mock.patch('twisted.python.log.msg') as mock_log:
yield self.send_message({'op': 'keepalive', 'seq_number': 0})
mock_log.assert_any_call("Connection keepalive confirmed.")
self.assert_sent_messages([{'op': 'response', 'seq_number': 0, 'result': None}])
@defer.inlineCallbacks
def test_call_start_command_success(self):
self.setup_with_worker_for_builder()
# check if directory was created
with mock.patch('os.makedirs') as mkdir:
yield self.send_message({
'op': 'start_command',
'seq_number': 0,
'command_id': '123',
'command_name': 'mkdir',
'args': {'paths': ['basedir/test_dir'], 'test1': 'value1', 'test2': 'value2'},
})
mkdir.assert_called()
@defer.inlineCallbacks
def test_call_start_command_failed(self):
self.patch(time, 'time', lambda: 123.0)
self.setup_with_worker_for_builder()
path = os.path.join('basedir', 'test_dir')
# check if directory was created
with mock.patch('os.makedirs') as mkdir:
mkdir.side_effect = OSError(1, 'test_error')
yield self.send_message({
'op': 'start_command',
'seq_number': 1,
'command_id': '123',
'command_name': 'mkdir',
'args': {'paths': [path], 'test1': 'value1', 'test2': 'value2'},
})
mkdir.assert_called()
self.assert_sent_messages([
{
'op': 'update',
'args': [
['rc', 1],
['elapsed', 0],
['header', [f'mkdir: test_error: {path}\n', [35], [123.0]]],
],
'command_id': '123',
'seq_number': 0,
},
{'op': 'complete', 'args': None, 'command_id': '123', 'seq_number': 1},
# response result is always None, even if the command failed
{'op': 'response', 'result': None, 'seq_number': 1},
])
def create_msg(seq_number):
return {'op': 'response', 'seq_number': seq_number, 'result': None}
yield self.send_message(create_msg(0))
yield self.send_message(create_msg(1))
# worker should not send any new messages in response to masters 'response'
self.assertEqual(self.list_send_message_args, [])
@defer.inlineCallbacks
def test_call_start_command_shell_success(self):
self.patch(time, 'time', lambda: 123.0)
self.setup_with_worker_for_builder()
# patch runprocess to handle the 'echo', below
workdir = os.path.join('basedir', 'test_basedir')
self.patch_runprocess(
Expect(['echo'], workdir)
.update('header', 'headers') # note that this is partial line
.update('stdout', 'hello\n')
.update('rc', 0)
.exit(0)
)
yield self.send_message({
'op': 'start_command',
'seq_number': 1,
'command_id': '123',
'command_name': 'shell',
'args': {'command': ['echo'], 'workdir': workdir},
})
self.assert_sent_messages([
{
'op': 'update',
'args': [
['stdout', ['hello\n', [5], [123.0]]],
['rc', 0],
['elapsed', 0],
['header', ['headers\n', [7], [123.0]]],
],
'command_id': '123',
'seq_number': 0,
},
{'op': 'complete', 'args': None, 'command_id': '123', 'seq_number': 1},
{'op': 'response', 'seq_number': 1, 'result': None},
])
@defer.inlineCallbacks
def test_call_start_command_shell_success_logs(self):
self.patch(time, 'time', lambda: 123.0)
self.setup_with_worker_for_builder()
workdir = os.path.join('basedir', 'test_basedir')
self.patch_runprocess(
Expect(['echo'], workdir)
.update('header', 'headers\n')
.update('log', ('test_log', ('hello')))
.update('log', ('test_log', ('hello1\n')))
.update('log', ('test_log2', ('hello2\n')))
.update('log', ('test_log3', ('hello3')))
.update('rc', 0)
.exit(0)
)
yield self.send_message({
'op': 'start_command',
'seq_number': 1,
'command_id': '123',
'command_name': 'shell',
'args': {'command': ['echo'], 'workdir': workdir},
})
self.assert_sent_messages([
{
'op': 'update',
'args': [
['header', ['headers\n', [7], [123.0]]],
['log', ['test_log', ['hellohello1\n', [11], [123.0]]]],
['log', ['test_log2', ['hello2\n', [6], [123.0]]]],
['rc', 0],
['elapsed', 0],
['log', ['test_log3', ['hello3\n', [6], [123.0]]]],
],
'command_id': '123',
'seq_number': 0,
},
{'op': 'complete', 'args': None, 'command_id': '123', 'seq_number': 1},
{'op': 'response', 'seq_number': 1, 'result': None},
])
@defer.inlineCallbacks
def test_start_command_shell_success_updates_single(self):
self.patch(time, 'time', lambda: 123.0)
self.setup_with_worker_for_builder()
# patch runprocess to handle the 'echo', below
workdir = os.path.join('basedir', 'test_basedir')
self.patch_runprocess(
Expect(['echo'], workdir)
.updates([('header', 'headers'), ('stdout', 'hello\n'), ('rc', 0)])
.exit(0)
)
yield self.send_message({
'op': 'start_command',
'seq_number': 1,
'command_id': '123',
'command_name': 'shell',
'args': {'command': ['echo'], 'workdir': workdir},
})
self.assert_sent_messages([
{
'op': 'update',
'args': [
['stdout', ['hello\n', [5], [123.0]]],
['rc', 0],
['elapsed', 0],
['header', ['headers\n', [7], [123.0]]],
],
'command_id': '123',
'seq_number': 0,
},
{'op': 'complete', 'args': None, 'command_id': '123', 'seq_number': 1},
{'op': 'response', 'seq_number': 1, 'result': None},
])
@defer.inlineCallbacks
def test_call_shutdown_success(self):
# shutdown stops reactor, we can not test it so we just mock
self.protocol.factory.buildbot_bot.remote_shutdown = mock.Mock()
yield self.send_message({'op': 'shutdown', 'seq_number': 0})
self.protocol.factory.buildbot_bot.remote_shutdown.assert_called()
@defer.inlineCallbacks
def test_call_interrupt_command_no_command_to_interrupt(self):
self.setup_with_worker_for_builder()
self.protocol.factory.command.doInterrupt = mock.Mock()
with mock.patch('twisted.python.log.msg') as mock_log:
yield self.send_message({
'op': 'interrupt_command',
'seq_number': 1,
'command_id': '123',
'why': 'test_reason',
})
mock_log.assert_any_call('asked to interrupt current command: {}'.format('test_reason'))
mock_log.assert_any_call(' .. but none was running')
self.protocol.factory.command.doInterrupt.assert_not_called()
@defer.inlineCallbacks
def test_call_interrupt_command_success(self):
self.patch(time, 'time', lambda: 123.0)
self.setup_with_worker_for_builder()
self.protocol.factory.command.doInterrupt = mock.Mock()
# patch runprocess to pretend to sleep (it will really just hang forever,
# except that we interrupt it)
workdir = os.path.join('basedir', 'test_basedir')
self.patch_runprocess(
Expect(['sleep', '10'], workdir).update('header', 'headers').update('wait', True)
)
yield self.send_message({
'op': 'start_command',
'seq_number': 1,
'command_id': '123',
'command_name': 'shell',
'args': {'command': ['sleep', '10'], 'workdir': workdir},
})
# wait a jiffy..
d = defer.Deferred()
reactor.callLater(0.01, d.callback, None)
yield d
self.assert_sent_messages([{'op': 'response', 'seq_number': 1, 'result': None}])
yield self.send_message({
'op': 'interrupt_command',
'seq_number': 1,
'command_id': '123',
'why': 'test_reason',
})
self.assert_sent_messages([
{
'op': 'update',
'seq_number': 0,
'command_id': '123',
'args': [['header', ['headers\n', [7], [123.0]]]],
},
{
'op': 'update',
'seq_number': 1,
'command_id': '123',
'args': [['rc', -1], ['header', ['killing\n', [7], [123.0]]]],
},
{'op': 'complete', 'seq_number': 2, 'command_id': '123', 'args': None},
{'op': 'response', 'seq_number': 1, 'result': None},
])
| 20,363 | Python | .py | 471 | 32.73673 | 100 | 0.565217 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
5,048 | test_commands_shell.py | buildbot_buildbot/worker/buildbot_worker/test/unit/test_commands_shell.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
from twisted.internet import defer
from twisted.trial import unittest
from buildbot_worker.commands import shell
from buildbot_worker.test.fake.runprocess import Expect
from buildbot_worker.test.util.command import CommandTestMixin
class TestWorkerShellCommand(CommandTestMixin, unittest.TestCase):
def setUp(self):
self.setUpCommand()
def tearDown(self):
self.tearDownCommand()
@defer.inlineCallbacks
def test_simple(self):
workdir = os.path.join(self.basedir, 'workdir')
self.make_command(
shell.WorkerShellCommand, {'command': ['echo', 'hello'], 'workdir': workdir}
)
self.patch_runprocess(
Expect(['echo', 'hello'], self.basedir_workdir)
.update('header', 'headers')
.update('stdout', 'hello\n')
.update('rc', 0)
.exit(0)
)
yield self.run_command()
# note that WorkerShellCommand does not add any extra updates of it own
self.assertUpdates(
[('header', 'headers'), ('stdout', 'hello\n'), ('rc', 0)], self.protocol_command.show()
)
# TODO: test all functionality that WorkerShellCommand adds atop RunProcess
| 1,929 | Python | .py | 44 | 38.227273 | 99 | 0.707577 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
5,049 | test_scripts_stop.py | buildbot_buildbot/worker/buildbot_worker/test/unit/test_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.trial import unittest
from buildbot_worker.scripts import stop
from buildbot_worker.test.util import compat
from buildbot_worker.test.util import misc
try:
from unittest import mock
except ImportError:
from unittest import mock
class TestStopWorker(misc.FileIOMixin, misc.StdoutAssertionsMixin, unittest.TestCase):
"""
Test buildbot_worker.scripts.stop.stopWorker()
"""
PID = 9876
def setUp(self):
self.setUpStdoutAssertions()
# patch os.chdir() to do nothing
self.patch(os, "chdir", mock.Mock())
def test_no_pid_file(self):
"""
test calling stopWorker() when no pid file is present
"""
# patch open() to raise 'file not found' exception
self.setUpOpenError(2)
# check that stop() raises WorkerNotRunning exception
with self.assertRaises(stop.WorkerNotRunning):
stop.stopWorker(None, False)
@compat.skipUnlessPlatformIs("posix")
def test_successful_stop(self):
"""
test stopWorker() on a successful worker stop
"""
def emulated_kill(pid, sig):
if sig == 0:
# when probed if a signal can be send to the process
# emulate that it is dead with 'No such process' error
raise OSError(errno.ESRCH, "dummy")
# patch open() to return a pid file
self.setUpOpen(str(self.PID))
# patch os.kill to emulate successful kill
mocked_kill = mock.Mock(side_effect=emulated_kill)
self.patch(os, "kill", mocked_kill)
# don't waste time
self.patch(time, "sleep", mock.Mock())
# check that stopWorker() sends expected signal to right PID
# and print correct message to stdout
exit_code = stop.stopWorker(None, False)
self.assertEqual(exit_code, 0)
mocked_kill.assert_has_calls([mock.call(self.PID, signal.SIGTERM), mock.call(self.PID, 0)])
self.assertStdoutEqual(f"worker process {self.PID} is dead\n")
@compat.skipUnlessPlatformIs("posix")
def test_stop_timeout(self):
"""
test stopWorker() when stop timeouts
"""
# patch open() to return a pid file
self.setUpOpen(str(self.PID))
# patch os.kill to emulate successful kill
mocked_kill = mock.Mock()
self.patch(os, "kill", mocked_kill)
# don't waste time
self.patch(time, "sleep", mock.Mock())
# check that stopWorker() sends expected signal to right PID
# and print correct message to stdout
exit_code = stop.stopWorker(None, False)
self.assertEqual(exit_code, 1)
mocked_kill.assert_has_calls([mock.call(self.PID, signal.SIGTERM), mock.call(self.PID, 0)])
self.assertStdoutEqual("never saw process go away\n")
class TestStop(misc.IsWorkerDirMixin, misc.StdoutAssertionsMixin, unittest.TestCase):
"""
Test buildbot_worker.scripts.stop.stop()
"""
config = {"basedir": "dummy", "quiet": False}
def test_bad_basedir(self):
"""
test calling stop() with invalid basedir path
"""
# patch isWorkerDir() to fail
self.setupUpIsWorkerDir(False)
# call startCommand() and check that correct exit code is returned
self.assertEqual(stop.stop(self.config), 1, "unexpected exit code")
# check that isWorkerDir was called with correct argument
self.isWorkerDir.assert_called_once_with(self.config["basedir"])
def test_no_worker_running(self):
"""
test calling stop() when no worker is running
"""
self.setUpStdoutAssertions()
# patch basedir check to always succeed
self.setupUpIsWorkerDir(True)
# patch stopWorker() to raise an exception
mock_stopWorker = mock.Mock(side_effect=stop.WorkerNotRunning())
self.patch(stop, "stopWorker", mock_stopWorker)
exit_code = stop.stop(self.config)
self.assertEqual(exit_code, 0)
self.assertStdoutEqual("worker not running\n")
def test_successful_stop(self):
"""
test calling stop() when worker is running
"""
# patch basedir check to always succeed
self.setupUpIsWorkerDir(True)
# patch stopWorker() to do nothing
mock_stopWorker = mock.Mock(return_value=0)
self.patch(stop, "stopWorker", mock_stopWorker)
exit_code = stop.stop(self.config)
self.assertEqual(exit_code, 0)
mock_stopWorker.assert_called_once_with(
self.config["basedir"], self.config["quiet"], "TERM"
)
def test_failed_stop(self):
"""
test failing stop()
"""
# patch basedir check to always succeed
self.setupUpIsWorkerDir(True)
# patch stopWorker() to do nothing
mock_stopWorker = mock.Mock(return_value=17)
self.patch(stop, "stopWorker", mock_stopWorker)
exit_code = stop.stop(self.config)
self.assertEqual(exit_code, 17)
mock_stopWorker.assert_called_once_with(
self.config["basedir"], self.config["quiet"], "TERM"
)
| 5,928 | Python | .py | 141 | 34.48227 | 99 | 0.66597 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
5,050 | test_commands_base.py | buildbot_buildbot/worker/buildbot_worker/test/unit/test_commands_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.internet import defer
from twisted.trial import unittest
from buildbot_worker.commands.base import Command
from buildbot_worker.test.util.command import CommandTestMixin
# set up a fake Command subclass to test the handling in Command. Think of
# this as testing Command's subclassability.
class DummyCommand(Command):
def setup(self, args):
self.setup_done = True
self.interrupted = False
self.started = False
def start(self):
self.started = True
data = []
for key, value in self.args.items():
data.append((key, value))
self.sendStatus(data)
self.cmd_deferred = defer.Deferred()
return self.cmd_deferred
def interrupt(self):
self.interrupted = True
self.finishCommand()
def finishCommand(self):
d = self.cmd_deferred
self.cmd_deferred = None
d.callback(None)
def failCommand(self):
d = self.cmd_deferred
self.cmd_deferred = None
d.errback(RuntimeError("forced failure"))
class DummyArgsCommand(DummyCommand):
requiredArgs = ['workdir']
class TestDummyCommand(CommandTestMixin, unittest.TestCase):
def setUp(self):
self.setUpCommand()
def tearDown(self):
self.tearDownCommand()
def assertState(self, setup_done, running, started, interrupted, msg=None):
self.assertEqual(
{
'setup_done': self.cmd.setup_done,
'running': self.cmd.running,
'started': self.cmd.started,
'interrupted': self.cmd.interrupted,
},
{
'setup_done': setup_done,
'running': running,
'started': started,
'interrupted': interrupted,
},
msg,
)
def test_run(self):
cmd = self.make_command(DummyCommand, {'stdout': 'yay'})
self.assertState(True, False, False, False, "setup called by constructor")
# start the command
d = self.run_command()
self.assertState(True, True, True, False, "started and running both set")
# allow the command to finish and check the result
cmd.finishCommand()
def check(_):
self.assertState(True, False, True, False, "started and not running when done")
d.addCallback(check)
def checkresult(_):
self.assertUpdates([('stdout', 'yay')], "updates processed")
d.addCallback(checkresult)
return d
def test_run_failure(self):
cmd = self.make_command(DummyCommand, {})
self.assertState(True, False, False, False, "setup called by constructor")
# start the command
d = self.run_command()
self.assertState(True, True, True, False, "started and running both set")
# fail the command with an exception, and check the result
cmd.failCommand()
def check(_):
self.assertState(True, False, True, False, "started and not running when done")
d.addErrback(check)
def checkresult(_):
self.assertUpdates([], "updates processed")
d.addCallback(checkresult)
return d
def test_run_interrupt(self):
cmd = self.make_command(DummyCommand, {})
self.assertState(True, False, False, False, "setup called by constructor")
# start the command
d = self.run_command()
self.assertState(True, True, True, False, "started and running both set")
# interrupt the command
cmd.doInterrupt()
self.assertTrue(cmd.interrupted)
def check(_):
self.assertState(True, False, True, True, "finishes with interrupted set")
d.addCallback(check)
return d
def test_required_args(self):
self.make_command(DummyArgsCommand, {'workdir': '.'})
try:
self.make_command(DummyArgsCommand, {'stdout': 'boo'})
except ValueError:
return
self.fail("Command was supposed to raise ValueError when missing args")
| 4,808 | Python | .py | 117 | 32.820513 | 91 | 0.648625 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
5,051 | test_commands_registry.py | buildbot_buildbot/worker/buildbot_worker/test/unit/test_commands_registry.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.trial import unittest
from buildbot_worker.commands import registry
from buildbot_worker.commands import shell
class Registry(unittest.TestCase):
def test_getFactory(self):
factory = registry.getFactory('shell')
self.assertEqual(factory, shell.WorkerShellCommand)
def test_getFactory_KeyError(self):
with self.assertRaises(KeyError):
registry.getFactory('nosuchcommand')
def test_getAllCommandNames(self):
self.assertTrue('shell' in registry.getAllCommandNames())
def test_all_commands_exist(self):
# if this doesn't raise a KeyError, then we're good
for n in registry.getAllCommandNames():
registry.getFactory(n)
| 1,427 | Python | .py | 30 | 43.4 | 79 | 0.760432 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
5,052 | test_commands_transfer.py | buildbot_buildbot/worker/buildbot_worker/test/unit/test_commands_transfer.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 re
import shutil
import tarfile
from twisted.internet import defer
from twisted.internet import reactor
from twisted.python import failure
from twisted.python import runtime
from twisted.trial import unittest
from buildbot_worker.commands import transfer
from buildbot_worker.test.fake.remote import FakeRemote
from buildbot_worker.test.util.command import CommandTestMixin
class FakeMasterMethods:
# a fake to represent any of:
# - FileWriter
# - FileDirectoryWriter
# - FileReader
def __init__(self, add_update):
self.add_update = add_update
self.delay_write = False
self.count_writes = False
self.keep_data = False
self.write_out_of_space_at = None
self.delay_read = False
self.count_reads = False
self.unpack_fail = False
self.written = False
self.read = False
self.data = b''
def remote_write(self, data):
if self.write_out_of_space_at is not None:
self.write_out_of_space_at -= len(data)
if self.write_out_of_space_at <= 0:
f = failure.Failure(RuntimeError("out of space"))
return defer.fail(f)
if self.count_writes:
self.add_update(f'write {len(data)}')
elif not self.written:
self.add_update('write(s)')
self.written = True
if self.keep_data:
self.data += data
if self.delay_write:
d = defer.Deferred()
reactor.callLater(0.01, d.callback, None)
return d
return None
def remote_read(self, length):
if self.count_reads:
self.add_update(f'read {length}')
elif not self.read:
self.add_update('read(s)')
self.read = True
if not self.data:
return ''
_slice, self.data = self.data[:length], self.data[length:]
if self.delay_read:
d = defer.Deferred()
reactor.callLater(0.01, d.callback, _slice)
return d
return _slice
def remote_unpack(self):
self.add_update('unpack')
if self.unpack_fail:
return defer.fail(failure.Failure(RuntimeError("out of space")))
return None
def remote_utime(self, accessed_modified):
self.add_update(f'utime - {accessed_modified[0]}')
def remote_close(self):
self.add_update('close')
class TestUploadFile(CommandTestMixin, unittest.TestCase):
def setUp(self):
self.setUpCommand()
self.fakemaster = FakeMasterMethods(self.add_update)
# write 180 bytes of data to upload
self.datadir = os.path.join(self.basedir, 'workdir')
if os.path.exists(self.datadir):
shutil.rmtree(self.datadir)
os.makedirs(self.datadir)
self.datafile = os.path.join(self.datadir, 'data')
# note: use of 'wb' here ensures newlines aren't translated on the
# upload
with open(self.datafile, mode="wb") as f:
f.write(b"this is some data\n" * 10)
def tearDown(self):
self.tearDownCommand()
if os.path.exists(self.datadir):
shutil.rmtree(self.datadir)
@defer.inlineCallbacks
def test_simple(self):
self.fakemaster.count_writes = True # get actual byte counts
path = os.path.join(self.basedir, 'workdir', os.path.expanduser('data'))
self.make_command(
transfer.WorkerFileUploadCommand,
{
'path': path,
'writer': FakeRemote(self.fakemaster),
'maxsize': 1000,
'blocksize': 64,
'keepstamp': False,
},
)
yield self.run_command()
self.assertUpdates([
('header', f'sending {self.datafile}\n'),
'write 64',
'write 64',
'write 52',
'close',
('rc', 0),
])
@defer.inlineCallbacks
def test_truncated(self):
self.fakemaster.count_writes = True # get actual byte counts
path = os.path.join(self.basedir, 'workdir', os.path.expanduser('data'))
self.make_command(
transfer.WorkerFileUploadCommand,
{
'path': path,
'writer': FakeRemote(self.fakemaster),
'maxsize': 100,
'blocksize': 64,
'keepstamp': False,
},
)
yield self.run_command()
self.assertUpdates([
('header', f'sending {self.datafile}\n'),
'write 64',
'write 36',
'close',
('rc', 1),
('stderr', f"Maximum filesize reached, truncating file '{self.datafile}'"),
])
@defer.inlineCallbacks
def test_missing(self):
path = os.path.join(self.basedir, 'workdir', os.path.expanduser('data-nosuch'))
self.make_command(
transfer.WorkerFileUploadCommand,
{
'path': path,
'writer': FakeRemote(self.fakemaster),
'maxsize': 100,
'blocksize': 64,
'keepstamp': False,
},
)
yield self.run_command()
df = self.datafile + "-nosuch"
self.assertUpdates([
('header', f'sending {df}\n'),
'close',
('rc', 1),
('stderr', f"Cannot open file '{df}' for upload"),
])
@defer.inlineCallbacks
def test_out_of_space(self):
self.fakemaster.write_out_of_space_at = 70
self.fakemaster.count_writes = True # get actual byte counts
path = os.path.join(self.basedir, 'workdir', os.path.expanduser('data'))
self.make_command(
transfer.WorkerFileUploadCommand,
{
'path': path,
'writer': FakeRemote(self.fakemaster),
'maxsize': 1000,
'blocksize': 64,
'keepstamp': False,
},
)
yield self.assertFailure(self.run_command(), RuntimeError)
self.assertUpdates([
('header', f'sending {self.datafile}\n'),
'write 64',
'close',
('rc', 1),
])
@defer.inlineCallbacks
def test_interrupted(self):
self.fakemaster.delay_write = True # write very slowly
path = os.path.join(self.basedir, 'workdir', os.path.expanduser('data'))
self.make_command(
transfer.WorkerFileUploadCommand,
{
'path': path,
'writer': FakeRemote(self.fakemaster),
'maxsize': 100,
'blocksize': 2,
'keepstamp': False,
},
)
d = self.run_command()
# wait a jiffy..
interrupt_d = defer.Deferred()
reactor.callLater(0.01, interrupt_d.callback, None)
# and then interrupt the step
def do_interrupt(_):
return self.cmd.interrupt()
interrupt_d.addCallback(do_interrupt)
yield defer.DeferredList([d, interrupt_d])
self.assertUpdates([
('header', f'sending {self.datafile}\n'),
'write(s)',
'close',
('rc', 1),
])
@defer.inlineCallbacks
def test_timestamp(self):
self.fakemaster.count_writes = True # get actual byte counts
timestamp = (os.path.getatime(self.datafile), os.path.getmtime(self.datafile))
path = os.path.join(self.basedir, 'workdir', os.path.expanduser('data'))
self.make_command(
transfer.WorkerFileUploadCommand,
{
'path': path,
'writer': FakeRemote(self.fakemaster),
'maxsize': 1000,
'blocksize': 64,
'keepstamp': True,
},
)
yield self.run_command()
self.assertUpdates([
('header', f'sending {self.datafile}\n'),
'write 64',
'write 64',
'write 52',
'close',
f'utime - {timestamp[0]}',
('rc', 0),
])
class TestWorkerDirectoryUpload(CommandTestMixin, unittest.TestCase):
def setUp(self):
self.setUpCommand()
self.fakemaster = FakeMasterMethods(self.add_update)
# write a directory to upload
self.datadir = os.path.join(self.basedir, 'workdir', 'data')
if os.path.exists(self.datadir):
shutil.rmtree(self.datadir)
os.makedirs(self.datadir)
with open(os.path.join(self.datadir, "aa"), mode="wb") as f:
f.write(b"lots of a" * 100)
with open(os.path.join(self.datadir, "bb"), mode="wb") as f:
f.write(b"and a little b" * 17)
def tearDown(self):
self.tearDownCommand()
if os.path.exists(self.datadir):
shutil.rmtree(self.datadir)
@defer.inlineCallbacks
def test_simple(self, compress=None):
self.fakemaster.keep_data = True
path = os.path.join(self.basedir, 'workdir', os.path.expanduser('data'))
self.make_command(
transfer.WorkerDirectoryUploadCommand,
{
'workdir': 'workdir',
'path': path,
'writer': FakeRemote(self.fakemaster),
'maxsize': None,
'blocksize': 512,
'compress': compress,
},
)
yield self.run_command()
self.assertUpdates([
('header', f'sending {self.datadir}\n'),
'write(s)',
'unpack', # note no 'close"
('rc', 0),
])
f = io.BytesIO(self.fakemaster.data)
a = tarfile.open(fileobj=f, name='check.tar', mode="r")
exp_names = ['.', 'aa', 'bb']
got_names = [n.rstrip('/') for n in a.getnames()]
# py27 uses '' instead of '.'
got_names = sorted([n or '.' for n in got_names])
self.assertEqual(got_names, exp_names, "expected archive contents")
a.close()
f.close()
# try it again with bz2 and gzip
def test_simple_bz2(self):
return self.test_simple('bz2')
def test_simple_gz(self):
return self.test_simple('gz')
# except bz2 can't operate in stream mode on py24
@defer.inlineCallbacks
def test_out_of_space_unpack(self):
self.fakemaster.keep_data = True
self.fakemaster.unpack_fail = True
path = os.path.join(self.basedir, 'workdir', os.path.expanduser('data'))
self.make_command(
transfer.WorkerDirectoryUploadCommand,
{
'path': path,
'workersrc': 'data',
'writer': FakeRemote(self.fakemaster),
'maxsize': None,
'blocksize': 512,
'compress': None,
},
)
yield self.assertFailure(self.run_command(), RuntimeError)
self.assertUpdates([
('header', f'sending {self.datadir}\n'),
'write(s)',
'unpack',
('rc', 1),
])
class TestWorkerDirectoryUploadNoDir(CommandTestMixin, unittest.TestCase):
def setUp(self):
self.setUpCommand()
self.fakemaster = FakeMasterMethods(self.add_update)
def tearDown(self):
self.tearDownCommand()
@defer.inlineCallbacks
def test_directory_not_available(self):
path = os.path.join(self.basedir, 'workdir', os.path.expanduser('data'))
self.make_command(
transfer.WorkerDirectoryUploadCommand,
{
'path': path,
'workersrc': 'data',
'writer': FakeRemote(self.fakemaster),
'maxsize': None,
'blocksize': 512,
'compress': None,
},
)
yield self.run_command()
updates = self.get_updates()
self.assertEqual(updates[0], ('rc', 1))
self.assertEqual(updates[1][0], "stderr")
error_msg = updates[1][1]
pattern = re.compile("Cannot read directory (.*?) for upload: (.*?)")
match = pattern.match(error_msg)
self.assertNotEqual(error_msg, match)
class TestDownloadFile(CommandTestMixin, unittest.TestCase):
def setUp(self):
self.setUpCommand()
self.fakemaster = FakeMasterMethods(self.add_update)
# the command will write to the basedir, so make sure it exists
if os.path.exists(self.basedir):
shutil.rmtree(self.basedir)
os.makedirs(self.basedir)
def tearDown(self):
self.tearDownCommand()
if os.path.exists(self.basedir):
shutil.rmtree(self.basedir)
@defer.inlineCallbacks
def test_simple(self):
self.fakemaster.count_reads = True # get actual byte counts
self.fakemaster.data = test_data = b'1234' * 13
assert len(self.fakemaster.data) == 52
path = os.path.join(self.basedir, os.path.expanduser('data'))
self.make_command(
transfer.WorkerFileDownloadCommand,
{
'path': path,
'reader': FakeRemote(self.fakemaster),
'maxsize': None,
'blocksize': 32,
'mode': 0o777,
},
)
yield self.run_command()
self.assertUpdates(['read 32', 'read 32', 'read 32', 'close', ('rc', 0)])
datafile = os.path.join(self.basedir, 'data')
self.assertTrue(os.path.exists(datafile))
with open(datafile, mode="rb") as f:
datafileContent = f.read()
self.assertEqual(datafileContent, test_data)
if runtime.platformType != 'win32':
self.assertEqual(os.stat(datafile).st_mode & 0o777, 0o777)
@defer.inlineCallbacks
def test_mkdir(self):
self.fakemaster.data = test_data = b'hi'
path = os.path.join(
self.basedir, 'workdir', os.path.expanduser(os.path.join('subdir', 'data'))
)
self.make_command(
transfer.WorkerFileDownloadCommand,
{
'path': path,
'reader': FakeRemote(self.fakemaster),
'maxsize': None,
'blocksize': 32,
'mode': 0o777,
},
)
yield self.run_command()
self.assertUpdates(['read(s)', 'close', ('rc', 0)])
datafile = os.path.join(self.basedir, 'workdir', 'subdir', 'data')
self.assertTrue(os.path.exists(datafile))
with open(datafile, mode="rb") as f:
datafileContent = f.read()
self.assertEqual(datafileContent, test_data)
@defer.inlineCallbacks
def test_failure(self):
self.fakemaster.data = 'hi'
os.makedirs(os.path.join(self.basedir, 'dir'))
path = os.path.join(self.basedir, os.path.expanduser('dir'))
self.make_command(
transfer.WorkerFileDownloadCommand,
{
'path': path,
'reader': FakeRemote(self.fakemaster),
'maxsize': None,
'blocksize': 32,
'mode': 0o777,
},
)
yield self.run_command()
self.assertUpdates([
'close',
('rc', 1),
(
'stderr',
"Cannot open file '{}' for download".format(os.path.join(self.basedir, 'dir')),
),
])
@defer.inlineCallbacks
def test_truncated(self):
self.fakemaster.data = test_data = b'tenchars--' * 10
path = os.path.join(self.basedir, os.path.expanduser('data'))
self.make_command(
transfer.WorkerFileDownloadCommand,
{
'path': path,
'reader': FakeRemote(self.fakemaster),
'maxsize': 50,
'blocksize': 32,
'mode': 0o777,
},
)
yield self.run_command()
self.assertUpdates([
'read(s)',
'close',
('rc', 1),
(
'stderr',
"Maximum filesize reached, truncating file '{}'".format(
os.path.join(self.basedir, 'data')
),
),
])
datafile = os.path.join(self.basedir, 'data')
self.assertTrue(os.path.exists(datafile))
with open(datafile, mode="rb") as f:
data = f.read()
self.assertEqual(data, test_data[:50])
@defer.inlineCallbacks
def test_interrupted(self):
self.fakemaster.data = b'tenchars--' * 100 # 1k
self.fakemaster.delay_read = True # read very slowly
path = os.path.join(self.basedir, os.path.expanduser('data'))
self.make_command(
transfer.WorkerFileDownloadCommand,
{
'path': path,
'reader': FakeRemote(self.fakemaster),
'maxsize': 100,
'blocksize': 2,
'mode': 0o777,
},
)
d = self.run_command()
# wait a jiffy..
interrupt_d = defer.Deferred()
reactor.callLater(0.01, interrupt_d.callback, None)
# and then interrupt the step
def do_interrupt(_):
return self.cmd.interrupt()
interrupt_d.addCallback(do_interrupt)
yield defer.DeferredList([d, interrupt_d])
self.assertUpdates(['read(s)', 'close', ('rc', 1)])
| 18,253 | Python | .py | 491 | 26.556008 | 95 | 0.560238 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
5,053 | test_scripts_create_worker.py | buildbot_buildbot/worker/buildbot_worker/test/unit/test_scripts_create_worker.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
from twisted.trial import unittest
from buildbot_worker.scripts import create_worker
from buildbot_worker.test.util import misc
try:
from unittest import mock
except ImportError:
from unittest import mock
def _regexp_path(name, *names):
"""
Join two or more path components and create a regexp that will match that
path.
"""
return os.path.join(name, *names).replace("\\", "\\\\")
class TestDefaultOptionsMixin:
# default options and required arguments
options = {
# flags
"no-logrotate": False,
"relocatable": False,
"quiet": False,
"use-tls": False,
"delete-leftover-dirs": False,
# options
"basedir": "bdir",
"allow-shutdown": None,
"umask": None,
"log-size": 16,
"log-count": 8,
"keepalive": 4,
"maxdelay": 2,
"numcpus": None,
"protocol": "pb",
"maxretries": None,
"connection-string": None,
"proxy-connection-string": None,
# arguments
"host": "masterhost",
"port": 1234,
"name": "workername",
"passwd": "orange",
}
class TestMakeTAC(TestDefaultOptionsMixin, unittest.TestCase):
"""
Test buildbot_worker.scripts.create_worker._make_tac()
"""
def assert_tac_file_contents(self, tac_contents, expected_args, relocate=None):
"""
Check that generated TAC file is a valid Python script and it does what
is typical for TAC file logic. Mainly create instance of Worker with
expected arguments.
"""
# pylint: disable=import-outside-toplevel
# import modules for mocking
import twisted.application.service
import twisted.python.logfile
import buildbot_worker.bot
# mock service.Application class
application_mock = mock.Mock()
application_class_mock = mock.Mock(return_value=application_mock)
self.patch(twisted.application.service, "Application", application_class_mock)
# mock logging stuff
logfile_mock = mock.Mock()
self.patch(twisted.python.logfile.LogFile, "fromFullPath", logfile_mock)
# mock Worker class
worker_mock = mock.Mock()
worker_class_mock = mock.Mock(return_value=worker_mock)
self.patch(buildbot_worker.bot, "Worker", worker_class_mock)
# Executed .tac file with mocked functions with side effect.
# This will raise exception if .tac file is not valid Python file.
globals_dict = {}
if relocate:
globals_dict["__file__"] = os.path.join(relocate, "buildbot.tac")
exec(tac_contents, globals_dict, globals_dict) # pylint: disable=exec-used
# only one Application must be created in .tac
application_class_mock.assert_called_once_with("buildbot-worker")
# check that Worker created with passed options
worker_class_mock.assert_called_once_with(
expected_args["host"],
expected_args["port"],
expected_args["name"],
expected_args["passwd"],
expected_args["basedir"],
expected_args["keepalive"],
umask=expected_args["umask"],
numcpus=expected_args["numcpus"],
protocol=expected_args["protocol"],
maxdelay=expected_args["maxdelay"],
allow_shutdown=expected_args["allow-shutdown"],
maxRetries=expected_args["maxretries"],
useTls=expected_args["use-tls"],
delete_leftover_dirs=expected_args["delete-leftover-dirs"],
connection_string=expected_args["connection-string"],
proxy_connection_string=expected_args["proxy-connection-string"],
)
# check that Worker instance attached to application
self.assertEqual(worker_mock.method_calls, [mock.call.setServiceParent(application_mock)])
# .tac file must define global variable "application", instance of
# Application
self.assertTrue(
'application' in globals_dict, ".tac file doesn't define \"application\" variable"
)
self.assertTrue(
globals_dict['application'] is application_mock,
"defined \"application\" variable in .tac file is not Application instance",
)
def test_default_tac_contents(self):
"""
test that with default options generated TAC file is valid.
"""
tac_contents = create_worker._make_tac(self.options.copy())
self.assert_tac_file_contents(tac_contents, self.options)
def test_backslash_in_basedir(self):
"""
test that using backslash (typical for Windows platform) in basedir
won't break generated TAC file.
"""
options = self.options.copy()
options["basedir"] = r"C:\buildbot-worker dir\\"
tac_contents = create_worker._make_tac(options.copy())
self.assert_tac_file_contents(tac_contents, options)
def test_quotes_in_basedir(self):
"""
test that using quotes in basedir won't break generated TAC file.
"""
options = self.options.copy()
options["basedir"] = r"Buildbot's \"dir"
tac_contents = create_worker._make_tac(options.copy())
self.assert_tac_file_contents(tac_contents, options)
def test_double_quotes_in_basedir(self):
"""
test that using double quotes at begin and end of basedir won't break
generated TAC file.
"""
options = self.options.copy()
options["basedir"] = r"\"\"Buildbot''"
tac_contents = create_worker._make_tac(options.copy())
self.assert_tac_file_contents(tac_contents, options)
def test_special_characters_in_options(self):
"""
test that using special characters in options strings won't break
generated TAC file.
"""
test_string = "\"\" & | ^ # @ \\& \\| \\^ \\# \\@ \\n \x07 \" \\\" ' \\' ''"
options = self.options.copy()
options["basedir"] = test_string
options["host"] = test_string
options["passwd"] = test_string
options["name"] = test_string
tac_contents = create_worker._make_tac(options.copy())
self.assert_tac_file_contents(tac_contents, options)
def test_flags_with_non_default_values(self):
"""
test that flags with non-default values will be correctly written to
generated TAC file.
"""
options = self.options.copy()
options["quiet"] = True
options["use-tls"] = True
options["delete-leftover-dirs"] = True
tac_contents = create_worker._make_tac(options.copy())
self.assert_tac_file_contents(tac_contents, options)
def test_log_rotate(self):
"""
test that when --no-logrotate options is not used, correct tac file
is generated.
"""
options = self.options.copy()
options["no-logrotate"] = False
tac_contents = create_worker._make_tac(options.copy())
self.assertIn("from twisted.python.logfile import LogFile", tac_contents)
self.assert_tac_file_contents(tac_contents, options)
def test_no_log_rotate(self):
"""
test that when --no-logrotate options is used, correct tac file
is generated.
"""
options = self.options.copy()
options["no-logrotate"] = True
tac_contents = create_worker._make_tac(options.copy())
self.assertNotIn("from twisted.python.logfile import LogFile", tac_contents)
self.assert_tac_file_contents(tac_contents, options)
def test_relocatable_true(self):
"""
test that when --relocatable option is True, worker is created from
generated TAC file with correct basedir argument before and after
relocation.
"""
options = self.options.copy()
options["relocatable"] = True
options["basedir"] = os.path.join(os.getcwd(), "worker1")
tac_contents = create_worker._make_tac(options.copy())
self.assert_tac_file_contents(tac_contents, options, relocate=options["basedir"])
_relocate = os.path.join(os.getcwd(), "worker2")
options["basedir"] = _relocate
self.assert_tac_file_contents(tac_contents, options, relocate=_relocate)
def test_relocatable_false(self):
"""
test that when --relocatable option is False, worker is created from
generated TAC file with the same basedir argument before and after
relocation.
"""
options = self.options.copy()
options["relocatable"] = False
options["basedir"] = os.path.join(os.getcwd(), "worker1")
tac_contents = create_worker._make_tac(options.copy())
self.assert_tac_file_contents(tac_contents, options, relocate=options["basedir"])
_relocate = os.path.join(os.getcwd(), "worker2")
self.assert_tac_file_contents(tac_contents, options, relocate=_relocate)
def test_options_with_non_default_values(self):
"""
test that options with non-default values will be correctly written to
generated TAC file and used as argument of Worker.
"""
options = self.options.copy()
options["allow-shutdown"] = "signal"
options["umask"] = "18"
options["log-size"] = 160
options["log-count"] = "80"
options["keepalive"] = 40
options["maxdelay"] = 20
options["numcpus"] = "10"
options["protocol"] = "null"
options["maxretries"] = "1"
options["proxy-connection-string"] = "TCP:proxy.com:8080"
tac_contents = create_worker._make_tac(options.copy())
# These values are expected to be used as non-string literals in
# generated TAC file.
self.assertIn("rotateLength = 160", tac_contents)
self.assertIn("maxRotatedFiles = 80", tac_contents)
self.assertIn("keepalive = 40", tac_contents)
self.assertIn("maxdelay = 20", tac_contents)
self.assertIn("umask = 18", tac_contents)
self.assertIn("numcpus = 10", tac_contents)
self.assertIn("maxretries = 1", tac_contents)
# Check also as arguments used in Worker initialization.
options["umask"] = 18
options["numcpus"] = 10
options["maxretries"] = 1
self.assert_tac_file_contents(tac_contents, options)
def test_umask_octal_value(self):
"""
test that option umask with octal value will be correctly written to
generated TAC file and used as argument of Worker.
"""
options = self.options.copy()
options["umask"] = "0o22"
tac_contents = create_worker._make_tac(options.copy())
self.assertIn("umask = 0o22", tac_contents)
options["umask"] = 18
self.assert_tac_file_contents(tac_contents, options)
def test_connection_string(self):
"""
test that when --connection-string options is used, correct tac file
is generated.
"""
options = self.options.copy()
options["connection-string"] = "TLS:buildbot-master.com:9989"
tac_contents = create_worker._make_tac(options.copy())
options["host"] = None
options["port"] = None
self.assert_tac_file_contents(tac_contents, options)
class TestMakeBaseDir(misc.StdoutAssertionsMixin, unittest.TestCase):
"""
Test buildbot_worker.scripts.create_worker._makeBaseDir()
"""
def setUp(self):
# capture stdout
self.setUpStdoutAssertions()
# patch os.mkdir() to do nothing
self.mkdir = mock.Mock()
self.patch(os, "mkdir", self.mkdir)
def testBasedirExists(self):
"""
test calling _makeBaseDir() on existing base directory
"""
self.patch(os.path, "exists", mock.Mock(return_value=True))
# call _makeBaseDir()
create_worker._makeBaseDir("dummy", False)
# check that correct message was printed to stdout
self.assertStdoutEqual("updating existing installation\n")
# check that os.mkdir was not called
self.assertFalse(self.mkdir.called, "unexpected call to os.mkdir()")
def testBasedirExistsQuiet(self):
"""
test calling _makeBaseDir() on existing base directory with
quiet flag enabled
"""
self.patch(os.path, "exists", mock.Mock(return_value=True))
# call _makeBaseDir()
create_worker._makeBaseDir("dummy", True)
# check that nothing was printed to stdout
self.assertWasQuiet()
# check that os.mkdir was not called
self.assertFalse(self.mkdir.called, "unexpected call to os.mkdir()")
def testBasedirCreated(self):
"""
test creating new base directory with _makeBaseDir()
"""
self.patch(os.path, "exists", mock.Mock(return_value=False))
# call _makeBaseDir()
create_worker._makeBaseDir("dummy", False)
# check that os.mkdir() was called with correct path
self.mkdir.assert_called_once_with("dummy")
# check that correct message was printed to stdout
self.assertStdoutEqual("mkdir dummy\n")
def testBasedirCreatedQuiet(self):
"""
test creating new base directory with _makeBaseDir()
and quiet flag enabled
"""
self.patch(os.path, "exists", mock.Mock(return_value=False))
# call _makeBaseDir()
create_worker._makeBaseDir("dummy", True)
# check that os.mkdir() was called with correct path
self.mkdir.assert_called_once_with("dummy")
# check that nothing was printed to stdout
self.assertWasQuiet()
def testMkdirError(self):
"""
test that _makeBaseDir() handles error creating directory correctly
"""
self.patch(os.path, "exists", mock.Mock(return_value=False))
# patch os.mkdir() to raise an exception
self.patch(os, "mkdir", mock.Mock(side_effect=OSError(0, "dummy-error")))
# check that correct exception was raised
with self.assertRaisesRegex(
create_worker.CreateWorkerError, "error creating directory dummy"
):
create_worker._makeBaseDir("dummy", False)
class TestMakeBuildbotTac(misc.StdoutAssertionsMixin, misc.FileIOMixin, unittest.TestCase):
"""
Test buildbot_worker.scripts.create_worker._makeBuildbotTac()
"""
def setUp(self):
# capture stdout
self.setUpStdoutAssertions()
# patch os.chmod() to do nothing
self.chmod = mock.Mock()
self.patch(os, "chmod", self.chmod)
# generate OS specific relative path to buildbot.tac inside basedir
self.tac_file_path = _regexp_path("bdir", "buildbot.tac")
def testTacOpenError(self):
"""
test that _makeBuildbotTac() handles open() errors on buildbot.tac
"""
self.patch(os.path, "exists", mock.Mock(return_value=True))
# patch open() to raise exception
self.setUpOpenError()
# call _makeBuildbotTac() and check that correct exception is raised
expected_message = f"error reading {self.tac_file_path}"
with self.assertRaisesRegex(create_worker.CreateWorkerError, expected_message):
create_worker._makeBuildbotTac("bdir", "contents", False)
def testTacReadError(self):
"""
test that _makeBuildbotTac() handles read() errors on buildbot.tac
"""
self.patch(os.path, "exists", mock.Mock(return_value=True))
# patch read() to raise exception
self.setUpReadError()
# call _makeBuildbotTac() and check that correct exception is raised
expected_message = f"error reading {self.tac_file_path}"
with self.assertRaisesRegex(create_worker.CreateWorkerError, expected_message):
create_worker._makeBuildbotTac("bdir", "contents", False)
def testTacWriteError(self):
"""
test that _makeBuildbotTac() handles write() errors on buildbot.tac
"""
self.patch(os.path, "exists", mock.Mock(return_value=False))
# patch write() to raise exception
self.setUpWriteError(0)
# call _makeBuildbotTac() and check that correct exception is raised
expected_message = f"could not write {self.tac_file_path}"
with self.assertRaisesRegex(create_worker.CreateWorkerError, expected_message):
create_worker._makeBuildbotTac("bdir", "contents", False)
def checkTacFileCorrect(self, quiet):
"""
Utility function to test calling _makeBuildbotTac() on base directory
with existing buildbot.tac file, which does not need to be changed.
@param quiet: the value of 'quiet' argument for _makeBuildbotTac()
"""
# set-up mocks to simulate buildbot.tac file in the basedir
self.patch(os.path, "exists", mock.Mock(return_value=True))
self.setUpOpen("test-tac-contents")
# call _makeBuildbotTac()
create_worker._makeBuildbotTac("bdir", "test-tac-contents", quiet)
# check that write() was not called
self.assertFalse(self.fileobj.write.called, "unexpected write() call")
# check output to stdout
if quiet:
self.assertWasQuiet()
else:
self.assertStdoutEqual("buildbot.tac already exists and is correct\n")
def testTacFileCorrect(self):
"""
call _makeBuildbotTac() on base directory which contains a buildbot.tac
file, which does not need to be changed
"""
self.checkTacFileCorrect(False)
def testTacFileCorrectQuiet(self):
"""
call _makeBuildbotTac() on base directory which contains a buildbot.tac
file, which does not need to be changed. Check that quite flag works
"""
self.checkTacFileCorrect(True)
def checkDiffTacFile(self, quiet):
"""
Utility function to test calling _makeBuildbotTac() on base directory
with a buildbot.tac file, with does needs to be changed.
@param quiet: the value of 'quiet' argument for _makeBuildbotTac()
"""
# set-up mocks to simulate buildbot.tac file in basedir
self.patch(os.path, "exists", mock.Mock(return_value=True))
self.setUpOpen("old-tac-contents")
# call _makeBuildbotTac()
create_worker._makeBuildbotTac("bdir", "new-tac-contents", quiet)
# check that buildbot.tac.new file was created with expected contents
tac_file_path = os.path.join("bdir", "buildbot.tac")
self.open.assert_has_calls([
mock.call(tac_file_path),
mock.call(tac_file_path + ".new", "w"),
])
self.fileobj.write.assert_called_once_with("new-tac-contents")
self.chmod.assert_called_once_with(tac_file_path + ".new", 0o600)
# check output to stdout
if quiet:
self.assertWasQuiet()
else:
self.assertStdoutEqual(
"not touching existing buildbot.tac\ncreating buildbot.tac.new instead\n"
)
def testDiffTacFile(self):
"""
call _makeBuildbotTac() on base directory which contains a buildbot.tac
file, with does needs to be changed.
"""
self.checkDiffTacFile(False)
def testDiffTacFileQuiet(self):
"""
call _makeBuildbotTac() on base directory which contains a buildbot.tac
file, with does needs to be changed. Check that quite flag works
"""
self.checkDiffTacFile(True)
def testNoTacFile(self):
"""
call _makeBuildbotTac() on base directory with no buildbot.tac file
"""
self.patch(os.path, "exists", mock.Mock(return_value=False))
# capture calls to open() and write()
self.setUpOpen()
# call _makeBuildbotTac()
create_worker._makeBuildbotTac("bdir", "test-tac-contents", False)
# check that buildbot.tac file was created with expected contents
tac_file_path = os.path.join("bdir", "buildbot.tac")
self.open.assert_called_once_with(tac_file_path, "w")
self.fileobj.write.assert_called_once_with("test-tac-contents")
self.chmod.assert_called_once_with(tac_file_path, 0o600)
class TestMakeInfoFiles(misc.StdoutAssertionsMixin, misc.FileIOMixin, unittest.TestCase):
"""
Test buildbot_worker.scripts.create_worker._makeInfoFiles()
"""
def setUp(self):
# capture stdout
self.setUpStdoutAssertions()
def checkMkdirError(self, quiet):
"""
Utility function to test _makeInfoFiles() when os.mkdir() fails.
Patch os.mkdir() to raise an exception, and check that _makeInfoFiles()
handles mkdir errors correctly.
@param quiet: the value of 'quiet' argument for _makeInfoFiles()
"""
self.patch(os.path, "exists", mock.Mock(return_value=False))
# patch os.mkdir() to raise an exception
self.patch(os, "mkdir", mock.Mock(side_effect=OSError(0, "err-msg")))
# call _makeInfoFiles() and check that correct exception is raised
with self.assertRaisesRegex(
create_worker.CreateWorkerError,
"error creating directory {}".format(_regexp_path("bdir", "info")),
):
create_worker._makeInfoFiles("bdir", quiet)
# check output to stdout
if quiet:
self.assertWasQuiet()
else:
self.assertStdoutEqual("mkdir {}\n".format(os.path.join("bdir", "info")))
def testMkdirError(self):
"""
test _makeInfoFiles() when os.mkdir() fails
"""
self.checkMkdirError(False)
def testMkdirErrorQuiet(self):
"""
test _makeInfoFiles() when os.mkdir() fails and quiet flag is enabled
"""
self.checkMkdirError(True)
def checkIOError(self, error_type, quiet):
"""
Utility function to test _makeInfoFiles() when open() or write() fails.
Patch file IO functions to raise an exception, and check that
_makeInfoFiles() handles file IO errors correctly.
@param error_type: type of error to emulate,
'open' - patch open() to fail
'write' - patch write() to fail
@param quiet: the value of 'quiet' argument for _makeInfoFiles()
"""
# patch os.path.exists() to simulate that 'info' directory exists
# but not 'admin' or 'host' files
self.patch(os.path, "exists", lambda path: path.endswith("info"))
# set-up requested IO error
if error_type == "open":
self.setUpOpenError()
elif error_type == "write":
self.setUpWriteError()
else:
self.fail(f"unexpected error_type '{error_type}'")
# call _makeInfoFiles() and check that correct exception is raised
with self.assertRaisesRegex(
create_worker.CreateWorkerError,
"could not write {}".format(_regexp_path("bdir", "info", "admin")),
):
create_worker._makeInfoFiles("bdir", quiet)
# check output to stdout
if quiet:
self.assertWasQuiet()
else:
self.assertStdoutEqual(
"Creating {}, you need to edit it appropriately.\n".format(
os.path.join("info", "admin")
)
)
def testOpenError(self):
"""
test _makeInfoFiles() when open() fails
"""
self.checkIOError("open", False)
def testOpenErrorQuiet(self):
"""
test _makeInfoFiles() when open() fails and quiet flag is enabled
"""
self.checkIOError("open", True)
def testWriteError(self):
"""
test _makeInfoFiles() when write() fails
"""
self.checkIOError("write", False)
def testWriteErrorQuiet(self):
"""
test _makeInfoFiles() when write() fails and quiet flag is enabled
"""
self.checkIOError("write", True)
def checkCreatedSuccessfully(self, quiet):
"""
Utility function to test _makeInfoFiles() when called on
base directory that does not have 'info' sub-directory.
@param quiet: the value of 'quiet' argument for _makeInfoFiles()
"""
# patch os.path.exists() to report the no dirs/files exists
self.patch(os.path, "exists", mock.Mock(return_value=False))
# patch os.mkdir() to do nothing
mkdir_mock = mock.Mock()
self.patch(os, "mkdir", mkdir_mock)
# capture calls to open() and write()
self.setUpOpen()
# call _makeInfoFiles()
create_worker._makeInfoFiles("bdir", quiet)
# check calls to os.mkdir()
info_path = os.path.join("bdir", "info")
mkdir_mock.assert_called_once_with(info_path)
# check open() calls
self.open.assert_has_calls([
mock.call(os.path.join(info_path, "admin"), "w"),
mock.call(os.path.join(info_path, "host"), "w"),
])
# check write() calls
self.fileobj.write.assert_has_calls([
mock.call("Your Name Here <[email protected]>\n"),
mock.call("Please put a description of this build host here\n"),
])
# check output to stdout
if quiet:
self.assertWasQuiet()
else:
self.assertStdoutEqual(
(
"mkdir {}\n"
"Creating {}, you need to edit it appropriately.\n"
"Creating {}, you need to edit it appropriately.\n"
"Not creating {} - add it if you wish\n"
"Please edit the files in {} appropriately.\n"
).format(
info_path,
os.path.join("info", "admin"),
os.path.join("info", "host"),
os.path.join("info", "access_uri"),
info_path,
)
)
def testCreatedSuccessfully(self):
"""
test calling _makeInfoFiles() on basedir without 'info' directory
"""
self.checkCreatedSuccessfully(False)
def testCreatedSuccessfullyQuiet(self):
"""
test calling _makeInfoFiles() on basedir without 'info' directory
and quiet flag is enabled
"""
self.checkCreatedSuccessfully(True)
def testInfoDirExists(self):
"""
test calling _makeInfoFiles() on basedir with fully populated
'info' directory
"""
self.patch(os.path, "exists", mock.Mock(return_value=True))
create_worker._makeInfoFiles("bdir", False)
# there should be no messages to stdout
self.assertWasQuiet()
class TestCreateWorker(misc.StdoutAssertionsMixin, TestDefaultOptionsMixin, unittest.TestCase):
"""
Test buildbot_worker.scripts.create_worker.createWorker()
"""
def setUp(self):
# capture stdout
self.setUpStdoutAssertions()
def setUpMakeFunctions(self, exception=None):
"""
patch create_worker._make*() functions with a mocks
@param exception: if not None, the mocks will raise this exception.
"""
self._makeBaseDir = mock.Mock(side_effect=exception)
self.patch(create_worker, "_makeBaseDir", self._makeBaseDir)
self._makeBuildbotTac = mock.Mock(side_effect=exception)
self.patch(create_worker, "_makeBuildbotTac", self._makeBuildbotTac)
self._makeInfoFiles = mock.Mock(side_effect=exception)
self.patch(create_worker, "_makeInfoFiles", self._makeInfoFiles)
def assertMakeFunctionsCalls(self, basedir, tac_contents, quiet):
"""
assert that create_worker._make*() were called with specified arguments
"""
self._makeBaseDir.assert_called_once_with(basedir, quiet)
self._makeBuildbotTac.assert_called_once_with(basedir, tac_contents, quiet)
self._makeInfoFiles.assert_called_once_with(basedir, quiet)
def testCreateError(self):
"""
test that errors while creating worker directory are handled
correctly by createWorker()
"""
# patch _make*() functions to raise an exception
self.setUpMakeFunctions(create_worker.CreateWorkerError("err-msg"))
# call createWorker() and check that we get error exit code
self.assertEqual(create_worker.createWorker(self.options), 1, "unexpected exit code")
# check that correct error message was printed on stdout
self.assertStdoutEqual("err-msg\nfailed to configure worker in bdir\n")
def testMinArgs(self):
"""
test calling createWorker() with only required arguments
"""
# patch _make*() functions to do nothing
self.setUpMakeFunctions()
# call createWorker() and check that we get success exit code
self.assertEqual(create_worker.createWorker(self.options), 0, "unexpected exit code")
# check _make*() functions were called with correct arguments
expected_tac_contents = create_worker._make_tac(self.options.copy())
self.assertMakeFunctionsCalls(
self.options["basedir"], expected_tac_contents, self.options["quiet"]
)
# check that correct info message was printed
self.assertStdoutEqual("worker configured in bdir\n")
def testQuiet(self):
"""
test calling createWorker() with --quiet flag
"""
options = self.options.copy()
options["quiet"] = True
# patch _make*() functions to do nothing
self.setUpMakeFunctions()
# call createWorker() and check that we get success exit code
self.assertEqual(create_worker.createWorker(options), 0, "unexpected exit code")
# check _make*() functions were called with correct arguments
expected_tac_contents = create_worker._make_tac(self.options)
self.assertMakeFunctionsCalls(options["basedir"], expected_tac_contents, options["quiet"])
# there should be no output on stdout
self.assertWasQuiet()
| 31,018 | Python | .py | 697 | 35.388809 | 98 | 0.636174 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
5,054 | test_bot.py | buildbot_buildbot/worker/buildbot_worker/test/unit/test_bot.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 multiprocessing
import os
import shutil
from twisted.internet import defer
from twisted.internet import reactor
from twisted.internet import task
from twisted.python import failure
from twisted.python import log
from twisted.trial import unittest
import buildbot_worker
from buildbot_worker import base
from buildbot_worker import pb
from buildbot_worker.commands.base import Command
from buildbot_worker.test.fake.remote import FakeRemote
from buildbot_worker.test.fake.runprocess import Expect
from buildbot_worker.test.util import command
try:
from unittest import mock
except ImportError:
from unittest import mock
class TestBot(unittest.TestCase):
def setUp(self):
self.basedir = os.path.abspath("basedir")
if os.path.exists(self.basedir):
shutil.rmtree(self.basedir)
os.makedirs(self.basedir)
# create test-release-file
with open(f"{self.basedir}/test-release-file", "w") as fout:
fout.write("""
# unit test release file
OS_NAME="Test"
VERSION="1.0"
ID=test
ID_LIKE=generic
PRETTY_NAME="Test 1.0 Generic"
VERSION_ID="1"
""")
self.real_bot = pb.BotPbLike(self.basedir, False)
self.real_bot.setOsReleaseFile(f"{self.basedir}/test-release-file")
self.real_bot.startService()
self.bot = FakeRemote(self.real_bot)
@defer.inlineCallbacks
def tearDown(self):
if self.real_bot and self.real_bot.running:
yield self.real_bot.stopService()
if os.path.exists(self.basedir):
shutil.rmtree(self.basedir)
@defer.inlineCallbacks
def test_getCommands(self):
cmds = yield self.bot.callRemote("getCommands")
# just check that 'shell' is present..
self.assertTrue('shell' in cmds)
@defer.inlineCallbacks
def test_getVersion(self):
vers = yield self.bot.callRemote("getVersion")
self.assertEqual(vers, buildbot_worker.version)
@defer.inlineCallbacks
def test_getWorkerInfo(self):
infodir = os.path.join(self.basedir, "info")
os.makedirs(infodir)
with open(os.path.join(infodir, "admin"), "w") as f:
f.write("testy!")
with open(os.path.join(infodir, "foo"), "w") as f:
f.write("bar")
with open(os.path.join(infodir, "environ"), "w") as f:
f.write("something else")
info = yield self.bot.callRemote("getWorkerInfo")
# remove any os_ fields as they are dependent on the test environment
info = {k: v for k, v in info.items() if not k.startswith("os_")}
self.assertEqual(
info,
{
"admin": 'testy!',
"foo": 'bar',
"environ": os.environ,
"system": os.name,
"basedir": self.basedir,
"worker_commands": self.real_bot.remote_getCommands(),
"version": self.real_bot.remote_getVersion(),
"numcpus": multiprocessing.cpu_count(),
"delete_leftover_dirs": False,
},
)
@defer.inlineCallbacks
def test_getWorkerInfo_nodir(self):
info = yield self.bot.callRemote("getWorkerInfo")
info = {k: v for k, v in info.items() if not k.startswith("os_")}
self.assertEqual(
set(info.keys()),
set([
'environ',
'system',
'numcpus',
'basedir',
'worker_commands',
'version',
'delete_leftover_dirs',
]),
)
@defer.inlineCallbacks
def test_getWorkerInfo_decode_error(self):
infodir = os.path.join(self.basedir, "info")
os.makedirs(infodir)
with open(os.path.join(infodir, "admin"), "w") as f:
f.write("testy!")
with open(os.path.join(infodir, "foo"), "w") as f:
f.write("bar")
with open(os.path.join(infodir, "environ"), "w") as f:
f.write("something else")
# This will not be part of worker info
with open(os.path.join(infodir, "binary"), "wb") as f:
f.write(b"\x90")
# patch the log.err, otherwise trial will think something *actually*
# failed
self.patch(log, "err", lambda f, x: None)
info = yield self.bot.callRemote("getWorkerInfo")
# remove any os_ fields as they are dependent on the test environment
info = {k: v for k, v in info.items() if not k.startswith("os_")}
self.assertEqual(
info,
{
"admin": 'testy!',
"foo": 'bar',
"environ": os.environ,
"system": os.name,
"basedir": self.basedir,
"worker_commands": self.real_bot.remote_getCommands(),
"version": self.real_bot.remote_getVersion(),
"numcpus": multiprocessing.cpu_count(),
"delete_leftover_dirs": False,
},
)
def test_shutdown(self):
d1 = defer.Deferred()
self.patch(reactor, "stop", lambda: d1.callback(None))
d2 = self.bot.callRemote("shutdown")
# don't return until both the shutdown method has returned, and
# reactor.stop has been called
return defer.gatherResults([d1, d2])
class FakeStep:
"A fake master-side BuildStep that records its activities."
def __init__(self):
self.finished_d = defer.Deferred()
self.actions = []
def wait_for_finish(self):
return self.finished_d
def remote_update(self, updates):
for update in updates:
if 'elapsed' in update[0]:
update[0]['elapsed'] = 1
self.actions.append(["update", updates])
def remote_complete(self, f):
self.actions.append(["complete", f])
self.finished_d.callback(None)
class FakeBot(pb.BotPbLike):
WorkerForBuilder = pb.WorkerForBuilderPbLike
class TestWorkerForBuilder(command.CommandTestMixin, unittest.TestCase):
@defer.inlineCallbacks
def setUp(self):
self.basedir = os.path.abspath("basedir")
if os.path.exists(self.basedir):
shutil.rmtree(self.basedir)
os.makedirs(self.basedir)
self.bot = FakeBot(self.basedir, False)
self.bot.startService()
# get a WorkerForBuilder object from the bot and wrap it as a fake
# remote
builders = yield self.bot.remote_setBuilderList([('wfb', 'wfb')])
self.wfb = FakeRemote(builders['wfb'])
self.setUpCommand()
@defer.inlineCallbacks
def tearDown(self):
self.tearDownCommand()
if self.bot and self.bot.running:
yield self.bot.stopService()
if os.path.exists(self.basedir):
shutil.rmtree(self.basedir)
def test_print(self):
return self.wfb.callRemote("print", "Hello, WorkerForBuilder.")
def test_printWithCommand(self):
self.wfb.original.command = Command("builder", "1", ["arg1", "arg2"])
return self.wfb.callRemote("print", "Hello again, WorkerForBuilder.")
def test_setMaster(self):
# not much to check here - what the WorkerForBuilder does with the
# master is not part of the interface (and, in fact, it does very
# little)
return self.wfb.callRemote("setMaster", mock.Mock())
def test_startBuild(self):
return self.wfb.callRemote("startBuild")
@defer.inlineCallbacks
def test_startCommand(self):
# set up a fake step to receive updates
st = FakeStep()
# patch runprocess to handle the 'echo', below
self.patch_runprocess(
Expect(['echo', 'hello'], os.path.join(self.basedir, 'wfb', 'workdir'))
.update('header', 'headers')
.update('stdout', 'hello\n')
.update('rc', 0)
.exit(0)
)
yield self.wfb.callRemote(
"startCommand",
FakeRemote(st),
"13",
"shell",
{"command": ['echo', 'hello'], "workdir": 'workdir'},
)
yield st.wait_for_finish()
self.assertEqual(
st.actions,
[
['update', [[{'stdout': 'hello\n'}, 0]]],
['update', [[{'rc': 0}, 0]]],
['update', [[{'elapsed': 1}, 0]]],
['update', [[{'header': 'headers\n'}, 0]]],
['complete', None],
],
)
@defer.inlineCallbacks
def test_startCommand_interruptCommand(self):
# set up a fake step to receive updates
st = FakeStep()
# patch runprocess to pretend to sleep (it will really just hang forever,
# except that we interrupt it)
self.patch_runprocess(
Expect(['sleep', '10'], os.path.join(self.basedir, 'wfb', 'workdir'))
.update('header', 'headers')
.update('wait', True)
)
yield self.wfb.callRemote(
"startCommand",
FakeRemote(st),
"13",
"shell",
{"command": ['sleep', '10'], "workdir": 'workdir'},
)
# wait a jiffy..
d = defer.Deferred()
reactor.callLater(0.01, d.callback, None)
yield d
# and then interrupt the step
yield self.wfb.callRemote("interruptCommand", "13", "tl/dr")
yield st.wait_for_finish()
self.assertEqual(
st.actions,
[
['update', [[{'rc': -1}, 0]]],
['update', [[{'header': 'headerskilling\n'}, 0]]],
['complete', None],
],
)
@defer.inlineCallbacks
def test_startCommand_failure(self):
# set up a fake step to receive updates
st = FakeStep()
# patch runprocess to generate a failure
self.patch_runprocess(
Expect(['sleep', '10'], os.path.join(self.basedir, 'wfb', 'workdir')).exception(
failure.Failure(Exception("Oops"))
)
)
# patch the log.err, otherwise trial will think something *actually*
# failed
self.patch(log, "err", lambda f: None)
yield self.wfb.callRemote(
"startCommand",
FakeRemote(st),
"13",
"shell",
{"command": ['sleep', '10'], "workdir": 'workdir'},
)
yield st.wait_for_finish()
self.assertEqual(st.actions[1][0], 'complete')
self.assertTrue(isinstance(st.actions[1][1], failure.Failure))
@defer.inlineCallbacks
def test_startCommand_missing_args(self):
# set up a fake step to receive updates
st = FakeStep()
def do_start():
return self.wfb.callRemote("startCommand", FakeRemote(st), "13", "shell", {})
yield self.assertFailure(do_start(), KeyError)
@defer.inlineCallbacks
def test_startCommand_invalid_command(self):
# set up a fake step to receive updates
st = FakeStep()
def do_start():
return self.wfb.callRemote("startCommand", FakeRemote(st), "13", "invalid command", {})
unknownCommand = yield self.assertFailure(do_start(), base.UnknownCommand)
self.assertEqual(
str(unknownCommand), "(command 13): unrecognized WorkerCommand 'invalid command'"
)
class TestBotFactory(unittest.TestCase):
def setUp(self):
self.bf = pb.BotFactory('mstr', 9010, 35, 200)
# tests
def test_timers(self):
clock = self.bf._reactor = task.Clock()
calls = []
def callRemote(method):
calls.append(clock.seconds())
self.assertEqual(method, 'keepalive')
# simulate the response taking a few seconds
d = defer.Deferred()
clock.callLater(5, d.callback, None)
return d
self.bf.perspective = mock.Mock()
self.bf.perspective.callRemote = callRemote
self.bf.startTimers()
clock.callLater(100, self.bf.stopTimers)
clock.pump(1 for _ in range(150))
self.assertEqual(calls, [35, 70])
def test_timers_exception(self):
clock = self.bf._reactor = task.Clock()
self.bf.perspective = mock.Mock()
def callRemote(method):
return defer.fail(RuntimeError("oh noes"))
self.bf.perspective.callRemote = callRemote
self.bf.startTimers()
clock.advance(35)
self.assertEqual(len(self.flushLoggedErrors(RuntimeError)), 1)
# note that the Worker class is tested in test_bot_Worker
| 13,323 | Python | .py | 336 | 30.419643 | 99 | 0.602557 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
5,055 | test_util_deferwaiter.py | buildbot_buildbot/worker/buildbot_worker/test/unit/test_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.trial import unittest
from buildbot_worker.util.deferwaiter import DeferWaiter
class TestException(Exception):
pass
class WaiterTests(unittest.TestCase):
def test_add_deferred_called(self):
w = DeferWaiter()
w.add(defer.succeed(None))
self.assertFalse(w.has_waited())
d = w.wait()
self.assertTrue(d.called)
def test_add_non_deferred(self):
w = DeferWaiter()
w.add(2)
self.assertFalse(w.has_waited())
d = w.wait()
self.assertTrue(d.called)
def test_add_deferred_not_called_and_call_later(self):
w = DeferWaiter()
d1 = defer.Deferred()
w.add(d1)
self.assertTrue(w.has_waited())
d = w.wait()
self.assertFalse(d.called)
d1.callback(None)
self.assertFalse(w.has_waited())
self.assertTrue(d.called)
@defer.inlineCallbacks
def test_passes_result(self):
w = DeferWaiter()
d1 = defer.Deferred()
w.add(d1)
d1.callback(123)
res = yield d1
self.assertEqual(res, 123)
d = w.wait()
self.assertTrue(d.called)
@defer.inlineCallbacks
def test_cancel_not_called(self):
w = DeferWaiter()
d1 = defer.Deferred()
w.add(d1)
self.assertTrue(w.has_waited())
w.cancel()
self.assertFalse(w.has_waited())
d = w.wait()
self.assertTrue(d.called)
with self.assertRaises(defer.CancelledError):
yield d1
self.flushLoggedErrors(defer.CancelledError)
@defer.inlineCallbacks
def test_cancel_called(self):
w = DeferWaiter()
d1_waited = defer.Deferred()
d1 = defer.succeed(None)
d1.addCallback(lambda _: d1_waited)
w.add(d1)
w.cancel()
d = w.wait()
self.assertTrue(d.called)
self.assertTrue(d1.called)
self.assertTrue(d1_waited.called)
with self.assertRaises(defer.CancelledError):
yield d1
self.flushLoggedErrors(defer.CancelledError)
| 2,834 | Python | .py | 80 | 28.3875 | 79 | 0.661533 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
5,056 | test_scripts_restart.py | buildbot_buildbot/worker/buildbot_worker/test/unit/test_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 twisted.trial import unittest
from buildbot_worker.scripts import restart
from buildbot_worker.scripts import start
from buildbot_worker.scripts import stop
from buildbot_worker.test.util import misc
try:
from unittest import mock
except ImportError:
from unittest import mock
class TestRestart(misc.IsWorkerDirMixin, misc.StdoutAssertionsMixin, unittest.TestCase):
"""
Test buildbot_worker.scripts.restart.restart()
"""
config = {"basedir": "dummy", "nodaemon": False, "quiet": False}
def setUp(self):
self.setUpStdoutAssertions()
# patch start.startWorker() to do nothing
self.startWorker = mock.Mock()
self.patch(start, "startWorker", self.startWorker)
def test_bad_basedir(self):
"""
test calling restart() with invalid basedir path
"""
# patch isWorkerDir() to fail
self.setupUpIsWorkerDir(False)
# call startCommand() and check that correct exit code is returned
self.assertEqual(restart.restart(self.config), 1, "unexpected exit code")
# check that isWorkerDir was called with correct argument
self.isWorkerDir.assert_called_once_with(self.config["basedir"])
def test_no_worker_running(self):
"""
test calling restart() when no worker is running
"""
# patch basedir check to always succeed
self.setupUpIsWorkerDir(True)
# patch stopWorker() to raise an exception
mock_stopWorker = mock.Mock(side_effect=stop.WorkerNotRunning())
self.patch(stop, "stopWorker", mock_stopWorker)
# check that restart() calls startWorker() and outputs correct messages
restart.restart(self.config)
self.startWorker.assert_called_once_with(
self.config["basedir"], self.config["quiet"], self.config["nodaemon"]
)
self.assertStdoutEqual(
"no old worker process found to stop\nnow restarting worker process..\n"
)
def test_restart(self):
"""
test calling restart() when worker is running
"""
# patch basedir check to always succeed
self.setupUpIsWorkerDir(True)
# patch stopWorker() to do nothing
mock_stopWorker = mock.Mock()
self.patch(stop, "stopWorker", mock_stopWorker)
# check that restart() calls startWorker() and outputs correct messages
restart.restart(self.config)
self.startWorker.assert_called_once_with(
self.config["basedir"], self.config["quiet"], self.config["nodaemon"]
)
self.assertStdoutEqual("now restarting worker process..\n")
| 3,358 | Python | .py | 75 | 38.24 | 88 | 0.703125 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
5,057 | test_commands_fs.py | buildbot_buildbot/worker/buildbot_worker/test/unit/test_commands_fs.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 shutil
import stat
import sys
from twisted.internet import defer
from twisted.python import runtime
from twisted.trial import unittest
from buildbot_worker.commands import fs
from buildbot_worker.commands import utils
from buildbot_worker.test.fake.runprocess import Expect
from buildbot_worker.test.util.command import CommandTestMixin
from buildbot_worker.test.util.compat import skipUnlessPlatformIs
class TestRemoveDirectory(CommandTestMixin, unittest.TestCase):
def setUp(self):
self.setUpCommand()
def tearDown(self):
self.tearDownCommand()
@defer.inlineCallbacks
def test_simple_real(self):
file_path = os.path.join(self.basedir, 'workdir')
self.make_command(fs.RemoveDirectory, {'paths': [file_path]}, True)
yield self.run_command()
self.assertFalse(os.path.exists(os.path.abspath(file_path)))
self.assertIn(('rc', 0), self.get_updates(), self.protocol_command.show())
@skipUnlessPlatformIs('posix')
@defer.inlineCallbacks
def test_simple_posix(self):
file_path = os.path.join(self.basedir, 'remove')
self.make_command(fs.RemoveDirectory, {'paths': [file_path]}, True)
self.patch_runprocess(
Expect(["rm", "-rf", file_path], self.basedir, sendRC=0, timeout=120)
.update('header', 'headers')
.update('stdout', '')
.update('rc', 0)
.exit(0)
)
yield self.run_command()
self.assertEqual(self.get_updates()[-2], ('rc', 0))
self.assertIn('elapsed', self.get_updates()[-1])
@defer.inlineCallbacks
def test_simple_exception_real(self):
if runtime.platformType == "posix":
return # we only use rmdirRecursive on windows
def fail(dir):
raise RuntimeError("oh noes")
self.patch(utils, 'rmdirRecursive', fail)
self.make_command(fs.RemoveDirectory, {'paths': ['workdir']}, True)
yield self.run_command()
self.assertIn(('rc', -1), self.get_updates(), self.protocol_command.show())
@defer.inlineCallbacks
def test_multiple_dirs_real(self):
paths = [os.path.join(self.basedir, 'workdir'), os.path.join(self.basedir, 'sourcedir')]
self.make_command(fs.RemoveDirectory, {'paths': paths}, True)
yield self.run_command()
for path in paths:
self.assertFalse(os.path.exists(os.path.abspath(path)))
self.assertIn(('rc', 0), self.get_updates(), self.protocol_command.show())
@skipUnlessPlatformIs('posix')
@defer.inlineCallbacks
def test_multiple_dirs_posix(self):
dir_1 = os.path.join(self.basedir, 'remove_1')
dir_2 = os.path.join(self.basedir, 'remove_2')
self.make_command(fs.RemoveDirectory, {'paths': [dir_1, dir_2]}, True)
self.patch_runprocess(
Expect(["rm", "-rf", dir_1], self.basedir, sendRC=0, timeout=120)
.update('header', 'headers')
.update('stdout', '')
.update('rc', 0)
.exit(0),
Expect(["rm", "-rf", dir_2], self.basedir, sendRC=0, timeout=120)
.update('header', 'headers')
.update('stdout', '')
.update('rc', 0)
.exit(0),
)
yield self.run_command()
self.assertEqual(self.get_updates()[-2], ('rc', 0))
self.assertIn('elapsed', self.get_updates()[-1])
@skipUnlessPlatformIs('posix')
@defer.inlineCallbacks
def test_rm_after_chmod(self):
dir = os.path.join(self.basedir, 'remove')
self.make_command(fs.RemoveDirectory, {'paths': [dir]}, True)
self.patch_runprocess(
Expect(["rm", "-rf", dir], self.basedir, sendRC=0, timeout=120)
.update('header', 'headers')
.update('stderr', 'permission denied')
.update('rc', 1)
.exit(1),
Expect(['chmod', '-Rf', 'u+rwx', dir], self.basedir, sendRC=0, timeout=120)
.update('header', 'headers')
.update('stdout', '')
.update('rc', 0)
.exit(0),
Expect(["rm", "-rf", dir], self.basedir, sendRC=0, timeout=120)
.update('header', 'headers')
.update('stdout', '')
.update('rc', 0)
.exit(0),
)
yield self.run_command()
self.assertEqual(self.get_updates()[-2], ('rc', 0))
self.assertIn('elapsed', self.get_updates()[-1])
@skipUnlessPlatformIs('posix')
@defer.inlineCallbacks
def test_rm_after_failed(self):
dir = os.path.join(self.basedir, 'remove')
self.make_command(fs.RemoveDirectory, {'paths': [dir]}, True)
self.patch_runprocess(
Expect(["rm", "-rf", dir], self.basedir, sendRC=0, timeout=120)
.update('header', 'headers')
.update('stderr', 'permission denied')
.update('rc', 1)
.exit(1),
Expect(['chmod', '-Rf', 'u+rwx', dir], self.basedir, sendRC=0, timeout=120)
.update('header', 'headers')
.update('stdout', '')
.update('rc', 0)
.exit(0),
Expect(["rm", "-rf", dir], self.basedir, sendRC=0, timeout=120)
.update('header', 'headers')
.update('stdout', '')
.update('rc', 1)
.exit(1),
)
yield self.run_command()
self.assertEqual(self.get_updates()[-2], ('rc', 1))
self.assertIn('elapsed', self.get_updates()[-1])
class TestCopyDirectory(CommandTestMixin, unittest.TestCase):
def setUp(self):
self.setUpCommand()
def tearDown(self):
self.tearDownCommand()
@defer.inlineCallbacks
def test_simple(self):
from_path = os.path.join(self.basedir, 'workdir')
to_path = os.path.join(self.basedir, 'copy')
self.make_command(fs.CopyDirectory, {'from_path': from_path, 'to_path': to_path}, True)
yield self.run_command()
self.assertTrue(os.path.exists(os.path.abspath(to_path)))
self.assertIn(
('rc', 0), # this may ignore a 'header' : '..', which is OK
self.get_updates(),
self.protocol_command.show(),
)
@defer.inlineCallbacks
def test_simple_exception(self):
if runtime.platformType == "posix":
return # we only use rmdirRecursive on windows
def fail(src, dest):
raise RuntimeError("oh noes")
self.patch(shutil, 'copytree', fail)
from_path = os.path.join(self.basedir, 'workdir')
to_path = os.path.join(self.basedir, 'copy')
self.make_command(fs.CopyDirectory, {'from_path': from_path, 'to_path': to_path}, True)
yield self.run_command()
self.assertIn(('rc', -1), self.get_updates(), self.protocol_command.show())
class TestMakeDirectory(CommandTestMixin, unittest.TestCase):
def setUp(self):
self.setUpCommand()
def tearDown(self):
self.tearDownCommand()
@defer.inlineCallbacks
def test_empty_paths(self):
self.make_command(fs.MakeDirectory, {'paths': []}, True)
yield self.run_command()
self.assertUpdates([('rc', 0)], self.protocol_command.show())
@defer.inlineCallbacks
def test_simple(self):
paths = [os.path.join(self.basedir, 'test_dir')]
self.make_command(fs.MakeDirectory, {'paths': paths}, True)
yield self.run_command()
self.assertTrue(os.path.exists(os.path.abspath(paths[0])))
self.assertUpdates([('rc', 0)], self.protocol_command.show())
@defer.inlineCallbacks
def test_two_dirs(self):
paths = [os.path.join(self.basedir, 'test-dir'), os.path.join(self.basedir, 'test-dir2')]
self.make_command(fs.MakeDirectory, {'paths': paths}, True)
yield self.run_command()
for path in paths:
self.assertTrue(os.path.exists(os.path.abspath(path)))
self.assertUpdates([('rc', 0)], self.protocol_command.show())
@defer.inlineCallbacks
def test_already_exists(self):
self.make_command(
fs.MakeDirectory, {'paths': [os.path.join(self.basedir, 'workdir')]}, True
)
yield self.run_command()
self.assertUpdates([('rc', 0)], self.protocol_command.show())
@defer.inlineCallbacks
def test_error_existing_file(self):
paths = [os.path.join(self.basedir, 'test-file')]
self.make_command(fs.MakeDirectory, {'paths': paths}, True)
with open(paths[0], "w"):
pass
yield self.run_command()
self.assertIn(('rc', errno.EEXIST), self.get_updates(), self.protocol_command.show())
class TestStatFile(CommandTestMixin, unittest.TestCase):
def setUp(self):
self.setUpCommand()
def tearDown(self):
self.tearDownCommand()
@defer.inlineCallbacks
def test_non_existent(self):
path = os.path.join(self.basedir, 'no-such-file')
self.make_command(fs.StatFile, {'path': path}, True)
yield self.run_command()
self.assertIn(('rc', errno.ENOENT), self.get_updates(), self.protocol_command.show())
@defer.inlineCallbacks
def test_directory(self):
path = os.path.join(self.basedir, 'workdir')
self.make_command(fs.StatFile, {'path': path}, True)
yield self.run_command()
self.assertTrue(stat.S_ISDIR(self.get_updates()[0][1][stat.ST_MODE]))
self.assertIn(('rc', 0), self.get_updates(), self.protocol_command.show())
@defer.inlineCallbacks
def test_file(self):
path = os.path.join(self.basedir, 'test-file')
self.make_command(fs.StatFile, {'path': path}, True)
with open(os.path.join(self.basedir, 'test-file'), "w"):
pass
yield self.run_command()
self.assertTrue(stat.S_ISREG(self.get_updates()[0][1][stat.ST_MODE]))
self.assertIn(('rc', 0), self.get_updates(), self.protocol_command.show())
@defer.inlineCallbacks
def test_file_workdir(self):
path = os.path.join(self.basedir, 'wd', 'test-file')
self.make_command(fs.StatFile, {'path': path}, True)
os.mkdir(os.path.join(self.basedir, 'wd'))
with open(os.path.join(self.basedir, 'wd', 'test-file'), "w"):
pass
yield self.run_command()
self.assertTrue(stat.S_ISREG(self.get_updates()[0][1][stat.ST_MODE]))
self.assertIn(('rc', 0), self.get_updates(), self.protocol_command.show())
class TestGlobPath(CommandTestMixin, unittest.TestCase):
def setUp(self):
self.setUpCommand()
def tearDown(self):
self.tearDownCommand()
@defer.inlineCallbacks
def test_non_existent(self):
self.make_command(fs.GlobPath, {'path': os.path.join(self.basedir, 'no-*-file')}, True)
yield self.run_command()
self.assertEqual(self.get_updates()[0][1], [])
self.assertIn(('rc', 0), self.get_updates(), self.protocol_command.show())
@defer.inlineCallbacks
def test_directory(self):
self.make_command(fs.GlobPath, {'path': os.path.join(self.basedir, '[wxyz]or?d*')}, True)
yield self.run_command()
self.assertEqual(self.get_updates()[0][1], [os.path.join(self.basedir, 'workdir')])
self.assertIn(('rc', 0), self.get_updates(), self.protocol_command.show())
@defer.inlineCallbacks
def test_file(self):
self.make_command(fs.GlobPath, {'path': os.path.join(self.basedir, 't*-file')}, True)
with open(os.path.join(self.basedir, 'test-file'), "w"):
pass
yield self.run_command()
self.assertEqual(self.get_updates()[0][1], [os.path.join(self.basedir, 'test-file')])
self.assertIn(('rc', 0), self.get_updates(), self.protocol_command.show())
@defer.inlineCallbacks
def test_recursive(self):
self.make_command(fs.GlobPath, {'path': os.path.join(self.basedir, '**/*.txt')}, True)
os.makedirs(os.path.join(self.basedir, 'test/testdir'))
with open(os.path.join(self.basedir, 'test/testdir/test.txt'), 'w'):
pass
yield self.run_command()
if sys.platform == 'win32':
filename = 'test\\testdir\\test.txt'
else:
filename = 'test/testdir/test.txt'
self.assertEqual(self.get_updates()[0][1], [os.path.join(self.basedir, filename)])
self.assertIn(('rc', 0), self.get_updates(), self.protocol_command.show())
class TestListDir(CommandTestMixin, unittest.TestCase):
def setUp(self):
self.setUpCommand()
def tearDown(self):
self.tearDownCommand()
@defer.inlineCallbacks
def test_non_existent(self):
path = os.path.join(self.basedir, 'no-such-dir')
self.make_command(fs.ListDir, {'path': path}, True)
yield self.run_command()
self.assertIn(('rc', errno.ENOENT), self.get_updates(), self.protocol_command.show())
@defer.inlineCallbacks
def test_dir(self):
workdir = os.path.join(self.basedir, 'workdir')
self.make_command(fs.ListDir, {'path': workdir}, True)
with open(os.path.join(workdir, 'file1'), "w"):
pass
with open(os.path.join(workdir, 'file2'), "w"):
pass
yield self.run_command()
def any(items): # not a builtin on python-2.4
for i in items:
if i:
return True
return None
self.assertIn(('rc', 0), self.get_updates(), self.protocol_command.show())
self.assertTrue(
any(
'files' in upd and sorted(upd[1]) == ['file1', 'file2']
for upd in self.get_updates()
),
self.protocol_command.show(),
)
class TestRemoveFile(CommandTestMixin, unittest.TestCase):
def setUp(self):
self.setUpCommand()
def tearDown(self):
self.tearDownCommand()
@defer.inlineCallbacks
def test_simple(self):
workdir = os.path.join(self.basedir, 'workdir')
file1_path = os.path.join(workdir, 'file1')
self.make_command(fs.RemoveFile, {'path': file1_path}, True)
with open(file1_path, "w"):
pass
yield self.run_command()
self.assertFalse(os.path.exists(file1_path))
self.assertIn(
('rc', 0), # this may ignore a 'header' : '..', which is OK
self.get_updates(),
self.protocol_command.show(),
)
@defer.inlineCallbacks
def test_simple_exception(self):
workdir = os.path.join(self.basedir, 'workdir')
file2_path = os.path.join(workdir, 'file2')
self.make_command(fs.RemoveFile, {'path': file2_path}, True)
yield self.run_command()
self.assertIn(('rc', 2), self.get_updates(), self.protocol_command.show())
| 15,546 | Python | .py | 346 | 36.289017 | 97 | 0.61947 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
5,058 | runprocess-scripts.py | buildbot_buildbot/worker/buildbot_worker/test/unit/runprocess-scripts.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 file contains scripts run by the test_runprocess tests. Note that since
# this code runs in a different Python interpreter, it does not necessarily
# have access to any of the Buildbot source. Functions here should be kept
# very simple!
from __future__ import annotations
import os
import select
import signal
import subprocess
import sys
import time
from typing import Callable
import psutil
# utils
def invoke_script(function, *args):
cmd = [sys.executable, __file__, function, *list(args)]
if os.name == 'nt':
DETACHED_PROCESS = 0x00000008
subprocess.Popen(
cmd,
shell=False,
stdin=None,
stdout=None,
stderr=None,
close_fds=True,
creationflags=DETACHED_PROCESS,
)
else:
subprocess.Popen(cmd, shell=False, stdin=None, stdout=None, stderr=None, close_fds=True)
def write_pidfile(pidfile):
pidfile_tmp = pidfile + "~"
f = open(pidfile_tmp, "w")
f.write(str(os.getpid()))
f.close()
os.rename(pidfile_tmp, pidfile)
def sleep_forever():
signal.alarm(110) # die after 110 seconds
while True:
time.sleep(10)
script_fns: dict[str, Callable] = {}
def script(fn):
script_fns[fn.__name__] = fn
return fn
# scripts
@script
def write_pidfile_and_sleep():
pidfile = sys.argv[2]
write_pidfile(pidfile)
sleep_forever()
@script
def spawn_child():
parent_pidfile, child_pidfile = sys.argv[2:]
invoke_script('write_pidfile_and_sleep', child_pidfile)
write_pidfile(parent_pidfile)
sleep_forever()
@script
def wait_for_pid_death_and_write_pidfile_and_sleep():
wait_pid = int(sys.argv[2])
pidfile = sys.argv[3]
while psutil.pid_exists(wait_pid):
time.sleep(0.01)
write_pidfile(pidfile)
sleep_forever()
@script
def double_fork():
if os.name == 'posix':
# when using a PTY, the child process will get SIGHUP when the
# parent process exits, so ignore that.
signal.signal(signal.SIGHUP, signal.SIG_IGN)
parent_pidfile, child_pidfile = sys.argv[2:]
parent_pid = os.getpid()
invoke_script('wait_for_pid_death_and_write_pidfile_and_sleep', str(parent_pid), child_pidfile)
write_pidfile(parent_pidfile)
sys.exit(0)
@script
def assert_stdin_closed():
# EOF counts as readable data, so we should see stdin in the readable list,
# although it may not appear immediately, and select may return early
bail_at = time.time() + 10
while True:
r, _, __ = select.select([0], [], [], 0.01)
if r == [0]:
return # success!
if time.time() > bail_at:
raise AssertionError() # failure :(
# make sure this process dies if necessary
if not hasattr(signal, 'alarm'):
signal.alarm = lambda t: 0
signal.alarm(110) # die after 110 seconds
# dispatcher
script_fns[sys.argv[1]]()
| 3,628 | Python | .py | 105 | 29.933333 | 99 | 0.692572 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
5,059 | test_util.py | buildbot_buildbot/worker/buildbot_worker/test/unit/test_util.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.trial import unittest
from buildbot_worker import util
class remove_userpassword(unittest.TestCase):
def assertUrl(self, real_url, expected_url):
new_url = util.remove_userpassword(real_url)
self.assertEqual(expected_url, new_url)
def test_url_with_no_user_and_password(self):
self.assertUrl('http://myurl.com/myrepo', 'http://myurl.com/myrepo')
def test_url_with_user_and_password(self):
self.assertUrl('http://myuser:[email protected]/myrepo', 'http://myurl.com/myrepo')
def test_another_url_with_no_user_and_password(self):
self.assertUrl('http://myurl2.com/myrepo2', 'http://myurl2.com/myrepo2')
def test_another_url_with_user_and_password(self):
self.assertUrl('http://myuser2:[email protected]/myrepo2', 'http://myurl2.com/myrepo2')
def test_with_different_protocol_without_user_and_password(self):
self.assertUrl('ssh://myurl3.com/myrepo3', 'ssh://myurl3.com/myrepo3')
def test_with_different_protocol_with_user_and_password(self):
self.assertUrl('ssh://myuser3:[email protected]/myrepo3', 'ssh://myurl3.com/myrepo3')
def test_file_path(self):
self.assertUrl('/home/me/repos/my-repo', '/home/me/repos/my-repo')
def test_file_path_with_at_sign(self):
self.assertUrl('/var/repos/speci@l', '/var/repos/speci@l')
def test_win32file_path(self):
self.assertUrl('c:\\repos\\my-repo', 'c:\\repos\\my-repo')
class TestObfuscated(unittest.TestCase):
def testSimple(self):
c = util.Obfuscated('real', '****')
self.assertEqual(str(c), '****')
self.assertEqual(repr(c), "'****'")
def testObfuscatedCommand(self):
cmd = ['echo', util.Obfuscated('password', '*******')]
cmd_bytes = [b'echo', util.Obfuscated(b'password', b'*******')]
cmd_unicode = ['echo', util.Obfuscated('password', 'привет')]
self.assertEqual(['echo', 'password'], util.Obfuscated.get_real(cmd))
self.assertEqual(['echo', '*******'], util.Obfuscated.get_fake(cmd))
self.assertEqual([b'echo', b'password'], util.Obfuscated.get_real(cmd_bytes))
self.assertEqual([b'echo', b'*******'], util.Obfuscated.get_fake(cmd_bytes))
self.assertEqual(['echo', 'password'], util.Obfuscated.get_real(cmd_unicode))
self.assertEqual(['echo', 'привет'], util.Obfuscated.get_fake(cmd_unicode))
def testObfuscatedNonString(self):
cmd = ['echo', 1]
cmd_bytes = [b'echo', 2]
cmd_unicode = ['привет', 3]
self.assertEqual(['echo', '1'], util.Obfuscated.get_real(cmd))
self.assertEqual([b'echo', '2'], util.Obfuscated.get_fake(cmd_bytes))
self.assertEqual(['привет', '3'], util.Obfuscated.get_fake(cmd_unicode))
def testObfuscatedNonList(self):
cmd = 1
self.assertEqual(1, util.Obfuscated.get_real(cmd))
self.assertEqual(1, util.Obfuscated.get_fake(cmd))
class TestRewrap(unittest.TestCase):
def test_main(self):
tests = [
("", "", None),
("\n", "\n", None),
("\n ", "\n", None),
(" \n", "\n", None),
(" \n ", "\n", None),
(
"""
multiline
with
indent
""",
"\nmultiline with indent",
None,
),
(
"""\
multiline
with
indent
""",
"multiline with indent\n",
None,
),
(
"""\
multiline
with
indent
""",
"multiline with indent\n",
None,
),
(
"""\
multiline
with
indent
and
formatting
""",
"multiline with indent\n and\n formatting\n",
None,
),
(
"""\
multiline
with
indent
and wrapping
and
formatting
""",
"multiline with\nindent and\nwrapping\n and\n formatting\n",
15,
),
]
for text, expected, width in tests:
self.assertEqual(util.rewrap(text, width=width), expected)
| 5,264 | Python | .py | 125 | 31.224 | 96 | 0.565337 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
5,060 | test_runprocess.py | buildbot_buildbot/worker/buildbot_worker/test/unit/test_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 os
import pprint
import re
import signal
import sys
import time
import psutil
from twisted.internet import defer
from twisted.internet import reactor
from twisted.internet import task
from twisted.python import log
from twisted.python import runtime
from twisted.python import util
from twisted.trial import unittest
from buildbot_worker import runprocess
from buildbot_worker import util as bsutil
from buildbot_worker.exceptions import AbandonChain
from buildbot_worker.test.util import compat
from buildbot_worker.test.util.misc import BasedirMixin
from buildbot_worker.test.util.misc import nl
try:
from unittest.mock import Mock
except ImportError:
from unittest.mock import Mock
def catCommand():
return [sys.executable, '-c', 'import sys; sys.stdout.write(sys.stdin.read())']
def stdoutCommand(output):
return [sys.executable, '-c', f'import sys; sys.stdout.write("{output}\\n")']
def stderrCommand(output):
return [sys.executable, '-c', f'import sys; sys.stderr.write("{output}\\n")']
def sleepCommand(dur):
return [sys.executable, '-c', f'import time; time.sleep({dur})']
def scriptCommand(function, *args):
runprocess_scripts = util.sibpath(__file__, 'runprocess-scripts.py')
return [sys.executable, runprocess_scripts, function, *list(args)]
def printArgsCommand():
return [sys.executable, '-c', 'import sys; sys.stdout.write(repr(sys.argv[1:]))']
def print_text_command(lines, phrase):
return [
sys.executable,
'-c',
f'''
import time
import sys
for _ in range({lines}):
sys.stdout.write("{phrase}\\n")
sys.stdout.flush()
time.sleep(0.2)
''',
]
# windows returns rc 1, because exit status cannot indicate "signalled";
# posix returns rc -1 for "signalled"
FATAL_RC = -1
if runtime.platformType == 'win32':
FATAL_RC = 1
# We would like to see debugging output in the test.log
runprocess.RunProcessPP.debug = True
class TestRunProcess(BasedirMixin, unittest.TestCase):
def setUp(self):
self.setUpBasedir()
self.updates = []
def send_update(self, status):
for st in status:
self.updates.append(st)
def show(self):
return pprint.pformat(self.updates)
def tearDown(self):
self.tearDownBasedir()
def testCommandEncoding(self):
s = runprocess.RunProcess(0, 'abcd', self.basedir, 'utf-8', self.send_update)
self.assertIsInstance(s.command, bytes)
self.assertIsInstance(s.fake_command, bytes)
def testCommandEncodingList(self):
s = runprocess.RunProcess(0, ['abcd', b'efg'], self.basedir, 'utf-8', self.send_update)
self.assertIsInstance(s.command[0], bytes)
self.assertIsInstance(s.fake_command[0], bytes)
def testCommandEncodingObfuscated(self):
s = runprocess.RunProcess(
0, [bsutil.Obfuscated('abcd', 'ABCD')], self.basedir, 'utf-8', self.send_update
)
self.assertIsInstance(s.command[0], bytes)
self.assertIsInstance(s.fake_command[0], bytes)
@defer.inlineCallbacks
def testStart(self):
s = runprocess.RunProcess(
0, stdoutCommand('hello'), self.basedir, 'utf-8', self.send_update
)
yield s.start()
self.assertTrue(('stdout', nl('hello\n')) in self.updates, self.show())
self.assertTrue(('rc', 0) in self.updates, self.show())
@defer.inlineCallbacks
def testNoStdout(self):
s = runprocess.RunProcess(
0, stdoutCommand('hello'), self.basedir, 'utf-8', self.send_update, sendStdout=False
)
yield s.start()
self.assertFalse(('stdout', nl('hello\n')) in self.updates, self.show())
self.assertTrue(('rc', 0) in self.updates, self.show())
@defer.inlineCallbacks
def testKeepStdout(self):
s = runprocess.RunProcess(
0, stdoutCommand('hello'), self.basedir, 'utf-8', self.send_update, keepStdout=True
)
yield s.start()
self.assertTrue(('stdout', nl('hello\n')) in self.updates, self.show())
self.assertTrue(('rc', 0) in self.updates, self.show())
self.assertEqual(s.stdout, nl('hello\n'))
@defer.inlineCallbacks
def testStderr(self):
s = runprocess.RunProcess(
0, stderrCommand("hello"), self.basedir, 'utf-8', self.send_update
)
yield s.start()
self.assertFalse(('stderr', nl('hello\n')) not in self.updates, self.show())
self.assertTrue(('rc', 0) in self.updates, self.show())
@defer.inlineCallbacks
def testNoStderr(self):
s = runprocess.RunProcess(
0, stderrCommand("hello"), self.basedir, 'utf-8', self.send_update, sendStderr=False
)
yield s.start()
self.assertFalse(('stderr', nl('hello\n')) in self.updates, self.show())
self.assertTrue(('rc', 0) in self.updates, self.show())
@defer.inlineCallbacks
def test_incrementalDecoder(self):
s = runprocess.RunProcess(
0, stderrCommand("hello"), self.basedir, 'utf-8', self.send_update, sendStderr=True
)
pp = runprocess.RunProcessPP(s)
# u"\N{SNOWMAN} when encoded to utf-8 bytes is b"\xe2\x98\x83"
pp.outReceived(b"\xe2")
pp.outReceived(b"\x98\x83")
pp.errReceived(b"\xe2")
pp.errReceived(b"\x98\x83")
yield s.start()
self.assertTrue(('stderr', "\N{SNOWMAN}") in self.updates)
self.assertTrue(('stdout', "\N{SNOWMAN}") in self.updates)
self.assertTrue(('rc', 0) in self.updates, self.show())
@defer.inlineCallbacks
def testInvalidUTF8(self):
s = runprocess.RunProcess(
0, stderrCommand("hello"), self.basedir, 'utf-8', self.send_update, sendStderr=True
)
pp = runprocess.RunProcessPP(s)
INVALID_UTF8 = b"\xff"
with self.assertRaises(UnicodeDecodeError):
INVALID_UTF8.decode('utf-8')
pp.outReceived(INVALID_UTF8)
yield s.start()
stdout = next(value for key, value in self.updates if key == 'stdout')
# On Python < 2.7 bytes is used, on Python >= 2.7 unicode
self.assertIn(stdout, (b'\xef\xbf\xbd', '\ufffd'))
self.assertTrue(('rc', 0) in self.updates, self.show())
@defer.inlineCallbacks
def testKeepStderr(self):
s = runprocess.RunProcess(
0, stderrCommand("hello"), self.basedir, 'utf-8', self.send_update, keepStderr=True
)
yield s.start()
self.assertTrue(('stderr', nl('hello\n')) in self.updates, self.show())
self.assertTrue(('rc', 0) in self.updates, self.show())
self.assertEqual(s.stderr, nl('hello\n'))
@defer.inlineCallbacks
def testStringCommand(self):
# careful! This command must execute the same on windows and UNIX
s = runprocess.RunProcess(0, 'echo hello', self.basedir, 'utf-8', self.send_update)
yield s.start()
self.assertTrue(('stdout', nl('hello\n')) in self.updates, self.show())
self.assertTrue(('rc', 0) in self.updates, self.show())
def testObfuscatedCommand(self):
s = runprocess.RunProcess(
0, [('obfuscated', 'abcd', 'ABCD')], self.basedir, 'utf-8', self.send_update
)
self.assertEqual(s.command, [b'abcd'])
self.assertEqual(s.fake_command, [b'ABCD'])
@defer.inlineCallbacks
def testMultiWordStringCommand(self):
# careful! This command must execute the same on windows and UNIX
s = runprocess.RunProcess(
0, 'echo Happy Days and Jubilation', self.basedir, 'utf-8', self.send_update
)
# no quoting occurs
exp = nl('Happy Days and Jubilation\n')
yield s.start()
self.assertTrue(('stdout', exp) in self.updates, self.show())
self.assertTrue(('rc', 0) in self.updates, self.show())
@defer.inlineCallbacks
def testInitialStdinUnicode(self):
s = runprocess.RunProcess(
0, catCommand(), self.basedir, 'utf-8', self.send_update, initialStdin='hello'
)
yield s.start()
self.assertTrue(('stdout', nl('hello')) in self.updates, self.show())
self.assertTrue(('rc', 0) in self.updates, self.show())
@defer.inlineCallbacks
def testMultiWordStringCommandQuotes(self):
# careful! This command must execute the same on windows and UNIX
s = runprocess.RunProcess(
0, 'echo "Happy Days and Jubilation"', self.basedir, 'utf-8', self.send_update
)
if runtime.platformType == "win32":
# echo doesn't parse out the quotes, so they come through in the
# output
exp = nl('"Happy Days and Jubilation"\n')
else:
exp = nl('Happy Days and Jubilation\n')
yield s.start()
self.assertTrue(('stdout', exp) in self.updates, self.show())
self.assertTrue(('rc', 0) in self.updates, self.show())
@defer.inlineCallbacks
def testTrickyArguments(self):
# make sure non-trivial arguments are passed verbatim
args = [
'Happy Days and Jubilation', # spaces
r"""!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~""", # special characters
'%PATH%', # Windows variable expansions
# Expansions get an argument of their own, because the Windows
# shell doesn't treat % as special unless it surrounds a
# variable name.
]
s = runprocess.RunProcess(
0, printArgsCommand() + args, self.basedir, 'utf-8', self.send_update
)
yield s.start()
self.assertTrue(('stdout', nl(repr(args))) in self.updates, self.show())
self.assertTrue(('rc', 0) in self.updates, self.show())
@defer.inlineCallbacks
@compat.skipUnlessPlatformIs("win32")
def testPipeString(self):
# this is highly contrived, but it proves the point.
cmd = sys.executable + ' -c "import sys; sys.stdout.write(\'b\\na\\n\')" | sort'
s = runprocess.RunProcess(0, cmd, self.basedir, 'utf-8', self.send_update)
yield s.start()
self.assertTrue(('stdout', nl('a\nb\n')) in self.updates, self.show())
self.assertTrue(('rc', 0) in self.updates, self.show())
@defer.inlineCallbacks
def testCommandTimeout(self):
s = runprocess.RunProcess(
0, sleepCommand(10), self.basedir, 'utf-8', self.send_update, timeout=5
)
clock = task.Clock()
s._reactor = clock
d = s.start()
clock.advance(6)
yield d
self.assertTrue(('stdout', nl('hello\n')) not in self.updates, self.show())
self.assertTrue(('rc', FATAL_RC) in self.updates, self.show())
self.assertTrue(("failure_reason", "timeout_without_output") in self.updates, self.show())
@defer.inlineCallbacks
def testCommandMaxTime(self):
s = runprocess.RunProcess(
0, sleepCommand(10), self.basedir, 'utf-8', self.send_update, maxTime=5
)
clock = task.Clock()
s._reactor = clock
d = s.start()
clock.advance(6) # should knock out maxTime
yield d
self.assertTrue(('stdout', nl('hello\n')) not in self.updates, self.show())
self.assertTrue(('rc', FATAL_RC) in self.updates, self.show())
self.assertTrue(("failure_reason", "timeout") in self.updates, self.show())
@defer.inlineCallbacks
def test_command_max_lines(self):
s = runprocess.RunProcess(
0,
print_text_command(5, 'hello'),
self.basedir,
'utf-8',
self.send_update,
sendStdout=True,
max_lines=1,
)
d = s.start()
yield d
self.assertTrue(('stdout', nl('hello\n')) in self.updates, self.show())
self.assertTrue(('rc', FATAL_RC) in self.updates, self.show())
self.assertTrue(("failure_reason", "max_lines_failure") in self.updates, self.show())
@compat.skipUnlessPlatformIs("posix")
@defer.inlineCallbacks
def test_stdin_closed(self):
s = runprocess.RunProcess(
0,
scriptCommand('assert_stdin_closed'),
self.basedir,
'utf-8',
self.send_update,
# if usePTY=True, stdin is never closed
usePTY=False,
logEnviron=False,
)
yield s.start()
self.assertTrue(('rc', 0) in self.updates, self.show())
@defer.inlineCallbacks
def test_startCommand_exception(self):
s = runprocess.RunProcess(0, ['whatever'], self.basedir, 'utf-8', self.send_update)
# set up to cause an exception in _startCommand
def _startCommand(*args, **kwargs):
raise RuntimeError('error message')
s._startCommand = _startCommand
try:
yield s.start()
except AbandonChain:
pass
stderr = []
# Here we're checking that the exception starting up the command
# actually gets propagated back to the master in stderr.
for key, value in self.updates:
if key == 'stderr':
stderr.append(value)
stderr = ''.join(stderr)
self.assertTrue(stderr.startswith('error in RunProcess._startCommand (error message)'))
yield self.flushLoggedErrors()
@defer.inlineCallbacks
def testLogEnviron(self):
s = runprocess.RunProcess(
0,
stdoutCommand('hello'),
self.basedir,
'utf-8',
self.send_update,
environ={"FOO": "BAR"},
)
yield s.start()
headers = "".join([value for key, value in self.updates if key == "header"])
self.assertTrue("FOO=BAR" in headers, "got:\n" + headers)
@defer.inlineCallbacks
def testNoLogEnviron(self):
s = runprocess.RunProcess(
0,
stdoutCommand('hello'),
self.basedir,
'utf-8',
self.send_update,
environ={"FOO": "BAR"},
logEnviron=False,
)
yield s.start()
headers = "".join([
next(iter(update.values())) for update in self.updates if list(update) == ["header"]
])
self.assertTrue("FOO=BAR" not in headers, "got:\n" + headers)
@defer.inlineCallbacks
def testEnvironExpandVar(self):
environ = {
"EXPND": "-${PATH}-",
"DOESNT_EXPAND": "-${---}-",
"DOESNT_FIND": "-${DOESNT_EXISTS}-",
}
s = runprocess.RunProcess(
0, stdoutCommand('hello'), self.basedir, 'utf-8', self.send_update, environ=environ
)
yield s.start()
headers = "".join([value for key, value in self.updates if key == "header"])
self.assertTrue("EXPND=-$" not in headers, "got:\n" + headers)
self.assertTrue("DOESNT_FIND=--" in headers, "got:\n" + headers)
self.assertTrue("DOESNT_EXPAND=-${---}-" in headers, "got:\n" + headers)
@defer.inlineCallbacks
def testUnsetEnvironVar(self):
s = runprocess.RunProcess(
0,
stdoutCommand('hello'),
self.basedir,
'utf-8',
self.send_update,
environ={"PATH": None},
)
yield s.start()
headers = "".join([
next(iter(update.values())) for update in self.updates if list(update) == ["header"]
])
self.assertFalse(re.match('\bPATH=', headers), "got:\n" + headers)
@defer.inlineCallbacks
def testEnvironPythonPath(self):
s = runprocess.RunProcess(
0,
stdoutCommand('hello'),
self.basedir,
'utf-8',
self.send_update,
environ={"PYTHONPATH": 'a'},
)
yield s.start()
headers = "".join([
next(iter(update.values())) for update in self.updates if list(update) == ["header"]
])
self.assertFalse(re.match(f'\bPYTHONPATH=a{os.pathsep}', headers), "got:\n" + headers)
@defer.inlineCallbacks
def testEnvironArray(self):
s = runprocess.RunProcess(
0,
stdoutCommand('hello'),
self.basedir,
'utf-8',
self.send_update,
environ={"FOO": ['a', 'b']},
)
yield s.start()
headers = "".join([
next(iter(update.values())) for update in self.updates if list(update) == ["header"]
])
self.assertFalse(re.match(f'\bFOO=a{os.pathsep}b\b', headers), "got:\n" + headers)
def testEnvironInt(self):
with self.assertRaises(RuntimeError):
runprocess.RunProcess(
0,
stdoutCommand('hello'),
self.basedir,
'utf-8',
self.send_update,
environ={"BUILD_NUMBER": 13},
)
def _test_spawnAsBatch(self, cmd, comspec):
def spawnProcess(
processProtocol,
executable,
args=(),
env=None,
path=None,
uid=None,
gid=None,
usePTY=False,
childFDs=None,
):
self.assertTrue(args[0].lower().endswith("cmd.exe"), f"{args[0]} is not cmd.exe")
self.patch(runprocess.reactor, "spawnProcess", spawnProcess)
tempEnviron = os.environ.copy()
if 'COMSPEC' not in tempEnviron:
tempEnviron['COMSPEC'] = comspec
self.patch(os, "environ", tempEnviron)
s = runprocess.RunProcess(0, cmd, self.basedir, 'utf-8', self.send_update)
s.pp = runprocess.RunProcessPP(s)
s.deferred = defer.Deferred()
d = s._spawnAsBatch(s.pp, s.command, "args", tempEnviron, "path", False)
return d
def test_spawnAsBatchCommandString(self):
return self._test_spawnAsBatch("dir c:/", "cmd.exe")
def test_spawnAsBatchCommandList(self):
return self._test_spawnAsBatch(stdoutCommand('hello'), "cmd.exe /c")
def test_spawnAsBatchCommandWithNonAscii(self):
return self._test_spawnAsBatch("echo \u6211", "cmd.exe")
def test_spawnAsBatchCommandListWithNonAscii(self):
return self._test_spawnAsBatch(['echo', "\u6211"], "cmd.exe /c")
class TestPOSIXKilling(BasedirMixin, unittest.TestCase):
timeout = 60 # takes a while on oversubscribed test machines
if runtime.platformType != "posix":
skip = "not a POSIX platform"
def setUp(self):
self.pidfiles = []
self.setUpBasedir()
self.updates = []
def send_update(self, status):
self.updates.append(status)
def tearDown(self):
# make sure all of the subprocesses are dead
for pidfile in self.pidfiles:
if not os.path.exists(pidfile):
continue
with open(pidfile) as f:
pid = f.read()
if not pid:
return
pid = int(pid)
try:
os.kill(pid, signal.SIGKILL)
except OSError:
pass
# and clean up leftover pidfiles
for pidfile in self.pidfiles:
if os.path.exists(pidfile):
os.unlink(pidfile)
self.tearDownBasedir()
def newPidfile(self):
pidfile = os.path.abspath(f"test-{len(self.pidfiles)}.pid")
if os.path.exists(pidfile):
os.unlink(pidfile)
self.pidfiles.append(pidfile)
return pidfile
def waitForPidfile(self, pidfile):
# wait for a pidfile, and return the pid via a Deferred
until = time.time() + self.timeout
d = defer.Deferred()
def poll():
if reactor.seconds() > until:
d.errback(RuntimeError(f"pidfile {pidfile} never appeared"))
return
if os.path.exists(pidfile):
try:
with open(pidfile) as f:
pid = int(f.read())
except (OSError, TypeError, ValueError):
pid = None
if pid is not None:
d.callback(pid)
return
reactor.callLater(0.01, poll)
poll() # poll right away
return d
def assertAlive(self, pid):
try:
os.kill(pid, 0)
except OSError:
self.fail(f"pid {pid} still alive")
def assertDead(self, pid, timeout=5):
log.msg(f"checking pid {pid!r}")
def check():
try:
os.kill(pid, 0)
except OSError:
return True # dead
return False # alive
# check immediately
if check():
return
# poll every 100'th of a second; this allows us to test for
# processes that have been killed, but where the signal hasn't
# been delivered yet
until = time.time() + timeout
while time.time() < until:
time.sleep(0.01)
if check():
return
self.fail(f"pid {pid} still alive after {timeout}s")
# tests
def test_simple_interruptSignal(self):
return self.test_simple('TERM')
def test_simple(self, interruptSignal=None):
# test a simple process that just sleeps waiting to die
pidfile = self.newPidfile()
self.pid = None
s = runprocess.RunProcess(
0,
scriptCommand('write_pidfile_and_sleep', pidfile),
self.basedir,
'utf-8',
self.send_update,
)
if interruptSignal is not None:
s.interruptSignal = interruptSignal
runproc_d = s.start()
pidfile_d = self.waitForPidfile(pidfile)
def check_alive(pid):
self.pid = pid # for use in check_dead
# test that the process is still alive
self.assertAlive(pid)
# and tell the RunProcess object to kill it
s.kill("diaf")
pidfile_d.addCallback(check_alive)
def check_dead(_):
self.assertDead(self.pid)
runproc_d.addCallback(check_dead)
return defer.gatherResults([pidfile_d, runproc_d])
def test_sigterm(self, interruptSignal=None):
# Tests that the process will receive SIGTERM if sigtermTimeout
# is not None
pidfile = self.newPidfile()
self.pid = None
s = runprocess.RunProcess(
0,
scriptCommand('write_pidfile_and_sleep', pidfile),
self.basedir,
'utf-8',
self.send_update,
sigtermTime=1,
)
runproc_d = s.start()
pidfile_d = self.waitForPidfile(pidfile)
self.receivedSIGTERM = False
def check_alive(pid):
# Create a mock process that will check if we receive SIGTERM
mock_process = Mock(wraps=s.process)
mock_process.pgid = None # Skips over group SIGTERM
mock_process.pid = pid
process = s.process
def _mock_signalProcess(sig):
if sig == "TERM":
self.receivedSIGTERM = True
process.signalProcess(sig)
mock_process.signalProcess = _mock_signalProcess
s.process = mock_process
self.pid = pid # for use in check_dead
# test that the process is still alive
self.assertAlive(pid)
# and tell the RunProcess object to kill it
s.kill("diaf")
pidfile_d.addCallback(check_alive)
def check_dead(_):
self.assertEqual(self.receivedSIGTERM, True)
self.assertDead(self.pid)
runproc_d.addCallback(check_dead)
return defer.gatherResults([pidfile_d, runproc_d])
def test_pgroup_usePTY(self):
return self.do_test_pgroup(usePTY=True)
def test_pgroup_no_usePTY(self):
return self.do_test_pgroup(usePTY=False)
def test_pgroup_no_usePTY_no_pgroup(self):
# note that this configuration is not *used*, but that it is
# still supported, and correctly fails to kill the child process
return self.do_test_pgroup(usePTY=False, useProcGroup=False, expectChildSurvival=True)
@defer.inlineCallbacks
def do_test_pgroup(self, usePTY, useProcGroup=True, expectChildSurvival=False):
# test that a process group gets killed
parent_pidfile = self.newPidfile()
self.parent_pid = None
child_pidfile = self.newPidfile()
self.child_pid = None
s = runprocess.RunProcess(
0,
scriptCommand('spawn_child', parent_pidfile, child_pidfile),
self.basedir,
'utf-8',
self.send_update,
usePTY=usePTY,
useProcGroup=useProcGroup,
)
runproc_d = s.start()
# wait for both processes to start up, then call s.kill
parent_pidfile_d = self.waitForPidfile(parent_pidfile)
child_pidfile_d = self.waitForPidfile(child_pidfile)
pidfiles_d = defer.gatherResults([parent_pidfile_d, child_pidfile_d])
def got_pids(pids):
self.parent_pid, self.child_pid = pids
pidfiles_d.addCallback(got_pids)
def kill(_):
s.kill("diaf")
pidfiles_d.addCallback(kill)
# check that both processes are dead after RunProcess is done
yield defer.gatherResults([pidfiles_d, runproc_d])
self.assertDead(self.parent_pid)
if expectChildSurvival:
self.assertAlive(self.child_pid)
else:
self.assertDead(self.child_pid)
def test_double_fork_usePTY(self):
return self.do_test_double_fork(usePTY=True)
def test_double_fork_no_usePTY(self):
return self.do_test_double_fork(usePTY=False)
def test_double_fork_no_usePTY_no_pgroup(self):
# note that this configuration is not *used*, but that it is
# still supported, and correctly fails to kill the child process
return self.do_test_double_fork(usePTY=False, useProcGroup=False, expectChildSurvival=True)
@defer.inlineCallbacks
def do_test_double_fork(self, usePTY, useProcGroup=True, expectChildSurvival=False):
# when a spawned process spawns another process, and then dies itself
# (either intentionally or accidentally), we should be able to clean up
# the child.
parent_pidfile = self.newPidfile()
self.parent_pid = None
child_pidfile = self.newPidfile()
self.child_pid = None
s = runprocess.RunProcess(
0,
scriptCommand('double_fork', parent_pidfile, child_pidfile),
self.basedir,
'utf-8',
self.send_update,
usePTY=usePTY,
useProcGroup=useProcGroup,
)
runproc_d = s.start()
# wait for both processes to start up, then call s.kill
parent_pidfile_d = self.waitForPidfile(parent_pidfile)
child_pidfile_d = self.waitForPidfile(child_pidfile)
pidfiles_d = defer.gatherResults([parent_pidfile_d, child_pidfile_d])
def got_pids(pids):
self.parent_pid, self.child_pid = pids
pidfiles_d.addCallback(got_pids)
def kill(_):
s.kill("diaf")
pidfiles_d.addCallback(kill)
# check that both processes are dead after RunProcess is done
yield defer.gatherResults([pidfiles_d, runproc_d])
self.assertDead(self.parent_pid)
if expectChildSurvival:
self.assertAlive(self.child_pid)
else:
self.assertDead(self.child_pid)
class TestWindowsKilling(BasedirMixin, unittest.TestCase):
if runtime.platformType != "win32":
skip = "not a Windows platform"
def setUp(self):
self.pidfiles = []
self.setUpBasedir()
self.updates = []
def send_update(self, status):
self.updates.append(status)
def tearDown(self):
# make sure all of the subprocesses are dead
for pidfile in self.pidfiles:
if not os.path.exists(pidfile):
continue
with open(pidfile) as f:
pid = f.read()
if not pid:
return
pid = int(pid)
try:
psutil.Process(pid).kill()
except psutil.NoSuchProcess:
pass
while psutil.pid_exists(pid):
time.sleep(0.01)
# and clean up leftover pidfiles
for pidfile in self.pidfiles:
if os.path.exists(pidfile):
os.unlink(pidfile)
self.tearDownBasedir()
def new_pid_file(self):
pidfile = os.path.abspath(f"test-{len(self.pidfiles)}.pid")
if os.path.exists(pidfile):
os.unlink(pidfile)
self.pidfiles.append(pidfile)
return pidfile
def wait_for_pidfile(self, pidfile):
# wait for a pidfile, and return the pid via a Deferred
until = time.time() + 10
d = defer.Deferred()
def poll():
if reactor.seconds() > until:
d.errback(RuntimeError(f"pidfile {pidfile} never appeared"))
return
if os.path.exists(pidfile):
try:
with open(pidfile) as f:
pid = int(f.read())
except (OSError, TypeError, ValueError):
pid = None
if pid is not None:
d.callback(pid)
return
reactor.callLater(0.01, poll)
poll() # poll right away
return d
def assert_alive(self, pid):
if not psutil.pid_exists(pid):
self.fail(f"pid {pid} dead, but expected it to be alive")
def assert_dead(self, pid, timeout=5):
log.msg(f"checking pid {pid!r}")
# check immediately
if not psutil.pid_exists(pid):
return
# poll every 100'th of a second; this allows us to test for
# processes that have been killed, but where the signal hasn't
# been delivered yet
until = time.time() + timeout
while time.time() < until:
time.sleep(0.01)
if not psutil.pid_exists(pid):
return
self.fail(f"pid {pid} still alive after {timeout}s")
# tests
@defer.inlineCallbacks
def test_simple(self, interrupt_signal=None):
# test a simple process that just sleeps waiting to die
pidfile = self.new_pid_file()
s = runprocess.RunProcess(
0,
scriptCommand('write_pidfile_and_sleep', pidfile),
self.basedir,
'utf-8',
self.send_update,
)
if interrupt_signal is not None:
s.interruptSignal = interrupt_signal
runproc_d = s.start()
pid = yield self.wait_for_pidfile(pidfile)
self.assert_alive(pid)
# test that the process is still alive and tell the RunProcess object to kill it
s.kill("diaf")
yield runproc_d
self.assert_dead(pid)
@defer.inlineCallbacks
def test_sigterm(self):
# Tests that the process will receive SIGTERM if sigtermTimeout is not None
pidfile = self.new_pid_file()
s = runprocess.RunProcess(
0,
scriptCommand('write_pidfile_and_sleep', pidfile),
self.basedir,
'utf-8',
self.send_update,
sigtermTime=1,
)
taskkill_calls = []
orig_taskkill = s._win32_taskkill
def mock_taskkill(pid, force):
taskkill_calls.append(force)
orig_taskkill(pid, force)
s._win32_taskkill = mock_taskkill
runproc_d = s.start()
pid = yield self.wait_for_pidfile(pidfile)
# test that the process is still alive
self.assert_alive(pid)
# and tell the RunProcess object to kill it
s.kill("diaf")
yield runproc_d
self.assertEqual(taskkill_calls, [False, True])
self.assert_dead(pid)
@defer.inlineCallbacks
def test_with_child(self):
# test that a process group gets killed
parent_pidfile = self.new_pid_file()
child_pidfile = self.new_pid_file()
s = runprocess.RunProcess(
0,
scriptCommand('spawn_child', parent_pidfile, child_pidfile),
self.basedir,
'utf-8',
self.send_update,
)
runproc_d = s.start()
# wait for both processes to start up, then call s.kill
parent_pid = yield self.wait_for_pidfile(parent_pidfile)
child_pid = yield self.wait_for_pidfile(child_pidfile)
s.kill("diaf")
yield runproc_d
self.assert_dead(parent_pid)
self.assert_dead(child_pid)
@defer.inlineCallbacks
def test_with_child_parent_dies(self):
# when a spawned process spawns another process, and then dies itself
# (either intentionally or accidentally), we kill the child processes.
parent_pidfile = self.new_pid_file()
child_pidfile = self.new_pid_file()
s = runprocess.RunProcess(
0,
scriptCommand('double_fork', parent_pidfile, child_pidfile),
self.basedir,
'utf-8',
self.send_update,
)
runproc_d = s.start()
# wait for both processes to start up, then call s.kill
parent_pid = yield self.wait_for_pidfile(parent_pidfile)
child_pid = yield self.wait_for_pidfile(child_pidfile)
s.kill("diaf")
# check that both processes are dead after RunProcess is done
yield runproc_d
self.assert_dead(parent_pid)
self.assert_dead(child_pid)
class TestLogFileWatcher(BasedirMixin, unittest.TestCase):
def setUp(self):
self.setUpBasedir()
self.updates = []
def send_update(self, status):
for st in status:
self.updates.append(st)
def show(self):
return pprint.pformat(self.updates)
def tearDown(self):
self.tearDownBasedir()
def makeRP(self):
rp = runprocess.RunProcess(
0, stdoutCommand('hello'), self.basedir, 'utf-8', self.send_update
)
return rp
def test_statFile_missing(self):
rp = self.makeRP()
test_filename = 'test_runprocess_test_statFile_missing.log'
if os.path.exists(test_filename):
os.remove(test_filename)
lf = runprocess.LogFileWatcher(rp, 'test', test_filename, False)
self.assertFalse(lf.statFile(), f"{test_filename} doesn't exist")
def test_statFile_exists(self):
rp = self.makeRP()
test_filename = 'test_runprocess_test_statFile_exists.log'
try:
with open(test_filename, 'w') as f:
f.write('hi')
lf = runprocess.LogFileWatcher(rp, 'test', test_filename, False)
st = lf.statFile()
self.assertEqual(st and st[2], 2, "statfile.log exists and size is correct")
finally:
os.remove(test_filename)
def test_invalid_utf8(self):
# create the log file watcher first
rp = self.makeRP()
test_filename = 'test_runprocess_test_invalid_utf8.log'
try:
lf = runprocess.LogFileWatcher(rp, 'test', test_filename, follow=False, poll=False)
# now write to the log file
INVALID_UTF8 = b'before\xffafter'
with open(test_filename, 'wb') as f:
f.write(INVALID_UTF8)
# the watcher picks up the changed log
lf.poll()
# the log file content was captured and the invalid byte replaced with \ufffd (the
# replacement character, often a black diamond with a white question mark)
REPLACED = 'before\ufffdafter'
self.assertEqual(self.updates, [('log', ('test', REPLACED))])
finally:
lf.stop()
os.remove(f.name)
| 36,826 | Python | .py | 906 | 30.95585 | 99 | 0.603871 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
5,061 | test_scripts_runner.py | buildbot_buildbot/worker/buildbot_worker/test/unit/test_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
from __future__ import annotations
import os
import sys
from typing import Callable
from twisted.python import log
from twisted.python import usage
from twisted.trial import unittest
from buildbot_worker.scripts import runner
from buildbot_worker.test.util import misc
try:
from unittest import mock
except ImportError:
from unittest import mock
class OptionsMixin:
def assertOptions(self, opts, exp):
got = {k: opts[k] for k in exp}
if got != exp:
msg = []
for k in exp:
if opts[k] != exp[k]:
msg.append(f" {k}: expected {exp[k]!r}, got {opts[k]!r}")
self.fail("did not get expected options\n" + ("\n".join(msg)))
class BaseDirTestsMixin:
"""
Common tests for Options classes with 'basedir' parameter
"""
GETCWD_PATH = "test-dir"
ABSPATH_PREFIX = "test-prefix-"
MY_BASEDIR = "my-basedir"
# the options class to instantiate for test cases
options_class: type[usage.Options] | None = None
def setUp(self):
self.patch(os, "getcwd", lambda: self.GETCWD_PATH)
self.patch(os.path, "abspath", lambda path: self.ABSPATH_PREFIX + path)
def parse(self, *args):
assert self.options_class is not None
opts = self.options_class()
opts.parseOptions(args)
return opts
def test_defaults(self):
opts = self.parse()
self.assertEqual(
opts["basedir"], self.ABSPATH_PREFIX + self.GETCWD_PATH, "unexpected basedir path"
)
def test_basedir_arg(self):
opts = self.parse(self.MY_BASEDIR)
self.assertEqual(
opts["basedir"], self.ABSPATH_PREFIX + self.MY_BASEDIR, "unexpected basedir path"
)
def test_too_many_args(self):
with self.assertRaisesRegex(usage.UsageError, "I wasn't expecting so many arguments"):
self.parse("arg1", "arg2")
class TestMakerBase(BaseDirTestsMixin, unittest.TestCase):
"""
Test buildbot_worker.scripts.runner.MakerBase class.
"""
options_class = runner.MakerBase
class TestStopOptions(BaseDirTestsMixin, unittest.TestCase):
"""
Test buildbot_worker.scripts.runner.StopOptions class.
"""
options_class = runner.StopOptions
def test_synopsis(self):
opts = runner.StopOptions()
self.assertIn('buildbot-worker stop', opts.getSynopsis())
class TestStartOptions(OptionsMixin, BaseDirTestsMixin, unittest.TestCase):
"""
Test buildbot_worker.scripts.runner.StartOptions class.
"""
options_class = runner.StartOptions
def test_synopsis(self):
opts = runner.StartOptions()
self.assertIn('buildbot-worker start', opts.getSynopsis())
def test_all_args(self):
opts = self.parse("--quiet", "--nodaemon", self.MY_BASEDIR)
self.assertOptions(
opts,
{"quiet": True, "nodaemon": True, "basedir": self.ABSPATH_PREFIX + self.MY_BASEDIR},
)
class TestRestartOptions(OptionsMixin, BaseDirTestsMixin, unittest.TestCase):
"""
Test buildbot_worker.scripts.runner.RestartOptions class.
"""
options_class = runner.RestartOptions
def test_synopsis(self):
opts = runner.RestartOptions()
self.assertIn('buildbot-worker restart', opts.getSynopsis())
def test_all_args(self):
opts = self.parse("--quiet", "--nodaemon", self.MY_BASEDIR)
self.assertOptions(
opts,
{"quiet": True, "nodaemon": True, "basedir": self.ABSPATH_PREFIX + self.MY_BASEDIR},
)
class TestCreateWorkerOptions(OptionsMixin, unittest.TestCase):
"""
Test buildbot_worker.scripts.runner.CreateWorkerOptions class.
"""
req_args = ["bdir", "mstr:5678", "name", "pswd"]
def parse(self, *args):
opts = runner.CreateWorkerOptions()
opts.parseOptions(args)
return opts
def test_defaults(self):
with self.assertRaisesRegex(usage.UsageError, "incorrect number of arguments"):
self.parse()
def test_synopsis(self):
opts = runner.CreateWorkerOptions()
self.assertIn('buildbot-worker create-worker', opts.getSynopsis())
def test_min_args(self):
# patch runner.MakerBase.postOptions() so that 'basedir'
# argument will not be converted to absolute path
self.patch(runner.MakerBase, "postOptions", mock.Mock())
self.assertOptions(
self.parse(*self.req_args),
{"basedir": "bdir", "host": "mstr", "port": 5678, "name": "name", "passwd": "pswd"},
)
def test_all_args(self):
# patch runner.MakerBase.postOptions() so that 'basedir'
# argument will not be converted to absolute path
self.patch(runner.MakerBase, "postOptions", mock.Mock())
opts = self.parse(
"--force",
"--relocatable",
"--no-logrotate",
"--keepalive=4",
"--umask=0o22",
"--maxdelay=3",
"--numcpus=4",
"--log-size=2",
"--log-count=1",
"--allow-shutdown=file",
*self.req_args,
)
self.assertOptions(
opts,
{
"force": True,
"relocatable": True,
"no-logrotate": True,
"umask": "0o22",
"maxdelay": 3,
"numcpus": "4",
"log-size": 2,
"log-count": "1",
"allow-shutdown": "file",
"basedir": "bdir",
"host": "mstr",
"port": 5678,
"name": "name",
"passwd": "pswd",
},
)
def test_master_url(self):
with self.assertRaisesRegex(usage.UsageError, "<master> is not a URL - do not use URL"):
self.parse("a", "http://b.c", "d", "e")
def test_inv_keepalive(self):
with self.assertRaisesRegex(usage.UsageError, "keepalive parameter needs to be a number"):
self.parse("--keepalive=X", *self.req_args)
def test_inv_maxdelay(self):
with self.assertRaisesRegex(usage.UsageError, "maxdelay parameter needs to be a number"):
self.parse("--maxdelay=X", *self.req_args)
def test_inv_log_size(self):
with self.assertRaisesRegex(usage.UsageError, "log-size parameter needs to be a number"):
self.parse("--log-size=X", *self.req_args)
def test_inv_log_count(self):
with self.assertRaisesRegex(
usage.UsageError, "log-count parameter needs to be a number or None"
):
self.parse("--log-count=X", *self.req_args)
def test_inv_numcpus(self):
with self.assertRaisesRegex(
usage.UsageError, "numcpus parameter needs to be a number or None"
):
self.parse("--numcpus=X", *self.req_args)
def test_inv_umask(self):
with self.assertRaisesRegex(
usage.UsageError, "umask parameter needs to be a number or None"
):
self.parse("--umask=X", *self.req_args)
def test_inv_umask2(self):
with self.assertRaisesRegex(
usage.UsageError, "umask parameter needs to be a number or None"
):
self.parse("--umask=022", *self.req_args)
def test_inv_allow_shutdown(self):
with self.assertRaisesRegex(
usage.UsageError, "allow-shutdown needs to be one of 'signal' or 'file'"
):
self.parse("--allow-shutdown=X", *self.req_args)
def test_too_few_args(self):
with self.assertRaisesRegex(usage.UsageError, "incorrect number of arguments"):
self.parse("arg1", "arg2")
def test_too_many_args(self):
with self.assertRaisesRegex(usage.UsageError, "incorrect number of arguments"):
self.parse("extra_arg", *self.req_args)
def test_validateMasterArgument_no_port(self):
"""
test calling CreateWorkerOptions.validateMasterArgument()
on <master> argument without port specified.
"""
opts = runner.CreateWorkerOptions()
self.assertEqual(
opts.validateMasterArgument("mstrhost"),
("mstrhost", 9989),
"incorrect master host and/or port",
)
def test_validateMasterArgument_empty_master(self):
"""
test calling CreateWorkerOptions.validateMasterArgument()
on <master> without host part specified.
"""
opts = runner.CreateWorkerOptions()
with self.assertRaisesRegex(usage.UsageError, "invalid <master> argument ':1234'"):
opts.validateMasterArgument(":1234")
def test_validateMasterArgument_inv_port(self):
"""
test calling CreateWorkerOptions.validateMasterArgument()
on <master> without with unparsable port part
"""
opts = runner.CreateWorkerOptions()
with self.assertRaisesRegex(
usage.UsageError, "invalid master port 'apple', needs to be a number"
):
opts.validateMasterArgument("host:apple")
def test_validateMasterArgument_ok(self):
"""
test calling CreateWorkerOptions.validateMasterArgument()
on <master> with host and port parts specified.
"""
opts = runner.CreateWorkerOptions()
self.assertEqual(
opts.validateMasterArgument("mstrhost:4321"),
("mstrhost", 4321),
"incorrect master host and/or port",
)
def test_validateMasterArgument_ipv4(self):
"""
test calling CreateWorkerOptions.validateMasterArgument()
on <master> with ipv4 host specified.
"""
opts = runner.CreateWorkerOptions()
self.assertEqual(
opts.validateMasterArgument("192.168.0.0"),
("192.168.0.0", 9989),
"incorrect master host and/or port",
)
def test_validateMasterArgument_ipv4_port(self):
"""
test calling CreateWorkerOptions.validateMasterArgument()
on <master> with ipv4 host and port parts specified.
"""
opts = runner.CreateWorkerOptions()
self.assertEqual(
opts.validateMasterArgument("192.168.0.0:4321"),
("192.168.0.0", 4321),
"incorrect master host and/or port",
)
def test_validateMasterArgument_ipv6(self):
"""
test calling CreateWorkerOptions.validateMasterArgument()
on <master> with ipv6 host specified.
"""
opts = runner.CreateWorkerOptions()
self.assertEqual(
opts.validateMasterArgument("[2001:1:2:3:4::1]"),
("2001:1:2:3:4::1", 9989),
"incorrect master host and/or port",
)
def test_validateMasterArgument_ipv6_port(self):
"""
test calling CreateWorkerOptions.validateMasterArgument()
on <master> with ipv6 host and port parts specified.
"""
opts = runner.CreateWorkerOptions()
self.assertEqual(
opts.validateMasterArgument("[2001:1:2:3:4::1]:4321"),
("2001:1:2:3:4::1", 4321),
"incorrect master host and/or port",
)
def test_validateMasterArgument_ipv6_no_bracket(self):
"""
test calling CreateWorkerOptions.validateMasterArgument()
on <master> with ipv6 without [] specified.
"""
opts = runner.CreateWorkerOptions()
with self.assertRaisesRegex(
usage.UsageError,
r"invalid <master> argument '2001:1:2:3:4::1:4321', "
r"if it is an ipv6 address, it must be enclosed by \[\]",
):
opts.validateMasterArgument("2001:1:2:3:4::1:4321")
class TestOptions(misc.StdoutAssertionsMixin, unittest.TestCase):
"""
Test buildbot_worker.scripts.runner.Options class.
"""
def setUp(self):
self.setUpStdoutAssertions()
def parse(self, *args):
opts = runner.Options()
opts.parseOptions(args)
return opts
def test_defaults(self):
with self.assertRaisesRegex(usage.UsageError, "must specify a command"):
self.parse()
def test_version(self):
exception = self.assertRaises(SystemExit, self.parse, '--version')
self.assertEqual(exception.code, 0, "unexpected exit code")
self.assertInStdout('worker version:')
def test_verbose(self):
self.patch(log, 'startLogging', mock.Mock())
with self.assertRaises(usage.UsageError):
self.parse("--verbose")
log.startLogging.assert_called_once_with(sys.stderr)
# used by TestRun.test_run_good to patch in a callback
functionPlaceholder: Callable | None = None
class TestRun(misc.StdoutAssertionsMixin, unittest.TestCase):
"""
Test buildbot_worker.scripts.runner.run()
"""
def setUp(self):
self.setUpStdoutAssertions()
class TestSubCommand(usage.Options):
subcommandFunction = __name__ + ".functionPlaceholder"
optFlags = [["test-opt", None, None]]
class TestOptions(usage.Options):
"""
Option class that emulates usage error. The 'suboptions' flag
enables emulation of usage error in a sub-option.
"""
optFlags = [["suboptions", None, None]]
def postOptions(self):
if self["suboptions"]:
self.subOptions = "SubOptionUsage"
raise usage.UsageError("usage-error-message")
def __str__(self):
return "GeneralUsage"
def test_run_good(self):
"""
Test successful invocation of worker command.
"""
self.patch(sys, "argv", ["command", 'test', '--test-opt'])
# patch runner module to use our test subcommand class
self.patch(runner.Options, 'subCommands', [['test', None, self.TestSubCommand, None]])
# trace calls to subcommand function
subcommand_func = mock.Mock(return_value=42)
self.patch(sys.modules[__name__], "functionPlaceholder", subcommand_func)
# check that subcommand function called with correct arguments
# and that it's return value is used as exit code
exception = self.assertRaises(SystemExit, runner.run)
subcommand_func.assert_called_once_with({'test-opt': 1})
self.assertEqual(exception.code, 42, "unexpected exit code")
def test_run_bad_noargs(self):
"""
Test handling of invalid command line arguments.
"""
self.patch(sys, "argv", ["command"])
# patch runner module to use test Options class
self.patch(runner, "Options", self.TestOptions)
exception = self.assertRaises(SystemExit, runner.run)
self.assertEqual(exception.code, 1, "unexpected exit code")
self.assertStdoutEqual(
"command: usage-error-message\n\nGeneralUsage\n",
"unexpected error message on stdout",
)
def test_run_bad_suboption(self):
"""
Test handling of invalid command line arguments in a suboption.
"""
self.patch(sys, "argv", ["command", "--suboptions"])
# patch runner module to use test Options class
self.patch(runner, "Options", self.TestOptions)
exception = self.assertRaises(SystemExit, runner.run)
self.assertEqual(exception.code, 1, "unexpected exit code")
# check that we get error message for a sub-option
self.assertStdoutEqual(
"command: usage-error-message\n\nSubOptionUsage\n",
"unexpected error message on stdout",
)
| 16,300 | Python | .py | 392 | 32.780612 | 98 | 0.631466 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
5,062 | test_commands_utils.py | buildbot_buildbot/worker/buildbot_worker/test/unit/test_commands_utils.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 twisted.python.procutils
from twisted.python import runtime
from twisted.trial import unittest
from buildbot_worker.commands import utils
class GetCommand(unittest.TestCase):
def setUp(self):
# monkey-patch 'which' to return something appropriate
self.which_results = {}
def which(arg):
return self.which_results.get(arg, [])
self.patch(twisted.python.procutils, 'which', which)
# note that utils.py currently imports which by name, so we
# patch it there, too
self.patch(utils, 'which', which)
def set_which_results(self, results):
self.which_results = results
def test_getCommand_empty(self):
self.set_which_results({
'xeyes': [],
})
with self.assertRaises(RuntimeError):
utils.getCommand('xeyes')
def test_getCommand_single(self):
self.set_which_results({
'xeyes': ['/usr/bin/xeyes'],
})
self.assertEqual(utils.getCommand('xeyes'), '/usr/bin/xeyes')
def test_getCommand_multi(self):
self.set_which_results({
'xeyes': ['/usr/bin/xeyes', '/usr/X11/bin/xeyes'],
})
self.assertEqual(utils.getCommand('xeyes'), '/usr/bin/xeyes')
def test_getCommand_single_exe(self):
self.set_which_results({
'xeyes': ['/usr/bin/xeyes'],
# it should not select this option, since only one matched
# to begin with
'xeyes.exe': [r'c:\program files\xeyes.exe'],
})
self.assertEqual(utils.getCommand('xeyes'), '/usr/bin/xeyes')
def test_getCommand_multi_exe(self):
self.set_which_results({
'xeyes': [r'c:\program files\xeyes.com', r'c:\program files\xeyes.exe'],
'xeyes.exe': [r'c:\program files\xeyes.exe'],
})
# this one will work out differently depending on platform..
if runtime.platformType == 'win32':
self.assertEqual(utils.getCommand('xeyes'), r'c:\program files\xeyes.exe')
else:
self.assertEqual(utils.getCommand('xeyes'), r'c:\program files\xeyes.com')
class RmdirRecursive(unittest.TestCase):
# this is more complicated than you'd think because Twisted doesn't
# rmdir its test directory very well, either..
def setUp(self):
self.target = 'testdir'
try:
if os.path.exists(self.target):
shutil.rmtree(self.target)
except OSError as e:
# this test will probably fail anyway
raise unittest.SkipTest("could not clean before test") from e
# fill it with some files
os.mkdir(os.path.join(self.target))
with open(os.path.join(self.target, "a"), "w"):
pass
os.mkdir(os.path.join(self.target, "d"))
with open(os.path.join(self.target, "d", "a"), "w"):
pass
os.mkdir(os.path.join(self.target, "d", "d"))
with open(os.path.join(self.target, "d", "d", "a"), "w"):
pass
def tearDown(self):
try:
if os.path.exists(self.target):
shutil.rmtree(self.target)
except Exception:
print("\n(target directory was not removed by test, and cleanup failed too)\n")
raise
def test_rmdirRecursive_easy(self):
utils.rmdirRecursive(self.target)
self.assertFalse(os.path.exists(self.target))
def test_rmdirRecursive_symlink(self):
# this was intended as a regression test for #792, but doesn't seem
# to trigger it. It can't hurt to check it, all the same.
if runtime.platformType == 'win32':
raise unittest.SkipTest("no symlinks on this platform")
os.mkdir("noperms")
with open("noperms/x", "w"):
pass
os.chmod("noperms/x", 0)
try:
os.symlink("../noperms", os.path.join(self.target, "link"))
utils.rmdirRecursive(self.target)
# that shouldn't delete the target of the symlink
self.assertTrue(os.path.exists("noperms"))
finally:
# even Twisted can't clean this up very well, so try hard to
# clean it up ourselves..
os.chmod("noperms/x", 0o777)
os.unlink("noperms/x")
os.rmdir("noperms")
self.assertFalse(os.path.exists(self.target))
| 5,115 | Python | .py | 118 | 34.847458 | 91 | 0.632637 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
5,063 | test_scripts_base.py | buildbot_buildbot/worker/buildbot_worker/test/unit/test_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
import os
import sys
from twisted.trial import unittest
from buildbot_worker.compat import NativeStringIO
from buildbot_worker.scripts import base
from buildbot_worker.test.util import misc
class TestIsWorkerDir(misc.FileIOMixin, misc.StdoutAssertionsMixin, unittest.TestCase):
"""Test buildbot_worker.scripts.base.isWorkerDir()"""
def setUp(self):
# capture output to stdout
self.mocked_stdout = NativeStringIO()
self.patch(sys, "stdout", self.mocked_stdout)
# generate OS specific relative path to buildbot.tac inside basedir
self.tac_file_path = os.path.join("testdir", "buildbot.tac")
def assertReadErrorMessage(self, strerror):
expected_message = f"error reading '{self.tac_file_path}': {strerror}\ninvalid worker directory 'testdir'\n"
self.assertEqual(
self.mocked_stdout.getvalue(), expected_message, "unexpected error message on stdout"
)
def test_open_error(self):
"""Test that open() errors are handled."""
# patch open() to raise IOError
self.setUpOpenError(1, "open-error", "dummy")
# check that isWorkerDir() flags directory as invalid
self.assertFalse(base.isWorkerDir("testdir"))
# check that correct error message was printed to stdout
self.assertReadErrorMessage("open-error")
# check that open() was called with correct path
self.open.assert_called_once_with(self.tac_file_path)
def test_read_error(self):
"""Test that read() errors on buildbot.tac file are handled."""
# patch open() to return file object that raises IOError on read()
self.setUpReadError(1, "read-error", "dummy")
# check that isWorkerDir() flags directory as invalid
self.assertFalse(base.isWorkerDir("testdir"))
# check that correct error message was printed to stdout
self.assertReadErrorMessage("read-error")
# check that open() was called with correct path
self.open.assert_called_once_with(self.tac_file_path)
def test_unexpected_tac_contents(self):
"""Test that unexpected contents in buildbot.tac is handled."""
# patch open() to return file with unexpected contents
self.setUpOpen("dummy-contents")
# check that isWorkerDir() flags directory as invalid
self.assertFalse(base.isWorkerDir("testdir"))
# check that correct error message was printed to stdout
self.assertEqual(
self.mocked_stdout.getvalue(),
f"unexpected content in '{self.tac_file_path}'\n"
+ "invalid worker directory 'testdir'\n",
"unexpected error message on stdout",
)
# check that open() was called with correct path
self.open.assert_called_once_with(self.tac_file_path)
def test_workerdir_good(self):
"""Test checking valid worker directory."""
# patch open() to return file with valid worker tac contents
self.setUpOpen("Application('buildbot-worker')")
# check that isWorkerDir() flags directory as good
self.assertTrue(base.isWorkerDir("testdir"))
# check that open() was called with correct path
self.open.assert_called_once_with(self.tac_file_path)
| 3,984 | Python | .py | 76 | 45.394737 | 116 | 0.706595 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
5,064 | test_scripts_start.py | buildbot_buildbot/worker/buildbot_worker/test/unit/test_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
from twisted.trial import unittest
from buildbot_worker.scripts import start
from buildbot_worker.test.util import misc
try:
from unittest import mock
except ImportError:
from unittest import mock
class TestStartCommand(unittest.TestCase, misc.IsWorkerDirMixin):
"""
Test buildbot_worker.scripts.startup.startCommand()
"""
def test_start_command_bad_basedir(self):
"""
test calling startCommand() with invalid basedir path
"""
# patch isWorkerDir() to fail
self.setupUpIsWorkerDir(False)
# call startCommand() and check that correct exit code is returned
config = {"basedir": "dummy"}
self.assertEqual(start.startCommand(config), 1, "unexpected exit code")
# check that isWorkerDir was called with correct argument
self.isWorkerDir.assert_called_once_with("dummy")
def test_start_command_good(self):
"""
test successful startCommand() call
"""
# patch basedir check to always succeed
self.setupUpIsWorkerDir(True)
# patch startWorker() to do nothing
mocked_startWorker = mock.Mock(return_value=0)
self.patch(start, "startWorker", mocked_startWorker)
config = {"basedir": "dummy", "nodaemon": False, "quiet": False}
self.assertEqual(start.startCommand(config), 0, "unexpected exit code")
# check that isWorkerDir() and startWorker() were called
# with correct argument
self.isWorkerDir.assert_called_once_with("dummy")
mocked_startWorker.assert_called_once_with(
config["basedir"], config["quiet"], config["nodaemon"]
)
| 2,378 | Python | .py | 53 | 39.075472 | 79 | 0.714842 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
5,065 | protocolcommand.py | buildbot_buildbot/worker/buildbot_worker/test/fake/protocolcommand.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 pprint
from buildbot_worker.base import ProtocolCommandBase
class FakeProtocolCommand(ProtocolCommandBase):
debug = False
def __init__(self, basedir):
self.unicode_encoding = 'utf-8'
self.updates = []
self.worker_basedir = basedir
self.basedir = basedir
def show(self):
return pprint.pformat(self.updates)
def send_update(self, status):
if self.debug:
print("FakeWorkerForBuilder.sendUpdate", status)
for st in status:
self.updates.append(st)
# Returns a Deferred
def protocol_update_upload_file_close(self, writer):
return writer.callRemote("close")
# Returns a Deferred
def protocol_update_upload_file_utime(self, writer, access_time, modified_time):
return writer.callRemote("utime", (access_time, modified_time))
# Returns a Deferred
def protocol_update_upload_file_write(self, writer, data):
return writer.callRemote('write', data)
# Returns a Deferred
def protocol_update_upload_directory(self, writer):
return writer.callRemote("unpack")
# Returns a Deferred
def protocol_update_upload_directory_write(self, writer, data):
return writer.callRemote('write', data)
# Returns a Deferred
def protocol_update_read_file_close(self, reader):
return reader.callRemote('close')
# Returns a Deferred
def protocol_update_read_file(self, reader, length):
return reader.callRemote('read', length)
| 2,225 | Python | .py | 51 | 38.27451 | 84 | 0.723148 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
5,066 | reactor.py | buildbot_buildbot/worker/buildbot_worker/test/fake/reactor.py | # Copyright Buildbot Team Members
# Portions copyright 2015-2016 ClusterHQ Inc.
#
# 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 __future__ import annotations
from collections.abc import Callable
from collections.abc import Sequence
from typing import Any
from twisted.internet import defer
from twisted.internet import reactor
from twisted.internet.base import _ThreePhaseEvent
from twisted.internet.interfaces import IReactorCore
from twisted.internet.interfaces import IReactorThreads
from twisted.internet.task import Clock
from twisted.python import log
from twisted.python.failure import Failure
from zope.interface import implementer
# The code here is based on the implementations in
# https://twistedmatrix.com/trac/ticket/8295
# https://twistedmatrix.com/trac/ticket/8296
@implementer(IReactorCore)
class CoreReactor:
"""
Partial implementation of ``IReactorCore``.
"""
def __init__(self):
super().__init__()
self._triggers = {}
def addSystemEventTrigger(
self, phase: str, eventType: str, callable: Callable, *args: object, **kw: object
) -> Any:
event = self._triggers.setdefault(eventType, _ThreePhaseEvent())
return eventType, event.addTrigger(phase, callable, *args, **kw)
def removeSystemEventTrigger(self, triggerID):
eventType, handle = triggerID
event = self._triggers.setdefault(eventType, _ThreePhaseEvent())
event.removeTrigger(handle)
def fireSystemEvent(self, eventType):
event = self._triggers.get(eventType)
if event is not None:
event.fireEvent()
def callWhenRunning(self, callable: Callable, *args: object, **kwargs: object) -> Any | None:
callable(*args, **kwargs)
return None
def crash(self) -> None:
raise NotImplementedError()
def iterate(self, delay: float = 0) -> None:
raise NotImplementedError()
def run(self) -> None:
raise NotImplementedError()
def running(self) -> bool:
raise NotImplementedError()
def resolve(self, name: str, timeout: Sequence[int]) -> defer.Deferred[str]:
raise NotImplementedError()
def stop(self) -> None:
raise NotImplementedError()
class NonThreadPool:
"""
A stand-in for ``twisted.python.threadpool.ThreadPool`` so that the
majority of the test suite does not need to use multithreading.
This implementation takes the function call which is meant to run in a
thread pool and runs it synchronously in the calling thread.
:ivar int calls: The number of calls which have been dispatched to this
object.
"""
calls = 0
def __init__(self, **kwargs):
pass
def callInThreadWithCallback(self, onResult, func, *args, **kw):
self.calls += 1
try:
result = func(*args, **kw)
except: # noqa: E722
# We catch *everything* here, since normally this code would be
# running in a thread, where there is nothing that will catch
# error.
onResult(False, Failure())
else:
onResult(True, result)
def start(self):
pass
def stop(self):
pass
@implementer(IReactorThreads)
class NonReactor:
"""
A partial implementation of ``IReactorThreads`` which fits into
the execution model defined by ``NonThreadPool``.
"""
def suggestThreadPoolSize(self, size: int) -> None:
# we don't do threads, so this is a no-op
pass
def callFromThread(self, callable: Callable, *args: object, **kwargs: object) -> None:
callable(*args, **kwargs)
return None
def callInThread(self, callable: Callable, *args: object, **kwargs: object) -> None:
callable(*args, **kwargs)
return None
def getThreadPool(self):
return NonThreadPool()
class TestReactor(NonReactor, CoreReactor, Clock):
def __init__(self):
super().__init__()
# whether there are calls that should run right now
self._pendingCurrentCalls = False
self.stop_called = False
def _executeCurrentDelayedCalls(self):
while self.getDelayedCalls():
first = sorted(self.getDelayedCalls(), key=lambda a: a.getTime())[0]
if first.getTime() > self.seconds():
break
self.advance(0)
self._pendingCurrentCalls = False
@defer.inlineCallbacks
def _catchPrintExceptions(self, what, *a, **kw):
try:
r = what(*a, **kw)
if isinstance(r, defer.Deferred):
yield r
except Exception as e:
log.msg('Unhandled exception from deferred when doing TestReactor.advance()', e)
raise
def callLater(self, when, what, *a, **kw):
# Buildbot often uses callLater(0, ...) to defer execution of certain
# code to the next iteration of the reactor. This means that often
# there are pending callbacks registered to the reactor that might
# block other code from proceeding unless the test reactor has an
# iteration. To avoid deadlocks in tests we give the real reactor a
# chance to advance the test reactor whenever we detect that there
# are callbacks that should run in the next iteration of the test
# reactor.
#
# Additionally, we wrap all calls with a function that prints any
# unhandled exceptions
if when <= 0 and not self._pendingCurrentCalls:
reactor.callLater(0, self._executeCurrentDelayedCalls)
return super().callLater(when, self._catchPrintExceptions, what, *a, **kw)
def stop(self):
# first fire pending calls until the current time. Note that the real
# reactor only advances until the current time in the case of shutdown.
self.advance(0)
# then, fire the shutdown event
self.fireSystemEvent('shutdown')
self.stop_called = True
| 6,998 | Python | .py | 161 | 36.881988 | 97 | 0.690168 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
5,067 | runprocess.py | buildbot_buildbot/worker/buildbot_worker/test/fake/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
from twisted.internet import defer
class Expect:
"""
An expected instantiation of RunProcess. Usually used within a RunProcess
expect invocation:
rp.expect(
Expect("echo", "bar", usePTY=False)
+ { 'stdout' : 'hello!!' }
+ { 'rc' : 13 }
+ 13 # for a callback with rc=13; or
+ Failure(..), # for a failure
Expect(..) + .. ,
...
)
Note that the default values are accepted for all keyword arguments if they
are not omitted.
"""
def __init__(self, command, workdir, **kwargs):
self.kwargs = {"command": command, "workdir": workdir}
self.kwargs.update(kwargs)
self.result = None
self.status_updates = []
def __str__(self):
other_kwargs = self.kwargs.copy()
del other_kwargs['command']
del other_kwargs['workdir']
return "Command: {}\n workdir: {}\n kwargs: {}\n result: {}\n".format(
self.kwargs['command'], self.kwargs['workdir'], other_kwargs, self.result
)
def update(self, key, value):
self.status_updates.append([(key, value)])
return self
def updates(self, updates):
self.status_updates.append(updates)
return self
def exit(self, rc_code):
self.result = ('c', rc_code)
return self
def exception(self, error):
self.result = ('e', error)
return self
class FakeRunProcess:
"""
A fake version of L{buildbot_worker.runprocess.RunProcess} which will
simulate running external processes without actually running them (which is
very fragile in tests!)
This class is first programmed with the set of instances that are expected,
and with their expected results. It will raise an AssertionError if the
expected behavior is not seen.
Note that this handles sendStderr/sendStdout and keepStderr/keepStdout properly.
"""
@classmethod
def expect(cls, *expectations):
"""
Set the expectations for this test run
"""
cls._expectations = list(expectations)
# list the first expectation last, so we can pop it
cls._expectations.reverse()
@classmethod
def test_done(cls):
"""
Indicate that this test is finished; if any expected instantiations
have not taken place, this will raise the appropriate AssertionError.
"""
if cls._expectations:
raise AssertionError(f"{len(cls._expectations)} expected instances not created")
del cls._expectations
def __init__(self, command_id, command, workdir, unicode_encoding, send_update, **kwargs):
kwargs['command'] = command
kwargs['workdir'] = workdir
# the default values for the constructor kwargs; if we got a default
# value in **kwargs and didn't expect anything, well count that as OK
default_values = {
"environ": None,
"sendStdout": True,
"sendStderr": True,
"sendRC": True,
"timeout": None,
"maxTime": None,
"max_lines": None,
"sigtermTime": None,
"initialStdin": None,
"keepStdout": False,
"keepStderr": False,
"logEnviron": True,
"logfiles": {},
"usePTY": False,
}
if not self._expectations:
raise AssertionError(f"unexpected instantiation: {kwargs}")
exp = self._exp = self._expectations.pop()
if exp.kwargs != kwargs:
msg = []
# pylint: disable=consider-iterating-dictionary
for key in sorted(list(set(exp.kwargs.keys()) | set(kwargs.keys()))):
if key not in exp.kwargs:
if key in default_values:
if default_values[key] == kwargs[key]:
continue # default values are expected
msg.append(
f'{key}: expected default ({default_values[key]!r}),\n got {kwargs[key]!r}'
)
else:
msg.append(f'{key}: unexpected arg, value = {kwargs[key]!r}')
elif key not in kwargs:
msg.append(f'{key}: did not get expected arg')
elif exp.kwargs[key] != kwargs[key]:
msg.append(f'{key}: expected {exp.kwargs[key]!r},\n got {kwargs[key]!r}')
if msg:
msg.insert(
0,
'did not get expected __init__ arguments for\n {}'.format(
" ".join(map(repr, kwargs.get('command', ['unknown command'])))
),
)
self._expectations[:] = [] # don't expect any more instances, since we're failing
raise AssertionError("\n".join(msg))
self.send_update = send_update
self.stdout = ''
self.stderr = ''
def start(self):
# figure out the stdio-related parameters
keepStdout = self._exp.kwargs.get('keepStdout', False)
keepStderr = self._exp.kwargs.get('keepStderr', False)
sendStdout = self._exp.kwargs.get('sendStdout', True)
sendStderr = self._exp.kwargs.get('sendStderr', True)
if keepStdout:
self.stdout = ''
if keepStderr:
self.stderr = ''
finish_immediately = True
for update in self._exp.status_updates:
data = []
for key, value in update:
if key == 'stdout':
if keepStdout:
self.stdout += value
if not sendStdout:
continue # don't send this update
if key == 'stderr':
if keepStderr:
self.stderr += value
if not sendStderr:
continue
if key == 'wait':
finish_immediately = False
continue
data.append((key, value))
self.send_update(data)
d = self.run_deferred = defer.Deferred()
if finish_immediately:
self._finished()
return d
def _finished(self):
if self._exp.result[0] == 'e':
self.run_deferred.errback(self._exp.result[1])
else:
self.run_deferred.callback(self._exp.result[1])
def kill(self, reason):
self.send_update([('header', 'killing')])
self.send_update([('rc', -1)])
self.run_deferred.callback(-1)
| 7,376 | Python | .py | 177 | 30.677966 | 104 | 0.569317 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
5,068 | remote.py | buildbot_buildbot/worker/buildbot_worker/test/fake/remote.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 left for backward compatibility of old-named worker API.
# It should never be imported by Buildbot.
from twisted.internet import defer
class FakeRemote:
"""
Wrap a local object to make it look like it's remote
"""
def __init__(self, original, method_prefix="remote_"):
self.original = original
self.method_prefix = method_prefix
def callRemote(self, meth, *args, **kwargs):
fn = getattr(self.original, self.method_prefix + meth)
return defer.maybeDeferred(fn, *args, **kwargs)
def notifyOnDisconnect(self, what):
pass
def dontNotifyOnDisconnect(self, what):
pass
| 1,369 | Python | .py | 31 | 40.451613 | 79 | 0.741353 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
5,069 | command.py | buildbot_buildbot/worker/buildbot_worker/test/util/command.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 buildbot_worker.runprocess
from buildbot_worker.commands import utils
from buildbot_worker.test.fake import runprocess
from buildbot_worker.test.fake.protocolcommand import FakeProtocolCommand
class CommandTestMixin:
"""
Support for testing Command subclasses.
"""
def setUpCommand(self):
"""
Get things ready to test a Command
Sets:
self.basedir -- the basedir (an abs path)
self.basedir_workdir -- os.path.join(self.basedir, 'workdir')
self.basedir_source -- os.path.join(self.basedir, 'source')
"""
self.basedir = os.path.abspath('basedir')
self.basedir_workdir = os.path.join(self.basedir, 'workdir')
self.basedir_source = os.path.join(self.basedir, 'source')
# clean up the basedir unconditionally
if os.path.exists(self.basedir):
shutil.rmtree(self.basedir)
def tearDownCommand(self):
"""
Call this from the tearDown method to clean up any leftover workdirs and do
any additional cleanup required.
"""
# clean up the basedir unconditionally
if os.path.exists(self.basedir):
shutil.rmtree(self.basedir)
# finish up the runprocess
if hasattr(self, 'runprocess_patched') and self.runprocess_patched:
runprocess.FakeRunProcess.test_done()
def make_command(self, cmdclass, args, makedirs=False):
"""
Create a new command object, creating the necessary arguments. The
cmdclass argument is the Command class, and args is the args dict
to pass to its constructor.
This always creates the FakeProtocolCommand with a basedir (self.basedir).
If makedirs is true, it will create the basedir and a workdir directory
inside (named 'workdir').
The resulting command is returned, but as a side-effect, the following
attributes are set:
self.cmd -- the command
"""
# set up the workdir and basedir
if makedirs:
basedir_abs = os.path.abspath(os.path.join(self.basedir))
workdir_abs = os.path.abspath(os.path.join(self.basedir, 'workdir'))
if os.path.exists(basedir_abs):
shutil.rmtree(basedir_abs)
os.makedirs(workdir_abs)
self.protocol_command = FakeProtocolCommand(basedir=self.basedir)
self.cmd = cmdclass(self.protocol_command, 'fake-stepid', args)
return self.cmd
def run_command(self):
"""
Run the command created by make_command. Returns a deferred that will fire
on success or failure.
"""
return self.cmd.doStart()
def get_updates(self):
"""
Return the updates made so far
"""
return self.protocol_command.updates
def assertUpdates(self, updates, msg=None):
"""
Asserts that self.get_updates() matches updates, ignoring elapsed time data
"""
my_updates = []
for update in self.get_updates():
try:
if "elapsed" in update:
continue
except Exception:
pass
my_updates.append(update)
self.assertEqual(my_updates, updates, msg)
def add_update(self, upd):
self.protocol_command.updates.append(upd)
def patch_runprocess(self, *expectations):
"""
Patch a fake RunProcess class in, and set the given expectations.
"""
self.patch(buildbot_worker.runprocess, 'RunProcess', runprocess.FakeRunProcess)
buildbot_worker.runprocess.RunProcess.expect(*expectations)
self.runprocess_patched = True
def patch_getCommand(self, name, result):
"""
Patch utils.getCommand to return RESULT for NAME
"""
old_getCommand = utils.getCommand
def new_getCommand(n):
if n == name:
return result
return old_getCommand(n)
self.patch(utils, 'getCommand', new_getCommand)
def clean_environ(self):
"""
Temporarily clean out os.environ to { 'PWD' : '.' }
"""
self.patch(os, 'environ', {'PWD': '.'})
| 4,961 | Python | .py | 119 | 33.420168 | 87 | 0.654764 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
5,070 | site.py | buildbot_buildbot/worker/buildbot_worker/test/util/site.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.failure import Failure
from twisted.web.server import Site
class SiteWithClose(Site):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._protocols = []
def buildProtocol(self, addr):
p = super().buildProtocol(addr)
self._protocols.append(p)
return p
def close_connections(self):
for p in self._protocols:
p.connectionLost(Failure(RuntimeError("Closing down at the end of test")))
# There is currently no other way to force all pending server-side connections to
# close.
p._channel.transport.connectionLost(
Failure(RuntimeError("Closing down at the end of test"))
)
self._protocols = []
| 1,488 | Python | .py | 33 | 39.575758 | 93 | 0.704138 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
5,071 | sourcecommand.py | buildbot_buildbot/worker/buildbot_worker/test/util/sourcecommand.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.test.util import command
class SourceCommandTestMixin(command.CommandTestMixin):
"""
Support for testing Source Commands; an extension of CommandTestMixin
"""
def make_command(self, cmdclass, args, makedirs=False, initial_sourcedata=''):
"""
Same as the parent class method, but this also adds some source-specific
patches:
* writeSourcedata - writes to self.sourcedata (self is the TestCase)
* readSourcedata - reads from self.sourcedata
* doClobber - invokes RunProcess(0, ['clobber', DIRECTORY])
* doCopy - invokes RunProcess(0, ['copy', cmd.srcdir, cmd.workdir])
"""
cmd = command.CommandTestMixin.make_command(self, cmdclass, args, makedirs)
# note that these patches are to an *instance*, not a class, so there
# is no need to use self.patch() to reverse them
self.sourcedata = initial_sourcedata
def readSourcedata():
if self.sourcedata is None:
raise OSError("File not found")
return self.sourcedata
cmd.readSourcedata = readSourcedata
def writeSourcedata(res):
self.sourcedata = cmd.sourcedata
return res
cmd.writeSourcedata = writeSourcedata
def check_sourcedata(self, _, expected_sourcedata):
"""
Assert that the sourcedata (from the patched functions - see
make_command) is correct. Use this as a deferred callback.
"""
self.assertEqual(self.sourcedata, expected_sourcedata)
return _
| 2,296 | Python | .py | 48 | 41.145833 | 83 | 0.702908 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
5,072 | compat.py | buildbot_buildbot/worker/buildbot_worker/test/util/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 left for backward compatibility of old-named worker API.
# It should never be imported by Buildbot.
from twisted.python import runtime
def skipUnlessPlatformIs(platform):
def closure(test):
if runtime.platformType != platform:
test.skip = f"not a {platform} platform"
return test
return closure
| 1,058 | Python | .py | 23 | 43.217391 | 79 | 0.769903 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
5,073 | test_lineboundaries.py | buildbot_buildbot/worker/buildbot_worker/test/util/test_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
from twisted.trial import unittest
from buildbot_worker.util import lineboundaries
def join_line_info(info1, info2):
len_text1 = len(info1[0])
return (
info1[0] + info2[0],
info1[1] + [(len_text1 + index) for index in info2[1]],
info1[2] + info2[2],
)
class LBF(unittest.TestCase):
def setUp(self):
newline_re = r'(\r\n|\r(?=.)|\033\[u|\033\[[0-9]+;[0-9]+[Hf]|\033\[2J|\x08+)'
self.lbf = lineboundaries.LineBoundaryFinder(20, newline_re)
def test_empty_line(self):
self.assertEqual(self.lbf.append('1234', 1.0), None)
self.assertEqual(self.lbf.append('\n', 2.0), ('1234\n', [4], [1.0]))
self.assertEqual(self.lbf.append('5678\n', 3.0), ('5678\n', [4], [3.0]))
self.assertEqual(self.lbf.flush(), None)
def test_already_terminated(self):
self.assertEqual(self.lbf.append('abcd\ndefg\n', 1.0), ('abcd\ndefg\n', [4, 9], [1.0, 1.0]))
self.assertEqual(self.lbf.append('xyz\n', 2.0), ('xyz\n', [3], [2.0]))
self.assertEqual(self.lbf.flush(), None)
def test_partial_line(self):
self.assertEqual(self.lbf.append('hello\nworld', 1.0), ('hello\n', [5], [1.0]))
self.assertEqual(self.lbf.flush(), ('world\n', [5], [1.0]))
def test_empty_appends(self):
self.assertEqual(self.lbf.append('hello ', 1.0), None)
self.assertEqual(self.lbf.append('', 2.0), None)
self.assertEqual(self.lbf.append('world\n', 3.0), ('hello world\n', [11], [1.0]))
self.assertEqual(self.lbf.append('', 1.0), None)
def test_embedded_newlines(self):
self.assertEqual(self.lbf.append('hello, ', 1.0), None)
self.assertEqual(self.lbf.append('cruel\nworld', 2.0), ('hello, cruel\n', [12], [1.0]))
self.assertEqual(self.lbf.flush(), ('world\n', [5], [2.0]))
def test_windows_newlines_folded(self):
r"Windows' \r\n is treated as and converted to a newline"
self.assertEqual(self.lbf.append('hello, ', 1.0), None)
self.assertEqual(
self.lbf.append('cruel\r\n\r\nworld', 2.0), ('hello, cruel\n\n', [12, 13], [1.0, 2.0])
)
self.assertEqual(self.lbf.flush(), ('world\n', [5], [2.0]))
def test_bare_cr_folded(self):
r"a bare \r is treated as and converted to a newline"
self.assertEqual(
self.lbf.append('1%\r5%\r15%\r100%\nfinished', 1.0),
('1%\n5%\n15%\n100%\n', [2, 5, 9, 14], [1.0, 1.0, 1.0, 1.0]),
)
self.assertEqual(self.lbf.flush(), ('finished\n', [8], [1.0]))
def test_backspace_folded(self):
r"a lot of \b is treated as and converted to a newline"
self.lbf.append('1%\b\b5%\b\b15%\b\b\b100%\nfinished', 1.0)
self.assertEqual(self.lbf.flush(), ('finished\n', [8], [1.0]))
def test_mixed_consecutive_newlines(self):
r"mixing newline styles back-to-back doesn't collapse them"
self.assertEqual(self.lbf.append('1\r\n\n\r', 1.0), ('1\n\n', [1, 2], [1.0, 1.0]))
self.assertEqual(self.lbf.append('2\n\r\n', 2.0), ('\n2\n\n', [0, 2, 3], [1.0, 2.0, 2.0]))
def test_split_newlines(self):
r"multi-character newlines, split across chunks, are converted"
input = 'a\nb\r\nc\rd\n\re'
for splitpoint in range(1, len(input) - 1):
a = input[:splitpoint]
b = input[splitpoint:]
lines_info = []
lines_info.append(self.lbf.append(a, 2.0))
lines_info.append(self.lbf.append(b, 2.0))
lines_info.append(self.lbf.flush())
lines_info = [e for e in lines_info if e is not None]
joined_line_info = lines_info[0]
for line_info in lines_info[1:]:
joined_line_info = join_line_info(joined_line_info, line_info)
self.assertEqual(
joined_line_info,
('a\nb\nc\nd\n\ne\n', [1, 3, 5, 7, 8, 10], [2.0, 2.0, 2.0, 2.0, 2.0, 2.0]),
)
def test_split_terminal_control(self):
"""terminal control characters are converted"""
self.assertEqual(self.lbf.append('1234\033[u4321', 1.0), ('1234\n', [4], [1.0]))
self.assertEqual(self.lbf.flush(), ('4321\n', [4], [1.0]))
self.assertEqual(self.lbf.append('1234\033[1;2H4321', 2.0), ('1234\n', [4], [2.0]))
self.assertEqual(self.lbf.flush(), ('4321\n', [4], [2.0]))
self.assertEqual(self.lbf.append('1234\033[1;2f4321', 3.0), ('1234\n', [4], [3.0]))
self.assertEqual(self.lbf.flush(), ('4321\n', [4], [3.0]))
def test_long_lines(self):
"""long lines are split"""
self.assertEqual(self.lbf.append('123456789012', 1.0), None)
self.assertEqual(
self.lbf.append('123456789012', 2.0), ('1234567890121234567\n', [19], [1.0])
)
self.assertEqual(
self.lbf.append('123456789012345', 3.0), ('8901212345678901234\n', [19], [2.0])
)
self.assertEqual(self.lbf.append('123456789012', 4.0), None)
self.assertEqual(self.lbf.flush(), ('5123456789012\n', [13], [3.0]))
def test_empty_flush(self):
self.assertEqual(self.lbf.flush(), None)
| 5,854 | Python | .py | 109 | 45.633028 | 100 | 0.603985 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
5,074 | misc.py | buildbot_buildbot/worker/buildbot_worker/test/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
import builtins
import errno
import os
import re
import shutil
import sys
from io import StringIO
from unittest import mock
from twisted.python import log
from buildbot_worker.scripts import base
def nl(s):
"""Convert the given string to the native newline format, assuming it is
already in normal UNIX newline format (\n). Use this to create the
appropriate expectation in an assertEqual"""
if not isinstance(s, str):
return s
return s.replace('\n', os.linesep)
class BasedirMixin:
"""Mix this in and call setUpBasedir and tearDownBasedir to set up
a clean basedir with a name given in self.basedir."""
def setUpBasedir(self):
self.basedir = "test-basedir"
if os.path.exists(self.basedir):
shutil.rmtree(self.basedir)
def tearDownBasedir(self):
if os.path.exists(self.basedir):
shutil.rmtree(self.basedir)
class IsWorkerDirMixin:
"""
Mixin for setting up mocked base.isWorkerDir() function
"""
def setupUpIsWorkerDir(self, return_value):
self.isWorkerDir = mock.Mock(return_value=return_value)
self.patch(base, "isWorkerDir", self.isWorkerDir)
class PatcherMixin:
"""
Mix this in to get a few special-cased patching methods
"""
def patch_os_uname(self, replacement):
# twisted's 'patch' doesn't handle the case where an attribute
# doesn't exist..
if hasattr(os, 'uname'):
self.patch(os, 'uname', replacement)
else:
def cleanup():
del os.uname
self.addCleanup(cleanup)
os.uname = replacement
class FileIOMixin:
"""
Mixin for patching open(), read() and write() to simulate successful
I/O operations and various I/O errors.
"""
def setUpOpen(self, file_contents="dummy-contents"):
"""
patch open() to return file object with provided contents.
@param file_contents: contents that will be returned by file object's
read() method
"""
# Use mock.mock_open() to create a substitute for
# open().
fakeOpen = mock.mock_open(read_data=file_contents)
# When fakeOpen() is called, it returns a Mock
# that has these methods: read(), write(), __enter__(), __exit__().
# read() will always return the value of the 'file_contents variable.
self.fileobj = fakeOpen()
# patch open() to always return our Mock file object
self.open = mock.Mock(return_value=self.fileobj)
self.patch(builtins, "open", self.open)
def setUpOpenError(self, errno=errno.ENOENT, strerror="dummy-msg", filename="dummy-file"):
"""
patch open() to raise IOError
@param errno: exception's errno value
@param strerror: exception's strerror value
@param filename: exception's filename value
"""
# Use mock.mock_open() to create a substitute for
# open().
fakeOpen = mock.mock_open()
# Add side_effect so that calling fakeOpen() will always
# raise an IOError.
fakeOpen.side_effect = OSError(errno, strerror, filename)
self.open = fakeOpen
self.patch(builtins, "open", self.open)
def setUpReadError(self, errno=errno.EIO, strerror="dummy-msg", filename="dummy-file"):
"""
patch open() to return a file object that will raise IOError on read()
@param errno: exception's errno value
@param strerror: exception's strerror value
@param filename: exception's filename value
"""
# Use mock.mock_open() to create a substitute for
# open().
fakeOpen = mock.mock_open()
# When fakeOpen() is called, it returns a Mock
# that has these methods: read(), write(), __enter__(), __exit__().
self.fileobj = fakeOpen()
# Add side_effect so that calling read() will always
# raise an IOError.
self.fileobj.read.side_effect = OSError(errno, strerror, filename)
# patch open() to always return our Mock file object
self.open = mock.Mock(return_value=self.fileobj)
self.patch(builtins, "open", self.open)
def setUpWriteError(self, errno=errno.ENOSPC, strerror="dummy-msg", filename="dummy-file"):
"""
patch open() to return a file object that will raise IOError on write()
@param errno: exception's errno value
@param strerror: exception's strerror value
@param filename: exception's filename value
"""
# Use mock.mock_open() to create a substitute for
# open().
fakeOpen = mock.mock_open()
# When fakeOpen() is called, it returns a Mock
# that has these methods: read(), write(), __enter__(), __exit__().
self.fileobj = fakeOpen()
# Add side_effect so that calling write() will always
# raise an IOError.
self.fileobj.write.side_effect = OSError(errno, strerror, filename)
# patch open() to always return our Mock file object
self.open = mock.Mock(return_value=self.fileobj)
self.patch(builtins, "open", self.open)
class LoggingMixin:
def setUpLogging(self):
self._logEvents = []
log.addObserver(self._logEvents.append)
self.addCleanup(log.removeObserver, self._logEvents.append)
def assertLogged(self, *args):
for regexp in args:
r = re.compile(regexp)
for event in self._logEvents:
msg = log.textFromEventDict(event)
if msg is not None and r.search(msg):
return
self.fail(f"{regexp!r} not matched in log output.\n{self._logEvents} ")
def assertWasQuiet(self):
self.assertEqual(self._logEvents, [])
class StdoutAssertionsMixin:
"""
Mix this in to be able to assert on stdout during the test
"""
def setUpStdoutAssertions(self):
self.stdout = StringIO()
self.patch(sys, 'stdout', self.stdout)
def assertWasQuiet(self):
self.assertEqual(self.stdout.getvalue(), '')
def assertInStdout(self, exp):
self.assertIn(exp, self.stdout.getvalue())
def assertStdoutEqual(self, exp, msg=None):
self.assertEqual(exp, self.stdout.getvalue(), msg)
def getStdout(self):
return self.stdout.getvalue().strip()
| 7,120 | Python | .py | 166 | 35.39759 | 95 | 0.657399 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
5,075 | test_buffer_manager.py | buildbot_buildbot/worker/buildbot_worker/test/util/test_buffer_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 twisted.trial import unittest
from buildbot_worker.test.reactor import TestReactorMixin
from buildbot_worker.util import buffer_manager
class BufferManager(TestReactorMixin, unittest.TestCase):
def setUp(self):
self.results_collected = []
self.setup_test_reactor()
def message_consumer(self, msg_data):
self.results_collected.append(msg_data)
def assert_sent_messages(self, expected):
self.assertEqual(self.results_collected, expected)
self.results_collected = []
def test_append_message_rc_fits_in_buffer(self):
manager = buffer_manager.BufferManager(self.reactor, self.message_consumer, 20, 5)
manager.append("rc", 1)
self.assert_sent_messages([])
manager.flush()
self.assert_sent_messages([[("rc", 1)]])
def test_append_message_log_in_one_msg(self):
manager = buffer_manager.BufferManager(self.reactor, self.message_consumer, 40, 5)
manager.append("stdout", ('12\n', [2], [1.0]))
self.assert_sent_messages([])
manager.append("log", ('log_test', ('text\n', [4], [0.0])))
self.assert_sent_messages([])
manager.flush()
self.assert_sent_messages([
[("stdout", ('12\n', [2], [1.0])), ("log", ('log_test', ('text\n', [4], [0.0])))]
])
def test_append_message_rc_in_one_msg(self):
manager = buffer_manager.BufferManager(self.reactor, self.message_consumer, 40, 5)
manager.append("stdout", ('12\n', [2], [1.0]))
self.assert_sent_messages([])
manager.append("rc", 1)
self.assert_sent_messages([])
manager.flush()
self.assert_sent_messages([[("stdout", ('12\n', [2], [1.0])), ("rc", 1)]])
def test_append_message_log_exceeds_buffer(self):
manager = buffer_manager.BufferManager(self.reactor, self.message_consumer, 20, 5)
manager.append("stdout", ('12\n', [2], [1.0]))
self.assert_sent_messages([])
manager.append("log", ('log_test', ('tex\n', [4], [0.0])))
self.assert_sent_messages([[("stdout", ('12\n', [2], [1.0]))]])
manager.flush()
self.assert_sent_messages([[("log", ('log_test', ('tex\n', [4], [0.0])))]])
def test_append_message_rc_exceeds_buffer(self):
manager = buffer_manager.BufferManager(self.reactor, self.message_consumer, 20, 5)
manager.append("stdout", ('12\n', [2], [1.0]))
self.assert_sent_messages([])
manager.append("rc", 1)
self.assert_sent_messages([[("stdout", ('12\n', [2], [1.0]))]])
manager.flush()
self.assert_sent_messages([[("rc", 1)]])
def test_append_two_messages_rc_exceeds_buffer(self):
manager = buffer_manager.BufferManager(self.reactor, self.message_consumer, 15, 5)
manager.append("rc", 1)
self.assert_sent_messages([[("rc", 1)]])
manager.append("rc", 0)
self.assert_sent_messages([[("rc", 0)]])
manager.flush()
self.assert_sent_messages([])
def test_append_two_messages_rc_fits_in_buffer(self):
manager = buffer_manager.BufferManager(self.reactor, self.message_consumer, 40, 5)
manager.append("rc", 1)
self.assert_sent_messages([])
manager.append("rc", 0)
self.assert_sent_messages([])
manager.flush()
self.assert_sent_messages([[("rc", 1), ("rc", 0)]])
def test_append_message_exceeds_buffer(self):
manager = buffer_manager.BufferManager(self.reactor, self.message_consumer, 20, 5)
manager.append("stdout", ('12345\n', [5], [1.0]))
self.assert_sent_messages([[("stdout", ("12345\n", [5], [1.0]))]])
manager.flush()
self.assert_sent_messages([])
def test_append_message_fits_in_buffer(self):
manager = buffer_manager.BufferManager(self.reactor, self.message_consumer, 18, 5)
manager.append("stdout", ("1\n", [1], [1.0]))
self.assert_sent_messages([])
manager.flush()
self.assert_sent_messages([[("stdout", ("1\n", [1], [1.0]))]])
# only to see if flush does not send any more messages
manager.flush()
self.assert_sent_messages([])
def test_append_two_messages_exceeds_buffer(self):
manager = buffer_manager.BufferManager(self.reactor, self.message_consumer, 20, 5)
manager.append("stdout", ("1\n", [1], [1.0]))
self.assert_sent_messages([])
manager.append("stdout", ("22\n", [2], [2.0]))
self.assert_sent_messages([[("stdout", ("1\n", [1], [1.0]))]])
manager.flush()
self.assert_sent_messages([[('stdout', ('22\n', [2], [2.0]))]])
def test_append_two_messages_same_logname_log_joined(self):
manager = buffer_manager.BufferManager(self.reactor, self.message_consumer, 40, 5)
manager.append("log", ("log_test", ("1\n", [1], [1.0])))
self.assert_sent_messages([])
manager.append("log", ("log_test", ("2\n", [1], [2.0])))
self.assert_sent_messages([])
manager.flush()
self.assert_sent_messages([[("log", ("log_test", ("1\n2\n", [1, 3], [1.0, 2.0])))]])
def test_append_two_messages_same_logname_joined(self):
manager = buffer_manager.BufferManager(self.reactor, self.message_consumer, 40, 5)
manager.append("stdout", ("1\n", [1], [1.0]))
self.assert_sent_messages([])
manager.append("stdout", ("2\n", [1], [2.0]))
self.assert_sent_messages([])
manager.flush()
self.assert_sent_messages([[("stdout", ("1\n2\n", [1, 3], [1.0, 2.0]))]])
def test_append_two_messages_same_logname_log_joined_many_lines(self):
manager = buffer_manager.BufferManager(self.reactor, self.message_consumer, 80, 5)
manager.append("log", ("log_test", ("1\n2\n", [1, 3], [1.0, 2.0])))
self.assert_sent_messages([])
manager.append("log", ("log_test", ("3\n4\n", [1, 3], [3.0, 4.0])))
self.assert_sent_messages([])
manager.flush()
self.assert_sent_messages([
[("log", ("log_test", ("1\n2\n3\n4\n", [1, 3, 5, 7], [1.0, 2.0, 3.0, 4.0])))]
])
def test_append_two_messages_same_logname_joined_many_lines(self):
manager = buffer_manager.BufferManager(self.reactor, self.message_consumer, 80, 5)
manager.append("stdout", ("1\n2\n", [1, 3], [1.0, 2.0]))
self.assert_sent_messages([])
manager.append("stdout", ("3\n4\n", [1, 3], [3.0, 4.0]))
self.assert_sent_messages([])
manager.flush()
self.assert_sent_messages([
[("stdout", ("1\n2\n3\n4\n", [1, 3, 5, 7], [1.0, 2.0, 3.0, 4.0]))]
])
def test_append_three_messages_not_same_logname_log_not_joined(self):
manager = buffer_manager.BufferManager(self.reactor, self.message_consumer, 70, 5)
manager.append("log", ("log_test", ("1\n", [1], [1.0])))
self.assert_sent_messages([])
manager.append("log", ("log_test2", ("2\n", [1], [2.0])))
self.assert_sent_messages([])
manager.append("log", ("log_test3", ("3\n", [1], [3.0])))
self.assert_sent_messages([])
manager.flush()
self.assert_sent_messages([
[
("log", ("log_test", ("1\n", [1], [1.0]))),
("log", ("log_test2", ("2\n", [1], [2.0]))),
("log", ("log_test3", ("3\n", [1], [3.0]))),
]
])
def test_append_three_messages_not_same_logname_not_joined(self):
manager = buffer_manager.BufferManager(self.reactor, self.message_consumer, 60, 5)
manager.append("stdout", ("1\n", [1], [1.0]))
self.assert_sent_messages([])
manager.append("stderr", ("2\n", [1], [2.0]))
self.assert_sent_messages([])
manager.append("stdout", ("3\n", [1], [3.0]))
self.assert_sent_messages([])
manager.flush()
self.assert_sent_messages([
[
("stdout", ("1\n", [1], [1.0])),
("stderr", ("2\n", [1], [2.0])),
("stdout", ("3\n", [1], [3.0])),
]
])
def test_append_two_messages_same_logname_log_exceeds_buffer(self):
manager = buffer_manager.BufferManager(self.reactor, self.message_consumer, 20, 5)
manager.append("log", ("log_test", ("1234\n", [4], [1.0])))
self.assert_sent_messages([[("log", ("log_test", ("1234\n", [4], [1.0])))]])
manager.append("log", ("log_test", ("5678\n", [4], [2.0])))
self.assert_sent_messages([[("log", ("log_test", ("5678\n", [4], [2.0])))]])
manager.flush()
self.assert_sent_messages([])
def test_append_two_messages_same_logname_exceeds_buffer(self):
manager = buffer_manager.BufferManager(self.reactor, self.message_consumer, 20, 5)
manager.append("stdout", ("1234\n", [4], [1.0]))
self.assert_sent_messages([[("stdout", ("1234\n", [4], [1.0]))]])
manager.append("stdout", ("5678\n", [4], [2.0]))
self.assert_sent_messages([[("stdout", ("5678\n", [4], [2.0]))]])
manager.flush()
self.assert_sent_messages([])
def test_append_exceeds_buffer_log_long_line_first_line_too_long(self):
manager = buffer_manager.BufferManager(self.reactor, self.message_consumer, 20, 5)
manager.append(
"log",
(
"log_test",
("tbe5\nta4\ntbe5\nt3\ntd4\n", [4, 8, 13, 16, 20], [1.0, 2.0, 3.0, 4.0, 5.0]),
),
)
self.assert_sent_messages([
[("log", ("log_test", ("tbe5\n", [4], [1.0])))],
[("log", ("log_test", ("ta4\n", [3], [2.0])))],
[("log", ("log_test", ("tbe5\n", [4], [3.0])))],
[("log", ("log_test", ("t3\n", [2], [4.0])))],
[("log", ("log_test", ("td4\n", [3], [5.0])))],
])
manager.flush()
self.assert_sent_messages([])
def test_append_exceeds_buffer_long_line_first_line_too_long(self):
manager = buffer_manager.BufferManager(self.reactor, self.message_consumer, 20, 5)
manager.append(
"stdout", ("tbe5\nta4\ntbe5\nt3\ntd4\n", [4, 8, 13, 16, 20], [1.0, 2.0, 3.0, 4.0, 5.0])
)
self.assert_sent_messages([
[("stdout", ("tbe5\n", [4], [1.0]))],
[("stdout", ("ta4\n", [3], [2.0]))],
[("stdout", ("tbe5\n", [4], [3.0]))],
[("stdout", ("t3\n", [2], [4.0]))],
[("stdout", ("td4\n", [3], [5.0]))],
])
manager.flush()
self.assert_sent_messages([])
def test_append_exceeds_buffer_log_long_line_middle_line_too_long(self):
manager = buffer_manager.BufferManager(self.reactor, self.message_consumer, 20, 5)
manager.append(
"log",
(
"log_test",
("t3\nta4\ntbe5\nt3\ntd4\n", [2, 6, 11, 14, 18], [1.0, 2.0, 3.0, 4.0, 5.0]),
),
)
self.assert_sent_messages([
[("log", ("log_test", ("t3\n", [2], [1.0])))],
[("log", ("log_test", ("ta4\n", [3], [2.0])))],
[("log", ("log_test", ("tbe5\n", [4], [3.0])))],
[("log", ("log_test", ("t3\n", [2], [4.0])))],
[("log", ("log_test", ("td4\n", [3], [5.0])))],
])
manager.flush()
self.assert_sent_messages([])
def test_append_exceeds_buffer_long_line_middle_line_too_long(self):
manager = buffer_manager.BufferManager(self.reactor, self.message_consumer, 20, 5)
manager.append(
"stdout", ("t3\nta4\ntbe5\nt3\ntd4\n", [2, 6, 11, 14, 18], [1.0, 2.0, 3.0, 4.0, 5.0])
)
self.assert_sent_messages([
[("stdout", ("t3\n", [2], [1.0]))],
[("stdout", ("ta4\n", [3], [2.0]))],
[("stdout", ("tbe5\n", [4], [3.0]))],
[("stdout", ("t3\n", [2], [4.0]))],
[("stdout", ("td4\n", [3], [5.0]))],
])
manager.flush()
self.assert_sent_messages([])
def test_append_long_line_log_concatenate(self):
manager = buffer_manager.BufferManager(self.reactor, self.message_consumer, 60, 5)
manager.append(
"log",
(
"log_test",
(
"text_text_text_text_text_text_text_text_\nlex\nteym\nte\ntuz\n",
[40, 44, 49, 52, 56],
[1.0, 2.0, 3.0, 4.0, 5.0],
),
),
)
self.assert_sent_messages([
[("log", ("log_test", ("text_text_text_text_text_text_text_text_\n", [40], [1.0])))],
[("log", ("log_test", ("lex\nteym\nte\n", [3, 8, 11], [2.0, 3.0, 4.0])))],
[("log", ("log_test", ("tuz\n", [3], [5.0])))],
])
manager.flush()
self.assert_sent_messages([])
def test_append_long_line_concatenate(self):
manager = buffer_manager.BufferManager(self.reactor, self.message_consumer, 60, 5)
manager.append(
"stdout",
(
"text_text_text_text_text_text_text_text_\nlex\nteym\nte\ntuz\n",
[40, 44, 49, 52, 56],
[1.0, 2.0, 3.0, 4.0, 5.0],
),
)
self.assert_sent_messages([
[("stdout", ("text_text_text_text_text_text_text_text_\n", [40], [1.0]))],
[("stdout", ("lex\nteym\nte\n", [3, 8, 11], [2.0, 3.0, 4.0]))],
[("stdout", ("tuz\n", [3], [5.0]))],
])
manager.flush()
self.assert_sent_messages([])
def test_append_log_not_fitting_line_after_fitting_line(self):
manager = buffer_manager.BufferManager(self.reactor, self.message_consumer, 20, 5)
manager.append("log", ("log_test", ("12\n", [4], [1.0])))
self.assert_sent_messages([])
manager.append("log", ("log_test", ("345678\n", [6], [2.0])))
self.assert_sent_messages([
[("log", ("log_test", ("12\n", [4], [1.0])))],
[("log", ("log_test", ("345678\n", [6], [2.0])))],
])
manager.flush()
self.assert_sent_messages([])
def test_append_not_fitting_line_after_fitting_line(self):
manager = buffer_manager.BufferManager(self.reactor, self.message_consumer, 20, 5)
manager.append("stdout", ("12\n", [4], [1.0]))
self.assert_sent_messages([])
manager.append("stdout", ("345678\n", [6], [2.0]))
self.assert_sent_messages([
[("stdout", ("12\n", [4], [1.0]))],
[("stdout", ("345678\n", [6], [2.0]))],
])
manager.flush()
self.assert_sent_messages([])
def test_append_timeout_fits_in_buffer_timeout_expires_with_message(self):
manager = buffer_manager.BufferManager(self.reactor, self.message_consumer, 20, 5)
manager.append("stdout", ('12\n', [2], [1.0]))
self.assert_sent_messages([])
self.reactor.advance(4)
self.assert_sent_messages([])
self.reactor.advance(1)
self.assert_sent_messages([[("stdout", ("12\n", [2], [1.0]))]])
self.reactor.advance(5)
self.assert_sent_messages([])
manager.flush()
self.assert_sent_messages([])
def test_append_timeout_fits_in_buffer_two_messages_before_timeout_expires(self):
manager = buffer_manager.BufferManager(self.reactor, self.message_consumer, 40, 5)
manager.append("stdout", ('12\n', [2], [1.0]))
self.assert_sent_messages([])
self.reactor.advance(1)
manager.append("stdout", ('345\n', [3], [2.0]))
self.assert_sent_messages([])
self.reactor.advance(4)
self.assert_sent_messages([[("stdout", ("12\n345\n", [2, 6], [1.0, 2.0]))]])
self.reactor.advance(5)
self.assert_sent_messages([])
manager.flush()
self.assert_sent_messages([])
def test_append_timeout_two_messages_timeout_expires_with_single_message(self):
manager = buffer_manager.BufferManager(self.reactor, self.message_consumer, 40, 5)
manager.append("stdout", ('12\n', [2], [1.0]))
self.assert_sent_messages([])
self.reactor.advance(5)
self.assert_sent_messages([[("stdout", ("12\n", [2], [1.0]))]])
manager.append("stdout", ('345\n', [3], [2.0]))
self.assert_sent_messages([])
self.reactor.advance(5)
self.assert_sent_messages([[("stdout", ("345\n", [3], [2.0]))]])
manager.flush()
self.assert_sent_messages([])
def test_append_timeout_long_line_flushes_short_line_before_timeout(self):
manager = buffer_manager.BufferManager(self.reactor, self.message_consumer, 20, 5)
manager.append("stdout", ('12\n', [2], [1.0]))
self.assert_sent_messages([])
manager.append("stdout", ('345678\n', [6], [2.0]))
self.assert_sent_messages([
[("stdout", ("12\n", [2], [1.0]))],
[("stdout", ("345678\n", [6], [2.0]))],
])
self.reactor.advance(5)
self.assert_sent_messages([])
manager.flush()
self.assert_sent_messages([])
| 17,818 | Python | .py | 362 | 39.577348 | 99 | 0.551637 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
5,076 | __init__.py | buildbot_buildbot/worker/buildbot_worker/monkeypatches/__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
def patch_all():
from buildbot_worker.monkeypatches import testcase_assert
testcase_assert.patch()
| 815 | Python | .py | 17 | 46.294118 | 79 | 0.787421 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
5,077 | testcase_assert.py | buildbot_buildbot/worker/buildbot_worker/monkeypatches/testcase_assert.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 unittest
def patch():
hasAssertRaisesRegex = getattr(unittest.TestCase, "assertRaisesRegex", None)
if not hasAssertRaisesRegex:
# Python 2.6 and Python 2.7
unittest.TestCase.assertRaisesRegex = unittest.TestCase.assertRaisesRegexp
| 970 | Python | .py | 20 | 46.15 | 82 | 0.783527 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
5,078 | fs.py | buildbot_buildbot/worker/buildbot_worker/commands/fs.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 glob
import os
import platform
import shutil
import sys
from twisted.internet import defer
from twisted.internet import threads
from twisted.python import runtime
from buildbot_worker import runprocess
from buildbot_worker.commands import base
from buildbot_worker.commands import utils
class MakeDirectory(base.Command):
header = "mkdir"
# args['paths'] specifies the absolute paths of directories to create
requiredArgs = ['paths']
def start(self):
paths = self.args['paths']
for dirname in paths:
try:
if not os.path.isdir(dirname):
os.makedirs(dirname)
except OSError as e:
self.log_msg(f"MakeDirectory {dirname} failed: {e}")
self.sendStatus([
('header', f'{self.header}: {e.strerror}: {dirname}'),
('rc', e.errno),
])
return
self.sendStatus([('rc', 0)])
class RemoveDirectory(base.Command):
header = "rmdir"
# args['paths'] specifies the absolute paths of directories or files to remove
requiredArgs = ['paths']
def setup(self, args):
self.logEnviron = args.get('logEnviron', True)
@defer.inlineCallbacks
def start(self):
args = self.args
dirnames = args['paths']
self.timeout = args.get('timeout', 120)
self.maxTime = args.get('maxTime', None)
self.rc = 0
assert dirnames
for path in dirnames:
res = yield self.removeSingleDir(path)
# Even if single removal of single file/dir consider it as
# failure of whole command, but continue removing other files
# Send 'rc' to master to handle failure cases
if res != 0:
self.rc = res
self.sendStatus([('rc', self.rc)])
def removeSingleDir(self, path):
if runtime.platformType != "posix":
d = threads.deferToThread(utils.rmdirRecursive, path)
def cb(_):
return 0 # rc=0
def eb(f):
self.sendStatus([('header', 'exception from rmdirRecursive\n' + f.getTraceback())])
return -1 # rc=-1
d.addCallbacks(cb, eb)
else:
d = self._clobber(None, path)
return d
@defer.inlineCallbacks
def _clobber(self, dummy, path, chmodDone=False):
command = ["rm", "-rf", path]
c = runprocess.RunProcess(
self.command_id,
command,
self.protocol_command.worker_basedir,
self.protocol_command.unicode_encoding,
self.protocol_command.send_update,
sendRC=0,
timeout=self.timeout,
maxTime=self.maxTime,
logEnviron=self.logEnviron,
usePTY=False,
)
self.command = c
# sendRC=0 means the rm command will send stdout/stderr to the
# master, but not the rc=0 when it finishes. That job is left to
# _sendRC
rc = yield c.start()
# The rm -rf may fail if there is a left-over subdir with chmod 000
# permissions. So if we get a failure, we attempt to chmod suitable
# permissions and re-try the rm -rf.
if not chmodDone:
rc = yield self._tryChmod(rc, path)
return rc
@defer.inlineCallbacks
def _tryChmod(self, rc, path):
assert isinstance(rc, int)
if rc == 0:
return 0
# Attempt a recursive chmod and re-try the rm -rf after.
command = ["chmod", "-Rf", "u+rwx", path]
if sys.platform.startswith('freebsd'):
# Work around a broken 'chmod -R' on FreeBSD (it tries to recurse into a
# directory for which it doesn't have permission, before changing that
# permission) by running 'find' instead
command = ["find", path, '-exec', 'chmod', 'u+rwx', '{}', ';']
c = runprocess.RunProcess(
self.command_id,
command,
self.protocol_command.worker_basedir,
self.protocol_command.unicode_encoding,
self.protocol_command.send_update,
sendRC=0,
timeout=self.timeout,
maxTime=self.maxTime,
logEnviron=self.logEnviron,
usePTY=False,
)
self.command = c
rc = yield c.start()
rc = yield self._clobber(rc, path, True)
return rc
class CopyDirectory(base.Command):
header = "cpdir"
# args['to_path'] and args['from_path'] are relative to Builder directory, and
# are required.
requiredArgs = ['to_path', 'from_path']
def setup(self, args):
self.logEnviron = args.get('logEnviron', True)
def start(self):
args = self.args
from_path = self.args['from_path']
to_path = self.args['to_path']
self.timeout = args.get('timeout', 120)
self.maxTime = args.get('maxTime', None)
if runtime.platformType != "posix":
d = threads.deferToThread(shutil.copytree, from_path, to_path)
def cb(_):
return 0 # rc=0
def eb(f):
self.sendStatus([('header', 'exception from copytree\n' + f.getTraceback())])
return -1 # rc=-1
d.addCallbacks(cb, eb)
@d.addCallback
def send_rc(rc):
self.sendStatus([('rc', rc)])
else:
if not os.path.exists(os.path.dirname(to_path)):
os.makedirs(os.path.dirname(to_path))
if os.path.exists(to_path):
# I don't think this happens, but just in case..
self.log_msg(
f"cp target '{to_path}' already exists -- cp will not do what you think!"
)
if platform.system().lower().find('solaris') >= 0:
command = ['cp', '-R', '-P', '-p', from_path, to_path]
else:
command = ['cp', '-R', '-P', '-p', '-v', from_path, to_path]
c = runprocess.RunProcess(
self.command_id,
command,
self.protocol_command.worker_basedir,
self.protocol_command.unicode_encoding,
self.protocol_command.send_update,
sendRC=False,
timeout=self.timeout,
maxTime=self.maxTime,
logEnviron=self.logEnviron,
usePTY=False,
)
self.command = c
d = c.start()
d.addCallback(self._abandonOnFailure)
d.addCallbacks(self._sendRC, self._checkAbandoned)
return d
class StatFile(base.Command):
header = "stat"
# args['path'] absolute path of a file
requireArgs = ['path']
def start(self):
filename = self.args['path']
try:
stat = os.stat(filename)
self.sendStatus([('stat', tuple(stat)), ('rc', 0)])
except OSError as e:
self.log_msg(f"StatFile {filename} failed: {e}")
self.sendStatus([
('header', f'{self.header}: {e.strerror}: {filename}'),
('rc', e.errno),
])
class GlobPath(base.Command):
header = "glob"
# args['path'] shell-style path specification of a pattern
requiredArgs = ['path']
def start(self):
pathname = self.args['path']
try:
files = glob.glob(pathname, recursive=True)
self.sendStatus([('files', files), ('rc', 0)])
except OSError as e:
self.log_msg(f"GlobPath {pathname} failed: {e}")
self.sendStatus([
('header', f'{self.header}: {e.strerror}: {pathname}'),
('rc', e.errno),
])
class ListDir(base.Command):
header = "listdir"
# args['path'] absolute path of the directory to list
requireArgs = ['path']
def start(self):
dirname = self.args['path']
try:
files = os.listdir(dirname)
self.sendStatus([('files', files), ('rc', 0)])
except OSError as e:
self.log_msg(f"ListDir {dirname} failed: {e}")
self.sendStatus([
('header', f'{self.header}: {e.strerror}: {dirname}'),
('rc', e.errno),
])
class RemoveFile(base.Command):
header = "rmfile"
# args['path'] absolute path of a file to delete
requiredArgs = ['path']
def start(self):
pathname = self.args['path']
try:
os.remove(pathname)
self.sendStatus([('rc', 0)])
except OSError as e:
self.log_msg(f"remove file {pathname} failed: {e}")
self.sendStatus([
('header', f'{self.header}: {e.strerror}: {pathname}'),
('rc', e.errno),
])
| 9,610 | Python | .py | 244 | 29.155738 | 99 | 0.571382 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
5,079 | transfer.py | buildbot_buildbot/worker/buildbot_worker/commands/transfer.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 tarfile
import tempfile
from twisted.internet import defer
from twisted.python import log
from buildbot_worker.commands.base import Command
class TransferCommand(Command):
def finished(self, res):
if self.debug:
self.log_msg(f'finished: stderr={self.stderr!r}, rc={self.rc!r}')
# don't use self.sendStatus here, since we may no longer be running
# if we have been interrupted
updates = [('rc', self.rc)]
if self.stderr:
updates.append(('stderr', self.stderr))
self.protocol_command.send_update(updates)
return res
def interrupt(self):
if self.debug:
self.log_msg('interrupted')
if self.interrupted:
return
self.rc = 1
self.interrupted = True
# now we wait for the next trip around the loop. It abandon the file
# when it sees self.interrupted set.
class WorkerFileUploadCommand(TransferCommand):
"""
Upload a file from worker to build master
Arguments:
- ['path']: path to read from
- ['writer']: RemoteReference to a buildbot_worker.protocols.base.FileWriterProxy object
- ['maxsize']: max size (in bytes) of file to write
- ['blocksize']: max size for each data block
- ['keepstamp']: whether to preserve file modified and accessed times
"""
debug = False
requiredArgs = ['path', 'writer', 'blocksize']
def setup(self, args):
self.path = args['path']
self.writer = args['writer']
self.remaining = args['maxsize']
self.blocksize = args['blocksize']
self.keepstamp = args.get('keepstamp', False)
self.stderr = None
self.rc = 0
self.fp = None
def start(self):
if self.debug:
self.log_msg('WorkerFileUploadCommand started')
access_time = None
modified_time = None
try:
if self.keepstamp:
access_time = os.path.getatime(self.path)
modified_time = os.path.getmtime(self.path)
self.fp = open(self.path, 'rb')
if self.debug:
self.log_msg(f"Opened '{self.path}' for upload")
except Exception:
self.fp = None
self.stderr = f"Cannot open file '{self.path}' for upload"
self.rc = 1
if self.debug:
self.log_msg(f"Cannot open file '{self.path}' for upload")
self.sendStatus([('header', f"sending {self.path}\n")])
d = defer.Deferred()
self._reactor.callLater(0, self._loop, d)
@defer.inlineCallbacks
def _close_ok(res):
if self.fp:
self.fp.close()
self.fp = None
yield self.protocol_command.protocol_update_upload_file_close(self.writer)
if self.keepstamp:
yield self.protocol_command.protocol_update_upload_file_utime(
self.writer, access_time, modified_time
)
def _close_err(f):
self.rc = 1
if self.fp:
self.fp.close()
self.fp = None
# call remote's close(), but keep the existing failure
d1 = self.protocol_command.protocol_update_upload_file_close(self.writer)
def eb(f2):
self.log_msg("ignoring error from remote close():")
log.err(f2)
d1.addErrback(eb)
d1.addBoth(lambda _: f) # always return _loop failure
return d1
d.addCallbacks(_close_ok, _close_err)
d.addBoth(self.finished)
return d
def _loop(self, fire_when_done):
d = defer.maybeDeferred(self._writeBlock)
def _done(finished):
if finished:
fire_when_done.callback(None)
else:
self._loop(fire_when_done)
def _err(why):
fire_when_done.errback(why)
d.addCallbacks(_done, _err)
return None
def _writeBlock(self):
"""Write a block of data to the remote writer"""
if self.interrupted or self.fp is None:
if self.debug:
self.log_msg('WorkerFileUploadCommand._writeBlock(): end')
return True
length = self.blocksize
if self.remaining is not None and length > self.remaining:
length = self.remaining
if length <= 0:
if self.stderr is None:
self.stderr = f'Maximum filesize reached, truncating file \'{self.path}\''
self.rc = 1
data = ''
else:
data = self.fp.read(length)
if self.debug:
self.log_msg(
'WorkerFileUploadCommand._writeBlock(): ' + f'allowed={length} readlen={len(data)}'
)
if not data:
self.log_msg("EOF: callRemote(close)")
return True
if self.remaining is not None:
self.remaining = self.remaining - len(data)
assert self.remaining >= 0
d = self.do_protocol_write(data)
d.addCallback(lambda res: False)
return d
def do_protocol_write(self, data):
return self.protocol_command.protocol_update_upload_file_write(self.writer, data)
class WorkerDirectoryUploadCommand(WorkerFileUploadCommand):
debug = False
requiredArgs = ['path', 'writer', 'blocksize']
def setup(self, args):
self.path = args['path']
self.writer = args['writer']
self.remaining = args['maxsize']
self.blocksize = args['blocksize']
self.compress = args['compress']
self.stderr = None
self.rc = 0
def start(self):
if self.debug:
self.log_msg('WorkerDirectoryUploadCommand started')
if self.debug:
self.log_msg(f"path: {self.path!r}")
# Create temporary archive
fd, self.tarname = tempfile.mkstemp(prefix='buildbot-transfer-')
self.fp = os.fdopen(fd, "rb+")
if self.compress == 'bz2':
mode = 'w|bz2'
elif self.compress == 'gz':
mode = 'w|gz'
else:
mode = 'w'
with tarfile.open(mode=mode, fileobj=self.fp) as archive:
try:
archive.add(self.path, '')
except OSError as e:
# if directory does not exist, bail out with an error
self.stderr = f"Cannot read directory '{self.path}' for upload: {e}"
self.rc = 1
archive.close() # need to close it before self.finished() runs below
d = defer.succeed(False)
d.addCallback(self.finished)
return d
# Transfer it
self.fp.seek(0)
self.sendStatus([('header', f"sending {self.path}\n")])
d = defer.Deferred()
self._reactor.callLater(0, self._loop, d)
def unpack(res):
d1 = self.protocol_command.protocol_update_upload_directory(self.writer)
def unpack_err(f):
self.rc = 1
return f
d1.addErrback(unpack_err)
d1.addCallback(lambda ignored: res)
return d1
d.addCallback(unpack)
d.addBoth(self.finished)
return d
def finished(self, res):
self.fp.close()
self.fp = None
os.remove(self.tarname)
return TransferCommand.finished(self, res)
def do_protocol_write(self, data):
return self.protocol_command.protocol_update_upload_directory_write(self.writer, data)
class WorkerFileDownloadCommand(TransferCommand):
"""
Download a file from master to worker
Arguments:
- ['path']: path of the worker-side file to be created
- ['reader']: RemoteReference to a buildbot_worker.protocols.base.FileReaderProxy object
- ['maxsize']: max size (in bytes) of file to write
- ['blocksize']: max size for each data block
- ['mode']: access mode for the new file
"""
debug = False
requiredArgs = ['path', 'reader', 'blocksize']
def setup(self, args):
self.path = args['path']
self.reader = args['reader']
self.bytes_remaining = args['maxsize']
self.blocksize = args['blocksize']
self.mode = args['mode']
self.stderr = None
self.rc = 0
self.fp = None
def start(self):
if self.debug:
self.log_msg('WorkerFileDownloadCommand starting')
dirname = os.path.dirname(self.path)
if not os.path.exists(dirname):
os.makedirs(dirname)
try:
self.fp = open(self.path, 'wb')
if self.debug:
self.log_msg(f"Opened '{self.path}' for download")
if self.mode is not None:
# note: there is a brief window during which the new file
# will have the worker's default (umask) mode before we
# set the new one. Don't use this mode= feature to keep files
# private: use the worker's umask for that instead. (it
# is possible to call os.umask() before and after the open()
# call, but cleaning up from exceptions properly is more of a
# nuisance that way).
os.chmod(self.path, self.mode)
except OSError:
# TODO: this still needs cleanup
if self.fp:
self.fp.close()
self.fp = None
self.stderr = f"Cannot open file '{self.path}' for download"
self.rc = 1
if self.debug:
self.log_msg(f"Cannot open file '{self.path}' for download")
d = defer.Deferred()
self._reactor.callLater(0, self._loop, d)
def _close(res):
# close the file, but pass through any errors from _loop
d1 = self.protocol_command.protocol_update_read_file_close(self.reader)
d1.addErrback(log.err, 'while trying to close reader')
d1.addCallback(lambda ignored: res)
return d1
d.addBoth(_close)
d.addBoth(self.finished)
return d
def _loop(self, fire_when_done):
d = defer.maybeDeferred(self._readBlock)
def _done(finished):
if finished:
fire_when_done.callback(None)
else:
self._loop(fire_when_done)
def _err(why):
fire_when_done.errback(why)
d.addCallbacks(_done, _err)
return None
def _readBlock(self):
"""Read a block of data from the remote reader."""
if self.interrupted or self.fp is None:
if self.debug:
self.log_msg('WorkerFileDownloadCommand._readBlock(): end')
return True
length = self.blocksize
if self.bytes_remaining is not None and length > self.bytes_remaining:
length = self.bytes_remaining
if length <= 0:
if self.stderr is None:
self.stderr = f"Maximum filesize reached, truncating file '{self.path}'"
self.rc = 1
return True
else:
d = self.protocol_command.protocol_update_read_file(self.reader, length)
d.addCallback(self._writeData)
return d
def _writeData(self, data):
if self.debug:
self.log_msg(f'WorkerFileDownloadCommand._readBlock(): readlen={len(data)}')
if not data:
return True
if self.bytes_remaining is not None:
self.bytes_remaining = self.bytes_remaining - len(data)
assert self.bytes_remaining >= 0
self.fp.write(data)
return False
def finished(self, res):
if self.fp:
self.fp.close()
self.fp = None
return TransferCommand.finished(self, res)
| 12,636 | Python | .py | 313 | 29.958466 | 99 | 0.587966 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
5,080 | utils.py | buildbot_buildbot/worker/buildbot_worker/commands/utils.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 twisted.python import log
from twisted.python import runtime
from twisted.python.procutils import which
def getCommand(name):
possibles = which(name)
if not possibles:
raise RuntimeError(f"Couldn't find executable for '{name}'")
#
# Under windows, if there is more than one executable "thing"
# that matches (e.g. *.bat, *.cmd and *.exe), we not just use
# the first in alphabet (*.bat/*.cmd) if there is a *.exe.
# e.g. under MSysGit/Windows, there is both a git.cmd and a
# git.exe on path, but we want the git.exe, since the git.cmd
# does not seem to work properly with regard to errors raised
# and caught in buildbot worker command (vcs.py)
#
if runtime.platformType == 'win32' and len(possibles) > 1:
possibles_exe = which(name + ".exe")
if possibles_exe:
return possibles_exe[0]
return possibles[0]
# this just keeps pyflakes happy on non-Windows systems
if runtime.platformType != 'win32':
WindowsError: type | None = RuntimeError
else:
WindowsError = None
if runtime.platformType == 'win32': # pragma: no cover
def rmdirRecursive(dir):
"""This is a replacement for shutil.rmtree that works better under
windows. Thanks to Bear at the OSAF for the code."""
if not os.path.exists(dir):
return
if os.path.islink(dir) or os.path.isfile(dir):
os.remove(dir)
return
# Verify the directory is read/write/execute for the current user
os.chmod(dir, 0o700)
# os.listdir below only returns a list of unicode filenames if the parameter is unicode
# Thus, if a non-unicode-named dir contains a unicode filename, that filename will get
# garbled.
# So force dir to be unicode.
if not isinstance(dir, str):
try:
dir = str(dir, "utf-8")
except UnicodeDecodeError:
log.err("rmdirRecursive: decoding from UTF-8 failed (ignoring)")
try:
list = os.listdir(dir)
except WindowsError as e:
msg = (
"rmdirRecursive: unable to listdir {} ({}). Trying to " "remove like a dir".format(
dir, e.strerror.decode('mbcs')
)
)
log.msg(msg.encode('utf-8'))
os.rmdir(dir)
return
for name in list:
full_name = os.path.join(dir, name)
# on Windows, if we don't have write permission we can't remove
# the file/directory either, so turn that on
if os.name == 'nt':
if not os.access(full_name, os.W_OK):
# I think this is now redundant, but I don't have an NT
# machine to test on, so I'm going to leave it in place
# -warner
os.chmod(full_name, 0o600)
if os.path.islink(full_name):
os.remove(full_name) # as suggested in bug #792
elif os.path.isdir(full_name):
rmdirRecursive(full_name)
else:
if os.path.isfile(full_name):
os.chmod(full_name, 0o700)
os.remove(full_name)
os.rmdir(dir)
else:
# use rmtree on POSIX
import shutil
rmdirRecursive = shutil.rmtree
| 4,117 | Python | .py | 96 | 34.28125 | 99 | 0.630527 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
5,081 | base.py | buildbot_buildbot/worker/buildbot_worker/commands/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 twisted.internet import reactor
from twisted.python import log
from zope.interface import implementer
from buildbot_worker import util
from buildbot_worker.exceptions import AbandonChain
from buildbot_worker.interfaces import IWorkerCommand
# The following identifier should be updated each time this file is changed
command_version = "3.3"
# version history:
# >=1.17: commands are interruptable
# >=1.28: Arch understands 'revision', added Bazaar
# >=1.33: Source classes understand 'retry'
# >=1.39: Source classes correctly handle changes in branch (except Git)
# Darcs accepts 'revision' (now all do but Git) (well, and P4Sync)
# Arch/Baz should accept 'build-config'
# >=1.51: (release 0.7.3)
# >= 2.1: SlaveShellCommand now accepts 'initial_stdin', 'keep_stdin_open',
# and 'logfiles'. It now sends 'log' messages in addition to
# stdout/stdin/header/rc. It acquired writeStdin/closeStdin methods,
# but these are not remotely callable yet.
# (not externally visible: ShellCommandPP has writeStdin/closeStdin.
# ShellCommand accepts new arguments (logfiles=, initialStdin=,
# keepStdinOpen=) and no longer accepts stdin=)
# (release 0.7.4)
# >= 2.2: added monotone, uploadFile, and downloadFile (release 0.7.5)
# >= 2.3: added bzr (release 0.7.6)
# >= 2.4: Git understands 'revision' and branches
# >= 2.5: workaround added for remote 'hg clone --rev REV' when hg<0.9.2
# >= 2.6: added uploadDirectory
# >= 2.7: added usePTY option to SlaveShellCommand
# >= 2.8: added username and password args to SVN class
# >= 2.9: add depth arg to SVN class
# >= 2.10: CVS can handle 'extra_options' and 'export_options'
# >= 2.11: Arch, Bazaar, and Monotone removed
# >= 2.12: SlaveShellCommand no longer accepts 'keep_stdin_open'
# >= 2.13: SlaveFileUploadCommand supports option 'keepstamp'
# >= 2.14: RemoveDirectory can delete multiple directories
# >= 2.15: 'interruptSignal' option is added to SlaveShellCommand
# >= 2.16: 'sigtermTime' option is added to SlaveShellCommand
# >= 2.16: runprocess supports obfuscation via tuples (#1748)
# >= 2.16: listdir command added to read a directory
# >= 3.0: new buildbot-worker package:
# * worker-side usePTY configuration (usePTY='slave-config') support
# dropped,
# * remote method getSlaveInfo() renamed to getWorkerInfo().
# * "slavesrc" command argument renamed to "workersrc" in uploadFile and
# uploadDirectory commands.
# * "slavedest" command argument renamed to "workerdest" in downloadFile
# command.
# >= 3.1: rmfile command added to remove a file
# >= 3.2: shell command now reports failure reason in case the command timed out.
# >= 3.3: shell command now supports max_lines parameter.
@implementer(IWorkerCommand)
class Command:
"""This class defines one command that can be invoked by the build master.
The command is executed on the worker side, and always sends back a
completion message when it finishes. It may also send intermediate status
as it runs (by calling builder.sendStatus). Some commands can be
interrupted (either by the build master or a local timeout), in which
case the step is expected to complete normally with a status message that
indicates an error occurred.
These commands are used by BuildSteps on the master side. Each kind of
BuildStep uses a single Command. The worker must implement all the
Commands required by the set of BuildSteps used for any given build:
this is checked at startup time.
All Commands are constructed with the same signature:
c = CommandClass(builder, stepid, args)
where 'builder' is the parent WorkerForBuilder object, and 'args' is a
dict that is interpreted per-command.
The setup(args) method is available for setup, and is run from __init__.
Mandatory args can be declared by listing them in the requiredArgs property.
They will be checked before calling the setup(args) method.
The Command is started with start(). This method must be implemented in a
subclass, and it should return a Deferred. When your step is done, you
should fire the Deferred (the results are not used). If the command is
interrupted, it should fire the Deferred anyway.
While the command runs. it may send status messages back to the
buildmaster by calling self.sendStatus(statusdict). The statusdict is
interpreted by the master-side BuildStep however it likes.
A separate completion message is sent when the deferred fires, which
indicates that the Command has finished, but does not carry any status
data. If the Command needs to return an exit code of some sort, that
should be sent as a regular status message before the deferred is fired .
Once builder.commandComplete has been run, no more status messages may be
sent.
If interrupt() is called, the Command should attempt to shut down as
quickly as possible. Child processes should be killed, new ones should
not be started. The Command should send some kind of error status update,
then complete as usual by firing the Deferred.
.interrupted should be set by interrupt(), and can be tested to avoid
sending multiple error status messages.
If .running is False, the bot is shutting down (or has otherwise lost the
connection to the master), and should not send any status messages. This
is checked in Command.sendStatus .
"""
# builder methods:
# sendStatus(list of tuples) (zero or more)
# commandComplete() or commandInterrupted() (one, at end)
requiredArgs: list[str] = []
debug = False
interrupted = False
# set by Builder, cleared on shutdown or when the Deferred fires
running = False
_reactor = reactor
def __init__(self, protocol_command, command_id, args):
self.protocol_command = protocol_command
self.command_id = command_id # just for logging
self.args = args
self.startTime = None
missingArgs = [arg for arg in self.requiredArgs if arg not in args]
if missingArgs:
raise ValueError(
"{} is missing args: {}".format(self.__class__.__name__, ", ".join(missingArgs))
)
self.setup(args)
def log_msg(self, msg, *args):
log.msg(f"(command {self.command_id}): {msg}", *args)
def setup(self, args):
"""Override this in a subclass to extract items from the args dict."""
def doStart(self):
self.running = True
self.startTime = util.now(self._reactor)
d = defer.maybeDeferred(self.start)
def commandComplete(res):
self.sendStatus([("elapsed", util.now(self._reactor) - self.startTime)])
self.running = False
return res
d.addBoth(commandComplete)
return d
def start(self):
"""Start the command. This method should return a Deferred that will
fire when the command has completed. The Deferred's argument will be
ignored.
This method should be overridden by subclasses."""
raise NotImplementedError("You must implement this in a subclass")
def sendStatus(self, status):
"""Send a status update to the master."""
if self.debug:
self.log_msg(f"sendStatus: {status}")
if not self.running:
self.log_msg("would sendStatus but not .running")
return
self.protocol_command.send_update(status)
def doInterrupt(self):
self.running = False
self.interrupt()
def interrupt(self):
"""Override this in a subclass to allow commands to be interrupted.
May be called multiple times, test and set self.interrupted=True if
this matters."""
# utility methods, mostly used by WorkerShellCommand and the like
def _abandonOnFailure(self, rc):
if not isinstance(rc, int):
self.log_msg(f"weird, _abandonOnFailure was given rc={rc} ({type(rc)})")
assert isinstance(rc, int)
if rc != 0:
raise AbandonChain(rc)
return rc
def _sendRC(self, res):
self.sendStatus([('rc', 0)])
def _checkAbandoned(self, why):
self.log_msg("_checkAbandoned", why)
why.trap(AbandonChain)
self.log_msg(" abandoning chain", why.value)
self.sendStatus([('rc', why.value.args[0])])
return None
| 9,238 | Python | .py | 182 | 45.730769 | 96 | 0.707982 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
5,082 | shell.py | buildbot_buildbot/worker/buildbot_worker/commands/shell.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 import runprocess
from buildbot_worker.commands import base
class WorkerShellCommand(base.Command):
requiredArgs = ['workdir', 'command']
def start(self):
args = self.args
workdir = args['workdir']
c = runprocess.RunProcess(
self.command_id,
args['command'],
workdir,
self.protocol_command.unicode_encoding,
self.protocol_command.send_update,
environ=args.get('env'),
timeout=args.get('timeout', None),
maxTime=args.get('maxTime', None),
max_lines=args.get('max_lines', None),
sigtermTime=args.get('sigtermTime', None),
sendStdout=args.get('want_stdout', True),
sendStderr=args.get('want_stderr', True),
sendRC=True,
initialStdin=args.get('initial_stdin'),
logfiles=args.get('logfiles', {}),
usePTY=args.get('usePTY', False),
logEnviron=args.get('logEnviron', True),
)
if args.get('interruptSignal'):
c.interruptSignal = args['interruptSignal']
c._reactor = self._reactor
self.command = c
d = self.command.start()
return d
def interrupt(self):
self.interrupted = True
self.command.kill("command interrupted")
def writeStdin(self, data):
self.command.writeStdin(data)
def closeStdin(self):
self.command.closeStdin()
| 2,189 | Python | .py | 53 | 33.735849 | 79 | 0.660714 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
5,083 | registry.py | buildbot_buildbot/worker/buildbot_worker/commands/registry.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 buildbot_worker.commands.fs
import buildbot_worker.commands.shell
import buildbot_worker.commands.transfer
commandRegistry = {
# command name : fully qualified factory (callable)
"shell": buildbot_worker.commands.shell.WorkerShellCommand,
"uploadFile": buildbot_worker.commands.transfer.WorkerFileUploadCommand,
"upload_file": buildbot_worker.commands.transfer.WorkerFileUploadCommand,
"uploadDirectory": buildbot_worker.commands.transfer.WorkerDirectoryUploadCommand,
"upload_directory": buildbot_worker.commands.transfer.WorkerDirectoryUploadCommand,
"downloadFile": buildbot_worker.commands.transfer.WorkerFileDownloadCommand,
"download_file": buildbot_worker.commands.transfer.WorkerFileDownloadCommand,
"mkdir": buildbot_worker.commands.fs.MakeDirectory,
"rmdir": buildbot_worker.commands.fs.RemoveDirectory,
"cpdir": buildbot_worker.commands.fs.CopyDirectory,
"stat": buildbot_worker.commands.fs.StatFile,
"glob": buildbot_worker.commands.fs.GlobPath,
"listdir": buildbot_worker.commands.fs.ListDir,
"rmfile": buildbot_worker.commands.fs.RemoveFile,
}
def getFactory(command):
factory = commandRegistry[command]
return factory
def getAllCommandNames():
return list(commandRegistry)
| 1,978 | Python | .py | 39 | 47.717949 | 87 | 0.797206 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
5,084 | buffer_manager.py | buildbot_buildbot/worker/buildbot_worker/util/buffer_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
class BufferManager:
def __init__(self, reactor, message_consumer, buffer_size, buffer_timeout):
self._reactor = reactor
self._buflen = 0
self._buffered = []
self._buffer_size = buffer_size
self._buffer_timeout = buffer_timeout
self._send_message_timer = None
self._message_consumer = message_consumer
def join_line_info(self, previous_line_info, new_line_info):
previous_line_text = previous_line_info[0]
len_previous_line_text = len(previous_line_text)
new_line_text = previous_line_text + new_line_info[0]
new_line_indexes = previous_line_info[1]
for index in new_line_info[1]:
new_line_indexes.append(len_previous_line_text + index)
new_time_indexes = previous_line_info[2]
for time in new_line_info[2]:
new_time_indexes.append(time)
return (new_line_text, new_line_indexes, new_time_indexes)
def buffered_append_maybe_join_lines(self, logname, msg_data):
# if logname is the same as before: join message's line information with previous one
if len(self._buffered) > 0 and self._buffered[-1][0] == logname:
# different data format, when logname is 'log'
# compare a log of first element of the data
# second element is information about line
# e.g. data = ('test_log', ('hello\n', [5], [0.0]))
udpate_output = self._buffered[-1][1]
if logname == "log":
if udpate_output[0] == msg_data[0]:
joined_line_info = self.join_line_info(udpate_output[1], msg_data[1])
self._buffered[-1] = (logname, (msg_data[0], joined_line_info))
return
else:
joined_line_info = self.join_line_info(udpate_output, msg_data)
self._buffered[-1] = (logname, joined_line_info)
return
self._buffered.append((logname, msg_data))
def setup_timeout(self):
if not self._send_message_timer:
self._send_message_timer = self._reactor.callLater(
self._buffer_timeout, self.send_message_from_buffer
)
def append(self, logname, data):
# add data to the buffer for logname
# keep appending to self._buffered until it gets longer than BUFFER_SIZE
# which requires emptying the buffer by sending the message to the master
is_log_message = logname in ("log", "stdout", "stderr", "header")
if not is_log_message:
len_data = 20
else:
if logname == "log":
# different data format, when logname is 'log'
# e.g. data = ('test_log', ('hello\n', [5], [0.0]))
len_data = len(data[1][0]) + 8 * (len(data[1][1]) + len(data[1][2]))
else:
len_data = len(data[0]) + 8 * (len(data[1]) + len(data[2]))
space_left = self._buffer_size - self._buflen
if len_data <= space_left:
# fills the buffer with short lines
if not is_log_message:
self._buffered.append((logname, data))
else:
self.buffered_append_maybe_join_lines(logname, data)
self._buflen += len_data
self.setup_timeout()
return
self.send_message_from_buffer()
if len_data <= self._buffer_size:
self._buffered.append((logname, data))
self._buflen += len_data
self.setup_timeout()
return
if not is_log_message:
self.send_message([(logname, data)])
return
if logname == "log":
log = data[0]
data = data[1]
pos_start = 0
while pos_start < len(data[1]):
# pos_end: which line is the last to be sent as a message (non-inclusive range)
pos_end = pos_start + 1
# Finds the range of lines to be sent:
# pos_start - inclusive index of first line to be sent
# pos_end - exclusive index of last line to be sent
while pos_end <= len(data[1]):
if pos_start == 0:
string_part_size = data[1][pos_end - 1] + 1
else:
string_part_size = data[1][pos_end - 1] - (data[1][pos_start - 1])
index_list_part_size = (pos_end - pos_start) * 8
times_list_part_size = (pos_end - pos_start) * 8
line_size = string_part_size + index_list_part_size + times_list_part_size
if line_size <= self._buffer_size:
pos_end += 1
else:
if pos_end > pos_start + 1:
pos_end -= 1
break
if pos_end > len(data[1]):
# no more lines are left to grab
pos_end -= 1
pos_substring_end = data[1][pos_end - 1] + 1
if pos_start != 0:
pos_substring_start = data[1][pos_start - 1] + 1
line_info = (
data[0][pos_substring_start:pos_substring_end],
[index - pos_substring_start for index in data[1][pos_start:pos_end]],
data[2][pos_start:pos_end],
)
else:
line_info = (data[0][:pos_substring_end], data[1][:pos_end], data[2][:pos_end])
if logname == "log":
msg_data = (log, line_info)
else:
msg_data = line_info
self.send_message([(logname, msg_data)])
pos_start = pos_end
def send_message_from_buffer(self):
self.send_message(self._buffered)
self._buffered = []
self._buflen = 0
if self._send_message_timer:
if self._send_message_timer.active():
self._send_message_timer.cancel()
self._send_message_timer = None
def send_message(self, data_to_send):
if len(data_to_send) == 0:
return
self._message_consumer(data_to_send)
def flush(self):
if len(self._buffered) > 0:
self.send_message_from_buffer()
| 6,954 | Python | .py | 148 | 35.121622 | 95 | 0.562998 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
5,085 | lineboundaries.py | buildbot_buildbot/worker/buildbot_worker/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__ = ['max_line_length', 'newline_re', 'partial_line', 'warned', 'time']
def __init__(self, max_line_length, newline_re):
# split at reasonable line length.
# too big lines will fill master's memory, and slow down the UI too much.
self.max_line_length = max_line_length
self.newline_re = re.compile(newline_re)
self.partial_line = ""
self.warned = False
self.time = None
def append(self, text, time):
# returns a tuple containing three elements:
# - text: string containing one or more lines
# - lf_positions: newline position in returned string
# - line times: times when first line symbol was received
had_partial_line = False
time_partial_line = None
if self.partial_line:
had_partial_line = True
text = self.partial_line + text
time_partial_line = self.time
text = self.newline_re.sub('\n', text)
lf_positions = self.get_lf_positions(text)
ret_lines = [] # lines with appropriate number of symbols and their separators \n
ret_indexes = [] # ret_indexes is a list of '\n' symbols
ret_text_length = -1
ret_line_count = 0
first_position = 0
for position in lf_positions:
# finds too long lines and splits them, each element in ret_lines will be a line of
# appropriate length
while position - first_position >= self.max_line_length:
line = text[first_position : self.max_line_length - 1] + '\n'
ret_lines.append(line)
ret_line_count += 1
ret_text_length = ret_text_length + len(line)
ret_indexes.append(ret_text_length)
first_position = first_position + self.max_line_length
line = text[first_position : (position + 1)]
ret_lines.append(line)
ret_line_count += 1
ret_text_length = ret_text_length + len(line)
ret_indexes.append(ret_text_length)
first_position = position + 1
position = len(text)
while position - first_position >= self.max_line_length:
line = text[first_position : self.max_line_length - 1] + '\n'
ret_lines.append(line)
ret_text_length = ret_text_length + len(line)
ret_indexes.append(ret_text_length)
first_position = first_position + self.max_line_length - 1
if had_partial_line:
times = []
if ret_line_count > 1:
times = [time] * (ret_line_count - 1)
line_times = [time_partial_line, *times]
else:
line_times = ret_line_count * [time]
ret_text = "".join(ret_lines)
if ret_text != '' or not had_partial_line:
self.time = time
self.partial_line = text[first_position:position]
if ret_text == '':
return None
return (ret_text, ret_indexes, line_times)
def get_lf_positions(self, text):
lf_position = 0
lf_positions = []
while lf_position != -1:
lf_position = text.find('\n', lf_position)
if lf_position < 0:
break
lf_positions.append(lf_position)
lf_position = lf_position + 1
return lf_positions
def flush(self):
if self.partial_line != "":
return self.append('\n', self.time)
return None
| 4,310 | Python | .py | 96 | 35.541667 | 95 | 0.613073 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
5,086 | _hangcheck.py | buildbot_buildbot/worker/buildbot_worker/util/_hangcheck.py | """
Protocol wrapper that will detect hung connections.
In particular, since PB expects the server to talk first and HTTP
expects the client to talk first, when a PB client talks to an HTTP
server, neither side will talk, leading to a hung connection. This
wrapper will disconnect in that case, and inform the caller.
"""
from twisted.internet.interfaces import IProtocol
from twisted.internet.interfaces import IProtocolFactory
from twisted.python.components import proxyForInterface
def _noop():
pass
class HangCheckProtocol(
proxyForInterface(IProtocol, '_wrapped_protocol'), # type: ignore[misc]
):
"""
Wrap a protocol, so the underlying connection will disconnect if
the other end doesn't send data within a given timeout.
"""
transport = None
_hungConnectionTimer = None
# hung connections wait for a relatively long time, since a busy master may
# take a while to get back to us.
_HUNG_CONNECTION_TIMEOUT = 120
def __init__(self, wrapped_protocol, hung_callback=_noop, reactor=None):
"""
:param IProtocol wrapped_protocol: The protocol to wrap.
:param hung_callback: Called when the connection has hung.
:type hung_callback: callable taking no arguments.
:param IReactorTime reactor: The reactor to use to schedule
the hang check.
"""
if reactor is None:
from twisted.internet import reactor
self._wrapped_protocol = wrapped_protocol
self._reactor = reactor
self._hung_callback = hung_callback
def makeConnection(self, transport):
# Note that we don't wrap the transport for the protocol,
# because we only care about noticing data received, not
# sent.
self.transport = transport
super().makeConnection(transport)
self._startHungConnectionTimer()
def dataReceived(self, data):
self._stopHungConnectionTimer()
super().dataReceived(data)
def connectionLost(self, reason):
self._stopHungConnectionTimer()
super().connectionLost(reason)
def _startHungConnectionTimer(self):
"""
Start a timer to detect if the connection is hung.
"""
def hungConnection():
self._hung_callback()
self._hungConnectionTimer = None
self.transport.loseConnection()
self._hungConnectionTimer = self._reactor.callLater(
self._HUNG_CONNECTION_TIMEOUT, hungConnection
)
def _stopHungConnectionTimer(self):
"""
Cancel the hang check timer, since we have received data or
been closed.
"""
if self._hungConnectionTimer:
self._hungConnectionTimer.cancel()
self._hungConnectionTimer = None
class HangCheckFactory(
proxyForInterface(IProtocolFactory, '_wrapped_factory'), # type: ignore[misc]
):
"""
Wrap a protocol factory, so the underlying connection will
disconnect if the other end doesn't send data within a given
timeout.
"""
def __init__(self, wrapped_factory, hung_callback):
"""
:param IProtocolFactory wrapped_factory: The factory to wrap.
:param hung_callback: Called when the connection has hung.
:type hung_callback: callable taking no arguments.
"""
self._wrapped_factory = wrapped_factory
self._hung_callback = hung_callback
def buildProtocol(self, addr):
protocol = self._wrapped_factory.buildProtocol(addr)
return HangCheckProtocol(protocol, hung_callback=self._hung_callback)
# This is used as a ClientFactory, which doesn't have a specific interface, so forward the
# additional methods.
def startedConnecting(self, connector):
self._wrapped_factory.startedConnecting(connector)
def clientConnectionFailed(self, connector, reason):
self._wrapped_factory.clientConnectionFailed(connector, reason)
def clientConnectionLost(self, connector, reason):
self._wrapped_factory.clientConnectionLost(connector, reason)
| 4,082 | Python | .py | 96 | 35.479167 | 94 | 0.698889 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
5,087 | __init__.py | buildbot_buildbot/worker/buildbot_worker/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
import itertools
import textwrap
import time
from ._hangcheck import HangCheckFactory
from ._notifier import Notifier
__all__ = [
"remove_userpassword",
"now",
"Obfuscated",
"rewrap",
"HangCheckFactory",
"Notifier",
]
def remove_userpassword(url):
if '@' not in url:
return url
if '://' not in url:
return url
# urlparse would've been nice, but doesn't support ssh... sigh
(protocol, repo_url) = url.split('://')
repo_url = repo_url.split('@')[-1]
return protocol + '://' + repo_url
def now(_reactor=None):
if _reactor and hasattr(_reactor, "seconds"):
return _reactor.seconds()
return time.time()
class Obfuscated:
"""An obfuscated string in a command"""
def __init__(self, real, fake):
self.real = real
self.fake = fake
def __str__(self):
return self.fake
def __repr__(self):
return repr(self.fake)
def __eq__(self, other):
return (
other.__class__ is self.__class__
and other.real == self.real
and other.fake == self.fake
)
@staticmethod
def to_text(s):
if isinstance(s, (str, bytes)):
return s
return str(s)
@staticmethod
def get_real(command):
rv = command
if isinstance(command, list):
rv = []
for elt in command:
if isinstance(elt, Obfuscated):
rv.append(elt.real)
else:
rv.append(Obfuscated.to_text(elt))
return rv
@staticmethod
def get_fake(command):
rv = command
if isinstance(command, list):
rv = []
for elt in command:
if isinstance(elt, Obfuscated):
rv.append(elt.fake)
else:
rv.append(Obfuscated.to_text(elt))
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
| 3,506 | Python | .py | 106 | 26.141509 | 87 | 0.63275 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
5,088 | _notifier.py | buildbot_buildbot/worker/buildbot_worker/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:
# this is a copy of buildbot.util.Notifier
def __init__(self):
self._waiters = []
def wait(self):
d = Deferred()
self._waiters.append(d)
return d
def notify(self, result):
waiters = self._waiters
self._waiters = []
for waiter in waiters:
waiter.callback(result)
def __bool__(self):
return bool(self._waiters)
| 1,566 | Python | .py | 36 | 39.611111 | 72 | 0.737845 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
5,089 | deferwaiter.py | buildbot_buildbot/worker/buildbot_worker/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
# this is a copy of buildbot.util.Notifier
from twisted.internet import defer
from twisted.python import failure
from twisted.python import log
from buildbot_worker.util import Notifier
class DeferWaiter:
"""This class manages a set of Deferred objects and allows waiting for their completion"""
def __init__(self):
self._waited = {}
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.pop(id(d))
if not self._waited:
self._finish_notifier.notify(None)
return result
def add(self, d):
if not isinstance(d, defer.Deferred):
return None
self._waited[id(d)] = d
d.addBoth(self._finished, d)
return d
def cancel(self):
for d in list(self._waited.values()):
d.cancel()
self._waited.clear()
def has_waited(self):
return bool(self._waited)
@defer.inlineCallbacks
def wait(self):
if not self._waited:
return
yield self._finish_notifier.wait()
| 1,918 | Python | .py | 49 | 33.387755 | 94 | 0.692888 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
5,090 | start.py | buildbot_buildbot/worker/buildbot_worker/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
import time
from buildbot_worker.scripts import base
from buildbot_worker.util import rewrap
class Follower:
def follow(self):
from twisted.internet import reactor
from buildbot_worker.scripts.logwatcher import LogWatcher
self.rc = 0
print("Following twistd.log until startup finished..")
lw = LogWatcher("twistd.log")
d = lw.start()
d.addCallbacks(self._success, self._failure)
reactor.run()
return self.rc
def _success(self, processtype):
from twisted.internet import reactor
print(f"The {processtype} appears to have (re)started correctly.")
self.rc = 0
reactor.stop()
def _failure(self, why):
from twisted.internet import reactor
from buildbot_worker.scripts.logwatcher import WorkerTimeoutError
if why.check(WorkerTimeoutError):
print(
rewrap("""\
The worker took more than 10 seconds to start and/or connect
to the buildmaster, so we were unable to confirm that it
started and connected correctly.
Please 'tail twistd.log' and look for a line that says
'message from master: attached' to verify correct startup.
If you see a bunch of messages like 'will retry in 6 seconds',
your worker might not have the correct hostname or portnumber
for the buildmaster, or the buildmaster might not be running.
If you see messages like
'Failure: twisted.cred.error.UnauthorizedLogin'
then your worker might be using the wrong botname or password.
Please correct these problems and then restart the worker.
""")
)
else:
print(
rewrap("""\
Unable to confirm that the worker started correctly.
You may need to stop it, fix the config file, and restart.
""")
)
print(why)
self.rc = 1
reactor.stop()
def startCommand(config):
basedir = config['basedir']
if not base.isWorkerDir(basedir):
return 1
return startWorker(basedir, config['quiet'], config['nodaemon'])
def startWorker(basedir, quiet, nodaemon):
"""
Start worker process.
Fork and start twisted application described in basedir buildbot.tac file.
Print it's log messages to stdout for a while and try to figure out if
start was successful.
If quiet or nodaemon parameters are True, or we are running on a win32
system, will not fork and log will not be printed to stdout.
@param basedir: worker's basedir path
@param quiet: don't display startup log messages
@param nodaemon: don't daemonize (stay in foreground)
@return: 0 if worker was successfully started,
1 if we are not sure that worker started successfully
"""
os.chdir(basedir)
if quiet or nodaemon:
return launch(nodaemon)
# we probably can't do this os.fork under windows
from twisted.python.runtime import platformType
if platformType == "win32":
return launch(nodaemon)
# fork a child to launch the daemon, while the parent process tails the
# logfile
if os.fork():
# this is the parent
rc = Follower().follow()
return rc
# this is the child: give the logfile-watching parent a chance to start
# watching it before we start the daemon
time.sleep(0.2)
launch(nodaemon)
return None
def launch(nodaemon):
sys.path.insert(0, os.path.abspath(os.getcwd()))
# see if we can launch the application without actually having to
# spawn twistd, since spawning processes correctly is a real hassle
# on windows.
from twisted.python.runtime import platformType
from twisted.scripts.twistd import run
argv = [
"twistd",
"--no_save",
"--logfile=twistd.log", # windows doesn't use the same default
"--python=buildbot.tac",
]
if nodaemon:
argv.extend(["--nodaemon"])
if platformType != 'win32':
# windows doesn't use pidfile option.
argv.extend(["--pidfile="])
sys.argv = argv
run()
| 5,038 | Python | .py | 122 | 33.47541 | 79 | 0.664484 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
5,091 | logwatcher.py | buildbot_buildbot/worker/buildbot_worker/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.protocols.basic import LineOnlyReceiver
from twisted.python.failure import Failure
from buildbot_worker.compat import unicode2bytes
class FakeTransport:
disconnecting = False
class WorkerTimeoutError(Exception):
pass
class TailProcess(protocol.ProcessProtocol):
def outReceived(self, data):
self.lw.dataReceived(unicode2bytes(data))
def errReceived(self, data):
print(f"ERR: '{data}'")
class LogWatcher(LineOnlyReceiver):
POLL_INTERVAL = 0.1
TIMEOUT_DELAY = 10.0
delimiter = unicode2bytes(os.linesep)
def __init__(self, logfile):
self.logfile = logfile
self.in_reconfig = False
self.transport = FakeTransport()
self.pp = TailProcess()
self.pp.lw = self
self.timer = None
def start(self):
# If the log file doesn't exist, create it now.
if not os.path.exists(self.logfile):
open(self.logfile, 'a').close()
# return a Deferred that fires when the start process has
# finished. It errbacks with TimeoutError if the finish line has not
# been seen within 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"
self.p = reactor.spawnProcess(
self.pp,
tailBin,
("tail", "-f", "-n", "0", self.logfile),
env=os.environ,
)
self.running = True
d = defer.maybeDeferred(self._start)
return d
def _start(self):
self.d = defer.Deferred()
self.timer = reactor.callLater(self.TIMEOUT_DELAY, self.timeout)
return self.d
def timeout(self):
self.timer = None
e = WorkerTimeoutError()
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 lineReceived(self, line):
if not self.running:
return None
if b"Log opened." in line:
self.in_reconfig = True
if b"loading configuration from" in line:
self.in_reconfig = True
if self.in_reconfig:
print(line)
if b"message from master: attached" in line:
return self.finished("buildbot-worker")
return None
| 3,741 | Python | .py | 98 | 31 | 89 | 0.661789 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
5,092 | windows_service.py | buildbot_buildbot/worker/buildbot_worker/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_worker_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_worker_windows_service --user mark --password secret \
# --startup auto install
# Alternatively, you could execute:
# % buildbot_worker_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_worker_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_worker_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:
# % buildbot_worker_windows_service 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
from contextlib import contextmanager
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 https://buildbot.net'
def __init__(self, args):
win32serviceutil.ServiceFramework.__init__(self, 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 the Handle and 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 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.winerror != 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)
@contextmanager
def GetLocalSecurityPolicyHandle(systemName, desiredAccess):
# Context manager for GetPolicyHandle
policyHandle = win32security.GetPolicyHandle(systemName, desiredAccess)
yield policyHandle
win32security.LsaClose(policyHandle)
def ConfigureLogOnAsAServicePolicy(accountName):
# Modifies LocalSecurityPolicy to allow run buildbot as specified user
# You can do it manually by running "secpol.msc"
# Open Local Policies > User Rights Assignment > Log on as a service
# Add User or Group...
#
# Args:
# accountName(str): fully qualified string in the domain_name\user_name format.
# use ".\user_name" format for local account
SE_SERVICE_LOGON_RIGHT = "SeServiceLogonRight"
try:
if "\\" not in accountName or accountName.startswith(".\\"):
computerName = os.environ['COMPUTERNAME']
if not computerName:
computerName = win32api.GetComputerName()
if not computerName:
print("error: Cannot determine computer name")
return
accountName = "{}\\{}".format(computerName, accountName.lstrip(".\\"))
account = win32security.LookupAccountName(None, accountName)
accountSid = account[0]
sid = win32security.ConvertSidToStringSid(accountSid)
except win32api.error as err:
print(f"error {err.winerror} ({err.funcname}): {err.strerror}")
return
with GetLocalSecurityPolicyHandle('', win32security.POLICY_ALL_ACCESS) as policy:
win32security.LsaAddAccountRights(policy, accountSid, [SE_SERVICE_LOGON_RIGHT])
# verify if policy was really modified
with GetLocalSecurityPolicyHandle('', win32security.POLICY_ALL_ACCESS) as policy:
try:
privileges = win32security.LsaEnumerateAccountRights(policy, accountSid)
except win32api.error as err:
# If no account rights are found or if the function fails for any other reason,
# the function returns throws winerror.ERROR_FILE_NOT_FOUND or any other
print(f"error {err.winerror} ({err.funcname}): {err.strerror}")
privileges = []
if SE_SERVICE_LOGON_RIGHT in privileges:
print(f"Account {accountName}({sid}) has granted {SE_SERVICE_LOGON_RIGHT} privilege.")
else:
print(
f"error: Account {accountName}({sid}) does not have {SE_SERVICE_LOGON_RIGHT} privilege."
)
# A custom install function.
def CustomInstall(opts):
# Register this process with the Windows Firewaall
import pythoncom
try:
RegisterWithFirewall(sys.executable, "BuildBot")
except pythoncom.com_error as why:
print("FAILED to register with the Windows firewall")
print(why)
userName = None
for opt, val in opts:
if opt == '--username':
userName = val
ConfigureLogOnAsAServicePolicy(userName)
# 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/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 buildbot worker or a master and
returns the appropriate run function."""
try:
import buildbot_worker.scripts.runner
tacfile = os.path.join(bbdir, 'buildbot.tac')
if os.path.exists(tacfile):
with open(tacfile) as f:
contents = f.read()
if 'import Worker' in contents:
return buildbot_worker.scripts.runner.run
except ImportError:
# Use the default
pass
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()
| 24,257 | Python | .py | 517 | 38.518375 | 104 | 0.659362 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
5,093 | runner.py | buildbot_buildbot/worker/buildbot_worker/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.
from __future__ import annotations
import os
import re
import sys
import textwrap
from twisted.python import log
from twisted.python import reflect
from twisted.python import usage
# the create/start/stop commands should all be run as the same user,
# preferably a separate 'buildbot' account.
# Note that the terms 'options' and 'config' are used interchangeably here - in
# fact, they are interchanged several times. Caveat legator.
class MakerBase(usage.Options):
optFlags: list[list[str | None]] = [
['help', 'h', "Display this message"],
["quiet", "q", "Do not emit the commands being run"],
]
longdesc = textwrap.dedent("""
Operates upon the specified <basedir> (or the current directory, if not
specified).
""")
# 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="worker base directory")]
)
opt_h = usage.Options.opt_help
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):
self['basedir'] = os.path.abspath(self['basedir'])
class StartOptions(MakerBase):
subcommandFunction = "buildbot_worker.scripts.start.startCommand"
optFlags = [
['quiet', 'q', "Don't display startup log messages"],
['nodaemon', None, "Don't daemonize (stay in foreground)"],
]
def getSynopsis(self):
return "Usage: buildbot-worker start [<basedir>]"
class StopOptions(MakerBase):
subcommandFunction = "buildbot_worker.scripts.stop.stop"
def getSynopsis(self):
return "Usage: buildbot-worker stop [<basedir>]"
class RestartOptions(MakerBase):
subcommandFunction = "buildbot_worker.scripts.restart.restart"
optFlags = [
['quiet', 'q', "Don't display startup log messages"],
['nodaemon', None, "Don't daemonize (stay in foreground)"],
]
def getSynopsis(self):
return "Usage: buildbot-worker restart [<basedir>]"
class CreateWorkerOptions(MakerBase):
subcommandFunction = "buildbot_worker.scripts.create_worker.createWorker"
optFlags = [
["force", "f", "Re-use an existing directory"],
["relocatable", "r", "Create a relocatable buildbot.tac"],
["no-logrotate", "n", "Do not permit buildmaster rotate logs by itself"],
['use-tls', None, "Uses TLS to connect to master"],
[
'delete-leftover-dirs',
None,
'Delete folders that are not required by the master on connection',
],
]
optParameters = [
["keepalive", "k", 600, "Interval at which keepalives should be sent (in seconds)"],
[
"umask",
None,
"None",
"controls permissions of generated files. Use --umask=0o22 to be world-readable",
],
["maxdelay", None, 300, "Maximum time between connection attempts"],
["maxretries", None, 'None', "Maximum number of retries before worker shutdown"],
["numcpus", None, "None", "Number of available cpus to use on a build. "],
["log-size", "s", "10000000", "size at which to rotate twisted log files"],
[
"log-count",
"l",
"10",
"limit the number of kept old twisted log files (None for unlimited)",
],
[
"allow-shutdown",
"a",
None,
"Allows the worker to initiate a graceful shutdown. One of 'signal' or 'file'",
],
["protocol", None, "pb", "Protocol to be used when creating master-worker connection"],
[
"connection-string",
None,
None,
"Twisted endpoint connection string (this will override master host[:port])",
],
["proxy-connection-string", None, None, "Address of HTTP proxy to tunnel through"],
]
longdesc = textwrap.dedent("""
This command creates a buildbot worker directory and buildbot.tac
file. The bot will use the <name> and <passwd> arguments to authenticate
itself when connecting to the master. All commands are run in a
build-specific subdirectory of <basedir>. <master> is a string of the
form 'hostname[:port]', and specifies where the buildmaster can be reached.
port defaults to 9989.
The appropriate values for <name>, <passwd>, and <master> should be
provided to you by the buildmaster administrator. You must choose <basedir>
yourself.
""")
def validateMasterArgument(self, master_arg):
"""
Parse the <master> argument.
@param master_arg: the <master> argument to parse
@return: tuple of master's host and port
@raise UsageError: on errors parsing the argument
"""
if master_arg[:5] == "http:":
raise usage.UsageError("<master> is not a URL - do not use URL")
if master_arg.startswith("[") and "]" in master_arg:
# detect ipv6 address with format [2001:1:2:3:4::1]:4321
master, port_tmp = master_arg.split("]")
master = master[1:]
if ":" not in port_tmp:
port = 9989
else:
port = port_tmp.split(":")[1]
elif ":" not in master_arg:
master = master_arg
port = 9989
else:
try:
master, port = master_arg.split(":")
except ValueError as e:
raise usage.UsageError(
f"invalid <master> argument '{master_arg}', "
"if it is an ipv6 address, it must be enclosed by []"
) from e
if not master:
raise usage.UsageError(f"invalid <master> argument '{master_arg}'")
try:
port = int(port)
except ValueError as e:
raise usage.UsageError(f"invalid master port '{port}', needs to be a number") from e
return master, port
def getSynopsis(self):
return (
"Usage: buildbot-worker create-worker "
"[options] <basedir> <master> <name> <passwd>"
)
def parseArgs(self, *args):
if len(args) != 4:
raise usage.UsageError("incorrect number of arguments")
basedir, master, name, passwd = args
self['basedir'] = basedir
self['host'], self['port'] = self.validateMasterArgument(master)
self['name'] = name
self['passwd'] = passwd
def postOptions(self):
MakerBase.postOptions(self)
# check and convert numeric parameters
for argument in ["keepalive", "maxdelay", "log-size"]:
try:
self[argument] = int(self[argument])
except ValueError as e:
raise usage.UsageError(f"{argument} parameter needs to be a number") from e
for argument in ["log-count", "maxretries", "umask", "numcpus"]:
if not re.match(r'^((0o)\d+|0|[1-9]\d*)$', self[argument]) and self[argument] != 'None':
raise usage.UsageError(f"{argument} parameter needs to be a number or None")
if self['allow-shutdown'] not in [None, 'signal', 'file']:
raise usage.UsageError("allow-shutdown needs to be one of 'signal' or 'file'")
class Options(usage.Options):
synopsis = "Usage: buildbot-worker <command> [command options]"
subCommands = [
# the following are all admin commands
[
'create-worker',
None,
CreateWorkerOptions,
"Create and populate a directory for a new worker",
],
['start', None, StartOptions, "Start a worker"],
['stop', None, StopOptions, "Stop a worker"],
['restart', None, RestartOptions, "Restart a worker"],
]
def opt_version(self):
import buildbot_worker # pylint: disable=import-outside-toplevel
print(f"worker version: {buildbot_worker.version}")
usage.Options.opt_version(self)
def opt_verbose(self):
log.startLogging(sys.stderr)
def postOptions(self):
if not hasattr(self, 'subOptions'):
raise usage.UsageError("must specify a command")
def run():
config = Options()
try:
config.parseOptions()
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))
| 9,857 | Python | .py | 229 | 34.737991 | 100 | 0.627414 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
5,094 | base.py | buildbot_buildbot/worker/buildbot_worker/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
# This module is left for backward compatibility of old-named worker API.
# It should never be imported by Buildbot.
import os
def isWorkerDir(dir):
def print_error(error_message):
print(f"{error_message}\ninvalid worker directory '{dir}'")
buildbot_tac = os.path.join(dir, "buildbot.tac")
try:
with open(buildbot_tac) as f:
contents = f.read()
except OSError as exception:
print_error(f"error reading '{buildbot_tac}': {exception.strerror}")
return False
if "Application('buildbot-worker')" not in contents:
print_error(f"unexpected content in '{buildbot_tac}'")
return False
return True
| 1,385 | Python | .py | 31 | 40.741935 | 79 | 0.736451 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
5,095 | restart.py | buildbot_buildbot/worker/buildbot_worker/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
# This module is left for backward compatibility of old-named worker API.
# It should never be imported by Buildbot.
from buildbot_worker.scripts import base
from buildbot_worker.scripts import start
from buildbot_worker.scripts import stop
def restart(config):
quiet = config['quiet']
basedir = config['basedir']
if not base.isWorkerDir(basedir):
return 1
try:
stop.stopWorker(basedir, quiet)
except stop.WorkerNotRunning:
if not quiet:
print("no old worker process found to stop")
if not quiet:
print("now restarting worker process..")
return start.startWorker(basedir, quiet, config['nodaemon'])
| 1,383 | Python | .py | 32 | 39.75 | 79 | 0.756696 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
5,096 | create_worker.py | buildbot_buildbot/worker/buildbot_worker/scripts/create_worker.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
workerTACTemplate = [
"""
import os
from buildbot_worker.bot import Worker
from twisted.application import service
basedir = %(basedir)r
rotateLength = %(log-size)d
maxRotatedFiles = %(log-count)s
# if this is a relocatable tac file, get the directory containing the TAC
if basedir == '.':
import os.path
basedir = os.path.abspath(os.path.dirname(__file__))
# note: this line is matched against to check that this is a worker
# directory; do not edit it.
application = service.Application('buildbot-worker')
""",
"""
from twisted.python.logfile import LogFile
from twisted.python.log import ILogObserver, FileLogObserver
logfile = LogFile.fromFullPath(
os.path.join(basedir, "twistd.log"), rotateLength=rotateLength,
maxRotatedFiles=maxRotatedFiles)
application.setComponent(ILogObserver, FileLogObserver(logfile).emit)
""",
"""
buildmaster_host = %(host)r
port = %(port)d
connection_string = None
""",
"""
buildmaster_host = None # %(host)r
port = None # %(port)d
connection_string = %(connection-string)r
""",
"""
workername = %(name)r
passwd = %(passwd)r
keepalive = %(keepalive)d
umask = %(umask)s
maxdelay = %(maxdelay)d
numcpus = %(numcpus)s
allow_shutdown = %(allow-shutdown)r
maxretries = %(maxretries)s
use_tls = %(use-tls)s
delete_leftover_dirs = %(delete-leftover-dirs)s
proxy_connection_string = %(proxy-connection-string)r
protocol = %(protocol)r
s = Worker(buildmaster_host, port, workername, passwd, basedir,
keepalive, umask=umask, maxdelay=maxdelay,
numcpus=numcpus, allow_shutdown=allow_shutdown,
maxRetries=maxretries, protocol=protocol, useTls=use_tls,
delete_leftover_dirs=delete_leftover_dirs,
connection_string=connection_string,
proxy_connection_string=proxy_connection_string)
s.setServiceParent(application)
""",
]
class CreateWorkerError(Exception):
"""
Raised on errors while setting up worker directory.
"""
def _make_tac(config):
if config['relocatable']:
config['basedir'] = '.'
workerTAC = [workerTACTemplate[0]]
if not config['no-logrotate']:
workerTAC.append(workerTACTemplate[1])
if not config['connection-string']:
workerTAC.append(workerTACTemplate[2])
else:
workerTAC.append(workerTACTemplate[3])
workerTAC.extend(workerTACTemplate[4:])
return "".join(workerTAC) % config
def _makeBaseDir(basedir, quiet):
"""
Make worker base directory if needed.
@param basedir: worker base directory relative path
@param quiet: if True, don't print info messages
@raise CreateWorkerError: on error making base directory
"""
if os.path.exists(basedir):
if not quiet:
print("updating existing installation")
return
if not quiet:
print("mkdir", basedir)
try:
os.mkdir(basedir)
except OSError as exception:
raise CreateWorkerError(f"error creating directory {basedir}") from exception
def _makeBuildbotTac(basedir, tac_file_contents, quiet):
"""
Create buildbot.tac file. If buildbot.tac file already exists with
different contents, create buildbot.tac.new instead.
@param basedir: worker base directory relative path
@param tac_file_contents: contents of buildbot.tac file to write
@param quiet: if True, don't print info messages
@raise CreateWorkerError: on error reading or writing tac file
"""
tacfile = os.path.join(basedir, "buildbot.tac")
if os.path.exists(tacfile):
try:
with open(tacfile) as f:
oldcontents = f.read()
except OSError as exception:
raise CreateWorkerError(f"error reading {tacfile}") from exception
if oldcontents == tac_file_contents:
if not quiet:
print("buildbot.tac already exists and is correct")
return
if not quiet:
print("not touching existing buildbot.tac")
print("creating buildbot.tac.new instead")
tacfile = os.path.join(basedir, "buildbot.tac.new")
try:
with open(tacfile, "w") as f:
f.write(tac_file_contents)
os.chmod(tacfile, 0o600)
except OSError as exception:
raise CreateWorkerError(f"could not write {tacfile}") from exception
def _makeInfoFiles(basedir, quiet):
"""
Create info/* files inside basedir.
@param basedir: worker base directory relative path
@param quiet: if True, don't print info messages
@raise CreateWorkerError: on error making info directory or
writing info files
"""
def createFile(path, file, contents):
filepath = os.path.join(path, file)
if os.path.exists(filepath):
return False
if not quiet:
print(
"Creating {}, you need to edit it appropriately.".format(os.path.join("info", file))
)
try:
open(filepath, "w").write(contents)
except OSError as exception:
raise CreateWorkerError(f"could not write {filepath}") from exception
return True
path = os.path.join(basedir, "info")
if not os.path.exists(path):
if not quiet:
print("mkdir", path)
try:
os.mkdir(path)
except OSError as exception:
raise CreateWorkerError(f"error creating directory {path}") from exception
# create 'info/admin' file
created = createFile(path, "admin", "Your Name Here <[email protected]>\n")
# create 'info/host' file
created = createFile(path, "host", "Please put a description of this build host here\n")
access_uri = os.path.join(path, "access_uri")
if not os.path.exists(access_uri):
if not quiet:
print("Not creating {} - add it if you wish".format(os.path.join("info", "access_uri")))
if created and not quiet:
print(f"Please edit the files in {path} appropriately.")
def createWorker(config):
basedir = config['basedir']
quiet = config['quiet']
contents = _make_tac(config)
try:
_makeBaseDir(basedir, quiet)
_makeBuildbotTac(basedir, contents, quiet)
_makeInfoFiles(basedir, quiet)
except CreateWorkerError as exception:
print("{}\nfailed to configure worker in {}".format(exception, config['basedir']))
return 1
if not quiet:
print(f"worker configured in {basedir}")
return 0
| 7,203 | Python | .py | 188 | 32.388298 | 100 | 0.686818 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
5,097 | stop.py | buildbot_buildbot/worker/buildbot_worker/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 os
import signal
import time
from buildbot_worker.scripts import base
class WorkerNotRunning(Exception):
"""
raised when trying to stop worker process that is not running
"""
def stopWorker(basedir, quiet, signame="TERM"):
"""
Stop worker process by sending it a signal.
Using the specified basedir path, read worker process's pid file and
try to terminate that process with specified signal.
@param basedir: worker's basedir path
@param quite: if False, don't print any messages to stdout
@param signame: signal to send to the worker process
@raise WorkerNotRunning: if worker pid file is not found
"""
os.chdir(basedir)
try:
f = open("twistd.pid")
except OSError as e:
raise WorkerNotRunning() from e
pid = int(f.read().strip())
signum = getattr(signal, "SIG" + signame)
timer = 0
try:
os.kill(pid, signum)
except OSError as e:
if e.errno != 3:
raise
time.sleep(0.1)
while timer < 10:
# poll once per second until twistd.pid goes away, up to 10 seconds
try:
os.kill(pid, 0)
except OSError:
if not quiet:
print(f"worker process {pid} is dead")
return 0
timer += 1
time.sleep(1)
if not quiet:
print("never saw process go away")
return 1
def stop(config, signame="TERM"):
quiet = config['quiet']
basedir = config['basedir']
if not base.isWorkerDir(basedir):
return 1
try:
return stopWorker(basedir, quiet, signame)
except WorkerNotRunning:
if not quiet:
print("worker not running")
return 0
| 2,424 | Python | .py | 70 | 29.057143 | 79 | 0.681779 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
5,098 | test_python_twisted.py | buildbot_buildbot/master/buildbot/test/unit/steps/test_python_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
import textwrap
from twisted.internet import defer
from twisted.trial import unittest
from buildbot.process.properties import Property
from buildbot.process.results import FAILURE
from buildbot.process.results import SKIPPED
from buildbot.process.results import SUCCESS
from buildbot.process.results import WARNINGS
from buildbot.steps import python_twisted
from buildbot.test.reactor import TestReactorMixin
from buildbot.test.steps import ExpectShell
from buildbot.test.steps import TestBuildStepMixin
failureLog = """\
buildbot.test.unit.test_steps_python_twisted.Trial.testProperties ... [FAILURE]
buildbot.test.unit.test_steps_python_twisted.Trial.test_run_env ... [FAILURE]
buildbot.test.unit.test_steps_python_twisted.Trial.test_run_env_nodupe ... [FAILURE]/home/dustin/code/buildbot/t/buildbot/master/buildbot/test/fake/logfile.py:92: UserWarning: step uses removed LogFile method `getText`
buildbot.test.unit.test_steps_python_twisted.Trial.test_run_env_supplement ... [FAILURE]/home/dustin/code/buildbot/t/buildbot/master/buildbot/test/fake/logfile.py:92: UserWarning: step uses removed LogFile method `getText`
buildbot.test.unit.test_steps_python_twisted.Trial.test_run_jobs ... [FAILURE]/home/dustin/code/buildbot/t/buildbot/master/buildbot/test/fake/logfile.py:92: UserWarning: step uses removed LogFile method `getText`
buildbot.test.unit.test_steps_python_twisted.Trial.test_run_jobsProperties ... [FAILURE]
buildbot.test.unit.test_steps_python_twisted.Trial.test_run_plural ... [FAILURE]
buildbot.test.unit.test_steps_python_twisted.Trial.test_run_singular ... [FAILURE]
===============================================================================
[FAIL]
Traceback (most recent call last):
File "/home/dustin/code/buildbot/t/buildbot/master/buildbot/test/util/steps.py", line 244, in check
"expected step outcome")
File "/home/dustin/code/buildbot/t/buildbot/sandbox/lib/python2.7/site-packages/twisted/trial/_synctest.py", line 356, in assertEqual
% (msg, pformat(first), pformat(second)))
twisted.trial.unittest.FailTest: expected step outcome
not equal:
a = {'result': 3, 'status_text': ['2 tests', 'passed']}
b = {'result': 0, 'status_text': ['2 tests', 'passed']}
buildbot.test.unit.test_steps_python_twisted.Trial.testProperties
buildbot.test.unit.test_steps_python_twisted.Trial.test_run_plural
===============================================================================
[FAIL]
Traceback (most recent call last):
File "/home/dustin/code/buildbot/t/buildbot/master/buildbot/test/util/steps.py", line 244, in check
"expected step outcome")
File "/home/dustin/code/buildbot/t/buildbot/sandbox/lib/python2.7/site-packages/twisted/trial/_synctest.py", line 356, in assertEqual
% (msg, pformat(first), pformat(second)))
twisted.trial.unittest.FailTest: expected step outcome
not equal:
a = {'result': 3, 'status_text': ['no tests', 'run']}
b = {'result': 0, 'status_text': ['no tests', 'run']}
buildbot.test.unit.test_steps_python_twisted.Trial.test_run_env
buildbot.test.unit.test_steps_python_twisted.Trial.test_run_env_nodupe
buildbot.test.unit.test_steps_python_twisted.Trial.test_run_env_supplement
===============================================================================
[FAIL]
Traceback (most recent call last):
File "/home/dustin/code/buildbot/t/buildbot/master/buildbot/test/util/steps.py", line 244, in check
"expected step outcome")
File "/home/dustin/code/buildbot/t/buildbot/sandbox/lib/python2.7/site-packages/twisted/trial/_synctest.py", line 356, in assertEqual
% (msg, pformat(first), pformat(second)))
twisted.trial.unittest.FailTest: expected step outcome
not equal:
a = {'result': 3, 'status_text': ['1 test', 'passed']}
b = {'result': 0, 'status_text': ['1 test', 'passed']}
buildbot.test.unit.test_steps_python_twisted.Trial.test_run_jobs
buildbot.test.unit.test_steps_python_twisted.Trial.test_run_jobsProperties
buildbot.test.unit.test_steps_python_twisted.Trial.test_run_singular
-------------------------------------------------------------------------------
Ran 8 tests in 0.101s
FAILED (failures=8)
"""
class Trial(TestBuildStepMixin, TestReactorMixin, unittest.TestCase):
def setUp(self):
self.setup_test_reactor(auto_tear_down=False)
return self.setup_test_build_step()
@defer.inlineCallbacks
def tearDown(self):
yield self.tear_down_test_build_step()
yield self.tear_down_test_reactor()
def test_run_env(self):
self.setup_step(
python_twisted.Trial(
workdir='build', tests='testname', testpath=None, env={'PYTHONPATH': 'somepath'}
)
)
self.expect_commands(
ExpectShell(
workdir='build',
command=['trial', '--reporter=bwverbose', 'testname'],
logfiles={'test.log': '_trial_temp/test.log'},
env={"PYTHONPATH": 'somepath'},
)
.stdout("Ran 0 tests\n")
.exit(0)
)
self.expect_outcome(result=SUCCESS, state_string='no tests run')
return self.run_step()
def test_run_env_supplement(self):
self.setup_step(
python_twisted.Trial(
workdir='build',
tests='testname',
testpath='path1',
env={'PYTHONPATH': ['path2', 'path3']},
)
)
self.expect_commands(
ExpectShell(
workdir='build',
command=['trial', '--reporter=bwverbose', 'testname'],
logfiles={'test.log': '_trial_temp/test.log'},
env={"PYTHONPATH": ['path1', 'path2', 'path3']},
)
.stdout("Ran 0 tests\n")
.exit(0)
)
self.expect_outcome(result=SUCCESS, state_string='no tests run')
return self.run_step()
def test_run_env_nodupe(self):
self.setup_step(
python_twisted.Trial(
workdir='build',
tests='testname',
testpath='path2',
env={'PYTHONPATH': ['path1', 'path2']},
)
)
self.expect_commands(
ExpectShell(
workdir='build',
command=['trial', '--reporter=bwverbose', 'testname'],
logfiles={'test.log': '_trial_temp/test.log'},
env={"PYTHONPATH": ['path1', 'path2']},
)
.stdout("Ran 0 tests\n")
.exit(0)
)
self.expect_outcome(result=SUCCESS, state_string='no tests run')
return self.run_step()
def test_run_singular(self):
self.setup_step(python_twisted.Trial(workdir='build', tests='testname', testpath=None))
self.expect_commands(
ExpectShell(
workdir='build',
command=['trial', '--reporter=bwverbose', 'testname'],
logfiles={'test.log': '_trial_temp/test.log'},
)
.stdout("Ran 1 tests\n")
.exit(0)
)
self.expect_outcome(result=SUCCESS, state_string='1 test passed')
return self.run_step()
def test_run_plural(self):
self.setup_step(python_twisted.Trial(workdir='build', tests='testname', testpath=None))
self.expect_commands(
ExpectShell(
workdir='build',
command=['trial', '--reporter=bwverbose', 'testname'],
logfiles={'test.log': '_trial_temp/test.log'},
)
.stdout("Ran 2 tests\n")
.exit(0)
)
self.expect_outcome(result=SUCCESS, state_string='2 tests passed')
return self.run_step()
def test_run_failure(self):
self.setup_step(python_twisted.Trial(workdir='build', tests='testname', testpath=None))
self.expect_commands(
ExpectShell(
workdir='build',
command=['trial', '--reporter=bwverbose', 'testname'],
logfiles={'test.log': '_trial_temp/test.log'},
)
.stdout(failureLog)
.exit(1)
)
self.expect_outcome(result=FAILURE, state_string='tests 8 failures (failure)')
self.expect_log_file(
'problems', failureLog.split('\n\n', 1)[1][:-1] + '\nprogram finished with exit code 1'
)
self.expect_log_file(
'warnings',
textwrap.dedent("""\
buildbot.test.unit.test_steps_python_twisted.Trial.test_run_env_nodupe ... [FAILURE]/home/dustin/code/buildbot/t/buildbot/master/buildbot/test/fake/logfile.py:92: UserWarning: step uses removed LogFile method `getText`
buildbot.test.unit.test_steps_python_twisted.Trial.test_run_env_supplement ... [FAILURE]/home/dustin/code/buildbot/t/buildbot/master/buildbot/test/fake/logfile.py:92: UserWarning: step uses removed LogFile method `getText`
buildbot.test.unit.test_steps_python_twisted.Trial.test_run_jobs ... [FAILURE]/home/dustin/code/buildbot/t/buildbot/master/buildbot/test/fake/logfile.py:92: UserWarning: step uses removed LogFile method `getText`
buildbot.test.unit.test_steps_python_twisted.Trial.test_run_jobsProperties ... [FAILURE]
"""),
)
return self.run_step()
def test_renderable_properties(self):
self.setup_step(
python_twisted.Trial(workdir='build', tests=Property('test_list'), testpath=None)
)
self.build.setProperty('test_list', ['testname'], 'Test')
self.expect_commands(
ExpectShell(
workdir='build',
command=['trial', '--reporter=bwverbose', 'testname'],
logfiles={'test.log': '_trial_temp/test.log'},
)
.stdout("Ran 2 tests\n")
.exit(0)
)
self.expect_outcome(result=SUCCESS, state_string='2 tests passed')
return self.run_step()
def test_build_changed_files(self):
self.setup_build(build_files=['my/test/file.py', 'my/test/file2.py'])
self.setup_step(
python_twisted.Trial(workdir='build', testChanges=True, testpath=None),
)
self.expect_commands(
ExpectShell(
workdir='build',
command=[
'trial',
'--reporter=bwverbose',
'--testmodule=my/test/file.py',
'--testmodule=my/test/file2.py',
],
logfiles={'test.log': '_trial_temp/test.log'},
)
.stdout("Ran 2 tests\n")
.exit(0)
)
self.expect_outcome(result=SUCCESS, state_string='2 tests passed')
return self.run_step()
def test_test_path_env_python_path(self):
self.setup_step(
python_twisted.Trial(
workdir='build',
tests='testname',
testpath='custom/test/path',
env={'PYTHONPATH': '/existing/pypath'},
)
)
self.expect_commands(
ExpectShell(
workdir='build',
command=['trial', '--reporter=bwverbose', 'testname'],
logfiles={'test.log': '_trial_temp/test.log'},
env={'PYTHONPATH': ['custom/test/path', '/existing/pypath']},
)
.stdout("Ran 2 tests\n")
.exit(0)
)
self.expect_outcome(result=SUCCESS, state_string='2 tests passed')
return self.run_step()
def test_custom_reactor(self):
self.setup_step(
python_twisted.Trial(
workdir='build', reactor='customreactor', tests='testname', testpath=None
)
)
self.expect_commands(
ExpectShell(
workdir='build',
command=['trial', '--reporter=bwverbose', '--reactor=customreactor', 'testname'],
logfiles={'test.log': '_trial_temp/test.log'},
)
.stdout("Ran 2 tests\n")
.exit(0)
)
self.expect_outcome(result=SUCCESS, state_string='2 tests passed (custom)')
return self.run_step()
def test_custom_python(self):
self.setup_step(
python_twisted.Trial(
workdir='build', tests='testname', python='/bin/mypython', testpath=None
)
)
self.expect_commands(
ExpectShell(
workdir='build',
command=['/bin/mypython', 'trial', '--reporter=bwverbose', 'testname'],
logfiles={'test.log': '_trial_temp/test.log'},
)
.stdout("Ran 2 tests\n")
.exit(0)
)
self.expect_outcome(result=SUCCESS, state_string='2 tests passed')
return self.run_step()
def test_randomly(self):
self.setup_step(
python_twisted.Trial(workdir='build', randomly=True, tests='testname', testpath=None)
)
self.expect_commands(
ExpectShell(
workdir='build',
command=['trial', '--reporter=bwverbose', '--random=0', 'testname'],
logfiles={'test.log': '_trial_temp/test.log'},
)
.stdout("Ran 2 tests\n")
.exit(0)
)
self.expect_outcome(result=SUCCESS, state_string='2 tests passed')
return self.run_step()
def test_run_jobs(self):
"""
The C{jobs} kwarg should correspond to trial's -j option (
included since Twisted 12.3.0), and make corresponding changes to
logfiles.
"""
self.setup_step(
python_twisted.Trial(workdir='build', tests='testname', testpath=None, jobs=2)
)
self.expect_commands(
ExpectShell(
workdir='build',
command=['trial', '--reporter=bwverbose', '--jobs=2', 'testname'],
logfiles={
'test.0.log': '_trial_temp/0/test.log',
'err.0.log': '_trial_temp/0/err.log',
'out.0.log': '_trial_temp/0/out.log',
'test.1.log': '_trial_temp/1/test.log',
'err.1.log': '_trial_temp/1/err.log',
'out.1.log': '_trial_temp/1/out.log',
},
)
.stdout("Ran 1 tests\n")
.exit(0)
)
self.expect_outcome(result=SUCCESS, state_string='1 test passed')
return self.run_step()
def test_run_jobsProperties(self):
"""
C{jobs} should accept Properties
"""
self.setup_step(
python_twisted.Trial(
workdir='build', tests='testname', jobs=Property('jobs_count'), testpath=None
)
)
self.build.setProperty('jobs_count', '2', 'Test')
self.expect_commands(
ExpectShell(
workdir='build',
command=['trial', '--reporter=bwverbose', '--jobs=2', 'testname'],
logfiles={
'test.0.log': '_trial_temp/0/test.log',
'err.0.log': '_trial_temp/0/err.log',
'out.0.log': '_trial_temp/0/out.log',
'test.1.log': '_trial_temp/1/test.log',
'err.1.log': '_trial_temp/1/err.log',
'out.1.log': '_trial_temp/1/out.log',
},
)
.stdout("Ran 1 tests\n")
.exit(0)
)
self.expect_outcome(result=SUCCESS, state_string='1 test passed')
return self.run_step()
class HLint(TestBuildStepMixin, TestReactorMixin, unittest.TestCase):
def setUp(self):
self.setup_test_reactor(auto_tear_down=False)
return self.setup_test_build_step()
@defer.inlineCallbacks
def tearDown(self):
yield self.tear_down_test_build_step()
yield self.tear_down_test_reactor()
def test_run_ok(self):
self.setup_build(build_files=['foo.xhtml'])
self.setup_step(python_twisted.HLint(workdir='build'))
self.expect_commands(
ExpectShell(
workdir='build',
command=['bin/lore', '-p', '--output', 'lint', 'foo.xhtml'],
)
.stdout("dunno what hlint output looks like..\n")
.exit(0)
)
self.expect_log_file('files', 'foo.xhtml\n')
self.expect_outcome(result=SUCCESS, state_string='0 hlints')
return self.run_step()
def test_custom_python(self):
self.setup_build(build_files=['foo.xhtml'])
self.setup_step(python_twisted.HLint(workdir='build', python='/bin/mypython'))
self.expect_commands(
ExpectShell(
workdir='build',
command=['/bin/mypython', 'bin/lore', '-p', '--output', 'lint', 'foo.xhtml'],
).exit(0)
)
self.expect_log_file('files', 'foo.xhtml\n')
self.expect_outcome(result=SUCCESS, state_string='0 hlints')
return self.run_step()
def test_command_failure(self):
self.setup_build(build_files=['foo.xhtml'])
self.setup_step(python_twisted.HLint(workdir='build'))
self.expect_commands(
ExpectShell(
workdir='build',
command=['bin/lore', '-p', '--output', 'lint', 'foo.xhtml'],
).exit(1)
)
self.expect_log_file('files', 'foo.xhtml\n')
self.expect_outcome(result=FAILURE, state_string='hlint (failure)')
return self.run_step()
def test_no_build_files(self):
self.setup_step(python_twisted.HLint(workdir='build'))
self.expect_outcome(result=SKIPPED, state_string='hlint (skipped)')
return self.run_step()
def test_run_warnings(self):
self.setup_build(build_files=['foo.xhtml'])
self.setup_step(python_twisted.HLint(workdir='build'))
self.expect_commands(
ExpectShell(
workdir='build', command=['bin/lore', '-p', '--output', 'lint', 'foo.xhtml']
)
.stdout("colon: meaning warning\n")
.exit(0)
)
self.expect_log_file('warnings', 'colon: meaning warning')
self.expect_outcome(result=WARNINGS, state_string='1 hlint (warnings)')
return self.run_step()
class RemovePYCs(TestBuildStepMixin, TestReactorMixin, unittest.TestCase):
def setUp(self):
self.setup_test_reactor(auto_tear_down=False)
return self.setup_test_build_step()
@defer.inlineCallbacks
def tearDown(self):
yield self.tear_down_test_build_step()
yield self.tear_down_test_reactor()
def test_run_ok(self):
self.setup_step(python_twisted.RemovePYCs())
self.expect_commands(
ExpectShell(
workdir='wkdir',
command=['find', '.', '-name', '\'*.pyc\'', '-exec', 'rm', '{}', ';'],
).exit(0)
)
self.expect_outcome(result=SUCCESS, state_string='remove .pycs')
return self.run_step()
| 19,764 | Python | .pyt | 442 | 34.599548 | 238 | 0.5901 | buildbot/buildbot | 5,232 | 1,616 | 728 | GPL-2.0 | 9/5/2024, 5:09:21 PM (Europe/Amsterdam) |
5,099 | test_python.py | buildbot_buildbot/master/buildbot/test/unit/steps/test_python.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 parameterized import parameterized
from twisted.internet import defer
from twisted.trial import unittest
from buildbot import config
from buildbot.process.results import FAILURE
from buildbot.process.results import SUCCESS
from buildbot.process.results import WARNINGS
from buildbot.steps import python
from buildbot.test.reactor import TestReactorMixin
from buildbot.test.steps import ExpectShell
from buildbot.test.steps import TestBuildStepMixin
log_output_success = """\
Making output directory...
Running Sphinx v1.0.7
loading pickled environment... not yet created
No builder selected, using default: html
building [html]: targets for 24 source files that are out of date
updating environment: 24 added, 0 changed, 0 removed
reading sources... [ 4%] index
reading sources... [ 8%] manual/cfg-builders
...
copying static files... done
dumping search index... done
dumping object inventory... done
build succeeded.
"""
log_output_nochange = """\
Running Sphinx v1.0.7
loading pickled environment... done
No builder selected, using default: html
building [html]: targets for 0 source files that are out of date
updating environment: 0 added, 0 changed, 0 removed
looking for now-outdated files... none found
no targets are out of date.
"""
log_output_warnings = """\
Running Sphinx v1.0.7
loading pickled environment... done
building [html]: targets for 1 source files that are out of date
updating environment: 0 added, 1 changed, 0 removed
reading sources... [100%] file
file.rst:18: (WARNING/2) Literal block expected; none found.
looking for now-outdated files... none found
pickling environment... done
checking consistency... done
preparing documents... done
writing output... [ 50%] index
writing output... [100%] file
index.rst:: WARNING: toctree contains reference to document 'preamble' that \
doesn't have a title: no link will be generated
writing additional files... search
copying static files... done
dumping search index... done
dumping object inventory... done
build succeeded, 2 warnings."""
log_output_warnings_strict = """\
Running Sphinx v1.0.7
loading pickled environment... done
building [html]: targets for 1 source files that are out of date
updating environment: 0 added, 1 changed, 0 removed
reading sources... [100%] file
Warning, treated as error:
file.rst:18:Literal block expected; none found.
"""
warnings = """\
file.rst:18: (WARNING/2) Literal block expected; none found.
index.rst:: WARNING: toctree contains reference to document 'preamble' that \
doesn't have a title: no link will be generated\
"""
# this is from a run of epydoc against the buildbot source..
epydoc_output = """\
[...............
+---------------------------------------------------------------------
| In /home/dustin/code/buildbot/t/buildbot/master/buildbot/
| ec2.py:
| Import failed (but source code parsing was successful).
| Error: ImportError: No module named boto (line 19)
|
[....
Warning: Unable to extract the base list for
twisted.web.resource.EncodingResourceWrapper: Bad dotted name
[......
+---------------------------------------------------------------------
| In /home/dustin/code/buildbot/t/buildbot/master/buildbot/worker/
| ec2.py:
| Import failed (but source code parsing was successful).
| Error: ImportError: No module named boto (line 28)
|
[...........
+---------------------------------------------------------------------
| In /home/dustin/code/buildbot/t/buildbot/master/buildbot/status/
| status_push.py:
| Import failed (but source code parsing was successful).
| Error: ImportError: No module named status_json (line 40)
|
[....................<paragraph>Special descriptor for class __provides__</paragraph>
"""
class BuildEPYDoc(TestBuildStepMixin, TestReactorMixin, unittest.TestCase):
def setUp(self):
self.setup_test_reactor(auto_tear_down=False)
return self.setup_test_build_step()
@defer.inlineCallbacks
def tearDown(self):
yield self.tear_down_test_build_step()
yield self.tear_down_test_reactor()
def test_sample(self):
self.setup_step(python.BuildEPYDoc())
self.expect_commands(
ExpectShell(workdir='wkdir', command=['make', 'epydocs']).stdout(epydoc_output).exit(1),
)
self.expect_outcome(result=FAILURE, state_string='epydoc warn=1 err=3 (failure)')
return self.run_step()
class PyLint(TestBuildStepMixin, TestReactorMixin, unittest.TestCase):
def setUp(self):
self.setup_test_reactor(auto_tear_down=False)
return self.setup_test_build_step()
@defer.inlineCallbacks
def tearDown(self):
yield self.tear_down_test_build_step()
yield self.tear_down_test_reactor()
@parameterized.expand([('no_results', True), ('with_results', False)])
def test_success(self, name, store_results):
self.setup_step(python.PyLint(command=['pylint'], store_results=store_results))
self.expect_commands(
ExpectShell(workdir='wkdir', command=['pylint'])
.stdout('Your code has been rated at 10/10')
.exit(python.PyLint.RC_OK)
)
self.expect_outcome(result=SUCCESS, state_string='pylint')
if store_results:
self.expect_test_result_sets([('Pylint warnings', 'code_issue', 'message')])
self.expect_test_results([])
return self.run_step()
@parameterized.expand([('no_results', True), ('with_results', False)])
def test_error(self, name, store_results):
self.setup_step(python.PyLint(command=['pylint'], store_results=store_results))
self.expect_commands(
ExpectShell(workdir='wkdir', command=['pylint'])
.stdout(
'W: 11: Bad indentation. Found 6 spaces, expected 4\n'
'E: 12: Undefined variable \'foo\'\n'
)
.exit(python.PyLint.RC_WARNING | python.PyLint.RC_ERROR)
)
self.expect_outcome(result=FAILURE, state_string='pylint error=1 warning=1 (failure)')
self.expect_property('pylint-warning', 1)
self.expect_property('pylint-error', 1)
if store_results:
self.expect_test_result_sets([('Pylint warnings', 'code_issue', 'message')])
# note that no results are submitted for tests where we don't know the location
return self.run_step()
def test_header_output(self):
self.setup_step(python.PyLint(command=['pylint'], store_results=False))
self.expect_commands(
ExpectShell(workdir='wkdir', command=['pylint'])
.log('stdio', header='W: 11: Bad indentation. Found 6 spaces, expected 4\n')
.exit(0)
)
self.expect_outcome(result=SUCCESS, state_string='pylint')
return self.run_step()
def test_failure(self):
self.setup_step(python.PyLint(command=['pylint'], store_results=False))
self.expect_commands(
ExpectShell(workdir='wkdir', command=['pylint'])
.stdout(
'W: 11: Bad indentation. Found 6 spaces, expected 4\n'
'F: 13: something really strange happened\n'
)
.exit(python.PyLint.RC_WARNING | python.PyLint.RC_FATAL)
)
self.expect_outcome(result=FAILURE, state_string='pylint fatal=1 warning=1 (failure)')
self.expect_property('pylint-warning', 1)
self.expect_property('pylint-fatal', 1)
return self.run_step()
def test_failure_zero_returncode(self):
# Make sure that errors result in a failed step when pylint's
# return code is 0, e.g. when run through a wrapper script.
self.setup_step(python.PyLint(command=['pylint'], store_results=False))
self.expect_commands(
ExpectShell(workdir='wkdir', command=['pylint'])
.stdout(
'W: 11: Bad indentation. Found 6 spaces, expected 4\n'
'E: 12: Undefined variable \'foo\'\n'
)
.exit(0)
)
self.expect_outcome(result=FAILURE, state_string='pylint error=1 warning=1 (failure)')
self.expect_property('pylint-warning', 1)
self.expect_property('pylint-error', 1)
return self.run_step()
def test_regex_text(self):
self.setup_step(python.PyLint(command=['pylint'], store_results=False))
self.expect_commands(
ExpectShell(workdir='wkdir', command=['pylint'])
.stdout(
'W: 11: Bad indentation. Found 6 spaces, expected 4\n'
'C: 1:foo123: Missing docstring\n'
)
.exit(python.PyLint.RC_WARNING | python.PyLint.RC_CONVENTION)
)
self.expect_outcome(
result=WARNINGS, state_string='pylint convention=1 warning=1 (warnings)'
)
self.expect_property('pylint-warning', 1)
self.expect_property('pylint-convention', 1)
self.expect_property('pylint-total', 2)
return self.run_step()
def test_regex_text_0_24(self):
# pylint >= 0.24.0 prints out column offsets when using text format
self.setup_step(python.PyLint(command=['pylint'], store_results=False))
self.expect_commands(
ExpectShell(workdir='wkdir', command=['pylint'])
.stdout(
'W: 11,0: Bad indentation. Found 6 spaces, expected 4\n'
'C: 3,10:foo123: Missing docstring\n'
)
.exit(python.PyLint.RC_WARNING | python.PyLint.RC_CONVENTION)
)
self.expect_outcome(
result=WARNINGS, state_string='pylint convention=1 warning=1 (warnings)'
)
self.expect_property('pylint-warning', 1)
self.expect_property('pylint-convention', 1)
self.expect_property('pylint-total', 2)
return self.run_step()
def test_regex_text_1_3_1(self):
# at least pylint 1.3.1 prints out space padded column offsets when
# using text format
self.setup_step(python.PyLint(command=['pylint'], store_results=False))
self.expect_commands(
ExpectShell(workdir='wkdir', command=['pylint'])
.stdout(
'W: 11, 0: Bad indentation. Found 6 spaces, expected 4\n'
'C: 3,10:foo123: Missing docstring\n'
)
.exit(python.PyLint.RC_WARNING | python.PyLint.RC_CONVENTION)
)
self.expect_outcome(
result=WARNINGS, state_string='pylint convention=1 warning=1 (warnings)'
)
self.expect_property('pylint-warning', 1)
self.expect_property('pylint-convention', 1)
self.expect_property('pylint-total', 2)
return self.run_step()
@parameterized.expand([('no_results', True), ('with_results', False)])
def test_regex_text_2_0_0(self, name, store_results):
# pylint 2.0.0 changed default format to include file path
self.setup_step(python.PyLint(command=['pylint'], store_results=store_results))
stdout = (
'test.py:9:4: W0311: Bad indentation. Found 6 spaces, expected 4 (bad-indentation)\n'
+ 'test.py:1:0: C0114: Missing module docstring (missing-module-docstring)\n'
)
self.expect_commands(
ExpectShell(workdir='wkdir', command=['pylint'])
.stdout(stdout)
.exit(python.PyLint.RC_WARNING | python.PyLint.RC_CONVENTION)
)
self.expect_outcome(
result=WARNINGS, state_string='pylint convention=1 warning=1 (warnings)'
)
self.expect_property('pylint-warning', 1)
self.expect_property('pylint-convention', 1)
self.expect_property('pylint-total', 2)
if store_results:
self.expect_test_result_sets([('Pylint warnings', 'code_issue', 'message')])
self.expect_test_results([
(
1000,
'test.py:9:4: W0311: Bad indentation. Found 6 spaces, expected 4 '
+ '(bad-indentation)',
None,
'test.py',
9,
None,
),
(
1000,
'test.py:1:0: C0114: Missing module docstring (missing-module-docstring)',
None,
'test.py',
1,
None,
),
])
return self.run_step()
def test_regex_text_2_0_0_invalid_line(self):
self.setup_step(python.PyLint(command=['pylint'], store_results=False))
stdout = 'test.py:abc:0: C0114: Missing module docstring (missing-module-docstring)\n'
self.expect_commands(
ExpectShell(workdir='wkdir', command=['pylint'])
.stdout(stdout)
.exit(python.PyLint.RC_CONVENTION)
)
self.expect_outcome(result=SUCCESS, state_string='pylint')
self.expect_property('pylint-warning', 0)
self.expect_property('pylint-convention', 0)
self.expect_property('pylint-total', 0)
return self.run_step()
def test_regex_text_ids(self):
self.setup_step(python.PyLint(command=['pylint'], store_results=False))
self.expect_commands(
ExpectShell(workdir='wkdir', command=['pylint'])
.stdout('W0311: 11: Bad indentation.\nC0111: 1:funcName: Missing docstring\n')
.exit(python.PyLint.RC_WARNING | python.PyLint.RC_CONVENTION)
)
self.expect_outcome(
result=WARNINGS, state_string='pylint convention=1 warning=1 (warnings)'
)
self.expect_property('pylint-warning', 1)
self.expect_property('pylint-convention', 1)
self.expect_property('pylint-total', 2)
return self.run_step()
def test_regex_text_ids_0_24(self):
# pylint >= 0.24.0 prints out column offsets when using text format
self.setup_step(python.PyLint(command=['pylint'], store_results=False))
self.expect_commands(
ExpectShell(workdir='wkdir', command=['pylint'])
.stdout('W0311: 11,0: Bad indentation.\nC0111: 3,10:foo123: Missing docstring\n')
.exit(python.PyLint.RC_WARNING | python.PyLint.RC_CONVENTION)
)
self.expect_outcome(
result=WARNINGS, state_string='pylint convention=1 warning=1 (warnings)'
)
self.expect_property('pylint-warning', 1)
self.expect_property('pylint-convention', 1)
self.expect_property('pylint-total', 2)
return self.run_step()
@parameterized.expand([('no_results', True), ('with_results', False)])
def test_regex_parseable_ids(self, name, store_results):
self.setup_step(python.PyLint(command=['pylint'], store_results=store_results))
self.expect_commands(
ExpectShell(workdir='wkdir', command=['pylint'])
.stdout(
'test.py:9: [W0311] Bad indentation.\n'
'test.py:3: [C0111, foo123] Missing docstring\n'
)
.exit(python.PyLint.RC_WARNING | python.PyLint.RC_CONVENTION)
)
self.expect_outcome(
result=WARNINGS, state_string='pylint convention=1 warning=1 (warnings)'
)
self.expect_property('pylint-warning', 1)
self.expect_property('pylint-convention', 1)
self.expect_property('pylint-total', 2)
if store_results:
self.expect_test_result_sets([('Pylint warnings', 'code_issue', 'message')])
self.expect_test_results([
(1000, 'test.py:9: [W0311] Bad indentation.', None, 'test.py', 9, None),
(1000, 'test.py:3: [C0111, foo123] Missing docstring', None, 'test.py', 3, None),
])
return self.run_step()
def test_regex_parseable(self):
self.setup_step(python.PyLint(command=['pylint'], store_results=False))
self.expect_commands(
ExpectShell(workdir='wkdir', command=['pylint'])
.stdout('test.py:9: [W] Bad indentation.\ntest.py:3: [C, foo123] Missing docstring\n')
.exit(python.PyLint.RC_WARNING | python.PyLint.RC_CONVENTION)
)
self.expect_outcome(
result=WARNINGS, state_string='pylint convention=1 warning=1 (warnings)'
)
self.expect_property('pylint-warning', 1)
self.expect_property('pylint-convention', 1)
self.expect_property('pylint-total', 2)
return self.run_step()
def test_regex_parseable_1_3_1(self):
"""In pylint 1.3.1, output parseable is deprecated, but looks like
that, this is also the new recommended format string:
--msg-template={path}:{line}: [{msg_id}({symbol}), {obj}] {msg}
"""
self.setup_step(python.PyLint(command=['pylint'], store_results=False))
self.expect_commands(
ExpectShell(workdir='wkdir', command=['pylint'])
.stdout(
'test.py:9: [W0311(bad-indentation), ] '
'Bad indentation. Found 6 '
'spaces, expected 4\n'
'test.py:3: [C0111(missing-docstring), myFunc] Missing '
'function docstring\n'
)
.exit(python.PyLint.RC_WARNING | python.PyLint.RC_CONVENTION)
)
self.expect_outcome(
result=WARNINGS, state_string='pylint convention=1 warning=1 (warnings)'
)
self.expect_property('pylint-warning', 1)
self.expect_property('pylint-convention', 1)
self.expect_property('pylint-total', 2)
return self.run_step()
class PyFlakes(TestBuildStepMixin, TestReactorMixin, unittest.TestCase):
def setUp(self):
self.setup_test_reactor(auto_tear_down=False)
return self.setup_test_build_step()
@defer.inlineCallbacks
def tearDown(self):
yield self.tear_down_test_build_step()
yield self.tear_down_test_reactor()
def test_success(self):
self.setup_step(python.PyFlakes())
self.expect_commands(ExpectShell(workdir='wkdir', command=['make', 'pyflakes']).exit(0))
self.expect_outcome(result=SUCCESS, state_string='pyflakes')
return self.run_step()
def test_content_in_header(self):
self.setup_step(python.PyFlakes())
self.expect_commands(
ExpectShell(workdir='wkdir', command=['make', 'pyflakes'])
# don't match pyflakes-like output in the header
.log('stdio', header="foo.py:1: 'bar' imported but unused\n")
.exit(0)
)
self.expect_outcome(result=0, state_string='pyflakes')
return self.run_step()
def test_unused(self):
self.setup_step(python.PyFlakes())
self.expect_commands(
ExpectShell(workdir='wkdir', command=['make', 'pyflakes'])
.stdout("foo.py:1: 'bar' imported but unused\n")
.exit(1)
)
self.expect_outcome(result=WARNINGS, state_string='pyflakes unused=1 (warnings)')
self.expect_property('pyflakes-unused', 1)
self.expect_property('pyflakes-total', 1)
return self.run_step()
def test_undefined(self):
self.setup_step(python.PyFlakes())
self.expect_commands(
ExpectShell(workdir='wkdir', command=['make', 'pyflakes'])
.stdout("foo.py:1: undefined name 'bar'\n")
.exit(1)
)
self.expect_outcome(result=FAILURE, state_string='pyflakes undefined=1 (failure)')
self.expect_property('pyflakes-undefined', 1)
self.expect_property('pyflakes-total', 1)
return self.run_step()
def test_redefs(self):
self.setup_step(python.PyFlakes())
self.expect_commands(
ExpectShell(workdir='wkdir', command=['make', 'pyflakes'])
.stdout("foo.py:2: redefinition of unused 'foo' from line 1\n")
.exit(1)
)
self.expect_outcome(result=WARNINGS, state_string='pyflakes redefs=1 (warnings)')
self.expect_property('pyflakes-redefs', 1)
self.expect_property('pyflakes-total', 1)
return self.run_step()
def test_importstar(self):
self.setup_step(python.PyFlakes())
self.expect_commands(
ExpectShell(workdir='wkdir', command=['make', 'pyflakes'])
.stdout("foo.py:1: 'from module import *' used; unable to detect undefined names\n")
.exit(1)
)
self.expect_outcome(result=WARNINGS, state_string='pyflakes import*=1 (warnings)')
self.expect_property('pyflakes-import*', 1)
self.expect_property('pyflakes-total', 1)
return self.run_step()
def test_misc(self):
self.setup_step(python.PyFlakes())
self.expect_commands(
ExpectShell(workdir='wkdir', command=['make', 'pyflakes'])
.stdout("foo.py:2: redefinition of function 'bar' from line 1\n")
.exit(1)
)
self.expect_outcome(result=WARNINGS, state_string='pyflakes misc=1 (warnings)')
self.expect_property('pyflakes-misc', 1)
self.expect_property('pyflakes-total', 1)
return self.run_step()
class TestSphinx(TestBuildStepMixin, TestReactorMixin, unittest.TestCase):
def setUp(self):
self.setup_test_reactor(auto_tear_down=False)
return self.setup_test_build_step()
@defer.inlineCallbacks
def tearDown(self):
yield self.tear_down_test_build_step()
yield self.tear_down_test_reactor()
def test_builddir_required(self):
with self.assertRaises(config.ConfigErrors):
python.Sphinx()
def test_bad_mode(self):
with self.assertRaises(config.ConfigErrors):
python.Sphinx(sphinx_builddir="_build", mode="don't care")
def test_success(self):
self.setup_step(python.Sphinx(sphinx_builddir="_build"))
self.expect_commands(
ExpectShell(workdir='wkdir', command=['sphinx-build', '.', '_build'])
.stdout(log_output_success)
.exit(0)
)
self.expect_outcome(result=SUCCESS, state_string="sphinx 0 warnings")
return self.run_step()
def test_failure(self):
self.setup_step(python.Sphinx(sphinx_builddir="_build"))
self.expect_commands(
ExpectShell(workdir='wkdir', command=['sphinx-build', '.', '_build'])
.stdout('oh noes!')
.exit(1)
)
self.expect_outcome(result=FAILURE, state_string="sphinx 0 warnings (failure)")
return self.run_step()
def test_strict_warnings(self):
self.setup_step(python.Sphinx(sphinx_builddir="_build", strict_warnings=True))
self.expect_commands(
ExpectShell(workdir='wkdir', command=['sphinx-build', '-W', '.', '_build'])
.stdout(log_output_warnings_strict)
.exit(1)
)
self.expect_outcome(result=FAILURE, state_string="sphinx 1 warnings (failure)")
return self.run_step()
def test_nochange(self):
self.setup_step(python.Sphinx(sphinx_builddir="_build"))
self.expect_commands(
ExpectShell(workdir='wkdir', command=['sphinx-build', '.', '_build'])
.stdout(log_output_nochange)
.exit(0)
)
self.expect_outcome(result=SUCCESS, state_string="sphinx 0 warnings")
return self.run_step()
@defer.inlineCallbacks
def test_warnings(self):
self.setup_step(python.Sphinx(sphinx_builddir="_build"))
self.expect_commands(
ExpectShell(workdir='wkdir', command=['sphinx-build', '.', '_build'])
.stdout(log_output_warnings)
.exit(0)
)
self.expect_outcome(result=WARNINGS, state_string="sphinx 2 warnings (warnings)")
self.expect_log_file("warnings", warnings)
yield self.run_step()
self.assertEqual(self.get_nth_step(0).statistics, {'warnings': 2})
def test_constr_args(self):
self.setup_step(
python.Sphinx(
sphinx_sourcedir='src',
sphinx_builddir="bld",
sphinx_builder='css',
sphinx="/path/to/sphinx-build",
tags=['a', 'b'],
strict_warnings=True,
defines={"empty": None, "t": True, "f": False, "s": 'str'},
mode='full',
)
)
self.expect_commands(
ExpectShell(
workdir='wkdir',
command=[
'/path/to/sphinx-build',
'-b',
'css',
'-t',
'a',
'-t',
'b',
'-D',
'empty',
'-D',
'f=0',
'-D',
's=str',
'-D',
't=1',
'-E',
'-W',
'src',
'bld',
],
)
.stdout(log_output_success)
.exit(0)
)
self.expect_outcome(result=SUCCESS, state_string="sphinx 0 warnings")
return self.run_step()
| 25,885 | Python | .pyt | 586 | 34.982935 | 100 | 0.616268 | 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.