List of usage examples for com.amazonaws.services.ec2.model RunInstancesRequest setKernelId
public void setKernelId(String kernelId)
The ID of the kernel.
From source file:com.appdynamics.connectors.AWSConnector.java
License:Apache License
public IMachine createMachine(IComputeCenter computeCenter, IImage image, IMachineDescriptor machineDescriptor) throws InvalidObjectException, ConnectorException { boolean succeeded = false; Exception createFailureRootCause = null; Instance instance = null;//from w w w. ja v a 2s . c om try { IProperty[] macProps = machineDescriptor.getProperties(); AmazonEC2 connector = getConnector(image, computeCenter, controllerServices); String amiName = Utils.getAMIName(image.getProperties(), controllerServices); List<String> securityGroups = getSecurityGroup(macProps); validateAndConfigureSecurityGroups(securityGroups, connector); controllerServices.getStringPropertyByName(macProps, Utils.SECURITY_GROUP) .setValue(getSecurityGroupsAsString(securityGroups)); String keyPair = Utils.getKeyPair(macProps, controllerServices); InstanceType instanceType = getInstanceType(macProps); String zone = Utils.getZone(macProps, controllerServices); String kernel = Utils.getKernel(macProps, controllerServices); String ramdisk = Utils.getRamDisk(macProps, controllerServices); String controllerHost = System.getProperty(CONTROLLER_SERVICES_HOST_NAME_PROPERTY_KEY, InetAddress.getLocalHost().getHostName()); int controllerPort = Integer.getInteger(CONTROLLER_SERVICES_PORT_PROPERTY_KEY, DEFAULT_CONTROLLER_PORT_VALUE); IAccount account = computeCenter.getAccount(); String accountName = account.getName(); String accountAccessKey = account.getAccessKey(); AgentResolutionEncoder agentResolutionEncoder = new AgentResolutionEncoder(controllerHost, controllerPort, accountName, accountAccessKey); String userData = agentResolutionEncoder.encodeAgentResolutionInfo(); String instanceName = Utils.getInstanceName(macProps, controllerServices); logger.info("Starting EC2 machine of Image :" + amiName + " Name :" + instanceName + " security :" + securityGroups + " keypair :" + keyPair + " instance :" + instanceType + " zone :" + zone + " kernel :" + kernel + " ramdisk :" + ramdisk + " userData :" + userData); RunInstancesRequest runInstancesRequest = new RunInstancesRequest(amiName, 1, 1); runInstancesRequest.setSecurityGroups(securityGroups); runInstancesRequest.setUserData(Base64.encodeAsString(userData.getBytes())); runInstancesRequest.setKeyName(keyPair); runInstancesRequest.setInstanceType(instanceType); runInstancesRequest.setKernelId(kernel); runInstancesRequest.setRamdiskId(ramdisk); Reservation reservation = connector.runInstances(runInstancesRequest).getReservation(); List<Instance> instances = reservation.getInstances(); if (instances.size() == 0) throw new ConnectorException("Cannot create instance for image :" + image.getName()); instance = instances.get(0); //Set name for the instance if (!Strings.isNullOrEmpty(instanceName)) { CreateTagsRequest createTagsRequest = new CreateTagsRequest(); createTagsRequest.withResources(instance.getInstanceId()).withTags(new Tag("Name", instanceName)); connector.createTags(createTagsRequest); } logger.info("EC2 machine started; id:" + instance.getInstanceId()); IMachine machine; if (Strings.isNullOrEmpty(instance.getPublicDnsName())) { machine = controllerServices.createMachineInstance(instance.getInstanceId(), agentResolutionEncoder.getUniqueHostIdentifier(), computeCenter, machineDescriptor, image, getAgentPort()); } else { machine = controllerServices.createMachineInstance(instance.getInstanceId(), agentResolutionEncoder.getUniqueHostIdentifier(), instance.getPublicDnsName(), computeCenter, machineDescriptor, image, getAgentPort()); } if (kernel == null) { controllerServices.getStringPropertyByName(macProps, Utils.KERNEL).setValue(instance.getKernelId()); } if (zone == null) { DescribeAvailabilityZonesResult describeAvailabilityZonesResult = connector .describeAvailabilityZones(); List<AvailabilityZone> availabilityZones = describeAvailabilityZonesResult.getAvailabilityZones(); controllerServices.getStringPropertyByName(macProps, Utils.ZONE) .setValue(availabilityZones.get(0).getZoneName()); } controllerServices.getStringPropertyByName(macProps, Utils.INSTANCE_TYPE) .setValue(instance.getInstanceType()); succeeded = true; return machine; } catch (InvalidObjectException e) { createFailureRootCause = e; throw e; } catch (ConnectorException e) { createFailureRootCause = e; throw e; } catch (Exception e) { createFailureRootCause = e; throw new ConnectorException(e.getMessage(), e); } finally { // We have to make sure to terminate any orphan EC2 instances if // the machine create fails. if (!succeeded && instance != null) { try { ConnectorLocator.getInstance().getConnector(computeCenter, controllerServices) .terminateInstances( new TerminateInstancesRequest(Lists.newArrayList(instance.getInstanceId()))); } catch (Exception e) { throw new ConnectorException("Machine create failed, but terminate failed as well! " + "We have an orphan EC2 instance with id: " + instance.getInstanceId() + " that must be shut down manually. Root cause for machine " + "create failure is following: ", createFailureRootCause); } } } }
From source file:datameer.awstasks.ant.ec2.Ec2LaunchTask.java
License:Apache License
@Override public void doExecute(AmazonEC2 ec2) throws BuildException { LOG.info("executing " + getClass().getSimpleName() + " with groupName '" + _groupName + "'"); try {/*from ww w .j a v a2 s.c om*/ boolean instancesRunning = Ec2Util.findByGroup(ec2, _groupName, false, InstanceStateName.Pending, InstanceStateName.Running) != null; if (!isReuseRunningInstances() && instancesRunning) { throw new IllegalStateException("found already running instances for group '" + _groupName + "'"); } if (!Ec2Util.groupExists(ec2, _groupName)) { LOG.info("group '" + _groupName + "' does not exists - creating it"); String groupDescription = getGroupDescription(); if (groupDescription == null) { throw new BuildException("must specify groupDescription"); } ec2.createSecurityGroup(new CreateSecurityGroupRequest(_groupName, groupDescription)); } List<String> securityGroups = Arrays.asList("default", _groupName); List<IpPermission> existingPermissions = Ec2Util.getPermissions(ec2, securityGroups); for (GroupPermission groupPermission : _groupPermissions) { if (groupPermission.getToPort() == -1) { groupPermission.setToPort(groupPermission.getFromPort()); } if (!permissionExists(groupPermission, existingPermissions)) { LOG.info("did not found permission '" + groupPermission + "' - creating it..."); ec2.authorizeSecurityGroupIngress(new AuthorizeSecurityGroupIngressRequest() .withGroupName(_groupName).withIpPermissions(groupPermission.toIpPermission())); } } InstanceGroup instanceGroup = new InstanceGroupImpl(ec2); RunInstancesRequest launchConfiguration = new RunInstancesRequest(_ami, _instanceCount, _instanceCount); if (_kernelId != null) { launchConfiguration.setKernelId(_kernelId); } if (_ramDiskId != null) { launchConfiguration.setKernelId(_ramDiskId); } launchConfiguration.setKeyName(_privateKeyName); launchConfiguration.setSecurityGroups(securityGroups); if (_userData != null) { launchConfiguration.setUserData(Base64.encodeBase64String(_userData.getBytes())); } if (_instanceType != null) { launchConfiguration.setInstanceType(_instanceType); } launchConfiguration.setPlacement(new Placement(_availabilityZone)); if (instancesRunning) { instanceGroup.connectTo(_groupName); } else { instanceGroup.launch(launchConfiguration, TimeUnit.MINUTES, _maxStartTime); if (_instanceName != null) { LOG.info("tagging instances with name '" + _instanceName + " [<idx>]'"); int idx = 1; for (Instance instance : instanceGroup.getInstances(false)) { CreateTagsRequest createTagsRequest = new CreateTagsRequest(); createTagsRequest.withResources(instance.getInstanceId()) // .withTags(new Tag("Name", _instanceName + " [" + idx + "]")); ec2.createTags(createTagsRequest); idx++; } } } } catch (Exception e) { LOG.error("execution " + getClass().getSimpleName() + " with groupName '" + _groupName + "' failed: " + e.getMessage()); throw new BuildException(e); } }
From source file:net.roboconf.iaas.ec2.IaasEc2.java
License:Apache License
/** * Prepares the request.// www .j ava2 s.com * @param machineImageId the ID of the image to use * @param userData the user data to pass * @return a request * @throws UnsupportedEncodingException */ private RunInstancesRequest prepareEC2RequestNode(String machineImageId, String userData) throws UnsupportedEncodingException { RunInstancesRequest runInstancesRequest = new RunInstancesRequest(); String flavor = this.iaasProperties.get(Ec2Constants.VM_INSTANCE_TYPE); if (StringUtils.isBlank(flavor)) flavor = "t1.micro"; runInstancesRequest.setInstanceType(this.iaasProperties.get(Ec2Constants.VM_INSTANCE_TYPE)); if (StringUtils.isBlank(machineImageId)) runInstancesRequest.setImageId(this.iaasProperties.get(Ec2Constants.AMI_VM_NODE)); else runInstancesRequest.setImageId(machineImageId); // FIXME (VZ): why this kernel ID? runInstancesRequest.setKernelId("aki-62695816"); runInstancesRequest.setMinCount(1); runInstancesRequest.setMaxCount(1); runInstancesRequest.setKeyName(this.iaasProperties.get(Ec2Constants.SSH_KEY_NAME)); String secGroup = this.iaasProperties.get(Ec2Constants.SECURITY_GROUP_NAME); if (StringUtils.isBlank(secGroup)) secGroup = "default"; runInstancesRequest.setSecurityGroups(Arrays.asList(secGroup)); /* // Create the block device mapping to describe the root partition. BlockDeviceMapping blockDeviceMapping = new BlockDeviceMapping(); blockDeviceMapping.setDeviceName("/dev/sda1"); // Set the delete on termination flag to false. EbsBlockDevice ebs = new EbsBlockDevice(); ebs.setSnapshotId(snapshotId); ebs.setDeleteOnTermination(Boolean.FALSE); blockDeviceMapping.setEbs(ebs); // Add the block device mapping to the block list. ArrayList<BlockDeviceMapping> blockList = new ArrayList<BlockDeviceMapping>(); blockList.add(blockDeviceMapping); // Set the block device mapping configuration in the launch specifications. runInstancesRequest.setBlockDeviceMappings(blockList); */ // The following part enables to transmit data to the VM. // When the VM is up, it will be able to read this data. String encodedUserData = new String(Base64.encodeBase64(userData.getBytes("UTF-8")), "UTF-8"); runInstancesRequest.setUserData(encodedUserData); return runInstancesRequest; }
From source file:org.gridgain.grid.spi.cloud.ec2lite.GridEc2LiteCloudSpi.java
License:GNU General Public License
/** * Creates Amazon EC2 run instances request by provided command. * * @param cmd Cloud command.//from ww w . java 2 s .com * @return EC2 run instances request. * @throws GridSpiException If any exception occurs. */ private RunInstancesRequest createRunInstancesRequest(GridCloudCommand cmd) throws GridSpiException { assert cmd != null; Collection<GridCloudResource> rsrcs = cmd.resources(); int num = cmd.number(); assert rsrcs != null && !rsrcs.isEmpty(); assert num > 0; GridCloudResource img = null; Collection<String> grps = new ArrayList<String>(); // Separate image and security groups for (GridCloudResource rsrc : rsrcs) if (rsrc.type() == CLD_IMAGE) img = rsrc; else if (rsrc.type() == CLD_SECURITY_GROUP) grps.add(rsrc.id()); assert img != null; Map<String, String> imgParams = img.parameters(); Map<String, String> cmdParams = cmd.parameters(); if (imgParams == null) throw new GridSpiException( "Unable to process command (image parameters are null) [cmd=" + cmd + ", image=" + img + ']'); RunInstancesRequest req = new RunInstancesRequest(); req.setImageId(img.id()); req.setMinCount(num); req.setMaxCount(num); if (!grps.isEmpty()) req.setSecurityGroups(grps); String val; if (!F.isEmpty(val = imgParams.get(IMG_KERNEL_ID))) req.setKernelId(val); if (!F.isEmpty(val = imgParams.get(IMG_RAMDISK_ID))) req.setRamdiskId(val); Collection<String> userDataList = new LinkedList<String>(); if (cmdParams != null) { if (!F.isEmpty(val = cmdParams.get(INST_TYPE))) req.setInstanceType(val); if (!F.isEmpty(val = cmdParams.get(INST_PLACEMENT))) req.setPlacement(new Placement(val)); if (!F.isEmpty(val = cmdParams.get(INST_KEY_PAIR_NAME))) req.setKeyName(val); if (!F.isEmpty(val = cmdParams.get(INST_MON))) req.setMonitoring(Boolean.parseBoolean(val)); if (!F.isEmpty(val = cmdParams.get(INST_PASS_EC2_KEYS)) && Boolean.parseBoolean(val)) { userDataList.add(GRIDGAIN_ACCESS_KEY_ID_KEY + '=' + accessKeyId); userDataList.add(GRIDGAIN_SECRET_KEY_KEY + '=' + secretAccessKey); } if (!F.isEmpty(val = cmdParams.get(INST_MAIN_S3_BUCKET))) userDataList.add(GRIDGAIN_MAIN_S3_BUCKET_KEY + '=' + val); if (!F.isEmpty(val = cmdParams.get(INST_USER_S3_BUCKET))) userDataList.add(GRIDGAIN_EXT_S3_BUCKET_KEY + '=' + val); if (!F.isEmpty(val = cmdParams.get(INST_JVM_OPTS))) userDataList.add(val); } if (req.isMonitoring() == null) // Monitoring was not set from params, set default value req.setMonitoring(enableMon); if (!userDataList.isEmpty()) req.setUserData(new String(Base64.encodeBase64(F.concat(userDataList, USER_DATA_DELIM).getBytes()))); return req; }
From source file:pl.edu.agh.samm.tadapter.eucalyptus.EucalyptusTransportAdapter.java
License:Open Source License
/** * starts new VM instance, <b>does not add new resource to core</b> * * @param resource// w w w . ja va 2s . c om * @param imageId * @param instanceType * @return * @throws Exception */ private Instance startOneInstanceAction(Resource resource, final String imageId, String instanceType, String userData) throws Exception { AmazonEC2Client client = ec2Clients.get(resource); Image image = getImageByImageID(client, imageId); if (!IMAGE_TYPE_MACHINE.equals(image.getImageType())) { throw new RuntimeException("Provided image type is not machine!"); } if (!IMAGE_STATE_AVAILABLE.equals(image.getState())) { throw new RuntimeException("Provided image state is not " + IMAGE_STATE_AVAILABLE); } RunInstancesRequest command = new RunInstancesRequest(); if (userData != null) { command.setUserData(userData); } command.setImageId(image.getImageId()); command.setInstanceType(instanceType); command.setKernelId(image.getKernelId()); command.setMaxCount(1); command.setMinCount(1); command.setRamdiskId(image.getRamdiskId()); command.setKeyName(resource.getProperty(EUCALYPTUS_KEY_NAME).toString()); RunInstancesResult result = client.runInstances(command); List<Instance> instances = result.getReservation().getInstances(); if (instances.size() < 1) { logger.error("Something bad happend while running VM instance"); } Instance instance = instances.get(0); instance = EC2Util.waitForRunningState(client, instance); logger.info("Started new instance of image " + imageId + "! InstanceId = " + instance.getInstanceId()); instance = EC2Util.waitForPublicDNS(client, instance); logger.info("Instance IP address is: " + instance.getPublicDnsName()); return instance; }