2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 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 * ECOMP is a trademark and service mark of AT&T Intellectual Property.
22 * ============LICENSE_END=========================================================
25 package org.onap.appc.adapter.iaas.provider.operation.impl;
27 import org.onap.appc.Constants;
28 import org.onap.appc.adapter.iaas.ProviderAdapter;
29 import org.onap.appc.adapter.iaas.impl.IdentityURL;
30 import org.onap.appc.adapter.iaas.impl.ProviderAdapterImpl;
31 import org.onap.appc.adapter.iaas.impl.RequestContext;
32 import org.onap.appc.adapter.iaas.impl.RequestFailedException;
33 import org.onap.appc.adapter.iaas.impl.VMURL;
34 import org.onap.appc.adapter.iaas.provider.operation.common.enums.Operation;
35 import org.onap.appc.adapter.iaas.provider.operation.impl.base.ProviderServerOperation;
36 import org.onap.appc.configuration.Configuration;
37 import org.onap.appc.configuration.ConfigurationFactory;
38 import org.onap.appc.exceptions.APPCException;
39 import org.onap.appc.i18n.Msg;
40 import com.att.cdp.exceptions.ContextConnectionException;
41 import com.att.cdp.exceptions.ResourceNotFoundException;
42 import com.att.cdp.exceptions.ZoneException;
43 import com.att.cdp.zones.ComputeService;
44 import com.att.cdp.zones.Context;
45 import com.att.cdp.zones.Provider;
46 import com.att.cdp.zones.model.Hypervisor;
47 import com.att.cdp.zones.model.Hypervisor.Status;
48 import com.att.cdp.zones.model.Hypervisor.State;
49 import com.att.cdp.zones.model.Image;
50 import com.att.cdp.zones.model.ModelObject;
51 import com.att.cdp.zones.model.Server;
52 import com.att.eelf.configuration.EELFLogger;
53 import com.att.eelf.configuration.EELFManager;
54 import com.att.eelf.i18n.EELFResourceManager;
55 import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
56 import org.glassfish.grizzly.http.util.HttpStatus;
58 import java.text.DateFormat;
59 import java.text.SimpleDateFormat;
60 import java.util.Arrays;
61 import java.util.Date;
62 import java.util.List;
64 import java.util.TimeZone;
65 import static org.onap.appc.adapter.utils.Constants.ADAPTER_NAME;
67 public class EvacuateServer extends ProviderServerOperation {
69 private static final EELFLogger logger = EELFManager.getInstance().getLogger(EvacuateServer.class);
70 private static EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger();
71 private static final Configuration configuration = ConfigurationFactory.getConfiguration();
72 private ProviderAdapterImpl paImpl = null;
75 private void evacuateServer(RequestContext rc, @SuppressWarnings("unused") Server server, String target_host)
76 throws ZoneException, RequestFailedException {
78 Context ctx = server.getContext();
79 Provider provider = ctx.getProvider();
80 ComputeService service = ctx.getComputeService();
83 * Pending is a bit of a special case. If we find the server is in a pending state, then the provider is in the
84 * process of changing state of the server. So, lets try to wait a little bit and see if the state settles down
85 * to one we can deal with. If not, then we have to fail the request.
88 if (server.getStatus().equals(Server.Status.PENDING)) {
89 waitForStateChange(rc, server, Server.Status.READY, Server.Status.RUNNING, Server.Status.ERROR,
90 Server.Status.SUSPENDED, Server.Status.PAUSED);
92 } catch (RequestFailedException e) {
93 // evacuate is a special case. If the server is still in a Pending state, we want to
94 // continue with evacuate
95 logger.info("Evacuate server - ignore RequestFailedException from waitForStateChange() ...");
98 SetTimeForMetricsLogger();
102 while (rc.attempt()) {
104 logger.debug("Calling CDP moveServer - server id = " + server.getId());
105 service.moveServer(server.getId(), target_host);
106 // Wait for completion, expecting the server to go to a non pending state
107 waitForStateChange(rc, server, Server.Status.READY, Server.Status.RUNNING, Server.Status.ERROR,
108 Server.Status.SUSPENDED, Server.Status.PAUSED);
110 } catch (ContextConnectionException e) {
111 msg = EELFResourceManager.format(Msg.CONNECTION_FAILED_RETRY, provider.getName(), service.getURL(),
112 ctx.getTenant().getName(), ctx.getTenant().getId(), e.getMessage(),
113 Long.toString(rc.getRetryDelay()), Integer.toString(rc.getAttempts()),
114 Integer.toString(rc.getRetryLimit()));
115 logger.error(msg, e);
116 metricsLogger.error(msg, e);
121 } catch (ZoneException e) {
122 msg = EELFResourceManager.format(Msg.EVACUATE_SERVER_FAILED, server.getName(), server.getId(),
125 metricsLogger.error(msg);
126 throw new RequestFailedException("Evacute Server", msg, HttpStatus.BAD_GATEWAY_502, server);
130 msg = EELFResourceManager.format(Msg.CONNECTION_FAILED, provider.getName(), service.getURL());
132 metricsLogger.error(msg);
133 throw new RequestFailedException("Evacuate Server", msg, HttpStatus.BAD_GATEWAY_502, server);
140 * @see org.onap.appc.adapter.iaas.ProviderAdapter#evacuateServer(java.util.Map,
141 * org.onap.ccsdk.sli.core.sli.SvcLogicContext)
143 private Server evacuateServer(Map<String, String> params, SvcLogicContext ctx) throws APPCException {
144 Server server = null;
145 RequestContext rc = new RequestContext(ctx);
148 SetTimeForMetricsLogger();
151 ctx.setAttribute("EVACUATE_STATUS", "ERROR");
153 validateParametersExist(params, ProviderAdapter.PROPERTY_INSTANCE_URL,
154 ProviderAdapter.PROPERTY_PROVIDER_NAME);
156 String appName = configuration.getProperty(Constants.PROPERTY_APPLICATION_NAME);
157 String vm_url = params.get(ProviderAdapter.PROPERTY_INSTANCE_URL);
158 VMURL vm = VMURL.parseURL(vm_url);
159 if (validateVM(rc, appName, vm_url, vm))
162 IdentityURL ident = IdentityURL.parseURL(params.get(ProviderAdapter.PROPERTY_IDENTITY_URL));
163 String identStr = (ident == null) ? null : ident.toString();
165 // retrieve the optional parameters
166 String rebuild_vm = params.get(ProviderAdapter.PROPERTY_REBUILD_VM);
167 String targethost_id = params.get(ProviderAdapter.PROPERTY_TARGETHOST_ID);
169 Context context = null;
171 context = getContext(rc, vm_url, identStr);
172 if (context != null) {
174 server = lookupServer(rc, context, vm.getServerId());
175 logger.debug(Msg.SERVER_FOUND, vm_url, context.getTenantName(), server.getStatus().toString());
177 // check target host status
178 if (isComputeNodeDown(context, targethost_id)) {
179 msg = EELFResourceManager.format(Msg.EVACUATE_SERVER_FAILED, server.getName(), server.getId(),
180 "Target host " + targethost_id + " status is not UP/ENABLED");
182 metricsLogger.error(msg);
183 throw new RequestFailedException("Evacuate Server", msg, HttpStatus.BAD_REQUEST_400, server);
186 // save hypervisor name before evacuate
187 String hypervisor = server.getHypervisor().getHostName();
189 evacuateServer(rc, server, targethost_id);
192 String hypervisor_after_evacuate = server.getHypervisor().getHostName();
193 logger.debug("Hostname before evacuate: " + hypervisor + ", After evacuate: "
194 + hypervisor_after_evacuate);
196 // check hypervisor host name after evacuate. If it is unchanged, the evacuate
198 if ((hypervisor != null) && (hypervisor.equals(hypervisor_after_evacuate))) {
199 msg = EELFResourceManager.format(Msg.EVACUATE_SERVER_FAILED, server.getName(), server.getId(),
200 "Hypervisor host " + hypervisor
201 + " after evacuate is the same as before evacuate. Provider (ex. Openstack) recovery actions may be needed.");
203 metricsLogger.error(msg);
204 throw new RequestFailedException("Evacuate Server", msg, HttpStatus.INTERNAL_SERVER_ERROR_500,
209 // check VM status after evacuate
210 if (server.getStatus() == Server.Status.ERROR) {
211 msg = EELFResourceManager.format(Msg.EVACUATE_SERVER_FAILED, server.getName(), server.getId(),
212 "VM is in ERROR state after evacuate. Provider (ex. Openstack) recovery actions may be needed.");
214 metricsLogger.error(msg);
215 throw new RequestFailedException("Evacuate Server", msg, HttpStatus.INTERNAL_SERVER_ERROR_500,
221 ctx.setAttribute("EVACUATE_STATUS", "SUCCESS");
223 // If a snapshot exists, do a rebuild to apply the latest snapshot to the
225 // This is the default behavior unless the optional parameter is set to FALSE.
226 if ((rebuild_vm == null) || !(rebuild_vm.equalsIgnoreCase("false"))) {
227 List<Image> snapshots = server.getSnapshots();
228 if (snapshots == null || snapshots.isEmpty()) {
229 logger.debug("No snapshots available - skipping rebuild after evacuate");
230 } else if (paImpl != null) {
231 logger.debug("Executing a rebuild after evacuate");
232 paImpl.rebuildServer(params, ctx);
233 // Check error code for rebuild errors. Evacuate had set it to 200 after
234 // a successful evacuate. Rebuild updates the error code.
235 String rebuildErrorCode =
236 ctx.getAttribute(org.onap.appc.Constants.ATTRIBUTE_ERROR_CODE);
237 if (rebuildErrorCode != null) {
239 int error_code = Integer.parseInt(rebuildErrorCode);
240 if (error_code != HttpStatus.OK_200.getStatusCode()) {
241 logger.debug("Rebuild after evacuate failed - error code=" + error_code
242 + ", message=" + ctx.getAttribute(
243 org.onap.appc.Constants.ATTRIBUTE_ERROR_MESSAGE));
244 msg = EELFResourceManager.format(Msg.EVACUATE_SERVER_REBUILD_FAILED,
245 server.getName(), hypervisor, hypervisor_after_evacuate,
246 ctx.getAttribute(org.onap.appc.Constants.ATTRIBUTE_ERROR_MESSAGE));
248 metricsLogger.error(msg);
249 ctx.setAttribute("EVACUATE_STATUS", "ERROR");
250 // update error message while keeping the error code the
252 doFailure(rc, HttpStatus.getHttpStatus(error_code), msg);
254 } catch (NumberFormatException e) {
262 } catch (ResourceNotFoundException e) {
263 msg = EELFResourceManager.format(Msg.SERVER_NOT_FOUND, e, vm_url);
265 metricsLogger.error(msg);
266 doFailure(rc, HttpStatus.NOT_FOUND_404, msg);
267 } catch (RequestFailedException e) {
268 doFailure(rc, e.getStatus(), e.getMessage());
269 } catch (Exception e1) {
270 msg = EELFResourceManager.format(Msg.SERVER_OPERATION_EXCEPTION, e1, e1.getClass().getSimpleName(),
271 Operation.EVACUATE_SERVICE.toString(), vm_url,
272 context == null ? "Unknown" : context.getTenantName());
273 logger.error(msg, e1);
274 metricsLogger.error(msg, e1);
275 doFailure(rc, HttpStatus.INTERNAL_SERVER_ERROR_500, msg);
277 } catch (RequestFailedException e) {
278 msg = EELFResourceManager.format(Msg.EVACUATE_SERVER_FAILED, "n/a", "n/a", e.getMessage());
280 metricsLogger.error(msg);
281 doFailure(rc, e.getStatus(), e.getMessage());
288 * Check if a Compute node is down.
290 * This method attempts to find a given host in the list of hypervisors for a given context. The only case where a
291 * node is considered down is if a matching hypervisor is found and it's state and status are not UP/ENABLED.
293 * @param context The current context
295 * @param host The host name (short or fully qualified) of a compute node
297 * @return true if the node is determined as down, false for all other cases
299 private boolean isComputeNodeDown(Context context, String host) throws ZoneException {
300 ComputeService service = context.getComputeService();
301 boolean node_down = false;
303 // Check host status. A node is considered down only if a matching target host is
304 // found and it's state/status is not UP/ENABLED.
305 if ((host != null) && !(host.isEmpty())) {
306 List<Hypervisor> hypervisors = service.getHypervisors();
307 logger.debug("List of Hypervisors retrieved: " + Arrays.toString(hypervisors.toArray()));
308 for (Hypervisor h : hypervisors) {
309 if (h.getHostName().startsWith(host)) {
310 // host matches one of the hypervisors
311 State hstate = h.getState();
312 Status hstatus = h.getStatus();
313 logger.debug("Host matching hypervisor: " + h.getHostName() + ", State/Status: " + hstate.toString()
314 + "/" + hstatus.toString());
315 if (hstate != State.UP || hstatus != Status.ENABLED) {
325 protected ModelObject executeProviderOperation(Map<String, String> params, SvcLogicContext context)
326 throws APPCException {
327 setMDC(Operation.EVACUATE_SERVICE.toString(), "App-C IaaS Adapter:Evacuate", ADAPTER_NAME);
328 logOperation(Msg.EVACUATING_SERVER, params, context);
330 SetTimeForMetricsLogger();
332 metricsLogger.info("Executing Provider Operation: Evacuate");
333 return evacuateServer(params, context);
336 private void SetTimeForMetricsLogger() {
337 long startTime = System.currentTimeMillis();
338 TimeZone tz = TimeZone.getTimeZone("UTC");
339 DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
341 long endTime = System.currentTimeMillis();
342 long duration = endTime - startTime;
343 String durationStr = String.valueOf(duration);
344 String endTimeStrUTC = df.format(new Date());
345 MDC.put("EndTimestamp", endTimeStrUTC);
346 MDC.put("ElapsedTime", durationStr);
347 MDC.put("TargetEntity", "cdp");
348 MDC.put("TargetServiceName", "evacuate server");
349 MDC.put("ClassName", "org.onap.appc.adapter.iaas.provider.operation.impl.EvacuateServer");
352 public void setProvideAdapterRef(ProviderAdapterImpl pai) {