2 * ============LICENSE_START=======================================================
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
17 * http://www.apache.org/licenses/LICENSE-2.0
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.
25 * ============LICENSE_END=========================================================
28 package org.onap.appc.adapter.iaas.provider.operation.impl;
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;
63 import java.io.IOException;
64 import java.util.Arrays;
65 import java.util.Date;
66 import java.util.List;
68 import static org.onap.appc.adapter.utils.Constants.ADAPTER_NAME;
70 public class EvacuateServer extends ProviderServerOperation {
72 private static final String EVACUATE_STATUS = "EVACUATE_STATUS";
73 private static final String EVACUATE_SERVER = "Evacuate Server";
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;
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();
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.
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);
96 } catch (RequestFailedException e) {
97 // evacuate is a special case. If the server is still in a Pending state, we
99 // continue with evacuate
100 logger.info("Evacuate server - ignore RequestFailedException from waitForStateChange() ...", e);
102 setTimeForMetricsLogger();
105 evacuateServerNested(rc, service, server, provider, targetHost);
106 } catch (ZoneException e) {
107 msg = EELFResourceManager.format(Msg.EVACUATE_SERVER_FAILED, server.getName(), server.getId(),
109 logger.error(msg, e);
110 metricsLogger.error(msg);
111 throw new RequestFailedException(EVACUATE_SERVER, msg, HttpStatus.BAD_GATEWAY_502, server);
114 msg = EELFResourceManager.format(Msg.CONNECTION_FAILED, provider.getName(), service.getURL());
116 metricsLogger.error(msg);
117 throw new RequestFailedException(EVACUATE_SERVER, msg, HttpStatus.BAD_GATEWAY_502, server);
122 private void evacuateServerNested(RequestContext rcCtx, ComputeService svc, Server server, Provider provider,
123 String targetHost) throws ZoneException, RequestFailedException {
125 Context ctx = server.getContext();
126 while (rcCtx.attempt()) {
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);
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);
147 * @see org.onap.appc.adapter.iaas.ProviderAdapter#evacuateServer(java.util.Map,
148 * org.onap.ccsdk.sli.core.sli.SvcLogicContext)
150 private Server evacuateServer(Map<String, String> params, SvcLogicContext ctx) throws APPCException {
151 Server server = null;
152 RequestContext rc = new RequestContext(ctx);
154 setTimeForMetricsLogger();
156 ctx.setAttribute(EVACUATE_STATUS, "ERROR");
158 validateParametersExist(params, ProviderAdapter.PROPERTY_INSTANCE_URL,
159 ProviderAdapter.PROPERTY_PROVIDER_NAME);
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)) {
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());
177 private Server evacuateServerMapNestedFirst(Map<String, String> params, Server server, RequestContext rqstCtx,
178 SvcLogicContext ctx, VMURL vm, String vmUrl) throws APPCException {
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
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);
199 String hypervisorAfterEvacuate = server.getHypervisor().getHostName();
201 "Hostname before evacuate: " + hypervisor + ", After evacuate: " + hypervisorAfterEvacuate);
202 // check hypervisor host name after evacuate. If it is unchanged, the evacuate
204 checkHypervisor(server, hypervisor, hypervisorAfterEvacuate);
205 // check VM status after evacuate
209 ctx.setAttribute(EVACUATE_STATUS, "SUCCESS");
210 // If a snapshot exists, do a rebuild to apply the latest snapshot to the
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);
226 } catch (ResourceNotFoundException e) {
227 msg = EELFResourceManager.format(Msg.SERVER_NOT_FOUND, e, vmUrl);
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());
250 private void evacuateServerMapNestedSecond(Server server, RequestContext rc, SvcLogicContext ctx, String hypervisor,
251 String hypervisorAfterEvacuate) {
253 String rebuildErrorCode = ctx.getAttribute(org.onap.appc.Constants.ATTRIBUTE_ERROR_CODE);
254 if (rebuildErrorCode != null) {
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));
263 metricsLogger.error(msg);
264 ctx.setAttribute(EVACUATE_STATUS, "ERROR");
265 // update error message while keeping the error code the
267 doFailure(rc, HttpStatus.getHttpStatus(errorCode), msg);
269 } catch (NumberFormatException e) {
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");
281 metricsLogger.error(msg);
282 throw new RequestFailedException(EVACUATE_SERVER, msg, HttpStatus.BAD_REQUEST_400, server);
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.");
293 metricsLogger.error(msg);
294 throw new RequestFailedException(EVACUATE_SERVER, msg, HttpStatus.INTERNAL_SERVER_ERROR_500, server);
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.");
303 metricsLogger.error(msg);
304 throw new RequestFailedException(EVACUATE_SERVER, msg, HttpStatus.INTERNAL_SERVER_ERROR_500, server);
309 * Check if a Compute node is down.
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.
316 * The current context
319 * The host name (short or fully qualified) of a compute node
321 * @return true if the node is determined as down, false for all other cases
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);
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) {
349 private boolean isHostMatchesHypervisor(String host, Hypervisor hypervisor) {
350 return hypervisor.getHostName().startsWith(host);
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);
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");
375 public void setProvideAdapterRef(ProviderAdapterImpl pai) {