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();
127 while (rcCtx.attempt()) {
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);
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);
148 * @see org.onap.appc.adapter.iaas.ProviderAdapter#evacuateServer(java.util.Map,
149 * org.onap.ccsdk.sli.core.sli.SvcLogicContext)
151 private Server evacuateServer(Map<String, String> params, SvcLogicContext ctx) throws APPCException {
152 Server server = null;
153 RequestContext rc = new RequestContext(ctx);
155 setTimeForMetricsLogger();
157 ctx.setAttribute(EVACUATE_STATUS, "ERROR");
159 validateParametersExist(params, ProviderAdapter.PROPERTY_INSTANCE_URL,
160 ProviderAdapter.PROPERTY_PROVIDER_NAME);
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)) {
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());
178 private Server evacuateServerMapNestedFirst(Map<String, String> params, Server server, RequestContext rqstCtx,
179 SvcLogicContext ctx, VMURL vm, String vmUrl) throws APPCException {
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
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);
200 String hypervisorAfterEvacuate = server.getHypervisor().getHostName();
202 "Hostname before evacuate: " + hypervisor + ", After evacuate: " + hypervisorAfterEvacuate);
203 // check hypervisor host name after evacuate. If it is unchanged, the evacuate
205 checkHypervisor(server, hypervisor, hypervisorAfterEvacuate);
206 // check VM status after evacuate
210 ctx.setAttribute(EVACUATE_STATUS, "SUCCESS");
211 // If a snapshot exists, do a rebuild to apply the latest snapshot to the
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);
227 } catch (ResourceNotFoundException e) {
228 msg = EELFResourceManager.format(Msg.SERVER_NOT_FOUND, e, vmUrl);
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());
251 private void evacuateServerMapNestedSecond(Server server, RequestContext rc, SvcLogicContext ctx, String hypervisor,
252 String hypervisorAfterEvacuate) {
254 String rebuildErrorCode = ctx.getAttribute(org.onap.appc.Constants.ATTRIBUTE_ERROR_CODE);
255 if (rebuildErrorCode != null) {
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));
264 metricsLogger.error(msg);
265 ctx.setAttribute(EVACUATE_STATUS, "ERROR");
266 // update error message while keeping the error code the
268 doFailure(rc, HttpStatus.getHttpStatus(errorCode), msg);
270 } catch (NumberFormatException e) {
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");
282 metricsLogger.error(msg);
283 throw new RequestFailedException(EVACUATE_SERVER, msg, HttpStatus.BAD_REQUEST_400, server);
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.");
294 metricsLogger.error(msg);
295 throw new RequestFailedException(EVACUATE_SERVER, msg, HttpStatus.INTERNAL_SERVER_ERROR_500, server);
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.");
304 metricsLogger.error(msg);
305 throw new RequestFailedException(EVACUATE_SERVER, msg, HttpStatus.INTERNAL_SERVER_ERROR_500, server);
310 * Check if a Compute node is down.
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.
317 * The current context
320 * The host name (short or fully qualified) of a compute node
322 * @return true if the node is determined as down, false for all other cases
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);
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) {
350 private boolean isHostMatchesHypervisor(String host, Hypervisor hypervisor) {
351 return hypervisor.getHostName().startsWith(host);
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);
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");
376 public void setProvideAdapterRef(ProviderAdapterImpl pai) {