/*
 * Copyright (C) 2014-2016 LinkedIn Corp. All rights reserved.
 *
 * 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.
 */
package gobblin.aws;

import java.util.List;

import org.apache.helix.messaging.AsyncCallback;
import org.apache.helix.model.Message;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.amazonaws.regions.Region;
import com.google.common.base.Optional;


/**
 * Class that handles Helix shutdown response and consequently shutdowns Amazon AutoScaling group.
 *
 * @author Abhishek Tiwari
 */
public class AWSShutdownHandler extends AsyncCallback {
  private static final Logger LOGGER = LoggerFactory.getLogger(AWSShutdownHandler.class);

  private static final boolean SHOULD_FORCE_DELETE_ASG_DEFAULT = false;

  private final AWSClusterSecurityManager awsClusterSecurityManager;
  private final Region region;
  private final Optional<List<String>> optionalLaunchConfigurationNames;
  private final Optional<List<String>> optionalAutoScalingGroupNames;

  public AWSShutdownHandler(AWSClusterSecurityManager awsClusterSecurityManager,
      Region region,
      Optional<List<String>> optionalLaunchConfigurationNames,
      Optional<List<String>> optionalAutoScalingGroupNames) {
    this.awsClusterSecurityManager = awsClusterSecurityManager;
    this.region = region;
    this.optionalLaunchConfigurationNames = optionalLaunchConfigurationNames;
    this.optionalAutoScalingGroupNames = optionalAutoScalingGroupNames;
  }

  @Override
  public void onTimeOut() {
    LOGGER.warn("Timeout while waiting for Helix controller and participants shutdown. "
        + "Moving ahead with ungraceful shutdown of Amazon AutoScaling group");

    shutdownASG();
  }

  @Override
  public void onReplyMessage(Message message) {
    LOGGER.info("Successfully shutdown Helix controller and participants shutdown. "
        + "Moving ahead with graceful shutdown of Amazon AutoScaling group");

    shutdownASG();
  }

  private void shutdownASG() {
    if (optionalLaunchConfigurationNames.isPresent()) {
      for (String launchConfigurationName : optionalLaunchConfigurationNames.get()) {
        AWSSdkClient.deleteLaunchConfiguration(this.awsClusterSecurityManager,
            this.region,
            launchConfigurationName);
      }
    }
    if (optionalAutoScalingGroupNames.isPresent()) {
      for (String autoScalingGroupName : optionalAutoScalingGroupNames.get()) {
        AWSSdkClient.deleteAutoScalingGroup(this.awsClusterSecurityManager,
            this.region,
            autoScalingGroupName,
            SHOULD_FORCE_DELETE_ASG_DEFAULT);
      }
    }
  }
}

@@ -2498,32 +2498,48 @@
 nNames.get()) %7B%0A
+        try %7B%0A  
         AWSSdkCl
@@ -2605,32 +2605,34 @@
 er,%0A            
+  
 this.region,%0A   
@@ -2620,32 +2620,34 @@
    this.region,%0A
+  
             laun
@@ -2668,16 +2668,239 @@
 nName);%0A
+        %7D catch (Exception e) %7B%0A          // Ignore and continue, so that we clean up as many resources as possible%0A          LOGGER.error(%22Issue in deleting launch configuration: %22 + launchConfigurationName, e);%0A        %7D%0A
       %7D%0A
@@ -3030,32 +3030,48 @@
 pNames.get()) %7B%0A
+        try %7B%0A  
         AWSSdkCl
@@ -3134,32 +3134,34 @@
 er,%0A            
+  
 this.region,%0A   
@@ -3149,32 +3149,34 @@
    this.region,%0A
+  
             auto
@@ -3205,16 +3205,18 @@
         
+ 
+ 
 SHOULD_F
@@ -3241,16 +3241,686 @@
 FAULT);%0A
+        %7D catch (Exception e1) %7B%0A          LOGGER.error(%22Issue in deleting auto scaling group (in graceful mode): %22 + autoScalingGroupName%0A              + %22 Going to try forceful cleanup.%22, e1);%0A%0A          try %7B%0A            // Delete forcefully%0A            AWSSdkClient.deleteAutoScalingGroup(this.awsClusterSecurityManager,%0A                this.region,%0A                autoScalingGroupName,%0A                true);%0A          %7D catch (Exception e2) %7B%0A            // Ignore and continue, so that we clean up as many resources as possible%0A            LOGGER.error(%22Issue in deleting auto scaling group (in forced mode): %22 + autoScalingGroupName, e2);%0A          %7D%0A        %7D%0A
       %7D%0A

Add forceful deletion of resources in gobblin-aws upon failure