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