This file is indexed.

/usr/lib/python3/dist-packages/plainbox/impl/commands/run.py is in python3-plainbox 0.5.3-2.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
# This file is part of Checkbox.
#
# Copyright 2012-2013 Canonical Ltd.
# Written by:
#   Zygmunt Krynicki <zygmunt.krynicki@canonical.com>
#
# 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 <http://www.gnu.org/licenses/>.

"""
:mod:`plainbox.impl.commands.run` -- run sub-command
====================================================

.. warning::

    THIS MODULE DOES NOT HAVE STABLE PUBLIC API
"""

from argparse import FileType
from logging import getLogger
from os.path import join
from shutil import copyfileobj
import io
import sys

from plainbox.abc import IJobResult
from plainbox.i18n import gettext as _
from plainbox.impl.commands import PlainBoxCommand
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.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.session import SessionStateLegacyAPI as SessionState
from plainbox.impl.transport import TransportError
from plainbox.impl.transport import get_all_transports


logger = getLogger("plainbox.commands.run")


class RunInvocation(CheckBoxInvocationMixIn):

    def __init__(self, provider_list, config, ns):
        super().__init__(provider_list, config)
        self.ns = ns

    @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
        if ns.output_format == _('?'):
            self._print_output_format_list(ns)
            return 0
        elif ns.output_options == _('?'):
            self._print_output_option_list(ns)
            return 0
        elif ns.transport == _('?'):
            self._print_transport_list(ns)
            return 0
        else:
            exporter = self._prepare_exporter(ns)
            transport = self._prepare_transport(ns)
            job_list = self.get_job_list(ns)
            return self._run_jobs(ns, job_list, exporter, transport)

    def _print_output_format_list(self, ns):
        print(_("Available output formats: {}").format(
            ', '.join(get_all_exporters())))

    def _print_output_option_list(self, ns):
        print(_("Each format may support a different set of options"))
        for name, exporter_cls in get_all_exporters().items():
            print("{}: {}".format(
                name, ", ".join(exporter_cls.supported_option_list)))

    def _print_transport_list(self, ns):
        print(_("Available transports: {}").format(
            ', '.join(get_all_transports())))

    def _prepare_exporter(self, ns):
        exporter_cls = get_all_exporters()[ns.output_format]
        if ns.output_options:
            option_list = ns.output_options.split(',')
        else:
            option_list = None
        try:
            exporter = exporter_cls(option_list)
        except ValueError as exc:
            raise SystemExit(str(exc))
        return exporter

    def _prepare_transport(self, ns):
        if ns.transport not in get_all_transports():
            return None
        transport_cls = get_all_transports()[ns.transport]
        try:
            return transport_cls(ns.transport_where, ns.transport_options)
        except ValueError as exc:
            raise SystemExit(str(exc))

    def ask_for_resume(self):
        # TODO: use proper APIs for yes-no questions
        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, session):
        last_job = session.metadata.running_job_name
        if last_job is None:
            return
        print(_("Previous session run 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:
            session.update_job_result(
                session.job_state_map[last_job].job, result)
            session.metadata.running_job_name = None
            session.persistent_save()

    def _run_jobs(self, ns, job_list, exporter, transport=None):
        # Compute the run list, this can give us notification about problems in
        # the selected jobs. Currently we just display each problem
        matching_job_list = self._get_matching_job_list(ns, job_list)
        print(_("[ Analyzing Jobs ]").center(80, '='))
        # Create a session that handles most of the stuff needed to run jobs
        try:
            session = SessionState(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 id {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 session.open():
            if session.previous_session_file():
                if self.ask_for_resume():
                    session.resume()
                    self._maybe_skip_last_job_after_resume(session)
                else:
                    session.clean()
            session.metadata.title = " ".join(sys.argv)
            session.persistent_save()
            self._update_desired_job_list(session, matching_job_list)
            # Ask the password before anything else in order to run jobs
            # requiring privileges
            if self._auth_warmup_needed(session):
                print(_("[ Authentication ]").center(80, '='))
                return_code = authenticate_warmup()
                if return_code:
                    raise SystemExit(return_code)
            runner = JobRunner(
                session.session_dir, self.provider_list,
                session.jobs_io_log_dir, dry_run=ns.dry_run)
            self._run_jobs_with_session(ns, session, runner)
            # Get a stream with exported session data.
            exported_stream = io.BytesIO()
            data_subset = exporter.get_session_data_subset(session)
            exporter.dump(data_subset, exported_stream)
            exported_stream.seek(0)  # Need to rewind the file, puagh
            # Write the stream to file if requested
            self._save_results(ns.output_file, exported_stream)
            # Invoke the transport?
            if transport:
                exported_stream.seek(0)
                try:
                    transport.send(exported_stream.read(), self.config, session)
                except TransportError as exc:
                    print(str(exc))

        # FIXME: sensible return value
        return 0

    def _auth_warmup_needed(self, session):
        # 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
        # acutally 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 session.run_list):
            return False
        # Otherwise, do pre-authentication
        return True

    def _save_results(self, output_file, input_stream):
        if output_file is sys.stdout:
            print(_("[ Results ]").center(80, '='))
            # This requires a bit more finesse, as exporters output bytes
            # and stdout needs a string.
            translating_stream = ByteStringStreamTranslator(
                output_file, "utf-8")
            copyfileobj(input_stream, translating_stream)
        else:
            print(_("Saving results to {}").format(output_file.name))
            copyfileobj(input_stream, output_file)
        if output_file is not sys.stdout:
            output_file.close()

    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, session, desired_job_list):
        problem_list = session.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"))
        (estimated_duration_auto,
         estimated_duration_manual) = session.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."))

    def _run_jobs_with_session(self, ns, session, 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).
        print(_("[ Running All Jobs ]").center(80, '='))
        again = True
        while again:
            again = False
            for job in 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
                if session.job_state_map[job.id].result.outcome is not None:
                    continue
                self._run_single_job_with_session(ns, session, runner, job)
                session.persistent_save()
                if job.plugin == "local":
                    # After each local job runs rebuild the list of matching
                    # jobs and run everything again
                    new_matching_job_list = self._get_matching_job_list(
                        ns, session.job_list)
                    self._update_desired_job_list(
                        session, new_matching_job_list)
                    again = True
                    break

    def _run_single_job_with_session(self, ns, session, runner, job):
        print("[ {} ]".format(job.id).center(80, '-'))
        if job.description is not None:
            print(job.description)
            print("^" * len(job.description.splitlines()[-1]))
            print()
        job_state = session.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():
            print(_("Running... (output in {}.*)").format(
                join(session.jobs_io_log_dir, slugify(job.id))))
            session.metadata.running_job_name = job.id
            session.persistent_save()
            # 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)
            session.metadata.running_job_name = None
            session.persistent_save()
            print(_("Outcome: {}").format(job_result.outcome))
            print(_("Comments: {}").format(job_result.comments))
        else:
            job_result = MemoryJobResult({
                'outcome': IJobResult.OUTCOME_NOT_SUPPORTED,
                'comments': job_state.get_readiness_description()
            })
        if job_result is not None:
            session.update_job_result(job, job_result)


class RunCommand(PlainBoxCommand, CheckBoxCommandMixIn):

    def __init__(self, provider_list, config):
        self.provider_list = provider_list
        self.config = config

    def invoked(self, ns):
        return RunInvocation(self.provider_list, self.config, ns).run()

    def register_parser(self, subparsers):
        parser = subparsers.add_parser("run", help=_("run a test job"))
        parser.set_defaults(command=self)
        group = parser.add_argument_group(title=_("user interface options"))
        group.add_argument(
            '--not-interactive', action='store_true',
            help=_("skip tests that require interactivity"))
        group.add_argument(
            '-n', '--dry-run', action='store_true',
            help=_("don't really run most jobs"))
        group = parser.add_argument_group(_("output options"))
        assert 'text' in get_all_exporters()
        group.add_argument(
            '-f', '--output-format', default='text',
            metavar=_('FORMAT'), choices=[_('?')] + list(
                get_all_exporters().keys()),
            help=_('save test results in the specified FORMAT'
                   ' (pass ? for a list of choices)'))
        group.add_argument(
            '-p', '--output-options', default='',
            metavar=_('OPTIONS'),
            help=_('comma-separated list of options for the export mechanism'
                   ' (pass ? for a list of choices)'))
        group.add_argument(
            '-o', '--output-file', default='-',
            metavar=_('FILE'), type=FileType("wb"),
            help=_('save test results to the specified FILE'
                   ' (or to stdout if FILE is -)'))
        group.add_argument(
            '-t', '--transport',
            metavar=_('TRANSPORT'), choices=[_('?')] + list(
                get_all_transports().keys()),
            help=_('use TRANSPORT to send results somewhere'
                   ' (pass ? for a list of choices)'))
        group.add_argument(
            '--transport-where',
            metavar=_('WHERE'),
            help=_('where to send data using the selected transport'))
        group.add_argument(
            '--transport-options',
            metavar=_('OPTIONS'),
            help=_('comma-separated list of key-value options (k=v) to '
                   'be passed to the transport'))
        # Call enhance_parser from CheckBoxCommandMixIn
        self.enhance_parser(parser)