Fix LCM evacuate issue
[appc.git] / appc-adapters / appc-iaas-adapter / appc-iaas-adapter-bundle / src / main / java / org / onap / appc / adapter / iaas / provider / operation / impl / EvacuateServer.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  * Modifications Copyright (C) 2019 Ericsson
10  * =============================================================================
11  * Modification Copyright (C) 2019 IBM
12  * =============================================================================
13  * Licensed under the Apache License, Version 2.0 (the "License");
14  * you may not use this file except in compliance with the License.
15  * You may obtain a copy of the License at
16  * 
17  *      http://www.apache.org/licenses/LICENSE-2.0
18  * 
19  * Unless required by applicable law or agreed to in writing, software
20  * distributed under the License is distributed on an "AS IS" BASIS,
21  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
22  * See the License for the specific language governing permissions and
23  * limitations under the License.
24  * 
25  * ============LICENSE_END=========================================================
26  */
27
28 package org.onap.appc.adapter.iaas.provider.operation.impl;
29
30 import org.onap.appc.Constants;
31 import org.onap.appc.adapter.iaas.ProviderAdapter;
32 import org.onap.appc.adapter.iaas.impl.IdentityURL;
33 import org.onap.appc.adapter.iaas.impl.ProviderAdapterImpl;
34 import org.onap.appc.adapter.iaas.impl.RequestContext;
35 import org.onap.appc.adapter.iaas.impl.RequestFailedException;
36 import org.onap.appc.adapter.iaas.impl.VMURL;
37 import org.onap.appc.adapter.iaas.provider.operation.common.enums.Operation;
38 import org.onap.appc.adapter.iaas.provider.operation.impl.base.ProviderServerOperation;
39 import org.onap.appc.configuration.Configuration;
40 import org.onap.appc.configuration.ConfigurationFactory;
41 import org.onap.appc.exceptions.APPCException;
42 import org.onap.appc.i18n.Msg;
43 import org.onap.appc.logging.LoggingConstants;
44 import org.onap.appc.logging.LoggingUtils;
45 import com.att.cdp.exceptions.ContextConnectionException;
46 import com.att.cdp.exceptions.ResourceNotFoundException;
47 import com.att.cdp.exceptions.ZoneException;
48 import com.att.cdp.zones.ComputeService;
49 import com.att.cdp.zones.Context;
50 import com.att.cdp.zones.Provider;
51 import com.att.cdp.zones.model.Hypervisor;
52 import com.att.cdp.zones.model.Hypervisor.Status;
53 import com.att.cdp.zones.model.Hypervisor.State;
54 import com.att.cdp.zones.model.Image;
55 import com.att.cdp.zones.model.ModelObject;
56 import com.att.cdp.zones.model.Server;
57 import com.att.eelf.configuration.EELFLogger;
58 import com.att.eelf.configuration.EELFManager;
59 import com.att.eelf.i18n.EELFResourceManager;
60 import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
61 import org.glassfish.grizzly.http.util.HttpStatus;
62 import org.slf4j.MDC;
63 import java.io.IOException;
64 import java.util.Arrays;
65 import java.util.Date;
66 import java.util.List;
67 import java.util.Map;
68 import static org.onap.appc.adapter.utils.Constants.ADAPTER_NAME;
69
70 public class EvacuateServer extends ProviderServerOperation {
71
72     private static final String EVACUATE_STATUS = "EVACUATE_STATUS";
73     private static final String EVACUATE_SERVER = "Evacuate Server";
74
75     private static final EELFLogger logger = EELFManager.getInstance().getLogger(EvacuateServer.class);
76     private static EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger();
77     private static final Configuration configuration = ConfigurationFactory.getConfiguration();
78     private ProviderAdapterImpl paImpl = null;
79
80     private void evacuateServer(RequestContext rc, @SuppressWarnings("unused") Server server, String targetHost)
81             throws ZoneException, RequestFailedException {
82         Context ctx = server.getContext();
83         Provider provider = ctx.getProvider();
84         ComputeService service = ctx.getComputeService();
85         /*
86          * Pending is a bit of a special case. If we find the server is in a pending
87          * state, then the provider is in the process of changing state of the server.
88          * So, lets try to wait a little bit and see if the state settles down to one we
89          * can deal with. If not, then we have to fail the request.
90          */
91         try {
92             if (server.getStatus().equals(Server.Status.PENDING)) {
93                 waitForStateChange(rc, server, Server.Status.READY, Server.Status.RUNNING, Server.Status.ERROR,
94                         Server.Status.SUSPENDED, Server.Status.PAUSED);
95             }
96         } catch (RequestFailedException e) {
97             // evacuate is a special case. If the server is still in a Pending state, we
98             // want to
99             // continue with evacuate
100             logger.info("Evacuate server - ignore RequestFailedException from waitForStateChange() ...", e);
101         }
102         setTimeForMetricsLogger();
103         String msg;
104         try {
105             evacuateServerNested(rc, service, server, provider, targetHost);
106         } catch (ZoneException e) {
107             msg = EELFResourceManager.format(Msg.EVACUATE_SERVER_FAILED, server.getName(), server.getId(),
108                     e.getMessage());
109             logger.error(msg, e);
110             metricsLogger.error(msg);
111             throw new RequestFailedException(EVACUATE_SERVER, msg, HttpStatus.BAD_GATEWAY_502, server);
112         }
113         if (rc.isFailed()) {
114             msg = EELFResourceManager.format(Msg.CONNECTION_FAILED, provider.getName(), service.getURL());
115             logger.error(msg);
116             metricsLogger.error(msg);
117             throw new RequestFailedException(EVACUATE_SERVER, msg, HttpStatus.BAD_GATEWAY_502, server);
118         }
119         rc.reset();
120     }
121
122     private void evacuateServerNested(RequestContext rcCtx, ComputeService svc, Server server, Provider provider,
123             String targetHost) throws ZoneException, RequestFailedException {
124         String msg;
125         Context ctx = server.getContext();
126         rcCtx.reset();
127         while (rcCtx.attempt()) {
128             try {
129                 logger.debug("Calling CDP moveServer - server id = " + server.getId());
130                 svc.moveServer(server.getId(), targetHost);
131                 // Wait for completion, expecting the server to go to a non pending state
132                 waitForStateChange(rcCtx, server, Server.Status.READY, Server.Status.RUNNING, Server.Status.ERROR,
133                         Server.Status.SUSPENDED, Server.Status.PAUSED);
134                 break;
135             } catch (ContextConnectionException e) {
136                 msg = EELFResourceManager.format(Msg.CONNECTION_FAILED_RETRY, provider.getName(), svc.getURL(),
137                         ctx.getTenant().getName(), ctx.getTenant().getId(), e.getMessage(),
138                         Long.toString(rcCtx.getRetryDelay()), Integer.toString(rcCtx.getAttempts()),
139                         Integer.toString(rcCtx.getRetryLimit()));
140                 logger.error(msg, e);
141                 metricsLogger.error(msg, e);
142                 rcCtx.delay();
143             }
144         }
145     }
146
147     /**
148      * @see org.onap.appc.adapter.iaas.ProviderAdapter#evacuateServer(java.util.Map,
149      *      org.onap.ccsdk.sli.core.sli.SvcLogicContext)
150      */
151     private Server evacuateServer(Map<String, String> params, SvcLogicContext ctx) throws APPCException {
152         Server server = null;
153         RequestContext rc = new RequestContext(ctx);
154         rc.isAlive();
155         setTimeForMetricsLogger();
156         String msg;
157         ctx.setAttribute(EVACUATE_STATUS, "ERROR");
158         try {
159             validateParametersExist(params, ProviderAdapter.PROPERTY_INSTANCE_URL,
160                     ProviderAdapter.PROPERTY_PROVIDER_NAME);
161
162             String appName = configuration.getProperty(Constants.PROPERTY_APPLICATION_NAME);
163             String vmUrl = params.get(ProviderAdapter.PROPERTY_INSTANCE_URL);
164             VMURL vm = VMURL.parseURL(vmUrl);
165             if (validateVM(rc, appName, vmUrl, vm)) {
166                 return null;
167             }
168             server = evacuateServerMapNestedFirst(params, server, rc, ctx, vm, vmUrl);
169         } catch (RequestFailedException e) {
170             msg = EELFResourceManager.format(Msg.EVACUATE_SERVER_FAILED, "n/a", "n/a", e.getMessage());
171             logger.error(msg, e);
172             metricsLogger.error(msg);
173             doFailure(rc, e.getStatus(), e.getMessage());
174         }
175         return server;
176     }
177
178     private Server evacuateServerMapNestedFirst(Map<String, String> params, Server server, RequestContext rqstCtx,
179             SvcLogicContext ctx, VMURL vm, String vmUrl) throws APPCException {
180         String msg;
181         Context context;
182         IdentityURL ident = IdentityURL.parseURL(params.get(ProviderAdapter.PROPERTY_IDENTITY_URL));
183         String identStr = (ident == null) ? null : ident.toString();
184         // retrieve the optional parameters
185         String rebuildVm = params.get(ProviderAdapter.PROPERTY_REBUILD_VM);
186         String targetHostId = params.get(ProviderAdapter.PROPERTY_TARGETHOST_ID);
187         String tenantName = "Unknown";// to be used also in case of exception
188         try {
189             context = getContext(rqstCtx, vmUrl, identStr);
190             if (context != null) {
191                 tenantName = context.getTenantName();// this variable also is used in case of exception
192                 server = lookupServer(rqstCtx, context, vm.getServerId());
193                 logger.debug(Msg.SERVER_FOUND, vmUrl, tenantName, server.getStatus().toString());
194                 // check target host status
195                 checkHostStatus(server, targetHostId, context);
196                 // save hypervisor name before evacuate
197                 String hypervisor = server.getHypervisor().getHostName();
198                 evacuateServer(rqstCtx, server, targetHostId);
199                 server.refreshAll();
200                 String hypervisorAfterEvacuate = server.getHypervisor().getHostName();
201                 logger.debug(
202                         "Hostname before evacuate: " + hypervisor + ", After evacuate: " + hypervisorAfterEvacuate);
203                 // check hypervisor host name after evacuate. If it is unchanged, the evacuate
204                 // failed.
205                 checkHypervisor(server, hypervisor, hypervisorAfterEvacuate);
206                 // check VM status after evacuate
207                 checkStatus(server);
208                 context.close();
209                 doSuccess(rqstCtx);
210                 ctx.setAttribute(EVACUATE_STATUS, "SUCCESS");
211                 // If a snapshot exists, do a rebuild to apply the latest snapshot to the
212                 // evacuated server.
213                 // This is the default behavior unless the optional parameter is set to FALSE.
214                 if (rebuildVm == null || !"false".equalsIgnoreCase(rebuildVm)) {
215                     List<Image> snapshots = server.getSnapshots();
216                     if (snapshots == null || snapshots.isEmpty()) {
217                         logger.debug("No snapshots available - skipping rebuild after evacuate");
218                     } else if (paImpl != null) {
219                         logger.debug("Executing a rebuild after evacuate");
220                         paImpl.rebuildServer(params, ctx);
221                         // Check error code for rebuild errors. Evacuate had set it to 200 after
222                         // a successful evacuate. Rebuild updates the error code.
223                         evacuateServerMapNestedSecond(server, rqstCtx, ctx, hypervisor, hypervisorAfterEvacuate);
224                     }
225                 }
226             }
227         } catch (ResourceNotFoundException e) {
228             msg = EELFResourceManager.format(Msg.SERVER_NOT_FOUND, e, vmUrl);
229             logger.error(msg);
230             metricsLogger.error(msg);
231             doFailure(rqstCtx, HttpStatus.NOT_FOUND_404, msg);
232         } catch (RequestFailedException e) {
233             logger.error("Request failed", e);
234             doFailure(rqstCtx, e.getStatus(), e.getMessage());
235         } catch (IOException | ZoneException e1) {
236             msg = EELFResourceManager.format(Msg.SERVER_OPERATION_EXCEPTION, e1, e1.getClass().getSimpleName(),
237                     Operation.EVACUATE_SERVICE.toString(), vmUrl, tenantName);
238             logger.error(msg, e1);
239             metricsLogger.error(msg, e1);
240             doFailure(rqstCtx, HttpStatus.INTERNAL_SERVER_ERROR_500, e1.getMessage());
241         } catch (Exception e1) {
242             msg = EELFResourceManager.format(Msg.SERVER_OPERATION_EXCEPTION, e1, e1.getClass().getSimpleName(),
243                     Operation.EVACUATE_SERVICE.toString(), vmUrl, tenantName);
244             logger.error(msg, e1);
245             metricsLogger.error(msg);
246             doFailure(rqstCtx, HttpStatus.INTERNAL_SERVER_ERROR_500, e1.getMessage());
247         }
248         return server;
249     }
250
251     private void evacuateServerMapNestedSecond(Server server, RequestContext rc, SvcLogicContext ctx, String hypervisor,
252             String hypervisorAfterEvacuate) {
253         String msg;
254         String rebuildErrorCode = ctx.getAttribute(org.onap.appc.Constants.ATTRIBUTE_ERROR_CODE);
255         if (rebuildErrorCode != null) {
256             try {
257                 int errorCode = Integer.parseInt(rebuildErrorCode);
258                 if (errorCode != HttpStatus.OK_200.getStatusCode()) {
259                     logger.debug("Rebuild after evacuate failed - error code=" + errorCode + ", message="
260                             + ctx.getAttribute(org.onap.appc.Constants.ATTRIBUTE_ERROR_MESSAGE));
261                     msg = EELFResourceManager.format(Msg.EVACUATE_SERVER_REBUILD_FAILED, server.getName(), hypervisor,
262                             hypervisorAfterEvacuate, ctx.getAttribute(org.onap.appc.Constants.ATTRIBUTE_ERROR_MESSAGE));
263                     logger.error(msg);
264                     metricsLogger.error(msg);
265                     ctx.setAttribute(EVACUATE_STATUS, "ERROR");
266                     // update error message while keeping the error code the
267                     // same as before
268                     doFailure(rc, HttpStatus.getHttpStatus(errorCode), msg);
269                 }
270             } catch (NumberFormatException e) {
271                 // ignore
272             }
273         }
274     }
275
276     private void checkHostStatus(Server server, String targetHostId, Context context)
277             throws ZoneException, RequestFailedException {
278         if (isComputeNodeDown(context, targetHostId)) {
279             String msg = EELFResourceManager.format(Msg.EVACUATE_SERVER_FAILED, server.getName(), server.getId(),
280                     "Target host " + targetHostId + " status is not UP/ENABLED");
281             logger.error(msg);
282             metricsLogger.error(msg);
283             throw new RequestFailedException(EVACUATE_SERVER, msg, HttpStatus.BAD_REQUEST_400, server);
284         }
285     }
286
287     private void checkHypervisor(Server server, String hypervisor, String hypervisorAfterEvacuate)
288             throws RequestFailedException {
289         if (hypervisor != null && hypervisor.equals(hypervisorAfterEvacuate)) {
290             String msg = EELFResourceManager.format(Msg.EVACUATE_SERVER_FAILED, server.getName(), server.getId(),
291                     "Hypervisor host " + hypervisor
292                             + " after evacuate is the same as before evacuate. Provider (ex. Openstack) recovery actions may be needed.");
293             logger.error(msg);
294             metricsLogger.error(msg);
295             throw new RequestFailedException(EVACUATE_SERVER, msg, HttpStatus.INTERNAL_SERVER_ERROR_500, server);
296         }
297     }
298
299     private void checkStatus(Server server) throws RequestFailedException {
300         if (server.getStatus() == Server.Status.ERROR) {
301             String msg = EELFResourceManager.format(Msg.EVACUATE_SERVER_FAILED, server.getName(), server.getId(),
302                     "VM is in ERROR state after evacuate. Provider (ex. Openstack) recovery actions may be needed.");
303             logger.error(msg);
304             metricsLogger.error(msg);
305             throw new RequestFailedException(EVACUATE_SERVER, msg, HttpStatus.INTERNAL_SERVER_ERROR_500, server);
306         }
307     }
308
309     /**
310      * Check if a Compute node is down.
311      * 
312      * This method attempts to find a given host in the list of hypervisors for a
313      * given context. The only case where a node is considered down is if a matching
314      * hypervisor is found and it's state and status are not UP/ENABLED.
315      * 
316      * @param context
317      *            The current context
318      * 
319      * @param host
320      *            The host name (short or fully qualified) of a compute node
321      * 
322      * @return true if the node is determined as down, false for all other cases
323      */
324     private boolean isComputeNodeDown(Context context, String host) throws ZoneException {
325         ComputeService service = context.getComputeService();
326         boolean nodeDown = false;
327         if (host != null && !host.isEmpty()) {
328             List<Hypervisor> hypervisors = service.getHypervisors();
329             logger.debug("List of Hypervisors retrieved: " + Arrays.toString(hypervisors.toArray()));
330             for (Hypervisor hv : hypervisors) {
331                 nodeDown = isNodeDown(host, nodeDown, hv);
332             }
333         }
334         return nodeDown;
335     }
336
337     private boolean isNodeDown(String host, boolean nodeDown, Hypervisor hv) {
338         if (isHostMatchesHypervisor(host, hv)) {
339             State hstate = hv.getState();
340             Status hstatus = hv.getStatus();
341             logger.debug("Host matching hypervisor: " + hv.getHostName() + ", State/Status: " + hstate.toString() + "/"
342                     + hstatus.toString());
343             if (hstate != State.UP || hstatus != Status.ENABLED) {
344                 return true;
345             }
346         }
347         return nodeDown;
348     }
349
350     private boolean isHostMatchesHypervisor(String host, Hypervisor hypervisor) {
351         return hypervisor.getHostName().startsWith(host);
352     }
353
354     @Override
355     protected ModelObject executeProviderOperation(Map<String, String> params, SvcLogicContext context)
356             throws APPCException {
357         setMDC(Operation.EVACUATE_SERVICE.toString(), "App-C IaaS Adapter:Evacuate", ADAPTER_NAME);
358         logOperation(Msg.EVACUATING_SERVER, params, context);
359         setTimeForMetricsLogger();
360         metricsLogger.info("Executing Provider Operation: Evacuate");
361         return evacuateServer(params, context);
362     }
363
364     private void setTimeForMetricsLogger() {
365         String timestamp = LoggingUtils.generateTimestampStr((new Date()).toInstant());
366         MDC.put(LoggingConstants.MDCKeys.BEGIN_TIMESTAMP, timestamp);
367         MDC.put(LoggingConstants.MDCKeys.END_TIMESTAMP, timestamp);
368         MDC.put(LoggingConstants.MDCKeys.ELAPSED_TIME, "0");
369         MDC.put(LoggingConstants.MDCKeys.STATUS_CODE, LoggingConstants.StatusCodes.COMPLETE);
370         MDC.put(LoggingConstants.MDCKeys.TARGET_ENTITY, "cdp");
371         MDC.put(LoggingConstants.MDCKeys.TARGET_SERVICE_NAME, "evacuate server");
372         MDC.put(LoggingConstants.MDCKeys.CLASS_NAME,
373                 "org.onap.appc.adapter.iaas.provider.operation.impl.EvacuateServer");
374     }
375
376     public void setProvideAdapterRef(ProviderAdapterImpl pai) {
377         paImpl = pai;
378     }
379 }