[VVP] Removing unnecessary trademark lines
[vvp/validation-scripts.git] / ice_validator / tests / utils / network_roles.py
1 # -*- coding: utf8 -*-
2 # ============LICENSE_START=======================================================
3 # org.onap.vvp/validation-scripts
4 # ===================================================================
5 # Copyright © 2017 AT&T Intellectual Property. All rights reserved.
6 # ===================================================================
7 #
8 # Unless otherwise specified, all software contained herein is licensed
9 # under the Apache License, Version 2.0 (the "License");
10 # you may not use this software except in compliance with the License.
11 # You may obtain a copy of the License at
12 #
13 #             http://www.apache.org/licenses/LICENSE-2.0
14 #
15 # Unless required by applicable law or agreed to in writing, software
16 # distributed under the License is distributed on an "AS IS" BASIS,
17 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18 # See the License for the specific language governing permissions and
19 # limitations under the License.
20 #
21 #
22 #
23 # Unless otherwise specified, all documentation contained herein is licensed
24 # under the Creative Commons License, Attribution 4.0 Intl. (the "License");
25 # you may not use this documentation except in compliance with the License.
26 # You may obtain a copy of the License at
27 #
28 #             https://creativecommons.org/licenses/by/4.0/
29 #
30 # Unless required by applicable law or agreed to in writing, documentation
31 # distributed under the License is distributed on an "AS IS" BASIS,
32 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
33 # See the License for the specific language governing permissions and
34 # limitations under the License.
35 #
36 # ============LICENSE_END============================================
37 #
38 #
39
40 import re
41 import socket
42
43 PARAM_FORMATS = [
44     ["network", "string", "internal", re.compile(r"int_(.+?)_net_id")],
45     ["network", "string", "internal", re.compile(r"int_(.+?)_net_name")],
46     ["network", "string", "external", re.compile(r"(.+?)_net_id")],
47     ["network", "string", "external", re.compile(r"(.+?)_net_name")],
48 ]
49
50 RESOURCE_FORMATS = [
51     re.compile(r"int_(.+?)_network"),  # OS::ContrailV2::VirtualNetwork
52     re.compile(r"int_(.+?)_RVN"),  # OS::ContrailV2::VirtualNetwork
53     re.compile(r"int_(.+?)"),  # OS::Neutron::Net
54 ]
55
56
57 def get_network_role_and_type(resource):
58     """
59     Derive the network role and type (internal vs. external) from an
60     OS::Neutron::Port.
61
62     :param resource: dict of Resource attributes
63     :return: tuple of (network_role, network_type) where network_type is
64              'internal' or 'external'.  Returns (None, None) if resource
65              is not a port or the values cannot be derived.
66     """
67     if not isinstance(resource, dict):
68         return None, None
69     if resource.get("type", "") != "OS::Neutron::Port":
70         return None, None
71
72     network_props = resource.get("properties", {}).get("network", {})
73     is_resource = "get_resource" in network_props
74     if is_resource:
75         network = network_props.get("get_resource", "")
76     else:
77         network = network_props.get("get_param", "")
78
79     if is_resource:  # connecting to an network in the template
80         for format in RESOURCE_FORMATS:
81             m = format.match(network)
82             if m and m.group(1):
83                 return m.group(1), "internal"
84     else:
85         for format in PARAM_FORMATS:
86             m = format[3].match(network)
87             if m and m.group(1):
88                 return m.group(1), format[2]
89     return None, None
90
91
92 def get_network_role_from_port(resource):
93     """
94     Get the network-role from a OS::Neutron::Port resource.  Returns None
95     if resource is not a port or the network-role cannot be derived
96     """
97     return get_network_role_and_type(resource)[0]
98
99
100 def get_network_roles(resources, of_type=""):
101     """
102     Returns the network roles derived from the OS::Neutron::Port resources
103     in the collection of ``resources``.  If ``of_type`` is not specified
104     then all network roles will be returned, or ``external`` or ``internal``
105     can be passed to select only those network roles
106
107     :param resources:   collection of resource attributes (dict)
108     :param of_type:     "internal" or "external"
109     :return:            set of network roles discovered
110     """
111     valid_of_type = ("", "external", "internal")
112     if of_type not in ("", "external", "internal"):
113         raise RuntimeError("of_type must one of " + ", ".join(valid_of_type))
114     network_roles = set()
115     for v in resources.values():
116         nr, nt = get_network_role_and_type(v)
117         if not nr:
118             continue
119         if not of_type:
120             network_roles.add(nr)
121         elif of_type and of_type == nt:
122             network_roles.add(nr)
123     return network_roles
124
125
126 def get_network_type_from_port(resource):
127     """
128     Get the network-type (internal or external) from an OS::Neutron::Port
129     resource.  Returns None if the resource is not a port or the type
130     cannot be derived.
131     """
132     return get_network_role_and_type(resource)[1]
133
134
135 def is_valid_ip_address(ip_address, ip_type="ipv4"):
136     """
137     check if an ip address is valid
138     """
139     if ip_type == "ipv4":
140         return is_valid_ipv4_address(ip_address)
141     elif ip_type == "ipv6":
142         return is_valid_ipv6_address(ip_address)
143     return False
144
145
146 def is_valid_ipv4_address(ip_address):
147     """
148     check if an ip address of the type ipv4
149     is valid
150     """
151     try:
152         socket.inet_pton(socket.AF_INET, ip_address)
153     except AttributeError:
154         try:
155             socket.inet_aton(ip_address)
156         except (OSError, socket.error):
157             return False
158         return ip_address.count(".") == 3
159     except (OSError, socket.error):
160         return False
161     return True
162
163
164 def is_valid_ipv6_address(ip_address):
165     """
166     check if an ip address of the type ipv6
167     is valid
168     """
169     try:
170         socket.inet_pton(socket.AF_INET6, ip_address)
171     except (OSError, socket.error):
172         return False
173     return True
174
175
176 def property_uses_get_resource(resource, property_name):
177     """
178     returns true if a port's network property
179     uses the get_resource function
180     """
181     if not isinstance(resource, dict):
182         return False
183     if "properties" not in resource:
184         return False
185     for k1, v1 in resource["properties"].items():
186         if k1 != property_name:
187             continue
188         if isinstance(v1, dict) and "get_resource" in v1:
189             return True
190     return False