2  * ============LICENSE_START=======================================================
 
   4  * ================================================================================
 
   5  * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
 
   6  * ================================================================================
 
   7  * Copyright (C) 2017 Amdocs
 
   8  * ================================================================================
 
   9  * Modification Copyright (C) 2019 IBM
 
  10  * =============================================================================
 
  11  * Licensed under the Apache License, Version 2.0 (the "License");
 
  12  * you may not use this file except in compliance with the License.
 
  13  * You may obtain a copy of the License at
 
  15  *      http://www.apache.org/licenses/LICENSE-2.0
 
  17  * Unless required by applicable law or agreed to in writing, software
 
  18  * distributed under the License is distributed on an "AS IS" BASIS,
 
  19  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 
  20  * See the License for the specific language governing permissions and
 
  21  * limitations under the License.
 
  23  * ============LICENSE_END=========================================================
 
  26 package org.onap.appc.adapter.iaas.provider.operation.impl;
 
  27 import com.att.cdp.exceptions.ContextConnectionException;
 
  28 import com.att.cdp.exceptions.ZoneException;
 
  29 import com.att.cdp.zones.ComputeService;
 
  30 import com.att.cdp.zones.Context;
 
  31 import com.att.cdp.zones.model.ModelObject;
 
  32 import com.att.cdp.zones.model.Server;
 
  33 import com.att.eelf.configuration.EELFLogger;
 
  34 import com.att.eelf.configuration.EELFManager;
 
  35 import com.att.eelf.i18n.EELFResourceManager;
 
  36 import org.glassfish.grizzly.http.util.HttpStatus;
 
  37 import org.onap.appc.Constants;
 
  38 import org.onap.appc.logging.LoggingConstants;
 
  39 import org.onap.appc.logging.LoggingUtils;
 
  40 import org.onap.appc.adapter.iaas.ProviderAdapter;
 
  41 import org.onap.appc.adapter.iaas.impl.IdentityURL;
 
  42 import org.onap.appc.adapter.iaas.impl.RequestContext;
 
  43 import org.onap.appc.adapter.iaas.impl.RequestFailedException;
 
  44 import org.onap.appc.adapter.iaas.impl.VMURL;
 
  45 import org.onap.appc.adapter.iaas.provider.operation.common.constants.Property;
 
  46 import org.onap.appc.adapter.iaas.provider.operation.common.enums.Operation;
 
  47 import org.onap.appc.adapter.iaas.provider.operation.impl.base.ProviderServerOperation;
 
  48 import org.onap.appc.configuration.Configuration;
 
  49 import org.onap.appc.configuration.ConfigurationFactory;
 
  50 import org.onap.appc.exceptions.APPCException;
 
  51 import org.onap.appc.i18n.Msg;
 
  52 import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
 
  54 import java.io.IOException;
 
  55 import java.util.Arrays;
 
  56 import java.util.Collection;
 
  57 import java.util.Date;
 
  59 import static org.onap.appc.adapter.iaas.provider.operation.common.enums.Operation.MIGRATE_SERVICE;
 
  60 import static org.onap.appc.adapter.utils.Constants.ADAPTER_NAME;
 
  62 public class MigrateServer extends ProviderServerOperation {
 
  64     private static final EELFLogger logger = EELFManager.getInstance().getLogger(MigrateServer.class);
 
  65     private static EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger();
 
  66     private static final Configuration configuration = ConfigurationFactory.getConfiguration();
 
  69      * A list of valid initial VM statuses for a migrate operations
 
  71     private final Collection<Server.Status> migratableStatuses = Arrays.asList(Server.Status.READY,
 
  72             Server.Status.RUNNING, Server.Status.SUSPENDED);
 
  74     private String getConnectionExceptionMessage(RequestContext rc, Context ctx, ZoneException e) throws ZoneException {
 
  75         return EELFResourceManager.format(Msg.CONNECTION_FAILED_RETRY, ctx.getProvider().getName(),
 
  76                 ctx.getComputeService().getURL(), ctx.getTenant().getName(), ctx.getTenant().getId(), e.getMessage(),
 
  77                 Long.toString(rc.getRetryDelay()), Integer.toString(rc.getAttempts()),
 
  78                 Integer.toString(rc.getRetryLimit()));
 
  81     private void migrateServer(RequestContext rc, Server server, SvcLogicContext svcCtx)
 
  82             throws ZoneException, RequestFailedException {
 
  84         Context ctx = server.getContext();
 
  85         ComputeService service = ctx.getComputeService();
 
  86         // Init status will equal final status
 
  87         Server.Status initialStatus = server.getStatus();
 
  88         if (initialStatus == null) {
 
  89             throw new ZoneException("Failed to determine server's starting status");
 
  91         // We can only migrate certain statuses
 
  92         if (!migratableStatuses.contains(initialStatus)) {
 
  93             throw new ZoneException(String.format("Cannot migrate server that is in %s state. Must be in one of [%s]",
 
  94                     initialStatus, migratableStatuses));
 
  96         setTimeForMetricsLogger();
 
  97         // Is the skip Hypervisor check attribute populated?
 
  98         String skipHypervisorCheck = configuration.getProperty(Property.SKIP_HYPERVISOR_CHECK);
 
  99         if (skipHypervisorCheck == null && svcCtx != null) {
 
 100             skipHypervisorCheck = svcCtx.getAttribute(ProviderAdapter.SKIP_HYPERVISOR_CHECK);
 
 102         // Always perform Hypervisor check
 
 103         // unless the skip is set to true
 
 104         if (skipHypervisorCheck == null || (!(("true").equalsIgnoreCase(skipHypervisorCheck)))) {
 
 105             // Check of the Hypervisor for the VM Server is UP and reachable
 
 106             checkHypervisor(server);
 
 109         boolean inConfirmPhase = false;
 
 111             while (rc.attempt()) {
 
 113                     if (!inConfirmPhase) {
 
 114                         // Initial migrate request
 
 115                         service.migrateServer(server.getId());
 
 116                         // Wait for change to verify resize
 
 117                         waitForStateChange(rc, server, Server.Status.READY);
 
 118                         inConfirmPhase = true;
 
 120                     if (server.getStatus() != null && server.getStatus().equals(Server.Status.ERROR)) {
 
 121                         msg = "Cannot Perform 'processResize' in  vm_state " + Server.Status.ERROR;
 
 123                         msg = EELFResourceManager.format(Msg.MIGRATE_SERVER_FAILED, service.getURL());
 
 126                         throw new RequestFailedException("Waiting for State Change", msg, HttpStatus.CONFLICT_409,
 
 130                         logger.debug("MigrateServer: Before  service.processResize");
 
 131                         service.processResize(server);
 
 132                         logger.debug("MigrateServer:before 2nd waitForStateChange Current Status:" + server.getStatus()
 
 133                                 + " Initail Status: " + initialStatus);
 
 134                         // Wait for complete. will go back to init status
 
 135                         waitForStateChange(rc, server, initialStatus);
 
 136                         logger.info("Completed migrate request successfully");
 
 137                         metricsLogger.info("Completed migrate request successfully");
 
 140                 } catch (ContextConnectionException e) {
 
 141                     msg = getConnectionExceptionMessage(rc, ctx, e);
 
 142                     if (server.getStatus() != null && server.getStatus().equals(Server.Status.ERROR)) {
 
 143                         throw new RequestFailedException("Migrate Server", msg, HttpStatus.CONFLICT_409, server);
 
 145                         logger.info("Migrate Server: Going to delay in ConnectionException");
 
 146                         logger.debug("Server Status: " + server.getStatus());
 
 153         } catch (ZoneException e) {
 
 154             String phase = inConfirmPhase ? "VERIFY MIGRATE" : "REQUEST MIGRATE";
 
 155             msg = EELFResourceManager.format(Msg.MIGRATE_SERVER_FAILED, server.getName(), server.getId(), phase,
 
 158             logger.error(msg, e);
 
 159             throw new RequestFailedException("Migrate Server", msg, HttpStatus.METHOD_NOT_ALLOWED_405, server);
 
 164      * @see org.onap.appc.adapter.iaas.ProviderAdapter#migrateServer(java.util.Map,
 
 165      *      org.onap.ccsdk.sli.core.sli.SvcLogicContext)
 
 167     private Server migrateServer(Map<String, String> params, SvcLogicContext ctx) {
 
 168         Server server = null;
 
 169         RequestContext rc = new RequestContext(ctx);
 
 171         setTimeForMetricsLogger();
 
 173             validateParametersExist(params, ProviderAdapter.PROPERTY_INSTANCE_URL,
 
 174                     ProviderAdapter.PROPERTY_PROVIDER_NAME);
 
 175             String vmUrl = params.get(ProviderAdapter.PROPERTY_INSTANCE_URL);
 
 176             String appName = configuration.getProperty(Constants.PROPERTY_APPLICATION_NAME);
 
 177             VMURL vm = VMURL.parseURL(vmUrl);
 
 178             if (validateVM(rc, appName, vmUrl, vm))
 
 180             IdentityURL ident = IdentityURL.parseURL(params.get(ProviderAdapter.PROPERTY_IDENTITY_URL));
 
 181             String identStr = (ident == null) ? null : ident.toString();
 
 182             server = conductServerMigration(rc, vmUrl, identStr, ctx);
 
 183         } catch (RequestFailedException e) {
 
 184             doFailure(rc, e.getStatus(), e.getMessage());
 
 190     protected ModelObject executeProviderOperation(Map<String, String> params, SvcLogicContext context)
 
 191             throws APPCException {
 
 192         setMDC(Operation.MIGRATE_SERVICE.toString(), "App-C IaaS Adapter:Migrate", ADAPTER_NAME);
 
 193         logOperation(Msg.MIGRATING_SERVER, params, context);
 
 194         setTimeForMetricsLogger();
 
 195         metricsLogger.info("Executing Provider Operation: Migrate");
 
 196         return migrateServer(params, context);
 
 199     private void setTimeForMetricsLogger() {
 
 200         String timestamp = LoggingUtils.generateTimestampStr((new Date()).toInstant());
 
 201         MDC.put(LoggingConstants.MDCKeys.BEGIN_TIMESTAMP, timestamp);
 
 202         MDC.put(LoggingConstants.MDCKeys.END_TIMESTAMP, timestamp);
 
 203         MDC.put(LoggingConstants.MDCKeys.ELAPSED_TIME, "0");
 
 204         MDC.put(LoggingConstants.MDCKeys.STATUS_CODE, LoggingConstants.StatusCodes.COMPLETE);
 
 205         MDC.put(LoggingConstants.MDCKeys.TARGET_ENTITY, "cdp");
 
 206         MDC.put(LoggingConstants.MDCKeys.TARGET_SERVICE_NAME, "migrate server");
 
 207         MDC.put(LoggingConstants.MDCKeys.CLASS_NAME,
 
 208                 "org.onap.appc.adapter.iaas.provider.operation.impl.MigrateServer");
 
 212     private Server conductServerMigration(RequestContext rc, String vmUrl, String identStr, SvcLogicContext ctx)
 
 213             throws RequestFailedException {
 
 215         Context context = getContext(rc, vmUrl, identStr);
 
 216         VMURL vm = VMURL.parseURL(vmUrl);
 
 217         Server server = null;
 
 219             if (context != null) {
 
 220                 server = lookupServer(rc, context, vm.getServerId());
 
 221                 logger.debug(Msg.SERVER_FOUND, vmUrl, context.getTenantName(), server.getStatus().toString());
 
 222                 migrateServer(rc, server, ctx);
 
 223                 server.refreshStatus();
 
 227         } catch (IOException | ZoneException e1) {
 
 228             msg = EELFResourceManager.format(Msg.SERVER_OPERATION_EXCEPTION, e1, e1.getClass().getSimpleName(),
 
 229                     MIGRATE_SERVICE.toString(), vmUrl, context.getTenantName());
 
 230             logger.error(msg, e1);
 
 231             metricsLogger.error(msg);
 
 232             doFailure(rc, HttpStatus.INTERNAL_SERVER_ERROR_500, msg);