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