15fe873fa5e31b59c229c54bd04dd5eed5545030
[apex.git] / lib / python / apex / 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 yaml
11 import re
12 from .common.constants import (
13     ADMIN_NETWORK,
14     PRIVATE_NETWORK,
15     STORAGE_NETWORK,
16     PUBLIC_NETWORK,
17     API_NETWORK,
18     CONTROLLER_PRE,
19     COMPUTE_PRE,
20     PRE_CONFIG_DIR
21 )
22
23 PORTS = '/ports'
24 # Resources defined by <resource name>: <prefix>
25 EXTERNAL_RESOURCES = {'OS::TripleO::Network::External': None,
26                       'OS::TripleO::Network::Ports::ExternalVipPort': PORTS,
27                       'OS::TripleO::Controller::Ports::ExternalPort': PORTS,
28                       'OS::TripleO::Compute::Ports::ExternalPort': PORTS}
29 TENANT_RESOURCES = {'OS::TripleO::Network::Tenant': None,
30                     'OS::TripleO::Controller::Ports::TenantPort': PORTS,
31                     'OS::TripleO::Compute::Ports::TenantPort': PORTS}
32 STORAGE_RESOURCES = {'OS::TripleO::Network::Storage': None,
33                      'OS::TripleO::Network::Ports::StorageVipPort': PORTS,
34                      'OS::TripleO::Controller::Ports::StoragePort': PORTS,
35                      'OS::TripleO::Compute::Ports::StoragePort': PORTS}
36 API_RESOURCES = {'OS::TripleO::Network::InternalApi': None,
37                  'OS::TripleO::Network::Ports::InternalApiVipPort': PORTS,
38                  'OS::TripleO::Controller::Ports::InternalApiPort': PORTS,
39                  'OS::TripleO::Compute::Ports::InternalApiPort': PORTS}
40
41 # A list of flags that will be set to true when IPv6 is enabled
42 IPV6_FLAGS = ["NovaIPv6", "MongoDbIPv6", "CorosyncIPv6", "CephIPv6",
43               "RabbitIPv6", "MemcachedIPv6"]
44
45 reg = 'resource_registry'
46 param_def = 'parameter_defaults'
47
48
49 class NetworkEnvironment(dict):
50     """
51     This class creates a Network Environment to be used in TripleO Heat
52     Templates.
53
54     The class builds upon an existing network-environment file and modifies
55     based on a NetworkSettings object.
56     """
57     def __init__(self, net_settings, filename, compute_pre_config=False,
58                  controller_pre_config=False):
59         init_dict = {}
60         if type(filename) is str:
61             with open(filename, 'r') as net_env_fh:
62                 init_dict = yaml.safe_load(net_env_fh)
63
64         super().__init__(init_dict)
65         try:
66             enabled_networks = net_settings.enabled_network_list
67         except:
68             raise NetworkEnvException('Invalid Network Setting object')
69
70         self._set_tht_dir()
71
72         enabled_networks = net_settings.get_enabled_networks()
73
74         admin_cidr = net_settings[ADMIN_NETWORK]['cidr']
75         admin_prefix = str(admin_cidr.prefixlen)
76         self[param_def]['ControlPlaneSubnetCidr'] = admin_prefix
77         self[param_def]['ControlPlaneDefaultRoute'] = \
78             net_settings[ADMIN_NETWORK]['provisioner_ip']
79         public_cidr = net_settings[PUBLIC_NETWORK]['cidr']
80         self[param_def]['ExternalNetCidr'] = str(public_cidr)
81         if net_settings[PUBLIC_NETWORK]['vlan'] != 'native':
82             self[param_def]['NeutronExternalNetworkBridge'] = '""'
83             self[param_def]['ExternalNetworkVlanID'] = \
84                 net_settings[PUBLIC_NETWORK]['vlan']
85         public_range = \
86             net_settings[PUBLIC_NETWORK]['usable_ip_range'].split(',')
87         self[param_def]['ExternalAllocationPools'] = \
88             [{'start':
89               public_range[0],
90               'end': public_range[1]
91               }]
92         self[param_def]['ExternalInterfaceDefaultRoute'] = \
93             net_settings[PUBLIC_NETWORK]['gateway']
94         self[param_def]['EC2MetadataIp'] = \
95             net_settings[ADMIN_NETWORK]['provisioner_ip']
96         self[param_def]['DnsServers'] = net_settings['dns_servers']
97
98         if public_cidr.version == 6:
99             postfix = '/external_v6.yaml'
100         else:
101             postfix = '/external.yaml'
102
103         # apply resource registry update for EXTERNAL_RESOURCES
104         self._config_resource_reg(EXTERNAL_RESOURCES, postfix)
105
106         if PRIVATE_NETWORK in enabled_networks:
107             priv_range = net_settings[PRIVATE_NETWORK][
108                 'usable_ip_range'].split(',')
109             self[param_def]['TenantAllocationPools'] = \
110                 [{'start':
111                   priv_range[0],
112                   'end': priv_range[1]
113                   }]
114             priv_cidr = net_settings[PRIVATE_NETWORK]['cidr']
115             self[param_def]['TenantNetCidr'] = str(priv_cidr)
116             if priv_cidr.version == 6:
117                 postfix = '/tenant_v6.yaml'
118             else:
119                 postfix = '/tenant.yaml'
120             if net_settings[PRIVATE_NETWORK]['vlan'] != 'native':
121                 self[param_def]['TenantNetworkVlanID'] = \
122                     net_settings[PRIVATE_NETWORK]['vlan']
123         else:
124             postfix = '/noop.yaml'
125
126         # apply resource registry update for TENANT_RESOURCES
127         self._config_resource_reg(TENANT_RESOURCES, postfix)
128
129         if STORAGE_NETWORK in enabled_networks:
130             storage_range = net_settings[STORAGE_NETWORK][
131                 'usable_ip_range'].split(',')
132             self[param_def]['StorageAllocationPools'] = \
133                 [{'start':
134                   storage_range[0],
135                   'end':
136                   storage_range[1]
137                   }]
138             storage_cidr = net_settings[STORAGE_NETWORK]['cidr']
139             self[param_def]['StorageNetCidr'] = str(storage_cidr)
140             if storage_cidr.version == 6:
141                 postfix = '/storage_v6.yaml'
142             else:
143                 postfix = '/storage.yaml'
144             if net_settings[STORAGE_NETWORK]['vlan'] != 'native':
145                 self[param_def]['StorageNetworkVlanID'] = \
146                     net_settings[STORAGE_NETWORK]['vlan']
147         else:
148             postfix = '/noop.yaml'
149
150         # apply resource registry update for STORAGE_RESOURCES
151         self._config_resource_reg(STORAGE_RESOURCES, postfix)
152
153         if API_NETWORK in enabled_networks:
154             api_range = net_settings[API_NETWORK][
155                 'usable_ip_range'].split(',')
156             self[param_def]['InternalApiAllocationPools'] = \
157                 [{'start': api_range[0],
158                   'end': api_range[1]
159                   }]
160             api_cidr = net_settings[API_NETWORK]['cidr']
161             self[param_def]['InternalApiNetCidr'] = str(api_cidr)
162             if api_cidr.version == 6:
163                 postfix = '/internal_api_v6.yaml'
164             else:
165                 postfix = '/internal_api.yaml'
166             if net_settings[API_NETWORK]['vlan'] != 'native':
167                 self[param_def]['InternalApiNetworkVlanID'] = \
168                     net_settings[API_NETWORK]['vlan']
169         else:
170             postfix = '/noop.yaml'
171
172         # apply resource registry update for API_RESOURCES
173         self._config_resource_reg(API_RESOURCES, postfix)
174
175         if compute_pre_config:
176             self[reg][COMPUTE_PRE] = PRE_CONFIG_DIR + "compute/numa.yaml"
177         if controller_pre_config:
178             self[reg][CONTROLLER_PRE] = PRE_CONFIG_DIR + "controller/numa.yaml"
179
180         # Set IPv6 related flags to True. Not that we do not set those to False
181         # when IPv4 is configured, we'll use the default or whatever the user
182         # may have set.
183         if net_settings.get_ip_addr_family() == 6:
184             for flag in IPV6_FLAGS:
185                 self[param_def][flag] = True
186
187     def _set_tht_dir(self):
188         self.tht_dir = None
189         for key, prefix in TENANT_RESOURCES.items():
190             if prefix is None:
191                 prefix = ''
192             m = re.split('%s/\w+\.yaml' % prefix, self[reg][key])
193             if m is not None:
194                 self.tht_dir = m[0]
195                 break
196         if not self.tht_dir:
197             raise NetworkEnvException('Unable to parse THT Directory')
198
199     def _config_resource_reg(self, resources, postfix):
200         for key, prefix in resources.items():
201             if prefix is None:
202                 prefix = ''
203             self[reg][key] = self.tht_dir + prefix + postfix
204
205
206 class NetworkEnvException(Exception):
207     def __init__(self, value):
208         self.value = value
209
210     def __str__(self):
211             return self.value