Add vnfd validity check
[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 from lcm.pub.exceptions import NFLCMException
22
23 logger = logging.getLogger(__name__)
24
25
26 def _format_validation_error(error):
27     """
28     :param error: validation error to format
29     :type error: jsonchema.exceptions.ValidationError
30     :returns: string representation of the validation error
31     :rtype: str
32     """
33     match = re.search("(.+) is a required property", error.message)
34     if match:
35         message = 'Error: missing required property {}.'.format(
36             match.group(1))
37     else:
38         message = 'Error: {}\n'.format(error.message)
39         if len(error.absolute_path) > 0:
40             message += 'Path: {}\n'.format(
41                        '.'.join(
42                            [six.text_type(path)
43                             for path in error.absolute_path]))
44         message += 'Value: {}'.format(json.dumps(error.instance))
45
46     return message
47
48
49 def verify(new_vnfd):
50     errors_found = []
51     vnfd_schema_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), "vnf_vnfd_all_schema.json")
52     with open(vnfd_schema_path, "r") as fvnfd_schema:
53         vnfd_schema = json.load(fvnfd_schema)
54         vnfd_validator = jsonschema.validators.Draft4Validator(schema=vnfd_schema)
55         for error in vnfd_validator.iter_errors(new_vnfd):
56             # print("Error:%s" % error)
57             logger.error("vnfd verify fail,%s" % _format_validation_error(error))
58             errors_found.append(_format_validation_error(error))
59     if len(errors_found) > 0:
60         raise NFLCMException(errors_found)
61     return True