sonarFixes. reduce code smell
[appc.git] / appc-adapters / appc-iaas-adapter / appc-iaas-adapter-bundle / src / main / java / org / onap / appc / adapter / iaas / provider / operation / impl / DettachVolumeServer.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP : APPC
4  * ================================================================================
5  * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Copyright (C) 2017 Amdocs
8  * ================================================================================
9  * Modifications Copyright (C) 2019 Ericsson
10  * =============================================================================
11  * Licensed under the Apache License, Version 2.0 (the "License");
12  * you may not use this file except in compliance with the License.
13  * You may obtain a copy of the License at
14  *
15  * http://www.apache.org/licenses/LICENSE-2.0
16  *
17  * Unless required by applicable law or agreed to in writing, software
18  * distributed under the License is distributed on an "AS IS" BASIS,
19  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20  * See the License for the specific language governing permissions and
21  * limitations under the License.
22  *
23  * ============LICENSE_END=========================================================
24  */
25 package org.onap.appc.adapter.iaas.provider.operation.impl;
26
27 import static org.onap.appc.adapter.iaas.provider.operation.common.enums.Operation.DETACHVOLUME_SERVICE;
28 import static org.onap.appc.adapter.utils.Constants.ADAPTER_NAME;
29 import com.att.cdp.exceptions.ZoneException;
30 import com.att.cdp.zones.ComputeService;
31 import com.att.cdp.zones.Context;
32 import com.att.cdp.zones.model.ModelObject;
33 import com.att.cdp.zones.model.Server;
34 import com.att.cdp.zones.model.Volume;
35 import com.att.eelf.configuration.EELFLogger;
36 import com.att.eelf.configuration.EELFManager;
37 import com.att.eelf.i18n.EELFResourceManager;
38 import java.util.Map;
39 import java.util.Map.Entry;
40 import java.util.Iterator;
41 import org.glassfish.grizzly.http.util.HttpStatus;
42 import org.onap.appc.Constants;
43 import org.onap.appc.adapter.iaas.ProviderAdapter;
44 import org.onap.appc.adapter.iaas.impl.IdentityURL;
45 import org.onap.appc.adapter.iaas.impl.RequestContext;
46 import org.onap.appc.adapter.iaas.impl.RequestFailedException;
47 import org.onap.appc.configuration.Configuration;
48 import org.onap.appc.configuration.ConfigurationFactory;
49 import org.onap.appc.adapter.iaas.impl.VMURL;
50 import org.onap.appc.adapter.iaas.provider.operation.common.enums.Operation;
51 import org.onap.appc.adapter.iaas.provider.operation.impl.base.ProviderServerOperation;
52 import org.onap.appc.exceptions.APPCException;
53 import com.att.cdp.exceptions.TimeoutException;
54 import com.att.cdp.openstack.util.ExceptionMapper;
55 import org.onap.appc.i18n.Msg;
56 import com.woorea.openstack.base.client.OpenStackBaseException;
57 import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
58 import org.onap.appc.adapter.iaas.provider.operation.common.constants.Property;
59
60 public class DettachVolumeServer extends ProviderServerOperation {
61     private final EELFLogger logger = EELFManager.getInstance().getLogger(DettachVolumeServer.class);
62     private static final Configuration config = ConfigurationFactory.getConfiguration();
63
64     @Override
65     protected ModelObject executeProviderOperation(Map<String, String> params, SvcLogicContext context)
66             throws APPCException {
67         setMDC(Operation.DETACHVOLUME_SERVICE.toString(), "App-C IaaS Adapter:dettachVolume", ADAPTER_NAME);
68         logOperation(Msg.DETTACHINGVOLUME_SERVER, params, context);
69         return dettachVolume(params, context);
70     }
71
72     private Server dettachVolume(Map<String, String> params, SvcLogicContext ctx) {
73         Server server = null;
74         RequestContext requestContext = new RequestContext(ctx);
75         requestContext.isAlive();
76         String appName = configuration.getProperty(Constants.PROPERTY_APPLICATION_NAME);
77         String vmUrl = params.get(ProviderAdapter.PROPERTY_INSTANCE_URL);
78         String volumeId = params.get(ProviderAdapter.VOLUME_ID);
79         VMURL vm = VMURL.parseURL(vmUrl);
80         Context context;
81         String tenantName = "Unknown";// to be used also in case of exception
82         try {
83             if (validateVM(requestContext, appName, vmUrl, vm)) {
84                 return null;
85             }
86             IdentityURL ident = IdentityURL.parseURL(params.get(ProviderAdapter.PROPERTY_IDENTITY_URL));
87             String identStr = (ident == null) ? null : ident.toString();
88             context = getContext(requestContext, vmUrl, identStr);
89             String skipHypervisorCheck = configuration.getProperty(Property.SKIP_HYPERVISOR_CHECK);
90             if (skipHypervisorCheck == null && ctx != null) {
91                 skipHypervisorCheck = ctx.getAttribute(ProviderAdapter.SKIP_HYPERVISOR_CHECK);
92             }
93             if (context != null) {
94                 tenantName = context.getTenantName();// this variable also is
95                                                         // used in case of
96                                                         // exception
97                 requestContext.reset();
98                 server = lookupServer(requestContext, context, vm.getServerId());
99                 // Always perform Hypervisor check
100                 // unless the skip is set to true
101                 if (!"true".equalsIgnoreCase(skipHypervisorCheck)) {
102                     // Check of the Hypervisor for the VM Server is UP and reachable
103                     checkHypervisor(server);
104                 }
105                 logger.debug(Msg.SERVER_FOUND, vmUrl, context.getTenantName(), server.getStatus().toString());
106                 if (volumeId == null || volumeId.isEmpty()) {
107                     if(ctx != null){
108                         ctx.setAttribute("VOLUME_STATUS", "FAILURE");
109                     }
110                     doFailure(requestContext, HttpStatus.BAD_REQUEST_400, "Volumeid is mandatory");
111                 }
112                 Context contx = server.getContext();
113                 ComputeService service = contx.getComputeService();
114                 Volume volume = new Volume();
115                 boolean flag = false;
116                 if (validateDetach(service, vm.getServerId(), volumeId)) {
117                     volume.setId(volumeId);
118                     logger.info("Ready to Detach Volume from the server:");
119                     service.detachVolume(server, volume);
120                     flag = true;
121                 } else {
122                     String msg = "Volume with volume id " + volumeId + " cannot be detached as it does not exists";
123                     logger.info("Volume doesnot exists:");
124                     if(ctx != null){
125                         ctx.setAttribute("VOLUME_STATUS", "FAILURE");
126                     }
127                     doFailure(requestContext, HttpStatus.METHOD_NOT_ALLOWED_405, msg);
128                     flag = false;
129                 }
130                 if (flag) {
131                     if (validateDetach(requestContext, service, vm.getServerId(), volumeId)) {
132                         String msg = "Volume with volume id " + volumeId + " cannot be detached ";
133                         if(ctx != null){
134                             ctx.setAttribute("VOLUME_STATUS", "FAILURE");
135                         }
136                         doFailure(requestContext, HttpStatus.CONFLICT_409, msg);
137                     } else {
138                         logger.info("status of detaching volume");
139                         if(ctx != null){
140                            ctx.setAttribute("VOLUME_STATUS", "SUCCESS");
141                         }
142                         doSuccess(requestContext);
143                     }
144                 }
145                 context.close();
146             } else {
147                 if(ctx != null){
148                     ctx.setAttribute("VOLUME_STATUS", "CONTEXT_NOT_FOUND");
149                 }
150             }
151         } catch (ZoneException e) {
152             String msg = EELFResourceManager.format(Msg.SERVER_NOT_FOUND, e, vmUrl);
153             logger.error(msg);
154             doFailure(requestContext, HttpStatus.NOT_FOUND_404, msg);
155         } catch (RequestFailedException e) {
156             logger.error("An error occurred when processing the request", e);
157             doFailure(requestContext, e.getStatus(), e.getMessage());
158         } catch (Exception e) {
159             String msg = EELFResourceManager.format(Msg.DETTACHINGVOLUME_SERVER, e, e.getClass().getSimpleName(),
160                     DETACHVOLUME_SERVICE.toString(), vmUrl, tenantName);
161             logger.error(msg, e);
162             try {
163                 ExceptionMapper.mapException((OpenStackBaseException) e);
164             } catch (ZoneException e1) {
165                 logger.error(e1.getMessage());
166             }
167
168             doFailure(requestContext, HttpStatus.INTERNAL_SERVER_ERROR_500, msg);
169         }
170         return server;
171     }
172
173     protected boolean validateDetach(ComputeService ser, String vm, String volumeId)
174             throws RequestFailedException, ZoneException {
175         boolean flag = false;
176         Map<String, String> map = ser.getAttachments(vm);
177         if (map != null && !(map.isEmpty())) {
178             Iterator<Entry<String, String>> it = map.entrySet().iterator();
179             while (it.hasNext()) {
180                 Map.Entry<String, String> volumes = it.next();
181                 logger.info("volumes available in before detach");
182                 logger.info("device" + volumes.getKey() + "volume" + volumes.getValue());
183                 if (volumes.getValue().equals(volumeId)) {
184                     flag = true;
185                 }
186             }
187         }
188         logger.info("DettachVolume  Flag" + flag);
189         return flag;
190     }
191
192     protected boolean validateDetach(RequestContext rc, ComputeService ser, String vm, String volumeId)
193             throws ZoneException {
194         boolean flag = false;
195         String msg = null;
196         config.setProperty(Constants.PROPERTY_RETRY_DELAY, "10");
197         config.setProperty(Constants.PROPERTY_RETRY_LIMIT, "30");
198         while (rc.attempt()) {
199             Map<String, String> map = ser.getAttachments(vm);
200             if (map != null && !(map.isEmpty())) {
201                 Iterator<Entry<String, String>> it = map.entrySet().iterator();
202                 logger.info("volumes available after  detach ");
203                 while (it.hasNext()) {
204                     Map.Entry<String, String> volumes = it.next();
205                     logger.info(" devices " + volumes.getKey() + " volumes" + volumes.getValue());
206                     if (volumes.getValue().equals(volumeId)) {
207                         logger.info("Device" + volumes.getKey() + "Volume" + volumes.getValue());
208                         flag = true;
209                         break;
210                     } else {
211                         flag = false;
212                     }
213                     logger.info("Dettachvolume flag-->" + flag + "Attempts" + rc.getAttempts());
214                 }
215                 if (flag) {
216                     rc.delay();
217                 } else {
218                     break;
219                 }
220             } else {
221                 flag = false;
222                 logger.info(rc.getAttempts() + "No.of attempts");
223                 break;
224             }
225         }
226         if ((rc.getAttempts() == 30) && (!flag)) {
227             msg = EELFResourceManager.format(Msg.CONNECTION_FAILED_RETRY, Long.toString(rc.getRetryDelay()),
228                     Integer.toString(rc.getAttempts()), Integer.toString(rc.getRetryLimit()));
229             logger.error(msg);
230             logger.info(msg);
231             throw new TimeoutException(msg);
232         }
233         logger.info("DettachVolume Flag -->" + flag);
234         return flag;
235     }
236
237 }