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 com.att.cdp.exceptions.ContextConnectionException;
40 import com.att.cdp.exceptions.ResourceNotFoundException;
41 import com.att.cdp.exceptions.ZoneException;
42 import com.att.cdp.zones.ComputeService;
43 import com.att.cdp.zones.Context;
44 import com.att.cdp.zones.Provider;
45 import com.att.cdp.zones.model.Hypervisor;
46 import com.att.cdp.zones.model.Hypervisor.Status;
47 import com.att.cdp.zones.model.Hypervisor.State;
48 import com.att.cdp.zones.model.Image;
49 import com.att.cdp.zones.model.ModelObject;
50 import com.att.cdp.zones.model.Server;
51 import com.att.eelf.configuration.EELFLogger;
52 import com.att.eelf.configuration.EELFManager;
53 import com.att.eelf.i18n.EELFResourceManager;
54 import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
55 import org.glassfish.grizzly.http.util.HttpStatus;
58 import java.io.IOException;
59 import java.text.DateFormat;
60 import java.text.SimpleDateFormat;
61 import java.util.Arrays;
62 import java.util.Date;
63 import java.util.List;
65 import java.util.TimeZone;
66 import static org.onap.appc.adapter.utils.Constants.ADAPTER_NAME;
68 public class EvacuateServer extends ProviderServerOperation {
70 private static final String EVACUATE_STATUS = "EVACUATE_STATUS";
71 private static final String EVACUATE_SERVER = "Evacuate Server";
73 private static final EELFLogger logger = EELFManager.getInstance().getLogger(EvacuateServer.class);
74 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 {
82 Context ctx = server.getContext();
83 Provider provider = ctx.getProvider();
84 ComputeService service = ctx.getComputeService();
87 * Pending is a bit of a special case. If we find the server is in a pending state, then the provider is in the
88 * process of changing state of the server. So, lets try to wait a little bit and see if the state settles down
89 * to one we 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 want to
98 // continue with evacuate
99 logger.info("Evacuate server - ignore RequestFailedException from waitForStateChange() ..." ,e);
102 setTimeForMetricsLogger();
106 evacuateServerNested(rc,service,server,provider,targetHost);
107 } catch (ZoneException e) {
108 msg = EELFResourceManager.format(Msg.EVACUATE_SERVER_FAILED, server.getName(), server.getId(),
110 logger.error(msg, e);
111 metricsLogger.error(msg);
112 throw new RequestFailedException(EVACUATE_SERVER, msg, HttpStatus.BAD_GATEWAY_502, server);
116 msg = EELFResourceManager.format(Msg.CONNECTION_FAILED, provider.getName(), service.getURL());
118 metricsLogger.error(msg);
119 throw new RequestFailedException(EVACUATE_SERVER, msg, HttpStatus.BAD_GATEWAY_502, server);
124 private void evacuateServerNested(RequestContext rcCtx,ComputeService svc,Server server,Provider provider, String targetHost)
125 throws ZoneException, RequestFailedException {
127 Context ctx = server.getContext();
129 while (rcCtx.attempt()) {
131 logger.debug("Calling CDP moveServer - server id = " + server.getId());
132 svc.moveServer(server.getId(), targetHost);
133 // Wait for completion, expecting the server to go to a non pending state
134 waitForStateChange(rcCtx, server, Server.Status.READY, Server.Status.RUNNING, Server.Status.ERROR,
135 Server.Status.SUSPENDED, Server.Status.PAUSED);
137 } catch (ContextConnectionException e) {
138 msg = EELFResourceManager.format(Msg.CONNECTION_FAILED_RETRY, provider.getName(), svc.getURL(),
139 ctx.getTenant().getName(), ctx.getTenant().getId(), e.getMessage(),
140 Long.toString(rcCtx.getRetryDelay()), Integer.toString(rcCtx.getAttempts()),
141 Integer.toString(rcCtx.getRetryLimit()));
142 logger.error(msg, e);
143 metricsLogger.error(msg, e);
149 * @see org.onap.appc.adapter.iaas.ProviderAdapter#evacuateServer(java.util.Map,
150 * org.onap.ccsdk.sli.core.sli.SvcLogicContext)
152 private Server evacuateServer(Map<String, String> params, SvcLogicContext ctx) throws APPCException {
153 Server server = null;
154 RequestContext rc = new RequestContext(ctx);
157 setTimeForMetricsLogger();
160 ctx.setAttribute(EVACUATE_STATUS, "ERROR");
162 validateParametersExist(params, ProviderAdapter.PROPERTY_INSTANCE_URL,
163 ProviderAdapter.PROPERTY_PROVIDER_NAME);
165 String appName = configuration.getProperty(Constants.PROPERTY_APPLICATION_NAME);
166 String vmUrl = params.get(ProviderAdapter.PROPERTY_INSTANCE_URL);
167 VMURL vm = VMURL.parseURL(vmUrl);
169 if (validateVM(rc, appName, vmUrl, vm)) {
173 server = evacuateServerMapNestedFirst(params, server, rc, ctx, vm, vmUrl);
175 } catch (RequestFailedException e) {
176 msg = EELFResourceManager.format(Msg.EVACUATE_SERVER_FAILED, "n/a", "n/a", e.getMessage());
177 logger.error(msg, e);
178 metricsLogger.error(msg);
179 doFailure(rc, e.getStatus(), e.getMessage());
185 private Server evacuateServerMapNestedFirst(Map<String, String> params, Server server, RequestContext rqstCtx, SvcLogicContext ctx,
186 VMURL vm, String vmUrl)
187 throws APPCException {
192 IdentityURL ident = IdentityURL.parseURL(params.get(ProviderAdapter.PROPERTY_IDENTITY_URL));
193 String identStr = (ident == null) ? null : ident.toString();
194 // retrieve the optional parameters
195 String rebuildVm = params.get(ProviderAdapter.PROPERTY_REBUILD_VM);
196 String targetHostId = params.get(ProviderAdapter.PROPERTY_TARGETHOST_ID);
197 String tenantName = "Unknown";//to be used also in case of exception
199 context = getContext(rqstCtx, vmUrl, identStr);
200 if (context != null) {
201 tenantName = context.getTenantName();//this variable also is used in case of exception
202 server = lookupServer(rqstCtx, context, vm.getServerId());
204 logger.debug(Msg.SERVER_FOUND, vmUrl, tenantName, server.getStatus().toString());
206 // check target host status
207 checkHostStatus(server, targetHostId, context);
209 // save hypervisor name before evacuate
210 String hypervisor = server.getHypervisor().getHostName();
212 evacuateServer(rqstCtx, server, targetHostId);
215 String hypervisorAfterEvacuate = server.getHypervisor().getHostName();
216 logger.debug("Hostname before evacuate: " + hypervisor + ", After evacuate: " + hypervisorAfterEvacuate);
218 // check hypervisor host name after evacuate. If it is unchanged, the evacuate
220 checkHypervisor(server, hypervisor, hypervisorAfterEvacuate);
222 // check VM status after evacuate
226 ctx.setAttribute(EVACUATE_STATUS, "SUCCESS");
228 // If a snapshot exists, do a rebuild to apply the latest snapshot to the evacuated server.
229 // This is the default behavior unless the optional parameter is set to FALSE.
230 if (rebuildVm == null || !"false".equalsIgnoreCase(rebuildVm)) {
231 List<Image> snapshots = server.getSnapshots();
232 if (snapshots == null || snapshots.isEmpty()) {
233 logger.debug("No snapshots available - skipping rebuild after evacuate");
234 } else if (paImpl != null) {
235 logger.debug("Executing a rebuild after evacuate");
236 paImpl.rebuildServer(params, ctx);
237 // Check error code for rebuild errors. Evacuate had set it to 200 after
238 // a successful evacuate. Rebuild updates the error code.
239 evacuateServerMapNestedSecond(server, rqstCtx, ctx, hypervisor, hypervisorAfterEvacuate);
244 } catch (ResourceNotFoundException e) {
245 msg = EELFResourceManager.format(Msg.SERVER_NOT_FOUND, e, vmUrl);
247 metricsLogger.error(msg);
248 doFailure(rqstCtx, HttpStatus.NOT_FOUND_404, msg);
249 } catch (RequestFailedException e) {
250 logger.error("Request failed", e);
251 doFailure(rqstCtx, e.getStatus(), e.getMessage());
252 } catch (IOException | ZoneException e1) {
253 msg = EELFResourceManager.format(Msg.SERVER_OPERATION_EXCEPTION, e1, e1.getClass().getSimpleName(),
254 Operation.EVACUATE_SERVICE.toString(), vmUrl, tenantName);
255 logger.error(msg, e1);
256 metricsLogger.error(msg, e1);
257 doFailure(rqstCtx, HttpStatus.INTERNAL_SERVER_ERROR_500, msg);
262 private void evacuateServerMapNestedSecond(Server server,RequestContext rc, SvcLogicContext ctx,
263 String hypervisor,String hypervisorAfterEvacuate) {
266 String rebuildErrorCode = ctx.getAttribute(org.onap.appc.Constants.ATTRIBUTE_ERROR_CODE);
268 if (rebuildErrorCode != null) {
270 int errorCode = Integer.parseInt(rebuildErrorCode);
271 if (errorCode != HttpStatus.OK_200.getStatusCode()) {
272 logger.debug("Rebuild after evacuate failed - error code=" + errorCode
273 + ", message=" + ctx.getAttribute(org.onap.appc.Constants.ATTRIBUTE_ERROR_MESSAGE));
274 msg = EELFResourceManager.format(Msg.EVACUATE_SERVER_REBUILD_FAILED,
275 server.getName(), hypervisor, hypervisorAfterEvacuate,
276 ctx.getAttribute(org.onap.appc.Constants.ATTRIBUTE_ERROR_MESSAGE));
278 metricsLogger.error(msg);
279 ctx.setAttribute(EVACUATE_STATUS, "ERROR");
280 // update error message while keeping the error code the
282 doFailure(rc, HttpStatus.getHttpStatus(errorCode), msg);
284 } catch (NumberFormatException e) {
290 private void checkHostStatus(Server server, String targetHostId, Context context)
291 throws ZoneException, RequestFailedException {
292 if (isComputeNodeDown(context, targetHostId)) {
293 String msg = EELFResourceManager.format(Msg.EVACUATE_SERVER_FAILED, server.getName(), server.getId(),
294 "Target host " + targetHostId + " status is not UP/ENABLED");
296 metricsLogger.error(msg);
297 throw new RequestFailedException(EVACUATE_SERVER, msg, HttpStatus.BAD_REQUEST_400, server);
301 private void checkHypervisor(Server server, String hypervisor, String hypervisorAfterEvacuate)
302 throws RequestFailedException {
303 if (hypervisor != null && hypervisor.equals(hypervisorAfterEvacuate)) {
304 String msg = EELFResourceManager.format(Msg.EVACUATE_SERVER_FAILED, server.getName(), server.getId(),
305 "Hypervisor host " + hypervisor
306 + " after evacuate is the same as before evacuate. Provider (ex. Openstack) recovery actions may be needed.");
308 metricsLogger.error(msg);
309 throw new RequestFailedException(EVACUATE_SERVER, msg, HttpStatus.INTERNAL_SERVER_ERROR_500, server);
313 private void checkStatus(Server server) throws RequestFailedException {
314 if (server.getStatus() == Server.Status.ERROR) {
315 String msg = EELFResourceManager.format(Msg.EVACUATE_SERVER_FAILED, server.getName(), server.getId(),
316 "VM is in ERROR state after evacuate. Provider (ex. Openstack) recovery actions may be needed.");
318 metricsLogger.error(msg);
319 throw new RequestFailedException(EVACUATE_SERVER, msg, HttpStatus.INTERNAL_SERVER_ERROR_500, server);
324 * Check if a Compute node is down.
326 * This method attempts to find a given host in the list of hypervisors for a given context. The only case where a
327 * node is considered down is if a matching hypervisor is found and it's state and status are not UP/ENABLED.
329 * @param context The current context
331 * @param host The host name (short or fully qualified) of a compute node
333 * @return true if the node is determined as down, false for all other cases
335 private boolean isComputeNodeDown(Context context, String host) throws ZoneException {
336 ComputeService service = context.getComputeService();
337 boolean nodeDown = false;
339 if (host != null && ! host.isEmpty()) {
340 List<Hypervisor> hypervisors = service.getHypervisors();
341 logger.debug("List of Hypervisors retrieved: " + Arrays.toString(hypervisors.toArray()));
342 for (Hypervisor hv : hypervisors) {
343 nodeDown = isNodeDown(host, nodeDown, hv);
349 private boolean isNodeDown(String host, boolean nodeDown, Hypervisor hv) {
350 if (isHostMatchesHypervisor(host, hv)) {
351 State hstate = hv.getState();
352 Status hstatus = hv.getStatus();
353 logger.debug("Host matching hypervisor: " + hv.getHostName() + ", State/Status: " + hstate.toString()
354 + "/" + hstatus.toString());
355 if (hstate != State.UP || hstatus != Status.ENABLED) {
362 private boolean isHostMatchesHypervisor(String host, Hypervisor hypervisor) {
363 return hypervisor.getHostName().startsWith(host);
367 protected ModelObject executeProviderOperation(Map<String, String> params, SvcLogicContext context)
368 throws APPCException {
369 setMDC(Operation.EVACUATE_SERVICE.toString(), "App-C IaaS Adapter:Evacuate", ADAPTER_NAME);
370 logOperation(Msg.EVACUATING_SERVER, params, context);
372 setTimeForMetricsLogger();
374 metricsLogger.info("Executing Provider Operation: Evacuate");
375 return evacuateServer(params, context);
378 private void setTimeForMetricsLogger() {
379 long startTime = System.currentTimeMillis();
380 TimeZone tz = TimeZone.getTimeZone("UTC");
381 DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
383 long endTime = System.currentTimeMillis();
384 long duration = endTime - startTime;
385 String durationStr = String.valueOf(duration);
386 String endTimeStrUTC = df.format(new Date());
387 MDC.put("EndTimestamp", endTimeStrUTC);
388 MDC.put("ElapsedTime", durationStr);
389 MDC.put("TargetEntity", "cdp");
390 MDC.put("TargetServiceName", "evacuate server");
391 MDC.put("ClassName", "org.onap.appc.adapter.iaas.provider.operation.impl.EvacuateServer");
394 public void setProvideAdapterRef(ProviderAdapterImpl pai) {