blob: a67b86b749dd228fb8ffd8003f94f7e86dd60724 [file] [log] [blame]
Basil Eljuse4b14afb2020-09-30 13:07:23 +01001#!/usr/bin/env python3
2
3__copyright__ = """
4/*
5 * Copyright (c) 2020, Arm Limited. All rights reserved.
6 *
7 * SPDX-License-Identifier: BSD-3-Clause
8 *
9 */
10 """
11
12""" data_validator.py:
13
14 JSON data validator class. This class is aimed at validating the JSON
15 data sent in curl command with the JSON schema, so that before pushing
16 the data to the database, it is ensured that required data is received
17 in agreed-upon format.
18
19"""
20
21import sys
22import json
23import os.path
24import constants
25import jsonschema
26from jsonschema import validate
27
28
29class DataValidator:
30 @staticmethod
31 def validate_request_sanity(data_dict):
32 """
33 Input sanitisation/authentication in the application flow
34
35 :param: data_dict: Data to be validated
36 :return: Validation info and error code
37 """
38 if 'metrics' in data_dict['metadata'] and 'api_version' in data_dict and \
39 data_dict['metadata']['metrics'] in constants.VALID_METRICS:
40 if data_dict['api_version'] not in constants.SUPPORTED_API_VERSIONS:
41 return 'Incorrect API version', 401
42
43 filename = 'metrics-schemas/' + data_dict['metadata']['metrics'] + '_schema_' + \
44 data_dict['api_version'].replace(".", "_") + '.json'
45 if not os.path.exists(filename):
46 return filename + ' does not exist', 501
47
48 try:
49 with open(filename, 'r') as handle:
50 parsed = json.load(handle)
51 validate(data_dict, parsed)
52 sys.stdout.write('Record OK\n')
53 return 'OK', 204
54 except jsonschema.exceptions.ValidationError as ve:
55 sys.stdout.write('Record ERROR\n')
56 sys.stderr.write(str(ve) + "\n")
57 return 'Incorrect JSON Schema: ' + \
58 str(ve).split('\n', 1)[0], 400
59 else:
60 return 'Invalid schema - metrics or api version missing\n', 401