Merge "fixed sonar issue in MsoTenantAdapter.java"
[so.git] / adapters / mso-openstack-adapters / src / main / java / org / onap / so / adapters / tenant / MsoTenantAdapterImpl.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) 2018 IBM.
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.adapters.tenant;
24
25
26 import java.util.Map;
27
28 import javax.annotation.Resource;
29 import javax.jws.WebService;
30 import javax.xml.ws.Holder;
31 import javax.xml.ws.WebServiceContext;
32
33 import org.onap.so.adapters.tenant.exceptions.TenantAlreadyExists;
34 import org.onap.so.adapters.tenant.exceptions.TenantException;
35 import org.onap.so.adapters.tenantrest.TenantRollback;
36 import org.onap.so.entity.MsoRequest;
37 import org.onap.so.logger.MessageEnum;
38 import org.onap.so.logger.MsoLogger;
39 import org.onap.so.openstack.beans.MsoTenant;
40 import org.onap.so.openstack.exceptions.MsoCloudSiteNotFound;
41 import org.onap.so.openstack.exceptions.MsoException;
42 import org.onap.so.openstack.utils.MsoTenantUtils;
43 import org.onap.so.openstack.utils.MsoTenantUtilsFactory;
44 import org.springframework.beans.factory.annotation.Autowired;
45 import org.springframework.stereotype.Component;
46
47 @WebService(serviceName = "TenantAdapter", endpointInterface = "org.onap.so.adapters.tenant.MsoTenantAdapter", targetNamespace = "http://org.onap.so/tenant")
48 @Component
49 public class MsoTenantAdapterImpl implements MsoTenantAdapter {
50         public static final String CREATE_TENANT = "createTenant";
51     public static final String OPENSTACK = "OpenStack";
52     public static final String QUERY_TENANT = "QueryTenant";
53     public static final String DELETE_TENANT = "DeleteTenant";
54     public static final String ROLLBACK_TENANT = "RollbackTenant";
55         private static final String SUCCESS_RESPONSE_OPENSTACK="Successfully received response from Open Stack";
56         private static final String OPENSTACK_COMMUNICATE_EXCEPTION_MSG="Exception while communicate with Open Stack";
57     @Resource
58     private WebServiceContext wsContext;
59
60     @Autowired
61         private MsoTenantUtilsFactory tFactory;
62     private static MsoLogger logger = MsoLogger.getMsoLogger (MsoLogger.Catalog.RA,MsoTenantAdapterImpl.class);
63     /**
64      * Health Check web method. Does nothing but return to show the adapter is deployed.
65      */
66     @Override
67     public void healthCheck () {
68         logger.debug ("Health check call in Tenant Adapter");
69     }
70
71     /**
72      * This is the "Create Tenant" web service implementation. It will create
73      * a new Tenant in the specified cloud. If the tenant already exists, this
74      * can be considered a success or failure, depending on the value of the
75      * 'failIfExists' parameter.
76      *
77      * The method returns the tenantId (the Openstack ID), and a TenantRollback
78      * object. This last object can be passed as-is to the rollbackTenant method
79      * to undo what (if anything) was created. This is useful if a Tenant is
80      * successfully created but the orchestrator fails on a subsequent operation.
81      */
82     @Override
83     public void createTenant (String cloudSiteId,
84                               String tenantName,
85                               Map <String, String> metadata,
86                               Boolean failIfExists,
87                               Boolean backout,
88                               MsoRequest msoRequest,
89                               Holder <String> tenantId,
90                               Holder <TenantRollback> rollback) throws TenantException {
91         MsoLogger.setLogContext (msoRequest);
92         MsoLogger.setServiceName (CREATE_TENANT);
93
94         logger.debug ("Call to MSO createTenant adapter. Creating Tenant: " + tenantName
95                                       + "in "
96                                       + cloudSiteId);
97
98         // Will capture total time for metrics
99         long startTime = System.currentTimeMillis ();
100
101         // Start building up rollback object
102         TenantRollback tenantRollback = new TenantRollback ();
103         tenantRollback.setCloudId (cloudSiteId);
104         tenantRollback.setMsoRequest (msoRequest);
105         
106         MsoTenantUtils tUtils;
107                 try {
108                         tUtils = tFactory.getTenantUtils (cloudSiteId);
109                 } catch (MsoCloudSiteNotFound me) {
110             logger.error (MessageEnum.RA_CREATE_TENANT_ERR, me.getMessage(), OPENSTACK, CREATE_TENANT, MsoLogger.ErrorCode.DataError, "no implementation found for " + cloudSiteId, me);
111             throw new TenantException (me);
112                 }
113
114         MsoTenant newTenant = null;
115         String newTenantId;
116         long queryTenantStartTime = System.currentTimeMillis ();
117         try {
118             newTenant = tUtils.queryTenantByName (tenantName, cloudSiteId);
119             logger.recordMetricEvent (queryTenantStartTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, SUCCESS_RESPONSE_OPENSTACK, OPENSTACK, QUERY_TENANT, null);
120         } catch (MsoException me) {
121             logger.recordMetricEvent (queryTenantStartTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.CommunicationError, OPENSTACK_COMMUNICATE_EXCEPTION_MSG, OPENSTACK, QUERY_TENANT, null);
122             String error = "Create Tenant " + tenantName + ": " + me;
123             logger.error (MessageEnum.RA_CREATE_TENANT_ERR, me.getMessage(), OPENSTACK, CREATE_TENANT, MsoLogger.ErrorCode.DataError, OPENSTACK_COMMUNICATE_EXCEPTION_MSG, me);
124             logger.recordAuditEvent (startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.CommunicationError, error);
125             throw new TenantException (me);
126         }
127         if (newTenant == null) {
128             if (backout == null)
129                 backout = true;
130             long createTenantStartTime = System.currentTimeMillis ();
131             try {
132                 newTenantId = tUtils.createTenant (tenantName, cloudSiteId, metadata, backout.booleanValue ());
133                 logger.recordMetricEvent (createTenantStartTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, SUCCESS_RESPONSE_OPENSTACK, OPENSTACK, CREATE_TENANT, null);
134             } catch (MsoException me) {
135                 logger.recordMetricEvent (createTenantStartTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.CommunicationError, OPENSTACK_COMMUNICATE_EXCEPTION_MSG, OPENSTACK, CREATE_TENANT, null);
136                 String error = "Create Tenant " + tenantName + ": " + me;
137                 logger.error (MessageEnum.RA_CREATE_TENANT_ERR, me.getMessage(), OPENSTACK, CREATE_TENANT, MsoLogger.ErrorCode.DataError, OPENSTACK_COMMUNICATE_EXCEPTION_MSG, me);
138                 logger.recordAuditEvent (startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.CommunicationError, error);
139                 throw new TenantException (me);
140             }
141             tenantRollback.setTenantId (newTenantId);
142             tenantRollback.setTenantCreated (true);
143             logger.debug ("Tenant " + tenantName + " successfully created with ID " + newTenantId);
144         } else {
145             if (failIfExists != null && failIfExists) {
146                 String error = CREATE_TENANT + ": Tenant " + tenantName + " already exists in " + cloudSiteId;
147                 logger.error (MessageEnum.RA_TENANT_ALREADY_EXIST, tenantName, cloudSiteId, OPENSTACK, "", MsoLogger.ErrorCode.DataError, CREATE_TENANT + ", Tenant already exists");
148                 logger.recordAuditEvent (startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.DataError, error);
149                 throw new TenantAlreadyExists (tenantName, cloudSiteId, newTenant.getTenantId ());
150             }
151
152             newTenantId = newTenant.getTenantId ();
153             tenantRollback.setTenantCreated (false);
154             logger.debug ("Tenant " + tenantName + " already exists with ID " + newTenantId);
155         }
156
157
158         tenantId.value = newTenantId;
159         rollback.value = tenantRollback;
160         logger.recordAuditEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully create tenant");
161         return;
162     }
163
164     @Override
165     public void queryTenant (String cloudSiteId,
166                              String tenantNameOrId,
167                              MsoRequest msoRequest,
168                              Holder <String> tenantId,
169                              Holder <String> tenantName,
170                              Holder <Map <String, String>> metadata) throws TenantException {
171         MsoLogger.setLogContext (msoRequest);
172         MsoLogger.setServiceName (QUERY_TENANT);
173         logger.debug ("Querying Tenant " + tenantNameOrId + " in " + cloudSiteId);
174
175         // Will capture execution time for metrics
176         long startTime = System.currentTimeMillis ();
177
178         MsoTenantUtils tUtils;
179                 try {
180                         tUtils = tFactory.getTenantUtils (cloudSiteId);
181                 } catch (MsoCloudSiteNotFound me) {
182             logger.error (MessageEnum.RA_CREATE_TENANT_ERR, me.getMessage(), OPENSTACK, CREATE_TENANT, MsoLogger.ErrorCode.DataError, "no implementation found for " + cloudSiteId, me);
183             throw new TenantException (me);
184                 }
185         
186         MsoTenant qTenant = null;
187         long subStartTime = System.currentTimeMillis ();
188         try {
189             qTenant = tUtils.queryTenant (tenantNameOrId, cloudSiteId);
190             logger.recordMetricEvent (subStartTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, SUCCESS_RESPONSE_OPENSTACK, OPENSTACK, QUERY_TENANT, null);
191             if (qTenant == null) {
192                 // Not found by ID, Try by name.
193                 qTenant = tUtils.queryTenantByName (tenantNameOrId, cloudSiteId);
194             }
195
196             if (qTenant == null) {
197                 logger.debug ("QueryTenant: Tenant " + tenantNameOrId + " not found");
198                 tenantId.value = null;
199                 tenantName.value = null;
200                 metadata.value = null;
201             } else {
202                 logger.debug ("QueryTenant: Tenant " + tenantNameOrId + " found with ID " + qTenant.getTenantId ());
203                 tenantId.value = qTenant.getTenantId ();
204                 tenantName.value = qTenant.getTenantName ();
205                 metadata.value = qTenant.getMetadata ();
206             }
207         } catch (MsoException me) {
208             String error = "Query Tenant " + tenantNameOrId + ": " + me;
209             logger.recordMetricEvent (subStartTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.CommunicationError, error, OPENSTACK, QUERY_TENANT, null);
210             logger.error (MessageEnum.RA_GENERAL_EXCEPTION, me.getMessage(), OPENSTACK, "", MsoLogger.ErrorCode.DataError, "Exception in queryTenant", me);
211             logger.recordAuditEvent (startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.CommunicationError, error);
212             throw new TenantException (me);
213         }
214         logger.recordAuditEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully query tenant");
215         return;
216     }
217
218     @Override
219     public void deleteTenant (String cloudSiteId,
220                               String tenantId,
221                               MsoRequest msoRequest,
222                               Holder <Boolean> tenantDeleted) throws TenantException {
223         MsoLogger.setLogContext (msoRequest);
224         MsoLogger.setServiceName (DELETE_TENANT);
225
226         logger.debug ("Deleting Tenant " + tenantId + " in " + cloudSiteId);
227
228         // Will capture execution time for metrics
229         long startTime = System.currentTimeMillis ();
230
231         // Delete the Tenant.
232         long subStartTime = System.currentTimeMillis ();
233         try {
234                 
235                 MsoTenantUtils tUtils = tFactory.getTenantUtils (cloudSiteId);
236             boolean deleted = tUtils.deleteTenant (tenantId, cloudSiteId);
237             tenantDeleted.value = deleted;
238             logger.recordMetricEvent (subStartTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully communicate with Open Stack", OPENSTACK, DELETE_TENANT, null);
239         } catch (MsoException me) {
240             String error = "Delete Tenant " + tenantId + ": " + me;
241             logger.recordMetricEvent (subStartTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.CommunicationError, error, OPENSTACK, DELETE_TENANT, null);
242             logger.error (MessageEnum.RA_DELETE_TEMAMT_ERR, me.getMessage(), OPENSTACK, "", MsoLogger.ErrorCode.DataError, "Exception - DeleteTenant", me);
243             logger.recordAuditEvent (startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.CommunicationError, error);
244             throw new TenantException (me);
245         }
246
247         // On success, nothing is returned.
248         logger.recordAuditEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully delete tenant");
249         return;
250     }
251
252     /**
253      * This web service endpoint will rollback a previous Create VNF operation.
254      * A rollback object is returned to the client in a successful creation
255      * response. The client can pass that object as-is back to the rollbackVnf
256      * operation to undo the creation.
257      *
258      * The rollback includes removing the VNF and deleting the tenant if the
259      * tenant did not exist prior to the VNF creation.
260      */
261     @Override
262     public void rollbackTenant (TenantRollback rollback) throws TenantException {
263         long startTime = System.currentTimeMillis ();
264         MsoLogger.setServiceName (ROLLBACK_TENANT);
265         // rollback may be null (e.g. if stack already existed when Create was called)
266         if (rollback == null) {
267             logger.warn (MessageEnum.RA_ROLLBACK_NULL, OPENSTACK, "rollbackTenant", MsoLogger.ErrorCode.DataError, "rollbackTenant, rollback is null");
268             return;
269         }
270
271         // Get the elements of the VnfRollback object for easier access
272         String cloudSiteId = rollback.getCloudId ();
273         String tenantId = rollback.getTenantId ();
274
275         MsoLogger.setLogContext (rollback.getMsoRequest ());
276         logger.debug ("Rolling Back Tenant " + rollback.getTenantId () + " in " + cloudSiteId);
277
278         long subStartTime = System.currentTimeMillis ();
279         if (rollback.getTenantCreated ()) {
280             try {
281                  
282                 MsoTenantUtils tUtils = tFactory.getTenantUtils (cloudSiteId);
283                 tUtils.deleteTenant (tenantId, cloudSiteId);
284                 logger.recordMetricEvent (subStartTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully communicate with Open Stack", OPENSTACK, ROLLBACK_TENANT, null);
285             } catch (MsoException me) {
286                 me.addContext (ROLLBACK_TENANT);
287                 // Failed to delete the tenant.
288                 String error = "Rollback Tenant " + tenantId + ": " + me;
289                 logger.recordMetricEvent (subStartTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.CommunicationError, error, OPENSTACK, ROLLBACK_TENANT, null);
290                 logger.error (MessageEnum.RA_ROLLBACK_TENANT_ERR, me.getMessage(), OPENSTACK, "rollbackTenant", MsoLogger.ErrorCode.DataError, "Exception - rollbackTenant", me);
291                 logger.recordAuditEvent (startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.CommunicationError, error);
292                 throw new TenantException (me);
293             }
294         }
295         logger.recordAuditEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully roll back tenant");
296         return;
297     }
298 }