cfd816e14fc86fd18e2fcffc12c3c4339f42eb6b
[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         while (rcCtx.attempt()) {
127             try {
128                 logger.debug("Calling CDP moveServer - server id = " + server.getId());
129                 svc.moveServer(server.getId(), targetHost);
130                 // Wait for completion, expecting the server to go to a non pending state
131                 waitForStateChange(rcCtx, server, Server.Status.READY, Server.Status.RUNNING, Server.Status.ERROR,
132                         Server.Status.SUSPENDED, Server.Status.PAUSED);
133                 break;
134             } catch (ContextConnectionException e) {
135                 msg = EELFResourceManager.format(Msg.CONNECTION_FAILED_RETRY, provider.getName(), svc.getURL(),
136                         ctx.getTenant().getName(), ctx.getTenant().getId(), e.getMessage(),
137                         Long.toString(rcCtx.getRetryDelay()), Integer.toString(rcCtx.getAttempts()),
138                         Integer.toString(rcCtx.getRetryLimit()));
139                 logger.error(msg, e);
140                 metricsLogger.error(msg, e);
141                 rcCtx.delay();
142             }
143         }
144     }
145
146     /**
147      * @see org.onap.appc.adapter.iaas.ProviderAdapter#evacuateServer(java.util.Map,
148      *      org.onap.ccsdk.sli.core.sli.SvcLogicContext)
149      */
150     private Server evacuateServer(Map<String, String> params, SvcLogicContext ctx) throws APPCException {
151         Server server = null;
152         RequestContext rc = new RequestContext(ctx);
153         rc.isAlive();
154         setTimeForMetricsLogger();
155         String msg;
156         ctx.setAttribute(EVACUATE_STATUS, "ERROR");
157         try {
158             validateParametersExist(params, ProviderAdapter.PROPERTY_INSTANCE_URL,
159                     ProviderAdapter.PROPERTY_PROVIDER_NAME);
160
161             String appName = configuration.getProperty(Constants.PROPERTY_APPLICATION_NAME);
162             String vmUrl = params.get(ProviderAdapter.PROPERTY_INSTANCE_URL);
163             VMURL vm = VMURL.parseURL(vmUrl);
164             if (validateVM(rc, appName, vmUrl, vm)) {
165                 return null;
166             }
167             server = evacuateServerMapNestedFirst(params, server, rc, ctx, vm, vmUrl);
168         } catch (RequestFailedException e) {
169             msg = EELFResourceManager.format(Msg.EVACUATE_SERVER_FAILED, "n/a", "n/a", e.getMessage());
170             logger.error(msg, e);
171             metricsLogger.error(msg);
172             doFailure(rc, e.getStatus(), e.getMessage());
173         }
174         return server;
175     }
176
177     private Server evacuateServerMapNestedFirst(Map<String, String> params, Server server, RequestContext rqstCtx,
178             SvcLogicContext ctx, VMURL vm, String vmUrl) throws APPCException {
179         String msg;
180         Context context;
181         IdentityURL ident = IdentityURL.parseURL(params.get(ProviderAdapter.PROPERTY_IDENTITY_URL));
182         String identStr = (ident == null) ? null : ident.toString();
183         // retrieve the optional parameters
184         String rebuildVm = params.get(ProviderAdapter.PROPERTY_REBUILD_VM);
185         String targetHostId = params.get(ProviderAdapter.PROPERTY_TARGETHOST_ID);
186         String tenantName = "Unknown";// to be used also in case of exception
187         try {
188             context = getContext(rqstCtx, vmUrl, identStr);
189             if (context != null) {
190                 tenantName = context.getTenantName();// this variable also is used in case of exception
191                 server = lookupServer(rqstCtx, context, vm.getServerId());
192                 logger.debug(Msg.SERVER_FOUND, vmUrl, tenantName, server.getStatus().toString());
193                 // check target host status
194                 checkHostStatus(server, targetHostId, context);
195                 // save hypervisor name before evacuate
196                 String hypervisor = server.getHypervisor().getHostName();
197                 evacuateServer(rqstCtx, server, targetHostId);
198                 server.refreshAll();
199                 String hypervisorAfterEvacuate = server.getHypervisor().getHostName();
200                 logger.debug(
201                         "Hostname before evacuate: " + hypervisor + ", After evacuate: " + hypervisorAfterEvacuate);
202                 // check hypervisor host name after evacuate. If it is unchanged, the evacuate
203                 // failed.
204                 checkHypervisor(server, hypervisor, hypervisorAfterEvacuate);
205                 // check VM status after evacuate
206                 checkStatus(server);
207                 context.close();
208                 doSuccess(rqstCtx);
209                 ctx.setAttribute(EVACUATE_STATUS, "SUCCESS");
210                 // If a snapshot exists, do a rebuild to apply the latest snapshot to the
211                 // evacuated server.
212                 // This is the default behavior unless the optional parameter is set to FALSE.
213                 if (rebuildVm == null || !"false".equalsIgnoreCase(rebuildVm)) {
214                     List<Image> snapshots = server.getSnapshots();
215                     if (snapshots == null || snapshots.isEmpty()) {
216                         logger.debug("No snapshots available - skipping rebuild after evacuate");
217                     } else if (paImpl != null) {
218                         logger.debug("Executing a rebuild after evacuate");
219                         paImpl.rebuildServer(params, ctx);
220                         // Check error code for rebuild errors. Evacuate had set it to 200 after
221                         // a successful evacuate. Rebuild updates the error code.
222                         evacuateServerMapNestedSecond(server, rqstCtx, ctx, hypervisor, hypervisorAfterEvacuate);
223                     }
224                 }
225             }
226         } catch (ResourceNotFoundException e) {
227             msg = EELFResourceManager.format(Msg.SERVER_NOT_FOUND, e, vmUrl);
228             logger.error(msg);
229             metricsLogger.error(msg);
230             doFailure(rqstCtx, HttpStatus.NOT_FOUND_404, msg);
231         } catch (RequestFailedException e) {
232             logger.error("Request failed", e);
233             doFailure(rqstCtx, e.getStatus(), e.getMessage());
234         } catch (IOException | ZoneException e1) {
235             msg = EELFResourceManager.format(Msg.SERVER_OPERATION_EXCEPTION, e1, e1.getClass().getSimpleName(),
236                     Operation.EVACUATE_SERVICE.toString(), vmUrl, tenantName);
237             logger.error(msg, e1);
238             metricsLogger.error(msg, e1);
239             doFailure(rqstCtx, HttpStatus.INTERNAL_SERVER_ERROR_500, e1.getMessage());
240         } catch (Exception e1) {
241             msg = EELFResourceManager.format(Msg.SERVER_OPERATION_EXCEPTION, e1, e1.getClass().getSimpleName(),
242                     Operation.EVACUATE_SERVICE.toString(), vmUrl, tenantName);
243             logger.error(msg, e1);
244             metricsLogger.error(msg);
245             doFailure(rqstCtx, HttpStatus.INTERNAL_SERVER_ERROR_500, e1.getMessage());
246         }
247         return server;
248     }
249
250     private void evacuateServerMapNestedSecond(Server server, RequestContext rc, SvcLogicContext ctx, String hypervisor,
251             String hypervisorAfterEvacuate) {
252         String msg;
253         String rebuildErrorCode = ctx.getAttribute(org.onap.appc.Constants.ATTRIBUTE_ERROR_CODE);
254         if (rebuildErrorCode != null) {
255             try {
256                 int errorCode = Integer.parseInt(rebuildErrorCode);
257                 if (errorCode != HttpStatus.OK_200.getStatusCode()) {
258                     logger.debug("Rebuild after evacuate failed - error code=" + errorCode + ", message="
259                             + ctx.getAttribute(org.onap.appc.Constants.ATTRIBUTE_ERROR_MESSAGE));
260                     msg = EELFResourceManager.format(Msg.EVACUATE_SERVER_REBUILD_FAILED, server.getName(), hypervisor,
261                             hypervisorAfterEvacuate, ctx.getAttribute(org.onap.appc.Constants.ATTRIBUTE_ERROR_MESSAGE));
262                     logger.error(msg);
263                     metricsLogger.error(msg);
264                     ctx.setAttribute(EVACUATE_STATUS, "ERROR");
265                     // update error message while keeping the error code the
266                     // same as before
267                     doFailure(rc, HttpStatus.getHttpStatus(errorCode), msg);
268                 }
269             } catch (NumberFormatException e) {
270                 // ignore
271             }
272         }
273     }
274
275     private void checkHostStatus(Server server, String targetHostId, Context context)
276             throws ZoneException, RequestFailedException {
277         if (isComputeNodeDown(context, targetHostId)) {
278             String msg = EELFResourceManager.format(Msg.EVACUATE_SERVER_FAILED, server.getName(), server.getId(),
279                     "Target host " + targetHostId + " status is not UP/ENABLED");
280             logger.error(msg);
281             metricsLogger.error(msg);
282             throw new RequestFailedException(EVACUATE_SERVER, msg, HttpStatus.BAD_REQUEST_400, server);
283         }
284     }
285
286     private void checkHypervisor(Server server, String hypervisor, String hypervisorAfterEvacuate)
287             throws RequestFailedException {
288         if (hypervisor != null && hypervisor.equals(hypervisorAfterEvacuate)) {
289             String msg = EELFResourceManager.format(Msg.EVACUATE_SERVER_FAILED, server.getName(), server.getId(),
290                     "Hypervisor host " + hypervisor
291                             + " after evacuate is the same as before evacuate. Provider (ex. Openstack) recovery actions may be needed.");
292             logger.error(msg);
293             metricsLogger.error(msg);
294             throw new RequestFailedException(EVACUATE_SERVER, msg, HttpStatus.INTERNAL_SERVER_ERROR_500, server);
295         }
296     }
297
298     private void checkStatus(Server server) throws RequestFailedException {
299         if (server.getStatus() == Server.Status.ERROR) {
300             String msg = EELFResourceManager.format(Msg.EVACUATE_SERVER_FAILED, server.getName(), server.getId(),
301                     "VM is in ERROR state after evacuate. Provider (ex. Openstack) recovery actions may be needed.");
302             logger.error(msg);
303             metricsLogger.error(msg);
304             throw new RequestFailedException(EVACUATE_SERVER, msg, HttpStatus.INTERNAL_SERVER_ERROR_500, server);
305         }
306     }
307
308     /**
309      * Check if a Compute node is down.
310      * 
311      * This method attempts to find a given host in the list of hypervisors for a
312      * given context. The only case where a node is considered down is if a matching
313      * hypervisor is found and it's state and status are not UP/ENABLED.
314      * 
315      * @param context
316      *            The current context
317      * 
318      * @param host
319      *            The host name (short or fully qualified) of a compute node
320      * 
321      * @return true if the node is determined as down, false for all other cases
322      */
323     private boolean isComputeNodeDown(Context context, String host) throws ZoneException {
324         ComputeService service = context.getComputeService();
325         boolean nodeDown = false;
326         if (host != null && !host.isEmpty()) {
327             List<Hypervisor> hypervisors = service.getHypervisors();
328             logger.debug("List of Hypervisors retrieved: " + Arrays.toString(hypervisors.toArray()));
329             for (Hypervisor hv : hypervisors) {
330                 nodeDown = isNodeDown(host, nodeDown, hv);
331             }
332         }
333         return nodeDown;
334     }
335
336     private boolean isNodeDown(String host, boolean nodeDown, Hypervisor hv) {
337         if (isHostMatchesHypervisor(host, hv)) {
338             State hstate = hv.getState();
339             Status hstatus = hv.getStatus();
340             logger.debug("Host matching hypervisor: " + hv.getHostName() + ", State/Status: " + hstate.toString() + "/"
341                     + hstatus.toString());
342             if (hstate != State.UP || hstatus != Status.ENABLED) {
343                 return true;
344             }
345         }
346         return nodeDown;
347     }
348
349     private boolean isHostMatchesHypervisor(String host, Hypervisor hypervisor) {
350         return hypervisor.getHostName().startsWith(host);
351     }
352
353     @Override
354     protected ModelObject executeProviderOperation(Map<String, String> params, SvcLogicContext context)
355             throws APPCException {
356         setMDC(Operation.EVACUATE_SERVICE.toString(), "App-C IaaS Adapter:Evacuate", ADAPTER_NAME);
357         logOperation(Msg.EVACUATING_SERVER, params, context);
358         setTimeForMetricsLogger();
359         metricsLogger.info("Executing Provider Operation: Evacuate");
360         return evacuateServer(params, context);
361     }
362
363     private void setTimeForMetricsLogger() {
364         String timestamp = LoggingUtils.generateTimestampStr((new Date()).toInstant());
365         MDC.put(LoggingConstants.MDCKeys.BEGIN_TIMESTAMP, timestamp);
366         MDC.put(LoggingConstants.MDCKeys.END_TIMESTAMP, timestamp);
367         MDC.put(LoggingConstants.MDCKeys.ELAPSED_TIME, "0");
368         MDC.put(LoggingConstants.MDCKeys.STATUS_CODE, LoggingConstants.StatusCodes.COMPLETE);
369         MDC.put(LoggingConstants.MDCKeys.TARGET_ENTITY, "cdp");
370         MDC.put(LoggingConstants.MDCKeys.TARGET_SERVICE_NAME, "evacuate server");
371         MDC.put(LoggingConstants.MDCKeys.CLASS_NAME,
372                 "org.onap.appc.adapter.iaas.provider.operation.impl.EvacuateServer");
373     }
374
375     public void setProvideAdapterRef(ProviderAdapterImpl pai) {
376         paImpl = pai;
377     }
378 }