Fault tolerant handling of exceptions thrown by verifyvnfd
[vfc/gvnfm/vnflcm.git] / lcm / lcm / pub / verifyvnfd / verifyvnfd.py
1 # Copyright 2016 ZTE Corporation.
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 #         http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14
15 import json
16 import re
17 import os
18 import six
19 import logging
20 import jsonschema
21
22 logger = logging.getLogger(__name__)
23
24
25 def _format_validation_error(error):
26     """
27     :param error: validation error to format
28     :type error: jsonchema.exceptions.ValidationError
29     :returns: string representation of the validation error
30     :rtype: str
31     """
32     match = re.search("(.+) is a required property", error.message)
33     if match:
34         message = 'Error: missing required property {}.'.format(
35             match.group(1))
36     else:
37         message = 'Error: {}\n'.format(error.message)
38         if len(error.absolute_path) > 0:
39             message += 'Path: {}\n'.format(
40                        '.'.join(
41                            [six.text_type(path)
42                             for path in error.absolute_path]))
43         message += 'Value: {}'.format(json.dumps(error.instance))
44
45     return message
46
47
48 def verify(new_vnfd):
49     errors_found = []
50     vnfd_schema_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), "vnf_vnfd_all_schema.json")
51     with open(vnfd_schema_path, "r") as fvnfd_schema:
52         vnfd_schema = json.load(fvnfd_schema)
53         vnfd_validator = jsonschema.validators.Draft4Validator(schema=vnfd_schema)
54         for error in vnfd_validator.iter_errors(new_vnfd):
55             # print("Error:%s" % error)
56             logger.error("vnfd verify fail,%s" % _format_validation_error(error))
57             errors_found.append(_format_validation_error(error))
58     if len(errors_found) > 0:
59         logger.error(errors_found)
60         return errors_found
61     return True