bugfix for error handling while detaching volumes
[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  * 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  *
21  * ECOMP is a trademark and service mark of AT&T Intellectual Property.
22  * ============LICENSE_END=========================================================
23  */
24 package org.onap.appc.adapter.iaas.provider.operation.impl;
25
26 import static org.onap.appc.adapter.iaas.provider.operation.common.enums.Operation.DETACHVOLUME_SERVICE;
27 import static org.onap.appc.adapter.utils.Constants.ADAPTER_NAME;
28 import com.att.cdp.exceptions.ZoneException;
29 import com.att.cdp.zones.ComputeService;
30 import com.att.cdp.zones.Context;
31 import com.att.cdp.zones.VolumeService;
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.List;
39 import java.util.Map;
40 import java.util.Map.Entry;
41 import java.util.Iterator;
42 import org.glassfish.grizzly.http.util.HttpStatus;
43 import org.onap.appc.Constants;
44 import org.onap.appc.adapter.iaas.ProviderAdapter;
45 import org.onap.appc.adapter.iaas.impl.IdentityURL;
46 import org.onap.appc.adapter.iaas.impl.RequestContext;
47 import org.onap.appc.adapter.iaas.impl.RequestFailedException;
48 import org.onap.appc.configuration.Configuration;
49 import org.onap.appc.configuration.ConfigurationFactory;
50 import org.onap.appc.adapter.iaas.impl.VMURL;
51 import org.onap.appc.adapter.iaas.provider.operation.common.enums.Operation;
52 import org.onap.appc.adapter.iaas.provider.operation.impl.base.ProviderServerOperation;
53 import org.onap.appc.exceptions.APPCException;
54 import com.att.cdp.exceptions.TimeoutException;
55 import com.att.cdp.openstack.util.ExceptionMapper;
56 import org.onap.appc.i18n.Msg;
57 import com.woorea.openstack.base.client.OpenStackBaseException;
58 import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
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             if (context != null) {
90                 tenantName = context.getTenantName();// this variable also is
91                                                         // used in case of
92                                                         // exception
93                 requestContext.reset();
94                 server = lookupServer(requestContext, context, vm.getServerId());
95                 logger.debug(Msg.SERVER_FOUND, vmUrl, context.getTenantName(), server.getStatus().toString());
96                 Context contx = server.getContext();
97                 ComputeService service = contx.getComputeService();
98                 Volume volume = new Volume();
99                 VolumeService vs = contx.getVolumeService();
100                 Volume s = vs.getVolume(volumeId);
101                 boolean flag = false;
102                 if (validateDetach(service, vm.getServerId(), volumeId)) {
103                     volume.setId(volumeId);
104                     logger.info("Ready to Detach Volume from the server:");
105                     service.detachVolume(server, volume);
106                     flag = true;
107                 } else {
108                     String msg = "Volume with volume id " + volumeId + " cannot be detached as it does not exists";
109                     logger.info("Volume doesnot exists:");
110                     ctx.setAttribute("VOLUME_STATUS", "FAILURE");
111                     doFailure(requestContext, HttpStatus.METHOD_NOT_ALLOWED_405, msg);
112                     flag = false;
113                 }
114                 if (flag) {
115                     if (validateDetach(requestContext, service, vm.getServerId(), volumeId)) {
116                         String msg = "Volume with volume id " + volumeId + " cannot be detached ";
117                         ctx.setAttribute("VOLUME_STATUS", "FAILURE");
118                         doFailure(requestContext, HttpStatus.CONFLICT_409, msg);
119                     } else {
120                         logger.info("status of detaching volume");
121                         ctx.setAttribute("VOLUME_STATUS", "SUCCESS");
122                         doSuccess(requestContext);
123                     }
124                 }
125                 context.close();
126             } else {
127                 ctx.setAttribute("VOLUME_STATUS", "CONTEXT_NOT_FOUND");
128             }
129         } catch (ZoneException e) {
130             String msg = EELFResourceManager.format(Msg.SERVER_NOT_FOUND, e, vmUrl);
131             logger.error(msg);
132             doFailure(requestContext, HttpStatus.NOT_FOUND_404, msg);
133         } catch (RequestFailedException e) {
134             logger.error("An error occurred when processing the request", e);
135             doFailure(requestContext, e.getStatus(), e.getMessage());
136         } catch (Exception e) {
137             String msg = EELFResourceManager.format(Msg.DETTACHINGVOLUME_SERVER, e, e.getClass().getSimpleName(),
138                     DETACHVOLUME_SERVICE.toString(), vmUrl, tenantName);
139             logger.error(msg, e);
140             try {
141                 ExceptionMapper.mapException((OpenStackBaseException) e);
142             } catch (ZoneException e1) {
143                 logger.error(e1.getMessage());
144             }
145
146             doFailure(requestContext, HttpStatus.INTERNAL_SERVER_ERROR_500, msg);
147         }
148         return server;
149     }
150
151     protected boolean validateDetach(ComputeService ser, String vm, String volumeId)
152             throws RequestFailedException, ZoneException {
153         boolean flag = false;
154         Map<String, String> map = ser.getAttachments(vm);
155         if (map != null && !(map.isEmpty())) {
156             Iterator<Entry<String, String>> it = map.entrySet().iterator();
157             while (it.hasNext()) {
158                 Map.Entry volumes = (Map.Entry) it.next();
159                 logger.info("volumes available in before detach");
160                 logger.info("device" + volumes.getKey() + "volume" + volumes.getValue());
161                 if (volumes.getValue().equals(volumeId)) {
162                     flag = true;
163                 }
164             }
165         }
166         logger.info("DettachVolume  Flag" + flag);
167         return flag;
168     }
169
170     protected boolean validateDetach(RequestContext rc, ComputeService ser, String vm, String volumeId)
171             throws RequestFailedException, ZoneException {
172         boolean flag = false;
173         String msg = null;
174         config.setProperty(Constants.PROPERTY_RETRY_DELAY, "10");
175         config.setProperty(Constants.PROPERTY_RETRY_LIMIT, "30");
176         while (rc.attempt()) {
177             Map<String, String> map = ser.getAttachments(vm);
178             if (map != null && !(map.isEmpty())) {
179             Iterator<Entry<String, String>> it = map.entrySet().iterator();
180             logger.info("volumes available after  detach ");
181             while (it.hasNext()) {
182                 Map.Entry volumes = (Map.Entry) it.next();
183                 logger.info(" devices " + volumes.getKey() + " volumes" + volumes.getValue());
184                 if (volumes.getValue().equals(volumeId)) {
185                     logger.info("Device" + volumes.getKey() + "Volume" + volumes.getValue());
186                     flag = true;
187                     break;
188                 } else {
189                     flag = false;
190                 }
191                 logger.info("Dettachvolume flag-->" + flag+"Attempts"+rc.getAttempts());
192             }
193             if (flag) {
194                 rc.delay();
195             } else {
196                 flag = false;
197                 break;
198             }
199         }
200             else
201             {
202                 flag = false;
203                 logger.info( rc.getAttempts() + "No.of attempts");
204                 break;
205             }
206         }
207         if ((rc.getAttempts() == 30) && (!flag)) {
208             msg = EELFResourceManager.format(Msg.CONNECTION_FAILED_RETRY, Long.toString(rc.getRetryDelay()),
209                     Integer.toString(rc.getAttempts()), Integer.toString(rc.getRetryLimit()));
210             logger.error(msg);
211             logger.info(msg);
212             throw new TimeoutException(msg);
213         }
214         logger.info("DettachVolume Flag -->" + flag);
215         return flag;
216     }
217
218 }