org.jclouds.compute.ComputeService Java Examples

The following examples show how to use org.jclouds.compute.ComputeService. 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: BrooklynImageChooser.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Override
public ImageChooserFromOrdering cloneFor(ComputeService service) {
    if (Iterables.tryFind(orderings, Predicates.instanceOf(ComputeServiceAwareChooser.class)).isPresent()) {
        List<Ordering<? super Image>> clonedOrderings = Lists.newArrayList();
        for (Ordering<? super Image> ordering : orderings) {
            if (ordering instanceof ComputeServiceAwareChooser) {
                clonedOrderings.add(BrooklynImageChooser.cloneFor(ordering, service));
            } else {
                clonedOrderings.add(ordering);
            }
        }
        return new ImageChooserFromOrdering(clonedOrderings);
    } else {
        return this;
    }
}
 
Example #2
Source File: MainApp.java    From jclouds-examples with Apache License 2.0 6 votes vote down vote up
private static void runScriptOnGroup(final ComputeService compute,
                                     final LoginCredentials login, final String groupName, final Statement command)
        throws RunScriptOnNodesException {
    // when you run commands, you can pass options to decide whether
    // to run it as root, supply or own credentials vs from cache,
    // and wrap in an init script vs directly invoke
    Map<? extends NodeMetadata, ExecResponse> execResponses =
            compute.runScriptOnNodesMatching(//
                    inGroup(groupName), // predicate used to select nodes
                    command, // what you actually intend to run
                    overrideLoginCredentials(login)); // use the local user & ssh key

    for (Entry<? extends NodeMetadata, ExecResponse> response : execResponses.entrySet()) {
        System.out.printf(
                "<< node %s: %s%n",
                response.getKey().getId(),
                concat(response.getKey().getPrivateAddresses(), response.getKey()
                        .getPublicAddresses())
        );
        System.out.printf("<<     %s%n", response.getValue());
    }
}
 
Example #3
Source File: JcloudsSshMachineLocation.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
protected Optional<Image> getOptionalImage() {
  if (_image == null) {
      if (imageId == null) {
          _image = Optional.absent(); // can happen with JcloudsLocation.resumeMachine() usage
      } else {
          try {
              ComputeService computeService = getComputeServiceOrNull();
              if (computeService == null) {
                  if (LOG.isDebugEnabled()) LOG.debug("Cannot get image (with id {}) for {}, because cannot get compute-service from parent {}", new Object[] {imageId, this, getParent()});
                  _image = Optional.absent();
              } else {
                  _image = Optional.fromNullable(computeService.getImage(imageId));
              }
          } catch (Exception e) {
              Exceptions.propagateIfFatal(e);
              if (LOG.isDebugEnabled()) LOG.debug("Problem getting image for " + this + ", image id " + imageId + " (continuing)", e);
              _image = Optional.absent();
          }
      }
  }
  return _image;
}
 
Example #4
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 #5
Source File: ChildEntityCustomizer.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Override
public void customize(JcloudsLocation location, ComputeService computeService, JcloudsMachineLocation machine) {
    EntitySpec<?> spec = config().get(CHILD_ENTITY_SPEC);
    Boolean create = config().get(CREATE_CHILD_ENTITY);
    Duration timeout = config().get(BrooklynConfigKeys.START_TIMEOUT);
    Entity parent = getCallerContext(machine);

    if (Boolean.TRUE.equals(create) && spec != null) {
        LOG.info("Creating child entity for {} in {}", parent, machine);
        Entity child = getBrooklynManagementContext().getEntityManager().createEntity(spec);
        child.setParent(parent);
        Task<Void> start = Entities.invokeEffectorWithArgs(parent, child, Startable.START, ImmutableList.of(machine));
        if (!start.blockUntilEnded(timeout)) {
            throw new IllegalStateException(String.format("Timed out while starting child entity for %s", parent));
        }
    }
}
 
Example #6
Source File: JcloudsLocation.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
/**
 * Brings an existing machine with the given details under management.
 * <p/>
 * Note that this method does <b>not</b> call the lifecycle methods of any
 * {@link #getCustomizers(ConfigBag) customizers} attached to this location.
 *
 * @param flags See {@link #registerMachine(ConfigBag)} for a description of required fields.
 * @see #registerMachine(ConfigBag)
 */
@Override
public JcloudsMachineLocation resumeMachine(Map<?, ?> flags) {
    ConfigBag setup = ConfigBag.newInstanceExtending(config().getBag(), flags);
    LOG.info("{} using resuming node matching properties: {}", this, Sanitizer.sanitize(setup));
    ComputeService computeService = getComputeService(setup);
    NodeMetadata node = findNodeOrThrow(setup);
    LOG.debug("{} resuming {}", this, node);
    computeService.resumeNode(node.getId());
    // Load the node a second time once it is resumed to get an object with
    // hostname and addresses populated.
    node = findNodeOrThrow(setup);
    LOG.debug("{} resumed {}", this, node);
    JcloudsMachineLocation registered = registerMachineLocation(setup, node);
    LOG.info("{} resumed and registered {}", this, registered);
    return registered;
}
 
Example #7
Source File: ComputeServiceBuilderUtil.java    From attic-stratos with Apache License 2.0 6 votes vote down vote up
public static ComputeService buildDefaultComputeService(IaasProvider iaasProvider) {

        Properties properties = new Properties();

        // load properties
        for (Map.Entry<String, String> entry : iaasProvider.getProperties().entrySet()) {
            properties.put(entry.getKey(), entry.getValue());
        }

        // set modules
        Iterable<Module> modules =
                ImmutableSet.<Module>of(new SshjSshClientModule(), new SLF4JLoggingModule(),
                        new EnterpriseConfigurationModule());

        // build context
        ContextBuilder builder =
                ContextBuilder.newBuilder(iaasProvider.getProvider())
                        .credentials(iaasProvider.getIdentity(), iaasProvider.getCredential()).modules(modules)
                        .overrides(properties);

        return builder.buildView(ComputeServiceContext.class).getComputeService();
    }
 
Example #8
Source File: JcloudsLocationSecurityGroupCustomizer.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
/**
 * Removes the given security group permissions from the given node.
 * <p>
 * Takes no action if the compute service does not have a security group extension.
 * @param location Location of the node to remove permissions from
 * @param permissions The set of permissions to be removed from the node
 */
private void removePermissionsInternal(JcloudsMachineLocation location, Iterable<IpPermission> permissions) {
    ComputeService computeService = location.getParent().getComputeService();
    String nodeId = location.getNode().getId();

    final Optional<SecurityGroupExtension> securityApi = computeService.getSecurityGroupExtension();
    if (!securityApi.isPresent()) {
        LOG.warn("Security group extension for {} absent; cannot update node {} with {}",
                new Object[] {computeService, nodeId, permissions});
        return;
    }

    final SecurityGroupEditor editor = createSecurityGroupEditor(securityApi.get(), location.getNode().getLocation());
    String locationId = computeService.getContext().unwrap().getId();
    SecurityGroup machineUniqueSecurityGroup = getMachineUniqueSecurityGroup(nodeId, locationId, editor);
    editor.removePermissions(machineUniqueSecurityGroup, permissions);
}
 
Example #9
Source File: MainApp.java    From jclouds-examples with Apache License 2.0 6 votes vote down vote up
private static ComputeService initComputeService(final String provider, final String identity,
                                                 final String credential) {
    // example of specific properties, in this case optimizing image list to
    // only amazon supplied
    Properties properties = new Properties();
    long scriptTimeout = TimeUnit.MILLISECONDS.convert(20, TimeUnit.MINUTES);
    properties.setProperty(TIMEOUT_SCRIPT_COMPLETE, scriptTimeout + "");

    // example of injecting a ssh implementation
    Iterable<Module> modules =
            ImmutableSet.<Module>of(new SshjSshClientModule(), new SLF4JLoggingModule(),
                    new EnterpriseConfigurationModule());

    ContextBuilder builder =
            ContextBuilder.newBuilder(provider).credentials(identity, credential).modules(modules)
                    .overrides(properties);

    System.out.printf(">> initializing %s%n", builder.getApiMetadata());

    return builder.buildView(ComputeServiceContext.class).getComputeService();
}
 
Example #10
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 #11
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 #12
Source File: JcloudsLocationResolverTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testJcloudsImageChooserConfiguredFromBrooklynProperties() {
    brooklynProperties.put("brooklyn.location.named.myloc", "jclouds:aws-ec2");
    brooklynProperties.put("brooklyn.location.named.myloc.imageChooser", JcloudsLocationResolverTest.class.getName()+"$"+MyFunction.class.getSimpleName());
    brooklynProperties.put("brooklyn.location.jclouds.openstack-nova.foo", "bar");
    JcloudsLocation loc = resolve("myloc");
    
    // Test relies on the computeService not being used! Not great, but good enough.
    Function<Iterable<? extends Image>, Image> chooser = loc.getImageChooser((ComputeService)null, loc.config().getLocalBag());
    assertTrue(chooser instanceof MyFunction, "chooser="+chooser);
}
 
Example #13
Source File: AbstractComputeServiceRegistry.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
public ComputeService get() {
    // Synchronizing to avoid deadlock from sun.reflect.annotation.AnnotationType.
    // See https://github.com/brooklyncentral/brooklyn/issues/974
    synchronized (createComputeServicesMutex) {
        ComputeServiceContext computeServiceContext = ContextBuilder.newBuilder(provider)
                .modules(modules)
                .credentialsSupplier(AbstractComputeServiceRegistry.this.makeCredentials(conf))
                .overrides(properties)
                .build(ComputeServiceContext.class);
        return computeServiceContext.getComputeService();
    }
}
 
Example #14
Source File: AWSEC2ComputeServiceApiMockTest.java    From attic-stratos with Apache License 2.0 5 votes vote down vote up
public void createNodeWithIAMInstanceProfileArn() throws Exception {
   enqueueRegions(DEFAULT_REGION);
   enqueueXml(DEFAULT_REGION, "/amzn_images.xml");
   enqueueXml(DEFAULT_REGION, "/describe_images_cc.xml");
   enqueueXml(DEFAULT_REGION, "/availabilityZones.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, "/new_instance.xml");
   enqueueXml(DEFAULT_REGION, "/describe_instances_running-1.xml");
   enqueueXml(DEFAULT_REGION, "/describe_images.xml");
   enqueue(DEFAULT_REGION, new MockResponse()); // create tags

   ComputeService computeService = computeService();

   NodeMetadata node = Iterables.getOnlyElement(computeService.createNodesInGroup("test", 1,
         blockUntilRunning(false).iamInstanceProfileArn(iamInstanceProfileArn).noKeyPair()));
   assertEquals(node.getId(), "us-east-1/i-2baa5550");

   assertPosted(DEFAULT_REGION, "Action=DescribeRegions");
   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=DescribeAvailabilityZones");
   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=RunInstances&ImageId=ami-8ce4b5c9&MinCount=1&MaxCount=1&InstanceType=" + getDefaultParavirtualInstanceType() + "&SecurityGroup.1=jclouds%23test&UserData=I2Nsb3VkLWNvbmZpZwpyZXBvX3VwZ3JhZGU6IG5vbmUK&IamInstanceProfile.Arn=arn%3Aaws%3Aiam%3A%3A123456789012%3Ainstance-profile/application_abc/component_xyz/Webserver");
   assertPosted(DEFAULT_REGION, "Action=DescribeInstances&InstanceId.1=i-2baa5550");
   assertPosted(DEFAULT_REGION, "Action=DescribeImages&ImageId.1=ami-aecd60c7");
   assertPosted(DEFAULT_REGION, "Action=CreateTags&Tag.1.Key=Name&Tag.1.Value=test-2baa5550&ResourceId.1=i-2baa5550");
}
 
Example #15
Source File: CloudExplorerSupport.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
protected void doCall(ComputeService computeService, String indent) throws Exception {

    for (String imageId : names) {
        Image image = computeService.getImage(imageId);
        if (image == null) {
            return;
        }
        stdout.println(indent+"Image "+imageId+" {");
        stdout.println(indent+"\t"+image);
        stdout.println(indent+"}");
    }
}
 
Example #16
Source File: StubbedComputeServiceRegistry.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
/**
 * If using {@link #allowCloudQueries}, then we'll go through the jclouds code to instantiate
 * a delegate {@link ComputeService}. That takes about a second (because of everything guice
 * does), so is unpleasant to do in unit tests.
 * 
 * Better is to create the {@link StubbedComputeServiceRegistry} with that disabled, which will
 * throw an exception if any unexpected method is called on {@link ComputeService}.
 */
@Override
public ComputeService findComputeService(ConfigBag conf, boolean allowReuse) {
    if (allowCloudQueries) {
        ComputeService delegate = ComputeServiceRegistryImpl.INSTANCE.findComputeService(conf, allowReuse);
        return new MinimalComputeService(delegate, nodeCreator);
    } else {
        return new StubbedComputeService(nodeCreator);
    }
}
 
Example #17
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);
}
 
Example #18
Source File: PortableTemplateBuilder.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
public TemplateBuilder newJcloudsTemplateBuilder(ComputeService svc) {
    TemplateBuilder tb = svc.templateBuilder();
    for (Function<TemplateBuilder,TemplateBuilder> c: commands) {
        tb = c.apply(tb);
    }
    
    tb.options(computeAggregatedOptions(true));
    
    return tb;
}
 
Example #19
Source File: CloudExplorerSupport.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
protected void doCall(ComputeService computeService, String indent) throws Exception {
    Set<? extends ComputeMetadata> instances = computeService.listNodes();
    stdout.println(indent+"Instances {");
    for (ComputeMetadata instance : instances) {
        stdout.println(indent+"\t"+instance);
    }
    stdout.println(indent+"}");
}
 
Example #20
Source File: BrooklynImageChooser.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
protected void use(ComputeService service) {
    if (this.computeService!=null && !this.computeService.equals(service))
        throw new IllegalStateException("ImageChooser must be cloned to set a compute service");
    this.computeService = service;
    if (computeService!=null) {
        cloudProviderName = computeService.getContext().unwrap().getId();
    }
}
 
Example #21
Source File: JcloudsUtil.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
public static String waitForPasswordOnAws(ComputeService computeService, final NodeMetadata node, long timeout, TimeUnit timeUnit) throws TimeoutException {
    ComputeServiceContext computeServiceContext = computeService.getContext();
    AWSEC2Api ec2Client = computeServiceContext.unwrapApi(AWSEC2Api.class);
    final WindowsApi client = ec2Client.getWindowsApi().get();
    final String region = node.getLocation().getParent().getId();

    // The Administrator password will take some time before it is ready - Amazon says sometimes 15 minutes.
    // So we create a predicate that tests if the password is ready, and wrap it in a retryable predicate.
    Predicate<String> passwordReady = new Predicate<String>() {
        @Override public boolean apply(String s) {
            if (Strings.isNullOrEmpty(s)) return false;
            PasswordData data = client.getPasswordDataInRegion(region, s);
            if (data == null) return false;
            return !Strings.isNullOrEmpty(data.getPasswordData());
        }
    };

    LOG.info("Waiting for password, for "+node.getProviderId()+":"+node.getId());
    Predicate<String> passwordReadyRetryable = Predicates2.retry(passwordReady, timeUnit.toMillis(timeout), 10*1000, TimeUnit.MILLISECONDS);
    boolean ready = passwordReadyRetryable.apply(node.getProviderId());
    if (!ready) throw new TimeoutException("Password not available for "+node+" in region "+region+" after "+timeout+" "+timeUnit.name());

    // Now pull together Amazon's encrypted password blob, and the private key that jclouds generated
    PasswordDataAndPrivateKey dataAndKey = new PasswordDataAndPrivateKey(
            client.getPasswordDataInRegion(region, node.getProviderId()),
            node.getCredentials().getPrivateKey());

    // And apply it to the decryption function
    WindowsLoginCredentialsFromEncryptedData f = computeServiceContext.utils().injector().getInstance(WindowsLoginCredentialsFromEncryptedData.class);
    LoginCredentials credentials = f.apply(dataAndKey);

    return credentials.getPassword();
}
 
Example #22
Source File: SecurityGroupLiveTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
private SecurityGroupEditor makeEditor() {
    final org.jclouds.domain.Location nodeLocation = jcloudsMachineLocation.getNode().getLocation();
    ComputeService computeService = jcloudsMachineLocation.getParent().getComputeService();
    final Optional<SecurityGroupExtension> securityGroupExtension = computeService.getSecurityGroupExtension();
    if (securityGroupExtension.isPresent()) {
        return new SecurityGroupEditor(nodeLocation, securityGroupExtension.get());
    } else {
        throw new IllegalArgumentException("Expected SecurityGroupExtension not found in " + computeService);
    }
}
 
Example #23
Source File: AbstractComputeServiceRegistry.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
public ComputeService findComputeService(ConfigBag conf, boolean allowReuse) {
    JCloudsPropertiesBuilder propertiesBuilder = new JCloudsPropertiesBuilder(conf)
            .setCommonJcloudsProperties();

    // Enable aws-ec2 lazy image fetching, if given a specific imageId; otherwise customize for specific owners; or all as a last resort
    // See https://issues.apache.org/jira/browse/WHIRR-416
    String provider = getProviderFromConfig(conf);
    if ("aws-ec2".equals(provider)) {
        propertiesBuilder.setAWSEC2Properties();
    } else if ("azurecompute-arm".equals(provider)) {
        propertiesBuilder.setAzureComputeArmProperties();
    }

    Properties properties = propertiesBuilder
            .setCustomJcloudsProperties()
            .setEndpointProperty()
            .build();

    ImmutableSet.Builder<? extends Module> modulesBuilder = ImmutableSet.<Module>builder()
            .addAll(commonModules())
            .addAll(userDefinedModules(conf))
            .addAll(linkingContext(conf));

    Iterable<? extends Module> modules = modulesBuilder.build();

    //Check for missing endpoint when provider is azure
    if (properties.getProperty(Constants.PROPERTY_ENDPOINT) == null && ("azurecompute-arm".equals(provider))) {
        throw new IllegalArgumentException("Endpoint property cannot be null when provider is azure-arm");
    }

    Supplier<ComputeService> computeServiceSupplier = new ComputeServiceSupplier(conf, modules, properties);
    if (allowReuse) {
        return cachedComputeServices.computeIfAbsent(makeCacheKey(conf, properties), key -> computeServiceSupplier.get());
    }
    return computeServiceSupplier.get();
}
 
Example #24
Source File: CloudExplorerSupport.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
protected void doCall(ComputeService computeService, String indent) throws Exception {

    for (String instanceId : names) {
        NodeMetadata instance = computeService.getNodeMetadata(instanceId);
        if (instance == null) {
            stderr.println(indent+"Cannot terminate instance; could not find "+instanceId);
        } else {
            boolean confirmed = confirm(indent, "terminate "+instanceId+" ("+instance+")");
            if (confirmed) {
                computeService.destroyNode(instanceId);
            }
        }
    }
}
 
Example #25
Source File: EC2Iaas.java    From attic-stratos with Apache License 2.0 5 votes vote down vote up
@Override
public void buildComputeServiceAndTemplate() {
    // builds and sets Compute Service
    ComputeService computeService = ComputeServiceBuilderUtil.buildDefaultComputeService(getIaasProvider());
    getIaasProvider().setComputeService(computeService);

    // builds and sets Template
    buildTemplate();
}
 
Example #26
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, JcloudsMachineLocation machine) {
    if (computeService instanceof EC2ComputeService) {
        AWSEC2Api ec2Client = computeService.getContext().unwrapApi(AWSEC2Api.class);
        ElasticBlockStoreApi ebsClient = ec2Client.getElasticBlockStoreApi().get();
        ebsClient.attachVolumeInRegion(region, volumeId, machine.getJcloudsId(), ec2DeviceName);
        mountFilesystem((JcloudsSshMachineLocation) machine);
    } else {
        LOG.debug("Skipping configuration of non-EC2 ComputeService {}", computeService);
    }
}
 
Example #27
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, JcloudsMachineLocation machine) {
    if (computeService instanceof EC2ComputeService) {
        mountFilesystem((JcloudsSshMachineLocation) machine);
    } else {
        LOG.debug("Skipping configuration of non-EC2 ComputeService {}", computeService);
    }
}
 
Example #28
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).mapEBSSnapshotToDeviceName(ec2DeviceName, snapshotId, sizeInGib, deleteOnTermination);
    } else {
        LOG.debug("Skipping configuration of non-EC2 TemplateOptions {}", templateOptions);
    }
}
 
Example #29
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, JcloudsMachineLocation machine) {
    if (computeService instanceof EC2ComputeService) {
        createFilesystem((JcloudsSshMachineLocation) machine, filesystemType);
        mountFilesystem((JcloudsSshMachineLocation) machine);
    } else {
        LOG.debug("Skipping configuration of non-EC2 ComputeService {}", computeService);
    }
}
 
Example #30
Source File: JcloudsIaasUtil.java    From attic-stratos with Apache License 2.0 5 votes vote down vote up
private static void buildDefaultComputeService(IaasProvider iaasProvider) throws InvalidIaasProviderException {
    try {
        ComputeService computeService = ComputeServiceBuilderUtil.buildDefaultComputeService(iaasProvider);
        iaasProvider.setComputeService(computeService);
    } catch (Exception e) {
        String msg = "Unable to build the jclouds object for iaas of type: " + iaasProvider.getType();
        log.error(msg, e);
        throw new InvalidIaasProviderException(msg, e);
    }
}