checkbox-ng-0.3/0000775000175000017500000000000012320610512013504 5ustar zygazyga00000000000000checkbox-ng-0.3/contrib/0000775000175000017500000000000012320610512015144 5ustar zygazyga00000000000000checkbox-ng-0.3/contrib/com.canonical.certification.PlainBox1.service0000664000175000017500000000013212320607367025662 0ustar zygazyga00000000000000[D-BUS Service] Name=com.canonical.certification.PlainBox1 Exec=/usr/bin/checkbox service checkbox-ng-0.3/checkbox_ng/0000775000175000017500000000000012320610512015756 5ustar zygazyga00000000000000checkbox-ng-0.3/checkbox_ng/certification.py0000664000175000017500000001404312320607367021173 0ustar zygazyga00000000000000# This file is part of Checkbox. # # Copyright 2013 Canonical Ltd. # Written by: # Zygmunt Krynicki # Daniel Manrique # # Checkbox is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License version 3, # as published by the Free Software Foundation. # # Checkbox is distributed in the hope that 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 Checkbox. If not, see . """ :mod:`checkbox.certification` -- plainbox transport to certification database ============================================================================= This module contains a PlainBox transport that knows how to send the certification XML data to the Canonical certification database. """ from gettext import gettext as _ from logging import getLogger import re from plainbox.impl.transport import TransportBase from plainbox.impl.transport import TransportError import requests from checkbox_ng.config import SECURE_ID_PATTERN logger = getLogger("checkbox.ng.certification") class InvalidSecureIDError(ValueError): def __init__(self, value): self.value = value def __str__(self): return repr(self.value) class CertificationTransport(TransportBase): """ Transport for sending data to certification database. - POSTs data to a http(s) endpoint - Adds a header with a hardware identifier - Data is expected to be in checkbox xml-compatible format. This means it will work best with a stream produced by the xml exporter. """ def __init__(self, where, options): """ Initialize the Certification Transport. The options string may contain 'secure_id' which must be a 15- or 18-character alphanumeric ID for the system. """ super().__init__(where, options) self._secure_id = self.options.get('secure_id') if self._secure_id is not None: self._validate_secure_id(self._secure_id) def send(self, data, config=None, session_state=None): """ Sends data to the specified server. :param data: Data containing the xml dump to be sent to the server. This can be either bytes or a file-like object (BytesIO works fine too). If this is a file-like object, it will be read and streamed "on the fly". :param config: Optional PlainBoxConfig object. If http_proxy and https_proxy values are set in this config object, they will be used to send data via the specified protocols. Note that the transport also honors the http_proxy and https_proxy environment variables. Proxy string format is http://[user:password@]:port :param session_state: The session for which this transport is associated with the data being sent (optional) :returns: A dictionary with responses from the server if submission was successful. This should contain an 'id' key, however the server response may change, so the only guarantee we make is that this will be non-False if the server accepted the data. :raises requests.exceptions.Timeout: If sending timed out. :raises requests.exceptions.ConnectionError: If connection failed outright. :raises requests.exceptions.HTTPError: If the server returned a non-success result code """ proxies = None if config: proxies = { proto[:-len("_proxy")]: config.environment[proto] for proto in ['http_proxy', 'https_proxy'] if proto in config.environment } # Find the effective value of secure_id: # - use the configuration object (if available) # - override with secure_id= option (if defined) secure_id = None if config is not None and hasattr(config, 'secure_id'): secure_id = config.secure_id if self._secure_id is not None: secure_id = self._secure_id if secure_id is None: raise InvalidSecureIDError(_("Secure ID not specified")) self._validate_secure_id(secure_id) logger.debug("Sending to %s, hardware id is %s", self.url, secure_id) headers = {"X_HARDWARE_ID": secure_id} # Requests takes care of properly handling a file-like data. form_payload = {"data": data} try: response = requests.post( self.url, files=form_payload, headers=headers, proxies=proxies) except requests.exceptions.Timeout as exc: raise TransportError( _("Request to {0} timed out: {1}").format(self.url, exc)) except requests.exceptions.InvalidSchema as exc: raise TransportError( _("Invalid destination URL: {0}").format(exc)) except requests.exceptions.ConnectionError as exc: raise TransportError( _("Unable to connect to {0}: {1}").format(self.url, exc)) if response is not None: try: # This will raise HTTPError for status != 20x response.raise_for_status() except requests.exceptions.RequestException as exc: raise TransportError(str(exc)) logger.debug("Success! Server said %s", response.text) try: return response.json() except Exception as exc: raise TransportError(str(exc)) # XXX: can response be None? return {} def _validate_secure_id(self, secure_id): if not re.match(SECURE_ID_PATTERN, secure_id): raise InvalidSecureIDError( _("secure_id must be 15 or 18-character alphanumeric string")) checkbox-ng-0.3/checkbox_ng/launchpad.py0000664000175000017500000002064012320607367020307 0ustar zygazyga00000000000000# This file is part of Checkbox. # # Copyright 2014 Canonical Ltd. # Written by: # Brendan Donegan # # Checkbox is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License version 3, # as published by the Free Software Foundation. # # Checkbox is distributed in the hope that 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 Checkbox. If not, see . """ :mod:`checkbox_ng.launchpad` -- plainbox transport to Launchpad database ============================================================================= This module contains a PlainBox transport that knows how to send the submission XML data to the Launchpad hardware database. """ from datetime import datetime from gettext import gettext as _ from io import BytesIO from logging import getLogger from socket import gethostname import bz2 import hashlib import re import requests from checkbox_support.lib.dmi import Dmi from plainbox.impl.secure.config import Unset from plainbox.impl.transport import TransportBase, TransportError logger = getLogger("checkbox.ng.launchpad") class InvalidSubmissionDataError(TransportError): def __init__(self, value): self.value = value def __str__(self): return repr(self.value) class LaunchpadTransport(TransportBase): """ Transport for sending data to Launchpad database. - POSTs data to a http(s) endpoint - Adds a header with a hardware identifier - Data is expected to be in checkbox xml-compatible format. This means it will work best with a stream produced by the xml exporter. """ def __init__(self, where, options): """ Initialize the Launchpad Transport. """ super().__init__(where, options) def _get_resource_attr(self, session_state, resource, attr): resource_result = session_state.resource_map.get(resource) if not resource_result: raise InvalidSubmissionDataError("Cannot get {} " "resource job".format(resource)) attr_value = getattr(resource_result[0], attr) if attr_value is None: raise InvalidSubmissionDataError("{} has no attribute " "{}".format(resource, attr)) return attr_value def _get_launchpad_form_fields(self, session_state): form_fields = {} form_fields['field.private'] = 'False' form_fields['field.contactable'] = 'False' form_fields['field.live_cd'] = 'False' form_fields['field.format'] = 'VERSION_1' form_fields['field.actions.upload'] = 'Upload' form_fields['field.date_created'] = datetime.utcnow().strftime( "%Y-%m-%dT%H:%M:%S") arch = self._get_resource_attr(session_state, '2013.com.canonical.certification::dpkg', 'architecture') form_fields['field.architecture'] = arch distro = self._get_resource_attr(session_state, '2013.com.canonical.certification::lsb', 'distributor_id') form_fields['field.distribution'] = distro series = self._get_resource_attr(session_state, '2013.com.canonical.certification::lsb', 'codename') form_fields['field.distroseries'] = series dmi_resources = session_state.resource_map.get( '2013.com.canonical.certification::dmi') if dmi_resources is None: raise InvalidSubmissionDataError("barf") system_id = "" for resource in dmi_resources: if resource.category == 'CHASSIS': chassis_type = Dmi.chassis_name_to_type[resource.product] vendor = getattr(resource, 'vendor', "") model = getattr(resource, 'model', "") fingerprint = hashlib.md5() for field in ["Computer", "unknown", chassis_type, vendor, model]: fingerprint.update(field.encode('utf-8')) system_id = fingerprint.hexdigest() if not system_id: raise InvalidSubmissionDataError("puke") form_fields['field.system'] = system_id fingerprint = hashlib.md5() fingerprint.update(system_id.encode('utf-8')) fingerprint.update(str(datetime.utcnow()).encode('utf-8')) form_fields['field.submission_key'] = fingerprint.hexdigest() return form_fields def send(self, data, config=None, session_state=None): """ Sends data to the specified server. :param data: Data containing the xml dump to be sent to the server. This can be either bytes or a file-like object (BytesIO works fine too). If this is a file-like object, it will be read and streamed "on the fly". :param config: optional PlainBoxConfig object. If http_proxy and https_proxy values are set in this config object, they will be used to send data via the specified protocols. Note that the transport also honors the http_proxy and https_proxy environment variables. Proxy string format is http://[user:password@]:port :param session_state: :returns: a dictionary with responses from the server if submission was successful. :raises ValueError: If no session state was provided. :raises TransportError: - If sending timed out. - If connection failed outright. - If the server returned a non-success result code - If a required resource job is missing from the submission or a resource job is missing a required attribute. The following resource/attribute pairs are needed: - dpkg: architecture - lsb: distributor_id - lsb: codename - dmi: product """ proxies = None if config: proxies = { proto[:-len("_proxy")]: config.environment[proto] for proto in ['http_proxy', 'https_proxy'] if proto in config.environment } if session_state is None: raise ValueError("LaunchpadTransport requires a session " "state to be provided.") logger.debug("Sending to %s, email is %s", self.url, self.options['field.emailaddress']) lp_headers = {"x-launchpad-hwdb-submission": ""} form_fields = self._get_launchpad_form_fields(session_state) form_fields['field.emailaddress'] = self.options['field.emailaddress'] compressed_payload = bz2.compress(data.encode('utf-8')) file = BytesIO(compressed_payload) file.name = "{}.xml.bz2".format(gethostname()) file.size = len(compressed_payload) submission_data = {'field.submission_data': file} try: response = requests.post(self.url, data=form_fields, files=submission_data, headers=lp_headers, proxies=proxies) except requests.exceptions.Timeout as exc: raise TransportError( _("Request to {0} timed out: {1}").format(self.url, exc)) except requests.exceptions.InvalidSchema as exc: raise TransportError( _("Invalid destination URL: {0}").format(exc)) except requests.exceptions.ConnectionError as exc: raise TransportError( _("Unable to connect to {0}: {1}").format(self.url, exc)) if response is not None: try: # This will raise HTTPError for status != 20x response.raise_for_status() except requests.exceptions.RequestException as exc: raise TransportError(str(exc)) logger.debug("Success! Server said %s", response.text) status = _('The submission was uploaded to Launchpad succesfully.') if (response.headers['x-launchpad-hwdb-submission'] != 'OK data stored'): status = response.headers['x-launchpad-hwdb-submission'] return {'status': status} # XXX: can response be None? return {} checkbox-ng-0.3/checkbox_ng/tests.py0000664000175000017500000000276012320607367017515 0ustar zygazyga00000000000000# This file is part of Checkbox. # # Copyright 2012 Canonical Ltd. # Written by: # Zygmunt Krynicki # # Checkbox is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License version 3, # as published by the Free Software Foundation. # # Checkbox is distributed in the hope that 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 Checkbox. If not, see . """ :mod:`checkbox_ng.tests` -- auxiliary test loaders for checkbox-ng ================================================================== """ import inspect import os import unittest import checkbox_ng def load_unit_tests(): """ Load all unit tests and return a TestSuite object """ # Discover all unit tests. By simple convention those are kept in # python modules that start with the word 'test_' . return unittest.defaultTestLoader.discover( os.path.dirname( inspect.getabsfile(checkbox_ng))) def test_suite(): """ Test suite function used by setuptools test loader. Uses unittest test discovery system to get a list of test cases defined inside checkbox-ng. See setup.py setup(test_suite=...) for a matching entry """ return load_unit_tests() checkbox-ng-0.3/checkbox_ng/commands/0000775000175000017500000000000012320610512017557 5ustar zygazyga00000000000000checkbox-ng-0.3/checkbox_ng/commands/certification.py0000664000175000017500000001501112320607367022770 0ustar zygazyga00000000000000# This file is part of Checkbox. # # Copyright 2013 Canonical Ltd. # Written by: # Sylvain Pineau # # Checkbox is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License version 3, # as published by the Free Software Foundation. # # Checkbox is distributed in the hope that 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 Checkbox. If not, see . """ :mod:`checkbox_ng.commands.certification` -- Certification sub-command ====================================================================== .. warning:: THIS MODULE DOES NOT HAVE STABLE PUBLIC API """ from logging import getLogger from plainbox.impl.commands.check_config import CheckConfigInvocation from plainbox.impl.secure.config import Unset, ValidationError from requests.exceptions import ConnectionError, InvalidSchema, HTTPError from checkbox_ng.certification import CertificationTransport from checkbox_ng.certification import InvalidSecureIDError from checkbox_ng.commands.cli import CliCommand, CliInvocation logger = getLogger("checkbox.ng.commands.certification") class CertificationInvocation(CliInvocation): """ Helper class instantiated to perform a particular invocation of the certification command. Unlike the certification command itself, this class is instantiated each time. """ def save_results(self, session): super().save_results(session) if self.config.secure_id is Unset: again = True if not self.is_interactive: again = False while again: if self.ask_user( "\nSubmit results to certification.canonical.com?", ('y', 'n') ).lower() == "y": try: self.config.secure_id = input("Secure ID: ") except ValidationError: print( "ERROR: Secure ID must be 15 or 18-character" " alphanumeric string") else: again = False self.submit_results(session) else: again = False else: # Automatically try to submit results if the secure_id is valid self.submit_results(session) def submit_results(self, session): print("Submitting results to {0} for secure_id {1}".format( self.config.c3_url, self.config.secure_id)) options_string = "secure_id={0}".format(self.config.secure_id) # Create the transport object try: transport = CertificationTransport( self.config.c3_url, options_string) except InvalidSecureIDError as exc: print(exc) return False with open(self.submission_file) as stream: try: # Send the data, reading from the fallback file result = transport.send(stream, self.config) if 'url' in result: print("Successfully sent, submission status at {0}".format( result['url'])) else: print("Successfully sent, server response: {0}".format( result)) except InvalidSchema as exc: print("Invalid destination URL: {0}".format(exc)) except ConnectionError as exc: print("Unable to connect to destination URL: {0}".format(exc)) except HTTPError as exc: print(("Server returned an error when " "receiving or processing: {0}").format(exc)) except IOError as exc: print("Problem reading a file: {0}".format(exc)) class CertificationCommand(CliCommand): """ Command for running certification tests using the command line UI. This class allows submissions to the certification database. """ def invoked(self, ns): # Copy command-line arguments over configuration variables try: if ns.secure_id: self.config.secure_id = ns.secure_id if ns.c3_url: self.config.c3_url = ns.c3_url except ValidationError as exc: print("Configuration problems prevent running tests") print(exc) return 1 # Run check-config, if requested if ns.check_config: retval = CheckConfigInvocation(self.config).run() return retval return CertificationInvocation(self.provider_list, self.config, self.settings, ns).run() def register_parser(self, subparsers): parser = subparsers.add_parser(self.settings['subparser_name'], help=self.settings['subparser_help']) parser.set_defaults(command=self) parser.add_argument( "--check-config", action="store_true", help="Run check-config") parser.add_argument( '--not-interactive', action='store_true', help="Skip tests that require interactivity") group = parser.add_argument_group("certification-specific options") # Set defaults from based on values from the config file group.set_defaults(c3_url=self.config.c3_url) if self.config.secure_id is not Unset: group.set_defaults(secure_id=self.config.secure_id) group.add_argument( '--secure-id', metavar="SECURE-ID", action='store', help=("Associate submission with a machine using this" " SECURE-ID (%(default)s)")) group.add_argument( '--destination', metavar="URL", dest='c3_url', action='store', help=("POST the test report XML to this URL" " (%(default)s)")) group.add_argument( '--staging', dest='c3_url', action='store_const', const='https://certification.staging.canonical.com' '/submissions/submit/', help='Override --destination to use the staging certification ' 'website') # Call enhance_parser from CheckBoxCommandMixIn self.enhance_parser(parser) checkbox-ng-0.3/checkbox_ng/commands/test_sru.py0000664000175000017500000000553012320607367022022 0ustar zygazyga00000000000000# This file is part of Checkbox. # # Copyright 2013 Canonical Ltd. # Written by: # Zygmunt Krynicki # # Checkbox is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License version 3, # as published by the Free Software Foundation. # # Checkbox is distributed in the hope that 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 Checkbox. If not, see . """ plainbox.impl.commands.test_sru =============================== Test definitions for plainbox.impl.box module """ from inspect import cleandoc from unittest import TestCase from plainbox.testing_utils.io import TestIO from checkbox_ng.main import main class TestSru(TestCase): def test_help(self): with TestIO(combined=True) as io: with self.assertRaises(SystemExit) as call: main(['sru', '--help']) self.assertEqual(call.exception.args, (0,)) self.maxDiff = None expected = """ usage: checkbox sru [-h] [--check-config] --secure-id SECURE-ID [--fallback FILE] [--destination URL] [--staging] [-n] [-i PATTERN] [-x PATTERN] [-w WHITELIST] optional arguments: -h, --help show this help message and exit --check-config Run plainbox check-config before starting sru-specific options: --secure-id SECURE-ID Associate submission with a machine using this SECURE- ID (unset) --fallback FILE If submission fails save the test report as FILE (unset) --destination URL POST the test report XML to this URL (https://certific ation.canonical.com/submissions/submit/) --staging Override --destination to use the staging certification website execution options: -n, --dry-run Skip all usual jobs. Only local, resource and attachment jobs are started job definition options: -i PATTERN, --include-pattern PATTERN include jobs matching the given regular expression -x PATTERN, --exclude-pattern PATTERN exclude jobs matching the given regular expression -w WHITELIST, --whitelist WHITELIST load whitelist containing run patterns """ self.assertEqual(io.combined, cleandoc(expected) + "\n") checkbox-ng-0.3/checkbox_ng/commands/test_cli.py0000664000175000017500000001332312320607367021757 0ustar zygazyga00000000000000# This file is part of Checkbox. # # Copyright 2014 Canonical Ltd. # Written by: # Sylvain Pineau # # Checkbox is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License version 3, # as published by the Free Software Foundation. # # Checkbox is distributed in the hope that 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 Checkbox. If not, see . """ checkbox_ng.commands.test_cli ============================= Test definitions for checkbox_ng.commands.cli module """ from unittest import TestCase from plainbox.impl.job import JobOutputTextSource, JobDefinition from plainbox.impl.secure.rfc822 import Origin from plainbox.impl.secure.rfc822 import RFC822Record from plainbox.impl.testing_utils import make_job from checkbox_ng.commands.cli import SelectableJobTreeNode class TestSelectableJobTreeNode(TestCase): def setUp(self): self.A = make_job('a', name='A') self.B = make_job('b', name='B', plugin='local', description='foo') self.C = make_job('c', name='C') self.D = self.B.create_child_job_from_record( RFC822Record( data={'id': 'd', 'name': 'D', 'plugin': 'shell'}, origin=Origin(source=JobOutputTextSource(self.B), line_start=1, line_end=1))) self.E = self.B.create_child_job_from_record( RFC822Record( data={'id': 'e', 'name': 'E', 'plugin': 'shell'}, origin=Origin(source=JobOutputTextSource(self.B), line_start=1, line_end=1))) self.F = make_job('f', name='F', plugin='resource', description='baz') self.tree = SelectableJobTreeNode.create_tree([ self.A, self.B, self.C, self.D, self.E, self.F ], legacy_mode=True) def test_create_tree(self): self.assertIsInstance(self.tree, SelectableJobTreeNode) self.assertEqual(len(self.tree.categories), 1) [self.assertIsInstance(c, SelectableJobTreeNode) for c in self.tree.categories] self.assertEqual(len(self.tree.jobs), 2) [self.assertIsInstance(j, JobDefinition) for j in self.tree.jobs] self.assertTrue(self.tree.selected) [self.assertTrue(self.tree.job_selection[j]) for j in self.tree.job_selection] self.assertTrue(self.tree.expanded) self.assertIsNone(self.tree.parent) self.assertEqual(self.tree.depth, 0) def test_get_node_by_index(self): self.assertEqual(self.tree.get_node_by_index(0)[0].name, 'foo') self.assertEqual(self.tree.get_node_by_index(1)[0].name, 'D') self.assertEqual(self.tree.get_node_by_index(2)[0].name, 'E') self.assertEqual(self.tree.get_node_by_index(3)[0].name, 'A') self.assertEqual(self.tree.get_node_by_index(4)[0].name, 'C') self.assertIsNone(self.tree.get_node_by_index(5)[0]) def test_render(self): expected = ['[X] - foo', '[X] D', '[X] E', '[X] A', '[X] C'] self.assertEqual(self.tree.render(), expected) def test_render_deselected_all(self): self.tree.set_descendants_state(False) expected = ['[ ] - foo', '[ ] D', '[ ] E', '[ ] A', '[ ] C'] self.assertEqual(self.tree.render(), expected) def test_render_reselected_all(self): self.tree.set_descendants_state(False) self.tree.set_descendants_state(True) expected = ['[X] - foo', '[X] D', '[X] E', '[X] A', '[X] C'] self.assertEqual(self.tree.render(), expected) def test_render_with_child_collapsed(self): self.tree.categories[0].expanded = False expected = ['[X] + foo', '[X] A', '[X] C'] self.assertEqual(self.tree.render(), expected) def test_set_ancestors_state(self): self.tree.set_descendants_state(False) node = self.tree.categories[0] node.job_selection[self.E] = True node.update_selected_state() node.set_ancestors_state(node.selected) expected = ['[X] - foo', '[ ] D', '[X] E', '[ ] A', '[ ] C'] self.assertEqual(self.tree.render(), expected) node.selected = not(node.selected) node.set_ancestors_state(node.selected) node.set_descendants_state(node.selected) expected = ['[ ] - foo', '[ ] D', '[ ] E', '[ ] A', '[ ] C'] self.assertEqual(self.tree.render(), expected) def test_selection(self): self.tree.set_descendants_state(False) node = self.tree.categories[0] node.job_selection[self.D] = True node.update_selected_state() node.set_ancestors_state(node.selected) # Note that in addition to the selected (D) test, we need the # tree selection to contain the resource (F), even though the # user never saw it in the previous tests for visual presentation. self.assertEqual(self.tree.selection, [self.D, self.F]) checkbox-ng-0.3/checkbox_ng/commands/sru.py0000664000175000017500000002643712320607367020774 0ustar zygazyga00000000000000# This file is part of Checkbox. # # # Copyright 2013 Canonical Ltd. # Written by: # Zygmunt Krynicki # # Checkbox is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License version 3, # as published by the Free Software Foundation. # # Checkbox is distributed in the hope that 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 Checkbox. If not, see . """ :mod:`checkbox_ng.commands.sru` -- sru sub-command ================================================== .. warning:: THIS MODULE DOES NOT HAVE STABLE PUBLIC API """ import logging import sys import tempfile from plainbox.impl.applogic import get_matching_job_list from plainbox.impl.applogic import get_whitelist_by_name from plainbox.impl.applogic import run_job_if_possible from plainbox.impl.commands import PlainBoxCommand from plainbox.impl.commands.check_config import CheckConfigInvocation from plainbox.impl.commands.checkbox import CheckBoxCommandMixIn from plainbox.impl.commands.checkbox import CheckBoxInvocationMixIn from plainbox.impl.depmgr import DependencyDuplicateError from plainbox.impl.exporter import ByteStringStreamTranslator from plainbox.impl.exporter.xml import XMLSessionStateExporter from plainbox.impl.runner import JobRunner from plainbox.impl.secure.config import ValidationError, Unset from plainbox.impl.session import SessionStateLegacyAPI as SessionState from plainbox.impl.transport import TransportError from checkbox_ng.certification import CertificationTransport logger = logging.getLogger("plainbox.commands.sru") class _SRUInvocation(CheckBoxInvocationMixIn): """ Helper class instantiated to perform a particular invocation of the sru command. Unlike the SRU command itself, this class is instantiated each time. """ def __init__(self, provider_list, config, ns): super().__init__(provider_list, config) self.ns = ns if self.ns.whitelist: self.whitelist = self.get_whitelist_from_file( self.ns.whitelist[0].name, self.ns.whitelist) elif self.config.whitelist is not Unset: self.whitelist = self.get_whitelist_from_file( self.config.whitelist) else: self.whitelist = get_whitelist_by_name(provider_list, 'sru') self.job_list = self.get_job_list(ns) # XXX: maybe allow specifying system_id from command line? self.exporter = XMLSessionStateExporter(system_id=None) self.session = None self.runner = None def run(self): # Compute the run list, this can give us notification about problems in # the selected jobs. Currently we just display each problem # Create a session that handles most of the stuff needed to run jobs try: self.session = SessionState(self.job_list) except DependencyDuplicateError as exc: # Handle possible DependencyDuplicateError that can happen if # someone is using plainbox for job development. print("The job database you are currently using is broken") print("At least two jobs contend for the name {0}".format( exc.job.id)) print("First job defined in: {0}".format(exc.job.origin)) print("Second job defined in: {0}".format( exc.duplicate_job.origin)) raise SystemExit(exc) with self.session.open(): self._set_job_selection() self.runner = JobRunner( self.session.session_dir, self.provider_list, self.session.jobs_io_log_dir, command_io_delegate=self, dry_run=self.ns.dry_run) self._run_all_jobs() if self.config.fallback_file is not Unset: self._save_results() self._submit_results() # FIXME: sensible return value return 0 def _set_job_selection(self): desired_job_list = get_matching_job_list(self.job_list, self.whitelist) problem_list = self.session.update_desired_job_list(desired_job_list) if problem_list: logger.warning("There were some problems with the selected jobs") for problem in problem_list: logger.warning("- %s", problem) logger.warning("Problematic jobs will not be considered") def _save_results(self): print("Saving results to {0}".format(self.config.fallback_file)) data = self.exporter.get_session_data_subset(self.session) with open(self.config.fallback_file, "wt", encoding="UTF-8") as stream: translating_stream = ByteStringStreamTranslator(stream, "UTF-8") self.exporter.dump(data, translating_stream) def _submit_results(self): print("Submitting results to {0} for secure_id {1}".format( self.config.c3_url, self.config.secure_id)) options_string = "secure_id={0}".format(self.config.secure_id) # Create the transport object transport = CertificationTransport(self.config.c3_url, options_string) # Prepare the data for submission data = self.exporter.get_session_data_subset(self.session) with tempfile.NamedTemporaryFile(mode='w+b') as stream: # Dump the data to the temporary file self.exporter.dump(data, stream) # Flush and rewind stream.flush() stream.seek(0) try: # Send the data, reading from the temporary file result = transport.send(stream, self.config, self.session) if 'url' in result: print("Successfully sent, submission status at {0}".format( result['url'])) else: print("Successfully sent, server response: {0}".format( result)) except (ValueError, TransportError) as exc: print(str(exc)) except IOError as exc: print("Problem reading a file: {0}".format(exc)) def _run_all_jobs(self): again = True while again: again = False for job in self.session.run_list: # Skip jobs that already have result, this is only needed when # we run over the list of jobs again, after discovering new # jobs via the local job output result = self.session.job_state_map[job.id].result if result.outcome is not None: continue self._run_single_job(job) self.session.persistent_save() if job.plugin == "local": # After each local job runs rebuild the list of matching # jobs and run everything again self._set_job_selection() again = True break def _run_single_job(self, job): print("- {}:".format(job.id), end=' ') sys.stdout.flush() job_state, job_result = run_job_if_possible( self.session, self.runner, self.config, job) print("{0}".format(job_result.outcome)) sys.stdout.flush() if job_result.comments is not None: print("comments: {0}".format(job_result.comments)) if job_state.readiness_inhibitor_list: print("inhibitors:") for inhibitor in job_state.readiness_inhibitor_list: print(" * {}".format(inhibitor)) self.session.update_job_result(job, job_result) class SRUCommand(PlainBoxCommand, CheckBoxCommandMixIn): """ Command for running Stable Release Update (SRU) tests. Stable release updates are periodic fixes for nominated bugs that land in existing supported Ubuntu releases. To ensure a certain level of quality all SRU updates affecting hardware enablement are automatically tested on a pool of certified machines. This command is _temporary_ and will eventually migrate to the checkbox side. Its intended lifecycle is for the development and validation of plainbox core on realistic workloads. """ def __init__(self, provider_list, config): self.provider_list = provider_list self.config = config def invoked(self, ns): # Copy command-line arguments over configuration variables try: if ns.secure_id: self.config.secure_id = ns.secure_id if ns.fallback_file and ns.fallback_file is not Unset: self.config.fallback_file = ns.fallback_file if ns.c3_url: self.config.c3_url = ns.c3_url except ValidationError as exc: print("Configuration problems prevent running SRU tests") print(exc) return 1 # Run check-config, if requested if ns.check_config: retval = CheckConfigInvocation(self.config).run() if retval != 0: return retval return _SRUInvocation(self.provider_list, self.config, ns).run() def register_parser(self, subparsers): parser = subparsers.add_parser( "sru", help="run automated stable release update tests") parser.set_defaults(command=self) parser.add_argument( "--check-config", action="store_true", help="Run plainbox check-config before starting") group = parser.add_argument_group("sru-specific options") # Set defaults from based on values from the config file group.set_defaults( secure_id=self.config.secure_id, c3_url=self.config.c3_url, fallback_file=self.config.fallback_file) group.add_argument( '--secure-id', metavar="SECURE-ID", action='store', # NOTE: --secure-id is optional only when set in a config file required=self.config.secure_id is Unset, help=("Associate submission with a machine using this SECURE-ID" " (%(default)s)")) group.add_argument( '--fallback', metavar="FILE", dest='fallback_file', action='store', default=Unset, help=("If submission fails save the test report as FILE" " (%(default)s)")) group.add_argument( '--destination', metavar="URL", dest='c3_url', action='store', help=("POST the test report XML to this URL" " (%(default)s)")) group.add_argument( '--staging', dest='c3_url', action='store_const', const='https://certification.staging.canonical.com/submissions/submit/', help='Override --destination to use the staging certification website') group = parser.add_argument_group(title="execution options") group.add_argument( '-n', '--dry-run', action='store_true', default=False, help=("Skip all usual jobs." " Only local, resource and attachment jobs are started")) # Call enhance_parser from CheckBoxCommandMixIn self.enhance_parser(parser) checkbox-ng-0.3/checkbox_ng/commands/__init__.py0000664000175000017500000000000012320607367021674 0ustar zygazyga00000000000000checkbox-ng-0.3/checkbox_ng/commands/service.py0000664000175000017500000001124212320607367021607 0ustar zygazyga00000000000000# This file is part of Checkbox. # # Copyright 2013 Canonical Ltd. # Written by: # Zygmunt Krynicki # # Checkbox is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License version 3, # as published by the Free Software Foundation. # # Checkbox is distributed in the hope that 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 Checkbox. If not, see . """ :mod:`checkbox_ng.commands.service` -- service sub-command ========================================================== """ import logging import os from dbus import StarterBus, SessionBus from dbus.mainloop.glib import DBusGMainLoop, threads_init from dbus.service import BusName from gi.repository import GObject from plainbox.impl.commands import PlainBoxCommand from plainbox.impl.highlevel import Service from checkbox_ng.service import ServiceWrapper logger = logging.getLogger("checkbox.ng.commands.service") def connect_to_session_bus(): """ Connect to the session bus properly. Returns a tuple (session_bus, loop) where loop is a GObject.MainLoop instance. The loop is there so that you can listen to signals. """ # We'll need an event loop to observe signals. We will need the instance # later below so let's keep it. Note that we're not passing it directly # below as DBus needs specific API. The DBusGMainLoop class that we # instantiate and pass is going to work with this instance transparently. # # NOTE: DBus tutorial suggests that we should create the loop _before_ # connecting to the bus. logger.debug("Setting up glib-based event loop") # Make sure gobject threads don't crash GObject.threads_init() threads_init() loop = GObject.MainLoop() # Let's get the system bus object. logger.debug("Connecting to DBus session bus") if os.getenv("DBUS_STARTER_ADDRESS"): session_bus = StarterBus(mainloop=DBusGMainLoop()) else: session_bus = SessionBus(mainloop=DBusGMainLoop()) return session_bus, loop class ServiceInvocation: def __init__(self, provider_list, config, ns): self.provider_list = provider_list self.config = config self.ns = ns def run(self): bus, loop = connect_to_session_bus() logger.info("Setting up DBus objects...") session_list = [] # TODO: load sessions logger.debug("Constructing Service object") service_obj = Service(self.provider_list, session_list, self.config) logger.debug("Constructing ServiceWrapper") service_wrp = ServiceWrapper(service_obj, on_exit=lambda: loop.quit()) logger.info("Publishing all objects on DBus") service_wrp.publish_related_objects(bus) logger.info("Publishing all managed objects (events should fire there)") service_wrp.publish_managed_objects() logger.debug("Attempting to claim bus name: %s", self.ns.bus_name) bus_name = BusName(self.ns.bus_name, bus) logger.info( "PlainBox DBus service ready, claimed name: %s", bus_name.get_name()) try: loop.run() except KeyboardInterrupt: logger.warning(( "Main loop interrupted!" " It is recommended to call the Exit() method on the" " exported service object instead")) finally: logger.debug("Releasing %s", bus_name) # XXX: ugly but that's how one can reliably release a bus name del bus_name # Remove objects from the bus service_wrp.remove_from_connection() logger.debug("Closing %s", bus) bus.close() logger.debug("Main loop terminated, exiting...") class ServiceCommand(PlainBoxCommand): """ DBus service for PlainBox """ # XXX: Maybe drop provider / config and handle them differently def __init__(self, provider_list, config): self.provider_list = provider_list self.config = config def invoked(self, ns): return ServiceInvocation(self.provider_list, self.config, ns).run() def register_parser(self, subparsers): parser = subparsers.add_parser("service", help="spawn dbus service") parser.add_argument( '--bus-name', action="store", default="com.canonical.certification.PlainBox1", help="Use the specified DBus bus name") parser.set_defaults(command=self) checkbox-ng-0.3/checkbox_ng/commands/cli.py0000664000175000017500000010636112320607367020725 0ustar zygazyga00000000000000# This file is part of Checkbox. # # Copyright 2013 Canonical Ltd. # Written by: # Sylvain Pineau # # Checkbox is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License version 3, # as published by the Free Software Foundation. # # Checkbox is distributed in the hope that 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 Checkbox. If not, see . """ :mod:`checkbox_ng.commands.cli` -- Command line sub-command =========================================================== .. warning:: THIS MODULE DOES NOT HAVE STABLE PUBLIC API """ from logging import getLogger from os.path import join from shutil import copyfileobj import io import os import sys import textwrap from plainbox.abc import IJobResult from plainbox.impl.applogic import get_whitelist_by_name from plainbox.impl.commands import PlainBoxCommand from plainbox.impl.commands.check_config import CheckConfigInvocation from plainbox.impl.commands.checkbox import CheckBoxCommandMixIn from plainbox.impl.commands.checkbox import CheckBoxInvocationMixIn from plainbox.impl.depmgr import DependencyDuplicateError from plainbox.impl.exporter import ByteStringStreamTranslator from plainbox.impl.exporter import get_all_exporters from plainbox.impl.exporter.html import HTMLSessionStateExporter from plainbox.impl.exporter.xml import XMLSessionStateExporter from plainbox.impl.job import JobTreeNode from plainbox.impl.result import DiskJobResult, MemoryJobResult from plainbox.impl.runner import JobRunner from plainbox.impl.runner import authenticate_warmup from plainbox.impl.runner import slugify from plainbox.impl.secure.config import Unset from plainbox.impl.secure.qualifiers import CompositeQualifier from plainbox.impl.secure.qualifiers import NonLocalJobQualifier from plainbox.impl.secure.qualifiers import WhiteList from plainbox.impl.secure.qualifiers import select_jobs from plainbox.impl.session import SessionManager, SessionStorageRepository from plainbox.vendor.textland import DrawingContext from plainbox.vendor.textland import EVENT_KEYBOARD from plainbox.vendor.textland import EVENT_RESIZE from plainbox.vendor.textland import Event from plainbox.vendor.textland import IApplication from plainbox.vendor.textland import KeyboardData from plainbox.vendor.textland import Size from plainbox.vendor.textland import TextImage from plainbox.vendor.textland import get_display from plainbox.vendor.textland import NORMAL, REVERSE, UNDERLINE logger = getLogger("checkbox.ng.commands.cli") class SelectableJobTreeNode(JobTreeNode): """ Implementation of a node in a tree that can be selected/deselected """ def __init__(self, job=None): super().__init__(job) self.selected = True self.job_selection = {} self.expanded = True self.current_index = 0 self._resource_jobs = [] def get_node_by_index(self, index, tree=None): """ Return the node found at the position given by index considering the tree from a top-down list view. """ if tree is None: tree = self if self.expanded: for category in self.categories: if index == tree.current_index: tree.current_index = 0 return (category, None) else: tree.current_index += 1 result = category.get_node_by_index(index, tree) if result != (None, None): return result for job in self.jobs: if index == tree.current_index: tree.current_index = 0 return (job, self) else: tree.current_index += 1 return (None, None) def render(self, cols=80): """ Return the tree as a simple list of categories and jobs suitable for display. Jobs are properly indented to respect the tree hierarchy and selection marks are added automatically at the beginning of each element. The node titles should not exceed the width of a the terminal and thus are cut to fit inside. """ self._flat_list = [] if self.expanded: for category in self.categories: prefix = '[ ]' if category.selected: prefix = '[X]' line = '' title = category.name if category.jobs or category.categories: if category.expanded: line = prefix + self.depth * ' ' + ' - ' + title else: line = prefix + self.depth * ' ' + ' + ' + title else: line = prefix + self.depth * ' ' + ' ' + title if len(line) > cols: col_max = cols - 4 # includes len('...') + a space line = line[:col_max] + '...' self._flat_list.append(line) self._flat_list.extend(category.render(cols)) for job in self.jobs: prefix = '[ ]' if self.job_selection[job]: prefix = '[X]' title = job.name line = prefix + self.depth * ' ' + ' ' + title if len(line) > cols: col_max = cols - 4 # includes len('...') + a space line = line[:col_max] + '...' self._flat_list.append(line) return self._flat_list def add_job(self, job): if job.plugin == 'resource': # I don't want the user to see resources but I need to keep # track of them to put them in the final selection. I also # don't want to add them to the tree. self._resource_jobs.append(job) return super().add_job(job) self.job_selection[job] = True @property def selection(self): """ Return all the jobs currently selected """ self._selection_list = [] for category in self.categories: self._selection_list.extend(category.selection) for job in self.job_selection: if self.job_selection[job]: self._selection_list.append(job) # Don't forget to append the collected resource jobs to the final # selection self._selection_list.extend(self._resource_jobs) return self._selection_list def set_ancestors_state(self, new_state): """ Set the selection state of all ancestors consistently """ # If child is set, then all ancestors must be set if new_state: parent = self.parent while parent: parent.selected = new_state parent = parent.parent # If child is not set, then all ancestors mustn't be set # unless another child of the ancestor is set else: parent = self.parent while parent: if any((category.selected for category in parent.categories)): break if any((parent.job_selection[job] for job in parent.job_selection)): break parent.selected = new_state parent = parent.parent def update_selected_state(self): """ Update the category state according to its job selection """ if any((self.job_selection[job] for job in self.job_selection)): self.selected = True else: self.selected = False def set_descendants_state(self, new_state): """ Set the selection state of all descendants recursively """ self.selected = new_state for job in self.job_selection: self.job_selection[job] = new_state for category in self.categories: category.set_descendants_state(new_state) class ShowWelcome(IApplication): """ Display a welcome message """ def __init__(self, text): self.image = TextImage(Size(0, 0)) self.text = text def consume_event(self, event: Event): if event.kind == EVENT_RESIZE: self.image = TextImage(event.data) # data is the new size elif event.kind == EVENT_KEYBOARD and event.data.key == "enter": raise StopIteration self.repaint(event) return self.image def repaint(self, event: Event): ctx = DrawingContext(self.image) i = 0 ctx.border() for paragraph in self.text.splitlines(): i += 1 for line in textwrap.fill( paragraph, self.image.size.width - 8, replace_whitespace=False).splitlines(): ctx.move_to(4, i) ctx.print(line) i += 1 ctx.move_to(4, i + 1) ctx.attributes.style = REVERSE ctx.print("< Continue >") class ShowMenu(IApplication): """ Display the appropriate menu and return the selected options """ def __init__(self, title, menu): self.image = TextImage(Size(0, 0)) self.title = title self.menu = menu self.option_count = len(menu) self.position = 0 # Zero-based index of the selected menu option self.selection = [self.position] def consume_event(self, event: Event): if event.kind == EVENT_RESIZE: self.image = TextImage(event.data) # data is the new size elif event.kind == EVENT_KEYBOARD: if event.data.key == "down": if self.position < self.option_count: self.position += 1 else: self.position = 0 elif event.data.key == "up": if self.position > 0: self.position -= 1 else: self.position = self.option_count elif (event.data.key == "enter" and self.position == self.option_count): raise StopIteration(self.selection) elif event.data.key == "space": if self.position in self.selection: self.selection.remove(self.position) elif self.position < self.option_count: self.selection.append(self.position) self.repaint(event) return self.image def repaint(self, event: Event): ctx = DrawingContext(self.image) ctx.border(tm=1) ctx.attributes.style = REVERSE ctx.print(' ' * self.image.size.width) ctx.move_to(1, 0) ctx.print(self.title) # Display all the menu items for i in range(self.option_count): ctx.attributes.style = NORMAL if i == self.position: ctx.attributes.style = REVERSE # Display options from line 3, column 4 ctx.move_to(4, 3 + i) ctx.print("[{}] - {}".format( 'X' if i in self.selection else ' ', self.menu[i].replace('ihv-', '').capitalize())) # Display "OK" at bottom of menu ctx.attributes.style = NORMAL if self.position == self.option_count: ctx.attributes.style = REVERSE # Add an empty line before the last option ctx.move_to(4, 4 + self.option_count) ctx.print("< OK >") class ScrollableTreeNode(IApplication): """ Class used to interact with a SelectableJobTreeNode """ def __init__(self, tree, title): self.image = TextImage(Size(0, 0)) self.tree = tree self.title = title self.top = 0 # Top line number self.highlight = 0 # Highlighted line number def consume_event(self, event: Event): if event.kind == EVENT_RESIZE: self.image = TextImage(event.data) # data is the new size elif event.kind == EVENT_KEYBOARD: self.image = TextImage(self.image.size) if event.data.key == "up": self._scroll("up") elif event.data.key == "down": self._scroll("down") elif event.data.key == "space": self._selectNode() elif event.data.key == "enter": self._toggleNode() elif event.data.key in 'sS': self.tree.set_descendants_state(True) elif event.data.key in 'dD': self.tree.set_descendants_state(False) elif event.data.key in 'tT': raise StopIteration self.repaint(event) return self.image def repaint(self, event: Event): ctx = DrawingContext(self.image) ctx.border(tm=1, bm=1) cols = self.image.size.width extra_cols = 0 if cols > 80: extra_cols = cols - 80 ctx.attributes.style = REVERSE ctx.print(' ' * cols) ctx.move_to(1, 0) bottom = self.top + self.image.size.height - 4 ctx.print(self.title) ctx.move_to(1, self.image.size.height - 1) ctx.attributes.style = UNDERLINE ctx.print("Enter") ctx.move_to(6, self.image.size.height - 1) ctx.attributes.style = NORMAL ctx.print(": Expand/Collapse") ctx.move_to(27, self.image.size.height - 1) ctx.attributes.style = UNDERLINE ctx.print("S") ctx.move_to(28, self.image.size.height - 1) ctx.attributes.style = NORMAL ctx.print("elect All") ctx.move_to(41, self.image.size.height - 1) ctx.attributes.style = UNDERLINE ctx.print("D") ctx.move_to(42, self.image.size.height - 1) ctx.attributes.style = NORMAL ctx.print("eselect All") ctx.move_to(66 + extra_cols, self.image.size.height - 1) ctx.print("Start ") ctx.move_to(72 + extra_cols, self.image.size.height - 1) ctx.attributes.style = UNDERLINE ctx.print("T") ctx.move_to(73 + extra_cols, self.image.size.height - 1) ctx.attributes.style = NORMAL ctx.print("esting") for i, line in enumerate(self.tree.render(cols - 3)[self.top:bottom]): ctx.move_to(2, i + 2) if i != self.highlight: ctx.attributes.style = NORMAL else: # highlight the current line ctx.attributes.style = REVERSE ctx.print(line) def _selectNode(self): """ Mark a node/job as selected for this test run. See :meth:`SelectableJobTreeNode.set_ancestors_state()` and :meth:`SelectableJobTreeNode.set_descendants_state()` for details about the automatic selection of parents and descendants. """ node, category = self.tree.get_node_by_index(self.top + self.highlight) if category: # then the selected node is a job not a category job = node category.job_selection[job] = not(category.job_selection[job]) category.update_selected_state() category.set_ancestors_state(category.job_selection[job]) else: node.selected = not(node.selected) node.set_descendants_state(node.selected) node.set_ancestors_state(node.selected) def _toggleNode(self): """ Expand/collapse a node """ node, is_job = self.tree.get_node_by_index(self.top + self.highlight) if not is_job: node.expanded = not(node.expanded) def _scroll(self, direction): visible_length = len(self.tree.render()) # Scroll the tree view if (direction == "up" and self.highlight == 0 and self.top != 0): self.top -= 1 return elif (direction == "down" and (self.highlight + 1) == (self.image.size.height - 4) and (self.top + self.image.size.height - 4) != visible_length): self.top += 1 return # Move the highlighted line if (direction == "up" and (self.top != 0 or self.highlight != 0)): self.highlight -= 1 elif (direction == "down" and (self.top + self.highlight + 1) != visible_length and (self.highlight + 1) != (self.image.size.height - 4)): self.highlight += 1 class CliInvocation(CheckBoxInvocationMixIn): def __init__(self, provider_list, config, settings, ns, display=None): super().__init__(provider_list, config) self.settings = settings self.display = display self.ns = ns self.whitelists = [] self._local_only = False # Only run local jobs if self.ns.whitelist: for whitelist in self.ns.whitelist: self.whitelists.append(WhiteList.from_file(whitelist.name)) elif self.config.whitelist is not Unset: self.whitelists.append(WhiteList.from_file(self.config.whitelist)) elif self.ns.include_pattern_list: self.whitelists.append(WhiteList(self.ns.include_pattern_list)) @property def is_interactive(self): """ Flag indicating that this is an interactive invocation and we can interact with the user when we encounter OUTCOME_UNDECIDED """ return (sys.stdin.isatty() and sys.stdout.isatty() and not self.ns.not_interactive) def run(self): ns = self.ns job_list = self.get_job_list(ns) previous_session_file = SessionStorageRepository().get_last_storage() resume_in_progress = False if previous_session_file: if self.is_interactive: if self.ask_for_resume(): resume_in_progress = True manager = SessionManager.load_session( job_list, previous_session_file) self._maybe_skip_last_job_after_resume(manager) else: resume_in_progress = True manager = SessionManager.load_session( job_list, previous_session_file) if not resume_in_progress: # Create a session that handles most of the stuff needed to run # jobs try: manager = SessionManager.create_with_job_list( job_list, legacy_mode=True) except DependencyDuplicateError as exc: # Handle possible DependencyDuplicateError that can happen if # someone is using plainbox for job development. print("The job database you are currently using is broken") print("At least two jobs contend for the name {0}".format( exc.job.id)) print("First job defined in: {0}".format(exc.job.origin)) print("Second job defined in: {0}".format( exc.duplicate_job.origin)) raise SystemExit(exc) manager.state.metadata.title = " ".join(sys.argv) if self.is_interactive: if self.display is None: self.display = get_display() if self.settings['welcome_text']: self.display.run( ShowWelcome(self.settings['welcome_text'])) if not self.whitelists: whitelists = [] for p in self.provider_list: if p.name in self.settings['default_providers']: whitelists.extend( [w.name for w in p.get_builtin_whitelists()]) selection = self.display.run(ShowMenu("Suite selection", whitelists)) if not selection: raise SystemExit('No whitelists selected, aborting...') for s in selection: self.whitelists.append( get_whitelist_by_name(self.provider_list, whitelists[s])) else: self.whitelists.append( get_whitelist_by_name( self.provider_list, self.settings['default_whitelist'])) manager.checkpoint() if self.is_interactive and not resume_in_progress: # Pre-run all local jobs desired_job_list = select_jobs( manager.state.job_list, [CompositeQualifier( self.whitelists + [NonLocalJobQualifier(inclusive=False)] )]) self._update_desired_job_list(manager, desired_job_list) # Ask the password before anything else in order to run local jobs # requiring privileges if self._auth_warmup_needed(manager): print("[ Authentication ]".center(80, '=')) return_code = authenticate_warmup() if return_code: raise SystemExit(return_code) self._local_only = True self._run_jobs(ns, manager) self._local_only = False if not resume_in_progress: # Run the rest of the desired jobs desired_job_list = select_jobs(manager.state.job_list, self.whitelists) self._update_desired_job_list(manager, desired_job_list) if self.is_interactive: # Ask the password before anything else in order to run jobs # requiring privileges if self._auth_warmup_needed(manager): print("[ Authentication ]".center(80, '=')) return_code = authenticate_warmup() if return_code: raise SystemExit(return_code) tree = SelectableJobTreeNode.create_tree( manager.state.run_list, legacy_mode=True) title = 'Choose tests to run on your system:' if self.display is None: self.display = get_display() self.display.run(ScrollableTreeNode(tree, title)) self._update_desired_job_list(manager, tree.selection) estimated_duration_auto, estimated_duration_manual = \ manager.state.get_estimated_duration() if estimated_duration_auto: print( "Estimated duration is {:.2f} " "for automated jobs.".format(estimated_duration_auto)) else: print( "Estimated duration cannot be " "determined for automated jobs.") if estimated_duration_manual: print( "Estimated duration is {:.2f} " "for manual jobs.".format(estimated_duration_manual)) else: print( "Estimated duration cannot be " "determined for manual jobs.") self._run_jobs(ns, manager) manager.destroy() # FIXME: sensible return value return 0 def ask_for_resume(self): return self.ask_user( "Do you want to resume the previous session?", ('y', 'n') ).lower() == "y" def ask_for_resume_action(self): return self.ask_user( "What do you want to do with that job?", ('skip', 'fail', 'run')) def ask_user(self, prompt, allowed): answer = None while answer not in allowed: answer = input("{} [{}] ".format(prompt, ", ".join(allowed))) return answer def _maybe_skip_last_job_after_resume(self, manager): last_job = manager.state.metadata.running_job_name if last_job is None: return print("We have previously tried to execute {}".format(last_job)) action = self.ask_for_resume_action() if action == 'skip': result = MemoryJobResult({ 'outcome': 'skip', 'comment': "Skipped after resuming execution" }) elif action == 'fail': result = MemoryJobResult({ 'outcome': 'fail', 'comment': "Failed after resuming execution" }) elif action == 'run': result = None if result: manager.state.update_job_result( manager.state.job_state_map[last_job].job, result) manager.state.metadata.running_job_name = None manager.checkpoint() def _run_jobs(self, ns, manager): runner = JobRunner( manager.storage.location, self.provider_list, os.path.join(manager.storage.location, 'io-logs'), command_io_delegate=self) self._run_jobs_with_session(ns, manager, runner) if not self._local_only: self.save_results(manager) def _auth_warmup_needed(self, manager): # Don't warm up plainbox-trusted-launcher-1 if none of the providers # use it. We assume that the mere presence of a provider makes it # possible for a root job to be preset but it could be improved to # actually know when this step is absolutely not required (no local # jobs, no jobs # need root) if all(not provider.secure for provider in self.provider_list): return False # Don't use authentication warm-up if none of the jobs on the run list # requires it. if all(job.user is None for job in manager.state.run_list): return False # Otherwise, do pre-authentication return True def save_results(self, manager): if self.is_interactive: print("[ Results ]".center(80, '=')) exporter = get_all_exporters()['text']() exported_stream = io.BytesIO() data_subset = exporter.get_session_data_subset(manager.state) exporter.dump(data_subset, exported_stream) exported_stream.seek(0) # Need to rewind the file, puagh # This requires a bit more finesse, as exporters output bytes # and stdout needs a string. translating_stream = ByteStringStreamTranslator( sys.stdout, "utf-8") copyfileobj(exported_stream, translating_stream) base_dir = os.path.join( os.getenv( 'XDG_DATA_HOME', os.path.expanduser("~/.local/share/")), "plainbox") if not os.path.exists(base_dir): os.makedirs(base_dir) results_file = os.path.join(base_dir, 'results.html') submission_file = os.path.join(base_dir, 'submission.xml') exporter_list = [XMLSessionStateExporter, HTMLSessionStateExporter] if 'xlsx' in get_all_exporters(): from plainbox.impl.exporter.xlsx import XLSXSessionStateExporter exporter_list.append(XLSXSessionStateExporter) # We'd like these options for our reports. exp_options = ['with-sys-info', 'with-summary', 'with-job-description', 'with-text-attachments'] for exporter_cls in exporter_list: # Exporters may support different sets of options, ensure we don't pass # an unsupported one (which would cause a crash) actual_options = [opt for opt in exp_options if opt in exporter_cls.supported_option_list] exporter = exporter_cls(actual_options) data_subset = exporter.get_session_data_subset(manager.state) results_path = results_file if exporter_cls is XMLSessionStateExporter: results_path = submission_file if 'xlsx' in get_all_exporters(): if exporter_cls is XLSXSessionStateExporter: results_path = results_path.replace('html', 'xlsx') with open(results_path, "wb") as stream: exporter.dump(data_subset, stream) print("\nSaving submission file to {}".format(submission_file)) self.submission_file = submission_file print("View results (HTML): file://{}".format(results_file)) if 'xlsx' in get_all_exporters(): print("View results (XLSX): file://{}".format( results_file.replace('html', 'xlsx'))) def _interaction_callback(self, runner, job, config, prompt=None, allowed_outcome=None): result = {} if prompt is None: prompt = "Select an outcome or an action: " if allowed_outcome is None: allowed_outcome = [IJobResult.OUTCOME_PASS, IJobResult.OUTCOME_FAIL, IJobResult.OUTCOME_SKIP] allowed_actions = ['comments'] if job.command: allowed_actions.append('test') result['outcome'] = IJobResult.OUTCOME_UNDECIDED while result['outcome'] not in allowed_outcome: print("Allowed answers are: {}".format(", ".join(allowed_outcome + allowed_actions))) choice = input(prompt) if choice in allowed_outcome: result['outcome'] = choice break elif choice == 'test': (result['return_code'], result['io_log_filename']) = runner._run_command(job, config) elif choice == 'comments': result['comments'] = input('Please enter your comments:\n') return DiskJobResult(result) def _update_desired_job_list(self, manager, desired_job_list): problem_list = manager.state.update_desired_job_list(desired_job_list) if problem_list: print("[ Warning ]".center(80, '*')) print("There were some problems with the selected jobs") for problem in problem_list: print(" * {}".format(problem)) print("Problematic jobs will not be considered") def _run_jobs_with_session(self, ns, manager, runner): # TODO: run all resource jobs concurrently with multiprocessing # TODO: make local job discovery nicer, it would be best if # desired_jobs could be managed entirely internally by SesionState. In # such case the list of jobs to run would be changed during iteration # but would be otherwise okay). if self._local_only: print("[ Loading Jobs Definition ]".center(80, '=')) else: print("[ Running All Jobs ]".center(80, '=')) again = True while again: again = False for job in manager.state.run_list: # Skip jobs that already have result, this is only needed when # we run over the list of jobs again, after discovering new # jobs via the local job output if (manager.state.job_state_map[job.id].result.outcome is not None): continue self._run_single_job_with_session(ns, manager, runner, job) manager.checkpoint() if job.plugin == "local": # After each local job runs rebuild the list of matching # jobs and run everything again desired_job_list = select_jobs(manager.state.job_list, self.whitelists) if self._local_only: desired_job_list = [ job for job in desired_job_list if job.plugin == 'local'] self._update_desired_job_list(manager, desired_job_list) again = True break def _run_single_job_with_session(self, ns, manager, runner, job): if job.plugin not in ['local', 'resource']: print("[ {} ]".format(job.tr_summary()).center(80, '-')) job_state = manager.state.job_state_map[job.id] logger.debug("Job id: %s", job.id) logger.debug("Plugin: %s", job.plugin) logger.debug("Direct dependencies: %s", job.get_direct_dependencies()) logger.debug("Resource dependencies: %s", job.get_resource_dependencies()) logger.debug("Resource program: %r", job.requires) logger.debug("Command: %r", job.command) logger.debug("Can start: %s", job_state.can_start()) logger.debug("Readiness: %s", job_state.get_readiness_description()) if job_state.can_start(): if job.plugin not in ['local', 'resource']: if job.description is not None: print(job.description) print("^" * len(job.description.splitlines()[-1])) print() print("Running... (output in {}.*)".format( join(manager.storage.location, slugify(job.id)))) manager.state.metadata.running_job_name = job.id manager.checkpoint() # TODO: get a confirmation from the user for certain types of # job.plugin job_result = runner.run_job(job, self.config) if (job_result.outcome == IJobResult.OUTCOME_UNDECIDED and self.is_interactive): job_result = self._interaction_callback( runner, job, self.config) manager.state.metadata.running_job_name = None manager.checkpoint() if job.plugin not in ['local', 'resource']: print("Outcome: {}".format(job_result.outcome)) if job_result.comments is not None: print("Comments: {}".format(job_result.comments)) else: job_result = MemoryJobResult({ 'outcome': IJobResult.OUTCOME_NOT_SUPPORTED, 'comments': job_state.get_readiness_description() }) if job.plugin not in ['local', 'resource']: print("Outcome: {}".format(job_result.outcome)) if job_result is not None: manager.state.update_job_result(job, job_result) class CliCommand(PlainBoxCommand, CheckBoxCommandMixIn): """ Command for running tests using the command line UI. """ def __init__(self, provider_list, config, settings): self.provider_list = provider_list self.config = config self.settings = settings def invoked(self, ns): # Run check-config, if requested if ns.check_config: retval = CheckConfigInvocation(self.config).run() return retval return CliInvocation(self.provider_list, self.config, self.settings, ns).run() def register_parser(self, subparsers): parser = subparsers.add_parser(self.settings['subparser_name'], help=self.settings['subparser_help']) parser.set_defaults(command=self) parser.add_argument( "--check-config", action="store_true", help="Run check-config") parser.add_argument( '--not-interactive', action='store_true', help="Skip tests that require interactivity") # Call enhance_parser from CheckBoxCommandMixIn self.enhance_parser(parser) checkbox-ng-0.3/checkbox_ng/test_certification.py0000664000175000017500000001531112320607367022231 0ustar zygazyga00000000000000# This file is part of Checkbox. # # Copyright 2012, 2013 Canonical Ltd. # Written by: # Zygmunt Krynicki # Daniel Manrique # # Checkbox is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License version 3, # as published by the Free Software Foundation. # # Checkbox is distributed in the hope that 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 Checkbox. If not, see . """ plainbox.impl.transport.test_certification ========================================== Test definitions for plainbox.impl.certification module """ from io import BytesIO from unittest import TestCase from pkg_resources import resource_string from plainbox.impl.applogic import PlainBoxConfig from plainbox.impl.transport import TransportError from plainbox.vendor import mock from plainbox.vendor.mock import MagicMock from requests.exceptions import ConnectionError, InvalidSchema, HTTPError import requests from checkbox_ng.certification import CertificationTransport from checkbox_ng.certification import InvalidSecureIDError class CertificationTransportTests(TestCase): #URL are just here to exemplify, since we mock away all network access, #they're not really used. valid_url = "https://certification.canonical.com/submissions/submit" invalid_url = "htz://:3128" unreachable_url = "http://i.dont.exist" valid_secure_id = "a00D000000Kkk5j" valid_option_string = "secure_id={}".format(valid_secure_id) def setUp(self): self.sample_xml = BytesIO(resource_string( "plainbox", "test-data/xml-exporter/example-data.xml" )) self.patcher = mock.patch('requests.post') self.mock_requests = self.patcher.start() def test_parameter_parsing(self): #Makes sense since I'm overriding the base class's constructor. transport = CertificationTransport( self.valid_url, self.valid_option_string) self.assertEqual(self.valid_url, transport.url) self.assertEqual(self.valid_secure_id, transport.options['secure_id']) def test_invalid_length_secure_id_are_rejected(self): for length in (14, 16, 20): dummy_id = "a" * length option_string = "secure_id={}".format(dummy_id) with self.assertRaises(InvalidSecureIDError): CertificationTransport(self.valid_url, option_string) def test_invalid_characters_in_secure_id_are_rejected(self): option_string = "secure_id=aA0#" with self.assertRaises(InvalidSecureIDError): CertificationTransport(self.valid_url, option_string) def test_invalid_url(self): transport = CertificationTransport( self.invalid_url, self.valid_option_string) dummy_data = BytesIO(b"some data to send") requests.post.side_effect = InvalidSchema with self.assertRaises(TransportError): result = transport.send(dummy_data) self.assertIsNotNone(result) requests.post.assert_called_with( self.invalid_url, files={'data': dummy_data}, headers={'X_HARDWARE_ID': self.valid_secure_id}, proxies=None) def test_valid_url_cant_connect(self): transport = CertificationTransport( self.unreachable_url, self.valid_option_string) dummy_data = BytesIO(b"some data to send") requests.post.side_effect = ConnectionError with self.assertRaises(TransportError): result = transport.send(dummy_data) self.assertIsNotNone(result) requests.post.assert_called_with(self.unreachable_url, files={'data': dummy_data}, headers={'X_HARDWARE_ID': self.valid_secure_id}, proxies=None) def test_send_success(self): transport = CertificationTransport( self.valid_url, self.valid_option_string) requests.post.return_value = MagicMock(name='response') requests.post.return_value.status_code = 200 requests.post.return_value.text = '{"id": 768}' result = transport.send(self.sample_xml) self.assertTrue(result) def test_send_failure(self): transport = CertificationTransport( self.valid_url, self.valid_option_string) requests.post.return_value = MagicMock(name='response') requests.post.return_value.status_code = 412 requests.post.return_value.text = 'Some error' #Oops, raise_for_status doesn't get fooled by my mocking, #so I have to mock *that* method as well.. requests.post.return_value.raise_for_status = MagicMock( side_effect=HTTPError) with self.assertRaises(TransportError): transport.send(self.sample_xml) def proxy_test(self, environment, proxies): test_environment = environment test_proxies = proxies test_config = PlainBoxConfig() test_config.environment = test_environment transport = CertificationTransport( self.valid_url, self.valid_option_string) dummy_data = BytesIO(b"some data to send") requests.post.return_value = MagicMock(name='response') requests.post.return_value.status_code = 200 requests.post.return_value.text = '{"id": 768}' result = transport.send(dummy_data, config=test_config) self.assertTrue(result) requests.post.assert_called_with( self.valid_url, files={'data': dummy_data}, headers={'X_HARDWARE_ID': self.valid_secure_id}, proxies=test_proxies) def test_set_only_one_proxy(self): test_environment = {'http_proxy': "http://1.2.3.4:5"} test_proxies = {'http': "http://1.2.3.4:5"} self.proxy_test(test_environment, test_proxies) def test_set_two_proxies(self): test_environment = {'http_proxy': "http://1.2.3.4:5", 'https_proxy': "http://1.2.3.4:6"} test_proxies = {'http': "http://1.2.3.4:5", 'https': "http://1.2.3.4:6"} self.proxy_test(test_environment, test_proxies) def test_behavior_with_extraneous_environment(self): test_environment = {'http_proxy': "http://1.2.3.4:5", 'weird_value': 'What is this'} test_proxies = {'http': "http://1.2.3.4:5"} self.proxy_test(test_environment, test_proxies) checkbox-ng-0.3/checkbox_ng/config.py0000664000175000017500000001046612320607367017622 0ustar zygazyga00000000000000# This file is part of Checkbox. # # Copyright 2013 Canonical Ltd. # Written by: # Zygmunt Krynicki # # Checkbox is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License version 3, # as published by the Free Software Foundation. # # Checkbox is distributed in the hope that 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 Checkbox. If not, see . """ :mod:`checkbox_ng.config` -- CheckBoxNG configuration ===================================================== """ import os import itertools from plainbox.impl.applogic import PlainBoxConfig from plainbox.impl.secure import config SECURE_ID_PATTERN =r"^[a-zA-Z0-9]{15}$|^[a-zA-Z0-9]{18}$" class CheckBoxConfig(PlainBoxConfig): """ Configuration for checkbox-ng """ secure_id = config.Variable( section="sru", help_text="Secure ID of the system", validator_list=[config.PatternValidator(SECURE_ID_PATTERN)]) # TODO: Add a validator to check if URL looks fine c3_url = config.Variable( section="sru", help_text="URL of the certification website", default="https://certification.canonical.com/submissions/submit/") fallback_file = config.Variable( section="sru", help_text="Location of the fallback file") whitelist = config.Variable( section="sru", help_text="Optional whitelist with which to run SRU testing") class Meta(PlainBoxConfig.Meta): # TODO: properly depend on xdg and use real code that also handles # XDG_CONFIG_HOME. # # NOTE: filename_list is composed of checkbox and plainbox variables, # mixed so that: # - checkbox takes precedence over plainbox # - ~/.config takes precedence over /etc filename_list = list( itertools.chain( *zip( PlainBoxConfig.Meta.filename_list, ( '/etc/xdg/checkbox.conf', os.path.expanduser('~/.config/checkbox.conf'))))) class CertificationConfig(CheckBoxConfig): """ Configuration for canonical-certification """ class Meta(CheckBoxConfig.Meta): # TODO: properly depend on xdg and use real code that also handles # XDG_CONFIG_HOME. # # NOTE: filename_list is composed of canonical-certification, checkbox # and plainbox variables, mixed so that: # - canonical-certification takes precedence over checkbox # - checkbox takes precedence over plainbox # - ~/.config takes precedence over /etc filename_list = list( itertools.chain( *zip( itertools.islice( CheckBoxConfig.Meta.filename_list, 0, None, 2), itertools.islice( CheckBoxConfig.Meta.filename_list, 1, None, 2), ('/etc/xdg/canonical-certification.conf', os.path.expanduser( '~/.config/canonical-certification.conf'))))) class CDTSConfig(CheckBoxConfig): """ Configuration for canonical-driver-test-suite (CDTS) """ class Meta(CheckBoxConfig.Meta): # TODO: properly depend on xdg and use real code that also handles # XDG_CONFIG_HOME. # # NOTE: filename_list is composed of canonical-certification, checkbox # and plainbox variables, mixed so that: # - CDTS takes precedence over checkbox # - checkbox takes precedence over plainbox # - ~/.config takes precedence over /etc filename_list = list( itertools.chain( *zip( itertools.islice( CheckBoxConfig.Meta.filename_list, 0, None, 2), itertools.islice( CheckBoxConfig.Meta.filename_list, 1, None, 2), ('/etc/xdg/canonical-driver-test-suite.conf', os.path.expanduser( '~/.config/canonical-driver-test-suite.conf'))))) checkbox-ng-0.3/checkbox_ng/dbus_ex/0000775000175000017500000000000012320610512017407 5ustar zygazyga00000000000000checkbox-ng-0.3/checkbox_ng/dbus_ex/__init__.py0000664000175000017500000000315612320607367021543 0ustar zygazyga00000000000000# This file is part of Checkbox. # # Copyright 2013 Canonical Ltd. # Written by: # Zygmunt Krynicki # # Checkbox is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License version 3, # as published by the Free Software Foundation. # # Checkbox is distributed in the hope that 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 Checkbox. If not, see . """ :mod:`checkbox_ng.dbus_ex` -- DBus Extensions ============================================= """ __all__ = [ 'service', 'exceptions', 'Signature', 'Struct', 'types', 'INTROSPECTABLE_IFACE', 'PEER_IFACE', 'PROPERTIES_IFACE', 'OBJECT_MANAGER_IFACE', ] import re from dbus import INTROSPECTABLE_IFACE from dbus import PEER_IFACE from dbus import PROPERTIES_IFACE from dbus import Signature from dbus import Struct from dbus import exceptions from dbus import types OBJECT_MANAGER_IFACE = "org.freedesktop.DBus.ObjectManager" from checkbox_ng.dbus_ex import service def mangle_object_path(path): """ "Mangles" the provided candidate dbus object path to ensure it complies with the dbus specification. Returns the mangled path. """ # TODO: It just enforces the valid characters rule, not the rest of the # DBus path construction rules return re.sub(r"[^a-zA-Z0-9_/]", "_", path) checkbox-ng-0.3/checkbox_ng/dbus_ex/service.py0000664000175000017500000006060212320607367021443 0ustar zygazyga00000000000000# This file is part of Checkbox. # # Copyright 2013 Canonical Ltd. # Written by: # Zygmunt Krynicki # # Checkbox is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License version 3, # as published by the Free Software Foundation. # # Checkbox is distributed in the hope that 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 Checkbox. If not, see . """ :mod:`plainbox.impl.dbus_ex.service` -- DBus Service Extensions =============================================================== """ import logging import threading import weakref from plainbox.impl.signal import Signal import _dbus_bindings import dbus import dbus.exceptions import dbus.service from checkbox_ng.dbus_ex import INTROSPECTABLE_IFACE from checkbox_ng.dbus_ex import OBJECT_MANAGER_IFACE from checkbox_ng.dbus_ex import PROPERTIES_IFACE # Note: use our own version of the decorators because # vanilla versions choke on annotations from checkbox_ng.dbus_ex.decorators import method, signal # This is the good old standard python property decorator _property = property __all__ = [ 'Interface', 'Object', 'method', 'property', 'signal', ] logger = logging.getLogger("checkbox.ng.dbus_ex") class InterfaceType(dbus.service.InterfaceType): """ Subclass of :class:`dbus.service.InterfaceType` that also handles properties. """ def _reflect_on_property(cls, func): reflection_data = ( ' \n').format( func._dbus_property, func._signature, func.dbus_access_flag) return reflection_data #Subclass of :class:`dbus.service.Interface` that also handles properties Interface = InterfaceType('Interface', (dbus.service.Interface,), {}) class property: """ property that handles DBus stuff """ def __init__(self, signature, dbus_interface, dbus_property=None, setter=False): """ Initialize new dbus_property with the given interface name. If dbus_property is not specified it is set to the name of the decorated method. In special circumstances you may wish to specify alternate dbus property name explicitly. If setter is set to True then the implicit decorated function is a setter, not the default getter. This allows to define write-only properties. """ self.__name__ = None self.__doc__ = None self._signature = signature self._dbus_interface = dbus_interface self._dbus_property = dbus_property self._getf = None self._setf = None self._implicit_setter = setter def __repr__(self): return "".format(self.__name__) @_property def dbus_access_flag(self): """ access flag of this DBus property :returns: either "readwrite", "read" or "write" :raises TypeError: if the property is ill-defined """ if self._getf and self._setf: return "readwrite" elif self._getf: return "read" elif self._setf: return "write" else: raise TypeError( "property provides neither readable nor writable") @_property def dbus_interface(self): """ name of the DBus interface of this DBus property """ return self._dbus_interface @_property def dbus_property(self): """ name of this DBus property """ return self._dbus_property @_property def signature(self): """ signature of this DBus property """ return self._signature @_property def setter(self): """ decorator for setter functions This property can be used to decorate additional method that will be used as a property setter. Otherwise properties cannot be assigned. """ def decorator(func): self._setf = func return self return decorator @_property def getter(self): """ decorator for getter functions This property can be used to decorate additional method that will be used as a property getter. It is only provider for parity as by default, the @dbus.service.property() decorator designates a getter function. This behavior can be controlled by passing setter=True to the property initializer. """ def decorator(func): self._getf = func return self return decorator def __call__(self, func): """ Decorate a getter function and return the property object This method sets __name__, __doc__ and _dbus_property. """ self.__name__ = func.__name__ if self.__doc__ is None: self.__doc__ = func.__doc__ if self._dbus_property is None: self._dbus_property = func.__name__ if self._implicit_setter: return self.setter(func) else: return self.getter(func) def __get__(self, instance, owner): if instance is None: return self else: if self._getf is None: raise dbus.exceptions.DBusException( "property is not readable") return self._getf(instance) def __set__(self, instance, value): if self._setf is None: raise dbus.exceptions.DBusException( "property is not writable") self._setf(instance, value) # This little helper is here is to help :meth:`Object.Introspect()` # figure out how to handle properties. _dbus_is_property = True class Object(Interface, dbus.service.Object): """ dbus.service.Object subclass that providers additional features. This class providers the following additional features: * Implementation of the PROPERTIES_IFACE. This includes the methods Get(), Set(), GetAll() and the signal PropertiesChanged() * Implementation of the OBJECT_MANAGER_IFACE. This includes the method GetManagedObjects() and signals InterfacesAdded() and InterfacesRemoved(). * Tracking of object-path-to-object association using the new :meth:`find_object_by_path()` method * Selective activation of any of the above interfaces using :meth:`should_expose_interface()` method. * Improved version of the INTROSPECTABLE_IFACE that understands properties """ def __init__(self, conn=None, object_path=None, bus_name=None): dbus.service.Object.__init__(self, conn, object_path, bus_name) self._managed_object_list = [] # [ Public DBus methods of the INTROSPECTABLE_IFACE interface ] @method( dbus_interface=INTROSPECTABLE_IFACE, in_signature='', out_signature='s', path_keyword='object_path', connection_keyword='connection') def Introspect(self, object_path, connection): """ Return a string of XML encoding this object's supported interfaces, methods and signals. """ logger.debug("Introspect(object_path=%r)", object_path) reflection_data = ( _dbus_bindings.DBUS_INTROSPECT_1_0_XML_DOCTYPE_DECL_NODE) reflection_data += '\n' % object_path interfaces = self._dct_entry for (name, funcs) in interfaces.items(): # Allow classes to ignore certain interfaces This is useful because # this class implements all kinds of methods internally (for # simplicity) but does not really advertise them all directly # unless asked to. if not self.should_expose_interface(name): continue reflection_data += ' \n' % (name) for func in funcs.values(): if getattr(func, '_dbus_is_method', False): reflection_data += self.__class__._reflect_on_method(func) elif getattr(func, '_dbus_is_signal', False): reflection_data += self.__class__._reflect_on_signal(func) elif getattr(func, '_dbus_is_property', False): reflection_data += ( self.__class__._reflect_on_property(func)) reflection_data += ' \n' for name in connection.list_exported_child_objects(object_path): reflection_data += ' \n' % name reflection_data += '\n' logger.debug("Introspect() returns: %s", reflection_data) return reflection_data # [ Public DBus methods of the PROPERTIES_IFACE interface ] @dbus.service.method( dbus_interface=dbus.PROPERTIES_IFACE, in_signature="ss", out_signature="v") def Get(self, interface_name, property_name): """ Get the value of a property @property_name on interface @interface_name. """ logger.debug( "%r.Get(%r, %r) -> ...", self, interface_name, property_name) try: props = self._dct_entry[interface_name] except KeyError: raise dbus.exceptions.DBusException( dbus.PROPERTIES_IFACE, "No such interface {}".format(interface_name)) try: prop = props[property_name] except KeyError: raise dbus.exceptions.DBusException( dbus.PROPERTIES_IFACE, "No such property {}:{}".format( interface_name, property_name)) try: value = prop.__get__(self, self.__class__) except dbus.exceptions.DBusException as exc: logger.error( "%r.Get(%r, %r) -> (exception) %r", self, interface_name, property_name, exc) raise except Exception as exc: logger.exception( "runaway exception from Get(%r, %r)", interface_name, property_name) raise dbus.exceptions.DBusException( dbus.PROPERTIES_IFACE, "Unable to get property interface/property {}:{}: {!r}".format( interface_name, property_name, exc)) else: logger.debug( "%r.Get(%r, %r) -> %r", self, interface_name, property_name, value) return value @dbus.service.method( dbus_interface=dbus.PROPERTIES_IFACE, in_signature="ssv", out_signature="") def Set(self, interface_name, property_name, value): logger.debug( "%r.Set(%r, %r, %r) -> ...", self, interface_name, property_name, value) try: props = self._dct_entry[interface_name] except KeyError: raise dbus.exceptions.DBusException( dbus.PROPERTIES_IFACE, "No such interface {}".format(interface_name)) try: # Map the real property name prop = { prop.dbus_property: prop for prop in props.values() if isinstance(prop, property) }[property_name] if not isinstance(prop, property): raise KeyError(property_name) except KeyError: raise dbus.exceptions.DBusException( dbus.PROPERTIES_IFACE, "No such property {}:{}".format( interface_name, property_name)) try: prop.__set__(self, value) except dbus.exceptions.DBusException: raise except Exception as exc: logger.exception( "runaway exception from %r.Set(%r, %r, %r)", self, interface_name, property_name, value) raise dbus.exceptions.DBusException( dbus.PROPERTIES_IFACE, "Unable to set property {}:{}: {!r}".format( interface_name, property_name, exc)) logger.debug( "%r.Set(%r, %r, %r) -> None", self, interface_name, property_name, value) @dbus.service.method( dbus_interface=dbus.PROPERTIES_IFACE, in_signature="s", out_signature="a{sv}") def GetAll(self, interface_name): logger.debug("%r.GetAll(%r)", self, interface_name) try: props = self._dct_entry[interface_name] except KeyError: raise dbus.exceptions.DBusException( dbus.PROPERTIES_IFACE, "No such interface {}".format(interface_name)) result = {} for prop in props.values(): if not isinstance(prop, property): continue prop_name = prop.dbus_property try: prop_value = prop.__get__(self, self.__class__) except: logger.exception( "Unable to read property %r from %r", prop, self) else: result[prop_name] = prop_value return result @dbus.service.signal( dbus_interface=dbus.PROPERTIES_IFACE, signature='sa{sv}as') def PropertiesChanged( self, interface_name, changed_properties, invalidated_properties): logger.debug( "PropertiesChanged(%r, %r, %r)", interface_name, changed_properties, invalidated_properties) # [ Public DBus methods of the OBJECT_MANAGER_IFACE interface ] @dbus.service.method( dbus_interface=OBJECT_MANAGER_IFACE, in_signature="", out_signature="a{oa{sa{sv}}}") def GetManagedObjects(self): logger.debug("%r.GetManagedObjects() -> ...", self) result = {} for obj in self._managed_object_list: logger.debug("Looking for stuff exported by %r", obj) result[obj] = {} for iface_name in obj._dct_entry.keys(): props = obj.GetAll(iface_name) if len(props): result[obj][iface_name] = props logger.debug("%r.GetManagedObjects() -> %r", self, result) return result @dbus.service.signal( dbus_interface=OBJECT_MANAGER_IFACE, signature='oa{sa{sv}}') def InterfacesAdded(self, object_path, interfaces_and_properties): logger.debug("%r.InterfacesAdded(%r, %r)", self, object_path, interfaces_and_properties) @dbus.service.signal( dbus_interface=OBJECT_MANAGER_IFACE, signature='oas') def InterfacesRemoved(self, object_path, interfaces): logger.debug("%r.InterfacesRemoved(%r, %r)", self, object_path, interfaces) # [ Overridden methods of dbus.service.Object ] def add_to_connection(self, connection, path): """ Version of dbus.service.Object.add_to_connection() that keeps track of all object paths. """ with self._object_path_map_lock: # Super-call add_to_connection(). This can fail which is # okay as we haven't really modified anything yet. super(Object, self).add_to_connection(connection, path) # Touch self.connection, this will fail if the call above failed # and self._connection (mind the leading underscore) is still None. # It will also fail if the object is being exposed on multiple # connections (so self._connection is _MANY). We are interested in # the second check as _MANY connections are not supported here. self.connection # If everything is okay, just add the specified path to the # _object_path_to_object_map. self._object_path_to_object_map[path] = self def remove_from_connection(self, connection=None, path=None): with self._object_path_map_lock: # Touch self.connection, this triggers a number of interesting # checks, in particular checks for self._connection (mind the # leading underscore) being _MANY or being None. Both of those # throw an AttributeError that we can simply propagate at this # point. self.connection # Create a copy of locations. This is required because locations # are modified by remove_from_connection() which can also fail. If # we were to use self.locations here directly we would have to undo # any changes if remove_from_connection() raises an exception. # Instead it is easier to first super-call remove_from_connection() # and then do what we need to at this layer, after # remove_from_connection() finishes successfully. locations_copy = list(self.locations) # Super-call remove_from_connection() super(Object, self).remove_from_connection(connection, path) # If either path or connection are none then treat them like # match-any wild-cards. The same logic is implemented in the # superclass version of this method. if path is None or connection is None: # Location is a tuple of at least two elements, connection and # path. There may be other elements added later so let's not # assume this is a simple pair. for location in locations_copy: location_conn = location[0] location_path = location[1] # If (connection matches or is None) # and (path matches or is None) # then remove that association if ((location_conn == connection or connection is None) and (path == location_path or path is None)): del self._object_path_to_object_map[location_path] else: # If connection and path were specified, just remove the # association from the specified path. del self._object_path_to_object_map[path] # [ Custom Extension Methods ] def should_expose_interface(self, iface_name): """ Check if the specified interface should be exposed. This method controls which of the interfaces are visible as implemented by this Object. By default objects don't implement any interface expect for PEER_IFACE. There are two more interfaces that are implemented internally but need to be explicitly exposed: the PROPERTIES_IFACE and OBJECT_MANAGER_IFACE. Typically subclasses should NOT override this method, instead subclasses should define class-scope HIDDEN_INTERFACES as a frozenset() of classes to hide and remove one of the entries found in _STD_INTERFACES from it to effectively enable that interface. """ return iface_name not in self.HIDDEN_INTERFACES @classmethod def find_object_by_path(cls, object_path): """ Find and return the object that is exposed as object_path on any connection. Using multiple connections is not supported at this time. .. note:: This obviously only works for objects exposed from the same application. The main use case is to have a way to lookup object paths that may be passed as arguments and also originate in the same application. """ # XXX: ideally this would be per-connection method. with cls._object_path_map_lock: return cls._object_path_to_object_map[object_path] @_property def managed_objects(self): """ list of of managed objects. This collection is a part of the OBJECT_MANAGER_IFACE. While it can be manipulated directly (technically) it should only be manipulated using :meth:`add_managed_object()`, :meth:`add_manage_object_list()`, :meth:`remove_managed_object()` and :meth:`remove_managed_object_list()` as they send appropriate DBus signals. """ return self._managed_object_list def add_managed_object(self, obj): self.add_managed_object_list([obj]) def remove_managed_object(self, obj): self.remove_managed_object_list([obj]) def add_managed_object_list(self, obj_list): logger.debug("Adding managed objects: %s", obj_list) for obj in obj_list: if not isinstance(obj, Object): raise TypeError("obj must be of type {!r}".format(Object)) old = self._managed_object_list new = list(old) new.extend(obj_list) self._managed_object_list = new self._on_managed_objects_changed(old, new) def remove_managed_object_list(self, obj_list): logger.debug("Removing managed objects: %s", obj_list) for obj in obj_list: if not isinstance(obj, Object): raise TypeError("obj must be of type {!r}".format(Object)) old = self._managed_object_list new = list(old) for obj in obj_list: new.remove(obj) self._managed_object_list = new self._on_managed_objects_changed(old, new) # [ Custom Private Implementation Data ] _STD_INTERFACES = frozenset([ INTROSPECTABLE_IFACE, OBJECT_MANAGER_IFACE, # TODO: peer interface is not implemented in this class # PEER_IFACE, PROPERTIES_IFACE ]) HIDDEN_INTERFACES = frozenset([ OBJECT_MANAGER_IFACE, PROPERTIES_IFACE ]) # Lock protecting access to _object_path_to_object_map. # XXX: ideally this would be a per-connection attribute _object_path_map_lock = threading.Lock() # Map of object_path -> dbus.service.Object instances # XXX: ideally this would be a per-connection attribute _object_path_to_object_map = weakref.WeakValueDictionary() # [ Custom Private Implementation Methods ] @_property def _dct_key(self): """ the key indexing this Object in Object.__class__._dbus_class_table """ return self.__class__.__module__ + '.' + self.__class__.__name__ @_property def _dct_entry(self): """ same as self.__class__._dbus_class_table[self._dct_key] """ return self.__class__._dbus_class_table[self._dct_key] @Signal.define def _on_managed_objects_changed(self, old_objs, new_objs): logger.debug("%r._on_managed_objects_changed(%r, %r)", self, old_objs, new_objs) for obj in frozenset(new_objs) - frozenset(old_objs): ifaces_and_props = {} for iface_name in obj._dct_entry.keys(): try: props = obj.GetAll(iface_name) except dbus.exceptions.DBusException as exc: logger.warning("Caught %r", exc) else: ifaces_and_props[iface_name] = props self.InterfacesAdded(obj.__dbus_object_path__, ifaces_and_props) for obj in frozenset(old_objs) - frozenset(new_objs): ifaces = list(obj._dct_entry.keys()) self.InterfacesRemoved(obj.__dbus_object_path__, ifaces) class ObjectWrapper(Object): """ Wrapper for a single python object which makes it easier to expose over DBus as a service. The object should be injected into something that extends dbus.service.Object class. The class maintains an association between each wrapper and native object and offers methods for converting between the two. """ # Lock protecting access to _native_id_to_wrapper_map _native_id_map_lock = threading.Lock() # Man of id(wrapper.native) -> wrapper _native_id_to_wrapper_map = weakref.WeakValueDictionary() def __init__(self, native, conn=None, object_path=None, bus_name=None): """ Create a new wrapper for the specified native object """ super(ObjectWrapper, self).__init__(conn, object_path, bus_name) with self._native_id_map_lock: self._native_id_to_wrapper_map[id(native)] = self self._native = native @_property def native(self): """ native python object being wrapped by this wrapper """ return self._native @classmethod def find_wrapper_by_native(cls, native): """ Find the wrapper associated with the specified native object """ with cls._native_id_map_lock: return cls._native_id_to_wrapper_map[id(native)] checkbox-ng-0.3/checkbox_ng/dbus_ex/test_dbus.py0000664000175000017500000000303512320607367021774 0ustar zygazyga00000000000000# This file is part of Checkbox. # # Copyright 2012, 2013 Canonical Ltd. # Written by: # # Daniel Manrique # # Checkbox is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License version 3, # as published by the Free Software Foundation. # # Checkbox is distributed in the hope that 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 Checkbox. If not, see . """ checkbox_ng.dbus_ex.test_dbus ============================= Test definitions for checkbox_ng.dbus_ex module """ import re from plainbox.testing_utils.testcases import TestCaseWithParameters from checkbox_ng.dbus_ex import mangle_object_path class TestManglePath(TestCaseWithParameters): parameter_names = ('dbus_path',) parameter_values = ( ('/plainbox/whitelist/some-bogus.whitelist', ), ('/plainbox/provider/2013.com.example:test-provider', )) def setUp(self): # Note this regex fails to capture the root ("/") dbus path, not # a problem in this use case though. self.dbus_regex = re.compile(r'^/([a-zA-Z0-9_]+/)+([a-zA-Z0-9_]+)$') def test_mangle_path(self): mangled_path = mangle_object_path(self.parameters.dbus_path) self.assertTrue(self.dbus_regex.match(mangled_path), mangled_path) checkbox-ng-0.3/checkbox_ng/dbus_ex/decorators.py0000664000175000017500000003665112320607367022157 0ustar zygazyga00000000000000"""Service-side D-Bus decorators.""" # Copyright (C) 2003, 2004, 2005, 2006 Red Hat Inc. # Copyright (C) 2003 David Zeuthen # Copyright (C) 2004 Rob Taylor # Copyright (C) 2005, 2006 Collabora Ltd. # # Permission is hereby granted, free of charge, to any person # obtaining a copy of this software and associated documentation # files (the "Software"), to deal in the Software without # restriction, including without limitation the rights to use, copy, # modify, merge, publish, distribute, sublicense, and/or sell copies # of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT # HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER # DEALINGS IN THE SOFTWARE. __all__ = ('method', 'signal') __docformat__ = 'restructuredtext' import functools import inspect import logging from dbus import validate_interface_name, Signature, validate_member_name from dbus.lowlevel import SignalMessage from dbus.exceptions import DBusException from dbus._compat import is_py2 _logger = logging.getLogger('checkbox.ng.dbus_ex.decorators') def method(dbus_interface, in_signature=None, out_signature=None, async_callbacks=None, sender_keyword=None, path_keyword=None, destination_keyword=None, message_keyword=None, connection_keyword=None, byte_arrays=False, rel_path_keyword=None, **kwargs): """Factory for decorators used to mark methods of a `dbus.service.Object` to be exported on the D-Bus. The decorated method will be exported over D-Bus as the method of the same name on the given D-Bus interface. :Parameters: `dbus_interface` : str Name of a D-Bus interface `in_signature` : str or None If not None, the signature of the method parameters in the usual D-Bus notation `out_signature` : str or None If not None, the signature of the return value in the usual D-Bus notation `async_callbacks` : tuple containing (str,str), or None If None (default) the decorated method is expected to return values matching the `out_signature` as usual, or raise an exception on error. If not None, the following applies: `async_callbacks` contains the names of two keyword arguments to the decorated function, which will be used to provide a success callback and an error callback (in that order). When the decorated method is called via the D-Bus, its normal return value will be ignored; instead, a pair of callbacks are passed as keyword arguments, and the decorated method is expected to arrange for one of them to be called. On success the success callback must be called, passing the results of this method as positional parameters in the format given by the `out_signature`. On error the decorated method may either raise an exception before it returns, or arrange for the error callback to be called with an Exception instance as parameter. `sender_keyword` : str or None If not None, contains the name of a keyword argument to the decorated function, conventionally ``'sender'``. When the method is called, the sender's unique name will be passed as this keyword argument. `path_keyword` : str or None If not None (the default), the decorated method will receive the destination object path as a keyword argument with this name. Normally you already know the object path, but in the case of "fallback paths" you'll usually want to use the object path in the method's implementation. For fallback objects, `rel_path_keyword` (new in 0.82.2) is likely to be more useful. :Since: 0.80.0? `rel_path_keyword` : str or None If not None (the default), the decorated method will receive the destination object path, relative to the path at which the object was exported, as a keyword argument with this name. For non-fallback objects the relative path will always be '/'. :Since: 0.82.2 `destination_keyword` : str or None If not None (the default), the decorated method will receive the destination bus name as a keyword argument with this name. Included for completeness - you shouldn't need this. :Since: 0.80.0? `message_keyword` : str or None If not None (the default), the decorated method will receive the `dbus.lowlevel.MethodCallMessage` as a keyword argument with this name. :Since: 0.80.0? `connection_keyword` : str or None If not None (the default), the decorated method will receive the `dbus.connection.Connection` as a keyword argument with this name. This is generally only useful for objects that are available on more than one connection. :Since: 0.82.0 `utf8_strings` : bool If False (default), D-Bus strings are passed to the decorated method as objects of class dbus.String, a unicode subclass. If True, D-Bus strings are passed to the decorated method as objects of class dbus.UTF8String, a str subclass guaranteed to be encoded in UTF-8. This option does not affect object-paths and signatures, which are always 8-bit strings (str subclass) encoded in ASCII. :Since: 0.80.0 `byte_arrays` : bool If False (default), a byte array will be passed to the decorated method as an `Array` (a list subclass) of `Byte` objects. If True, a byte array will be passed to the decorated method as a `ByteArray`, a str subclass. This is usually what you want, but is switched off by default to keep dbus-python's API consistent. :Since: 0.80.0 """ validate_interface_name(dbus_interface) def decorator(func): # If the function is decorated and uses @functools.wrapper then use the # __wrapped__ attribute to look at the original function signature. # # This allows us to see past the generic *args, **kwargs seen on most decorators. if hasattr(func, '__wrapped__'): args = inspect.getfullargspec(func.__wrapped__)[0] else: args = inspect.getfullargspec(func)[0] args.pop(0) if async_callbacks: if type(async_callbacks) != tuple: raise TypeError('async_callbacks must be a tuple of (keyword for return callback, keyword for error callback)') if len(async_callbacks) != 2: raise ValueError('async_callbacks must be a tuple of (keyword for return callback, keyword for error callback)') args.remove(async_callbacks[0]) args.remove(async_callbacks[1]) if sender_keyword: args.remove(sender_keyword) if rel_path_keyword: args.remove(rel_path_keyword) if path_keyword: args.remove(path_keyword) if destination_keyword: args.remove(destination_keyword) if message_keyword: args.remove(message_keyword) if connection_keyword: args.remove(connection_keyword) if in_signature: in_sig = tuple(Signature(in_signature)) if len(in_sig) > len(args): raise ValueError('input signature is longer than the number of arguments taken') elif len(in_sig) < len(args): raise ValueError('input signature is shorter than the number of arguments taken') func._dbus_is_method = True func._dbus_async_callbacks = async_callbacks func._dbus_interface = dbus_interface func._dbus_in_signature = in_signature func._dbus_out_signature = out_signature func._dbus_sender_keyword = sender_keyword func._dbus_path_keyword = path_keyword func._dbus_rel_path_keyword = rel_path_keyword func._dbus_destination_keyword = destination_keyword func._dbus_message_keyword = message_keyword func._dbus_connection_keyword = connection_keyword func._dbus_args = args func._dbus_get_args_options = dict(byte_arrays=byte_arrays) if is_py2: func._dbus_get_args_options['utf8_strings'] = kwargs.get( 'utf8_strings', False) elif 'utf8_strings' in kwargs: raise TypeError("unexpected keyword argument 'utf8_strings'") @functools.wraps(func) def sanity(*args, **kwargs): try: return func(*args, **kwargs) except DBusException: raise except Exception: _logger.exception("DBus method call failed") raise return sanity return decorator def signal(dbus_interface, signature=None, path_keyword=None, rel_path_keyword=None): """Factory for decorators used to mark methods of a `dbus.service.Object` to emit signals on the D-Bus. Whenever the decorated method is called in Python, after the method body is executed, a signal with the same name as the decorated method, with the given D-Bus interface, will be emitted from this object. :Parameters: `dbus_interface` : str The D-Bus interface whose signal is emitted `signature` : str The signature of the signal in the usual D-Bus notation `path_keyword` : str or None A keyword argument to the decorated method. If not None, that argument will not be emitted as an argument of the signal, and when the signal is emitted, it will appear to come from the object path given by the keyword argument. Note that when calling the decorated method, you must always pass in the object path as a keyword argument, not as a positional argument. This keyword argument cannot be used on objects where the class attribute ``SUPPORTS_MULTIPLE_OBJECT_PATHS`` is true. :Deprecated: since 0.82.0. Use `rel_path_keyword` instead. `rel_path_keyword` : str or None A keyword argument to the decorated method. If not None, that argument will not be emitted as an argument of the signal. When the signal is emitted, if the named keyword argument is given, the signal will appear to come from the object path obtained by appending the keyword argument to the object's object path. This is useful to implement "fallback objects" (objects which own an entire subtree of the object-path tree). If the object is available at more than one object-path on the same or different connections, the signal will be emitted at an appropriate object-path on each connection - for instance, if the object is exported at /abc on connection 1 and at /def and /x/y/z on connection 2, and the keyword argument is /foo, then signals will be emitted from /abc/foo and /def/foo on connection 1, and /x/y/z/foo on connection 2. :Since: 0.82.0 """ validate_interface_name(dbus_interface) if path_keyword is not None: from warnings import warn warn(DeprecationWarning('dbus.service.signal::path_keyword has been ' 'deprecated since dbus-python 0.82.0, and ' 'will not work on objects that support ' 'multiple object paths'), DeprecationWarning, stacklevel=2) if rel_path_keyword is not None: raise TypeError('dbus.service.signal::path_keyword and ' 'rel_path_keyword cannot both be used') def decorator(func): member_name = func.__name__ validate_member_name(member_name) def emit_signal(self, *args, **keywords): abs_path = None if path_keyword is not None: if self.SUPPORTS_MULTIPLE_OBJECT_PATHS: raise TypeError('path_keyword cannot be used on the ' 'signals of an object that supports ' 'multiple object paths') abs_path = keywords.pop(path_keyword, None) if (abs_path != self.__dbus_object_path__ and not self.__dbus_object_path__.startswith(abs_path + '/')): raise ValueError('Path %r is not below %r', abs_path, self.__dbus_object_path__) rel_path = None if rel_path_keyword is not None: rel_path = keywords.pop(rel_path_keyword, None) func(self, *args, **keywords) for location in self.locations: if abs_path is None: # non-deprecated case if rel_path is None or rel_path in ('/', ''): object_path = location[1] else: # will be validated by SignalMessage ctor in a moment object_path = location[1] + rel_path else: object_path = abs_path message = SignalMessage(object_path, dbus_interface, member_name) message.append(signature=signature, *args) location[0].send_message(message) # end emit_signal if hasattr(func, '__wrapped__'): args = inspect.getfullargspec(func.__wrapped__)[0] else: args = inspect.getfullargspec(func)[0] args.pop(0) for keyword in rel_path_keyword, path_keyword: if keyword is not None: try: args.remove(keyword) except ValueError: raise ValueError('function has no argument "%s"' % keyword) if signature: sig = tuple(Signature(signature)) if len(sig) > len(args): raise ValueError('signal signature is longer than the number of arguments provided') elif len(sig) < len(args): raise ValueError('signal signature is shorter than the number of arguments provided') emit_signal.__name__ = func.__name__ emit_signal.__doc__ = func.__doc__ emit_signal._dbus_is_signal = True emit_signal._dbus_interface = dbus_interface emit_signal._dbus_signature = signature emit_signal._dbus_args = args return emit_signal return decorator checkbox-ng-0.3/checkbox_ng/__init__.py0000664000175000017500000000157512320610306020100 0ustar zygazyga00000000000000# This file is part of Checkbox. # # Copyright 2013 Canonical Ltd. # Written by: # Zygmunt Krynicki # # Checkbox is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License version 3, # as published by the Free Software Foundation. # # Checkbox is distributed in the hope that 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 Checkbox. If not, see . """ :mod:`checkbox_ng` -- checkbox-ng package ========================================= CheckBoxNG is a new version of CheckBox built on top of PlainBox """ __version__ = (0, 3, 0, "final", 0) checkbox-ng-0.3/checkbox_ng/service.py0000664000175000017500000016367412320607367020027 0ustar zygazyga00000000000000# This file is part of Checkbox. # # Copyright 2013, 2014 Canonical Ltd. # Written by: # Zygmunt Krynicki # # Checkbox is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License version 3, # as published by the Free Software Foundation. # # Checkbox is distributed in the hope that 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 Checkbox. If not, see . """ :mod:`checkbox_ng.service` -- DBus service for CheckBox ======================================================= """ from threading import Lock import collections import functools import itertools import logging try: from inspect import Signature except ImportError: try: from plainbox.vendor.funcsigs import Signature except ImportError: raise SystemExit("DBus parts require 'funcsigs' from pypi.") from plainbox.abc import IJobResult from plainbox.impl.job import JobDefinition from plainbox.impl.result import MemoryJobResult from plainbox.impl.secure.qualifiers import select_jobs from plainbox.impl.session import JobState from plainbox.impl.signal import remove_signals_listeners from plainbox.vendor import extcmd from checkbox_ng import dbus_ex as dbus from checkbox_ng.dbus_ex import OBJECT_MANAGER_IFACE from checkbox_ng.dbus_ex import mangle_object_path logger = logging.getLogger("checkbox.ng.service") _BASE_IFACE = "com.canonical.certification." SERVICE_IFACE = _BASE_IFACE + "PlainBox.Service1" SESSION_IFACE = _BASE_IFACE + "PlainBox.Session1" PROVIDER_IFACE = _BASE_IFACE + "PlainBox.Provider1" JOB_IFACE = _BASE_IFACE + "PlainBox.JobDefinition1" JOB_RESULT_IFACE = _BASE_IFACE + "PlainBox.Result1" JOB_STATE_IFACE = _BASE_IFACE + "PlainBox.JobState1" WHITELIST_IFACE = _BASE_IFACE + "PlainBox.WhiteList1" CHECKBOX_JOB_IFACE = _BASE_IFACE + "CheckBox.JobDefinition1" RUNNING_JOB_IFACE = _BASE_IFACE + "PlainBox.RunningJob1" class PlainBoxObjectWrapper(dbus.service.ObjectWrapper): """ Wrapper for exporting PlainBox object over DBus. Allows to keep the python object logic separate from the DBus counterpart. Has a set of utility methods to publish the object and any children objects to DBus. """ # Use a different logger for the translate decorator. # This is just so that we don't spam people that want to peek # at the service module. _logger = logging.getLogger("plainbox.dbus.service.translate") def __init__(self, native, conn=None, object_path=None, bus_name=None, **kwargs): super(PlainBoxObjectWrapper, self).__init__( native, conn, object_path, bus_name) logger.debug("Created DBus wrapper %s for: %r", id(self), self.native) self.__shared_initialize__(**kwargs) def __del__(self): logger.debug("DBus wrapper %s died", id(self)) def __shared_initialize__(self, **kwargs): """ Optional initialize method that can use any unused keyword arguments that were originally passed to __init__(). This makes it far easier to subclass as __init__() is rather complicated. Inspired by STANDARD GENERIC FUNCTION SHARED-INITIALIZE See hyperspec page: http://clhs.lisp.se/Body/f_shared.htm """ def _get_preferred_object_path(self): """ Return the preferred object path of this object on DBus """ return "/plainbox/{}/{}".format( self.native.__class__.__name__, id(self.native)) def publish_self(self, connection): """ Publish this object to the connection """ # Don't publish this object if it's already on the required connection # TODO: check if we can just drop this test and publish unconditionally try: if self.connection is connection: return except AttributeError: pass object_path = self._get_preferred_object_path() self.add_to_connection(connection, object_path) logger.debug("Published DBus wrapper for %r as %s", self.native, object_path) def publish_related_objects(self, connection): """ Publish this and any other objects to the connection Do not send ObjectManager events, just register any additional objects on the bus. By default only the object itself is published but collection managers are expected to publish all of the children here. This method is meant to be called only once, soon after the object is constructed but before :meth:`publish_managed_objects()` is called. """ self.publish_self(connection) def publish_managed_objects(self): """ This method is specific to ObjectManager, it basically adds children and sends the right events. This is a separate stage so that the whole hierarchy can first put all of the objects on the bus and then tell the world about it in one big signal message. This method is meant to be called only once, soon after :meth:`publish_related_objects()` was called. """ @classmethod def translate(cls, func): """ Decorator for Wrapper methods. The decorated method does not need to manually lookup objects when the caller (across DBus) passes an object path. Type information is provided using parameter annotations. The annotation accepts DBus type expressions (but in practice it is very limited). For the moment it cannot infer the argument types from the decorator for dbus.service.method. """ sig = Signature.from_function(func) def translate_o(object_path): try: obj = cls.find_object_by_path(object_path) except KeyError as exc: raise dbus.exceptions.DBusException(( "object path {} does not designate an existing" " object").format(exc)) else: return obj.native def translate_ao(object_path_list): try: obj_list = [cls.find_object_by_path(object_path) for object_path in object_path_list] except KeyError as exc: raise dbus.exceptions.DBusException(( "object path {} does not designate an existing" " object").format(exc)) else: return [obj.native for obj in obj_list] def translate_return_o(obj): if isinstance(obj, PlainBoxObjectWrapper): cls._logger.warning( "Application error: %r should have returned native object" " but returned wrapper instead", func) return obj try: return cls.find_wrapper_by_native(obj) except KeyError: raise dbus.exceptions.DBusException( "(o) internal error, unable to lookup object wrapper") def translate_return_ao(object_list): try: return dbus.types.Array([ cls.find_wrapper_by_native(obj) for obj in object_list ], signature='o') except KeyError: raise dbus.exceptions.DBusException( "(ao) internal error, unable to lookup object wrapper") def translate_return_a_brace_so_brace(mapping): try: return dbus.types.Dictionary({ key: cls.find_wrapper_by_native(value) for key, value in mapping.items() }, signature='so') except KeyError: raise dbus.exceptions.DBusException( "(a{so}) internal error, unable to lookup object wrapper") @functools.wraps(func) def wrapper(*args, **kwargs): bound = sig.bind(*args, **kwargs) cls._logger.debug( "wrapped %s called with %s", func, bound.arguments) for param in sig.parameters.values(): if param.annotation is Signature.empty: pass elif param.annotation == 'o': object_path = bound.arguments[param.name] bound.arguments[param.name] = translate_o(object_path) elif param.annotation == 'ao': object_path_list = bound.arguments[param.name] bound.arguments[param.name] = translate_ao( object_path_list) elif param.annotation in ('s', 'as'): strings = bound.arguments[param.name] bound.arguments[param.name] = strings else: raise ValueError( "unsupported translation {!r}".format( param.annotation)) cls._logger.debug( "unwrapped %s called with %s", func, bound.arguments) retval = func(**bound.arguments) cls._logger.debug("unwrapped %s returned %r", func, retval) if sig.return_annotation is Signature.empty: pass elif sig.return_annotation == 'o': retval = translate_return_o(retval) elif sig.return_annotation == 'ao': retval = translate_return_ao(retval) elif sig.return_annotation == 'a{so}': retval = translate_return_a_brace_so_brace(retval) else: raise ValueError( "unsupported translation {!r}".format( sig.return_annotation)) cls._logger.debug("wrapped %s returned %r", func, retval) return retval return wrapper class JobDefinitionWrapper(PlainBoxObjectWrapper): """ Wrapper for exposing JobDefinition objects on DBus. .. note:: Life cycle of JobDefinition wrappers is associated _either_ with a Provider wrapper or with a Session wrapper, depending on if the job itself is generated or not. """ HIDDEN_INTERFACES = frozenset([ OBJECT_MANAGER_IFACE, ]) # Some internal helpers def __shared_initialize__(self, **kwargs): self._checksum = self.native.checksum self._is_generated = False def _get_preferred_object_path(self): # TODO: this clashes with providers, maybe use a random ID instead return "/plainbox/job/{}".format(self._checksum) # PlainBox properties @dbus.service.property(dbus_interface=JOB_IFACE, signature="s") def name(self): # XXX: name should be removed but for now it should just return the # full id instead of the old name (name may be very well gone) return self.native.id @dbus.service.property(dbus_interface=JOB_IFACE, signature="s") def summary(self): return self.native.summary @dbus.service.property(dbus_interface=JOB_IFACE, signature="s") def tr_summary(self): return self.native.tr_summary() @dbus.service.property(dbus_interface=JOB_IFACE, signature="s") def id(self): return self.native.id @dbus.service.property(dbus_interface=JOB_IFACE, signature="s") def partial_id(self): return self.native.partial_id @dbus.service.property(dbus_interface=JOB_IFACE, signature="s") def description(self): return self.native.description or "" @dbus.service.property(dbus_interface=JOB_IFACE, signature="s") def tr_description(self): return self.native.tr_description() or "" @dbus.service.property(dbus_interface=JOB_IFACE, signature="s") def checksum(self): # This is a bit expensive to compute so let's keep it cached return self._checksum @dbus.service.property(dbus_interface=JOB_IFACE, signature="s") def requires(self): return self.native.requires or "" @dbus.service.property(dbus_interface=JOB_IFACE, signature="s") def depends(self): return self.native.depends or "" @dbus.service.property(dbus_interface=JOB_IFACE, signature="d") def estimated_duration(self): return self.native.estimated_duration or -1 # PlainBox methods @dbus.service.method(dbus_interface=JOB_IFACE, in_signature='', out_signature='as') def GetDirectDependencies(self): return dbus.Array( self.native.get_direct_dependencies(), signature="s") @dbus.service.method(dbus_interface=JOB_IFACE, in_signature='', out_signature='as') def GetResourceDependencies(self): return dbus.Array( self.native.get_resource_dependencies(), signature="s") @dbus.service.method(dbus_interface=CHECKBOX_JOB_IFACE, in_signature='', out_signature='as') def GetEnvironSettings(self): return dbus.Array(self.native.get_environ_settings(), signature='s') # CheckBox properties @dbus.service.property(dbus_interface=CHECKBOX_JOB_IFACE, signature="s") def plugin(self): return self.native.plugin @dbus.service.property(dbus_interface=CHECKBOX_JOB_IFACE, signature="s") def via(self): return self.native.via or "" @dbus.service.property( dbus_interface=CHECKBOX_JOB_IFACE, signature="(suu)") def origin(self): if self.native.origin is not None: return dbus.Struct([ str(self.native.origin.source), self.native.origin.line_start, self.native.origin.line_end ], signature="suu") else: return dbus.Struct(["", 0, 0], signature="suu") @dbus.service.property(dbus_interface=CHECKBOX_JOB_IFACE, signature="s") def command(self): return self.native.command or "" @dbus.service.property(dbus_interface=CHECKBOX_JOB_IFACE, signature="s") def environ(self): return self.native.environ or "" @dbus.service.property(dbus_interface=CHECKBOX_JOB_IFACE, signature="s") def user(self): return self.native.user or "" class WhiteListWrapper(PlainBoxObjectWrapper): """ Wrapper for exposing WhiteList objects on DBus """ HIDDEN_INTERFACES = frozenset([ OBJECT_MANAGER_IFACE, ]) # Some internal helpers def _get_preferred_object_path(self): # TODO: this clashes with providers, maybe use a random ID instead return "/plainbox/whitelist/{}".format( mangle_object_path(self.native.name)) # Value added @dbus.service.property(dbus_interface=WHITELIST_IFACE, signature="s") def name(self): """ name of this whitelist """ return self.native.name or "" @dbus.service.method( dbus_interface=WHITELIST_IFACE, in_signature='', out_signature='as') def GetPatternList(self): """ Get a list of regular expression patterns that make up this whitelist """ return dbus.Array([ qualifier.pattern_text for qualifier in self.native.inclusive_qualifier_list], signature='s') @dbus.service.method( dbus_interface=WHITELIST_IFACE, in_signature='o', out_signature='b') @PlainBoxObjectWrapper.translate def Designates(self, job: 'o'): return self.native.designates(job) class JobResultWrapper(PlainBoxObjectWrapper): """ Wrapper for exposing JobResult objects on DBus. This wrapper class exposes two mutable properties, 'outcome' and 'comments'. Changing them either through native python APIs or through DBus property API will result in synchronized updates as well as property change notification signals being sent. """ HIDDEN_INTERFACES = frozenset([ OBJECT_MANAGER_IFACE, ]) def __shared_initialize__(self, **kwargs): self.native.on_outcome_changed.connect(self._outcome_changed) self.native.on_comments_changed.connect(self._comments_changed) def __del__(self): super(JobResultWrapper, self).__del__() self.native.on_comments_changed.disconnect(self._comments_changed) self.native.on_outcome_changed.disconnect(self._outcome_changed) # Value added @dbus.service.property(dbus_interface=JOB_RESULT_IFACE, signature="s") def outcome(self): """ outcome of the job The result is one of a set of fixed strings. """ # XXX: it would be nice if we could not do this remapping. return self.native.outcome or "none" @outcome.setter def outcome(self, new_value): """ set outcome of the job to a new value """ # XXX: it would be nice if we could not do this remapping. if new_value == "none": new_value = None self.native.outcome = new_value def _outcome_changed(self, old, new): """ Internal method called when the value of self.native.outcome changes It sends the DBus PropertiesChanged signal for the 'outcome' property. """ self.PropertiesChanged(JOB_RESULT_IFACE, { self.__class__.outcome._dbus_property: new }, []) @dbus.service.property(dbus_interface=JOB_RESULT_IFACE, signature="d") def execution_duration(self): """ The amount of time in seconds it took to run this jobs command. :returns: The value of execution_duration or -1.0 if the command was not executed yet. """ execution_duration = self.native.execution_duration if execution_duration is None: return -1.0 else: return execution_duration @dbus.service.property(dbus_interface=JOB_RESULT_IFACE, signature="v") def return_code(self): """ return code of the called program """ value = self.native.return_code if value is None: return "" else: return value # comments are settable, useful thing that @dbus.service.property(dbus_interface=JOB_RESULT_IFACE, signature="s") def comments(self): """ comment added by the operator """ return self.native.comments or "" @comments.setter def comments(self, value): """ set comments to a new value """ self.native.comments = value def _comments_changed(self, old, new): """ Internal method called when the value of self.native.comments changes It sends the DBus PropertiesChanged signal for the 'comments' property. """ self.PropertiesChanged(JOB_RESULT_IFACE, { self.__class__.comments._dbus_property: new }, []) @dbus.service.property( dbus_interface=JOB_RESULT_IFACE, signature="a(dsay)") def io_log(self): """ The input-output log. Contains a record of all of the output (actually, it has no input logs) that was sent by the called program. The format is: array>> """ return dbus.types.Array(self.native.get_io_log(), signature="(dsay)") class JobStateWrapper(PlainBoxObjectWrapper): """ Wrapper for exposing JobState objects on DBus. Each job state wrapper has two related objects, job definition and job result. The job state wrapper itself is not a object manager so all of the managed objects belong in the session this job state is associated with. The job property is immutable. The result property is mutable but only through native python API. Any changes to the result property are propagated to changes in the DBus layer. When the 'result' property changes it is not reflecting changes of the object referenced by that property (those are separate) but instead indicates that the whole referenced object has been replaced by another object. Since JobStateWrapper is not an ObjectManager it does not manage the exact lifecycle and does not keep a collection that would reference the various result objects it must delegate this task to an instance of SessionWrapper (the instance that it is associated with). """ HIDDEN_INTERFACES = frozenset([ OBJECT_MANAGER_IFACE, ]) def __shared_initialize__(self, session_wrapper, **kwargs): # We need a reference to the session wrapper so that we can # react to result changes. self._session_wrapper = session_wrapper # Let's cache (and hold) references to the wrappers that # we should know about. This keeps them in the live set and makes # accessing relevant properties faster. self._result_wrapper = self.find_wrapper_by_native(self.native.result) self._job_wrapper = self.find_wrapper_by_native(self.native.job) # Connect to the on_result_changed signal so that we can keep the # referenced 'result' wrapper in sync with the native result object. self.native.on_result_changed.connect(self._result_changed) def __del__(self): super(JobStateWrapper, self).__del__() self.native.on_result_changed.disconnect(self._result_changed) def publish_related_objects(self, connection): super(JobStateWrapper, self).publish_related_objects(connection) self._result_wrapper.publish_related_objects(connection) self._job_wrapper.publish_related_objects(connection) # Value added @dbus.service.method( dbus_interface=JOB_STATE_IFACE, in_signature='', out_signature='b') def CanStart(self): """ Quickly check if the associated job can run right now. """ return self.native.can_start() @dbus.service.method( dbus_interface=JOB_STATE_IFACE, in_signature='', out_signature='s') def GetReadinessDescription(self): """ Get a human readable description of the current readiness state """ return self.native.get_readiness_description() @dbus.service.property(dbus_interface=JOB_STATE_IFACE, signature='o') @PlainBoxObjectWrapper.translate def job(self) -> 'o': """ Job associated with this state """ return self.native.job @dbus.service.property(dbus_interface=JOB_STATE_IFACE, signature='o') @PlainBoxObjectWrapper.translate def result(self) -> 'o': """ Result of running the associated job """ return self.native.result def _result_changed(self, old, new): """ Internal method called when the value of self.native.comments changes It ensures that we have appropriate wrapper for the new result wrapper and that it is properly accounted for by the session. It also sends the DBus PropertiesChanged signal for the 'result' property. """ logger.debug("_result_changed(%r, %r)", old, new) # Add the new result object try: result_wrapper = self.find_wrapper_by_native(new) except KeyError: result_wrapper = self._session_wrapper.add_result(new) # Notify applications that the result property has changed self.PropertiesChanged(JOB_STATE_IFACE, { self.__class__.result._dbus_property: result_wrapper }, []) # Remove the old result object self._session_wrapper.remove_result(old) @dbus.service.property(dbus_interface=JOB_STATE_IFACE, signature='a(isss)') def readiness_inhibitor_list(self): """ The list of readiness inhibitors of the associated job The list is represented as an array of structures. Each structure has a integer and two strings. The integer encodes the cause of inhibition. Cause may have one of the following values: 0 - UNDESIRED: This job was not selected to run in this session 1 - PENDING_DEP: This job depends on another job which was not started yet 2 - FAILED_DEP: This job depends on another job which was started and failed 3 - PENDING_RESOURCE: This job has a resource requirement expression that uses a resource produced by another job which was not started yet 4 - FAILED_RESOURCE: This job has a resource requirement that evaluated to a false value The next two strings are the name of the related job and the name of the related expression. Either may be empty. """ return dbus.types.Array([ (inhibitor.cause, inhibitor.cause_name, (inhibitor.related_job.id if inhibitor.related_job is not None else ""), (inhibitor.related_expression.text if inhibitor.related_expression is not None else "")) for inhibitor in self.native.readiness_inhibitor_list ], signature="(isss)") class SessionWrapper(PlainBoxObjectWrapper): """ Wrapper for exposing SessionState objects on DBus """ HIDDEN_INTERFACES = frozenset() # XXX: those will change to SessionManager later and session state will be # a part of that (along with session storage) def __shared_initialize__(self, **kwargs): # Wrap the initial set of objects reachable via the session state map # We don't use the add_{job,result,state}() methods as they also # change managed_object_list and we just want to send one big event # rather than a storm of tiny events. self._job_state_map_wrapper = {} for job_name, job_state in self.native.job_state_map.items(): # NOTE: we assume that each job is already wrapped by its provider job_wrapper = self.find_wrapper_by_native(job_state.job) assert job_wrapper is not None # Wrap the result and the state object result_wrapper = self._maybe_wrap(job_state.result) assert result_wrapper is not None state_wrapper = self._maybe_wrap(job_state) self._job_state_map_wrapper[job_name] = state_wrapper # Keep track of new jobs as they are added to the session self.native.on_job_added.connect(self._job_added) self.native.on_job_removed.connect(self._job_removed) def publish_related_objects(self, connection): super(SessionWrapper, self).publish_related_objects(connection) # Publish all the JobState wrappers and their related objects for job_state in self._job_state_map_wrapper.values(): job_state.publish_related_objects(connection) def publish_managed_objects(self): wrapper_list = list(self._iter_wrappers()) self.add_managed_object_list(wrapper_list) for wrapper in wrapper_list: wrapper.publish_managed_objects() def _iter_wrappers(self): return itertools.chain( # Get all of the JobState wrappers self._job_state_map_wrapper.values(), # And all the JobResult wrappers [self.find_wrapper_by_native(job_state_wrapper.native.result) for job_state_wrapper in self._job_state_map_wrapper.values()]) def add_result(self, result): """ Add a result representation to DBus. Take a IJobResult subclass instance, wrap it in JobResultWrapper, publish it so that it shows up on DBus, add it to the collection of objects managed by this SessionWrapper so that it sends InterfacesAdded signals and can be enumerated with GetManagedObjects() and return the wrapper to the caller. :returns: The wrapper for the result that was added """ logger.info("Adding result %r to DBus", result) result_wrapper = self._maybe_wrap(result) result_wrapper.publish_self(self.connection) self.add_managed_object(result_wrapper) return result_wrapper def remove_result(self, result): """ Remove a result representation from DBus. Take a IJobResult subclass instance, find the JobResultWrapper that it is wrapped in. Remove it from the collection of objects managed by this SessionWrapper so that it sends InterfacesRemoved signal and can no longer be enumerated with GetManagedObjects(), remove it from the bus and return the wrapper to the caller. :returns: The wrapper for the result that was removed """ logger.info("Removing result %r from DBus", result) result_wrapper = self.find_wrapper_by_native(result) self.remove_managed_object(result_wrapper) result_wrapper.remove_from_connection() return result_wrapper def add_job(self, job): """ Add a job representation to DBus. :param job: Job to add to the bus :ptype job: JobDefinition Take a JobDefinition, wrap it in JobResultWrapper, publish it so that it shows up on DBus, add it to the collection of objects managed by this SessionWrapper so that it sends InterfacesAdded signals and can be enumerated with GetManagedObjects. :returns: The wrapper for the job that was added """ logger.info("Adding job %r to DBus", job) job_wrapper = self._maybe_wrap(job) # Mark this job as generated, so far we only add generated jobs at # runtime and we need to treat those differently when we're changing # the session. job_wrapper._is_generated = True job_wrapper.publish_self(self.connection) self.add_managed_object(job_wrapper) return job_wrapper def add_state(self, state): """ Add a job state representatio to DBus. :param state: Job state to add to the bus :ptype state: JobState :returns: The wrapper for the job that was added Take a JobState, wrap it in JobStateWrapper, publish it so that it shows up on DBus, add it to the collection of objects managed by this SessionWrapper so that it sends InterfacesAdded signals and can be enumerated with GetManagedObjects. .. note:: This method must be called after both result and job definition have been added (presumably with :meth:`add_job()` and :meth:`add_result()`). This method *does not* publish those objects, it only publishes the state object. """ logger.info("Adding job state %r to DBus", state) state_wrapper = self._maybe_wrap(state) state_wrapper.publish_self(self.connection) self.add_managed_object(state_wrapper) return state_wrapper def _maybe_wrap(self, obj): """ Wrap a native object in the appropriate DBus wrapper. :param obj: The object to wrap :ptype obj: JobDefinition, IJobResult or JobState :returns: The wrapper associated with the object The object is only wrapped if it was not wrapped previously (at most one wrapper is created for any given native object). Only a few classes are supported, those are JobDefinition, IJobResult, JobState. """ try: return self.find_wrapper_by_native(obj) except LookupError: if isinstance(obj, JobDefinition): return JobDefinitionWrapper(obj) elif isinstance(obj, IJobResult): return JobResultWrapper(obj) elif isinstance(obj, JobState): return JobStateWrapper(obj, session_wrapper=self) else: raise TypeError("Unable to wrap object of type %r" % type(obj)) def _job_added(self, job): """ Internal method connected to the SessionState.on_job_added() signal. This method is called when a generated job is added to the session. This method adds the corresponding job definition, job result and job state to the bus and sends appropriate notifications. """ logger.debug("_job_added(%r)", job) # Get references to the three key objects, job, state and result state = self.native.job_state_map[job.id] result = state.result assert job is state.job # Wrap them in the right order (state has to be last) self.add_job(job) self.add_result(result) state_wrapper = self.add_state(state) # Update the job_state_map wrapper that we have here self._job_state_map_wrapper[job.id] = state_wrapper # Send the signal that the 'job_state_map' property has changed self.PropertiesChanged(SESSION_IFACE, { self.__class__.job_state_map._dbus_property: self._job_state_map_wrapper }, []) def _job_removed(self, job): """ Internal method connected to the SessionState.on_job_removed() signal. This method is called (so far) only when the list of jobs is trimmed after doing calling :meth:`Resume()`. This method looks up the associated state and result object and removes them. If the removed job was not a part of the provider set (it was a generated job) it is also removed. Lastly this method sends the appropriate notifications. """ logger.debug("_job_removed(%r)", job) # Get references to the three key objects, job, state and result state_wrapper = self._job_state_map_wrapper[job.id] result_wrapper = state_wrapper._result_wrapper job_wrapper = state_wrapper._job_wrapper # Remove result and state from our managed object list self.remove_managed_object(result_wrapper) self.remove_managed_object(state_wrapper) # Remove job from managed object list if it was generated if job_wrapper._is_generated: self.remove_managed_object(job_wrapper) # Remove result and state wrappers from dbus result_wrapper.remove_from_connection() state_wrapper.remove_from_connection() # Remove job from dbus if it was generated if job_wrapper._is_generated: job_wrapper.remove_from_connection() # Update the job_state_map wrapper that we have here del self._job_state_map_wrapper[job.id] # Send the signal that the 'job_state_map' property has changed self.PropertiesChanged(SESSION_IFACE, { self.__class__.job_state_map._dbus_property: self._job_state_map_wrapper }, []) # Value added @dbus.service.method( dbus_interface=SESSION_IFACE, in_signature='ao', out_signature='as') @PlainBoxObjectWrapper.translate def UpdateDesiredJobList(self, desired_job_list: 'ao'): logger.info("UpdateDesiredJobList(%r)", desired_job_list) problem_list = self.native.update_desired_job_list(desired_job_list) # TODO: map each problem into a structure (check which fields should be # presented). Document this in the docstring. return [str(problem) for problem in problem_list] @dbus.service.method( dbus_interface=SESSION_IFACE, in_signature='oo', out_signature='') @PlainBoxObjectWrapper.translate def UpdateJobResult(self, job: 'o', result: 'o'): logger.info("UpdateJobResult(%r, %r)", job, result) self.native.update_job_result(job, result) @dbus.service.method( dbus_interface=SESSION_IFACE, in_signature='', out_signature='(dd)') def GetEstimatedDuration(self): automated, manual = self.native.get_estimated_duration() if automated is None: automated = -1.0 if manual is None: manual = -1.0 return automated, manual @dbus.service.method( dbus_interface=SESSION_IFACE, in_signature='', out_signature='s') def PreviousSessionFile(self): # TODO: this method makes no sense here, it should not be on a session # object, it should, if anything, be on the service object. logger.info("PreviousSessionFile()") previous_session_file = self.native.previous_session_file() logger.info("PreviousSessionFile() -> %r", previous_session_file) if previous_session_file: return previous_session_file else: return '' @dbus.service.method( dbus_interface=SESSION_IFACE, in_signature='', out_signature='') def Resume(self): self.native.resume() @dbus.service.method( dbus_interface=SESSION_IFACE, in_signature='', out_signature='') def Clean(self): logger.info("Clean()") self.native.clean() @dbus.service.method( dbus_interface=SESSION_IFACE, in_signature='', out_signature='') def Remove(self): logger.info("Remove()") # Disconnect all signals listeners from the native session object remove_signals_listeners(self) for wrapper in self.managed_objects: wrapper.remove_from_connection() self.remove_from_connection() self.native.remove() logger.debug("Remove() completed") @dbus.service.method( dbus_interface=SESSION_IFACE, in_signature='', out_signature='') def PersistentSave(self): logger.info("PersistentSave()") self.native.persistent_save() @dbus.service.property(dbus_interface=SESSION_IFACE, signature='ao') @PlainBoxObjectWrapper.translate def job_list(self) -> 'ao': return self.native.job_list # TODO: signal @dbus.service.property(dbus_interface=SESSION_IFACE, signature='ao') @PlainBoxObjectWrapper.translate def desired_job_list(self) -> 'ao': return self.native.desired_job_list # TODO: signal @dbus.service.property(dbus_interface=SESSION_IFACE, signature='ao') @PlainBoxObjectWrapper.translate def run_list(self) -> 'ao': return self.native.run_list # TODO: signal @dbus.service.property(dbus_interface=SESSION_IFACE, signature='a{so}') @PlainBoxObjectWrapper.translate def job_state_map(self) -> 'a{so}': return self.native.job_state_map @dbus.service.property(dbus_interface=SESSION_IFACE, signature='a{sv}') def metadata(self): return dbus.types.Dictionary({ 'title': self.native.metadata.title or "", 'flags': dbus.types.Array( sorted(self.native.metadata.flags), signature='s'), 'running_job_name': self.native.metadata.running_job_name or "", 'app_blob': self.native.metadata.app_blob or b'', 'app_id': self.native.metadata.app_id or '' }, signature="sv") @metadata.setter def metadata(self, value): self.native.metadata.title = value['title'] self.native.metadata.running_job_name = value['running_job_name'] self.native.metadata.flags = value['flags'] self.native.metadata.app_blob = bytes(value.get('app_blob', b'')) self.native.metadata.app_id = value.get('app_id', '') # TODO: signal @dbus.service.signal( dbus_interface=SESSION_IFACE, signature='os') def AskForOutcome(self, primed_job: 'o', suggested_outcome: 's'): """ Signal sent when the user should be consulted for the outcome. The signal carries: - the primed_job instance (which is the sender of this signal anyway). - the suggested_outcome for the test based on the execution of the test command if it exists. This signal triggers important interactions in the GUI, the typical use case for the suggested_outcome is: - When the "test" button is clicked on a manual test, the outcome (e.g. the yes/no/skip radiobox) needs to be automatically updated to reflect actual test result. Otherwise, a failing test will not be detected by the user, which will cause embarrassment. """ logger.info("AskForOutcome(%r) suggested outcome is (%s)", primed_job, suggested_outcome) @dbus.service.signal( dbus_interface=SESSION_IFACE, signature='o') def ShowInteractiveUI(self, primed_job: 'o'): """ Signal sent when the test requires user interaction. The signal carries: - the primed_job instance (which is the sender of this signal anyway). This signal triggers important interactions in the GUI. """ logger.info("ShowInteractiveUI(%r)", primed_job) class ProviderWrapper(PlainBoxObjectWrapper): """ Wrapper for exposing Provider1 objects on DBus """ HIDDEN_INTERFACES = frozenset() def __shared_initialize__(self, **kwargs): self._job_wrapper_list = [ JobDefinitionWrapper(job) for job in self.native.get_builtin_jobs()] self._whitelist_wrapper_list = [ WhiteListWrapper(whitelist) for whitelist in self.native.get_builtin_whitelists()] def _get_preferred_object_path(self): mangled_name = mangle_object_path(self.native.name) return "/plainbox/provider/{}".format(mangled_name) def publish_related_objects(self, connection): super(ProviderWrapper, self).publish_related_objects(connection) wrapper_list = list(self._iter_wrappers()) for wrapper in wrapper_list: wrapper.publish_related_objects(connection) def publish_managed_objects(self): wrapper_list = list(self._iter_wrappers()) self.add_managed_object_list(wrapper_list) def _iter_wrappers(self): return itertools.chain( self._job_wrapper_list, self._whitelist_wrapper_list) # Value added @dbus.service.property(dbus_interface=PROVIDER_IFACE, signature="s") def name(self): """ name of this provider """ return self.native.name @dbus.service.property(dbus_interface=PROVIDER_IFACE, signature="s") def description(self): """ description of this provider """ return self.native.description @dbus.service.property(dbus_interface=PROVIDER_IFACE, signature="s") def gettext_domain(self): """ the name of the gettext domain associated with this provider This value may be empty, in such case provider data cannot be localized for the user environment. """ return self.native.gettext_domain or "" class ServiceWrapper(PlainBoxObjectWrapper): """ Wrapper for exposing Service objects on DBus """ HIDDEN_INTERFACES = frozenset() # Internal setup stuff def __shared_initialize__(self, on_exit, **kwargs): self._on_exit = on_exit self._provider_wrapper_list = [ ProviderWrapper(provider) for provider in self.native.provider_list] def _get_preferred_object_path(self): return "/plainbox/service1" def publish_related_objects(self, connection): super(ServiceWrapper, self).publish_related_objects(connection) for wrapper in self._provider_wrapper_list: wrapper.publish_related_objects(connection) def publish_managed_objects(self): # First publish all of our providers self.add_managed_object_list(self._provider_wrapper_list) # Then ask the providers to publish their own objects for wrapper in self._provider_wrapper_list: wrapper.publish_managed_objects() # Value added @dbus.service.property(dbus_interface=SERVICE_IFACE, signature="s") def version(self): """ version of this provider """ return self.native.version @dbus.service.method( dbus_interface=SERVICE_IFACE, in_signature='', out_signature='') def Exit(self): """ Shut down the service and terminate """ # TODO: raise exception when job is in progress logger.info("Exit()") self.native.close() self._on_exit() @dbus.service.method( dbus_interface=SERVICE_IFACE, in_signature='', out_signature='a{sas}') def GetAllExporters(self): """ Get all exporters names and their respective options """ return self.native.get_all_exporters() @dbus.service.method( dbus_interface=SERVICE_IFACE, in_signature='osas', out_signature='s') @PlainBoxObjectWrapper.translate def ExportSession(self, session: 'o', output_format: 's', option_list: 'as'): return self.native.export_session(session, output_format, option_list) @dbus.service.method( dbus_interface=SERVICE_IFACE, in_signature='osass', out_signature='s') @PlainBoxObjectWrapper.translate def ExportSessionToFile(self, session: 'o', output_format: 's', option_list: 'as', output_file: 's'): return self.native.export_session_to_file( session, output_format, option_list, output_file) @dbus.service.method( dbus_interface=SERVICE_IFACE, in_signature='', out_signature='as') def GetAllTransports(self): """ Get all transports names and their respective options """ return self.native.get_all_transports() @dbus.service.method( dbus_interface=SERVICE_IFACE, in_signature='ossss', out_signature='s') @PlainBoxObjectWrapper.translate def SendDataViaTransport(self, session: 'o', transport: 's', where: 's', options: 's', data: 's'): return self.native.send_data_via_transport(session, transport, where, options, data) @dbus.service.method( dbus_interface=SERVICE_IFACE, in_signature='ao', out_signature='o') @PlainBoxObjectWrapper.translate def CreateSession(self, job_list: 'ao'): logger.info("CreateSession(%r)", job_list) # Create a session session_obj = self.native.create_session(job_list) # Wrap it session_wrp = SessionWrapper(session_obj) # Publish all objects session_wrp.publish_related_objects(self.connection) # Announce the session is there self.add_managed_object(session_wrp) # Announce any session children session_wrp.publish_managed_objects() # Return the session wrapper back return session_wrp @dbus.service.method( dbus_interface=SERVICE_IFACE, in_signature='oo', out_signature='o') @PlainBoxObjectWrapper.translate def PrimeJob(self, session: 'o', job: 'o') -> 'o': logger.info("PrimeJob(%r, %r)", session, job) # Get a primed job for the arguments we've got... primed_job = self.native.prime_job(session, job) # ...wrap it for DBus... primed_job_wrapper = PrimedJobWrapper( primed_job, session_wrapper=self.find_wrapper_by_native(session)) # ...publish it... primed_job_wrapper.publish_self(self.connection) # Call the method that decides on what to really do, see the docstring # for details. This cannot be called inside __init__() as we need to # publish the wrapper first. When that happens this method can safely # send signals. primed_job_wrapper._decide_on_what_to_do() # ...and return it return primed_job RunJob = PrimeJob @dbus.service.method( dbus_interface=SERVICE_IFACE, in_signature='ao', out_signature='ao') @PlainBoxObjectWrapper.translate def SelectJobs(self, whitelist_list: 'ao') -> 'ao': """ Compute the effective desired job list out of a list of (arbitrary) desired whitelists or job definitions. :param whitelist_list: A list of jobs or whitelists to select. Each whitelist selects all the jobs selected by that whitelist. This argument is a simple, limited, encoding of job qualifiers that is sufficient to implement the desired semantics of the Checkbox GUI. :returns: A list of jobs that were selected. """ job_list = list( itertools.chain(*[ p.load_all_jobs()[0] for p in self.native.provider_list])) return select_jobs(job_list, whitelist_list) class UIOutputPrinter(extcmd.DelegateBase): """ Delegate for extcmd that redirect all output to the UI. """ def __init__(self, runner): self._lineno = collections.defaultdict(int) self._runner = runner def on_line(self, stream_name, line): # FIXME: this is not a line number, # TODO: tie this into existing code in runner.py (the module) self._lineno[stream_name] += 1 self._runner.IOLogGenerated(self._lineno[stream_name], stream_name, line) class PrimedJobWrapper(PlainBoxObjectWrapper): """ Wrapper for exposing PrimedJob objects on DBus """ HIDDEN_INTERFACES = frozenset( OBJECT_MANAGER_IFACE, ) def __shared_initialize__(self, session_wrapper, **kwargs): # SessionWrapper instance, we're using it to publish/unpublish results # on DBus as they technically belong to the session. self._session_wrapper = session_wrapper # A result object we got from running the command OR the result this # job used to have before. It should be always published on the bus. self._result = None # A future for the result each time we're waiting for the command to # finish. Gets reset to None after the command is done executing. self._result_future = None # A lock that protects access to :ivar:`_result` and # :ivar:`_result_future` from concurrent access from the thread that is # executing Future callback which we register, the # :meth:`_result_ready()` self._result_lock = Lock() @dbus.service.method( dbus_interface=RUNNING_JOB_IFACE, in_signature='', out_signature='') def Kill(self): """ Unused method. Could be used to implement a way to cancel the command. """ # NOTE: this should: # 1) attempt to cancel the future in the extremely rare case where it # is not started yet # 2) kill the job otherwise logger.error("Kill() is not implemented") @dbus.service.method( dbus_interface=RUNNING_JOB_IFACE, in_signature='', out_signature='') def RunCommand(self): """ Method invoked by the GUI each time the "test" button is pressed. Two cases are possible here: 1) The command isn't running. In this case we start the command and return. A callback will interpret the result once the command finishes executing (see :meth:`_legacy_result_juggle()`) 2) The command is running. In that case we just ignore the call and log a warning. The GUI should not make the "test" button clickable while the command is runninig. """ if self.native.job.automated: logger.error( "RunCommand() should not be called for automated jobs") with self._result_lock: if self._result_future is None: logger.info("RunCommand() is starting to run the job") self._result_future = self._run_and_set_callback() else: logger.warning( "RunCommand() ignored, waiting for command to finish") # Legacy GUI behavior method. # Should be redesigned when we can change GUI internals @dbus.service.method( dbus_interface=RUNNING_JOB_IFACE, in_signature='ss', out_signature='') def SetOutcome(self, outcome, comments=None): """ Method called by the GUI when the "continue" button is pressed. Three cases are possible: 1) There is no result yet 2) There is a result already 3) The command is still running! (not handled) """ logger.info("SetOutcome(%r, %r)", outcome, comments) with self._result_lock: if self._result_future is not None: logger.error( "SetOutcome() called while the command is still running!") if self._result is None: # Warn us if this method is being called on jobs other than # 'manual' before we get the result after running RunCommand() if self.native.job.plugin != "manual": logger.warning("SetOutcome() called before RunCommand()") logger.warning("But the job is not manual, it is %s", self.native.job.plugin) # Create a new result object self._result = MemoryJobResult({ 'outcome': outcome, 'comments': comments }) # Add the new result object to the bus self._session_wrapper.add_result(self._result) else: # Set the values as requested self._result.outcome = outcome self._result.comments = comments # Notify the application that the result is ready. This has to be # done unconditionally each time this method called. self.JobResultAvailable( self.find_wrapper_by_native(self.native.job), self.find_wrapper_by_native(self._result)) # Legacy GUI behavior signal. # Should be redesigned when we can change GUI internals @dbus.service.property(dbus_interface=RUNNING_JOB_IFACE, signature="s") def outcome_from_command(self): """ property that contains the 'outcome' of the result. """ with self._result_lock: if self._result is not None: # TODO: make it so that we don't have to do this translation if self._result.outcome == IJobResult.OUTCOME_NONE: return "none" else: return self._result.outcome else: logger.warning("outcome_from_command() called too early!") logger.warning("There is nothing to return yet") return "" @dbus.service.signal( dbus_interface=SERVICE_IFACE, signature='dsay') def IOLogGenerated(self, delay, stream_name, data): """ Signal sent when IOLogRecord is generated ..note:: This is not called at all in this implementation. """ logger.info("IOLogGenerated(%r, %r, %r)", delay, stream_name, data) # Legacy GUI behavior signal. # Should be redesigned when we can change GUI internals @dbus.service.signal( dbus_interface=SERVICE_IFACE, signature='oo') def JobResultAvailable(self, job: 'o', result: 'o'): """ Signal sent when result of running a job is ready """ logger.info("JobResultAvailable(%r, %r)", job, result) def _decide_on_what_to_do(self): """ Internal method of PrimedJobWrapper. This methods decides on how to behave after we get initialized This is a bit of a SNAFU... :/ The GUI runs jobs differently, depending on the 'plugin' value. It either expects to call Service.RunJob() and see the job running (so waiting for signals when it is done) or it calls Service.RunJob() *and* runs RunCommand() on the returned object (possibly many times). """ # TODO: change this to depend on jobbox 'startup' property # http://jobbox.readthedocs.org/en/latest/jobspec.html#startup if self.native.job.startup_user_interaction_required: logger.info( "Sending ShowInteractiveUI() and not starting the job...") # Ask the application to show the interaction GUI self._session_wrapper.ShowInteractiveUI(self) else: logger.info("Running %r right away", self.native.job) with self._result_lock: self._result_future = self._run_and_set_callback() def _run_and_set_callback(self): """ Internal method of PrimedJobWrapper Starts the future for the job result, adds a callbacks to it and returns the future. """ future = self.native.run() future.add_done_callback(self._result_ready) return future def _result_ready(self, result_future): """ Internal method called when the result future becomes ready """ logger.debug("_result_ready(%r)", result_future) with self._result_lock: if self._result is not None: # NOTE: I'm not sure how this would behave if someone were to # already assign the old result to any state objects. self._session_wrapper.remove_result(self._result) # Unpack the result from the future self._result = result_future.result() # Add the new result object to the session wrapper (and to the bus) self._session_wrapper.add_result(self._result) # Reset the future so that RunCommand() can run the job again self._result_future = None # Now fiddle with the GUI notifications if self._result.outcome != IJobResult.OUTCOME_UNDECIDED: # NOTE: OUTCOME_UNDECIDED is never handled by this method as # the user should already see the manual test interaction # dialog on their screen. For all other cases we need to notify # the GUI that execution has finished and we are really just # done with testing. logger.debug( "calling JobResultAvailable(%r, %r)", self.native.job, self._result) self.JobResultAvailable( self.find_wrapper_by_native(self.native.job), self.find_wrapper_by_native(self._result)) else: logger.debug( ("sending AskForOutcome() after job finished" " running with OUTCOME_UNDECIDED")) # Convert the return of the command to the suggested_outcome # for the job if self._result.return_code == 0: suggested_outcome = IJobResult.OUTCOME_PASS else: suggested_outcome = IJobResult.OUTCOME_FAIL self._session_wrapper.AskForOutcome(self, suggested_outcome) checkbox-ng-0.3/checkbox_ng/test_config.py0000664000175000017500000000260712320607367020657 0ustar zygazyga00000000000000# This file is part of Checkbox. # # Copyright 2013 Canonical Ltd. # Written by: # Zygmunt Krynicki # # Checkbox is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License version 3, # as published by the Free Software Foundation. # # Checkbox is distributed in the hope that 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 Checkbox. If not, see . """ checkbox_ng.test_config ======================= Test definitions for checkbox_ng.config module """ from unittest import TestCase from plainbox.impl.secure.config import Unset from checkbox_ng.config import CheckBoxConfig class PlainBoxConfigTests(TestCase): def test_smoke(self): config = CheckBoxConfig() self.assertIs(config.secure_id, Unset) secure_id = "0123456789ABCDE" config.secure_id = secure_id self.assertEqual(config.secure_id, secure_id) with self.assertRaises(ValueError): config.secure_id = "bork" self.assertEqual(config.secure_id, secure_id) del config.secure_id self.assertIs(config.secure_id, Unset) checkbox-ng-0.3/checkbox_ng/main.py0000664000175000017500000001427112320607367017277 0ustar zygazyga00000000000000# This file is part of Checkbox. # # Copyright 2012, 2013 Canonical Ltd. # Written by: # Zygmunt Krynicki # # Checkbox is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License version 3, # as published by the Free Software Foundation. # # Checkbox is distributed in the hope that 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 Checkbox. If not, see . """ :mod:`checkbox_ng.main` -- command line interface ================================================= """ import logging import sys from plainbox.impl.commands import PlainBoxToolBase from plainbox.impl.commands.check_config import CheckConfigCommand from plainbox.impl.commands.dev import DevCommand from plainbox.impl.commands.script import ScriptCommand from checkbox_ng import __version__ as version from checkbox_ng.commands.certification import CertificationCommand from checkbox_ng.commands.cli import CliCommand from checkbox_ng.commands.sru import SRUCommand try: from checkbox_ng.commands.service import ServiceCommand except ImportError: pass from checkbox_ng.config import CertificationConfig, CheckBoxConfig, CDTSConfig logger = logging.getLogger("checkbox.ng.main") checkbox_cli_settings = { 'subparser_name': 'checkbox-cli', 'subparser_help': 'application for system testing', 'default_whitelist': 'default', 'default_providers': ['2013.com.canonical.certification:checkbox'], 'welcome_text': """\ Welcome to System Testing! Checkbox provides tests to confirm that your system is working properly. \ Once you are finished running the tests, you can view a summary report for \ your system. Warning: Some tests could cause your system to freeze or become \ unresponsive. Please save all your work and close all other running \ applications before beginning the testing process.""" } cdts_cli_settings = { 'subparser_name': 'driver-test-suite-cli', 'subparser_help': 'driver test suite application', 'default_whitelist': 'ihv-firmware', 'default_providers': ['2013.com.canonical:canonical-driver-test-suite'], 'welcome_text': """\ Welcome to the Canonical Driver Test Suite. This program contains automated and manual tests to help you discover issues \ that will arise when running your device drivers on Ubuntu. This application will step the user through these tests in a predetermined \ order and automatically collect both system information as well as test \ results. It will also prompt the user for input when manual testing is \ required. The run time for the tests is determined by which tests you decide to \ execute. The user will have the opportunity to customize the test run to \ accommodate the driver and the amount of time available for testing. If you have any questions during or after completing your test run, please \ do not hesitate to contact your Canonical account representative. To begin, simply press the Continue button below and follow the onscreen \ instructions.""" } cert_cli_settings = { 'subparser_name': 'certification-server', 'subparser_help': 'application for server certification', 'default_whitelist': 'server-selftest-14.04', 'default_providers': ['2013.com.canonical.certification:certification-server'], 'welcome_text': """\ Welcome to System Certification! This application will gather information from your system. Then you will be \ asked manual tests to confirm that the system is working properly. Finally, \ you will be asked for the Secure ID of the computer to submit the \ information to the certification.canonical.com database. To learn how to create or locate the Secure ID, please see here: https://certification.canonical.com/""" } class CheckBoxNGTool(PlainBoxToolBase): @classmethod def get_exec_name(cls): return "checkbox" @classmethod def get_exec_version(cls): return cls.format_version_tuple(version) @classmethod def get_config_cls(cls): return CheckBoxConfig def add_subcommands(self, subparsers): SRUCommand( self._provider_list, self._config).register_parser(subparsers) CheckConfigCommand( self._config).register_parser(subparsers) ScriptCommand( self._provider_list, self._config).register_parser(subparsers) DevCommand( self._provider_list, self._config).register_parser(subparsers) CliCommand( self._provider_list, self._config, checkbox_cli_settings ).register_parser(subparsers) CliCommand( self._provider_list, self._config, cdts_cli_settings ).register_parser(subparsers) CertificationCommand( self._provider_list, self._config, cert_cli_settings ).register_parser(subparsers) try: ServiceCommand(self._provider_list, self._config).register_parser( subparsers) except NameError: pass class CertificationNGTool(CheckBoxNGTool): @classmethod def get_config_cls(cls): return CertificationConfig class CDTSTool(CheckBoxNGTool): @classmethod def get_config_cls(cls): return CDTSConfig def main(argv=None): """ checkbox command line utility """ raise SystemExit(CheckBoxNGTool().main(argv)) def checkbox_cli(argv=None): """ CheckBox command line utility """ if argv: args = argv else: args = sys.argv[1:] raise SystemExit( CheckBoxNGTool().main(['checkbox-cli'] + args)) def cdts_cli(argv=None): """ certification-server command line utility """ if argv: args = argv else: args = sys.argv[1:] raise SystemExit( CDTSTool().main(['driver-test-suite-cli'] + args)) def cert_server(argv=None): """ certification-server command line utility """ if argv: args = argv else: args = sys.argv[1:] raise SystemExit( CertificationNGTool().main(['certification-server'] + args)) checkbox-ng-0.3/checkbox_ng/test_main.py0000664000175000017500000001376212320607367020342 0ustar zygazyga00000000000000# This file is part of Checkbox. # # Copyright 2012-2013 Canonical Ltd. # Written by: # Zygmunt Krynicki # # Checkbox is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License version 3, # as published by the Free Software Foundation. # # Checkbox is distributed in the hope that 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 Checkbox. If not, see . """ checkbox_ng.test_main ===================== Test definitions for checkbox_ng.main module """ from inspect import cleandoc from unittest import TestCase from plainbox.impl.clitools import ToolBase from plainbox.testing_utils.io import TestIO from checkbox_ng import __version__ as version from checkbox_ng.main import cert_server, main class TestMain(TestCase): def test_version(self): with TestIO(combined=True) as io: with self.assertRaises(SystemExit) as call: main(['--version']) self.assertEqual(call.exception.args, (0,)) self.assertEqual(io.combined, "{}\n".format( ToolBase.format_version_tuple(version))) def test_help(self): with TestIO(combined=True) as io: with self.assertRaises(SystemExit) as call: main(['--help']) self.assertEqual(call.exception.args, (0,)) self.maxDiff = None expected = """ usage: checkbox [-h] [--version] [--providers {all,stub}] [-v] [-D] [-C] [-T LOGGER] [-P] [-I] {sru,check-config,script,dev,checkbox-cli,driver-test-suite-cli,certification-server,service} ... positional arguments: {sru,check-config,script,dev,checkbox-cli,driver-test-suite-cli,certification-server,service} sru run automated stable release update tests check-config check and display plainbox configuration script run a command from a job dev development commands checkbox-cli application for system testing driver-test-suite-cli driver test suite application certification-server application for server certification service spawn dbus service optional arguments: -h, --help show this help message and exit --version show program's version number and exit provider list and development: --providers {all,stub} which providers to load logging and debugging: -v, --verbose be more verbose (same as --log-level=INFO) -D, --debug enable DEBUG messages on the root logger -C, --debug-console display DEBUG messages in the console -T LOGGER, --trace LOGGER enable DEBUG messages on the specified logger (can be used multiple times) -P, --pdb jump into pdb (python debugger) when a command crashes -I, --debug-interrupt crash on SIGINT/KeyboardInterrupt, useful with --pdb """ self.assertEqual(io.combined, cleandoc(expected) + "\n") def test_run_without_args(self): with TestIO(combined=True) as io: with self.assertRaises(SystemExit) as call: main([]) self.assertEqual(call.exception.args, (2,)) expected = """ usage: checkbox [-h] [--version] [--providers {all,stub}] [-v] [-D] [-C] [-T LOGGER] [-P] [-I] {sru,check-config,script,dev,checkbox-cli,driver-test-suite-cli,certification-server,service} ... checkbox: error: too few arguments """ self.assertEqual(io.combined, cleandoc(expected) + "\n") class TestCertServer(TestCase): def test_help(self): with TestIO(combined=True) as io: with self.assertRaises(SystemExit) as call: cert_server(['--help']) self.assertEqual(call.exception.args, (0,)) self.maxDiff = None expected = """ usage: checkbox certification-server [-h] [--check-config] [--not-interactive] [--secure-id SECURE-ID] [--destination URL] [--staging] [-i PATTERN] [-x PATTERN] [-w WHITELIST] optional arguments: -h, --help show this help message and exit --check-config Run check-config --not-interactive Skip tests that require interactivity certification-specific options: --secure-id SECURE-ID Associate submission with a machine using this SECURE- ID (None) --destination URL POST the test report XML to this URL (https://certific ation.canonical.com/submissions/submit/) --staging Override --destination to use the staging certification website job definition options: -i PATTERN, --include-pattern PATTERN include jobs matching the given regular expression -x PATTERN, --exclude-pattern PATTERN exclude jobs matching the given regular expression -w WHITELIST, --whitelist WHITELIST load whitelist containing run patterns """ self.assertEqual(io.combined, cleandoc(expected) + "\n") checkbox-ng-0.3/docs/0000775000175000017500000000000012320610512014434 5ustar zygazyga00000000000000checkbox-ng-0.3/docs/changelog.rst0000664000175000017500000000073112320610410017113 0ustar zygazyga00000000000000ChangeLog ========= .. note:: This changelog contains only a summary of changes. For a more accurate accounting of development history please inspect the source history directly. CheckBoxNG 0.3 -------------- * Bugfixes: https://launchpad.net/checkbox-ng/+milestone/0.3 CheckBoxNG 0.2 -------------- ??? CheckBoxNG 0.1 -------------- * Initial release * Support for displaying configuration * Support for running SRU tests (automatic regression testing) checkbox-ng-0.3/docs/release.rst0000664000175000017500000002211612320607367016626 0ustar zygazyga00000000000000======================== CheckBox Release Process ======================== This page describes the necessary steps for releasing versions of CheckBox and CheckBox Certification to the stable PPA belonging to the Hardware Certification team, on a regular basis. Throughout this document the term 'CheckBox' is used as a catch-all term to cover all versions of CheckBox owned by the Hardware Certification team, currently CheckBox itself and the CheckBox Certification extensions. Overview ======== Currently the process runs on a bi-weekly cadence, with a new release of Checkbox every two weeks. This covers ten working days, and the tasks carried out on each day or group of days is described below: * Days 1-4: Time allowed for new changes to be introduced into trunk. * Day 5: Changes are merged from the trunk of ``lp:checkbox`` and ``lp:checkbox-certification`` to their respective release branches. The changelogs for both are *bumped* at this point and revisions are tagged. At this stage it may also be necessary to copy the package 'fwts' from the `FWTS Stable PPA `_ to the `Checkbox Release Testing PPA `_. * Days 6-9: Testing is performed by the release manager for the Hardware Certification team, and a representative of the CE QA team (the main customer for CheckBox within Canonical) * Day 9: A release meeting is held between the release manager for the Hardware Certification team and the representative of the CE QA team. Potential issues with the release are identified and plans made to address them. * Day 10: The tested version of CheckBox is copied to the stable PPA. Launchpad Branches ================== The release process requires separate branches in Launchpad containing a semi-frozen version of the code that was in trunk on day 5 of the process. This is so that development can continue on trunk without jeopardising the stability of the to-be released version of CheckBox. The relationship between all branches involved in the process is as shown below: * `lp:checkbox/release` <- `lp:checkbox` * `lp:checkbox-certification/release` <- `lp:checkbox-certification` * `lp:~checkbox-dev/checkbox/checkbox-packaging-release` <- `lp:~checkbox-dev/checkbox/checkbox-packaging` Auditing milestoned bugs ======================== Prior to creating the release candidate the release manager should review the list of bugs milestoned for the next release of CheckBox. They should visit `checkbox milestones `_ and locate the milestone dated with the release date. * For bugs that are set to In Progress with a branch associated - liase with the branch owner to see if the merge can be completed before the deadline. * For bugs that are in any other non-closed status (except *Fix Commited*) - re-milestone them to the following milestone. Cutting the release =================== In order to cut the release, we have to merge the changes from trunk into the release branch, commit them with a suitable message and update the changelog in trunk so that future changes go under the correct version. For each combination of branches shown above, do the following (the example uses ``lp:checkbox`` and ``lp:checkbox/release``):: bzr branch lp:checkbox/release checkbox-release bzr branch lp:checkbox checkbox-trunk cd checkbox-release current_stable=`head -n1 $(find . -name 'changelog') | grep -oP '(?<=\().*(?=\))'` bzr merge lp:checkbox at this point if no changes (other than one to ``debian/changelog``) get merged in then we do not perform a release of the package in question. In practice this often happens with ``checkbox-certification`` but never with ``checkbox``:: bzr commit -m "Merged in changes from rev$(bzr revno -r tag:$current_stable lp:checkbox) to rev$(bzr revno lp:checkbox) from lp:checkbox" bzr push lp:checkbox/release cd `find . -name 'debian'`; cd .. bzr tag `head -n1 debian/changelog | grep -oP '(?<=\().*(?=\))'` dch -r (save modified changelog) dch -i -U 'Incremented changelog' debcommit bzr push lp:checkbox The last step in the process is to perform a build of the packages in the ``ppa:checkbox-dev/testing PPA``. To do this we need to go to the recipe pages for the ``checkbox`` and/or ``checkbox-certification`` release branches. * `checkbox-testing recipe `_ * `checkbox-certification-testing recipe `_ The **Build Now** option should be available on the page. Click it to start a build. Copying Firmware Test Suite to the Testing PPA ============================================== The Firmware Test Suite tool is a test tool for system firmware that is naturally heavily utilised by Checkbox. To make sure the latest version which contains fixes and new tests/features needed by Checkbox is available and also doesn't break anything in Checkbox, we need to release it alongside Checkbox. After cutting the release if the Firmware Testing team have notified that a new version is available and that this version should be used for certification, we need to copy it to the Testing PPA. To do this we need to go to the `Copy packages view of the Firmware Test Suite (Stable) PPA `_ and select the 'fwts' packages for all releases back to Precise. We need to set the 'Destination PPA' as 'Checkbox Release Testing [~checkbox-dev/testing]' and the 'Copy options' field to 'Copy existing binaries', then click 'Copy packages'. This step then needs to be repeated but set the 'Destination PPA' field to 'PPA for Checkbox Developers [~checkbox-dev/ppa]'. Next Release of Checkbox e-mail =============================== So that everyone has the opportunity to perform whatever testing is required in a timely manner, after the PPA builds have been completed an email should be sent to the following mailing lists: * `hardware-certification-team@lists.canonical.com `_ * `commercial-engineering@lists.canonical.com `_ The content is typically something like this:: Subject: Next Release of CheckBox (18/11/2013) Hi, The next release of CheckBox is available in the https://code.launchpad.net/~checkbox-dev/+archive/testing PPA. Please test it at your convenience. CheckBox is based on revision 2484 of lp:checkbox and CheckBox Certification is based on revision 586 of lp:checkbox-certification. Thanks, If one or the other of CheckBox and CheckBox Certification have not been updated then there is no need to mention that package Testing the release =================== Now that the release has been cut, testing should take place prior to the release meeting. From the point of view of the certification team, what needs to be tested is ``checkbox-certification-client`` and ``checkbox-certification-server`` which form the basis for CE QAs OEM specific versions of CheckBox. CheckBox certification server is tested in the CI loop CheckBox certification client needs to be tested manually. Release Meeting =============== On the Thursday before the release is made, a meeting is held between a representative of the Certification team and a representative of the **Commercial Engineering QA** team. The meeting is held at 7:30 UTC as shown in this `calendar invite `_. An agenda for the meeting is included in the invite. Publishing the release ====================== To publish the release we simply need to copy a number of packages from the `Checkbox Release Testing PPA `_ to the `Hardware Certification Public PPA `_. To do this we go to the `Copy packages view of the Checkbox Release Testing PPA `_ and select all versions of the following list of packages: ``checkbox, checkbox-certification, fwts``. Make sure that the 'Destination PPA' field is set to 'Public PPA for Hardware Certification [~hardware-certification/public]' and that the 'Copy options' field is set to 'Copy existing binaries', then click 'Copy Packages'. After that is done an announcement email should be sent to `commercial-engineering@lists.canonical.com `_. A template for the announcement in included below:: Hi, A new release of checkbox has been uploaded to the Hardware Certification Public PPA (https://launchpad.net/~hardware-certification/+archive/public). The release is based on revision 2294 of lp:checkbox Thanks, Please attach the most recent part of the changelog as release notes checkbox-ng-0.3/docs/index.rst0000664000175000017500000000344212320607367016316 0ustar zygazyga00000000000000.. CheckBoxNG documentation master file, created by sphinx-quickstart on Wed Feb 13 11:18:39 2013. You can adapt this file completely to your liking, but it should at least contain the root `toctree` directive. CheckBoxNG ========== :term:`CheckBoxNG` is a hardware testing tool useful for certifying laptops, desktops and servers with Ubuntu. It is a new version of :term:`CheckBox` that is built directly on top of :term:`PlainBox` CheckBoxNG *replaces* CheckBox, where applicable. .. warning:: Documentation is under development. Some things are wrong, inaccurate or describe development goals rather than current state. Installation ^^^^^^^^^^^^ CheckBoxNG can be installed from a :abbr:`PPA (Personal Package Archive)` (recommended) or :abbr:`pypi (python package index)` on Ubuntu Precise (12.04) or newer. .. code-block:: bash $ sudo add-apt-repository ppa:checkbox-dev/ppa && sudo apt-get update && sudo apt-get install checkbox-ng Running stable release update tests ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ CheckBoxNG has special support for running stable release updates tests in an automated manner. This runs all the jobs from the *sru.whitelist* and sends the results to the certification website. To run SRU tests you will need to know the so-called :term:`Secure ID` of the device you are testing. Once you know that all you need to do is run: .. code-block:: bash $ checkbox sru $secure_id submission.xml The second argument, submission.xml, is a name of the fallback file that is only created when sending the data to the certification website fails to work for any reason. Table of contents ================= .. toctree:: :maxdepth: 2 scripts/index.rst release.rst Indices and tables ================== * :ref:`genindex` * :ref:`modindex` * :ref:`search` checkbox-ng-0.3/docs/scripts/0000775000175000017500000000000012320610512016123 5ustar zygazyga00000000000000checkbox-ng-0.3/docs/scripts/index.rst0000664000175000017500000000021712320607367020002 0ustar zygazyga00000000000000Test Scripts ============ Test 'scripts' are small programs which are used to aid in implementing tests. .. toctree:: brightness_test.rst checkbox-ng-0.3/docs/scripts/brightness_test.rst0000664000175000017500000000105112320607367022077 0ustar zygazyga00000000000000brightness_test =============== This script tests the brightness of the systems backlight can be changed by using the kernel interfaces in /sys/class/backlight. There may be more than one interface to choose from, so the correct interface to use is selected by using the heuristic prescribed in https://www.kernel.org/doc/Documentation/ABI/stable/sysfs-class-backlight. The brightness is manipulated by updating the brightness file of the interface and the actual_brightness file is checked to see if the value was modified to the brightness selected. checkbox-ng-0.3/docs/conf.py0000664000175000017500000002107112320607367015752 0ustar zygazyga00000000000000#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # CheckBoxNG documentation build configuration file, created by # sphinx-quickstart on Wed Feb 13 11:18:39 2013. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys, os try: import plainbox except ImportError as exc: raise SystemExit("plainbox has to be importable") else: # Inject mock modules so that we can build the # documentation without having the real stuff available from plainbox.vendor import mock for mod_name in ['lxml', 'xlsxwriter', 'requests', 'requests.exceptions', 'dbus', 'dbus.lowlevel', 'dbus.exceptions', 'dbus._compat', 'dbus.service', '_dbus_bindings']: sys.modules[mod_name] = mock.Mock() print("Mocked {}".format(mod_name)) # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. #sys.path.insert(0, os.path.abspath('.')) # -- General configuration ----------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = ['sphinx.ext.autodoc', 'sphinx.ext.doctest', 'sphinx.ext.todo', 'sphinx.ext.coverage', 'sphinx.ext.viewcode'] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = 'CheckBoxNG' copyright = '2013, Zygmunt Krynicki' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = '0.1' # The full version, including alpha/beta/rc tags. release = '0.1' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = [] # The reST default role (used for this markup: `text`) to use for all documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # -- Options for HTML output --------------------------------------------------- try: import sphinx_bootstrap_theme except ImportError: html_theme = 'default' html_theme_options = {} else: html_theme = 'bootstrap' html_theme_path = sphinx_bootstrap_theme.get_html_theme_path() html_theme_options = { 'bootswatch_theme': 'united', 'navbar_class': "navbar navbar-inverse", } # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # " v documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'CheckBoxNGdoc' # -- Options for LaTeX output -------------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ ('index', 'CheckBoxNG.tex', 'CheckBoxNG Documentation', 'Zygmunt Krynicki', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output -------------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'checkbox_ng', 'CheckBoxNG Documentation', ['Zygmunt Krynicki'], 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output ------------------------------------------------ # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ('index', 'CheckBoxNG', 'CheckBoxNG Documentation', 'Zygmunt Krynicki', 'CheckBoxNG', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote' checkbox-ng-0.3/setup.cfg0000664000175000017500000000017712320610512015332 0ustar zygazyga00000000000000[upload] sign = True [upload_docs] upload-dir = build/sphinx/html [egg_info] tag_date = 0 tag_build = tag_svn_revision = 0 checkbox-ng-0.3/MANIFEST.in0000664000175000017500000000017012320607367015256 0ustar zygazyga00000000000000include README.md include COPYING recursive-include contrib *.service recursive-include docs *.rst include docs/conf.py checkbox-ng-0.3/PKG-INFO0000664000175000017500000000155212320610512014604 0ustar zygazyga00000000000000Metadata-Version: 1.0 Name: checkbox-ng Version: 0.3 Summary: CheckBox / Next Generation Home-page: https://launchpad.net/checkbox/ Author: Zygmunt Krynicki Author-email: zygmunt.krynicki@canonical.com License: GPLv3 Description: CheckBoxNG ========== :term:`CheckBoxNG` is a hardware testing tool useful for certifying laptops, desktops and servers with Ubuntu. It is a new version of :term:`CheckBox` that is built directly on top of :term:`PlainBox` CheckBoxNG *replaces* CheckBox, where applicable. Installation ============ Installation is a bit tricky. You need to have python3-plainbox installed first (which may come from the checkbox daily ppa) or you need to (recommended, for the time being) develop plainbox. Platform: UNKNOWN checkbox-ng-0.3/setup.py0000775000175000017500000000523412320610274015232 0ustar zygazyga00000000000000#!/usr/bin/env python3 # This file is part of Checkbox. # # Copyright 2013 Canonical Ltd. # Written by: # Zygmunt Krynicki # # Checkbox is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License version 3, # as published by the Free Software Foundation. # # Checkbox is distributed in the hope that 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 Checkbox. If not, see . # To avoid an error in atexit._run_exitfuncs while running tests: import concurrent.futures import os import sys from setuptools import setup, find_packages if "test" in sys.argv: # Reset locale for setup.py test os.environ["LANG"] = "" os.environ["LANGUAGE"] = "" os.environ["LC_ALL"] = "C.UTF-8" base_dir = os.path.dirname(__file__) # Load the README.rst file relative to the setup file with open(os.path.join(base_dir, "README.rst"), encoding="UTF-8") as stream: long_description = stream.read() # Check if we are running on readthedocs.org builder. on_rtd = os.environ.get('READTHEDOCS', None) == 'True' # When building on readthedocs.org, skip all real dependencies as those are # mocked away in 'plainbox/docs/conf.py'. This speeds up the build process. # and makes it independent on any packages that are hard to get in a virtualenv if on_rtd: install_requires = [] else: install_requires = [ 'checkbox-support >= 0.2', 'plainbox >= 0.5.3', 'requests >= 1.0', ] setup( name="checkbox-ng", version="0.3", url="https://launchpad.net/checkbox/", packages=find_packages(), author="Zygmunt Krynicki", test_suite='checkbox_ng.tests.test_suite', author_email="zygmunt.krynicki@canonical.com", license="GPLv3", description="CheckBox / Next Generation", long_description=long_description, install_requires=install_requires, entry_points={ 'console_scripts': [ 'canonical-certification-server=checkbox_ng.main:cert_server', 'canonical-driver-test-suite-cli=checkbox_ng.main:cdts_cli', 'checkbox=checkbox_ng.main:main', 'checkbox-cli=checkbox_ng.main:checkbox_cli', ], 'plainbox.transport': [ 'certification=' 'checkbox_ng.certification:CertificationTransport', 'launchpad=' 'checkbox_ng.launchpad:LaunchpadTransport', ], }, include_package_data=True) checkbox-ng-0.3/README.rst0000664000175000017500000000076112320607367015215 0ustar zygazyga00000000000000CheckBoxNG ========== :term:`CheckBoxNG` is a hardware testing tool useful for certifying laptops, desktops and servers with Ubuntu. It is a new version of :term:`CheckBox` that is built directly on top of :term:`PlainBox` CheckBoxNG *replaces* CheckBox, where applicable. Installation ============ Installation is a bit tricky. You need to have python3-plainbox installed first (which may come from the checkbox daily ppa) or you need to (recommended, for the time being) develop plainbox. checkbox-ng-0.3/COPYING0000664000175000017500000010451312320607367014561 0ustar zygazyga00000000000000 GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . checkbox-ng-0.3/checkbox_ng.egg-info/0000775000175000017500000000000012320610512017450 5ustar zygazyga00000000000000checkbox-ng-0.3/checkbox_ng.egg-info/entry_points.txt0000664000175000017500000000054712320610511022753 0ustar zygazyga00000000000000[console_scripts] checkbox-cli = checkbox_ng.main:checkbox_cli canonical-driver-test-suite-cli = checkbox_ng.main:cdts_cli canonical-certification-server = checkbox_ng.main:cert_server checkbox = checkbox_ng.main:main [plainbox.transport] certification = checkbox_ng.certification:CertificationTransport launchpad = checkbox_ng.launchpad:LaunchpadTransport checkbox-ng-0.3/checkbox_ng.egg-info/PKG-INFO0000664000175000017500000000155212320610511020547 0ustar zygazyga00000000000000Metadata-Version: 1.0 Name: checkbox-ng Version: 0.3 Summary: CheckBox / Next Generation Home-page: https://launchpad.net/checkbox/ Author: Zygmunt Krynicki Author-email: zygmunt.krynicki@canonical.com License: GPLv3 Description: CheckBoxNG ========== :term:`CheckBoxNG` is a hardware testing tool useful for certifying laptops, desktops and servers with Ubuntu. It is a new version of :term:`CheckBox` that is built directly on top of :term:`PlainBox` CheckBoxNG *replaces* CheckBox, where applicable. Installation ============ Installation is a bit tricky. You need to have python3-plainbox installed first (which may come from the checkbox daily ppa) or you need to (recommended, for the time being) develop plainbox. Platform: UNKNOWN checkbox-ng-0.3/checkbox_ng.egg-info/requires.txt0000664000175000017500000000007112320610511022045 0ustar zygazyga00000000000000checkbox-support >= 0.2 plainbox >= 0.5.3 requests >= 1.0checkbox-ng-0.3/checkbox_ng.egg-info/dependency_links.txt0000664000175000017500000000000112320610511023515 0ustar zygazyga00000000000000 checkbox-ng-0.3/checkbox_ng.egg-info/top_level.txt0000664000175000017500000000001412320610511022174 0ustar zygazyga00000000000000checkbox_ng checkbox-ng-0.3/checkbox_ng.egg-info/SOURCES.txt0000664000175000017500000000202012320610512021326 0ustar zygazyga00000000000000COPYING MANIFEST.in README.rst setup.cfg setup.py checkbox_ng/__init__.py checkbox_ng/certification.py checkbox_ng/config.py checkbox_ng/launchpad.py checkbox_ng/main.py checkbox_ng/service.py checkbox_ng/test_certification.py checkbox_ng/test_config.py checkbox_ng/test_main.py checkbox_ng/tests.py checkbox_ng.egg-info/PKG-INFO checkbox_ng.egg-info/SOURCES.txt checkbox_ng.egg-info/dependency_links.txt checkbox_ng.egg-info/entry_points.txt checkbox_ng.egg-info/requires.txt checkbox_ng.egg-info/top_level.txt checkbox_ng/commands/__init__.py checkbox_ng/commands/certification.py checkbox_ng/commands/cli.py checkbox_ng/commands/service.py checkbox_ng/commands/sru.py checkbox_ng/commands/test_cli.py checkbox_ng/commands/test_sru.py checkbox_ng/dbus_ex/__init__.py checkbox_ng/dbus_ex/decorators.py checkbox_ng/dbus_ex/service.py checkbox_ng/dbus_ex/test_dbus.py contrib/com.canonical.certification.PlainBox1.service docs/changelog.rst docs/conf.py docs/index.rst docs/release.rst docs/scripts/brightness_test.rst docs/scripts/index.rst