org.jclouds.compute.domain.Template Java Examples

The following examples show how to use org.jclouds.compute.domain.Template. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: JcloudsLocationSecurityGroupCustomizer.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
/**
 * Replaces security groups configured on the given template with one that allows
 * SSH access on port 22 and allows communication on all ports between machines in
 * the same group. Security groups are reused when templates have equal
 * {@link org.jclouds.compute.domain.Template#getLocation locations}.
 * <p>
 * This method is called by Brooklyn when obtaining machines, as part of the
 * {@link JcloudsLocationCustomizer} contract. It
 * should not be called from anywhere else.
 *
 * @param location The Brooklyn location that has called this method while obtaining a machine
 * @param computeService The compute service being used by the location argument to provision a machine
 * @param template The machine template created by the location argument
 */
@Override
public void customize(JcloudsLocation location, ComputeService computeService, Template template) {
    final Optional<SecurityGroupExtension> securityApi = computeService.getSecurityGroupExtension();
    if (!securityApi.isPresent()) {
        LOG.warn("Security group extension for {} absent; cannot configure security groups in context: {}",
            computeService, applicationId);

    } else if (template.getLocation() == null) {
        LOG.warn("No location has been set on {}; cannot configure security groups in context: {}",
            template, applicationId);

    } else {
        LOG.info("Configuring security groups on location {} in context {}", location, applicationId);
        SecurityGroupEditor groupEditor = createSecurityGroupEditor(securityApi.get(), template.getLocation());

        setSecurityGroupOnTemplate(location, template, groupEditor);
    }
}
 
Example #2
Source File: JcloudsTemplateOptionsStubbedTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Override
protected NodeCreator newNodeCreator() {
    return new AbstractNodeCreator() {
        @Override protected NodeMetadata newNode(String group, Template template) {
            NodeMetadata result = new NodeMetadataBuilder()
                    .id("myid")
                    .credentials(LoginCredentials.builder().identity("myuser").credential("mypassword").build())
                    .loginPort(22)
                    .status(Status.RUNNING)
                    .publicAddresses(ImmutableList.of("173.194.32.123"))
                    .privateAddresses(ImmutableList.of("172.168.10.11"))
                    .build();
            return result;
        }
    };
}
 
Example #3
Source File: JcloudsSshMachineLocationStubbedTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Override
protected NodeCreator newNodeCreator() {
    return new AbstractNodeCreator() {
        @Override protected NodeMetadata newNode(String group, Template template) {
            NodeMetadata result = new NodeMetadataBuilder()
                    .id("myid")
                    .credentials(LoginCredentials.builder().identity("myuser").credential("mypassword").build())
                    .loginPort(22)
                    .status(Status.RUNNING)
                    .publicAddresses(publicAddresses)
                    .privateAddresses(privateAddresses)
                    .build();
            return result;
        }
    };
}
 
Example #4
Source File: JcloudsLocationSecurityGroupCustomizerTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testSecurityGroupAddedWhenJcloudsLocationCustomised() {
    Template template = mock(Template.class);
    TemplateOptions templateOptions = mock(TemplateOptions.class);
    when(template.getLocation()).thenReturn(location);
    when(template.getOptions()).thenReturn(templateOptions);
    SecurityGroup group = newGroup("id");
    when(securityApi.createSecurityGroup(anyString(), eq(location))).thenReturn(group);
    when(securityApi.addIpPermission(any(IpPermission.class), eq(group))).thenReturn(group);

    // Two Brooklyn.JcloudsLocations added to same Jclouds.Location
    JcloudsLocation jcloudsLocationA = new JcloudsLocation(MutableMap.of("deferConstruction", true));
    JcloudsLocation jcloudsLocationB = new JcloudsLocation(MutableMap.of("deferConstruction", true));
    customizer.customize(jcloudsLocationA, computeService, template);
    customizer.customize(jcloudsLocationB, computeService, template);

    // One group with three permissions shared by both locations.
    // Expect TCP, UDP and ICMP between members of group and SSH to Brooklyn
    verify(securityApi).createSecurityGroup(anyString(), eq(location));
    verify(securityApi, times(4)).addIpPermission(any(IpPermission.class), eq(group));
    // New groups set on options
    verify(templateOptions, times(2)).securityGroups(anyString());
}
 
Example #5
Source File: JcloudsLocationSecurityGroupCustomizerTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testSharedGroupLoadedWhenItExistsButIsNotCached() {
    Template template = mock(Template.class);
    TemplateOptions templateOptions = mock(TemplateOptions.class);
    when(template.getLocation()).thenReturn(location);
    when(template.getOptions()).thenReturn(templateOptions);
    JcloudsLocation jcloudsLocation = new JcloudsLocation(MutableMap.of("deferConstruction", true));
    SecurityGroup shared = newGroup(customizer.getNameForSharedSecurityGroup());
    SecurityGroup irrelevant = newGroup("irrelevant");
    when(securityApi.createSecurityGroup(shared.getName(), location)).thenReturn(shared);
    when(securityApi.createSecurityGroup(irrelevant.getName(), location)).thenReturn(irrelevant);
    when(securityApi.listSecurityGroupsInLocation(location)).thenReturn(ImmutableSet.of(irrelevant, shared));
    when(securityApi.addIpPermission(any(IpPermission.class), eq(shared))).thenReturn(shared);
    when(securityApi.addIpPermission(any(IpPermission.class), eq(irrelevant))).thenReturn(irrelevant);

    customizer.customize(jcloudsLocation, computeService, template);

    verify(securityApi).listSecurityGroupsInLocation(location);
    verify(securityApi, never()).createSecurityGroup(anyString(), any(Location.class));
}
 
Example #6
Source File: StubbedComputeServiceRegistry.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Override
protected NodeMetadata newNode(String group, Template template) {
    int suffix = counter.getAndIncrement();
    org.jclouds.domain.Location region = new LocationBuilder()
            .scope(LocationScope.REGION)
            .id("us-east-1")
            .description("us-east-1")
            .parent(new LocationBuilder()
                    .scope(LocationScope.PROVIDER)
                    .id("aws-ec2")
                    .description("aws-ec2")
                    .build())
            .build();
    NodeMetadata result = new NodeMetadataBuilder()
            .id("mynodeid"+suffix)
            .credentials(LoginCredentials.builder().identity("myuser").credential("mypassword").build())
            .loginPort(22)
            .status(Status.RUNNING)
            .publicAddresses(ImmutableList.of("173.194.32."+suffix))
            .privateAddresses(ImmutableList.of("172.168.10."+suffix))
            .location(region)
            .build();
    return result;
}
 
Example #7
Source File: CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptions.java    From attic-stratos with Apache License 2.0 6 votes vote down vote up
@Override
protected void addSecurityGroups(String region, String group, Template template, RunInstancesOptions instanceOptions) {
   AWSEC2TemplateOptions awsTemplateOptions = AWSEC2TemplateOptions.class.cast(template.getOptions());
   AWSRunInstancesOptions awsInstanceOptions = AWSRunInstancesOptions.class.cast(instanceOptions);
   if (!awsTemplateOptions.getGroupIds().isEmpty())
      awsInstanceOptions.withSecurityGroupIds(awsTemplateOptions.getGroupIds());
   String subnetId = awsTemplateOptions.getSubnetId();
    boolean associatePublicIpAddress = awsTemplateOptions.isPublicIpAddressAssociated();
   if (subnetId != null) {
       if (associatePublicIpAddress){
           AWSRunInstancesOptions.class.cast(instanceOptions).associatePublicIpAddressAndSubnetId(subnetId);
           if (awsTemplateOptions.getGroupIds().size() > 0)
               awsInstanceOptions.withSecurityGroupIdsForNetworkInterface(awsTemplateOptions.getGroupIds());
       } else {
           AWSRunInstancesOptions.class.cast(instanceOptions).withSubnetId(subnetId);
           if (awsTemplateOptions.getGroupIds().size() > 0)
               awsInstanceOptions.withSecurityGroupIds(awsTemplateOptions.getGroupIds());
       }
   } else {
       if (!awsTemplateOptions.getGroupIds().isEmpty())
           awsInstanceOptions.withSecurityGroupIds(awsTemplateOptions.getGroupIds());
      super.addSecurityGroups(region, group, template, instanceOptions);
   }
}
 
Example #8
Source File: JcloudsByonLocationResolverStubbedTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Override
protected NodeCreator newNodeCreator() {
    return new AbstractNodeCreator() {
        @Override
        public Set<? extends NodeMetadata> listNodesDetailsMatching(Predicate<? super NodeMetadata> filter) {
            NodeMetadata result = new NodeMetadataBuilder()
                    .id(nodeId)
                    .credentials(LoginCredentials.builder().identity("dummy").credential("dummy").build())
                    .loginPort(22)
                    .status(Status.RUNNING)
                    .publicAddresses(ImmutableList.of(nodePublicAddress))
                    .privateAddresses(ImmutableList.of(nodePrivateAddress))
                    .build();
            return ImmutableSet.copyOf(Iterables.filter(ImmutableList.of(result), filter));
        }
        @Override
        protected NodeMetadata newNode(String group, Template template) {
            throw new UnsupportedOperationException();
        }
    };
}
 
Example #9
Source File: JcloudsSshMachineLocationAddressOverwriteTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Override
protected NodeCreator newNodeCreator() {
    return new AbstractNodeCreator() {
        @Override protected NodeMetadata newNode(String group, Template template) {
            NodeMetadata result = new NodeMetadataBuilder()
                    .id("myid")
                    .credentials(LoginCredentials.builder().identity("myuser").credential("mypassword").build())
                    .loginPort(22)
                    .status(Status.RUNNING)
                    .publicAddresses(publicAddresses)
                    .privateAddresses(privateAddresses)
                    .build();
            return result;
        }
    };
}
 
Example #10
Source File: CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptions.java    From attic-stratos with Apache License 2.0 6 votes vote down vote up
public AWSRunInstancesOptions execute(String region, String group, Template template) {
   AWSRunInstancesOptions instanceOptions = AWSRunInstancesOptions.class
         .cast(super.execute(region, group, template));

   String placementGroupName = template.getHardware().getId().startsWith("cc") ? createNewPlacementGroupUnlessUserSpecifiedOtherwise(
         region, group, template.getOptions()) : null;

   if (placementGroupName != null)
      instanceOptions.inPlacementGroup(placementGroupName);

   AWSEC2TemplateOptions awsTemplateOptions = AWSEC2TemplateOptions.class.cast(template.getOptions());
   if (awsTemplateOptions.isMonitoringEnabled())
      instanceOptions.enableMonitoring();
   if (awsTemplateOptions.getIAMInstanceProfileArn() != null)
      instanceOptions.withIAMInstanceProfileArn(awsTemplateOptions.getIAMInstanceProfileArn());
   if (awsTemplateOptions.getIAMInstanceProfileName() != null)
      instanceOptions.withIAMInstanceProfileName(awsTemplateOptions.getIAMInstanceProfileName());
   if (awsTemplateOptions.getPrivateIpAddress() != null)
      instanceOptions.withPrivateIpAddress(awsTemplateOptions.getPrivateIpAddress());

   return instanceOptions;
}
 
Example #11
Source File: CreateServer.java    From jclouds-examples with Apache License 2.0 6 votes vote down vote up
/**
 * Create a server based on a Template. This method uses Template.fromHardware() and Template.fromImage() to
 * also demonstrate iterating through Hardware and Images. Alternatively you do the same without iterating
 * using the following Template.
 *
 * Template template = computeService.templateBuilder()
 *     .locationId(getLocationId())
 *     .osFamily(OsFamily.UBUNTU)
 *     .osVersionMatches("14.04")
 *     .minRam(1024)
 *     .build();
 */
private void createServer() throws RunNodesException, TimeoutException {
   System.out.format("Create Server%n");

   Template template = computeService.templateBuilder()
         .locationId(REGION)
         .fromHardware(getHardware())
         .fromImage(getImage())
         .build();

   // This method will continue to poll for the server status and won't return until this server is ACTIVE
   // If you want to know what's happening during the polling, enable logging. See
   // /jclouds-example/rackspace/src/main/java/org/jclouds/examples/rackspace/Logging.java
   Set<? extends NodeMetadata> nodes = computeService.createNodesInGroup(NAME, 1, template);

   NodeMetadata nodeMetadata = nodes.iterator().next();
   String publicAddress = nodeMetadata.getPublicAddresses().iterator().next();

   System.out.format("  %s%n", nodeMetadata);
   System.out.format("  Login: ssh %s@%s%n", nodeMetadata.getCredentials().getUser(), publicAddress);
   System.out.format("  Password: %s%n", nodeMetadata.getCredentials().getOptionalPassword().get());
}
 
Example #12
Source File: AWSEC2CreateNodesInGroupThenAddToSet.java    From attic-stratos with Apache License 2.0 6 votes vote down vote up
@Override
protected Set<RunningInstance> createNodesInRegionAndZone(String region, String zone, String group,
         int count, Template template, RunInstancesOptions instanceOptions) {
   Float spotPrice = getSpotPriceOrNull(template.getOptions());
   if (spotPrice != null) {
      AWSEC2TemplateOptions awsOptions = AWSEC2TemplateOptions.class.cast(template.getOptions());
      LaunchSpecification spec = AWSRunInstancesOptions.class.cast(instanceOptions).getLaunchSpecificationBuilder()
            .imageId(template.getImage().getProviderId()).availabilityZone(zone).subnetId(awsOptions.getSubnetId())
              .publicIpAddressAssociated(awsOptions.isPublicIpAddressAssociated())
              .iamInstanceProfileArn(awsOptions.getIAMInstanceProfileArn())
            .iamInstanceProfileName(awsOptions.getIAMInstanceProfileName()).build();
      RequestSpotInstancesOptions options = awsOptions.getSpotOptions();
      if (logger.isDebugEnabled())
         logger.debug(">> requesting %d spot instances region(%s) price(%f) spec(%s) options(%s)", count, region,
                  spotPrice, spec, options);
      return ImmutableSet.<RunningInstance> copyOf(transform(client.getSpotInstanceApi().get()
            .requestSpotInstancesInRegion(region, spotPrice, count, spec, options), spotConverter));
   }
   return super.createNodesInRegionAndZone(region, zone, group, count, template, instanceOptions);
}
 
Example #13
Source File: JcloudsLocationUsageTrackingTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Override
protected NodeCreator newNodeCreator() {
    return new AbstractNodeCreator() {
        @Override protected NodeMetadata newNode(String group, Template template) {
            NodeMetadata result = new NodeMetadataBuilder()
                    .id("myNodeId")
                    .credentials(LoginCredentials.builder().identity("myuser").credential("mypassword").build())
                    .loginPort(serverSocket.getLocalPort())
                    .status(Status.RUNNING)
                    .publicAddresses(ImmutableList.of(serverSocket.getInetAddress().getHostAddress()))
                    .privateAddresses(ImmutableList.of("1.2.3.4"))
                    .imageId(template.getImage().getId())
                    .tags(template.getOptions().getTags())
                    .hardware(includeNodeHardwareMetadata ? template.getHardware() : null)
                    .group(template.getOptions().getGroups().isEmpty() ? "myGroup" : Iterables.get(template.getOptions().getGroups(), 0))
                    .build();
            return result;
        }
    };
}
 
Example #14
Source File: CloudServersPublish.java    From jclouds-examples with Apache License 2.0 6 votes vote down vote up
private Set<? extends NodeMetadata> createServer() throws RunNodesException, TimeoutException {
   System.out.format("Create Server%n");

   RegionAndId regionAndId = RegionAndId.fromRegionAndId(REGION, "performance1-1");
   Template template = computeService.templateBuilder()
         .locationId(REGION)
         .osDescriptionMatches(".*Ubuntu 14.04.*")
         .hardwareId(regionAndId.slashEncode())
         .build();

   // This method will continue to poll for the server status and won't return until this server is ACTIVE
   // If you want to know what's happening during the polling, enable logging.
   // See /jclouds-example/rackspace/src/main/java/org/jclouds/examples/rackspace/Logging.java
   Set<? extends NodeMetadata> nodes = computeService.createNodesInGroup(NAME, numServers, template);

   for (NodeMetadata nodeMetadata: nodes) {
      System.out.format("  %s%n", nodeMetadata);
   }

   return nodes;
}
 
Example #15
Source File: CloudExplorerSupport.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Override
protected void doCall(JcloudsLocation loc, String indent) throws Exception {

    ComputeService computeService = loc.getComputeService();
    ConfigBag setup = loc.config().getBag();
    
    JcloudsLocationCustomizer customizersDelegate = LocationCustomizerDelegate.newInstance(loc.getManagementContext(), setup);
    Template template = loc.buildTemplate(computeService, setup, customizersDelegate);
    Image image = template.getImage();
    Hardware hardware = template.getHardware();
    org.jclouds.domain.Location location = template.getLocation();
    TemplateOptions options = template.getOptions();
    stdout.println(indent+"Default template {");
    stdout.println(indent+"\tImage: "+image);
    stdout.println(indent+"\tHardware: "+hardware);
    stdout.println(indent+"\tLocation: "+location);
    stdout.println(indent+"\tOptions: "+options);
    stdout.println(indent+"}");
}
 
Example #16
Source File: CreateServerWithKeyPair.java    From jclouds-examples with Apache License 2.0 6 votes vote down vote up
/**
 * Create a server with the key pair.
 */
private NodeMetadata createServer(KeyPair keyPair) throws RunNodesException, TimeoutException {
   System.out.format("  Create Server%n");

   NovaTemplateOptions options = NovaTemplateOptions.Builder.keyPairName(keyPair.getName());

   RegionAndId regionAndId = RegionAndId.fromRegionAndId(REGION, "performance1-1");
   Template template = computeService.templateBuilder()
         .locationId(REGION)
         .osDescriptionMatches(".*Ubuntu 14.04.*")
         .hardwareId(regionAndId.slashEncode())
         .options(options)
         .build();

   // This method will continue to poll for the server status and won't return until this server is ACTIVE
   // If you want to know what's happening during the polling, enable logging.
   // See /jclouds-example/rackspace/src/main/java/org/jclouds/examples/rackspace/Logging.java
   Set<? extends NodeMetadata> nodes = computeService.createNodesInGroup(NAME, 1, template);
   NodeMetadata node = Iterables.getOnlyElement(nodes);

   System.out.format("    %s%n", node);

   return node;
}
 
Example #17
Source File: CreateVolumeAndAttach.java    From jclouds-examples with Apache License 2.0 6 votes vote down vote up
private NodeMetadata createServer() throws RunNodesException, TimeoutException {
   System.out.format("Create Server%n");

   RegionAndId regionAndId = RegionAndId.fromRegionAndId(REGION, "performance1-1");
   Template template = computeService.templateBuilder()
         .locationId(REGION)
         .osDescriptionMatches(".*Ubuntu 12.04.*")
         .hardwareId(regionAndId.slashEncode())
         .build();

   Set<? extends NodeMetadata> nodes = computeService.createNodesInGroup(NAME, 1, template);
   NodeMetadata nodeMetadata = nodes.iterator().next();
   String publicAddress = nodeMetadata.getPublicAddresses().iterator().next();

   // We set the password to something we know so we can login in the DetachVolume example
   novaApi.getServerApi(REGION).changeAdminPass(nodeMetadata.getProviderId(), PASSWORD);

   System.out.format("  %s%n", nodeMetadata);
   System.out.format("  Login: ssh %s@%s%n", nodeMetadata.getCredentials().getUser(), publicAddress);
   System.out.format("  Password: %s%n", PASSWORD);

   return nodeMetadata;
}
 
Example #18
Source File: JcloudsSshMachineLocation.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
/**
 * @since 0.9.0
 * @deprecated since 0.9.0 (only added as aid until the deprecated {@link #getTemplate()} is deleted)
 */
@Deprecated
protected Optional<Template> getOptionalTemplate() {
    if (_template == null) {
        _template = Optional.absent();
    }
    return _template;
}
 
Example #19
Source File: AbstractPortableTemplateBuilder.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
public T fromTemplate(final Template template) {
    this.template = template;
    commands.add(new Function<TemplateBuilder,TemplateBuilder>() { 
        @Override
        public TemplateBuilder apply(TemplateBuilder b) { return b.fromTemplate(template); }});
    return (T)this;
}
 
Example #20
Source File: JcloudsLocationSecurityGroupCustomizerTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testAddPermissionsToNodeUsesUncachedSecurityGroup() {
    JcloudsLocation jcloudsLocation = new JcloudsLocation(MutableMap.of("deferConstruction", true));
    SecurityGroup sharedGroup = newGroup(customizer.getNameForSharedSecurityGroup());
    SecurityGroup uniqueGroup = newGroup("unique");

    Template template = mock(Template.class);
    TemplateOptions templateOptions = mock(TemplateOptions.class);
    when(template.getLocation()).thenReturn(location);
    when(template.getOptions()).thenReturn(templateOptions);
    when(securityApi.createSecurityGroup(anyString(), eq(location))).thenReturn(sharedGroup);
    when(securityApi.addIpPermission(any(IpPermission.class), eq(uniqueGroup))).thenReturn(uniqueGroup);
    when(securityApi.addIpPermission(any(IpPermission.class), eq(sharedGroup))).thenReturn(sharedGroup);

    when(computeService.getContext().unwrap().getId()).thenReturn("aws-ec2");

    // Call customize to cache the shared group
    customizer.customize(jcloudsLocation, computeService, template);
    reset(securityApi);
    when(securityApi.listSecurityGroupsForNode(NODE_ID)).thenReturn(ImmutableSet.of(uniqueGroup, sharedGroup));
    IpPermission ssh = newPermission(22);
    SecurityGroup updatedSharedSecurityGroup = newGroup(sharedGroup.getId(), ImmutableSet.of(ssh));
    when(securityApi.addIpPermission(ssh, uniqueGroup)).thenReturn(updatedSharedSecurityGroup);
    SecurityGroup updatedUniqueSecurityGroup = newGroup("unique", ImmutableSet.of(ssh));
    when(securityApi.addIpPermission(ssh, sharedGroup)).thenReturn(updatedUniqueSecurityGroup);
    customizer.addPermissionsToLocation(jcloudsMachineLocation, ImmutableSet.of(ssh));

    // Expect the per-machine group to have been altered, not the shared group
    verify(securityApi).addIpPermission(ssh, uniqueGroup);
    verify(securityApi, never()).addIpPermission(any(IpPermission.class), eq(sharedGroup));
}
 
Example #21
Source File: JcloudsGceHardwareProfilesStubbedLiveTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
protected NodeCreator newNodeCreator() {
    return new BasicNodeCreator() {
        @Override protected NodeMetadata newNode(String group, Template template) {
            JcloudsGceHardwareProfilesStubbedLiveTest.this.template = template;
            return super.newNode(group, template);
        }
    };
}
 
Example #22
Source File: JcloudsImageChoiceStubbedLiveTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
protected NodeCreator newNodeCreator() {
    return new BasicNodeCreator() {
        @Override protected NodeMetadata newNode(String group, Template template) {
            JcloudsImageChoiceStubbedLiveTest.this.template = template;
            return super.newNode(group, template);
        }
    };
}
 
Example #23
Source File: JcloudsRebindStubUnitTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testRebind() throws Exception {
    this.nodeCreator = newNodeCreator();
    this.computeServiceRegistry = new StubbedComputeServiceRegistry(nodeCreator, false);

    JcloudsLocation origJcloudsLoc = newJcloudsLocation(computeServiceRegistry);

    JcloudsSshMachineLocation origMachine = (JcloudsSshMachineLocation) obtainMachine(origJcloudsLoc, ImmutableMap.of("imageId", IMAGE_ID));
    
    String origHostname = origMachine.getHostname();
    NodeMetadata origNode = origMachine.getNode();

    rebind();
    
    // Check the machine is as before.
    // Call to getOptionalNode() will cause it to try to resolve this node in Softlayer; but it won't find it.
    JcloudsSshMachineLocation newMachine = (JcloudsSshMachineLocation) mgmt().getLocationManager().getLocation(origMachine.getId());
    JcloudsLocation newJcloudsLoc = newMachine.getParent();
    String newHostname = newMachine.getHostname();
    String newNodeId = newMachine.getJcloudsId();
    Optional<NodeMetadata> newNode = newMachine.getOptionalNode();
    Optional<Template> newTemplate = newMachine.getOptionalTemplate();
    
    assertEquals(newHostname, origHostname);
    assertEquals(origNode.getId(), newNodeId);
    assertTrue(newNode.isPresent(), "newNode="+newNode);
    assertEquals(newNode.get(), origNode);
    assertFalse(newTemplate.isPresent(), "newTemplate="+newTemplate);
    
    assertEquals(newJcloudsLoc.getProvider(), origJcloudsLoc.getProvider());

    // Release the machine
    newJcloudsLoc.release(newMachine);
}
 
Example #24
Source File: StubbedComputeServiceRegistry.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
public Set<? extends NodeMetadata> createNodesInGroup(String group, int count, Template template) throws RunNodesException {
    Set<NodeMetadata> result = Sets.newLinkedHashSet();
    for (int i = 0; i < count; i++) {
        NodeMetadata node = newNode(group, template);
        created.add(node);
        result.add(node);
    }
    return result;
}
 
Example #25
Source File: AWSEC2ComputeServiceApiMockTest.java    From attic-stratos with Apache License 2.0 5 votes vote down vote up
public void launchSpotInstanceIAMInstanceProfileName() throws Exception {
   enqueueRegions(DEFAULT_REGION);
   enqueueXml(DEFAULT_REGION, "/availabilityZones.xml");
   enqueueXml(DEFAULT_REGION, "/describe_images.xml");
   enqueueXml(DEFAULT_REGION, "/describe_images_cc.xml");
   enqueueXml(DEFAULT_REGION, "/created_securitygroup.xml");
   enqueueXml(DEFAULT_REGION, "/new_securitygroup.xml");
   enqueueXml(DEFAULT_REGION, "/new_securitygroup.xml");
   enqueueXml(DEFAULT_REGION, "/new_securitygroup.xml");
   enqueueXml(DEFAULT_REGION, "/authorize_securitygroup_ingress_response.xml");
   enqueueXml(DEFAULT_REGION, "/request_spot_instances-ebs.xml");
   enqueueXml(DEFAULT_REGION, "/request_spot_instances-ebs.xml");
   enqueueXml(DEFAULT_REGION, "/describe_images_ebs.xml");
   enqueue(DEFAULT_REGION, new MockResponse()); // create tags

   ComputeService computeService = computeService();

   Template template = computeService.templateBuilder().locationId("us-east-1a").build();

   template.getOptions().as(AWSEC2TemplateOptions.class).spotPrice(1f).iamInstanceProfileName("Webserver")
         .noKeyPair().blockUntilRunning(false);

   NodeMetadata node = Iterables.getOnlyElement(computeService.createNodesInGroup("test", 1, template));
   assertEquals(node.getId(), "us-east-1/sir-228e6406");

   assertPosted(DEFAULT_REGION, "Action=DescribeRegions");
   assertPosted(DEFAULT_REGION, "Action=DescribeAvailabilityZones");
   assertPosted(DEFAULT_REGION, "Action=DescribeImages&Filter.1.Name=owner-id&Filter.1.Value.1=137112412989&Filter.1.Value.2=801119661308&Filter.1.Value.3=063491364108&Filter.1.Value.4=099720109477&Filter.1.Value.5=411009282317&Filter.2.Name=state&Filter.2.Value.1=available&Filter.3.Name=image-type&Filter.3.Value.1=machine");
   assertPosted(DEFAULT_REGION, "Action=DescribeImages&Filter.1.Name=virtualization-type&Filter.1.Value.1=hvm&Filter.2.Name=architecture&Filter.2.Value.1=x86_64&Filter.3.Name=owner-id&Filter.3.Value.1=137112412989&Filter.3.Value.2=099720109477&Filter.4.Name=hypervisor&Filter.4.Value.1=xen&Filter.5.Name=state&Filter.5.Value.1=available&Filter.6.Name=image-type&Filter.6.Value.1=machine&Filter.7.Name=root-device-type&Filter.7.Value.1=ebs");
   assertPosted(DEFAULT_REGION, "Action=CreateSecurityGroup&GroupName=jclouds%23test&GroupDescription=jclouds%23test");
   assertPosted(DEFAULT_REGION, "Action=DescribeSecurityGroups&GroupName.1=jclouds%23test");
   assertPosted(DEFAULT_REGION, "Action=DescribeSecurityGroups&GroupName.1=jclouds%23test");
   assertPosted(DEFAULT_REGION, "Action=DescribeSecurityGroups&GroupName.1=jclouds%23test");
   assertPosted(DEFAULT_REGION, "Action=AuthorizeSecurityGroupIngress&GroupId=sg-3c6ef654&IpPermissions.0.IpProtocol=tcp&IpPermissions.0.FromPort=22&IpPermissions.0.ToPort=22&IpPermissions.0.IpRanges.0.CidrIp=0.0.0.0/0&IpPermissions.1.IpProtocol=tcp&IpPermissions.1.FromPort=0&IpPermissions.1.ToPort=65535&IpPermissions.1.Groups.0.UserId=993194456877&IpPermissions.1.Groups.0.GroupId=sg-3c6ef654&IpPermissions.2.IpProtocol=udp&IpPermissions.2.FromPort=0&IpPermissions.2.ToPort=65535&IpPermissions.2.Groups.0.UserId=993194456877&IpPermissions.2.Groups.0.GroupId=sg-3c6ef654");
   assertPosted(DEFAULT_REGION, "Action=RequestSpotInstances&SpotPrice=1.0&InstanceCount=1&LaunchSpecification.ImageId=ami-" + getDefaultImageId() + "&LaunchSpecification.Placement.AvailabilityZone=us-east-1a&LaunchSpecification.SecurityGroup.1=jclouds%23test&LaunchSpecification.InstanceType=" + getDefaultSmallestInstanceType() + "&LaunchSpecification.UserData=I2Nsb3VkLWNvbmZpZwpyZXBvX3VwZ3JhZGU6IG5vbmUK&LaunchSpecification.IamInstanceProfile.Name=Webserver");
   assertPosted(DEFAULT_REGION, "Action=DescribeSpotInstanceRequests&SpotInstanceRequestId.1=sir-228e6406");
   assertPosted(DEFAULT_REGION, "Action=DescribeImages&ImageId.1=ami-595a0a1c");
   assertPosted(DEFAULT_REGION, "Action=CreateTags&Tag.1.Key=Name&Tag.1.Value=test-228e6406&ResourceId.1=sir-228e6406");
}
 
Example #26
Source File: AWSEC2ComputeServiceApiMockTest.java    From attic-stratos with Apache License 2.0 5 votes vote down vote up
public void launchSpotInstanceIAMInstanceProfileArn() throws Exception {
   enqueueRegions(DEFAULT_REGION);
   enqueueXml(DEFAULT_REGION, "/availabilityZones.xml");
   enqueueXml(DEFAULT_REGION, "/describe_images.xml");
   enqueueXml(DEFAULT_REGION, "/describe_images_cc.xml");
   enqueueXml(DEFAULT_REGION, "/created_securitygroup.xml");
   enqueueXml(DEFAULT_REGION, "/new_securitygroup.xml");
   enqueueXml(DEFAULT_REGION, "/new_securitygroup.xml");
   enqueueXml(DEFAULT_REGION, "/new_securitygroup.xml");
   enqueueXml(DEFAULT_REGION, "/authorize_securitygroup_ingress_response.xml");
   enqueueXml(DEFAULT_REGION, "/request_spot_instances-ebs.xml");
   enqueueXml(DEFAULT_REGION, "/request_spot_instances-ebs.xml");
   enqueueXml(DEFAULT_REGION, "/describe_images_ebs.xml");
   enqueue(DEFAULT_REGION, new MockResponse()); // create tags

   ComputeService computeService = computeService();

   Template template = computeService.templateBuilder().locationId("us-east-1a").build();

   template.getOptions().as(AWSEC2TemplateOptions.class).spotPrice(1f).iamInstanceProfileArn(iamInstanceProfileArn)
         .noKeyPair().blockUntilRunning(false);

   NodeMetadata node = Iterables.getOnlyElement(computeService.createNodesInGroup("test", 1, template));
   assertEquals(node.getId(), "us-east-1/sir-228e6406");

   assertPosted(DEFAULT_REGION, "Action=DescribeRegions");
   assertPosted(DEFAULT_REGION, "Action=DescribeAvailabilityZones");
   assertPosted(DEFAULT_REGION, "Action=DescribeImages&Filter.1.Name=owner-id&Filter.1.Value.1=137112412989&Filter.1.Value.2=801119661308&Filter.1.Value.3=063491364108&Filter.1.Value.4=099720109477&Filter.1.Value.5=411009282317&Filter.2.Name=state&Filter.2.Value.1=available&Filter.3.Name=image-type&Filter.3.Value.1=machine");
   assertPosted(DEFAULT_REGION, "Action=DescribeImages&Filter.1.Name=virtualization-type&Filter.1.Value.1=hvm&Filter.2.Name=architecture&Filter.2.Value.1=x86_64&Filter.3.Name=owner-id&Filter.3.Value.1=137112412989&Filter.3.Value.2=099720109477&Filter.4.Name=hypervisor&Filter.4.Value.1=xen&Filter.5.Name=state&Filter.5.Value.1=available&Filter.6.Name=image-type&Filter.6.Value.1=machine&Filter.7.Name=root-device-type&Filter.7.Value.1=ebs");
   assertPosted(DEFAULT_REGION, "Action=CreateSecurityGroup&GroupName=jclouds%23test&GroupDescription=jclouds%23test");
   assertPosted(DEFAULT_REGION, "Action=DescribeSecurityGroups&GroupName.1=jclouds%23test");
   assertPosted(DEFAULT_REGION, "Action=DescribeSecurityGroups&GroupName.1=jclouds%23test");
   assertPosted(DEFAULT_REGION, "Action=DescribeSecurityGroups&GroupName.1=jclouds%23test");
   assertPosted(DEFAULT_REGION, "Action=AuthorizeSecurityGroupIngress&GroupId=sg-3c6ef654&IpPermissions.0.IpProtocol=tcp&IpPermissions.0.FromPort=22&IpPermissions.0.ToPort=22&IpPermissions.0.IpRanges.0.CidrIp=0.0.0.0/0&IpPermissions.1.IpProtocol=tcp&IpPermissions.1.FromPort=0&IpPermissions.1.ToPort=65535&IpPermissions.1.Groups.0.UserId=993194456877&IpPermissions.1.Groups.0.GroupId=sg-3c6ef654&IpPermissions.2.IpProtocol=udp&IpPermissions.2.FromPort=0&IpPermissions.2.ToPort=65535&IpPermissions.2.Groups.0.UserId=993194456877&IpPermissions.2.Groups.0.GroupId=sg-3c6ef654");
   assertPosted(DEFAULT_REGION, "Action=RequestSpotInstances&SpotPrice=1.0&InstanceCount=1&LaunchSpecification.ImageId=ami-" + getDefaultImageId() + "&LaunchSpecification.Placement.AvailabilityZone=us-east-1a&LaunchSpecification.SecurityGroup.1=jclouds%23test&LaunchSpecification.InstanceType=" + getDefaultSmallestInstanceType() + "&LaunchSpecification.UserData=I2Nsb3VkLWNvbmZpZwpyZXBvX3VwZ3JhZGU6IG5vbmUK&LaunchSpecification.IamInstanceProfile.Arn=arn%3Aaws%3Aiam%3A%3A123456789012%3Ainstance-profile/application_abc/component_xyz/Webserver");
   assertPosted(DEFAULT_REGION, "Action=DescribeSpotInstanceRequests&SpotInstanceRequestId.1=sir-228e6406");
   assertPosted(DEFAULT_REGION, "Action=DescribeImages&ImageId.1=ami-595a0a1c");
   assertPosted(DEFAULT_REGION, "Action=CreateTags&Tag.1.Key=Name&Tag.1.Value=test-228e6406&ResourceId.1=sir-228e6406");
}
 
Example #27
Source File: AWSEC2ComputeServiceApiMockTest.java    From attic-stratos with Apache License 2.0 5 votes vote down vote up
public void launchVPCSpotInstanceSubnetId() throws Exception {
   enqueueRegions(DEFAULT_REGION);
   enqueueXml(DEFAULT_REGION, "/availabilityZones.xml");
   enqueueXml(DEFAULT_REGION, "/describe_images.xml");
   enqueueXml(DEFAULT_REGION, "/describe_images_cc.xml");
   enqueueXml(DEFAULT_REGION, "/request_spot_instances-ebs.xml");
   enqueueXml(DEFAULT_REGION, "/request_spot_instances-ebs.xml");
   enqueueXml(DEFAULT_REGION, "/describe_images_ebs.xml");
   enqueue(DEFAULT_REGION, new MockResponse()); // create tags

   ComputeService computeService = computeService();

   Template template = computeService.templateBuilder().locationId("us-east-1a").build();

   template.getOptions().as(AWSEC2TemplateOptions.class)
         .spotPrice(1f).subnetId("subnet-xyz").keyPair("Demo").blockUntilRunning(false);

   NodeMetadata node = Iterables.getOnlyElement(computeService.createNodesInGroup("test", 1, template));
   assertEquals(node.getId(), "us-east-1/sir-228e6406");

   assertPosted(DEFAULT_REGION, "Action=DescribeRegions");
   assertPosted(DEFAULT_REGION, "Action=DescribeAvailabilityZones");
   assertPosted(DEFAULT_REGION, "Action=DescribeImages&Filter.1.Name=owner-id&Filter.1.Value.1=137112412989&Filter.1.Value.2=801119661308&Filter.1.Value.3=063491364108&Filter.1.Value.4=099720109477&Filter.1.Value.5=411009282317&Filter.2.Name=state&Filter.2.Value.1=available&Filter.3.Name=image-type&Filter.3.Value.1=machine");
   assertPosted(DEFAULT_REGION, "Action=DescribeImages&Filter.1.Name=virtualization-type&Filter.1.Value.1=hvm&Filter.2.Name=architecture&Filter.2.Value.1=x86_64&Filter.3.Name=owner-id&Filter.3.Value.1=137112412989&Filter.3.Value.2=099720109477&Filter.4.Name=hypervisor&Filter.4.Value.1=xen&Filter.5.Name=state&Filter.5.Value.1=available&Filter.6.Name=image-type&Filter.6.Value.1=machine&Filter.7.Name=root-device-type&Filter.7.Value.1=ebs");
   assertPosted(DEFAULT_REGION, "Action=RequestSpotInstances&SpotPrice=1.0&InstanceCount=1&LaunchSpecification.ImageId=ami-" + getDefaultImageId() + "&LaunchSpecification.Placement.AvailabilityZone=us-east-1a&LaunchSpecification.InstanceType=" + getDefaultSmallestInstanceType() + "&LaunchSpecification.SubnetId=subnet-xyz&LaunchSpecification.KeyName=Demo&LaunchSpecification.UserData=I2Nsb3VkLWNvbmZpZwpyZXBvX3VwZ3JhZGU6IG5vbmUK");
   assertPosted(DEFAULT_REGION, "Action=DescribeSpotInstanceRequests&SpotInstanceRequestId.1=sir-228e6406");
   assertPosted(DEFAULT_REGION, "Action=DescribeImages&ImageId.1=ami-595a0a1c");
   assertPosted(DEFAULT_REGION, "Action=CreateTags&Tag.1.Key=Name&Tag.1.Value=test-228e6406&ResourceId.1=sir-228e6406");
}
 
Example #28
Source File: JcloudsHardwareProfilesStubbedLiveTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
protected NodeCreator newNodeCreator() {
    return new BasicNodeCreator() {
        @Override protected NodeMetadata newNode(String group, Template template) {
            JcloudsHardwareProfilesStubbedLiveTest.this.template = template;
            return super.newNode(group, template);
        }
    };
}
 
Example #29
Source File: JcloudsAwsImageChoiceStubbedLiveTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
protected NodeCreator newNodeCreator() {
    return new BasicNodeCreator() {
        @Override protected NodeMetadata newNode(String group, Template template) {
            JcloudsAwsImageChoiceStubbedLiveTest.this.template = template;
            return super.newNode(group, template);
        }
    };
}
 
Example #30
Source File: BailOutJcloudsLocation.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
public Template buildTemplate(ComputeService computeService, ConfigBag config, JcloudsLocationCustomizer customizersDelegate) {
    lastConfigBag = config;
    if (getConfig(BUILD_TEMPLATE_INTERCEPTOR) != null) {
        getConfig(BUILD_TEMPLATE_INTERCEPTOR).apply(config);
    }
    if (Boolean.TRUE.equals(getConfig(BUILD_TEMPLATE))) {
        template = super.buildTemplate(computeService, config, customizersDelegate);
    }
    throw new RuntimeException(BAIL_OUT_FOR_TESTING);
}