Adding checks to upgrade and validation tools
[osm/devops.git] / descriptor-packages / tools / validate_descriptor.py
1 #!/usr/bin/env python2
2 # -*- coding: utf-8 -*-
3
4 ##
5 # All Rights Reserved.
6 #
7 # Licensed under the Apache License, Version 2.0 (the "License"); you may
8 # not use this file except in compliance with the License. You may obtain
9 # a copy of the License at
10 #
11 # http://www.apache.org/licenses/LICENSE-2.0
12 #
13 # Unless required by applicable law or agreed to in writing, software
14 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
15 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
16 # License for the specific language governing permissions and limitations
17 # under the License.
18 #
19 ##
20 from __future__ import print_function
21 import json
22 import yaml
23 import sys
24 import getopt
25
26 """
27 Tests the format of OSM VNFD and NSD descriptors
28 """
29 __author__ = "Alfonso Tierno, Guillermo Calvino"
30 __date__ = "2018-04-16"
31 __version__ = "0.0.1"
32 version_date = "Apr 2018"
33
34
35 class ArgumentParserError(Exception):
36 pass
37
38
39 def usage():
40 print("Usage: {} [options] FILE".format(sys.argv[0]))
41 print(" EXPERIMENTAL: Validates vnfd, nsd descriptors format")
42 print(" FILE: a yaml or json vnfd-catalog or nsd-catalog descriptor")
43 print(" OPTIONS:")
44 print(" -v|--version: prints current version")
45 print(" -h|--help: shows this help")
46 print(" -i|--input FILE: (same as param FILE) descriptor file to be upgraded")
47 return
48
49 def remove_prefix(desc, prefix):
50 """
51 Recursively removes prefix from keys
52 :param desc: dictionary or list to change
53 :param prefix: prefix to remove. Must
54 :return: None, param desc is changed
55 """
56 prefix_len = len(prefix)
57 if isinstance(desc, dict):
58 prefixed_list=[]
59 for k,v in desc.items():
60 if isinstance(v, (list, tuple, dict)):
61 remove_prefix(v, prefix)
62 if isinstance(k, str) and k.startswith(prefix) and k != prefix:
63 prefixed_list.append(k)
64 for k in prefixed_list:
65 desc[k[prefix_len:]] = desc.pop(k)
66 elif isinstance(desc, (list, tuple)):
67 for i in desc:
68 if isinstance(desc, (list, tuple, dict)):
69 remove_prefix(i, prefix)
70
71 if __name__=="__main__":
72 error_position = []
73 format_output_yaml = True
74 input_file_name = None
75 test_file = None
76 file_name = None
77 try:
78 # load parameters and configuration
79 opts, args = getopt.getopt(sys.argv[1:], "hvi:o:", ["input=", "help", "version",])
80
81 for o, a in opts:
82 if o in ("-v", "--version"):
83 print ("test descriptor version THREE " + __version__ + ' ' + version_date)
84 sys.exit()
85 elif o in ("-h", "--help"):
86 usage()
87 sys.exit()
88 elif o in ("-i", "--input"):
89 input_file_name = a
90 else:
91 assert False, "Unhandled option"
92 if not input_file_name:
93 if not args:
94 raise ArgumentParserError("missing DESCRIPTOR_FILE parameter. Type --help for more info")
95 input_file_name = args[0]
96
97 # Open files
98 file_name = input_file_name
99 with open(file_name, 'r') as f:
100 descriptor_str = f.read()
101 file_name = None
102
103 if input_file_name.endswith('.yaml') or input_file_name.endswith('.yml') or not \
104 (input_file_name.endswith('.json') or '\t' in descriptor_str):
105 data = yaml.load(descriptor_str)
106 else: # json
107 data = json.loads(descriptor_str)
108 format_output_yaml = False
109
110 import osm_im.vnfd as vnfd_catalog
111 import osm_im.nsd as nsd_catalog
112 from pyangbind.lib.serialise import pybindJSONDecoder
113
114 if "vnfd:vnfd-catalog" in data or "vnfd-catalog" in data:
115 descriptor = "VNF"
116 # Check if mgmt-interface is defined:
117 remove_prefix(data, "vnfd:")
118 vnfd_descriptor = data["vnfd-catalog"]
119 vnfd_list = vnfd_descriptor["vnfd"]
120 mgmt_iface = False
121 for vnfd in vnfd_list:
122 if vnfd.get("mgmt-interface"):
123 mgmt_iface = True
124 if not mgmt_iface:
125 raise KeyError("'mgmt-iface' is a mandatory field and it is not defined")
126 myvnfd = vnfd_catalog.vnfd()
127 pybindJSONDecoder.load_ietf_json(data, None, None, obj=myvnfd)
128 elif "nsd:nsd-catalog" in data or "nsd-catalog" in data:
129 descriptor = "NS"
130 mynsd = nsd_catalog.nsd()
131 pybindJSONDecoder.load_ietf_json(data, None, None, obj=mynsd)
132 else:
133 descriptor = None
134 raise KeyError("This is not neither nsd-catalog nor vnfd-catalog descriptor")
135 exit(0)
136
137 except yaml.YAMLError as exc:
138 error_pos = ""
139 if hasattr(exc, 'problem_mark'):
140 mark = exc.problem_mark
141 error_pos = "at line:%s column:%s" % (mark.line + 1, mark.column + 1)
142 print("Error loading file '{}'. yaml format error {}".format(input_file_name, error_pos), file=sys.stderr)
143 except ArgumentParserError as e:
144 print(str(e), file=sys.stderr)
145 except IOError as e:
146 print("Error loading file '{}': {}".format(file_name, e), file=sys.stderr)
147 except ImportError as e:
148 print ("Package python-osm-im not installed: {}".format(e), file=sys.stderr)
149 except Exception as e:
150 if file_name:
151 print("Error loading file '{}': {}".format(file_name, str(e)), file=sys.stderr)
152 else:
153 if descriptor:
154 print("Error. Invalid {} descriptor format in '{}': {}".format(descriptor, input_file_name, str(e)), file=sys.stderr)
155 else:
156 print("Error. Invalid descriptor format in '{}': {}".format(input_file_name, str(e)), file=sys.stderr)
157 exit(1)