Removed MsoLogger class
[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 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;
64
65 @Component
66 public class MsoNeutronUtils extends MsoCommonUtils
67 {
68
69         // Fetch cloud configuration each time (may be cached in CloudConfig class)
70         @Autowired
71         private CloudConfig cloudConfig;
72
73         @Autowired
74     private AuthenticationMethodFactory authenticationMethodFactory;
75         
76         @Autowired
77         private MsoTenantUtilsFactory tenantUtilsFactory;
78
79         @Autowired
80         private KeystoneV3Authentication keystoneV3Authentication;
81
82     private static Logger logger = LoggerFactory.getLogger(MsoNeutronUtils.class);
83
84     public enum NetworkType {
85                 BASIC, PROVIDER, MULTI_PROVIDER
86         };
87
88         /**
89          * Create a network with the specified parameters in the given cloud/tenant.
90          *
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.
93          * <p>
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
104          */
105         public NetworkInfo createNetwork (String cloudSiteId, String tenantId, NetworkType type, String networkName, String provider, List<Integer> vlans)
106             throws MsoException
107         {
108                 // Obtain the cloud site information where we will create the stack
109         CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId).orElseThrow(
110                 () -> new MsoCloudSiteNotFound(cloudSiteId));
111
112                 Quantum neutronClient = getNeutronClient (cloudSite, tenantId);
113
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);
117
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);
124                 }
125
126                 // Does not exist, create a new one
127                 network = new Network();
128                 network.setName(networkName);
129                 network.setAdminStateUp(true);
130
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));
136                         }
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);
145
146                                         segments.add(segment);
147                                 }
148                                 network.setSegments(segments);
149                         }
150                 }
151
152                 try {
153                         OpenStackRequest<Network> request = neutronClient.networks().create(network);
154                         Network newNetwork = executeAndRecordOpenstackRequest(request);
155                         return new NetworkInfoMapper(newNetwork).map();
156                 }
157                 catch (OpenStackBaseException e) {
158                         // Convert Neutron exception to an MsoOpenstackException
159                         MsoException me = neutronExceptionToMsoException (e, "CreateNetwork");
160                         throw me;
161                 }
162                 catch (RuntimeException e) {
163                         // Catch-all
164                         MsoException me = runtimeExceptionToMsoException(e, "CreateNetwork");
165                         throw me;
166                 }
167         }
168
169
170         /**
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.
173          * <p>
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.
176          * <p>
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
183          */
184     public NetworkInfo queryNetwork(String networkNameOrId, String tenantId, String cloudSiteId) throws MsoException
185         {
186       logger.debug("In queryNetwork");
187
188                 // Obtain the cloud site information
189         CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId).orElseThrow(
190                 () -> new MsoCloudSiteNotFound(cloudSiteId));
191
192                 Quantum neutronClient = getNeutronClient (cloudSite, tenantId);
193
194                 // Check if the network exists and return its info
195                 try {
196                         Network network = findNetworkByNameOrId (neutronClient, networkNameOrId);
197                         if (network == null) {
198           logger.debug("Query Network: {} not found in tenant {}", networkNameOrId, tenantId);
199           return null;
200                         }
201                         return new NetworkInfoMapper(network).map();
202                 }
203                 catch (OpenStackBaseException e) {
204                         // Convert Neutron exception to an MsoOpenstackException
205                         MsoException me = neutronExceptionToMsoException (e, "QueryNetwork");
206                         throw me;
207                 }
208                 catch (RuntimeException e) {
209                         // Catch-all
210                         MsoException me = runtimeExceptionToMsoException(e, "QueryNetwork");
211                         throw me;
212                 }
213         }
214
215         /**
216          * Delete the specified Network (by ID) in the given cloud.
217          * If the network does not exist, success is returned.
218          * <p>
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
226          */
227     public boolean deleteNetwork(String networkId, String tenantId, String cloudSiteId) throws MsoException
228         {
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);
233
234                 try {
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);
240           return false;
241                         }
242
243                         OpenStackRequest<Void> request = neutronClient.networks().delete(network.getId());
244                         executeAndRecordOpenstackRequest(request);
245
246         logger.debug("Deleted Network {} ({})", network.getId(), network.getName());
247     }
248                 catch (OpenStackBaseException e) {
249                         // Convert Neutron exception to an MsoOpenstackException
250                         MsoException me = neutronExceptionToMsoException (e, "Delete Network");
251                         throw me;
252                 }
253                 catch (RuntimeException e) {
254                         // Catch-all
255                         MsoException me = runtimeExceptionToMsoException(e, "DeleteNetwork");
256                         throw me;
257                 }
258
259                 return true;
260         }
261
262
263         /**
264          * Update a network with the specified parameters in the given cloud/tenant.
265          *
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.
269          * <p>
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).
273          *
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
284          */
285         public NetworkInfo updateNetwork (String cloudSiteId, String tenantId, String networkId, NetworkType type, String provider, List<Integer> vlans)
286             throws MsoException
287         {
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);
292
293                 // Check that the network exists
294                 Network network = findNetworkById (neutronClient, networkId);
295
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);
301                 }
302
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));
309                         }
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);
318
319                                         segments.add(segment);
320                                 }
321                                 network.setSegments(segments);
322                         }
323                 }
324
325                 try {
326                         OpenStackRequest<Network> request = neutronClient.networks().update(network);
327                         Network newNetwork = executeAndRecordOpenstackRequest(request);
328                         return new NetworkInfoMapper(newNetwork).map();
329                 }
330                 catch (OpenStackBaseException e) {
331                         // Convert Neutron exception to an MsoOpenstackException
332                         MsoException me = neutronExceptionToMsoException (e, "UpdateNetwork");
333                         throw me;
334                 }
335                 catch (RuntimeException e) {
336                         // Catch-all
337                         MsoException me = runtimeExceptionToMsoException(e, "UpdateNetwork");
338                         throw me;
339                 }
340         }
341
342
343         // -------------------------------------------------------------------
344         // PRIVATE UTILITY FUNCTIONS FOR USE WITHIN THIS CLASS
345
346         /**
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.
351          * <p>
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.
355          *
356          * @param cloudSite - a cloud site definition
357          * @param tenantId - Openstack tenant ID
358          * @return an authenticated Quantum object
359          */
360     private Quantum getNeutronClient(CloudSite cloudSite, String tenantId) throws MsoException
361         {
362                 String cloudId = cloudSite.getId();
363                 String region = cloudSite.getRegionId();        
364
365
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;
373                 try {
374                 if (ServerType.KEYSTONE.equals(cloudIdentity.getIdentityServerType())) {
375                                 Keystone keystoneTenantClient = new Keystone(keystoneUrl);
376                                 Access access = null;
377                                 
378                                 Authentication credentials = authenticationMethodFactory.getAuthenticationFor(cloudIdentity);
379                                 OpenStackRequest<Access> request = keystoneTenantClient.tokens().authenticate(credentials).withTenantId(tenantId);
380                                 access = executeAndRecordOpenstackRequest(request);
381                                 
382                                 
383                                 try {
384                                         neutronUrl = KeystoneUtils.findEndpointURL(access.getServiceCatalog(), "network", region, "public");
385                                         if (! neutronUrl.endsWith("/")) {
386                                 neutronUrl += "/v2.0/";
387                             }
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);
392                                 }
393                                 tokenId = access.getToken().getId();
394                                 expiration = access.getToken().getExpires();
395                 } else if (ServerType.KEYSTONE_V3.equals(cloudIdentity.getIdentityServerType())) {
396                         try {
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/";
403                             }
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);
408                         }
409                 }
410                 }
411                 catch (OpenStackResponseException e) {
412                         if (e.getStatus() == 401) {
413                                 // Authentication error.
414                                 String error = "Authentication Failure: tenant=" + tenantId + ",cloud=" + cloudIdentity.getId();
415
416                                 throw new MsoAdapterException(error);
417                         }
418                         else {
419                                 MsoException me = keystoneErrorToMsoException(e, "TokenAuth");
420                                 throw me;
421                         }
422                 }
423                 catch (OpenStackConnectException e) {
424                         // Connection to Openstack failed
425                         MsoIOException me = new MsoIOException (e.getMessage(), e);
426                         me.addContext("TokenAuth");
427                         throw me;
428                 }
429                 catch (RuntimeException e) {
430                         // Catch-all
431                         MsoException me = runtimeExceptionToMsoException(e, "TokenAuth");
432                         throw me;
433                 }
434
435                 Quantum neutronClient = new Quantum(neutronUrl);
436                 neutronClient.token(tokenId);
437                 return neutronClient;
438         }
439
440         /*
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.
443          *
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
447          */
448         public Network findNetworkByNameOrId (Quantum neutronClient, String networkNameOrId)
449         {
450                 if (networkNameOrId == null) {
451             return null;
452         }
453
454                 Network network = findNetworkById(neutronClient, networkNameOrId);
455
456                 if (network == null) {
457             network = findNetworkByName(neutronClient, networkNameOrId);
458         }
459
460                 return network;
461         }
462
463         /*
464          * Find a network (or query its existence) by its Id.
465          *
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
469          */
470         private Network findNetworkById (Quantum neutronClient, String networkId)
471         {
472                 if (networkId == null) {
473             return null;
474         }
475
476                 try {
477                         OpenStackRequest<Network> request = neutronClient.networks().show(networkId);
478                         Network network = executeAndRecordOpenstackRequest(request);
479                         return network;
480                 }
481                 catch (OpenStackResponseException e) {
482                         if (e.getStatus() == 404) {
483                                 return null;
484                         } else {
485           logger.error("{} {} Openstack Error, GET Network By ID ({}): ", MessageEnum.RA_CONNECTION_EXCEPTION,
486               ErrorCode.DataError.getValue(), networkId, e);
487           throw e;
488                         }
489                 }
490         }
491
492         /*
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.
495          *
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.
500          *
501          * TODO:
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
504          * the first match).
505          *
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
509          */
510         public Network findNetworkByName (Quantum neutronClient, String networkName)
511         {
512                 if (networkName == null) {
513             return null;
514         }
515
516                 try {
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);
522             return network;
523                                 }
524                         }
525         logger.debug("findNetworkByName - no match found for {}", networkName);
526         return null;
527                 }
528                 catch (OpenStackResponseException e) {
529                         if (e.getStatus() == 404) {
530                                 return null;
531                         } else {
532           logger.error("{} {} Openstack Error, GET Network By Name ({}): ", MessageEnum.RA_CONNECTION_EXCEPTION,
533               ErrorCode.DataError.getValue(), networkName, e);
534           throw e;
535                         }
536                 }
537         }
538 }