List of usage examples for com.google.common.util.concurrent Atomics newReference
public static <V> AtomicReference<V> newReference(@Nullable V initialValue)
From source file:org.jclouds.ec2.compute.extensions.EC2ImageExtension.java
@Override public ListenableFuture<Image> createImage(ImageTemplate template) { checkState(template instanceof CloneImageTemplate, " ec2 only supports creating images through cloning."); CloneImageTemplate cloneTemplate = (CloneImageTemplate) template; String[] parts = AWSUtils.parseHandle(cloneTemplate.getSourceNodeId()); String region = parts[0];//from w w w .j av a 2 s. co m String instanceId = parts[1]; String imageId = ec2Api.getAMIApi().get().createImageInRegion(region, cloneTemplate.getName(), instanceId, CreateImageOptions.NONE); final AtomicReference<Image> image = Atomics .newReference(new ImageBuilder().location(find(locations.get(), idEquals(region))) .id(region + "/" + imageId).providerId(imageId).description(cloneTemplate.getName()) .operatingSystem(OperatingSystem.builder().description(cloneTemplate.getName()).build()) .status(Image.Status.PENDING).build()); return userExecutor.submit(new Callable<Image>() { @Override public Image call() throws Exception { if (imageAvailablePredicate.apply(image)) return image.get(); // TODO: get rid of the expectation that the image will be available, as it is very brittle throw new UncheckedTimeoutException("Image was not created within the time limit: " + image.get()); } }); }
From source file:org.jclouds.googlecomputeengine.compute.functions.ResetWindowsPassword.java
@Override public String apply(Map<String, ?> params) { String zone = (String) params.get("zone"); final AtomicReference<Instance> instance = (AtomicReference<Instance>) params.get("instance"); String userName = (String) params.get("userName"); String email = (String) params.get("email"); // Generate the public/private key pair for encryption and decryption. // TODO do we need to explicitly set 2048 bits? Presumably "RSA" is implicit KeyPair keys = crypto.rsaKeyPairGenerator().genKeyPair(); // Update instance's metadata with new "windows-keys" entry, and wait for operation to // complete.//from w ww. j a va 2 s.c o m logger.debug("Generating windows key for instance %s, by updating metadata", instance.get().name()); final InstanceApi instanceApi = api.instancesInZone(zone); Metadata metadata = instance.get().metadata(); try { // If disableHtmlEscaping is not there, == will be escaped from modulus value metadata.put("windows-keys", new GsonBuilder().disableHtmlEscaping().create() .toJson(extractKeyMetadata(keys, userName, email))); } catch (NoSuchAlgorithmException e) { Throwables.propagate(e); } catch (InvalidKeySpecException e) { Throwables.propagate(e); } AtomicReference<Operation> operation = Atomics .newReference(instanceApi.setMetadata(instance.get().name(), metadata)); operationDone.apply(operation); if (operation.get().httpErrorStatusCode() != null) { logger.warn("Generating windows key for %s failed. Http Error Code: %d HttpError: %s", operation.get().targetId(), operation.get().httpErrorStatusCode(), operation.get().httpErrorMessage()); } try { final Map<String, String> passwordDict = new HashMap<String, String>(); boolean passwordRetrieved = Predicates2.retry(new Predicate<Instance>() { public boolean apply(Instance instance) { String serialPortContents = instanceApi.getSerialPortOutput(instance.name(), 4).contents(); if (!serialPortContents.startsWith("{\"ready\":true")) { return false; } String[] contentEntries = serialPortContents.split("\n"); passwordDict.clear(); passwordDict.putAll(new Gson().fromJson(contentEntries[contentEntries.length - 1], Map.class)); passwordDict.put("passwordDictContentEntries", contentEntries[contentEntries.length - 1]); return passwordDict.get("encryptedPassword") != null; } }, 10 * 60, 30, TimeUnit.SECONDS).apply(instance.get()); // Notice that timeoutDuration should be less than EXPIRE_DURATION if (passwordRetrieved) { return decryptPassword( checkNotNull(passwordDict.get("encryptedPassword"), "encryptedPassword shouldn't be null"), keys); } else { throw new IllegalStateException( "encryptedPassword shouldn't be null: " + passwordDict.get("passwordDictContentEntries")); } } catch (Exception e) { throw Throwables.propagate(e); } }
From source file:org.jclouds.cloudstack.compute.extensions.CloudStackImageExtension.java
@Override public ListenableFuture<Image> createImage(ImageTemplate template) { checkState(template instanceof CloneImageTemplate, " cloudstack only currently supports creating images through cloning."); CloneImageTemplate cloneTemplate = (CloneImageTemplate) template; VirtualMachine vm = client.getVirtualMachineApi().getVirtualMachine(cloneTemplate.getSourceNodeId()); String stopJob = client.getVirtualMachineApi().stopVirtualMachine(vm.getId()); jobComplete.apply(stopJob);// w w w . j av a 2 s .c om Set<Volume> volumes = client.getVolumeApi() .listVolumes(ListVolumesOptions.Builder.virtualMachineId(vm.getId())); Volume volume = Iterables.getOnlyElement(volumes); CreateTemplateOptions options = CreateTemplateOptions.Builder.volumeId(volume.getId()); AsyncCreateResponse templateJob = client.getTemplateApi() .createTemplate(TemplateMetadata.builder().name(cloneTemplate.getName()).osTypeId(vm.getGuestOSId()) .displayText(cloneTemplate.getName()).build(), options); Template newTemplate = blockUntilJobCompletesAndReturnResult.<Template>apply(templateJob); logger.info(">> Registered new template %s, waiting for it to become available.", newTemplate.getId()); final AtomicReference<Image> image = Atomics.newReference( new ImageBuilder().location(find(locations.get(), idEquals(vm.getZoneId()))).id(newTemplate.getId()) .providerId(newTemplate.getId()).description(cloneTemplate.getName()) .operatingSystem(OperatingSystem.builder().description(cloneTemplate.getName()).build()) .status(Image.Status.PENDING).build()); return userExecutor.submit(new Callable<Image>() { @Override public Image call() throws Exception { if (imageAvailablePredicate.apply(image)) return image.get(); // TODO: get rid of the expectation that the image will be available, as it is very brittle throw new UncheckedTimeoutException("Image was not created within the time limit: " + image.get()); } }); }
From source file:org.jclouds.googlecomputeengine.compute.extensions.GoogleComputeEngineSecurityGroupExtension.java
@Override public boolean removeSecurityGroup(String id) { checkNotNull(id, "id"); if (api.getNetworkApiForProject(userProject.get()).get(id) == null) { return false; }//ww w . ja v a 2 s .c o m ListOptions options = new ListOptions.Builder().filter("network eq .*/" + id); FluentIterable<Firewall> fws = api.getFirewallApiForProject(userProject.get()).list(options).concat(); for (Firewall fw : fws) { AtomicReference<Operation> operation = Atomics .newReference(api.getFirewallApiForProject(userProject.get()).delete(fw.getName())); retry(operationDonePredicate, operationCompleteCheckTimeout, operationCompleteCheckInterval, MILLISECONDS).apply(operation); checkState(!operation.get().getHttpError().isPresent(), "Could not delete firewall, operation failed" + operation); } AtomicReference<Operation> operation = Atomics .newReference(api.getNetworkApiForProject(userProject.get()).delete(id)); retry(operationDonePredicate, operationCompleteCheckTimeout, operationCompleteCheckInterval, MILLISECONDS) .apply(operation); checkState(!operation.get().getHttpError().isPresent(), "Could not create network, operation failed" + operation); return true; }
From source file:org.jclouds.googlecomputeengine.compute.GoogleComputeEngineServiceAdapter.java
@Override public NodeAndInitialCredentials<Instance> createNodeWithGroupEncodedIntoName(String group, String name, Template template) {//ww w . ja v a 2 s . c o m GoogleComputeEngineTemplateOptions options = GoogleComputeEngineTemplateOptions.class .cast(template.getOptions()); checkNotNull(options.getNetworks(), "template options must specify a network"); checkNotNull(template.getHardware().getUri(), "hardware must have a URI"); checkNotNull(template.getImage().getUri(), "image URI is null"); String zone = template.getLocation().getId(); List<AttachDisk> disks = Lists.newArrayList(); disks.add(AttachDisk.newBootDisk(template.getImage().getUri(), getDiskTypeArgument(options, zone))); Iterator<String> networks = options.getNetworks().iterator(); URI network = URI.create(networks.next()); assert !networks.hasNext() : "Error: Options should specify only one network"; Scheduling scheduling = getScheduling(options); NewInstance newInstance = new NewInstance.Builder(name, template.getHardware().getUri(), // machineType network, disks).description(group).tags(Tags.create(null, ImmutableList.copyOf(options.getTags()))) .serviceAccounts(options.serviceAccounts()).scheduling(scheduling).build(); // Add metadata from template and for ssh key and image id newInstance.metadata().putAll(options.getUserMetadata()); LoginCredentials credentials = resolveNodeCredentials(template); if (options.getPublicKey() != null) { newInstance.metadata().put("sshKeys", format("%s:%s %s@localhost", credentials.getUser(), options.getPublicKey(), credentials.getUser())); } InstanceApi instanceApi = api.instancesInZone(zone); Operation create = instanceApi.create(newInstance); // We need to see the created instance so that we can access the newly created disk. AtomicReference<Instance> instance = Atomics.newReference(Instance.create( // "0000000000000000000", // id can't be null, but isn't available until provisioning is done. null, // creationTimestamp create.targetLink(), // selfLink newInstance.name(), // name newInstance.description(), // description newInstance.tags(), // tags newInstance.machineType(), // machineType Instance.Status.PROVISIONING, // status null, // statusMessage create.zone(), // zone null, // canIpForward null, // networkInterfaces null, // disks newInstance.metadata(), // metadata newInstance.serviceAccounts(), // serviceAccounts scheduling) // scheduling ); checkState(instanceVisible.apply(instance), "instance %s is not api visible!", instance.get()); // Add lookup for InstanceToNodeMetadata diskURIToImage.getUnchecked(instance.get().disks().get(0).source()); if ((options.autoCreateWindowsPassword() != null && options.autoCreateWindowsPassword()) || OsFamily.WINDOWS == template.getImage().getOperatingSystem().getFamily()) { Map<String, ?> params = ImmutableMap.of("instance", instance, "zone", zone, "email", create.user(), "userName", credentials.getUser()); String password = windowsPasswordGenerator.apply(params); credentials = LoginCredentials.builder(credentials).password(password).build(); } return new NodeAndInitialCredentials<Instance>(instance.get(), instance.get().selfLink().toString(), credentials); }
From source file:org.jclouds.joyent.cloudapi.v6_5.compute.JoyentCloudComputeServiceAdapter.java
@Override public void destroyNode(String id) { final AtomicReference<MachineInDatacenter> machine = Atomics.newReference(getNode(id)); if (machine.get() == null) return;//from w w w. j a va 2 s. com if (machine.get().get().getState() == State.RUNNING) { logger.debug(">> stopping machine(%s) current state(%s)", machine.get().getId(), machine.get().get().getState()); cloudApiApi.getMachineApiForDatacenter(machine.get().getDatacenter()).stop(machine.get().getId()); } checkState(retry(new Predicate<String>() { public boolean apply(String id) { machine.set(getNode(id)); return machine == null || machine.get().get().getState() != State.RUNNING; } }, timeouts.nodeSuspended).apply(id), "<< unable to stop machine(%s) current state(%s)", machine.get().getId(), machine.get().get().getState()); logger.debug(">> deleting machine(%s) current state(%s)", machine.get().getId(), machine.get().get().getState()); cloudApiApi.getMachineApiForDatacenter(machine.get().getDatacenter()).delete(machine.get().getId()); }
From source file:org.jclouds.googlecomputeengine.compute.GoogleComputeEngineService.java
private void cleanUpFirewallsForGroup(final String groupName) { GroupNamingConvention namingScheme = namingConvention.create(); FirewallApi firewallApi = api.firewalls(); for (Firewall firewall : concat(firewallApi.list())) { String foundGroup = namingScheme.groupInUniqueNameOrNull(firewall.name()); if ((foundGroup != null) && foundGroup.equals(groupName)) { AtomicReference<Operation> operation = Atomics.newReference(firewallApi.delete(firewall.name())); operationDone.apply(operation); if (operation.get().httpErrorStatusCode() != null) { logger.warn("delete orphaned firewall %s failed. Http Error Code: %d HttpError: %s", operation.get().targetId(), operation.get().httpErrorStatusCode(), operation.get().httpErrorMessage()); }//from www . j a v a 2 s .com } } }
From source file:org.jclouds.googlecomputeengine.compute.strategy.CreateNodesWithGroupEncodedIntoNameThenAddToSet.java
/** * Ensures that a firewall exists for every inbound port that the instance * requests./*from w w w.jav a 2s . c om*/ * <p> * For each port, there must be a firewall with a name following the * {@link FirewallTagNamingConvention}, with a target tag also following the * {@link FirewallTagNamingConvention}, which opens the requested port for * all sources on both TCP and UDP protocols. * * @see org.jclouds.googlecomputeengine.features.FirewallApi#patch(String, * org.jclouds.googlecomputeengine.options.FirewallOptions) */ private void getOrCreateFirewalls(GoogleComputeEngineTemplateOptions templateOptions, Network network, FirewallTagNamingConvention naming) { Set<String> tags = Sets.newLinkedHashSet(templateOptions.getTags()); FirewallApi firewallApi = api.firewalls(); if (!templateOptions.getGroups().isEmpty()) { for (String firewallName : templateOptions.getGroups()) { Firewall firewall = firewallApi.get(firewallName); validateFirewall(firewall, network); if (!firewall.targetTags().isEmpty()) { // Add tags coming from firewalls tags.addAll(firewall.targetTags()); } } } int[] inboundPorts = templateOptions.getInboundPorts(); if ((inboundPorts == null) || inboundPorts.length == 0) { return; } List<String> ports = simplifyPorts(inboundPorts); String name = naming.name(ports); Firewall firewall = firewallApi.get(name); AtomicReference<Operation> operation = null; if (firewall == null) { List<Rule> rules = ImmutableList.of(Rule.create("tcp", ports), Rule.create("udp", ports)); FirewallOptions firewallOptions = new FirewallOptions().name(name).network(network.selfLink()) .allowedRules(rules).sourceTags(templateOptions.getTags()) .sourceRanges(of(DEFAULT_INTERNAL_NETWORK_RANGE, EXTERIOR_RANGE)) .targetTags(ImmutableList.of(name)); operation = Atomics.newReference( firewallApi.createInNetwork(firewallOptions.name(), network.selfLink(), firewallOptions)); operationDone.apply(operation); checkState(operation.get().httpErrorStatusCode() == null, "Could not insert firewall, operation failed %s", operation); // Add tags for firewalls tags.add(name); } templateOptions.tags(tags); }
From source file:org.jclouds.googlecomputeengine.compute.extensions.GoogleComputeEngineSecurityGroupExtension.java
@Override public SecurityGroup addIpPermission(IpPermission ipPermission, SecurityGroup group) { checkNotNull(group, "group"); checkNotNull(ipPermission, "ipPermission"); checkNotNull(api.getNetworkApiForProject(userProject.get()).get(group.getId()) == null, "network for group is null"); ListOptions options = new ListOptions.Builder().filter("network eq .*/" + group.getName()); if (api.getFirewallApiForProject(userProject.get()).list(options).concat() .anyMatch(providesIpPermission(ipPermission))) { // Permission already exists. return group; }/*from w w w.j av a 2 s .c o m*/ FirewallOptions fwOptions = new FirewallOptions(); String uniqueFwName = namingConvention.createWithoutPrefix().uniqueNameForGroup(group.getName()); fwOptions.name(uniqueFwName); fwOptions.network(group.getUri()); if (!ipPermission.getGroupIds().isEmpty()) { fwOptions.sourceTags(ipPermission.getGroupIds()); } if (!ipPermission.getCidrBlocks().isEmpty()) { fwOptions.sourceRanges(ipPermission.getCidrBlocks()); } Firewall.Rule.Builder ruleBuilder = Firewall.Rule.builder(); ruleBuilder.IpProtocol(ipPermission.getIpProtocol()); if (ipPermission.getFromPort() > 0) { if (ipPermission.getFromPort() == ipPermission.getToPort()) { ruleBuilder.addPort(ipPermission.getToPort()); } else { ruleBuilder.addPortRange(ipPermission.getFromPort(), ipPermission.getToPort()); } } fwOptions.addAllowedRule(ruleBuilder.build()); AtomicReference<Operation> operation = Atomics.newReference(api.getFirewallApiForProject(userProject.get()) .createInNetwork(uniqueFwName, group.getUri(), fwOptions)); retry(operationDonePredicate, operationCompleteCheckTimeout, operationCompleteCheckInterval, MILLISECONDS) .apply(operation); checkState(!operation.get().getHttpError().isPresent(), "Could not create firewall, operation failed" + operation); return getSecurityGroupById(group.getId()); }
From source file:org.jclouds.googlecomputeengine.compute.extensions.GoogleComputeEngineSecurityGroupExtension.java
@Override public SecurityGroup removeIpPermission(IpPermission ipPermission, SecurityGroup group) { checkNotNull(group, "group"); checkNotNull(ipPermission, "ipPermission"); checkNotNull(api.getNetworkApiForProject(userProject.get()).get(group.getId()) == null, "network for group is null"); ListOptions options = new ListOptions.Builder().filter("network eq .*/" + group.getName()); FluentIterable<Firewall> fws = api.getFirewallApiForProject(userProject.get()).list(options).concat(); for (Firewall fw : fws) { if (equalsIpPermission(ipPermission).apply(fw)) { AtomicReference<Operation> operation = Atomics .newReference(api.getFirewallApiForProject(userProject.get()).delete(fw.getName())); retry(operationDonePredicate, operationCompleteCheckTimeout, operationCompleteCheckInterval, MILLISECONDS).apply(operation); checkState(!operation.get().getHttpError().isPresent(), "Could not delete firewall, operation failed" + operation); }/*from w w w. ja v a2s.c om*/ } return getSecurityGroupById(group.getId()); }