summaryrefslogtreecommitdiffstats
path: root/src/VBox/ValidationKit/testmanager/cgi/status.py
blob: 39c8af0302c2b91eb9a07ce1a0de9b6d155ea7bb (plain)
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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# $Id: status.py $

"""
CGI - Administrator Web-UI.
"""

__copyright__ = \
"""
Copyright (C) 2012-2023 Oracle and/or its affiliates.

This file is part of VirtualBox base platform packages, as
available from https://www.virtualbox.org.

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation, in version 3 of the
License.

This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, see <https://www.gnu.org/licenses>.

The contents of this file may alternatively be used under the terms
of the Common Development and Distribution License Version 1.0
(CDDL), a copy of it is provided in the "COPYING.CDDL" file included
in the VirtualBox distribution, in which case the provisions of the
CDDL are applicable instead of those of the GPL.

You may elect to license modified versions of this file under the
terms and conditions of either the GPL or the CDDL or both.

SPDX-License-Identifier: GPL-3.0-only OR CDDL-1.0
"""
__version__ = "$Revision: 155244 $"


# Standard python imports.
import os
import sys

# Only the main script needs to modify the path.
g_ksValidationKitDir = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))));
sys.path.append(g_ksValidationKitDir);

# Validation Kit imports.
from testmanager                        import config;
from testmanager.core.webservergluecgi  import WebServerGlueCgi;

from common                             import constants;
from testmanager.core.base              import TMExceptionBase;
from testmanager.core.db                import TMDatabaseConnection;



def timeDeltaToHours(oTimeDelta):
    return oTimeDelta.days * 24 + oTimeDelta.seconds // 3600


def testbox_data_processing(oDb):
    testboxes_dict = {}
    while True:
        line = oDb.fetchOne();
        if line is None:
            break;
        testbox_name = line[0]
        test_result = line[1]
        oTimeDeltaSinceStarted = line[2]
        test_box_os = line[3]
        test_sched_group = line[4]

        # idle testboxes might have an assigned testsets, skipping them
        if test_result not in g_kdTestStatuses:
            continue

        testboxes_dict = dict_update(testboxes_dict, testbox_name, test_result)

        if "testbox_os" not in testboxes_dict[testbox_name]:
            testboxes_dict[testbox_name].update({"testbox_os": test_box_os})

        if "sched_group" not in testboxes_dict[testbox_name]:
            testboxes_dict[testbox_name].update({"sched_group": test_sched_group})
        elif test_sched_group not in testboxes_dict[testbox_name]["sched_group"]:
            testboxes_dict[testbox_name]["sched_group"] += "," + test_sched_group

        if test_result == "running":
            testboxes_dict[testbox_name].update({"hours_running": timeDeltaToHours(oTimeDeltaSinceStarted)})

    return testboxes_dict;


def os_results_separating(vb_dict, test_name, testbox_os, test_result):
    if testbox_os == "linux":
        dict_update(vb_dict, test_name + " / linux", test_result)
    elif testbox_os == "win":
        dict_update(vb_dict, test_name + " / windows", test_result)
    elif testbox_os == "darwin":
        dict_update(vb_dict, test_name + " / darwin", test_result)
    elif testbox_os == "solaris":
        dict_update(vb_dict, test_name + " / solaris", test_result)
    else:
        dict_update(vb_dict, test_name + " / other", test_result)


# const/immutable.
g_kdTestStatuses = {
    'running': 0,
    'success': 0,
    'skipped': 0,
    'bad-testbox': 0,
    'aborted': 0,
    'failure': 0,
    'timed-out': 0,
    'rebooted': 0,
}

def dict_update(target_dict, key_name, test_result):
    if key_name not in target_dict:
        target_dict.update({key_name: g_kdTestStatuses.copy()})
    if test_result in g_kdTestStatuses:
        target_dict[key_name][test_result] += 1
    return target_dict


def formatDataEntry(sKey, dEntry):
    # There are variations in the first and second "columns".
    if "hours_running" in dEntry:
        sRet = "%s;%s;%s | running: %s;%s" \
             % (sKey, dEntry["testbox_os"], dEntry["sched_group"], dEntry["running"], dEntry["hours_running"]);
    else:
        if "testbox_os" in dEntry:
            sRet = "%s;%s;%s" % (sKey, dEntry["testbox_os"], dEntry["sched_group"],);
        else:
            sRet = sKey;
        sRet += " | running: %s" % (dEntry["running"],)

    # The rest is currently identical:
    sRet += " | success: %s | skipped: %s | bad-testbox: %s | aborted: %s | failure: %s | timed-out: %s | rebooted: %s | \n" \
          % (dEntry["success"], dEntry["skipped"], dEntry["bad-testbox"], dEntry["aborted"],
             dEntry["failure"], dEntry["timed-out"], dEntry["rebooted"],);
    return sRet;


def format_data(dData, fSorted):
    sRet = "";
    if not fSorted:
        for sKey in dData:
            sRet += formatDataEntry(sKey, dData[sKey]);
    else:
        for sKey in sorted(dData.keys()):
            sRet += formatDataEntry(sKey, dData[sKey]);
    return sRet;

######

class StatusDispatcherException(TMExceptionBase):
    """
    Exception class for TestBoxController.
    """
    pass;                               # pylint: disable=unnecessary-pass


class StatusDispatcher(object): # pylint: disable=too-few-public-methods
    """
    Status dispatcher class.
    """


    def __init__(self, oSrvGlue):
        """
        Won't raise exceptions.
        """
        self._oSrvGlue          = oSrvGlue;
        self._sAction           = None; # _getStandardParams / dispatchRequest sets this later on.
        self._dParams           = None; # _getStandardParams / dispatchRequest sets this later on.
        self._asCheckedParams   = [];
        self._dActions          = \
        {
            'MagicMirrorTestResults': self._actionMagicMirrorTestResults,
            'MagicMirrorTestBoxes':   self._actionMagicMirrorTestBoxes,
        };

    def _getStringParam(self, sName, asValidValues = None, fStrip = False, sDefValue = None):
        """
        Gets a string parameter (stripped).

        Raises exception if not found and no default is provided, or if the
        value isn't found in asValidValues.
        """
        if sName not in self._dParams:
            if sDefValue is None:
                raise StatusDispatcherException('%s parameter %s is missing' % (self._sAction, sName));
            return sDefValue;
        sValue = self._dParams[sName];
        if fStrip:
            sValue = sValue.strip();

        if sName not in self._asCheckedParams:
            self._asCheckedParams.append(sName);

        if asValidValues is not None and sValue not in asValidValues:
            raise StatusDispatcherException('%s parameter %s value "%s" not in %s '
                                            % (self._sAction, sName, sValue, asValidValues));
        return sValue;

    def _getIntParam(self, sName, iMin = None, iMax = None, iDefValue = None):
        """
        Gets a string parameter.
        Raises exception if not found, not a valid integer, or if the value
        isn't in the range defined by iMin and iMax.
        """
        if sName not in self._dParams:
            if iDefValue is None:
                raise StatusDispatcherException('%s parameter %s is missing' % (self._sAction, sName));
            return iDefValue;
        sValue = self._dParams[sName];
        try:
            iValue = int(sValue, 0);
        except:
            raise StatusDispatcherException('%s parameter %s value "%s" cannot be convert to an integer'
                                            % (self._sAction, sName, sValue));
        if sName not in self._asCheckedParams:
            self._asCheckedParams.append(sName);

        if   (iMin is not None and iValue < iMin) \
          or (iMax is not None and iValue > iMax):
            raise StatusDispatcherException('%s parameter %s value %d is out of range [%s..%s]'
                                            % (self._sAction, sName, iValue, iMin, iMax));
        return iValue;

    def _getBoolParam(self, sName, fDefValue = None):
        """
        Gets a boolean parameter.

        Raises exception if not found and no default is provided, or if not a
        valid boolean.
        """
        sValue = self._getStringParam(sName, [ 'True', 'true', '1', 'False', 'false', '0'], sDefValue = str(fDefValue));
        return sValue in ('True', 'true', '1',);

    def _checkForUnknownParameters(self):
        """
        Check if we've handled all parameters, raises exception if anything
        unknown was found.
        """

        if len(self._asCheckedParams) != len(self._dParams):
            sUnknownParams = '';
            for sKey in self._dParams:
                if sKey not in self._asCheckedParams:
                    sUnknownParams += ' ' + sKey + '=' + self._dParams[sKey];
            raise StatusDispatcherException('Unknown parameters: ' + sUnknownParams);

        return True;

    def _connectToDb(self):
        """
        Connects to the database.

        Returns (TMDatabaseConnection, (more later perhaps) ) on success.
        Returns (None, ) on failure after sending the box an appropriate response.
        May raise exception on DB error.
        """
        return (TMDatabaseConnection(self._oSrvGlue.dprint),);

    def _actionMagicMirrorTestBoxes(self):
        """
        Produces test result status for the magic mirror dashboard
        """

        #
        # Parse arguments and connect to the database.
        #
        cHoursBack = self._getIntParam('cHours', 1, 24*14, 12);
        fSorted   = self._getBoolParam('fSorted', False);
        self._checkForUnknownParameters();

        #
        # Get the data.
        #
        # Note! We're not joining on TestBoxesWithStrings.idTestBox =
        #       TestSets.idGenTestBox here because of indexes.  This is
        #       also more consistent with the rest of the query.
        # Note! The original SQL is slow because of the 'OR TestSets.tsDone'
        #       part, using AND and UNION is significatly faster because
        #       it matches the TestSetsGraphBoxIdx (index).
        #
        (oDb,) = self._connectToDb();
        if oDb is None:
            return False;

        #
        # some comments regarding select below:
        # first part is about fetching all finished tests for last cHoursBack hours
        # second part is fetching all tests which isn't done
        # both old (running more than cHoursBack) and fresh (less than cHoursBack) ones
        # 'cause we want to know if there's a hanging tests together with currently running
        #
        # there's also testsets without status at all, likely because disabled testboxes still have an assigned testsets
        #
        oDb.execute('''
(   SELECT  TestBoxesWithStrings.sName,
            TestSets.enmStatus,
            CURRENT_TIMESTAMP - TestSets.tsCreated,
            TestBoxesWithStrings.sOS,
            SchedGroupNames.sSchedGroupNames
    FROM    (
            SELECT TestBoxesInSchedGroups.idTestBox AS idTestBox,
            STRING_AGG(SchedGroups.sName, ',') AS sSchedGroupNames
            FROM   TestBoxesInSchedGroups
            INNER JOIN SchedGroups
                    ON SchedGroups.idSchedGroup = TestBoxesInSchedGroups.idSchedGroup
            WHERE   TestBoxesInSchedGroups.tsExpire = 'infinity'::TIMESTAMP
                AND SchedGroups.tsExpire            = 'infinity'::TIMESTAMP
            GROUP BY TestBoxesInSchedGroups.idTestBox
            ) AS SchedGroupNames,
            TestBoxesWithStrings
    LEFT OUTER JOIN TestSets
                 ON TestSets.idTestBox  = TestBoxesWithStrings.idTestBox
                AND TestSets.tsCreated >= (CURRENT_TIMESTAMP - '%s hours'::interval)
                AND TestSets.tsDone IS NOT NULL
    WHERE   TestBoxesWithStrings.tsExpire = 'infinity'::TIMESTAMP
      AND   SchedGroupNames.idTestBox = TestBoxesWithStrings.idTestBox
) UNION (
    SELECT  TestBoxesWithStrings.sName,
            TestSets.enmStatus,
            CURRENT_TIMESTAMP - TestSets.tsCreated,
            TestBoxesWithStrings.sOS,
            SchedGroupNames.sSchedGroupNames
    FROM    (
            SELECT TestBoxesInSchedGroups.idTestBox AS idTestBox,
            STRING_AGG(SchedGroups.sName, ',') AS sSchedGroupNames
            FROM   TestBoxesInSchedGroups
            INNER JOIN SchedGroups
                    ON SchedGroups.idSchedGroup = TestBoxesInSchedGroups.idSchedGroup
            WHERE   TestBoxesInSchedGroups.tsExpire = 'infinity'::TIMESTAMP
                AND SchedGroups.tsExpire            = 'infinity'::TIMESTAMP
            GROUP BY TestBoxesInSchedGroups.idTestBox
            ) AS SchedGroupNames,
            TestBoxesWithStrings
    LEFT OUTER JOIN TestSets
                 ON TestSets.idTestBox  = TestBoxesWithStrings.idTestBox
                AND TestSets.tsDone IS NULL
    WHERE   TestBoxesWithStrings.tsExpire = 'infinity'::TIMESTAMP
      AND   SchedGroupNames.idTestBox = TestBoxesWithStrings.idTestBox
)
''', (cHoursBack, cHoursBack,));


        #
        # Process, format and output data.
        #
        dResult = testbox_data_processing(oDb);
        self._oSrvGlue.setContentType('text/plain');
        self._oSrvGlue.write(format_data(dResult, fSorted));

        return True;

    def _actionMagicMirrorTestResults(self):
        """
        Produces test result status for the magic mirror dashboard
        """

        #
        # Parse arguments and connect to the database.
        #
        sBranch = self._getStringParam('sBranch');
        cHoursBack = self._getIntParam('cHours', 1, 24*14, 6); ## @todo why 6 hours here and 12 for test boxes?
        fSorted   = self._getBoolParam('fSorted', False);
        self._checkForUnknownParameters();

        #
        # Get the data.
        #
        # Note! These queries should be joining TestBoxesWithStrings and TestSets
        #       on idGenTestBox rather than on idTestBox and tsExpire=inf, but
        #       we don't have any index matching those.  So, we'll ignore tests
        #       performed by deleted testboxes for the present as that doesn't
        #       happen often and we want the ~1000x speedup.
        #
        (oDb,) = self._connectToDb();
        if oDb is None:
            return False;

        if sBranch == 'all':
            oDb.execute('''
SELECT  TestSets.enmStatus,
        TestCases.sName,
        TestBoxesWithStrings.sOS
FROM    TestSets
INNER JOIN TestCases
        ON TestCases.idGenTestCase         = TestSets.idGenTestCase
INNER JOIN TestBoxesWithStrings
        ON TestBoxesWithStrings.idTestBox  = TestSets.idTestBox
       AND TestBoxesWithStrings.tsExpire   = 'infinity'::TIMESTAMP
WHERE   TestSets.tsCreated                >= (CURRENT_TIMESTAMP - '%s hours'::interval)
''', (cHoursBack,));
        else:
            oDb.execute('''
SELECT  TestSets.enmStatus,
        TestCases.sName,
        TestBoxesWithStrings.sOS
FROM    TestSets
INNER JOIN BuildCategories
        ON BuildCategories.idBuildCategory = TestSets.idBuildCategory
       AND BuildCategories.sBranch         = %s
INNER JOIN TestCases
        ON TestCases.idGenTestCase         = TestSets.idGenTestCase
INNER JOIN TestBoxesWithStrings
        ON TestBoxesWithStrings.idTestBox  = TestSets.idTestBox
       AND TestBoxesWithStrings.tsExpire   = 'infinity'::TIMESTAMP
WHERE   TestSets.tsCreated                >= (CURRENT_TIMESTAMP - '%s hours'::interval)
''', (sBranch, cHoursBack,));

        # Process the data
        dResult = {};
        while True:
            aoRow = oDb.fetchOne();
            if aoRow is None:
                break;
            os_results_separating(dResult, aoRow[1], aoRow[2], aoRow[0])  # save all test results

        # Format and output it.
        self._oSrvGlue.setContentType('text/plain');
        self._oSrvGlue.write(format_data(dResult, fSorted));

        return True;

    def _getStandardParams(self, dParams):
        """
        Gets the standard parameters and validates them.

        The parameters are returned as a tuple: sAction, (more later, maybe)
        Note! the sTextBoxId can be None if it's a SIGNON request.

        Raises StatusDispatcherException on invalid input.
        """
        #
        # Get the action parameter and validate it.
        #
        if constants.tbreq.ALL_PARAM_ACTION not in dParams:
            raise StatusDispatcherException('No "%s" parameter in request (params: %s)'
                                            % (constants.tbreq.ALL_PARAM_ACTION, dParams,));
        sAction = dParams[constants.tbreq.ALL_PARAM_ACTION];

        if sAction not in self._dActions:
            raise StatusDispatcherException('Unknown action "%s" in request (params: %s; action: %s)'
                                            % (sAction, dParams, self._dActions));
        #
        # Update the list of checked parameters.
        #
        self._asCheckedParams.extend([constants.tbreq.ALL_PARAM_ACTION,]);

        return (sAction,);

    def dispatchRequest(self):
        """
        Dispatches the incoming request.

        Will raise StatusDispatcherException on failure.
        """

        #
        # Must be a GET request.
        #
        try:
            sMethod = self._oSrvGlue.getMethod();
        except Exception as oXcpt:
            raise StatusDispatcherException('Error retriving request method: %s' % (oXcpt,));
        if sMethod != 'GET':
            raise StatusDispatcherException('Error expected POST request not "%s"' % (sMethod,));

        #
        # Get the parameters and checks for duplicates.
        #
        try:
            dParams = self._oSrvGlue.getParameters();
        except Exception as oXcpt:
            raise StatusDispatcherException('Error retriving parameters: %s' % (oXcpt,));
        for sKey in dParams.keys():
            if len(dParams[sKey]) > 1:
                raise StatusDispatcherException('Parameter "%s" is given multiple times: %s' % (sKey, dParams[sKey]));
            dParams[sKey] = dParams[sKey][0];
        self._dParams = dParams;

        #
        # Get+validate the standard action parameters and dispatch the request.
        #
        (self._sAction, ) = self._getStandardParams(dParams);
        return self._dActions[self._sAction]();


def main():
    """
    Main function a la C/C++. Returns exit code.
    """

    oSrvGlue = WebServerGlueCgi(g_ksValidationKitDir, fHtmlOutput = False);
    try:
        oDisp = StatusDispatcher(oSrvGlue);
        oDisp.dispatchRequest();
        oSrvGlue.flush();
    except Exception as oXcpt:
        return oSrvGlue.errorPage('Internal error: %s' % (str(oXcpt),), sys.exc_info());

    return 0;

if __name__ == '__main__':
    if config.g_kfProfileAdmin:
        from testmanager.debug import cgiprofiling;
        sys.exit(cgiprofiling.profileIt(main));
    else:
        sys.exit(main());