2  * ============LICENSE_START=======================================================
 
   4  * ================================================================================
 
   5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
 
   6  * Copyright (C) 2017 Amdocs
 
   7  * ================================================================================
 
   8  * Licensed under the Apache License, Version 2.0 (the "License");
 
   9  * you may not use this file except in compliance with the License.
 
  10  * You may obtain a copy of the License at
 
  12  *      http://www.apache.org/licenses/LICENSE-2.0
 
  14  * Unless required by applicable law or agreed to in writing, software
 
  15  * distributed under the License is distributed on an "AS IS" BASIS,
 
  16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 
  17  * See the License for the specific language governing permissions and
 
  18  * limitations under the License.
 
  19  * ============LICENSE_END=========================================================
 
  20  * ECOMP is a trademark and service mark of AT&T Intellectual Property.
 
  23 package org.openecomp.appc.adapter.iaas.provider.operation.impl;
 
  25 import org.openecomp.appc.Constants;
 
  26 import org.openecomp.appc.adapter.iaas.ProviderAdapter;
 
  27 import org.openecomp.appc.adapter.iaas.impl.IdentityURL;
 
  28 import org.openecomp.appc.adapter.iaas.impl.ProviderAdapterImpl;
 
  29 import org.openecomp.appc.adapter.iaas.impl.RequestContext;
 
  30 import org.openecomp.appc.adapter.iaas.impl.RequestFailedException;
 
  31 import org.openecomp.appc.adapter.iaas.impl.VMURL;
 
  32 import org.openecomp.appc.adapter.iaas.provider.operation.common.enums.Operation;
 
  33 import org.openecomp.appc.adapter.iaas.provider.operation.impl.base.ProviderServerOperation;
 
  34 import org.openecomp.appc.configuration.Configuration;
 
  35 import org.openecomp.appc.configuration.ConfigurationFactory;
 
  36 import org.openecomp.appc.exceptions.APPCException;
 
  37 import org.openecomp.appc.i18n.Msg;
 
  38 import com.att.cdp.exceptions.ContextConnectionException;
 
  39 import com.att.cdp.exceptions.ResourceNotFoundException;
 
  40 import com.att.cdp.exceptions.ZoneException;
 
  41 import com.att.cdp.zones.ComputeService;
 
  42 import com.att.cdp.zones.Context;
 
  43 import com.att.cdp.zones.Provider;
 
  44 import com.att.cdp.zones.model.Hypervisor;
 
  45 import com.att.cdp.zones.model.Hypervisor.Status;
 
  46 import com.att.cdp.zones.model.Hypervisor.State;
 
  47 import com.att.cdp.zones.model.Image;
 
  48 import com.att.cdp.zones.model.ModelObject;
 
  49 import com.att.cdp.zones.model.Server;
 
  50 import com.att.eelf.configuration.EELFLogger;
 
  51 import com.att.eelf.configuration.EELFManager;
 
  52 import com.att.eelf.i18n.EELFResourceManager;
 
  53 import org.openecomp.sdnc.sli.SvcLogicContext;
 
  54 import org.glassfish.grizzly.http.util.HttpStatus;
 
  57 import java.text.DateFormat;
 
  58 import java.text.SimpleDateFormat;
 
  59 import java.util.Arrays;
 
  60 import java.util.Date;
 
  61 import java.util.List;
 
  63 import java.util.TimeZone;
 
  65 import static org.openecomp.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) 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, Server.Status.SUSPENDED, Server.Status.PAUSED);
 
  91         } catch (RequestFailedException e) {
 
  92                 // evacuate is a special case. If the server is still in a Pending state, we want to continue with evacuate
 
  93                 logger.info("Evacuate server - ignore RequestFailedException from waitForStateChange() ...");
 
  97          * Set Time for Metrics Logger
 
  99         long startTime = System.currentTimeMillis();
 
 100         TimeZone tz = TimeZone.getTimeZone("UTC");
 
 101         DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
 
 103         String startTimeStr = df.format(new Date());
 
 104         long endTime = System.currentTimeMillis();
 
 105         long duration = endTime - startTime;
 
 106         String endTimeStr = String.valueOf(endTime);
 
 107         String durationStr = String.valueOf(duration);
 
 108         String endTimeStrUTC = df.format(new Date());
 
 109         MDC.put("EndTimestamp", endTimeStrUTC);
 
 110         MDC.put("ElapsedTime", durationStr);
 
 111         MDC.put("TargetEntity", "cdp");
 
 112         MDC.put("TargetServiceName", "evacuate server");
 
 113         MDC.put("ClassName", "org.openecomp.appc.adapter.iaas.provider.operation.impl.EvacuteServer"); 
 
 117             while (rc.attempt()) {
 
 119                         logger.debug("Calling CDP moveServer - server id = " + server.getId());
 
 120                     service.moveServer(server.getId(), target_host);
 
 121                     // Wait for completion, expecting the server to go to a non pending state
 
 122                     waitForStateChange(rc, server, Server.Status.READY, Server.Status.RUNNING, Server.Status.ERROR, Server.Status.SUSPENDED, Server.Status.PAUSED);
 
 124                 } catch (ContextConnectionException e) {
 
 125                     msg = EELFResourceManager.format(Msg.CONNECTION_FAILED_RETRY, provider.getName(), service.getURL(),
 
 126                             ctx.getTenant().getName(), ctx.getTenant().getId(), e.getMessage(),
 
 127                             Long.toString(rc.getRetryDelay()), Integer.toString(rc.getAttempts()),
 
 128                             Integer.toString(rc.getRetryLimit()));
 
 129                     logger.error(msg, e);
 
 130                     metricsLogger.error(msg,e);
 
 135         } catch (ZoneException e) {
 
 137                     EELFResourceManager.format(Msg.EVACUATE_SERVER_FAILED, server.getName(), server.getId(), e.getMessage());
 
 139             metricsLogger.error(msg);
 
 140             throw new RequestFailedException("Evacute Server", msg, HttpStatus.BAD_GATEWAY_502, server);
 
 144             msg = EELFResourceManager.format(Msg.CONNECTION_FAILED, provider.getName(), service.getURL());
 
 146             metricsLogger.error(msg);
 
 147             throw new RequestFailedException("Evacuate Server", msg, HttpStatus.BAD_GATEWAY_502, server);
 
 154      * @see org.openecomp.appc.adapter.iaas.ProviderAdapter#evacuateServer(java.util.Map, org.openecomp.sdnc.sli.SvcLogicContext)
 
 156     private Server evacuateServer(Map<String, String> params, SvcLogicContext ctx) throws APPCException {
 
 157         Server server = null;
 
 158         RequestContext rc = new RequestContext(ctx);
 
 161         String appName = configuration.getProperty(Constants.PROPERTY_APPLICATION_NAME);
 
 165          * Set Time for Metrics Logger
 
 167         long startTime = System.currentTimeMillis();
 
 168         TimeZone tz = TimeZone.getTimeZone("UTC");
 
 169         DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
 
 171         String startTimeStr = df.format(new Date());
 
 172         long endTime = System.currentTimeMillis();
 
 173         long duration = endTime - startTime;
 
 174         String endTimeStr = String.valueOf(endTime);
 
 175         String durationStr = String.valueOf(duration);
 
 176         String endTimeStrUTC = df.format(new Date());
 
 177         MDC.put("EndTimestamp", endTimeStrUTC);
 
 178         MDC.put("ElapsedTime", durationStr);
 
 179         MDC.put("TargetEntity", "cdp");
 
 180         MDC.put("TargetServiceName", "evacuate server");
 
 181         MDC.put("ClassName", "org.openecomp.appc.adapter.iaas.provider.operation.impl.EvacuateServer");
 
 183         ctx.setAttribute("EVACUATE_STATUS", "ERROR");
 
 185             validateParametersExist(params, ProviderAdapter.PROPERTY_INSTANCE_URL,
 
 186                     ProviderAdapter.PROPERTY_PROVIDER_NAME);
 
 187             String vm_url = params.get(ProviderAdapter.PROPERTY_INSTANCE_URL);
 
 189             VMURL vm = VMURL.parseURL(vm_url);
 
 190             if (validateVM(rc, appName, vm_url, vm)) return null;
 
 192             IdentityURL ident = IdentityURL.parseURL(params.get(ProviderAdapter.PROPERTY_IDENTITY_URL));
 
 193             String identStr = (ident == null) ? null : ident.toString();
 
 195             // retrieve the optional parameters
 
 196             String rebuild_vm = params.get(ProviderAdapter.PROPERTY_REBUILD_VM);
 
 197             String targethost_id = params.get(ProviderAdapter.PROPERTY_TARGETHOST_ID);
 
 199             Context context = null;
 
 201                 context = getContext(rc, vm_url, identStr);
 
 202                 if (context != null) {
 
 204                     server = lookupServer(rc, context, vm.getServerId());
 
 205                     logger.debug(Msg.SERVER_FOUND, vm_url, context.getTenantName(), server.getStatus().toString());
 
 207                     // check target host status
 
 208                         if (isComputeNodeDown(context, targethost_id)) {
 
 209                                 msg = EELFResourceManager.format(Msg.EVACUATE_SERVER_FAILED, server.getName(), server.getId(),
 
 210                                                 "Target host " + targethost_id +" status is not UP/ENABLED");
 
 212                         metricsLogger.error(msg);
 
 213                         throw new RequestFailedException("Evacuate Server", msg, HttpStatus.BAD_REQUEST_400, server);
 
 216                     // save hypervisor name before evacuate
 
 217                     String hypervisor = server.getHypervisor().getHostName();
 
 219                     evacuateServer(rc, server, targethost_id);
 
 222                     String hypervisor_after_evacuate = server.getHypervisor().getHostName();
 
 223                     logger.debug("Hostname before evacuate: " + hypervisor + ", After evacuate: " + hypervisor_after_evacuate);
 
 225                     // check hypervisor host name after evacuate. If it is unchanged, the evacuate failed.
 
 226                     if ((hypervisor != null) && (hypervisor.equals(hypervisor_after_evacuate))) {
 
 227                         msg = EELFResourceManager.format(Msg.EVACUATE_SERVER_FAILED, server.getName(), server.getId(),
 
 228                                         "Hypervisor host " + hypervisor + " after evacuate is the same as before evacuate. Provider (ex. Openstack) recovery actions may be needed.");
 
 230                         metricsLogger.error(msg);
 
 231                         throw new RequestFailedException("Evacuate Server", msg, HttpStatus.INTERNAL_SERVER_ERROR_500, server);
 
 235                     // check VM status after evacuate
 
 236                     if (server.getStatus() == Server.Status.ERROR) {
 
 237                         msg = EELFResourceManager.format(Msg.EVACUATE_SERVER_FAILED, server.getName(), server.getId(),
 
 238                                         "VM is in ERROR state after evacuate. Provider (ex. Openstack) recovery actions may be needed.");
 
 240                         metricsLogger.error(msg);
 
 241                         throw new RequestFailedException("Evacuate Server", msg, HttpStatus.INTERNAL_SERVER_ERROR_500, server);
 
 246                     ctx.setAttribute("EVACUATE_STATUS", "SUCCESS");
 
 248                     // If a snapshot exists, do a rebuild to apply the latest snapshot to the evacuated server.
 
 249                     // This is the default behavior unless the optional parameter is set to FALSE.
 
 250                     if ((rebuild_vm == null) || !(rebuild_vm.equalsIgnoreCase("false"))) {
 
 251                         List<Image> snapshots = server.getSnapshots();
 
 252                         if (snapshots == null || snapshots.isEmpty()) {
 
 253                                 logger.debug("No snapshots available - skipping rebuild after evacuate");
 
 254                         } else if (paImpl != null) {
 
 255                                 logger.debug("Executing a rebuild after evacuate");
 
 256                                 paImpl.rebuildServer(params, ctx);
 
 257                                 // Check error code for rebuild errors. Evacuate had set it to 200 after
 
 258                                 // a successful evacuate. Rebuild updates the error code.
 
 259                                 String rebuildErrorCode = ctx.getAttribute(org.openecomp.appc.Constants.ATTRIBUTE_ERROR_CODE);
 
 260                             if (rebuildErrorCode != null) {
 
 262                                         int error_code = Integer.parseInt(rebuildErrorCode);
 
 263                                         if (error_code != HttpStatus.OK_200.getStatusCode()) {
 
 264                                                 logger.debug("Rebuild after evacuate failed - error code=" + error_code
 
 265                                                                 + ", message=" + ctx.getAttribute(org.openecomp.appc.Constants.ATTRIBUTE_ERROR_MESSAGE));
 
 266                                                 msg = EELFResourceManager.format(Msg.EVACUATE_SERVER_REBUILD_FAILED, server.getName(), hypervisor,
 
 267                                                         hypervisor_after_evacuate, ctx.getAttribute(org.openecomp.appc.Constants.ATTRIBUTE_ERROR_MESSAGE));
 
 269                                         metricsLogger.error(msg);
 
 270                                                 ctx.setAttribute("EVACUATE_STATUS", "ERROR");
 
 271                                                 // update error message while keeping the error code the same as before
 
 272                                                 doFailure(rc, HttpStatus.getHttpStatus(error_code), msg);
 
 274                                 } catch (NumberFormatException e) {
 
 282             } catch (ResourceNotFoundException e) {
 
 283                 msg = EELFResourceManager.format(Msg.SERVER_NOT_FOUND, e, vm_url);
 
 285                 metricsLogger.error(msg);
 
 286                 doFailure(rc, HttpStatus.NOT_FOUND_404, msg);
 
 287             } catch (RequestFailedException e) {
 
 288                 doFailure(rc, e.getStatus(), e.getMessage());
 
 289             } catch (Throwable t) {
 
 290                 msg = EELFResourceManager.format(Msg.SERVER_OPERATION_EXCEPTION, t, t.getClass().getSimpleName(),
 
 291                         Operation.EVACUATE_SERVICE.toString(), vm_url, context == null ? "Unknown" : context.getTenantName());
 
 292                 logger.error(msg, t);
 
 293                 metricsLogger.error(msg, t);
 
 294                 doFailure(rc, HttpStatus.INTERNAL_SERVER_ERROR_500, msg);
 
 296         } catch (RequestFailedException e) {
 
 297                 msg = EELFResourceManager.format(Msg.EVACUATE_SERVER_FAILED, "n/a", "n/a", e.getMessage());
 
 299             metricsLogger.error(msg);
 
 300             doFailure(rc, e.getStatus(), e.getMessage());
 
 307      * Check if a Compute node is down.
 
 309      * This method attempts to find a given host in the list of hypervisors for a given
 
 310      * context. The only case where a node is considered down is if a matching hypervisor
 
 311      * is found and it's state and status are not UP/ENABLED.
 
 314      *                  The current context
 
 316      *                  The host name (short or fully qualified) of a compute node
 
 317      * @return true if the node is determined as down, false for all other cases
 
 319     private boolean isComputeNodeDown(Context context, String host) throws ZoneException {
 
 320         ComputeService service = context.getComputeService();
 
 321         boolean node_down = false;
 
 323         // Check host status. A node is considered down only if a matching target host is
 
 324         //  found and it's state/status is not UP/ENABLED.
 
 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 h : hypervisors) {
 
 329                 if (h.getHostName().startsWith(host)) {
 
 330                         // host matches one of the hypervisors
 
 331                     State hstate = h.getState();
 
 332                     Status hstatus = h.getStatus();
 
 333                     logger.debug("Host matching hypervisor: " + h.getHostName() + ", State/Status: "
 
 334                                                 + hstate.toString() + "/" + hstatus.toString());
 
 335                     if ((hstate != null) && (hstatus != null)) {
 
 336                         if (!(hstate.equals(State.UP)) || !(hstatus.equals(Status.ENABLED))) {
 
 347     protected ModelObject executeProviderOperation(Map<String, String> params, SvcLogicContext context) throws APPCException {
 
 349         setMDC(Operation.EVACUATE_SERVICE.toString(), "App-C IaaS Adapter:Evacuate", ADAPTER_NAME);
 
 350         logOperation(Msg.EVACUATING_SERVER, params, context);
 
 353          * Set Time for Metrics Logger
 
 355         long startTime = System.currentTimeMillis();
 
 356         TimeZone tz = TimeZone.getTimeZone("UTC");
 
 357         DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
 
 359         String startTimeStr = df.format(new Date());
 
 360         long endTime = System.currentTimeMillis();
 
 361         long duration = endTime - startTime;
 
 362         String endTimeStr = String.valueOf(endTime);
 
 363         String durationStr = String.valueOf(duration);
 
 364         String endTimeStrUTC = df.format(new Date());
 
 365         MDC.put("EndTimestamp", endTimeStrUTC);
 
 366         MDC.put("ElapsedTime", durationStr);
 
 367         MDC.put("TargetEntity", "cdp");
 
 368         MDC.put("TargetServiceName", "evacuate server");
 
 369         MDC.put("ClassName", "org.openecomp.appc.adapter.iaas.provider.operation.impl.EvacuateServer"); 
 
 372         metricsLogger.info("Executing Provider Operation: Evacuate");
 
 373         return evacuateServer(params, context);
 
 376     public void setProvideAdapterRef(ProviderAdapterImpl pai) {