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 com.woorea.openstack.base.client.OpenStackBaseException;
27 import com.woorea.openstack.base.client.OpenStackConnectException;
28 import com.woorea.openstack.base.client.OpenStackRequest;
29 import com.woorea.openstack.base.client.OpenStackResponseException;
30 import com.woorea.openstack.keystone.Keystone;
31 import com.woorea.openstack.keystone.model.Access;
32 import com.woorea.openstack.keystone.model.Authentication;
33 import com.woorea.openstack.keystone.utils.KeystoneUtils;
34 import com.woorea.openstack.quantum.Quantum;
35 import com.woorea.openstack.quantum.model.Network;
36 import com.woorea.openstack.quantum.model.Networks;
37 import com.woorea.openstack.quantum.model.Segment;
38 import java.util.ArrayList;
39 import java.util.Calendar;
40 import java.util.List;
41 import org.onap.so.cloud.CloudConfig;
42 import org.onap.so.cloud.authentication.AuthenticationMethodFactory;
43 import org.onap.so.cloud.authentication.KeystoneAuthHolder;
44 import org.onap.so.cloud.authentication.KeystoneV3Authentication;
45 import org.onap.so.cloud.authentication.ServiceEndpointNotFoundException;
46 import org.onap.so.db.catalog.beans.CloudIdentity;
47 import org.onap.so.db.catalog.beans.CloudSite;
48 import org.onap.so.db.catalog.beans.ServerType;
49 import org.onap.so.logger.ErrorCode;
50 import org.onap.so.logger.MessageEnum;
51 import org.onap.so.openstack.beans.NetworkInfo;
52 import org.onap.so.openstack.exceptions.MsoAdapterException;
53 import org.onap.so.openstack.exceptions.MsoCloudSiteNotFound;
54 import org.onap.so.openstack.exceptions.MsoException;
55 import org.onap.so.openstack.exceptions.MsoIOException;
56 import org.onap.so.openstack.exceptions.MsoNetworkAlreadyExists;
57 import org.onap.so.openstack.exceptions.MsoNetworkNotFound;
58 import org.onap.so.openstack.exceptions.MsoOpenstackException;
59 import org.onap.so.openstack.mappers.NetworkInfoMapper;
60 import org.slf4j.Logger;
61 import org.slf4j.LoggerFactory;
62 import org.springframework.beans.factory.annotation.Autowired;
63 import org.springframework.stereotype.Component;
66 public class MsoNeutronUtils extends MsoCommonUtils
69 // Fetch cloud configuration each time (may be cached in CloudConfig class)
71 private CloudConfig cloudConfig;
74 private AuthenticationMethodFactory authenticationMethodFactory;
77 private MsoTenantUtilsFactory tenantUtilsFactory;
80 private KeystoneV3Authentication keystoneV3Authentication;
82 private static Logger logger = LoggerFactory.getLogger(MsoNeutronUtils.class);
84 public enum NetworkType {
85 BASIC, PROVIDER, MULTI_PROVIDER
89 * Create a network with the specified parameters in the given cloud/tenant.
91 * If a network already exists with the same name, an exception will be thrown. Note that
92 * this is an MSO-imposed restriction. Openstack does not require uniqueness on network names.
94 * @param cloudSiteId The cloud identifier (may be a region) in which to create the network.
95 * @param tenantId The tenant in which to create the network
96 * @param type The type of network to create (Basic, Provider, Multi-Provider)
97 * @param networkName The network name to create
98 * @param provider The provider network name (for Provider or Multi-Provider networks)
99 * @param vlans A list of VLAN segments for the network (for Provider or Multi-Provider networks)
100 * @return a NetworkInfo object which describes the newly created network
101 * @throws MsoNetworkAlreadyExists Thrown if a network with the same name already exists
102 * @throws MsoOpenstackException Thrown if the Openstack API call returns an exception
103 * @throws MsoCloudSiteNotFound Thrown if the cloudSite is invalid or unknown
105 public NetworkInfo createNetwork (String cloudSiteId, String tenantId, NetworkType type, String networkName, String provider, List<Integer> vlans)
108 // Obtain the cloud site information where we will create the stack
109 CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId).orElseThrow(
110 () -> new MsoCloudSiteNotFound(cloudSiteId));
112 Quantum neutronClient = getNeutronClient (cloudSite, tenantId);
114 // Check if a network already exists with this name
115 // Openstack will allow duplicate name, so require explicit check
116 Network network = findNetworkByName (neutronClient, networkName);
118 if (network != null) {
119 // Network already exists. Throw an exception
120 logger.error("{} Network {} on Cloud site {} for tenant {} already exists {}",
121 MessageEnum.RA_NETWORK_ALREADY_EXIST, networkName, cloudSiteId, tenantId,
122 ErrorCode.DataError.getValue());
123 throw new MsoNetworkAlreadyExists (networkName, tenantId, cloudSiteId);
126 // Does not exist, create a new one
127 network = new Network();
128 network.setName(networkName);
129 network.setAdminStateUp(true);
131 if (type == NetworkType.PROVIDER) {
132 if (provider != null && vlans != null && vlans.size() > 0) {
133 network.setProviderPhysicalNetwork (provider);
134 network.setProviderNetworkType("vlan");
135 network.setProviderSegmentationId (vlans.get(0));
137 } else if (type == NetworkType.MULTI_PROVIDER) {
138 if (provider != null && vlans != null && vlans.size() > 0) {
139 List<Segment> segments = new ArrayList<>(vlans.size());
140 for (int vlan : vlans) {
141 Segment segment = new Segment();
142 segment.setProviderPhysicalNetwork (provider);
143 segment.setProviderNetworkType("vlan");
144 segment.setProviderSegmentationId (vlan);
146 segments.add(segment);
148 network.setSegments(segments);
153 OpenStackRequest<Network> request = neutronClient.networks().create(network);
154 Network newNetwork = executeAndRecordOpenstackRequest(request);
155 return new NetworkInfoMapper(newNetwork).map();
157 catch (OpenStackBaseException e) {
158 // Convert Neutron exception to an MsoOpenstackException
159 MsoException me = neutronExceptionToMsoException (e, "CreateNetwork");
162 catch (RuntimeException e) {
164 MsoException me = runtimeExceptionToMsoException(e, "CreateNetwork");
171 * Query for a network with the specified name or ID in the given cloud. If the network exists,
172 * return an NetworkInfo object. If not, return null.
174 * Whenever possible, the network ID should be used as it is much more efficient. Query by
175 * name requires retrieval of all networks for the tenant and search for matching name.
177 * @param networkNameOrId The network to query
178 * @param tenantId The Openstack tenant to look in for the network
179 * @param cloudSiteId The cloud identifier (may be a region) in which to query the network.
180 * @return a NetworkInfo object describing the queried network, or null if not found
181 * @throws MsoOpenstackException Thrown if the Openstack API call returns an exception
182 * @throws MsoCloudSiteNotFound
184 public NetworkInfo queryNetwork(String networkNameOrId, String tenantId, String cloudSiteId) throws MsoException
186 logger.debug("In queryNetwork");
188 // Obtain the cloud site information
189 CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId).orElseThrow(
190 () -> new MsoCloudSiteNotFound(cloudSiteId));
192 Quantum neutronClient = getNeutronClient (cloudSite, tenantId);
194 // Check if the network exists and return its info
196 Network network = findNetworkByNameOrId (neutronClient, networkNameOrId);
197 if (network == null) {
198 logger.debug("Query Network: {} not found in tenant {}", networkNameOrId, tenantId);
201 return new NetworkInfoMapper(network).map();
203 catch (OpenStackBaseException e) {
204 // Convert Neutron exception to an MsoOpenstackException
205 MsoException me = neutronExceptionToMsoException (e, "QueryNetwork");
208 catch (RuntimeException e) {
210 MsoException me = runtimeExceptionToMsoException(e, "QueryNetwork");
216 * Delete the specified Network (by ID) in the given cloud.
217 * If the network does not exist, success is returned.
219 * @param networkId Openstack ID of the network to delete
220 * @param tenantId The Openstack tenant.
221 * @param cloudSiteId The cloud identifier (may be a region) from which to delete the network.
222 * @return true if the network was deleted, false if the network did not exist
223 * @throws MsoOpenstackException If the Openstack API call returns an exception, this local
224 * exception will be thrown.
225 * @throws MsoCloudSiteNotFound
227 public boolean deleteNetwork(String networkId, String tenantId, String cloudSiteId) throws MsoException
229 // Obtain the cloud site information where we will create the stack
230 CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId).orElseThrow(
231 () -> new MsoCloudSiteNotFound(cloudSiteId));
232 Quantum neutronClient = getNeutronClient (cloudSite, tenantId);
235 // Check that the network exists.
236 Network network = findNetworkById (neutronClient, networkId);
237 if (network == null) {
238 logger.info("{} Network not found! Network id: {} Cloud site: {} Tenant: {} ",
239 MessageEnum.RA_DELETE_NETWORK_EXC, networkId, cloudSiteId, tenantId);
243 OpenStackRequest<Void> request = neutronClient.networks().delete(network.getId());
244 executeAndRecordOpenstackRequest(request);
246 logger.debug("Deleted Network {} ({})", network.getId(), network.getName());
248 catch (OpenStackBaseException e) {
249 // Convert Neutron exception to an MsoOpenstackException
250 MsoException me = neutronExceptionToMsoException (e, "Delete Network");
253 catch (RuntimeException e) {
255 MsoException me = runtimeExceptionToMsoException(e, "DeleteNetwork");
264 * Update a network with the specified parameters in the given cloud/tenant.
266 * Specifically, this call is intended to update the VLAN segments on a
267 * multi-provider network. The provider segments will be replaced with the
268 * supplied list of VLANs.
270 * Note that updating the 'segments' array is not normally supported by Neutron.
271 * This method relies on a Platform Orchestration extension (using SDN controller
272 * to manage the virtual networking).
274 * @param cloudSiteId The cloud site ID (may be a region) in which to update the network.
275 * @param tenantId Openstack ID of the tenant in which to update the network
276 * @param networkId The unique Openstack ID of the network to be updated
277 * @param type The network type (Basic, Provider, Multi-Provider)
278 * @param provider The provider network name. This should not change.
279 * @param vlans The list of VLAN segments to replace
280 * @return a NetworkInfo object which describes the updated network
281 * @throws MsoNetworkNotFound Thrown if the requested network does not exist
282 * @throws MsoOpenstackException Thrown if the Openstack API call returns an exception
283 * @throws MsoCloudSiteNotFound
285 public NetworkInfo updateNetwork (String cloudSiteId, String tenantId, String networkId, NetworkType type, String provider, List<Integer> vlans)
288 // Obtain the cloud site information where we will create the stack
289 CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId).orElseThrow(
290 () -> new MsoCloudSiteNotFound(cloudSiteId));
291 Quantum neutronClient = getNeutronClient (cloudSite, tenantId);
293 // Check that the network exists
294 Network network = findNetworkById (neutronClient, networkId);
296 if (network == null) {
297 // Network not found. Throw an exception
298 logger.error("{} Network {} on Cloud site {} for Tenant {} not found {}", MessageEnum.RA_NETWORK_NOT_FOUND,
299 networkId, cloudSiteId, tenantId, ErrorCode.DataError.getValue());
300 throw new MsoNetworkNotFound (networkId, tenantId, cloudSiteId);
303 // Overwrite the properties to be updated
304 if (type == NetworkType.PROVIDER) {
305 if (provider != null && vlans != null && vlans.size() > 0) {
306 network.setProviderPhysicalNetwork (provider);
307 network.setProviderNetworkType("vlan");
308 network.setProviderSegmentationId (vlans.get(0));
310 } else if (type == NetworkType.MULTI_PROVIDER) {
311 if (provider != null && vlans != null && vlans.size() > 0) {
312 List<Segment> segments = new ArrayList<>(vlans.size());
313 for (int vlan : vlans) {
314 Segment segment = new Segment();
315 segment.setProviderPhysicalNetwork (provider);
316 segment.setProviderNetworkType("vlan");
317 segment.setProviderSegmentationId (vlan);
319 segments.add(segment);
321 network.setSegments(segments);
326 OpenStackRequest<Network> request = neutronClient.networks().update(network);
327 Network newNetwork = executeAndRecordOpenstackRequest(request);
328 return new NetworkInfoMapper(newNetwork).map();
330 catch (OpenStackBaseException e) {
331 // Convert Neutron exception to an MsoOpenstackException
332 MsoException me = neutronExceptionToMsoException (e, "UpdateNetwork");
335 catch (RuntimeException e) {
337 MsoException me = runtimeExceptionToMsoException(e, "UpdateNetwork");
343 // -------------------------------------------------------------------
344 // PRIVATE UTILITY FUNCTIONS FOR USE WITHIN THIS CLASS
347 * Get a Neutron (Quantum) client for the Openstack Network service.
348 * This requires a 'member'-level userId + password, which will be retrieved from
349 * properties based on the specified cloud Id. The tenant in which to operate
350 * must also be provided.
352 * On successful authentication, the Quantum object will be cached for the
353 * tenantID + cloudId so that it can be reused without reauthenticating with
354 * Openstack every time.
356 * @param cloudSite - a cloud site definition
357 * @param tenantId - Openstack tenant ID
358 * @return an authenticated Quantum object
360 private Quantum getNeutronClient(CloudSite cloudSite, String tenantId) throws MsoException
362 String cloudId = cloudSite.getId();
363 String region = cloudSite.getRegionId();
366 // Obtain an MSO token for the tenant from the identity service
367 CloudIdentity cloudIdentity = cloudSite.getIdentityService();
368 MsoTenantUtils tenantUtils = tenantUtilsFactory.getTenantUtilsByServerType(cloudIdentity.getIdentityServerType());
369 final String keystoneUrl = tenantUtils.getKeystoneUrl(cloudId, cloudIdentity);
370 String neutronUrl = null;
371 String tokenId = null;
372 Calendar expiration = null;
374 if (ServerType.KEYSTONE.equals(cloudIdentity.getIdentityServerType())) {
375 Keystone keystoneTenantClient = new Keystone(keystoneUrl);
376 Access access = null;
378 Authentication credentials = authenticationMethodFactory.getAuthenticationFor(cloudIdentity);
379 OpenStackRequest<Access> request = keystoneTenantClient.tokens().authenticate(credentials).withTenantId(tenantId);
380 access = executeAndRecordOpenstackRequest(request);
384 neutronUrl = KeystoneUtils.findEndpointURL(access.getServiceCatalog(), "network", region, "public");
385 if (! neutronUrl.endsWith("/")) {
386 neutronUrl += "/v2.0/";
388 } catch (RuntimeException e) {
389 // This comes back for not found (probably an incorrect region ID)
390 String error = "Network service not found: region=" + region + ",cloud=" + cloudIdentity.getId();
391 throw new MsoAdapterException (error, e);
393 tokenId = access.getToken().getId();
394 expiration = access.getToken().getExpires();
395 } else if (ServerType.KEYSTONE_V3.equals(cloudIdentity.getIdentityServerType())) {
397 KeystoneAuthHolder holder = keystoneV3Authentication.getToken(cloudSite, tenantId, "network");
398 tokenId = holder.getId();
399 expiration = holder.getexpiration();
400 neutronUrl = holder.getServiceUrl();
401 if (! neutronUrl.endsWith("/")) {
402 neutronUrl += "/v2.0/";
404 } catch (ServiceEndpointNotFoundException e) {
405 // This comes back for not found (probably an incorrect region ID)
406 String error = "Network service not found: region=" + region + ",cloud=" + cloudIdentity.getId();
407 throw new MsoAdapterException (error, e);
411 catch (OpenStackResponseException e) {
412 if (e.getStatus() == 401) {
413 // Authentication error.
414 String error = "Authentication Failure: tenant=" + tenantId + ",cloud=" + cloudIdentity.getId();
416 throw new MsoAdapterException(error);
419 MsoException me = keystoneErrorToMsoException(e, "TokenAuth");
423 catch (OpenStackConnectException e) {
424 // Connection to Openstack failed
425 MsoIOException me = new MsoIOException (e.getMessage(), e);
426 me.addContext("TokenAuth");
429 catch (RuntimeException e) {
431 MsoException me = runtimeExceptionToMsoException(e, "TokenAuth");
435 Quantum neutronClient = new Quantum(neutronUrl);
436 neutronClient.token(tokenId);
437 return neutronClient;
441 * Find a tenant (or query its existence) by its Name or Id. Check first against the
442 * ID. If that fails, then try by name.
444 * @param adminClient an authenticated Keystone object
445 * @param tenantName the tenant name or ID to query
446 * @return a Tenant object or null if not found
448 public Network findNetworkByNameOrId (Quantum neutronClient, String networkNameOrId)
450 if (networkNameOrId == null) {
454 Network network = findNetworkById(neutronClient, networkNameOrId);
456 if (network == null) {
457 network = findNetworkByName(neutronClient, networkNameOrId);
464 * Find a network (or query its existence) by its Id.
466 * @param neutronClient an authenticated Quantum object
467 * @param networkId the network ID to query
468 * @return a Network object or null if not found
470 private Network findNetworkById (Quantum neutronClient, String networkId)
472 if (networkId == null) {
477 OpenStackRequest<Network> request = neutronClient.networks().show(networkId);
478 Network network = executeAndRecordOpenstackRequest(request);
481 catch (OpenStackResponseException e) {
482 if (e.getStatus() == 404) {
485 logger.error("{} {} Openstack Error, GET Network By ID ({}): ", MessageEnum.RA_CONNECTION_EXCEPTION,
486 ErrorCode.DataError.getValue(), networkId, e);
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("{} {} Openstack Error, GET Network By Name ({}): ", MessageEnum.RA_CONNECTION_EXCEPTION,
533 ErrorCode.DataError.getValue(), networkName, e);