2 * ============LICENSE_START=======================================================
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
13 * http://www.apache.org/licenses/LICENSE-2.0
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.
21 * ============LICENSE_END=========================================================
24 package org.onap.appc.adapter.iaas.provider.operation.impl;
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;
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;
66 import java.util.TimeZone;
67 import static org.onap.appc.adapter.utils.Constants.ADAPTER_NAME;
69 public class EvacuateServer extends ProviderServerOperation {
71 private static final String EVACUATE_STATUS = "EVACUATE_STATUS";
72 private static final String EVACUATE_SERVER = "Evacuate Server";
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;
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();
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.
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);
95 } catch (RequestFailedException e) {
96 // evacuate is a special case. If the server is still in a Pending state, we
98 // continue with evacuate
99 logger.info("Evacuate server - ignore RequestFailedException from waitForStateChange() ...", e);
101 setTimeForMetricsLogger();
104 evacuateServerNested(rc, service, server, provider, targetHost);
105 } catch (ZoneException e) {
106 msg = EELFResourceManager.format(Msg.EVACUATE_SERVER_FAILED, server.getName(), server.getId(),
108 logger.error(msg, e);
109 metricsLogger.error(msg);
110 throw new RequestFailedException(EVACUATE_SERVER, msg, HttpStatus.BAD_GATEWAY_502, server);
113 msg = EELFResourceManager.format(Msg.CONNECTION_FAILED, provider.getName(), service.getURL());
115 metricsLogger.error(msg);
116 throw new RequestFailedException(EVACUATE_SERVER, msg, HttpStatus.BAD_GATEWAY_502, server);
121 private void evacuateServerNested(RequestContext rcCtx, ComputeService svc, Server server, Provider provider,
122 String targetHost) throws ZoneException, RequestFailedException {
124 Context ctx = server.getContext();
125 while (rcCtx.attempt()) {
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);
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);
146 * @see org.onap.appc.adapter.iaas.ProviderAdapter#evacuateServer(java.util.Map,
147 * org.onap.ccsdk.sli.core.sli.SvcLogicContext)
149 private Server evacuateServer(Map<String, String> params, SvcLogicContext ctx) throws APPCException {
150 Server server = null;
151 RequestContext rc = new RequestContext(ctx);
153 setTimeForMetricsLogger();
155 ctx.setAttribute(EVACUATE_STATUS, "ERROR");
157 validateParametersExist(params, ProviderAdapter.PROPERTY_INSTANCE_URL,
158 ProviderAdapter.PROPERTY_PROVIDER_NAME);
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)) {
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());
176 private Server evacuateServerMapNestedFirst(Map<String, String> params, Server server, RequestContext rqstCtx,
177 SvcLogicContext ctx, VMURL vm, String vmUrl) throws APPCException {
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
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);
198 String hypervisorAfterEvacuate = server.getHypervisor().getHostName();
200 "Hostname before evacuate: " + hypervisor + ", After evacuate: " + hypervisorAfterEvacuate);
201 // check hypervisor host name after evacuate. If it is unchanged, the evacuate
203 checkHypervisor(server, hypervisor, hypervisorAfterEvacuate);
204 // check VM status after evacuate
208 ctx.setAttribute(EVACUATE_STATUS, "SUCCESS");
209 // If a snapshot exists, do a rebuild to apply the latest snapshot to the
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);
225 } catch (ResourceNotFoundException e) {
226 msg = EELFResourceManager.format(Msg.SERVER_NOT_FOUND, e, vmUrl);
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());
249 private void evacuateServerMapNestedSecond(Server server, RequestContext rc, SvcLogicContext ctx, String hypervisor,
250 String hypervisorAfterEvacuate) {
252 String rebuildErrorCode = ctx.getAttribute(org.onap.appc.Constants.ATTRIBUTE_ERROR_CODE);
253 if (rebuildErrorCode != null) {
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));
262 metricsLogger.error(msg);
263 ctx.setAttribute(EVACUATE_STATUS, "ERROR");
264 // update error message while keeping the error code the
266 doFailure(rc, HttpStatus.getHttpStatus(errorCode), msg);
268 } catch (NumberFormatException e) {
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");
280 metricsLogger.error(msg);
281 throw new RequestFailedException(EVACUATE_SERVER, msg, HttpStatus.BAD_REQUEST_400, server);
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.");
292 metricsLogger.error(msg);
293 throw new RequestFailedException(EVACUATE_SERVER, msg, HttpStatus.INTERNAL_SERVER_ERROR_500, server);
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.");
302 metricsLogger.error(msg);
303 throw new RequestFailedException(EVACUATE_SERVER, msg, HttpStatus.INTERNAL_SERVER_ERROR_500, server);
308 * Check if a Compute node is down.
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.
315 * The current context
318 * The host name (short or fully qualified) of a compute node
320 * @return true if the node is determined as down, false for all other cases
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);
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) {
348 private boolean isHostMatchesHypervisor(String host, Hypervisor hypervisor) {
349 return hypervisor.getHostName().startsWith(host);
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);
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");
374 public void setProvideAdapterRef(ProviderAdapterImpl pai) {