Bugfixes for error handling while attaching volume
[appc.git] / appc-adapters / appc-iaas-adapter / appc-iaas-adapter-bundle / src / main / java / org / onap / appc / adapter / iaas / provider / operation / impl / AttachVolumeServer.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.ATTACHVOLUME_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 org.glassfish.grizzly.http.util.HttpStatus;
41 import org.onap.appc.Constants;
42 import org.onap.appc.adapter.iaas.ProviderAdapter;
43 import org.onap.appc.adapter.iaas.impl.IdentityURL;
44 import org.onap.appc.adapter.iaas.impl.RequestContext;
45 import org.onap.appc.adapter.iaas.impl.RequestFailedException;
46 import com.att.cdp.exceptions.TimeoutException;
47 import org.onap.appc.adapter.iaas.impl.VMURL;
48 import org.onap.appc.adapter.iaas.provider.operation.common.enums.Operation;
49 import org.onap.appc.adapter.iaas.provider.operation.impl.base.ProviderServerOperation;
50 import com.woorea.openstack.base.client.OpenStackBaseException;
51 import com.att.cdp.openstack.util.ExceptionMapper;
52 import org.onap.appc.configuration.Configuration;
53 import org.onap.appc.configuration.ConfigurationFactory;
54 import java.util.Iterator;
55 import org.onap.appc.exceptions.APPCException;
56 import org.onap.appc.i18n.Msg;
57 import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
58
59 public class AttachVolumeServer extends ProviderServerOperation {
60
61     private final EELFLogger logger = EELFManager.getInstance().getLogger(AttachVolumeServer.class);
62     private static final Configuration config = ConfigurationFactory.getConfiguration();
63
64     private Server attachVolume(Map<String, String> params, SvcLogicContext ctx) throws APPCException {
65         Server server = null;
66         RequestContext requestContext = new RequestContext(ctx);
67         requestContext.isAlive();
68         String appName = configuration.getProperty(Constants.PROPERTY_APPLICATION_NAME);
69         String vmUrl = params.get(ProviderAdapter.PROPERTY_INSTANCE_URL);
70         String volumeId = params.get(ProviderAdapter.VOLUME_ID);
71         String device = params.get(ProviderAdapter.DEVICE);
72         VMURL vm = VMURL.parseURL(vmUrl);
73         Context context;
74         String tenantName = "Unknown";// to be used also in case of exception
75         try {
76             if (validateVM(requestContext, appName, vmUrl, vm)) {
77                 return null;
78             }
79             IdentityURL ident = IdentityURL.parseURL(params.get(ProviderAdapter.PROPERTY_IDENTITY_URL));
80             String identStr = (ident == null) ? null : ident.toString();
81             context = getContext(requestContext, vmUrl, identStr);
82             if (context != null) {
83                 tenantName = context.getTenantName();// this variable also is
84                                                         // used in case of
85                                                         // exception
86                 requestContext.reset();
87                 server = lookupServer(requestContext, context, vm.getServerId());
88                 logger.debug(Msg.SERVER_FOUND, vmUrl, context.getTenantName(), server.getStatus().toString());
89                 Context contx = server.getContext();
90                 ComputeService service = contx.getComputeService();
91                 VolumeService volumeService = contx.getVolumeService();
92                 logger.info("collecting volume status for volume -id:" + volumeId);
93                 List<Volume> volumes = volumeService.getVolumes();
94                 Volume volume = new Volume();
95                 boolean isAttached = false;
96                 if (validateAttach(service, vm.getServerId(), volumeId, device)) {
97                     String msg = "Volume with volume id " + volumeId + " cannot be attached as it already exists";
98                     logger.info("Already volumes exists:");
99                     ctx.setAttribute("VOLUME_STATUS", "FAILURE");
100                     doFailure(requestContext, HttpStatus.METHOD_NOT_ALLOWED_405, msg);
101                     isAttached = false;
102                 } else {
103                     volume.setId(volumeId);
104                     logger.info("Ready to Attach Volume to the server:");
105                     service.attachVolume(server, volume, device);
106                     isAttached = true;
107                 }
108                 if (isAttached) {
109                     if (validateAttach(requestContext, service, vm.getServerId(), volumeId, device)) {
110                         ctx.setAttribute("VOLUME_STATUS", "SUCCESS");
111                         doSuccess(requestContext);
112                     } else {
113                         String msg = "Volume with " + volumeId + " unable  to attach";
114                         logger.info("Volume with " + volumeId + " unable to attach");
115                         ctx.setAttribute("VOLUME_STATUS", "FAILURE");
116                         doFailure(requestContext, HttpStatus.CONFLICT_409, msg);
117                     }
118                 }
119                 context.close();
120             } else {
121                 ctx.setAttribute("VOLUME_STATUS", "CONTEXT_NOT_FOUND");
122             }
123         } catch (ZoneException e) {
124             String msg = EELFResourceManager.format(Msg.SERVER_NOT_FOUND, e, vmUrl);
125             logger.error(msg);
126             ctx.setAttribute("VOLUME_STATUS", "FAILURE");
127             doFailure(requestContext, HttpStatus.NOT_FOUND_404, msg);
128         } catch (RequestFailedException e) {
129             ctx.setAttribute("VOLUME_STATUS", "FAILURE");
130             doFailure(requestContext, e.getStatus(), e.getMessage());
131         } catch (Exception ex) {
132             String msg = EELFResourceManager.format(Msg.SERVER_OPERATION_EXCEPTION, ex, ex.getClass().getSimpleName(),
133                     ATTACHVOLUME_SERVICE.toString(), vmUrl, tenantName);
134             ctx.setAttribute("VOLUME_STATUS", "FAILURE");
135             try {
136                 ExceptionMapper.mapException((OpenStackBaseException) ex);
137             } catch (ZoneException e1) {
138                 logger.error(e1.getMessage());
139             }
140             doFailure(requestContext, HttpStatus.INTERNAL_SERVER_ERROR_500, msg);
141         }
142         return server;
143     }
144
145     @Override
146     protected ModelObject executeProviderOperation(Map<String, String> params, SvcLogicContext context)
147             throws APPCException {
148         setMDC(Operation.ATTACHVOLUME_SERVICE.toString(), "App-C IaaS Adapter:attachVolume", ADAPTER_NAME);
149         logOperation(Msg.ATTACHINGVOLUME_SERVER, params, context);
150         return attachVolume(params, context);
151     }
152
153     protected boolean validateAttach(ComputeService ser, String vm, String volumeId, String device)
154             throws RequestFailedException, ZoneException {
155         boolean isValid = false;
156         Map<String, String> map = ser.getAttachments(vm);
157         Iterator<Entry<String, String>> it = map.entrySet().iterator();
158         while (it.hasNext()) {
159             Map.Entry volumes = (Map.Entry) it.next();
160             if (map != null && !(map.isEmpty())) {
161                 logger.info("volumes available before attach");
162                 logger.info("device" + volumes.getKey() + "Values" + volumes.getValue());
163                 if (volumes.getKey().equals(device) && (volumes.getValue().equals(volumeId))) {
164                     logger.info("Device " + volumes.getKey() + "Volumes" + volumes.getValue());
165                     isValid = true;
166                 }
167             }
168         }
169         logger.info("AttachVolumeFlag" + isValid);
170         return isValid;
171     }
172     
173     protected boolean validateAttach(RequestContext rc, ComputeService ser, String vm, String volumeId, String device)
174             throws RequestFailedException, ZoneException {
175         boolean isValid = 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 attach ");
184                 while (it.hasNext()) {
185                     Map.Entry volumes = (Map.Entry) it.next();
186                     logger.info(" devices " + volumes.getKey() + "volumes" + volumes.getValue());
187                     if (volumes.getKey().equals(device) && (volumes.getValue().equals(volumeId))) {
188                         logger.info("Device" + volumes.getKey() + "Volume" + volumes.getValue());
189                         isValid = true;
190                         break;
191                     }
192                 }
193                 if (isValid) {
194                     logger.info("AttachVolume" + rc.getAttempts() + "No.of attempts");
195                     break;
196                 } else {
197                     rc.delay();
198                 }
199             }
200         }
201         if ((rc.getAttempts() == 30) && (!isValid)) {
202
203             msg = EELFResourceManager.format(Msg.CONNECTION_FAILED_RETRY, Long.toString(rc.getRetryDelay()),
204                     Integer.toString(rc.getAttempts()), Integer.toString(rc.getRetryLimit()));
205             logger.error(msg);
206             throw new TimeoutException(msg);
207         }
208         logger.info("AttachVolume Flag -->" + isValid);
209         return isValid;
210     }
211 }