2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END=========================================================
21 package org.openecomp.mso.openstack.utils;
24 import java.io.Serializable;
25 import java.util.ArrayList;
26 import java.util.Calendar;
27 import java.util.HashMap;
28 import java.util.List;
31 import org.openecomp.mso.cloud.CloudConfig;
32 import org.openecomp.mso.cloud.CloudConfigFactory;
33 import org.openecomp.mso.cloud.CloudIdentity;
34 import org.openecomp.mso.cloud.CloudSite;
35 import org.openecomp.mso.logger.MessageEnum;
36 import org.openecomp.mso.logger.MsoAlarmLogger;
37 import org.openecomp.mso.logger.MsoLogger;
38 import org.openecomp.mso.openstack.beans.NetworkInfo;
39 import org.openecomp.mso.openstack.exceptions.MsoAdapterException;
40 import org.openecomp.mso.openstack.exceptions.MsoCloudSiteNotFound;
41 import org.openecomp.mso.openstack.exceptions.MsoException;
42 import org.openecomp.mso.openstack.exceptions.MsoIOException;
43 import org.openecomp.mso.openstack.exceptions.MsoNetworkAlreadyExists;
44 import org.openecomp.mso.openstack.exceptions.MsoNetworkNotFound;
45 import org.openecomp.mso.openstack.exceptions.MsoOpenstackException;
46 import com.woorea.openstack.base.client.OpenStackBaseException;
47 import com.woorea.openstack.base.client.OpenStackConnectException;
48 import com.woorea.openstack.base.client.OpenStackRequest;
49 import com.woorea.openstack.base.client.OpenStackResponseException;
50 import com.woorea.openstack.keystone.Keystone;
51 import com.woorea.openstack.keystone.model.Access;
52 import com.woorea.openstack.keystone.utils.KeystoneUtils;
53 import com.woorea.openstack.quantum.Quantum;
54 import com.woorea.openstack.quantum.model.Network;
55 import com.woorea.openstack.quantum.model.Networks;
56 import com.woorea.openstack.quantum.model.Segment;
57 import com.woorea.openstack.keystone.model.Authentication;
59 public class MsoNeutronUtils extends MsoCommonUtils
61 // Cache Neutron Clients statically. Since there is just one MSO user, there is no
62 // benefit to re-authentication on every request (or across different flows). The
63 // token will be used until it expires.
65 // The cache key is "tenantId:cloudId"
66 private static Map<String,NeutronCacheEntry> neutronClientCache = new HashMap<>();
68 private CloudConfigFactory cloudConfigFactory;
70 private static MsoLogger LOGGER = MsoLogger.getMsoLogger (MsoLogger.Catalog.RA);
71 private String msoPropID;
73 public enum NetworkType {
74 BASIC, PROVIDER, MULTI_PROVIDER
77 public MsoNeutronUtils(String msoPropID, CloudConfigFactory cloudConfigFactory) {
78 this.cloudConfigFactory = cloudConfigFactory;
79 this.msoPropID = msoPropID;
82 protected CloudConfigFactory getCloudConfigFactory() {
83 return cloudConfigFactory;
87 * Create a network with the specified parameters in the given cloud/tenant.
89 * If a network already exists with the same name, an exception will be thrown. Note that
90 * this is an MSO-imposed restriction. Openstack does not require uniqueness on network names.
92 * @param cloudSiteId The cloud identifier (may be a region) in which to create the network.
93 * @param tenantId The tenant in which to create the network
94 * @param type The type of network to create (Basic, Provider, Multi-Provider)
95 * @param networkName The network name to create
96 * @param provider The provider network name (for Provider or Multi-Provider networks)
97 * @param vlans A list of VLAN segments for the network (for Provider or Multi-Provider networks)
98 * @return a NetworkInfo object which describes the newly created network
99 * @throws MsoNetworkAlreadyExists Thrown if a network with the same name already exists
100 * @throws MsoOpenstackException Thrown if the Openstack API call returns an exception
101 * @throws MsoCloudSiteNotFound Thrown if the cloudSite is invalid or unknown
103 public NetworkInfo createNetwork (String cloudSiteId, String tenantId, NetworkType type, String networkName, String provider, List<Integer> vlans)
106 // Obtain the cloud site information where we will create the stack
107 CloudSite cloudSite = getCloudConfigFactory().getCloudConfig().getCloudSite(cloudSiteId).orElseThrow(
108 () -> new MsoCloudSiteNotFound(cloudSiteId));
110 Quantum neutronClient = getNeutronClient (cloudSite, tenantId);
112 // Check if a network already exists with this name
113 // Openstack will allow duplicate name, so require explicit check
114 Network network = findNetworkByName (neutronClient, networkName);
116 if (network != null) {
117 // Network already exists. Throw an exception
118 LOGGER.error(MessageEnum.RA_NETWORK_ALREADY_EXIST, networkName, cloudSiteId, tenantId, "Openstack", "", MsoLogger.ErrorCode.DataError, "Network already exists");
119 throw new MsoNetworkAlreadyExists (networkName, tenantId, cloudSiteId);
122 // Does not exist, create a new one
123 network = new Network();
124 network.setName(networkName);
125 network.setAdminStateUp(true);
127 if (type == NetworkType.PROVIDER) {
128 if (provider != null && vlans != null && vlans.size() > 0) {
129 network.setProviderPhysicalNetwork (provider);
130 network.setProviderNetworkType("vlan");
131 network.setProviderSegmentationId (vlans.get(0));
133 } else if (type == NetworkType.MULTI_PROVIDER) {
134 if (provider != null && vlans != null && vlans.size() > 0) {
135 List<Segment> segments = new ArrayList<>(vlans.size());
136 for (int vlan : vlans) {
137 Segment segment = new Segment();
138 segment.setProviderPhysicalNetwork (provider);
139 segment.setProviderNetworkType("vlan");
140 segment.setProviderSegmentationId (vlan);
142 segments.add(segment);
144 network.setSegments(segments);
149 OpenStackRequest<Network> request = neutronClient.networks().create(network);
150 Network newNetwork = executeAndRecordOpenstackRequest(request);
151 return new NetworkInfo(newNetwork);
153 catch (OpenStackBaseException e) {
154 // Convert Neutron exception to an MsoOpenstackException
155 MsoException me = neutronExceptionToMsoException (e, "CreateNetwork");
158 catch (RuntimeException e) {
160 MsoException me = runtimeExceptionToMsoException(e, "CreateNetwork");
167 * Query for a network with the specified name or ID in the given cloud. If the network exists,
168 * return an NetworkInfo object. If not, return null.
170 * Whenever possible, the network ID should be used as it is much more efficient. Query by
171 * name requires retrieval of all networks for the tenant and search for matching name.
173 * @param networkNameOrId The network to query
174 * @param tenantId The Openstack tenant to look in for the network
175 * @param cloudSiteId The cloud identifier (may be a region) in which to query the network.
176 * @return a NetworkInfo object describing the queried network, or null if not found
177 * @throws MsoOpenstackException Thrown if the Openstack API call returns an exception
178 * @throws MsoCloudSiteNotFound
180 public NetworkInfo queryNetwork(String networkNameOrId, String tenantId, String cloudSiteId) throws MsoException
182 LOGGER.debug("In queryNetwork");
184 // Obtain the cloud site information
185 CloudSite cloudSite = getCloudConfigFactory().getCloudConfig().getCloudSite(cloudSiteId).orElseThrow(
186 () -> new MsoCloudSiteNotFound(cloudSiteId));
188 Quantum neutronClient = getNeutronClient (cloudSite, tenantId);
189 // Check if the network exists and return its info
191 Network network = findNetworkByNameOrId (neutronClient, networkNameOrId);
192 if (network == null) {
193 LOGGER.debug ("Query Network: " + networkNameOrId + " not found in tenant " + tenantId);
196 return new NetworkInfo(network);
198 catch (OpenStackBaseException e) {
199 // Convert Neutron exception to an MsoOpenstackException
200 MsoException me = neutronExceptionToMsoException (e, "QueryNetwork");
203 catch (RuntimeException e) {
205 MsoException me = runtimeExceptionToMsoException(e, "QueryNetwork");
211 * Delete the specified Network (by ID) in the given cloud.
212 * If the network does not exist, success is returned.
214 * @param networkId Openstack ID of the network to delete
215 * @param tenantId The Openstack tenant.
216 * @param cloudSiteId The cloud identifier (may be a region) from which to delete the network.
217 * @return true if the network was deleted, false if the network did not exist
218 * @throws MsoOpenstackException If the Openstack API call returns an exception, this local
219 * exception will be thrown.
220 * @throws MsoCloudSiteNotFound
222 public boolean deleteNetwork(String networkId, String tenantId, String cloudSiteId) throws MsoException
224 // Obtain the cloud site information where we will create the stack
225 CloudSite cloudSite = getCloudConfigFactory().getCloudConfig().getCloudSite(cloudSiteId).orElseThrow(
226 () -> new MsoCloudSiteNotFound(cloudSiteId));
227 Quantum neutronClient = getNeutronClient (cloudSite, tenantId);
229 // Check that the network exists.
230 Network network = findNetworkById (neutronClient, networkId);
231 if (network == null) {
232 LOGGER.info(MessageEnum.RA_DELETE_NETWORK_EXC, networkId, cloudSiteId, tenantId, "Openstack", "");
236 OpenStackRequest<Void> request = neutronClient.networks().delete(network.getId());
237 executeAndRecordOpenstackRequest(request);
239 LOGGER.debug ("Deleted Network " + network.getId() + " (" + network.getName() + ")");
241 catch (OpenStackBaseException e) {
242 // Convert Neutron exception to an MsoOpenstackException
243 MsoException me = neutronExceptionToMsoException (e, "Delete Network");
246 catch (RuntimeException e) {
248 MsoException me = runtimeExceptionToMsoException(e, "DeleteNetwork");
257 * Update a network with the specified parameters in the given cloud/tenant.
259 * Specifically, this call is intended to update the VLAN segments on a
260 * multi-provider network. The provider segments will be replaced with the
261 * supplied list of VLANs.
263 * Note that updating the 'segments' array is not normally supported by Neutron.
264 * This method relies on a Platform Orchestration extension (using SDN controller
265 * to manage the virtual networking).
267 * @param cloudSiteId The cloud site ID (may be a region) in which to update the network.
268 * @param tenantId Openstack ID of the tenant in which to update the network
269 * @param networkId The unique Openstack ID of the network to be updated
270 * @param type The network type (Basic, Provider, Multi-Provider)
271 * @param provider The provider network name. This should not change.
272 * @param vlans The list of VLAN segments to replace
273 * @return a NetworkInfo object which describes the updated network
274 * @throws MsoNetworkNotFound Thrown if the requested network does not exist
275 * @throws MsoOpenstackException Thrown if the Openstack API call returns an exception
276 * @throws MsoCloudSiteNotFound
278 public NetworkInfo updateNetwork (String cloudSiteId, String tenantId, String networkId, NetworkType type, String provider, List<Integer> vlans)
281 // Obtain the cloud site information where we will create the stack
282 CloudSite cloudSite = getCloudConfigFactory().getCloudConfig().getCloudSite(cloudSiteId).orElseThrow(
283 () -> new MsoCloudSiteNotFound(cloudSiteId));
284 Quantum neutronClient = getNeutronClient (cloudSite, tenantId);
285 // Check that the network exists
286 Network network = findNetworkById (neutronClient, networkId);
288 if (network == null) {
289 // Network not found. Throw an exception
290 LOGGER.error(MessageEnum.RA_NETWORK_NOT_FOUND, networkId, cloudSiteId, tenantId, "Openstack", "", MsoLogger.ErrorCode.DataError, "Network not found");
291 throw new MsoNetworkNotFound (networkId, tenantId, cloudSiteId);
294 // Overwrite the properties to be updated
295 if (type == NetworkType.PROVIDER) {
296 if (provider != null && vlans != null && vlans.size() > 0) {
297 network.setProviderPhysicalNetwork (provider);
298 network.setProviderNetworkType("vlan");
299 network.setProviderSegmentationId (vlans.get(0));
301 } else if (type == NetworkType.MULTI_PROVIDER) {
302 if (provider != null && vlans != null && vlans.size() > 0) {
303 List<Segment> segments = new ArrayList<>(vlans.size());
304 for (int vlan : vlans) {
305 Segment segment = new Segment();
306 segment.setProviderPhysicalNetwork (provider);
307 segment.setProviderNetworkType("vlan");
308 segment.setProviderSegmentationId (vlan);
310 segments.add(segment);
312 network.setSegments(segments);
317 OpenStackRequest<Network> request = neutronClient.networks().update(network);
318 Network newNetwork = executeAndRecordOpenstackRequest(request);
319 return new NetworkInfo(newNetwork);
321 catch (OpenStackBaseException e) {
322 // Convert Neutron exception to an MsoOpenstackException
323 MsoException me = neutronExceptionToMsoException (e, "UpdateNetwork");
326 catch (RuntimeException e) {
328 MsoException me = runtimeExceptionToMsoException(e, "UpdateNetwork");
334 // -------------------------------------------------------------------
335 // PRIVATE UTILITY FUNCTIONS FOR USE WITHIN THIS CLASS
338 * Get a Neutron (Quantum) client for the Openstack Network service.
339 * This requires a 'member'-level userId + password, which will be retrieved from
340 * properties based on the specified cloud Id. The tenant in which to operate
341 * must also be provided.
343 * On successful authentication, the Quantum object will be cached for the
344 * tenantID + cloudId so that it can be reused without reauthenticating with
345 * Openstack every time.
347 * @param cloudSite - a cloud site definition
348 * @param tenantId - Openstack tenant ID
349 * @return an authenticated Quantum object
351 private Quantum getNeutronClient(CloudSite cloudSite, String tenantId) throws MsoException
353 String cloudId = cloudSite.getId();
355 // Check first in the cache of previously authorized clients
356 String cacheKey = cloudId + ":" + tenantId;
357 if (neutronClientCache.containsKey(cacheKey)) {
358 if (! neutronClientCache.get(cacheKey).isExpired()) {
359 LOGGER.debug ("Using Cached HEAT Client for " + cacheKey);
360 Quantum neutronClient = neutronClientCache.get(cacheKey).getNeutronClient();
361 return neutronClient;
364 // Token is expired. Remove it from cache.
365 neutronClientCache.remove(cacheKey);
366 LOGGER.debug ("Expired Cached Neutron Client for " + cacheKey);
370 // Obtain an MSO token for the tenant from the identity service
371 CloudIdentity cloudIdentity = cloudSite.getIdentityService();
372 Keystone keystoneTenantClient = new Keystone (cloudIdentity.getKeystoneUrl(cloudId, msoPropID));
373 Access access = null;
375 Authentication credentials = cloudIdentity.getAuthentication ();
376 OpenStackRequest<Access> request = keystoneTenantClient.tokens().authenticate(credentials).withTenantId(tenantId);
377 access = executeAndRecordOpenstackRequest(request);
379 catch (OpenStackResponseException e) {
380 if (e.getStatus() == 401) {
381 // Authentication error.
382 String error = "Authentication Failure: tenant=" + tenantId + ",cloud=" + cloudIdentity.getId();
383 alarmLogger .sendAlarm("MsoAuthenticationError", MsoAlarmLogger.CRITICAL, error);
384 throw new MsoAdapterException(error);
387 MsoException me = keystoneErrorToMsoException(e, "TokenAuth");
391 catch (OpenStackConnectException e) {
392 // Connection to Openstack failed
393 MsoIOException me = new MsoIOException (e.getMessage(), e);
394 me.addContext("TokenAuth");
397 catch (RuntimeException e) {
399 MsoException me = runtimeExceptionToMsoException(e, "TokenAuth");
403 String region = cloudSite.getRegionId();
404 String neutronUrl = null;
406 neutronUrl = KeystoneUtils.findEndpointURL(access.getServiceCatalog(), "network", region, "public");
407 if (! neutronUrl.endsWith("/")) {
408 neutronUrl += "/v2.0/";
410 } catch (RuntimeException e) {
411 // This comes back for not found (probably an incorrect region ID)
412 String error = "Network service not found: region=" + region + ",cloud=" + cloudIdentity.getId();
413 alarmLogger.sendAlarm("MsoConfigurationError", MsoAlarmLogger.CRITICAL, error);
414 throw new MsoAdapterException (error, e);
417 Quantum neutronClient = new Quantum(neutronUrl);
418 neutronClient.token(access.getToken().getId());
420 neutronClientCache.put(cacheKey, new NeutronCacheEntry(neutronUrl, access.getToken().getId(), access.getToken().getExpires()));
421 LOGGER.debug ("Caching Neutron Client for " + cacheKey);
423 return neutronClient;
427 * Forcibly expire a Neutron client from the cache. This call is for use by
428 * the KeystoneClient in case where a tenant is deleted. In that case,
429 * all cached credentials must be purged so that fresh authentication is
430 * done on subsequent calls.
432 public static void expireNeutronClient (String tenantId, String cloudId) {
433 String cacheKey = cloudId + ":" + tenantId;
434 if (neutronClientCache.containsKey(cacheKey)) {
435 neutronClientCache.remove(cacheKey);
436 LOGGER.debug ("Deleted Cached Neutron Client for " + cacheKey);
442 * Find a tenant (or query its existence) by its Name or Id. Check first against the
443 * ID. If that fails, then try by name.
445 * @param adminClient an authenticated Keystone object
446 * @param tenantName the tenant name or ID to query
447 * @return a Tenant object or null if not found
449 public Network findNetworkByNameOrId (Quantum neutronClient, String networkNameOrId)
451 if (networkNameOrId == null) {
455 Network network = findNetworkById(neutronClient, networkNameOrId);
457 if (network == null) {
458 network = findNetworkByName(neutronClient, networkNameOrId);
465 * Find a network (or query its existence) by its Id.
467 * @param neutronClient an authenticated Quantum object
468 * @param networkId the network ID to query
469 * @return a Network object or null if not found
471 private static Network findNetworkById (Quantum neutronClient, String networkId)
473 if (networkId == null) {
478 OpenStackRequest<Network> request = neutronClient.networks().show(networkId);
479 Network network = executeAndRecordOpenstackRequest(request);
482 catch (OpenStackResponseException e) {
483 if (e.getStatus() == 404) {
486 LOGGER.error (MessageEnum.RA_CONNECTION_EXCEPTION, "OpenStack", "Openstack Error, GET Network By ID (" + networkId + "): " + e, "Openstack", "", MsoLogger.ErrorCode.DataError, "Exception in Openstack");
493 * Find a network (or query its existence) by its Name. This method avoids an
494 * initial lookup by ID when it's known that we have the network Name.
496 * Neutron does not support 'name=*' query parameter for Network query (show).
497 * The only way to query by name is to retrieve all networks and look for the
498 * match. While inefficient, this capability will be provided as it is needed
499 * by MSO, but should be avoided in favor of ID whenever possible.
502 * Network names are not required to be unique, though MSO will attempt to enforce
503 * uniqueness. This call probably needs to return an error (instead of returning
506 * @param neutronClient an authenticated Quantum object
507 * @param networkName the network name to query
508 * @return a Network object or null if not found
510 public Network findNetworkByName (Quantum neutronClient, String networkName)
512 if (networkName == null) {
517 OpenStackRequest<Networks> request = neutronClient.networks().list();
518 Networks networks = executeAndRecordOpenstackRequest(request);
519 for (Network network : networks.getList()) {
520 if (network.getName().equals(networkName)) {
521 LOGGER.debug ("Found match on network name: " + networkName);
525 LOGGER.debug ("findNetworkByName - no match found for " + networkName);
528 catch (OpenStackResponseException e) {
529 if (e.getStatus() == 404) {
532 LOGGER.error (MessageEnum.RA_CONNECTION_EXCEPTION, "OpenStack", "Openstack Error, GET Network By Name (" + networkName + "): " + e, "OpenStack", "", MsoLogger.ErrorCode.DataError, "Exception in OpenStack");
540 * An entry in the Neutron Client Cache. It saves the Neutron client object
541 * along with the token expiration. After this interval, this cache
542 * item will no longer be used.
544 private static class NeutronCacheEntry implements Serializable
546 private static final long serialVersionUID = 1L;
548 private String neutronUrl;
549 private String token;
550 private Calendar expires;
552 public NeutronCacheEntry (String neutronUrl, String token, Calendar expires) {
553 this.neutronUrl = neutronUrl;
555 this.expires = expires;
558 public Quantum getNeutronClient () {
559 Quantum neutronClient = new Quantum(neutronUrl);
560 neutronClient.token(token);
561 return neutronClient;
564 public boolean isExpired() {
565 return expires == null || System.currentTimeMillis() > expires.getTimeInMillis();
570 * Clean up the Neutron client cache to remove expired entries.
572 public static void neutronCacheCleanup () {
573 for (String cacheKey : neutronClientCache.keySet()) {
574 if (neutronClientCache.get(cacheKey).isExpired()) {
575 neutronClientCache.remove(cacheKey);
576 LOGGER.debug ("Cleaned Up Cached Neutron Client for " + cacheKey);
582 * Reset the Neutron client cache.
583 * This may be useful if cached credentials get out of sync.
585 public static void neutronCacheReset () {
586 neutronClientCache = new HashMap<>();