enchance rebuildaction to make snapshotid Optional
[appc.git] / appc-adapters / appc-iaas-adapter / appc-iaas-adapter-bundle / src / main / java / org / onap / appc / adapter / iaas / provider / operation / impl / RebuildServer.java
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;
     }
 }