org.jclouds.compute.options.TemplateOptions Java Examples

The following examples show how to use org.jclouds.compute.options.TemplateOptions. 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: EC2CloudTLCInstanceParameters.java    From tlaplus with MIT License 6 votes vote down vote up
@Override
public void mungeTemplateOptions(TemplateOptions templateOptions) {
	//TODO Create (and the reuse) subnet automatically for instance types that require it.
	final String subnetId = System.getProperty("aws-ec2.subnetid");
	if (subnetId != null) {
		// Manually create a subnet first:
		// 1) Log into https://console.aws.amazon.com/vpc/ and select the correct region (match getRegion())
		// 1a) Optionally choose tenancy "dedicated" for more predictable performance
		// 2) Create a VPC (defaults are fine)
		// 3) Create a subnet (accept defaults) associated with VPC
		// 3a) "Modify auto-assign IP settings" of newly created subnet to automatically assign a public ip
		// 4) Create an Internet Gateway associated with the VPC
		// 4a) Associate with VPC 
		// 5) Create a Route Table for the VPC
		// 5a) Create a route with CIDR 0.0.0.0/0 via the gateway created in 4)
		// 6) Modify inbound rules of (automatically) created security group to include ssh/22,http/80,https/443 with source "0.0.0.0/0"
		templateOptions.as(AWSEC2TemplateOptions.class).subnetId(subnetId);
	}
}
 
Example #2
Source File: NetworkNameOption.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Override
    public void apply(TemplateOptions t, ConfigBag props, Object v) {
        if (t instanceof AWSEC2TemplateOptions) {
            // subnet ID is the sensible interpretation of network name in EC2
            ((AWSEC2TemplateOptions) t).subnetId((String) v);

        } else {
            if (isGoogleComputeTemplateOptions(t)) {
                // no warning needed
                // we think this is the only jclouds endpoint which supports this option

            } else if (t instanceof SoftLayerTemplateOptions) {
                LOG.warn("networkName is not be supported in SoftLayer; use `templateOptions` with `primaryNetworkComponentNetworkVlanId` or `primaryNetworkBackendComponentNetworkVlanId`");
            } else if (!(t instanceof CloudStackTemplateOptions) && !(t instanceof NovaTemplateOptions)) {
                LOG.warn("networkName is experimental in many jclouds endpoints may not be supported in this cloud");
                // NB, from @andreaturli
//                                Cloudstack uses custom securityGroupIds and networkIds not the generic networks
//                                Openstack Nova uses securityGroupNames which is marked as @deprecated (suggests to use groups which is maybe even more confusing)
//                                Azure supports the custom networkSecurityGroupName
            }

            t.networks((String) v);
        }
    }
 
Example #3
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 #4
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 #5
Source File: JcloudsStubTemplateBuilder.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
protected TemplateOptions newTemplateOptions() {
    switch (providerName) {
    case "aws-ec2" :
        return new AWSEC2TemplateOptions();
    case "ec2" :
        return new EC2TemplateOptions();
    case "google-compute-engine" :
        return new GoogleComputeEngineTemplateOptions();
        //return mock(GoogleComputeEngineTemplateOptions.class);
    case "azurecompute-arm" :
        return new org.jclouds.azurecompute.arm.compute.options.AzureTemplateOptions();
    case "softlayer" :
        return new SoftLayerTemplateOptions();
    default:
        throw new UnsupportedOperationException("Unsupported stubbed TemplateOptions for provider "+providerName);
    }
}
 
Example #6
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 #7
Source File: CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptions.java    From attic-stratos with Apache License 2.0 6 votes vote down vote up
@VisibleForTesting
String createNewPlacementGroupUnlessUserSpecifiedOtherwise(String region, String group, TemplateOptions options) {
   String placementGroupName = null;
   boolean shouldAutomaticallyCreatePlacementGroup = true;
   if (options instanceof EC2TemplateOptions) {
      placementGroupName = AWSEC2TemplateOptions.class.cast(options).getPlacementGroup();
      if (placementGroupName == null)
         shouldAutomaticallyCreatePlacementGroup = AWSEC2TemplateOptions.class.cast(options)
               .shouldAutomaticallyCreatePlacementGroup();
   }
   if (placementGroupName == null && shouldAutomaticallyCreatePlacementGroup) {
      // placementGroupName must be unique within an account per
      // http://docs.amazonwebservices.com/AWSEC2/latest/UserGuide/index.html?using_cluster_computing.html
      placementGroupName = String.format("jclouds#%s#%s", group, region);
      RegionAndName regionAndName = new RegionAndName(region, placementGroupName);
      // make this entry as needed
      placementGroupMap.getUnchecked(regionAndName);
   }
   return placementGroupName;
}
 
Example #8
Source File: CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptions.java    From attic-stratos with Apache License 2.0 6 votes vote down vote up
@Override
public String createNewKeyPairUnlessUserSpecifiedOtherwise(String region, String group, TemplateOptions options) {
   RegionAndName key = new RegionAndName(region, group);
   KeyPair pair;
   if (and(hasPublicKeyMaterial, or(doesntNeedSshAfterImportingPublicKey, hasLoginCredential)).apply(options)) {
      pair = importExistingKeyPair.apply(new RegionNameAndPublicKeyMaterial(region, group, options.getPublicKey()));
      options.dontAuthorizePublicKey();
      if (hasLoginCredential.apply(options))
         pair = pair.toBuilder().keyMaterial(options.getLoginPrivateKey()).build();
      credentialsMap.put(key, pair);
   } else {
      if (hasPublicKeyMaterial.apply(options)) {
         logger.warn("to avoid creating temporary keys in aws-ec2, use templateOption overrideLoginCredentialWith(id_rsa)");
      }
      return super.createNewKeyPairUnlessUserSpecifiedOtherwise(region, group, options);
   }
   return pair.getKeyName();
}
 
Example #9
Source File: InboundPortsOption.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
public void apply(TemplateOptions t, ConfigBag props, Object v) {
    int[] inboundPorts = toIntPortArray(v);
    if (LOG.isDebugEnabled())
        LOG.debug("opening inbound ports {} for cloud/type {}", Arrays.toString(inboundPorts), t.getClass());
    t.inboundPorts(inboundPorts);
}
 
Example #10
Source File: TemplateOptionsOption.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
public void apply(TemplateOptions options, ConfigBag config, Object v) {
    if (v == null) return;
    @SuppressWarnings("unchecked") Map<String, Object> optionsMap = (Map<String, Object>) v;
    if (optionsMap.isEmpty()) return;

    Class<? extends TemplateOptions> clazz = options.getClass();
    for (final Map.Entry<String, Object> option : optionsMap.entrySet()) {
        Object optionValue = option.getValue();
        if (optionValue != null) {

            try {
                final ExecutionContext exec = BrooklynTaskTags.getCurrentExecutionContext();
                if (exec != null) {
                    optionValue = Tasks.resolveDeepValue(optionValue, Object.class, exec);
                }
            } catch (ExecutionException | InterruptedException e) {
                Exceptions.propagate(e);
            }

            Maybe<?> result = MethodCoercions.tryFindAndInvokeBestMatchingMethod(options, option.getKey(), optionValue);
            if (result.isAbsent()) {
                LOG.warn("Ignoring request to set template option {} because this is not supported by {}", new Object[]{option.getKey(), clazz.getCanonicalName()});
            }
        } else {
            // jclouds really doesn't like you to pass nulls; don't do it! For us,
            // null is the only way to remove an inherited value when the templateOptions
            // map is being merged.
            LOG.debug("Ignoring request to set template option {} because value is null", new Object[]{option.getKey(), clazz.getCanonicalName()});
        }
    }
}
 
Example #11
Source File: AbstractPortableTemplateBuilder.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
/** adds customization options; if options have already been set, this will additively set selected options
 * (but not all, see addTemplateOptions for more info)
 */
public T addOptions(final TemplateOptions options) {
    this.additionalOptions.add(options);
    commands.add(new Function<TemplateBuilder,TemplateBuilder>() { 
        @Override
        public TemplateBuilder apply(TemplateBuilder b) { return b.options(options); }});
    return (T)this;
}
 
Example #12
Source File: KeyPairOption.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
public void apply(TemplateOptions t, ConfigBag props, Object v) {
    if (t instanceof EC2TemplateOptions) {
        ((EC2TemplateOptions) t).keyPair(v.toString());
    } else if (t instanceof NovaTemplateOptions) {
        ((NovaTemplateOptions) t).keyPairName(v.toString());
    } else if (t instanceof CloudStackTemplateOptions) {
        ((CloudStackTemplateOptions) t).keyPair(v.toString());
    } else {
        LOG.info("ignoring keyPair({}) in VM creation because not supported for cloud/type ({})", v, t);
    }
}
 
Example #13
Source File: JcloudsLocation.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
/**
 * Set up the TemplateOptions to create the user.
 */
protected LoginCredentials initTemplateForCreateUser(Template template, ConfigBag config) {
    CreateUserStatements userCreation = createUserStatements(template.getImage(), config);

    if (!userCreation.statements().isEmpty()) {
        TemplateOptions options = template.getOptions();
        options.runScript(new StatementList(userCreation.statements()));
    }

    return userCreation.credentials();
}
 
Example #14
Source File: ReusableMachineTemplate.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
public List<TemplateOptions> getAdditionalOptionalOptions() {
    List<TemplateOptions> result = new ArrayList<TemplateOptions>();
    result.addAll(super.getAdditionalOptions());
    addStrictOptions(result);
    return result;
}
 
Example #15
Source File: AutoGenerateKeypairsOption.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
public void apply(TemplateOptions t, ConfigBag props, Object v) {
    if (t instanceof NovaTemplateOptions) {
        ((NovaTemplateOptions) t).generateKeyPair((Boolean) v);
    } else if (t instanceof CloudStackTemplateOptions) {
        ((CloudStackTemplateOptions) t).generateKeyPair((Boolean) v);
    } else {
        LOG.info("ignoring auto-generate-keypairs({}) in VM creation because not supported for cloud/type ({})", v, t);
    }
}
 
Example #16
Source File: EbsVolumeCustomizers.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
public void customize(JcloudsLocation location, ComputeService computeService, TemplateOptions templateOptions) {
    if (templateOptions instanceof EC2TemplateOptions) {
        ((EC2TemplateOptions) templateOptions).mapNewVolumeToDeviceName(ec2DeviceName, sizeInGib, deleteOnTermination);
    } else {
        LOG.debug("Skipping configuration of non-EC2 TemplateOptions {}", templateOptions);
    }
}
 
Example #17
Source File: ExtraPublicKeyDataToAuthOption.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("deprecation")
@Override
public void apply(TemplateOptions t, ConfigBag props, Object v) {
    // this is unreliable:
    // * seems now (Aug 2016) to be run *before* the TO.runScript which creates the user,
    // so is installed for the initial login user not the created user
    // * not supported in GCE (it uses it as the login public key, see email to jclouds list, 29 Aug 2015)
    // so only works if you also overrideLoginPrivateKey
    // --
    // for this reason we also inspect these ourselves
    // along with EXTRA_PUBLIC_KEY_URLS_TO_AUTH
    // and install after creation;
    // --
    // we also do it here for legacy reasons though i (alex) can't think of any situations it's needed
    // --
    // also we warn on exceptions in case someone is dumping comments or something else
    //
    // TODO remove in 1.1 or later, if we confirm there is no need for this
    try {
        if (BrooklynSystemProperties.JCLOUDS_AUTHORIZE_EXTRA_SSH_PUBLIC_KEY_DATA.isEnabled()) {
            // May 2018 - disabled this unless explicitly enabled as it breaks the use of key pairs
            t.authorizePublicKey(v.toString());
        }
    } catch (Exception e) {
        Exceptions.propagateIfFatal(e);
        LOG.warn("Error trying jclouds authorizePublicKey; will run later: " + e, e);
    }
}
 
Example #18
Source File: LoginUserPrivateKeyFileOption.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
public void apply(TemplateOptions t, ConfigBag props, Object v) {
    if (v != null) {
        String privateKeyFileName = v.toString();
        String privateKey;
        try {
            privateKey = Files.toString(new File(Os.tidyPath(privateKeyFileName)), Charsets.UTF_8);
        } catch (IOException e) {
            LOG.error(privateKeyFileName + "not found", e);
            throw Exceptions.propagate(e);
        }
        t.overrideLoginPrivateKey(privateKey);
    }
}
 
Example #19
Source File: PortableTemplateBuilder.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
protected String makeNonTrivialArgumentsString() {
    String s = super.makeNonTrivialArgumentsString();
    TemplateOptions aggr = computeAggregatedOptions(false);
    if (aggr.getInboundPorts().length>0) s = "ports="+Ints.asList(aggr.getInboundPorts())+(s!=null && s.length()>0 ? ", "+s : "");
    if (!aggr.getUserMetadata().isEmpty()) s = "metadata="+aggr.getUserMetadata()+(s!=null && s.length()>0 ? ", "+s : "");
    if (!aggr.getTags().isEmpty()) s = "tags="+aggr.getTags()+(s!=null && s.length()>0 ? ", "+s : "");
    return s;
}
 
Example #20
Source File: AutoAssignFloatingIpOption.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
public void apply(TemplateOptions t, ConfigBag props, Object v) {
    if (t instanceof NovaTemplateOptions) {
        ((NovaTemplateOptions) t).autoAssignFloatingIp((Boolean) v);
    } else if (t instanceof CloudStackTemplateOptions) {
        ((CloudStackTemplateOptions) t).setupStaticNat((Boolean) v);
    } else {
        LOG.info("ignoring auto-assign-floating-ip({}) in VM creation because not supported for cloud/type ({})", v, t);
    }
}
 
Example #21
Source File: AWSEC2TemplateBuilderImpl.java    From attic-stratos with Apache License 2.0 5 votes vote down vote up
@Inject
protected AWSEC2TemplateBuilderImpl(@Memoized Supplier<Set<? extends Location>> locations,
      ImageCacheSupplier images, @Memoized Supplier<Set<? extends Hardware>> sizes,
      Supplier<Location> defaultLocation, @Named("DEFAULT") Provider<TemplateOptions> optionsProvider,
      @Named("DEFAULT") Provider<TemplateBuilder> defaultTemplateProvider, GetImageStrategy getImageStrategy,
      Supplier<LoadingCache<RegionAndName, ? extends Image>> imageMap) {
   super(locations, images, sizes, defaultLocation, optionsProvider, defaultTemplateProvider, getImageStrategy, imageMap);
}
 
Example #22
Source File: StringTagsOption.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
public void apply(TemplateOptions t, ConfigBag props, Object v) {
    List<String> tags = Strings.toStringList(v);
    if (LOG.isDebugEnabled()) {
        LOG.debug("setting VM tags {} for {}", tags, t);
    }
    t.tags(tags);
}
 
Example #23
Source File: PortableTemplateBuilder.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
public TemplateBuilder from(TemplateBuilderSpec spec) {
    TemplateOptions options = new TemplateOptions();
    addOptionalOptions(options);
    TemplateBuilder result = spec.copyTo(this, options);
    return result;
}
 
Example #24
Source File: AWSEC2ComputeService.java    From attic-stratos with Apache License 2.0 5 votes vote down vote up
@Inject
protected AWSEC2ComputeService(ComputeServiceContext context, Map<String, Credentials> credentialStore,
      @Memoized Supplier<Set<? extends Image>> images, @Memoized Supplier<Set<? extends Hardware>> sizes,
      @Memoized Supplier<Set<? extends Location>> locations, ListNodesStrategy listNodesStrategy,
      GetImageStrategy getImageStrategy, GetNodeMetadataStrategy getNodeMetadataStrategy,
      CreateNodesInGroupThenAddToSet runNodesAndAddToSetStrategy, RebootNodeStrategy rebootNodeStrategy,
      DestroyNodeStrategy destroyNodeStrategy, ResumeNodeStrategy startNodeStrategy,
      SuspendNodeStrategy stopNodeStrategy, Provider<TemplateBuilder> templateBuilderProvider,
      @Named("DEFAULT") Provider<TemplateOptions> templateOptionsProvider,
      @Named(TIMEOUT_NODE_RUNNING) Predicate<AtomicReference<NodeMetadata>> nodeRunning,
      @Named(TIMEOUT_NODE_TERMINATED) Predicate<AtomicReference<NodeMetadata>> nodeTerminated,
      @Named(TIMEOUT_NODE_SUSPENDED) Predicate<AtomicReference<NodeMetadata>> nodeSuspended,
      InitializeRunScriptOnNodeOrPlaceInBadMap.Factory initScriptRunnerFactory,
      RunScriptOnNode.Factory runScriptOnNodeFactory, InitAdminAccess initAdminAccess,
      PersistNodeCredentials persistNodeCredentials, Timeouts timeouts,
      @Named(Constants.PROPERTY_USER_THREADS) ListeningExecutorService userExecutor, AWSEC2Api client,
      ConcurrentMap<RegionAndName, KeyPair> credentialsMap,
      @Named("SECURITY") LoadingCache<RegionAndName, String> securityGroupMap,
      @Named("PLACEMENT") LoadingCache<RegionAndName, String> placementGroupMap,
      @Named("DELETED") Predicate<PlacementGroup> placementGroupDeleted, Optional<ImageExtension> imageExtension,
      GroupNamingConvention.Factory namingConvention,
      @Named(PROPERTY_EC2_GENERATE_INSTANCE_NAMES) boolean generateInstanceNames,
      Optional<SecurityGroupExtension> securityGroupExtension) {
   super(context, credentialStore, images, sizes, locations, listNodesStrategy, getImageStrategy,
         getNodeMetadataStrategy, runNodesAndAddToSetStrategy, rebootNodeStrategy, destroyNodeStrategy,
         startNodeStrategy, stopNodeStrategy, templateBuilderProvider, templateOptionsProvider, nodeRunning,
         nodeTerminated, nodeSuspended, initScriptRunnerFactory, runScriptOnNodeFactory, initAdminAccess,
         persistNodeCredentials, timeouts, userExecutor, client, credentialsMap, securityGroupMap, imageExtension,
         namingConvention, generateInstanceNames, securityGroupExtension);
   this.client = client;
   this.placementGroupMap = placementGroupMap;
   this.placementGroupDeleted = placementGroupDeleted;
}
 
Example #25
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 #26
Source File: SharedLocationSecurityGroupCustomizerTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@BeforeMethod(alwaysRun = true)
public void setUp() {
    sgCustomizer = mock(JcloudsLocationSecurityGroupCustomizer.class);
    customizer = new TestSharedLocationSecurityGroupCustomizer();
    location = mock(Location.class);
    securityApi = mock(SecurityGroupExtension.class);
    computeService = mock(ComputeService.class, Answers.RETURNS_DEEP_STUBS.get());
    mockTemplate = mock(Template.class);
    mockOptions = mock(TemplateOptions.class);
    when(computeService.getSecurityGroupExtension()).thenReturn(Optional.of(securityApi));
    when(mockTemplate.getOptions()).thenReturn(mockOptions);
    when(mockOptions.getInboundPorts()).thenReturn(new int[]{});
}
 
Example #27
Source File: JcloudsLocationTemplateOptionsCustomisersLiveTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
/**
 * Invoke a specific template options customizer on a TemplateOptions instance.
 *
 * @param templateOptions the TemplateOptions instance that you expect the customizer to modify.
 * @param keyToTest the config key that identifies the customizer. This must be present in both @{code locationConfig} and @{link JcloudsLocation.SUPPORTED_TEMPLATE_OPTIONS_PROPERTIES}.
 * @param locationConfig simulated configuration for the location. This must contain at least an entry for @{code keyToTest}.
 */
private void invokeCustomizeTemplateOptions(TemplateOptions templateOptions, ConfigKey<?> keyToTest, ConfigBag locationConfig) {
    checkNotNull(templateOptions, "templateOptions");
    checkNotNull(keyToTest, "keyToTest");
    checkNotNull(locationConfig, "locationConfig");
    checkState(JcloudsLocation.SUPPORTED_TEMPLATE_OPTIONS_PROPERTIES.containsKey(keyToTest),
            "SUPPORTED_TEMPLATE_OPTIONS_PROPERTIES does not contain a customiser for the key " + keyToTest.getName());
    checkState(locationConfig.containsKey(keyToTest),
            "location config does not contain the key " + keyToTest.getName());

    TemplateOptionCustomizer code = JcloudsLocation.SUPPORTED_TEMPLATE_OPTIONS_PROPERTIES.get(keyToTest);
    code.apply(templateOptions, locationConfig, locationConfig.get(keyToTest));
}
 
Example #28
Source File: JcloudsCustomizerInstantiationYamlDslTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
public static TemplateOptions findTemplateOptionsInCustomizerArgs() {
    for (CallParams call : calls) {
        Optional<?> templateOptions = Iterables.tryFind(call.args, Predicates.instanceOf(TemplateOptions.class));
        if (templateOptions.isPresent()) {
            return (TemplateOptions) templateOptions.get();
        }
    }
    throw new NoSuchElementException();
}
 
Example #29
Source File: AWSEC2ComputeServiceDependenciesModule.java    From attic-stratos with Apache License 2.0 5 votes vote down vote up
@Override
protected void configure() {
   bind(TemplateBuilder.class).to(EC2TemplateBuilderImpl.class);
   bind(TemplateOptions.class).to(AWSEC2TemplateOptions.class);
   bind(ComputeService.class).to(AWSEC2ComputeService.class);
   bind(new TypeLiteral<CacheLoader<RunningInstance, Optional<LoginCredentials>>>() {
   }).to(CredentialsForInstance.class);
   bind(new TypeLiteral<CacheLoader<RegionAndName, String>>() {
   }).annotatedWith(Names.named("SECURITY")).to(AWSEC2CreateSecurityGroupIfNeeded.class);
   bind(new TypeLiteral<CacheLoader<RegionAndName, String>>() {
   }).annotatedWith(Names.named("ELASTICIP")).to(LoadPublicIpForInstanceOrNull.class);
   bind(new TypeLiteral<Function<String, String>>() {
   }).annotatedWith(Names.named("SECGROUP_NAME_TO_ID")).to(EC2SecurityGroupIdFromName.class);
   bind(new TypeLiteral<Function<PasswordDataAndPrivateKey, LoginCredentials>>() {
   }).to(WindowsLoginCredentialsFromEncryptedData.class);
   bind(new TypeLiteral<Function<RunningInstance, LoginCredentials>>() {
   }).to(PasswordCredentialsFromWindowsInstance.class);
   bind(new TypeLiteral<Function<RegionAndName, KeyPair>>() {
   }).to(CreateUniqueKeyPair.class);
   bind(new TypeLiteral<Function<RegionNameAndPublicKeyMaterial, KeyPair>>() {
   }).to(ImportOrReturnExistingKeypair.class);
   bind(new TypeLiteral<CacheLoader<RegionAndName, Image>>() {
   }).to(RegionAndIdToImage.class);
   install(new FactoryModuleBuilder().build(CallForImages.Factory.class));
   bind(new TypeLiteral<Function<org.jclouds.ec2.domain.Image, Image>>() {
   }).to(EC2ImageParser.class);
   bind(new TypeLiteral<Function<org.jclouds.ec2.domain.SecurityGroup, SecurityGroup>>() {
   }).to(AWSEC2SecurityGroupToSecurityGroup.class);
   bind(new TypeLiteral<ImageExtension>() {
   }).to(EC2ImageExtension.class);
   bind(new TypeLiteral<SecurityGroupExtension>() {
   }).to(AWSEC2SecurityGroupExtension.class);
}
 
Example #30
Source File: AWSEC2TemplateOptions.java    From attic-stratos with Apache License 2.0 5 votes vote down vote up
@Override
public void copyTo(TemplateOptions to) {
   super.copyTo(to);
   if (to instanceof AWSEC2TemplateOptions) {
      AWSEC2TemplateOptions eTo = AWSEC2TemplateOptions.class.cast(to);
      if (getSubnetId() != null)
         eTo.subnetId(getSubnetId());
      if (getIAMInstanceProfileArn() != null)
         eTo.iamInstanceProfileArn(getIAMInstanceProfileArn());
      if (getIAMInstanceProfileName() != null)
         eTo.iamInstanceProfileName(getIAMInstanceProfileName());
      if (isMonitoringEnabled())
         eTo.enableMonitoring();
       if (isPublicIpAddressAssociated())
           eTo.associatePublicIpAddress();
      if (!shouldAutomaticallyCreatePlacementGroup())
         eTo.noPlacementGroup();
      if (getPlacementGroup() != null)
         eTo.placementGroup(getPlacementGroup());
      if (!getGroupIds().isEmpty())
         eTo.securityGroupIds(getGroupIds());
      if (getSpotPrice() != null)
         eTo.spotPrice(getSpotPrice());
      if (getSpotOptions() != null)
         eTo.spotOptions(getSpotOptions());
      if (getPrivateIpAddress() != null)
         eTo.privateIpAddress(getPrivateIpAddress());
   }
}