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 / 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                 if ((volumeId == null || volumeId.isEmpty()) || (device == null || device.isEmpty())) {
92                     ctx.setAttribute("VOLUME_STATUS", "FAILURE");
93                     doFailure(requestContext, HttpStatus.BAD_REQUEST_400, "Both Device or Volumeid are mandatory");
94                 }
95                 VolumeService volumeService = contx.getVolumeService();
96                 logger.info("collecting volume status for volume -id:" + volumeId);
97                 List<Volume> volumes = volumeService.getVolumes();
98                 Volume volume = new Volume();
99                 boolean isAttached = false;
100                 if (validateAttach(service, vm.getServerId(), volumeId, device)) {
101                     String msg = "Volume with volume id " + volumeId + " cannot be attached as it already exists";
102                     logger.info("Already volumes exists:");
103                     ctx.setAttribute("VOLUME_STATUS", "FAILURE");
104                     doFailure(requestContext, HttpStatus.METHOD_NOT_ALLOWED_405, msg);
105                     isAttached = false;
106                 } else {
107                     volume.setId(volumeId);
108                     logger.info("Ready to Attach Volume to the server:");
109                     service.attachVolume(server, volume, device);
110                     isAttached = true;
111                 }
112                 if (isAttached) {
113                     if (validateAttach(requestContext, service, vm.getServerId(), volumeId, device)) {
114                         ctx.setAttribute("VOLUME_STATUS", "SUCCESS");
115                         doSuccess(requestContext);
116                     } else {
117                         String msg = "Volume with " + volumeId + " unable  to attach";
118                         logger.info("Volume with " + volumeId + " unable to attach");
119                         ctx.setAttribute("VOLUME_STATUS", "FAILURE");
120                         doFailure(requestContext, HttpStatus.CONFLICT_409, msg);
121                     }
122                 }
123                 context.close();
124             } else {
125                 ctx.setAttribute("VOLUME_STATUS", "CONTEXT_NOT_FOUND");
126             }
127         } catch (ZoneException e) {
128             String msg = EELFResourceManager.format(Msg.SERVER_NOT_FOUND, e, vmUrl);
129             logger.error(msg);
130             ctx.setAttribute("VOLUME_STATUS", "FAILURE");
131             doFailure(requestContext, HttpStatus.NOT_FOUND_404, msg);
132         } catch (RequestFailedException e) {
133             ctx.setAttribute("VOLUME_STATUS", "FAILURE");
134             doFailure(requestContext, e.getStatus(), e.getMessage());
135         } catch (Exception ex) {
136             String msg = EELFResourceManager.format(Msg.SERVER_OPERATION_EXCEPTION, ex, ex.getClass().getSimpleName(),
137                     ATTACHVOLUME_SERVICE.toString(), vmUrl, tenantName);
138             ctx.setAttribute("VOLUME_STATUS", "FAILURE");
139             try {
140                 ExceptionMapper.mapException((OpenStackBaseException) ex);
141             } catch (ZoneException e1) {
142                 logger.error(e1.getMessage());
143             }
144             doFailure(requestContext, HttpStatus.INTERNAL_SERVER_ERROR_500, msg);
145         }
146         return server;
147     }
148
149     @Override
150     protected ModelObject executeProviderOperation(Map<String, String> params, SvcLogicContext context)
151             throws APPCException {
152         setMDC(Operation.ATTACHVOLUME_SERVICE.toString(), "App-C IaaS Adapter:attachVolume", ADAPTER_NAME);
153         logOperation(Msg.ATTACHINGVOLUME_SERVER, params, context);
154         return attachVolume(params, context);
155     }
156
157     protected boolean validateAttach(ComputeService ser, String vm, String volumeId, String device)
158             throws RequestFailedException, ZoneException {
159         boolean isValid = false;
160         Map<String, String> map = ser.getAttachments(vm);
161         Iterator<Entry<String, String>> it = map.entrySet().iterator();
162         while (it.hasNext()) {
163             Map.Entry volumes = (Map.Entry) it.next();
164             if (map != null && !(map.isEmpty())) {
165                 logger.info("volumes available before attach");
166                 logger.info("device" + volumes.getKey() + "Values" + volumes.getValue());
167                 if (volumes.getKey().equals(device) && (volumes.getValue().equals(volumeId))) {
168                     logger.info("Device " + volumes.getKey() + "Volumes" + volumes.getValue());
169                     isValid = true;
170                 }
171             }
172         }
173         logger.info("AttachVolumeFlag" + isValid);
174         return isValid;
175     }
176
177     protected boolean validateAttach(RequestContext rc, ComputeService ser, String vm, String volumeId, String device)
178             throws RequestFailedException, ZoneException {
179         boolean isValid = false;
180         String msg = null;
181         config.setProperty(Constants.PROPERTY_RETRY_DELAY, "10");
182         config.setProperty(Constants.PROPERTY_RETRY_LIMIT, "30");
183         while (rc.attempt()) {
184             Map<String, String> map = ser.getAttachments(vm);
185             if (map != null && !(map.isEmpty())) {
186                 Iterator<Entry<String, String>> it = map.entrySet().iterator();
187                 logger.info("volumes available after attach ");
188                 while (it.hasNext()) {
189                     Map.Entry volumes = (Map.Entry) it.next();
190                     logger.info(" devices " + volumes.getKey() + "volumes" + volumes.getValue());
191                     if (volumes.getKey().equals(device) && (volumes.getValue().equals(volumeId))) {
192                         logger.info("Device" + volumes.getKey() + "Volume" + volumes.getValue());
193                         isValid = true;
194                         break;
195                     }
196                 }
197                 if (isValid) {
198                     logger.info("AttachVolume" + rc.getAttempts() + "No.of attempts");
199                     break;
200                 } else {
201                     rc.delay();
202                 }
203             }
204         }
205         if ((rc.getAttempts() == 30) && (!isValid)) {
206             msg = EELFResourceManager.format(Msg.CONNECTION_FAILED_RETRY, Long.toString(rc.getRetryDelay()),
207                     Integer.toString(rc.getAttempts()), Integer.toString(rc.getRetryLimit()));
208             logger.error(msg);
209             throw new TimeoutException(msg);
210         }
211         logger.info("AttachVolume Flag -->" + isValid);
212         return isValid;
213     }
214 }