2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Modifications Copyright (c) 2019 Samsung
8 * ================================================================================
9 * Licensed under the Apache License, Version 2.0 (the "License");
10 * you may not use this file except in compliance with the License.
11 * You may obtain a copy of the License at
13 * http://www.apache.org/licenses/LICENSE-2.0
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 * ============LICENSE_END=========================================================
23 package org.onap.so.openstack.utils;
26 import java.util.ArrayList;
27 import java.util.Calendar;
28 import java.util.List;
29 import java.util.Optional;
31 import org.onap.so.cloud.CloudConfig;
32 import org.onap.so.cloud.authentication.AuthenticationMethodFactory;
33 import org.onap.so.cloud.authentication.KeystoneAuthHolder;
34 import org.onap.so.cloud.authentication.KeystoneV3Authentication;
35 import org.onap.so.cloud.authentication.ServiceEndpointNotFoundException;
36 import org.onap.so.db.catalog.beans.CloudIdentity;
37 import org.onap.so.db.catalog.beans.CloudSite;
38 import org.onap.so.db.catalog.beans.ServerType;
39 import org.onap.so.logger.ErrorCode;
40 import org.onap.so.logger.MessageEnum;
41 import org.onap.so.openstack.beans.NetworkInfo;
42 import org.onap.so.openstack.exceptions.MsoAdapterException;
43 import org.onap.so.openstack.exceptions.MsoCloudSiteNotFound;
44 import org.onap.so.openstack.exceptions.MsoException;
45 import org.onap.so.openstack.exceptions.MsoIOException;
46 import org.onap.so.openstack.exceptions.MsoNetworkAlreadyExists;
47 import org.onap.so.openstack.exceptions.MsoNetworkNotFound;
48 import org.onap.so.openstack.exceptions.MsoOpenstackException;
49 import org.onap.so.openstack.mappers.NetworkInfoMapper;
50 import org.slf4j.Logger;
51 import org.slf4j.LoggerFactory;
52 import org.springframework.beans.factory.annotation.Autowired;
53 import org.springframework.stereotype.Component;
55 import com.woorea.openstack.base.client.OpenStackBaseException;
56 import com.woorea.openstack.base.client.OpenStackConnectException;
57 import com.woorea.openstack.base.client.OpenStackRequest;
58 import com.woorea.openstack.base.client.OpenStackResponseException;
59 import com.woorea.openstack.keystone.Keystone;
60 import com.woorea.openstack.keystone.model.Access;
61 import com.woorea.openstack.keystone.model.Authentication;
62 import com.woorea.openstack.keystone.utils.KeystoneUtils;
63 import com.woorea.openstack.quantum.Quantum;
64 import com.woorea.openstack.quantum.model.Network;
65 import com.woorea.openstack.quantum.model.Networks;
66 import com.woorea.openstack.quantum.model.Port;
67 import com.woorea.openstack.quantum.model.Segment;
70 public class MsoNeutronUtils extends MsoCommonUtils
73 // Fetch cloud configuration each time (may be cached in CloudConfig class)
75 private CloudConfig cloudConfig;
78 private AuthenticationMethodFactory authenticationMethodFactory;
81 private MsoTenantUtilsFactory tenantUtilsFactory;
84 private KeystoneV3Authentication keystoneV3Authentication;
86 private static Logger logger = LoggerFactory.getLogger(MsoNeutronUtils.class);
88 public enum NetworkType {
89 BASIC, PROVIDER, MULTI_PROVIDER
93 * Create a network with the specified parameters in the given cloud/tenant.
95 * If a network already exists with the same name, an exception will be thrown. Note that
96 * this is an MSO-imposed restriction. Openstack does not require uniqueness on network names.
98 * @param cloudSiteId The cloud identifier (may be a region) in which to create the network.
99 * @param tenantId The tenant in which to create the network
100 * @param type The type of network to create (Basic, Provider, Multi-Provider)
101 * @param networkName The network name to create
102 * @param provider The provider network name (for Provider or Multi-Provider networks)
103 * @param vlans A list of VLAN segments for the network (for Provider or Multi-Provider networks)
104 * @return a NetworkInfo object which describes the newly created network
105 * @throws MsoNetworkAlreadyExists Thrown if a network with the same name already exists
106 * @throws MsoOpenstackException Thrown if the Openstack API call returns an exception
107 * @throws MsoCloudSiteNotFound Thrown if the cloudSite is invalid or unknown
109 public NetworkInfo createNetwork (String cloudSiteId, String tenantId, NetworkType type, String networkName, String provider, List<Integer> vlans)
112 // Obtain the cloud site information where we will create the stack
113 CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId).orElseThrow(
114 () -> new MsoCloudSiteNotFound(cloudSiteId));
116 Quantum neutronClient = getNeutronClient (cloudSite, tenantId);
118 // Check if a network already exists with this name
119 // Openstack will allow duplicate name, so require explicit check
120 Network network = findNetworkByName (neutronClient, networkName);
122 if (network != null) {
123 // Network already exists. Throw an exception
124 logger.error("{} Network {} on Cloud site {} for tenant {} already exists {}",
125 MessageEnum.RA_NETWORK_ALREADY_EXIST, networkName, cloudSiteId, tenantId,
126 ErrorCode.DataError.getValue());
127 throw new MsoNetworkAlreadyExists (networkName, tenantId, cloudSiteId);
130 // Does not exist, create a new one
131 network = new Network();
132 network.setName(networkName);
133 network.setAdminStateUp(true);
135 if (type == NetworkType.PROVIDER) {
136 if (provider != null && vlans != null && vlans.size() > 0) {
137 network.setProviderPhysicalNetwork (provider);
138 network.setProviderNetworkType("vlan");
139 network.setProviderSegmentationId (vlans.get(0));
141 } else if (type == NetworkType.MULTI_PROVIDER) {
142 if (provider != null && vlans != null && vlans.size() > 0) {
143 List<Segment> segments = new ArrayList<>(vlans.size());
144 for (int vlan : vlans) {
145 Segment segment = new Segment();
146 segment.setProviderPhysicalNetwork (provider);
147 segment.setProviderNetworkType("vlan");
148 segment.setProviderSegmentationId (vlan);
150 segments.add(segment);
152 network.setSegments(segments);
157 OpenStackRequest<Network> request = neutronClient.networks().create(network);
158 Network newNetwork = executeAndRecordOpenstackRequest(request);
159 return new NetworkInfoMapper(newNetwork).map();
161 catch (OpenStackBaseException e) {
162 // Convert Neutron exception to an MsoOpenstackException
163 MsoException me = neutronExceptionToMsoException (e, "CreateNetwork");
166 catch (RuntimeException e) {
168 MsoException me = runtimeExceptionToMsoException(e, "CreateNetwork");
175 * Query for a network with the specified name or ID in the given cloud. If the network exists,
176 * return an NetworkInfo object. If not, return null.
178 * Whenever possible, the network ID should be used as it is much more efficient. Query by
179 * name requires retrieval of all networks for the tenant and search for matching name.
181 * @param networkNameOrId The network to query
182 * @param tenantId The Openstack tenant to look in for the network
183 * @param cloudSiteId The cloud identifier (may be a region) in which to query the network.
184 * @return a NetworkInfo object describing the queried network, or null if not found
185 * @throws MsoOpenstackException Thrown if the Openstack API call returns an exception
186 * @throws MsoCloudSiteNotFound
188 public NetworkInfo queryNetwork(String networkNameOrId, String tenantId, String cloudSiteId) throws MsoException
190 logger.debug("In queryNetwork");
192 // Obtain the cloud site information
193 CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId).orElseThrow(
194 () -> new MsoCloudSiteNotFound(cloudSiteId));
196 Quantum neutronClient = getNeutronClient (cloudSite, tenantId);
198 // Check if the network exists and return its info
200 Network network = findNetworkByNameOrId (neutronClient, networkNameOrId);
201 if (network == null) {
202 logger.debug("Query Network: {} not found in tenant {}", networkNameOrId, tenantId);
205 return new NetworkInfoMapper(network).map();
207 catch (OpenStackBaseException e) {
208 // Convert Neutron exception to an MsoOpenstackException
209 MsoException me = neutronExceptionToMsoException (e, "QueryNetwork");
212 catch (RuntimeException e) {
214 MsoException me = runtimeExceptionToMsoException(e, "QueryNetwork");
219 public Optional<Port> getNeutronPort(String neutronPortId, String tenantId, String cloudSiteId)
222 CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId).orElseThrow(
223 () -> new MsoCloudSiteNotFound(cloudSiteId));
224 Quantum neutronClient = getNeutronClient (cloudSite, tenantId);
225 Port port = findPortById (neutronClient, neutronPortId);
227 return Optional.empty();
229 return Optional.of(port);
231 catch (RuntimeException | MsoException e) {
232 logger.error("Error retrieving neutron port", e);
233 return Optional.empty();
238 * Delete the specified Network (by ID) in the given cloud.
239 * If the network does not exist, success is returned.
241 * @param networkId Openstack ID of the network to delete
242 * @param tenantId The Openstack tenant.
243 * @param cloudSiteId The cloud identifier (may be a region) from which to delete the network.
244 * @return true if the network was deleted, false if the network did not exist
245 * @throws MsoOpenstackException If the Openstack API call returns an exception, this local
246 * exception will be thrown.
247 * @throws MsoCloudSiteNotFound
249 public boolean deleteNetwork(String networkId, String tenantId, String cloudSiteId) throws MsoException
251 // Obtain the cloud site information where we will create the stack
252 CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId).orElseThrow(
253 () -> new MsoCloudSiteNotFound(cloudSiteId));
254 Quantum neutronClient = getNeutronClient (cloudSite, tenantId);
257 // Check that the network exists.
258 Network network = findNetworkById (neutronClient, networkId);
259 if (network == null) {
260 logger.info("{} Network not found! Network id: {} Cloud site: {} Tenant: {} ",
261 MessageEnum.RA_DELETE_NETWORK_EXC, networkId, cloudSiteId, tenantId);
265 OpenStackRequest<Void> request = neutronClient.networks().delete(network.getId());
266 executeAndRecordOpenstackRequest(request);
268 logger.debug("Deleted Network {} ({})", network.getId(), network.getName());
270 catch (OpenStackBaseException e) {
271 // Convert Neutron exception to an MsoOpenstackException
272 MsoException me = neutronExceptionToMsoException (e, "Delete Network");
275 catch (RuntimeException e) {
277 MsoException me = runtimeExceptionToMsoException(e, "DeleteNetwork");
286 * Update a network with the specified parameters in the given cloud/tenant.
288 * Specifically, this call is intended to update the VLAN segments on a
289 * multi-provider network. The provider segments will be replaced with the
290 * supplied list of VLANs.
292 * Note that updating the 'segments' array is not normally supported by Neutron.
293 * This method relies on a Platform Orchestration extension (using SDN controller
294 * to manage the virtual networking).
296 * @param cloudSiteId The cloud site ID (may be a region) in which to update the network.
297 * @param tenantId Openstack ID of the tenant in which to update the network
298 * @param networkId The unique Openstack ID of the network to be updated
299 * @param type The network type (Basic, Provider, Multi-Provider)
300 * @param provider The provider network name. This should not change.
301 * @param vlans The list of VLAN segments to replace
302 * @return a NetworkInfo object which describes the updated network
303 * @throws MsoNetworkNotFound Thrown if the requested network does not exist
304 * @throws MsoOpenstackException Thrown if the Openstack API call returns an exception
305 * @throws MsoCloudSiteNotFound
307 public NetworkInfo updateNetwork (String cloudSiteId, String tenantId, String networkId, NetworkType type, String provider, List<Integer> vlans)
310 // Obtain the cloud site information where we will create the stack
311 CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId).orElseThrow(
312 () -> new MsoCloudSiteNotFound(cloudSiteId));
313 Quantum neutronClient = getNeutronClient (cloudSite, tenantId);
315 // Check that the network exists
316 Network network = findNetworkById (neutronClient, networkId);
318 if (network == null) {
319 // Network not found. Throw an exception
320 logger.error("{} Network {} on Cloud site {} for Tenant {} not found {}", MessageEnum.RA_NETWORK_NOT_FOUND,
321 networkId, cloudSiteId, tenantId, ErrorCode.DataError.getValue());
322 throw new MsoNetworkNotFound (networkId, tenantId, cloudSiteId);
325 // Overwrite the properties to be updated
326 if (type == NetworkType.PROVIDER) {
327 if (provider != null && vlans != null && vlans.size() > 0) {
328 network.setProviderPhysicalNetwork (provider);
329 network.setProviderNetworkType("vlan");
330 network.setProviderSegmentationId (vlans.get(0));
332 } else if (type == NetworkType.MULTI_PROVIDER) {
333 if (provider != null && vlans != null && vlans.size() > 0) {
334 List<Segment> segments = new ArrayList<>(vlans.size());
335 for (int vlan : vlans) {
336 Segment segment = new Segment();
337 segment.setProviderPhysicalNetwork (provider);
338 segment.setProviderNetworkType("vlan");
339 segment.setProviderSegmentationId (vlan);
341 segments.add(segment);
343 network.setSegments(segments);
348 OpenStackRequest<Network> request = neutronClient.networks().update(network);
349 Network newNetwork = executeAndRecordOpenstackRequest(request);
350 return new NetworkInfoMapper(newNetwork).map();
352 catch (OpenStackBaseException e) {
353 // Convert Neutron exception to an MsoOpenstackException
354 MsoException me = neutronExceptionToMsoException (e, "UpdateNetwork");
357 catch (RuntimeException e) {
359 MsoException me = runtimeExceptionToMsoException(e, "UpdateNetwork");
365 // -------------------------------------------------------------------
366 // PRIVATE UTILITY FUNCTIONS FOR USE WITHIN THIS CLASS
369 * Get a Neutron (Quantum) client for the Openstack Network service.
370 * This requires a 'member'-level userId + password, which will be retrieved from
371 * properties based on the specified cloud Id. The tenant in which to operate
372 * must also be provided.
374 * On successful authentication, the Quantum object will be cached for the
375 * tenantID + cloudId so that it can be reused without reauthenticating with
376 * Openstack every time.
378 * @param cloudSite - a cloud site definition
379 * @param tenantId - Openstack tenant ID
380 * @return an authenticated Quantum object
382 private Quantum getNeutronClient(CloudSite cloudSite, String tenantId) throws MsoException
384 String cloudId = cloudSite.getId();
385 String region = cloudSite.getRegionId();
388 // Obtain an MSO token for the tenant from the identity service
389 CloudIdentity cloudIdentity = cloudSite.getIdentityService();
390 MsoTenantUtils tenantUtils = tenantUtilsFactory.getTenantUtilsByServerType(cloudIdentity.getIdentityServerType());
391 final String keystoneUrl = tenantUtils.getKeystoneUrl(cloudId, cloudIdentity);
392 String neutronUrl = null;
393 String tokenId = null;
394 Calendar expiration = null;
396 if (ServerType.KEYSTONE.equals(cloudIdentity.getIdentityServerType())) {
397 Keystone keystoneTenantClient = new Keystone(keystoneUrl);
398 Access access = null;
400 Authentication credentials = authenticationMethodFactory.getAuthenticationFor(cloudIdentity);
401 OpenStackRequest<Access> request = keystoneTenantClient.tokens().authenticate(credentials).withTenantId(tenantId);
402 access = executeAndRecordOpenstackRequest(request);
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 throw new MsoAdapterException (error, e);
415 tokenId = access.getToken().getId();
416 expiration = access.getToken().getExpires();
417 } else if (ServerType.KEYSTONE_V3.equals(cloudIdentity.getIdentityServerType())) {
419 KeystoneAuthHolder holder = keystoneV3Authentication.getToken(cloudSite, tenantId, "network");
420 tokenId = holder.getId();
421 expiration = holder.getexpiration();
422 neutronUrl = holder.getServiceUrl();
423 if (! neutronUrl.endsWith("/")) {
424 neutronUrl += "/v2.0/";
426 } catch (ServiceEndpointNotFoundException e) {
427 // This comes back for not found (probably an incorrect region ID)
428 String error = "Network service not found: region=" + region + ",cloud=" + cloudIdentity.getId();
429 throw new MsoAdapterException (error, e);
433 catch (OpenStackResponseException e) {
434 if (e.getStatus() == 401) {
435 // Authentication error.
436 String error = "Authentication Failure: tenant=" + tenantId + ",cloud=" + cloudIdentity.getId();
438 throw new MsoAdapterException(error);
441 MsoException me = keystoneErrorToMsoException(e, "TokenAuth");
445 catch (OpenStackConnectException e) {
446 // Connection to Openstack failed
447 MsoIOException me = new MsoIOException (e.getMessage(), e);
448 me.addContext("TokenAuth");
451 catch (RuntimeException e) {
453 MsoException me = runtimeExceptionToMsoException(e, "TokenAuth");
457 Quantum neutronClient = new Quantum(neutronUrl);
458 neutronClient.token(tokenId);
459 return neutronClient;
463 * Find a tenant (or query its existence) by its Name or Id. Check first against the
464 * ID. If that fails, then try by name.
466 * @param adminClient an authenticated Keystone object
467 * @param tenantName the tenant name or ID to query
468 * @return a Tenant object or null if not found
470 public Network findNetworkByNameOrId (Quantum neutronClient, String networkNameOrId)
472 if (networkNameOrId == null) {
476 Network network = findNetworkById(neutronClient, networkNameOrId);
478 if (network == null) {
479 network = findNetworkByName(neutronClient, networkNameOrId);
486 * Find a network (or query its existence) by its Id.
488 * @param neutronClient an authenticated Quantum object
489 * @param networkId the network ID to query
490 * @return a Network object or null if not found
492 private Network findNetworkById (Quantum neutronClient, String networkId)
494 if (networkId == null) {
499 OpenStackRequest<Network> request = neutronClient.networks().show(networkId);
500 Network network = executeAndRecordOpenstackRequest(request);
503 catch (OpenStackResponseException e) {
504 if (e.getStatus() == 404) {
507 logger.error("{} {} Openstack Error, GET Network By ID ({}): ", MessageEnum.RA_CONNECTION_EXCEPTION,
508 ErrorCode.DataError.getValue(), networkId, e);
515 private Port findPortById (Quantum neutronClient, String neutronPortId)
517 if (neutronPortId == null) {
522 OpenStackRequest<Port> request = neutronClient.ports().show(neutronPortId);
523 Port port = executeAndRecordOpenstackRequest(request);
526 catch (OpenStackResponseException e) {
527 if (e.getStatus() == 404) {
530 logger.error("{} {} Openstack Error, GET Neutron Port By ID ({}): ", MessageEnum.RA_CONNECTION_EXCEPTION,
531 ErrorCode.DataError.getValue(), neutronPortId, e);
538 * Find a network (or query its existence) by its Name. This method avoids an
539 * initial lookup by ID when it's known that we have the network Name.
541 * Neutron does not support 'name=*' query parameter for Network query (show).
542 * The only way to query by name is to retrieve all networks and look for the
543 * match. While inefficient, this capability will be provided as it is needed
544 * by MSO, but should be avoided in favor of ID whenever possible.
547 * Network names are not required to be unique, though MSO will attempt to enforce
548 * uniqueness. This call probably needs to return an error (instead of returning
551 * @param neutronClient an authenticated Quantum object
552 * @param networkName the network name to query
553 * @return a Network object or null if not found
555 public Network findNetworkByName (Quantum neutronClient, String networkName)
557 if (networkName == null) {
562 OpenStackRequest<Networks> request = neutronClient.networks().list();
563 Networks networks = executeAndRecordOpenstackRequest(request);
564 for (Network network : networks.getList()) {
565 if (network.getName().equals(networkName)) {
566 logger.debug("Found match on network name: {}", networkName);
570 logger.debug("findNetworkByName - no match found for {}", networkName);
573 catch (OpenStackResponseException e) {
574 if (e.getStatus() == 404) {
577 logger.error("{} {} Openstack Error, GET Network By Name ({}): ", MessageEnum.RA_CONNECTION_EXCEPTION,
578 ErrorCode.DataError.getValue(), networkName, e);