__init__.py 42.7 KB
Newer Older
1
2
from functools import wraps
from simplejson import JSONDecodeError
3
import yaml
4
import sys
5

6
from django.conf import settings
7
from django.core.exceptions import PermissionDenied
8
from django.db.models import Count, Q
9
from django.db import transaction
10
from linaro_django_xmlrpc.models import ExposedAPI
11
12
13
from lava_scheduler_app.models import (
    Device,
    DeviceType,
14
    JSONDataError,
15
    DevicesUnavailableException,
16
    TestJob,
Neil Williams's avatar
Neil Williams committed
17
)
18
from lava_scheduler_app.views import (
19
    get_restricted_job
20
)
21
22
23
from lava_scheduler_app.dbutils import (
    device_type_summary,
    testjob_submission
24
)
25
26
27
28
29
30
from lava_scheduler_app.schema import (
    validate_submission,
    validate_device,
    SubmissionException,
)

31
32
33
34
35
36
37
if sys.version_info[0] == 2:
    # Python 2.x
    import xmlrpclib
elif sys.version_info[0] == 3:
    # For Python 3.0 and later
    import xmlrpc.client as xmlrpclib

38
39
# 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
40

Neil Williams's avatar
Neil Williams committed
41
42
43
# 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
44

45
46
47
48
49
50
51
52
53
54
55
56
57
58
def check_superuser(f):
    """ decorator to check that the caller is a super-user """
    @wraps(f)
    def wrapper(self, *args, **kwargs):
        self._authenticate()
        if not self.user.is_superuser:
            raise xmlrpclib.Fault(
                403,
                "User '%s' is not superuser." % self.user.username
            )
        return f(self, *args, **kwargs)
    return wrapper


59
60
61
def build_device_status_display(state, health):
    if state == Device.STATE_IDLE:
        if health in [Device.HEALTH_GOOD, Device.HEALTH_UNKNOWN]:
62
            return "idle"
63
        elif health == Device.HEALTH_RETIRED:
64
            return "retired"
65
        else:
66
            return "offline"
67
    elif state == Device.STATE_RESERVED:
68
        return "reserved"
69
    else:
70
        return "running"
71
72


73
74
75
class SchedulerAPI(ExposedAPI):

    def submit_job(self, job_data):
76
77
78
79
80
81
82
        """
        Name
        ----
        `submit_job` (`job_data`)

        Description
        -----------
83
84
        Submit the given job data which is in LAVA job JSON or YAML format as a
        new job to LAVA scheduler.
85
86
87
88

        Arguments
        ---------
        `job_data`: string
89
            Job JSON or YAML string.
90
91
92
93

        Return value
        ------------
        This function returns an XML-RPC integer which is the newly created
94
        job's id, provided the user is authenticated with an username and token.
95
96
        If the job is a multinode job, this function returns the list of created
        job IDs.
97
        """
98
        self._authenticate()
Michael-Doyle Hudson's avatar
Michael-Doyle Hudson committed
99
        if not self.user.has_perm('lava_scheduler_app.add_testjob'):
100
101
102
103
            raise xmlrpclib.Fault(
                403, "Permission denied.  User %r does not have the "
                "'lava_scheduler_app.add_testjob' permission.  Contact "
                "the administrators." % self.user.username)
Neil Williams's avatar
Neil Williams committed
104
        try:
105
106
            job = testjob_submission(job_data, self.user)
        except SubmissionException as exc:
107
            raise xmlrpclib.Fault(400, "Problem with submitted job data: %s" % exc)
Rémi Duraffort's avatar
Rémi Duraffort committed
108
        # FIXME: json error is not needed anymore
Neil Williams's avatar
Neil Williams committed
109
110
        except (JSONDataError, JSONDecodeError, ValueError) as exc:
            raise xmlrpclib.Fault(400, "Decoding job submission failed: %s." % exc)
111
112
        except (Device.DoesNotExist, DeviceType.DoesNotExist):
            raise xmlrpclib.Fault(404, "Specified device or device type not found.")
113
        except DevicesUnavailableException as exc:
Rémi Duraffort's avatar
Rémi Duraffort committed
114
            raise xmlrpclib.Fault(400, "Device unavailable: %s" % str(exc))
115
        if isinstance(job, type(list())):
116
            return [j.sub_id for j in job]
117
118
        else:
            return job.id
119

120
    def resubmit_job(self, job_id):
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
        """
        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.
        """
141
142
143
144
145
146
        self._authenticate()
        if not self.user.has_perm('lava_scheduler_app.add_testjob'):
            raise xmlrpclib.Fault(
                403, "Permission denied.  User %r does not have the "
                "'lava_scheduler_app.add_testjob' permission.  Contact "
                "the administrators." % self.user.username)
Paul Larson's avatar
Paul Larson committed
147
        try:
148
            job = get_restricted_job(self.user, job_id)
Paul Larson's avatar
Paul Larson committed
149
150
        except TestJob.DoesNotExist:
            raise xmlrpclib.Fault(404, "Specified job not found.")
151

152
        if job.is_multinode:
153
154
155
            return self.submit_job(job.multinode_definition)
        else:
            return self.submit_job(job.definition)
156

157
    def cancel_job(self, job_id):
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
        """
        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.
        """
176
177
178
179
180
        self._authenticate()
        if not job_id:
            raise xmlrpclib.Fault(400, "Bad request: TestJob id was not "
                                  "specified.")

181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
        with transaction.atomic():
            try:
                job = get_restricted_job(self.user, job_id, for_update=True)
            except PermissionDenied:
                raise xmlrpclib.Fault(
                    401, "Permission denied for user to job %s" % job_id)
            except TestJob.DoesNotExist:
                raise xmlrpclib.Fault(404, "Specified job not found.")

            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):
                raise xmlrpclib.Fault(403, "Permission denied.")

            if job.is_multinode:
                multinode_jobs = TestJob.objects.select_for_update().filter(
                    target_group=job.target_group)
                for multinode_job in multinode_jobs:
                    multinode_job.go_state_canceling()
                    multinode_job.save()
            else:
                job.go_state_canceling()
                job.save()
205
        return True
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
    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
            yaml_data = yaml.load(yaml_string)
        except yaml.YAMLError as exc:
            raise xmlrpclib.Fault(400, "Decoding job submission failed: %s." % exc)
        try:
            # validate against the submission schema.
            validate_submission(yaml_data)  # raises SubmissionException if invalid.
        except SubmissionException as exc:
            raise xmlrpclib.Fault(400, "Invalid YAML submission: %s" % exc)

242
    def job_output(self, job_id, offset=0):
243
244
245
        """
        Name
        ----
246
        `job_output` (`job_id`, `offset=0`)
247
248
249
250
251
252
253
254
255

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

        Arguments
        ---------
        `job_id`: string
            Job id for which the output is required.
256
257
258
        `offset`: integer
            Offset from which to start reading the output file specified in bytes.
            It defaults to 0.
259
260
261

        Return value
        ------------
262
263
        This function returns an XML-RPC binary data of output file, provided
        the user is authenticated with an username and token.
264
        """
265
266
267
268
        self._authenticate()
        if not job_id:
            raise xmlrpclib.Fault(400, "Bad request: TestJob id was not "
                                  "specified.")
269
        try:
270
            job = get_restricted_job(self.user, job_id)
271
272
        except PermissionDenied:
            raise xmlrpclib.Fault(
273
                401, "Permission denied for user to job %s" % job_id)
274
275
276
        except TestJob.DoesNotExist:
            raise xmlrpclib.Fault(404, "Specified job not found.")

277
278
        output_file = job.output_file()
        if output_file:
279
            output_file.seek(offset)
280
281
282
            return xmlrpclib.Binary(output_file.read().encode('UTF-8'))
        else:
            raise xmlrpclib.Fault(404, "Job output not found.")
283
284
285
286
287
288
289
290
291

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

        Description
        -----------
292
        Get all the available devices with their state and type information.
293
294
295
296
297
298
299
300

        Arguments
        ---------
        None

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

304
        [['panda01', 'panda', 'running', 'good', 164, False], ['qemu01', 'qemu', 'idle', 'unknwon', None, True]]
305
306
        """

307
        devices_list = []
308
        for dev in Device.objects.exclude(health=Device.HEALTH_RETIRED):
309
310
            if not dev.is_visible_to(self.user):
                continue
311
            devices_list.append(dev)
312

313
        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, dev.is_pipeline]
314
                for dev in devices_list]
315
316
317
318
319
320
321
322
323
324

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

        Description
        -----------
        Get all the available device types with their state and count
325
        information.
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340

        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}]
        """

341
342
        device_type_names = []
        all_device_types = []
Neil Williams's avatar
Neil Williams committed
343
        keys = ['busy', 'idle', 'offline']
344

345
        for dev_type in DeviceType.objects.all():
346
            if not dev_type.some_devices_visible_to(self.user):
347
                continue
348
            device_type_names.append(dev_type.name)
349

Neil Williams's avatar
Neil Williams committed
350
        device_types = device_type_summary(device_type_names)
351
352

        for dev_type in device_types:
Neil Williams's avatar
Neil Williams committed
353
            device_type = {'name': dev_type['device_type']}
354
            for key in keys:
Neil Williams's avatar
Neil Williams committed
355
                device_type[key] = dev_type[key]
356
            all_device_types.append(device_type)
357

358
        return all_device_types
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
    def get_recent_jobs_for_device_type(self, device_type, count=1, restrict_to_user=False):
        """
        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:
            raise xmlrpclib.Fault(
                400, "Bad request: device_type was not specified."
            )
        if count < 0:
            raise xmlrpclib.Fault(
                400, "Bad request: count must not be negative."
            )
        try:
            dt = DeviceType.objects.get(name=device_type, display=True)
        except Device.DoesNotExist:
            raise xmlrpclib.Fault(
                404, "DeviceType '%s' was not found." % device_type
            )

        if not dt.some_devices_visible_to(self.user):
            raise xmlrpclib.Fault(
                403, "DeviceType '%s' not available to user '%s'." %
                (device_type, self.user)
            )
424
425
426
        job_qs = TestJob.objects.filter(state=TestJob.STATE_FINISHED) \
                                .filter(requested_device_type=dt) \
                                .order_by('-id')
427
428
429
430
431
432
433
        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
434
                "status": job.get_legacy_status_display(),
435
436
437
438
439
440
441
                "device": job.actual_device.hostname,
            }
            if not job.can_view(self.user):
                job_dict["id"] = None
            job_list.append(job_dict)
        return job_list

442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
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
    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:
            raise xmlrpclib.Fault(
                400, "Bad request: device was not specified."
            )
        if count < 0:
            raise xmlrpclib.Fault(
                400, "Bad request: count must not be negative."
            )
        try:
            device_obj = Device.objects.get(hostname=device)
        except Device.DoesNotExist:
            raise xmlrpclib.Fault(
                404, "Device '%s' was not found." % device
            )

        if not device_obj.is_visible_to(self.user):
            raise xmlrpclib.Fault(
                403, "Device '%s' not available to user '%s'." %
                (device, self.user)
            )
504
505
506
        job_qs = TestJob.objects.filter(state=TestJob.STATE_FINISHED) \
                                .filter(actual_device=device_obj) \
                                .order_by('-id')
507
508
509
510
511
512
513
        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
514
                "status": job.get_legacy_status_display(),
515
516
517
518
519
520
            }
            if not job.can_view(self.user):
                job_dict["id"] = None
            job_list.append(job_dict)
        return job_list

521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
    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)
        return {
            alias: [device_type.name for device_type in aliases]
        }

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
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
    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:
            raise xmlrpclib.Fault(
                400, "Bad request: Hostname was not specified."
            )
        try:
            device = Device.objects.get(hostname=hostname)
        except Device.DoesNotExist:
            raise xmlrpclib.Fault(
                404, "Device '%s' was not found." % hostname
            )

        device_dict = {}
        if device.is_visible_to(self.user):
            device_dict["hostname"] = device.hostname
604
            device_dict["status"] = build_device_status_display(device.state, device.health)
605
606
607
            device_dict["job"] = None
            device_dict["offline_since"] = None
            device_dict["offline_by"] = None
608
            device_dict["is_pipeline"] = device.is_pipeline
609

610
611
612
            current_job = device.current_job()
            if current_job is not None:
                device_dict["job"] = current_job.pk
613
614
615
616
617
618
        else:
            raise xmlrpclib.Fault(
                403, "Permission denied for user to access %s information." % hostname
            )
        return device_dict

619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
    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:
            raise xmlrpclib.Fault(
                400, "Bad request: Hostname was not specified."
            )
        if not reason:
            raise xmlrpclib.Fault(
                400, "Bad request: Reason was not specified."
            )
655
656
657
658
659
660
661
662
663
664
665
666
667
668
        with transaction.atomic():
            try:
                device = Device.objects.select_for_update().get(hostname=hostname)
            except Device.DoesNotExist:
                raise xmlrpclib.Fault(
                    404, "Device '%s' was not found." % hostname
                )
            if device.can_admin(self.user):
                device.health = Device.HEALTH_MAINTENANCE
                device.save()
            else:
                raise xmlrpclib.Fault(
                    403, "Permission denied for user to put %s into maintenance mode." % hostname
                )
669

670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
    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:
            raise xmlrpclib.Fault(
                400, "Bad request: Hostname was not specified."
            )
        if not reason:
            raise xmlrpclib.Fault(
                400, "Bad request: Reason was not specified."
            )
706
707
708
709
710
711
712
713
714
715
716
717
718
719
        with transaction.atomic():
            try:
                device = Device.objects.select_for_update().get(hostname=hostname)
            except Device.DoesNotExist:
                raise xmlrpclib.Fault(
                    404, "Device '%s' was not found." % hostname
                )
            if device.can_admin(self.user):
                device.health = Device.HEALTH_UNKNOWN
                device.save()
            else:
                raise xmlrpclib.Fault(
                    403, "Permission denied for user to put %s into online mode." % hostname
                )
720

721
    def pending_jobs_by_device_type(self):
722
723
724
        """
        Name
        ----
725
        `pending_jobs_by_device_type` ()
726
727
728

        Description
        -----------
729
        Get number of pending jobs in each device type.
730
731
732
733
734
735
736

        Arguments
        ---------
        None

        Return value
        ------------
737
738
        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.
739
740
        For example:

741
        {'qemu': 0, 'panda': 3}
742
743
        """

744
        pending_jobs_by_device = {}
745

746
747
748
        jobs_res = TestJob.objects.filter(state=TestJob.STATE_SUBMITTED) \
                                  .values_list('requested_device_type_id')\
                                  .annotate(pending_jobs=(Count('id')))
749
750
751
752
753
754
        jobs = {}
        jobs_hash = dict(jobs_res)
        for job in jobs_hash:
            if job:
                jobs[job] = jobs_hash[job]
        pending_jobs_by_device.update(jobs)
755

756
757
758
759
760
        # Get rest of the devices and put number of pending jobs as 0.
        device_types = DeviceType.objects.values_list('name', flat=True)
        for device_type in device_types:
            if device_type not in pending_jobs_by_device:
                pending_jobs_by_device[device_type] = 0
Neil Williams's avatar
Neil Williams committed
761

762
        return pending_jobs_by_device
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782

    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.
783
784

        The elements available in XML-RPC structure include:
Rémi Duraffort's avatar
Rémi Duraffort committed
785
        _state, submitter_id, is_pipeline, id, failure_comment,
786
787
788
789
790
791
        multinode_definition, user_id, priority, _actual_device_cache,
        original_definition, status, health_check, description,
        admin_notifications, 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
792
        """
793
        self._authenticate()
794
        if not job_id:
795
796
            raise xmlrpclib.Fault(400, "Bad request: TestJob id was not "
                                  "specified.")
797
        try:
798
            job = get_restricted_job(self.user, job_id)
Rémi Duraffort's avatar
Rémi Duraffort committed
799
            job.status = job.get_legacy_status_display()
800
801
            job.state = job.get_state_display()
            job.health = job.get_health_display()
802
            job.submitter_username = job.submitter.username
803
            job.absolute_url = job.get_absolute_url()
804
805
        except PermissionDenied:
            raise xmlrpclib.Fault(
806
                401, "Permission denied for user to job %s" % job_id)
807
808
809
810
        except TestJob.DoesNotExist:
            raise xmlrpclib.Fault(404, "Specified job not found.")

        return job
811
812
813
814
815

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

818
        `job_status` (`job_id`)
819
820
821
822
823
824
825
826
827
828
829
830

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

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

        Return value
        ------------
831
832
        This function returns an XML-RPC structures of job status with the
        following fields.
833
        The user is authenticated with an username and token.
Neil Williams's avatar
Neil Williams committed
834

835
        `job_status`: string
836
        ['Submitted'|'Running'|'Complete'|'Incomplete'|'Canceled'|'Canceling']
837
838

        `bundle_sha1`: string
839
        The sha1 hash code of the bundle, if it existed. Otherwise it will be
840
        an empty string. (LAVA V1 only)
841
        """
842
843
844
845
        self._authenticate()
        if not job_id:
            raise xmlrpclib.Fault(400, "Bad request: TestJob id was not "
                                  "specified.")
846
        try:
847
            job = get_restricted_job(self.user, job_id)
848
849
850
        except PermissionDenied:
            raise xmlrpclib.Fault(
                401, "Permission denied for user to job %s" % job_id)
851
852
853
        except TestJob.DoesNotExist:
            raise xmlrpclib.Fault(404, "Specified job not found.")

854
855
856
857
858
859
860
        job_status = {'job_id': job.id}

        if job.is_multinode:
            job_status.update({
                'sub_id': job.sub_id
            })

861
        if job.is_pipeline:
862
            job_status.update({
Rémi Duraffort's avatar
Rémi Duraffort committed
863
                'job_status': job.get_legacy_status_display(),
Neil Williams's avatar
Neil Williams committed
864
                'bundle_sha1': ""
865
866
            })
            return job_status
867
868

        # DEPRECATED
869
        bundle_sha1 = ""
Neil Williams's avatar
Neil Williams committed
870
871
872
873
874
        if job.results_link:
            try:
                bundle_sha1 = job.results_link.split('/')[-2]
            except IndexError:
                pass
875

876
        job_status.update({
Rémi Duraffort's avatar
Rémi Duraffort committed
877
            'job_status': job.get_legacy_status_display(),
Neil Williams's avatar
Neil Williams committed
878
            'bundle_sha1': bundle_sha1
879
        })
880
881

        return job_status
882

883
884
885
886
    def job_list_status(self, job_id_list):
        """
        Name
        ----
887
888
        DEPRECATED - use `job_health` or `job_state` instead.

889
890
891
892
893
894
895
896
897
898
899
900
901
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
        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):
            raise xmlrpclib.Fault(400, "Bad request: needs to be a list")
        if not all(isinstance(chk, (float, int)) for chk in job_id_list):
            raise xmlrpclib.Fault(400, "Bad request: needs to be a list of integers or floats")
        jobs = TestJob.objects.filter(
            Q(id__in=job_id_list) | Q(sub_id__in=job_id_list)).select_related(
927
                'actual_device', 'requested_device_type')
928
929
930
931
932
933
        for job in jobs:
            device_type = job.job_device_type()
            if not job.can_view(self.user) or not job.is_accessible_by(self.user) and not self.user.is_superuser:
                continue
            if device_type.owners_only:
                # do the more expensive check second and only for a hidden device type
934
                if not device_type.some_devices_visible_to(self.user):
935
                    continue
Rémi Duraffort's avatar
Rémi Duraffort committed
936
            job_status[str(job.display_id)] = job.get_legacy_status_display()
937
938
        return job_status

939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
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
984
985
986
987
988
989
990
991
992
993
994
995
996
997
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
1027
1028
1029
1030
1031
1032
1033
1034
    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:
            raise xmlrpclib.Fault(400, "Bad request: TestJob id was not "
                                  "specified.")
        try:
            job = get_restricted_job(self.user, job_id)
        except PermissionDenied:
            raise xmlrpclib.Fault(
                401, "Permission denied for user to job %s" % job_id)
        except TestJob.DoesNotExist:
            raise xmlrpclib.Fault(404, "Specified job not found.")

        job_health = {
            'job_id': job.id,
            'job_health': job.get_health_display()
        }

        if job.is_multinode:
            job_health.update({
                'sub_id': job.sub_id
            })

        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:
            raise xmlrpclib.Fault(400, "Bad request: TestJob id was not "
                                  "specified.")
        try:
            job = get_restricted_job(self.user, job_id)
        except PermissionDenied:
            raise xmlrpclib.Fault(
                401, "Permission denied for user to job %s" % job_id)
        except TestJob.DoesNotExist:
            raise xmlrpclib.Fault(404, "Specified job not found.")

        job_state = {
            'job_id': job.id,
            'job_state': job.get_state_display()
        }

        if job.is_multinode:
            job_state.update({
                'sub_id': job.sub_id
            })

        return job_state

1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
    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:

1056
1057
1058
        [[73, 'multinode-job', 'submitted', None, 'kvm', '72.1'],
        [72, 'multinode-job', 'submitted', None, 'kvm', '72.0'],
        [71, 'test-job', 'running', 'kvm01', None, None]]
1059
1060
        """

1061
        jobs = TestJob.objects.exclude(state=TestJob.STATE_FINISHED).order_by('-id')
Rémi Duraffort's avatar
Rémi Duraffort committed
1062
        jobs_list = [[job.id, job.description, job.get_legacy_status_display().lower(),
1063
                      job.actual_device, job.requested_device_type, job.sub_id] for job in jobs]
1064
1065

        return jobs_list
1066
1067
1068
1069
1070

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

1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
        `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.

1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
        Return value
        ------------
        This function returns an XML-RPC binary data of output file.
        """
        return get_device_config(device_hostname, context)

    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}')`

1112
1113
1114
1115
1116
1117
1118
1119
        Return value
        ------------
        This function returns an XML-RPC binary data of output file.
        """
        if not device_hostname:
            raise xmlrpclib.Fault(400, "Bad request: Device hostname was not "
                                  "specified.")

1120
1121
1122
1123
1124
1125
1126
1127
        job_ctx = None
        if context is not None:
            try:
                job_ctx = yaml.load(context)
            except yaml.YAMLError as exc:
                raise xmlrpclib.Fault(
                    400,
                    "Job context '%s' is not valid. %s" % (context, exc))
1128
1129
1130
        try:
            device = Device.objects.get(hostname=device_hostname)
        except Device.DoesNotExist:
1131
            raise xmlrpclib.Fault(404, "Specified device was not found.")
1132

1133
        config = device.load_configuration(job_ctx=job_ctx, output_format="yaml")
1134
1135

        # validate against the device schema
1136
        validate_device(yaml.load(config))
1137

1138
        return xmlrpclib.Binary(config.encode('UTF-8'))
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156

    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
1157
            Device configuration as Jinja2
1158
1159
1160
1161
1162
1163
1164
1165
1166

        Return value
        ------------
        This function returns an XML-RPC binary data of output file.
        """
        self._authenticate()
        if not self.user.is_superuser:
            raise xmlrpclib.Fault(
                403,
1167
                "User '%s' is not superuser." % self.user.username
1168
1169
            )
        try:
1170
            device = Device.objects.get(hostname=hostname)
1171
1172
1173
1174
        except DeviceType.DoesNotExist:
            raise xmlrpclib.Fault(
                404, "Device '%s' was not found." % hostname
            )
1175
        if not device.save_configuration(jinja_str):
1176
            raise xmlrpclib.Fault(
1177
                400, "Unable to store the configuration for %s on disk" % hostname
1178
            )
1179
1180

        return "Device dictionary updated for %s" % hostname
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207

    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:
            raise xmlrpclib.Fault(
1208
                403, "User '%s' is not superuser." % self.user.username
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
            )
        try:
            device = Device.objects.get(hostname=hostname)
        except DeviceType.DoesNotExist:
            raise xmlrpclib.Fault(
                404, "Device '%s' was not found." % hostname
            )
        if not device.is_pipeline:
            raise xmlrpclib.Fault(
                400, "Device '%s' is not a pipeline device" % hostname
            )
1220
1221

        device_dict = device.load_configuration(output_format="raw")
1222
1223
1224
1225
        if not device_dict:
            raise xmlrpclib.Fault(
                404, "Device '%s' does not have a device dictionary" % hostname
            )
1226
1227

        return xmlrpclib.Binary(device_dict.encode('UTF-8'))
1228

1229
    def validate_pipeline_devices(self, name=None):
1230
1231
1232
        """
        Name
        ----
1233
        `validate_pipeline_device` [`name`]
1234
1235
1236
1237
1238
1239

        Description
        -----------
        Validate that the device dictionary and device-type template
        together create a valid YAML file which matches the pipeline
        device schema.
1240
        Retired devices are ignored.
1241
1242
1243
1244
1245

        See also get_pipeline_device_config

        Arguments
        ---------
1246
1247
1248
1249
1250
1251
1252
        `name`: string
            Can be device hostname or device type name.
        If name is specified, method will search for either a matching device
        hostname or matching device type name in which case it will only
        validate that(those) device(s).
        If not specified, this method will validate all non-retired devices
        in the system.
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264

        Return value
        ------------
        This function returns an XML-RPC structure of results with the
        following fields.

        `device_hostname`: {'Valid': null}
        or
        `device_hostname`: {'Invalid': message}
        `

        """
1265
        if not name:
1266
            devices = Device.objects.filter(is_pipeline=True).exclude(health=Device.HEALTH_RETIRED)
1267
        else:
1268
            devices = Device.objects.filter(is_pipeline=True).exclude(health=Device.HEALTH_RETIRED).filter(device_type__name=name)
1269
            if not devices:
1270
                devices = Device.objects.filter(is_pipeline=True).exclude(health=Device.HEALTH_RETIRED).filter(hostname=name)
1271
        if not devices and name:
1272
            raise xmlrpclib.Fault(
1273
1274
                404,
                "No devices found with hostname or device type name %s" % name
1275
            )
1276
        if not devices and not name:
1277
1278
1279
1280
1281
1282
            raise xmlrpclib.Fault(
                404, "No pipeline device found on this instance."
            )
        results = {}
        for device in devices:
            key = str(device.hostname)
1283
1284
            config = device.load_configuration(output_format="yaml")
            if config is None:
1285
1286
1287
1288
                results[key] = {'Invalid': "Missing device dictionary"}
                continue
            try:
                # validate against the device schema
1289
                validate_device(yaml.load(config))
1290
1291
1292
1293
1294
            except SubmissionException as exc:
                results[key] = {'Invalid': exc}
                continue
            results[key] = {'Valid': None}
        return xmlrpclib.Binary(yaml.dump(results))
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307

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

        Return value
        ------------
        This function exposes the EVENT_SOCKET from the settings file which is
        used for the lava-publisher daemon.
        """
        return settings.EVENT_SOCKET