enchance rebuildaction to make snapshotid Optional 31/55231/4
authorModaboina, Kusumakumari (km583p) <km583p@us.att.com>
Thu, 21 Jun 2018 20:08:00 +0000 (16:08 -0400)
committerTakamune Cho <tc012c@att.com>
Fri, 22 Jun 2018 14:16:56 +0000 (14:16 +0000)
Issue-ID: APPC-1011
Change-Id: I58d71df2c71a2964cd5957119e3967e35912ac6b
Signed-off-by: Modaboina, Kusumakumari (km583p) <km583p@us.att.com>
appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/ProviderAdapter.java
appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/provider/operation/common/constants/Property.java
appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/provider/operation/impl/AttachVolumeServer.java
appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/provider/operation/impl/CreateSnapshot.java
appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/provider/operation/impl/DettachVolumeServer.java
appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/provider/operation/impl/EvacuateServer.java
appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/provider/operation/impl/MigrateServer.java
appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/provider/operation/impl/RebuildServer.java
appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/provider/operation/impl/RestartServer.java
appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/provider/operation/impl/SnapshotStack.java
appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/provider/operation/impl/StopServer.java

index 5055305..1eebe50 100644 (file)
@@ -78,8 +78,11 @@ public interface ProviderAdapter extends SvcLogicJavaPlugin {
     static final String PROPERTY_INPUT_SNAPSHOT_ID = "org.onap.appc.snapshot.id";
     static final String DG_OUTPUT_PARAM_NAMESPACE = "output.";
     static final String SKIP_HYPERVISOR_CHECK = "org.onap.appc.skiphypervisorcheck";
+    static final String PAYLOAD = "payload";
     static final String VOLUME_ID = "org.onap.appc.volumeid";
     static final String DEVICE = "org.onap.appc.device";
+    static final String REBOOT_TYPE = "org.onap.appc.reboot.type";
+    static final String PROPERTY_REQUEST_SNAPSHOT_ID = "snapshot-id";
     /**
      * This method is used to restart an existing virtual machine given the fully qualified URL of the machine.
      * <p>
@@ -262,4 +265,5 @@ public interface ProviderAdapter extends SvcLogicJavaPlugin {
      * @throws APPCException If the server cannot be restarted for some reason
      */
     Image createSnapshot(Map<String, String> params, SvcLogicContext ctx) throws APPCException;
+    
 }
index c14fb81..d60906b 100644 (file)
@@ -39,4 +39,6 @@ public class Property {
     public static final String PROVIDER_TENANT_USERID = "userid";
     public static final String PROVIDER_TYPE = "type";
     public static final String SKIP_HYPERVISOR_CHECK = "org.onap.appc.iaas.skiphypervisorcheck";
+    public static final String PAYLOAD = "org.onap.appc.payload";
+
 }
index 3588317..e9b0c97 100644 (file)
@@ -88,6 +88,10 @@ public class AttachVolumeServer extends ProviderServerOperation {
                 logger.debug(Msg.SERVER_FOUND, vmUrl, context.getTenantName(), server.getStatus().toString());
                 Context contx = server.getContext();
                 ComputeService service = contx.getComputeService();
+                if ((volumeId == null || volumeId.isEmpty()) || (device == null || device.isEmpty())) {
+                    ctx.setAttribute("VOLUME_STATUS", "FAILURE");
+                    doFailure(requestContext, HttpStatus.BAD_REQUEST_400, "Both Device or Volumeid are mandatory");
+                }
                 VolumeService volumeService = contx.getVolumeService();
                 logger.info("collecting volume status for volume -id:" + volumeId);
                 List<Volume> volumes = volumeService.getVolumes();
@@ -169,7 +173,7 @@ public class AttachVolumeServer extends ProviderServerOperation {
         logger.info("AttachVolumeFlag" + isValid);
         return isValid;
     }
-    
+
     protected boolean validateAttach(RequestContext rc, ComputeService ser, String vm, String volumeId, String device)
             throws RequestFailedException, ZoneException {
         boolean isValid = false;
@@ -199,7 +203,6 @@ public class AttachVolumeServer extends ProviderServerOperation {
             }
         }
         if ((rc.getAttempts() == 30) && (!isValid)) {
-
             msg = EELFResourceManager.format(Msg.CONNECTION_FAILED_RETRY, Long.toString(rc.getRetryDelay()),
                     Integer.toString(rc.getAttempts()), Integer.toString(rc.getRetryLimit()));
             logger.error(msg);
index 708de28..ba0160c 100644 (file)
@@ -49,6 +49,7 @@ import org.onap.appc.configuration.Configuration;
 import org.onap.appc.configuration.ConfigurationFactory;
 import org.onap.appc.exceptions.APPCException;
 import org.onap.appc.i18n.Msg;
+import org.onap.appc.logging.LoggingConstants;
 import org.slf4j.MDC;
 import java.text.DateFormat;
 import java.text.SimpleDateFormat;
@@ -66,10 +67,8 @@ public class CreateSnapshot extends ProviderServerOperation {
 
     private String generateSnapshotName(String server) {
         setTimeForMetricsLogger();
-
         SimpleDateFormat df = new SimpleDateFormat(DATE_FORMAT);
         metricsLogger.info("Snapshot Name Generated: Snapshot of %s at %s", server, df.format(new Date()));
-
         return String.format("Snapshot of %s at %s", server, df.format(new Date()));
     }
 
@@ -77,16 +76,12 @@ public class CreateSnapshot extends ProviderServerOperation {
         Context context = server.getContext();
         Provider provider = context.getProvider();
         ImageService service = context.getImageService(); // Already checked access by this point
-
         String snapshotName = generateSnapshotName(server.getName());
-
         setTimeForMetricsLogger();
-
         logger.info(String.format("Creating snapshot of server %s (%s) with name %s", server.getName(), server.getId(),
                 snapshotName));
         metricsLogger.info(String.format("Creating snapshot of server %s (%s) with name %s", server.getName(),
                 server.getId(), snapshotName));
-
         // Request Snapshot
         String msg;
         while (rc.attempt()) {
@@ -110,7 +105,6 @@ public class CreateSnapshot extends ProviderServerOperation {
             throw new RequestFailedException("Stop Server", msg, HttpStatus.BAD_GATEWAY_502, server);
         }
         rc.reset();
-
         // Locate snapshot image
         Image snapshot = null;
         while (rc.attempt()) {
@@ -136,10 +130,8 @@ public class CreateSnapshot extends ProviderServerOperation {
             throw new RequestFailedException("Stop Server", msg, HttpStatus.BAD_GATEWAY_502, server);
         }
         rc.reset();
-
         // Wait for it to be ready
         waitForStateChange(rc, snapshot, Image.Status.ACTIVE);
-
         return snapshot;
     }
 
@@ -147,7 +139,6 @@ public class CreateSnapshot extends ProviderServerOperation {
         Image snapshot = null;
         RequestContext rc = new RequestContext(ctx);
         rc.isAlive();
-
         setTimeForMetricsLogger();
         try {
             validateParametersExist(params, ProviderAdapter.PROPERTY_INSTANCE_URL,
@@ -157,7 +148,6 @@ public class CreateSnapshot extends ProviderServerOperation {
             VMURL vm = VMURL.parseURL(vm_url);
             if (validateVM(rc, appName, vm_url, vm))
                 return null;
-
             IdentityURL ident = IdentityURL.parseURL(params.get(ProviderAdapter.PROPERTY_IDENTITY_URL));
             String identStr = (ident == null) ? null : ident.toString();
             snapshot = createSnapshotNested(snapshot, rc, vm, vm_url, identStr);
@@ -167,21 +157,17 @@ public class CreateSnapshot extends ProviderServerOperation {
         return snapshot;
     }
 
-    private Image createSnapshotNested(Image SnapShot, RequestContext RcContext, VMURL vm, String vmUrl, String identStr) 
-            throws APPCException {
-
+    private Image createSnapshotNested(Image SnapShot, RequestContext RcContext, VMURL vm, String vmUrl,
+            String identStr) throws APPCException {
         String msg;
-
         Context context = null;
-        String tenantName = "Unknown";//this variable is also used in catch
+        String tenantName = "Unknown";// this variable is also used in catch
         try {
             context = getContext(RcContext, vmUrl, identStr);
             if (context != null) {
                 tenantName = context.getTenantName();
                 Server server = lookupServer(RcContext, context, vm.getServerId());
-
                 logger.debug(Msg.SERVER_FOUND, vmUrl, tenantName, server.getStatus().toString());
-
                 if (hasImageAccess(RcContext, context)) {
                     SnapShot = createSnapshot(RcContext, server);
                     doSuccess(RcContext);
@@ -201,8 +187,7 @@ public class CreateSnapshot extends ProviderServerOperation {
             doFailure(RcContext, HttpStatus.NOT_FOUND_404, msg);
         } catch (Exception e1) {
             msg = EELFResourceManager.format(Msg.SERVER_OPERATION_EXCEPTION, e1, e1.getClass().getSimpleName(),
-                    Operation.SNAPSHOT_SERVICE.toString(), vmUrl,
-                    tenantName);
+                    Operation.SNAPSHOT_SERVICE.toString(), vmUrl, tenantName);
             logger.error(msg, e1);
             doFailure(RcContext, HttpStatus.INTERNAL_SERVER_ERROR_500, msg);
         }
@@ -212,29 +197,17 @@ public class CreateSnapshot extends ProviderServerOperation {
     @Override
     protected ModelObject executeProviderOperation(Map<String, String> params, SvcLogicContext context)
             throws APPCException {
-
         setMDC(Operation.SNAPSHOT_SERVICE.toString(), "App-C IaaS Adapter:Snapshot", ADAPTER_NAME);
         logOperation(Msg.SNAPSHOTING_SERVER, params, context);
         setTimeForMetricsLogger();
-
         metricsLogger.info("Executing Provider Operation: Create Snapshot");
-
         return createSnapshot(params, context);
     }
 
     private void setTimeForMetricsLogger() {
-        long startTime = System.currentTimeMillis();
-        TimeZone tz = TimeZone.getTimeZone("UTC");
-        DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
-        df.setTimeZone(tz);
-        long endTime = System.currentTimeMillis();
-        long duration = endTime - startTime;
-        String durationStr = String.valueOf(duration);
-        String endTimeStrUTC = df.format(new Date());
-        MDC.put("EndTimestamp", endTimeStrUTC);
-        MDC.put("ElapsedTime", durationStr);
-        MDC.put("TargetEntity", "cdp");
-        MDC.put("TargetServiceName", "create snapshot");
-        MDC.put("ClassName", "org.onap.appc.adapter.iaas.provider.operation.impl.CreateSnapshot");
+        MDC.put(LoggingConstants.MDCKeys.TARGET_ENTITY, "cdp");
+        MDC.put(LoggingConstants.MDCKeys.TARGET_SERVICE_NAME, "create snapshot");
+        MDC.put(LoggingConstants.MDCKeys.CLASS_NAME,
+                "org.onap.appc.adapter.iaas.provider.operation.impl.CreateSnapshot");
     }
 }
index 5892c12..218c83e 100644 (file)
@@ -92,6 +92,10 @@ public class DettachVolumeServer extends ProviderServerOperation {
                 requestContext.reset();
                 server = lookupServer(requestContext, context, vm.getServerId());
                 logger.debug(Msg.SERVER_FOUND, vmUrl, context.getTenantName(), server.getStatus().toString());
+                if (volumeId == null || volumeId.isEmpty()) {
+                    ctx.setAttribute("VOLUME_STATUS", "FAILURE");
+                    doFailure(requestContext, HttpStatus.BAD_REQUEST_400, "Volumeid is mandatory");
+                }
                 Context contx = server.getContext();
                 ComputeService service = contx.getComputeService();
                 Volume volume = new Volume();
@@ -175,31 +179,29 @@ public class DettachVolumeServer extends ProviderServerOperation {
         while (rc.attempt()) {
             Map<String, String> map = ser.getAttachments(vm);
             if (map != null && !(map.isEmpty())) {
-            Iterator<Entry<String, String>> it = map.entrySet().iterator();
-            logger.info("volumes available after  detach ");
-            while (it.hasNext()) {
-                Map.Entry volumes = (Map.Entry) it.next();
-                logger.info(" devices " + volumes.getKey() + " volumes" + volumes.getValue());
-                if (volumes.getValue().equals(volumeId)) {
-                    logger.info("Device" + volumes.getKey() + "Volume" + volumes.getValue());
-                    flag = true;
-                    break;
+                Iterator<Entry<String, String>> it = map.entrySet().iterator();
+                logger.info("volumes available after  detach ");
+                while (it.hasNext()) {
+                    Map.Entry volumes = (Map.Entry) it.next();
+                    logger.info(" devices " + volumes.getKey() + " volumes" + volumes.getValue());
+                    if (volumes.getValue().equals(volumeId)) {
+                        logger.info("Device" + volumes.getKey() + "Volume" + volumes.getValue());
+                        flag = true;
+                        break;
+                    } else {
+                        flag = false;
+                    }
+                    logger.info("Dettachvolume flag-->" + flag + "Attempts" + rc.getAttempts());
+                }
+                if (flag) {
+                    rc.delay();
                 } else {
                     flag = false;
+                    break;
                 }
-                logger.info("Dettachvolume flag-->" + flag+"Attempts"+rc.getAttempts());
-            }
-            if (flag) {
-                rc.delay();
             } else {
                 flag = false;
-                break;
-            }
-        }
-            else
-            {
-                flag = false;
-                logger.info( rc.getAttempts() + "No.of attempts");
+                logger.info(rc.getAttempts() + "No.of attempts");
                 break;
             }
         }
index 88bb37b..0d34246 100644 (file)
@@ -36,6 +36,8 @@ import org.onap.appc.configuration.Configuration;
 import org.onap.appc.configuration.ConfigurationFactory;
 import org.onap.appc.exceptions.APPCException;
 import org.onap.appc.i18n.Msg;
+import org.onap.appc.logging.LoggingConstants;
+import org.onap.appc.logging.LoggingUtils;
 import com.att.cdp.exceptions.ContextConnectionException;
 import com.att.cdp.exceptions.ResourceNotFoundException;
 import com.att.cdp.exceptions.ZoneException;
@@ -54,7 +56,6 @@ import com.att.eelf.i18n.EELFResourceManager;
 import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
 import org.glassfish.grizzly.http.util.HttpStatus;
 import org.slf4j.MDC;
-
 import java.io.IOException;
 import java.text.DateFormat;
 import java.text.SimpleDateFormat;
@@ -72,21 +73,19 @@ public class EvacuateServer extends ProviderServerOperation {
 
     private static final EELFLogger logger = EELFManager.getInstance().getLogger(EvacuateServer.class);
     private static EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger();
-
     private static final Configuration configuration = ConfigurationFactory.getConfiguration();
     private ProviderAdapterImpl paImpl = null;
 
     private void evacuateServer(RequestContext rc, @SuppressWarnings("unused") Server server, String targetHost)
             throws ZoneException, RequestFailedException {
-
         Context ctx = server.getContext();
         Provider provider = ctx.getProvider();
         ComputeService service = ctx.getComputeService();
-
         /*
-         * Pending is a bit of a special case. If we find the server is in a pending state, then the provider is in the
-         * process of changing state of the server. So, lets try to wait a little bit and see if the state settles down
-         * to one we can deal with. If not, then we have to fail the request.
+         * Pending is a bit of a special case. If we find the server is in a pending
+         * state, then the provider is in the process of changing state of the server.
+         * So, lets try to wait a little bit and see if the state settles down to one we
+         * can deal with. If not, then we have to fail the request.
          */
         try {
             if (server.getStatus().equals(Server.Status.PENDING)) {
@@ -94,16 +93,15 @@ public class EvacuateServer extends ProviderServerOperation {
                         Server.Status.SUSPENDED, Server.Status.PAUSED);
             }
         } catch (RequestFailedException e) {
-            // evacuate is a special case. If the server is still in a Pending state, we want to
+            // evacuate is a special case. If the server is still in a Pending state, we
+            // want to
             // continue with evacuate
-            logger.info("Evacuate server - ignore RequestFailedException from waitForStateChange() ..." ,e);
+            logger.info("Evacuate server - ignore RequestFailedException from waitForStateChange() ..."e);
         }
-
         setTimeForMetricsLogger();
-
         String msg;
         try {
-            evacuateServerNested(rc,service,server,provider,targetHost);
+            evacuateServerNested(rc, service, server, provider, targetHost);
         } catch (ZoneException e) {
             msg = EELFResourceManager.format(Msg.EVACUATE_SERVER_FAILED, server.getName(), server.getId(),
                     e.getMessage());
@@ -111,7 +109,6 @@ public class EvacuateServer extends ProviderServerOperation {
             metricsLogger.error(msg);
             throw new RequestFailedException(EVACUATE_SERVER, msg, HttpStatus.BAD_GATEWAY_502, server);
         }
-
         if (rc.isFailed()) {
             msg = EELFResourceManager.format(Msg.CONNECTION_FAILED, provider.getName(), service.getURL());
             logger.error(msg);
@@ -121,11 +118,10 @@ public class EvacuateServer extends ProviderServerOperation {
         rc.reset();
     }
 
-    private void evacuateServerNested(RequestContext rcCtx,ComputeService svc,Server server,Provider provider, String targetHost) 
-            throws ZoneException, RequestFailedException {
+    private void evacuateServerNested(RequestContext rcCtx, ComputeService svc, Server server, Provider provider,
+            String targetHost) throws ZoneException, RequestFailedException {
         String msg;
         Context ctx = server.getContext();
-
         while (rcCtx.attempt()) {
             try {
                 logger.debug("Calling CDP moveServer - server id = " + server.getId());
@@ -145,6 +141,7 @@ public class EvacuateServer extends ProviderServerOperation {
             }
         }
     }
+
     /**
      * @see org.onap.appc.adapter.iaas.ProviderAdapter#evacuateServer(java.util.Map,
      *      org.onap.ccsdk.sli.core.sli.SvcLogicContext)
@@ -153,9 +150,7 @@ public class EvacuateServer extends ProviderServerOperation {
         Server server = null;
         RequestContext rc = new RequestContext(ctx);
         rc.isAlive();
-
         setTimeForMetricsLogger();
-
         String msg;
         ctx.setAttribute(EVACUATE_STATUS, "ERROR");
         try {
@@ -165,67 +160,54 @@ public class EvacuateServer extends ProviderServerOperation {
             String appName = configuration.getProperty(Constants.PROPERTY_APPLICATION_NAME);
             String vmUrl = params.get(ProviderAdapter.PROPERTY_INSTANCE_URL);
             VMURL vm = VMURL.parseURL(vmUrl);
-
             if (validateVM(rc, appName, vmUrl, vm)) {
                 return null;
             }
-
             server = evacuateServerMapNestedFirst(params, server, rc, ctx, vm, vmUrl);
-
         } catch (RequestFailedException e) {
             msg = EELFResourceManager.format(Msg.EVACUATE_SERVER_FAILED, "n/a", "n/a", e.getMessage());
             logger.error(msg, e);
             metricsLogger.error(msg);
             doFailure(rc, e.getStatus(), e.getMessage());
         }
-
         return server;
     }
 
-    private Server evacuateServerMapNestedFirst(Map<String, String> params, Server server, RequestContext rqstCtx, SvcLogicContext ctx,
-                VMURL vm, String vmUrl)
-            throws APPCException {
-
+    private Server evacuateServerMapNestedFirst(Map<String, String> params, Server server, RequestContext rqstCtx,
+            SvcLogicContext ctx, VMURL vm, String vmUrl) throws APPCException {
         String msg;
         Context context;
-
         IdentityURL ident = IdentityURL.parseURL(params.get(ProviderAdapter.PROPERTY_IDENTITY_URL));
         String identStr = (ident == null) ? null : ident.toString();
         // retrieve the optional parameters
         String rebuildVm = params.get(ProviderAdapter.PROPERTY_REBUILD_VM);
         String targetHostId = params.get(ProviderAdapter.PROPERTY_TARGETHOST_ID);
-        String tenantName = "Unknown";//to be used also in case of exception
+        String tenantName = "Unknown";// to be used also in case of exception
         try {
             context = getContext(rqstCtx, vmUrl, identStr);
             if (context != null) {
-                tenantName = context.getTenantName();//this variable also is used in case of exception
+                tenantName = context.getTenantName();// this variable also is used in case of exception
                 server = lookupServer(rqstCtx, context, vm.getServerId());
-
                 logger.debug(Msg.SERVER_FOUND, vmUrl, tenantName, server.getStatus().toString());
-
                 // check target host status
                 checkHostStatus(server, targetHostId, context);
-
                 // save hypervisor name before evacuate
                 String hypervisor = server.getHypervisor().getHostName();
-
                 evacuateServer(rqstCtx, server, targetHostId);
-
                 server.refreshAll();
                 String hypervisorAfterEvacuate = server.getHypervisor().getHostName();
-                logger.debug("Hostname before evacuate: " + hypervisor + ", After evacuate: " + hypervisorAfterEvacuate);
-
+                logger.debug(
+                        "Hostname before evacuate: " + hypervisor + ", After evacuate: " + hypervisorAfterEvacuate);
                 // check hypervisor host name after evacuate. If it is unchanged, the evacuate
                 // failed.
                 checkHypervisor(server, hypervisor, hypervisorAfterEvacuate);
-
                 // check VM status after evacuate
                 checkStatus(server);
                 context.close();
                 doSuccess(rqstCtx);
                 ctx.setAttribute(EVACUATE_STATUS, "SUCCESS");
-
-                // If a snapshot exists, do a rebuild to apply the latest snapshot to the evacuated server.
+                // If a snapshot exists, do a rebuild to apply the latest snapshot to the
+                // evacuated server.
                 // This is the default behavior unless the optional parameter is set to FALSE.
                 if (rebuildVm == null || !"false".equalsIgnoreCase(rebuildVm)) {
                     List<Image> snapshots = server.getSnapshots();
@@ -239,7 +221,6 @@ public class EvacuateServer extends ProviderServerOperation {
                         evacuateServerMapNestedSecond(server, rqstCtx, ctx, hypervisor, hypervisorAfterEvacuate);
                     }
                 }
-
             }
         } catch (ResourceNotFoundException e) {
             msg = EELFResourceManager.format(Msg.SERVER_NOT_FOUND, e, vmUrl);
@@ -254,26 +235,29 @@ public class EvacuateServer extends ProviderServerOperation {
                     Operation.EVACUATE_SERVICE.toString(), vmUrl, tenantName);
             logger.error(msg, e1);
             metricsLogger.error(msg, e1);
-            doFailure(rqstCtx, HttpStatus.INTERNAL_SERVER_ERROR_500, msg);
+            doFailure(rqstCtx, HttpStatus.INTERNAL_SERVER_ERROR_500, e1.getMessage());
+        } catch (Exception e1) {
+            msg = EELFResourceManager.format(Msg.SERVER_OPERATION_EXCEPTION, e1, e1.getClass().getSimpleName(),
+                    Operation.EVACUATE_SERVICE.toString(), vmUrl, tenantName);
+            logger.error(msg, e1);
+            metricsLogger.error(msg);
+            doFailure(rqstCtx, HttpStatus.INTERNAL_SERVER_ERROR_500, e1.getMessage());
         }
         return server;
     }
 
-    private void evacuateServerMapNestedSecond(Server server,RequestContext rc, SvcLogicContext ctx,
-            String hypervisor,String hypervisorAfterEvacuate) {
-
+    private void evacuateServerMapNestedSecond(Server server, RequestContext rc, SvcLogicContext ctx, String hypervisor,
+            String hypervisorAfterEvacuate) {
         String msg;
         String rebuildErrorCode = ctx.getAttribute(org.onap.appc.Constants.ATTRIBUTE_ERROR_CODE);
-
         if (rebuildErrorCode != null) {
             try {
                 int errorCode = Integer.parseInt(rebuildErrorCode);
                 if (errorCode != HttpStatus.OK_200.getStatusCode()) {
-                    logger.debug("Rebuild after evacuate failed - error code=" + errorCode
-                            + ", message=" + ctx.getAttribute(org.onap.appc.Constants.ATTRIBUTE_ERROR_MESSAGE));
-                    msg = EELFResourceManager.format(Msg.EVACUATE_SERVER_REBUILD_FAILED,
-                            server.getName(), hypervisor, hypervisorAfterEvacuate,
-                            ctx.getAttribute(org.onap.appc.Constants.ATTRIBUTE_ERROR_MESSAGE));
+                    logger.debug("Rebuild after evacuate failed - error code=" + errorCode + ", message="
+                            + ctx.getAttribute(org.onap.appc.Constants.ATTRIBUTE_ERROR_MESSAGE));
+                    msg = EELFResourceManager.format(Msg.EVACUATE_SERVER_REBUILD_FAILED, server.getName(), hypervisor,
+                            hypervisorAfterEvacuate, ctx.getAttribute(org.onap.appc.Constants.ATTRIBUTE_ERROR_MESSAGE));
                     logger.error(msg);
                     metricsLogger.error(msg);
                     ctx.setAttribute(EVACUATE_STATUS, "ERROR");
@@ -288,7 +272,7 @@ public class EvacuateServer extends ProviderServerOperation {
     }
 
     private void checkHostStatus(Server server, String targetHostId, Context context)
-        throws ZoneException, RequestFailedException {
+            throws ZoneException, RequestFailedException {
         if (isComputeNodeDown(context, targetHostId)) {
             String msg = EELFResourceManager.format(Msg.EVACUATE_SERVER_FAILED, server.getName(), server.getId(),
                     "Target host " + targetHostId + " status is not UP/ENABLED");
@@ -299,7 +283,7 @@ public class EvacuateServer extends ProviderServerOperation {
     }
 
     private void checkHypervisor(Server server, String hypervisor, String hypervisorAfterEvacuate)
-        throws RequestFailedException {
+            throws RequestFailedException {
         if (hypervisor != null && hypervisor.equals(hypervisorAfterEvacuate)) {
             String msg = EELFResourceManager.format(Msg.EVACUATE_SERVER_FAILED, server.getName(), server.getId(),
                     "Hypervisor host " + hypervisor
@@ -323,20 +307,22 @@ public class EvacuateServer extends ProviderServerOperation {
     /**
      * Check if a Compute node is down.
      * 
-     * This method attempts to find a given host in the list of hypervisors for a given context. The only case where a
-     * node is considered down is if a matching hypervisor is found and it's state and status are not UP/ENABLED.
+     * This method attempts to find a given host in the list of hypervisors for a
+     * given context. The only case where a node is considered down is if a matching
+     * hypervisor is found and it's state and status are not UP/ENABLED.
      * 
-     * @param context The current context
+     * @param context
+     *            The current context
      * 
-     * @param host The host name (short or fully qualified) of a compute node
+     * @param host
+     *            The host name (short or fully qualified) of a compute node
      * 
      * @return true if the node is determined as down, false for all other cases
      */
     private boolean isComputeNodeDown(Context context, String host) throws ZoneException {
         ComputeService service = context.getComputeService();
         boolean nodeDown = false;
-
-        if (host != null && ! host.isEmpty()) {
+        if (host != null && !host.isEmpty()) {
             List<Hypervisor> hypervisors = service.getHypervisors();
             logger.debug("List of Hypervisors retrieved: " + Arrays.toString(hypervisors.toArray()));
             for (Hypervisor hv : hypervisors) {
@@ -350,8 +336,8 @@ public class EvacuateServer extends ProviderServerOperation {
         if (isHostMatchesHypervisor(host, hv)) {
             State hstate = hv.getState();
             Status hstatus = hv.getStatus();
-            logger.debug("Host matching hypervisor: " + hv.getHostName() + ", State/Status: " + hstate.toString()
-                    + "/" + hstatus.toString());
+            logger.debug("Host matching hypervisor: " + hv.getHostName() + ", State/Status: " + hstate.toString() + "/"
+                    + hstatus.toString());
             if (hstate != State.UP || hstatus != Status.ENABLED) {
                 return true;
             }
@@ -368,27 +354,21 @@ public class EvacuateServer extends ProviderServerOperation {
             throws APPCException {
         setMDC(Operation.EVACUATE_SERVICE.toString(), "App-C IaaS Adapter:Evacuate", ADAPTER_NAME);
         logOperation(Msg.EVACUATING_SERVER, params, context);
-
         setTimeForMetricsLogger();
-
         metricsLogger.info("Executing Provider Operation: Evacuate");
         return evacuateServer(params, context);
     }
 
     private void setTimeForMetricsLogger() {
-        long startTime = System.currentTimeMillis();
-        TimeZone tz = TimeZone.getTimeZone("UTC");
-        DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
-        df.setTimeZone(tz);
-        long endTime = System.currentTimeMillis();
-        long duration = endTime - startTime;
-        String durationStr = String.valueOf(duration);
-        String endTimeStrUTC = df.format(new Date());
-        MDC.put("EndTimestamp", endTimeStrUTC);
-        MDC.put("ElapsedTime", durationStr);
-        MDC.put("TargetEntity", "cdp");
-        MDC.put("TargetServiceName", "evacuate server");
-        MDC.put("ClassName", "org.onap.appc.adapter.iaas.provider.operation.impl.EvacuateServer");
+        String timestamp = LoggingUtils.generateTimestampStr(((Date) new Date()).toInstant());
+        MDC.put(LoggingConstants.MDCKeys.BEGIN_TIMESTAMP, timestamp);
+        MDC.put(LoggingConstants.MDCKeys.END_TIMESTAMP, timestamp);
+        MDC.put(LoggingConstants.MDCKeys.ELAPSED_TIME, "0");
+        MDC.put(LoggingConstants.MDCKeys.STATUS_CODE, LoggingConstants.StatusCodes.COMPLETE);
+        MDC.put(LoggingConstants.MDCKeys.TARGET_ENTITY, "cdp");
+        MDC.put(LoggingConstants.MDCKeys.TARGET_SERVICE_NAME, "evacuate server");
+        MDC.put(LoggingConstants.MDCKeys.CLASS_NAME,
+                "org.onap.appc.adapter.iaas.provider.operation.impl.EvacuateServer");
     }
 
     public void setProvideAdapterRef(ProviderAdapterImpl pai) {
index 3ce290b..559659a 100644 (file)
@@ -22,7 +22,7 @@
  */
 
 package org.onap.appc.adapter.iaas.provider.operation.impl;
-
+import com.att.cdp.exceptions.ContextConnectionException;
 import com.att.cdp.exceptions.ZoneException;
 import com.att.cdp.zones.ComputeService;
 import com.att.cdp.zones.Context;
@@ -33,6 +33,8 @@ import com.att.eelf.configuration.EELFManager;
 import com.att.eelf.i18n.EELFResourceManager;
 import org.glassfish.grizzly.http.util.HttpStatus;
 import org.onap.appc.Constants;
+import org.onap.appc.logging.LoggingConstants;
+import org.onap.appc.logging.LoggingUtils;
 import org.onap.appc.adapter.iaas.ProviderAdapter;
 import org.onap.appc.adapter.iaas.impl.IdentityURL;
 import org.onap.appc.adapter.iaas.impl.RequestContext;
@@ -45,6 +47,8 @@ import org.onap.appc.configuration.Configuration;
 import org.onap.appc.configuration.ConfigurationFactory;
 import org.onap.appc.exceptions.APPCException;
 import org.onap.appc.i18n.Msg;
+import org.onap.appc.logging.LoggingConstants;
+import org.onap.appc.logging.LoggingUtils;
 import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
 import org.slf4j.MDC;
 import java.io.IOException;
@@ -61,19 +65,17 @@ import static org.onap.appc.adapter.utils.Constants.ADAPTER_NAME;
 
 public class MigrateServer extends ProviderServerOperation {
 
-    private static final EELFLogger logger = EELFManager.getInstance().getLogger(EvacuateServer.class);
+    private static final EELFLogger logger = EELFManager.getInstance().getLogger(MigrateServer.class);
     private static EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger();
     private static final Configuration configuration = ConfigurationFactory.getConfiguration();
 
     /**
      * A list of valid initial VM statuses for a migrate operations
      */
-    private final Collection<Server.Status> migratableStatuses =
-            Arrays.asList(Server.Status.READY, Server.Status.RUNNING, Server.Status.SUSPENDED);
-
+    private final Collection<Server.Status> migratableStatuses = Arrays.asList(Server.Status.READY,
+            Server.Status.RUNNING, Server.Status.SUSPENDED);
 
-    private String getConnectionExceptionMessage(RequestContext rc, Context ctx, ZoneException e)
-            throws ZoneException {
+    private String getConnectionExceptionMessage(RequestContext rc, Context ctx, ZoneException e) throws ZoneException {
         return EELFResourceManager.format(Msg.CONNECTION_FAILED_RETRY, ctx.getProvider().getName(),
                 ctx.getComputeService().getURL(), ctx.getTenant().getName(), ctx.getTenant().getId(), e.getMessage(),
                 Long.toString(rc.getRetryDelay()), Integer.toString(rc.getAttempts()),
@@ -85,28 +87,22 @@ public class MigrateServer extends ProviderServerOperation {
         String msg;
         Context ctx = server.getContext();
         ComputeService service = ctx.getComputeService();
-
         // Init status will equal final status
         Server.Status initialStatus = server.getStatus();
-
         if (initialStatus == null) {
             throw new ZoneException("Failed to determine server's starting status");
         }
-
         // We can only migrate certain statuses
         if (!migratableStatuses.contains(initialStatus)) {
             throw new ZoneException(String.format("Cannot migrate server that is in %s state. Must be in one of [%s]",
                     initialStatus, migratableStatuses));
         }
-
         setTimeForMetricsLogger();
-
         // Is the skip Hypervisor check attribute populated?
         String skipHypervisorCheck = configuration.getProperty(Property.SKIP_HYPERVISOR_CHECK);
         if (skipHypervisorCheck == null && svcCtx != null) {
             skipHypervisorCheck = svcCtx.getAttribute(ProviderAdapter.SKIP_HYPERVISOR_CHECK);
         }
-
         // Always perform Hypervisor check
         // unless the skip is set to true
         if (skipHypervisorCheck == null || (!skipHypervisorCheck.equalsIgnoreCase("true"))) {
@@ -115,42 +111,57 @@ public class MigrateServer extends ProviderServerOperation {
         }
 
         boolean inConfirmPhase = false;
-
-        while (rc.attempt()) {
-            try {
-                if (!inConfirmPhase) {
-                    // Initial migrate request
-                    service.migrateServer(server.getId());
-                    // Wait for change to verify resize
-                    waitForStateChange(rc, server, Server.Status.READY);
-                    inConfirmPhase = true;
-                }
-
-                // Verify resize
-                service.processResize(server);
-                // Wait for complete. will go back to init status
-                waitForStateChange(rc, server, initialStatus);
-                logger.info("Completed migrate request successfully");
-                metricsLogger.info("Completed migrate request successfully");
-
-                break;
-
-            } catch (ZoneException e) {
+        try {
+            while (rc.attempt()) {
                 try {
+                    if (!inConfirmPhase) {
+                        // Initial migrate request
+                        service.migrateServer(server.getId());
+                        // Wait for change to verify resize
+                        waitForStateChange(rc, server, Server.Status.READY);
+                        inConfirmPhase = true;
+                    }
+                    if (server.getStatus() != null && server.getStatus().equals(Server.Status.ERROR)) {
+                        msg = "Cannot Perform 'processResize' in  vm_state " + Server.Status.ERROR;
+                        logger.info(msg);
+                        msg = EELFResourceManager.format(Msg.MIGRATE_SERVER_FAILED, service.getURL());
+                        logger.error(msg);
+                        logger.info(msg);
+                        throw new RequestFailedException("Waiting for State Change", msg, HttpStatus.CONFLICT_409,
+                                server);
+                    } else {
+                        // Verify resize
+                        logger.debug("MigrateServer: Before  service.processResize");
+                        service.processResize(server);
+                        logger.debug("MigrateServer:before 2nd waitForStateChange Current Status:" + server.getStatus()
+                                + " Initail Status: " + initialStatus);
+                        // Wait for complete. will go back to init status
+                        waitForStateChange(rc, server, initialStatus);
+                        logger.info("Completed migrate request successfully");
+                        metricsLogger.info("Completed migrate request successfully");
+                        return;
+                    }
+                } catch (ContextConnectionException e) {
                     msg = getConnectionExceptionMessage(rc, ctx, e);
-                } catch (ZoneException e1) {
-                    String phase = inConfirmPhase ? "VERIFY MIGRATE" : "REQUEST MIGRATE";
-                    msg = EELFResourceManager.format(Msg.MIGRATE_SERVER_FAILED, server.getName(), server.getId(), phase,
-                        e1.getMessage());
-                    generateEvent(rc, false, msg);
-                    logger.error(msg, e1);
-                    metricsLogger.error(msg, e1);
-                    throw new RequestFailedException("Migrate Server", msg, HttpStatus.METHOD_NOT_ALLOWED_405, server);
+                    // logger.info(msg, e);
+                    if (server.getStatus() != null && server.getStatus().equals(Server.Status.ERROR)) {
+                        throw new RequestFailedException("Migrate Server", msg, HttpStatus.CONFLICT_409, server);
+                    } else {
+                        logger.info("Migrate Server: Going to delay in ConnectionException");
+                        logger.debug("Server Status: " + server.getStatus());
+                        rc.delay();
+                    }
                 }
-                logger.error(msg, e);
-                metricsLogger.error(msg, e);
-                rc.delay();
+
             }
+
+        } catch (ZoneException e) {
+            String phase = inConfirmPhase ? "VERIFY MIGRATE" : "REQUEST MIGRATE";
+            msg = EELFResourceManager.format(Msg.MIGRATE_SERVER_FAILED, server.getName(), server.getId(), phase,
+                    e.getMessage());
+
+            logger.error(msg, e);
+            throw new RequestFailedException("Migrate Server", msg, HttpStatus.METHOD_NOT_ALLOWED_405, server);
         }
     }
 
@@ -162,29 +173,21 @@ public class MigrateServer extends ProviderServerOperation {
         Server server = null;
         RequestContext rc = new RequestContext(ctx);
         rc.isAlive();
-
         setTimeForMetricsLogger();
-
         try {
             validateParametersExist(params, ProviderAdapter.PROPERTY_INSTANCE_URL,
                     ProviderAdapter.PROPERTY_PROVIDER_NAME);
             String vm_url = params.get(ProviderAdapter.PROPERTY_INSTANCE_URL);
-
             String appName = configuration.getProperty(Constants.PROPERTY_APPLICATION_NAME);
             VMURL vm = VMURL.parseURL(vm_url);
-
             if (validateVM(rc, appName, vm_url, vm))
                 return null;
-
             IdentityURL ident = IdentityURL.parseURL(params.get(ProviderAdapter.PROPERTY_IDENTITY_URL));
             String identStr = (ident == null) ? null : ident.toString();
-
             server = conductServerMigration(rc, vm_url, identStr, ctx);
-
         } catch (RequestFailedException e) {
             doFailure(rc, e.getStatus(), e.getMessage());
         }
-
         return server;
     }
 
@@ -193,36 +196,30 @@ public class MigrateServer extends ProviderServerOperation {
             throws APPCException {
         setMDC(Operation.MIGRATE_SERVICE.toString(), "App-C IaaS Adapter:Migrate", ADAPTER_NAME);
         logOperation(Msg.MIGRATING_SERVER, params, context);
-
         setTimeForMetricsLogger();
-
         metricsLogger.info("Executing Provider Operation: Migrate");
-
         return migrateServer(params, context);
     }
 
     private void setTimeForMetricsLogger() {
-        long startTime = System.currentTimeMillis();
-        TimeZone tz = TimeZone.getTimeZone("UTC");
-        DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
-        df.setTimeZone(tz);
-        long endTime = System.currentTimeMillis();
-        long duration = endTime - startTime;
-        String durationStr = String.valueOf(duration);
-        String endTimeStrUTC = df.format(new Date());
-        MDC.put("EndTimestamp", endTimeStrUTC);
-        MDC.put("ElapsedTime", durationStr);
-        MDC.put("TargetEntity", "cdp");
-        MDC.put("TargetServiceName", "migrate server");
-        MDC.put("ClassName", "org.onap.appc.adapter.iaas.provider.operation.impl.MigrateServer");
+        String timestamp = LoggingUtils.generateTimestampStr(((Date) new Date()).toInstant());
+        MDC.put(LoggingConstants.MDCKeys.BEGIN_TIMESTAMP, timestamp);
+        MDC.put(LoggingConstants.MDCKeys.END_TIMESTAMP, timestamp);
+        MDC.put(LoggingConstants.MDCKeys.ELAPSED_TIME, "0");
+        MDC.put(LoggingConstants.MDCKeys.STATUS_CODE, LoggingConstants.StatusCodes.COMPLETE);
+        MDC.put(LoggingConstants.MDCKeys.TARGET_ENTITY, "cdp");
+        MDC.put(LoggingConstants.MDCKeys.TARGET_SERVICE_NAME, "migrate server");
+        MDC.put(LoggingConstants.MDCKeys.CLASS_NAME,
+                "org.onap.appc.adapter.iaas.provider.operation.impl.MigrateServer");
+
     }
 
-    private Server conductServerMigration(RequestContext rc, String vm_url, String identStr, SvcLogicContext ctx) throws RequestFailedException {
+    private Server conductServerMigration(RequestContext rc, String vm_url, String identStr, SvcLogicContext ctx)
+            throws RequestFailedException {
         String msg;
         Context context = getContext(rc, vm_url, identStr);
         VMURL vm = VMURL.parseURL(vm_url);
         Server server = null;
-
         try {
             if (context != null) {
                 server = lookupServer(rc, context, vm.getServerId());
index d5be609..fa8b22b 100644 (file)
@@ -1,25 +1,25 @@
 /*
- * ============LICENSE_START=======================================================
- * ONAP : APPC
- * ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Copyright (C) 2017 Amdocs
- * =============================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- 
- *      http://www.apache.org/licenses/LICENSE-2.0
- 
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- 
- * ============LICENSE_END=========================================================
- */
+* ============LICENSE_START=======================================================
+* ONAP : APPC
+* ================================================================================
+* Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+* ================================================================================
+* Copyright (C) 2017 Amdocs
+* =============================================================================
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+* 
+*      http://www.apache.org/licenses/LICENSE-2.0
+* 
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+* 
+* ============LICENSE_END=========================================================
+*/
 
 package org.onap.appc.adapter.iaas.provider.operation.impl;
 
@@ -39,6 +39,8 @@ import com.att.eelf.configuration.EELFManager;
 import com.att.eelf.i18n.EELFResourceManager;
 import org.glassfish.grizzly.http.util.HttpStatus;
 import org.onap.appc.Constants;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
 import org.onap.appc.adapter.iaas.ProviderAdapter;
 import org.onap.appc.adapter.iaas.impl.IdentityURL;
 import org.onap.appc.adapter.iaas.impl.RequestContext;
@@ -52,6 +54,8 @@ import org.onap.appc.configuration.Configuration;
 import org.onap.appc.configuration.ConfigurationFactory;
 import org.onap.appc.exceptions.APPCException;
 import org.onap.appc.i18n.Msg;
+import org.onap.appc.logging.LoggingConstants;
+import org.onap.appc.logging.LoggingUtils;
 import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
 import org.slf4j.MDC;
 import java.text.DateFormat;
@@ -62,38 +66,42 @@ import java.util.Map;
 import java.util.TimeZone;
 import static org.onap.appc.adapter.iaas.provider.operation.common.enums.Operation.STOP_SERVICE;
 import static org.onap.appc.adapter.utils.Constants.ADAPTER_NAME;
+import com.att.cdp.exceptions.StateException;
 
 public class RebuildServer extends ProviderServerOperation {
 
     private static final EELFLogger logger = EELFManager.getInstance().getLogger(RebuildServer.class);
     private static EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger();
     private static final Configuration configuration = ConfigurationFactory.getConfiguration();
-    //the sleep time used by thread.sleep to give "some time for OpenStack to start processing the request"
+    // the sleep time used by thread.sleep to give "some time for OpenStack to start
+    // processing the request"
     private long rebuildSleepTime = 10L * 1000L;
 
     /**
-     * Rebuild the indicated server with the indicated image. This method assumes the server has been determined to be
-     * in the correct state to do the rebuild.
+     * Rebuild the indicated server with the indicated image. This method assumes
+     * the server has been determined to be in the correct state to do the rebuild.
      *
-     * @param rc The request context that manages the state and recovery of the request for the life of its processing.
-     * @param server the server to be rebuilt
-     * @param image The image to be used (or snapshot)
-     * @throws RequestFailedException if the server does not change state in the allotted time
+     * @param rc
+     *            The request context that manages the state and recovery of the
+     *            request for the life of its processing.
+     * @param server
+     *            the server to be rebuilt
+     * @param image
+     *            The image to be used (or snapshot)
+     * @throws RequestFailedException
+     *             if the server does not change state in the allotted time
      */
     @SuppressWarnings("nls")
     private void rebuildServer(RequestContext rc, Server server, String image) throws RequestFailedException {
         logger.debug(Msg.REBUILD_SERVER, server.getId());
-
         String msg;
         Context context = server.getContext();
         Provider provider = context.getProvider();
         ComputeService service = context.getComputeService();
-
         /*
          * Set Time for Metrics Logger
          */
         setTimeForMetricsLogger();
-
         try {
             while (rc.attempt()) {
                 try {
@@ -109,7 +117,6 @@ public class RebuildServer extends ProviderServerOperation {
                     rc.delay();
                 }
             }
-
             /*
              * We need to provide some time for OpenStack to start processing the request.
              */
@@ -126,14 +133,13 @@ public class RebuildServer extends ProviderServerOperation {
             metricsLogger.error(msg);
             throw new RequestFailedException("Rebuild Server", msg, HttpStatus.BAD_GATEWAY_502, server);
         }
-
         rc.reset();
         /*
-         * Once we have started the process, now we wait for the final state of stopped. This should be the final state
-         * (since we started the rebuild with the server stopped).
+         * Once we have started the process, now we wait for the final state of stopped.
+         * This should be the final state (since we started the rebuild with the server
+         * stopped).
          */
         waitForStateChange(rc, server, Server.Status.READY);
-
         if (rc.isFailed()) {
             msg = EELFResourceManager.format(Msg.CONNECTION_FAILED, provider.getName(), service.getURL());
             logger.error(msg);
@@ -146,25 +152,29 @@ public class RebuildServer extends ProviderServerOperation {
     /**
      * This method is called to rebuild the provided server.
      * <p>
-     * If the server was booted from a volume, then the request is failed immediately and no action is taken. Rebuilding
-     * a VM from a bootable volume, where the bootable volume itself is not rebuilt, serves no purpose.
+     * If the server was booted from a volume, then the request is failed
+     * immediately and no action is taken. Rebuilding a VM from a bootable volume,
+     * where the bootable volume itself is not rebuilt, serves no purpose.
      * </p>
      *
-     * @param rc The request context that manages the state and recovery of the request for the life of its processing.
-     * @param server The server to be rebuilt
-     * @throws ZoneException When error occurs
-     * @throws RequestFailedException When server status is error
+     * @param rc
+     *            The request context that manages the state and recovery of the
+     *            request for the life of its processing.
+     * @param server
+     *            The server to be rebuilt
+     * @throws ZoneException
+     *             When error occurs
+     * @throws RequestFailedException
+     *             When server status is error
      */
     @SuppressWarnings("nls")
     private void rebuildServer(RequestContext rc, Server server, SvcLogicContext ctx)
             throws ZoneException, RequestFailedException {
         ServerBootSource builtFrom = server.getBootSource();
-
         /*
          * Set Time for Metrics Logger
          */
         setTimeForMetricsLogger();
-
         String msg;
         // Throw exception for non image/snap boot source
         if (ServerBootSource.VOLUME.equals(builtFrom)) {
@@ -175,11 +185,11 @@ public class RebuildServer extends ProviderServerOperation {
             metricsLogger.error(msg);
             throw new RequestFailedException("Rebuild Server", msg, HttpStatus.FORBIDDEN_403, server);
         }
-
         /*
-         * Pending is a bit of a special case. If we find the server is in a pending state, then the provider is in the
-         * process of changing state of the server. So, lets try to wait a little bit and see if the state settles down
-         * to one we can deal with. If not, then we have to fail the request.
+         * Pending is a bit of a special case. If we find the server is in a pending
+         * state, then the provider is in the process of changing state of the server.
+         * So, lets try to wait a little bit and see if the state settles down to one we
+         * can deal with. If not, then we have to fail the request.
          */
         Context context = server.getContext();
         Provider provider = context.getProvider();
@@ -189,27 +199,39 @@ public class RebuildServer extends ProviderServerOperation {
             waitForStateChange(rc, server, Server.Status.READY, Server.Status.RUNNING, Server.Status.ERROR,
                     Server.Status.SUSPENDED, Server.Status.PAUSED);
         }
-
         // Is the skip Hypervisor check attribute populated?
         String skipHypervisorCheck = configuration.getProperty(Property.SKIP_HYPERVISOR_CHECK);
         if (skipHypervisorCheck == null && ctx != null) {
             skipHypervisorCheck = ctx.getAttribute(ProviderAdapter.SKIP_HYPERVISOR_CHECK);
         }
-
         // Always perform Hypervisor Status checks
         // unless the skip is set to true
         if (skipHypervisorCheck == null || (!skipHypervisorCheck.equalsIgnoreCase("true"))) {
             // Check of the Hypervisor for the VM Server is UP and reachable
             checkHypervisor(server);
         }
-
         /*
-         * Get the image to use. This is determined by the presence or absence of snapshot images. If any snapshots
-         * exist, then the latest snapshot is used, otherwise the image used to construct the VM is used.
+         * Get the image to use in this priority order: (1) If snapshot-id provided in
+         * the request, use this (2) If any snapshots exist, then the latest snapshot is
+         * used (3) Otherwise the image used to construct the VM is used.
          */
+        String imageToUse = "";
+        try {
+            ObjectMapper mapper = new ObjectMapper();
+            String payloadStr = configuration.getProperty(Property.PAYLOAD);
+            if (payloadStr == null || payloadStr.isEmpty()) {
+                payloadStr = ctx.getAttribute(ProviderAdapter.PAYLOAD);
+            }
+            JsonNode payloadNode = mapper.readTree(payloadStr);
+            imageToUse = payloadNode.get(ProviderAdapter.PROPERTY_REQUEST_SNAPSHOT_ID).textValue();
+            logger.debug("Pulled snapshot-id " + imageToUse + " from the payload");
+        } catch (Exception e) {
+            logger.debug("Exception attempting to pull snapshot-id from the payload: " + e.toString());
+        }
         List<Image> snapshots = server.getSnapshots();
-        String imageToUse;
-        if (snapshots != null && !snapshots.isEmpty()) {
+        if (!imageToUse.isEmpty()) {
+            logger.debug("Using snapshot-id " + imageToUse + " for the rebuild request");
+        } else if (snapshots != null && !snapshots.isEmpty()) {
             imageToUse = snapshots.get(0).getId();
         } else {
             imageToUse = server.getImage();
@@ -219,8 +241,8 @@ public class RebuildServer extends ProviderServerOperation {
                 while (rc.attempt()) {
                     try {
                         /*
-                         * We are just trying to make sure that the image exists. We arent interested in the details at
-                         * this point.
+                         * We are just trying to make sure that the image exists. We arent interested in
+                         * the details at this point.
                          */
                         imageService.getImage(imageToUse);
                         break;
@@ -249,82 +271,75 @@ public class RebuildServer extends ProviderServerOperation {
             throw new RequestFailedException("Rebuild Server", msg, HttpStatus.BAD_GATEWAY_502, server);
         }
         rc.reset();
-
         /*
          * We determine what to do based on the current state of the server
          */
         switch (server.getStatus()) {
-            case DELETED:
-                // Nothing to do, the server is gone
-                msg = EELFResourceManager.format(Msg.SERVER_DELETED, server.getName(), server.getId(),
-                        server.getTenantId(), "rebuilt");
-                generateEvent(rc, false, msg);
-                logger.error(msg);
-                metricsLogger.error(msg);
-                throw new RequestFailedException("Rebuild Server", msg, HttpStatus.METHOD_NOT_ALLOWED_405, server);
-
-            case RUNNING:
-                // Attempt to stop the server, then rebuild it
-                stopServer(rc, server);
-                rc.reset();
-                rebuildServer(rc, server, imageToUse);
-                rc.reset();
-                startServer(rc, server);
-                generateEvent(rc, true, Outcome.SUCCESS.toString());
-                metricsLogger.info("Server status: RUNNING");
-                break;
-
-            case ERROR:
-                msg = EELFResourceManager.format(Msg.SERVER_ERROR_STATE, server.getName(), server.getId(),
-                        server.getTenantId(), "rebuild");
-                generateEvent(rc, false, msg);
-                logger.error(msg);
-                metricsLogger.error(msg);
-                throw new RequestFailedException("Rebuild Server", msg, HttpStatus.METHOD_NOT_ALLOWED_405, server);
-
-            case READY:
-                // Attempt to rebuild the server
-                rebuildServer(rc, server, imageToUse);
-                rc.reset();
-                startServer(rc, server);
-                generateEvent(rc, true, Outcome.SUCCESS.toString());
-                metricsLogger.info("Server status: READY");
-                break;
-
-            case PAUSED:
-                // if paused, un-pause it, stop it, and rebuild it
-                unpauseServer(rc, server);
-                rc.reset();
-                stopServer(rc, server);
-                rc.reset();
-                rebuildServer(rc, server, imageToUse);
-                rc.reset();
-                startServer(rc, server);
-                generateEvent(rc, true, Outcome.SUCCESS.toString());
-                metricsLogger.info("Server status: PAUSED");
-                break;
-
-            case SUSPENDED:
-                // Attempt to resume the suspended server, stop it, and rebuild it
-                resumeServer(rc, server);
-                rc.reset();
-                stopServer(rc, server);
-                rc.reset();
-                rebuildServer(rc, server, imageToUse);
-                rc.reset();
-                startServer(rc, server);
-                generateEvent(rc, true, Outcome.SUCCESS.toString());
-                metricsLogger.info("Server status: SUSPENDED");
-                break;
-
-            default:
-                // Hmmm, unknown status, should never occur
-                msg = EELFResourceManager.format(Msg.UNKNOWN_SERVER_STATE, server.getName(), server.getId(),
-                        server.getTenantId(), server.getStatus().name());
-                generateEvent(rc, false, msg);
-                logger.error(msg);
-                metricsLogger.error(msg);
-                throw new RequestFailedException("Rebuild Server", msg, HttpStatus.METHOD_NOT_ALLOWED_405, server);
+        case DELETED:
+            // Nothing to do, the server is gone
+            msg = EELFResourceManager.format(Msg.SERVER_DELETED, server.getName(), server.getId(), server.getTenantId(),
+                    "rebuilt");
+            generateEvent(rc, false, msg);
+            logger.error(msg);
+            metricsLogger.error(msg);
+            throw new RequestFailedException("Rebuild Server", msg, HttpStatus.METHOD_NOT_ALLOWED_405, server);
+        case RUNNING:
+            // Attempt to stop the server, then rebuild it
+            stopServer(rc, server);
+            rc.reset();
+            rebuildServer(rc, server, imageToUse);
+            rc.reset();
+            startServer(rc, server);
+            generateEvent(rc, true, Outcome.SUCCESS.toString());
+            metricsLogger.info("Server status: RUNNING");
+            break;
+        case ERROR:
+            msg = EELFResourceManager.format(Msg.SERVER_ERROR_STATE, server.getName(), server.getId(),
+                    server.getTenantId(), "rebuild");
+            generateEvent(rc, false, msg);
+            logger.error(msg);
+            metricsLogger.error(msg);
+            throw new RequestFailedException("Rebuild Server", msg, HttpStatus.METHOD_NOT_ALLOWED_405, server);
+        case READY:
+            // Attempt to rebuild the server
+            rebuildServer(rc, server, imageToUse);
+            rc.reset();
+            startServer(rc, server);
+            generateEvent(rc, true, Outcome.SUCCESS.toString());
+            metricsLogger.info("Server status: READY");
+            break;
+        case PAUSED:
+            // if paused, un-pause it, stop it, and rebuild it
+            unpauseServer(rc, server);
+            rc.reset();
+            stopServer(rc, server);
+            rc.reset();
+            rebuildServer(rc, server, imageToUse);
+            rc.reset();
+            startServer(rc, server);
+            generateEvent(rc, true, Outcome.SUCCESS.toString());
+            metricsLogger.info("Server status: PAUSED");
+            break;
+        case SUSPENDED:
+            // Attempt to resume the suspended server, stop it, and rebuild it
+            resumeServer(rc, server);
+            rc.reset();
+            stopServer(rc, server);
+            rc.reset();
+            rebuildServer(rc, server, imageToUse);
+            rc.reset();
+            startServer(rc, server);
+            generateEvent(rc, true, Outcome.SUCCESS.toString());
+            metricsLogger.info("Server status: SUSPENDED");
+            break;
+        default:
+            // Hmmm, unknown status, should never occur
+            msg = EELFResourceManager.format(Msg.UNKNOWN_SERVER_STATE, server.getName(), server.getId(),
+                    server.getTenantId(), server.getStatus().name());
+            generateEvent(rc, false, msg);
+            logger.error(msg);
+            metricsLogger.error(msg);
+            throw new RequestFailedException("Rebuild Server", msg, HttpStatus.METHOD_NOT_ALLOWED_405, server);
         }
     }
 
@@ -337,9 +352,7 @@ public class RebuildServer extends ProviderServerOperation {
         Server server = null;
         RequestContext rc = new RequestContext(ctx);
         rc.isAlive();
-
         setTimeForMetricsLogger();
-
         String msg;
         try {
             validateParametersExist(params, ProviderAdapter.PROPERTY_INSTANCE_URL,
@@ -350,21 +363,18 @@ public class RebuildServer extends ProviderServerOperation {
             VMURL vm = VMURL.parseURL(vm_url);
             if (validateVM(rc, appName, vm_url, vm))
                 return null;
-
             IdentityURL ident = IdentityURL.parseURL(params.get(ProviderAdapter.PROPERTY_IDENTITY_URL));
             String identStr = (ident == null) ? null : ident.toString();
             ctx.setAttribute("REBUILD_STATUS", "ERROR");
-
             Context context = null;
-            String tenantName = "Unknown";//to be used also in case of exception
+            String tenantName = "Unknown";// to be used also in case of exception
             try {
                 context = getContext(rc, vm_url, identStr);
                 if (context != null) {
-                    tenantName = context.getTenantName();//this varaible also is used in case of exception
+                    tenantName = context.getTenantName();// this varaible also is used in case of exception
                     rc.reset();
                     server = lookupServer(rc, context, vm.getServerId());
                     logger.debug(Msg.SERVER_FOUND, vm_url, tenantName, server.getStatus().toString());
-
                     // Manually checking image service until new PAL release
                     if (hasImageAccess(rc, context)) {
                         rebuildServer(rc, server, ctx);
@@ -381,7 +391,12 @@ public class RebuildServer extends ProviderServerOperation {
                 } else {
                     ctx.setAttribute("REBUILD_STATUS", "CONTEXT_NOT_FOUND");
                 }
-            } catch (RequestFailedException e) {
+            } catch (StateException ex) {
+                logger.error(ex.getMessage());
+                ctx.setAttribute("REBUILD_STATUS", "ERROR");
+                doFailure(rc, HttpStatus.CONFLICT_409, ex.getMessage());
+            }
+            catch (RequestFailedException e) {
                 doFailure(rc, e.getStatus(), e.getMessage());
                 ctx.setAttribute("REBUILD_STATUS", "ERROR");
             } catch (ResourceNotFoundException e) {
@@ -399,10 +414,10 @@ public class RebuildServer extends ProviderServerOperation {
                 doFailure(rc, HttpStatus.INTERNAL_SERVER_ERROR_500, msg);
             }
         } catch (RequestFailedException e) {
-            doFailure(rc, e.getStatus(), e.getMessage());
+
             ctx.setAttribute("REBUILD_STATUS", "ERROR");
+            doFailure(rc, e.getStatus(), e.getMessage());
         }
-
         return server;
     }
 
@@ -411,37 +426,32 @@ public class RebuildServer extends ProviderServerOperation {
             throws APPCException {
         setMDC(Operation.REBUILD_SERVICE.toString(), "App-C IaaS Adapter:Rebuild", ADAPTER_NAME);
         logOperation(Msg.REBUILDING_SERVER, params, context);
-
         setTimeForMetricsLogger();
-
         metricsLogger.info("Executing Provider Operation: Rebuild");
-
         return rebuildServer(params, context);
     }
 
     private void setTimeForMetricsLogger() {
-        long startTime = System.currentTimeMillis();
-        TimeZone tz = TimeZone.getTimeZone("UTC");
-        DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
-        df.setTimeZone(tz);
-        long endTime = System.currentTimeMillis();
-        long duration = endTime - startTime;
-        String durationStr = String.valueOf(duration);
-        String endTimeStrUTC = df.format(new Date());
-        MDC.put("EndTimestamp", endTimeStrUTC);
-        MDC.put("ElapsedTime", durationStr);
-        MDC.put("TargetEntity", "cdp");
-        MDC.put("TargetServiceName", "rebuild server");
-        MDC.put("ClassName", "org.onap.appc.adapter.iaas.provider.operation.impl.RebuildServer");
+        String timestamp = LoggingUtils.generateTimestampStr(((Date) new Date()).toInstant());
+        MDC.put(LoggingConstants.MDCKeys.BEGIN_TIMESTAMP, timestamp);
+        MDC.put(LoggingConstants.MDCKeys.END_TIMESTAMP, timestamp);
+        MDC.put(LoggingConstants.MDCKeys.ELAPSED_TIME, "0");
+        MDC.put(LoggingConstants.MDCKeys.STATUS_CODE, LoggingConstants.StatusCodes.COMPLETE);
+        MDC.put(LoggingConstants.MDCKeys.TARGET_ENTITY, "cdp");
+        MDC.put(LoggingConstants.MDCKeys.TARGET_SERVICE_NAME, "rebuild server");
+        MDC.put(LoggingConstants.MDCKeys.CLASS_NAME,
+                "org.onap.appc.adapter.iaas.provider.operation.impl.RebuildServer");
+
     }
-    
+
     /**
-     * Sets the sleep time used by thread.sleep to give
-     * "some time for OpenStack to start processing the request".
+     * Sets the sleep time used by thread.sleep to give "some time for OpenStack to
+     * start processing the request".
      *
-     * @param millis Time to sleep in milliseconds
+     * @param millis
+     *            Time to sleep in milliseconds
      */
-    public void setRebuildSleepTime(long millis){
+    public void setRebuildSleepTime(long millis) {
         this.rebuildSleepTime = millis;
     }
 }
index fbd3165..518b2e4 100644 (file)
@@ -45,6 +45,8 @@ import org.onap.appc.exceptions.UnknownProviderException;
 import org.onap.appc.i18n.Msg;
 import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
 import org.slf4j.MDC;
+import org.onap.appc.logging.LoggingConstants;
+import org.onap.appc.logging.LoggingUtils;
 import java.text.DateFormat;
 import java.text.SimpleDateFormat;
 import java.util.Date;
@@ -58,123 +60,122 @@ public class RestartServer extends ProviderServerOperation {
     private static final EELFLogger logger = EELFManager.getInstance().getLogger(RestartServer.class);
     private static EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger();
 
-
     /**
-     * This method handles the case of restarting a server once we have found the server and have obtained the abstract
-     * representation of the server via the context (i.e., the "Server" object from the CDP-Zones abstraction).
+     * This method handles the case of restarting a server once we have found the
+     * server and have obtained the abstract representation of the server via the
+     * context (i.e., the "Server" object from the CDP-Zones abstraction).
      *
-     * @param rc The request context that manages the state and recovery of the request for the life of its processing.
-     * @param server The server object representing the server we want to operate on
-     * @throws ZoneException when error occurs.
-     * @throws RequestFailedException when server status is error.
+     * @param rc
+     *            The request context that manages the state and recovery of the
+     *            request for the life of its processing.
+     * @param server
+     *            The server object representing the server we want to operate on
+     * @throws ZoneException
+     *             when error occurs.
+     * @throws RequestFailedException
+     *             when server status is error.
      */
     @SuppressWarnings("nls")
     private void restartServer(RequestContext rc, Server server, SvcLogicContext ctx)
             throws ZoneException, RequestFailedException {
         /*
-         * Pending is a bit of a special case. If we find the server is in a pending state, then the provider is in the
-         * process of changing state of the server. So, lets try to wait a little bit and see if the state settles down
-         * to one we can deal with. If not, then we have to fail the request.
+         * Pending is a bit of a special case. If we find the server is in a pending
+         * state, then the provider is in the process of changing state of the server.
+         * So, lets try to wait a little bit and see if the state settles down to one we
+         * can deal with. If not, then we have to fail the request.
          */
         String msg;
         if (server.getStatus().equals(Server.Status.PENDING)) {
             waitForStateChange(rc, server, Server.Status.READY, Server.Status.RUNNING, Server.Status.ERROR,
                     Server.Status.SUSPENDED, Server.Status.PAUSED);
         }
-
         setTimeForMetricsLogger("restart server");
-
         String skipHypervisorCheck = configuration.getProperty(Property.SKIP_HYPERVISOR_CHECK);
         if (skipHypervisorCheck == null && ctx != null) {
             skipHypervisorCheck = ctx.getAttribute(ProviderAdapter.SKIP_HYPERVISOR_CHECK);
         }
-
         // Always perform Virtual Machine/Hypervisor Status/Network checks
         // unless the skip is set to true
         if (skipHypervisorCheck == null || (!skipHypervisorCheck.equalsIgnoreCase("true"))) {
             // Check of the Hypervisor for the VM Server is UP and reachable
             checkHypervisor(server);
         }
-
         /*
          * We determine what to do based on the current state of the server
          */
         switch (server.getStatus()) {
-            case DELETED:
-                // Nothing to do, the server is gone
-                msg = EELFResourceManager.format(Msg.SERVER_DELETED, server.getName(), server.getId(),
-                        server.getTenantId(), "restarted");
-                generateEvent(rc, false, msg);
-                logger.error(msg);
-                metricsLogger.error(msg);
-                break;
-
-            case RUNNING:
-                // Attempt to stop and start the server
-                stopServer(rc, server);
-                startServer(rc, server);
-                generateEvent(rc, true, Outcome.SUCCESS.toString());
-                metricsLogger.info("Server status: RUNNING");
-                break;
-
-            case ERROR:
-                msg = EELFResourceManager.format(Msg.SERVER_ERROR_STATE, server.getName(), server.getId(),
-                        server.getTenantId(), "restart");
-                generateEvent(rc, false, msg);
-                logger.error(msg);
-                metricsLogger.error(msg);
-                throw new RequestFailedException("Restart Server", msg, HttpStatus.METHOD_NOT_ALLOWED_405, server);
-
-            case READY:
-                // Attempt to start the server
-                startServer(rc, server);
-                generateEvent(rc, true, Outcome.SUCCESS.toString());
-                metricsLogger.info("Server status: READY");
-                break;
-
-            case PAUSED:
-                // if paused, un-pause it
-                unpauseServer(rc, server);
-                generateEvent(rc, true, Outcome.SUCCESS.toString());
-                metricsLogger.info("Server status: PAUSED");
-                break;
-
-            case SUSPENDED:
-                // Attempt to resume the suspended server
-                resumeServer(rc, server);
-                generateEvent(rc, true, Outcome.SUCCESS.toString());
-                metricsLogger.info("Server status: SUSPENDED");
-                break;
-
-            default:
-                // Hmmm, unknown status, should never occur
-                msg = EELFResourceManager.format(Msg.UNKNOWN_SERVER_STATE, server.getName(), server.getId(),
-                        server.getTenantId(), server.getStatus().name());
-                generateEvent(rc, false, msg);
-                logger.error(msg);
-                metricsLogger.error(msg);
-                break;
+        case DELETED:
+            // Nothing to do, the server is gone
+            msg = EELFResourceManager.format(Msg.SERVER_DELETED, server.getName(), server.getId(), server.getTenantId(),
+                    "restarted");
+            generateEvent(rc, false, msg);
+            logger.error(msg);
+            metricsLogger.error(msg);
+            break;
+        case RUNNING:
+            // Attempt to stop and start the server
+            stopServer(rc, server);
+            startServer(rc, server);
+            generateEvent(rc, true, Outcome.SUCCESS.toString());
+            metricsLogger.info("Server status: RUNNING");
+            break;
+        case ERROR:
+            msg = EELFResourceManager.format(Msg.SERVER_ERROR_STATE, server.getName(), server.getId(),
+                    server.getTenantId(), "restart");
+            generateEvent(rc, false, msg);
+            logger.error(msg);
+            metricsLogger.error(msg);
+            throw new RequestFailedException("Restart Server", msg, HttpStatus.METHOD_NOT_ALLOWED_405, server);
+        case READY:
+            // Attempt to start the server
+            startServer(rc, server);
+            generateEvent(rc, true, Outcome.SUCCESS.toString());
+            metricsLogger.info("Server status: READY");
+            break;
+        case PAUSED:
+            // if paused, un-pause it
+            unpauseServer(rc, server);
+            generateEvent(rc, true, Outcome.SUCCESS.toString());
+            metricsLogger.info("Server status: PAUSED");
+            break;
+        case SUSPENDED:
+            // Attempt to resume the suspended server
+            resumeServer(rc, server);
+            generateEvent(rc, true, Outcome.SUCCESS.toString());
+            metricsLogger.info("Server status: SUSPENDED");
+            break;
+        default:
+            // Hmmm, unknown status, should never occur
+            msg = EELFResourceManager.format(Msg.UNKNOWN_SERVER_STATE, server.getName(), server.getId(),
+                    server.getTenantId(), server.getStatus().name());
+            generateEvent(rc, false, msg);
+            logger.error(msg);
+            metricsLogger.error(msg);
+            break;
         }
-
-
     }
 
     /**
-     * This method is used to restart an existing virtual machine given the fully qualified URL of the machine.
+     * This method is used to restart an existing virtual machine given the fully
+     * qualified URL of the machine.
      * <p>
-     * The fully qualified URL contains enough information to locate the appropriate server. The URL is of the form
+     * The fully qualified URL contains enough information to locate the appropriate
+     * server. The URL is of the form
      * 
      * <pre>
      *  [scheme]://[host[:port]] / [path] / [tenant_id] / servers / [vm_id]
      * </pre>
      * 
-     * Where the various parts of the URL can be parsed and extracted and used to locate the appropriate service in the
-     * provider service catalog. This then allows us to open a context using the CDP abstraction, obtain the server by
+     * Where the various parts of the URL can be parsed and extracted and used to
+     * locate the appropriate service in the provider service catalog. This then
+     * allows us to open a context using the CDP abstraction, obtain the server by
      * its UUID, and then perform the restart.
      * </p>
      *
-     * @throws UnknownProviderException If the provider cannot be found
-     * @throws IllegalArgumentException if the expected argument(s) are not defined or are invalid
+     * @throws UnknownProviderException
+     *             If the provider cannot be found
+     * @throws IllegalArgumentException
+     *             if the expected argument(s) are not defined or are invalid
      * @see org.onap.appc.adapter.iaas.ProviderAdapter#restartServer(java.util.Map,
      *      org.onap.ccsdk.sli.core.sli.SvcLogicContext)
      */
@@ -184,34 +185,27 @@ public class RestartServer extends ProviderServerOperation {
         Server server = null;
         RequestContext rc = new RequestContext(ctx);
         rc.isAlive();
-
         String appName = configuration.getProperty(Constants.PROPERTY_APPLICATION_NAME);
-
         /*
          * Set Time for Metrics Logger
          */
         setTimeForMetricsLogger("GET server status");
-
         ctx.setAttribute("RESTART_STATUS", "ERROR");
         try {
             validateParametersExist(params, ProviderAdapter.PROPERTY_INSTANCE_URL,
                     ProviderAdapter.PROPERTY_PROVIDER_NAME);
-
             String vm_url = params.get(ProviderAdapter.PROPERTY_INSTANCE_URL);
-
             VMURL vm = VMURL.parseURL(vm_url);
             if (validateVM(rc, appName, vm_url, vm))
                 return null;
-
             IdentityURL ident = IdentityURL.parseURL(params.get(ProviderAdapter.PROPERTY_IDENTITY_URL));
             String identStr = (ident == null) ? null : ident.toString();
-
             Context context = null;
-            String tenantName = "Unknown";//to be used also in case of exception
+            String tenantName = "Unknown";// to be used also in case of exception
             try {
                 context = getContext(rc, vm_url, identStr);
                 if (context != null) {
-                    tenantName = context.getTenantName();//this varaible also is used in case of exception
+                    tenantName = context.getTenantName();// this varaible also is used in case of exception
                     rc.reset();
                     server = lookupServer(rc, context, vm.getServerId());
                     logger.debug(Msg.SERVER_FOUND, vm_url, tenantName, server.getStatus().toString());
@@ -232,8 +226,7 @@ public class RestartServer extends ProviderServerOperation {
                 doFailure(rc, HttpStatus.NOT_FOUND_404, msg);
             } catch (Exception e1) {
                 String msg = EELFResourceManager.format(Msg.SERVER_OPERATION_EXCEPTION, e1,
-                        e1.getClass().getSimpleName(), RESTART_SERVICE.toString(), vm_url,
-                        tenantName);
+                        e1.getClass().getSimpleName(), RESTART_SERVICE.toString(), vm_url, tenantName);
                 logger.error(msg, e1);
                 metricsLogger.error(msg, e1);
                 doFailure(rc, HttpStatus.INTERNAL_SERVER_ERROR_500, msg);
@@ -241,7 +234,6 @@ public class RestartServer extends ProviderServerOperation {
         } catch (RequestFailedException e) {
             doFailure(rc, e.getStatus(), e.getMessage());
         }
-
         return server;
     }
 
@@ -250,27 +242,20 @@ public class RestartServer extends ProviderServerOperation {
             throws UnknownProviderException {
         setMDC(RESTART_SERVICE.toString(), "App-C IaaS Adapter:Restart", ADAPTER_NAME);
         logOperation(Msg.RESTARTING_SERVER, params, context);
-
         setTimeForMetricsLogger("execute restart");
-
         metricsLogger.info("Executing Provider Operation: Restart");
-
         return restartServer(params, context);
     }
 
     private void setTimeForMetricsLogger(String targetServiceName) {
-        long startTime = System.currentTimeMillis();
-        TimeZone tz = TimeZone.getTimeZone("UTC");
-        DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
-        df.setTimeZone(tz);
-        long endTime = System.currentTimeMillis();
-        long duration = endTime - startTime;
-        String durationStr = String.valueOf(duration);
-        String endTimeStrUTC = df.format(new Date());
-        MDC.put("EndTimestamp", endTimeStrUTC);
-        MDC.put("ElapsedTime", durationStr);
-        MDC.put("TargetEntity", "cdp");
-        MDC.put("TargetServiceName", targetServiceName);
-        MDC.put("ClassName", "org.onap.appc.adapter.iaas.provider.operation.impl.RestartServer");
+        String timestamp = LoggingUtils.generateTimestampStr(((Date) new Date()).toInstant());
+        MDC.put(LoggingConstants.MDCKeys.BEGIN_TIMESTAMP, timestamp);
+        MDC.put(LoggingConstants.MDCKeys.END_TIMESTAMP, timestamp);
+        MDC.put(LoggingConstants.MDCKeys.ELAPSED_TIME, "0");
+        MDC.put(LoggingConstants.MDCKeys.STATUS_CODE, LoggingConstants.StatusCodes.COMPLETE);
+        MDC.put(LoggingConstants.MDCKeys.TARGET_ENTITY, "cdp");
+        MDC.put(LoggingConstants.MDCKeys.TARGET_SERVICE_NAME, targetServiceName);
+        MDC.put(LoggingConstants.MDCKeys.CLASS_NAME,
+                "org.onap.appc.adapter.iaas.provider.operation.impl.RestartServer");
     }
 }
index ac35d4b..a0ce25c 100644 (file)
@@ -50,6 +50,8 @@ import org.onap.appc.adapter.openstack.heat.model.CreateSnapshotParams;
 import org.onap.appc.adapter.openstack.heat.model.Snapshot;
 import org.onap.appc.exceptions.APPCException;
 import org.onap.appc.i18n.Msg;
+import org.onap.appc.logging.LoggingConstants;
+import org.onap.appc.logging.LoggingUtils;
 import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
 import org.slf4j.MDC;
 import java.text.DateFormat;
@@ -64,41 +66,29 @@ public class SnapshotStack extends ProviderStackOperation {
     private static final EELFLogger logger = EELFManager.getInstance().getLogger(SnapshotStack.class);
     private static EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger();
 
-
     private Snapshot snapshotStack(@SuppressWarnings("unused") RequestContext rc, Stack stack)
             throws ZoneException, RequestFailedException {
         Snapshot snapshot = new Snapshot();
         Context context = stack.getContext();
-
         OpenStackContext osContext = (OpenStackContext) context;
-
         final HeatConnector heatConnector = osContext.getHeatConnector();
         ((OpenStackContext) context).refreshIfStale(heatConnector);
-
         trackRequest(context);
         RequestState.put("SERVICE", "Orchestration");
         RequestState.put("SERVICE_URL", heatConnector.getEndpoint());
-
         Heat heat = heatConnector.getClient();
-
         SnapshotResource snapshotResource = new SnapshotResource(heat);
-
         setTimeForMetricsLogger();
-
         try {
-
             snapshot = snapshotResource.create(stack.getName(), stack.getId(), new CreateSnapshotParams()).execute();
-
             // wait for the stack deletion
             StackResource stackResource = new StackResource(heat);
             if (!waitForStack(stack, stackResource, "SNAPSHOT_COMPLETE")) {
                 throw new RequestFailedException("Stack Snapshot failed.");
             }
-
         } catch (OpenStackBaseException e) {
             ExceptionMapper.mapException(e);
         }
-
         return snapshot;
     }
 
@@ -108,33 +98,26 @@ public class SnapshotStack extends ProviderStackOperation {
         RequestContext rc = new RequestContext(ctx);
         rc.isAlive();
         ctx.setAttribute("SNAPSHOT_STATUS", "STACK_NOT_FOUND");
-
         setTimeForMetricsLogger();
-
         String vm_url = null;
         Context context = null;
-        String tenantName = "Unknown";//to be used also in case of exception
+        String tenantName = "Unknown";// to be used also in case of exception
         try {
             validateParametersExist(params, ProviderAdapter.PROPERTY_INSTANCE_URL,
                     ProviderAdapter.PROPERTY_PROVIDER_NAME, ProviderAdapter.PROPERTY_STACK_ID);
-
             String stackId = params.get(ProviderAdapter.PROPERTY_STACK_ID);
             String appName = configuration.getProperty(Constants.PROPERTY_APPLICATION_NAME);
             vm_url = params.get(ProviderAdapter.PROPERTY_INSTANCE_URL);
             context = resolveContext(rc, params, appName, vm_url);
-
             if (context != null) {
-                tenantName = context.getTenantName();//this varaible also is used in case of exception
+                tenantName = context.getTenantName();// this varaible also is used in case of exception
                 stack = lookupStack(rc, context, stackId);
                 logger.debug(Msg.STACK_FOUND, vm_url, tenantName, stack.getStatus().toString());
                 logger.info(EELFResourceManager.format(Msg.SNAPSHOTING_STACK, stack.getName()));
                 metricsLogger.info(EELFResourceManager.format(Msg.SNAPSHOTING_STACK, stack.getName()));
-
                 Snapshot snapshot = snapshotStack(rc, stack);
-
                 ctx.setAttribute(ProviderAdapter.DG_OUTPUT_PARAM_NAMESPACE + ProviderAdapter.PROPERTY_SNAPSHOT_ID,
                         snapshot.getId());
-
                 logger.info(EELFResourceManager.format(Msg.STACK_SNAPSHOTED, stack.getName(), snapshot.getId()));
                 metricsLogger.info(EELFResourceManager.format(Msg.STACK_SNAPSHOTED, stack.getName(), snapshot.getId()));
                 context.close();
@@ -142,7 +125,6 @@ public class SnapshotStack extends ProviderStackOperation {
             } else {
                 ctx.setAttribute(Constants.DG_ATTRIBUTE_STATUS, "failure");
             }
-
         } catch (ResourceNotFoundException e) {
             String msg = EELFResourceManager.format(Msg.STACK_NOT_FOUND, e, vm_url);
             logger.error(msg);
@@ -168,27 +150,20 @@ public class SnapshotStack extends ProviderStackOperation {
             throws APPCException {
         setMDC(Operation.SNAPSHOT_STACK.toString(), "App-C IaaS Adapter:Snapshot-Stack", ADAPTER_NAME);
         logOperation(Msg.SNAPSHOTING_STACK, params, context);
-
         setTimeForMetricsLogger();
-
         metricsLogger.info("Executing Provider Operation: Snapshot Stack");
-
         return snapshotStack(params, context);
     }
 
     private void setTimeForMetricsLogger() {
-        long startTime = System.currentTimeMillis();
-        TimeZone tz = TimeZone.getTimeZone("UTC");
-        DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
-        df.setTimeZone(tz);
-        long endTime = System.currentTimeMillis();
-        long duration = endTime - startTime;
-        String durationStr = String.valueOf(duration);
-        String endTimeStrUTC = df.format(new Date());
-        MDC.put("EndTimestamp", endTimeStrUTC);
-        MDC.put("ElapsedTime", durationStr);
-        MDC.put("TargetEntity", "cdp");
-        MDC.put("TargetServiceName", "snapshot stack");
-        MDC.put("ClassName", "org.onap.appc.adapter.iaas.provider.operation.impl.SnapshotStack");
+        String timestamp = LoggingUtils.generateTimestampStr(((Date) new Date()).toInstant());
+        MDC.put(LoggingConstants.MDCKeys.BEGIN_TIMESTAMP, timestamp);
+        MDC.put(LoggingConstants.MDCKeys.END_TIMESTAMP, timestamp);
+        MDC.put(LoggingConstants.MDCKeys.ELAPSED_TIME, "0");
+        MDC.put(LoggingConstants.MDCKeys.STATUS_CODE, LoggingConstants.StatusCodes.COMPLETE);
+        MDC.put(LoggingConstants.MDCKeys.TARGET_ENTITY, "cdp");
+        MDC.put(LoggingConstants.MDCKeys.TARGET_SERVICE_NAME, "snapshot stack");
+        MDC.put(LoggingConstants.MDCKeys.CLASS_NAME,
+                "org.onap.appc.adapter.iaas.provider.operation.impl.SnapshotStack");
     }
 }
index 933b5d8..10236a8 100644 (file)
@@ -33,6 +33,8 @@ import org.onap.appc.adapter.iaas.provider.operation.common.enums.Outcome;
 import org.onap.appc.adapter.iaas.provider.operation.impl.base.ProviderServerOperation;
 import org.onap.appc.exceptions.APPCException;
 import org.onap.appc.i18n.Msg;
+import org.onap.appc.logging.LoggingConstants;
+import org.onap.appc.logging.LoggingUtils;
 import com.att.cdp.exceptions.ResourceNotFoundException;
 import com.att.cdp.zones.Context;
 import com.att.cdp.zones.model.ModelObject;
@@ -42,135 +44,117 @@ import com.att.eelf.configuration.EELFManager;
 import com.att.eelf.i18n.EELFResourceManager;
 import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
 import org.glassfish.grizzly.http.util.HttpStatus;
+import java.util.Date;
 import java.util.Map;
+import org.slf4j.MDC;
 import static org.onap.appc.adapter.iaas.provider.operation.common.enums.Operation.STOP_SERVICE;
 import static org.onap.appc.adapter.utils.Constants.ADAPTER_NAME;
 
 public class StopServer extends ProviderServerOperation {
 
-    private static final EELFLogger logger = EELFManager.getInstance().getLogger(StopServer.class);
-    private static EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger();
+    private final EELFLogger logger = EELFManager.getInstance().getLogger(StopServer.class);
+    private final EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger();
 
     /**
      * @see org.onap.appc.adapter.iaas.ProviderAdapter#stopServer(java.util.Map,
-     *      org.onap.ccsdk.sli.core.sli.SvcLogicContext)
+     *      org.openecomp.sdnc.sli.SvcLogicContext)
      */
     @SuppressWarnings("nls")
-    public Server stopServer(Map<String, String> params, SvcLogicContext ctx) throws APPCException {
+    private Server stopServer(Map<String, String> params, SvcLogicContext ctx) throws APPCException {
         Server server = null;
         RequestContext rc = new RequestContext(ctx);
         rc.isAlive();
-
+        setTimeForMetricsLogger();
         String appName = configuration.getProperty(Constants.PROPERTY_APPLICATION_NAME);
-
         try {
             validateParametersExist(params, ProviderAdapter.PROPERTY_INSTANCE_URL,
                     ProviderAdapter.PROPERTY_PROVIDER_NAME);
-
             String vm_url = params.get(ProviderAdapter.PROPERTY_INSTANCE_URL);
             ctx.setAttribute("STOP_STATUS", "SUCCESS");
-
             VMURL vm = VMURL.parseURL(vm_url);
             if (validateVM(rc, appName, vm_url, vm))
                 return null;
-
             IdentityURL ident = IdentityURL.parseURL(params.get(ProviderAdapter.PROPERTY_IDENTITY_URL));
             String identStr = (ident == null) ? null : ident.toString();
-
             Context context = null;
-            String tenantName = "Unknown";//to be used also in case of exception
             ctx.setAttribute("STOP_STATUS", "ERROR");
             try {
                 context = getContext(rc, vm_url, identStr);
                 if (context != null) {
-                    tenantName = context.getTenantName();//this varaible also is used in case of exception
                     rc.reset();
                     server = lookupServer(rc, context, vm.getServerId());
-                    logger.debug(Msg.SERVER_FOUND, vm_url, tenantName, server.getStatus().toString());
-
+                    logger.debug(Msg.SERVER_FOUND, vm_url, context.getTenantName(), server.getStatus().toString());
                     String msg;
                     /*
                      * We determine what to do based on the current state of the server
                      */
-
                     /*
-                     * Pending is a bit of a special case. If we find the server is in a pending state, then the
-                     * provider is in the process of changing state of the server. So, lets try to wait a little bit and
-                     * see if the state settles down to one we can deal with. If not, then we have to fail the request.
+                     * Pending is a bit of a special case. If we find the server is in a pending
+                     * state, then the provider is in the process of changing state of the server.
+                     * So, lets try to wait a little bit and see if the state settles down to one we
+                     * can deal with. If not, then we have to fail the request.
                      */
-
                     if (server.getStatus().equals(Server.Status.PENDING)) {
                         waitForStateChange(rc, server, Server.Status.READY, Server.Status.RUNNING, Server.Status.ERROR,
                                 Server.Status.SUSPENDED, Server.Status.PAUSED, Server.Status.DELETED);
                     }
-
                     switch (server.getStatus()) {
-                        case DELETED:
-                            // Nothing to do, the server is gone
-                            msg = EELFResourceManager.format(Msg.SERVER_DELETED, server.getName(), server.getId(),
-                                    server.getTenantId(), "stopped");
-                            generateEvent(rc, false, msg);
-                            logger.error(msg);
-                            metricsLogger.error(msg);
-                            throw new RequestFailedException("Stop Server", msg, HttpStatus.METHOD_NOT_ALLOWED_405,
-                                    server);
-
-                        case RUNNING:
-                            // Attempt to stop the server
-                            rc.reset();
-                            stopServer(rc, server);
-                            generateEvent(rc, true, Outcome.SUCCESS.toString());
-                            break;
-
-                        case ERROR:
-                            // Server is in error state
-                            msg = EELFResourceManager.format(Msg.SERVER_ERROR_STATE, server.getName(), server.getId(),
-                                    server.getTenantId(), "stop");
-                            generateEvent(rc, false, msg);
-                            logger.error(msg);
-                            metricsLogger.error(msg);
-                            throw new RequestFailedException("Stop Server", msg, HttpStatus.METHOD_NOT_ALLOWED_405,
-                                    server);
-
-                        case READY:
-                            // Nothing to do, the server was already stopped
-                            logger.info("Server was already stopped");
-                            break;
-
-                        case PAUSED:
-                            // if paused, un-pause it and then stop it
-                            rc.reset();
-                            unpauseServer(rc, server);
-                            rc.reset();
-                            stopServer(rc, server);
-                            generateEvent(rc, true, Outcome.SUCCESS.toString());
-                            break;
-
-                        case SUSPENDED:
-                            // Attempt to resume the suspended server and after that stop it
-                            rc.reset();
-                            resumeServer(rc, server);
-                            rc.reset();
-                            stopServer(rc, server);
-                            generateEvent(rc, true, Outcome.SUCCESS.toString());
-                            break;
-
-                        default:
-                            // Hmmm, unknown status, should never occur
-                            msg = EELFResourceManager.format(Msg.UNKNOWN_SERVER_STATE, server.getName(), server.getId(),
-                                    server.getTenantId(), server.getStatus().name());
-                            generateEvent(rc, false, msg);
-                            logger.error(msg);
-                            metricsLogger.error(msg);
-                            throw new RequestFailedException("Stop Server", msg, HttpStatus.METHOD_NOT_ALLOWED_405,
-                                    server);
+                    case DELETED:
+                        // Nothing to do, the server is gone
+                        msg = EELFResourceManager.format(Msg.SERVER_DELETED, server.getName(), server.getId(),
+                                server.getTenantId(), "stopped");
+                        generateEvent(rc, false, msg);
+                        logger.error(msg);
+                        metricsLogger.error(msg);
+                        throw new RequestFailedException("Stop Server", msg, HttpStatus.METHOD_NOT_ALLOWED_405, server);
+                    case RUNNING:
+                        // Attempt to stop the server
+                        rc.reset();
+                        stopServer(rc, server);
+                        generateEvent(rc, true, Outcome.SUCCESS.toString());
+                        break;
+                    case ERROR:
+                        // Server is in error state
+                        msg = EELFResourceManager.format(Msg.SERVER_ERROR_STATE, server.getName(), server.getId(),
+                                server.getTenantId(), "stop");
+                        generateEvent(rc, false, msg);
+                        logger.error(msg);
+                        metricsLogger.error(msg);
+                        throw new RequestFailedException("Stop Server", msg, HttpStatus.METHOD_NOT_ALLOWED_405, server);
+                    case READY:
+                        // Nothing to do, the server was already stopped
+                        logger.info("Server was already stopped");
+                        break;
+                    case PAUSED:
+                        // if paused, un-pause it and then stop it
+                        rc.reset();
+                        unpauseServer(rc, server);
+                        rc.reset();
+                        stopServer(rc, server);
+                        generateEvent(rc, true, Outcome.SUCCESS.toString());
+                        break;
+                    case SUSPENDED:
+                        // Attempt to resume the suspended server and after that stop it
+                        rc.reset();
+                        resumeServer(rc, server);
+                        rc.reset();
+                        stopServer(rc, server);
+                        generateEvent(rc, true, Outcome.SUCCESS.toString());
+                        break;
+                    default:
+                        // Hmmm, unknown status, should never occur
+                        msg = EELFResourceManager.format(Msg.UNKNOWN_SERVER_STATE, server.getName(), server.getId(),
+                                server.getTenantId(), server.getStatus().name());
+                        generateEvent(rc, false, msg);
+                        logger.error(msg);
+                        metricsLogger.error(msg);
+                        throw new RequestFailedException("Stop Server", msg, HttpStatus.METHOD_NOT_ALLOWED_405, server);
                     }
                     context.close();
                     doSuccess(rc);
                     ctx.setAttribute("STOP_STATUS", "SUCCESS");
                     msg = EELFResourceManager.format(Msg.SUCCESS_EVENT_MESSAGE, "StopServer", vm_url);
                     ctx.setAttribute(org.onap.appc.Constants.ATTRIBUTE_SUCCESS_MESSAGE, msg);
-
                 } else {
                     ctx.setAttribute("STOP_STATUS", "CONTEXT_NOT_FOUND");
                 }
@@ -179,9 +163,9 @@ public class StopServer extends ProviderServerOperation {
                 logger.error(msg);
                 doFailure(rc, HttpStatus.NOT_FOUND_404, msg);
             } catch (Exception e1) {
-                String msg =
-                        EELFResourceManager.format(Msg.SERVER_OPERATION_EXCEPTION, e1, e1.getClass().getSimpleName(),
-                                STOP_SERVICE.toString(), vm_url, tenantName);
+                String msg = EELFResourceManager.format(Msg.SERVER_OPERATION_EXCEPTION, e1,
+                        e1.getClass().getSimpleName(), STOP_SERVICE.toString(), vm_url,
+                        context == null ? "Unknown" : context.getTenantName());
                 logger.error(msg, e1);
                 doFailure(rc, HttpStatus.INTERNAL_SERVER_ERROR_500, msg);
             }
@@ -189,7 +173,6 @@ public class StopServer extends ProviderServerOperation {
             logger.error(EELFResourceManager.format(Msg.STOP_SERVER_FAILED, appName, "n/a", "n/a", e.getMessage()));
             doFailure(rc, e.getStatus(), e.getMessage());
         }
-
         return server;
     }
 
@@ -200,4 +183,15 @@ public class StopServer extends ProviderServerOperation {
         logOperation(Msg.STOPPING_SERVER, params, context);
         return stopServer(params, context);
     }
+    private void setTimeForMetricsLogger() {
+        String timestamp = LoggingUtils.generateTimestampStr(((Date) new Date()).toInstant());
+        MDC.put(LoggingConstants.MDCKeys.BEGIN_TIMESTAMP, timestamp);
+        MDC.put(LoggingConstants.MDCKeys.END_TIMESTAMP, timestamp);
+        MDC.put(LoggingConstants.MDCKeys.ELAPSED_TIME, "0");
+        MDC.put(LoggingConstants.MDCKeys.STATUS_CODE, LoggingConstants.StatusCodes.COMPLETE);
+        MDC.put(LoggingConstants.MDCKeys.TARGET_ENTITY, "cdp");
+        MDC.put(LoggingConstants.MDCKeys.TARGET_SERVICE_NAME, "stop server");
+        MDC.put(LoggingConstants.MDCKeys.CLASS_NAME, "org.onap.appc.adapter.iaas.provider.operation.impl.StopServer");
+    }
+
 }