c2e9991aab31dd1cc601d1bc67cbe3c91a53b30a
[apex.git] / apex / network / network_environment.py
1 ##############################################################################
2 # Copyright (c) 2016 Tim Rozet (trozet@redhat.com) and others.
3 #
4 # All rights reserved. This program and the accompanying materials
5 # are made available under the terms of the Apache License, Version 2.0
6 # which accompanies this distribution, and is available at
7 # http://www.apache.org/licenses/LICENSE-2.0
8 ##############################################################################
9
10 import re
11
12 import yaml
13
14 from apex.settings.network_settings import NetworkSettings
15 from apex.common.constants import (
16     CONTROLLER,
17     COMPUTE,
18     ADMIN_NETWORK,
19     TENANT_NETWORK,
20     STORAGE_NETWORK,
21     EXTERNAL_NETWORK,
22     API_NETWORK
23 )
24
25 HEAT_NONE = 'OS::Heat::None'
26 PORTS = '/ports'
27 # Resources defined by <resource name>: <prefix>
28 EXTERNAL_RESOURCES = {'OS::TripleO::Network::External': None,
29                       'OS::TripleO::Network::Ports::ExternalVipPort': PORTS,
30                       'OS::TripleO::Controller::Ports::ExternalPort': PORTS,
31                       'OS::TripleO::Compute::Ports::ExternalPort': PORTS}
32 TENANT_RESOURCES = {'OS::TripleO::Network::Tenant': None,
33                     'OS::TripleO::Controller::Ports::TenantPort': PORTS,
34                     'OS::TripleO::Compute::Ports::TenantPort': PORTS}
35 STORAGE_RESOURCES = {'OS::TripleO::Network::Storage': None,
36                      'OS::TripleO::Network::Ports::StorageVipPort': PORTS,
37                      'OS::TripleO::Controller::Ports::StoragePort': PORTS,
38                      'OS::TripleO::Compute::Ports::StoragePort': PORTS}
39 API_RESOURCES = {'OS::TripleO::Network::InternalApi': None,
40                  'OS::TripleO::Network::Ports::InternalApiVipPort': PORTS,
41                  'OS::TripleO::Controller::Ports::InternalApiPort': PORTS,
42                  'OS::TripleO::Compute::Ports::InternalApiPort': PORTS}
43
44 # A list of flags that will be set to true when IPv6 is enabled
45 IPV6_FLAGS = ["NovaIPv6", "MongoDbIPv6", "CorosyncIPv6", "CephIPv6",
46               "RabbitIPv6", "MemcachedIPv6"]
47
48 reg = 'resource_registry'
49 param_def = 'parameter_defaults'
50
51
52 class NetworkEnvironment(dict):
53     """
54     This class creates a Network Environment to be used in TripleO Heat
55     Templates.
56
57     The class builds upon an existing network-environment file and modifies
58     based on a NetworkSettings object.
59     """
60     def __init__(self, net_settings, filename, compute_pre_config=False,
61                  controller_pre_config=False):
62         """
63         Create Network Environment according to Network Settings
64         """
65         init_dict = {}
66         if isinstance(filename, str):
67             with open(filename, 'r') as net_env_fh:
68                 init_dict = yaml.safe_load(net_env_fh)
69
70         super().__init__(init_dict)
71         if not isinstance(net_settings, NetworkSettings):
72             raise NetworkEnvException('Invalid Network Settings object')
73
74         self._set_tht_dir()
75
76         nets = net_settings['networks']
77
78         admin_cidr = nets[ADMIN_NETWORK]['cidr']
79         admin_prefix = str(admin_cidr.prefixlen)
80         self[param_def]['ControlPlaneSubnetCidr'] = admin_prefix
81         self[param_def]['ControlPlaneDefaultRoute'] = \
82             nets[ADMIN_NETWORK]['installer_vm']['ip']
83         self[param_def]['EC2MetadataIp'] = \
84             nets[ADMIN_NETWORK]['installer_vm']['ip']
85         self[param_def]['DnsServers'] = net_settings['dns_servers']
86
87         if EXTERNAL_NETWORK in net_settings.enabled_network_list:
88             external_cidr = net_settings.get_network(EXTERNAL_NETWORK)['cidr']
89             self[param_def]['ExternalNetCidr'] = str(external_cidr)
90             external_vlan = self._get_vlan(net_settings.get_network(
91                                            EXTERNAL_NETWORK))
92             if isinstance(external_vlan, int):
93                 self[param_def]['NeutronExternalNetworkBridge'] = '""'
94                 self[param_def]['ExternalNetworkVlanID'] = external_vlan
95             external_range = net_settings.get_network(EXTERNAL_NETWORK)[
96                 'overcloud_ip_range']
97             self[param_def]['ExternalAllocationPools'] = \
98                 [{'start': str(external_range[0]),
99                   'end': str(external_range[1])}]
100             self[param_def]['ExternalInterfaceDefaultRoute'] = \
101                 net_settings.get_network(EXTERNAL_NETWORK)['gateway']
102
103             if external_cidr.version == 6:
104                 postfix = '/external_v6.yaml'
105             else:
106                 postfix = '/external.yaml'
107         else:
108             postfix = '/noop.yaml'
109
110         # apply resource registry update for EXTERNAL_RESOURCES
111         self._config_resource_reg(EXTERNAL_RESOURCES, postfix)
112
113         if TENANT_NETWORK in net_settings.enabled_network_list:
114             tenant_range = nets[TENANT_NETWORK]['overcloud_ip_range']
115             self[param_def]['TenantAllocationPools'] = \
116                 [{'start': str(tenant_range[0]),
117                   'end': str(tenant_range[1])}]
118             tenant_cidr = nets[TENANT_NETWORK]['cidr']
119             self[param_def]['TenantNetCidr'] = str(tenant_cidr)
120             if tenant_cidr.version == 6:
121                 postfix = '/tenant_v6.yaml'
122                 # set overlay_ip_version option in Neutron ML2 config
123                 self[param_def]['NeutronOverlayIPVersion'] = "6"
124             else:
125                 postfix = '/tenant.yaml'
126
127             tenant_vlan = self._get_vlan(nets[TENANT_NETWORK])
128             if isinstance(tenant_vlan, int):
129                 self[param_def]['TenantNetworkVlanID'] = tenant_vlan
130         else:
131             postfix = '/noop.yaml'
132
133         # apply resource registry update for TENANT_RESOURCES
134         self._config_resource_reg(TENANT_RESOURCES, postfix)
135
136         if STORAGE_NETWORK in net_settings.enabled_network_list:
137             storage_range = nets[STORAGE_NETWORK]['overcloud_ip_range']
138             self[param_def]['StorageAllocationPools'] = \
139                 [{'start': str(storage_range[0]),
140                   'end': str(storage_range[1])}]
141             storage_cidr = nets[STORAGE_NETWORK]['cidr']
142             self[param_def]['StorageNetCidr'] = str(storage_cidr)
143             if storage_cidr.version == 6:
144                 postfix = '/storage_v6.yaml'
145             else:
146                 postfix = '/storage.yaml'
147             storage_vlan = self._get_vlan(nets[STORAGE_NETWORK])
148             if isinstance(storage_vlan, int):
149                 self[param_def]['StorageNetworkVlanID'] = storage_vlan
150         else:
151             postfix = '/noop.yaml'
152
153         # apply resource registry update for STORAGE_RESOURCES
154         self._config_resource_reg(STORAGE_RESOURCES, postfix)
155
156         if API_NETWORK in net_settings.enabled_network_list:
157             api_range = nets[API_NETWORK]['overcloud_ip_range']
158             self[param_def]['InternalApiAllocationPools'] = \
159                 [{'start': str(api_range[0]),
160                   'end': str(api_range[1])}]
161             api_cidr = nets[API_NETWORK]['cidr']
162             self[param_def]['InternalApiNetCidr'] = str(api_cidr)
163             if api_cidr.version == 6:
164                 postfix = '/internal_api_v6.yaml'
165             else:
166                 postfix = '/internal_api.yaml'
167             api_vlan = self._get_vlan(nets[API_NETWORK])
168             if isinstance(api_vlan, int):
169                 self[param_def]['InternalApiNetworkVlanID'] = api_vlan
170         else:
171             postfix = '/noop.yaml'
172
173         # apply resource registry update for API_RESOURCES
174         self._config_resource_reg(API_RESOURCES, postfix)
175
176         # Set IPv6 related flags to True. Not that we do not set those to False
177         # when IPv4 is configured, we'll use the default or whatever the user
178         # may have set.
179         if net_settings.get_ip_addr_family() == 6:
180             for flag in IPV6_FLAGS:
181                 self[param_def][flag] = True
182
183     def _get_vlan(self, network):
184         if isinstance(network['nic_mapping'][CONTROLLER]['vlan'], int):
185             return network['nic_mapping'][CONTROLLER]['vlan']
186         elif isinstance(network['nic_mapping'][COMPUTE]['vlan'], int):
187             return network['nic_mapping'][COMPUTE]['vlan']
188         else:
189             return 'native'
190
191     def _set_tht_dir(self):
192         self.tht_dir = None
193         for key, prefix in TENANT_RESOURCES.items():
194             if prefix is None:
195                 prefix = ''
196             m = re.split('%s/\w+\.yaml' % prefix, self[reg][key])
197             if m is not None and len(m) > 1:
198                 self.tht_dir = m[0]
199                 break
200         if not self.tht_dir:
201             raise NetworkEnvException('Unable to parse THT Directory')
202
203     def _config_resource_reg(self, resources, postfix):
204         for key, prefix in resources.items():
205             if prefix is None:
206                 if postfix == '/noop.yaml':
207                     self[reg][key] = HEAT_NONE
208                     continue
209                 prefix = ''
210             self[reg][key] = self.tht_dir + prefix + postfix
211
212
213 class NetworkEnvException(Exception):
214     def __init__(self, value):
215         self.value = value
216
217     def __str__(self):
218             return self.value