File: api.py

package info (click to toggle)
lava 2019.01-5
  • links: PTS, VCS
  • area: main
  • in suites: buster, sid
  • size: 24,200 kB
  • sloc: python: 57,974; sh: 1,113; makefile: 329
file content (755 lines) | stat: -rw-r--r-- 25,590 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
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
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
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
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
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
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
655
656
657
658
659
660
661
662
663
664
665
666
667
668
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
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
# -*- coding: utf-8 -*-
# Copyright (C) 2015-2018 Linaro Limited
#
# Author: Stevan Radakovic <stevan.radakovic@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/>.

import csv
import io
import yaml
import xmlrpc.client

from linaro_django_xmlrpc.models import ExposedAPI

from django.db.models.fields import FieldDoesNotExist

from lava_results_app.dbutils import export_testsuite, testsuite_export_fields
from lava_results_app.models import (
    Query,
    QueryCondition,
    RefreshLiveQueryError,
    QueryUpdatedError,
    TestCase,
    TestSuite,
    InvalidContentTypeError,
)
from lava_results_app.utils import (
    export_testcase,
    get_testcases_with_limit,
    testcase_export_fields,
)
from lava_scheduler_app.models import TestJob


class ResultsAPI(ExposedAPI):
    def make_custom_query(self, entity, conditions, limit=200):
        """
        Name
        ----
        `make_custom_query` (`entity`, `conditions`, `limit`)

        Description
        -----------
        Construct and run a custom query and return the results.

        Arguments
        ---------
        `entity`: string
            The entity you want to query
        `conditions`: string
            The conditions of the query
        `limit`: integer
            Add a limit to the number of results returned.
            Defaults to 200.

        Return value
        ------------
        A list of dictionaries containing the query results.

        The user should be authenticated with a username and token.

        Example
        -------

        # Get all test jobs submitted by the user 'kernel-ci', and which ended
        # as 'Incomplete':
        server.results.make_custom_query("testjob",
            "testjob__submitter__exact__kernel-ci,"
            "testjob__health__exact__Incomplete")
        [{ jobXX }, { jobXY }, ...]

        # Get all test cases in a test suite named 'custom-tests', that failed,
        # and for whom the job ended after '2017-04-26 00:00:00'.
        server.results.make_custom_query("testcase",
            "testsuite__name__exact__1_custom-tests,"
            "testcase__result__exact__Test failed,"
            "testjob__end_time__gt__2017-04-26 00:00:00")
        [{ testcaseXX }, { testcaseXY }, ...]

        """
        self._authenticate()
        try:
            content_type = Query.get_content_type(entity)
        except InvalidContentTypeError:
            raise xmlrpc.client.Fault(
                400,
                "Wrong table name in entity parameter. " "Please refer to query docs.",
            )

        if content_type.model_class() not in QueryCondition.RELATION_MAP:
            raise xmlrpc.client.Fault(
                400,
                "Wrong table name in entity parameter. " "Please refer to query docs.",
            )

        conditions = Query.parse_conditions(content_type, conditions)

        try:
            results = Query.get_queryset(content_type, conditions).visible_by_user(
                self.user
            )
        except FieldDoesNotExist:
            raise xmlrpc.client.Fault(
                400,
                "Conditions URL incorrect: Field does not exist. "
                "Please refer to query docs.",
            )
        return list(results[:limit])

    def run_query(self, query_name, limit=200, username=None):
        """
        Name
        ----
        `run_query` (`query_name`, `limit=200`, `username=None`)

        Description
        -----------
        Run the specified query and return the results of the query.

        Arguments
        ---------
        `query_name`: string
            Query name string.
        `limit`: integer
            Add a limit to the number of results returned.
            Defaults to 200.
        `username`: string
            Username of the user which is owner of the query you would like the
            results.
            Defaults to None, in which case the method will consider the
            authenticated user to be the owner.
            Either way, the authenticated user needs to have special access to
            this query (being an owner or belonging to the group which has
            admin access to the query).

        Return value
        ------------
        A list of dictionaries containing the query results.

        The user should be authenticated with a username and token.
        """
        self._authenticate()
        if not username:
            username = self.user.username

        try:
            query = Query.objects.get(name=query_name, owner__username=username)
        except Query.DoesNotExist:
            raise xmlrpc.client.Fault(
                404,
                "Query with name %s owned by user %s does not exist."
                % (query_name, username),
            )

        if not query.is_accessible_by(self.user):
            raise xmlrpc.client.Fault(
                403, "Permission denied for user to query %s" % query_name
            )

        return list(query.get_results(self.user)[:limit])

    def refresh_query(self, query_name, username=None):
        """
        Name
        ----
        `refresh_query` (`query_name`, `username`)

        Description
        -----------
        Refreshes the query with the given name owned by specific user.

        Arguments
        ---------
        `query_name`: string
            Query name string.
        `username`: string
            Username of the user which is owner of/created the query you would
            like to update. Defaults to None, in which case the method will
            consider the authenticated user to be the owner.
            Either way, the authenticated user needs to have special access to
            this query (being an owner or belonging to the group which has
            admin access to the query).

        Return value
        ------------
        None. The user should be authenticated with a username and token.
        """
        self._authenticate()
        if not username:
            username = self.user.username

        try:
            query = Query.objects.get(name=query_name, owner__username=username)
        except Query.DoesNotExist:
            raise xmlrpc.client.Fault(
                400,
                "Query with name %s owned by user %s does not exist."
                % (query_name, username),
            )

        if not query.is_accessible_by(self.user):
            raise xmlrpc.client.Fault(
                401, "Permission denied for user to query %s" % query_name
            )

        try:
            query.refresh_view()
        except QueryUpdatedError:
            raise xmlrpc.client.Fault(
                400,
                "Query with name %s owned by user %s was recently refreshed."
                % (query_name, username),
            )
        except RefreshLiveQueryError:
            raise xmlrpc.client.Fault(
                400,
                "Query with name %s owned by user %s cannot be refreshed since it's a live query."
                % (query_name, username),
            )
        except Exception as exc:
            raise xmlrpc.client.Fault(
                401,
                "Query refresh failed. Please contact system administrator: %s"
                % str(exc),
            )

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

        Description
        -----------
        Refreshes all queries in the system. Available only for superusers.

        Arguments
        ---------
        None.

        Return value
        ------------
        None. The user should be authenticated with a username and token.
        """
        self._authenticate()

        if not self.user.is_superuser:
            raise xmlrpc.client.Fault(
                401,
                "Permission denied for user %s. Must be a superuser to "
                "refresh all queries." % self.user.username,
            )

        for query in Query.objects.all().filter(is_live=False):
            try:
                query.refresh_view()
            except QueryUpdatedError:
                raise xmlrpc.client.Fault(
                    400,
                    "Query with name %s owned by user %s was recently refreshed."
                    % (query.name, self.user.username),
                )
            except Exception as exc:
                raise xmlrpc.client.Fault(
                    401,
                    "Refresh operation for query with name %s owned by user %s failed. Please contact system administrator. Error: %s"
                    % (query.name, query.owner.username, str(exc)),
                )

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

        Description
        -----------
        Get the job results of given job id in the YAML format.

        Arguments
        ---------
        `job_id`: string
            Job id for which the results are required.

        Return value
        ------------
        This function returns an XML-RPC structures of job results in YAML
        format, provided the user is authenticated with an username and token.
        """

        self._authenticate()
        if not job_id:
            raise xmlrpc.client.Fault(400, "Bad request: TestJob id was not specified.")
        try:
            job = TestJob.get_by_job_number(job_id)
            if not job.can_view(self.user):
                raise xmlrpc.client.Fault(
                    401, "Permission denied for user to job %s" % job_id
                )
            yaml_list = []
            for test_suite in job.testsuite_set.all():
                for test_case in test_suite.testcase_set.all():
                    yaml_list.append(export_testcase(test_case))

        except TestJob.DoesNotExist:
            raise xmlrpc.client.Fault(404, "Specified job not found.")

        return yaml.dump(yaml_list)

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

        Description
        -----------
        Get the job level metadata which includes entries created by
        LAVA as well as submitted in the test job definition

        Arguments
        ---------
        `job_id`: string
            Job id for which the results are required.

        Return value
        ------------
        This function returns an XML-RPC structures of job results as
        a list of dictionaries, provided the user is authenticated with
        a username and token.

        [
            {name: value},
            {name: value},
        ]

        For example:
        [
            {'boot.0.hikey-oe.commands': 'fastboot'},
            {'source': 'https://git.linaro.org/lava-team/refactoring.git'},
            {'test.0.tlxc.definition.path': 'ubuntu/smoke-tests-basic.yaml'}
        ]
        """
        self._authenticate()
        if not job_id:
            raise xmlrpc.client.Fault(400, "Bad request: TestJob id was not specified.")
        try:
            job = TestJob.get_by_job_number(job_id)
            if not job.can_view(self.user):
                raise xmlrpc.client.Fault(
                    401, "Permission denied for user to job %s" % job_id
                )
        except TestJob.DoesNotExist:
            raise xmlrpc.client.Fault(404, "Specified job not found.")

        return job.get_metadata_dict()

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

        Description
        -----------
        Get the job results of given job id in CSV format.

        Arguments
        ---------
        `job_id`: string
            Job id for which the results are required.

        Return value
        ------------
        This function returns an XML-RPC structures of job results in CSV
        format, provided the user is authenticated with an username and token.
        """

        self._authenticate()
        if not job_id:
            raise xmlrpc.client.Fault(400, "Bad request: TestJob id was not specified.")
        try:
            job = TestJob.get_by_job_number(job_id)
            if not job.can_view(self.user):
                raise xmlrpc.client.Fault(
                    401, "Permission denied for user to job %s" % job_id
                )
            output = io.StringIO()
            writer = csv.DictWriter(
                output,
                quoting=csv.QUOTE_ALL,
                extrasaction="ignore",
                fieldnames=testcase_export_fields(),
            )
            writer.writeheader()
            for test_suite in job.testsuite_set.all():
                for row in test_suite.testcase_set.all():
                    writer.writerow(export_testcase(row))

        except TestJob.DoesNotExist:
            raise xmlrpc.client.Fault(404, "Specified job not found.")

        return output.getvalue()

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

        Description
        -----------
        Get the test suites list from job results of given job id in CSV format.

        Arguments
        ---------
        `job_id`: string
            Job id for which the test suites are required.

        Return value
        ------------
        This function returns an XML-RPC structures of test suites list from
        job results in CSV format, provided the user is authenticated with an
        username and token.
        """

        self._authenticate()
        if not job_id:
            raise xmlrpc.client.Fault(400, "Bad request: TestJob id was not specified.")
        try:
            job = TestJob.get_by_job_number(job_id)
            if not job.can_view(self.user):
                raise xmlrpc.client.Fault(
                    401, "Permission denied for user to job %s" % job_id
                )
            output = io.StringIO()
            writer = csv.DictWriter(
                output,
                quoting=csv.QUOTE_ALL,
                extrasaction="ignore",
                fieldnames=testsuite_export_fields(),
            )
            writer.writeheader()
            for test_suite in job.testsuite_set.all():
                writer.writerow(export_testsuite(test_suite))

        except TestJob.DoesNotExist:
            raise xmlrpc.client.Fault(404, "Specified job not found.")

        return output.getvalue()

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

        Description
        -----------
        Get the test suites list from job results of given job id in YAML format.

        Arguments
        ---------
        `job_id`: string
            Job id for which the test suites are required.

        Return value
        ------------
        This function returns an XML-RPC structures of test suites list from
        job results in YAML format, provided the user is authenticated with an
        username and token.
        """

        self._authenticate()
        if not job_id:
            raise xmlrpc.client.Fault(400, "Bad request: TestJob id was not specified.")
        try:
            job = TestJob.get_by_job_number(job_id)
            if not job.can_view(self.user):
                raise xmlrpc.client.Fault(
                    401, "Permission denied for user to job %s" % job_id
                )
            yaml_list = []
            for test_suite in job.testsuite_set.all():
                yaml_list.append(export_testsuite(test_suite))

        except TestJob.DoesNotExist:
            raise xmlrpc.client.Fault(404, "Specified job not found.")

        return yaml.dump(yaml_list)

    def get_testsuite_results_yaml(self, job_id, suite_name, limit=None, offset=None):
        """
        Name
        ----
        `get_testsuite_results_yaml` (`job_id`, `suite_name`, `limit=None`, `offset=None`)

        Description
        -----------
        Get the suite results of given job id and suite name in YAML format.

        Arguments
        ---------
        `job_id`: string
            Job id for which the results are required.
        `suite_name`: string
            Name of the suite for which the results are required.
        `limit`: int
            Limit the number of test cases fetched.
        `offset`: int
            Start fetching test cases from a specific point.

        Return value
        ------------
        This function returns an XML-RPC structures of suite results in YAML
        format, provided the user is authenticated with an username and token.
        """

        self._authenticate()
        if not job_id:
            raise xmlrpc.client.Fault(400, "Bad request: TestJob id was not specified.")
        try:
            job = TestJob.get_by_job_number(job_id)
            if not job.can_view(self.user):
                raise xmlrpc.client.Fault(
                    401, "Permission denied for user to job %s" % job_id
                )
            yaml_list = []
            test_suite = job.testsuite_set.get(name=suite_name)
            for test_case in get_testcases_with_limit(test_suite, limit, offset):
                yaml_list.append(export_testcase(test_case))

        except TestJob.DoesNotExist:
            raise xmlrpc.client.Fault(404, "Specified job not found.")
        except TestSuite.DoesNotExist:
            raise xmlrpc.client.Fault(404, "Specified test suite not found.")

        return yaml.dump(yaml_list)

    def get_testsuite_results_csv(self, job_id, suite_name, limit=None, offset=None):
        """
        Name
        ----
        `get_testsuite_results_csv` (`job_id`, `suite_name`, `limit=None`, `offset=None`)

        Description
        -----------
        Get the suite results of given job id and suite name in CSV format.

        Arguments
        ---------
        `job_id`: string
            Job id for which the results are required.
        `suite_name`: string
            Name of the suite for which the results are required.
        `limit`: int
            Limit the number of test cases fetched.
        `offset`: int
            Start fetching test cases from a specific point.

        Return value
        ------------
        This function returns an XML-RPC structures of suite results in CSV
        format, provided the user is authenticated with an username and token.
        """

        self._authenticate()
        if not job_id:
            raise xmlrpc.client.Fault(400, "Bad request: TestJob id was not specified.")
        try:
            job = TestJob.get_by_job_number(job_id)
            if not job.can_view(self.user):
                raise xmlrpc.client.Fault(
                    401, "Permission denied for user to job %s" % job_id
                )
            output = io.StringIO()
            writer = csv.DictWriter(
                output,
                quoting=csv.QUOTE_ALL,
                extrasaction="ignore",
                fieldnames=testcase_export_fields(),
            )
            writer.writeheader()
            test_suite = job.testsuite_set.get(name=suite_name)
            for row in get_testcases_with_limit(test_suite, limit, offset):
                writer.writerow(export_testcase(row))

        except TestJob.DoesNotExist:
            raise xmlrpc.client.Fault(404, "Specified job not found.")
        except TestSuite.DoesNotExist:
            raise xmlrpc.client.Fault(404, "Specified test suite not found.")

        return output.getvalue()

    def get_testsuite_results_count(self, job_id, suite_name):
        """
        Name
        ----
        `get_testsuite_results_count` (`job_id`, `suite_name`)

        Description
        -----------
        Get the count of test cases in test suite.

        Arguments
        ---------
        `job_id`: string
            Job id for which the results are required.
        `suite_name`: string
            Name of the suite for which the test case count is required.

        Return value
        ------------
        This function returns a count of test cases in particular test suite,
        provided the user is authenticated with an username and token.
        """

        self._authenticate()
        if not job_id:
            raise xmlrpc.client.Fault(400, "Bad request: TestJob id was not specified.")
        try:
            job = TestJob.get_by_job_number(job_id)
            if not job.can_view(self.user):
                raise xmlrpc.client.Fault(
                    401, "Permission denied for user to job %s" % job_id
                )

            test_suite = job.testsuite_set.get(name=suite_name)
            test_case_count = test_suite.testcase_set.all().count()

        except TestJob.DoesNotExist:
            raise xmlrpc.client.Fault(404, "Specified job not found.")
        except TestSuite.DoesNotExist:
            raise xmlrpc.client.Fault(404, "Specified test suite not found.")

        return test_case_count

    def get_testcase_results_yaml(self, job_id, suite_name, case_name):
        """
        Name
        ----
        `get_testcase_results_yaml` (`job_id`, `suite_name`, `case_name`)

        Description
        -----------
        Get the test case results of given job id, suite and test case name
        in YAML format.

        Arguments
        ---------
        `job_id`: string
            Job id for which the results are required.
        `suite_name`: string
            Name of the suite for which the results are required.
        `case_name`: string
            Name of the test case for which the results are required.

        Return value
        ------------
        This function returns an XML-RPC structures of test case results in
        YAML format, provided the user is authenticated with an username and
        token.
        """

        self._authenticate()
        if not job_id:
            raise xmlrpc.client.Fault(400, "Bad request: TestJob id was not specified.")
        try:
            job = TestJob.get_by_job_number(job_id)
            if not job.can_view(self.user):
                raise xmlrpc.client.Fault(
                    401, "Permission denied for user to job %s" % job_id
                )
            test_suite = job.testsuite_set.get(name=suite_name)
            test_cases = test_suite.testcase_set.filter(name=case_name)
            yaml_list = [export_testcase(test_case) for test_case in test_cases]

        except TestJob.DoesNotExist:
            raise xmlrpc.client.Fault(404, "Specified job not found.")
        except TestSuite.DoesNotExist:
            raise xmlrpc.client.Fault(404, "Specified test suite not found.")
        except TestCase.DoesNotExist:
            raise xmlrpc.client.Fault(404, "Specified test case not found.")

        return yaml.dump(yaml_list)

    def get_testcase_results_csv(self, job_id, suite_name, case_name):
        """
        Name
        ----
        `get_testcase_results_csv` (`job_id`, `suite_name`, `case_name`)

        Description
        -----------
        Get the test case results of given job id, suite and test case name
        in CSV format.

        Arguments
        ---------
        `job_id`: string
            Job id for which the results are required.
        `suite_name`: string
            Name of the suite for which the results are required.
        `case_name`: string
            Name of the test case for which the results are required.

        Return value
        ------------
        This function returns an XML-RPC structures of test case results in
        CSV format, provided the user is authenticated with an username and
        token.
        """

        self._authenticate()
        if not job_id:
            raise xmlrpc.client.Fault(400, "Bad request: TestJob id was not specified.")
        try:
            job = TestJob.get_by_job_number(job_id)
            if not job.can_view(self.user):
                raise xmlrpc.client.Fault(
                    401, "Permission denied for user to job %s" % job_id
                )

            output = io.StringIO()
            writer = csv.DictWriter(
                output,
                quoting=csv.QUOTE_ALL,
                extrasaction="ignore",
                fieldnames=testcase_export_fields(),
            )
            writer.writeheader()
            test_suite = job.testsuite_set.get(name=suite_name)
            test_case = test_suite.testcase_set.get(name=case_name)
            writer.writerow(export_testcase(test_case))

        except TestJob.DoesNotExist:
            raise xmlrpc.client.Fault(404, "Specified job not found.")
        except TestSuite.DoesNotExist:
            raise xmlrpc.client.Fault(404, "Specified test suite not found.")
        except TestCase.DoesNotExist:
            raise xmlrpc.client.Fault(404, "Specified test case not found.")

        return output.getvalue()