enchance rebuildaction to make snapshotid Optional
[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  * ============LICENSE_END=========================================================
22  */
23 package org.onap.appc.adapter.iaas.provider.operation.impl;
24
25 import static org.onap.appc.adapter.iaas.provider.operation.common.enums.Operation.DETACHVOLUME_SERVICE;
26 import static org.onap.appc.adapter.utils.Constants.ADAPTER_NAME;
27 import com.att.cdp.exceptions.ZoneException;
28 import com.att.cdp.zones.ComputeService;
29 import com.att.cdp.zones.Context;
30 import com.att.cdp.zones.VolumeService;
31 import com.att.cdp.zones.model.ModelObject;
32 import com.att.cdp.zones.model.Server;
33 import com.att.cdp.zones.model.Volume;
34 import com.att.eelf.configuration.EELFLogger;
35 import com.att.eelf.configuration.EELFManager;
36 import com.att.eelf.i18n.EELFResourceManager;
37 import java.util.List;
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
59 public class DettachVolumeServer extends ProviderServerOperation {
60     private final EELFLogger logger = EELFManager.getInstance().getLogger(DettachVolumeServer.class);
61     private static final Configuration config = ConfigurationFactory.getConfiguration();
62
63     @Override
64     protected ModelObject executeProviderOperation(Map<String, String> params, SvcLogicContext context)
65             throws APPCException {
66         setMDC(Operation.DETACHVOLUME_SERVICE.toString(), "App-C IaaS Adapter:dettachVolume", ADAPTER_NAME);
67         logOperation(Msg.DETTACHINGVOLUME_SERVER, params, context);
68         return dettachVolume(params, context);
69     }
70
71     private Server dettachVolume(Map<String, String> params, SvcLogicContext ctx) {
72         Server server = null;
73         RequestContext requestContext = new RequestContext(ctx);
74         requestContext.isAlive();
75         String appName = configuration.getProperty(Constants.PROPERTY_APPLICATION_NAME);
76         String vmUrl = params.get(ProviderAdapter.PROPERTY_INSTANCE_URL);
77         String volumeId = params.get(ProviderAdapter.VOLUME_ID);
78         VMURL vm = VMURL.parseURL(vmUrl);
79         Context context;
80         String tenantName = "Unknown";// to be used also in case of exception
81         try {
82             if (validateVM(requestContext, appName, vmUrl, vm)) {
83                 return null;
84             }
85             IdentityURL ident = IdentityURL.parseURL(params.get(ProviderAdapter.PROPERTY_IDENTITY_URL));
86             String identStr = (ident == null) ? null : ident.toString();
87             context = getContext(requestContext, vmUrl, identStr);
88             if (context != null) {
89                 tenantName = context.getTenantName();// this variable also is
90                                                         // used in case of
91                                                         // exception
92                 requestContext.reset();
93                 server = lookupServer(requestContext, context, vm.getServerId());
94                 logger.debug(Msg.SERVER_FOUND, vmUrl, context.getTenantName(), server.getStatus().toString());
95                 if (volumeId == null || volumeId.isEmpty()) {
96                     ctx.setAttribute("VOLUME_STATUS", "FAILURE");
97                     doFailure(requestContext, HttpStatus.BAD_REQUEST_400, "Volumeid is mandatory");
98                 }
99                 Context contx = server.getContext();
100                 ComputeService service = contx.getComputeService();
101                 Volume volume = new Volume();
102                 VolumeService vs = contx.getVolumeService();
103                 Volume s = vs.getVolume(volumeId);
104                 boolean flag = false;
105                 if (validateDetach(service, vm.getServerId(), volumeId)) {
106                     volume.setId(volumeId);
107                     logger.info("Ready to Detach Volume from the server:");
108                     service.detachVolume(server, volume);
109                     flag = true;
110                 } else {
111                     String msg = "Volume with volume id " + volumeId + " cannot be detached as it does not exists";
112                     logger.info("Volume doesnot exists:");
113                     ctx.setAttribute("VOLUME_STATUS", "FAILURE");
114                     doFailure(requestContext, HttpStatus.METHOD_NOT_ALLOWED_405, msg);
115                     flag = false;
116                 }
117                 if (flag) {
118                     if (validateDetach(requestContext, service, vm.getServerId(), volumeId)) {
119                         String msg = "Volume with volume id " + volumeId + " cannot be detached ";
120                         ctx.setAttribute("VOLUME_STATUS", "FAILURE");
121                         doFailure(requestContext, HttpStatus.CONFLICT_409, msg);
122                     } else {
123                         logger.info("status of detaching volume");
124                         ctx.setAttribute("VOLUME_STATUS", "SUCCESS");
125                         doSuccess(requestContext);
126                     }
127                 }
128                 context.close();
129             } else {
130                 ctx.setAttribute("VOLUME_STATUS", "CONTEXT_NOT_FOUND");
131             }
132         } catch (ZoneException e) {
133             String msg = EELFResourceManager.format(Msg.SERVER_NOT_FOUND, e, vmUrl);
134             logger.error(msg);
135             doFailure(requestContext, HttpStatus.NOT_FOUND_404, msg);
136         } catch (RequestFailedException e) {
137             logger.error("An error occurred when processing the request", e);
138             doFailure(requestContext, e.getStatus(), e.getMessage());
139         } catch (Exception e) {
140             String msg = EELFResourceManager.format(Msg.DETTACHINGVOLUME_SERVER, e, e.getClass().getSimpleName(),
141                     DETACHVOLUME_SERVICE.toString(), vmUrl, tenantName);
142             logger.error(msg, e);
143             try {
144                 ExceptionMapper.mapException((OpenStackBaseException) e);
145             } catch (ZoneException e1) {
146                 logger.error(e1.getMessage());
147             }
148
149             doFailure(requestContext, HttpStatus.INTERNAL_SERVER_ERROR_500, msg);
150         }
151         return server;
152     }
153
154     protected boolean validateDetach(ComputeService ser, String vm, String volumeId)
155             throws RequestFailedException, ZoneException {
156         boolean flag = false;
157         Map<String, String> map = ser.getAttachments(vm);
158         if (map != null && !(map.isEmpty())) {
159             Iterator<Entry<String, String>> it = map.entrySet().iterator();
160             while (it.hasNext()) {
161                 Map.Entry volumes = (Map.Entry) it.next();
162                 logger.info("volumes available in before detach");
163                 logger.info("device" + volumes.getKey() + "volume" + volumes.getValue());
164                 if (volumes.getValue().equals(volumeId)) {
165                     flag = true;
166                 }
167             }
168         }
169         logger.info("DettachVolume  Flag" + flag);
170         return flag;
171     }
172
173     protected boolean validateDetach(RequestContext rc, ComputeService ser, String vm, String volumeId)
174             throws RequestFailedException, ZoneException {
175         boolean flag = false;
176         String msg = null;
177         config.setProperty(Constants.PROPERTY_RETRY_DELAY, "10");
178         config.setProperty(Constants.PROPERTY_RETRY_LIMIT, "30");
179         while (rc.attempt()) {
180             Map<String, String> map = ser.getAttachments(vm);
181             if (map != null && !(map.isEmpty())) {
182                 Iterator<Entry<String, String>> it = map.entrySet().iterator();
183                 logger.info("volumes available after  detach ");
184                 while (it.hasNext()) {
185                     Map.Entry volumes = (Map.Entry) it.next();
186                     logger.info(" devices " + volumes.getKey() + " volumes" + volumes.getValue());
187                     if (volumes.getValue().equals(volumeId)) {
188                         logger.info("Device" + volumes.getKey() + "Volume" + volumes.getValue());
189                         flag = true;
190                         break;
191                     } else {
192                         flag = false;
193                     }
194                     logger.info("Dettachvolume flag-->" + flag + "Attempts" + rc.getAttempts());
195                 }
196                 if (flag) {
197                     rc.delay();
198                 } else {
199                     flag = false;
200                     break;
201                 }
202             } else {
203                 flag = false;
204                 logger.info(rc.getAttempts() + "No.of attempts");
205                 break;
206             }
207         }
208         if ((rc.getAttempts() == 30) && (!flag)) {
209             msg = EELFResourceManager.format(Msg.CONNECTION_FAILED_RETRY, Long.toString(rc.getRetryDelay()),
210                     Integer.toString(rc.getAttempts()), Integer.toString(rc.getRetryLimit()));
211             logger.error(msg);
212             logger.info(msg);
213             throw new TimeoutException(msg);
214         }
215         logger.info("DettachVolume Flag -->" + flag);
216         return flag;
217     }
218
219 }