93460ff119c1d5a28165baac3d91343e33b5aee5
[so.git] / adapters / mso-adapter-utils / src / main / java / org / onap / so / openstack / utils / MsoNeutronUtils.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
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
12  * 
13  *      http://www.apache.org/licenses/LICENSE-2.0
14  * 
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=========================================================
21  */
22
23 package org.onap.so.openstack.utils;
24
25
26 import java.util.ArrayList;
27 import java.util.Calendar;
28 import java.util.List;
29 import java.util.Optional;
30
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;
54
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;
68
69 @Component
70 public class MsoNeutronUtils extends MsoCommonUtils
71 {
72
73         // Fetch cloud configuration each time (may be cached in CloudConfig class)
74         @Autowired
75         private CloudConfig cloudConfig;
76
77         @Autowired
78     private AuthenticationMethodFactory authenticationMethodFactory;
79         
80         @Autowired
81         private MsoTenantUtilsFactory tenantUtilsFactory;
82
83         @Autowired
84         private KeystoneV3Authentication keystoneV3Authentication;
85
86     private static Logger logger = LoggerFactory.getLogger(MsoNeutronUtils.class);
87
88     public enum NetworkType {
89                 BASIC, PROVIDER, MULTI_PROVIDER
90         };
91
92         /**
93          * Create a network with the specified parameters in the given cloud/tenant.
94          *
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.
97          * <p>
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
108          */
109         public NetworkInfo createNetwork (String cloudSiteId, String tenantId, NetworkType type, String networkName, String provider, List<Integer> vlans)
110             throws MsoException
111         {
112                 // Obtain the cloud site information where we will create the stack
113         CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId).orElseThrow(
114                 () -> new MsoCloudSiteNotFound(cloudSiteId));
115
116                 Quantum neutronClient = getNeutronClient (cloudSite, tenantId);
117
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);
121
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);
128                 }
129
130                 // Does not exist, create a new one
131                 network = new Network();
132                 network.setName(networkName);
133                 network.setAdminStateUp(true);
134
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));
140                         }
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);
149
150                                         segments.add(segment);
151                                 }
152                                 network.setSegments(segments);
153                         }
154                 }
155
156                 try {
157                         OpenStackRequest<Network> request = neutronClient.networks().create(network);
158                         Network newNetwork = executeAndRecordOpenstackRequest(request);
159                         return new NetworkInfoMapper(newNetwork).map();
160                 }
161                 catch (OpenStackBaseException e) {
162                         // Convert Neutron exception to an MsoOpenstackException
163                         MsoException me = neutronExceptionToMsoException (e, "CreateNetwork");
164                         throw me;
165                 }
166                 catch (RuntimeException e) {
167                         // Catch-all
168                         MsoException me = runtimeExceptionToMsoException(e, "CreateNetwork");
169                         throw me;
170                 }
171         }
172
173
174         /**
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.
177          * <p>
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.
180          * <p>
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
187          */
188     public NetworkInfo queryNetwork(String networkNameOrId, String tenantId, String cloudSiteId) throws MsoException
189         {
190       logger.debug("In queryNetwork");
191
192                 // Obtain the cloud site information
193         CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId).orElseThrow(
194                 () -> new MsoCloudSiteNotFound(cloudSiteId));
195
196                 Quantum neutronClient = getNeutronClient (cloudSite, tenantId);
197
198                 // Check if the network exists and return its info
199                 try {
200                         Network network = findNetworkByNameOrId (neutronClient, networkNameOrId);
201                         if (network == null) {
202           logger.debug("Query Network: {} not found in tenant {}", networkNameOrId, tenantId);
203           return null;
204                         }
205                         return new NetworkInfoMapper(network).map();
206                 }
207                 catch (OpenStackBaseException e) {
208                         // Convert Neutron exception to an MsoOpenstackException
209                         MsoException me = neutronExceptionToMsoException (e, "QueryNetwork");
210                         throw me;
211                 }
212                 catch (RuntimeException e) {
213                         // Catch-all
214                         MsoException me = runtimeExceptionToMsoException(e, "QueryNetwork");
215                         throw me;
216                 }
217         }
218     
219     public Optional<Port> getNeutronPort(String neutronPortId, String tenantId, String cloudSiteId)
220         {
221                 try {
222                           CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId).orElseThrow(
223                                 () -> new MsoCloudSiteNotFound(cloudSiteId));
224                                 Quantum neutronClient = getNeutronClient (cloudSite, tenantId);
225                         Port port = findPortById (neutronClient, neutronPortId);
226                         if (port == null) {                             
227                                 return Optional.empty();
228                         }
229                         return Optional.of(port);
230                 }
231                 catch (RuntimeException | MsoException e) {
232                         logger.error("Error retrieving neutron port", e);
233                         return Optional.empty();
234                 }
235         }
236
237         /**
238          * Delete the specified Network (by ID) in the given cloud.
239          * If the network does not exist, success is returned.
240          * <p>
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
248          */
249     public boolean deleteNetwork(String networkId, String tenantId, String cloudSiteId) throws MsoException
250         {
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);
255
256                 try {
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);
262           return false;
263                         }
264
265                         OpenStackRequest<Void> request = neutronClient.networks().delete(network.getId());
266                         executeAndRecordOpenstackRequest(request);
267
268         logger.debug("Deleted Network {} ({})", network.getId(), network.getName());
269     }
270                 catch (OpenStackBaseException e) {
271                         // Convert Neutron exception to an MsoOpenstackException
272                         MsoException me = neutronExceptionToMsoException (e, "Delete Network");
273                         throw me;
274                 }
275                 catch (RuntimeException e) {
276                         // Catch-all
277                         MsoException me = runtimeExceptionToMsoException(e, "DeleteNetwork");
278                         throw me;
279                 }
280
281                 return true;
282         }
283
284
285         /**
286          * Update a network with the specified parameters in the given cloud/tenant.
287          *
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.
291          * <p>
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).
295          *
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
306          */
307         public NetworkInfo updateNetwork (String cloudSiteId, String tenantId, String networkId, NetworkType type, String provider, List<Integer> vlans)
308             throws MsoException
309         {
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);
314
315                 // Check that the network exists
316                 Network network = findNetworkById (neutronClient, networkId);
317
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);
323                 }
324
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));
331                         }
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);
340
341                                         segments.add(segment);
342                                 }
343                                 network.setSegments(segments);
344                         }
345                 }
346
347                 try {
348                         OpenStackRequest<Network> request = neutronClient.networks().update(network);
349                         Network newNetwork = executeAndRecordOpenstackRequest(request);
350                         return new NetworkInfoMapper(newNetwork).map();
351                 }
352                 catch (OpenStackBaseException e) {
353                         // Convert Neutron exception to an MsoOpenstackException
354                         MsoException me = neutronExceptionToMsoException (e, "UpdateNetwork");
355                         throw me;
356                 }
357                 catch (RuntimeException e) {
358                         // Catch-all
359                         MsoException me = runtimeExceptionToMsoException(e, "UpdateNetwork");
360                         throw me;
361                 }
362         }
363
364
365         // -------------------------------------------------------------------
366         // PRIVATE UTILITY FUNCTIONS FOR USE WITHIN THIS CLASS
367
368         /**
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.
373          * <p>
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.
377          *
378          * @param cloudSite - a cloud site definition
379          * @param tenantId - Openstack tenant ID
380          * @return an authenticated Quantum object
381          */
382     private Quantum getNeutronClient(CloudSite cloudSite, String tenantId) throws MsoException
383         {
384                 String cloudId = cloudSite.getId();
385                 String region = cloudSite.getRegionId();        
386
387
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;
395                 try {
396                 if (ServerType.KEYSTONE.equals(cloudIdentity.getIdentityServerType())) {
397                                 Keystone keystoneTenantClient = new Keystone(keystoneUrl);
398                                 Access access = null;
399                                 
400                                 Authentication credentials = authenticationMethodFactory.getAuthenticationFor(cloudIdentity);
401                                 OpenStackRequest<Access> request = keystoneTenantClient.tokens().authenticate(credentials).withTenantId(tenantId);
402                                 access = executeAndRecordOpenstackRequest(request);
403                                 
404                                 
405                                 try {
406                                         neutronUrl = KeystoneUtils.findEndpointURL(access.getServiceCatalog(), "network", region, "public");
407                                         if (! neutronUrl.endsWith("/")) {
408                                 neutronUrl += "/v2.0/";
409                             }
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);
414                                 }
415                                 tokenId = access.getToken().getId();
416                                 expiration = access.getToken().getExpires();
417                 } else if (ServerType.KEYSTONE_V3.equals(cloudIdentity.getIdentityServerType())) {
418                         try {
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/";
425                             }
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);
430                         }
431                 }
432                 }
433                 catch (OpenStackResponseException e) {
434                         if (e.getStatus() == 401) {
435                                 // Authentication error.
436                                 String error = "Authentication Failure: tenant=" + tenantId + ",cloud=" + cloudIdentity.getId();
437
438                                 throw new MsoAdapterException(error);
439                         }
440                         else {
441                                 MsoException me = keystoneErrorToMsoException(e, "TokenAuth");
442                                 throw me;
443                         }
444                 }
445                 catch (OpenStackConnectException e) {
446                         // Connection to Openstack failed
447                         MsoIOException me = new MsoIOException (e.getMessage(), e);
448                         me.addContext("TokenAuth");
449                         throw me;
450                 }
451                 catch (RuntimeException e) {
452                         // Catch-all
453                         MsoException me = runtimeExceptionToMsoException(e, "TokenAuth");
454                         throw me;
455                 }
456
457                 Quantum neutronClient = new Quantum(neutronUrl);
458                 neutronClient.token(tokenId);
459                 return neutronClient;
460         }
461
462         /*
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.
465          *
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
469          */
470         public Network findNetworkByNameOrId (Quantum neutronClient, String networkNameOrId)
471         {
472                 if (networkNameOrId == null) {
473             return null;
474         }
475
476                 Network network = findNetworkById(neutronClient, networkNameOrId);
477
478                 if (network == null) {
479             network = findNetworkByName(neutronClient, networkNameOrId);
480         }
481
482                 return network;
483         }
484
485         /*
486          * Find a network (or query its existence) by its Id.
487          *
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
491          */
492         private Network findNetworkById (Quantum neutronClient, String networkId)
493         {
494                 if (networkId == null) {
495             return null;
496         }
497
498                 try {
499                         OpenStackRequest<Network> request = neutronClient.networks().show(networkId);
500                         Network network = executeAndRecordOpenstackRequest(request);
501                         return network;
502                 }
503                 catch (OpenStackResponseException e) {
504                         if (e.getStatus() == 404) {
505                                 return null;
506                         } else {
507           logger.error("{} {} Openstack Error, GET Network By ID ({}): ", MessageEnum.RA_CONNECTION_EXCEPTION,
508               ErrorCode.DataError.getValue(), networkId, e);
509           throw e;
510                         }
511                 }
512         }
513         
514         
515         private Port findPortById (Quantum neutronClient, String neutronPortId)
516         {
517                 if (neutronPortId == null) {
518             return null;
519         }
520
521                 try {
522                         OpenStackRequest<Port> request = neutronClient.ports().show(neutronPortId);
523                         Port port = executeAndRecordOpenstackRequest(request);
524                         return port;
525                 }
526                 catch (OpenStackResponseException e) {
527                         if (e.getStatus() == 404) {
528                                 return null;
529                         } else {
530                                 logger.error("{} {} Openstack Error, GET Neutron Port By ID ({}): ", MessageEnum.RA_CONNECTION_EXCEPTION,
531                                         ErrorCode.DataError.getValue(), neutronPortId, e);
532                                 throw e;
533                         }
534                 }
535         }
536
537         /*
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.
540          *
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.
545          *
546          * TODO:
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
549          * the first match).
550          *
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
554          */
555         public Network findNetworkByName (Quantum neutronClient, String networkName)
556         {
557                 if (networkName == null) {
558             return null;
559         }
560
561                 try {
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);
567             return network;
568                                 }
569                         }
570         logger.debug("findNetworkByName - no match found for {}", networkName);
571         return null;
572                 }
573                 catch (OpenStackResponseException e) {
574                         if (e.getStatus() == 404) {
575                                 return null;
576                         } else {
577           logger.error("{} {} Openstack Error, GET Network By Name ({}): ", MessageEnum.RA_CONNECTION_EXCEPTION,
578               ErrorCode.DataError.getValue(), networkName, e);
579           throw e;
580                         }
581                 }
582         }
583 }