__init__.py 43.4 KB
Newer Older
Rémi Duraffort's avatar
Rémi Duraffort committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# -*- coding: utf-8 -*-
# Copyright (C) 2017-2018 Linaro Limited
#
# Author: Neil Williams <neil.williams@linaro.org>
#         Senthil Kumaran <senthil.kumaran@linaro.org>
#
# This file is part of LAVA.
#
# LAVA is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License version 3
# as published by the Free Software Foundation
#
# LAVA is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with LAVA.  If not, see <http://www.gnu.org/licenses/>.

21
22
from functools import wraps
from simplejson import JSONDecodeError
23
import yaml
24
import sys
Neil Williams's avatar
Neil Williams committed
25
import xmlrpc.client
26
from django.conf import settings
27
from django.core.exceptions import PermissionDenied
28
from django.db.models import Count, Q
29
from django.db import transaction
30
from linaro_django_xmlrpc.models import ExposedAPI
31
32
33
from lava_scheduler_app.models import (
    Device,
    DeviceType,
34
    JSONDataError,
35
    DevicesUnavailableException,
36
    TestJob,
Neil Williams's avatar
Neil Williams committed
37
)
38
from lava_scheduler_app.views import get_restricted_job
39
40
from lava_scheduler_app.dbutils import (
    device_type_summary,
41
42
    testjob_submission,
    active_device_types,
43
)
44
45
46
47
48
49
50
51
from lava_scheduler_app.schema import (
    validate_submission,
    validate_device,
    SubmissionException,
)

# functions need to be members to be exposed in the API
# pylint: disable=no-self-use
Michael-Doyle Hudson's avatar
Michael-Doyle Hudson committed
52

Neil Williams's avatar
Neil Williams committed
53
54
55
# to make a function visible in the API, it must be a member of SchedulerAPI
# pylint: disable=no-self-use

Michael-Doyle Hudson's avatar
Michael-Doyle Hudson committed
56

57
58
def check_perm(perm):
    """ decorator to check that the caller has the given permission """
59

60
61
62
63
64
65
66
    def decorator(f):
        @wraps(f)
        def wrapper(self, *args, **kwargs):
            self._authenticate()
            if not self.user.has_perm(perm):
                raise xmlrpc.client.Fault(
                    403,
67
                    "User '%s' is missing permission %s ." % (self.user.username, perm),
68
69
                )
            return f(self, *args, **kwargs)
70

71
        return wrapper
72

73
    return decorator
74
75


76
77
78
def build_device_status_display(state, health):
    if state == Device.STATE_IDLE:
        if health in [Device.HEALTH_GOOD, Device.HEALTH_UNKNOWN]:
79
            return "idle"
80
        elif health == Device.HEALTH_RETIRED:
81
            return "retired"
82
        else:
83
            return "offline"
84
    elif state == Device.STATE_RESERVED:
85
        return "reserved"
86
    else:
87
        return "running"
88
89


90
91
class SchedulerAPI(ExposedAPI):
    def submit_job(self, job_data):
92
93
94
95
96
97
98
        """
        Name
        ----
        `submit_job` (`job_data`)

        Description
        -----------
99
100
        Submit the given job data which is in LAVA job JSON or YAML format as a
        new job to LAVA scheduler.
101
102
103
104

        Arguments
        ---------
        `job_data`: string
105
            Job JSON or YAML string.
106
107
108
109

        Return value
        ------------
        This function returns an XML-RPC integer which is the newly created
110
        job's id, provided the user is authenticated with an username and token.
111
112
        If the job is a multinode job, this function returns the list of created
        job IDs.
113
        """
114
        self._authenticate()
115
        if not self.user.has_perm("lava_scheduler_app.add_testjob"):
Neil Williams's avatar
Neil Williams committed
116
            raise xmlrpc.client.Fault(
117
118
                403,
                "Permission denied.  User %r does not have the "
119
                "'lava_scheduler_app.add_testjob' permission.  Contact "
120
121
                "the administrators." % self.user.username,
            )
Neil Williams's avatar
Neil Williams committed
122
        try:
123
124
            job = testjob_submission(job_data, self.user)
        except SubmissionException as exc:
Neil Williams's avatar
Neil Williams committed
125
            raise xmlrpc.client.Fault(400, "Problem with submitted job data: %s" % exc)
Rémi Duraffort's avatar
Rémi Duraffort committed
126
        # FIXME: json error is not needed anymore
Neil Williams's avatar
Neil Williams committed
127
        except (JSONDataError, JSONDecodeError, ValueError) as exc:
Neil Williams's avatar
Neil Williams committed
128
            raise xmlrpc.client.Fault(400, "Decoding job submission failed: %s." % exc)
129
        except (Device.DoesNotExist, DeviceType.DoesNotExist):
Neil Williams's avatar
Neil Williams committed
130
            raise xmlrpc.client.Fault(404, "Specified device or device type not found.")
131
        except DevicesUnavailableException as exc:
Neil Williams's avatar
Neil Williams committed
132
            raise xmlrpc.client.Fault(400, "Device unavailable: %s" % str(exc))
133
        if isinstance(job, list):
134
            return [j.sub_id for j in job]
135
136
        else:
            return job.id
137

138
    def resubmit_job(self, job_id):
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
        """
        Name
        ----
        `resubmit_job` (`job_id`)

        Description
        -----------
        Resubmit the given job reffered by its id.

        Arguments
        ---------
        `job_id`: string
            The job's id which should be re-submitted.

        Return value
        ------------
        This function returns an XML-RPC integer which is the newly created
        job's id,  provided the user is authenticated with an username and
        token.
        """
159
        self._authenticate()
160
        if not self.user.has_perm("lava_scheduler_app.add_testjob"):
Neil Williams's avatar
Neil Williams committed
161
            raise xmlrpc.client.Fault(
162
163
                403,
                "Permission denied.  User %r does not have the "
164
                "'lava_scheduler_app.add_testjob' permission.  Contact "
165
166
                "the administrators." % self.user.username,
            )
Paul Larson's avatar
Paul Larson committed
167
        try:
168
            job = get_restricted_job(self.user, job_id)
Paul Larson's avatar
Paul Larson committed
169
        except TestJob.DoesNotExist:
Neil Williams's avatar
Neil Williams committed
170
            raise xmlrpc.client.Fault(404, "Specified job not found.")
171

172
        if job.is_multinode:
173
174
175
            return self.submit_job(job.multinode_definition)
        else:
            return self.submit_job(job.definition)
176

177
    def cancel_job(self, job_id):
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
        """
        Name
        ----
        `cancel_job` (`job_id`)

        Description
        -----------
        Cancel the given job reffered by its id.

        Arguments
        ---------
        `job_id`: string
            Job id which should be canceled.

        Return value
        ------------
        None. The user should be authenticated with an username and token.
        """
196
197
        self._authenticate()
        if not job_id:
198
            raise xmlrpc.client.Fault(400, "Bad request: TestJob id was not specified.")
199

200
201
202
203
        with transaction.atomic():
            try:
                job = get_restricted_job(self.user, job_id, for_update=True)
            except PermissionDenied:
Neil Williams's avatar
Neil Williams committed
204
                raise xmlrpc.client.Fault(
205
206
                    401, "Permission denied for user to job %s" % job_id
                )
207
            except TestJob.DoesNotExist:
Neil Williams's avatar
Neil Williams committed
208
                raise xmlrpc.client.Fault(404, "Specified job not found.")
209
210
211
212
213

            if job.state in [TestJob.STATE_CANCELING, TestJob.STATE_FINISHED]:
                # Don't do anything for jobs that ended already
                return True
            if not job.can_cancel(self.user):
Neil Williams's avatar
Neil Williams committed
214
                raise xmlrpc.client.Fault(403, "Permission denied.")
215
216
217

            if job.is_multinode:
                multinode_jobs = TestJob.objects.select_for_update().filter(
218
219
                    target_group=job.target_group
                )
220
221
222
223
224
225
                for multinode_job in multinode_jobs:
                    multinode_job.go_state_canceling()
                    multinode_job.save()
            else:
                job.go_state_canceling()
                job.save()
226
        return True
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
    def validate_yaml(self, yaml_string):
        """
        Name
        ----
        validate_yaml (yaml_job_data)

        Description
        -----------
        Validate the supplied pipeline YAML against the submission schema.

        Note: this does not validate the job itself, just the YAML against the
        submission schema. A job which validates against the schema can still be
        an invalid job for the dispatcher and such jobs will be accepted as Submitted,
        scheduled and then marked as Incomplete with a failure comment. Full validation
        only happens after a device has been assigned to the Submitted job.

        Arguments
        ---------
        'yaml_job_data': string

        Return value
        ------------
        Raises an Exception if the yaml_job_data is invalid.
        """
        try:
            # YAML can parse JSON as YAML, JSON cannot parse YAML at all
254
            yaml_data = yaml.safe_load(yaml_string)
255
        except yaml.YAMLError as exc:
Neil Williams's avatar
Neil Williams committed
256
            raise xmlrpc.client.Fault(400, "Decoding job submission failed: %s." % exc)
257
258
259
260
        try:
            # validate against the submission schema.
            validate_submission(yaml_data)  # raises SubmissionException if invalid.
        except SubmissionException as exc:
Neil Williams's avatar
Neil Williams committed
261
            raise xmlrpc.client.Fault(400, "Invalid YAML submission: %s" % exc)
262

263
    def job_output(self, job_id, offset=0):
264
265
266
        """
        Name
        ----
267
        `job_output` (`job_id`, `offset=0`)
268
269
270
271
272
273
274
275
276

        Description
        -----------
        Get the output of given job id.

        Arguments
        ---------
        `job_id`: string
            Job id for which the output is required.
277
278
279
        `offset`: integer
            Offset from which to start reading the output file specified in bytes.
            It defaults to 0.
280
281
282

        Return value
        ------------
283
284
        This function returns an XML-RPC binary data of output file, provided
        the user is authenticated with an username and token.
285
        """
286
287
        self._authenticate()
        if not job_id:
288
            raise xmlrpc.client.Fault(400, "Bad request: TestJob id was not specified.")
289
        try:
290
            job = get_restricted_job(self.user, job_id)
291
        except PermissionDenied:
Neil Williams's avatar
Neil Williams committed
292
            raise xmlrpc.client.Fault(
293
294
                401, "Permission denied for user to job %s" % job_id
            )
295
        except TestJob.DoesNotExist:
Neil Williams's avatar
Neil Williams committed
296
            raise xmlrpc.client.Fault(404, "Specified job not found.")
297

298
299
        output_file = job.output_file()
        if output_file:
300
            output_file.seek(offset)
301
            return xmlrpc.client.Binary(output_file.read().encode("UTF-8"))
302
        else:
Neil Williams's avatar
Neil Williams committed
303
            raise xmlrpc.client.Fault(404, "Job output not found.")
304
305
306
307
308
309
310
311
312

    def all_devices(self):
        """
        Name
        ----
        `all_devices` ()

        Description
        -----------
313
        Get all the available devices with their state and type information.
314
315
316
317
318
319
320
321

        Arguments
        ---------
        None

        Return value
        ------------
        This function returns an XML-RPC array in which each item is a list of
322
323
        device hostname, device type, device state, current running job id and
        if device is pipeline. For example:
324

325
        [['panda01', 'panda', 'running', 'good', 164, False], ['qemu01', 'qemu', 'idle', 'unknwon', None, True]]
326
327
        """

328
        devices_list = []
329
        for dev in Device.objects.exclude(health=Device.HEALTH_RETIRED):
330
331
            if not dev.is_visible_to(self.user):
                continue
332
            devices_list.append(dev)
333

334
335
336
337
338
339
340
341
342
343
        return [
            [
                dev.hostname,
                dev.device_type.name,
                build_device_status_display(dev.state, dev.health),
                dev.current_job().pk if dev.current_job() else None,
                True,
            ]
            for dev in devices_list
        ]
344
345
346
347
348
349
350
351
352
353

    def all_device_types(self):
        """
        Name
        ----
        `all_device_types` ()

        Description
        -----------
        Get all the available device types with their state and count
354
        information.
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369

        Arguments
        ---------
        None

        Return value
        ------------
        This function returns an XML-RPC array in which each item is a dict
        which contains name (device type), idle, busy, offline counts.
        For example:

        [{'idle': 1, 'busy': 0, 'name': 'panda', 'offline': 0},
        {'idle': 1, 'busy': 0, 'name': 'qemu', 'offline': 0}]
        """

370
371
        device_type_names = []
        all_device_types = []
372
        keys = ["busy", "idle", "offline"]
373

374
        for dev_type in DeviceType.objects.all():
375
            if not dev_type.some_devices_visible_to(self.user):
376
                continue
377
            device_type_names.append(dev_type.name)
378

Neil Williams's avatar
Neil Williams committed
379
        device_types = device_type_summary(device_type_names)
380
381

        for dev_type in device_types:
382
            device_type = {"name": dev_type["device_type"]}
383
            for key in keys:
Neil Williams's avatar
Neil Williams committed
384
                device_type[key] = dev_type[key]
385
            all_device_types.append(device_type)
386

387
        return all_device_types
388

389
390
391
    def get_recent_jobs_for_device_type(
        self, device_type, count=1, restrict_to_user=False
    ):
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
424
425
426
427
428
429
430
431
432
433
434
435
        """
        Name
        ----

        `get_recent_jobs_for_device_type` (`device_type`, `count=1`, `restrict_to_user=False`)

        Description
        -----------
        Get details of recently finished jobs for a given device_type. Limits the list
        to test jobs submitted by the user making the query if restrict_to_user is set to
        True. Get only the most recent job by default, but count can be set higher to
        get for example the last 10 jobs.

        Arguments
        ---------
        `device_type`: string
            Name of the device_type for which you want the jobs
        `count`: integer (Optional, default=1)
            Number of last jobs you want
        `restrict_to_user`: boolean (Optional, default=False)
            Fetch only the jobs submitted by the user making the query if set to True

        Return value
        ------------
        This function returns a list of dictionaries, which correspond to the
        list of recently finished jobs informations (Complete or Incomplete)
        for this device, ordered from youngest to oldest.

        [
            {
                'description': 'ramdisk health check',
                'id': 359828,
                'status': 'Complete',
                'device': 'black01'
            },
            {
                'description': 'standard ARMMP NFS',
                'id': 359827
                'status': 'Incomplete',
                'device': 'black02'
            }
        ]
        """
        if not device_type:
Neil Williams's avatar
Neil Williams committed
436
            raise xmlrpc.client.Fault(
437
438
439
                400, "Bad request: device_type was not specified."
            )
        if count < 0:
440
            raise xmlrpc.client.Fault(400, "Bad request: count must not be negative.")
441
442
443
        try:
            dt = DeviceType.objects.get(name=device_type, display=True)
        except Device.DoesNotExist:
Neil Williams's avatar
Neil Williams committed
444
            raise xmlrpc.client.Fault(
445
446
447
448
                404, "DeviceType '%s' was not found." % device_type
            )

        if not dt.some_devices_visible_to(self.user):
Neil Williams's avatar
Neil Williams committed
449
            raise xmlrpc.client.Fault(
450
451
452
                403,
                "DeviceType '%s' not available to user '%s'."
                % (device_type, self.user),
453
            )
454
455
456
457
458
        job_qs = (
            TestJob.objects.filter(state=TestJob.STATE_FINISHED)
            .filter(requested_device_type=dt)
            .order_by("-id")
        )
459
460
461
462
        if restrict_to_user:
            job_qs = job_qs.filter(submitter=self.user)
        job_list = []
        for job in job_qs.all()[:count]:
463
            hostname = ""
464
465
            if job.actual_device:
                hostname = job.actual_device.hostname
466
467
468
            job_dict = {
                "id": job.id,
                "description": job.description,
Rémi Duraffort's avatar
Rémi Duraffort committed
469
                "status": job.get_legacy_status_display(),
470
                "device": hostname,
471
472
473
474
475
476
            }
            if not job.can_view(self.user):
                job_dict["id"] = None
            job_list.append(job_dict)
        return job_list

477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
    def get_recent_jobs_for_device(self, device, count=1, restrict_to_user=False):
        """
        Name
        ----

        `get_recent_jobs_for_device` (`device`, `count=1`, `restrict_to_user=False`)

        Description
        -----------
        Get details of recently finished jobs for a given device. Limits the list
        to test jobs submitted by the user making the query if restrict_to_user is set to
        True. Get only the most recent job by default, but count can be set higher to
        get for example the last 10 jobs.

        Arguments
        ---------
        `device`: string
            Name of the device for which you want the jobs
        `count`: integer (Optional, default=1)
            Number of last jobs you want
        `restrict_to_user`: boolean (Optional, default=False)
            Fetch only the jobs submitted by the user making the query if set to True

        Return value
        ------------
        This function returns a list of dictionaries, which correspond to the
        list of recently finished jobs informations (Complete or Incomplete)
        for this device, ordered from youngest to oldest.

        [
            {
                'description': 'mainline--armada-370-db--multi_v7_defconfig--network',
                'id': 359828,
                'status': 'Complete'
            },
            {
                'description': 'mainline--armada-370-db--multi_v7_defconfig--sata',
                'id': 359827
                'status': 'Incomplete'
            }
        ]
        """
        if not device:
520
            raise xmlrpc.client.Fault(400, "Bad request: device was not specified.")
521
        if count < 0:
522
            raise xmlrpc.client.Fault(400, "Bad request: count must not be negative.")
523
524
525
        try:
            device_obj = Device.objects.get(hostname=device)
        except Device.DoesNotExist:
526
            raise xmlrpc.client.Fault(404, "Device '%s' was not found." % device)
527
528

        if not device_obj.is_visible_to(self.user):
Neil Williams's avatar
Neil Williams committed
529
            raise xmlrpc.client.Fault(
530
                403, "Device '%s' not available to user '%s'." % (device, self.user)
531
            )
532
533
534
535
536
        job_qs = (
            TestJob.objects.filter(state=TestJob.STATE_FINISHED)
            .filter(actual_device=device_obj)
            .order_by("-id")
        )
537
538
539
540
541
542
543
        if restrict_to_user:
            job_qs = job_qs.filter(submitter=self.user)
        job_list = []
        for job in job_qs.all()[:count]:
            job_dict = {
                "id": job.id,
                "description": job.description,
Rémi Duraffort's avatar
Rémi Duraffort committed
544
                "status": job.get_legacy_status_display(),
545
546
547
548
549
550
            }
            if not job.can_view(self.user):
                job_dict["id"] = None
            job_list.append(job_dict)
        return job_list

551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
    def get_device_type_by_alias(self, alias):
        """
        Name
        ----

        `get_device_type_by_alias` (`alias`)

        Description
        -----------
        Get the matching device-type(s) for the specified alias. It is
        possible that more than one device-type can be returned, depending
        on local admin configuration. An alias can be used to provide the
        link between the device-type name and the Device Tree name.
        It is possible for multiple device-types to have the same alias
        (to assist in transitions and migrations).
        The specified alias string can be a partial match, returning all
        device-types which have an alias name containing the requested
        string.

        Arguments
        ---------
        `alias`: string
            Name of the alias to lookup

        Return value
        ------------
        This function returns a dictionary containing the alias as the key
        and a list of device-types which use that alias as the value. If the
        specified alias does not match any device-type, the dictionary contains
        an empty list for the alias key.

        {'apq8016-sbc': ['dragonboard410c']}
        {'ompa4-panda': ['panda', 'panda-es']}
        """

        aliases = DeviceType.objects.filter(aliases__name__contains=alias)
587
        return {alias: [device_type.name for device_type in aliases]}
588

589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
    def get_device_status(self, hostname):
        """
        Name
        ----
        `get_device_status` (`hostname`)

        Description
        -----------
        Get status, running job, date from which it is offline of the given
        device and the user who put it offline.

        Arguments
        ---------
        `hostname`: string
            Name of the device for which the status is asked.

        Return value
        ------------
        This function returns an XML-RPC dictionary which contains hostname,
        status, date from which the device is offline if the device is offline,
        the user who put the device offline if the device is offline and the
        job id of the running job.
        The device has to be visible to the user who requested device's status.

        Note that offline_since and offline_by can be empty strings if the device
        status is manually changed by an administrator in the database or from
        the admin site of LAVA even if device's status is offline.
        """

        if not hostname:
619
            raise xmlrpc.client.Fault(400, "Bad request: Hostname was not specified.")
620
621
622
        try:
            device = Device.objects.get(hostname=hostname)
        except Device.DoesNotExist:
623
            raise xmlrpc.client.Fault(404, "Device '%s' was not found." % hostname)
624
625
626
627

        device_dict = {}
        if device.is_visible_to(self.user):
            device_dict["hostname"] = device.hostname
628
629
630
            device_dict["status"] = build_device_status_display(
                device.state, device.health
            )
631
632
633
            device_dict["job"] = None
            device_dict["offline_since"] = None
            device_dict["offline_by"] = None
Rémi Duraffort's avatar
Rémi Duraffort committed
634
            device_dict["is_pipeline"] = True
635

636
637
638
            current_job = device.current_job()
            if current_job is not None:
                device_dict["job"] = current_job.pk
639
        else:
Neil Williams's avatar
Neil Williams committed
640
            raise xmlrpc.client.Fault(
641
642
643
644
                403, "Permission denied for user to access %s information." % hostname
            )
        return device_dict

645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
    def put_into_maintenance_mode(self, hostname, reason, notify=None):
        """
        Name
        ----
        `put_into_maintenance_mode` (`hostname`, `reason`, `notify`)

        Description
        -----------
        Put the given device in maintenance mode with the given reason and optionally
        notify the given mail address when the job has finished.

        Arguments
        ---------
        `hostname`: string
            Name of the device to put into maintenance mode.
        `reason`: string
            The reason given to justify putting the device into maintenance mode.
        `notify`: string
            Email address of the user to notify when the job has finished. Can be
            omitted.

        Return value
        ------------
        None. The user should be authenticated with a username and token and has
        sufficient permission.
        """

        self._authenticate()
        if not hostname:
674
            raise xmlrpc.client.Fault(400, "Bad request: Hostname was not specified.")
675
        if not reason:
676
            raise xmlrpc.client.Fault(400, "Bad request: Reason was not specified.")
677
678
679
680
        with transaction.atomic():
            try:
                device = Device.objects.select_for_update().get(hostname=hostname)
            except Device.DoesNotExist:
681
                raise xmlrpc.client.Fault(404, "Device '%s' was not found." % hostname)
682
683
684
685
            if device.can_admin(self.user):
                device.health = Device.HEALTH_MAINTENANCE
                device.save()
            else:
Neil Williams's avatar
Neil Williams committed
686
                raise xmlrpc.client.Fault(
687
688
689
                    403,
                    "Permission denied for user to put %s into maintenance mode."
                    % hostname,
690
                )
691

692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
    def put_into_online_mode(self, hostname, reason, skip_health_check=False):
        """
        Name
        ----
        `put_into_online_mode` (`hostname`, `reason`, `skip_health_check`)

        Description
        -----------
        Put the given device into online mode with the given reason ans skip health
        check if asked.

        Arguments
        ---------
        `hostname`: string
            Name of the device to put into online mode.
        `reason`: string
            The reason given to justify putting the device into online mode.
        `skip_health_check`: boolean
            Skip health check when putting the board into online mode. If
            omitted, health check is not skipped by default.

        Return value
        ------------
        None. The user should be authenticated with a username and token and has
        sufficient permission.
        """

        self._authenticate()
        if not hostname:
721
            raise xmlrpc.client.Fault(400, "Bad request: Hostname was not specified.")
722
        if not reason:
723
            raise xmlrpc.client.Fault(400, "Bad request: Reason was not specified.")
724
725
726
727
        with transaction.atomic():
            try:
                device = Device.objects.select_for_update().get(hostname=hostname)
            except Device.DoesNotExist:
728
                raise xmlrpc.client.Fault(404, "Device '%s' was not found." % hostname)
729
730
731
732
            if device.can_admin(self.user):
                device.health = Device.HEALTH_UNKNOWN
                device.save()
            else:
Neil Williams's avatar
Neil Williams committed
733
                raise xmlrpc.client.Fault(
734
735
                    403,
                    "Permission denied for user to put %s into online mode." % hostname,
736
                )
737

738
    def pending_jobs_by_device_type(self, all=False):
739
740
741
        """
        Name
        ----
742
        `pending_jobs_by_device_type` ()
743
744
745

        Description
        -----------
746
        Get number of pending jobs in each device type.
747
748
        Private test jobs and hidden device types are
        excluded, except for authenticated superusers.
749
750
751

        Arguments
        ---------
752
        `all`: boolean - include retired devices and undisplayed device-types in the listing.
753
754
755

        Return value
        ------------
756
757
        This function returns a dict where the key is the device type and
        the value is the number of jobs pending in that device type.
758
759
        For example:

760
        {'qemu': 0, 'panda': 3}
761
762
        """

763
        pending_jobs_by_device = {}
764

765
766
767
768
769
770
        jobs_res = TestJob.objects.filter(state=TestJob.STATE_SUBMITTED)
        jobs_res = jobs_res.exclude(requested_device_type_id__isnull=True)

        if not self.user or not self.user.is_superuser:
            jobs_res = jobs_res.filter(is_public=True)

771
772
        jobs_res = jobs_res.values_list("requested_device_type_id")
        jobs_res = jobs_res.annotate(pending_jobs=(Count("id")))
773

774
775
776
        jobs = {}
        jobs_hash = dict(jobs_res)
        for job in jobs_hash:
777
            jobs[job] = jobs_hash[job]
778
        pending_jobs_by_device.update(jobs)
779

780
        # Get rest of the devices and put number of pending jobs as 0.
781
        if all:
782
            device_types = DeviceType.objects.all()
783
        else:
784
            device_types = active_device_types()
785
786

        if not self.user or not self.user.is_superuser:
787
            device_types = device_types.filter(owners_only=False)
788

789
        for device_type in device_types.values_list("name", flat=True):
790
791
            if device_type not in pending_jobs_by_device:
                pending_jobs_by_device[device_type] = 0
Neil Williams's avatar
Neil Williams committed
792

793
        return pending_jobs_by_device
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813

    def job_details(self, job_id):
        """
        Name
        ----
        `job_details` (`job_id`)

        Description
        -----------
        Get the details of given job id.

        Arguments
        ---------
        `job_id`: string
            Job id for which the output is required.

        Return value
        ------------
        This function returns an XML-RPC structures of job details, provided
        the user is authenticated with an username and token.
814
815

        The elements available in XML-RPC structure include:
Rémi Duraffort's avatar
Rémi Duraffort committed
816
        _state, submitter_id, is_pipeline, id, failure_comment,
817
818
        multinode_definition, user_id, priority, _actual_device_cache,
        original_definition, status, health_check, description,
819
820
821
822
        start_time, target_group, visibility, pipeline_compatibility,
        submit_time, is_public, _old_status, actual_device_id, definition,
        sub_id, requested_device_type_id, end_time, group_id, absolute_url,
        submitter_username
823
        """
824
        self._authenticate()
825
        if not job_id:
826
            raise xmlrpc.client.Fault(400, "Bad request: TestJob id was not specified.")
827
        try:
828
            job = get_restricted_job(self.user, job_id)
Rémi Duraffort's avatar
Rémi Duraffort committed
829
            job.status = job.get_legacy_status_display()
830
831
            job.state = job.get_state_display()
            job.health = job.get_health_display()
832
            job.submitter_username = job.submitter.username
833
            job.absolute_url = job.get_absolute_url()
Rémi Duraffort's avatar
Rémi Duraffort committed
834
            job.is_pipeline = True
835
        except PermissionDenied:
Neil Williams's avatar
Neil Williams committed
836
            raise xmlrpc.client.Fault(
837
838
                401, "Permission denied for user to job %s" % job_id
            )
839
        except TestJob.DoesNotExist:
Neil Williams's avatar
Neil Williams committed
840
            raise xmlrpc.client.Fault(404, "Specified job not found.")
841
842

        return job
843
844
845
846
847

    def job_status(self, job_id):
        """
        Name
        ----
848
849
        DEPRECATED - use `job_health` or `job_state` instead.

850
        `job_status` (`job_id`)
851
852
853
854
855
856
857
858
859
860
861
862

        Description
        -----------
        Get the status of given job id.

        Arguments
        ---------
        `job_id`: string
            Job id for which the output is required.

        Return value
        ------------
863
864
        This function returns an XML-RPC structures of job status with the
        following fields.
865
        The user is authenticated with an username and token.
Neil Williams's avatar
Neil Williams committed
866

867
        `job_status`: string
868
        ['Submitted'|'Running'|'Complete'|'Incomplete'|'Canceled'|'Canceling']
869
870

        `bundle_sha1`: string
871
        The sha1 hash code of the bundle, if it existed. Otherwise it will be
872
        an empty string. (LAVA V1 only)
873
        """
874
875
        self._authenticate()
        if not job_id:
876
            raise xmlrpc.client.Fault(400, "Bad request: TestJob id was not specified.")
877
        try:
878
            job = get_restricted_job(self.user, job_id)
879
        except PermissionDenied:
Neil Williams's avatar
Neil Williams committed
880
            raise xmlrpc.client.Fault(
881
882
                401, "Permission denied for user to job %s" % job_id
            )
883
        except TestJob.DoesNotExist:
Neil Williams's avatar
Neil Williams committed
884
            raise xmlrpc.client.Fault(404, "Specified job not found.")
885

886
        job_status = {"job_id": job.id}
887
888

        if job.is_multinode:
889
890
891
892
893
            job_status.update({"sub_id": job.sub_id})

        job_status.update(
            {"job_status": job.get_legacy_status_display(), "bundle_sha1": ""}
        )
894
        return job_status
895

896
897
898
899
    def job_list_status(self, job_id_list):
        """
        Name
        ----
900
901
        DEPRECATED - use `job_health` or `job_state` instead.

902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
        job_list_status ([job_id, job_id, job_id])

        Description
        -----------
        Get the status of a list of job ids.

        Arguments
        ---------
        `job_id_list`: list
            List of job ids for which the output is required.
            For multinode jobs specify the job sub_id as a float
            in the XML-RPC call:
            job_list_status([1, 2, 3,1, 5])

        Return value
        ------------
        The user needs to be authenticated with an username and token.

        This function returns an XML-RPC structure of job status with the
        following content.

        `job_status`: string
        {ID: ['Submitted'|'Running'|'Complete'|'Incomplete'|'Canceled'|'Canceling']}

        If the user is not able to view one of the specified jobs, that entry
        will be omitted.

        """
        self._authenticate()
        job_status = {}
        # optimise the query for a long list instead of using the
        # convenience handlers
        if not isinstance(job_id_list, list):
Neil Williams's avatar
Neil Williams committed
935
            raise xmlrpc.client.Fault(400, "Bad request: needs to be a list")
936
        if not all(isinstance(chk, (float, int)) for chk in job_id_list):
937
938
939
            raise xmlrpc.client.Fault(
                400, "Bad request: needs to be a list of integers or floats"
            )
940
        jobs = TestJob.objects.filter(
941
942
            Q(id__in=job_id_list) | Q(sub_id__in=job_id_list)
        ).select_related("actual_device", "requested_device_type")
943
        for job in jobs:
Rémi Duraffort's avatar
Rémi Duraffort committed
944
            device_type = job.requested_device_type
945
946
947
948
949
            if (
                not job.can_view(self.user)
                or not job.is_accessible_by(self.user)
                and not self.user.is_superuser
            ):
950
                continue
Rémi Duraffort's avatar
Rémi Duraffort committed
951
            if device_type and device_type.owners_only:
952
                # do the more expensive check second and only for a hidden device type
953
                if not device_type.some_devices_visible_to(self.user):
954
                    continue
Rémi Duraffort's avatar
Rémi Duraffort committed
955
            job_status[str(job.display_id)] = job.get_legacy_status_display()
956
957
        return job_status

958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
    def job_health(self, job_id):
        """
        Name
        ----
        `job_health` (`job_id`)

        Description
        -----------
        Get the health of given job id.

        Arguments
        ---------
        `job_id`: string
            Job id for which the output is required.

        Return value
        ------------
        This function returns an XML-RPC structures of job health with the
        following fields.
        The user is authenticated with an username and token.

        `job_health`: string
        ['Unknown'|'Complete'|'Incomplete'|'Canceled']
        """
        self._authenticate()
        if not job_id:
984
            raise xmlrpc.client.Fault(400, "Bad request: TestJob id was not specified.")
985
986
987
        try:
            job = get_restricted_job(self.user, job_id)
        except PermissionDenied:
Neil Williams's avatar
Neil Williams committed
988
            raise xmlrpc.client.Fault(
989
990
                401, "Permission denied for user to job %s" % job_id
            )
991
        except TestJob.DoesNotExist:
Neil Williams's avatar
Neil Williams committed
992
            raise xmlrpc.client.Fault(404, "Specified job not found.")
993

994
        job_health = {"job_id": job.id, "job_health": job.get_health_display()}
995
996

        if job.is_multinode:
997
            job_health.update({"sub_id": job.sub_id})
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026

        return job_health

    def job_state(self, job_id):
        """
        Name
        ----
        `job_state` (`job_id`)

        Description
        -----------
        Get the state of given job id.

        Arguments
        ---------
        `job_id`: string
            Job id for which the output is required.

        Return value
        ------------
        This function returns an XML-RPC structures of job state with the
        following fields.
        The user is authenticated with an username and token.

        `job_state`: string
        ['Submitted'|'Scheduling'|'Scheduled'|'Running'|'Canceling'|'Finished']
        """
        self._authenticate()
        if not job_id:
1027
            raise xmlrpc.client.Fault(400, "Bad request: TestJob id was not specified.")
1028
1029
1030
        try:
            job = get_restricted_job(self.user, job_id)
        except PermissionDenied:
Neil Williams's avatar
Neil Williams committed
1031
            raise xmlrpc.client.Fault(
1032
1033
                401, "Permission denied for user to job %s" % job_id
            )
1034
        except TestJob.DoesNotExist:
Neil Williams's avatar
Neil Williams committed
1035
            raise xmlrpc.client.Fault(404, "Specified job not found.")
1036

1037
        job_state = {"job_id": job.id, "job_state": job.get_state_display()}
1038
1039

        if job.is_multinode:
1040
            job_state.update({"sub_id": job.sub_id})
1041
1042
1043

        return job_state

1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
    def all_jobs(self):
        """
        Name
        ----
        `all_jobs` ()

        Description
        -----------
        Get submitted or running jobs.

        Arguments
        ---------
        None

        Return value
        ------------
        This function returns a XML-RPC array of submitted and running jobs with their status and
        actual device for running jobs and requested device or device type for submitted jobs and
        job sub_id for multinode jobs.
        For example:

1065
1066
1067
        [[73, 'multinode-job', 'submitted', None, 'kvm', '72.1'],
        [72, 'multinode-job', 'submitted', None, 'kvm', '72.0'],
        [71, 'test-job', 'running', 'kvm01', None, None]]
1068
1069
        """

1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
        jobs = TestJob.objects.exclude(state=TestJob.STATE_FINISHED).order_by("-id")
        jobs_list = [
            [
                job.id,
                job.description,
                job.get_legacy_status_display().lower(),
                job.actual_device,
                job.requested_device_type,
                job.sub_id,
            ]
            for job in jobs
        ]
1082
1083

        return jobs_list
1084
1085
1086
1087
1088

    def get_pipeline_device_config(self, device_hostname):
        """
        Name
        ----
1089
1090
        DEPRECATED - use `get_device_config` instead.

1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
        `get_pipeline_device_config` (`device_hostname`)

        Description
        -----------
        Get the pipeline device configuration for given device hostname.

        Arguments
        ---------
        `device_hostname`: string
            Device hostname for which the configuration is required.

1102
1103
1104
1105
        Return value
        ------------
        This function returns an XML-RPC binary data of output file.
        """
1106
        return self.get_device_config(device_hostname)
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129

    def get_device_config(self, device_hostname, context=None):
        """
        New in api_version 2 - see system.api_version()

        Name
        ----
        `get_device_config` (`device_hostname`, context=None)

        Description
        -----------
        Get the device configuration for given device hostname.

        Arguments
        ---------
        `device_hostname`: string
            Device hostname for which the configuration is required.

        Some device templates need a context specified when processing the
        device-type template. This can be specified as a YAML string:

        `get_device_config` `('qemu01', '{arch: amd64}')`

1130
1131
1132
1133
1134
        Return value
        ------------
        This function returns an XML-RPC binary data of output file.
        """
        if not device_hostname:
Neil Williams's avatar
Neil Williams committed
1135
            raise xmlrpc.client.Fault(
1136
1137
                400, "Bad request: Device hostname was not specified."
            )
1138

1139
1140
1141
        job_ctx = None
        if context is not None:
            try:
1142
                job_ctx = yaml.safe_load(context)
1143
            except yaml.YAMLError as exc:
Neil Williams's avatar
Neil Williams committed
1144
                raise xmlrpc.client.Fault(
1145
1146
                    400, "Job context '%s' is not valid. %s" % (context, exc)
                )
1147
1148
1149
        try:
            device = Device.objects.get(hostname=device_hostname)
        except Device.DoesNotExist:
Neil Williams's avatar
Neil Williams committed
1150
            raise xmlrpc.client.Fault(404, "Specified device was not found.")
1151

1152
        config = device.load_configuration(job_ctx=job_ctx, output_format="yaml")
1153
1154

        # validate against the device schema
1155
        validate_device(yaml.safe_load(config))
1156

1157
        return xmlrpc.client.Binary(config.encode("UTF-8"))
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175

    def import_device_dictionary(self, hostname, jinja_str):
        """
        Name
        ----
        `import_device_dictionary` (`device_hostname`, `jinja_string`)

        Description
        -----------
        [superuser only]
        Import or update the device dictionary key value store for a
        pipeline device.

        Arguments
        ---------
        `device_hostname`: string
            Device hostname to update.
        `jinja_str`: string
1176
            Device configuration as Jinja2
1177
1178
1179
1180
1181
1182
1183

        Return value
        ------------
        This function returns an XML-RPC binary data of output file.
        """
        self._authenticate()
        if not self.user.is_superuser:
Neil Williams's avatar
Neil Williams committed
1184
            raise xmlrpc.client.Fault(
1185
                403, "User '%s' is not superuser." % self.user.username
1186
1187
            )
        try:
1188
            device = Device.objects.get(hostname=hostname)
1189
        except DeviceType.DoesNotExist:
1190
            raise xmlrpc.client.Fault(404, "Device '%s' was not found." % hostname)
1191
        if not device.save_configuration(jinja_str):
Neil Williams's avatar
Neil Williams committed
1192
            raise xmlrpc.client.Fault(
1193
                400, "Unable to store the configuration for %s on disk" % hostname
1194
            )
1195
1196

        return "Device dictionary updated for %s" % hostname
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222

    def export_device_dictionary(self, hostname):
        """
        Name
        ----
        `export_device_dictionary` (`device_hostname`)

        Description
        -----------
        [superuser only]
        Export the device dictionary key value store for a
        pipeline device.

        See also get_pipeline_device_config

        Arguments
        ---------
        `device_hostname`: string
            Device hostname to update.

        Return value
        ------------
        This function returns an XML-RPC binary data of output file.
        """
        self._authenticate()
        if not self.user.is_superuser:
Neil Williams's avatar
Neil Williams committed
1223
            raise xmlrpc.client.Fault(
1224
                403, "User '%s' is not superuser." % self.user.username
1225
1226
1227
1228
            )
        try:
            device = Device.objects.get(hostname=hostname)
        except DeviceType.DoesNotExist:
1229
            raise xmlrpc.client.Fault(404, "Device '%s' was not found." % hostname)
1230
        device_dict = device.load_configuration(output_format="raw")
1231
        if not device_dict:
Neil Williams's avatar
Neil Williams committed
1232
            raise xmlrpc.client.Fault(