简体   繁体   中英

AWS EC2 Instances: Launch Multiple Instance

I want to create ec2 instances when ever the new user arrive. I created a servlet class to do this. When User arrive i check DB that is user new or not if new then create the instance and send back his/her IP. When i send http request to this servlet one by one for users i get the IP correctly. But when i send HTTP Call in parallel (for user1 send request in tab1, for user2 send request in tab2 simultaneously before getting response from user1 HTTP call). When i do this i got error. Sometimes user1 said

"The instance ID 'i-0b79495934c3b5459' does not exist (Service: AmazonEC2; Status Code: 400; Error Code: InvalidInstanceID.NotFound; Request ID: e18a9eaa-cb1b-4130-a3ee-bf1b19fa184c) "

And user2 send IP in response. Kindly help me What is the issue and how to resolve this. This is the Servlet Class which i created.

public class GateKeeperController extends HttpServlet {
    private static final long serialVersionUID = 1L;
    BasicAWSCredentials awsCreds = new BasicAWSCredentials(credentials);
    AmazonEC2Client ec2Client = new AmazonEC2Client(awsCreds);
    RunInstancesRequest runInstancesRequest;
    RunInstancesResult runInstancesResult;
    Reservation reservation;
    Instance intstance;
    DescribeInstancesRequest describeInstanceRequest;
    DescribeInstancesResult describeInstanceResult;
    GatekeeperModal gateKeepermodal;
    String sourceAMI = null;
    String destinationAMI = null;

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        HttpSession s = request.getSession();
        String userID = (String) request.getParameter("userID");
        Double lattitude = Double.parseDouble((String) request.getParameter("lat"));
        Double lonitude = Double.parseDouble((String) request.getParameter("long"));
        if (userID != null) {
            Pair coordinates = new Pair(lattitude, lonitude);
            RegionSelection targetRegion = new RegionSelection();
            String regionResult = targetRegion.getRegion(coordinates);
            String instanceIP = null;
            gateKeepermodal = new GatekeeperModal();
            try {
                if (gateKeepermodal.checkUserIsNew(userID)) {
                    instanceIP = startInstance(userID, regionResult);
                    if (instanceIP != null) {
                        response.getWriter().write(instanceIP);
                    }
                } 
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        } else {

        }
    }

    private String startInstance(String userID, String region) {
        String ami_id = new AMI().getAMI_ID(region);

        ec2Client.setEndpoint(region);
        runInstancesRequest = new RunInstancesRequest();
        runInstancesRequest.withImageId(ami_id).withInstanceType("t2.micro").withMinCount(1).withMaxCount(1)
                .withKeyName("GateKeeper_User").withSecurityGroups("GateKeeper User");
        runInstancesResult = ec2Client.runInstances(runInstancesRequest);
        reservation = runInstancesResult.getReservation();
        intstance = reservation.getInstances().get(0);
        String s1 = intstance.getState().getName();
        String s2 = InstanceStateName.Running.name();
        while (!s1.toLowerCase().equals(s2.toLowerCase())) {
            describeInstanceRequest = new DescribeInstancesRequest();
            describeInstanceRequest.withInstanceIds(intstance.getInstanceId());
            ec2Client.setEndpoint(region);
            describeInstanceResult = ec2Client.describeInstances(describeInstanceRequest);
            reservation = describeInstanceResult.getReservations().get(0);
            intstance = reservation.getInstances().get(0);
            s1 = intstance.getState().getName();
            s2 = InstanceStateName.Running.name();
        }
        GateKeeperUser user = new GateKeeperUser(userID, intstance.getInstanceId(), intstance.getPublicIpAddress(),
                region);
        Boolean result;
        try {
            result = gateKeepermodal.createUser(user);
            if (result) {
                return intstance.getPublicIpAddress();
            } else {
                return null;
            }

        } catch (SQLException e) {

        }
        return null;
    }
}

According to the documentation :

"If you successfully run the RunInstances command, and then immediately run another command using the instance ID that was provided in the response of RunInstances, it may return an InvalidInstanceID.NotFound error. This does not mean the instance does not exist. Some specific commands that may be affected are: DescribeInstances: To confirm the actual state of the instance, run this command using an exponential backoff algorithm. TerminateInstances: To confirm the state of the instance, first run the DescribeInstances command using an exponential backoff algorithm."

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM