Rename the fields to match the regular expression
[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 7a66887..d7ade91 100644 (file)
@@ -2,7 +2,7 @@
 * ============LICENSE_START=======================================================
 * ONAP : APPC
 * ================================================================================
-* Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+* Copyright (C) 2017-2019 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=========================================================
 */
 
@@ -60,12 +60,9 @@ 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;
-import java.text.SimpleDateFormat;
 import java.util.Date;
 import java.util.List;
 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;
@@ -79,7 +76,7 @@ public class RebuildServer extends ProviderServerOperation {
     // 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.
      *
@@ -179,18 +176,19 @@ public class RebuildServer extends ProviderServerOperation {
          */
         setTimeForMetricsLogger();
         String msg;
-        //Throw error if boot source is unknown
+        // Throw error if boot source is unknown
         if (ServerBootSource.UNKNOWN.equals(builtFrom)) {
-            logger.debug("Boot Source Unknown" );
+            logger.debug("Boot Source Unknown");
             msg = String.format("Error occured when retrieving server boot source [%s]!!!", server.getId());
             logger.error(msg);
-            generateEvent(rc, false,msg);
+            generateEvent(rc, false, msg);
             metricsLogger.error(msg);
             throw new RequestFailedException("Rebuild Server", msg, HttpStatus.INTERNAL_SERVER_ERROR_500, server);
         }
 
         // Throw exception for non image/snap boot source
         if (ServerBootSource.VOLUME.equals(builtFrom)) {
+            logger.debug("Boot Source Not Supported built from bootable volume");
             msg = String.format("Rebuilding is currently not supported for servers built from bootable volumes [%s]",
                     server.getId());
             generateEvent(rc, false, msg);
@@ -219,7 +217,7 @@ public class RebuildServer extends ProviderServerOperation {
         }
         // Always perform Hypervisor Status checks
         // unless the skip is set to true
-        if (skipHypervisorCheck == null || (!skipHypervisorCheck.equalsIgnoreCase("true"))) {
+        if (skipHypervisorCheck == null || (!"true".equalsIgnoreCase(skipHypervisorCheck))) {
             // Check of the Hypervisor for the VM Server is UP and reachable
             checkHypervisor(server);
         }
@@ -242,13 +240,25 @@ public class RebuildServer extends ProviderServerOperation {
             logger.debug("Exception attempting to pull snapshot-id from the payload: " + e.toString());
         }
         List<Image> snapshots = server.getSnapshots();
+        ImageService imageService = server.getContext().getImageService();
+        List<Image> imageList = imageService.listImages();
         if (!imageToUse.isEmpty()) {
             logger.debug("Using snapshot-id " + imageToUse + " for the rebuild request");
+            boolean imgFound = validateSnapshotId(imageToUse, snapshots, imageList);
+
+            if (!imgFound) {
+                logger.debug("Image Snapshot Not Found");
+                msg = EELFResourceManager.format(Msg.REBUILD_SERVER_FAILED, server.getName(), server.getId(),
+                        "Invalid Snapshot-Id");
+                logger.error(msg);
+                metricsLogger.error(msg);
+                throw new RequestFailedException("Rebuild Server", msg, HttpStatus.FORBIDDEN_403, server);
+            }
         } else if (snapshots != null && !snapshots.isEmpty()) {
+            logger.debug("Using snapshot-id when image is Empty" + imageToUse + " for the rebuild request");
             imageToUse = snapshots.get(0).getId();
         } else {
             imageToUse = server.getImage();
-            ImageService imageService = server.getContext().getImageService();
             rc.reset();
             try {
                 while (rc.attempt()) {
@@ -370,11 +380,10 @@ public class RebuildServer extends ProviderServerOperation {
         try {
             validateParametersExist(params, ProviderAdapter.PROPERTY_INSTANCE_URL,
                     ProviderAdapter.PROPERTY_PROVIDER_NAME);
-
             String appName = configuration.getProperty(Constants.PROPERTY_APPLICATION_NAME);
-            String vm_url = params.get(ProviderAdapter.PROPERTY_INSTANCE_URL);
-            VMURL vm = VMURL.parseURL(vm_url);
-            if (validateVM(rc, appName, vm_url, vm))
+            String vmUrl = params.get(ProviderAdapter.PROPERTY_INSTANCE_URL);
+            VMURL vm = VMURL.parseURL(vmUrl);
+            if (validateVM(rc, appName, vmUrl, vm))
                 return null;
             IdentityURL ident = IdentityURL.parseURL(params.get(ProviderAdapter.PROPERTY_IDENTITY_URL));
             String identStr = (ident == null) ? null : ident.toString();
@@ -382,12 +391,12 @@ public class RebuildServer extends ProviderServerOperation {
             Context context = null;
             String tenantName = "Unknown";// to be used also in case of exception
             try {
-                context = getContext(rc, vm_url, identStr);
+                context = getContext(rc, vmUrl, 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, vmUrl, tenantName, server.getStatus().toString());
                     // Manually checking image service until new PAL release
                     if (hasImageAccess(rc, context)) {
                         rebuildServer(rc, server, ctx);
@@ -408,26 +417,24 @@ public class RebuildServer extends ProviderServerOperation {
                 logger.error(ex.getMessage());
                 ctx.setAttribute("REBUILD_STATUS", "ERROR");
                 doFailure(rc, HttpStatus.CONFLICT_409, ex.getMessage());
-            }
-            catch (RequestFailedException e) {
+            } catch (RequestFailedException e) {
                 doFailure(rc, e.getStatus(), e.getMessage());
                 ctx.setAttribute("REBUILD_STATUS", "ERROR");
             } catch (ResourceNotFoundException e) {
-                msg = EELFResourceManager.format(Msg.SERVER_NOT_FOUND, e, vm_url);
+                msg = EELFResourceManager.format(Msg.SERVER_NOT_FOUND, e, vmUrl);
                 ctx.setAttribute("REBUILD_STATUS", "ERROR");
                 logger.error(msg);
                 metricsLogger.error(msg);
                 doFailure(rc, HttpStatus.NOT_FOUND_404, msg);
             } catch (Exception e1) {
                 msg = EELFResourceManager.format(Msg.SERVER_OPERATION_EXCEPTION, e1, e1.getClass().getSimpleName(),
-                        STOP_SERVICE.toString(), vm_url, tenantName);
+                        STOP_SERVICE.toString(), vmUrl, tenantName);
                 ctx.setAttribute("REBUILD_STATUS", "ERROR");
                 logger.error(msg, e1);
                 metricsLogger.error(msg);
                 doFailure(rc, HttpStatus.INTERNAL_SERVER_ERROR_500, msg);
             }
         } catch (RequestFailedException e) {
-
             ctx.setAttribute("REBUILD_STATUS", "ERROR");
             doFailure(rc, e.getStatus(), e.getMessage());
         }
@@ -467,4 +474,37 @@ public class RebuildServer extends ProviderServerOperation {
     public void setRebuildSleepTime(long millis) {
         this.rebuildSleepTime = millis;
     }
+
+    private boolean validateSnapshotId(String imageToUse, List<Image> snapshotList, List<Image> imageList) {
+
+        logger.debug("Validating snapshot-id " + imageToUse + " for the rebuild request from payload");
+        boolean imageFound = false;
+        // If image is empty , the validation si not required . Hence return false.
+        // Ideally function should not be called with empty image Id
+        if (imageToUse.isEmpty()) {
+            return imageFound;
+        } else {
+            // The supplied snapshot id can be a snapshot id or an image Id. Check both
+            // available for the vnf.
+            // Check against snapshot id list and image list
+            return findImageExists(snapshotList, imageToUse, "snapshotidList")
+                    || findImageExists(imageList, imageToUse, "imageidList");
+        }
+    }
+
+    boolean findImageExists(List<Image> list, String imageToUse, String source) {
+        boolean imageExists = false;
+        logger.debug("Available Image-ids from :" + source + "Start\n");
+        for (Image img : list) {
+            String imgId = img.getId();
+            logger.debug("Image Id - " + imgId + "\n");
+            if (imgId.equals(imageToUse)) {
+                logger.debug("Image found in available " + source);
+                imageExists = true;
+                break;
+            }
+        }
+        return imageExists;
+
+    }
 }