use of org.jclouds.predicates.RetryablePredicate in project legacy-jclouds-examples by jclouds.
the class WindowsInstanceStarter method run.
public void run() {
final String region = arguments.getRegion();
// Build a template
Template template = computeService.templateBuilder().locationId(region).imageNameMatches(arguments.getImageNamePattern()).hardwareId(arguments.getInstanceType()).build();
logger.info("Selected AMI is: %s", template.getImage().toString());
template.getOptions().inboundPorts(3389);
// Create the node
logger.info("Creating node and waiting for it to become available");
Set<? extends NodeMetadata> nodes = null;
try {
nodes = computeService.createNodesInGroup("basic-ami", 1, template);
} catch (RunNodesException e) {
logger.error(e, "Unable to start nodes; aborting");
return;
}
NodeMetadata node = Iterables.getOnlyElement(nodes);
// Wait for the administrator password
logger.info("Waiting for administrator password to become available");
// This predicate will call EC2's API to get the Windows Administrator
// password, and returns true if there is password data available.
Predicate<String> passwordReady = new Predicate<String>() {
@Override
public boolean apply(@Nullable String s) {
if (Strings.isNullOrEmpty(s))
return false;
PasswordData data = ec2Client.getWindowsServices().getPasswordDataInRegion(region, s);
if (data == null)
return false;
return !Strings.isNullOrEmpty(data.getPasswordData());
}
};
// Now wait, using RetryablePredicate
final int maxWait = 600;
final int period = 10;
final TimeUnit timeUnit = TimeUnit.SECONDS;
RetryablePredicate<String> passwordReadyRetryable = new RetryablePredicate<String>(passwordReady, maxWait, period, timeUnit);
boolean isPasswordReady = passwordReadyRetryable.apply(node.getProviderId());
if (!isPasswordReady) {
logger.error("Password is not ready after %s %s - aborting and shutting down node", maxWait, timeUnit.toString());
computeService.destroyNode(node.getId());
return;
}
// Now we can get the password data, decrypt it, and get a LoginCredentials instance
PasswordDataAndPrivateKey dataAndKey = new PasswordDataAndPrivateKey(ec2Client.getWindowsServices().getPasswordDataInRegion(region, node.getProviderId()), node.getCredentials().getPrivateKey());
WindowsLoginCredentialsFromEncryptedData f = context.getUtils().getInjector().getInstance(WindowsLoginCredentialsFromEncryptedData.class);
LoginCredentials credentials = f.apply(dataAndKey);
// Send to the log the details you need to log in to the instance with RDP
String publicIp = Iterables.getFirst(node.getPublicAddresses(), null);
logger.info("IP address: %s", publicIp);
logger.info("Login name: %s", credentials.getUser());
logger.info("Password: %s", credentials.getPassword());
// Wait for Enter on the console
logger.info("Hit Enter to shut down the node.");
InputStreamReader converter = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(converter);
try {
in.readLine();
} catch (IOException e) {
logger.error(e, "IOException while reading console input");
}
// Tidy up
logger.info("Shutting down");
computeService.destroyNode(node.getId());
}
use of org.jclouds.predicates.RetryablePredicate in project legacy-jclouds-examples by jclouds.
the class MainApp method main.
public static void main(String[] args) {
if (args.length < PARAMETERS)
throw new IllegalArgumentException(INVALID_SYNTAX);
// Args
String accesskeyid = args[0];
String secretkey = args[1];
String group = args[2];
String command = args[3];
// Init
ComputeService compute = new ComputeServiceContextFactory().createContext("aws-ec2", accesskeyid, secretkey).getComputeService();
// wait up to 60 seconds for ssh to be accessible
RetryablePredicate<IPSocket> socketTester = new RetryablePredicate<IPSocket>(new InetSocketAddressConnect(), 60, 1, 1, TimeUnit.SECONDS);
try {
if (command.equals("create")) {
Template template = compute.templateBuilder().build();
template.getOptions().as(AWSEC2TemplateOptions.class).spotPrice(0.03f).authorizePublicKey(Files.toString(new File(System.getProperty("user.home") + "/.ssh/id_rsa.pub"), Charsets.UTF_8));
System.out.printf(">> running one spot node type(%s) with ami(%s) in group(%s)%n", template.getHardware().getProviderId(), template.getImage().getId(), group);
// run only a single node
NodeMetadata node = Iterables.getOnlyElement(compute.createNodesInGroup(group, 1, template));
System.out.printf("<< running node(%s)%n", node.getId());
IPSocket socket = new IPSocket(Iterables.get(node.getPublicAddresses(), 0), node.getLoginPort());
if (socketTester.apply(socket)) {
System.out.printf("<< socket ready [%s] node(%s)%n", socket, node.getId());
System.out.printf("ssh to node with the following command:%n ssh %s@%s%n", node.getCredentials().identity, socket.getAddress());
System.exit(0);
} else {
System.out.printf("<< socket not ready [%s] node(%s)%n", socket, node.getId());
}
} else if (command.equals("destroy")) {
System.out.printf(">> destroying nodes in group(%s)%n", group);
Set<? extends NodeMetadata> destroyed = compute.destroyNodesMatching(NodePredicates.inGroup(group));
System.out.printf("<< destroyed(%d)%n", destroyed.size());
System.exit(0);
} else {
System.err.println(INVALID_SYNTAX);
System.exit(1);
}
} catch (RunNodesException e) {
System.err.println(e.getMessage());
for (NodeMetadata node : e.getNodeErrors().keySet()) compute.destroyNode(node.getId());
System.exit(1);
} catch (IOException e) {
System.err.println(e.getMessage());
System.exit(1);
} finally {
compute.getContext().close();
}
}
use of org.jclouds.predicates.RetryablePredicate in project legacy-jclouds-examples by jclouds.
the class MainApp method blockUntilInstanceRunning.
static RunningInstance blockUntilInstanceRunning(EC2Client client, RunningInstance instance) throws TimeoutException {
// create utilities that wait for the instance to finish
RetryablePredicate<RunningInstance> runningTester = new RetryablePredicate<RunningInstance>(new InstanceStateRunning(client), 180, 5, TimeUnit.SECONDS);
System.out.printf("%d: %s awaiting instance to run %n", System.currentTimeMillis(), instance.getId());
if (!runningTester.apply(instance))
throw new TimeoutException("timeout waiting for instance to run: " + instance.getId());
instance = findInstanceById(client, instance.getId());
RetryablePredicate<HostAndPort> socketTester = new RetryablePredicate<HostAndPort>(new InetSocketAddressConnect(), 300, 1, TimeUnit.SECONDS);
System.out.printf("%d: %s awaiting ssh service to start%n", System.currentTimeMillis(), instance.getIpAddress());
if (!socketTester.apply(HostAndPort.fromParts(instance.getIpAddress(), 22)))
throw new TimeoutException("timeout waiting for ssh to start: " + instance.getIpAddress());
System.out.printf("%d: %s ssh service started%n", System.currentTimeMillis(), instance.getIpAddress());
System.out.printf("%d: %s awaiting http service to start%n", System.currentTimeMillis(), instance.getIpAddress());
if (!socketTester.apply(HostAndPort.fromParts(instance.getIpAddress(), 80)))
throw new TimeoutException("timeout waiting for http to start: " + instance.getIpAddress());
System.out.printf("%d: %s http service started%n", System.currentTimeMillis(), instance.getIpAddress());
return instance;
}
Aggregations