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