id
int64
0
458k
file_name
stringlengths
4
119
file_path
stringlengths
14
227
content
stringlengths
24
9.96M
size
int64
24
9.96M
language
stringclasses
1 value
extension
stringclasses
14 values
total_lines
int64
1
219k
avg_line_length
float64
2.52
4.63M
max_line_length
int64
5
9.91M
alphanum_fraction
float64
0
1
repo_name
stringlengths
7
101
repo_stars
int64
100
139k
repo_forks
int64
0
26.4k
repo_open_issues
int64
0
2.27k
repo_license
stringclasses
12 values
repo_extraction_date
stringclasses
433 values
4,200
modpython.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/django/contrib/auth/handlers/modpython.py
from mod_python import apache import os def authenhandler(req, **kwargs): """ Authentication handler that checks against Django's auth database. """ # mod_python fakes the environ, and thus doesn't process SetEnv. This fixes # that so that the following import works os.environ.update(req.subprocess_env) # apache 2.2 requires a call to req.get_basic_auth_pw() before # req.user and friends are available. req.get_basic_auth_pw() # check for PythonOptions _str_to_bool = lambda s: s.lower() in ('1', 'true', 'on', 'yes') options = req.get_options() permission_name = options.get('DjangoPermissionName', None) staff_only = _str_to_bool(options.get('DjangoRequireStaffStatus', "on")) superuser_only = _str_to_bool(options.get('DjangoRequireSuperuserStatus', "off")) settings_module = options.get('DJANGO_SETTINGS_MODULE', None) if settings_module: os.environ['DJANGO_SETTINGS_MODULE'] = settings_module from django.contrib.auth.models import User from django import db db.reset_queries() # check that the username is valid kwargs = {'username': req.user, 'is_active': True} if staff_only: kwargs['is_staff'] = True if superuser_only: kwargs['is_superuser'] = True try: try: user = User.objects.get(**kwargs) except User.DoesNotExist: return apache.HTTP_UNAUTHORIZED # check the password and any permission given if user.check_password(req.get_basic_auth_pw()): if permission_name: if user.has_perm(permission_name): return apache.OK else: return apache.HTTP_UNAUTHORIZED else: return apache.OK else: return apache.HTTP_UNAUTHORIZED finally: db.connection.close()
1,899
Python
.pyt
48
31.541667
85
0.644916
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
4,201
modpython.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/django/core/handlers/modpython.py
import os from pprint import pformat from django import http from django.core import signals from django.core.handlers.base import BaseHandler from django.core.urlresolvers import set_script_prefix from django.utils import datastructures from django.utils.encoding import force_unicode, smart_str, iri_to_uri # NOTE: do *not* import settings (or any module which eventually imports # settings) until after ModPythonHandler has been called; otherwise os.environ # won't be set up correctly (with respect to settings). class ModPythonRequest(http.HttpRequest): def __init__(self, req): self._req = req # FIXME: This isn't ideal. The request URI may be encoded (it's # non-normalized) slightly differently to the "real" SCRIPT_NAME # and PATH_INFO values. This causes problems when we compute path_info, # below. For now, don't use script names that will be subject to # encoding/decoding. self.path = force_unicode(req.uri) root = req.get_options().get('django.root', '') self.django_root = root # req.path_info isn't necessarily computed correctly in all # circumstances (it's out of mod_python's control a bit), so we use # req.uri and some string manipulations to get the right value. if root and req.uri.startswith(root): self.path_info = force_unicode(req.uri[len(root):]) else: self.path_info = self.path if not self.path_info: # Django prefers empty paths to be '/', rather than '', to give us # a common start character for URL patterns. So this is a little # naughty, but also pretty harmless. self.path_info = u'/' self._post_parse_error = False def __repr__(self): # Since this is called as part of error handling, we need to be very # robust against potentially malformed input. try: get = pformat(self.GET) except: get = '<could not parse>' if self._post_parse_error: post = '<could not parse>' else: try: post = pformat(self.POST) except: post = '<could not parse>' try: cookies = pformat(self.COOKIES) except: cookies = '<could not parse>' try: meta = pformat(self.META) except: meta = '<could not parse>' return smart_str(u'<ModPythonRequest\npath:%s,\nGET:%s,\nPOST:%s,\nCOOKIES:%s,\nMETA:%s>' % (self.path, unicode(get), unicode(post), unicode(cookies), unicode(meta))) def get_full_path(self): # RFC 3986 requires self._req.args to be in the ASCII range, but this # doesn't always happen, so rather than crash, we defensively encode it. return '%s%s' % (self.path, self._req.args and ('?' + iri_to_uri(self._req.args)) or '') def is_secure(self): try: return self._req.is_https() except AttributeError: # mod_python < 3.2.10 doesn't have req.is_https(). return self._req.subprocess_env.get('HTTPS', '').lower() in ('on', '1') def _load_post_and_files(self): "Populates self._post and self._files" if self.method != 'POST': self._post, self._files = http.QueryDict('', encoding=self._encoding), datastructures.MultiValueDict() return if 'content-type' in self._req.headers_in and self._req.headers_in['content-type'].startswith('multipart'): self._raw_post_data = '' try: self._post, self._files = self.parse_file_upload(self.META, self._req) except: # See django.core.handlers.wsgi.WSGIHandler for an explanation # of what's going on here. self._post = http.QueryDict('') self._files = datastructures.MultiValueDict() self._post_parse_error = True raise else: self._post, self._files = http.QueryDict(self.raw_post_data, encoding=self._encoding), datastructures.MultiValueDict() def _get_request(self): if not hasattr(self, '_request'): self._request = datastructures.MergeDict(self.POST, self.GET) return self._request def _get_get(self): if not hasattr(self, '_get'): self._get = http.QueryDict(self._req.args, encoding=self._encoding) return self._get def _set_get(self, get): self._get = get def _get_post(self): if not hasattr(self, '_post'): self._load_post_and_files() return self._post def _set_post(self, post): self._post = post def _get_cookies(self): if not hasattr(self, '_cookies'): self._cookies = http.parse_cookie(self._req.headers_in.get('cookie', '')) return self._cookies def _set_cookies(self, cookies): self._cookies = cookies def _get_files(self): if not hasattr(self, '_files'): self._load_post_and_files() return self._files def _get_meta(self): "Lazy loader that returns self.META dictionary" if not hasattr(self, '_meta'): self._meta = { 'AUTH_TYPE': self._req.ap_auth_type, 'CONTENT_LENGTH': self._req.headers_in.get('content-length', 0), 'CONTENT_TYPE': self._req.headers_in.get('content-type'), 'GATEWAY_INTERFACE': 'CGI/1.1', 'PATH_INFO': self.path_info, 'PATH_TRANSLATED': None, # Not supported 'QUERY_STRING': self._req.args, 'REMOTE_ADDR': self._req.connection.remote_ip, 'REMOTE_HOST': None, # DNS lookups not supported 'REMOTE_IDENT': self._req.connection.remote_logname, 'REMOTE_USER': self._req.user, 'REQUEST_METHOD': self._req.method, 'SCRIPT_NAME': self.django_root, 'SERVER_NAME': self._req.server.server_hostname, 'SERVER_PORT': self._req.connection.local_addr[1], 'SERVER_PROTOCOL': self._req.protocol, 'SERVER_SOFTWARE': 'mod_python' } for key, value in self._req.headers_in.items(): key = 'HTTP_' + key.upper().replace('-', '_') self._meta[key] = value return self._meta def _get_raw_post_data(self): try: return self._raw_post_data except AttributeError: self._raw_post_data = self._req.read() return self._raw_post_data def _get_method(self): return self.META['REQUEST_METHOD'].upper() GET = property(_get_get, _set_get) POST = property(_get_post, _set_post) COOKIES = property(_get_cookies, _set_cookies) FILES = property(_get_files) META = property(_get_meta) REQUEST = property(_get_request) raw_post_data = property(_get_raw_post_data) method = property(_get_method) class ModPythonHandler(BaseHandler): request_class = ModPythonRequest def __call__(self, req): # mod_python fakes the environ, and thus doesn't process SetEnv. This fixes that os.environ.update(req.subprocess_env) # now that the environ works we can see the correct settings, so imports # that use settings now can work from django.conf import settings # if we need to set up middleware, now that settings works we can do it now. if self._request_middleware is None: self.load_middleware() set_script_prefix(req.get_options().get('django.root', '')) signals.request_started.send(sender=self.__class__) try: try: request = self.request_class(req) except UnicodeDecodeError: response = http.HttpResponseBadRequest() else: response = self.get_response(request) # Apply response middleware for middleware_method in self._response_middleware: response = middleware_method(request, response) response = self.apply_response_fixes(request, response) finally: signals.request_finished.send(sender=self.__class__) # Convert our custom HttpResponse object back into the mod_python req. req.content_type = response['Content-Type'] for key, value in response.items(): if key != 'content-type': req.headers_out[str(key)] = str(value) for c in response.cookies.values(): req.headers_out.add('Set-Cookie', c.output(header='')) req.status = response.status_code try: for chunk in response: req.write(chunk) finally: response.close() return 0 # mod_python.apache.OK def handler(req): # mod_python hooks into this function. return ModPythonHandler()(req)
9,160
Python
.pyt
199
35.442211
130
0.590797
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
4,202
selector_stacked-remove.gif
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/contrib/admin/media/img/admin/selector_stacked-remove.gif
GIF89aÕ<ÁÁÁÎÖݼ¼¼ñññ­µ½´´´±±±»»»ÝÝÝÊÊʲ»Åààà°±²îî¿®°²¹¹¹ÕÜãÀÀÀ²²²æêï²»Ä÷÷÷¾¾¾èìðùùùüýýÍÍÍÌÌ̬°µðððÒÒÒÏÏ϶¶¶âæëååå×××ÇÇÇäéíÞÞÞÃÃÃËË˯±²ÂÂÂêê과Ƴ³³ØØØ±ºÃÎÎÎÛÛÛÈÈÈÕÕÕÉÉÉ···¿¿¿¸¸¸µµµÄÄÄõøûÿÿÿ!ù<,®@ž�q<B6!0j*b±8}0L†’y¿Þ’�"TÜhhb”¦é`<Sn«“v»E½Ž ´.3�xx�37„„/� ,  :— 8¦¦x§¦9±9x²± 6¼6©;½69".7È73 3É7L :ÕÖ×XC05ÝÞÝcN9+ ):6YMBE° KMA;
401
Python
.tac
3
133
338
0.546366
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
4,203
stacked.html
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/contrib/admin/templates/admin/edit_inline/stacked.html
{% load i18n adminmedia %} <div class="inline-group" id="{{ inline_admin_formset.formset.prefix }}-group"> <h2>{{ inline_admin_formset.opts.verbose_name_plural|title }}</h2> {{ inline_admin_formset.formset.management_form }} {{ inline_admin_formset.formset.non_form_errors }} {% for inline_admin_form in inline_admin_formset %}<div class="inline-related{% if forloop.last %} empty-form last-related{% endif %}" id="{{ inline_admin_formset.formset.prefix }}-{% if not forloop.last %}{{ forloop.counter0 }}{% else %}empty{% endif %}"> <h3><b>{{ inline_admin_formset.opts.verbose_name|title }}:</b>&nbsp;<span class="inline_label">{% if inline_admin_form.original %}{{ inline_admin_form.original }}{% else %}#{{ forloop.counter }}{% endif %}</span> {% if inline_admin_form.show_url %}<a href="../../../r/{{ inline_admin_form.original_content_type_id }}/{{ inline_admin_form.original.id }}/">{% trans "View on site" %}</a>{% endif %} {% if inline_admin_formset.formset.can_delete and inline_admin_form.original %}<span class="delete">{{ inline_admin_form.deletion_field.field }} {{ inline_admin_form.deletion_field.label_tag }}</span>{% endif %} </h3> {% if inline_admin_form.form.non_field_errors %}{{ inline_admin_form.form.non_field_errors }}{% endif %} {% for fieldset in inline_admin_form %} {% include "admin/includes/fieldset.html" %} {% endfor %} {% if inline_admin_form.has_auto_field %}{{ inline_admin_form.pk_field.field }}{% endif %} {{ inline_admin_form.fk_field.field }} </div>{% endfor %} </div> <script type="text/javascript"> (function($) { $(document).ready(function() { var rows = "#{{ inline_admin_formset.formset.prefix }}-group .inline-related"; var updateInlineLabel = function(row) { $(rows).find(".inline_label").each(function(i) { var count = i + 1; $(this).html($(this).html().replace(/(#\d+)/g, "#" + count)); }); } var reinitDateTimeShortCuts = function() { // Reinitialize the calendar and clock widgets by force, yuck. if (typeof DateTimeShortcuts != "undefined") { $(".datetimeshortcuts").remove(); DateTimeShortcuts.init(); } } var updateSelectFilter = function() { // If any SelectFilter widgets were added, instantiate a new instance. if (typeof SelectFilter != "undefined"){ $(".selectfilter").each(function(index, value){ var namearr = value.name.split('-'); SelectFilter.init(value.id, namearr[namearr.length-1], false, "{% admin_media_prefix %}"); }); $(".selectfilterstacked").each(function(index, value){ var namearr = value.name.split('-'); SelectFilter.init(value.id, namearr[namearr.length-1], true, "{% admin_media_prefix %}"); }); } } var initPrepopulatedFields = function(row) { row.find('.prepopulated_field').each(function() { var field = $(this); var input = field.find('input, select, textarea'); var dependency_list = input.data('dependency_list') || []; var dependencies = []; $.each(dependency_list, function(i, field_name) { dependencies.push('#' + row.find(field_name).find('input, select, textarea').attr('id')); }); if (dependencies.length) { input.prepopulate(dependencies, input.attr('maxlength')); } }); } $(rows).formset({ prefix: "{{ inline_admin_formset.formset.prefix }}", addText: "{% blocktrans with inline_admin_formset.opts.verbose_name|title as verbose_name %}Add another {{ verbose_name }}{% endblocktrans %}", formCssClass: "dynamic-{{ inline_admin_formset.formset.prefix }}", deleteCssClass: "inline-deletelink", deleteText: "{% trans "Remove" %}", emptyCssClass: "empty-form", removed: updateInlineLabel, added: (function(row) { initPrepopulatedFields(row); reinitDateTimeShortCuts(); updateSelectFilter(); updateInlineLabel(row); }) }); }); })(django.jQuery); </script>
4,425
Python
.tac
80
44.5125
256
0.580705
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
4,204
selector_stacked-remove.gif
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/django/contrib/admin/media/img/admin/selector_stacked-remove.gif
GIF89aÕ<ÁÁÁÎÖݼ¼¼ñññ­µ½´´´±±±»»»ÝÝÝÊÊʲ»Åààà°±²îî¿®°²¹¹¹ÕÜãÀÀÀ²²²æêï²»Ä÷÷÷¾¾¾èìðùùùüýýÍÍÍÌÌ̬°µðððÒÒÒÏÏ϶¶¶âæëååå×××ÇÇÇäéíÞÞÞÃÃÃËË˯±²ÂÂÂêê과Ƴ³³ØØØ±ºÃÎÎÎÛÛÛÈÈÈÕÕÕÉÉÉ···¿¿¿¸¸¸µµµÄÄÄõøûÿÿÿ!ù<,®@ž�q<B6!0j*b±8}0L†’y¿Þ’�"TÜhhb”¦é`<Sn«“v»E½Ž ´.3�xx�37„„/� ,  :— 8¦¦x§¦9±9x²± 6¼6©;½69".7È73 3É7L :ÕÖ×XC05ÝÞÝcN9+ ):6YMBE° KMA;
401
Python
.tac
3
133
338
0.546366
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
4,205
stacked.html
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/django/contrib/admin/templates/admin/edit_inline/stacked.html
{% load i18n adminmedia %} <div class="inline-group" id="{{ inline_admin_formset.formset.prefix }}-group"> <h2>{{ inline_admin_formset.opts.verbose_name_plural|title }}</h2> {{ inline_admin_formset.formset.management_form }} {{ inline_admin_formset.formset.non_form_errors }} {% for inline_admin_form in inline_admin_formset %}<div class="inline-related{% if forloop.last %} empty-form last-related{% endif %}" id="{{ inline_admin_formset.formset.prefix }}-{% if not forloop.last %}{{ forloop.counter0 }}{% else %}empty{% endif %}"> <h3><b>{{ inline_admin_formset.opts.verbose_name|title }}:</b>&nbsp;<span class="inline_label">{% if inline_admin_form.original %}{{ inline_admin_form.original }}{% else %}#{{ forloop.counter }}{% endif %}</span> {% if inline_admin_form.show_url %}<a href="../../../r/{{ inline_admin_form.original_content_type_id }}/{{ inline_admin_form.original.id }}/">{% trans "View on site" %}</a>{% endif %} {% if inline_admin_formset.formset.can_delete and inline_admin_form.original %}<span class="delete">{{ inline_admin_form.deletion_field.field }} {{ inline_admin_form.deletion_field.label_tag }}</span>{% endif %} </h3> {% if inline_admin_form.form.non_field_errors %}{{ inline_admin_form.form.non_field_errors }}{% endif %} {% for fieldset in inline_admin_form %} {% include "admin/includes/fieldset.html" %} {% endfor %} {% if inline_admin_form.has_auto_field %}{{ inline_admin_form.pk_field.field }}{% endif %} {{ inline_admin_form.fk_field.field }} </div>{% endfor %} </div> <script type="text/javascript"> (function($) { $(document).ready(function() { var rows = "#{{ inline_admin_formset.formset.prefix }}-group .inline-related"; var updateInlineLabel = function(row) { $(rows).find(".inline_label").each(function(i) { var count = i + 1; $(this).html($(this).html().replace(/(#\d+)/g, "#" + count)); }); } var reinitDateTimeShortCuts = function() { // Reinitialize the calendar and clock widgets by force, yuck. if (typeof DateTimeShortcuts != "undefined") { $(".datetimeshortcuts").remove(); DateTimeShortcuts.init(); } } var updateSelectFilter = function() { // If any SelectFilter widgets were added, instantiate a new instance. if (typeof SelectFilter != "undefined"){ $(".selectfilter").each(function(index, value){ var namearr = value.name.split('-'); SelectFilter.init(value.id, namearr[namearr.length-1], false, "{% admin_media_prefix %}"); }) $(".selectfilterstacked").each(function(index, value){ var namearr = value.name.split('-'); SelectFilter.init(value.id, namearr[namearr.length-1], true, "{% admin_media_prefix %}"); }) } } var initPrepopulatedFields = function(row) { row.find('.prepopulated_field').each(function() { var field = $(this); var input = field.find('input, select, textarea'); var dependency_list = input.data('dependency_list') || []; var dependencies = []; $.each(dependency_list, function(i, field_name) { dependencies.push('#' + row.find(field_name).find('input, select, textarea').attr('id')); }); if (dependencies.length) { input.prepopulate(dependencies, input.attr('maxlength')); } }); } $(rows).formset({ prefix: "{{ inline_admin_formset.formset.prefix }}", addText: "{% blocktrans with inline_admin_formset.opts.verbose_name|title as verbose_name %}Add another {{ verbose_name }}{% endblocktrans %}", formCssClass: "dynamic-{{ inline_admin_formset.formset.prefix }}", deleteCssClass: "inline-deletelink", deleteText: "{% trans "Remove" %}", emptyCssClass: "empty-form", removed: updateInlineLabel, added: (function(row) { initPrepopulatedFields(row); reinitDateTimeShortCuts(); updateSelectFilter(); updateInlineLabel(row); }) }); }); })(django.jQuery); </script>
4,423
Python
.tac
80
44.4875
256
0.580972
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
4,206
modwsgi.txt
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/docs/howto/deployment/modwsgi.txt
========================================== How to use Django with Apache and mod_wsgi ========================================== Deploying Django with Apache_ and `mod_wsgi`_ is the recommended way to get Django into production. .. _Apache: http://httpd.apache.org/ .. _mod_wsgi: http://code.google.com/p/modwsgi/ mod_wsgi is an Apache module which can be used to host any Python application which supports the `Python WSGI interface`_, including Django. Django will work with any version of Apache which supports mod_wsgi. .. _python wsgi interface: http://www.python.org/dev/peps/pep-0333/ The `official mod_wsgi documentation`_ is fantastic; it's your source for all the details about how to use mod_wsgi. You'll probably want to start with the `installation and configuration documentation`_. .. _official mod_wsgi documentation: http://code.google.com/p/modwsgi/ .. _installation and configuration documentation: http://code.google.com/p/modwsgi/wiki/InstallationInstructions Basic configuration =================== Once you've got mod_wsgi installed and activated, edit your ``httpd.conf`` file and add:: WSGIScriptAlias / /path/to/mysite/apache/django.wsgi The first bit above is the url you want to be serving your application at (``/`` indicates the root url), and the second is the location of a "WSGI file" -- see below -- on your system, usually inside of your project. This tells Apache to serve any request below the given URL using the WSGI application defined by that file. Next we'll need to actually create this WSGI application, so create the file mentioned in the second part of ``WSGIScriptAlias`` and add:: import os import sys os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings' import django.core.handlers.wsgi application = django.core.handlers.wsgi.WSGIHandler() If your project is not on your ``PYTHONPATH`` by default you can add:: path = '/path/to/mysite' if path not in sys.path: sys.path.append(path) just below the ``import sys`` line to place your project on the path. Remember to replace 'mysite.settings' with your correct settings file, and '/path/to/mysite' with your own project's location. .. _serving-media-files: Serving media files =================== Django doesn't serve media files itself; it leaves that job to whichever Web server you choose. We recommend using a separate Web server -- i.e., one that's not also running Django -- for serving media. Here are some good choices: * lighttpd_ * Nginx_ * TUX_ * A stripped-down version of Apache_ * Cherokee_ If, however, you have no option but to serve media files on the same Apache ``VirtualHost`` as Django, you can set up Apache to serve some URLs as static media, and others using the mod_wsgi interface to Django. This example sets up Django at the site root, but explicitly serves ``robots.txt``, ``favicon.ico``, any CSS file, and anything in the ``/media/`` URL space as a static file. All other URLs will be served using mod_wsgi:: Alias /robots.txt /usr/local/wsgi/static/robots.txt Alias /favicon.ico /usr/local/wsgi/static/favicon.ico AliasMatch ^/([^/]*\.css) /usr/local/wsgi/static/styles/$1 Alias /media/ /usr/local/wsgi/static/media/ <Directory /usr/local/wsgi/static> Order deny,allow Allow from all </Directory> WSGIScriptAlias / /usr/local/wsgi/scripts/django.wsgi <Directory /usr/local/wsgi/scripts> Order allow,deny Allow from all </Directory> .. _lighttpd: http://www.lighttpd.net/ .. _Nginx: http://wiki.nginx.org/Main .. _TUX: http://en.wikipedia.org/wiki/TUX_web_server .. _Apache: http://httpd.apache.org/ .. _Cherokee: http://www.cherokee-project.com/ More details on configuring a mod_wsgi site to serve static files can be found in the mod_wsgi documentation on `hosting static files`_. .. _hosting static files: http://code.google.com/p/modwsgi/wiki/ConfigurationGuidelines#Hosting_Of_Static_Files .. _serving-the-admin-files: Serving the admin files ======================= Note that the Django development server automagically serves admin media files, but this is not the case when you use any other server arrangement. You're responsible for setting up Apache, or whichever media server you're using, to serve the admin files. The admin files live in (:file:`django/contrib/admin/media`) of the Django distribution. Here are two recommended approaches: 1. Create a symbolic link to the admin media files from within your document root. This way, all of your Django-related files -- code **and** templates -- stay in one place, and you'll still be able to ``svn update`` your code to get the latest admin templates, if they change. 2. Or, copy the admin media files so that they live within your Apache document root. Details ======= For more details, see the `mod_wsgi documentation on Django integration`_, which explains the above in more detail, and walks through all the various options you've got when deploying under mod_wsgi. .. _mod_wsgi documentation on Django integration: http://code.google.com/p/modwsgi/wiki/IntegrationWithDjango
5,168
Python
.wsgi
100
48.77
112
0.737512
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
4,207
modwsgi.txt
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/docs/howto/deployment/modwsgi.txt
========================================== How to use Django with Apache and mod_wsgi ========================================== Deploying Django with Apache_ and `mod_wsgi`_ is the recommended way to get Django into production. .. _Apache: http://httpd.apache.org/ .. _mod_wsgi: http://code.google.com/p/modwsgi/ mod_wsgi is an Apache module which can be used to host any Python application which supports the `Python WSGI interface`_, including Django. Django will work with any version of Apache which supports mod_wsgi. .. _python wsgi interface: http://www.python.org/dev/peps/pep-0333/ The `official mod_wsgi documentation`_ is fantastic; it's your source for all the details about how to use mod_wsgi. You'll probably want to start with the `installation and configuration documentation`_. .. _official mod_wsgi documentation: http://code.google.com/p/modwsgi/ .. _installation and configuration documentation: http://code.google.com/p/modwsgi/wiki/InstallationInstructions Basic configuration =================== Once you've got mod_wsgi installed and activated, edit your ``httpd.conf`` file and add:: WSGIScriptAlias / /path/to/mysite/apache/django.wsgi The first bit above is the url you want to be serving your application at (``/`` indicates the root url), and the second is the location of a "WSGI file" -- see below -- on your system, usually inside of your project. This tells Apache to serve any request below the given URL using the WSGI application defined by that file. Next we'll need to actually create this WSGI application, so create the file mentioned in the second part of ``WSGIScriptAlias`` and add:: import os import sys os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings' import django.core.handlers.wsgi application = django.core.handlers.wsgi.WSGIHandler() If your project is not on your ``PYTHONPATH`` by default you can add:: path = '/path/to/mysite' if path not in sys.path: sys.path.append(path) just below the ``import sys`` line to place your project on the path. Remember to replace 'mysite.settings' with your correct settings file, and '/path/to/mysite' with your own project's location. Serving media files =================== Django doesn't serve media files itself; it leaves that job to whichever Web server you choose. We recommend using a separate Web server -- i.e., one that's not also running Django -- for serving media. Here are some good choices: * lighttpd_ * Nginx_ * TUX_ * A stripped-down version of Apache_ * Cherokee_ If, however, you have no option but to serve media files on the same Apache ``VirtualHost`` as Django, you can set up Apache to serve some URLs as static media, and others using the mod_wsgi interface to Django. This example sets up Django at the site root, but explicitly serves ``robots.txt``, ``favicon.ico``, any CSS file, and anything in the ``/media/`` URL space as a static file. All other URLs will be served using mod_wsgi:: Alias /robots.txt /usr/local/wsgi/static/robots.txt Alias /favicon.ico /usr/local/wsgi/static/favicon.ico AliasMatch ^/([^/]*\.css) /usr/local/wsgi/static/styles/$1 Alias /media/ /usr/local/wsgi/static/media/ <Directory /usr/local/wsgi/static> Order deny,allow Allow from all </Directory> WSGIScriptAlias / /usr/local/wsgi/scripts/django.wsgi <Directory /usr/local/wsgi/scripts> Order allow,deny Allow from all </Directory> .. _lighttpd: http://www.lighttpd.net/ .. _Nginx: http://wiki.nginx.org/Main .. _TUX: http://en.wikipedia.org/wiki/TUX_web_server .. _Apache: http://httpd.apache.org/ .. _Cherokee: http://www.cherokee-project.com/ More details on configuring a mod_wsgi site to serve static files can be found in the mod_wsgi documentation on `hosting static files`_. .. _hosting static files: http://code.google.com/p/modwsgi/wiki/ConfigurationGuidelines#Hosting_Of_Static_Files Details ======= For more details, see the `mod_wsgi documentation on Django integration`_, which explains the above in more detail, and walks through all the various options you've got when deploying under mod_wsgi. .. _mod_wsgi documentation on Django integration: http://code.google.com/p/modwsgi/wiki/IntegrationWithDjango
4,276
Python
.wsgi
83
48.746988
112
0.737374
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
4,208
.pyup.yml
buildbot_buildbot/.pyup.yml
# update schedule, default is not set # the bot will visit the repo once and bundle all updates in a single PR for the given # day/week/month schedule: "every two weeks" # allowed ["every day", "every week", "every two weeks", "every month"]
242
Python
.py
4
59.5
99
0.739496
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,209
setup.py
buildbot_buildbot/www/console_view/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 try: from buildbot_pkg import setup_www_plugin except ImportError: import sys print( 'Please install buildbot_pkg module in order to install that ' 'package, or use the pre-build .whl modules available on pypi', file=sys.stderr, ) sys.exit(1) setup_www_plugin( name='buildbot-console-view', description='Buildbot Console View plugin', author='Pierre Tardy', author_email='[email protected]', url='http://buildbot.net/', packages=['buildbot_console_view'], package_data={ '': [ 'VERSION', 'static/*', 'static/assets/*', ] }, entry_points=""" [buildbot.www] console_view = buildbot_console_view:ep """, classifiers=['License :: OSI Approved :: GNU General Public License v2 (GPLv2)'], )
1,572
Python
.py
46
29.717391
85
0.694025
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,210
__init__.py
buildbot_buildbot/www/console_view/buildbot_console_view/__init__.py
# This file is part of Buildbot. Buildbot is free software: you can # redistribute it and/or modify it under the terms of the GNU General Public # License as published by the Free Software Foundation, version 2. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more # details. # # You should have received a copy of the GNU General Public License along with # this program; if not, write to the Free Software Foundation, Inc., 51 # Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # Copyright Buildbot Team Members from buildbot.www.plugin import Application # create the interface for the setuptools entry point ep = Application(__package__, "Buildbot Console View plugin")
867
Python
.py
17
49.882353
79
0.792453
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,211
setup.py
buildbot_buildbot/www/nestedexample/setup.py
#!/usr/bin/env python try: from buildbot_pkg import setup_www_plugin except ImportError: import sys print( 'Please install buildbot_pkg module in order to install that ' 'package, or use the pre-build .whl modules available on pypi', file=sys.stderr, ) sys.exit(1) setup_www_plugin( name='buildbot-nestedexample', description='"An example of a custom nested parameter"', author='Ion Alberdi', author_email='[email protected]', url='http://buildbot.net/', version='0.0.1', packages=['buildbot_nestedexample'], install_requires=['klein'], package_data={'': ['VERSION', 'static/*']}, entry_points=""" [buildbot.www] nestedexample = buildbot_nestedexample:ep """, classifiers=['License :: OSI Approved :: GNU General Public License v2 (GPLv2)'], )
856
Python
.py
27
26.592593
85
0.662228
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,212
api.py
buildbot_buildbot/www/nestedexample/buildbot_nestedexample/api.py
import json from klein import Klein from twisted.internet import defer class Api: app = Klein() pizzaIngredients = { 'margherita': ['tomato', 'ham', 'cheese'], 'regina': ['tomato', 'ham', 'cheese', 'mushrooms'], } def __init__(self, ep): self.ep = ep @app.route("/getIngredients", methods=['GET']) def getIngredients(self, request): pizzaArgument = request.args.get('pizza') if pizzaArgument is None: return defer.succeed(json.dumps("invalid request")) pizza = pizzaArgument[0].lower() res = self.pizzaIngredients.get( pizza, [f"only {self.pizzaIngredients.keys()} are supported for now"] ) return defer.succeed(json.dumps(res))
754
Python
.py
21
28.952381
81
0.623626
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,213
__init__.py
buildbot_buildbot/www/nestedexample/buildbot_nestedexample/__init__.py
from twisted.internet import defer from buildbot.schedulers.forcesched import ChoiceStringParameter from buildbot.schedulers.forcesched import NestedParameter from buildbot.schedulers.forcesched import StringParameter from buildbot.schedulers.forcesched import ValidationError from buildbot.www.plugin import Application from .api import Api class NestedExample(NestedParameter): """UI zone""" type = "nestedexample" PIZZA = "pizza" INGREDIENTS = "ingredients" def __init__(self, **kw): pizzaInput = StringParameter( label="type the name of your pizza", name=self.PIZZA, required=True ) ingredientsInput = ChoiceStringParameter( name=self.INGREDIENTS, label="ingredients necessary to make the pizza", multiple=True, strict=False, default="", choices=[], ) self.params = {self.PIZZA: pizzaInput, self.INGREDIENTS: ingredientsInput} self.allIngredients = set(sum([ingr for ingr in Api.pizzaIngredients.values()], [])) fields = self.params.values() super().__init__(self.type, label='', fields=fields, **kw) def createNestedPropertyName(self, propertyName): return f"{self.type}_{propertyName}" @defer.inlineCallbacks def validateProperties(self, collector, properties): # we implement the check between the input and # the ingredients if properties[self.INGREDIENTS] not in self.allIngredients or not properties[self.PIZZA]: # we trigger a specific error message in PIZZA only def f(): return defer.fail(ValidationError('Invalid pizza')) nestedProp = self.createNestedPropertyName(self.PIZZA) yield collector.collectValidationErrors(nestedProp, f) @defer.inlineCallbacks def updateFromKwargs(self, kwargs, properties, collector, **kw): yield super().updateFromKwargs(kwargs, properties, collector, **kw) # the properties we have are in the form # {nestedexample: {input: <url>, # ingredients: <ingredients>}} # we just flatten the dict to have # - input, and # - ingredients # in properties for prop, val in properties.pop(self.type).items(): properties[prop] = val yield self.validateProperties(collector, properties) # create the interface for the setuptools entry point ep = Application(__package__, "Buildbot nested parameter example") api = Api(ep) ep.resource.putChild("api", api.app.resource())
2,604
Python
.py
57
37.877193
97
0.680473
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,214
setup.py
buildbot_buildbot/www/wsgi_dashboards/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 try: from buildbot_pkg import setup_www_plugin except ImportError: import sys print( 'Please install buildbot_pkg module in order to install that ' 'package, or use the pre-build .whl modules available on pypi', file=sys.stderr, ) sys.exit(1) setup_www_plugin( name='buildbot-wsgi-dashboards', description='Buildbot plugin to integrate flask or bottle' 'dashboards to buildbot UI (React)', author='Buildbot maintainers', author_email='[email protected]', url='http://buildbot.net/', packages=['buildbot_wsgi_dashboards'], package_data={'': ['VERSION', 'static/*']}, entry_points=""" [buildbot.www] wsgi_dashboards = buildbot_wsgi_dashboards:ep """, classifiers=['License :: OSI Approved :: GNU General Public License v2 (GPLv2)'], )
1,566
Python
.py
40
35.575
99
0.726855
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,215
__init__.py
buildbot_buildbot/www/wsgi_dashboards/buildbot_wsgi_dashboards/__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 twisted.internet import reactor from twisted.internet.threads import blockingCallFromThread from twisted.web.wsgi import WSGIResource from buildbot.util import unicode2bytes from buildbot.www.plugin import Application class WSGIDashboardsApplication(Application): def setConfiguration(self, config): super().setConfiguration(config) for dashboard in config: dashboard['app'].buildbot_api = self resource = WSGIResource(reactor, reactor.getThreadPool(), dashboard['app']) self.resource.putChild(unicode2bytes(dashboard['name']), resource) def dataGet(self, path, **kwargs): if not isinstance(path, tuple): path = tuple(path.strip("/").split("/")) return blockingCallFromThread(reactor, self.master.data.get, path, **kwargs) # create the interface for the setuptools entry point ep = WSGIDashboardsApplication(__name__, "Buildbot WSGI Dashboard Glue")
1,655
Python
.py
32
47.75
87
0.761139
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,216
setup.py
buildbot_buildbot/www/base/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 try: from buildbot_pkg import setup_www_plugin except ImportError: import sys print( 'Please install buildbot_pkg module in order to install that ' 'package, or use the pre-build .whl modules available on pypi', file=sys.stderr, ) sys.exit(1) setup_www_plugin( name='buildbot-www', description='Buildbot UI', author='Povilas Kanapickas', author_email='[email protected]', setup_requires=['buildbot_pkg'], install_requires=['buildbot'], url='http://buildbot.net/', packages=['buildbot_www'], package_data={ '': [ 'VERSION', 'static/*', 'static/assets/*', ] }, entry_points=""" [buildbot.www] base = buildbot_www:ep """, classifiers=['License :: OSI Approved :: GNU General Public License v2 (GPLv2)'], )
1,598
Python
.py
48
28.8125
85
0.687783
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,217
__init__.py
buildbot_buildbot/www/base/buildbot_www/__init__.py
# This file is part of Buildbot. Buildbot is free software: you can # redistribute it and/or modify it under the terms of the GNU General Public # License as published by the Free Software Foundation, version 2. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more # details. # # You should have received a copy of the GNU General Public License along with # this program; if not, write to the Free Software Foundation, Inc., 51 # Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # Copyright Buildbot Team Members from buildbot.www.plugin import Application # create the interface for the setuptools entry point ep = Application(__package__, "Buildbot UI (React)")
858
Python
.py
17
49.352941
79
0.789035
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,218
setup.py
buildbot_buildbot/www/grid_view/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 try: from buildbot_pkg import setup_www_plugin except ImportError: import sys print( 'Please install buildbot_pkg module in order to install that ' 'package, or use the pre-build .whl modules available on pypi', file=sys.stderr, ) sys.exit(1) setup_www_plugin( name='buildbot-grid-view', description='Buildbot Grid View plugin', author='Robin Jarry', author_email='[email protected]', url='http://buildbot.net/', packages=['buildbot_grid_view'], package_data={'': ['VERSION', 'static/*', 'static/assets/*']}, entry_points=""" [buildbot.www] grid_view = buildbot_grid_view:ep """, classifiers=['License :: OSI Approved :: GNU General Public License v2 (GPLv2)'], )
1,500
Python
.py
40
33.925
85
0.717227
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,219
__init__.py
buildbot_buildbot/www/grid_view/buildbot_grid_view/__init__.py
# This file is part of Buildbot. Buildbot is free software: you can # redistribute it and/or modify it under the terms of the GNU General Public # License as published by the Free Software Foundation, version 2. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more # details. # # You should have received a copy of the GNU General Public License along with # this program; if not, write to the Free Software Foundation, Inc., 51 # Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # Copyright Buildbot Team Members from buildbot.www.plugin import Application # create the interface for the setuptools entry point ep = Application(__package__, "Buildbot Grid View plugin")
864
Python
.py
17
49.705882
79
0.791716
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,220
setup.py
buildbot_buildbot/www/badges/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 try: from buildbot_pkg import setup_www_plugin except ImportError: import sys print( 'Please install buildbot_pkg module in order to install that ' 'package, or use the pre-build .whl modules available on pypi', file=sys.stderr, ) sys.exit(1) setup_www_plugin( name='buildbot-badges', description='Buildbot badges', author='Buildbot Team Members', author_email='[email protected]', url='http://buildbot.net/', packages=['buildbot_badges'], install_requires=['klein', 'CairoSVG', 'cairocffi', 'Jinja2'], package_data={ '': [ # dist is required by buildbot_pkg 'VERSION', 'templates/*.svg.j2', 'static/.placeholder', ], }, entry_points=""" [buildbot.www] badges = buildbot_badges:ep """, classifiers=['License :: OSI Approved :: GNU General Public License v2 (GPLv2)'], )
1,675
Python
.py
48
30.25
85
0.689039
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,221
__init__.py
buildbot_buildbot/www/badges/buildbot_badges/__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 xml.sax.saxutils import escape import cairocffi as cairo import cairosvg import jinja2 from klein import Klein from twisted.internet import defer from buildbot.process.results import Results from buildbot.util import bytes2unicode from buildbot.www.plugin import Application class Api: app = Klein() default = { # note that these defaults are documented in configuration/www.rst "left_pad": 5, "left_text": "Build Status", "left_color": "#555", "right_pad": 5, "border_radius": 5, "style": "plastic", "template_name": "{style}.svg.j2", "font_face": "DejaVu Sans", "font_size": 11, "color_scheme": { "exception": "#007ec6", # blue "failure": "#e05d44", # red "retry": "#007ec6", # blue "running": "#007ec6", # blue "skipped": "a4a61d", # yellowgreen "success": "#4c1", # brightgreen "unknown": "#9f9f9f", # lightgrey "warnings": "#dfb317", # yellow }, } def __init__(self, ep): self.ep = ep self.env = jinja2.Environment( loader=jinja2.ChoiceLoader([ jinja2.PackageLoader('buildbot_badges'), jinja2.FileSystemLoader('templates'), ]) ) def makeConfiguration(self, request): config = {} config.update(self.default) for k, v in self.ep.config.items(): if k == 'color_scheme': config[k].update(v) else: config[k] = v for k, v in request.args.items(): k = bytes2unicode(k) config[k] = escape(bytes2unicode(v[0])) return config @app.route("/<string:builder>.png", methods=['GET']) @defer.inlineCallbacks def getPng(self, request, builder): svg = yield self.getSvg(request, builder) request.setHeader('content-type', 'image/png') return cairosvg.svg2png(svg) @app.route("/<string:builder>.svg", methods=['GET']) @defer.inlineCallbacks def getSvg(self, request, builder): config = self.makeConfiguration(request) request.setHeader('content-type', 'image/svg+xml') request.setHeader('cache-control', 'no-cache') # get the last build for that builder using the data api last_build = yield self.ep.master.data.get( ("builders", builder, "builds"), limit=1, order=['-number'] ) # get the status text corresponding to results code results_txt = "unknown" if last_build: results = last_build[0]['results'] complete = last_build[0]['complete'] if not complete: results_txt = "running" elif results >= 0 and results < len(Results): results_txt = Results[results] svgdata = self.makesvg( results_txt, results_txt, left_text=config['left_text'], config=config ) return svgdata def textwidth(self, text, config): """Calculates the width of the specified text.""" surface = cairo.SVGSurface(None, 1280, 200) ctx = cairo.Context(surface) ctx.select_font_face(config['font_face'], cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_NORMAL) ctx.set_font_size(int(config['font_size'])) return ctx.text_extents(text)[4] def makesvg(self, right_text, status=None, left_text=None, left_color=None, config=None): """Renders an SVG from the template, using the specified data""" right_color = config['color_scheme'].get(status, "#9f9f9f") # Grey left_text = left_text or config['left_text'] left_color = left_color or config['left_color'] left = {"color": left_color, "text": left_text, "width": self.textwidth(left_text, config)} right = { "color": right_color, "text": right_text, "width": self.textwidth(right_text, config), } template = self.env.get_template(config['template_name'].format(**config)) return template.render(left=left, right=right, config=config) # create the interface for the setuptools entry point ep = Application(__package__, "Buildbot badges", ui=False) ep.resource = Api(ep).app.resource()
5,036
Python
.py
118
34.584746
100
0.627119
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,222
setup.py
buildbot_buildbot/www/waterfall_view/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 try: from buildbot_pkg import setup_www_plugin except ImportError: import sys print( 'Please install buildbot_pkg module in order to install that ' 'package, or use the pre-build .whl modules available on pypi', file=sys.stderr, ) sys.exit(1) setup_www_plugin( name='buildbot-waterfall-view', description='Buildbot Waterfall View plugin', author='Pierre Tardy', author_email='[email protected]', url='http://buildbot.net/', packages=['buildbot_waterfall_view'], package_data={'': ['VERSION', 'static/*', 'static/assets/*']}, entry_points=""" [buildbot.www] waterfall_view = buildbot_waterfall_view:ep """, classifiers=['License :: OSI Approved :: GNU General Public License v2 (GPLv2)'], )
1,521
Python
.py
40
34.45
85
0.721922
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,223
__init__.py
buildbot_buildbot/www/waterfall_view/buildbot_waterfall_view/__init__.py
# This file is part of Buildbot. Buildbot is free software: you can # redistribute it and/or modify it under the terms of the GNU General Public # License as published by the Free Software Foundation, version 2. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more # details. # # You should have received a copy of the GNU General Public License along with # this program; if not, write to the Free Software Foundation, Inc., 51 # Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # Copyright Buildbot Team Members from buildbot.www.plugin import Application # create the interface for the setuptools entry point ep = Application(__package__, "Buildbot Waterfall View plugin")
869
Python
.py
17
50
79
0.792941
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,224
setup.py
buildbot_buildbot/pkg/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 import buildbot_pkg from setuptools import setup setup( name='buildbot-pkg', version=buildbot_pkg.getVersion("."), description='Buildbot packaging tools', author='Pierre Tardy', author_email='[email protected]', url='http://buildbot.net/', py_modules=['buildbot_pkg'], install_requires=[ "setuptools >= 21.2.1", ], classifiers=['License :: OSI Approved :: GNU General Public License v2 (GPLv2)'], )
1,177
Python
.py
31
35.354839
85
0.743881
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,225
buildbot_pkg.py
buildbot_buildbot/pkg/buildbot_pkg.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 # Method to add build step taken from here # https://seasonofcode.com/posts/how-to-add-custom-build-steps-and-commands-to-setuppy.html import datetime import logging import os import re import shutil import subprocess import sys from subprocess import PIPE from subprocess import STDOUT from subprocess import Popen import setuptools.command.build_py import setuptools.command.egg_info from setuptools import Command from setuptools import setup old_listdir = os.listdir def listdir(path): # patch listdir to avoid looking into node_modules l = old_listdir(path) if "node_modules" in l: l.remove("node_modules") return l os.listdir = listdir def check_output(cmd, shell): """Version of check_output which does not throw error""" popen = subprocess.Popen(cmd, shell=shell, stdout=subprocess.PIPE) out = popen.communicate()[0].strip() if not isinstance(out, str): out = out.decode(sys.stdout.encoding) return out 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 and 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, dirs, 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" # JS build strategy: # # Obviously, building javascript with setuptools is not really something supported initially # # The goal of this hack are: # - override the distutils command to insert our js build # - has very small setup.py # # from buildbot_pkg import setup_www # # setup_www( # ... # packages=["buildbot_myplugin"] # ) # # We need to override the first command done, so that source tree is populated very soon, # as well as version is found from git tree or "VERSION" file # # This supports following setup.py commands: # # - develop, via egg_info # - install, via egg_info # - sdist, via egg_info # - bdist_wheel, via build # This is why we override both egg_info and build, and the first run build # the js. class BuildJsCommand(Command): """A custom command to run JS build.""" description = 'run JS build' already_run = False def initialize_options(self): """Set default values for options.""" def finalize_options(self): """Post-process options.""" def run(self): """Run command.""" if self.already_run: return if os.path.isdir('build'): shutil.rmtree('build') package = self.distribution.packages[0] if os.path.exists("package.json"): shell = bool(os.name == 'nt') yarn_program = None for program in ["yarnpkg", "yarn"]: try: yarn_version = check_output([program, "--version"], shell=shell) if yarn_version != "": yarn_program = program break except subprocess.CalledProcessError: pass assert yarn_program is not None, "need nodejs and yarn installed in current PATH" commands = [ [yarn_program, 'install', '--pure-lockfile'], [yarn_program, 'run', 'build'], ] for command in commands: logging.info('Running command: {}'.format(str(" ".join(command)))) try: subprocess.check_call(command, shell=shell) except subprocess.CalledProcessError as e: raise Exception( f"Exception = {e} command was called in directory = {os.getcwd()}" ) from e self.copy_tree( os.path.join(package, 'static'), os.path.join("build", "lib", package, "static") ) assert self.distribution.metadata.version is not None, "version is not set" with open(os.path.join("build", "lib", package, "VERSION"), "w") as f: f.write(self.distribution.metadata.version) with open(os.path.join(package, "VERSION"), "w") as f: f.write(self.distribution.metadata.version) self.already_run = True class BuildPyCommand(setuptools.command.build_py.build_py): """Custom build command.""" def run(self): self.run_command('build_js') super().run() class EggInfoCommand(setuptools.command.egg_info.egg_info): """Custom egginfo command.""" def run(self): self.run_command('build_js') super().run() def setup_www_plugin(**kw): package = kw['packages'][0] if 'version' not in kw: kw['version'] = getVersion(os.path.join(package, "__init__.py")) setup( cmdclass=dict(egg_info=EggInfoCommand, build_py=BuildPyCommand, build_js=BuildJsCommand), **kw, )
8,915
Python
.py
221
33.257919
118
0.644668
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,226
test_buildbot_pkg.py
buildbot_buildbot/pkg/test_buildbot_pkg.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 sys from subprocess import call from subprocess import check_call from textwrap import dedent from twisted.trial import unittest class BuildbotWWWPkg(unittest.TestCase): pkgName = "buildbot_www" pkgPaths = ["www", "base"] epName = "base" loadTestScript = dedent(r""" from importlib.metadata import entry_points import re apps = {} eps = entry_points() entry_point = "buildbot.www" if hasattr(eps, "select"): entry_point_group = eps.select(group=entry_point) else: entry_point_group = eps.get(entry_point, []) for ep in entry_point_group: apps[ep.name] = ep.load() print(apps["%(epName)s"]) print(apps["%(epName)s"].resource.listNames()) expected_file = "scripts.js" if "%(epName)s" == "base": expected_file = "index.html" assert(expected_file in apps["%(epName)s"].resource.listNames()) assert(re.match(r'\d+\.\d+\.\d+', apps["%(epName)s"].version) is not None) assert(apps["%(epName)s"].description is not None) """) @property def path(self): return os.path.abspath(os.path.join(os.path.dirname(__file__), "..", *self.pkgPaths)) def rmtree(self, d): if os.path.isdir(d): shutil.rmtree(d) def setUp(self): call("pip uninstall -y " + self.pkgName, shell=True) self.rmtree(os.path.join(self.path, "build")) self.rmtree(os.path.join(self.path, "dist")) self.rmtree(os.path.join(self.path, "static")) def run_build(self, kind): check_call([sys.executable, "-m", "build", "--no-isolation", f"--{kind}"], cwd=self.path) def check_correct_installation(self): # assert we can import buildbot_www # and that it has an endpoint with resource containing file "index.html" check_call([sys.executable, '-c', self.loadTestScript % dict(epName=self.epName)]) def test_wheel(self): self.run_build("wheel") check_call("pip install build dist/*.whl", shell=True, cwd=self.path) self.check_correct_installation() def test_develop_via_pip(self): check_call("pip install build -e .", shell=True, cwd=self.path) self.check_correct_installation() def test_sdist(self): self.run_build("sdist") check_call("pip install build dist/*.tar.gz", shell=True, cwd=self.path) self.check_correct_installation() class BuildbotConsolePkg(BuildbotWWWPkg): pkgName = "buildbot-console-view" pkgPaths = ["www", "console_view"] epName = "console_view" class BuildbotWaterfallPkg(BuildbotWWWPkg): pkgName = "buildbot-waterfall-view" pkgPaths = ["www", "waterfall_view"] epName = "waterfall_view"
3,519
Python
.py
82
36.695122
97
0.667252
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,227
porttostable.py
buildbot_buildbot/common/porttostable.py
import os from subprocess import CalledProcessError from subprocess import check_output import requests import yaml s = requests.Session() with open(os.path.expanduser('~/.config/hub')) as f: config = yaml.load(f)['github.com'][0] s.auth = config['user'], config['oauth_token'] os.system("git fetch --all") r = s.get( "https://api.github.com/search/issues?q=label:\"port%20to%20stable\"+repo:buildbot/buildbot" ) to_port = r.json() summary = "" for pr in to_port['items']: r = s.get("https://api.github.com/repos/buildbot/buildbot/pulls/{number}/commits".format(**pr)) commits = r.json() for c in commits: title = c['commit']['message'].split("\n")[0] try: check_output("git cherry-pick {sha} 2>&1".format(**c), shell=True) except CalledProcessError as e: os.system("git diff") os.system("git reset --hard HEAD 2>&1 >/dev/null") if '--allow-empty' in e.output: continue if 'fatal: bad object' in e.output: continue print("cannot automatically cherry-pick", pr['number'], c['sha'], title, e.output) else: summary += "\n#{number}: {title}".format(number=pr['number'], title=title, **c) print(summary)
1,274
Python
.py
33
32.30303
99
0.621163
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,228
gather_dependabot.py
buildbot_buildbot/common/gather_dependabot.py
#!/usr/bin/env python3 # this script takes all the PR created by dependabot and gather them into one import os import requests import yaml def main(): with open(os.path.expanduser("~/.config/hub")) as f: conf = yaml.safe_load(f) token = conf['github.com'][0]['oauth_token'] os.system("git fetch https://github.com/buildbot/buildbot master") os.system("git checkout FETCH_HEAD -B gather_dependabot") s = requests.Session() s.headers.update({'Authorization': 'token ' + token}) r = s.get("https://api.github.com/repos/buildbot/buildbot/pulls") r.raise_for_status() prs = r.json() pr_text = "This PR collects dependabot PRs:\n\n" for pr in prs: if 'dependabot' in pr['user']['login']: print(pr['number'], pr['title']) pr_text += f"#{pr['number']}: {pr['title']}\n" os.system( "git fetch https://github.com/buildbot/buildbot " f"refs/pull/{pr['number']}/head" ) os.system("git cherry-pick FETCH_HEAD") print("===========") print(pr_text) if __name__ == '__main__': main()
1,130
Python
.py
29
32.37931
98
0.60495
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,229
download_release.py
buildbot_buildbot/common/download_release.py
#!/usr/bin/env python3 import os import subprocess import requests import yaml def download(session, url, fn): if os.path.exists(fn): print(f'Removing old file {fn}') os.unlink(fn) print(f'Downloading {fn} from {url}') with open(fn, 'wb') as f: r = session.get(url, stream=True) r.raise_for_status() for c in r.iter_content(1024): f.write(c) def get_current_tag(): out = subprocess.check_output(['git', 'tag', '--points-at', 'HEAD']).strip() if not out: raise RuntimeError('Could not find any tags pointing to current release') tags = out.decode('utf-8').split(' ') if len(tags) > 1: raise RuntimeError(f'More than one tag points to HEAD: {tags}') return tags[0] def find_release_by_name(s, name): r = s.get("https://api.github.com/repos/buildbot/buildbot/releases") r.raise_for_status() for release in r.json(): if release['name'] == name: return release raise RuntimeError(f'Could not find release for name {name}') def main(): with open(os.path.expanduser("~/.config/hub")) as f: conf = yaml.safe_load(f) token = conf['github.com'][0]['oauth_token'] s = requests.Session() s.headers.update({'Authorization': 'token ' + token}) tag = get_current_tag() release = find_release_by_name(s, name=tag) upload_url = release['upload_url'].split('{')[0] assets = s.get( ("https://api.github.com/repos/buildbot/buildbot/releases/{id}/assets").format( id=release['id'] ) ) assets.raise_for_status() assets = assets.json() os.makedirs('dist', exist_ok=True) for url in (a['browser_download_url'] for a in assets): if 'gitarchive' in url: raise RuntimeError( 'The git archive has already been uploaded. Are you trying to fix ' 'broken upload? If this is the case, delete the asset in the GitHub ' 'UI and retry this command' ) if url.endswith(".whl") or url.endswith(".tar.gz"): fn = os.path.join('dist', url.split('/')[-1]) download(s, url, fn) # download tag archive url = f"https://github.com/buildbot/buildbot/archive/{tag}.tar.gz" fn = os.path.join('dist', f"buildbot-{tag}.gitarchive.tar.gz") download(s, url, fn) sigfn = fn + ".asc" if os.path.exists(sigfn): os.unlink(sigfn) # sign the tag archive for debian os.system(f"gpg --armor --detach-sign --output {sigfn} {fn}") sigfnbase = os.path.basename(sigfn) r = s.post( upload_url, headers={'Content-Type': "application/pgp-signature"}, params={"name": sigfnbase}, data=open(sigfn, 'rb'), ) print(r.content) fnbase = os.path.basename(fn) r = s.post( upload_url, headers={'Content-Type': "application/gzip"}, params={"name": fnbase}, data=open(fn, 'rb'), ) print(r.content) # remove files so that twine upload do not upload them os.unlink(sigfn) os.unlink(fn) if __name__ == '__main__': main()
3,147
Python
.py
87
29.333333
87
0.604796
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,230
setup.py
buildbot_buildbot/master/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. """ from setuptools import setup # isort:skip import inspect import os import sys from setuptools import Command from setuptools.command.sdist import sdist from buildbot import version BUILDING_WHEEL = bool("bdist_wheel" in sys.argv) class install_data_twisted(Command): """make sure VERSION file is installed in package.""" 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/VERSION file fn = os.path.join(self.install_dir, 'buildbot', '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/VERSION file fn = os.path.join(base_dir, 'buildbot', 'VERSION') with open(fn, 'w') as f: f.write(version) # ensure that NEWS has a copy of the latest release notes, with the # proper version substituted src_fn = os.path.join('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) def define_plugin_entry(name, module_name): """ helper to produce lines suitable for setup.py's entry_points """ if isinstance(name, tuple): entry, name = name else: entry = name return f'{entry} = {module_name}:{name}' def concat_dicts(*dicts): result = {} for d in dicts: result.update(d) return result def define_plugin_entries(groups): """ helper to all groups for plugins """ result = {} for group, modules in groups: tempo = [] for module_name, names in modules: tempo.extend([define_plugin_entry(name, module_name) for name in names]) result[group] = tempo return result __file__ = inspect.getframeinfo(inspect.currentframe()).filename with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as long_d_f: long_description = long_d_f.read() setup_args = { 'name': "buildbot", 'version': version, 'description': "The Continuous Integration Framework", 'long_description': long_description, '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)', 'Environment :: Web Environment', '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.8', 'Programming Language :: Python :: 3.9', 'Programming Language :: Python :: 3.10', 'Programming Language :: Python :: 3.11', 'Programming Language :: Python :: 3.12', ], 'packages': [ "buildbot", "buildbot.configurators", "buildbot.worker", "buildbot.worker.protocols", "buildbot.worker.protocols.manager", "buildbot.changes", "buildbot.clients", "buildbot.config", "buildbot.data", "buildbot.db", "buildbot.db.compression", "buildbot.db.migrations", "buildbot.db.migrations.versions", "buildbot.db.types", "buildbot.machine", "buildbot.monkeypatches", "buildbot.mq", "buildbot.plugins", "buildbot.process", "buildbot.process.users", "buildbot.reporters", "buildbot.reporters.generators", "buildbot.schedulers", "buildbot.scripts", "buildbot.secrets", "buildbot.secrets.providers", "buildbot.spec", "buildbot.spec.types", "buildbot.statistics", "buildbot.statistics.storage_backends", "buildbot.steps", "buildbot.steps.package", "buildbot.steps.package.deb", "buildbot.steps.package.rpm", "buildbot.steps.source", "buildbot.util", "buildbot.wamp", "buildbot.www", "buildbot.www.hooks", "buildbot.www.authz", "buildbot.test", "buildbot.test.util", "buildbot.test.fake", "buildbot.test.fakedb", "buildbot.test.integration.pki", "buildbot.test.integration.pki.ca", "buildbot.test.unit.test_templates_dir", "buildbot.test.unit.test_templates_dir.plugin", ] + ( [] if BUILDING_WHEEL else [ # skip tests for wheels (save 50% of the archive) "buildbot.test.fuzz", "buildbot.test.integration", "buildbot.test.integration.interop", "buildbot.test.regressions", "buildbot.test.unit", ] ), # mention data_files, even if empty, so install_data is called and # VERSION gets copied 'data_files': [("buildbot", [])], 'package_data': { "": ["VERSION"], "buildbot.reporters.templates": ["*.txt"], "buildbot.db.migrations": [ "alembic.ini", "README", ], "buildbot.db.migrations.versions": ["*.py"], "buildbot.scripts": [ "sample.cfg", "buildbot_tac.tmpl", ], "buildbot.spec": ["*.raml"], "buildbot.spec.types": ["*.raml"], "buildbot.test.unit.test_templates_dir": ["*.html"], "buildbot.test.unit.test_templates_dir.plugin": ["*.*"], "buildbot.test.integration.pki": ["*.*"], "buildbot.test.integration.pki.ca": ["*.*"], }, 'cmdclass': {'install_data': install_data_twisted, 'sdist': our_sdist}, 'entry_points': concat_dicts( define_plugin_entries([ ( 'buildbot.changes', [ ( 'buildbot.changes.mail', [ 'MaildirSource', 'CVSMaildirSource', 'SVNCommitEmailMaildirSource', 'BzrLaunchpadEmailMaildirSource', ], ), ('buildbot.changes.bitbucket', ['BitbucketPullrequestPoller']), ('buildbot.changes.github', ['GitHubPullrequestPoller']), ( 'buildbot.changes.gerritchangesource', ['GerritChangeSource', 'GerritEventLogPoller'], ), ('buildbot.changes.gitpoller', ['GitPoller']), ('buildbot.changes.hgpoller', ['HgPoller']), ('buildbot.changes.p4poller', ['P4Source']), ('buildbot.changes.pb', ['PBChangeSource']), ('buildbot.changes.svnpoller', ['SVNPoller']), ], ), ( 'buildbot.schedulers', [ ('buildbot.schedulers.basic', ['SingleBranchScheduler', 'AnyBranchScheduler']), ('buildbot.schedulers.dependent', ['Dependent']), ('buildbot.schedulers.triggerable', ['Triggerable']), ('buildbot.schedulers.forcesched', ['ForceScheduler']), ('buildbot.schedulers.timed', ['Periodic', 'Nightly', 'NightlyTriggerable']), ('buildbot.schedulers.trysched', ['Try_Jobdir', 'Try_Userpass']), ], ), ( 'buildbot.secrets', [ ('buildbot.secrets.providers.file', ['SecretInAFile']), ('buildbot.secrets.providers.passwordstore', ['SecretInPass']), ( 'buildbot.secrets.providers.vault_hvac', [ 'HashiCorpVaultKvSecretProvider', 'VaultAuthenticatorToken', 'VaultAuthenticatorApprole', ], ), ], ), ( 'buildbot.worker', [ ('buildbot.worker.base', ['Worker']), ('buildbot.worker.ec2', ['EC2LatentWorker']), ('buildbot.worker.libvirt', ['LibVirtWorker']), ('buildbot.worker.openstack', ['OpenStackLatentWorker']), ('buildbot.worker.docker', ['DockerLatentWorker']), ('buildbot.worker.kubernetes', ['KubeLatentWorker']), ('buildbot.worker.local', ['LocalWorker']), ], ), ( 'buildbot.machine', [ ('buildbot.machine.base', ['Machine']), ], ), ( 'buildbot.steps', [ ('buildbot.process.buildstep', ['BuildStep']), ('buildbot.steps.cmake', ['CMake']), ( 'buildbot.steps.configurable', ['BuildbotTestCiTrigger', 'BuildbotCiSetupSteps'], ), ('buildbot.steps.cppcheck', ['Cppcheck']), ('buildbot.steps.gitdiffinfo', ['GitDiffInfo']), ( 'buildbot.steps.http', ['HTTPStep', 'POST', 'GET', 'PUT', 'DELETE', 'HEAD', 'OPTIONS'], ), ( 'buildbot.steps.master', [ 'MasterShellCommand', 'SetProperty', 'SetProperties', 'LogRenderable', "Assert", ], ), ('buildbot.steps.maxq', ['MaxQ']), ('buildbot.steps.mswin', ['Robocopy']), ('buildbot.steps.package.deb.lintian', ['DebLintian']), ( 'buildbot.steps.package.deb.pbuilder', ['DebPbuilder', 'DebCowbuilder', 'UbuPbuilder', 'UbuCowbuilder'], ), ('buildbot.steps.package.rpm.mock', ['Mock', 'MockBuildSRPM', 'MockRebuild']), ('buildbot.steps.package.rpm.rpmbuild', ['RpmBuild']), ('buildbot.steps.package.rpm.rpmlint', ['RpmLint']), ('buildbot.steps.python', ['BuildEPYDoc', 'PyFlakes', 'PyLint', 'Sphinx']), ('buildbot.steps.python_twisted', ['HLint', 'Trial', 'RemovePYCs']), ( 'buildbot.steps.shell', [ 'ShellCommand', 'TreeSize', 'SetPropertyFromCommand', 'Configure', 'WarningCountingShellCommand', 'Compile', 'Test', 'PerlModuleTest', ], ), ('buildbot.steps.shellsequence', ['ShellSequence']), ('buildbot.steps.source.bzr', ['Bzr']), ('buildbot.steps.source.cvs', ['CVS']), ('buildbot.steps.source.darcs', ['Darcs']), ('buildbot.steps.source.gerrit', ['Gerrit']), ('buildbot.steps.source.git', ['Git', 'GitCommit', 'GitPush', 'GitTag']), ('buildbot.steps.source.github', ['GitHub']), ('buildbot.steps.source.gitlab', ['GitLab']), ('buildbot.steps.source.mercurial', ['Mercurial']), ('buildbot.steps.source.mtn', ['Monotone']), ('buildbot.steps.source.p4', ['P4']), ('buildbot.steps.source.repo', ['Repo']), ('buildbot.steps.source.svn', ['SVN']), ('buildbot.steps.subunit', ['SubunitShellCommand']), ( 'buildbot.steps.transfer', [ 'FileUpload', 'DirectoryUpload', 'MultipleFileUpload', 'FileDownload', 'StringDownload', 'JSONStringDownload', 'JSONPropertiesDownload', ], ), ('buildbot.steps.trigger', ['Trigger']), ( 'buildbot.steps.vstudio', [ 'VC6', 'VC7', 'VS2003', 'VC8', 'VS2005', 'VCExpress9', 'VC9', 'VS2008', 'VC10', 'VS2010', 'VC11', 'VS2012', 'VC12', 'VS2013', 'VC14', 'VS2015', 'VC141', 'VS2017', 'VS2019', 'VS2022', 'MsBuild4', 'MsBuild', 'MsBuild12', 'MsBuild14', 'MsBuild141', 'MsBuild15', 'MsBuild16', 'MsBuild17', ], ), ( 'buildbot.steps.worker', [ 'SetPropertiesFromEnv', 'FileExists', 'CopyDirectory', 'RemoveDirectory', 'MakeDirectory', ], ), ], ), ( 'buildbot.reporters', [ ( 'buildbot.reporters.generators.build', ['BuildStatusGenerator', 'BuildStartEndStatusGenerator'], ), ('buildbot.reporters.generators.buildrequest', ['BuildRequestGenerator']), ( "buildbot.reporters.generators.buildset", [ "BuildSetCombinedStatusGenerator", "BuildSetStatusGenerator", ], ), ('buildbot.reporters.generators.worker', ['WorkerMissingGenerator']), ('buildbot.reporters.mail', ['MailNotifier']), ('buildbot.reporters.pushjet', ['PushjetNotifier']), ('buildbot.reporters.pushover', ['PushoverNotifier']), ( 'buildbot.reporters.message', [ 'MessageFormatter', 'MessageFormatterEmpty', 'MessageFormatterFunction', "MessageFormatterFunctionRaw", 'MessageFormatterMissingWorker', 'MessageFormatterRenderable', ], ), ('buildbot.reporters.gerrit', ['GerritStatusPush']), ('buildbot.reporters.gerrit_verify_status', ['GerritVerifyStatusPush']), ('buildbot.reporters.http', ['HttpStatusPush']), ('buildbot.reporters.github', ['GitHubStatusPush', 'GitHubCommentPush']), ('buildbot.reporters.gitlab', ['GitLabStatusPush']), ( 'buildbot.reporters.bitbucketserver', [ 'BitbucketServerStatusPush', 'BitbucketServerCoreAPIStatusPush', 'BitbucketServerPRCommentPush', ], ), ('buildbot.reporters.bitbucket', ['BitbucketStatusPush']), ('buildbot.reporters.irc', ['IRC']), ('buildbot.reporters.telegram', ['TelegramBot']), ('buildbot.reporters.zulip', ['ZulipStatusPush']), ], ), ( 'buildbot.util', [ # Connection seems to be a way too generic name, though ('buildbot.worker.libvirt', ['Connection']), ('buildbot.changes.filter', ['ChangeFilter']), ('buildbot.changes.gerritchangesource', ['GerritChangeFilter']), ( 'buildbot.changes.svnpoller', [ ('svn.split_file_projects_branches', 'split_file_projects_branches'), ('svn.split_file_branches', 'split_file_branches'), ('svn.split_file_alwaystrunk', 'split_file_alwaystrunk'), ], ), ('buildbot.configurators.janitor', ['JanitorConfigurator']), ('buildbot.config.builder', ['BuilderConfig']), ( 'buildbot.locks', [ 'MasterLock', 'WorkerLock', ], ), ( 'buildbot.manhole', ['AuthorizedKeysManhole', 'PasswordManhole', 'TelnetManhole'], ), ( 'buildbot.process.builder', [ 'enforceChosenWorker', ], ), ( 'buildbot.process.factory', [ 'BuildFactory', 'GNUAutoconf', 'CPAN', 'Distutils', 'Trial', 'BasicBuildFactory', 'QuickBuildFactory', 'BasicSVN', ], ), ('buildbot.process.logobserver', ['LogLineObserver']), ('buildbot.process.project', ['Project']), ( 'buildbot.process.properties', [ 'FlattenList', 'Interpolate', 'Property', 'Transform', 'WithProperties', 'renderer', 'Secret', ], ), ('buildbot.process.users.manual', ['CommandlineUserManager']), ('buildbot.revlinks', ['RevlinkMatch']), ('buildbot.reporters.utils', ['URLForBuild']), ('buildbot.schedulers.canceller', ['OldBuildCanceller']), ('buildbot.schedulers.canceller_buildset', ['FailingBuildsetCanceller']), ( 'buildbot.schedulers.forcesched', [ 'AnyPropertyParameter', 'BooleanParameter', 'ChoiceStringParameter', 'CodebaseParameter', 'FileParameter', 'FixedParameter', 'InheritBuildParameter', 'IntParameter', 'NestedParameter', 'ParameterGroup', 'PatchParameter', 'StringParameter', 'TextParameter', 'UserNameParameter', 'WorkerChoiceParameter', ], ), ( 'buildbot.process.results', [ 'Results', 'SUCCESS', 'WARNINGS', 'FAILURE', 'SKIPPED', 'EXCEPTION', 'RETRY', 'CANCELLED', ], ), ( 'buildbot.steps.source.repo', [ ('repo.DownloadsFromChangeSource', 'RepoDownloadsFromChangeSource'), ('repo.DownloadsFromProperties', 'RepoDownloadsFromProperties'), ], ), ('buildbot.steps.shellsequence', ['ShellArg']), ( 'buildbot.util.git_credential', ['GitCredentialInputRenderer', 'GitCredentialOptions'], ), ( 'buildbot.util.kubeclientservice', [ 'KubeHardcodedConfig', 'KubeCtlProxyConfigLoader', 'KubeInClusterConfigLoader', ], ), ('buildbot.util.ssfilter', ['SourceStampFilter']), ('buildbot.www.avatar', ['AvatarGravatar', 'AvatarGitHub']), ( 'buildbot.www.auth', ['UserPasswordAuth', 'HTPasswdAuth', 'RemoteUserAuth', 'CustomAuth'], ), ('buildbot.www.ldapuserinfo', ['LdapUserInfo']), ( 'buildbot.www.oauth2', ['GoogleAuth', 'GitHubAuth', 'GitLabAuth', 'BitbucketAuth'], ), ('buildbot.db.dbconfig', ['DbConfig']), ('buildbot.www.authz', ['Authz', 'fnmatchStrMatcher', 'reStrMatcher']), ( 'buildbot.www.authz.roles', [ 'RolesFromEmails', 'RolesFromGroups', 'RolesFromOwner', 'RolesFromUsername', 'RolesFromDomain', ], ), ( 'buildbot.www.authz.endpointmatchers', [ 'AnyEndpointMatcher', 'StopBuildEndpointMatcher', 'ForceBuildEndpointMatcher', 'RebuildBuildEndpointMatcher', 'AnyControlEndpointMatcher', 'EnableSchedulerEndpointMatcher', ], ), ], ), ( 'buildbot.webhooks', [ ('buildbot.www.hooks.base', ['base']), ('buildbot.www.hooks.bitbucket', ['bitbucket']), ('buildbot.www.hooks.github', ['github']), ('buildbot.www.hooks.gitlab', ['gitlab']), ('buildbot.www.hooks.gitorious', ['gitorious']), ('buildbot.www.hooks.poller', ['poller']), ('buildbot.www.hooks.bitbucketcloud', ['bitbucketcloud']), ('buildbot.www.hooks.bitbucketserver', ['bitbucketserver']), ], ), ]), { 'console_scripts': [ 'buildbot=buildbot.scripts.runner:run', # this will also be shipped on non windows :-( 'buildbot_windows_service=buildbot.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 py_38 = sys.version_info[0] > 3 or (sys.version_info[0] == 3 and sys.version_info[1] >= 8) if not py_38: raise RuntimeError("Buildbot master requires at least Python-3.8") twisted_ver = ">= 22.1.0" bundle_version = version.split("-")[0] # dependencies setup_args['install_requires'] = [ 'setuptools >= 8.0', 'Twisted ' + twisted_ver, 'treq >= 20.9', 'Jinja2 >= 2.1', 'msgpack >= 0.6.0', "croniter >= 1.3.0", 'importlib-resources >= 5; python_version < "3.9"', # required for tests, but Twisted requires this anyway 'zope.interface >= 4.1.1', 'sqlalchemy >= 1.4.0', 'alembic >= 1.6.0', 'python-dateutil>=1.5', "txaio >= 2.2.2", "autobahn >= 0.16.0", 'packaging', 'PyJWT', 'pyyaml', 'unidiff >= 0.7.5', ] # buildbot_windows_service needs pywin32 if sys.platform == "win32": setup_args['install_requires'].append('pywin32') # Unit test dependencies. test_deps = [ # http client libraries 'treq', 'txrequests', # pypugjs required for custom templates tests 'pypugjs', # boto3 and moto required for running EC2 tests 'boto3', 'moto', "Markdown>=3.0.0", 'parameterized', ] if sys.platform != 'win32': test_deps += [ # LZ4 fails to build on Windows: # https://github.com/steeve/python-lz4/issues/27 # lz4 required for log compression tests. 'lz4', ] setup_args['tests_require'] = test_deps setup_args['extras_require'] = { 'test': ["setuptools_trial", "ruff", *test_deps], 'bundle': [ f"buildbot-www=={bundle_version}", f"buildbot-worker=={bundle_version}", f"buildbot-waterfall-view=={bundle_version}", f"buildbot-console-view=={bundle_version}", f"buildbot-grid-view=={bundle_version}", ], 'tls': [ 'Twisted[tls] ' + twisted_ver, # There are bugs with extras inside extras: # <https://github.com/pypa/pip/issues/3516> # so we explicitly include Twisted[tls] dependencies. 'pyopenssl >= 16.0.0', 'service_identity', 'idna >= 0.6', ], 'docs': [ 'docutils>=0.16.0', 'sphinx>=3.2.0', 'sphinx-rtd-theme>=0.5', 'sphinxcontrib-spelling', 'sphinxcontrib-websupport', 'pyenchant', 'sphinx-jinja', 'towncrier', ], 'brotli': [ 'Brotli>=1.1.0', ], 'zstd': [ 'zstandard>=0.23.0', ], 'configurable': [ 'evalidate >= 2.0.0', ], } 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 if __name__ == '__main__': setup(**setup_args) # Local Variables: # fill-column: 71 # End:
28,994
Python
.py
719
23.986092
99
0.45215
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,231
pbutil.py
buildbot_buildbot/master/buildbot/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.internet import protocol from twisted.python import log from twisted.spread import pb from twisted.spread.pb import PBClientFactory from buildbot.util import bytes2unicode class NewCredPerspective(pb.Avatar): def attached(self, mind): return self def detached(self, mind): pass class ReconnectingPBClientFactory(PBClientFactory, protocol.ReconnectingClientFactory): """Reconnecting client factory for PB brokers. Like PBClientFactory, but if the connection fails or is lost, the factory will attempt to reconnect. Instead of using f.getRootObject (which gives a Deferred that can only be fired once), override the gotRootObject method. Instead of using the newcred f.login (which is also one-shot), call f.startLogin() with the credentials and client, and override the gotPerspective method. Instead of using the oldcred f.getPerspective (also one-shot), call f.startGettingPerspective() with the same arguments, and override gotPerspective. gotRootObject and gotPerspective will be called each time the object is received (once per successful connection attempt). You will probably want to use obj.notifyOnDisconnect to find out when the connection is lost. If an authorization error occurs, failedToGetPerspective() will be invoked. To use me, subclass, then hand an instance to a connector (like TCPClient). """ def __init__(self): super().__init__() self._doingLogin = False self._doingGetPerspective = False def clientConnectionFailed(self, connector, reason): super().clientConnectionFailed(connector, reason) # Twisted-1.3 erroneously abandons the connection on non-UserErrors. # To avoid this bug, don't upcall, and implement the correct version # of the method here. if self.continueTrying: self.connector = connector self.retry() def clientConnectionLost(self, connector, reason): super().clientConnectionLost(connector, reason, reconnecting=True) RCF = protocol.ReconnectingClientFactory RCF.clientConnectionLost(self, connector, reason) def clientConnectionMade(self, broker): self.resetDelay() super().clientConnectionMade(broker) if self._doingLogin: self.doLogin(self._root) if self._doingGetPerspective: self.doGetPerspective(self._root) self.gotRootObject(self._root) # oldcred methods def getPerspective(self, *args): raise RuntimeError("getPerspective is one-shot: use startGettingPerspective instead") def startGettingPerspective( self, username, password, serviceName, perspectiveName=None, client=None ): self._doingGetPerspective = True if perspectiveName is None: perspectiveName = username self._oldcredArgs = (username, password, serviceName, perspectiveName, client) def doGetPerspective(self, root): # oldcred getPerspective() (username, password, serviceName, perspectiveName, client) = self._oldcredArgs d = self._cbAuthIdentity(root, username, password) d.addCallback(self._cbGetPerspective, serviceName, perspectiveName, client) d.addCallbacks(self.gotPerspective, self.failedToGetPerspective) # newcred methods 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 self._doingLogin = True def doLogin(self, root): # newcred login() d = self._cbSendUsername( root, self._credentials.username, self._credentials.password, self._client ) d.addCallbacks(self.gotPerspective, self.failedToGetPerspective) # 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.""" def failedToGetPerspective(self, why): """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") if why.check(pb.PBConnectionLost): log.msg("we lost the brand-new connection") # retrying might help here, let clientConnectionLost decide return # probably authorization self.stopTrying() # logging in harder won't help log.err(why) 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 worker sends a dictionary back to a Python 3 master. """ 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
6,263
Python
.py
132
40.681818
93
0.716628
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,232
warnings.py
buildbot_buildbot/master/buildbot/warnings.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 warnings class ConfigWarning(Warning): """ Warning for issues in the configuration. Use DeprecatedApiWarning for deprecated APIs """ # DeprecationWarning or PendingDeprecationWarning may be used as # the base class, but by default deprecation warnings are disabled in Python, # so by default old-API usage warnings will be ignored - this is not what # we want. class DeprecatedApiWarning(Warning): """ Warning for deprecated configuration options. """ def warn_deprecated(version, msg, stacklevel=2): warnings.warn( f"[{version} and later] {msg}", category=DeprecatedApiWarning, stacklevel=stacklevel )
1,363
Python
.py
31
41.419355
92
0.77568
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,233
errors.py
buildbot_buildbot/master/buildbot/errors.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 # Having them here prevents all kind of circular dependencies class PluginDBError(Exception): pass class CaptureCallbackError(Exception): pass
862
Python
.py
19
43.631579
79
0.794504
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,234
asyncio.py
buildbot_buildbot/master/buildbot/asyncio.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. # # Alternatively, you can use and copy this module under the MIT License # Copyright Buildbot Team Members import asyncio import inspect from asyncio import base_events from asyncio import events from twisted.internet import defer def as_deferred(f): return asyncio.get_event_loop().as_deferred(f) def as_future(d): return d.asFuture(asyncio.get_event_loop()) class AsyncIOLoopWithTwisted(base_events.BaseEventLoop): """ Minimal asyncio loop for Buildbot asyncio only dependencies as of now, only graphql is needing asyncio loop As of now, it can only run basic coroutines, no network operation is supported But this could be implemented as needed """ def __init__(self, reactor): self._running = False self._reactor = reactor super().__init__() self._running = True def start(self): self._running = True events._set_running_loop(self) def stop(self): self._running = False events._set_running_loop(None) def is_running(self): return self._running def call_soon(self, callback, *args, context=None): handle = events.Handle(callback, args, self, context) self._reactor.callLater(0, handle._run) return handle def call_soon_threadsafe(self, callback, *args, context=None): handle = events.Handle(callback, args, self, context) self._reactor.callFromThread(handle._run) return handle def time(self): # we delegate timekeeping to the reactor so that it can be faked return self._reactor.seconds() def call_at(self, when, callback, *args, context=None): handle = events.Handle(callback, args, self, context) # Twisted timers are relatives, contrary to asyncio. delay = when - self.time() delay = max(delay, 0) self._reactor.callLater(delay, handle._run) return handle def as_deferred(self, thing): if isinstance(thing, defer.Deferred): return thing # check for coroutine objects if inspect.isawaitable(thing): return defer.Deferred.fromFuture(asyncio.ensure_future(thing)) return defer.succeed(thing)
2,897
Python
.py
69
36.188406
82
0.706239
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,235
buildrequest.py
buildbot_buildbot/master/buildbot/buildrequest.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.process.buildrequest import BuildRequest # noqa: F401
775
Python
.py
15
50.6
79
0.793149
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,236
interfaces.py
buildbot_buildbot/master/buildbot/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 """Interface documentation. Define the interfaces that are implemented by various buildbot classes. """ # disable pylint warnings triggered by interface definitions # pylint: disable=no-self-argument # pylint: disable=no-method-argument # pylint: disable=inherit-non-class from __future__ import annotations from typing import TYPE_CHECKING from typing import Any from zope.interface import Attribute from zope.interface import Interface if TYPE_CHECKING: from twisted.internet.defer import Deferred from buildbot.config.master import MasterConfig from buildbot.process.build import Build from buildbot.process.log import Log from buildbot.process.properties import Properties from buildbot.process.workerforbuilder import LatentWorkerForBuilder from buildbot.reporters.base import ReporterBase # exceptions that can be raised while trying to start a build class BuilderInUseError(Exception): pass class WorkerSetupError(Exception): pass class LatentWorkerFailedToSubstantiate(Exception): def __str__(self) -> str: return " ".join(str(arg) for arg in self.args) class LatentWorkerCannotSubstantiate(Exception): def __str__(self) -> str: return " ".join(str(arg) for arg in self.args) class LatentWorkerSubstantiatiationCancelled(Exception): def __str__(self) -> str: return " ".join(str(arg) for arg in self.args) class IPlugin(Interface): """ Base interface for all Buildbot plugins """ class IChangeSource(IPlugin): """ Service which feeds Change objects to the changemaster. When files or directories are changed in version control, this object should represent the changes as a change dictionary and call:: self.master.data.updates.addChange(who=.., rev=.., ..) See 'Writing Change Sources' in the manual for more information. """ master = Attribute('master', 'Pointer to BuildMaster, automatically set when started.') def describe() -> str: """Return a string which briefly describes this source.""" raise NotImplementedError class ISourceStamp(Interface): """ @cvar branch: branch from which source was drawn @type branch: string or None @cvar revision: revision of the source, or None to use CHANGES @type revision: varies depending on VC @cvar patch: patch applied to the source, or None if no patch @type patch: None or tuple (level diff) @cvar changes: the source step should check out the latest revision in the given changes @type changes: tuple of L{buildbot.changes.changes.Change} instances, all of which are on the same branch @cvar project: project this source code represents @type project: string @cvar repository: repository from which source was drawn @type repository: string """ def canBeMergedWith(other: ISourceStamp) -> bool: """ Can this SourceStamp be merged with OTHER? """ raise NotImplementedError def mergeWith(others: list[ISourceStamp]) -> ISourceStamp: """Generate a SourceStamp for the merger of me and all the other SourceStamps. This is called by a Build when it starts, to figure out what its sourceStamp should be.""" raise NotImplementedError def getAbsoluteSourceStamp(got_revision: str) -> ISourceStamp: """Get a new SourceStamp object reflecting the actual revision found by a Source step.""" raise NotImplementedError def getText() -> str: """Returns a list of strings to describe the stamp. These are intended to be displayed in a narrow column. If more space is available, the caller should join them together with spaces before presenting them to the user.""" raise NotImplementedError class IEmailSender(Interface): """I know how to send email, and can be used by other parts of the Buildbot to contact developers.""" class IEmailLookup(Interface): def getAddress(user: str) -> Deferred: """Turn a User-name string into a valid email address. Either return a string (with an @ in it), None (to indicate that the user cannot be reached by email), or a Deferred which will fire with the same.""" raise NotImplementedError class ILogObserver(Interface): """Objects which provide this interface can be used in a BuildStep to watch the output of a LogFile and parse it incrementally. """ # internal methods def setStep(step: IBuildStep) -> None: pass def setLog(log: Log) -> None: pass # methods called by the LogFile def logChunk(build: Build, step: IBuildStep, log: Log, channel: str, text: str) -> None: pass class IWorker(IPlugin): # callback methods from the manager pass class ILatentWorker(IWorker): """A worker that is not always running, but can run when requested.""" substantiated = Attribute( 'Substantiated', 'Whether the latent worker is currently substantiated with a real instance.', ) def substantiate(wfb: Any, build: Any) -> Deferred[Any]: """Request that the worker substantiate with a real instance. Returns a deferred that will callback when a real instance has attached.""" raise NotImplementedError # there is an insubstantiate too, but that is not used externally ATM. def buildStarted(wfb: LatentWorkerForBuilder) -> None: """Inform the latent worker that a build has started. @param wfb: a L{LatentWorkerForBuilder}. The wfb is the one for whom the build finished. """ raise NotImplementedError def buildFinished(wfb: LatentWorkerForBuilder) -> None: """Inform the latent worker that a build has finished. @param wfb: a L{LatentWorkerForBuilder}. The wfb is the one for whom the build finished. """ raise NotImplementedError class IMachine(Interface): pass class IMachineAction(Interface): def perform(manager: IMachine) -> Deferred: """Perform an action on the machine managed by manager. Returns a deferred evaluating to True if it was possible to execute the action. """ class ILatentMachine(IMachine): """A machine that is not always running, but can be started when requested.""" class IRenderable(Interface): """An object that can be interpolated with properties from a build.""" def getRenderingFor(iprops: IProperties) -> Deferred: """Return a deferred that fires with interpolation with the given properties @param iprops: the L{IProperties} provider supplying the properties. """ raise NotImplementedError class IProperties(Interface): """ An object providing access to build properties """ def getProperty(name: str, default: Any = None) -> object: """Get the named property, returning the default if the property does not exist. @param name: property name @type name: string @param default: default value (default: @code{None}) @returns: property value """ raise NotImplementedError def hasProperty(name: str) -> bool: """Return true if the named property exists. @param name: property name @type name: string @returns: boolean """ raise NotImplementedError def has_key(name: str) -> bool: """Deprecated name for L{hasProperty}.""" raise NotImplementedError def setProperty(name: str, value: object, source: str, runtime: bool = False) -> None: """Set the given property, overwriting any existing value. The source describes the source of the value for human interpretation. @param name: property name @type name: string @param value: property value @type value: JSON-able value @param source: property source @type source: string @param runtime: (optional) whether this property was set during the build's runtime: usually left at its default value @type runtime: boolean """ def getProperties() -> Properties: """Get the L{buildbot.process.properties.Properties} instance storing these properties. Note that the interface for this class is not stable, so where possible the other methods of this interface should be used. @returns: L{buildbot.process.properties.Properties} instance """ raise NotImplementedError def getBuild() -> Build: """Get the L{buildbot.process.build.Build} instance for the current build. Note that this object is not available after the build is complete, at which point this method will return None. Try to avoid using this method, as the API of L{Build} instances is not well-defined. @returns L{buildbot.process.build.Build} instance """ raise NotImplementedError def render(value: Any) -> IRenderable: """Render @code{value} as an L{IRenderable}. This essentially coerces @code{value} to an L{IRenderable} and calls its @L{getRenderingFor} method. @name value: value to render @returns: rendered value """ raise NotImplementedError class IScheduler(IPlugin): pass class ITriggerableScheduler(Interface): """ A scheduler that can be triggered by buildsteps. """ def trigger( waited_for, sourcestamps=None, set_props=None, parent_buildid=None, parent_relationship=None ): """Trigger a build with the given source stamp and properties.""" class IBuildStepFactory(Interface): def buildStep() -> None: pass class IBuildStep(IPlugin): """ A build step """ # Currently has nothing class IConfigured(Interface): def getConfigDict() -> dict[str, Any]: return {} # return something to silence warnings at call sites class IReportGenerator(Interface): def generate( master: IConfigured, reporter: ReporterBase, key: str, build: Build ) -> Deferred[None]: raise NotImplementedError class IConfigLoader(Interface): def loadConfig() -> MasterConfig: """ Load the specified configuration. :return MasterConfig: """ raise NotImplementedError class IHttpResponse(Interface): def content() -> Deferred: """ :returns: raw (``bytes``) content of the response via deferred """ raise NotImplementedError def json() -> Deferred: """ :returns: json decoded content of the response via deferred """ raise NotImplementedError code = Attribute('code', "http status code of the request's response (e.g 200)") url = Attribute('url', "request's url (e.g https://api.github.com/endpoint')") class IConfigurator(Interface): def configure(config_dict: dict[str, Any]) -> None: """ Alter the buildbot config_dict, as defined in master.cfg like the master.cfg, this is run out of the main reactor thread, so this can block, but this can't call most Buildbot facilities. :returns: None """ raise NotImplementedError
12,073
Python
.py
282
36.255319
100
0.69827
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,237
__init__.py
buildbot_buildbot/master/buildbot/__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 # # 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 and 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 f"{major}.{minor}.{patch}.post{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, encoding='utf-8') 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,713
Python
.py
109
36.724771
114
0.66208
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,238
scheduler.py
buildbot_buildbot/master/buildbot/scheduler.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.schedulers.basic import AnyBranchScheduler from buildbot.schedulers.basic import Scheduler from buildbot.schedulers.dependent import Dependent from buildbot.schedulers.timed import Nightly from buildbot.schedulers.timed import Periodic from buildbot.schedulers.triggerable import Triggerable from buildbot.schedulers.trysched import Try_Jobdir from buildbot.schedulers.trysched import Try_Userpass _hush_pyflakes = [ Scheduler, AnyBranchScheduler, Dependent, Periodic, Nightly, Triggerable, Try_Jobdir, Try_Userpass, ] del _hush_pyflakes
1,292
Python
.py
33
37.090909
79
0.808917
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,239
manhole.py
buildbot_buildbot/master/buildbot/manhole.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 binascii import os import types from typing import ClassVar from typing import Sequence from twisted.application import strports from twisted.conch import manhole from twisted.conch import telnet from twisted.conch.insults import insults from twisted.cred import checkers from twisted.cred import portal from twisted.internet import protocol from twisted.python import log from zope.interface import implementer # requires Twisted-2.0 or later from buildbot import config from buildbot.util import ComparableMixin from buildbot.util import service from buildbot.util import unicode2bytes try: from twisted.conch import manhole_ssh from twisted.conch.checkers import SSHPublicKeyDatabase from twisted.conch.openssh_compat.factory import OpenSSHFactory except ImportError: manhole_ssh = None # type: ignore OpenSSHFactory = None # type: ignore SSHPublicKeyDatabase = None # type: ignore # makeTelnetProtocol and _TelnetRealm are for the TelnetManhole class makeTelnetProtocol: # this curries the 'portal' argument into a later call to # TelnetTransport() def __init__(self, portal): self.portal = portal def __call__(self): auth = telnet.AuthenticatingTelnetProtocol return telnet.TelnetTransport(auth, self.portal) @implementer(portal.IRealm) class _TelnetRealm: def __init__(self, namespace_maker): self.namespace_maker = namespace_maker def requestAvatar(self, avatarId, *interfaces): if telnet.ITelnetProtocol in interfaces: namespace = self.namespace_maker() p = telnet.TelnetBootstrapProtocol( insults.ServerProtocol, manhole.ColoredManhole, namespace ) return (telnet.ITelnetProtocol, p, lambda: None) raise NotImplementedError() class chainedProtocolFactory: # this curries the 'namespace' argument into a later call to # chainedProtocolFactory() def __init__(self, namespace): self.namespace = namespace def __call__(self): return insults.ServerProtocol(manhole.ColoredManhole, self.namespace) if SSHPublicKeyDatabase is not None: class AuthorizedKeysChecker(SSHPublicKeyDatabase): """Accept connections using SSH keys from a given file. SSHPublicKeyDatabase takes the username that the prospective client has requested and attempts to get a ~/.ssh/authorized_keys file for that username. This requires root access, so it isn't as useful as you'd like. Instead, this subclass looks for keys in a single file, given as an argument. This file is typically kept in the buildmaster's basedir. The file should have 'ssh-dss ....' lines in it, just like authorized_keys. """ def __init__(self, authorized_keys_file): self.authorized_keys_file = os.path.expanduser(authorized_keys_file) def checkKey(self, credentials): with open(self.authorized_keys_file, "rb") as f: for l in f.readlines(): l2 = l.split() if len(l2) < 2: continue try: if base64.decodebytes(l2[1]) == credentials.blob: return 1 except binascii.Error: continue return 0 class _BaseManhole(service.AsyncMultiService): """This provides remote access to a python interpreter (a read/exec/print loop) embedded in the buildmaster via an internal SSH server. This allows detailed inspection of the buildmaster state. It is of most use to buildbot developers. Connect to this by running an ssh client. """ def __init__(self, port, checker, ssh_hostkey_dir=None): """ @type port: string or int @param port: what port should the Manhole listen on? This is a strports specification string, like 'tcp:12345' or 'tcp:12345:interface=127.0.0.1'. Bare integers are treated as a simple tcp port. @type checker: an object providing the L{twisted.cred.checkers.ICredentialsChecker} interface @param checker: if provided, this checker is used to authenticate the client instead of using the username/password scheme. You must either provide a username/password or a Checker. Some useful values are:: import twisted.cred.checkers as credc import twisted.conch.checkers as conchc c = credc.AllowAnonymousAccess # completely open c = credc.FilePasswordDB(passwd_filename) # file of name:passwd c = conchc.UNIXPasswordDatabase # getpwnam() (probably /etc/passwd) @type ssh_hostkey_dir: str @param ssh_hostkey_dir: directory which contains ssh host keys for this server """ # unfortunately, these don't work unless we're running as root # c = credc.PluggableAuthenticationModulesChecker: PAM # c = conchc.SSHPublicKeyDatabase() # ~/.ssh/authorized_keys # and I can't get UNIXPasswordDatabase to work super().__init__() if isinstance(port, int): port = f"tcp:{port}" self.port = port # for comparison later self.checker = checker # to maybe compare later def makeNamespace(): master = self.master namespace = { 'master': master, 'show': show, } return namespace def makeProtocol(): namespace = makeNamespace() p = insults.ServerProtocol(manhole.ColoredManhole, namespace) return p self.ssh_hostkey_dir = ssh_hostkey_dir if self.ssh_hostkey_dir: self.using_ssh = True if not self.ssh_hostkey_dir: raise ValueError("Most specify a value for ssh_hostkey_dir") assert manhole_ssh is not None, "cryptography required for ssh mahole." r = manhole_ssh.TerminalRealm() r.chainedProtocolFactory = makeProtocol p = portal.Portal(r, [self.checker]) f = manhole_ssh.ConchFactory(p) assert OpenSSHFactory is not None, "cryptography required for ssh mahole." openSSHFactory = OpenSSHFactory() openSSHFactory.dataRoot = self.ssh_hostkey_dir openSSHFactory.dataModuliRoot = self.ssh_hostkey_dir f.publicKeys = openSSHFactory.getPublicKeys() f.privateKeys = openSSHFactory.getPrivateKeys() else: self.using_ssh = False r = _TelnetRealm(makeNamespace) p = portal.Portal(r, [self.checker]) f = protocol.ServerFactory() f.protocol = makeTelnetProtocol(p) s = strports.service(self.port, f) s.setServiceParent(self) def startService(self): if self.using_ssh: via = "via SSH" else: via = "via telnet" log.msg(f"Manhole listening {via} on port {self.port}") return super().startService() class TelnetManhole(_BaseManhole, ComparableMixin): compare_attrs: ClassVar[Sequence[str]] = ("port", "username", "password") def __init__(self, port, username, password): self.username = username self.password = password c = checkers.InMemoryUsernamePasswordDatabaseDontUse() c.addUser(unicode2bytes(username), unicode2bytes(password)) super().__init__(port, c) class PasswordManhole(_BaseManhole, ComparableMixin): compare_attrs: ClassVar[Sequence[str]] = ("port", "username", "password", "ssh_hostkey_dir") def __init__(self, port, username, password, ssh_hostkey_dir): if not manhole_ssh: config.error("cryptography required for ssh mahole.") self.username = username self.password = password self.ssh_hostkey_dir = ssh_hostkey_dir c = checkers.InMemoryUsernamePasswordDatabaseDontUse() c.addUser(unicode2bytes(username), unicode2bytes(password)) super().__init__(port, c, ssh_hostkey_dir) class AuthorizedKeysManhole(_BaseManhole, ComparableMixin): compare_attrs: ClassVar[Sequence[str]] = ("port", "keyfile", "ssh_hostkey_dir") def __init__(self, port, keyfile, ssh_hostkey_dir): if not manhole_ssh: config.error("cryptography required for ssh mahole.") # TODO: expanduser this, and make it relative to the buildmaster's # basedir self.keyfile = keyfile c = AuthorizedKeysChecker(keyfile) super().__init__(port, c, ssh_hostkey_dir) class ArbitraryCheckerManhole(_BaseManhole, ComparableMixin): """This Manhole accepts ssh connections, but uses an arbitrary user-supplied 'checker' object to perform authentication.""" compare_attrs: ClassVar[Sequence[str]] = ("port", "checker") def __init__(self, port, checker): """ @type port: string or int @param port: what port should the Manhole listen on? This is a strports specification string, like 'tcp:12345' or 'tcp:12345:interface=127.0.0.1'. Bare integers are treated as a simple tcp port. @param checker: an instance of a twisted.cred 'checker' which will perform authentication """ if not manhole_ssh: config.error("cryptography required for ssh mahole.") super().__init__(port, checker) # utility functions for the manhole def show(x): """Display the data attributes of an object in a readable format""" print(f"data attributes of {x!r}") names = dir(x) maxlen = max([0] + [len(n) for n in names]) for k in names: v = getattr(x, k) if isinstance(v, types.MethodType): continue if k[:2] == '__' and k[-2:] == '__': continue if isinstance(v, str): if len(v) > 80 - maxlen - 5: v = repr(v[: 80 - maxlen - 5]) + "..." elif isinstance(v, (int, type(None))): v = str(v) elif isinstance(v, (list, tuple, dict)): v = f"{v} ({len(v)} elements)" else: v = str(type(v)) print(f"{k.ljust(maxlen)} : {v}") return x
11,045
Python
.py
241
37.178423
96
0.658507
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,240
revlinks.py
buildbot_buildbot/master/buildbot/revlinks.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 class RevlinkMatch: def __init__(self, repo_urls, revlink): if isinstance(repo_urls, str): repo_urls = [repo_urls] self.repo_urls = [re.compile(url) for url in repo_urls] self.revlink = revlink def __call__(self, rev, repo): for url in self.repo_urls: m = url.match(repo) if m: return m.expand(self.revlink) % rev return None GithubRevlink = RevlinkMatch( repo_urls=[ r'https://github.com/([^/]*)/([^/]*?)(?:\.git)?$', r'git://github.com/([^/]*)/([^/]*?)(?:\.git)?$', r'[email protected]:([^/]*)/([^/]*?)(?:\.git)?$', r'ssh://[email protected]/([^/]*)/([^/]*?)(?:\.git)?$', ], revlink=r'https://github.com/\1/\2/commit/%s', ) BitbucketRevlink = RevlinkMatch( repo_urls=[ r'https://[^@]*@bitbucket.org/([^/]*)/([^/]*?)(?:\.git)?$', r'[email protected]:([^/]*)/([^/]*?)(?:\.git)?$', ], revlink=r'https://bitbucket.org/\1/\2/commits/%s', ) class GitwebMatch(RevlinkMatch): def __init__(self, repo_urls, revlink): super().__init__(repo_urls=repo_urls, revlink=revlink + r'?p=\g<repo>;a=commit;h=%s') SourceforgeGitRevlink = GitwebMatch( repo_urls=[ r'^git://([^.]*).git.sourceforge.net/gitroot/(?P<repo>.*)$', r'[^@]*@([^.]*).git.sourceforge.net:gitroot/(?P<repo>.*)$', r'ssh://(?:[^@]*@)?([^.]*).git.sourceforge.net/gitroot/(?P<repo>.*)$', ], revlink=r'http://\1.git.sourceforge.net/git/gitweb.cgi', ) # SourceForge recently upgraded to another platform called Allura # See introduction: # https://sourceforge.net/p/forge/documentation/Classic%20vs%20New%20SourceForge%20projects/ # And as reference: # https://sourceforge.net/p/forge/community-docs/SVN%20and%20project%20upgrades/ SourceforgeGitRevlink_AlluraPlatform = RevlinkMatch( repo_urls=[ r'git://git.code.sf.net/p/(?P<repo>.*)$', r'http://git.code.sf.net/p/(?P<repo>.*)$', r'ssh://(?:[^@]*@)?git.code.sf.net/p/(?P<repo>.*)$', ], revlink=r'https://sourceforge.net/p/\1/ci/%s/', ) class RevlinkMultiplexer: def __init__(self, *revlinks): self.revlinks = revlinks def __call__(self, rev, repo): for revlink in self.revlinks: url = revlink(rev, repo) if url: return url return None default_revlink_matcher = RevlinkMultiplexer( GithubRevlink, BitbucketRevlink, SourceforgeGitRevlink, SourceforgeGitRevlink_AlluraPlatform )
3,234
Python
.py
79
35.506329
96
0.626395
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,241
buildbot_net_usage_data.py
buildbot_buildbot/master/buildbot/buildbot_net_usage_data.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 files implement buildbotNetUsageData options It uses urllib instead of requests in order to avoid requiring another dependency for statistics feature. urllib supports http_proxy already. urllib is blocking and thus everything is done from a thread. """ import hashlib import inspect import json import os import platform import socket from urllib import error as urllib_error from urllib import request as urllib_request from twisted.internet import threads from twisted.python import log from buildbot.process.buildstep import _BuildStepFactory from buildbot.util import unicode2bytes from buildbot.www.config import get_environment_versions # This can't change! or we will need to make sure we are compatible with all # released version of buildbot >=0.9.0 PHONE_HOME_URL = "https://events.buildbot.net/events/phone_home" def linux_distribution(): os_release = "/etc/os-release" meta_data = {} if os.path.exists(os_release): with open("/etc/os-release", encoding='utf-8') as f: for line in f: try: k, v = line.strip().split("=") meta_data[k] = v.strip('"') except Exception: pass linux_id = meta_data.get("ID", "unknown_linux") linux_version = "unknown_version" # Pre-release versions of Debian contain VERSION_CODENAME but not VERSION_ID for version_key in ["VERSION_ID", "VERSION_CODENAME"]: linux_version = meta_data.get(version_key, linux_version) return linux_id, linux_version def get_distro(): system = platform.system() if system == "Linux": dist = linux_distribution() return f"{dist[0]}:{dist[1]}" elif system == "Windows": dist = platform.win32_ver() return f"{dist[0]}:{dist[1]}" elif system == "Java": dist = platform.java_ver() return f"{dist[0]}:{dist[1]}" elif system == "Darwin": dist = platform.mac_ver() return f"{dist[0]}" # else: return ":".join(platform.uname()[0:1]) def getName(obj): """This method finds the first parent class which is within the buildbot namespace it prepends the name with as many ">" as the class is subclassed """ # elastic search does not like '.' in dict keys, so we replace by / def sanitize(name): return name.replace(".", "/") if isinstance(obj, _BuildStepFactory): klass = obj.step_class else: klass = type(obj) name = "" klasses = (klass, *inspect.getmro(klass)) for klass in klasses: if hasattr(klass, "__module__") and klass.__module__.startswith("buildbot."): return sanitize(name + klass.__module__ + "." + klass.__name__) else: name += ">" return sanitize(type(obj).__name__) def countPlugins(plugins_uses, lst): if isinstance(lst, dict): lst = lst.values() for i in lst: name = getName(i) plugins_uses.setdefault(name, 0) plugins_uses[name] += 1 def basicData(master): plugins_uses = {} countPlugins(plugins_uses, master.config.workers) countPlugins(plugins_uses, master.config.builders) countPlugins(plugins_uses, master.config.schedulers) countPlugins(plugins_uses, master.config.services) countPlugins(plugins_uses, master.config.change_sources) for b in master.config.builders: countPlugins(plugins_uses, b.factory.steps) # we hash the master's name + various other master dependent variables # to get as much as possible an unique id # we hash it to not leak private information about the installation such as hostnames and domain # names hashInput = ( master.name # master name contains hostname + master basepath + socket.getfqdn() # we add the fqdn to account for people # call their buildbot host 'buildbot' # and install it in /var/lib/buildbot ) hashInput = unicode2bytes(hashInput) installid = hashlib.sha1(hashInput).hexdigest() return { 'installid': installid, 'versions': dict(get_environment_versions()), 'platform': { 'platform': platform.platform(), 'system': platform.system(), 'machine': platform.machine(), 'processor': platform.processor(), 'python_implementation': platform.python_implementation(), # xBSD including osx will disclose too much information after [4] like where it # was built 'version': " ".join(platform.version().split(' ')[:4]), 'distro': get_distro(), }, 'plugins': plugins_uses, 'db': master.config.db['db_url'].split("://")[0], 'mq': master.config.mq['type'], 'www_plugins': list(master.config.www['plugins'].keys()), } def fullData(master): """ Send the actual configuration of the builders, how the steps are agenced. Note that full data will never send actual detail of what command is run, name of servers, etc. """ builders = [] for b in master.config.builders: steps = [] for step in b.factory.steps: steps.append(getName(step)) builders.append(steps) return {'builders': builders} def computeUsageData(master): if master.config.buildbotNetUsageData is None: return None data = basicData(master) if master.config.buildbotNetUsageData != "basic": data.update(fullData(master)) if callable(master.config.buildbotNetUsageData): data = master.config.buildbotNetUsageData(data) return data def _sendWithUrlib(url, data): data = json.dumps(data).encode() clen = len(data) req = urllib_request.Request( url, data, {'Content-Type': 'application/json', 'Content-Length': clen} ) try: f = urllib_request.urlopen(req) except urllib_error.URLError: return None res = f.read() f.close() return res def _sendWithRequests(url, data): try: import requests # pylint: disable=import-outside-toplevel except ImportError: return None r = requests.post(url, json=data, timeout=30) return r.text def _sendBuildbotNetUsageData(data): log.msg(f"buildbotNetUsageData: sending {data}") # first try with requests, as this is the most stable http library res = _sendWithRequests(PHONE_HOME_URL, data) # then we try with stdlib, which not always work with https if res is None: res = _sendWithUrlib(PHONE_HOME_URL, data) # at last stage if res is None: log.msg( "buildbotNetUsageData: Could not send using https, " "please `pip install 'requests[security]'` for proper SSL implementation`" ) data['buggySSL'] = True res = _sendWithUrlib(PHONE_HOME_URL.replace("https://", "http://"), data) log.msg("buildbotNetUsageData: buildbot.net said:", res) def sendBuildbotNetUsageData(master): if master.config.buildbotNetUsageData is None: return data = computeUsageData(master) if data is None: return threads.deferToThread(_sendBuildbotNetUsageData, data)
7,891
Python
.py
200
33.245
100
0.671501
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,242
locks.py
buildbot_buildbot/master/buildbot/locks.py
# This file is part of Buildbot. Buildbot is free software: you can # redistribute it and/or modify it under the terms of the GNU General Public # License as published by the Free Software Foundation, version 2. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more # details. # # You should have received a copy of the GNU General Public License along with # this program; if not, write to the Free Software Foundation, Inc., 51 # Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # Copyright Buildbot Team Members from typing import ClassVar from typing import Sequence from twisted.internet import defer from twisted.python import log from buildbot import util from buildbot.util import service from buildbot.util import subscription from buildbot.util.eventual import eventually if False: # for debugging pylint: disable=using-constant-test debuglog = log.msg else: debuglog = lambda m: None class BaseLock: """ Class handling claiming and releasing of L{self}, and keeping track of current and waiting owners. We maintain the wait queue in FIFO order, and ensure that counting waiters in the queue behind exclusive waiters cannot acquire the lock. This ensures that exclusive waiters are not starved. """ description = "<BaseLock>" def __init__(self, name, maxCount=1): super().__init__() # Name of the lock self.lockName = name # Current queue, tuples (waiter_id, LockAccess, deferred) self.waiting = [] # Current owners, tuples (owner_id, LockAccess) self.owners = [] # maximal number of counting owners self.maxCount = maxCount # current number of claimed exclusive locks (0 or 1), must match # self.owners self._claimed_excl = 0 # current number of claimed counting locks (0 to self.maxCount), must # match self.owners. Note that self.maxCount is not a strict limit, the # number of claimed counting locks may be higher than self.maxCount if # it was lowered by self._claimed_counting = 0 # subscriptions to this lock being released self.release_subs = subscription.SubscriptionPoint(f"{self!r} releases") def __repr__(self): return self.description def setMaxCount(self, count): old_max_count = self.maxCount self.maxCount = count if count > old_max_count: self._tryWakeUp() def _find_waiting(self, requester): for idx, waiter in enumerate(self.waiting): if waiter[0] == id(requester): return idx return None def isAvailable(self, requester, access): """Return a boolean whether the lock is available for claiming""" debuglog(f"{self} isAvailable({requester}, {access}): self.owners={self.owners!r}") num_excl = self._claimed_excl num_counting = self._claimed_counting if not access.count: return True w_index = self._find_waiting(requester) if w_index is None: w_index = len(self.waiting) ahead = self.waiting[:w_index] if access.mode == 'counting': # Wants counting access return ( not num_excl and num_counting + len(ahead) + access.count <= self.maxCount and all(w[1].mode == 'counting' for w in ahead) ) # else Wants exclusive access return not num_excl and not num_counting and not ahead def _addOwner(self, owner, access): self.owners.append((id(owner), access)) if access.mode == 'counting': self._claimed_counting += access.count else: self._claimed_excl += 1 assert (self._claimed_excl and not self._claimed_counting) or ( not self._claimed_excl and self._claimed_excl <= self.maxCount ) def _removeOwner(self, owner, access): # returns True if owner removed, False if the lock has been already # released entry = (id(owner), access) if entry not in self.owners: return False self.owners.remove(entry) if access.mode == 'counting': self._claimed_counting -= access.count else: self._claimed_excl -= 1 return True def claim(self, owner, access): """Claim the lock (lock must be available)""" debuglog(f"{self} claim({owner}, {access.mode})") assert owner is not None assert self.isAvailable(owner, access), "ask for isAvailable() first" assert isinstance(access, LockAccess) assert access.mode in ['counting', 'exclusive'] assert isinstance(access.count, int) if access.mode == 'exclusive': assert access.count == 1 else: assert access.count >= 0 if not access.count: return self.waiting = [w for w in self.waiting if w[0] != id(owner)] self._addOwner(owner, access) debuglog(f" {self} is claimed '{access.mode}', {access.count} units") def subscribeToReleases(self, callback): """Schedule C{callback} to be invoked every time this lock is released. Returns a L{Subscription}.""" return self.release_subs.subscribe(callback) def release(self, owner, access): """Release the lock""" assert isinstance(access, LockAccess) if not access.count: return debuglog(f"{self} release({owner}, {access.mode}, {access.count})") if not self._removeOwner(owner, access): debuglog(f"{self} already released") return self._tryWakeUp() # notify any listeners self.release_subs.deliver() def _tryWakeUp(self): # After an exclusive access, we may need to wake up several waiting. # Break out of the loop when the first waiting client should not be # awakened. num_excl, num_counting = self._claimed_excl, self._claimed_counting for i, (w_owner_id, w_access, d) in enumerate(self.waiting): if w_access.mode == 'counting': if num_excl > 0 or num_counting >= self.maxCount: break num_counting = num_counting + w_access.count else: # w_access.mode == 'exclusive' if num_excl > 0 or num_counting > 0: break num_excl = num_excl + w_access.count # If the waiter has a deferred, wake it up and clear the deferred # from the wait queue entry to indicate that it has been woken. if d: self.waiting[i] = (w_owner_id, w_access, None) eventually(d.callback, self) def waitUntilMaybeAvailable(self, owner, access): """Fire when the lock *might* be available. The deferred may be fired spuriously and the lock is not necessarily available, thus the caller will need to check with isAvailable() when the deferred fires. A single requester must not have more than one pending waitUntilMaybeAvailable() on a single lock. The caller must guarantee, that once the returned deferred is fired, either the lock is checked for availability and claimed if it's available, or the it is indicated as no longer interesting by calling stopWaitingUntilAvailable(). The caller does not need to do this immediately after deferred is fired, an eventual execution is sufficient. """ debuglog(f"{self} waitUntilAvailable({owner})") assert isinstance(access, LockAccess) if self.isAvailable(owner, access): return defer.succeed(self) d = defer.Deferred() # Are we already in the wait queue? w_index = self._find_waiting(owner) if w_index is not None: _, _, old_d = self.waiting[w_index] assert old_d is None, ( "waitUntilMaybeAvailable() must not be called again before the " "previous deferred fired" ) self.waiting[w_index] = (id(owner), access, d) else: self.waiting.append((id(owner), access, d)) return d def stopWaitingUntilAvailable(self, owner, access, d): """Stop waiting for lock to become available. `d` must be the result of a previous call to `waitUntilMaybeAvailable()`. If `d` has not been woken up already by calling its callback, it will be done as part of this function """ debuglog(f"{self} stopWaitingUntilAvailable({owner})") assert isinstance(access, LockAccess) w_index = self._find_waiting(owner) assert w_index is not None, "The owner was not waiting for the lock" _, _, old_d = self.waiting[w_index] if old_d is not None: assert d is old_d, "The supplied deferred must be a result of waitUntilMaybeAvailable()" del self.waiting[w_index] d.callback(None) else: del self.waiting[w_index] # if the callback has already been woken up, then it must schedule another waiter, # otherwise we will have an available lock with a waiter list and no-one to wake the # waiters up. self._tryWakeUp() def isOwner(self, owner, access): return (id(owner), access) in self.owners class RealMasterLock(BaseLock, service.SharedService): def __init__(self, name): # the caller will want to call updateFromLockId after initialization super().__init__(name, 0) self.config_version = -1 self._updateDescription() def _updateDescription(self): self.description = f"<MasterLock({self.lockName}, {self.maxCount})>" def getLockForWorker(self, workername): return self def updateFromLockId(self, lockid, config_version): assert self.lockName == lockid.name assert isinstance(config_version, int) self.config_version = config_version self.setMaxCount(lockid.maxCount) self._updateDescription() class RealWorkerLock(service.SharedService): def __init__(self, name): super().__init__() # the caller will want to call updateFromLockId after initialization self.lockName = name self.maxCount = None self.maxCountForWorker = None self.config_version = -1 self._updateDescription() self.locks = {} def __repr__(self): return self.description def getLockForWorker(self, workername): if workername not in self.locks: maxCount = self.maxCountForWorker.get(workername, self.maxCount) lock = self.locks[workername] = BaseLock(self.lockName, maxCount) self._updateDescriptionForLock(lock, workername) self.locks[workername] = lock return self.locks[workername] def _updateDescription(self): self.description = ( f"<WorkerLock({self.lockName}, {self.maxCount}, {self.maxCountForWorker})>" ) def _updateDescriptionForLock(self, lock, workername): lock.description = ( f"<WorkerLock({lock.lockName}, {lock.maxCount})[{workername}] {id(lock)}>" ) def updateFromLockId(self, lockid, config_version): assert self.lockName == lockid.name assert isinstance(config_version, int) self.config_version = config_version self.maxCount = lockid.maxCount self.maxCountForWorker = lockid.maxCountForWorker self._updateDescription() for workername, lock in self.locks.items(): maxCount = self.maxCountForWorker.get(workername, self.maxCount) lock.setMaxCount(maxCount) self._updateDescriptionForLock(lock, workername) class LockAccess(util.ComparableMixin): """I am an object representing a way to access a lock. @param lockid: LockId instance that should be accessed. @type lockid: A MasterLock or WorkerLock instance. @param mode: Mode of accessing the lock. @type mode: A string, either 'counting' or 'exclusive'. @param count: How many units does the access occupy @type count: Integer, not negative, default is 1 for backwards compatibility """ compare_attrs: ClassVar[Sequence[str]] = ('lockid', 'mode', 'count') def __init__(self, lockid, mode, count=1): self.lockid = lockid self.mode = mode self.count = count assert isinstance(lockid, (MasterLock, WorkerLock)) assert mode in ['counting', 'exclusive'] assert isinstance(count, int) if mode == 'exclusive': assert count == 1 else: assert count >= 0 class BaseLockId(util.ComparableMixin): """Abstract base class for LockId classes. Sets up the 'access()' function for the LockId's available to the user (MasterLock and WorkerLock classes). Derived classes should add - Comparison with the L{util.ComparableMixin} via the L{compare_attrs} class variable. - Link to the actual lock class should be added with the L{lockClass} class variable. """ def access(self, mode, count=1): """Express how the lock should be accessed""" assert mode in ['counting', 'exclusive'] assert isinstance(count, int) assert count >= 0 return LockAccess(self, mode, count) def defaultAccess(self): """For buildbot 0.7.7 compatibility: When user doesn't specify an access mode, this one is chosen. """ return self.access('counting') # master.cfg should only reference the following MasterLock and WorkerLock # classes. They are identifiers that will be turned into real Locks later, # via the BotMaster.getLockByID method. class MasterLock(BaseLockId): """I am a semaphore that limits the number of simultaneous actions. Builds and BuildSteps can declare that they wish to claim me as they run. Only a limited number of such builds or steps will be able to run simultaneously. By default this number is one, but my maxCount parameter can be raised to allow two or three or more operations to happen at the same time. Use this to protect a resource that is shared among all builders and all workers, for example to limit the load on a common SVN repository. """ compare_attrs: ClassVar[Sequence[str]] = ('name', 'maxCount') lockClass = RealMasterLock def __init__(self, name, maxCount=1): self.name = name self.maxCount = maxCount class WorkerLock(BaseLockId): """I am a semaphore that limits simultaneous actions on each worker. Builds and BuildSteps can declare that they wish to claim me as they run. Only a limited number of such builds or steps will be able to run simultaneously on any given worker. By default this number is one, but my maxCount parameter can be raised to allow two or three or more operations to happen on a single worker at the same time. Use this to protect a resource that is shared among all the builds taking place on each worker, for example to limit CPU or memory load on an underpowered machine. Each worker will get an independent copy of this semaphore. By default each copy will use the same owner count (set with maxCount), but you can provide maxCountForWorker with a dictionary that maps workername to owner count, to allow some workers more parallelism than others. """ compare_attrs: ClassVar[Sequence[str]] = ('name', 'maxCount', '_maxCountForWorkerList') lockClass = RealWorkerLock def __init__(self, name, maxCount=1, maxCountForWorker=None): self.name = name self.maxCount = maxCount if maxCountForWorker is None: maxCountForWorker = {} self.maxCountForWorker = maxCountForWorker # for comparison purposes, turn this dictionary into a stably-sorted # list of tuples self._maxCountForWorkerList = tuple(sorted(self.maxCountForWorker.items()))
16,385
Python
.py
352
38.048295
100
0.659349
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,243
master.py
buildbot_buildbot/master/buildbot/master.py
# This file is part of Buildbot. Buildbot is free software: you can # redistribute it and/or modify it under the terms of the GNU General Public # License as published by the Free Software Foundation, version 2. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more # details. # # You should have received a copy of the GNU General Public License along with # this program; if not, write to the Free Software Foundation, Inc., 51 # Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # Copyright Buildbot Team Members import os import signal import socket from twisted.application import internet from twisted.internet import defer from twisted.internet import task from twisted.internet import threads from twisted.python import failure from twisted.python import log import buildbot from buildbot import config from buildbot import monkeypatches from buildbot.buildbot_net_usage_data import sendBuildbotNetUsageData from buildbot.changes.manager import ChangeManager from buildbot.config.master import FileLoader from buildbot.config.master import MasterConfig from buildbot.data import connector as dataconnector from buildbot.data import graphql from buildbot.db import connector as dbconnector from buildbot.db import exceptions from buildbot.machine.manager import MachineManager from buildbot.mq import connector as mqconnector from buildbot.process import cache from buildbot.process import debug from buildbot.process import metrics from buildbot.process.botmaster import BotMaster from buildbot.process.users.manager import UserManagerManager from buildbot.schedulers.manager import SchedulerManager from buildbot.secrets.manager import SecretManager from buildbot.util import check_functional_environment from buildbot.util import httpclientservice from buildbot.util import service from buildbot.util.eventual import eventually from buildbot.wamp import connector as wampconnector from buildbot.worker import manager as workermanager from buildbot.worker.protocols.manager.msgpack import MsgManager from buildbot.worker.protocols.manager.pb import PBManager from buildbot.www import service as wwwservice class LogRotation: def __init__(self): self.rotateLength = 1 * 1000 * 1000 self.maxRotatedFiles = 10 class BuildMaster(service.ReconfigurableServiceMixin, service.MasterService): # multiplier on RECLAIM_BUILD_INTERVAL at which a build is considered # unclaimed; this should be at least 2 to avoid false positives UNCLAIMED_BUILD_FACTOR = 6 def __init__(self, basedir, configFileName=None, umask=None, reactor=None, config_loader=None): super().__init__() if reactor is None: from twisted.internet import reactor self.reactor = reactor self.setName("buildmaster") self.umask = umask self.basedir = basedir if basedir is not None: # None is used in tests assert os.path.isdir(self.basedir) if config_loader is not None and configFileName is not None: raise config.ConfigErrors([ "Can't specify both `config_loader` and `configFilename`.", ]) if config_loader is None: if configFileName is None: configFileName = 'master.cfg' config_loader = FileLoader(self.basedir, configFileName) self.config_loader = config_loader self.configFileName = configFileName # flag so we don't try to do fancy things before the master is ready self._master_initialized = False self.initLock = defer.DeferredLock() # set up child services self._services_d = self.create_child_services() # db configured values self.configured_db_url = None # configuration / reconfiguration handling self.config = MasterConfig() self.config_version = 0 # increased by one on each reconfig self.reconfig_active = False self.reconfig_requested = False self.reconfig_notifier = None # this stores parameters used in the tac file, and is accessed by the # WebStatus to duplicate those values. self.log_rotation = LogRotation() # local cache for this master's object ID self._object_id = None self._got_sigterm = False # Check environment is sensible check_functional_environment(self.config) # figure out local hostname try: self.hostname = os.uname()[1] # only on unix except AttributeError: self.hostname = socket.getfqdn() # public attributes self.name = f"{self.hostname}:{os.path.abspath(self.basedir or '.')}" if isinstance(self.name, bytes): self.name = self.name.decode('ascii', 'replace') self.masterid = None @defer.inlineCallbacks def create_child_services(self): # note that these are order-dependent. If you get the order wrong, # you'll know it, as the master will fail to start. self.httpservice = yield httpclientservice.HTTPClientService.getService(self, '') self.metrics = metrics.MetricLogObserver() yield self.metrics.setServiceParent(self) self.caches = cache.CacheManager() yield self.caches.setServiceParent(self) self.pbmanager = PBManager() yield self.pbmanager.setServiceParent(self) self.msgmanager = MsgManager() yield self.msgmanager.setServiceParent(self) self.workers = workermanager.WorkerManager(self) yield self.workers.setServiceParent(self) self.change_svc = ChangeManager() yield self.change_svc.setServiceParent(self) self.botmaster = BotMaster() yield self.botmaster.setServiceParent(self) self.machine_manager = MachineManager() yield self.machine_manager.setServiceParent(self) self.scheduler_manager = SchedulerManager() yield self.scheduler_manager.setServiceParent(self) self.user_manager = UserManagerManager(self) yield self.user_manager.setServiceParent(self) self.db = dbconnector.DBConnector(self.basedir) yield self.db.setServiceParent(self) self.wamp = wampconnector.WampConnector() yield self.wamp.setServiceParent(self) self.mq = mqconnector.MQConnector() yield self.mq.setServiceParent(self) self.data = dataconnector.DataConnector() yield self.data.setServiceParent(self) self.graphql = graphql.GraphQLConnector() yield self.graphql.setServiceParent(self) self.www = wwwservice.WWWService() yield self.www.setServiceParent(self) self.debug = debug.DebugServices() yield self.debug.setServiceParent(self) self.secrets_manager = SecretManager() yield self.secrets_manager.setServiceParent(self) self.secrets_manager.reconfig_priority = self.db.reconfig_priority - 1 self.service_manager = service.BuildbotServiceManager() yield self.service_manager.setServiceParent(self) self.service_manager.reconfig_priority = 1000 self.masterHouskeepingTimer = 0 @defer.inlineCallbacks def heartbeat(): if self.masterid is not None: yield self.data.updates.masterActive(name=self.name, masterid=self.masterid) yield self.data.updates.expireMasters() self.masterHeartbeatService = internet.TimerService(60, heartbeat) self.masterHeartbeatService.clock = self.reactor # we do setServiceParent only when the master is configured # master should advertise itself only at that time # setup and reconfig handling _already_started = False @defer.inlineCallbacks def startService(self): assert not self._already_started, "can only start the master once" self._already_started = True # ensure child services have been set up. Normally we would do this in serServiceParent, # but buildmaster is used in contexts we can't control. if self._services_d is not None: yield self._services_d self._services_d = None log.msg(f"Starting BuildMaster -- buildbot.version: {buildbot.version}") # Set umask if self.umask is not None: os.umask(self.umask) # first, apply all monkeypatches monkeypatches.patch_all() # we want to wait until the reactor is running, so we can call # reactor.stop() for fatal errors d = defer.Deferred() self.reactor.callWhenRunning(d.callback, None) yield d startup_succeed = False try: yield self.initLock.acquire() # load the configuration file, treating errors as fatal try: # run the master.cfg in thread, so that it can use blocking # code self.config = yield threads.deferToThreadPool( self.reactor, self.reactor.getThreadPool(), self.config_loader.loadConfig ) except config.ConfigErrors as e: log.msg("Configuration Errors:") for msg in e.errors: log.msg(" " + msg) log.msg("Halting master.") self.reactor.stop() return except Exception: log.err(failure.Failure(), 'while starting BuildMaster') self.reactor.stop() return # set up services that need access to the config before everything # else gets told to reconfig yield self.secrets_manager.setup() try: yield self.db.setup() except exceptions.DatabaseNotReadyError: # (message was already logged) self.reactor.stop() return yield self.mq.setup() # the buildbot scripts send the SIGHUP signal to reconfig master if hasattr(signal, "SIGHUP"): def sighup(*args): eventually(self.reconfig) signal.signal(signal.SIGHUP, sighup) # the buildbot scripts send the SIGUSR1 signal to stop master if hasattr(signal, "SIGUSR1"): def sigusr1(*args): eventually(self.botmaster.cleanShutdown) signal.signal(signal.SIGUSR1, sigusr1) # get the masterid so other services can use it in # startup/reconfig. This goes directly to the DB since the data # API isn't initialized yet, and anyway, this method is aware of # the DB API since it just called its setup function self.masterid = yield self.db.masters.findMasterId(name=self.name) # mark this master as stopped, in case it crashed before yield self.data.updates.masterStopped(name=self.name, masterid=self.masterid) # call the parent method yield super().startService() # We make sure the housekeeping is done before configuring in order to cleanup # any remaining claimed schedulers or change sources from zombie # masters yield self.data.updates.expireMasters(forceHouseKeeping=True) # give all services a chance to load the new configuration, rather # than the base configuration yield self.reconfigServiceWithBuildbotConfig(self.config) # Mark the master as active now that mq is running yield self.data.updates.masterActive(name=self.name, masterid=self.masterid) # Start the heartbeat timer yield self.masterHeartbeatService.setServiceParent(self) # send the statistics to buildbot.net, without waiting self.sendBuildbotNetUsageData() startup_succeed = True except Exception: f = failure.Failure() log.err(f, 'while starting BuildMaster') self.reactor.stop() finally: @defer.inlineCallbacks def call_after_signal(sig_num, stack): if not self._got_sigterm: self._got_sigterm = True yield self.disownServiceParent() self.reactor.stop() else: log.msg('Ignoring SIGTERM, master is already shutting down.') signal.signal(signal.SIGTERM, call_after_signal) if startup_succeed: log.msg("BuildMaster is running") else: log.msg("BuildMaster startup failed") yield self.initLock.release() self._master_initialized = True def sendBuildbotNetUsageData(self): if "TRIAL_PYTHONPATH" in os.environ and self.config.buildbotNetUsageData is not None: raise RuntimeError("Should not enable buildbotNetUsageData in trial tests!") sendBuildbotNetUsageData(self) @defer.inlineCallbacks def stopService(self): try: yield self.initLock.acquire() if self.running: yield self.botmaster.cleanShutdown(quickMode=True, stopReactor=False) # Mark master as stopped only after all builds are shut down. Note that masterStopped # would forcibly mark all related build requests, builds, steps, logs, etc. as # complete, so this may make state inconsistent if done while the builds are still # running. if self.masterid is not None: yield self.data.updates.masterStopped(name=self.name, masterid=self.masterid) if self.running: yield super().stopService() log.msg("BuildMaster is stopped") self._master_initialized = False finally: yield self.initLock.release() @defer.inlineCallbacks def reconfig(self): # this method wraps doConfig, ensuring it is only ever called once at # a time, and alerting the user if the reconfig takes too long if self.reconfig_active: log.msg("reconfig already active; will reconfig again after") self.reconfig_requested = True return self.reconfig_active = self.reactor.seconds() metrics.MetricCountEvent.log("loaded_config", 1) # notify every 10 seconds that the reconfig is still going on, the duration of reconfigs is # longer on larger installations and may take a while. self.reconfig_notifier = task.LoopingCall( lambda: log.msg( "reconfig is ongoing for " f"{self.reactor.seconds() - self.reconfig_active:.3f} s" ) ) self.reconfig_notifier.start(10, now=False) timer = metrics.Timer("BuildMaster.reconfig") timer.start() try: yield self.doReconfig() except Exception as e: log.err(e, 'while reconfiguring') finally: timer.stop() self.reconfig_notifier.stop() self.reconfig_notifier = None self.reconfig_active = False if self.reconfig_requested: self.reconfig_requested = False self.reconfig() @defer.inlineCallbacks def doReconfig(self): log.msg("beginning configuration update") time_started = self.reactor.seconds() changes_made = False failed = False try: yield self.initLock.acquire() # Run the master.cfg in thread, so that it can use blocking code new_config = yield threads.deferToThreadPool( self.reactor, self.reactor.getThreadPool(), self.config_loader.loadConfig ) changes_made = True self.config_version += 1 self.config = new_config yield self.reconfigServiceWithBuildbotConfig(new_config) except config.ConfigErrors as e: for msg in e.errors: log.msg(msg) failed = True except Exception: log.err(failure.Failure(), 'during reconfig:') failed = True finally: yield self.initLock.release() if failed: if changes_made: msg = "WARNING: configuration update partially applied; master may malfunction" else: msg = "configuration update aborted without making any changes" else: msg = "configuration update complete" log.msg(f"{msg} (took {(self.reactor.seconds() - time_started):.3f} seconds)") def reconfigServiceWithBuildbotConfig(self, new_config): if self.config.mq['type'] != new_config.mq['type']: raise config.ConfigErrors([ "Cannot change c['mq']['type'] after the master has started", ]) return super().reconfigServiceWithBuildbotConfig(new_config) # informational methods def allSchedulers(self): return list(self.scheduler_manager) # state maintenance (private) def getObjectId(self): """ Return the object id for this master, for associating state with the master. @returns: ID, via Deferred """ # try to get the cached value if self._object_id is not None: return defer.succeed(self._object_id) # failing that, get it from the DB; multiple calls to this function # at the same time will not hurt d = self.db.state.getObjectId(self.name, "buildbot.master.BuildMaster") @d.addCallback def keep(id): self._object_id = id return id return d def _getState(self, name, default=None): "private wrapper around C{self.db.state.getState}" d = self.getObjectId() @d.addCallback def get(objectid): return self.db.state.getState(objectid, name, default) return d def _setState(self, name, value): "private wrapper around C{self.db.state.setState}" d = self.getObjectId() @d.addCallback def set(objectid): return self.db.state.setState(objectid, name, value) return d
18,507
Python
.py
400
36.2325
99
0.658499
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,244
sse.py
buildbot_buildbot/master/buildbot/www/sse.py
# This file is part of Buildbot. Buildbot is free software: you can # redistribute it and/or modify it under the terms of the GNU General Public # License as published by the Free Software Foundation, version 2. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more # details. # # You should have received a copy of the GNU General Public License along with # this program; if not, write to the Free Software Foundation, Inc., 51 # Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # Copyright Buildbot Team Members import json import uuid from twisted.python import log from twisted.web import resource from twisted.web import server from buildbot.data.exceptions import InvalidPathError from buildbot.util import bytes2unicode from buildbot.util import toJson from buildbot.util import unicode2bytes class Consumer: def __init__(self, request): self.request = request self.qrefs = {} def stopConsuming(self, key=None): if key is not None: self.qrefs[key].stopConsuming() else: for qref in self.qrefs.values(): qref.stopConsuming() self.qrefs = {} def onMessage(self, event, data): request = self.request key = [bytes2unicode(e) for e in event] msg = {"key": key, "message": data} request.write(b"event: " + b"event" + b"\n") request.write(b"data: " + unicode2bytes(json.dumps(msg, default=toJson)) + b"\n") request.write(b"\n") def registerQref(self, path, qref): self.qrefs[path] = qref class EventResource(resource.Resource): isLeaf = True def __init__(self, master): super().__init__() self.master = master self.consumers = {} def decodePath(self, path): for i, p in enumerate(path): if p == b'*': path[i] = None return path def finish(self, request, code, msg): request.setResponseCode(code) request.setHeader(b'content-type', b'text/plain; charset=utf-8') request.write(msg) return def render(self, request): consumer = None command = b"listen" path = request.postpath if path and path[-1] == b'': path = path[:-1] if path and path[0] in (b"listen", b"add", b"remove"): command = path[0] path = path[1:] if command == b"listen": cid = unicode2bytes(str(uuid.uuid4())) consumer = Consumer(request) elif command in (b"add", b"remove"): if path: cid = path[0] path = path[1:] if cid not in self.consumers: return self.finish(request, 400, b"unknown uuid") consumer = self.consumers[cid] else: return self.finish(request, 400, b"need uuid") pathref = b"/".join(path) path = self.decodePath(path) if command == b"add" or (command == b"listen" and path): options = request.args for k in options: if len(options[k]) == 1: options[k] = options[k][1] try: d = self.master.mq.startConsuming( consumer.onMessage, tuple(bytes2unicode(p) for p in path) ) @d.addCallback def register(qref): consumer.registerQref(pathref, qref) d.addErrback(log.err, "while calling startConsuming") except NotImplementedError: return self.finish(request, 404, b"not implemented") except InvalidPathError: return self.finish(request, 404, b"not implemented") elif command == b"remove": try: consumer.stopConsuming(pathref) except KeyError: return self.finish(request, 404, b"consumer is not listening to this event") if command == b"listen": self.consumers[cid] = consumer request.setHeader(b"content-type", b"text/event-stream") request.write(b"") request.write(b"event: handshake\n") request.write(b"data: " + cid + b"\n") request.write(b"\n") d = request.notifyFinish() @d.addBoth def onEndRequest(_): consumer.stopConsuming() del self.consumers[cid] return server.NOT_DONE_YET self.finish(request, 200, b"ok") return None
4,745
Python
.py
119
30.008403
92
0.59426
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,245
change_hook.py
buildbot_buildbot/master/buildbot/www/change_hook.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 # # code inspired/copied from contrib/github_buildbot # and inspired from code from the Chromium project # otherwise, Andrew Melo <[email protected]> wrote the rest # but "the rest" is pretty minimal import re from datetime import datetime from twisted.internet import defer from twisted.python import log from twisted.web import server from buildbot.plugins.db import get_plugins from buildbot.util import bytes2unicode from buildbot.util import datetime2epoch from buildbot.util import unicode2bytes from buildbot.www import resource class ChangeHookResource(resource.Resource): # this is a cheap sort of template thingy contentType = "text/html; charset=utf-8" children = {} needsReconfig = True def __init__(self, dialects=None, master=None): """ The keys of 'dialects' select a modules to load under master/buildbot/www/hooks/ The value is passed to the module's getChanges function, providing configuration options to the dialect. """ super().__init__(master) if dialects is None: dialects = {} self.dialects = dialects self._dialect_handlers = {} self.request_dialect = None self._plugins = get_plugins("webhooks") def reconfigResource(self, new_config): self.dialects = new_config.www.get('change_hook_dialects', {}) def getChild(self, name, request): return self def render_GET(self, request): """ Responds to events and starts the build process different implementations can decide on what methods they will accept """ return self.render_POST(request) def render_POST(self, request): """ Responds to events and starts the build process different implementations can decide on what methods they will accept :arguments: request the http request object """ try: d = self.getAndSubmitChanges(request) except Exception: d = defer.fail() def ok(_): request.setResponseCode(202) request.finish() def err(why): code = 500 if why.check(ValueError): code = 400 msg = unicode2bytes(why.getErrorMessage()) else: log.err(why, "adding changes from web hook") msg = b'Error processing changes.' request.setResponseCode(code, msg) request.write(msg) request.finish() d.addCallbacks(ok, err) return server.NOT_DONE_YET @defer.inlineCallbacks def getAndSubmitChanges(self, request): changes, src = yield self.getChanges(request) if not changes: request.write(b"no change found") else: yield self.submitChanges(changes, request, src) request.write(unicode2bytes(f"{len(changes)} change found")) def makeHandler(self, dialect): """create and cache the handler object for this dialect""" if dialect not in self.dialects: m = f"The dialect specified, '{dialect}', wasn't whitelisted in change_hook" log.msg(m) log.msg( "Note: if dialect is 'base' then it's possible your URL is " "malformed and we didn't regex it properly" ) raise ValueError(m) if dialect not in self._dialect_handlers: options = self.dialects[dialect] if isinstance(options, dict) and 'custom_class' in options: klass = options['custom_class'] else: if dialect not in self._plugins: m = ( f"The dialect specified, '{dialect}', is not registered as " "a buildbot.webhook plugin" ) log.msg(m) raise ValueError(m) klass = self._plugins.get(dialect) self._dialect_handlers[dialect] = klass(self.master, self.dialects[dialect]) return self._dialect_handlers[dialect] @defer.inlineCallbacks def getChanges(self, request): """ Take the logic from the change hook, and then delegate it to the proper handler We use the buildbot plugin mechanisms to find out about dialects and call getChanges() the return value is a list of changes if DIALECT is unspecified, a sample implementation is provided """ uriRE = re.search(r'^/change_hook/?([a-zA-Z0-9_]*)', bytes2unicode(request.uri)) if not uriRE: msg = f"URI doesn't match change_hook regex: {request.uri}" log.msg(msg) raise ValueError(msg) changes = [] src = None # Was there a dialect provided? if uriRE.group(1): dialect = uriRE.group(1) else: dialect = 'base' handler = self.makeHandler(dialect) changes, src = yield handler.getChanges(request) return (changes, src) @defer.inlineCallbacks def submitChanges(self, changes, request, src): for chdict in changes: when_timestamp = chdict.get('when_timestamp') if isinstance(when_timestamp, datetime): chdict['when_timestamp'] = datetime2epoch(when_timestamp) # unicodify stuff for k in ( 'comments', 'author', 'committer', 'revision', 'branch', 'category', 'revlink', 'repository', 'codebase', 'project', ): if k in chdict: chdict[k] = bytes2unicode(chdict[k]) if chdict.get('files'): chdict['files'] = [bytes2unicode(f) for f in chdict['files']] if chdict.get('properties'): chdict['properties'] = dict( (bytes2unicode(k), v) for k, v in chdict['properties'].items() ) chid = yield self.master.data.updates.addChange(src=bytes2unicode(src), **chdict) log.msg(f"injected change {chid}")
7,015
Python
.py
173
30.479769
93
0.608983
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,246
config.py
buildbot_buildbot/master/buildbot/www/config.py
# This file is part of Buildbot. Buildbot is free software: you can # redistribute it and/or modify it under the terms of the GNU General Public # License as published by the Free Software Foundation, version 2. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more # details. # # You should have received a copy of the GNU General Public License along with # this program; if not, write to the Free Software Foundation, Inc., 51 # Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # Copyright Buildbot Team Members import json import os from twisted.internet import defer from twisted.web.error import Error from buildbot.interfaces import IConfigured from buildbot.util import unicode2bytes from buildbot.www import resource def get_environment_versions(): import sys # pylint: disable=import-outside-toplevel import twisted # pylint: disable=import-outside-toplevel from buildbot import version as bbversion # pylint: disable=import-outside-toplevel pyversion = '.'.join(map(str, sys.version_info[:3])) tx_version_info = (twisted.version.major, twisted.version.minor, twisted.version.micro) txversion = '.'.join(map(str, tx_version_info)) return [ ('Python', pyversion), ('Buildbot', bbversion), ('Twisted', txversion), ] def get_www_frontend_config_dict(master, www_config): # This config is shared with the frontend. config = dict(www_config) versions = get_environment_versions() vs = config.get('versions') if isinstance(vs, list): versions += vs config['versions'] = versions config['buildbotURL'] = master.config.buildbotURL config['title'] = master.config.title config['titleURL'] = master.config.titleURL config['multiMaster'] = master.config.multiMaster # delete things that may contain secrets if 'change_hook_dialects' in config: del config['change_hook_dialects'] # delete things that may contain information about the serving host if 'custom_templates_dir' in config: del config['custom_templates_dir'] return config def serialize_www_frontend_config_dict_to_json(config): def to_json(obj): obj = IConfigured(obj).getConfigDict() if isinstance(obj, dict): return obj # don't leak object memory address obj = obj.__class__.__module__ + "." + obj.__class__.__name__ return repr(obj) + " not yet IConfigured" return json.dumps(config, default=to_json) _known_theme_variables = ( ("bb-sidebar-background-color", "#30426a"), ("bb-sidebar-header-background-color", "#273759"), ("bb-sidebar-header-text-color", "#fff"), ("bb-sidebar-title-text-color", "#627cb7"), ("bb-sidebar-footer-background-color", "#273759"), ("bb-sidebar-button-text-color", "#b2bfdc"), ("bb-sidebar-button-hover-background-color", "#1b263d"), ("bb-sidebar-button-hover-text-color", "#fff"), ("bb-sidebar-button-current-background-color", "#273759"), ("bb-sidebar-button-current-text-color", "#b2bfdc"), ("bb-sidebar-stripe-hover-color", "#e99d1a"), ("bb-sidebar-stripe-current-color", "#8c5e10"), ) def serialize_www_frontend_theme_to_css(config, indent): theme_config = config.get('theme', {}) return ('\n' + ' ' * indent).join([ f'--{name}: {theme_config.get(name, default)};' for name, default in _known_theme_variables ]) def replace_placeholder_range(string, start, end, replacement): # Simple string replacement is much faster than a multiline regex i1 = string.find(start) i2 = string.find(end) if i1 < 0 or i2 < 0: return string return string[0:i1] + replacement + string[i2 + len(end) :] class ConfigResource(resource.Resource): needsReconfig = True def reconfigResource(self, new_config): self.frontend_config = get_www_frontend_config_dict(self.master, new_config.www) def render_GET(self, request): return self.asyncRenderHelper(request, self.do_render) def do_render(self, request): config = {} request.setHeader(b"content-type", b'application/json') request.setHeader(b"Cache-Control", b"public,max-age=0") config.update(self.frontend_config) config.update({"user": self.master.www.getUserInfos(request)}) return defer.succeed( unicode2bytes(serialize_www_frontend_config_dict_to_json(config), encoding='ascii') ) class IndexResource(resource.Resource): # enable reconfigResource calls needsReconfig = True def __init__(self, master, staticdir): super().__init__(master) self.static_dir = staticdir with open(os.path.join(self.static_dir, 'index.html')) as index_f: self.index_template = index_f.read() def reconfigResource(self, new_config): self.config = new_config.www self.frontend_config = get_www_frontend_config_dict(self.master, self.config) def render_GET(self, request): return self.asyncRenderHelper(request, self.renderIndex) @defer.inlineCallbacks def renderIndex(self, request): config = {} request.setHeader(b"content-type", b'text/html') request.setHeader(b"Cache-Control", b"public,max-age=0") try: yield self.config['auth'].maybeAutoLogin(request) except Error as e: config["on_load_warning"] = e.message config.update(self.frontend_config) config.update({"user": self.master.www.getUserInfos(request)}) serialized_config = serialize_www_frontend_config_dict_to_json(config) serialized_css = serialize_www_frontend_theme_to_css(config, indent=8) rendered_index = self.index_template.replace( ' <!-- BUILDBOT_CONFIG_PLACEHOLDER -->', f"""<script id="bb-config"> window.buildbotFrontendConfig = {serialized_config}; </script>""", ) rendered_index = replace_placeholder_range( rendered_index, '<!-- BUILDBOT_THEME_CSS_PLACEHOLDER_BEGIN -->', '<!-- BUILDBOT_THEME_CSS_PLACEHOLDER_END -->', f"""<style> :root {{ {serialized_css} }} </style>""", ) return unicode2bytes(rendered_index, encoding='ascii')
6,470
Python
.py
145
38.337931
99
0.681159
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,247
rest.py
buildbot_buildbot/master/buildbot/www/rest.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 datetime import fnmatch import json import re from contextlib import contextmanager from typing import TYPE_CHECKING from urllib.parse import urlparse from twisted.internet import defer from twisted.internet.error import ConnectionDone from twisted.python import log from twisted.web.error import Error from twisted.web.resource import EncodingResourceWrapper from twisted.web.server import GzipEncoderFactory from buildbot.data import exceptions from buildbot.data.base import EndpointKind from buildbot.util import bytes2unicode from buildbot.util import toJson from buildbot.util import unicode2bytes from buildbot.www import resource from buildbot.www.authz import Forbidden from buildbot.www.encoding import BrotliEncoderFactory from buildbot.www.encoding import ZstandardEncoderFactory if TYPE_CHECKING: from typing import Any from twisted.web import server from buildbot.data.base import Endpoint from buildbot.data.resultspec import ResultSpec class BadJsonRpc2(Exception): def __init__(self, message, jsonrpccode): self.message = message self.jsonrpccode = jsonrpccode class ContentTypeParser: def __init__(self, contenttype: str | bytes | None) -> None: self.typeheader = contenttype def gettype(self) -> str | None: if self.typeheader is None: return None return bytes2unicode(self.typeheader).split(';', 1)[0] URL_ENCODED = b"application/x-www-form-urlencoded" JSON_ENCODED = b"application/json" class RestRootResource(resource.Resource): version_classes: dict[int, type[V2RootResource]] = {} @classmethod def addApiVersion(cls, version, version_cls): cls.version_classes[version] = version_cls version_cls.apiVersion = version def __init__(self, master): super().__init__(master) min_vers = master.config.www.get('rest_minimum_version', 0) encoders = [ BrotliEncoderFactory(), ZstandardEncoderFactory(), GzipEncoderFactory(), ] latest = max(list(self.version_classes)) for version, klass in self.version_classes.items(): if version < min_vers: continue child = EncodingResourceWrapper(klass(master), encoders) child_path = f'v{version}' child_path = unicode2bytes(child_path) self.putChild(child_path, child) if version == latest: self.putChild(b'latest', child) def render(self, request): request.setHeader(b"content-type", JSON_ENCODED) min_vers = self.master.config.www.get('rest_minimum_version', 0) api_versions = dict( (f'v{v}', f'{self.base_url}api/v{v}') for v in self.version_classes if v > min_vers ) data = json.dumps({"api_versions": api_versions}) return unicode2bytes(data) JSONRPC_CODES = { "parse_error": -32700, "invalid_request": -32600, "method_not_found": -32601, "invalid_params": -32602, "internal_error": -32603, } class V2RootResource(resource.Resource): # For GETs, this API follows http://jsonapi.org. The getter API does not # permit create, update, or delete, so this is limited to reading. # # Data API control methods can be invoked via a POST to the appropriate # URL. These follow http://www.jsonrpc.org/specification, with a few # limitations: # - params as list is not supported # - rpc call batching is not supported # - jsonrpc2 notifications are not supported (you always get an answer) # rather than construct the entire possible hierarchy of Rest resources, # this is marked as a leaf node, and any remaining path items are parsed # during rendering isLeaf = True # enable reconfigResource calls needsReconfig = True @defer.inlineCallbacks def getEndpoint(self, request, method, params): # note that trailing slashes are not allowed request_postpath = tuple(bytes2unicode(p) for p in request.postpath) yield self.master.www.assertUserAllowed(request, request_postpath, method, params) ret = yield self.master.data.getEndpoint(request_postpath) return ret @contextmanager def handleErrors(self, writeError): try: yield except ConnectionDone: # Connection was cleanly closed pass except exceptions.InvalidPathError as e: msg = unicode2bytes(e.args[0]) writeError( msg or b"invalid path", errcode=404, jsonrpccode=JSONRPC_CODES['invalid_request'] ) return except exceptions.InvalidControlException as e: msg = unicode2bytes(str(e)) writeError( msg or b"invalid control action", errcode=501, jsonrpccode=JSONRPC_CODES["method_not_found"], ) return except exceptions.InvalidQueryParameter as e: msg = unicode2bytes(e.args[0]) writeError( msg or b"invalid request", errcode=400, jsonrpccode=JSONRPC_CODES["method_not_found"], ) return except BadJsonRpc2 as e: msg = unicode2bytes(e.message) writeError(msg, errcode=400, jsonrpccode=e.jsonrpccode) return except Forbidden as e: # There is nothing in jsonrc spec about forbidden error, so pick # invalid request msg = unicode2bytes(e.message) writeError(msg, errcode=403, jsonrpccode=JSONRPC_CODES["invalid_request"]) return except Exception as e: log.err(_why='while handling API request') msg = unicode2bytes(repr(e)) writeError(repr(e), errcode=500, jsonrpccode=JSONRPC_CODES["internal_error"]) return # JSONRPC2 support def decodeJsonRPC2(self, request: server.Request): # Verify the content-type. Browsers are easily convinced to send # POST data to arbitrary URLs via 'form' elements, but they won't # use the application/json content-type. if ContentTypeParser(request.getHeader(b'content-type')).gettype() != "application/json": raise BadJsonRpc2( 'Invalid content-type (use application/json)', JSONRPC_CODES["invalid_request"] ) try: assert request.content is not None data = json.loads(bytes2unicode(request.content.read())) except Exception as e: raise BadJsonRpc2(f"JSON parse error: {e!s}", JSONRPC_CODES["parse_error"]) from e if isinstance(data, list): raise BadJsonRpc2( "JSONRPC batch requests are not supported", JSONRPC_CODES["invalid_request"] ) if not isinstance(data, dict): raise BadJsonRpc2( "JSONRPC root object must be an object", JSONRPC_CODES["invalid_request"] ) def check(name, types, typename): if name not in data: raise BadJsonRpc2(f"missing key '{name}'", JSONRPC_CODES["invalid_request"]) if not isinstance(data[name], types): raise BadJsonRpc2(f"'{name}' must be {typename}", JSONRPC_CODES["invalid_request"]) check("jsonrpc", (str,), "a string") check("method", (str,), "a string") check("id", (str, int, type(None)), "a string, number, or null") check("params", (dict,), "an object") if data['jsonrpc'] != '2.0': raise BadJsonRpc2("only JSONRPC 2.0 is supported", JSONRPC_CODES['invalid_request']) return data["method"], data["id"], data['params'] @defer.inlineCallbacks def renderJsonRpc(self, request): jsonRpcReply = {'jsonrpc': "2.0"} def writeError(msg, errcode=399, jsonrpccode=JSONRPC_CODES["internal_error"]): if isinstance(msg, bytes): msg = bytes2unicode(msg) if self.debug: log.msg(f"JSONRPC error: {msg}") request.setResponseCode(errcode) request.setHeader(b'content-type', JSON_ENCODED) if "error" not in jsonRpcReply: # already filled in by caller jsonRpcReply['error'] = {"code": jsonrpccode, "message": msg} data = json.dumps(jsonRpcReply) data = unicode2bytes(data) request.write(data) with self.handleErrors(writeError): method, id, params = self.decodeJsonRPC2(request) jsonRpcReply['id'] = id ep, kwargs = yield self.getEndpoint(request, method, params) userinfos = self.master.www.getUserInfos(request) if userinfos.get('anonymous'): owner = "anonymous" else: for field in ('email', 'username', 'full_name'): owner = userinfos.get(field, None) if owner: break params['owner'] = owner result = yield ep.control(method, params, kwargs) jsonRpcReply['result'] = result data = json.dumps(jsonRpcReply, default=toJson, sort_keys=True, separators=(',', ':')) request.setHeader(b'content-type', JSON_ENCODED) if request.method == b"HEAD": request.setHeader(b"content-length", unicode2bytes(str(len(data)))) request.write(b'') else: data = unicode2bytes(data) request.write(data) def decodeResultSpec(self, request, endpoint): args = request.args entityType = endpoint.rtype.entityType return self.master.data.resultspec_from_jsonapi( args, entityType, endpoint.kind == EndpointKind.COLLECTION ) def _write_rest_error(self, request: server.Request, msg, errcode: int = 404): if self.debug: log.msg(f"REST error: {msg}") request.setResponseCode(errcode) request.setHeader(b'content-type', b'text/plain; charset=utf-8') msg = bytes2unicode(msg) data = json.dumps({"error": msg}) data = unicode2bytes(data) request.write(data) def _write_not_found_rest_error( self, request: server.Request, ep: Endpoint, rspec: ResultSpec, kwargs: dict[str, Any], ): self._write_rest_error( request=request, msg=( f"not found while getting from {ep!r} with " f"arguments {rspec!r} and {kwargs!s}" ), ) async def _render_raw( self, request: server.Request, ep: Endpoint, rspec: ResultSpec, kwargs: dict[str, Any], ): assert ep.kind in (EndpointKind.RAW, EndpointKind.RAW_INLINE) is_stream_data = False try: data = await ep.stream(rspec, kwargs) is_stream_data = True except NotImplementedError: data = await ep.get(rspec, kwargs) if data is None: self._write_not_found_rest_error(request, ep, rspec=rspec, kwargs=kwargs) return request.setHeader(b"content-type", unicode2bytes(data['mime-type']) + b'; charset=utf-8') if ep.kind != EndpointKind.RAW_INLINE: request.setHeader( b"content-disposition", b'attachment; filename=' + unicode2bytes(data['filename']) ) if not is_stream_data: request.write(unicode2bytes(data['raw'])) return async for chunk in data['raw']: if request.finished or request.channel is None: # In case of lost connection, request is not marked as finished # detect this case with `channel` being None return request.write(unicode2bytes(chunk)) @defer.inlineCallbacks def renderRest(self, request: server.Request): def writeError(msg, errcode=404, jsonrpccode=None): self._write_rest_error(request, msg=msg, errcode=errcode) with self.handleErrors(writeError): ep, kwargs = yield self.getEndpoint(request, bytes2unicode(request.method), {}) rspec = self.decodeResultSpec(request, ep) if ep.kind in (EndpointKind.RAW, EndpointKind.RAW_INLINE): yield defer.Deferred.fromCoroutine(self._render_raw(request, ep, rspec, kwargs)) return data = yield ep.get(rspec, kwargs) if data is None: self._write_not_found_rest_error(request, ep, rspec=rspec, kwargs=kwargs) return # post-process any remaining parts of the resultspec data = rspec.apply(data) # annotate the result with some metadata meta = {} if ep.kind == EndpointKind.COLLECTION: offset, total = data.offset, data.total if offset is None: offset = 0 # add total, if known if total is not None: meta['total'] = total # get the real list instance out of the ListResult data = data.data else: data = [data] typeName = ep.rtype.plural data = {typeName: data, 'meta': meta} # set up the content type and formatting options; if the request # accepts text/html or text/plain, the JSON will be rendered in a # readable, multiline format. if b'application/json' in (request.getHeader(b'accept') or b''): compact = True request.setHeader(b"content-type", b'application/json; charset=utf-8') else: compact = False request.setHeader(b"content-type", b'text/plain; charset=utf-8') # set up caching if self.cache_seconds: now = datetime.datetime.now(datetime.timezone.utc) expires = now + datetime.timedelta(seconds=self.cache_seconds) expiresBytes = unicode2bytes(expires.strftime("%a, %d %b %Y %H:%M:%S GMT")) request.setHeader(b"Expires", expiresBytes) request.setHeader(b"Pragma", b"no-cache") # filter out blanks if necessary and render the data encoder = json.encoder.JSONEncoder(default=toJson, sort_keys=True) if compact: encoder.item_separator, encoder.key_separator = (',', ':') else: encoder.indent = 2 content_length = sum(len(unicode2bytes(chunk)) for chunk in encoder.iterencode(data)) request.setHeader(b"content-length", unicode2bytes(str(content_length))) if request.method != b"HEAD": for chunk in encoder.iterencode(data): request.write(unicode2bytes(chunk)) def reconfigResource(self, new_config): # buildbotURL may contain reverse proxy path, Origin header is just # scheme + host + port buildbotURL = urlparse(unicode2bytes(new_config.buildbotURL)) origin_self = buildbotURL.scheme + b"://" + buildbotURL.netloc # pre-translate the origin entries in the config self.origins = [] for o in new_config.www.get('allowed_origins', [origin_self]): origin = bytes2unicode(o).lower() self.origins.append(re.compile(fnmatch.translate(origin))) # and copy some other flags self.debug = new_config.www.get('debug') self.cache_seconds = new_config.www.get('json_cache_seconds', 0) def render(self, request): def writeError(msg, errcode=400): msg = bytes2unicode(msg) if self.debug: log.msg(f"HTTP error: {msg}") request.setResponseCode(errcode) request.setHeader(b'content-type', b'text/plain; charset=utf-8') if request.method == b'POST': # jsonRPC callers want the error message in error.message data = json.dumps({"error": {"message": msg}}) data = unicode2bytes(data) request.write(data) else: data = json.dumps({"error": msg}) data = unicode2bytes(data) request.write(data) request.finish() return self.asyncRenderHelper(request, self.asyncRender, writeError) @defer.inlineCallbacks def asyncRender(self, request): # Handle CORS, if necessary. origins = self.origins if origins is not None: isPreflight = False reqOrigin = request.getHeader(b'origin') if reqOrigin: err = None reqOrigin = reqOrigin.lower() if not any(o.match(bytes2unicode(reqOrigin)) for o in self.origins): err = b"invalid origin" elif request.method == b'OPTIONS': preflightMethod = request.getHeader(b'access-control-request-method') if preflightMethod not in (b'GET', b'POST', b'HEAD'): err = b'invalid method' isPreflight = True if err: raise Error(400, err) # If it's OK, then let the browser know we checked it out. The # Content-Type header is included here because CORS considers # content types other than form data and text/plain to not be # simple. request.setHeader(b"access-control-allow-origin", reqOrigin) request.setHeader(b"access-control-allow-headers", b"Content-Type") request.setHeader(b"access-control-max-age", b'3600') # if this was a preflight request, we're done if isPreflight: return b"" # based on the method, this is either JSONRPC or REST if request.method == b'POST': res = yield self.renderJsonRpc(request) elif request.method in (b'GET', b'HEAD'): res = yield self.renderRest(request) else: raise Error(400, b"invalid HTTP method") return res RestRootResource.addApiVersion(2, V2RootResource)
19,158
Python
.py
419
34.909308
99
0.616675
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,248
avatar.py
buildbot_buildbot/master/buildbot/www/avatar.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 hashlib from urllib.parse import urlencode from urllib.parse import urljoin from urllib.parse import urlparse from urllib.parse import urlunparse from twisted.internet import defer from twisted.python import log from buildbot import config from buildbot.util import httpclientservice from buildbot.util import unicode2bytes from buildbot.util.config import ConfiguredMixin from buildbot.www import resource class AvatarBase(ConfiguredMixin): name = "noavatar" def getUserAvatar(self, email, username, size, defaultAvatarUrl): raise NotImplementedError() class AvatarGitHub(AvatarBase): name = "github" DEFAULT_GITHUB_API_URL = 'https://api.github.com' def __init__( self, github_api_endpoint=None, token=None, client_id=None, client_secret=None, debug=False, verify=False, ): self.github_api_endpoint = github_api_endpoint if github_api_endpoint is None: self.github_api_endpoint = self.DEFAULT_GITHUB_API_URL self.token = token self.client_creds = None if bool(client_id) != bool(client_secret): config.error('client_id and client_secret must be both provided or none') if client_id: if token: config.error('client_id and client_secret must not be provided when token is') self.client_creds = base64.b64encode( b':'.join(cred.encode('utf-8') for cred in (client_id, client_secret)) ).decode('ascii') self.debug = debug self.verify = verify self.master = None self.client = None @defer.inlineCallbacks def _get_http_client(self): if self.client is not None: return self.client headers = { 'User-Agent': 'Buildbot', } if self.token: headers['Authorization'] = 'token ' + self.token elif self.client_creds: headers['Authorization'] = 'basic ' + self.client_creds self.client = yield httpclientservice.HTTPSession( self.master.httpservice, self.github_api_endpoint, headers=headers, debug=self.debug, verify=self.verify, ) return self.client @defer.inlineCallbacks def _get_avatar_by_username(self, username): headers = { 'Accept': 'application/vnd.github.v3+json', } url = f'/users/{username}' http = yield self._get_http_client() res = yield http.get(url, headers=headers) if res.code == 404: # Not found return None if 200 <= res.code < 300: data = yield res.json() return data['avatar_url'] log.msg(f'Failed looking up user: response code {res.code}') return None @defer.inlineCallbacks def _search_avatar_by_user_email(self, email): headers = { 'Accept': 'application/vnd.github.v3+json', } query = f'{email} in:email' url = f"/search/users?{urlencode({'q': query})}" http = yield self._get_http_client() res = yield http.get(url, headers=headers) if 200 <= res.code < 300: data = yield res.json() if data['total_count'] == 0: # Not found return None return data['items'][0]['avatar_url'] log.msg(f'Failed searching user by email: response code {res.code}') return None @defer.inlineCallbacks def _search_avatar_by_commit(self, email): headers = { 'Accept': 'application/vnd.github.v3+json,application/vnd.github.cloak-preview', } query = { 'q': f'author-email:{email}', 'sort': 'committer-date', 'per_page': '1', } sorted_query = sorted(query.items(), key=lambda x: x[0]) url = f'/search/commits?{urlencode(sorted_query)}' http = yield self._get_http_client() res = yield http.get(url, headers=headers) if 200 <= res.code < 300: data = yield res.json() if data['total_count'] == 0: # Not found return None author = data['items'][0]['author'] if author is None: # No Github account found return None return author['avatar_url'] log.msg(f'Failed searching user by commit: response code {res.code}') return None def _add_size_to_url(self, avatar, size): parts = urlparse(avatar) query = parts.query if query: query += '&' query += f's={size}' return urlunparse(( parts.scheme, parts.netloc, parts.path, parts.params, query, parts.fragment, )) @defer.inlineCallbacks def getUserAvatar(self, email, username, size, defaultAvatarUrl): avatar = None if username: username = username.decode('utf-8') if email: email = email.decode('utf-8') if username: avatar = yield self._get_avatar_by_username(username) if not avatar and email: # Try searching a user with said mail avatar = yield self._search_avatar_by_user_email(email) if not avatar and email: # No luck, try to find a commit with this email avatar = yield self._search_avatar_by_commit(email) if not avatar: # No luck return None if size: avatar = self._add_size_to_url(avatar, size) raise resource.Redirect(avatar) class AvatarGravatar(AvatarBase): name = "gravatar" # gravatar does not want intranet URL, which is most of where the bots are # just use same default as github (retro) default = "retro" def getUserAvatar(self, email, username, size, defaultAvatarUrl): # construct the url emailBytes = unicode2bytes(email.lower()) emailHash = hashlib.md5(emailBytes) gravatar_url = "//www.gravatar.com/avatar/" gravatar_url += emailHash.hexdigest() + "?" if self.default != "url": defaultAvatarUrl = self.default url = {'d': defaultAvatarUrl, 's': str(size)} sorted_url = sorted(url.items(), key=lambda x: x[0]) gravatar_url += urlencode(sorted_url) raise resource.Redirect(gravatar_url) class AvatarResource(resource.Resource): # enable reconfigResource calls needsReconfig = True defaultAvatarUrl = b"img/nobody.png" def reconfigResource(self, new_config): self.avatarMethods = new_config.www.get('avatar_methods', []) self.defaultAvatarFullUrl = urljoin( unicode2bytes(new_config.buildbotURL), unicode2bytes(self.defaultAvatarUrl) ) self.cache = {} # ensure the avatarMethods is a iterable if isinstance(self.avatarMethods, AvatarBase): self.avatarMethods = (self.avatarMethods,) for method in self.avatarMethods: method.master = self.master def render_GET(self, request): return self.asyncRenderHelper(request, self.renderAvatar) @defer.inlineCallbacks def renderAvatar(self, request): email = request.args.get(b"email", [b""])[0] size = request.args.get(b"size", [32])[0] try: size = int(size) except ValueError: size = 32 username = request.args.get(b"username", [None])[0] cache_key = (email, username, size) if self.cache.get(cache_key): raise self.cache[cache_key] for method in self.avatarMethods: try: res = yield method.getUserAvatar(email, username, size, self.defaultAvatarFullUrl) except resource.Redirect as r: self.cache[cache_key] = r raise if res is not None: request.setHeader(b'content-type', res[0]) request.setHeader(b'content-length', unicode2bytes(str(len(res[1])))) request.write(res[1]) return raise resource.Redirect(self.defaultAvatarUrl)
9,026
Python
.py
231
29.939394
98
0.614664
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,249
plugin.py
buildbot_buildbot/master/buildbot/www/plugin.py
# This file is part of Buildbot. Buildbot is free software: you can # redistribute it and/or modify it under the terms of the GNU General Public # License as published by the Free Software Foundation, version 2. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more # details. # # You should have received a copy of the GNU General Public License along with # this program; if not, write to the Free Software Foundation, Inc., 51 # Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # Copyright Buildbot Team Members import sys from twisted.web import static from buildbot.util import bytes2unicode if sys.version_info[:2] >= (3, 9): # We need importlib.resources.files, which is added in Python 3.9 # https://docs.python.org/3/library/importlib.resources.html import importlib.resources as importlib_resources else: import importlib_resources # type: ignore[import-not-found] class Application: def __init__(self, package_name, description, ui=True): self.description = description self.version = importlib_resources.files(package_name).joinpath("VERSION") self.version = bytes2unicode(self.version.read_bytes()) self.static_dir = importlib_resources.files(package_name) / "static" self.resource = static.File(self.static_dir) self.ui = ui def setMaster(self, master): self.master = master def setConfiguration(self, config): self.config = config def __repr__(self): return ( "www.plugin.Application(version={version}, " "description={description}, " "static_dir={static_dir})" ).format(**self.__dict__)
1,851
Python
.py
41
40.317073
82
0.720711
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,250
ldapuserinfo.py
buildbot_buildbot/master/buildbot/www/ldapuserinfo.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 # NOTE regarding LDAP encodings: # # By default the encoding used in ldap3 is utf-8. The encoding is user-configurable, though. # For more information check ldap3's documentation on this topic: # http://ldap3.readthedocs.io/encoding.html # # It is recommended to use ldap3's auto-decoded `attributes` values for # `unicode` and `raw_*` attributes for `bytes`. import importlib from urllib.parse import urlparse from twisted.internet import threads from buildbot.util import bytes2unicode from buildbot.util import flatten from buildbot.www import auth from buildbot.www import avatar try: import ldap3 except ImportError: ldap3 = None class LdapUserInfo(avatar.AvatarBase, auth.UserInfoProviderBase): name = 'ldap' def __init__( self, uri, bindUser, bindPw, accountBase, accountPattern, accountFullName, accountEmail, groupBase=None, groupMemberPattern=None, groupName=None, avatarPattern=None, avatarData=None, accountExtraFields=None, tls=None, ): # Throw import error now that this is being used if not ldap3: importlib.import_module('ldap3') self.uri = uri self.bindUser = bindUser self.bindPw = bindPw self.accountBase = accountBase self.accountEmail = accountEmail self.accountPattern = accountPattern self.accountFullName = accountFullName group_params = [p for p in (groupName, groupMemberPattern, groupBase) if p is not None] if len(group_params) not in (0, 3): raise ValueError( "Incomplete LDAP groups configuration. " "To use Ldap groups, you need to specify the three " "parameters (groupName, groupMemberPattern and groupBase). " ) self.groupName = groupName self.groupMemberPattern = groupMemberPattern self.groupBase = groupBase self.avatarPattern = avatarPattern self.avatarData = avatarData if accountExtraFields is None: accountExtraFields = [] self.accountExtraFields = accountExtraFields self.ldap_encoding = ldap3.get_config_parameter('DEFAULT_SERVER_ENCODING') self.tls = tls def connectLdap(self): server = urlparse(self.uri) netloc = server.netloc.split(":") # define the server and the connection s = ldap3.Server( netloc[0], port=int(netloc[1]), use_ssl=server.scheme == 'ldaps', get_info=ldap3.ALL, tls=self.tls, ) auth = ldap3.SIMPLE if self.bindUser is None and self.bindPw is None: auth = ldap3.ANONYMOUS c = ldap3.Connection( s, auto_bind=True, client_strategy=ldap3.SYNC, user=self.bindUser, password=self.bindPw, authentication=auth, ) return c def search(self, c, base, filterstr='f', attributes=None): c.search(base, filterstr, ldap3.SUBTREE, attributes=attributes) return c.response def getUserInfo(self, username): username = bytes2unicode(username) def thd(): c = self.connectLdap() infos = {'username': username} pattern = self.accountPattern % {"username": username} res = self.search( c, self.accountBase, pattern, attributes=[self.accountEmail, self.accountFullName, *self.accountExtraFields], ) if len(res) != 1: raise KeyError(f"ldap search \"{pattern}\" returned {len(res)} results") dn, ldap_infos = res[0]['dn'], res[0]['attributes'] def getFirstLdapInfo(x): if isinstance(x, list): x = x[0] if x else None return x infos['full_name'] = getFirstLdapInfo(ldap_infos[self.accountFullName]) infos['email'] = getFirstLdapInfo(ldap_infos[self.accountEmail]) for f in self.accountExtraFields: if f in ldap_infos: infos[f] = getFirstLdapInfo(ldap_infos[f]) if self.groupMemberPattern is None: infos['groups'] = [] return infos # needs double quoting of backslashing pattern = self.groupMemberPattern % {"dn": ldap3.utils.conv.escape_filter_chars(dn)} res = self.search(c, self.groupBase, pattern, attributes=[self.groupName]) infos['groups'] = flatten([ group_infos['attributes'][self.groupName] for group_infos in res ]) return infos return threads.deferToThread(thd) def findAvatarMime(self, data): # http://en.wikipedia.org/wiki/List_of_file_signatures if data.startswith(b"\xff\xd8\xff"): return (b"image/jpeg", data) if data.startswith(b"\x89PNG"): return (b"image/png", data) if data.startswith(b"GIF8"): return (b"image/gif", data) # ignore unknown image format return None def getUserAvatar(self, email, username, size, defaultAvatarUrl): if username: username = bytes2unicode(username) if email: email = bytes2unicode(email) def thd(): c = self.connectLdap() if username: pattern = self.accountPattern % {"username": username} elif email: pattern = self.avatarPattern % {"email": email} else: return None res = self.search(c, self.accountBase, pattern, attributes=[self.avatarData]) if not res: return None ldap_infos = res[0]['raw_attributes'] if ldap_infos.get(self.avatarData): data = ldap_infos[self.avatarData][0] return self.findAvatarMime(data) return None return threads.deferToThread(thd)
6,836
Python
.py
172
30.122093
96
0.620913
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,251
encoding.py
buildbot_buildbot/master/buildbot/www/encoding.py
# This file is part of Buildbot. Buildbot is free software: you can # redistribute it and/or modify it under the terms of the GNU General Public # License as published by the Free Software Foundation, version 2. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more # details. # # You should have received a copy of the GNU General Public License along with # this program; if not, write to the Free Software Foundation, Inc., 51 # Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # Copyright Buildbot Team Members from __future__ import annotations import re from twisted.web import iweb from zope.interface import implementer try: import brotli except ImportError: brotli = None try: import zstandard except ImportError: zstandard = None # type: ignore[assignment] @implementer(iweb._IRequestEncoderFactory) class _EncoderFactoryBase: def __init__( self, encoding_type: bytes, encoder_class: type[iweb._IRequestEncoder] | None ) -> None: self.encoding_type = encoding_type self.encoder_class = encoder_class self.check_regex = re.compile(rb"(:?^|[\s,])" + encoding_type + rb"(:?$|[\s,])") def encoderForRequest(self, request): """ Check the headers if the client accepts encoding, and encodes the request if so. """ if self.encoder_class is None: return None acceptHeaders = b",".join(request.requestHeaders.getRawHeaders(b"accept-encoding", [])) if self.check_regex.search(acceptHeaders): encoding = request.responseHeaders.getRawHeaders(b"content-encoding") if encoding: encoding = b",".join([*encoding, self.encoding_type]) else: encoding = self.encoding_type request.responseHeaders.setRawHeaders(b"content-encoding", [encoding]) return self.encoder_class(request) return None class BrotliEncoderFactory(_EncoderFactoryBase): def __init__(self) -> None: super().__init__(b'br', _BrotliEncoder if brotli is not None else None) class ZstandardEncoderFactory(_EncoderFactoryBase): def __init__(self) -> None: super().__init__(b'zstd', _ZstdEncoder if zstandard is not None else None) @implementer(iweb._IRequestEncoder) class _EncoderBase: def __init__(self, request) -> None: self._request = request def _compress(self, data: bytes) -> bytes: return data def _flush(self) -> bytes: return b'' def encode(self, data): """ Write to the request, automatically compressing data on the fly. """ if not self._request.startedWriting: # Remove the content-length header, we can't honor it # because we compress on the fly. self._request.responseHeaders.removeHeader(b"content-length") return self._compress(data) def finish(self): """ Finish handling the request request, flushing any data from the buffer. """ return self._flush() class _BrotliEncoder(_EncoderBase): def __init__(self, request): super().__init__(request) self._compressor = brotli.Compressor() if brotli is not None else None def _compress(self, data: bytes) -> bytes: if self._compressor is not None: return self._compressor.process(data) return data def _flush(self) -> bytes: if self._compressor is not None: data = self._compressor.finish() self._compressor = None return data return b'' class _ZstdEncoder(_EncoderBase): def __init__(self, request): super().__init__(request) self._compressor = ( zstandard.ZstdCompressor(write_content_size=True) if zstandard is not None else None ) self._compressobj = self._compressor.compressobj() if zstandard is not None else None def _compress(self, data: bytes) -> bytes: if self._compressor is not None: return self._compressobj.compress(data) return data def _flush(self) -> bytes: if self._compressor is not None: c_data = self._compressobj.flush() self._compressor = None self._compressobj = None return c_data return b''
4,515
Python
.py
111
33.477477
96
0.659278
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,252
auth.py
buildbot_buildbot/master/buildbot/www/auth.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 abc import ABCMeta from abc import abstractmethod import twisted from packaging.version import parse as parse_version from twisted.cred.checkers import FilePasswordDB from twisted.cred.checkers import ICredentialsChecker from twisted.cred.checkers import InMemoryUsernamePasswordDatabaseDontUse from twisted.cred.credentials import IUsernamePassword from twisted.cred.error import UnauthorizedLogin from twisted.cred.portal import IRealm from twisted.cred.portal import Portal from twisted.internet import defer from twisted.web.error import Error from twisted.web.guard import BasicCredentialFactory from twisted.web.guard import DigestCredentialFactory from twisted.web.guard import HTTPAuthSessionWrapper from twisted.web.resource import IResource from zope.interface import implementer from buildbot.util import bytes2unicode from buildbot.util import config from buildbot.util import unicode2bytes from buildbot.www import resource class AuthRootResource(resource.Resource): def getChild(self, path, request): # return dynamically generated resources if path == b'login': return self.master.www.auth.getLoginResource() elif path == b'logout': return self.master.www.auth.getLogoutResource() return super().getChild(path, request) class AuthBase(config.ConfiguredMixin): def __init__(self, userInfoProvider=None): self.userInfoProvider = userInfoProvider def reconfigAuth(self, master, new_config): self.master = master def maybeAutoLogin(self, request): return defer.succeed(None) def getLoginResource(self): raise Error(501, b"not implemented") def getLogoutResource(self): return LogoutResource(self.master) @defer.inlineCallbacks def updateUserInfo(self, request): session = request.getSession() if self.userInfoProvider is not None: infos = yield self.userInfoProvider.getUserInfo(session.user_info['username']) session.user_info.update(infos) session.updateSession(request) def getConfigDict(self): return {'name': type(self).__name__} class UserInfoProviderBase(config.ConfiguredMixin): name = "noinfo" def getUserInfo(self, username): return defer.succeed({'email': username}) class LoginResource(resource.Resource): def render_GET(self, request): return self.asyncRenderHelper(request, self.renderLogin) @defer.inlineCallbacks def renderLogin(self, request): raise NotImplementedError class NoAuth(AuthBase): pass class RemoteUserAuth(AuthBase): header = b"REMOTE_USER" headerRegex = re.compile(rb"(?P<username>[^ @]+)@(?P<realm>[^ @]+)") def __init__(self, header=None, headerRegex=None, **kwargs): super().__init__(**kwargs) if self.userInfoProvider is None: self.userInfoProvider = UserInfoProviderBase() if header is not None: self.header = unicode2bytes(header) if headerRegex is not None: self.headerRegex = re.compile(unicode2bytes(headerRegex)) def getLoginResource(self): current_version = parse_version(twisted.__version__) if current_version < parse_version("22.10.0"): from twisted.web.resource import ForbiddenResource return ForbiddenResource(message="URL is not supported for authentication") from twisted.web.pages import forbidden return forbidden(message="URL is not supported for authentication") @defer.inlineCallbacks def maybeAutoLogin(self, request): header = request.getHeader(self.header) if header is None: msg = b"missing http header " + self.header + b". Check your reverse proxy config!" raise Error(403, msg) res = self.headerRegex.match(header) if res is None: msg = ( b'http header does not match regex! "' + header + b'" not matching ' + self.headerRegex.pattern ) raise Error(403, msg) session = request.getSession() user_info = {k: bytes2unicode(v) for k, v in res.groupdict().items()} if session.user_info != user_info: session.user_info = user_info yield self.updateUserInfo(request) @implementer(IRealm) class AuthRealm: def __init__(self, master, auth): self.auth = auth self.master = master def requestAvatar(self, avatarId, mind, *interfaces): if IResource in interfaces: return (IResource, PreAuthenticatedLoginResource(self.master, avatarId), lambda: None) raise NotImplementedError() class TwistedICredAuthBase(AuthBase): def __init__(self, credentialFactories, checkers, **kwargs): super().__init__(**kwargs) if self.userInfoProvider is None: self.userInfoProvider = UserInfoProviderBase() self.credentialFactories = credentialFactories self.checkers = checkers def getLoginResource(self): return HTTPAuthSessionWrapper( Portal(AuthRealm(self.master, self), self.checkers), self.credentialFactories ) class HTPasswdAuth(TwistedICredAuthBase): def __init__(self, passwdFile, **kwargs): super().__init__( [DigestCredentialFactory(b"MD5", b"buildbot"), BasicCredentialFactory(b"buildbot")], [FilePasswordDB(passwdFile)], **kwargs, ) class UserPasswordAuth(TwistedICredAuthBase): def __init__(self, users, **kwargs): if isinstance(users, dict): users = {user: unicode2bytes(pw) for user, pw in users.items()} elif isinstance(users, list): users = [(user, unicode2bytes(pw)) for user, pw in users] super().__init__( [DigestCredentialFactory(b"MD5", b"buildbot"), BasicCredentialFactory(b"buildbot")], [InMemoryUsernamePasswordDatabaseDontUse(**dict(users))], **kwargs, ) @implementer(ICredentialsChecker) class CustomAuth(TwistedICredAuthBase): __metaclass__ = ABCMeta credentialInterfaces = [IUsernamePassword] def __init__(self, **kwargs): super().__init__([BasicCredentialFactory(b"buildbot")], [self], **kwargs) def requestAvatarId(self, cred): if self.check_credentials(cred.username, cred.password): return defer.succeed(cred.username) return defer.fail(UnauthorizedLogin()) @abstractmethod def check_credentials(self, username, password): return False def _redirect(master, request): url = request.args.get(b"redirect", [b"/"])[0] url = bytes2unicode(url) return resource.Redirect(master.config.buildbotURL + "#" + url) class PreAuthenticatedLoginResource(LoginResource): # a LoginResource which is already authenticated via a # HTTPAuthSessionWrapper def __init__(self, master, username): super().__init__(master) self.username = username @defer.inlineCallbacks def renderLogin(self, request): session = request.getSession() session.user_info = {"username": bytes2unicode(self.username)} yield self.master.www.auth.updateUserInfo(request) raise _redirect(self.master, request) class LogoutResource(resource.Resource): def render_GET(self, request): session = request.getSession() session.expire() session.updateSession(request) request.redirect(_redirect(self.master, request).url) return b''
8,295
Python
.py
189
36.957672
98
0.702595
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,253
resource.py
buildbot_buildbot/master/buildbot/www/resource.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.internet import defer from twisted.python import log from twisted.web import resource from twisted.web import server from twisted.web.error import Error from buildbot.util import unicode2bytes _CR_LF_RE = re.compile(rb"[\r\n]+.*") def protect_redirect_url(url): return _CR_LF_RE.sub(b"", url) class Redirect(Error): def __init__(self, url): super().__init__(302, "redirect") self.url = protect_redirect_url(unicode2bytes(url)) class Resource(resource.Resource): # if this is true for a class, then instances will have their # reconfigResource(new_config) methods called on reconfig. needsReconfig = False # as a convenience, subclasses have a ``master`` attribute, a # ``base_url`` attribute giving Buildbot's base URL, # and ``static_url`` attribute giving Buildbot's static files URL @property def base_url(self): return self.master.config.buildbotURL def __init__(self, master): super().__init__() self.master = master if self.needsReconfig and master is not None: master.www.resourceNeedsReconfigs(self) def reconfigResource(self, new_config): raise NotImplementedError def asyncRenderHelper(self, request, _callable, writeError=None): def writeErrorDefault(msg, errcode=400): request.setResponseCode(errcode) request.setHeader(b'content-type', b'text/plain; charset=utf-8') request.write(msg) request.finish() if writeError is None: writeError = writeErrorDefault try: d = _callable(request) except Exception as e: d = defer.fail(e) @d.addCallback def finish(s): try: if s is not None: request.write(s) request.finish() except RuntimeError: # pragma: no cover # this occurs when the client has already disconnected; ignore # it (see #2027) log.msg("http client disconnected before results were sent") @d.addErrback def failHttpRedirect(f): f.trap(Redirect) request.redirect(f.value.url) request.finish() return None @d.addErrback def failHttpError(f): f.trap(Error) e = f.value message = unicode2bytes(e.message) writeError(message, errcode=int(e.status)) @d.addErrback def fail(f): log.err(f, 'While rendering resource:') try: writeError(b'internal error - see logs', errcode=500) except Exception: try: request.finish() except Exception: pass return server.NOT_DONE_YET class RedirectResource(Resource): def __init__(self, master, basepath): super().__init__(master) self.basepath = basepath def render(self, request): redir = self.base_url + self.basepath request.redirect(protect_redirect_url(redir)) return redir
3,877
Python
.py
98
31.163265
79
0.644379
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,254
graphql.py
buildbot_buildbot/master/buildbot/www/graphql.py
# This file is part of Buildbot. Buildbot is free software: you can # redistribute it and/or modify it under the terms of the GNU General Public # License as published by the Free Software Foundation, version 2. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more # details. # # You should have received a copy of the GNU General Public License along with # this program; if not, write to the Free Software Foundation, Inc., 51 # Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # Copyright Buildbot Team Members import json from twisted.internet import defer from twisted.python import log from twisted.web.error import Error from buildbot.util import bytes2unicode from buildbot.util import unicode2bytes from buildbot.www import resource from buildbot.www.rest import RestRootResource class V3RootResource(resource.Resource): isLeaf = True # enable reconfigResource calls needsReconfig = True def reconfigResource(self, new_config): # @todo v2 has cross origin support, which might need to be factorized graphql_config = new_config.www.get("graphql") self.debug = True self.graphql = None if graphql_config is not None: self.graphql = True def render(self, request): def writeError(msg, errcode=400): if isinstance(msg, list): errors = msg else: msg = bytes2unicode(msg) errors = [{"message": msg}] if self.debug: log.msg(f"HTTP error: {errors}") request.setResponseCode(errcode) request.setHeader(b"content-type", b"application/json; charset=utf-8") data = json.dumps({"data": None, "errors": errors}) data = unicode2bytes(data) request.write(data) request.finish() return self.asyncRenderHelper(request, self.asyncRender, writeError) @defer.inlineCallbacks def asyncRender(self, request): if self.graphql is None: raise Error(501, "graphql not enabled") # graphql accepts its query either in post data or get query if request.method == b"POST": content_type = request.getHeader(b"content-type") if content_type == b"application/graphql": query = request.content.read().decode() elif content_type == b"application/json": json_query = json.load(request.content) query = json_query.pop('query') if json_query: fields = " ".join(json_query.keys()) raise Error(400, b"json request unsupported fields: " + fields.encode()) elif content_type is None: raise Error(400, b"no content-type") else: raise Error(400, b"unsupported content-type: " + content_type) elif request.method in (b"GET"): if b"query" not in request.args: raise Error(400, b"GET request must contain a 'query' parameter") query = request.args[b"query"][0].decode() else: raise Error(400, b"invalid HTTP method") res = yield self.master.graphql.query(query) errors = None if res.errors: errors = [e.formatted for e in res.errors] request.setHeader(b"content-type", b"application/json; charset=utf-8") data = json.dumps({"data": res.data, "errors": errors}).encode() request.write(data) RestRootResource.addApiVersion(3, V3RootResource)
3,735
Python
.py
82
36.707317
92
0.651182
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,255
oauth2.py
buildbot_buildbot/master/buildbot/www/oauth2.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 json import re import textwrap from posixpath import join from urllib.parse import parse_qs from urllib.parse import urlencode import jinja2 import requests from twisted.internet import defer from twisted.internet import threads from twisted.logger import Logger from twisted.web.error import Error import buildbot from buildbot import config from buildbot.process.properties import Properties from buildbot.util import bytes2unicode from buildbot.www import auth from buildbot.www import resource log = Logger() class OAuth2LoginResource(auth.LoginResource): # disable reconfigResource calls needsReconfig = False def __init__(self, master, _auth): super().__init__(master) self.auth = _auth def render_POST(self, request): return self.asyncRenderHelper(request, self.renderLogin) @defer.inlineCallbacks def renderLogin(self, request): code = request.args.get(b"code", [b""])[0] if not code: url = request.args.get(b"redirect", [None])[0] url = yield self.auth.getLoginURL(url) raise resource.Redirect(url) details = yield self.auth.verifyCode(code) if self.auth.userInfoProvider is not None: infos = yield self.auth.userInfoProvider.getUserInfo(details['username']) details.update(infos) session = request.getSession() session.user_info = details session.updateSession(request) state = request.args.get(b"state", [b""])[0] if state: for redirect in parse_qs(state).get('redirect', []): raise resource.Redirect(self.auth.homeUri + "#" + redirect) raise resource.Redirect(self.auth.homeUri) class OAuth2Auth(auth.AuthBase): name = 'oauth2' getTokenUseAuthHeaders = False authUri: str | None = None tokenUri: str | None = None grantType = 'authorization_code' authUriAdditionalParams: dict[str, str] = {} tokenUriAdditionalParams: dict[str, str] = {} loginUri = None homeUri = None def __init__(self, clientId, clientSecret, autologin=False, ssl_verify: bool = True, **kwargs): super().__init__(**kwargs) self.clientId = clientId self.clientSecret = clientSecret self.autologin = autologin self.ssl_verify = ssl_verify def reconfigAuth(self, master, new_config): self.master = master self.loginUri = join(new_config.buildbotURL, "auth/login") self.homeUri = new_config.buildbotURL def getConfigDict(self): return { "name": self.name, "oauth2": True, "fa_icon": self.faIcon, "autologin": self.autologin, } def getLoginResource(self): return OAuth2LoginResource(self.master, self) @defer.inlineCallbacks def getLoginURL(self, redirect_url): """ Returns the url to redirect the user to for user consent """ p = Properties() p.master = self.master clientId = yield p.render(self.clientId) oauth_params = { 'redirect_uri': self.loginUri, 'client_id': clientId, 'response_type': 'code', } if redirect_url is not None: oauth_params['state'] = urlencode({"redirect": redirect_url}) oauth_params.update(self.authUriAdditionalParams) sorted_oauth_params = sorted(oauth_params.items(), key=lambda val: val[0]) return f"{self.authUri}?{urlencode(sorted_oauth_params)}" def createSessionFromToken(self, token): s = requests.Session() error = token.get("error") if error: error_description = token.get("error_description") or error msg = f"OAuth2 session: creation failed: {error_description}" raise Error(503, msg) s.params = {'access_token': token['access_token']} s.verify = self.ssl_verify return s def get(self, session, path): ret = session.get(self.resourceEndpoint + path) return ret.json() # based on https://github.com/maraujop/requests-oauth # from Miguel Araujo, augmented to support header based clientSecret # passing @defer.inlineCallbacks def verifyCode(self, code): # everything in deferToThread is not counted with trial --coverage :-( def thd(client_id, client_secret): url = self.tokenUri data = {'redirect_uri': self.loginUri, 'code': code, 'grant_type': self.grantType} auth = None if self.getTokenUseAuthHeaders: auth = (client_id, client_secret) else: data.update({'client_id': client_id, 'client_secret': client_secret}) data.update(self.tokenUriAdditionalParams) response = requests.post(url, data=data, timeout=30, auth=auth, verify=self.ssl_verify) response.raise_for_status() responseContent = bytes2unicode(response.content) try: content = json.loads(responseContent) except ValueError: content = parse_qs(responseContent) for k, v in content.items(): content[k] = v[0] except TypeError: content = responseContent session = self.createSessionFromToken(content) return self.getUserInfoFromOAuthClient(session) p = Properties() p.master = self.master client_id = yield p.render(self.clientId) client_secret = yield p.render(self.clientSecret) result = yield threads.deferToThread(thd, client_id, client_secret) return result def getUserInfoFromOAuthClient(self, c): return {} class GoogleAuth(OAuth2Auth): name = "Google" faIcon = "fa-google-plus" resourceEndpoint = "https://www.googleapis.com/oauth2/v1" authUri = 'https://accounts.google.com/o/oauth2/auth' tokenUri = 'https://accounts.google.com/o/oauth2/token' authUriAdditionalParams = { "scope": ' '.join([ 'https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/userinfo.profile', ]) } def getUserInfoFromOAuthClient(self, c): data = self.get(c, '/userinfo') return { "full_name": data["name"], "username": data['email'].split("@")[0], "email": data["email"], "avatar_url": data["picture"], } class GitHubAuth(OAuth2Auth): name = "GitHub" faIcon = "fa-github" authUri = 'https://github.com/login/oauth/authorize' authUriAdditionalParams = {'scope': 'user:email read:org'} tokenUri = 'https://github.com/login/oauth/access_token' resourceEndpoint = 'https://api.github.com' getUserTeamsGraphqlTpl = textwrap.dedent(r""" {%- if organizations %} query getOrgTeamMembership { {%- for org_slug, org_name in organizations.items() %} {{ org_slug }}: organization(login: "{{ org_name }}") { teams(first: 100 userLogins: ["{{ user_info.username }}"]) { edges { node { name, slug } } } } {%- endfor %} } {%- endif %} """) def __init__( self, clientId, clientSecret, serverURL=None, autologin=False, apiVersion=3, getTeamsMembership=False, debug=False, **kwargs, ): super().__init__(clientId, clientSecret, autologin, **kwargs) self.apiResourceEndpoint = None if serverURL is not None: # setup for enterprise github serverURL = serverURL.rstrip("/") # v3 is accessible directly at /api/v3 for enterprise, but directly for SaaS.. self.resourceEndpoint = serverURL + '/api/v3' # v4 is accessible endpoint for enterprise self.apiResourceEndpoint = serverURL + '/api/graphql' self.authUri = f'{serverURL}/login/oauth/authorize' self.tokenUri = f'{serverURL}/login/oauth/access_token' self.serverURL = serverURL or self.resourceEndpoint if apiVersion not in (3, 4): config.error(f'GitHubAuth apiVersion must be 3 or 4 not {apiVersion}') self.apiVersion = apiVersion if apiVersion == 3: if getTeamsMembership is True: config.error( 'Retrieving team membership information using GitHubAuth is only ' 'possible using GitHub api v4.' ) else: defaultGraphqlEndpoint = self.serverURL + '/graphql' self.apiResourceEndpoint = self.apiResourceEndpoint or defaultGraphqlEndpoint if getTeamsMembership: # GraphQL name aliases must comply with /^[_a-zA-Z][_a-zA-Z0-9]*$/ self._orgname_slug_sub_re = re.compile(r'[^_a-zA-Z0-9]') self.getUserTeamsGraphqlTplC = jinja2.Template(self.getUserTeamsGraphqlTpl.strip()) self.getTeamsMembership = getTeamsMembership self.debug = debug def post(self, session, query): if self.debug: log.info( '{klass} GraphQL POST Request: {endpoint} -> DATA:\n----\n{data}\n----', klass=self.__class__.__name__, endpoint=self.apiResourceEndpoint, data=query, ) ret = session.post(self.apiResourceEndpoint, json={'query': query}) return ret.json() def getUserInfoFromOAuthClient(self, c): if self.apiVersion == 3: return self.getUserInfoFromOAuthClient_v3(c) return self.getUserInfoFromOAuthClient_v4(c) def getUserInfoFromOAuthClient_v3(self, c): user = self.get(c, '/user') emails = self.get(c, '/user/emails') for email in emails: if email.get('primary', False): user['email'] = email['email'] break orgs = self.get(c, '/user/orgs') return { "full_name": user['name'], "email": user['email'], "username": user['login'], "groups": [org['login'] for org in orgs], } def createSessionFromToken(self, token): s = requests.Session() s.headers = { 'Authorization': 'token ' + token['access_token'], 'User-Agent': f'buildbot/{buildbot.version}', } s.verify = self.ssl_verify return s def getUserInfoFromOAuthClient_v4(self, c): graphql_query = textwrap.dedent(""" query { viewer { email login name organizations(first: 100) { edges { node { login } } } } } """) data = self.post(c, graphql_query.strip()) data = data['data'] if self.debug: log.info( '{klass} GraphQL Response: {response}', klass=self.__class__.__name__, response=data ) user_info = { "full_name": data['viewer']['name'], "email": data['viewer']['email'], "username": data['viewer']['login'], "groups": [org['node']['login'] for org in data['viewer']['organizations']['edges']], } if self.getTeamsMembership: orgs_name_slug_mapping = { self._orgname_slug_sub_re.sub('_', n): n for n in user_info['groups'] } graphql_query = self.getUserTeamsGraphqlTplC.render({ 'user_info': user_info, 'organizations': orgs_name_slug_mapping, }) if graphql_query: data = self.post(c, graphql_query) if self.debug: log.info( '{klass} GraphQL Response: {response}', klass=self.__class__.__name__, response=data, ) teams = set() for org, team_data in data['data'].items(): if team_data is None: # Organizations can have OAuth App access restrictions enabled, # disallowing team data access to third-parties. continue for node in team_data['teams']['edges']: # On github we can mentions organization teams like # @org-name/team-name. Let's keep the team formatting # identical with the inclusion of the organization # since different organizations might share a common # team name teams.add(f"{orgs_name_slug_mapping[org]}/{node['node']['name']}") teams.add(f"{orgs_name_slug_mapping[org]}/{node['node']['slug']}") user_info['groups'].extend(sorted(teams)) if self.debug: log.info( '{klass} User Details: {user_info}', klass=self.__class__.__name__, user_info=user_info, ) return user_info class GitLabAuth(OAuth2Auth): name = "GitLab" faIcon = "fa-git" def __init__(self, instanceUri, clientId, clientSecret, **kwargs): uri = instanceUri.rstrip("/") self.authUri = f"{uri}/oauth/authorize" self.tokenUri = f"{uri}/oauth/token" self.resourceEndpoint = f"{uri}/api/v4" super().__init__(clientId, clientSecret, **kwargs) def getUserInfoFromOAuthClient(self, c): user = self.get(c, "/user") groups = self.get(c, "/groups") return { "full_name": user["name"], "username": user["username"], "email": user["email"], "avatar_url": user["avatar_url"], "groups": [g["path"] for g in groups], } class BitbucketAuth(OAuth2Auth): name = "Bitbucket" faIcon = "fa-bitbucket" authUri = 'https://bitbucket.org/site/oauth2/authorize' tokenUri = 'https://bitbucket.org/site/oauth2/access_token' resourceEndpoint = 'https://api.bitbucket.org/2.0' def getUserInfoFromOAuthClient(self, c): user = self.get(c, '/user') emails = self.get(c, '/user/emails') for email in emails["values"]: if email.get('is_primary', False): user['email'] = email['email'] break orgs = self.get(c, '/workspaces?role=member') return { "full_name": user['display_name'], "email": user['email'], "username": user['username'], "groups": [org['slug'] for org in orgs["values"]], }
15,722
Python
.py
385
30.475325
100
0.585312
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,256
service.py
buildbot_buildbot/master/buildbot/www/service.py
# This file is part of Buildbot. Buildbot is free software: you can # redistribute it and/or modify it under the terms of the GNU General Public # License as published by the Free Software Foundation, version 2. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more # details. # # You should have received a copy of the GNU General Public License along with # this program; if not, write to the Free Software Foundation, Inc., 51 # Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # Copyright Buildbot Team Members from __future__ import annotations import calendar import datetime import os from binascii import hexlify import jwt import twisted from packaging.version import parse as parse_version from twisted.application import strports from twisted.cred.portal import IRealm from twisted.cred.portal import Portal from twisted.internet import defer from twisted.python import components from twisted.python import log from twisted.python.logfile import LogFile from twisted.web import guard from twisted.web import resource from twisted.web import server from zope.interface import implementer from buildbot import config from buildbot.plugins.db import get_plugins from buildbot.util import bytes2unicode from buildbot.util import service from buildbot.util import unicode2bytes from buildbot.www import auth from buildbot.www import avatar from buildbot.www import change_hook from buildbot.www import config as wwwconfig from buildbot.www import graphql from buildbot.www import rest from buildbot.www import sse from buildbot.www import ws # as per: # http://security.stackexchange.com/questions/95972/what-are-requirements-for-hmac-secret-key # we need 128 bit key for HS256 SESSION_SECRET_LENGTH = 128 SESSION_SECRET_ALGORITHM = "HS256" class BuildbotSession(server.Session): # We deviate a bit from the twisted API in order to implement that. # We keep it a subclass of server.Session (to be safe against isinstance), # but we re implement all its API. # But as there is no support in twisted web for clustered session management, this leaves # us with few choice. expDelay = datetime.timedelta(weeks=1) def __init__(self, site, token=None): """ Initialize a session with a unique ID for that session. """ self.site = site assert self.site.session_secret is not None, "site.session_secret is not configured yet!" # Cannot use super() here as it would call server.Session.__init__ # which we explicitly want to override. However, we still want to call # server.Session parent class constructor components.Componentized.__init__(self) if token: self._fromToken(token) else: self._defaultValue() def _defaultValue(self): self.user_info = {"anonymous": True} def _fromToken(self, token): try: decoded = jwt.decode( token, self.site.session_secret, algorithms=[SESSION_SECRET_ALGORITHM] ) except jwt.exceptions.ExpiredSignatureError as e: raise KeyError(str(e)) from e except jwt.exceptions.InvalidSignatureError as e: log.msg( e, "Web request has been rejected." "Signature verification failed while decoding JWT.", ) raise KeyError(str(e)) from e except Exception as e: log.err(e, "while decoding JWT session") raise KeyError(str(e)) from e # might raise KeyError: will be caught by caller, which makes the token invalid self.user_info = decoded['user_info'] def updateSession(self, request): """ Update the cookie after session object was modified @param request: the request object which should get a new cookie """ # we actually need to copy some hardcoded constants from twisted :-( # Make sure we aren't creating a secure session on a non-secure page secure = request.isSecure() if not secure: cookieString = b"TWISTED_SESSION" else: cookieString = b"TWISTED_SECURE_SESSION" cookiename = b"_".join([cookieString, *request.sitepath]) request.addCookie(cookiename, self.uid, path=b"/", secure=secure) def expire(self): # caller must still call self.updateSession() to actually expire it self._defaultValue() def notifyOnExpire(self, callback): raise NotImplementedError("BuildbotSession can't support notify on session expiration") def touch(self): pass @property def uid(self): """uid is now generated automatically according to the claims. This should actually only be used for cookie generation """ exp = datetime.datetime.now(datetime.timezone.utc) + self.expDelay claims = { 'user_info': self.user_info, # Note that we use JWT standard 'exp' field to implement session expiration # we completely bypass twisted.web session expiration mechanisms 'exp': calendar.timegm(datetime.datetime.timetuple(exp)), } return jwt.encode(claims, self.site.session_secret, algorithm=SESSION_SECRET_ALGORITHM) class BuildbotSite(server.Site): """A custom Site for Buildbot needs. Supports rotating logs, and JWT sessions """ def __init__(self, root, logPath, rotateLength, maxRotatedFiles): super().__init__(root, logPath=logPath) self.rotateLength = rotateLength self.maxRotatedFiles = maxRotatedFiles self.session_secret = None def _openLogFile(self, path): self._nativeize = True return LogFile.fromFullPath( path, rotateLength=self.rotateLength, maxRotatedFiles=self.maxRotatedFiles ) def getResourceFor(self, request): request.responseHeaders.removeHeader('Server') return server.Site.getResourceFor(self, request) def setSessionSecret(self, secret): self.session_secret = secret def makeSession(self): """ Generate a new Session instance, but not store it for future reference (because it will be used by another master instance) The session will still be cached by twisted.request """ return BuildbotSession(self) def getSession(self, uid): """ Get a previously generated session. @param uid: Unique ID of the session (a JWT token). @type uid: L{bytes}. @raise: L{KeyError} if the session is not found. """ return BuildbotSession(self, uid) class WWWService(service.ReconfigurableServiceMixin, service.AsyncMultiService): name: str | None = 'www' # type: ignore[assignment] def __init__(self): super().__init__() self.port = None self.port_service = None self.site = None # load the apps early, in case something goes wrong in Python land self.apps = get_plugins('www', None, load_now=True) self.base_plugin_name = 'base' @property def auth(self): return self.master.config.www['auth'] @defer.inlineCallbacks def reconfigServiceWithBuildbotConfig(self, new_config): www = new_config.www self.authz = www.get('authz') if self.authz is not None: self.authz.setMaster(self.master) need_new_site = False if self.site: # if config params have changed, set need_new_site to True. # There are none right now. need_new_site = False else: if www['port']: need_new_site = True if need_new_site: self.setupSite(new_config) if self.site: self.reconfigSite(new_config) yield self.makeSessionSecret() if www['port'] != self.port: if self.port_service: yield self.port_service.disownServiceParent() self.port_service = None self.port = www['port'] if self.port: port = self.port if isinstance(port, int): port = f"tcp:{port}" self.port_service = strports.service(port, self.site) # monkey-patch in some code to get the actual Port object # returned by endpoint.listen(). But only for tests. if port == "tcp:0:interface=127.0.0.1": if hasattr(self.port_service, 'endpoint'): old_listen = self.port_service.endpoint.listen @defer.inlineCallbacks def listen(factory): port = yield old_listen(factory) self._getPort = lambda: port return port self.port_service.endpoint.listen = listen else: # older twisted's just have the port sitting there # as an instance attribute self._getPort = lambda: self.port_service._port yield self.port_service.setServiceParent(self) if not self.port_service: log.msg("No web server configured on this master") yield super().reconfigServiceWithBuildbotConfig(new_config) def getPortnum(self): # for tests, when the configured port is 0 and the kernel selects a # dynamic port. This will fail if the monkeypatch in reconfigService # was not made. return self._getPort().getHost().port def refresh_base_plugin_name(self, new_config): if 'base_react' in new_config.www.get('plugins', {}): config.error( "'base_react' plugin is no longer supported. Use 'base' plugin in master.cfg " "BuildmasterConfig['www'] dictionary instead. Remove 'buildbot-www-react' and " "install 'buildbot-www' package." ) self.base_plugin_name = 'base' def configPlugins(self, root, new_config): plugin_root = root current_version = parse_version(twisted.__version__) if current_version < parse_version("22.10.0"): from twisted.web.resource import NoResource plugin_root = NoResource() else: from twisted.web.pages import notFound plugin_root = notFound() root.putChild(b"plugins", plugin_root) known_plugins = set(new_config.www.get('plugins', {})) | set([self.base_plugin_name]) for key, plugin in list(new_config.www.get('plugins', {}).items()): log.msg(f"initializing www plugin {key!r}") if key not in self.apps: raise RuntimeError(f"could not find plugin {key}; is it installed?") app = self.apps.get(key) app.setMaster(self.master) app.setConfiguration(plugin) plugin_root.putChild(unicode2bytes(key), app.resource) for plugin_name in set(self.apps.names) - known_plugins: log.msg(f"NOTE: www plugin {plugin_name!r} is installed but not configured") def setupSite(self, new_config): self.refresh_base_plugin_name(new_config) self.reconfigurableResources = [] # we're going to need at least the base plugin (buildbot-www or buildbot-www-react) if self.base_plugin_name not in self.apps: raise RuntimeError("could not find buildbot-www; is it installed?") root = self.apps.get(self.base_plugin_name).resource self.configPlugins(root, new_config) # / root.putChild( b'', wwwconfig.IndexResource(self.master, self.apps.get(self.base_plugin_name).static_dir), ) # /auth root.putChild(b'auth', auth.AuthRootResource(self.master)) # /avatar root.putChild(b'avatar', avatar.AvatarResource(self.master)) # /api root.putChild(b'api', rest.RestRootResource(self.master)) _ = graphql # import is made for side effects # /config root.putChild(b'config', wwwconfig.ConfigResource(self.master)) # /ws root.putChild(b'ws', ws.WsResource(self.master)) # /sse root.putChild(b'sse', sse.EventResource(self.master)) # /change_hook resource_obj = change_hook.ChangeHookResource(master=self.master) # FIXME: this does not work with reconfig change_hook_auth = new_config.www.get('change_hook_auth') if change_hook_auth is not None: resource_obj = self.setupProtectedResource(resource_obj, change_hook_auth) root.putChild(b"change_hook", resource_obj) self.root = root rotateLength = ( new_config.www.get('logRotateLength') or self.master.log_rotation.rotateLength ) maxRotatedFiles = ( new_config.www.get('maxRotatedFiles') or self.master.log_rotation.maxRotatedFiles ) httplog = None if new_config.www['logfileName']: httplog = os.path.abspath( os.path.join(self.master.basedir, new_config.www['logfileName']) ) self.site = BuildbotSite( root, logPath=httplog, rotateLength=rotateLength, maxRotatedFiles=maxRotatedFiles ) self.site.sessionFactory = None # Make sure site.master is set. It is required for poller change_hook self.site.master = self.master # convert this to a tuple so it can't be appended anymore (in # case some dynamically created resources try to get reconfigs) self.reconfigurableResources = tuple(self.reconfigurableResources) def resourceNeedsReconfigs(self, resource): # flag this resource as needing to know when a reconfig occurs self.reconfigurableResources.append(resource) def reconfigSite(self, new_config): self.refresh_base_plugin_name(new_config) root = self.apps.get(self.base_plugin_name).resource self.configPlugins(root, new_config) new_config.www['auth'].reconfigAuth(self.master, new_config) cookie_expiration_time = new_config.www.get('cookie_expiration_time') if cookie_expiration_time is not None: BuildbotSession.expDelay = cookie_expiration_time for rsrc in self.reconfigurableResources: rsrc.reconfigResource(new_config) @defer.inlineCallbacks def makeSessionSecret(self): state = self.master.db.state objectid = yield state.getObjectId("www", "buildbot.www.service.WWWService") def create_session_secret(): # Bootstrap: We need to create a key, that will be shared with other masters # and other runs of this master # we encode that in hex for db storage convenience return bytes2unicode(hexlify(os.urandom(int(SESSION_SECRET_LENGTH / 8)))) session_secret = yield state.atomicCreateState( objectid, "session_secret", create_session_secret ) self.site.setSessionSecret(session_secret) def setupProtectedResource(self, resource_obj, checkers): @implementer(IRealm) class SimpleRealm: """ A realm which gives out L{ChangeHookResource} instances for authenticated users. """ def requestAvatar(self, avatarId, mind, *interfaces): if resource.IResource in interfaces: return (resource.IResource, resource_obj, lambda: None) raise NotImplementedError() portal = Portal(SimpleRealm(), checkers) credentialFactory = guard.BasicCredentialFactory('Protected area') wrapper = guard.HTTPAuthSessionWrapper(portal, [credentialFactory]) return wrapper def getUserInfos(self, request): session = request.getSession() return session.user_info def assertUserAllowed(self, request, ep, action, options): user_info = self.getUserInfos(request) return self.authz.assertUserAllowed(ep, action, options, user_info)
16,392
Python
.py
357
36.560224
98
0.654526
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,257
ws.py
buildbot_buildbot/master/buildbot/www/ws.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 import hashlib import json from autobahn.twisted.resource import WebSocketResource from autobahn.twisted.websocket import WebSocketServerFactory from autobahn.twisted.websocket import WebSocketServerProtocol from twisted.internet import defer from twisted.python import log from buildbot.util import bytes2unicode from buildbot.util import debounce from buildbot.util import toJson class Subscription: def __init__(self, query, id): self.query = query self.id = id self.last_value_chksum = None class WsProtocol(WebSocketServerProtocol): def __init__(self, master): super().__init__() self.master = master self.qrefs = {} self.debug = self.master.config.www.get("debug", False) self.is_graphql = None self.graphql_subs = {} self.graphql_consumer = None def to_json(self, msg): return json.dumps(msg, default=toJson, separators=(",", ":")).encode() def send_json_message(self, **msg): return self.sendMessage(self.to_json(msg)) def send_error(self, error, code, _id): if self.is_graphql: return self.send_json_message(message=error, type="error", id=_id) return self.send_json_message(error=error, code=code, _id=_id) def onMessage(self, frame, isBinary): """ Parse the incoming request. Can be either a graphql ws: https://github.com/apollographql/subscriptions-transport-ws/blob/master/PROTOCOL.md or legacy "buildbot" protocol (documented in www-server.rst) as they are very similar, we use the same routing method, distinguishing by the presence of _id or type attributes. """ if self.debug: log.msg(f"FRAME {frame}") frame = json.loads(bytes2unicode(frame)) _id = frame.get("_id") _type = frame.pop("type", None) if _id is None and _type is None: return self.send_error( error="no '_id' or 'type' in websocket frame", code=400, _id=None ) if _type is not None: cmdmeth = "graphql_cmd_" + _type if self.is_graphql is None: self.is_graphql = True elif not self.is_graphql: return self.send_error( error="using 'type' in websocket frame when" " already started using buildbot protocol", code=400, _id=None, ) else: if self.is_graphql is None: self.is_graphql = False elif self.is_graphql: return self.send_error( error="missing 'type' in websocket frame when already started using graphql", code=400, _id=None, ) self.is_graphql = False cmd = frame.pop("cmd", None) if cmd is None: return self.send_error(error="no 'cmd' in websocket frame", code=400, _id=None) cmdmeth = "cmd_" + cmd meth = getattr(self, cmdmeth, None) if meth is None: return self.send_error(error=f"no such command type '{cmd}'", code=404, _id=_id) try: return meth(**frame) except TypeError as e: return self.send_error(error=f"Invalid method argument '{e!s}'", code=400, _id=_id) except Exception as e: log.err(e, f"while calling command {cmdmeth}") return self.send_error(error=f"Internal Error '{e!s}'", code=500, _id=_id) # legacy protocol methods def ack(self, _id): return self.send_json_message(msg="OK", code=200, _id=_id) def parsePath(self, path): path = path.split("/") return tuple(str(p) if p != "*" else None for p in path) def isPath(self, path): if not isinstance(path, str): return False return True @defer.inlineCallbacks def cmd_startConsuming(self, path, _id): if not self.isPath(path): yield self.send_json_message(error=f"invalid path format '{path!s}'", code=400, _id=_id) return # if it's already subscribed, don't leak a subscription if self.qrefs is not None and path in self.qrefs: yield self.ack(_id=_id) return def callback(key, message): # protocol is deliberately concise in size return self.send_json_message(k="/".join(key), m=message) qref = yield self.master.mq.startConsuming(callback, self.parsePath(path)) # race conditions handling if self.qrefs is None or path in self.qrefs: qref.stopConsuming() # only store and ack if we were not disconnected in between if self.qrefs is not None: self.qrefs[path] = qref self.ack(_id=_id) @defer.inlineCallbacks def cmd_stopConsuming(self, path, _id): if not self.isPath(path): yield self.send_json_message(error=f"invalid path format '{path!s}'", code=400, _id=_id) return # only succeed if path has been started if path in self.qrefs: qref = self.qrefs.pop(path) yield qref.stopConsuming() yield self.ack(_id=_id) return yield self.send_json_message(error=f"path was not consumed '{path!s}'", code=400, _id=_id) def cmd_ping(self, _id): self.send_json_message(msg="pong", code=200, _id=_id) # graphql methods def graphql_cmd_connection_init(self, payload=None, id=None): return self.send_json_message(type="connection_ack") def graphql_got_event(self, key, message): # for now, we just ignore the events # an optimization would be to only re-run queries that # are impacted by the event self.graphql_dispatch_events() @debounce.method(0.1) @defer.inlineCallbacks def graphql_dispatch_events(self): """We got a bunch of events, dispatch them to the subscriptions For now, we just re-run all queries and see if they changed. We use a debouncer to ensure we only do that once a second per connection """ for sub in self.graphql_subs.values(): yield self.graphql_run_query(sub) @defer.inlineCallbacks def graphql_run_query(self, sub): res = yield self.master.graphql.query(sub.query) if res.data is None: # bad query, better not re-run it! self.graphql_cmd_stop(sub.id) errors = None if res.errors: errors = [e.formatted for e in res.errors] data = self.to_json({ "type": "data", "payload": {"data": res.data, "errors": errors}, "id": sub.id, }) cksum = hashlib.blake2b(data).digest() if cksum != sub.last_value_chksum: sub.last_value_chksum = cksum self.sendMessage(data) @defer.inlineCallbacks def graphql_cmd_start(self, id, payload=None): sub = Subscription(payload.get("query"), id) if not self.graphql_subs: # consume all events! self.graphql_consumer = yield self.master.mq.startConsuming( self.graphql_got_event, (None, None, None) ) self.graphql_subs[id] = sub yield self.graphql_run_query(sub) def graphql_cmd_stop(self, id, payload=None): if id in self.graphql_subs: del self.graphql_subs[id] else: return self.send_error(error="stopping unknown subscription", code=400, _id=id) if not self.graphql_subs and self.graphql_consumer: self.graphql_consumer.stopConsuming() self.graphql_consumer = None return None def connectionLost(self, reason): if self.debug: log.msg("connection lost", system=self) for qref in self.qrefs.values(): qref.stopConsuming() if self.graphql_consumer: self.graphql_consumer.stopConsuming() self.qrefs = None # to be sure we don't add any more def onConnect(self, request): # we don't mandate graphql-ws subprotocol, but if it is presented # we must acknowledge it if "graphql-ws" in request.protocols: self.is_graphql = True return "graphql-ws" return None class WsProtocolFactory(WebSocketServerFactory): def __init__(self, master): super().__init__() self.master = master pingInterval = self.master.config.www.get("ws_ping_interval", 0) self.setProtocolOptions(webStatus=False, autoPingInterval=pingInterval) def buildProtocol(self, addr): p = WsProtocol(self.master) p.factory = self return p class WsResource(WebSocketResource): def __init__(self, master): super().__init__(WsProtocolFactory(master))
9,652
Python
.py
225
33.577778
100
0.621336
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,258
roles.py
buildbot_buildbot/master/buildbot/www/authz/roles.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 RolesFromBase: def __init__(self): pass def getRolesFromUser(self, userDetails): return [] def setAuthz(self, authz): self.authz = authz self.master = authz.master class RolesFromGroups(RolesFromBase): def __init__(self, groupPrefix=""): super().__init__() self.groupPrefix = groupPrefix def getRolesFromUser(self, userDetails): roles = [] if 'groups' in userDetails: for group in userDetails['groups']: if group.startswith(self.groupPrefix): roles.append(group[len(self.groupPrefix) :]) return roles class RolesFromEmails(RolesFromBase): def __init__(self, **kwargs): super().__init__() self.roles = {} for role, emails in kwargs.items(): for email in emails: self.roles.setdefault(email, []).append(role) def getRolesFromUser(self, userDetails): if 'email' in userDetails: return self.roles.get(userDetails['email'], []) return [] class RolesFromDomain(RolesFromEmails): def __init__(self, **kwargs): super().__init__() self.domain_roles = {} for role, domains in kwargs.items(): for domain in domains: self.domain_roles.setdefault(domain, []).append(role) def getRolesFromUser(self, userDetails): if 'email' in userDetails: email = userDetails['email'] edomain = email.split('@')[-1] return self.domain_roles.get(edomain, []) return [] class RolesFromOwner(RolesFromBase): def __init__(self, role): super().__init__() self.role = role def getRolesFromUser(self, userDetails, owner): if 'email' in userDetails: if userDetails['email'] == owner and owner is not None: return [self.role] return [] class RolesFromUsername(RolesFromBase): def __init__(self, roles, usernames): self.roles = roles if None in usernames: from buildbot import config config.error('Usernames cannot be None') self.usernames = usernames def getRolesFromUser(self, userDetails): if userDetails.get('username') in self.usernames: return self.roles return []
3,056
Python
.py
77
32.025974
79
0.644692
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,259
endpointmatchers.py
buildbot_buildbot/master/buildbot/www/authz/endpointmatchers.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 inspect from twisted.internet import defer from buildbot.data.exceptions import InvalidPathError from buildbot.util import bytes2unicode class EndpointMatcherBase: def __init__(self, role, defaultDeny=True): self.role = role self.defaultDeny = defaultDeny self.owner = None def setAuthz(self, authz): self.authz = authz self.master = authz.master def match(self, ep, action="get", options=None): if options is None: options = {} try: epobject, epdict = self.master.data.getEndpoint(ep) for klass in inspect.getmro(epobject.__class__): m = getattr(self, "match_" + klass.__name__ + "_" + action, None) if m is not None: return m(epobject, epdict, options) m = getattr(self, "match_" + klass.__name__, None) if m is not None: return m(epobject, epdict, options) except InvalidPathError: return defer.succeed(None) return defer.succeed(None) def __repr__(self): # a repr for debugging. displays the class, and string attributes args = [] for k, v in self.__dict__.items(): if isinstance(v, str): args.append(f"{k}='{v}'") return f'{self.__class__.__name__}({", ".join(args)})' class Match: def __init__(self, master, build=None, buildrequest=None, buildset=None): self.master = master self.build = build self.buildrequest = buildrequest self.buildset = buildset def getOwner(self): if self.buildset: return self.getOwnerFromBuildset(self.buildset) elif self.buildrequest: return self.getOwnerFromBuildRequest(self.buildrequest) elif self.build: return self.getOwnerFromBuild(self.build) return defer.succeed(None) @defer.inlineCallbacks def getOwnerFromBuild(self, build): br = yield self.master.data.get(("buildrequests", build['buildrequestid'])) owner = yield self.getOwnerFromBuildRequest(br) return owner @defer.inlineCallbacks def getOwnerFromBuildsetOrBuildRequest(self, buildsetorbuildrequest): props = yield self.master.data.get(( "buildsets", buildsetorbuildrequest['buildsetid'], "properties", )) if 'owner' in props: return props['owner'][0] return None getOwnerFromBuildRequest = getOwnerFromBuildsetOrBuildRequest getOwnerFromBuildSet = getOwnerFromBuildsetOrBuildRequest class AnyEndpointMatcher(EndpointMatcherBase): def match(self, ep, action="get", options=None): return defer.succeed(Match(self.master)) class AnyControlEndpointMatcher(EndpointMatcherBase): def match(self, ep, action="", options=None): if bytes2unicode(action).lower() != "get": return defer.succeed(Match(self.master)) return defer.succeed(None) class StopBuildEndpointMatcher(EndpointMatcherBase): def __init__(self, builder=None, **kwargs): self.builder = builder super().__init__(**kwargs) @defer.inlineCallbacks def matchFromBuilderId(self, builderid): builder = yield self.master.data.get(('builders', builderid)) buildername = builder['name'] return self.authz.match(buildername, self.builder) @defer.inlineCallbacks def match_BuildEndpoint_stop(self, epobject, epdict, options): build = yield epobject.get({}, epdict) if self.builder is None: # no filtering needed: we match! return Match(self.master, build=build) # if filtering needed, we need to get some more info if build is not None: ret = yield self.matchFromBuilderId(build['builderid']) if ret: return Match(self.master, build=build) return None @defer.inlineCallbacks def match_BuildRequestEndpoint_stop(self, epobject, epdict, options): buildrequest = yield epobject.get({}, epdict) if self.builder is None: # no filtering needed: we match! return Match(self.master, buildrequest=buildrequest) # if filtering needed, we need to get some more info if buildrequest is not None: ret = yield self.matchFromBuilderId(buildrequest['builderid']) if ret: return Match(self.master, buildrequest=buildrequest) return None class ForceBuildEndpointMatcher(EndpointMatcherBase): def __init__(self, builder=None, **kwargs): self.builder = builder super().__init__(**kwargs) @defer.inlineCallbacks def match_ForceSchedulerEndpoint_force(self, epobject, epdict, options): if self.builder is None: # no filtering needed: we match without querying! return Match(self.master) sched = yield epobject.findForceScheduler(epdict['schedulername']) if sched is not None: builderNames = options.get('builderNames') builderid = options.get('builderid') builderNames = yield sched.computeBuilderNames(builderNames, builderid) for buildername in builderNames: if self.authz.match(buildername, self.builder): return Match(self.master) return None class RebuildBuildEndpointMatcher(EndpointMatcherBase): def __init__(self, builder=None, **kwargs): self.builder = builder super().__init__(**kwargs) @defer.inlineCallbacks def matchFromBuilderId(self, builderid): builder = yield self.master.data.get(('builders', builderid)) buildername = builder['name'] return self.authz.match(buildername, self.builder) @defer.inlineCallbacks def match_BuildEndpoint_rebuild(self, epobject, epdict, options): build = yield epobject.get({}, epdict) if self.builder is None: # no filtering needed: we match! return Match(self.master, build=build) # if filtering needed, we need to get some more info if build is not None: ret = yield self.matchFromBuilderId(build['builderid']) if ret: return Match(self.master, build=build) return None class EnableSchedulerEndpointMatcher(EndpointMatcherBase): def match_SchedulerEndpoint_enable(self, epobject, epdict, options): return defer.succeed(Match(self.master)) ##### # not yet implemented class ViewBuildsEndpointMatcher(EndpointMatcherBase): def __init__(self, branch=None, project=None, builder=None, **kwargs): super().__init__(**kwargs) self.branch = branch self.project = project self.builder = builder class BranchEndpointMatcher(EndpointMatcherBase): def __init__(self, branch, **kwargs): self.branch = branch super().__init__(**kwargs)
7,706
Python
.py
174
35.816092
83
0.662927
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,260
__init__.py
buildbot_buildbot/master/buildbot/www/authz/__init__.py
from buildbot.www.authz.authz import Authz from buildbot.www.authz.authz import Forbidden from buildbot.www.authz.authz import fnmatchStrMatcher from buildbot.www.authz.authz import reStrMatcher __all__ = ["Authz", "fnmatchStrMatcher", "reStrMatcher", "Forbidden"]
266
Python
.py
5
52
69
0.819231
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,261
authz.py
buildbot_buildbot/master/buildbot/www/authz/authz.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 fnmatch import re from twisted.internet import defer from twisted.web.error import Error from zope.interface import implementer from buildbot.interfaces import IConfigured from buildbot.util import unicode2bytes from buildbot.www.authz.roles import RolesFromOwner class Forbidden(Error): def __init__(self, msg): super().__init__(403, msg) # fnmatch and re.match are reversed API, we cannot just rename them def fnmatchStrMatcher(value, match): return fnmatch.fnmatch(value, match) def reStrMatcher(value, match): return re.match(match, value) @implementer(IConfigured) class Authz: def getConfigDict(self): return {} def __init__(self, allowRules=None, roleMatchers=None, stringsMatcher=fnmatchStrMatcher): self.match = stringsMatcher if allowRules is None: allowRules = [] if roleMatchers is None: roleMatchers = [] self.allowRules = allowRules self.roleMatchers = [r for r in roleMatchers if not isinstance(r, RolesFromOwner)] self.ownerRoleMatchers = [r for r in roleMatchers if isinstance(r, RolesFromOwner)] def setMaster(self, master): self.master = master for r in self.roleMatchers + self.ownerRoleMatchers + self.allowRules: r.setAuthz(self) def getRolesFromUser(self, userDetails): roles = set() for roleMatcher in self.roleMatchers: roles.update(set(roleMatcher.getRolesFromUser(userDetails))) return roles def getOwnerRolesFromUser(self, userDetails, owner): roles = set() for roleMatcher in self.ownerRoleMatchers: roles.update(set(roleMatcher.getRolesFromUser(userDetails, owner))) return roles @defer.inlineCallbacks def assertUserAllowed(self, ep, action, options, userDetails): roles = self.getRolesFromUser(userDetails) for rule in self.allowRules: match = yield rule.match(ep, action, options) if match is not None: # only try to get owner if there are owner Matchers if self.ownerRoleMatchers: owner = yield match.getOwner() if owner is not None: roles.update(self.getOwnerRolesFromUser(userDetails, owner)) for role in roles: if self.match(role, rule.role): return None if not rule.defaultDeny: continue # check next suitable rule if not denied error_msg = unicode2bytes(f"you need to have role '{rule.role}'") raise Forbidden(error_msg) return None
3,404
Python
.py
76
36.960526
93
0.688426
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,262
github.py
buildbot_buildbot/master/buildbot/www/hooks/github.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 hmac import json import logging import re from hashlib import sha1 from dateutil.parser import parse as dateparse from twisted.internet import defer from twisted.python import log from buildbot.process.properties import Properties from buildbot.util import bytes2unicode from buildbot.util import httpclientservice from buildbot.util import unicode2bytes from buildbot.util.pullrequest import PullRequestMixin from buildbot.www.hooks.base import BaseHookHandler _HEADER_EVENT = b'X-GitHub-Event' _HEADER_SIGNATURE = b'X-Hub-Signature' DEFAULT_SKIPS_PATTERN = (r'\[ *skip *ci *\]', r'\[ *ci *skip *\]') DEFAULT_GITHUB_API_URL = 'https://api.github.com' class GitHubEventHandler(PullRequestMixin): property_basename = "github" def __init__( self, secret, strict, codebase=None, github_property_whitelist=None, master=None, skips=None, github_api_endpoint=None, pullrequest_ref=None, token=None, debug=False, verify=False, ): if github_property_whitelist is None: github_property_whitelist = [] self._secret = secret self._strict = strict self._token = token self._codebase = codebase self.external_property_whitelist = github_property_whitelist self.pullrequest_ref = pullrequest_ref self.skips = skips self.github_api_endpoint = github_api_endpoint self.master = master if skips is None: self.skips = DEFAULT_SKIPS_PATTERN if github_api_endpoint is None: self.github_api_endpoint = DEFAULT_GITHUB_API_URL if self._strict and not self._secret: raise ValueError('Strict mode is requested while no secret is provided') self.debug = debug self.verify = verify @defer.inlineCallbacks def process(self, request): payload = yield self._get_payload(request) event_type = request.getHeader(_HEADER_EVENT) event_type = bytes2unicode(event_type) log.msg(f"X-GitHub-Event: {event_type}", logLevel=logging.DEBUG) handler = getattr(self, f'handle_{event_type}', None) if handler is None: raise ValueError(f'Unknown event: {event_type}') result = yield handler(payload, event_type) return result @defer.inlineCallbacks def _get_payload(self, request): content = request.content.read() content = bytes2unicode(content) signature = request.getHeader(_HEADER_SIGNATURE) signature = bytes2unicode(signature) if not signature and self._strict: raise ValueError('Request has no required signature') if self._secret and signature: try: hash_type, hexdigest = signature.split('=') except ValueError as e: raise ValueError(f'Wrong signature format: {signature}') from e if hash_type != 'sha1': raise ValueError(f'Unknown hash type: {hash_type}') p = Properties() p.master = self.master rendered_secret = yield p.render(self._secret) mac = hmac.new( unicode2bytes(rendered_secret), msg=unicode2bytes(content), digestmod=sha1 ) def _cmp(a, b): return hmac.compare_digest(a, b) if not _cmp(bytes2unicode(mac.hexdigest()), hexdigest): raise ValueError('Hash mismatch') 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(bytes2unicode(request.args[b'payload'][0])) else: raise ValueError(f'Unknown content type: {content_type}') log.msg(f"Payload: {payload}", logLevel=logging.DEBUG) return payload def handle_ping(self, _, __): return [], 'git' def handle_workflow_run(self, _, __): return [], 'git' def handle_push(self, payload, event): # This field is unused: user = None # user = payload['pusher']['name'] repo = payload['repository']['name'] repo_url = payload['repository']['html_url'] # NOTE: what would be a reasonable value for project? # project = request.args.get('project', [''])[0] project = payload['repository']['full_name'] # Inject some additional white-listed event payload properties properties = self.extractProperties(payload) changes = self._process_change(payload, user, repo, repo_url, project, event, properties) log.msg(f"Received {len(changes)} changes from github") return changes, 'git' @defer.inlineCallbacks def handle_pull_request(self, payload, event): changes = [] number = payload['number'] refname = f'refs/pull/{number}/{self.pullrequest_ref}' basename = payload['pull_request']['base']['ref'] commits = payload['pull_request']['commits'] title = payload['pull_request']['title'] comments = payload['pull_request']['body'] repo_full_name = payload['repository']['full_name'] head_sha = payload['pull_request']['head']['sha'] revlink = payload['pull_request']['_links']['html']['href'] log.msg(f'Processing GitHub PR #{number}', logLevel=logging.DEBUG) head_msg = yield self._get_commit_msg(repo_full_name, head_sha) if self._has_skip(head_msg): log.msg(f"GitHub PR #{number}, Ignoring: head commit message contains skip pattern") return ([], 'git') action = payload.get('action') if action not in ('opened', 'reopened', 'synchronize'): log.msg(f"GitHub PR #{number} {action}, ignoring") return (changes, 'git') files = yield self._get_pr_files(repo_full_name, number) properties = { 'pullrequesturl': revlink, 'event': event, 'basename': basename, **self.extractProperties(payload['pull_request']), } change = { 'revision': payload['pull_request']['head']['sha'], 'when_timestamp': dateparse(payload['pull_request']['created_at']), 'branch': refname, 'files': files, 'revlink': payload['pull_request']['_links']['html']['href'], 'repository': payload['repository']['html_url'], 'project': payload['pull_request']['base']['repo']['full_name'], 'category': 'pull', # TODO: Get author name based on login id using txgithub module 'author': payload['sender']['login'], 'comments': ( f"GitHub Pull Request #{number} ({commits} " f"commit{'s' if commits != 1 else ''})\n{title}\n{comments}" ), 'properties': properties, } if callable(self._codebase): change['codebase'] = self._codebase(payload) elif self._codebase is not None: change['codebase'] = self._codebase changes.append(change) log.msg(f"Received {len(changes)} changes from GitHub PR #{number}") return (changes, 'git') @defer.inlineCallbacks def _get_commit_msg(self, repo, sha): """ :param repo: the repo full name, ``{owner}/{project}``. e.g. ``buildbot/buildbot`` """ headers = { 'User-Agent': 'Buildbot', } if self._token: p = Properties() p.master = self.master p.setProperty("full_name", repo, "change_hook") token = yield p.render(self._token) headers['Authorization'] = 'token ' + token url = f'/repos/{repo}/commits/{sha}' http = yield httpclientservice.HTTPSession( self.master.httpservice, self.github_api_endpoint, headers=headers, debug=self.debug, verify=self.verify, ) res = yield http.get(url) if 200 <= res.code < 300: data = yield res.json() return data['commit']['message'] log.msg(f'Failed fetching PR commit message: response code {res.code}') return 'No message field' @defer.inlineCallbacks def _get_pr_files(self, repo, number): """ Get Files that belong to the Pull Request :param repo: the repo full name, ``{owner}/{project}``. e.g. ``buildbot/buildbot`` :param number: the pull request number. """ headers = {"User-Agent": "Buildbot"} if self._token: p = Properties() p.master = self.master p.setProperty("full_name", repo, "change_hook") token = yield p.render(self._token) headers["Authorization"] = "token " + token url = f"/repos/{repo}/pulls/{number}/files" http = yield httpclientservice.HTTPSession( self.master.httpservice, self.github_api_endpoint, headers=headers, debug=self.debug, verify=self.verify, ) res = yield http.get(url) if 200 <= res.code < 300: data = yield res.json() filenames = [] for f in data: filenames.append(f["filename"]) # If a file was moved this tell us where it was moved from. previous_filename = f.get("previous_filename") if previous_filename is not None: filenames.append(previous_filename) return filenames log.msg(f'Failed fetching PR files: response code {res.code}') return [] def _process_change(self, payload, user, repo, repo_url, project, event, properties): """ 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 = [] refname = payload['ref'] # We only care about regular heads or tags match = re.match(r"^refs/(heads|tags)/(.+)$", refname) if not match: log.msg(f"Ignoring refname `{refname}': Not a branch") return changes category = None # None is the legacy category for when hook only supported push if match.group(1) == "tags": category = "tag" branch = match.group(2) if payload.get('deleted'): log.msg(f"Branch `{branch}' deleted, ignoring") return changes # check skip pattern in commit message. e.g.: [ci skip] and [skip ci] head_msg = payload['head_commit'].get('message', '') if self._has_skip(head_msg): return changes commits = payload['commits'] if payload.get('created'): commits = [payload['head_commit']] for commit in commits: files = [] for kind in ('added', 'modified', 'removed'): files.extend(commit.get(kind, [])) when_timestamp = dateparse(commit['timestamp']) log.msg(f"New revision: {commit['id'][:8]}") change = { 'author': f"{commit['author']['name']} <{commit['author']['email']}>", 'committer': f"{commit['committer']['name']} <{commit['committer']['email']}>", 'files': files, 'comments': commit['message'], 'revision': commit['id'], 'when_timestamp': when_timestamp, 'branch': branch, 'revlink': commit['url'], 'repository': repo_url, 'project': project, 'properties': { 'github_distinct': commit.get('distinct', True), 'event': event, }, 'category': category, } # Update with any white-listed github event properties change['properties'].update(properties) if callable(self._codebase): change['codebase'] = self._codebase(payload) elif self._codebase is not None: change['codebase'] = self._codebase changes.append(change) return changes def _has_skip(self, msg): """ The message contains the skipping keyword or not. :return type: Bool """ for skip in self.skips: if re.search(skip, msg): return True return False # for GitHub, we do another level of indirection because # we already had documented API that encouraged people to subclass GitHubEventHandler # so we need to be careful not breaking that API. class GitHubHandler(BaseHookHandler): def __init__(self, master, options): if options is None: options = {} super().__init__(master, options) klass = options.get('class', GitHubEventHandler) klass_kwargs = { 'master': master, 'codebase': options.get('codebase', None), 'github_property_whitelist': options.get('github_property_whitelist', None), 'skips': options.get('skips', None), 'github_api_endpoint': options.get('github_api_endpoint', None) or 'https://api.github.com', 'pullrequest_ref': options.get('pullrequest_ref', None) or 'merge', 'token': options.get('token', None), 'debug': options.get('debug', None) or False, 'verify': options.get('verify', None) or False, } handler = klass(options.get('secret', None), options.get('strict', False), **klass_kwargs) self.handler = handler def getChanges(self, request): return self.handler.process(request) github = GitHubHandler
14,759
Python
.py
342
33.04386
98
0.594702
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,263
gitlab.py
buildbot_buildbot/master/buildbot/www/hooks/gitlab.py
# This file is part of Buildbot. Buildbot is free software: you can # redistribute it and/or modify it under the terms of the GNU General Public # License as published by the Free Software Foundation, version 2. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more # details. # # You should have received a copy of the GNU General Public License along with # this program; if not, write to the Free Software Foundation, Inc., 51 # Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # Copyright Buildbot Team Members import json import re from dateutil.parser import parse as dateparse from twisted.internet.defer import inlineCallbacks from twisted.python import log from buildbot.process.properties import Properties from buildbot.util import bytes2unicode from buildbot.www.hooks.base import BaseHookHandler _HEADER_EVENT = b'X-Gitlab-Event' _HEADER_GITLAB_TOKEN = b'X-Gitlab-Token' class GitLabHandler(BaseHookHandler): def _process_change(self, payload, user, repo, repo_url, event, codebase=None): """ Consumes the JSON as a python object and actually starts the build. :arguments: payload Python Object that represents the JSON sent by GitLab Service Hook. """ changes = [] refname = payload['ref'] # project name from http headers is empty for me, so get it from repository/name project = payload['repository']['name'] # We only care about regular heads or tags match = re.match(r"^refs/(heads|tags)/(.+)$", refname) if not match: log.msg(f"Ignoring refname `{refname}': Not a branch") return changes branch = match.group(2) if payload.get('deleted'): log.msg(f"Branch `{branch}' deleted, ignoring") return changes for commit in payload['commits']: if not commit.get('distinct', True): log.msg(f"Commit `{commit['id']}` is a non-distinct commit, ignoring...") continue files = [] for kind in ('added', 'modified', 'removed'): files.extend(commit.get(kind, [])) when_timestamp = dateparse(commit['timestamp']) log.msg(f"New revision: {commit['id'][:8]}") change = { 'author': f"{commit['author']['name']} <{commit['author']['email']}>", 'files': files, 'comments': commit['message'], 'revision': commit['id'], 'when_timestamp': when_timestamp, 'branch': branch, 'revlink': commit['url'], 'repository': repo_url, 'project': project, 'category': event, 'properties': { 'event': event, }, } if codebase is not None: change['codebase'] = codebase changes.append(change) return changes def _process_merge_request_change(self, payload, event, codebase=None): """ Consumes the merge_request JSON as a python object and turn it into a buildbot change. :arguments: payload Python Object that represents the JSON sent by GitLab Service Hook. """ attrs = payload['object_attributes'] commit = attrs['last_commit'] when_timestamp = dateparse(commit['timestamp']) # @todo provide and document a way to choose between http and ssh url repo_url = attrs['target']['git_http_url'] # project name from http headers is empty for me, so get it from # object_attributes/target/name project = attrs['target']['name'] # Filter out uninteresting events state = attrs['state'] if re.match('^(closed|merged|approved)$', state): log.msg(f"GitLab MR#{attrs['iid']}: Ignoring because state is {state}") return [] action = attrs['action'] if not re.match('^(open|reopen)$', action) and not ( action == "update" and "oldrev" in attrs ): log.msg( f"GitLab MR#{attrs['iid']}: Ignoring because action {action} was not open or " "reopen or an update that added code" ) return [] changes = [ { 'author': f"{commit['author']['name']} <{commit['author']['email']}>", 'files': [], # @todo use rest API 'comments': f"MR#{attrs['iid']}: {attrs['title']}\n\n{attrs['description']}", 'revision': commit['id'], 'when_timestamp': when_timestamp, 'branch': attrs['target_branch'], 'repository': repo_url, 'project': project, 'category': event, 'revlink': attrs['url'], 'properties': { 'source_branch': attrs['source_branch'], 'source_project_id': attrs['source_project_id'], 'source_repository': attrs['source']['git_http_url'], 'source_git_ssh_url': attrs['source']['git_ssh_url'], 'target_branch': attrs['target_branch'], 'target_project_id': attrs['target_project_id'], 'target_repository': attrs['target']['git_http_url'], 'target_git_ssh_url': attrs['target']['git_ssh_url'], 'event': event, }, } ] if codebase is not None: changes[0]['codebase'] = codebase return changes def _process_note_addition_to_merge_request(self, payload, event, codebase=None): """ Consumes a note event JSON as a python object and turn it into a buildbot change. :arguments: payload Python Object that represents the JSON sent by GitLab Service Hook. Comments in merge_requests are send as note events by the API """ attrs = payload['object_attributes'] # handle only note events coming from merge_requests # this can be direct comments or comments added to a changeset of the MR # # editing a comment does NOT lead to an event at all if 'merge_request' not in payload: log.msg(f"Found note event (id {attrs['id']}) without corresponding MR - ignore") return [] # change handling is very similar to the method above, but commit = payload['merge_request']['last_commit'] when_timestamp = dateparse(commit['timestamp']) # @todo provide and document a way to choose between http and ssh url repo_url = payload['merge_request']['target']['git_http_url'] # project name from http headers is empty for me, so get it from # object_attributes/target/name mr = payload['merge_request'] project = mr['target']['name'] log.msg(f"Found notes on MR#{mr['iid']}: {attrs['note']}") changes = [ { 'author': f"{commit['author']['name']} <{commit['author']['email']}>", 'files': [], # not provided by rest API 'comments': f"MR#{mr['iid']}: {mr['title']}\n\n{mr['description']}", 'revision': commit['id'], 'when_timestamp': when_timestamp, 'branch': mr['target_branch'], 'repository': repo_url, 'project': project, 'category': event, 'revlink': mr['url'], 'properties': { 'source_branch': mr['source_branch'], 'source_project_id': mr['source_project_id'], 'source_repository': mr['source']['git_http_url'], 'source_git_ssh_url': mr['source']['git_ssh_url'], 'target_branch': mr['target_branch'], 'target_project_id': mr['target_project_id'], 'target_repository': mr['target']['git_http_url'], 'target_git_ssh_url': mr['target']['git_ssh_url'], 'event': event, 'comments': attrs['note'], }, } ] if codebase is not None: changes[0]['codebase'] = codebase return changes @inlineCallbacks def getChanges(self, request): """ Reponds only to POST events and starts the build process :arguments: request the http request object """ expected_secret = isinstance(self.options, dict) and self.options.get('secret') if expected_secret: received_secret = request.getHeader(_HEADER_GITLAB_TOKEN) received_secret = bytes2unicode(received_secret) p = Properties() p.master = self.master expected_secret_value = yield p.render(expected_secret) if received_secret != expected_secret_value: raise ValueError("Invalid secret") try: content = request.content.read() payload = json.loads(bytes2unicode(content)) except Exception as e: raise ValueError("Error loading JSON: " + str(e)) from e event_type = request.getHeader(_HEADER_EVENT) event_type = bytes2unicode(event_type) # newer version of gitlab have a object_kind parameter, # which allows not to use the http header event_type = payload.get('object_kind', event_type) codebase = request.args.get(b'codebase', [None])[0] codebase = bytes2unicode(codebase) if event_type in ("push", "tag_push", "Push Hook"): user = payload['user_name'] repo = payload['repository']['name'] repo_url = payload['repository']['url'] changes = self._process_change( payload, user, repo, repo_url, event_type, codebase=codebase ) elif event_type == 'merge_request': changes = self._process_merge_request_change(payload, event_type, codebase=codebase) elif event_type == 'note': changes = self._process_note_addition_to_merge_request( payload, event_type, codebase=codebase ) else: changes = [] if changes: log.msg(f"Received {len(changes)} changes from {event_type} gitlab event") return (changes, 'git') gitlab = GitLabHandler
10,808
Python
.py
236
33.991525
96
0.566901
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,264
poller.py
buildbot_buildbot/master/buildbot/www/hooks/poller.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 change hook allows GitHub or a hand crafted curl invocation to "knock on # the door" and trigger a change source to poll. from buildbot.changes.base import ReconfigurablePollingChangeSource from buildbot.util import bytes2unicode from buildbot.util import unicode2bytes from buildbot.www.hooks.base import BaseHookHandler class PollingHandler(BaseHookHandler): def getChanges(self, req): change_svc = req.site.master.change_svc poll_all = b"poller" not in req.args allow_all = True allowed = [] if isinstance(self.options, dict) and b"allowed" in self.options: allow_all = False allowed = self.options[b"allowed"] pollers = [] for source in change_svc: if not isinstance(source, ReconfigurablePollingChangeSource): continue if not hasattr(source, "name"): continue if not poll_all and unicode2bytes(source.name) not in req.args[b'poller']: continue if not allow_all and unicode2bytes(source.name) not in allowed: continue pollers.append(source) if not poll_all: missing = set(req.args[b'poller']) - set(unicode2bytes(s.name) for s in pollers) if missing: raise ValueError(f'Could not find pollers: {bytes2unicode(b",".join(missing))}') for p in pollers: p.force() return [], None poller = PollingHandler
2,213
Python
.py
48
38.916667
96
0.692844
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,265
bitbucketserver.py
buildbot_buildbot/master/buildbot/www/hooks/bitbucketserver.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 # Copyright Mamba Team import json from twisted.python import log from buildbot.util import bytes2unicode from buildbot.util.pullrequest import PullRequestMixin GIT_BRANCH_REF = "refs/heads/{}" GIT_MERGE_REF = "refs/pull-requests/{}/merge" GIT_TAG_REF = "refs/tags/{}" _HEADER_EVENT = b'X-Event-Key' class BitbucketServerEventHandler(PullRequestMixin): property_basename = "bitbucket" def __init__(self, master, options=None): if options is None: options = {} self.master = master if not isinstance(options, dict): options = {} self.options = options self._codebase = self.options.get('codebase', None) self.external_property_whitelist = self.options.get('bitbucket_property_whitelist', []) def process(self, request): payload = self._get_payload(request) event_type = bytes2unicode(request.getHeader(_HEADER_EVENT)) log.msg(f"Processing event {_HEADER_EVENT.decode()}: {event_type}") event_type = event_type.replace(":", "_") handler = getattr(self, f'handle_{event_type}', None) if handler is None: raise ValueError(f'Unknown event: {event_type}') return handler(payload) def _get_payload(self, request): content = request.content.read() content = bytes2unicode(content) content_type = request.getHeader(b'Content-Type') content_type = bytes2unicode(content_type) if content_type.startswith('application/json'): payload = json.loads(content) else: raise ValueError(f'Unknown content type: {content_type}') log.msg(f"Payload: {payload}") return payload def handle_repo_refs_changed(self, payload): return self._handle_repo_refs_changed_common(payload) def handle_repo_push(self, payload): # repo:push works exactly like repo:refs_changed, but is no longer documented (not even # in the historical documentation of old versions of Bitbucket Server). The old code path # has been preserved for backwards compatibility. return self._handle_repo_refs_changed_common(payload) def _handle_repo_refs_changed_common(self, payload): changes = [] project = payload['repository']['project']['name'] repo_url = payload['repository']['links']['self'][0]['href'] repo_url = repo_url.rstrip('browse') for payload_change in payload['push']['changes']: if payload_change['new']: age = 'new' category = 'push' else: # when new is null the ref is deleted age = 'old' category = 'ref-deleted' commit_hash = payload_change[age]['target']['hash'] branch = None if payload_change[age]['type'] == 'branch': branch = GIT_BRANCH_REF.format(payload_change[age]['name']) elif payload_change[age]['type'] == 'tag': branch = GIT_TAG_REF.format(payload_change[age]['name']) change = { 'revision': commit_hash, 'revlink': f'{repo_url}commits/{commit_hash}', 'repository': repo_url, 'author': f"{payload['actor']['displayName']} <{payload['actor']['username']}>", 'comments': f'Bitbucket Server commit {commit_hash}', 'branch': branch, 'project': project, 'category': category, } if callable(self._codebase): change['codebase'] = self._codebase(payload) elif self._codebase is not None: change['codebase'] = self._codebase changes.append(change) return (changes, payload['repository']['scmId']) def handle_pullrequest_created(self, payload): return self.handle_pullrequest( payload, GIT_MERGE_REF.format(int(payload['pullrequest']['id'])), "pull-created" ) def handle_pullrequest_updated(self, payload): return self.handle_pullrequest( payload, GIT_MERGE_REF.format(int(payload['pullrequest']['id'])), "pull-updated" ) def handle_pullrequest_fulfilled(self, payload): return self.handle_pullrequest( payload, GIT_BRANCH_REF.format(payload['pullrequest']['toRef']['branch']['name']), "pull-fulfilled", ) def handle_pullrequest_rejected(self, payload): return self.handle_pullrequest( payload, GIT_BRANCH_REF.format(payload['pullrequest']['fromRef']['branch']['name']), "pull-rejected", ) def handle_pullrequest(self, payload, refname, category): pr_number = int(payload['pullrequest']['id']) repo_url = payload['repository']['links']['self'][0]['href'] repo_url = repo_url.rstrip('browse') revlink = payload['pullrequest']['link'] change = { 'revision': payload['pullrequest']['fromRef']['commit']['hash'], 'revlink': revlink, 'repository': repo_url, 'author': f"{payload['actor']['displayName']} <{payload['actor']['username']}>", 'comments': f'Bitbucket Server Pull Request #{pr_number}', 'branch': refname, 'project': payload['repository']['project']['name'], 'category': category, 'properties': { 'pullrequesturl': revlink, **self.extractProperties(payload['pullrequest']), }, } if callable(self._codebase): change['codebase'] = self._codebase(payload) elif self._codebase is not None: change['codebase'] = self._codebase return [change], payload['repository']['scmId'] def getChanges(self, request): return self.process(request) bitbucketserver = BitbucketServerEventHandler
6,660
Python
.py
142
37.401408
97
0.622243
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,266
base.py
buildbot_buildbot/master/buildbot/www/hooks/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 # # code inspired/copied from contrib/github_buildbot # and inspired from code from the Chromium project # otherwise, Andrew Melo <[email protected]> wrote the rest # but "the rest" is pretty minimal import json from buildbot.util import bytes2unicode class BaseHookHandler: def __init__(self, master, options): self.master = master self.options = options def getChanges(self, request): """ Consumes a naive build notification (the default for now) basically, set POST variables to match commit object parameters: revision, revlink, comments, branch, who, files, links files, links and properties will be de-json'd, the rest are interpreted as strings """ def firstOrNothing(value): """ Small helper function to return the first value (if value is a list) or return the whole thing otherwise. Make sure to properly decode bytes to unicode strings. """ if isinstance(value, type([])): value = value[0] return bytes2unicode(value) args = request.args # first, convert files, links and properties files = None if args.get(b'files'): files = json.loads(firstOrNothing(args.get(b'files'))) else: files = [] properties = None if args.get(b'properties'): properties = json.loads(firstOrNothing(args.get(b'properties'))) else: properties = {} revision = firstOrNothing(args.get(b'revision')) when = firstOrNothing(args.get(b'when_timestamp')) if when is None: when = firstOrNothing(args.get(b'when')) if when is not None: when = float(when) author = firstOrNothing(args.get(b'author')) if not author: author = firstOrNothing(args.get(b'who')) committer = firstOrNothing(args.get(b'committer')) comments = firstOrNothing(args.get(b'comments')) branch = firstOrNothing(args.get(b'branch')) category = firstOrNothing(args.get(b'category')) revlink = firstOrNothing(args.get(b'revlink')) repository = firstOrNothing(args.get(b'repository')) or '' project = firstOrNothing(args.get(b'project')) or '' codebase = firstOrNothing(args.get(b'codebase')) chdict = { "author": author, "committer": committer, "files": files, "comments": comments, "revision": revision, "when_timestamp": when, "branch": branch, "category": category, "revlink": revlink, "properties": properties, "repository": repository, "project": project, "codebase": codebase, } return ([chdict], None) base = BaseHookHandler # alternate name for buildbot plugin
3,660
Python
.py
87
33.770115
90
0.64362
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,267
gitorious.py
buildbot_buildbot/master/buildbot/www/hooks/gitorious.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 # # note: this file is based on github.py import json import re from dateutil.parser import parse as dateparse from twisted.python import log from buildbot.util import bytes2unicode from buildbot.www.hooks.base import BaseHookHandler class GitoriousHandler(BaseHookHandler): def getChanges(self, request): payload = json.loads(bytes2unicode(request.args[b'payload'][0])) user = payload['repository']['owner']['name'] repo = payload['repository']['name'] repo_url = payload['repository']['url'] project = payload['project']['name'] changes = self.process_change(payload, user, repo, repo_url, project) log.msg(f"Received {len(changes)} changes from gitorious") return (changes, 'git') def process_change(self, payload, user, repo, repo_url, project): changes = [] newrev = payload['after'] branch = payload['ref'] if re.match(r"^0*$", newrev): log.msg(f"Branch `{branch}' deleted, ignoring") return [] else: for commit in payload['commits']: files = [] # Gitorious doesn't send these, maybe later # if 'added' in commit: # files.extend(commit['added']) # if 'modified' in commit: # files.extend(commit['modified']) # if 'removed' in commit: # files.extend(commit['removed']) when_timestamp = dateparse(commit['timestamp']) log.msg(f"New revision: {commit['id'][:8]}") changes.append({ 'author': f"{commit['author']['name']} <{commit['author']['email']}>", 'files': files, 'comments': commit['message'], 'revision': commit['id'], 'when_timestamp': when_timestamp, 'branch': branch, 'revlink': commit['url'], 'repository': repo_url, 'project': project, }) return changes gitorious = GitoriousHandler
2,855
Python
.py
64
35.15625
90
0.608711
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,268
bitbucketcloud.py
buildbot_buildbot/master/buildbot/www/hooks/bitbucketcloud.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 # Copyright Mamba Team import json from twisted.python import log from buildbot.util import bytes2unicode from buildbot.util.pullrequest import PullRequestMixin GIT_BRANCH_REF = "refs/heads/{}" GIT_MERGE_REF = "refs/pull-requests/{}/merge" GIT_TAG_REF = "refs/tags/{}" _HEADER_EVENT = b'X-Event-Key' class BitbucketCloudEventHandler(PullRequestMixin): property_basename = "bitbucket" def __init__(self, master, options=None): self.master = master if not isinstance(options, dict): options = {} self.options = options self._codebase = self.options.get('codebase', None) self.external_property_whitelist = self.options.get('bitbucket_property_whitelist', []) def process(self, request): payload = self._get_payload(request) event_type = bytes2unicode(request.getHeader(_HEADER_EVENT)) log.msg(f"Processing event {_HEADER_EVENT.decode()}: {event_type}") event_type = event_type.replace(":", "_") handler = getattr(self, f'handle_{event_type}', None) if handler is None: raise ValueError(f'Unknown event: {event_type}') return handler(payload) def _get_payload(self, request): content = request.content.read() content = bytes2unicode(content) content_type = request.getHeader(b'Content-Type') content_type = bytes2unicode(content_type) if content_type.startswith('application/json'): payload = json.loads(content) else: raise ValueError(f'Unknown content type: {content_type}') log.msg(f"Payload: {payload}") return payload def handle_repo_push(self, payload): changes = [] project = payload['repository'].get('project', {'name': 'none'})['name'] repo_url = payload['repository']['links']['self']['href'] web_url = payload['repository']['links']['html']['href'] for payload_change in payload['push']['changes']: if payload_change['new']: age = 'new' category = 'push' else: # when new is null the ref is deleted age = 'old' category = 'ref-deleted' commit_hash = payload_change[age]['target']['hash'] branch = None if payload_change[age]['type'] == 'branch': branch = GIT_BRANCH_REF.format(payload_change[age]['name']) elif payload_change[age]['type'] == 'tag': branch = GIT_TAG_REF.format(payload_change[age]['name']) change = { 'revision': commit_hash, 'revlink': f'{web_url}/commits/{commit_hash}', 'repository': repo_url, 'author': f"{payload['actor']['display_name']} <{payload['actor']['nickname']}>", 'comments': f'Bitbucket Cloud commit {commit_hash}', 'branch': branch, 'project': project, 'category': category, } if callable(self._codebase): change['codebase'] = self._codebase(payload) elif self._codebase is not None: change['codebase'] = self._codebase changes.append(change) return (changes, payload['repository']['scm']) def handle_pullrequest_created(self, payload): return self.handle_pullrequest( payload, GIT_MERGE_REF.format(int(payload['pullrequest']['id'])), "pull-created" ) def handle_pullrequest_updated(self, payload): return self.handle_pullrequest( payload, GIT_MERGE_REF.format(int(payload['pullrequest']['id'])), "pull-updated" ) def handle_pullrequest_fulfilled(self, payload): return self.handle_pullrequest( payload, GIT_BRANCH_REF.format(payload['pullrequest']['toRef']['branch']['name']), "pull-fulfilled", ) def handle_pullrequest_rejected(self, payload): return self.handle_pullrequest( payload, GIT_BRANCH_REF.format(payload['pullrequest']['fromRef']['branch']['name']), "pull-rejected", ) def handle_pullrequest(self, payload, refname, category): pr_number = int(payload['pullrequest']['id']) repo_url = payload['repository']['links']['self']['href'] project = payload['repository'].get('project', {'name': 'none'})['name'] revlink = payload['pullrequest']['link'] change = { 'revision': payload['pullrequest']['fromRef']['commit']['hash'], 'revlink': revlink, 'repository': repo_url, 'author': f"{payload['actor']['display_name']} <{payload['actor']['nickname']}>", 'comments': f'Bitbucket Cloud Pull Request #{pr_number}', 'branch': refname, 'project': project, 'category': category, 'properties': { 'pullrequesturl': revlink, **self.extractProperties(payload['pullrequest']), }, } if callable(self._codebase): change['codebase'] = self._codebase(payload) elif self._codebase is not None: change['codebase'] = self._codebase return [change], payload['repository']['scm'] def getChanges(self, request): return self.process(request) bitbucketcloud = BitbucketCloudEventHandler
6,155
Python
.py
133
36.729323
97
0.613458
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,269
bitbucket.py
buildbot_buildbot/master/buildbot/www/hooks/bitbucket.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 # Copyright 2013 (c) Mamba Team import json from dateutil.parser import parse as dateparse from twisted.python import log from buildbot.util import bytes2unicode from buildbot.www.hooks.base import BaseHookHandler _HEADER_EVENT = b'X-Event-Key' class BitBucketHandler(BaseHookHandler): def getChanges(self, request): """Catch a POST request from BitBucket and start a build process Check the URL below if you require more information about payload https://confluence.atlassian.com/display/BITBUCKET/POST+Service+Management :param request: the http request Twisted object :param options: additional options """ event_type = request.getHeader(_HEADER_EVENT) event_type = bytes2unicode(event_type) payload = json.loads(bytes2unicode(request.args[b'payload'][0])) repo_url = f"{payload['canon_url']}{payload['repository']['absolute_url']}" project = request.args.get(b'project', [b''])[0] project = bytes2unicode(project) changes = [] for commit in payload['commits']: changes.append({ 'author': commit['raw_author'], 'files': [f['file'] for f in commit['files']], 'comments': commit['message'], 'revision': commit['raw_node'], 'when_timestamp': dateparse(commit['utctimestamp']), 'branch': commit['branch'], 'revlink': f"{repo_url}commits/{commit['raw_node']}", 'repository': repo_url, 'project': project, 'properties': { 'event': event_type, }, }) log.msg(f"New revision: {commit['node']}") log.msg(f'Received {len(changes)} changes from bitbucket') return (changes, payload['repository']['scm']) bitbucket = BitBucketHandler
2,607
Python
.py
55
39.527273
83
0.662727
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,270
usersclient.py
buildbot_buildbot/master/buildbot/clients/usersclient.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 class is known to contain cruft and will be looked at later, so # no current implementation utilizes it aside from scripts.runner. from twisted.cred import credentials from twisted.internet import reactor from twisted.spread import pb class UsersClient: """ Client set up in buildbot.scripts.runner to send `buildbot user` args over a PB connection to perspective_commandline that will execute the args on the database. """ def __init__(self, master, username, password, port): self.host = master self.username = username self.password = password self.port = int(port) def send(self, op, bb_username, bb_password, ids, info): f = pb.PBClientFactory() d = f.login(credentials.UsernamePassword(self.username, self.password)) reactor.connectTCP(self.host, self.port, f) @d.addCallback def call_commandline(remote): d = remote.callRemote("commandline", op, bb_username, bb_password, ids, info) @d.addCallback def returnAndLose(res): remote.broker.transport.loseConnection() return res return d return d
1,909
Python
.py
43
38.790698
89
0.716056
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,271
sendchange.py
buildbot_buildbot/master/buildbot/clients/sendchange.py
# This file is part of Buildbot. Buildbot is free software: you can # redistribute it and/or modify it under the terms of the GNU General Public # License as published by the Free Software Foundation, version 2. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more # details. # # You should have received a copy of the GNU General Public License along with # this program; if not, write to the Free Software Foundation, Inc., 51 # Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # Copyright Buildbot Team Members from twisted.cred import credentials from twisted.internet import reactor from twisted.spread import pb from buildbot.util import unicode2bytes class Sender: def __init__(self, master, auth=('change', 'changepw'), encoding='utf8'): self.username = unicode2bytes(auth[0]) self.password = unicode2bytes(auth[1]) self.host, self.port = master.split(":") self.port = int(self.port) self.encoding = encoding def send( self, branch, revision, comments, files, who=None, category=None, when=None, properties=None, repository='', vc=None, project='', revlink='', codebase=None, ): if properties is None: properties = {} change = { 'project': project, 'repository': repository, 'who': who, 'files': files, 'comments': comments, 'branch': branch, 'revision': revision, 'category': category, 'when': when, 'properties': properties, 'revlink': revlink, 'src': vc, } # codebase is only sent if set; this won't work with masters older than # 0.8.7 if codebase: change['codebase'] = codebase for key, value in change.items(): if isinstance(value, bytes): change[key] = value.decode(self.encoding, 'replace') change['files'] = list(change['files']) for i, file in enumerate(change.get('files', [])): if isinstance(file, bytes): change['files'][i] = file.decode(self.encoding, 'replace') f = pb.PBClientFactory() d = f.login(credentials.UsernamePassword(self.username, self.password)) reactor.connectTCP(self.host, self.port, f) @d.addCallback def call_addChange(remote): d = remote.callRemote('addChange', change) d.addCallback(lambda res: remote.broker.transport.loseConnection()) return d return d
2,844
Python
.py
77
28.727273
79
0.619376
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,272
tryclient.py
buildbot_buildbot/master/buildbot/clients/tryclient.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 import random import re import shlex import string import sys import time from twisted.cred import credentials from twisted.internet import defer from twisted.internet import protocol from twisted.internet import reactor from twisted.internet import task from twisted.internet import utils from twisted.python import log from twisted.python import runtime from twisted.python.procutils import which from twisted.spread import pb from buildbot.process.results import SUCCESS from buildbot.process.results import Results from buildbot.util import bytes2unicode from buildbot.util import now from buildbot.util import unicode2bytes from buildbot.util.eventual import fireEventually class SourceStamp: def __init__(self, branch, revision, patch, repository=''): self.branch = branch self.revision = revision self.patch = patch self.repository = repository def output(*msg): print(' '.join([str(m) for m in msg])) class SourceStampExtractor: def __init__(self, treetop, branch, repository): self.treetop = treetop self.repository = repository self.branch = branch exes = which(self.vcexe) if not exes: output(f"Could not find executable '{self.vcexe}'.") sys.exit(1) self.exe = exes[0] def dovc(self, cmd): """This accepts the arguments of a command, without the actual command itself.""" env = os.environ.copy() env['LC_ALL'] = "C" d = utils.getProcessOutputAndValue(self.exe, cmd, env=env, path=self.treetop) d.addCallback(self._didvc, cmd) return d def _didvc(self, res, cmd): stdout, _, __ = res # 'bzr diff' sets rc=1 if there were any differences. # cvs does something similar, so don't bother requiring rc=0. return stdout def get(self): """Return a Deferred that fires with a SourceStamp instance.""" d = self.getBaseRevision() d.addCallback(self.getPatch) d.addCallback(self.done) return d def readPatch(self, diff, patchlevel): if not diff: diff = None self.patch = (patchlevel, diff) def done(self, res): if not self.repository: self.repository = self.treetop # TODO: figure out the branch and project too ss = SourceStamp( bytes2unicode(self.branch), self.baserev, self.patch, repository=self.repository ) return ss class CVSExtractor(SourceStampExtractor): patchlevel = 0 vcexe = "cvs" def getBaseRevision(self): # this depends upon our local clock and the repository's clock being # reasonably synchronized with each other. We express everything in # UTC because the '%z' format specifier for strftime doesn't always # work. self.baserev = time.strftime("%Y-%m-%d %H:%M:%S +0000", time.gmtime(now())) return defer.succeed(None) def getPatch(self, res): # the -q tells CVS to not announce each directory as it works if self.branch is not None: # 'cvs diff' won't take both -r and -D at the same time (it # ignores the -r). As best I can tell, there is no way to make # cvs give you a diff relative to a timestamp on the non-trunk # branch. A bare 'cvs diff' will tell you about the changes # relative to your checked-out versions, but I know of no way to # find out what those checked-out versions are. output("Sorry, CVS 'try' builds don't work with branches") sys.exit(1) args = ['-q', 'diff', '-u', '-D', self.baserev] d = self.dovc(args) d.addCallback(self.readPatch, self.patchlevel) return d class SVNExtractor(SourceStampExtractor): patchlevel = 0 vcexe = "svn" def getBaseRevision(self): d = self.dovc(["status", "-u"]) d.addCallback(self.parseStatus) return d def parseStatus(self, res): # svn shows the base revision for each file that has been modified or # which needs an update. You can update each file to a different # version, so each file is displayed with its individual base # revision. It also shows the repository-wide latest revision number # on the last line ("Status against revision: \d+"). # for our purposes, we use the latest revision number as the "base" # revision, and get a diff against that. This means we will get # reverse-diffs for local files that need updating, but the resulting # tree will still be correct. The only weirdness is that the baserev # that we emit may be different than the version of the tree that we # first checked out. # to do this differently would probably involve scanning the revision # numbers to find the max (or perhaps the min) revision, and then # using that as a base. for line in res.split(b"\n"): m = re.search(rb'^Status against revision:\s+(\d+)', line) if m: self.baserev = m.group(1) return output(b"Could not find 'Status against revision' in SVN output: " + res) sys.exit(1) def getPatch(self, res): d = self.dovc(["diff", f"-r{self.baserev}"]) d.addCallback(self.readPatch, self.patchlevel) return d class BzrExtractor(SourceStampExtractor): patchlevel = 0 vcexe = "bzr" def getBaseRevision(self): d = self.dovc(["revision-info", "-rsubmit:"]) d.addCallback(self.get_revision_number) return d def get_revision_number(self, out): _, revid = out.split() self.baserev = 'revid:' + revid return def getPatch(self, res): d = self.dovc(["diff", f"-r{self.baserev}.."]) d.addCallback(self.readPatch, self.patchlevel) return d class MercurialExtractor(SourceStampExtractor): patchlevel = 1 vcexe = "hg" def _didvc(self, res, cmd): (stdout, stderr, code) = res if code: cs = ' '.join(['hg', *cmd]) if stderr: stderr = '\n' + stderr.rstrip() raise RuntimeError(f"{cs} returned {code} {stderr}") return stdout @defer.inlineCallbacks def getBaseRevision(self): upstream = "" if self.repository: upstream = f"r'{self.repository}'" output = '' try: output = yield self.dovc([ "log", "--template", "{node}\\n", "-r", f"max(::. - outgoing({upstream}))", ]) except RuntimeError: # outgoing() will abort if no default-push/default path is # configured if upstream: raise # fall back to current working directory parent output = yield self.dovc(["log", "--template", "{node}\\n", "-r", "p1()"]) m = re.search(rb'^(\w+)', output) if not m: raise RuntimeError(f"Revision {output!r} is not in the right format") self.baserev = m.group(0) def getPatch(self, res): d = self.dovc(["diff", "-r", self.baserev]) d.addCallback(self.readPatch, self.patchlevel) return d class PerforceExtractor(SourceStampExtractor): patchlevel = 0 vcexe = "p4" def getBaseRevision(self): d = self.dovc(["changes", "-m1", "..."]) d.addCallback(self.parseStatus) return d def parseStatus(self, res): # # extract the base change number # m = re.search(rb'Change (\d+)', res) if m: self.baserev = m.group(1) return output(b"Could not find change number in output: " + res) sys.exit(1) def readPatch(self, diff, patchlevel): # # extract the actual patch from "diff" # if not self.branch: output("you must specify a branch") sys.exit(1) mpatch = "" found = False for line in diff.split("\n"): m = re.search('==== //depot/' + self.branch + r'/([\w/\.\d\-_]+)#(\d+) -', line) if m: mpatch += f"--- {m.group(1)}#{m.group(2)}\n" mpatch += f"+++ {m.group(1)}\n" found = True else: mpatch += line mpatch += "\n" if not found: output(b"could not parse patch file") sys.exit(1) self.patch = (patchlevel, unicode2bytes(mpatch)) def getPatch(self, res): d = self.dovc(["diff"]) d.addCallback(self.readPatch, self.patchlevel) return d class DarcsExtractor(SourceStampExtractor): patchlevel = 1 vcexe = "darcs" def getBaseRevision(self): d = self.dovc(["changes", "--context"]) d.addCallback(self.parseStatus) return d def parseStatus(self, res): self.baserev = res # the whole context file def getPatch(self, res): d = self.dovc(["diff", "-u"]) d.addCallback(self.readPatch, self.patchlevel) return d class GitExtractor(SourceStampExtractor): patchlevel = 1 vcexe = "git" config = None def getBaseRevision(self): # If a branch is specified, parse out the rev it points to # and extract the local name. if self.branch: d = self.dovc(["rev-parse", self.branch]) d.addCallback(self.override_baserev) d.addCallback(self.extractLocalBranch) return d d = self.dovc(["branch", "--no-color", "-v", "--no-abbrev"]) d.addCallback(self.parseStatus) return d # remove remote-prefix from self.branch (assumes format <prefix>/<branch>) # this uses "git remote" to retrieve all configured remote names def extractLocalBranch(self, res): if '/' in self.branch: d = self.dovc(["remote"]) d.addCallback(self.fixBranch) return d return None # strip remote prefix from self.branch def fixBranch(self, remotes): for l in bytes2unicode(remotes).split("\n"): r = l.strip() if r and self.branch.startswith(r + "/"): self.branch = self.branch[len(r) + 1 :] break def readConfig(self): if self.config: return defer.succeed(self.config) d = self.dovc(["config", "-l"]) d.addCallback(self.parseConfig) return d def parseConfig(self, res): self.config = {} for l in res.split(b"\n"): if l.strip(): parts = l.strip().split(b"=", 2) if len(parts) < 2: parts.append('true') self.config[parts[0]] = parts[1] return self.config def parseTrackingBranch(self, res): # If we're tracking a remote, consider that the base. remote = self.config.get(b"branch." + self.branch + b".remote") ref = self.config.get(b"branch." + self.branch + b".merge") if remote and ref: remote_branch = ref.split(b"/", 2)[-1] baserev = remote + b"/" + remote_branch else: baserev = b"master" d = self.dovc(["rev-parse", baserev]) d.addCallback(self.override_baserev) return d def override_baserev(self, res): self.baserev = bytes2unicode(res).strip() def parseStatus(self, res): # The current branch is marked by '*' at the start of the # line, followed by the branch name and the SHA1. # # Branch names may contain pretty much anything but whitespace. m = re.search(rb'^\* (\S+)\s+([0-9a-f]{40})', res, re.MULTILINE) if m: self.baserev = m.group(2) self.branch = m.group(1) d = self.readConfig() d.addCallback(self.parseTrackingBranch) return d output(b"Could not find current GIT branch: " + res) sys.exit(1) def getPatch(self, res): d = self.dovc([ "diff", "--src-prefix=a/", "--dst-prefix=b/", "--no-textconv", "--no-ext-diff", self.baserev, ]) d.addCallback(self.readPatch, self.patchlevel) return d class MonotoneExtractor(SourceStampExtractor): patchlevel = 0 vcexe = "mtn" def getBaseRevision(self): d = self.dovc(["automate", "get_base_revision_id"]) d.addCallback(self.parseStatus) return d def parseStatus(self, output): hash = output.strip() if len(hash) != 40: self.baserev = None self.baserev = hash def getPatch(self, res): d = self.dovc(["diff"]) d.addCallback(self.readPatch, self.patchlevel) return d def getSourceStamp(vctype, treetop, branch=None, repository=None): if vctype == "cvs": cls = CVSExtractor elif vctype == "svn": cls = SVNExtractor elif vctype == "bzr": cls = BzrExtractor elif vctype == "hg": cls = MercurialExtractor elif vctype == "p4": cls = PerforceExtractor elif vctype == "darcs": cls = DarcsExtractor elif vctype == "git": cls = GitExtractor elif vctype == "mtn": cls = MonotoneExtractor elif vctype == "none": return defer.succeed(SourceStamp("", "", (1, ""), "")) else: output(f"unknown vctype '{vctype}'") sys.exit(1) return cls(treetop, branch, repository).get() def ns(s): return f"{len(s)}:{s}," def createJobfile( jobid, branch, baserev, patch_level, patch_body, repository, project, who, comment, builderNames, properties, ): # Determine job file version from provided arguments try: bytes2unicode(patch_body) version = 5 except UnicodeDecodeError: version = 6 job = "" job += ns(str(version)) job_dict = { 'jobid': jobid, 'branch': branch, 'baserev': str(baserev), 'patch_level': patch_level, 'repository': repository, 'project': project, 'who': who, 'comment': comment, 'builderNames': builderNames, 'properties': properties, } if version > 5: job_dict['patch_body_base64'] = bytes2unicode(base64.b64encode(patch_body)) else: job_dict['patch_body'] = bytes2unicode(patch_body) job += ns(json.dumps(job_dict)) return job def getTopdir(topfile, start=None): """walk upwards from the current directory until we find this topfile""" if not start: start = os.getcwd() here = start toomany = 20 while toomany > 0: if os.path.exists(os.path.join(here, topfile)): return here next = os.path.dirname(here) if next == here: break # we've hit the root here = next toomany -= 1 output(f"Unable to find topfile '{topfile}' anywhere from {start} upwards") sys.exit(1) class RemoteTryPP(protocol.ProcessProtocol): def __init__(self, job): self.job = job self.d = defer.Deferred() def connectionMade(self): self.transport.write(unicode2bytes(self.job)) self.transport.closeStdin() def outReceived(self, data): sys.stdout.write(bytes2unicode(data)) def errReceived(self, data): sys.stderr.write(bytes2unicode(data)) def processEnded(self, reason): sig = reason.value.signal rc = reason.value.exitCode if sig is not None or rc != 0: self.d.errback(RuntimeError(f"remote 'buildbot tryserver' failed: sig={sig}, rc={rc}")) return self.d.callback((sig, rc)) class FakeBuildSetStatus: def callRemote(self, name): if name == "getBuildRequests": return defer.succeed([]) raise NotImplementedError() class Try(pb.Referenceable): buildsetStatus = None quiet = False printloop = False def __init__(self, config): self.config = config self.connect = self.getopt('connect') if self.connect not in ['ssh', 'pb']: output("you must specify a connect style: ssh or pb") sys.exit(1) self.builderNames = self.getopt('builders') self.project = self.getopt('project', '') self.who = self.getopt('who') self.comment = self.getopt('comment') def getopt(self, config_name, default=None): value = self.config.get(config_name) if value is None or value == []: value = default return value def createJob(self): # returns a Deferred which fires when the job parameters have been # created # generate a random (unique) string. It would make sense to add a # hostname and process ID here, but a) I suspect that would cause # windows portability problems, and b) really this is good enough self.bsid = f"{time.time()}-{random.randint(0, 1000000)}" # common options branch = self.getopt("branch") difffile = self.config.get("diff") if difffile: baserev = self.config.get("baserev") if difffile == "-": diff = sys.stdin.read() else: with open(difffile, "rb") as f: diff = f.read() if not diff: diff = None patch = (self.config['patchlevel'], diff) ss = SourceStamp(branch, baserev, patch, repository=self.getopt("repository")) d = defer.succeed(ss) else: vc = self.getopt("vc") if vc in ("cvs", "svn"): # we need to find the tree-top topdir = self.getopt("topdir") if topdir: treedir = os.path.expanduser(topdir) else: topfile = self.getopt("topfile") if topfile: treedir = getTopdir(topfile) else: output("Must specify topdir or topfile.") sys.exit(1) else: treedir = os.getcwd() d = getSourceStamp(vc, treedir, branch, self.getopt("repository")) d.addCallback(self._createJob_1) return d def _createJob_1(self, ss): self.sourcestamp = ss patchlevel, diff = ss.patch if diff is None: output("WARNING: There is no patch to try, diff is empty.") if self.connect == "ssh": revspec = ss.revision if revspec is None: revspec = "" self.jobfile = createJobfile( self.bsid, ss.branch or "", revspec, patchlevel, diff, ss.repository, self.project, self.who, self.comment, self.builderNames, self.config.get('properties', {}), ) def fakeDeliverJob(self): # Display the job to be delivered, but don't perform delivery. ss = self.sourcestamp output( f"Job:\n\tRepository: {ss.repository}\n\tProject: {self.project}\n\tBranch: " f"{ss.branch}\n\tRevision: {ss.revision}\n\tBuilders: " f"{self.builderNames}\n{ss.patch[1]}" ) self.buildsetStatus = FakeBuildSetStatus() d = defer.Deferred() d.callback(True) return d def deliver_job_ssh(self): tryhost = self.getopt("host") tryport = self.getopt("port") tryuser = self.getopt("username") trydir = self.getopt("jobdir") buildbotbin = self.getopt("buildbotbin") ssh_command = self.getopt("ssh") if not ssh_command: ssh_commands = which("ssh") if not ssh_commands: raise RuntimeError( "couldn't find ssh executable, make sure it is available in the PATH" ) argv = [ssh_commands[0]] else: # Split the string on whitespace to allow passing options in # ssh command too, but preserving whitespace inside quotes to # allow using paths with spaces in them which is common under # Windows. And because Windows uses backslashes in paths, we # can't just use shlex.split there as it would interpret them # specially, so do it by hand. if runtime.platformType == 'win32': # Note that regex here matches the arguments, not the # separators, as it's simpler to do it like this. And then we # just need to get all of them together using the slice and # also remove the quotes from those that were quoted. argv = [ string.strip(a, '"') for a in re.split(r"""([^" ]+|"[^"]+")""", ssh_command)[1::2] ] else: # Do use standard tokenization logic under POSIX. argv = shlex.split(ssh_command) if tryuser: argv += ["-l", tryuser] if tryport: argv += ["-p", tryport] argv += [tryhost, buildbotbin, "tryserver", "--jobdir", trydir] pp = RemoteTryPP(self.jobfile) reactor.spawnProcess(pp, argv[0], argv, os.environ) d = pp.d return d @defer.inlineCallbacks def deliver_job_pb(self): user = self.getopt("username") passwd = self.getopt("passwd") master = self.getopt("master") tryhost, tryport = master.split(":") tryport = int(tryport) f = pb.PBClientFactory() d = f.login(credentials.UsernamePassword(unicode2bytes(user), unicode2bytes(passwd))) reactor.connectTCP(tryhost, tryport, f) remote = yield d ss = self.sourcestamp output("Delivering job; comment=", self.comment) self.buildsetStatus = yield remote.callRemote( "try", ss.branch, ss.revision, ss.patch, ss.repository, self.project, self.builderNames, self.who, self.comment, self.config.get('properties', {}), ) def deliverJob(self): # returns a Deferred that fires when the job has been delivered if self.connect == "ssh": return self.deliver_job_ssh() if self.connect == "pb": return self.deliver_job_pb() raise RuntimeError(f"unknown connecttype '{self.connect}', should be 'ssh' or 'pb'") def getStatus(self): # returns a Deferred that fires when the builds have finished, and # may emit status messages while we wait wait = bool(self.getopt("wait")) if not wait: output("not waiting for builds to finish") elif self.connect == "ssh": output("waiting for builds with ssh is not supported") else: self.running = defer.Deferred() if not self.buildsetStatus: output("try scheduler on the master does not have the builder configured") return None self._getStatus_1() # note that we don't wait for the returned Deferred if bool(self.config.get("dryrun")): self.statusDone() return self.running return None @defer.inlineCallbacks def _getStatus_1(self): # gather the set of BuildRequests brs = yield self.buildsetStatus.callRemote("getBuildRequests") self.builderNames = [] self.buildRequests = {} # self.builds holds the current BuildStatus object for each one self.builds = {} # self.outstanding holds the list of builderNames which haven't # finished yet self.outstanding = [] # self.results holds the list of build results. It holds a tuple of # (result, text) self.results = {} # self.currentStep holds the name of the Step that each build is # currently running self.currentStep = {} # self.ETA holds the expected finishing time (absolute time since # epoch) self.ETA = {} for n, br in brs: self.builderNames.append(n) self.buildRequests[n] = br self.builds[n] = None self.outstanding.append(n) self.results[n] = [None, None] self.currentStep[n] = None self.ETA[n] = None # get new Builds for this buildrequest. We follow each one until # it finishes or is interrupted. br.callRemote("subscribe", self) # now that those queries are in transit, we can start the # display-status-every-30-seconds loop if not self.getopt("quiet"): self.printloop = task.LoopingCall(self.printStatus) self.printloop.start(3, now=False) # these methods are invoked by the status objects we've subscribed to def remote_newbuild(self, bs, builderName): if self.builds[builderName]: self.builds[builderName].callRemote("unsubscribe", self) self.builds[builderName] = bs bs.callRemote("subscribe", self, 20) d = bs.callRemote("waitUntilFinished") d.addCallback(self._build_finished, builderName) def remote_stepStarted(self, buildername, build, stepname, step): self.currentStep[buildername] = stepname def remote_stepFinished(self, buildername, build, stepname, step, results): pass def remote_buildETAUpdate(self, buildername, build, eta): self.ETA[buildername] = now() + eta @defer.inlineCallbacks def _build_finished(self, bs, builderName): # we need to collect status from the newly-finished build. We don't # remove the build from self.outstanding until we've collected # everything we want. self.builds[builderName] = None self.ETA[builderName] = None self.currentStep[builderName] = "finished" self.results[builderName][0] = yield bs.callRemote("getResults") self.results[builderName][1] = yield bs.callRemote("getText") self.outstanding.remove(builderName) if not self.outstanding: self.statusDone() def printStatus(self): try: names = sorted(self.buildRequests.keys()) for n in names: if n not in self.outstanding: # the build is finished, and we have results code, text = self.results[n] t = Results[code] if text: t += f' ({" ".join(text)})' elif self.builds[n]: t = self.currentStep[n] or "building" if self.ETA[n]: t += f" [ETA {self.ETA[n] - now()}s]" else: t = "no build" self.announce(f"{n}: {t}") self.announce("") except Exception: log.err(None, "printing status") def statusDone(self): if self.printloop: self.printloop.stop() self.printloop = None output("All Builds Complete") # TODO: include a URL for all failing builds names = sorted(self.buildRequests.keys()) happy = True for n in names: code, text = self.results[n] t = f"{n}: {Results[code]}" if text: t += f' ({" ".join(text)})' output(t) if code != SUCCESS: happy = False if happy: self.exitcode = 0 else: self.exitcode = 1 self.running.callback(self.exitcode) @defer.inlineCallbacks def getAvailableBuilderNames(self): # This logs into the master using the PB protocol to # get the names of the configured builders that can # be used for the --builder argument if self.connect == "pb": user = self.getopt("username") passwd = self.getopt("passwd") master = self.getopt("master") tryhost, tryport = master.split(":") tryport = int(tryport) f = pb.PBClientFactory() d = f.login(credentials.UsernamePassword(unicode2bytes(user), unicode2bytes(passwd))) reactor.connectTCP(tryhost, tryport, f) remote = yield d buildernames = yield remote.callRemote("getAvailableBuilderNames") output("The following builders are available for the try scheduler: ") for buildername in buildernames: output(buildername) yield remote.broker.transport.loseConnection() return if self.connect == "ssh": output("Cannot get available builders over ssh.") sys.exit(1) raise RuntimeError(f"unknown connecttype '{self.connect}', should be 'pb'") def announce(self, message): if not self.quiet: output(message) @defer.inlineCallbacks def run_impl(self): output(f"using '{self.connect}' connect method") self.exitcode = 0 # we can't do spawnProcess until we're inside reactor.run(), so force asynchronous execution yield fireEventually(None) try: if bool(self.config.get("get-builder-names")): yield self.getAvailableBuilderNames() else: yield self.createJob() yield self.announce("job created") if bool(self.config.get("dryrun")): yield self.fakeDeliverJob() else: yield self.deliverJob() yield self.announce("job has been delivered") yield self.getStatus() if not bool(self.config.get("dryrun")): yield self.cleanup() except SystemExit as e: self.exitcode = e.code except Exception as e: log.err(e) raise def run(self): d = self.run_impl() d.addCallback(lambda res: reactor.stop()) reactor.run() sys.exit(self.exitcode) def trapSystemExit(self, why): why.trap(SystemExit) self.exitcode = why.value.code def cleanup(self, res=None): if self.buildsetStatus: self.buildsetStatus.broker.transport.loseConnection()
31,577
Python
.py
814
29.002457
100
0.586435
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,273
buildrequests.py
buildbot_buildbot/master/buildbot/data/buildrequests.py
# This file is part of Buildbot. Buildbot is free software: you can # redistribute it and/or modify it under the terms of the GNU General Public # License as published by the Free Software Foundation, version 2. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more # details. # # You should have received a copy of the GNU General Public License along with # this program; if not, write to the Free Software Foundation, Inc., 51 # Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # Copyright Buildbot Team Members from __future__ import annotations from typing import TYPE_CHECKING from twisted.internet import defer from buildbot.data import base from buildbot.data import types from buildbot.db.buildrequests import AlreadyClaimedError from buildbot.db.buildrequests import NotClaimedError from buildbot.process.results import RETRY if TYPE_CHECKING: from typing import Sequence from buildbot.data.resultspec import ResultSpec from buildbot.db.buildrequests import BuildRequestModel def _db2data(dbmodel: BuildRequestModel, properties: dict | None): return { 'buildrequestid': dbmodel.buildrequestid, 'buildsetid': dbmodel.buildsetid, 'builderid': dbmodel.builderid, 'priority': dbmodel.priority, 'claimed': dbmodel.claimed, 'claimed_at': dbmodel.claimed_at, 'claimed_by_masterid': dbmodel.claimed_by_masterid, 'complete': dbmodel.complete, 'results': dbmodel.results, 'submitted_at': dbmodel.submitted_at, 'complete_at': dbmodel.complete_at, 'waited_for': dbmodel.waited_for, 'properties': properties, } def _generate_filtered_properties(props: dict, filters: Sequence) -> dict | None: """ This method returns Build's properties according to property filters. :param props: Properties as a dict (from db) :param filters: Desired properties keys as a list (from API URI) """ # by default no properties are returned if not props and not filters: return None set_filters = set(filters) if '*' in set_filters: return props return {k: v for k, v in props.items() if k in set_filters} class Db2DataMixin: @defer.inlineCallbacks def get_buildset_properties_filtered(self, buildsetid: int, filters: Sequence): if not filters: return None assert hasattr(self, 'master') props = yield self.master.db.buildsets.getBuildsetProperties(buildsetid) return _generate_filtered_properties(props, filters) fieldMapping = { 'buildrequestid': 'buildrequests.id', 'buildsetid': 'buildrequests.buildsetid', 'builderid': 'buildrequests.builderid', 'priority': 'buildrequests.priority', 'complete': 'buildrequests.complete', 'results': 'buildrequests.results', 'submitted_at': 'buildrequests.submitted_at', 'complete_at': 'buildrequests.complete_at', 'waited_for': 'buildrequests.waited_for', # br claim 'claimed_at': 'buildrequest_claims.claimed_at', 'claimed_by_masterid': 'buildrequest_claims.masterid', } class BuildRequestEndpoint(Db2DataMixin, base.Endpoint): kind = base.EndpointKind.SINGLE pathPatterns = """ /buildrequests/n:buildrequestid """ @defer.inlineCallbacks def get(self, resultSpec: ResultSpec, kwargs): buildrequest = yield self.master.db.buildrequests.getBuildRequest(kwargs['buildrequestid']) if not buildrequest: return None filters = resultSpec.popProperties() if hasattr(resultSpec, 'popProperties') else [] properties = yield self.get_buildset_properties_filtered(buildrequest.buildsetid, filters) return _db2data(buildrequest, properties) @defer.inlineCallbacks def set_request_priority(self, brid, args, kwargs): priority = args['priority'] yield self.master.db.buildrequests.set_build_requests_priority( brids=[brid], priority=priority ) @defer.inlineCallbacks def control(self, action, args, kwargs): brid = kwargs['buildrequestid'] if action == "cancel": self.master.mq.produce( ('control', 'buildrequests', str(brid), 'cancel'), {'reason': args.get('reason', 'no reason')}, ) elif action == "set_priority": yield self.set_request_priority(brid, args, kwargs) else: raise ValueError(f"action: {action} is not supported") class BuildRequestsEndpoint(Db2DataMixin, base.Endpoint): kind = base.EndpointKind.COLLECTION pathPatterns = """ /buildrequests /builders/n:builderid/buildrequests """ rootLinkName = 'buildrequests' @defer.inlineCallbacks def get(self, resultSpec, kwargs): builderid = kwargs.get("builderid", None) complete = resultSpec.popBooleanFilter('complete') claimed_by_masterid = resultSpec.popBooleanFilter('claimed_by_masterid') if claimed_by_masterid: # claimed_by_masterid takes precedence over 'claimed' filter # (no need to check consistency with 'claimed' filter even if # 'claimed'=False with 'claimed_by_masterid' set, doesn't make sense) claimed = claimed_by_masterid else: claimed = resultSpec.popBooleanFilter('claimed') bsid = resultSpec.popOneFilter('buildsetid', 'eq') resultSpec.fieldMapping = self.fieldMapping buildrequests = yield self.master.db.buildrequests.getBuildRequests( builderid=builderid, complete=complete, claimed=claimed, bsid=bsid, resultSpec=resultSpec, ) results = [] filters = resultSpec.popProperties() if hasattr(resultSpec, 'popProperties') else [] for br in buildrequests: properties = yield self.get_buildset_properties_filtered(br.buildsetid, filters) results.append(_db2data(br, properties)) return results class BuildRequest(base.ResourceType): name = "buildrequest" plural = "buildrequests" endpoints = [BuildRequestEndpoint, BuildRequestsEndpoint] keyField = 'buildrequestid' eventPathPatterns = """ /buildsets/:buildsetid/builders/:builderid/buildrequests/:buildrequestid /buildrequests/:buildrequestid /builders/:builderid/buildrequests/:buildrequestid """ subresources = ["Build"] class EntityType(types.Entity): buildrequestid = types.Integer() buildsetid = types.Integer() builderid = types.Integer() priority = types.Integer() claimed = types.Boolean() claimed_at = types.NoneOk(types.DateTime()) claimed_by_masterid = types.NoneOk(types.Integer()) complete = types.Boolean() results = types.NoneOk(types.Integer()) submitted_at = types.DateTime() complete_at = types.NoneOk(types.DateTime()) waited_for = types.Boolean() properties = types.NoneOk(types.SourcedProperties()) entityType = EntityType(name, 'Buildrequest') @defer.inlineCallbacks def generateEvent(self, brids, event): for brid in brids: # get the build and munge the result for the notification br = yield self.master.data.get(('buildrequests', str(brid))) self.produceEvent(br, event) @defer.inlineCallbacks def callDbBuildRequests(self, brids, db_callable, event, **kw): if not brids: # empty buildrequest list. No need to call db API return True try: yield db_callable(brids, **kw) except AlreadyClaimedError: # the db layer returned an AlreadyClaimedError exception, usually # because one of the buildrequests has already been claimed by # another master return False yield self.generateEvent(brids, event) return True @base.updateMethod def claimBuildRequests(self, brids, claimed_at=None): return self.callDbBuildRequests( brids, self.master.db.buildrequests.claimBuildRequests, event="claimed", claimed_at=claimed_at, ) @base.updateMethod @defer.inlineCallbacks def unclaimBuildRequests(self, brids): if brids: yield self.master.db.buildrequests.unclaimBuildRequests(brids) yield self.generateEvent(brids, "unclaimed") @base.updateMethod @defer.inlineCallbacks def completeBuildRequests(self, brids, results, complete_at=None): assert results != RETRY, "a buildrequest cannot be completed with a retry status!" if not brids: # empty buildrequest list. No need to call db API return True try: yield self.master.db.buildrequests.completeBuildRequests( brids, results, complete_at=complete_at ) except NotClaimedError: # the db layer returned a NotClaimedError exception, usually # because one of the buildrequests has been claimed by another # master return False yield self.generateEvent(brids, "complete") # check for completed buildsets -- one call for each build request with # a unique bsid seen_bsids = set() for brid in brids: brdict = yield self.master.db.buildrequests.getBuildRequest(brid) if brdict: bsid = brdict.buildsetid if bsid in seen_bsids: continue seen_bsids.add(bsid) yield self.master.data.updates.maybeBuildsetComplete(bsid) return True @base.updateMethod @defer.inlineCallbacks def rebuildBuildrequest(self, buildrequest): # goal is to make a copy of the original buildset buildset = yield self.master.data.get(('buildsets', buildrequest['buildsetid'])) properties = yield self.master.data.get(( 'buildsets', buildrequest['buildsetid'], 'properties', )) # use original build id: after rebuild, it is saved in new buildset `rebuilt_buildid` column builds = yield self.master.data.get(( 'buildrequests', buildrequest['buildrequestid'], 'builds', )) # if already rebuilt build of the same initial build is rebuilt again only save the build # id of the initial build if len(builds) != 0 and buildset['rebuilt_buildid'] is None: rebuilt_buildid = builds[0]['buildid'] else: rebuilt_buildid = buildset['rebuilt_buildid'] ssids = [ss['ssid'] for ss in buildset['sourcestamps']] res = yield self.master.data.updates.addBuildset( waited_for=False, scheduler='rebuild', sourcestamps=ssids, reason='rebuild', properties=properties, builderids=[buildrequest['builderid']], external_idstring=buildset['external_idstring'], rebuilt_buildid=rebuilt_buildid, parent_buildid=buildset['parent_buildid'], parent_relationship=buildset['parent_relationship'], ) return res
11,544
Python
.py
267
34.621723
100
0.665094
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,274
buildsets.py
buildbot_buildbot/master/buildbot/data/buildsets.py
# This file is part of Buildbot. Buildbot is free software: you can # redistribute it and/or modify it under the terms of the GNU General Public # License as published by the Free Software Foundation, version 2. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more # details. # # You should have received a copy of the GNU General Public License along with # this program; if not, write to the Free Software Foundation, Inc., 51 # Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # Copyright Buildbot Team Members from __future__ import annotations import copy from typing import TYPE_CHECKING from twisted.internet import defer from twisted.python import log from buildbot.data import base from buildbot.data import sourcestamps as sourcestampsapi from buildbot.data import types from buildbot.db.buildsets import AlreadyCompleteError from buildbot.process.buildrequest import BuildRequestCollapser from buildbot.process.results import SUCCESS from buildbot.process.results import worst_status from buildbot.util import datetime2epoch from buildbot.util import epoch2datetime if TYPE_CHECKING: from buildbot.db.buildsets import BuildSetModel class Db2DataMixin: @defer.inlineCallbacks def db2data(self, model: BuildSetModel | None): if not model: return None buildset = { "bsid": model.bsid, "external_idstring": model.external_idstring, "reason": model.reason, "submitted_at": datetime2epoch(model.submitted_at), "complete": model.complete, "complete_at": datetime2epoch(model.complete_at), "results": model.results, "parent_buildid": model.parent_buildid, "parent_relationship": model.parent_relationship, "rebuilt_buildid": model.rebuilt_buildid, } # gather the actual sourcestamps, in parallel sourcestamps = [] @defer.inlineCallbacks def getSs(ssid): ss = yield self.master.data.get(('sourcestamps', str(ssid))) sourcestamps.append(ss) yield defer.DeferredList( [getSs(id) for id in model.sourcestamps], fireOnOneErrback=True, consumeErrors=True ) buildset['sourcestamps'] = sourcestamps return buildset fieldMapping = { 'bsid': 'buildsets.id', 'external_idstring': 'buildsets.external_idstring', 'reason': 'buildsets.reason', 'rebuilt_buildid': 'buildsets.rebuilt_buildid', 'submitted_at': 'buildsets.submitted_at', 'complete': 'buildsets.complete', 'complete_at': 'buildsets.complete_at', 'results': 'buildsets.results', 'parent_buildid': 'buildsets.parent_buildid', 'parent_relationship': 'buildsets.parent_relationship', } class BuildsetEndpoint(Db2DataMixin, base.Endpoint): kind = base.EndpointKind.SINGLE pathPatterns = """ /buildsets/n:bsid """ @defer.inlineCallbacks def get(self, resultSpec, kwargs): res = yield self.master.db.buildsets.getBuildset(kwargs['bsid']) res = yield self.db2data(res) return res class BuildsetsEndpoint(Db2DataMixin, base.Endpoint): kind = base.EndpointKind.COLLECTION pathPatterns = """ /buildsets """ rootLinkName = 'buildsets' @defer.inlineCallbacks def get(self, resultSpec, kwargs): complete = resultSpec.popBooleanFilter('complete') resultSpec.fieldMapping = self.fieldMapping buildsets = yield self.master.db.buildsets.getBuildsets( complete=complete, resultSpec=resultSpec ) buildsets = yield defer.gatherResults( [self.db2data(bs) for bs in buildsets], consumeErrors=True ) return buildsets class Buildset(base.ResourceType): name = "buildset" plural = "buildsets" endpoints = [BuildsetEndpoint, BuildsetsEndpoint] keyField = 'bsid' eventPathPatterns = """ /buildsets/:bsid """ class EntityType(types.Entity): bsid = types.Integer() external_idstring = types.NoneOk(types.String()) reason = types.String() rebuilt_buildid = types.NoneOk(types.Integer()) submitted_at = types.Integer() complete = types.Boolean() complete_at = types.NoneOk(types.Integer()) results = types.NoneOk(types.Integer()) sourcestamps = types.List(of=sourcestampsapi.SourceStamp.entityType) parent_buildid = types.NoneOk(types.Integer()) parent_relationship = types.NoneOk(types.String()) entityType = EntityType(name, 'Buildset') subresources = ["Property"] @base.updateMethod @defer.inlineCallbacks def addBuildset( self, waited_for, scheduler=None, sourcestamps=None, reason='', properties=None, builderids=None, external_idstring=None, rebuilt_buildid=None, parent_buildid=None, parent_relationship=None, priority=0, ): if sourcestamps is None: sourcestamps = [] if properties is None: properties = {} if builderids is None: builderids = [] submitted_at = int(self.master.reactor.seconds()) bsid, brids = yield self.master.db.buildsets.addBuildset( sourcestamps=sourcestamps, reason=reason, rebuilt_buildid=rebuilt_buildid, properties=properties, builderids=builderids, waited_for=waited_for, external_idstring=external_idstring, submitted_at=epoch2datetime(submitted_at), parent_buildid=parent_buildid, parent_relationship=parent_relationship, priority=priority, ) yield BuildRequestCollapser(self.master, list(brids.values())).collapse() # get each of the sourcestamps for this buildset (sequentially) bsdict = yield self.master.db.buildsets.getBuildset(bsid) sourcestamps = [] for ssid in bsdict.sourcestamps: sourcestamps.append((yield self.master.data.get(('sourcestamps', str(ssid)))).copy()) # notify about the component build requests brResource = self.master.data.getResourceType("buildrequest") brResource.generateEvent(list(brids.values()), 'new') # and the buildset itself msg = { "bsid": bsid, "external_idstring": external_idstring, "reason": reason, "parent_buildid": parent_buildid, "rebuilt_buildid": rebuilt_buildid, "submitted_at": submitted_at, "complete": False, "complete_at": None, "results": None, "scheduler": scheduler, "sourcestamps": sourcestamps, } # TODO: properties=properties) self.produceEvent(msg, "new") log.msg(f"added buildset {bsid} to database") # if there are no builders, then this is done already, so send the # appropriate messages for that if not builderids: yield self.maybeBuildsetComplete(bsid) return (bsid, brids) @base.updateMethod @defer.inlineCallbacks def maybeBuildsetComplete(self, bsid): brdicts = yield self.master.db.buildrequests.getBuildRequests(bsid=bsid, complete=False) # if there are incomplete buildrequests, bail out if brdicts: return brdicts = yield self.master.db.buildrequests.getBuildRequests(bsid=bsid) # figure out the overall results of the buildset: cumulative_results = SUCCESS for brdict in brdicts: cumulative_results = worst_status(cumulative_results, brdict.results) # get a copy of the buildset bsdict = yield self.master.db.buildsets.getBuildset(bsid) # if it's already completed, we're late to the game, and there's # nothing to do. # # NOTE: there's still a strong possibility of a race condition here, # which would cause buildset being completed twice. # in this case, the db layer will detect that and raise AlreadyCompleteError if bsdict.complete: return # mark it as completed in the database complete_at = epoch2datetime(int(self.master.reactor.seconds())) try: yield self.master.db.buildsets.completeBuildset( bsid, cumulative_results, complete_at=complete_at ) except AlreadyCompleteError: return # get the sourcestamps for the message # get each of the sourcestamps for this buildset (sequentially) bsdict = yield self.master.db.buildsets.getBuildset(bsid) sourcestamps = [] for ssid in bsdict.sourcestamps: sourcestamps.append( copy.deepcopy((yield self.master.data.get(('sourcestamps', str(ssid))))) ) msg = { "bsid": bsid, "external_idstring": bsdict.external_idstring, "reason": bsdict.reason, "rebuilt_buildid": bsdict.rebuilt_buildid, "sourcestamps": sourcestamps, "submitted_at": bsdict.submitted_at, "complete": True, "complete_at": complete_at, "results": cumulative_results, "parent_buildid": bsdict.parent_buildid, "parent_relationship": bsdict.parent_relationship, } # TODO: properties=properties) self.produceEvent(msg, "complete")
9,785
Python
.py
239
32.305439
97
0.657443
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,275
forceschedulers.py
buildbot_buildbot/master/buildbot/data/forceschedulers.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.data import base from buildbot.data import types from buildbot.schedulers import forcesched from buildbot.www.rest import JSONRPC_CODES from buildbot.www.rest import BadJsonRpc2 def forceScheduler2Data(sched): ret = { "all_fields": [], "name": str(sched.name), "button_name": str(sched.buttonName), "label": str(sched.label), "builder_names": [str(name) for name in sched.builderNames], "enabled": sched.enabled, } ret["all_fields"] = [field.getSpec() for field in sched.all_fields] return ret class ForceSchedulerEndpoint(base.Endpoint): kind = base.EndpointKind.SINGLE pathPatterns = """ /forceschedulers/i:schedulername """ def findForceScheduler(self, schedulername): # eventually this may be db backed. This is why the API is async for sched in self.master.allSchedulers(): if sched.name == schedulername and isinstance(sched, forcesched.ForceScheduler): return defer.succeed(sched) return None @defer.inlineCallbacks def get(self, resultSpec, kwargs): sched = yield self.findForceScheduler(kwargs['schedulername']) if sched is not None: return forceScheduler2Data(sched) return None @defer.inlineCallbacks def control(self, action, args, kwargs): if action == "force": sched = yield self.findForceScheduler(kwargs['schedulername']) if "owner" not in args: args['owner'] = "user" try: res = yield sched.force(**args) return res except forcesched.CollectedValidationError as e: raise BadJsonRpc2(e.errors, JSONRPC_CODES["invalid_params"]) from e return None class ForceSchedulersEndpoint(base.Endpoint): kind = base.EndpointKind.COLLECTION pathPatterns = """ /forceschedulers /builders/:builderid/forceschedulers """ rootLinkName = 'forceschedulers' @defer.inlineCallbacks def get(self, resultSpec, kwargs): ret = [] builderid = kwargs.get('builderid', None) bdict = None if builderid is not None: bdict = yield self.master.db.builders.getBuilder(builderid) for sched in self.master.allSchedulers(): if isinstance(sched, forcesched.ForceScheduler): if builderid is not None and bdict.name not in sched.builderNames: continue ret.append(forceScheduler2Data(sched)) return ret class ForceScheduler(base.ResourceType): name = "forcescheduler" plural = "forceschedulers" endpoints = [ForceSchedulerEndpoint, ForceSchedulersEndpoint] keyField = "name" class EntityType(types.Entity): name = types.Identifier(50) button_name = types.String() label = types.String() builder_names = types.List(of=types.Identifier(50)) enabled = types.Boolean() all_fields = types.List(of=types.JsonObject()) entityType = EntityType(name, 'Forcescheduler')
3,862
Python
.py
93
34.376344
92
0.684786
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,276
connector.py
buildbot_buildbot/master/buildbot/data/connector.py
# This file is part of Buildbot. Buildbot is free software: you can # redistribute it and/or modify it under the terms of the GNU General Public # License as published by the Free Software Foundation, version 2. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more # details. # # You should have received a copy of the GNU General Public License along with # this program; if not, write to the Free Software Foundation, Inc., 51 # Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # Copyright Buildbot Team Members import functools import inspect from twisted.internet import defer from twisted.python import reflect from buildbot.data import base from buildbot.data import exceptions from buildbot.data import resultspec from buildbot.util import bytes2unicode from buildbot.util import pathmatch from buildbot.util import service class Updates: # empty container object; see _scanModule, below pass class RTypes: # empty container object; see _scanModule, below pass class DataConnector(service.AsyncService): submodules = [ 'buildbot.data.build_data', 'buildbot.data.builders', 'buildbot.data.builds', 'buildbot.data.buildrequests', 'buildbot.data.workers', 'buildbot.data.steps', 'buildbot.data.logs', 'buildbot.data.logchunks', 'buildbot.data.buildsets', 'buildbot.data.changes', 'buildbot.data.changesources', 'buildbot.data.masters', 'buildbot.data.sourcestamps', 'buildbot.data.schedulers', 'buildbot.data.forceschedulers', 'buildbot.data.root', 'buildbot.data.projects', 'buildbot.data.properties', 'buildbot.data.test_results', 'buildbot.data.test_result_sets', ] name = "data" def __init__(self): self.matcher = pathmatch.Matcher() self.rootLinks = [] # links from the root of the API @defer.inlineCallbacks def setServiceParent(self, parent): yield super().setServiceParent(parent) self._setup() def _scanModule(self, mod, _noSetattr=False): for sym in dir(mod): obj = getattr(mod, sym) if inspect.isclass(obj) and issubclass(obj, base.ResourceType): rtype = obj(self.master) setattr(self.rtypes, rtype.name, rtype) setattr(self.plural_rtypes, rtype.plural, rtype) self.graphql_rtypes[rtype.entityType.toGraphQLTypeName()] = rtype # put its update methods into our 'updates' attribute for name in dir(rtype): o = getattr(rtype, name) if hasattr(o, 'isUpdateMethod'): setattr(self.updates, name, o) # load its endpoints for ep in rtype.getEndpoints(): # don't use inherited values for these parameters clsdict = ep.__class__.__dict__ pathPatterns = clsdict.get('pathPatterns', '') pathPatterns = pathPatterns.split() pathPatterns = [tuple(pp.split('/')[1:]) for pp in pathPatterns] for pp in pathPatterns: # special-case the root if pp == ('',): pp = () self.matcher[pp] = ep rootLinkName = clsdict.get('rootLinkName') if rootLinkName: self.rootLinks.append({'name': rootLinkName}) def _setup(self): self.updates = Updates() self.graphql_rtypes = {} self.rtypes = RTypes() self.plural_rtypes = RTypes() for moduleName in self.submodules: module = reflect.namedModule(moduleName) self._scanModule(module) def getEndpoint(self, path): try: return self.matcher[path] except KeyError as e: raise exceptions.InvalidPathError( "Invalid path: " + "/".join([str(p) for p in path]) ) from e def getResourceType(self, name): return getattr(self.rtypes, name, None) def getEndPointForResourceName(self, name): rtype = getattr(self.rtypes, name, None) rtype_plural = getattr(self.plural_rtypes, name, None) if rtype is not None: return rtype.getDefaultEndpoint() elif rtype_plural is not None: return rtype_plural.getCollectionEndpoint() return None def getResourceTypeForGraphQlType(self, type): if type not in self.graphql_rtypes: raise RuntimeError(f"Can't get rtype for {type}: {self.graphql_rtypes.keys()}") return self.graphql_rtypes.get(type) def get(self, path, filters=None, fields=None, order=None, limit=None, offset=None): resultSpec = resultspec.ResultSpec( filters=filters, fields=fields, order=order, limit=limit, offset=offset ) return self.get_with_resultspec(path, resultSpec) @defer.inlineCallbacks def get_with_resultspec(self, path, resultSpec): endpoint, kwargs = self.getEndpoint(path) rv = yield endpoint.get(resultSpec, kwargs) if resultSpec: rv = resultSpec.apply(rv) return rv def control(self, action, args, path): endpoint, kwargs = self.getEndpoint(path) return endpoint.control(action, args, kwargs) def produceEvent(self, rtype, msg, event): # warning, this is temporary api, until all code is migrated to data # api rsrc = self.getResourceType(rtype) return rsrc.produceEvent(msg, event) @functools.lru_cache(1) # noqa: B019 def allEndpoints(self): """return the full spec of the connector as a list of dicts""" paths = [] for k, v in sorted(self.matcher.iterPatterns()): paths.append({ "path": '/'.join(k), "plural": str(v.rtype.plural), "type": str(v.rtype.entityType.name), "type_spec": v.rtype.entityType.getSpec(), }) return paths def resultspec_from_jsonapi(self, req_args, entityType, is_collection): def checkFields(fields, negOk=False): for field in fields: k = bytes2unicode(field) if k[0] == '-' and negOk: k = k[1:] if k not in entityType.fieldNames: raise exceptions.InvalidQueryParameter(f"no such field '{k}'") limit = offset = order = fields = None filters = [] properties = [] for arg in req_args: argStr = bytes2unicode(arg) if argStr == 'order': order = tuple(bytes2unicode(o) for o in req_args[arg]) checkFields(order, True) elif argStr == 'field': fields = req_args[arg] checkFields(fields, False) elif argStr == 'limit': try: limit = int(req_args[arg][0]) except Exception as e: raise exceptions.InvalidQueryParameter('invalid limit') from e elif argStr == 'offset': try: offset = int(req_args[arg][0]) except Exception as e: raise exceptions.InvalidQueryParameter('invalid offset') from e elif argStr == 'property': try: props = [] for v in req_args[arg]: if not isinstance(v, (bytes, str)): raise TypeError(f"Invalid type {type(v)} for {v}") props.append(bytes2unicode(v)) except Exception as e: raise exceptions.InvalidQueryParameter( f'invalid property value for {arg}' ) from e properties.append(resultspec.Property(arg, 'eq', props)) elif argStr in entityType.fieldNames: field = entityType.fields[argStr] try: values = [field.valueFromString(v) for v in req_args[arg]] except Exception as e: raise exceptions.InvalidQueryParameter( f'invalid filter value for {argStr}' ) from e filters.append(resultspec.Filter(argStr, 'eq', values)) elif '__' in argStr: field, op = argStr.rsplit('__', 1) args = req_args[arg] operators = ( resultspec.Filter.singular_operators if len(args) == 1 else resultspec.Filter.plural_operators ) if op in operators and field in entityType.fieldNames: fieldType = entityType.fields[field] try: values = [fieldType.valueFromString(v) for v in req_args[arg]] except Exception as e: raise exceptions.InvalidQueryParameter( f'invalid filter value for {argStr}' ) from e filters.append(resultspec.Filter(field, op, values)) else: raise exceptions.InvalidQueryParameter(f"unrecognized query parameter '{argStr}'") # if ordering or filtering is on a field that's not in fields, bail out if fields: fields = [bytes2unicode(f) for f in fields] fieldsSet = set(fields) if order and {o.lstrip('-') for o in order} - fieldsSet: raise exceptions.InvalidQueryParameter("cannot order on un-selected fields") for filter in filters: if filter.field not in fieldsSet: raise exceptions.InvalidQueryParameter("cannot filter on un-selected fields") # build the result spec rspec = resultspec.ResultSpec( fields=fields, limit=limit, offset=offset, order=order, filters=filters, properties=properties, ) # for singular endpoints, only allow fields if not is_collection: if rspec.filters: raise exceptions.InvalidQueryParameter("this is not a collection") return rspec
10,661
Python
.py
242
31.739669
98
0.581095
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,277
patches.py
buildbot_buildbot/master/buildbot/data/patches.py
# This file is part of Buildbot. Buildbot is free software: you can # redistribute it and/or modify it under the terms of the GNU General Public # License as published by the Free Software Foundation, version 2. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more # details. # # You should have received a copy of the GNU General Public License along with # this program; if not, write to the Free Software Foundation, Inc., 51 # Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # Copyright Buildbot Team Members from __future__ import annotations from buildbot.data import base from buildbot.data import types # NOTE: patches are not available via endpoints class Patch(base.ResourceType): name = "patch" plural = "patches" endpoints: list[type[base.Endpoint]] = [] keyField = 'patchid' class EntityType(types.Entity): patchid = types.Integer() body = types.Binary() level = types.Integer() subdir = types.String() author = types.String() comment = types.String() entityType = EntityType(name, 'Patch')
1,276
Python
.py
31
37.580645
79
0.738076
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,278
test_results.py
buildbot_buildbot/master/buildbot/data/test_results.py
# This file is part of Buildbot. Buildbot is free software: you can # redistribute it and/or modify it under the terms of the GNU General Public # License as published by the Free Software Foundation, version 2. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more # details. # # You should have received a copy of the GNU General Public License along with # this program; if not, write to the Free Software Foundation, Inc., 51 # Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # Copyright Buildbot Team Members from __future__ import annotations from typing import TYPE_CHECKING from twisted.internet import defer from buildbot.data import base from buildbot.data import types if TYPE_CHECKING: from buildbot.db.test_results import TestResultModel class Db2DataMixin: def db2data(self, model: TestResultModel): return { 'test_resultid': model.id, 'builderid': model.builderid, 'test_result_setid': model.test_result_setid, 'test_name': model.test_name, 'test_code_path': model.test_code_path, 'line': model.line, 'duration_ns': model.duration_ns, 'value': model.value, } class TestResultsEndpoint(Db2DataMixin, base.Endpoint): kind = base.EndpointKind.COLLECTION pathPatterns = """ /test_result_sets/n:test_result_setid/results """ @defer.inlineCallbacks def get(self, resultSpec, kwargs): set_dbdict = yield self.master.db.test_result_sets.getTestResultSet( kwargs['test_result_setid'] ) if set_dbdict is None: return [] result_dbdicts = yield self.master.db.test_results.getTestResults( set_dbdict.builderid, kwargs['test_result_setid'], result_spec=resultSpec ) return [self.db2data(result) for result in result_dbdicts] class TestResult(base.ResourceType): name = "test_result" plural = "test_results" endpoints = [TestResultsEndpoint] keyField = 'test_resultid' eventPathPatterns = """ /test_result_sets/:test_result_setid/results """ class EntityType(types.Entity): test_resultid = types.Integer() builderid = types.Integer() test_result_setid = types.Integer() test_name = types.NoneOk(types.String()) test_code_path = types.NoneOk(types.String()) line = types.NoneOk(types.Integer()) duration_ns = types.NoneOk(types.Integer()) value = types.String() entityType = EntityType(name, 'TestResult') @base.updateMethod @defer.inlineCallbacks def addTestResults(self, builderid, test_result_setid, result_values): # We're not adding support for emitting any messages, because in all cases all test results # will be part of a test result set. The users should wait for a 'complete' event on a # test result set and only then fetch the test results, which won't change from that time # onward. yield self.master.db.test_results.addTestResults( builderid, test_result_setid, result_values )
3,315
Python
.py
77
36.467532
99
0.693478
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,279
steps.py
buildbot_buildbot/master/buildbot/data/steps.py
# This file is part of Buildbot. Buildbot is free software: you can # redistribute it and/or modify it under the terms of the GNU General Public # License as published by the Free Software Foundation, version 2. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more # details. # # You should have received a copy of the GNU General Public License along with # this program; if not, write to the Free Software Foundation, Inc., 51 # Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # Copyright Buildbot Team Members from __future__ import annotations from typing import TYPE_CHECKING from twisted.internet import defer from buildbot.data import base from buildbot.data import types if TYPE_CHECKING: from buildbot.db.steps import StepModel class Db2DataMixin: def db2data(self, model: StepModel): return { 'stepid': model.id, 'number': model.number, 'name': model.name, 'buildid': model.buildid, 'started_at': model.started_at, "locks_acquired_at": model.locks_acquired_at, 'complete': model.complete_at is not None, 'complete_at': model.complete_at, 'state_string': model.state_string, 'results': model.results, 'urls': [{'name': item.name, 'url': item.url} for item in model.urls], 'hidden': model.hidden, } class StepEndpoint(Db2DataMixin, base.BuildNestingMixin, base.Endpoint): kind = base.EndpointKind.SINGLE pathPatterns = """ /steps/n:stepid /builds/n:buildid/steps/i:step_name /builds/n:buildid/steps/n:step_number /builders/n:builderid/builds/n:build_number/steps/i:step_name /builders/n:builderid/builds/n:build_number/steps/n:step_number /builders/s:buildername/builds/n:build_number/steps/i:step_name /builders/s:buildername/builds/n:build_number/steps/n:step_number """ @defer.inlineCallbacks def get(self, resultSpec, kwargs): if 'stepid' in kwargs: dbdict = yield self.master.db.steps.getStep(kwargs['stepid']) return self.db2data(dbdict) if dbdict else None buildid = yield self.getBuildid(kwargs) if buildid is None: return None dbdict = yield self.master.db.steps.getStep( buildid=buildid, number=kwargs.get('step_number'), name=kwargs.get('step_name') ) return self.db2data(dbdict) if dbdict else None class StepsEndpoint(Db2DataMixin, base.BuildNestingMixin, base.Endpoint): kind = base.EndpointKind.COLLECTION pathPatterns = """ /builds/n:buildid/steps /builders/n:builderid/builds/n:build_number/steps /builders/s:buildername/builds/n:build_number/steps """ @defer.inlineCallbacks def get(self, resultSpec, kwargs): if 'buildid' in kwargs: buildid = kwargs['buildid'] else: buildid = yield self.getBuildid(kwargs) if buildid is None: return None steps = yield self.master.db.steps.getSteps(buildid=buildid) return [self.db2data(model) for model in steps] class UrlEntityType(types.Entity): name = types.String() url = types.String() class Step(base.ResourceType): name = "step" plural = "steps" endpoints = [StepEndpoint, StepsEndpoint] keyField = 'stepid' eventPathPatterns = """ /builds/:buildid/steps/:stepid /steps/:stepid """ subresources = ["Log"] class EntityType(types.Entity): stepid = types.Integer() number = types.Integer() name = types.Identifier(50) buildid = types.Integer() started_at = types.NoneOk(types.DateTime()) locks_acquired_at = types.NoneOk(types.DateTime()) complete = types.Boolean() complete_at = types.NoneOk(types.DateTime()) results = types.NoneOk(types.Integer()) state_string = types.String() urls = types.List(of=UrlEntityType("Url", "Url")) hidden = types.Boolean() entityType = EntityType(name, 'Step') @defer.inlineCallbacks def generateEvent(self, stepid, event): step = yield self.master.data.get(('steps', stepid)) self.produceEvent(step, event) @base.updateMethod @defer.inlineCallbacks def addStep(self, buildid, name): stepid, num, name = yield self.master.db.steps.addStep( buildid=buildid, name=name, state_string='pending' ) yield self.generateEvent(stepid, 'new') return (stepid, num, name) @base.updateMethod @defer.inlineCallbacks def startStep(self, stepid, started_at=None, locks_acquired=False): if started_at is None: started_at = int(self.master.reactor.seconds()) yield self.master.db.steps.startStep( stepid=stepid, started_at=started_at, locks_acquired=locks_acquired ) yield self.generateEvent(stepid, 'started') @base.updateMethod @defer.inlineCallbacks def set_step_locks_acquired_at(self, stepid, locks_acquired_at=None): if locks_acquired_at is None: locks_acquired_at = int(self.master.reactor.seconds()) yield self.master.db.steps.set_step_locks_acquired_at( stepid=stepid, locks_acquired_at=locks_acquired_at ) yield self.generateEvent(stepid, 'updated') @base.updateMethod @defer.inlineCallbacks def setStepStateString(self, stepid, state_string): yield self.master.db.steps.setStepStateString(stepid=stepid, state_string=state_string) yield self.generateEvent(stepid, 'updated') @base.updateMethod @defer.inlineCallbacks def addStepURL(self, stepid, name, url): yield self.master.db.steps.addURL(stepid=stepid, name=name, url=url) yield self.generateEvent(stepid, 'updated') @base.updateMethod @defer.inlineCallbacks def finishStep(self, stepid, results, hidden): yield self.master.db.steps.finishStep(stepid=stepid, results=results, hidden=hidden) yield self.generateEvent(stepid, 'finished')
6,329
Python
.py
149
35.067114
95
0.676743
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,280
changesources.py
buildbot_buildbot/master/buildbot/data/changesources.py
# This file is part of Buildbot. Buildbot is free software: you can # redistribute it and/or modify it under the terms of the GNU General Public # License as published by the Free Software Foundation, version 2. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more # details. # # You should have received a copy of the GNU General Public License along with # this program; if not, write to the Free Software Foundation, Inc., 51 # Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # Copyright Buildbot Team Members from __future__ import annotations from typing import TYPE_CHECKING from twisted.internet import defer from buildbot.data import base from buildbot.data import masters from buildbot.data import types from buildbot.db.changesources import ChangeSourceAlreadyClaimedError if TYPE_CHECKING: from buildbot.db.changesources import ChangeSourceModel class Db2DataMixin: @defer.inlineCallbacks def db2data(self, dbdict: ChangeSourceModel): master = None if dbdict.masterid is not None and hasattr(self, 'master'): master = yield self.master.data.get(('masters', dbdict.masterid)) data = { 'changesourceid': dbdict.id, 'name': dbdict.name, 'master': master, } return data class ChangeSourceEndpoint(Db2DataMixin, base.Endpoint): pathPatterns = """ /changesources/n:changesourceid /masters/n:masterid/changesources/n:changesourceid """ @defer.inlineCallbacks def get(self, resultSpec, kwargs): dbdict = yield self.master.db.changesources.getChangeSource(kwargs['changesourceid']) if 'masterid' in kwargs: if dbdict.masterid != kwargs['masterid']: return None return (yield self.db2data(dbdict)) if dbdict else None class ChangeSourcesEndpoint(Db2DataMixin, base.Endpoint): kind = base.EndpointKind.COLLECTION pathPatterns = """ /changesources /masters/n:masterid/changesources """ rootLinkName = 'changesources' @defer.inlineCallbacks def get(self, resultSpec, kwargs): changesources = yield self.master.db.changesources.getChangeSources( masterid=kwargs.get('masterid') ) csdicts = yield defer.DeferredList( [self.db2data(cs) for cs in changesources], consumeErrors=True, fireOnOneErrback=True ) return [r for (s, r) in csdicts] class ChangeSource(base.ResourceType): name = "changesource" plural = "changesources" endpoints = [ChangeSourceEndpoint, ChangeSourcesEndpoint] keyField = 'changesourceid' class EntityType(types.Entity): changesourceid = types.Integer() name = types.String() master = types.NoneOk(masters.Master.entityType) entityType = EntityType(name, 'Changesource') @base.updateMethod def findChangeSourceId(self, name): return self.master.db.changesources.findChangeSourceId(name) @base.updateMethod def trySetChangeSourceMaster(self, changesourceid, masterid): # the db layer throws an exception if the claim fails; we translate # that to a straight true-false value. We could trap the exception # type, but that seems a bit too restrictive d = self.master.db.changesources.setChangeSourceMaster(changesourceid, masterid) # set is successful: deferred result is True d.addCallback(lambda _: True) @d.addErrback def trapAlreadyClaimedError(why): # the db layer throws an exception if the claim fails; we squash # that error but let other exceptions continue upward why.trap(ChangeSourceAlreadyClaimedError) # set failed: deferred result is False return False return d @defer.inlineCallbacks def _masterDeactivated(self, masterid): changesources = yield self.master.db.changesources.getChangeSources(masterid=masterid) for cs in changesources: yield self.master.db.changesources.setChangeSourceMaster(cs.id, None)
4,279
Python
.py
97
37.43299
97
0.716999
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,281
root.py
buildbot_buildbot/master/buildbot/data/root.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.data import base from buildbot.data import types class RootEndpoint(base.Endpoint): kind = base.EndpointKind.COLLECTION pathPatterns = "/" def get(self, resultSpec, kwargs): return defer.succeed(self.master.data.rootLinks) class Root(base.ResourceType): name = "rootlink" plural = "rootlinks" endpoints = [RootEndpoint] class EntityType(types.Entity): name = types.String() entityType = EntityType(name, 'Rootlink') class SpecEndpoint(base.Endpoint): kind = base.EndpointKind.COLLECTION pathPatterns = "/application.spec" def get(self, resultSpec, kwargs): return defer.succeed(self.master.data.allEndpoints()) class Spec(base.ResourceType): name = "spec" plural = "specs" endpoints = [SpecEndpoint] class EntityType(types.Entity): path = types.String() type = types.String() plural = types.String() type_spec = types.JsonObject() entityType = EntityType(name, 'Spec')
1,760
Python
.py
44
35.886364
79
0.739847
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,282
resultspec.py
buildbot_buildbot/master/buildbot/data/resultspec.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 dataclasses from typing import TYPE_CHECKING import sqlalchemy as sa from twisted.python import log from buildbot.data import base if TYPE_CHECKING: from typing import Sequence class NotSupportedFieldTypeError(TypeError): def __init__(self, data, *args: object) -> None: super().__init__( ( f"Unsupported data type '{type(data)}': " "must be an instance of Dict or a Dataclass." ), *args, ) def _data_getter(d, fld): if isinstance(d, dict): return d[fld] if dataclasses.is_dataclass(d): try: return getattr(d, fld) except AttributeError as e: # backward compatibility when only dict was allowed raise KeyError(*e.args) from e raise NotSupportedFieldTypeError(d) class FieldBase: """ This class implements a basic behavior to wrap value into a `Field` instance """ __slots__ = ['field', 'op', 'values'] singular_operators = { 'eq': lambda d, v: d == v[0], 'ne': lambda d, v: d != v[0], 'lt': lambda d, v: d < v[0], 'le': lambda d, v: d <= v[0], 'gt': lambda d, v: d > v[0], 'ge': lambda d, v: d >= v[0], 'contains': lambda d, v: v[0] in d, 'in': lambda d, v: d in v, 'notin': lambda d, v: d not in v, } singular_operators_sql = { 'eq': lambda d, v: d == v[0], 'ne': lambda d, v: d != v[0], 'lt': lambda d, v: d < v[0], 'le': lambda d, v: d <= v[0], 'gt': lambda d, v: d > v[0], 'ge': lambda d, v: d >= v[0], 'contains': lambda d, v: d.contains(v[0]), # only support string values, because currently there are no queries against lists in SQL 'in': lambda d, v: d.in_(v), 'notin': lambda d, v: d.notin_(v), } plural_operators = { 'eq': lambda d, v: d in v, 'ne': lambda d, v: d not in v, 'contains': lambda d, v: len(set(v).intersection(set(d))) > 0, 'in': lambda d, v: d in v, 'notin': lambda d, v: d not in v, } plural_operators_sql = { 'eq': lambda d, v: d.in_(v), 'ne': lambda d, v: d.notin_(v), 'contains': lambda d, vs: sa.or_(*[d.contains(v) for v in vs]), 'in': lambda d, v: d.in_(v), 'notin': lambda d, v: d.notin_(v), # sqlalchemy v0.8's or_ cannot take generator arguments, so this has to be manually expanded # only support string values, because currently there are no queries against lists in SQL } def __init__(self, field: bytes | str, op: str, values: Sequence | set): self.field = field self.op = op self.values = values # `str` is a Sequence as well... assert not isinstance(values, str) def getOperator(self, sqlMode=False): v = self.values if len(v) == 1: if sqlMode: ops = self.singular_operators_sql else: ops = self.singular_operators else: if sqlMode: ops = self.plural_operators_sql else: ops = self.plural_operators v = set(v) return ops[self.op] def apply(self, data): fld = self.field v = self.values f = self.getOperator() return (d for d in data if f(_data_getter(d, fld), v)) def __repr__(self): return f"resultspec.{self.__class__.__name__}('{self.field}','{self.op}',{self.values})" def __eq__(self, b): for i in self.__slots__: if getattr(self, i) != getattr(b, i): return False return True def __ne__(self, b): return not self == b class Property(FieldBase): """ Wraps ``property`` type value(s) """ class Filter(FieldBase): """ Wraps ``filter`` type value(s) """ class NoneComparator: """ Object which wraps 'None' when doing comparisons in sorted(). '> None' and '< None' are not supported in Python 3. """ def __init__(self, value): self.value = value def __lt__(self, other): if self.value is None and other.value is None: return False elif self.value is None: return True elif other.value is None: return False return self.value < other.value def __eq__(self, other): return self.value == other.value def __ne__(self, other): return self.value != other.value def __gt__(self, other): if self.value is None and other.value is None: return False elif self.value is None: return False elif other.value is None: return True return self.value > other.value class ReverseComparator: """ Object which swaps '<' and '>' so instead of a < b, it does b < a, and instead of a > b, it does b > a. This can be used in reverse comparisons. """ def __init__(self, value): self.value = value def __lt__(self, other): return other.value < self.value def __eq__(self, other): return other.value == self.value def __ne__(self, other): return other.value != self.value def __gt__(self, other): return other.value > self.value class ResultSpec: __slots__ = ['filters', 'fields', 'properties', 'order', 'limit', 'offset', 'fieldMapping'] def __init__( self, filters=None, fields=None, properties=None, order=None, limit=None, offset=None ): self.filters = filters or [] self.properties = properties or [] self.fields = fields self.order = order self.limit = limit self.offset = offset self.fieldMapping = {} def __repr__(self): return ( f"ResultSpec(**{{'filters': {self.filters}, 'fields': {self.fields}, " f"'properties': {self.properties}, 'order': {self.order}, 'limit': {self.limit}, " f"'offset': {self.offset}" + "})" ) def __eq__(self, b): for i in ['filters', 'fields', 'properties', 'order', 'limit', 'offset']: if getattr(self, i) != getattr(b, i): return False return True def __ne__(self, b): return not self == b def popProperties(self): values = [] for p in self.properties: if p.field == b'property' and p.op == 'eq': self.properties.remove(p) values = p.values break return values def popFilter(self, field, op): for f in self.filters: if f.field == field and f.op == op: self.filters.remove(f) return f.values return None def popOneFilter(self, field, op): v = self.popFilter(field, op) return v[0] if v is not None else None def popBooleanFilter(self, field): eqVals = self.popFilter(field, 'eq') if eqVals and len(eqVals) == 1: return eqVals[0] neVals = self.popFilter(field, 'ne') if neVals and len(neVals) == 1: return not neVals[0] return None def popStringFilter(self, field): eqVals = self.popFilter(field, 'eq') if eqVals and len(eqVals) == 1: return eqVals[0] return None def popIntegerFilter(self, field): eqVals = self.popFilter(field, 'eq') if eqVals and len(eqVals) == 1: try: return int(eqVals[0]) except ValueError as e: raise ValueError( f"Filter value for {field} should be integer, but got: {eqVals[0]}" ) from e return None def removePagination(self): self.limit = self.offset = None def removeOrder(self): self.order = None def popField(self, field): try: i = self.fields.index(field) except ValueError: return False del self.fields[i] return True def findColumn(self, query, field): # will throw key error if field not in mapping mapped = self.fieldMapping[field] for col in query.inner_columns: if str(col) == mapped: return col raise KeyError(f"unable to find field {field} in query") def applyFilterToSQLQuery(self, query, f): field = f.field col = self.findColumn(query, field) # as sqlalchemy is overriding python operators, we can just use the same # python code generated by the filter return query.where(f.getOperator(sqlMode=True)(col, f.values)) def applyOrderToSQLQuery(self, query, o): reverse = False if o.startswith('-'): reverse = True o = o[1:] col = self.findColumn(query, o) if reverse: col = col.desc() return query.order_by(col) def applyToSQLQuery(self, query): filters = self.filters order = self.order unmatched_filters = [] unmatched_order = [] # apply the filters if the name of field is found in the model, and # db2data for f in filters: try: query = self.applyFilterToSQLQuery(query, f) except KeyError: # if filter is unmatched, we will do the filtering manually in # self.apply unmatched_filters.append(f) # apply order if necessary if order: for o in order: try: query = self.applyOrderToSQLQuery(query, o) except KeyError: # if order is unmatched, we will do the ordering manually # in self.apply unmatched_order.append(o) # we cannot limit in sql if there is missing filtering or ordering if unmatched_filters or unmatched_order: if self.offset is not None or self.limit is not None: log.msg( "Warning: limited data api query is not backed by db " "because of following filters", unmatched_filters, unmatched_order, ) self.filters = unmatched_filters self.order = tuple(unmatched_order) return query, None count_query = sa.select(sa.func.count()).select_from(query.alias('query')) self.order = None self.filters = [] # finally, slice out the limit/offset if self.offset is not None: query = query.offset(self.offset) self.offset = None if self.limit is not None: query = query.limit(self.limit) self.limit = None return query, count_query def thd_execute(self, conn, q, dictFromRow): offset = self.offset limit = self.limit q, qc = self.applyToSQLQuery(q) res = conn.execute(q) rv = [dictFromRow(row) for row in res.fetchall()] if qc is not None and (offset or limit): total = conn.execute(qc).scalar() rv = base.ListResult(rv) rv.offset = offset rv.total = total rv.limit = limit return rv def apply(self, data): if data is None: return data if self.fields: fields = set(self.fields) def includeFields(d): if isinstance(d, dict): return dict((k, v) for k, v in d.items() if k in fields) elif dataclasses.is_dataclass(d): raise TypeError("includeFields can't filter fields of dataclasses") raise NotSupportedFieldTypeError(d) applyFields = includeFields else: fields = None applyFields = None if isinstance(data, dict) or dataclasses.is_dataclass(data): # item details if fields: data = applyFields(data) return data else: filters = self.filters order = self.order # item collection if isinstance(data, base.ListResult): # if pagination was applied, then fields, etc. must be empty assert ( not fields and not order and not filters ), "endpoint must apply fields, order, and filters if it performs pagination" offset = data.offset total = data.total limit = data.limit else: offset = None total = None limit = None if fields: data = (applyFields(d) for d in data) # link the filters together and then flatten to list for f in self.filters: data = f.apply(data) data = list(data) if total is None: total = len(data) if self.order: def keyFunc(elem, order=self.order): """ Do a multi-level sort by passing in the keys to sort by. @param elem: each item in the list to sort. @param order: a list of keys to sort by, such as: ('lastName', 'firstName', 'age') @return: a key used by sorted(). This will be a list such as: [a['lastName', a['firstName'], a['age']] @rtype: a C{list} """ compareKey = [] for k in order: doReverse = False if k[0] == '-': # If we get a key '-lastName', # it means sort by 'lastName' in reverse. k = k[1:] doReverse = True val = NoneComparator(_data_getter(elem, k)) if doReverse: val = ReverseComparator(val) compareKey.append(val) return compareKey data.sort(key=keyFunc) # finally, slice out the limit/offset if self.offset is not None or self.limit is not None: if offset is not None or limit is not None: raise AssertionError("endpoint must clear offset/limit") end = (self.offset or 0) + self.limit if self.limit is not None else None data = data[self.offset : end] offset = self.offset limit = self.limit rv = base.ListResult(data) rv.offset = offset rv.total = total rv.limit = limit return rv # a resultSpec which does not implement filtering in python (for tests) class OptimisedResultSpec(ResultSpec): def apply(self, data): return data
15,926
Python
.py
418
27.244019
100
0.544352
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,283
properties.py
buildbot_buildbot/master/buildbot/data/properties.py
# This file is part of Buildbot. Buildbot is free software: you can # redistribute it and/or modify it under the terms of the GNU General Public # License as published by the Free Software Foundation, version 2. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more # details. # # You should have received a copy of the GNU General Public License along with # this program; if not, write to the Free Software Foundation, Inc., 51 # Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # Copyright Buildbot Team Members import json from twisted.internet import defer from buildbot.data import base from buildbot.data import types class BuildsetPropertiesEndpoint(base.Endpoint): kind = base.EndpointKind.SINGLE pathPatterns = """ /buildsets/n:bsid/properties """ def get(self, resultSpec, kwargs): return self.master.db.buildsets.getBuildsetProperties(kwargs['bsid']) class BuildPropertiesEndpoint(base.Endpoint): kind = base.EndpointKind.SINGLE pathPatterns = """ /builders/n:builderid/builds/n:build_number/properties /builds/n:buildid/properties """ @defer.inlineCallbacks def get(self, resultSpec, kwargs): retriever = base.NestedBuildDataRetriever(self.master, kwargs) buildid = yield retriever.get_build_id() build_properties = yield self.master.db.builds.getBuildProperties(buildid) return build_properties class PropertiesListEndpoint(base.Endpoint): kind = base.EndpointKind.COLLECTION pathPatterns = """ /builds/n:buildid/property_list /buildsets/n:bsid/properties_list /changes/n:changeid/properties_list """ buildFieldMapping = { "name": "build_properties.name", "source": "build_properties.source", "value": "build_properties.value", } buildsetFieldMapping = { "name": "buildset_properties.name", "source": "buildset_properties.source", "value": "buildset_properties.value", } changeFieldMapping = { "name": "change_properties.name", "source": "change_properties.source", "value": "change_properties.value", } @defer.inlineCallbacks def get(self, resultSpec, kwargs): buildid = kwargs.get("buildid", None) bsid = kwargs.get("bsid", None) changeid = kwargs.get("changeid", None) if buildid is not None: if resultSpec is not None: resultSpec.fieldMapping = self.buildFieldMapping props = yield self.master.db.builds.getBuildProperties(buildid, resultSpec) elif bsid is not None: if resultSpec is not None: resultSpec.fieldMapping = self.buildsetFieldMapping props = yield self.master.db.buildsets.getBuildsetProperties(bsid) elif changeid is not None: if resultSpec is not None: resultSpec.fieldMapping = self.buildsetFieldMapping props = yield self.master.db.changes.getChangeProperties(changeid) return [{'name': k, 'source': v[1], 'value': json.dumps(v[0])} for k, v in props.items()] class Property(base.ResourceType): name = "_property" plural = "_properties" endpoints = [PropertiesListEndpoint] keyField = "name" entityType = types.PropertyEntityType(name, 'Property') class Properties(base.ResourceType): name = "property" plural = "properties" endpoints = [BuildsetPropertiesEndpoint, BuildPropertiesEndpoint] keyField = "name" entityType = types.SourcedProperties() def generateUpdateEvent(self, buildid, newprops): # This event cannot use the produceEvent mechanism, as the properties resource type is a bit # specific (this is a dictionary collection) # We only send the new properties, and count on the client to merge the resulting properties # dict # We are good, as there is no way to delete a property. routingKey = ('builds', str(buildid), "properties", "update") newprops = self.sanitizeMessage(newprops) return self.master.mq.produce(routingKey, newprops) @base.updateMethod @defer.inlineCallbacks def setBuildProperties(self, buildid, properties): to_update = {} oldproperties = yield self.master.data.get(('builds', str(buildid), "properties")) properties = properties.getProperties() properties = yield properties.render(properties.asDict()) for k, v in properties.items(): if k in oldproperties and oldproperties[k] == v: continue to_update[k] = v if to_update: for k, v in to_update.items(): yield self.master.db.builds.setBuildProperty(buildid, k, v[0], v[1]) yield self.generateUpdateEvent(buildid, to_update) @base.updateMethod @defer.inlineCallbacks def setBuildProperty(self, buildid, name, value, source): res = yield self.master.db.builds.setBuildProperty(buildid, name, value, source) yield self.generateUpdateEvent(buildid, {"name": (value, source)}) return res
5,314
Python
.py
119
37.588235
100
0.691282
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,284
workers.py
buildbot_buildbot/master/buildbot/data/workers.py
# This file is part of Buildbot. Buildbot is free software: you can # redistribute it and/or modify it under the terms of the GNU General Public # License as published by the Free Software Foundation, version 2. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more # details. # # You should have received a copy of the GNU General Public License along with # this program; if not, write to the Free Software Foundation, Inc., 51 # Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # Copyright Buildbot Team Members from __future__ import annotations from typing import TYPE_CHECKING from twisted.internet import defer from buildbot.data import base from buildbot.data import exceptions from buildbot.data import types from buildbot.util import identifiers if TYPE_CHECKING: from buildbot.db.workers import WorkerModel class Db2DataMixin: def db2data(self, model: WorkerModel): return { 'workerid': model.id, 'name': model.name, 'workerinfo': model.workerinfo, 'paused': model.paused, "pause_reason": model.pause_reason, 'graceful': model.graceful, 'connected_to': [{'masterid': id} for id in model.connected_to], 'configured_on': [ {'masterid': c.masterid, 'builderid': c.builderid} for c in model.configured_on ], } class WorkerEndpoint(Db2DataMixin, base.Endpoint): kind = base.EndpointKind.SINGLE pathPatterns = """ /workers/n:workerid /workers/i:name /masters/n:masterid/workers/n:workerid /masters/n:masterid/workers/i:name /masters/n:masterid/builders/n:builderid/workers/n:workerid /masters/n:masterid/builders/n:builderid/workers/i:name /builders/n:builderid/workers/n:workerid /builders/n:builderid/workers/i:name """ @defer.inlineCallbacks def get(self, resultSpec, kwargs): sldict = yield self.master.db.workers.getWorker( workerid=kwargs.get('workerid'), name=kwargs.get('name'), masterid=kwargs.get('masterid'), builderid=kwargs.get('builderid'), ) if sldict: return self.db2data(sldict) return None @defer.inlineCallbacks def control(self, action, args, kwargs): if action not in ("stop", "pause", "unpause", "kill"): raise exceptions.InvalidControlException(f"action: {action} is not supported") worker = yield self.get(None, kwargs) if worker is not None: self.master.mq.produce( ("control", "worker", str(worker["workerid"]), action), {"reason": kwargs.get("reason", args.get("reason", "no reason"))}, ) else: raise exceptions.exceptions.InvalidPathError("worker not found") class WorkersEndpoint(Db2DataMixin, base.Endpoint): kind = base.EndpointKind.COLLECTION rootLinkName = 'workers' pathPatterns = """ /workers /masters/n:masterid/workers /masters/n:masterid/builders/n:builderid/workers /builders/n:builderid/workers """ @defer.inlineCallbacks def get(self, resultSpec, kwargs): paused = resultSpec.popBooleanFilter('paused') graceful = resultSpec.popBooleanFilter('graceful') workers_dicts = yield self.master.db.workers.getWorkers( builderid=kwargs.get('builderid'), masterid=kwargs.get('masterid'), paused=paused, graceful=graceful, ) return [self.db2data(w) for w in workers_dicts] class MasterBuilderEntityType(types.Entity): masterid = types.Integer() builderid = types.Integer() class MasterIdEntityType(types.Entity): masterid = types.Integer() class Worker(base.ResourceType): name = "worker" plural = "workers" endpoints = [WorkerEndpoint, WorkersEndpoint] keyField = 'workerid' eventPathPatterns = """ /workers/:workerid """ subresources = ["Build"] class EntityType(types.Entity): workerid = types.Integer() name = types.String() connected_to = types.List(of=MasterIdEntityType("master_id", 'MasterId')) configured_on = types.List(of=MasterBuilderEntityType("master_builder", 'MasterBuilder')) workerinfo = types.JsonObject() paused = types.Boolean() pause_reason = types.NoneOk(types.String()) graceful = types.Boolean() entityType = EntityType(name, 'Worker') @base.updateMethod # returns a Deferred that returns None def workerConfigured(self, workerid, masterid, builderids): return self.master.db.workers.workerConfigured( workerid=workerid, masterid=masterid, builderids=builderids ) @base.updateMethod def findWorkerId(self, name): if not identifiers.isIdentifier(50, name): raise ValueError(f"Worker name {name!r} is not a 50-character identifier") return self.master.db.workers.findWorkerId(name) @base.updateMethod @defer.inlineCallbacks def workerConnected(self, workerid, masterid, workerinfo): yield self.master.db.workers.workerConnected( workerid=workerid, masterid=masterid, workerinfo=workerinfo ) bs = yield self.master.data.get(('workers', workerid)) self.produceEvent(bs, 'connected') @base.updateMethod @defer.inlineCallbacks def workerDisconnected(self, workerid, masterid): yield self.master.db.workers.workerDisconnected(workerid=workerid, masterid=masterid) bs = yield self.master.data.get(('workers', workerid)) self.produceEvent(bs, 'disconnected') @base.updateMethod @defer.inlineCallbacks def workerMissing(self, workerid, masterid, last_connection, notify): bs = yield self.master.data.get(('workers', workerid)) bs['last_connection'] = last_connection bs['notify'] = notify self.produceEvent(bs, 'missing') @base.updateMethod @defer.inlineCallbacks def set_worker_paused(self, workerid, paused, pause_reason=None): yield self.master.db.workers.set_worker_paused( workerid=workerid, paused=paused, pause_reason=pause_reason ) bs = yield self.master.data.get(('workers', workerid)) self.produceEvent(bs, 'state_updated') @base.updateMethod @defer.inlineCallbacks def set_worker_graceful(self, workerid, graceful): yield self.master.db.workers.set_worker_graceful(workerid=workerid, graceful=graceful) bs = yield self.master.data.get(('workers', workerid)) self.produceEvent(bs, 'state_updated') @base.updateMethod def deconfigureAllWorkersForMaster(self, masterid): # unconfigure all workers for this master return self.master.db.workers.deconfigureAllWorkersForMaster(masterid=masterid) def _masterDeactivated(self, masterid): return self.deconfigureAllWorkersForMaster(masterid)
7,215
Python
.py
168
35.517857
97
0.685103
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,285
schedulers.py
buildbot_buildbot/master/buildbot/data/schedulers.py
# This file is part of Buildbot. Buildbot is free software: you can # redistribute it and/or modify it under the terms of the GNU General Public # License as published by the Free Software Foundation, version 2. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more # details. # # You should have received a copy of the GNU General Public License along with # this program; if not, write to the Free Software Foundation, Inc., 51 # Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # Copyright Buildbot Team Members from __future__ import annotations from typing import TYPE_CHECKING from twisted.internet import defer from buildbot.data import base from buildbot.data import masters from buildbot.data import types from buildbot.db.schedulers import SchedulerAlreadyClaimedError if TYPE_CHECKING: from buildbot.db.schedulers import SchedulerModel class Db2DataMixin: @defer.inlineCallbacks def db2data(self, dbdict: SchedulerModel): master = None if dbdict.masterid is not None and hasattr(self, 'master'): master = yield self.master.data.get(('masters', dbdict.masterid)) data = { 'schedulerid': dbdict.id, 'name': dbdict.name, 'enabled': dbdict.enabled, 'master': master, } return data class SchedulerEndpoint(Db2DataMixin, base.Endpoint): kind = base.EndpointKind.SINGLE pathPatterns = """ /schedulers/n:schedulerid /masters/n:masterid/schedulers/n:schedulerid """ @defer.inlineCallbacks def get(self, resultSpec, kwargs): dbdict = yield self.master.db.schedulers.getScheduler(kwargs['schedulerid']) if 'masterid' in kwargs: if dbdict.masterid != kwargs['masterid']: return None return (yield self.db2data(dbdict)) if dbdict else None @defer.inlineCallbacks def control(self, action, args, kwargs): if action == 'enable': schedulerid = kwargs['schedulerid'] v = args['enabled'] yield self.master.data.updates.schedulerEnable(schedulerid, v) return None class SchedulersEndpoint(Db2DataMixin, base.Endpoint): kind = base.EndpointKind.COLLECTION pathPatterns = """ /schedulers /masters/n:masterid/schedulers """ rootLinkName = 'schedulers' @defer.inlineCallbacks def get(self, resultSpec, kwargs): schedulers = yield self.master.db.schedulers.getSchedulers(masterid=kwargs.get('masterid')) schdicts = yield defer.DeferredList( [self.db2data(schdict) for schdict in schedulers], consumeErrors=True, fireOnOneErrback=True, ) return [r for (s, r) in schdicts] class Scheduler(base.ResourceType): name = "scheduler" plural = "schedulers" endpoints = [SchedulerEndpoint, SchedulersEndpoint] keyField = 'schedulerid' eventPathPatterns = """ /schedulers/:schedulerid """ class EntityType(types.Entity): schedulerid = types.Integer() name = types.String() enabled = types.Boolean() master = types.NoneOk(masters.Master.entityType) entityType = EntityType(name, 'Scheduler') @defer.inlineCallbacks def generateEvent(self, schedulerid, event): scheduler = yield self.master.data.get(('schedulers', str(schedulerid))) self.produceEvent(scheduler, event) @base.updateMethod @defer.inlineCallbacks def schedulerEnable(self, schedulerid, v): yield self.master.db.schedulers.enable(schedulerid, v) yield self.generateEvent(schedulerid, 'updated') return None @base.updateMethod def findSchedulerId(self, name): return self.master.db.schedulers.findSchedulerId(name) @base.updateMethod def trySetSchedulerMaster(self, schedulerid, masterid): d = self.master.db.schedulers.setSchedulerMaster(schedulerid, masterid) # set is successful: deferred result is True d.addCallback(lambda _: True) @d.addErrback def trapAlreadyClaimedError(why): # the db layer throws an exception if the claim fails; we squash # that error but let other exceptions continue upward why.trap(SchedulerAlreadyClaimedError) # set failed: deferred result is False return False return d @defer.inlineCallbacks def _masterDeactivated(self, masterid): schedulers = yield self.master.db.schedulers.getSchedulers(masterid=masterid) for sch in schedulers: yield self.master.db.schedulers.setSchedulerMaster(sch.id, None)
4,855
Python
.py
117
34.555556
99
0.700064
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,286
logs.py
buildbot_buildbot/master/buildbot/data/logs.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 Member from __future__ import annotations from typing import TYPE_CHECKING from twisted.internet import defer from buildbot.data import base from buildbot.data import types from buildbot.db.logs import LogSlugExistsError from buildbot.util import identifiers if TYPE_CHECKING: from buildbot.db.logs import LogModel class EndpointMixin: def db2data(self, model: LogModel): data = { 'logid': model.id, 'name': model.name, 'slug': model.slug, 'stepid': model.stepid, 'complete': model.complete, 'num_lines': model.num_lines, 'type': model.type, } return defer.succeed(data) class LogEndpoint(EndpointMixin, base.BuildNestingMixin, base.Endpoint): kind = base.EndpointKind.SINGLE pathPatterns = """ /logs/n:logid /steps/n:stepid/logs/i:log_slug /builds/n:buildid/steps/i:step_name/logs/i:log_slug /builds/n:buildid/steps/n:step_number/logs/i:log_slug /builders/n:builderid/builds/n:build_number/steps/i:step_name/logs/i:log_slug /builders/n:builderid/builds/n:build_number/steps/n:step_number/logs/i:log_slug /builders/s:buildername/builds/n:build_number/steps/i:step_name/logs/i:log_slug /builders/s:buildername/builds/n:build_number/steps/n:step_number/logs/i:log_slug """ @defer.inlineCallbacks def get(self, resultSpec, kwargs): if 'logid' in kwargs: dbdict = yield self.master.db.logs.getLog(kwargs['logid']) return (yield self.db2data(dbdict)) if dbdict else None retriever = base.NestedBuildDataRetriever(self.master, kwargs) step_dict = yield retriever.get_step_dict() if step_dict is None: return None dbdict = yield self.master.db.logs.getLogBySlug(step_dict.id, kwargs.get('log_slug')) return (yield self.db2data(dbdict)) if dbdict else None class LogsEndpoint(EndpointMixin, base.BuildNestingMixin, base.Endpoint): kind = base.EndpointKind.COLLECTION pathPatterns = """ /steps/n:stepid/logs /builds/n:buildid/steps/i:step_name/logs /builds/n:buildid/steps/n:step_number/logs /builders/n:builderid/builds/n:build_number/steps/i:step_name/logs /builders/n:builderid/builds/n:build_number/steps/n:step_number/logs /builders/s:buildername/builds/n:build_number/steps/i:step_name/logs /builders/s:buildername/builds/n:build_number/steps/n:step_number/logs """ @defer.inlineCallbacks def get(self, resultSpec, kwargs): retriever = base.NestedBuildDataRetriever(self.master, kwargs) step_dict = yield retriever.get_step_dict() if step_dict is None: return [] logs = yield self.master.db.logs.getLogs(stepid=step_dict.id) results = [] for dbdict in logs: results.append((yield self.db2data(dbdict))) return results class Log(base.ResourceType): name = "log" plural = "logs" endpoints = [LogEndpoint, LogsEndpoint] keyField = "logid" eventPathPatterns = """ /logs/:logid /steps/:stepid/logs/:slug """ subresources = ["LogChunk"] class EntityType(types.Entity): logid = types.Integer() name = types.String() slug = types.Identifier(50) stepid = types.Integer() complete = types.Boolean() num_lines = types.Integer() type = types.Identifier(1) entityType = EntityType(name, 'Log') @defer.inlineCallbacks def generateEvent(self, _id, event): # get the build and munge the result for the notification build = yield self.master.data.get(('logs', str(_id))) self.produceEvent(build, event) @base.updateMethod @defer.inlineCallbacks def addLog(self, stepid, name, type): slug = identifiers.forceIdentifier(50, name) while True: try: logid = yield self.master.db.logs.addLog( stepid=stepid, name=name, slug=slug, type=type ) except LogSlugExistsError: slug = identifiers.incrementIdentifier(50, slug) continue self.generateEvent(logid, "new") return logid @base.updateMethod @defer.inlineCallbacks def appendLog(self, logid, content): res = yield self.master.db.logs.appendLog(logid=logid, content=content) self.generateEvent(logid, "append") return res @base.updateMethod @defer.inlineCallbacks def finishLog(self, logid): res = yield self.master.db.logs.finishLog(logid=logid) self.generateEvent(logid, "finished") return res @base.updateMethod def compressLog(self, logid): return self.master.db.logs.compressLog(logid=logid)
5,569
Python
.py
133
34.466165
93
0.677199
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,287
projects.py
buildbot_buildbot/master/buildbot/data/projects.py
# This file is part of Buildbot. Buildbot is free software: you can # redistribute it and/or modify it under the terms of the GNU General Public # License as published by the Free Software Foundation, version 2. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more # details. # # You should have received a copy of the GNU General Public License along with # this program; if not, write to the Free Software Foundation, Inc., 51 # Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # Copyright Buildbot Team Members from __future__ import annotations from typing import TYPE_CHECKING from twisted.internet import defer from buildbot.data import base from buildbot.data import types if TYPE_CHECKING: from buildbot.db.projects import ProjectModel def project_db_to_data(model: ProjectModel, active=None): return { "projectid": model.id, "name": model.name, "slug": model.slug, "description": model.description, "description_format": model.description_format, "description_html": model.description_html, "active": active, } class ProjectEndpoint(base.BuildNestingMixin, base.Endpoint): kind = base.EndpointKind.SINGLE pathPatterns = """ /projects/n:projectid /projects/i:projectname """ @defer.inlineCallbacks def get(self, result_spec, kwargs): projectid = yield self.get_project_id(kwargs) if projectid is None: return None dbdict = yield self.master.db.projects.get_project(projectid) if not dbdict: return None return project_db_to_data(dbdict) class ProjectsEndpoint(base.Endpoint): kind = base.EndpointKind.COLLECTION rootLinkName = 'projects' pathPatterns = """ /projects """ @defer.inlineCallbacks def get(self, result_spec, kwargs): active = result_spec.popBooleanFilter("active") if active is None: dbdicts = yield self.master.db.projects.get_projects() elif active: dbdicts = yield self.master.db.projects.get_active_projects() else: # This is not optimized case which is assumed to be infrequently required dbdicts_all = yield self.master.db.projects.get_projects() dbdicts_active = yield self.master.db.projects.get_active_projects() ids_active = set(dbdict.id for dbdict in dbdicts_active) dbdicts = [dbdict for dbdict in dbdicts_all if dbdict.id not in ids_active] return [project_db_to_data(dbdict, active=active) for dbdict in dbdicts] def get_kwargs_from_graphql(self, parent, resolve_info, args): return {} class Project(base.ResourceType): name = "project" plural = "projects" endpoints = [ProjectEndpoint, ProjectsEndpoint] keyField = 'projectid' eventPathPatterns = """ /projects/:projectid """ subresources = ["Builder"] class EntityType(types.Entity): projectid = types.Integer() name = types.Identifier(70) slug = types.Identifier(70) active = types.NoneOk(types.Boolean()) description = types.NoneOk(types.String()) description_format = types.NoneOk(types.String()) description_html = types.NoneOk(types.String()) entityType = EntityType(name, 'Project') @defer.inlineCallbacks def generate_event(self, _id, event): project = yield self.master.data.get(('projects', str(_id))) self.produceEvent(project, event) @base.updateMethod def find_project_id(self, name): return self.master.db.projects.find_project_id(name) @base.updateMethod @defer.inlineCallbacks def update_project_info( self, projectid, slug, description, description_format, description_html ): yield self.master.db.projects.update_project_info( projectid, slug, description, description_format, description_html ) yield self.generate_event(projectid, "update")
4,198
Python
.py
102
34.676471
87
0.695311
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,288
masters.py
buildbot_buildbot/master/buildbot/data/masters.py
# This file is part of Buildbot. Buildbot is free software: you can # redistribute it and/or modify it under the terms of the GNU General Public # License as published by the Free Software Foundation, version 2. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more # details. # # You should have received a copy of the GNU General Public License along with # this program; if not, write to the Free Software Foundation, Inc., 51 # Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # Copyright Buildbot Team Members from __future__ import annotations from typing import TYPE_CHECKING from twisted.internet import defer from twisted.python import log from buildbot.data import base from buildbot.data import resultspec from buildbot.data import types from buildbot.process.results import RETRY from buildbot.util import epoch2datetime if TYPE_CHECKING: from buildbot.db.masters import MasterModel # time, in minutes, after which a master that hasn't checked in will be # marked as inactive EXPIRE_MINUTES = 10 def _db2data(model: MasterModel): return { "masterid": model.id, "name": model.name, "active": model.active, "last_active": model.last_active, } class MasterEndpoint(base.Endpoint): kind = base.EndpointKind.SINGLE pathPatterns = """ /masters/n:masterid /builders/n:builderid/masters/n:masterid """ @defer.inlineCallbacks def get(self, resultSpec, kwargs): # if a builder is given, only return the master if it's associated with # this builder if 'builderid' in kwargs: builder = yield self.master.db.builders.getBuilder(builderid=kwargs['builderid']) if not builder or kwargs['masterid'] not in builder.masterids: return None m = yield self.master.db.masters.getMaster(kwargs['masterid']) return _db2data(m) if m else None class MastersEndpoint(base.Endpoint): kind = base.EndpointKind.COLLECTION pathPatterns = """ /masters /builders/n:builderid/masters """ rootLinkName = 'masters' @defer.inlineCallbacks def get(self, resultSpec, kwargs): masterlist = yield self.master.db.masters.getMasters() if 'builderid' in kwargs: builder = yield self.master.db.builders.getBuilder(builderid=kwargs['builderid']) if builder: masterids = set(builder.masterids) masterlist = [m for m in masterlist if m.id in masterids] else: masterlist = [] return [_db2data(m) for m in masterlist] class Master(base.ResourceType): name = "master" plural = "masters" endpoints = [MasterEndpoint, MastersEndpoint] eventPathPatterns = """ /masters/:masterid """ keyField = "masterid" subresources = ["Builder"] class EntityType(types.Entity): masterid = types.Integer() name = types.String() active = types.Boolean() last_active = types.DateTime() entityType = EntityType(name, 'Master') @base.updateMethod @defer.inlineCallbacks def masterActive(self, name, masterid): activated = yield self.master.db.masters.setMasterState(masterid=masterid, active=True) if activated: self.produceEvent({"masterid": masterid, "name": name, "active": True}, 'started') @base.updateMethod @defer.inlineCallbacks def expireMasters(self, forceHouseKeeping=False): too_old = epoch2datetime(self.master.reactor.seconds() - 60 * EXPIRE_MINUTES) masters = yield self.master.db.masters.getMasters() for m in masters: if m.last_active is not None and m.last_active >= too_old: continue # mark the master inactive, and send a message on its behalf deactivated = yield self.master.db.masters.setMasterState(masterid=m.id, active=False) if deactivated: yield self._masterDeactivated(m.id, m.name) elif forceHouseKeeping: yield self._masterDeactivatedHousekeeping(m.id, m.name) @base.updateMethod @defer.inlineCallbacks def masterStopped(self, name, masterid): deactivated = yield self.master.db.masters.setMasterState(masterid=masterid, active=False) if deactivated: yield self._masterDeactivated(masterid, name) @defer.inlineCallbacks def _masterDeactivatedHousekeeping(self, masterid, name): log.msg(f"doing housekeeping for master {masterid} {name}") # common code for deactivating a master yield self.master.data.rtypes.worker._masterDeactivated(masterid=masterid) yield self.master.data.rtypes.builder._masterDeactivated(masterid=masterid) yield self.master.data.rtypes.scheduler._masterDeactivated(masterid=masterid) yield self.master.data.rtypes.changesource._masterDeactivated(masterid=masterid) # for each build running on that instance.. builds = yield self.master.data.get( ('builds',), filters=[ resultspec.Filter('masterid', 'eq', [masterid]), resultspec.Filter('complete', 'eq', [False]), ], ) for build in builds: # stop any running steps.. steps = yield self.master.data.get( ('builds', build['buildid'], 'steps'), filters=[resultspec.Filter('results', 'eq', [None])], ) for step in steps: # finish remaining logs for those steps.. logs = yield self.master.data.get( ('steps', step['stepid'], 'logs'), filters=[resultspec.Filter('complete', 'eq', [False])], ) for _log in logs: yield self.master.data.updates.finishLog(logid=_log['logid']) yield self.master.data.updates.finishStep( stepid=step['stepid'], results=RETRY, hidden=False ) # then stop the build itself yield self.master.data.updates.finishBuild(buildid=build['buildid'], results=RETRY) # unclaim all of the build requests owned by the deactivated instance buildrequests = yield self.master.db.buildrequests.getBuildRequests( complete=False, claimed=masterid ) yield self.master.db.buildrequests.unclaimBuildRequests( brids=[br.buildrequestid for br in buildrequests] ) @defer.inlineCallbacks def _masterDeactivated(self, masterid, name): yield self._masterDeactivatedHousekeeping(masterid, name) self.produceEvent({"masterid": masterid, "name": name, "active": False}, 'stopped')
6,963
Python
.py
156
36.198718
98
0.665585
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,289
builders.py
buildbot_buildbot/master/buildbot/data/builders.py
# This file is part of Buildbot. Buildbot is free software: you can # redistribute it and/or modify it under the terms of the GNU General Public # License as published by the Free Software Foundation, version 2. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more # details. # # You should have received a copy of the GNU General Public License along with # this program; if not, write to the Free Software Foundation, Inc., 51 # Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # Copyright Buildbot Team Members from __future__ import annotations from typing import TYPE_CHECKING from twisted.internet import defer from buildbot.data import base from buildbot.data import types if TYPE_CHECKING: from buildbot.db.builders import BuilderModel def _db2data(builder: BuilderModel): return { "builderid": builder.id, "name": builder.name, "masterids": builder.masterids, "description": builder.description, "description_format": builder.description_format, "description_html": builder.description_html, "projectid": builder.projectid, "tags": builder.tags, } class BuilderEndpoint(base.BuildNestingMixin, base.Endpoint): kind = base.EndpointKind.SINGLE pathPatterns = """ /builders/n:builderid /builders/s:buildername /masters/n:masterid/builders/n:builderid """ @defer.inlineCallbacks def get(self, resultSpec, kwargs): builderid = yield self.getBuilderId(kwargs) if builderid is None: return None builder = yield self.master.db.builders.getBuilder(builderid) if not builder: return None if 'masterid' in kwargs: if kwargs['masterid'] not in builder.masterids: return None return _db2data(builder) class BuildersEndpoint(base.Endpoint): kind = base.EndpointKind.COLLECTION rootLinkName = 'builders' pathPatterns = """ /builders /masters/n:masterid/builders /projects/n:projectid/builders /workers/n:workerid/builders """ @defer.inlineCallbacks def get(self, resultSpec, kwargs): bdicts = yield self.master.db.builders.getBuilders( masterid=kwargs.get('masterid', None), projectid=kwargs.get('projectid', None), workerid=kwargs.get('workerid', None), ) return [_db2data(bd) for bd in bdicts] def get_kwargs_from_graphql(self, parent, resolve_info, args): if parent is not None: return {'masterid': parent['masterid']} return {} class Builder(base.ResourceType): name = "builder" plural = "builders" endpoints = [BuilderEndpoint, BuildersEndpoint] keyField = 'builderid' eventPathPatterns = """ /builders/:builderid """ subresources = ["Build", "Forcescheduler", "Scheduler", "Buildrequest"] class EntityType(types.Entity): builderid = types.Integer() name = types.String() masterids = types.List(of=types.Integer()) description = types.NoneOk(types.String()) description_format = types.NoneOk(types.String()) description_html = types.NoneOk(types.String()) projectid = types.NoneOk(types.Integer()) tags = types.List(of=types.String()) entityType = EntityType(name, 'Builder') @defer.inlineCallbacks def generateEvent(self, _id, event): builder = yield self.master.data.get(('builders', str(_id))) self.produceEvent(builder, event) @base.updateMethod def findBuilderId(self, name): return self.master.db.builders.findBuilderId(name) @base.updateMethod @defer.inlineCallbacks def updateBuilderInfo( self, builderid, description, description_format, description_html, projectid, tags ): ret = yield self.master.db.builders.updateBuilderInfo( builderid, description, description_format, description_html, projectid, tags ) yield self.generateEvent(builderid, "update") return ret @base.updateMethod @defer.inlineCallbacks def updateBuilderList(self, masterid, builderNames): # get the "current" list of builders for this master, so we know what # changes to make. Race conditions here aren't a great worry, as this # is the only master inserting or deleting these records. builders = yield self.master.db.builders.getBuilders(masterid=masterid) # figure out what to remove and remove it builderNames_set = set(builderNames) for bldr in builders: if bldr.name not in builderNames_set: builderid = bldr.id yield self.master.db.builders.removeBuilderMaster( masterid=masterid, builderid=builderid ) self.master.mq.produce( ('builders', str(builderid), 'stopped'), {"builderid": builderid, "masterid": masterid, "name": bldr.name}, ) else: builderNames_set.remove(bldr.name) # now whatever's left in builderNames_set is new for name in builderNames_set: builderid = yield self.master.db.builders.findBuilderId(name) yield self.master.db.builders.addBuilderMaster(masterid=masterid, builderid=builderid) self.master.mq.produce( ('builders', str(builderid), 'started'), {"builderid": builderid, "masterid": masterid, "name": name}, ) # returns a Deferred that returns None def _masterDeactivated(self, masterid): # called from the masters rtype to indicate that the given master is # deactivated return self.updateBuilderList(masterid, [])
6,007
Python
.py
142
34.359155
98
0.670492
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,290
logchunks.py
buildbot_buildbot/master/buildbot/data/logchunks.py
# This file is part of Buildbot. Buildbot is free software: you can # redistribute it and/or modify it under the terms of the GNU General Public # License as published by the Free Software Foundation, version 2. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more # details. # # You should have received a copy of the GNU General Public License along with # this program; if not, write to the Free Software Foundation, Inc., 51 # Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # Copyright Buildbot Team Members from __future__ import annotations from typing import TYPE_CHECKING from twisted.internet import defer from buildbot.data import base from buildbot.data import types if TYPE_CHECKING: from typing import Any from typing import AsyncGenerator from buildbot.db.logs import LogModel class LogChunkEndpointBase(base.BuildNestingMixin, base.Endpoint): @staticmethod async def get_raw_log_lines(log_lines_generator: AsyncGenerator[str, None]) -> str: parts = [] async for chunk in log_lines_generator: parts.append(chunk) return ''.join(parts) async def get_log_lines( self, log_dict: LogModel, log_prefix: str, lines_batch: int = 1000, ) -> AsyncGenerator[str, None]: if log_prefix: yield log_prefix lastline = max(0, log_dict.num_lines) lines_batch = max(lines_batch, 1) for idx in range(0, lastline, lines_batch): line_start = idx line_end = min(lastline - 1, idx + lines_batch) # TODO: Add a new API to db.logs that yield lines lines: str = await self.master.db.logs.getLogLines(log_dict.id, line_start, line_end) if log_dict.type == 's': # for stdio logs, the first char is the stream type # ref: https://buildbot.readthedocs.io/en/latest/developer/raml/logchunk.html#logchunk for line in lines.splitlines(keepends=True): yield line[1:] continue yield lines @defer.inlineCallbacks def get_log_lines_raw_data(self, kwargs): retriever = base.NestedBuildDataRetriever(self.master, kwargs) log_dict = yield retriever.get_log_dict() if log_dict is None: return None, None, None # The following should be run sequentially instead of in gatherResults(), so that # they don't all start a query on step dict each. step_dict = yield retriever.get_step_dict() build_dict = yield retriever.get_build_dict() builder_dict = yield retriever.get_builder_dict() worker_dict = yield retriever.get_worker_dict() log_prefix = '' if log_dict.type == 's': if builder_dict is not None: log_prefix += f'Builder: {builder_dict.name}\n' if build_dict is not None: log_prefix += f'Build number: {build_dict.number}\n' if worker_dict is not None: log_prefix += f'Worker name: {worker_dict.name}\n' informative_parts = [] if builder_dict is not None: informative_parts += [builder_dict.name] if build_dict is not None: informative_parts += ['build', str(build_dict.number)] if step_dict is not None: informative_parts += ['step', step_dict.name] informative_parts += ['log', log_dict.slug] informative_slug = '_'.join(informative_parts) return self.get_log_lines(log_dict, log_prefix), log_dict.type, informative_slug class LogChunkEndpoint(LogChunkEndpointBase): # Note that this is a singular endpoint, even though it overrides the # offset/limit query params in ResultSpec kind = base.EndpointKind.SINGLE isPseudoCollection = True pathPatterns = """ /logchunks /logs/n:logid/contents /steps/n:stepid/logs/i:log_slug/contents /builds/n:buildid/steps/i:step_name/logs/i:log_slug/contents /builds/n:buildid/steps/n:step_number/logs/i:log_slug/contents /builders/n:builderid/builds/n:build_number/steps/i:step_name/logs/i:log_slug/contents /builders/n:builderid/builds/n:build_number/steps/n:step_number/logs/i:log_slug/contents """ rootLinkName = "logchunks" @defer.inlineCallbacks def get(self, resultSpec, kwargs): retriever = base.NestedBuildDataRetriever(self.master, kwargs) logid = yield retriever.get_log_id() if logid is None: return None firstline = int(resultSpec.offset or 0) lastline = None if resultSpec.limit is None else firstline + int(resultSpec.limit) - 1 resultSpec.removePagination() # get the number of lines, if necessary if lastline is None: log_dict = yield retriever.get_log_dict() if not log_dict: return None lastline = int(max(0, log_dict.num_lines - 1)) # bounds checks if firstline < 0 or lastline < 0 or firstline > lastline: return None logLines = yield self.master.db.logs.getLogLines(logid, firstline, lastline) return {'logid': logid, 'firstline': firstline, 'content': logLines} def get_kwargs_from_graphql(self, parent, resolve_info, args): if parent is not None: return self.get_kwargs_from_graphql_parent(parent, resolve_info.parent_type.name) return {"logid": args["logid"]} class RawLogChunkEndpoint(LogChunkEndpointBase): # Note that this is a singular endpoint, even though it overrides the # offset/limit query params in ResultSpec kind = base.EndpointKind.RAW pathPatterns = """ /logs/n:logid/raw /steps/n:stepid/logs/i:log_slug/raw /builds/n:buildid/steps/i:step_name/logs/i:log_slug/raw /builds/n:buildid/steps/n:step_number/logs/i:log_slug/raw /builders/n:builderid/builds/n:build_number/steps/i:step_name/logs/i:log_slug/raw /builders/n:builderid/builds/n:build_number/steps/n:step_number/logs/i:log_slug/raw """ @defer.inlineCallbacks def get(self, resultSpec, kwargs): data = yield defer.Deferred.fromCoroutine(self.stream(resultSpec, kwargs)) if data is None: return None data["raw"] = yield defer.Deferred.fromCoroutine( self.get_raw_log_lines(log_lines_generator=data["raw"]) ) return data async def stream(self, resultSpec: base.ResultSpec, kwargs: dict[str, Any]): log_lines_generator, log_type, log_slug = await self.get_log_lines_raw_data(kwargs) if log_lines_generator is None: return None return { 'raw': log_lines_generator, 'mime-type': 'text/html' if log_type == 'h' else 'text/plain', 'filename': log_slug, } class RawInlineLogChunkEndpoint(LogChunkEndpointBase): # Note that this is a singular endpoint, even though it overrides the # offset/limit query params in ResultSpec kind = base.EndpointKind.RAW_INLINE pathPatterns = """ /logs/n:logid/raw_inline /steps/n:stepid/logs/i:log_slug/raw_inline /builds/n:buildid/steps/i:step_name/logs/i:log_slug/raw_inline /builds/n:buildid/steps/n:step_number/logs/i:log_slug/raw_inline /builders/n:builderid/builds/n:build_number/steps/i:step_name/logs/i:log_slug/raw_inline /builders/n:builderid/builds/n:build_number/steps/n:step_number/logs/i:log_slug/raw_inline """ @defer.inlineCallbacks def get(self, resultSpec, kwargs): data = yield defer.Deferred.fromCoroutine(self.stream(resultSpec, kwargs)) if data is None: return None data["raw"] = yield defer.Deferred.fromCoroutine( self.get_raw_log_lines(log_lines_generator=data["raw"]) ) return data async def stream(self, resultSpec: base.ResultSpec, kwargs: dict[str, Any]): log_lines_generator, log_type, _ = await self.get_log_lines_raw_data(kwargs) if log_lines_generator is None: return None return { 'raw': log_lines_generator, 'mime-type': 'text/html' if log_type == 'h' else 'text/plain', } class LogChunk(base.ResourceType): name = "logchunk" plural = "logchunks" endpoints = [LogChunkEndpoint, RawLogChunkEndpoint, RawInlineLogChunkEndpoint] keyField = "logid" class EntityType(types.Entity): logid = types.Integer() firstline = types.Integer() content = types.String() entityType = EntityType(name, 'LogChunk')
8,861
Python
.py
190
38.231579
102
0.66141
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,291
base.py
buildbot_buildbot/master/buildbot/data/base.py
# This file is part of Buildbot. Buildbot is free software: you can # redistribute it and/or modify it under the terms of the GNU General Public # License as published by the Free Software Foundation, version 2. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more # details. # # You should have received a copy of the GNU General Public License along with # this program; if not, write to the Free Software Foundation, Inc., 51 # Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # Copyright Buildbot Team Members from __future__ import annotations import copy import enum import functools import re from collections import UserList from typing import TYPE_CHECKING from twisted.internet import defer from buildbot.data import exceptions from buildbot.util.twisted import async_to_deferred if TYPE_CHECKING: from typing import Any from typing import Literal from buildbot.data import types from buildbot.data.resultspec import ResultSpec from buildbot.db.builders import BuilderModel from buildbot.db.builds import BuildModel from buildbot.db.logs import LogModel from buildbot.db.steps import StepModel from buildbot.db.workers import WorkerModel class EndpointKind(enum.Enum): SINGLE = 1 COLLECTION = 2 RAW = 3 RAW_INLINE = 4 class ResourceType: name: str | None = None plural: str | None = None endpoints: list[type[Endpoint]] = [] keyField: str | None = None eventPathPatterns = "" entityType: types.Type | None = None subresources: list[str] = [] def __init__(self, master): self.master = master self.compileEventPathPatterns() def compileEventPathPatterns(self): # We'll run a single format, and then split the string # to get the final event path tuple pathPatterns = self.eventPathPatterns pathPatterns = pathPatterns.split() identifiers = re.compile(r':([^/]*)') for i, pp in enumerate(pathPatterns): pp = identifiers.sub(r'{\1}', pp) if pp.startswith("/"): pp = pp[1:] pathPatterns[i] = pp self.eventPaths = pathPatterns @functools.lru_cache(1) # noqa: B019 def getEndpoints(self): endpoints = self.endpoints[:] for i, ep in enumerate(endpoints): if not issubclass(ep, Endpoint): raise TypeError("Not an Endpoint subclass") endpoints[i] = ep(self, self.master) return endpoints @functools.lru_cache(1) # noqa: B019 def getDefaultEndpoint(self): for ep in self.getEndpoints(): if ep.kind != EndpointKind.COLLECTION: return ep return None @functools.lru_cache(1) # noqa: B019 def getCollectionEndpoint(self): for ep in self.getEndpoints(): if ep.kind == EndpointKind.COLLECTION or ep.isPseudoCollection: return ep return None @staticmethod def sanitizeMessage(msg): msg = copy.deepcopy(msg) return msg def produceEvent(self, msg, event): if msg is not None: msg = self.sanitizeMessage(msg) for path in self.eventPaths: path = path.format(**msg) routingKey = (*tuple(path.split("/")), event) self.master.mq.produce(routingKey, msg) class SubResource: def __init__(self, rtype): self.rtype = rtype self.endpoints = {} for endpoint in rtype.endpoints: if endpoint.kind == EndpointKind.COLLECTION: self.endpoints[rtype.plural] = endpoint else: self.endpoints[rtype.name] = endpoint class Endpoint: pathPatterns = "" rootLinkName: str | None = None isPseudoCollection = False kind = EndpointKind.SINGLE parentMapping: dict[str, str] = {} def __init__(self, rtype, master): self.rtype = rtype self.master = master def get(self, resultSpec: ResultSpec, kwargs: dict[str, Any]): raise NotImplementedError async def stream(self, resultSpec: ResultSpec, kwargs: dict[str, Any]): """ This is a prototype interface method for internal use. There could be breaking changes to it. Use at your own risks. """ raise NotImplementedError def control(self, action, args, kwargs): # we convert the action into a mixedCase method name action_method = getattr(self, "action" + action.capitalize(), None) if action_method is None: raise exceptions.InvalidControlException(f"action: {action} is not supported") return action_method(args, kwargs) def get_kwargs_from_graphql_parent(self, parent, parent_type): if parent_type not in self.parentMapping: rtype = self.master.data.getResourceTypeForGraphQlType(parent_type) if rtype.keyField in parent: parentid = rtype.keyField else: raise NotImplementedError( "Collection endpoint should implement " "get_kwargs_from_graphql or parentMapping" ) else: parentid = self.parentMapping[parent_type] ret = {'graphql': True} ret[parentid] = parent[parentid] return ret def get_kwargs_from_graphql(self, parent, resolve_info, args): if self.kind == EndpointKind.COLLECTION or self.isPseudoCollection: if parent is not None: return self.get_kwargs_from_graphql_parent(parent, resolve_info.parent_type.name) return {'graphql': True} ret = {'graphql': True} k = self.rtype.keyField v = args.pop(k) if v is not None: ret[k] = v return ret def __repr__(self): return "endpoint for " + ",".join(self.pathPatterns.split()) class NestedBuildDataRetriever: """ Efficiently retrieves data about various entities without repeating same queries over and over. The following arg keys are supported: - stepid - step_name - step_number - buildid - build_number - builderid - buildername - logid - log_slug """ __slots__ = ( 'master', 'args', 'step_dict', 'build_dict', 'builder_dict', 'log_dict', 'worker_dict', ) def __init__(self, master, args) -> None: self.master = master self.args = args # False is used as special value as "not set". None is used as "not exists". This solves # the problem of multiple database queries in case entity does not exist. self.step_dict: StepModel | None | Literal[False] = False self.build_dict: BuildModel | None | Literal[False] = False self.builder_dict: BuilderModel | None | Literal[False] = False self.log_dict: LogModel | None | Literal[False] = False self.worker_dict: WorkerModel | None | Literal[False] = False @async_to_deferred async def get_step_dict(self) -> StepModel | None: if self.step_dict is not False: return self.step_dict if 'stepid' in self.args: step_dict = self.step_dict = await self.master.db.steps.getStep( stepid=self.args['stepid'] ) return step_dict if 'step_name' in self.args or 'step_number' in self.args: build_dict = await self.get_build_dict() if build_dict is None: self.step_dict = None return None step_dict = self.step_dict = await self.master.db.steps.getStep( buildid=build_dict.id, number=self.args.get('step_number'), name=self.args.get('step_name'), ) return step_dict # fallback when there's only indirect information if 'logid' in self.args: log_dict = await self.get_log_dict() if log_dict is not None: step_dict = self.step_dict = await self.master.db.steps.getStep( stepid=log_dict.stepid ) return step_dict self.step_dict = None return self.step_dict @async_to_deferred async def get_build_dict(self) -> BuildModel | None: if self.build_dict is not False: return self.build_dict if 'buildid' in self.args: build_dict = self.build_dict = await self.master.db.builds.getBuild( self.args['buildid'] ) return build_dict if 'build_number' in self.args: builder_id = await self.get_builder_id() if builder_id is None: self.build_dict = None return None build_dict = self.build_dict = await self.master.db.builds.getBuildByNumber( builderid=builder_id, number=self.args['build_number'] ) return build_dict # fallback when there's only indirect information step_dict = await self.get_step_dict() if step_dict is not None: build_dict = self.build_dict = await self.master.db.builds.getBuild(step_dict.buildid) return build_dict self.build_dict = None return None @async_to_deferred async def get_build_id(self): if 'buildid' in self.args: return self.args['buildid'] build_dict = await self.get_build_dict() if build_dict is None: return None return build_dict.id @async_to_deferred async def get_builder_dict(self) -> BuilderModel | None: if self.builder_dict is not False: return self.builder_dict if 'builderid' in self.args: builder_dict = self.builder_dict = await self.master.db.builders.getBuilder( self.args['builderid'] ) return builder_dict if 'buildername' in self.args: builder_id = await self.master.db.builders.findBuilderId( self.args['buildername'], autoCreate=False ) builder_dict = None if builder_id is not None: builder_dict = await self.master.db.builders.getBuilder(builder_id) self.builder_dict = builder_dict return builder_dict # fallback when there's only indirect information build_dict = await self.get_build_dict() if build_dict is not None: builder_dict = self.builder_dict = await self.master.db.builders.getBuilder( build_dict.builderid ) return builder_dict self.builder_dict = None return None @async_to_deferred async def get_builder_id(self) -> int | None: if 'builderid' in self.args: return self.args['builderid'] builder_dict = await self.get_builder_dict() if builder_dict is None: return None return builder_dict.id @async_to_deferred async def get_log_dict(self) -> LogModel | None: if self.log_dict is not False: return self.log_dict if 'logid' in self.args: log_dict = self.log_dict = await self.master.db.logs.getLog(self.args['logid']) return log_dict step_dict = await self.get_step_dict() if step_dict is None: self.log_dict = None return None log_dict = self.log_dict = await self.master.db.logs.getLogBySlug( step_dict.id, self.args.get('log_slug') ) return log_dict @async_to_deferred async def get_log_id(self): if 'logid' in self.args: return self.args['logid'] log_dict = await self.get_log_dict() if log_dict is None: return None return log_dict.id @async_to_deferred async def get_worker_dict(self) -> WorkerModel | None: if self.worker_dict is not False: return self.worker_dict build_dict = await self.get_build_dict() if build_dict is not None: workerid = build_dict.workerid if workerid is not None: worker_dict = self.worker_dict = await self.master.db.workers.getWorker( workerid=workerid ) return worker_dict self.worker_dict = None return None class BuildNestingMixin: """ A mixin for methods to decipher the many ways a various entities can be specified. """ @defer.inlineCallbacks def getBuildid(self, kwargs): retriever = NestedBuildDataRetriever(self.master, kwargs) return (yield retriever.get_build_id()) @defer.inlineCallbacks def getBuilderId(self, kwargs): retriever = NestedBuildDataRetriever(self.master, kwargs) return (yield retriever.get_builder_id()) # returns Deferred that yields a number def get_project_id(self, kwargs): if "projectname" in kwargs: return self.master.db.projects.find_project_id(kwargs["projectname"], auto_create=False) return defer.succeed(kwargs["projectid"]) class ListResult(UserList): __slots__ = ['offset', 'total', 'limit'] def __init__(self, values, offset=None, total=None, limit=None): super().__init__(values) # if set, this is the index in the overall results of the first element of # this list self.offset = offset # if set, this is the total number of results self.total = total # if set, this is the limit, either from the user or the implementation self.limit = limit def __repr__(self): return ( f"ListResult({self.data!r}, offset={self.offset!r}, " f"total={self.total!r}, limit={self.limit!r})" ) def __eq__(self, other): if isinstance(other, ListResult): return ( self.data == other.data and self.offset == other.offset and self.total == other.total and self.limit == other.limit ) return ( self.data == other and self.offset is None and self.limit is None and (self.total is None or self.total == len(other)) ) def __ne__(self, other): return not self == other def updateMethod(func): """Decorate this resourceType instance as an update method, made available at master.data.updates.$funcname""" func.isUpdateMethod = True return func
14,878
Python
.py
376
30.223404
100
0.616403
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,292
graphql.py
buildbot_buildbot/master/buildbot/data/graphql.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 asyncio import functools import textwrap from types import ModuleType from buildbot.asyncio import AsyncIOLoopWithTwisted from buildbot.asyncio import as_deferred from buildbot.asyncio import as_future from buildbot.data import connector from buildbot.data import resultspec from buildbot.data.base import EndpointKind from buildbot.data.types import Entity from buildbot.util import service graphql: ModuleType | None = None try: import graphql from graphql.execution.execute import default_field_resolver except ImportError: # pragma: no cover graphql = None def _enforce_list(v): if isinstance(v, list): return v return [v] class GraphQLConnector(service.AsyncService): """Mixin class to separate the GraphQL traits for the data connector This class needs to use some async methods in the asyncio domain (instead of twisted) await in those domains are not compatible, and must be prefixed with as_deferred / as_future any method doing so must be prefixed with "_aio_" to indicate that their return value should be transformed with as_deferred, and they should themselves transform normal data api results with as_future() """ data: connector.DataConnector | None = None asyncio_loop: AsyncIOLoopWithTwisted | None = None # asyncio will create an event loop if none exists yet in get_event_loop(). We need to set it # back via set_event_loop() if we want it to be properly closed. _saved_event_loop: asyncio.AbstractEventLoop | None = None def reconfigServiceWithBuildbotConfig(self, new_config): if self.data is None: self.data = self.master.data config = new_config.www.get('graphql') self.enabled = False if config is None: return if graphql is None: raise ImportError("graphql is enabled but 'graphql-core' is not installed") self.enabled = True self.config = config loop = None try: if self._saved_event_loop is None: # Ideally we would like to use asyncio.get_event_loop() here. However, its API # makes it hard to use: the behavior depends on the current asyncio policy and # the default policy will create a new loop for the main thread if a loop was not # set before. Unfortunately we can't know whether a new loop was created, # and as a result we can't cleanup it in stopService(). Specifically, we can't # call the close() function, which results in occasional ResourceWarnings because # there is no one who would close the created loop. # # Using asyncio.get_running_loop() would potentially break if non-default asyncio # policy was used. The default policy is fine because separate threads have # separate event loops. Fortunately Buildbot does not change the default asyncio # policy, so this concern does not matter in practice. # # Note that asyncio.get_event_loop() is deprecated in favor of get_running_loop() loop = asyncio.get_running_loop() except RuntimeError: # get_running_loop throws if there's no current loop. # get_event_loop throws is there's no current loop and we're not on main thread. pass if self._saved_event_loop is None and not isinstance(loop, AsyncIOLoopWithTwisted): self._saved_event_loop = loop self.asyncio_loop = AsyncIOLoopWithTwisted(self.master.reactor) asyncio.set_event_loop(self.asyncio_loop) self.asyncio_loop.start() self.debug = self.config.get("debug") self.schema = graphql.build_schema(self.get_schema()) def stopService(self): if self.asyncio_loop: self.asyncio_loop.stop() self.asyncio_loop.close() # We want to restore the original event loop value even if was None because otherwise # we would be leaving our closed AsyncIOLoopWithTwisted instance as the event loop asyncio.set_event_loop(self._saved_event_loop) self.asyncio_loop = None return super().stopService() @functools.lru_cache(1) # noqa: B019 def get_schema(self): """Return the graphQL Schema of the buildbot data model""" types = {} schema = textwrap.dedent(""" # custom scalar types for buildbot data model scalar Date # stored as utc unix timestamp scalar Binary # arbitrary data stored as base85 scalar JSON # arbitrary json stored as string, mainly used for properties values """) # type dependencies must be added recursively def add_dependent_types(ent): typename = ent.toGraphQLTypeName() if typename in types: return if isinstance(ent, Entity): types[typename] = ent for dtyp in ent.graphQLDependentTypes(): add_dependent_types(dtyp) rtype = self.data.getResourceType(ent.name) if rtype is not None: for subresource in rtype.subresources: rtype = self.data.getResourceTypeForGraphQlType(subresource) add_dependent_types(rtype.entityType) # root query contain the list of item available directly # mapped against the rootLinks queries_schema = "" def format_query_fields(query_fields): query_fields = ",\n ".join(query_fields) if query_fields: query_fields = f"({query_fields})" return query_fields def format_subresource(rtype): queries_schema = "" typ = rtype.entityType typename = typ.toGraphQLTypeName() add_dependent_types(typ) query_fields = [] # build the queriable parameters, via query_fields for field, field_type in sorted(rtype.entityType.fields.items()): # in graphql, we handle properties as queriable sub resources # instead of hardcoded attributes like in rest api if field == 'properties': continue field_type_graphql = field_type.getGraphQLInputType() if field_type_graphql is None: continue query_fields.append(f"{field}: {field_type_graphql}") for op in sorted(operators): if op in ["in", "notin"]: if field_type_graphql in ["String", "Int"]: query_fields.append(f"{field}__{op}: [{field_type_graphql}]") else: query_fields.append(f"{field}__{op}: {field_type_graphql}") query_fields.extend(["order: String", "limit: Int", "offset: Int"]) ep = self.data.getEndPointForResourceName(rtype.plural) if ep is None or not ep.isPseudoCollection: plural_typespec = f"[{typename}]" else: plural_typespec = typename queries_schema += ( f" {rtype.plural}{format_query_fields(query_fields)}: {plural_typespec}!\n" ) # build the queriable parameter, via keyField keyfields = [] field = rtype.keyField if field not in rtype.entityType.fields: raise RuntimeError(f"bad keyField {field} not in entityType {rtype.entityType}") field_type = rtype.entityType.fields[field] field_type_graphql = field_type.toGraphQLTypeName() keyfields.append(f"{field}: {field_type_graphql}") queries_schema += f" {rtype.name}{format_query_fields(keyfields)}: {typename}\n" return queries_schema operators = set(resultspec.Filter.singular_operators) operators.update(resultspec.Filter.plural_operators) for rootlink in sorted(v["name"] for v in self.data.rootLinks): ep = self.data.matcher[(rootlink,)][0] queries_schema += format_subresource(ep.rtype) schema += "type Query {\n" + queries_schema + "}\n" schema += "type Subscription {\n" + queries_schema + "}\n" for name, typ in types.items(): type_spec = typ.toGraphQL() schema += f"type {name} {{\n" for field in type_spec.get("fields", []): field_type = field["type"] if not isinstance(field_type, str): field_type = field_type["type"] schema += f" {field['name']}: {field_type}\n" rtype = self.data.getResourceType(typ.name) if rtype is not None: for subresource in rtype.subresources: rtype = self.data.getResourceTypeForGraphQlType(subresource) schema += format_subresource(rtype) schema += "}\n" return schema async def _aio_ep_get(self, ep, kwargs, resultSpec): rv = await as_future(ep.get(resultSpec, kwargs)) if resultSpec: rv = resultSpec.apply(rv) return rv async def _aio_query(self, query): query = graphql.parse(query) errors = graphql.validate(self.schema, query) if errors: r = graphql.execution.ExecutionResult() r.errors = errors return r async def field_resolver(parent, resolve_info, **args): field = resolve_info.field_name if parent is not None and field in parent: res = default_field_resolver(parent, resolve_info, **args) if isinstance(res, list) and args: ep = self.data.getEndPointForResourceName(field) args = {k: _enforce_list(v) for k, v in args.items()} rspec = self.data.resultspec_from_jsonapi(args, ep.rtype.entityType, True) res = rspec.apply(res) return res ep = self.data.getEndPointForResourceName(field) rspec = None kwargs = ep.get_kwargs_from_graphql(parent, resolve_info, args) if ep.kind == EndpointKind.COLLECTION or ep.isPseudoCollection: args = {k: _enforce_list(v) for k, v in args.items()} rspec = self.data.resultspec_from_jsonapi(args, ep.rtype.entityType, True) return await self._aio_ep_get(ep, kwargs, rspec) # Execute res = await graphql.execute( self.schema, query, field_resolver=field_resolver, ) return res def query(self, query): return as_deferred(self._aio_query(query))
11,611
Python
.py
232
38.913793
97
0.626102
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,293
exceptions.py
buildbot_buildbot/master/buildbot/data/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 # copy some exceptions from the DB layer from buildbot.db.schedulers import SchedulerAlreadyClaimedError __all__ = [ 'SchedulerAlreadyClaimedError', 'InvalidPathError', 'InvalidControlException', ] class DataException(Exception): pass class InvalidPathError(DataException): "A path argument was invalid or unknown" class InvalidControlException(DataException): "Action is not supported" class InvalidQueryParameter(DataException): "Query Parameter was invalid"
1,205
Python
.py
29
39.206897
79
0.79485
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,294
test_result_sets.py
buildbot_buildbot/master/buildbot/data/test_result_sets.py
# This file is part of Buildbot. Buildbot is free software: you can # redistribute it and/or modify it under the terms of the GNU General Public # License as published by the Free Software Foundation, version 2. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more # details. # # You should have received a copy of the GNU General Public License along with # this program; if not, write to the Free Software Foundation, Inc., 51 # Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # Copyright Buildbot Team Members from __future__ import annotations from typing import TYPE_CHECKING from twisted.internet import defer from buildbot.data import base from buildbot.data import types if TYPE_CHECKING: from buildbot.db.test_result_sets import TestResultSetModel class Db2DataMixin: def db2data(self, model: TestResultSetModel): return { 'test_result_setid': model.id, 'builderid': model.builderid, 'buildid': model.buildid, 'stepid': model.stepid, 'description': model.description, 'category': model.category, 'value_unit': model.value_unit, 'tests_passed': model.tests_passed, 'tests_failed': model.tests_failed, 'complete': model.complete, } class TestResultSetsEndpoint(Db2DataMixin, base.BuildNestingMixin, base.Endpoint): kind = base.EndpointKind.COLLECTION pathPatterns = """ /builders/n:builderid/test_result_sets /builders/s:buildername/test_result_sets /builds/n:buildid/test_result_sets /steps/n:stepid/test_result_sets """ @defer.inlineCallbacks def get(self, resultSpec, kwargs): complete = resultSpec.popBooleanFilter('complete') if 'stepid' in kwargs: step_dbdict = yield self.master.db.steps.getStep(kwargs['stepid']) build_dbdict = yield self.master.db.builds.getBuild(step_dbdict.buildid) sets = yield self.master.db.test_result_sets.getTestResultSets( build_dbdict.builderid, buildid=step_dbdict.buildid, stepid=kwargs['stepid'], complete=complete, result_spec=resultSpec, ) elif 'buildid' in kwargs: build_dbdict = yield self.master.db.builds.getBuild(kwargs['buildid']) sets = yield self.master.db.test_result_sets.getTestResultSets( build_dbdict.builderid, buildid=kwargs['buildid'], complete=complete, result_spec=resultSpec, ) else: # The following is true: 'buildername' in kwargs or 'builderid' in kwargs: builderid = yield self.getBuilderId(kwargs) sets = yield self.master.db.test_result_sets.getTestResultSets( builderid, complete=complete, result_spec=resultSpec ) return [self.db2data(model) for model in sets] class TestResultSetEndpoint(Db2DataMixin, base.BuildNestingMixin, base.Endpoint): kind = base.EndpointKind.SINGLE pathPatterns = """ /test_result_sets/n:test_result_setid """ @defer.inlineCallbacks def get(self, resultSpec, kwargs): model = yield self.master.db.test_result_sets.getTestResultSet(kwargs['test_result_setid']) return self.db2data(model) if model else None class TestResultSet(base.ResourceType): name = "test_result_set" plural = "test_result_sets" endpoints = [TestResultSetsEndpoint, TestResultSetEndpoint] keyField = 'test_result_setid' eventPathPatterns = """ /test_result_sets/:test_result_setid """ class EntityType(types.Entity): test_result_setid = types.Integer() builderid = types.Integer() buildid = types.Integer() stepid = types.Integer() description = types.NoneOk(types.String()) category = types.String() value_unit = types.String() tests_passed = types.NoneOk(types.Integer()) tests_failed = types.NoneOk(types.Integer()) complete = types.Boolean() entityType = EntityType(name, 'TestResultSet') @defer.inlineCallbacks def generateEvent(self, test_result_setid, event): test_result_set = yield self.master.data.get(('test_result_sets', test_result_setid)) self.produceEvent(test_result_set, event) @base.updateMethod @defer.inlineCallbacks def addTestResultSet(self, builderid, buildid, stepid, description, category, value_unit): test_result_setid = yield self.master.db.test_result_sets.addTestResultSet( builderid, buildid, stepid, description, category, value_unit ) yield self.generateEvent(test_result_setid, 'new') return test_result_setid @base.updateMethod @defer.inlineCallbacks def completeTestResultSet(self, test_result_setid, tests_passed=None, tests_failed=None): yield self.master.db.test_result_sets.completeTestResultSet( test_result_setid, tests_passed, tests_failed ) yield self.generateEvent(test_result_setid, 'completed')
5,353
Python
.py
119
36.857143
99
0.68023
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,295
build_data.py
buildbot_buildbot/master/buildbot/data/build_data.py
# This file is part of Buildbot. Buildbot is free software: you can # redistribute it and/or modify it under the terms of the GNU General Public # License as published by the Free Software Foundation, version 2. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more # details. # # You should have received a copy of the GNU General Public License along with # this program; if not, write to the Free Software Foundation, Inc., 51 # Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # Copyright Buildbot Team Members from __future__ import annotations from typing import TYPE_CHECKING from twisted.internet import defer from buildbot.data import base from buildbot.data import types if TYPE_CHECKING: from buildbot.db.build_data import BuildDataModel def _db2data(model: BuildDataModel): return { 'buildid': model.buildid, 'name': model.name, 'value': model.value, 'length': model.length, 'source': model.source, } class BuildDatasNoValueEndpoint(base.BuildNestingMixin, base.Endpoint): kind = base.EndpointKind.COLLECTION pathPatterns = """ /builders/n:builderid/builds/n:build_number/data /builders/s:buildername/builds/n:build_number/data /builds/n:buildid/data """ @defer.inlineCallbacks def get(self, resultSpec, kwargs): buildid = yield self.getBuildid(kwargs) build_datadicts = yield self.master.db.build_data.getAllBuildDataNoValues(buildid) results = [] for dbdict in build_datadicts: results.append(_db2data(dbdict)) return results class BuildDataNoValueEndpoint(base.BuildNestingMixin, base.Endpoint): kind = base.EndpointKind.SINGLE pathPatterns = """ /builders/n:builderid/builds/n:build_number/data/i:name /builders/s:buildername/builds/n:build_number/data/i:name /builds/n:buildid/data/i:name """ @defer.inlineCallbacks def get(self, resultSpec, kwargs): buildid = yield self.getBuildid(kwargs) name = kwargs['name'] build_datadict = yield self.master.db.build_data.getBuildDataNoValue(buildid, name) return _db2data(build_datadict) if build_datadict else None class BuildDataEndpoint(base.BuildNestingMixin, base.Endpoint): kind = base.EndpointKind.RAW pathPatterns = """ /builders/n:builderid/builds/n:build_number/data/i:name/value /builders/s:buildername/builds/n:build_number/data/i:name/value /builds/n:buildid/data/i:name/value """ @defer.inlineCallbacks def get(self, resultSpec, kwargs): buildid = yield self.getBuildid(kwargs) name = kwargs['name'] dbdict = yield self.master.db.build_data.getBuildData(buildid, name) if not dbdict: return None return { 'raw': dbdict.value, 'mime-type': 'application/octet-stream', 'filename': dbdict.name, } class BuildData(base.ResourceType): name = "build_data" plural = "build_data" endpoints = [BuildDatasNoValueEndpoint, BuildDataNoValueEndpoint, BuildDataEndpoint] keyField = "name" class EntityType(types.Entity): buildid = types.Integer() name = types.String() length = types.Integer() value = types.NoneOk(types.Binary()) source = types.String() entityType = EntityType(name, 'BuildData') @base.updateMethod def setBuildData(self, buildid, name, value, source): # forward deferred directly return self.master.db.build_data.setBuildData(buildid, name, value, source)
3,806
Python
.py
92
35.119565
91
0.705723
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,296
builds.py
buildbot_buildbot/master/buildbot/data/builds.py
# This file is part of Buildbot. Buildbot is free software: you can # redistribute it and/or modify it under the terms of the GNU General Public # License as published by the Free Software Foundation, version 2. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more # details. # # You should have received a copy of the GNU General Public License along with # this program; if not, write to the Free Software Foundation, Inc., 51 # Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # Copyright Buildbot Team Members from __future__ import annotations from typing import TYPE_CHECKING from twisted.internet import defer from buildbot.data import base from buildbot.data import types from buildbot.data.resultspec import ResultSpec if TYPE_CHECKING: from buildbot.db.builds import BuildModel def _db2data(model: BuildModel): return { 'buildid': model.id, 'number': model.number, 'builderid': model.builderid, 'buildrequestid': model.buildrequestid, 'workerid': model.workerid, 'masterid': model.masterid, 'started_at': model.started_at, 'complete_at': model.complete_at, "locks_duration_s": model.locks_duration_s, 'complete': model.complete_at is not None, 'state_string': model.state_string, 'results': model.results, 'properties': {}, } class Db2DataMixin: def _generate_filtered_properties(self, props, filters): """ This method returns Build's properties according to property filters. .. seealso:: `Official Documentation <http://docs.buildbot.net/latest/developer/rtype-build.html>`_ :param props: The Build's properties as a dict (from db) :param filters: Desired properties keys as a list (from API URI) """ # by default none properties are returned if props and filters: return ( props if '*' in filters else dict(((k, v) for k, v in props.items() if k in filters)) ) return None fieldMapping = { 'buildid': 'builds.id', 'number': 'builds.number', 'builderid': 'builds.builderid', 'buildrequestid': 'builds.buildrequestid', 'workerid': 'builds.workerid', 'masterid': 'builds.masterid', 'started_at': 'builds.started_at', 'complete_at': 'builds.complete_at', "locks_duration_s": "builds.locks_duration_s", 'state_string': 'builds.state_string', 'results': 'builds.results', } class BuildEndpoint(Db2DataMixin, base.BuildNestingMixin, base.Endpoint): kind = base.EndpointKind.SINGLE pathPatterns = """ /builds/n:buildid /builders/n:builderid/builds/n:build_number /builders/s:buildername/builds/n:build_number """ @defer.inlineCallbacks def get(self, resultSpec, kwargs): if 'buildid' in kwargs: dbdict = yield self.master.db.builds.getBuild(kwargs['buildid']) else: bldr = yield self.getBuilderId(kwargs) if bldr is None: return None num = kwargs['build_number'] dbdict = yield self.master.db.builds.getBuildByNumber(bldr, num) data = _db2data(dbdict) if dbdict else None # In some cases, data could be None if data: filters = resultSpec.popProperties() if hasattr(resultSpec, 'popProperties') else [] # Avoid to request DB for Build's properties if not specified if filters: try: props = yield self.master.db.builds.getBuildProperties(data['buildid']) except (KeyError, TypeError): props = {} filtered_properties = self._generate_filtered_properties(props, filters) if filtered_properties: data['properties'] = filtered_properties return data @defer.inlineCallbacks def actionStop(self, args, kwargs): buildid = kwargs.get('buildid') if buildid is None: bldr = kwargs['builderid'] num = kwargs['build_number'] dbdict = yield self.master.db.builds.getBuildByNumber(bldr, num) buildid = dbdict.id self.master.mq.produce( ("control", "builds", str(buildid), 'stop'), {"reason": kwargs.get('reason', args.get('reason', 'no reason'))}, ) @defer.inlineCallbacks def actionRebuild(self, args, kwargs): # we use the self.get and not self.data.get to be able to support all # the pathPatterns of this endpoint build = yield self.get(ResultSpec(), kwargs) buildrequest = yield self.master.data.get(('buildrequests', build['buildrequestid'])) res = yield self.master.data.updates.rebuildBuildrequest(buildrequest) return res class BuildsEndpoint(Db2DataMixin, base.BuildNestingMixin, base.Endpoint): kind = base.EndpointKind.COLLECTION pathPatterns = """ /builds /builders/n:builderid/builds /builders/s:buildername/builds /buildrequests/n:buildrequestid/builds /changes/n:changeid/builds /workers/n:workerid/builds """ rootLinkName = 'builds' @defer.inlineCallbacks def get(self, resultSpec, kwargs): changeid = kwargs.get('changeid') if changeid is not None: builds = yield self.master.db.builds.getBuildsForChange(changeid) else: # following returns None if no filter # true or false, if there is a complete filter builderid = None if 'builderid' in kwargs or 'buildername' in kwargs: builderid = yield self.getBuilderId(kwargs) if builderid is None: return [] complete = resultSpec.popBooleanFilter("complete") buildrequestid = resultSpec.popIntegerFilter("buildrequestid") resultSpec.fieldMapping = self.fieldMapping builds = yield self.master.db.builds.getBuilds( builderid=builderid, buildrequestid=kwargs.get('buildrequestid', buildrequestid), workerid=kwargs.get('workerid'), complete=complete, resultSpec=resultSpec, ) # returns properties' list filters = resultSpec.popProperties() buildscol = [] for b in builds: data = _db2data(b) if kwargs.get('graphql'): # let the graphql engine manage the properties del data['properties'] else: # Avoid to request DB for Build's properties if not specified if filters: props = yield self.master.db.builds.getBuildProperties(data["buildid"]) filtered_properties = self._generate_filtered_properties(props, filters) if filtered_properties: data["properties"] = filtered_properties buildscol.append(data) return buildscol class Build(base.ResourceType): name = "build" plural = "builds" endpoints = [BuildEndpoint, BuildsEndpoint] keyField = "buildid" eventPathPatterns = """ /builders/:builderid/builds/:number /builds/:buildid /workers/:workerid/builds/:buildid """ subresources = ["Step", "Property"] class EntityType(types.Entity): buildid = types.Integer() number = types.Integer() builderid = types.Integer() buildrequestid = types.Integer() workerid = types.Integer() masterid = types.Integer() started_at = types.DateTime() complete = types.Boolean() complete_at = types.NoneOk(types.DateTime()) locks_duration_s = types.Integer() results = types.NoneOk(types.Integer()) state_string = types.String() properties = types.NoneOk(types.SourcedProperties()) entityType = EntityType(name, 'Build') @defer.inlineCallbacks def generateEvent(self, _id, event): # get the build and munge the result for the notification build = yield self.master.data.get(('builds', str(_id))) self.produceEvent(build, event) @base.updateMethod @defer.inlineCallbacks def addBuild(self, builderid, buildrequestid, workerid): res = yield self.master.db.builds.addBuild( builderid=builderid, buildrequestid=buildrequestid, workerid=workerid, masterid=self.master.masterid, state_string='created', ) return res @base.updateMethod def generateNewBuildEvent(self, buildid): return self.generateEvent(buildid, "new") @base.updateMethod @defer.inlineCallbacks def setBuildStateString(self, buildid, state_string): res = yield self.master.db.builds.setBuildStateString( buildid=buildid, state_string=state_string ) yield self.generateEvent(buildid, "update") return res @base.updateMethod @defer.inlineCallbacks def add_build_locks_duration(self, buildid, duration_s): yield self.master.db.builds.add_build_locks_duration(buildid=buildid, duration_s=duration_s) yield self.generateEvent(buildid, "update") @base.updateMethod @defer.inlineCallbacks def finishBuild(self, buildid, results): res = yield self.master.db.builds.finishBuild(buildid=buildid, results=results) yield self.generateEvent(buildid, "finished") return res
9,850
Python
.py
234
32.905983
100
0.641127
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,297
sourcestamps.py
buildbot_buildbot/master/buildbot/data/sourcestamps.py
# This file is part of Buildbot. Buildbot is free software: you can # redistribute it and/or modify it under the terms of the GNU General Public # License as published by the Free Software Foundation, version 2. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more # details. # # You should have received a copy of the GNU General Public License along with # this program; if not, write to the Free Software Foundation, Inc., 51 # Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # Copyright Buildbot Team Members from __future__ import annotations from typing import TYPE_CHECKING from twisted.internet import defer from buildbot.data import base from buildbot.data import patches from buildbot.data import types if TYPE_CHECKING: from typing import Any from buildbot.db.sourcestamps import SourceStampModel def _db2data(ss: SourceStampModel): data: dict[str, Any] = { 'ssid': ss.ssid, 'branch': ss.branch, 'revision': ss.revision, 'project': ss.project, 'repository': ss.repository, 'codebase': ss.codebase, 'created_at': ss.created_at, 'patch': None, } if ss.patch is not None: data['patch'] = { 'patchid': ss.patch.patchid, 'level': ss.patch.level, 'subdir': ss.patch.subdir, 'author': ss.patch.author, 'comment': ss.patch.comment, 'body': ss.patch.body, } return data class SourceStampEndpoint(base.Endpoint): kind = base.EndpointKind.SINGLE pathPatterns = """ /sourcestamps/n:ssid """ @defer.inlineCallbacks def get(self, resultSpec, kwargs): ssdict = yield self.master.db.sourcestamps.getSourceStamp(kwargs['ssid']) return _db2data(ssdict) if ssdict else None class SourceStampsEndpoint(base.Endpoint): kind = base.EndpointKind.COLLECTION pathPatterns = """ /sourcestamps /buildsets/:buildsetid/sourcestamps """ rootLinkName = 'sourcestamps' @defer.inlineCallbacks def get(self, resultSpec, kwargs): buildsetid = kwargs.get("buildsetid") if buildsetid is not None: sourcestamps = yield self.master.db.sourcestamps.get_sourcestamps_for_buildset( buildsetid ) else: sourcestamps = yield self.master.db.sourcestamps.getSourceStamps() return [_db2data(ssdict) for ssdict in sourcestamps] class SourceStamp(base.ResourceType): name = "sourcestamp" plural = "sourcestamps" endpoints = [SourceStampEndpoint, SourceStampsEndpoint] keyField = 'ssid' subresources = ["Change"] class EntityType(types.Entity): ssid = types.Integer() revision = types.NoneOk(types.String()) branch = types.NoneOk(types.String()) repository = types.String() project = types.String() codebase = types.String() patch = types.NoneOk(patches.Patch.entityType) created_at = types.DateTime() entityType = EntityType(name, 'Sourcestamp')
3,254
Python
.py
86
31.546512
91
0.685614
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,298
changes.py
buildbot_buildbot/master/buildbot/data/changes.py
# This file is part of Buildbot. Buildbot is free software: you can # redistribute it and/or modify it under the terms of the GNU General Public # License as published by the Free Software Foundation, version 2. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more # details. # # You should have received a copy of the GNU General Public License along with # this program; if not, write to the Free Software Foundation, Inc., 51 # Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # Copyright Buildbot Team Members from __future__ import annotations import copy import json from typing import TYPE_CHECKING from twisted.internet import defer from twisted.python import log from buildbot.data import base from buildbot.data import sourcestamps from buildbot.data import types from buildbot.process import metrics from buildbot.process.users import users from buildbot.util import datetime2epoch from buildbot.util import epoch2datetime if TYPE_CHECKING: from buildbot.db.changes import ChangeModel class FixerMixin: @defer.inlineCallbacks def _fixChange(self, model: ChangeModel, is_graphql: bool): # TODO: make these mods in the DB API data = { 'changeid': model.changeid, 'author': model.author, 'committer': model.committer, 'comments': model.comments, 'branch': model.branch, 'revision': model.revision, 'revlink': model.revlink, 'when_timestamp': datetime2epoch(model.when_timestamp), 'category': model.category, 'parent_changeids': model.parent_changeids, 'repository': model.repository, 'codebase': model.codebase, 'project': model.project, 'files': model.files, } if is_graphql: data['sourcestampid'] = model.sourcestampid else: sskey = ('sourcestamps', str(model.sourcestampid)) assert hasattr(self, "master"), "FixerMixin requires a master attribute" data['sourcestamp'] = yield self.master.data.get(sskey) if is_graphql: data['properties'] = [ {'name': k, 'source': v[1], 'value': json.dumps(v[0])} for k, v in model.properties.items() ] else: data['properties'] = model.properties return data fieldMapping = { 'author': 'changes.author', 'branch': 'changes.branch', 'category': 'changes.category', 'changeid': 'changes.changeid', 'codebase': 'changes.codebase', 'comments': 'changes.comments', 'committer': 'changes.committer', 'project': 'changes.project', 'repository': 'changes.repository', 'revision': 'changes.revision', 'revlink': 'changes.revlink', 'sourcestampid': 'changes.sourcestampid', 'when_timestamp': 'changes.when_timestamp', } class ChangeEndpoint(FixerMixin, base.Endpoint): kind = base.EndpointKind.SINGLE pathPatterns = """ /changes/n:changeid """ @defer.inlineCallbacks def get(self, resultSpec, kwargs): change = yield self.master.db.changes.getChange(kwargs['changeid']) if change is None: return None return (yield self._fixChange(change, is_graphql='graphql' in kwargs)) class ChangesEndpoint(FixerMixin, base.BuildNestingMixin, base.Endpoint): kind = base.EndpointKind.COLLECTION pathPatterns = """ /changes /builders/n:builderid/builds/n:build_number/changes /builds/n:buildid/changes /sourcestamps/n:ssid/changes """ rootLinkName = 'changes' @defer.inlineCallbacks def get(self, resultSpec, kwargs): buildid = kwargs.get('buildid') if 'build_number' in kwargs: buildid = yield self.getBuildid(kwargs) ssid = kwargs.get('ssid') changes = [] if buildid is not None: changes = yield self.master.db.changes.getChangesForBuild(buildid) elif ssid is not None: change = yield self.master.db.changes.getChangeFromSSid(ssid) if change is not None: changes = [change] else: changes = [] else: if resultSpec is not None: resultSpec.fieldMapping = self.fieldMapping changes = yield self.master.db.changes.getChanges(resultSpec=resultSpec) results = [] for ch in changes: results.append((yield self._fixChange(ch, is_graphql='graphql' in kwargs))) return results class Change(base.ResourceType): name = "change" plural = "changes" endpoints = [ChangeEndpoint, ChangesEndpoint] eventPathPatterns = """ /changes/:changeid """ keyField = "changeid" subresources = ["Build", "Property"] class EntityType(types.Entity): changeid = types.Integer() parent_changeids = types.List(of=types.Integer()) author = types.String() committer = types.String() files = types.List(of=types.String()) comments = types.String() revision = types.NoneOk(types.String()) when_timestamp = types.Integer() branch = types.NoneOk(types.String()) category = types.NoneOk(types.String()) revlink = types.NoneOk(types.String()) properties = types.SourcedProperties() repository = types.String() project = types.String() codebase = types.String() sourcestamp = sourcestamps.SourceStamp.entityType entityType = EntityType(name, 'Change') @base.updateMethod @defer.inlineCallbacks def addChange( self, files=None, comments=None, author=None, committer=None, revision=None, when_timestamp=None, branch=None, category=None, revlink='', properties=None, repository='', codebase=None, project='', src=None, _test_changeid=None, ): metrics.MetricCountEvent.log("added_changes", 1) if properties is None: properties = {} # add the source to the properties for k in properties: properties[k] = (properties[k], 'Change') # get a user id if src: # create user object, returning a corresponding uid uid = yield users.createUserObject(self.master, author, src) else: uid = None if not revlink and revision and repository and callable(self.master.config.revlink): # generate revlink from revision and repository using the configured callable revlink = self.master.config.revlink(revision, repository) or '' if callable(category): pre_change = self.master.config.preChangeGenerator( author=author, committer=committer, files=files, comments=comments, revision=revision, when_timestamp=when_timestamp, branch=branch, revlink=revlink, properties=properties, repository=repository, project=project, ) category = category(pre_change) # set the codebase, either the default, supplied, or generated if codebase is None and self.master.config.codebaseGenerator is not None: pre_change = self.master.config.preChangeGenerator( author=author, committer=committer, files=files, comments=comments, revision=revision, when_timestamp=when_timestamp, branch=branch, category=category, revlink=revlink, properties=properties, repository=repository, project=project, ) codebase = self.master.config.codebaseGenerator(pre_change) codebase = str(codebase) else: codebase = codebase or '' # add the Change to the database changeid = yield self.master.db.changes.addChange( author=author, committer=committer, files=files, comments=comments, revision=revision, when_timestamp=epoch2datetime(when_timestamp), branch=branch, category=category, revlink=revlink, properties=properties, repository=repository, codebase=codebase, project=project, uid=uid, _test_changeid=_test_changeid, ) # get the change and munge the result for the notification change = yield self.master.data.get(('changes', str(changeid))) change = copy.deepcopy(change) self.produceEvent(change, 'new') # log, being careful to handle funny characters msg = f"added change with revision {revision} to database" log.msg(msg.encode('utf-8', 'replace')) return changeid
9,360
Python
.py
244
28.844262
92
0.620405
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,299
types.py
buildbot_buildbot/master/buildbot/data/types.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 # See "Type Validation" in master/docs/developer/tests.rst from __future__ import annotations import datetime import json import re from buildbot import util from buildbot.util import bytes2unicode def capitalize(word): return ''.join(x.capitalize() or '_' for x in word.split('_')) class Type: name: Identifier | String | str | None = None doc: str | None = None graphQLType = "unknown" @property def ramlname(self): return self.name def valueFromString(self, arg): # convert a urldecoded bytestring as given in a URL to a value, or # raise an exception trying. This parent method raises an exception, # so if the method is missing in a subclass, it cannot be created from # a string. raise TypeError def cmp(self, val, arg): argVal = self.valueFromString(arg) if val < argVal: return -1 elif val == argVal: return 0 return 1 def validate(self, name, object): raise NotImplementedError def getSpec(self): r = {"name": self.name} if self.doc is not None: r["doc"] = self.doc return r def toGraphQL(self): return self.graphQLType def toGraphQLTypeName(self): return self.graphQLType def graphQLDependentTypes(self): return [] def getGraphQLInputType(self): return self.toGraphQLTypeName() class NoneOk(Type): def __init__(self, nestedType): assert isinstance(nestedType, Type) self.nestedType = nestedType self.name = self.nestedType.name + " or None" @property def ramlname(self): return self.nestedType.ramlname def valueFromString(self, arg): return self.nestedType.valueFromString(arg) def cmp(self, val, arg): return self.nestedType.cmp(val, arg) def validate(self, name, object): if object is None: return yield from self.nestedType.validate(name, object) def getSpec(self): r = self.nestedType.getSpec() r["can_be_null"] = True return r def toRaml(self): return self.nestedType.toRaml() def toGraphQL(self): # remove trailing ! if isinstance(self.nestedType, Entity): return self.nestedType.graphql_name return self.nestedType.toGraphQL()[:-1] def graphQLDependentTypes(self): return [self.nestedType] def getGraphQLInputType(self): return self.nestedType.getGraphQLInputType() class Instance(Type): types: tuple[type, ...] = () ramlType = "unknown" graphQLType = "unknown" @property def ramlname(self): return self.ramlType def validate(self, name, object): if not isinstance(object, self.types): yield f"{name} ({object!r}) is not a {self.name or repr(self.types)}" def toRaml(self): return self.ramlType def toGraphQL(self): return self.graphQLType + "!" class Integer(Instance): name = "integer" types = (int,) ramlType = "integer" graphQLType = "Int" def valueFromString(self, arg): return int(arg) class DateTime(Instance): name = "datetime" types = (datetime.datetime,) ramlType = "date" graphQLType = "Date" # custom def valueFromString(self, arg): return int(arg) def validate(self, name, object): if isinstance(object, datetime.datetime): return if isinstance(object, int): try: datetime.datetime.fromtimestamp(object) except (OverflowError, OSError): pass else: return yield f"{name} ({object}) is not a valid timestamp" class String(Instance): name = "string" types = (str,) ramlType = "string" graphQLType = "String" def valueFromString(self, arg): val = util.bytes2unicode(arg) return val class Binary(Instance): name = "binary" types = (bytes,) ramlType = "string" graphQLType = "Binary" # custom def valueFromString(self, arg): return arg class Boolean(Instance): name = "boolean" types = (bool,) ramlType = "boolean" graphQLType = "Boolean" # custom def valueFromString(self, arg): return util.string2boolean(arg) class Identifier(Type): name = "identifier" identRe = re.compile('^[a-zA-Z_-][a-zA-Z0-9._-]*$') ramlType = "string" graphQLType = "String" def __init__(self, len=None, **kwargs): super().__init__(**kwargs) self.len = len def valueFromString(self, arg): val = util.bytes2unicode(arg) if not self.identRe.match(val) or len(val) > self.len or not val: raise TypeError return val def validate(self, name, object): if not isinstance(object, str): yield f"{name} - {object!r} - is not a unicode string" elif not self.identRe.match(object): yield f"{name} - {object!r} - is not an identifier" elif not object: yield f"{name} - identifiers cannot be an empty string" elif len(object) > self.len: yield f"{name} - {object!r} - is longer than {self.len} characters" def toRaml(self): return {'type': self.ramlType, 'pattern': self.identRe.pattern} class List(Type): name = "list" ramlType = "list" @property def ramlname(self): return self.of.ramlname def __init__(self, of=None, **kwargs): super().__init__(**kwargs) self.of = of def validate(self, name, object): if not isinstance(object, list): # we want a list, and NOT a subclass yield f"{name} ({object!r}) is not a {self.name}" return for idx, elt in enumerate(object): yield from self.of.validate(f"{name}[{idx}]", elt) def valueFromString(self, arg): # valueFromString is used to process URL args, which come one at # a time, so we defer to the `of` return self.of.valueFromString(arg) def getSpec(self): return {"type": self.name, "of": self.of.getSpec()} def toRaml(self): return {'type': 'array', 'items': self.of.name} def toGraphQL(self): return f"[{self.of.toGraphQLTypeName()}]!" def toGraphQLTypeName(self): return f"[{self.of.toGraphQLTypeName()}]" def graphQLDependentTypes(self): return [self.of] def getGraphQLInputType(self): return self.of.getGraphQLInputType() def ramlMaybeNoneOrList(k, v): if isinstance(v, NoneOk): return k + "?" if isinstance(v, List): return k + "[]" return k class SourcedProperties(Type): name = "sourcedproperties" def validate(self, name, object): if not isinstance(object, dict): # we want a dict, and NOT a subclass yield f"{name} is not sourced properties (not a dict)" return for k, v in object.items(): if not isinstance(k, str): yield f"{name} property name {k!r} is not unicode" if not isinstance(v, tuple) or len(v) != 2: yield f"{name} property value for '{k}' is not a 2-tuple" return propval, propsrc = v if not isinstance(propsrc, str): yield f"{name}[{k}] source {propsrc!r} is not unicode" try: json.loads(bytes2unicode(propval)) except ValueError: yield f"{name}[{k!r}] value is not JSON-able" def toRaml(self): return { 'type': "object", 'properties': { '[]': { 'type': 'object', 'properties': {1: 'string', 2: 'integer | string | object | array | boolean'}, } }, } def toGraphQL(self): return "[Property]!" def graphQLDependentTypes(self): return [PropertyEntityType("property", 'Property')] def getGraphQLInputType(self): return None class JsonObject(Type): name = "jsonobject" ramlname = 'object' graphQLType = "JSON" def validate(self, name, object): if not isinstance(object, dict): yield f"{name} ({object!r}) is not a dictionary (got type {type(object)})" return # make sure JSON can represent it try: json.dumps(object) except Exception as e: yield f"{name} is not JSON-able: {e}" return def toRaml(self): return "object" class Entity(Type): # NOTE: this type is defined by subclassing it in each resource type class. # Instances are generally accessed at e.g., # * buildsets.Buildset.entityType or # * self.master.data.rtypes.buildsets.entityType name: Identifier | String | str | None = None # set in constructor graphql_name: str | None = None # set in constructor fields: dict[str, Type] = {} fieldNames: set[str] = set([]) def __init__(self, name, graphql_name): fields = {} for k, v in self.__class__.__dict__.items(): if isinstance(v, Type): fields[k] = v self.fields = fields self.fieldNames = set(fields) self.name = name self.graphql_name = graphql_name def validate(self, name, object): # this uses isinstance, allowing dict subclasses as used by the DB API if not isinstance(object, dict): yield f"{name} ({object!r}) is not a dictionary (got type {type(object)})" return gotNames = set(object.keys()) unexpected = gotNames - self.fieldNames if unexpected: yield f'{name} has unexpected keys {", ".join([repr(n) for n in unexpected])}' missing = self.fieldNames - gotNames if missing: yield f'{name} is missing keys {", ".join([repr(n) for n in missing])}' for k in gotNames & self.fieldNames: f = self.fields[k] yield from f.validate(f"{name}[{k!r}]", object[k]) def getSpec(self): return { "type": self.name, "fields": [ {"name": k, "type": v.name, "type_spec": v.getSpec()} for k, v in self.fields.items() ], } def toRaml(self): return { 'type': "object", 'properties': { ramlMaybeNoneOrList(k, v): {'type': v.ramlname, 'description': ''} for k, v in self.fields.items() }, } def toGraphQL(self): return { "type": self.graphql_name, "fields": [ {"name": k, "type": v.toGraphQL()} for k, v in self.fields.items() # in graphql, we handle properties as queriable sub resources # instead of hardcoded attributes like in rest api if k != "properties" ], } def toGraphQLTypeName(self): return self.graphql_name def graphQLDependentTypes(self): return self.fields.values() def getGraphQLInputType(self): # for now, complex types are not query able # in the future, we may want to declare (and implement) graphql input types return None class PropertyEntityType(Entity): name = String() source = String() value = JsonObject()
12,214
Python
.py
334
28.338323
98
0.606315
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)