From 550384bd222ff661dd207f29082083a21a28978c Mon Sep 17 00:00:00 2001 From: Andrew Phillips Date: Fri, 19 Mar 2010 09:02:17 +0100 Subject: [PATCH] Line ending changes and POM formatting. --- .../classes/archetype-resources/pom.xml | 158 ++--- .../aws/ec2/compute/EC2ComputeService.java | 248 ++++---- aws/demos/speedtest-sqs/pom.xml | 4 +- .../org/jclouds/compute/ComputeService.java | 310 +++++----- pom.xml | 6 +- .../ant/taskdefs/compute/ComputeTask.java | 552 +++++++++--------- .../compute/BaseVCloudComputeClient.java | 402 ++++++------- 7 files changed, 840 insertions(+), 840 deletions(-) diff --git a/archetypes/json-client-archetype/target/classes/archetype-resources/pom.xml b/archetypes/json-client-archetype/target/classes/archetype-resources/pom.xml index 5a39109e04..b4c1c6b367 100644 --- a/archetypes/json-client-archetype/target/classes/archetype-resources/pom.xml +++ b/archetypes/json-client-archetype/target/classes/archetype-resources/pom.xml @@ -1,79 +1,79 @@ -#set( $lcaseClientName = ${clientName.toLowerCase()} ) -#set( $symbol_dollar = '$' ) - - - - - org.jclouds - jclouds-project - 1.0-SNAPSHOT - ../project/pom.xml - - 4.0.0 - ${groupId} - jclouds-${artifactId} - jclouds ${clientName} core - jar - jclouds components to access ${clientName} - - - scm:svn:http://jclouds.googlecode.com/svn/trunk/${lcaseClientName} - scm:svn:https://jclouds.googlecode.com/svn/trunk/${lcaseClientName} - http://jclouds.googlecode.com/svn/trunk/${lcaseClientName} - - - ${clientUser} - ${clientPassword} - - - - ${symbol_dollar}{project.groupId} - jclouds-core - ${symbol_dollar}{project.version} - - - ${symbol_dollar}{project.groupId} - jclouds-core - ${symbol_dollar}{project.version} - test-jar - test - - - log4j - log4j - 1.2.14 - test - - - ${symbol_dollar}{project.groupId} - jclouds-log4j - ${symbol_dollar}{project.version} - test - - - +#set( $lcaseClientName = ${clientName.toLowerCase()} ) +#set( $symbol_dollar = '$' ) + + + + + org.jclouds + jclouds-project + 1.0-SNAPSHOT + ../project/pom.xml + + 4.0.0 + ${groupId} + jclouds-${artifactId} + jclouds ${clientName} core + jar + jclouds components to access ${clientName} + + + scm:svn:http://jclouds.googlecode.com/svn/trunk/${lcaseClientName} + scm:svn:https://jclouds.googlecode.com/svn/trunk/${lcaseClientName} + http://jclouds.googlecode.com/svn/trunk/${lcaseClientName} + + + ${clientUser} + ${clientPassword} + + + + ${symbol_dollar}{project.groupId} + jclouds-core + ${symbol_dollar}{project.version} + + + ${symbol_dollar}{project.groupId} + jclouds-core + ${symbol_dollar}{project.version} + test-jar + test + + + log4j + log4j + 1.2.14 + test + + + ${symbol_dollar}{project.groupId} + jclouds-log4j + ${symbol_dollar}{project.version} + test + + + diff --git a/aws/core/src/main/java/org/jclouds/aws/ec2/compute/EC2ComputeService.java b/aws/core/src/main/java/org/jclouds/aws/ec2/compute/EC2ComputeService.java index 5035a2d801..99f2b8f83b 100644 --- a/aws/core/src/main/java/org/jclouds/aws/ec2/compute/EC2ComputeService.java +++ b/aws/core/src/main/java/org/jclouds/aws/ec2/compute/EC2ComputeService.java @@ -1,125 +1,125 @@ -/** - * - * Copyright (C) 2009 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ -package org.jclouds.aws.ec2.compute; - -import java.util.Map; -import java.util.concurrent.ExecutorService; - -import javax.inject.Inject; -import javax.inject.Named; -import javax.inject.Provider; -import javax.inject.Singleton; - -import org.jclouds.Constants; -import org.jclouds.aws.domain.Region; -import org.jclouds.aws.ec2.EC2Client; -import org.jclouds.aws.ec2.compute.config.EC2ComputeServiceContextModule.GetRegionFromNodeOrDefault; -import org.jclouds.aws.ec2.compute.domain.KeyPairCredentials; -import org.jclouds.aws.ec2.compute.domain.PortsRegionTag; -import org.jclouds.aws.ec2.compute.domain.RegionTag; -import org.jclouds.aws.ec2.domain.RunningInstance; -import org.jclouds.compute.ComputeServiceContext; -import org.jclouds.compute.domain.Image; -import org.jclouds.compute.domain.NodeMetadata; -import org.jclouds.compute.domain.NodeState; -import org.jclouds.compute.domain.Size; -import org.jclouds.compute.domain.TemplateBuilder; -import org.jclouds.compute.internal.BaseComputeService; -import org.jclouds.compute.strategy.DestroyNodeStrategy; -import org.jclouds.compute.strategy.GetNodeMetadataStrategy; -import org.jclouds.compute.strategy.ListNodesStrategy; -import org.jclouds.compute.strategy.RebootNodeStrategy; -import org.jclouds.compute.strategy.RunNodesAndAddToSetStrategy; -import org.jclouds.compute.util.ComputeUtils; -import org.jclouds.domain.Location; - -import com.google.common.base.Predicate; -import com.google.common.collect.Iterables; - -/** - * @author Adrian Cole - */ -@Singleton -public class EC2ComputeService extends BaseComputeService { - protected final EC2Client ec2Client; - protected final GetRegionFromNodeOrDefault getRegionFromNodeOrDefault; - protected final Map credentialsMap; - protected final Map securityGroupMap; - protected final Predicate instanceStateTerminated; - - @Inject - protected EC2ComputeService(ComputeServiceContext context, - Provider> images, - Provider> sizes, - Provider> locations, - ListNodesStrategy listNodesStrategy, GetNodeMetadataStrategy getNodeMetadataStrategy, - RunNodesAndAddToSetStrategy runNodesAndAddToSetStrategy, - RebootNodeStrategy rebootNodeStrategy, DestroyNodeStrategy destroyNodeStrategy, - Provider templateBuilderProvider, ComputeUtils utils, - @Named(Constants.PROPERTY_USER_THREADS) ExecutorService executor, EC2Client ec2Client, - GetRegionFromNodeOrDefault getRegionFromNodeOrDefault, - Map credentialsMap, - Map securityGroupMap, - @Named("TERMINATED") Predicate instanceStateTerminated) { - super(context, images, sizes, locations, listNodesStrategy, getNodeMetadataStrategy, - runNodesAndAddToSetStrategy, rebootNodeStrategy, destroyNodeStrategy, - templateBuilderProvider, utils, executor); - this.ec2Client = ec2Client; - this.getRegionFromNodeOrDefault = getRegionFromNodeOrDefault; - this.credentialsMap = credentialsMap; - this.securityGroupMap = securityGroupMap; - this.instanceStateTerminated = instanceStateTerminated; - } - - private void deleteSecurityGroup(Region region, String tag) { - if (ec2Client.getSecurityGroupServices().describeSecurityGroupsInRegion(region, tag).size() > 0) { - logger.debug(">> deleting securityGroup(%s)", tag); - ec2Client.getSecurityGroupServices().deleteSecurityGroupInRegion(region, tag); - securityGroupMap.remove(new PortsRegionTag(region, tag, null)); // TODO: test this clear - // happens - logger.debug("<< deleted securityGroup(%s)", tag); - } - } - - private void deleteKeyPair(Region region, String tag) { - if (ec2Client.getKeyPairServices().describeKeyPairsInRegion(region, tag).size() > 0) { - logger.debug(">> deleting keyPair(%s)", tag); - ec2Client.getKeyPairServices().deleteKeyPairInRegion(region, tag); - credentialsMap.remove(new RegionTag(region, tag)); // TODO: test this clear happens - logger.debug("<< deleted keyPair(%s)", tag); - } - } - - @Override - public void destroyNodesWithTag(String tag) { - super.destroyNodesWithTag(tag); - Iterable nodes = Iterables.filter(getNodesWithTag(tag).values(), - new Predicate() { - @Override - public boolean apply(NodeMetadata input) { - return input.getState() == NodeState.TERMINATED; - } - }); - if (Iterables.size(nodes) > 0) { - Region region = getRegionFromNodeOrDefault.apply(Iterables.get(nodes, 0)); - deleteKeyPair(region, tag); - deleteSecurityGroup(region, tag); - } - } +/** + * + * Copyright (C) 2009 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ +package org.jclouds.aws.ec2.compute; + +import java.util.Map; +import java.util.concurrent.ExecutorService; + +import javax.inject.Inject; +import javax.inject.Named; +import javax.inject.Provider; +import javax.inject.Singleton; + +import org.jclouds.Constants; +import org.jclouds.aws.domain.Region; +import org.jclouds.aws.ec2.EC2Client; +import org.jclouds.aws.ec2.compute.config.EC2ComputeServiceContextModule.GetRegionFromNodeOrDefault; +import org.jclouds.aws.ec2.compute.domain.KeyPairCredentials; +import org.jclouds.aws.ec2.compute.domain.PortsRegionTag; +import org.jclouds.aws.ec2.compute.domain.RegionTag; +import org.jclouds.aws.ec2.domain.RunningInstance; +import org.jclouds.compute.ComputeServiceContext; +import org.jclouds.compute.domain.Image; +import org.jclouds.compute.domain.NodeMetadata; +import org.jclouds.compute.domain.NodeState; +import org.jclouds.compute.domain.Size; +import org.jclouds.compute.domain.TemplateBuilder; +import org.jclouds.compute.internal.BaseComputeService; +import org.jclouds.compute.strategy.DestroyNodeStrategy; +import org.jclouds.compute.strategy.GetNodeMetadataStrategy; +import org.jclouds.compute.strategy.ListNodesStrategy; +import org.jclouds.compute.strategy.RebootNodeStrategy; +import org.jclouds.compute.strategy.RunNodesAndAddToSetStrategy; +import org.jclouds.compute.util.ComputeUtils; +import org.jclouds.domain.Location; + +import com.google.common.base.Predicate; +import com.google.common.collect.Iterables; + +/** + * @author Adrian Cole + */ +@Singleton +public class EC2ComputeService extends BaseComputeService { + protected final EC2Client ec2Client; + protected final GetRegionFromNodeOrDefault getRegionFromNodeOrDefault; + protected final Map credentialsMap; + protected final Map securityGroupMap; + protected final Predicate instanceStateTerminated; + + @Inject + protected EC2ComputeService(ComputeServiceContext context, + Provider> images, + Provider> sizes, + Provider> locations, + ListNodesStrategy listNodesStrategy, GetNodeMetadataStrategy getNodeMetadataStrategy, + RunNodesAndAddToSetStrategy runNodesAndAddToSetStrategy, + RebootNodeStrategy rebootNodeStrategy, DestroyNodeStrategy destroyNodeStrategy, + Provider templateBuilderProvider, ComputeUtils utils, + @Named(Constants.PROPERTY_USER_THREADS) ExecutorService executor, EC2Client ec2Client, + GetRegionFromNodeOrDefault getRegionFromNodeOrDefault, + Map credentialsMap, + Map securityGroupMap, + @Named("TERMINATED") Predicate instanceStateTerminated) { + super(context, images, sizes, locations, listNodesStrategy, getNodeMetadataStrategy, + runNodesAndAddToSetStrategy, rebootNodeStrategy, destroyNodeStrategy, + templateBuilderProvider, utils, executor); + this.ec2Client = ec2Client; + this.getRegionFromNodeOrDefault = getRegionFromNodeOrDefault; + this.credentialsMap = credentialsMap; + this.securityGroupMap = securityGroupMap; + this.instanceStateTerminated = instanceStateTerminated; + } + + private void deleteSecurityGroup(Region region, String tag) { + if (ec2Client.getSecurityGroupServices().describeSecurityGroupsInRegion(region, tag).size() > 0) { + logger.debug(">> deleting securityGroup(%s)", tag); + ec2Client.getSecurityGroupServices().deleteSecurityGroupInRegion(region, tag); + securityGroupMap.remove(new PortsRegionTag(region, tag, null)); // TODO: test this clear + // happens + logger.debug("<< deleted securityGroup(%s)", tag); + } + } + + private void deleteKeyPair(Region region, String tag) { + if (ec2Client.getKeyPairServices().describeKeyPairsInRegion(region, tag).size() > 0) { + logger.debug(">> deleting keyPair(%s)", tag); + ec2Client.getKeyPairServices().deleteKeyPairInRegion(region, tag); + credentialsMap.remove(new RegionTag(region, tag)); // TODO: test this clear happens + logger.debug("<< deleted keyPair(%s)", tag); + } + } + + @Override + public void destroyNodesWithTag(String tag) { + super.destroyNodesWithTag(tag); + Iterable nodes = Iterables.filter(getNodesWithTag(tag).values(), + new Predicate() { + @Override + public boolean apply(NodeMetadata input) { + return input.getState() == NodeState.TERMINATED; + } + }); + if (Iterables.size(nodes) > 0) { + Region region = getRegionFromNodeOrDefault.apply(Iterables.get(nodes, 0)); + deleteKeyPair(region, tag); + deleteSecurityGroup(region, tag); + } + } } \ No newline at end of file diff --git a/aws/demos/speedtest-sqs/pom.xml b/aws/demos/speedtest-sqs/pom.xml index 6079a4f0ca..0392c060e7 100644 --- a/aws/demos/speedtest-sqs/pom.xml +++ b/aws/demos/speedtest-sqs/pom.xml @@ -28,8 +28,8 @@ 1.0-SNAPSHOT jclouds-speedtest-sqs - tests speed of sqs across regions - creates a queue in all amazon regions and then tests performance against it + Speed tests of SQS across regions + Creates a queue in all amazon regions and then tests performance against it ${project.groupId} diff --git a/compute/src/main/java/org/jclouds/compute/ComputeService.java b/compute/src/main/java/org/jclouds/compute/ComputeService.java index 7106d2a3a4..1503c43179 100644 --- a/compute/src/main/java/org/jclouds/compute/ComputeService.java +++ b/compute/src/main/java/org/jclouds/compute/ComputeService.java @@ -1,155 +1,155 @@ -/** - * - * Copyright (C) 2009 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ -package org.jclouds.compute; - -import java.util.Map; - -import org.jclouds.compute.domain.ComputeMetadata; -import org.jclouds.compute.domain.Image; -import org.jclouds.compute.domain.NodeMetadata; -import org.jclouds.compute.domain.Size; -import org.jclouds.compute.domain.Template; -import org.jclouds.compute.domain.TemplateBuilder; -import org.jclouds.compute.internal.BaseComputeService; -import org.jclouds.domain.Location; - -import com.google.inject.ImplementedBy; - -/** - * Provides portable access to launching compute instances. - * - * @author Adrian Cole - * @author Ivan Meredith - */ -@ImplementedBy(BaseComputeService.class) -public interface ComputeService { - - /** - * @return a reference to the context that created this ComputeService. - */ - ComputeServiceContext getContext(); - - /** - * Makes a new template builder for this service - */ - TemplateBuilder templateBuilder(); - - /** - * The get sizes command shows you the options including virtual cpu count, memory, and disks. - * cpu count is not a portable quantity across clouds, as they are measured differently. However, - * it is a good indicator of relative speed within a cloud. memory is measured in megabytes and - * disks in gigabytes. - * - * @return a map of sizes by ID, conceding that in some clouds the "id" is not used. - */ - Map getSizes(); - - /** - * Images define the operating system and metadata related to a node. In some clouds, Images are - * bound to a specific region, and their identifiers are different across these regions. For this - * reason, you should consider matching image requirements like operating system family with - * TemplateBuilder as opposed to choosing an image explicitly. The getImages() command returns a - * map of images by id. - */ - Map getImages(); - - /** - * all nodes available to the current user by id. If possible, the returned set will include - * {@link NodeMetadata} objects. - */ - Map getNodes(); - - /** - * The get locations command returns all the valid locations for nodes. A location has a scope, - * which is typically region or zone. A region is a general area, like eu-west, where a zone is - * similar to a datacenter. If a location has a parent, that implies it is within that location. - * For example a location can be a rack, whose parent is likely to be a zone. - */ - Map getLocations(); - - /** - * - * The compute api treats nodes as a group based on a tag you specify. Using this tag, you can - * choose to operate one or many nodes as a logical unit without regard to the implementation - * details of the cloud. - *

- * - * The set that is returned will include credentials you can use to ssh into the nodes. The "key" - * part of the credentials is either a password or a private key. You have to inspect the value - * to determine this. - * - *

-    * if (node.getCredentials().key.startsWith("-----BEGIN RSA PRIVATE KEY-----"))
-    *    // it is a private key, not a password.
-    * 
- * - *

- * Note. if all you want to do is execute a script at bootup, you should consider use of the - * runscript option. - *

- * If resources such as security groups are needed, they will be reused or created for you. - * Inbound port 22 will always be opened up. - * - * @param tag - * - common identifier to group nodes by, cannot contain hyphens - * @param count - * - how many to fire up. - * @param template - * - how to configure the nodes - * @return all of the nodes the api was able to launch in a running state. - */ - Map runNodesWithTag(String tag, int count, Template template); - - /** - * destroy the node. If it is the only node in a tag set, the dependent resources will also be - * destroyed. - */ - void destroyNode(ComputeMetadata node); - - /** - * nodes which are tagged are treated as a logical set. Using the delete command, you can save - * time by removing the nodes in parallel. When the last node in a set is destroyed, any indirect - * resources it uses, such as keypairs, are also destroyed. - */ - void destroyNodesWithTag(String tag); - - /** - * reboot the node. - */ - void rebootNode(ComputeMetadata node); - - /** - * nodes which are tagged are treated as a logical set. Using this command, you can save time by - * rebooting the nodes in parallel. - */ - void rebootNodesWithTag(String tag); - - /** - * Find a node by its id - */ - NodeMetadata getNodeMetadata(ComputeMetadata node); - - /** - * get all nodes matching the tag. - * - * @param tag - */ - Map getNodesWithTag(String tag); - -} +/** + * + * Copyright (C) 2009 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ +package org.jclouds.compute; + +import java.util.Map; + +import org.jclouds.compute.domain.ComputeMetadata; +import org.jclouds.compute.domain.Image; +import org.jclouds.compute.domain.NodeMetadata; +import org.jclouds.compute.domain.Size; +import org.jclouds.compute.domain.Template; +import org.jclouds.compute.domain.TemplateBuilder; +import org.jclouds.compute.internal.BaseComputeService; +import org.jclouds.domain.Location; + +import com.google.inject.ImplementedBy; + +/** + * Provides portable access to launching compute instances. + * + * @author Adrian Cole + * @author Ivan Meredith + */ +@ImplementedBy(BaseComputeService.class) +public interface ComputeService { + + /** + * @return a reference to the context that created this ComputeService. + */ + ComputeServiceContext getContext(); + + /** + * Makes a new template builder for this service + */ + TemplateBuilder templateBuilder(); + + /** + * The get sizes command shows you the options including virtual cpu count, memory, and disks. + * cpu count is not a portable quantity across clouds, as they are measured differently. However, + * it is a good indicator of relative speed within a cloud. memory is measured in megabytes and + * disks in gigabytes. + * + * @return a map of sizes by ID, conceding that in some clouds the "id" is not used. + */ + Map getSizes(); + + /** + * Images define the operating system and metadata related to a node. In some clouds, Images are + * bound to a specific region, and their identifiers are different across these regions. For this + * reason, you should consider matching image requirements like operating system family with + * TemplateBuilder as opposed to choosing an image explicitly. The getImages() command returns a + * map of images by id. + */ + Map getImages(); + + /** + * all nodes available to the current user by id. If possible, the returned set will include + * {@link NodeMetadata} objects. + */ + Map getNodes(); + + /** + * The get locations command returns all the valid locations for nodes. A location has a scope, + * which is typically region or zone. A region is a general area, like eu-west, where a zone is + * similar to a datacenter. If a location has a parent, that implies it is within that location. + * For example a location can be a rack, whose parent is likely to be a zone. + */ + Map getLocations(); + + /** + * + * The compute api treats nodes as a group based on a tag you specify. Using this tag, you can + * choose to operate one or many nodes as a logical unit without regard to the implementation + * details of the cloud. + *

+ * + * The set that is returned will include credentials you can use to ssh into the nodes. The "key" + * part of the credentials is either a password or a private key. You have to inspect the value + * to determine this. + * + *

+    * if (node.getCredentials().key.startsWith("-----BEGIN RSA PRIVATE KEY-----"))
+    *    // it is a private key, not a password.
+    * 
+ * + *

+ * Note. if all you want to do is execute a script at bootup, you should consider use of the + * runscript option. + *

+ * If resources such as security groups are needed, they will be reused or created for you. + * Inbound port 22 will always be opened up. + * + * @param tag + * - common identifier to group nodes by, cannot contain hyphens + * @param count + * - how many to fire up. + * @param template + * - how to configure the nodes + * @return all of the nodes the api was able to launch in a running state. + */ + Map runNodesWithTag(String tag, int count, Template template); + + /** + * destroy the node. If it is the only node in a tag set, the dependent resources will also be + * destroyed. + */ + void destroyNode(ComputeMetadata node); + + /** + * nodes which are tagged are treated as a logical set. Using the delete command, you can save + * time by removing the nodes in parallel. When the last node in a set is destroyed, any indirect + * resources it uses, such as keypairs, are also destroyed. + */ + void destroyNodesWithTag(String tag); + + /** + * reboot the node. + */ + void rebootNode(ComputeMetadata node); + + /** + * nodes which are tagged are treated as a logical set. Using this command, you can save time by + * rebooting the nodes in parallel. + */ + void rebootNodesWithTag(String tag); + + /** + * Find a node by its id + */ + NodeMetadata getNodeMetadata(ComputeMetadata node); + + /** + * get all nodes matching the tag. + * + * @param tag + */ + Map getNodesWithTag(String tag); + +} diff --git a/pom.xml b/pom.xml index 10496d33ad..e580f1e186 100644 --- a/pom.xml +++ b/pom.xml @@ -21,8 +21,8 @@ --> 4.0.0 - jclouds-project org.jclouds + jclouds-project 1.0-SNAPSHOT project/pom.xml @@ -49,8 +49,8 @@ rimuhosting twitter vcloud - gogrid - + gogrid + diff --git a/tools/antcontrib/src/main/java/org/jclouds/tools/ant/taskdefs/compute/ComputeTask.java b/tools/antcontrib/src/main/java/org/jclouds/tools/ant/taskdefs/compute/ComputeTask.java index 1b4077f54f..0b9038d494 100644 --- a/tools/antcontrib/src/main/java/org/jclouds/tools/ant/taskdefs/compute/ComputeTask.java +++ b/tools/antcontrib/src/main/java/org/jclouds/tools/ant/taskdefs/compute/ComputeTask.java @@ -1,276 +1,276 @@ -/** - * - * Copyright (C) 2009 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ -package org.jclouds.tools.ant.taskdefs.compute; - -import static org.jclouds.compute.util.ComputeUtils.isKeyAuth; -import static org.jclouds.tools.ant.taskdefs.compute.ComputeTaskUtils.buildComputeMap; -import static org.jclouds.tools.ant.taskdefs.compute.ComputeTaskUtils.createTemplateFromElement; -import static org.jclouds.tools.ant.taskdefs.compute.ComputeTaskUtils.ipOrEmptyString; - -import java.io.IOException; -import java.net.URI; -import java.util.Map; - -import javax.annotation.Nullable; - -import org.apache.tools.ant.BuildException; -import org.apache.tools.ant.Project; -import org.apache.tools.ant.Task; -import org.jclouds.compute.ComputeService; -import org.jclouds.compute.ComputeServiceContext; -import org.jclouds.compute.domain.ComputeMetadata; -import org.jclouds.compute.domain.Image; -import org.jclouds.compute.domain.NodeMetadata; -import org.jclouds.compute.domain.Size; -import org.jclouds.compute.domain.Template; -import org.jclouds.domain.Location; -import org.jclouds.http.HttpUtils; - -import com.google.common.base.CaseFormat; -import com.google.common.base.Splitter; -import com.google.inject.Provider; - -/** - * @author Adrian Cole - * @author Ivan Meredith - */ -public class ComputeTask extends Task { - - private final Map computeMap; - private String provider; - private String actions; - private NodeElement nodeElement; - - /** - * we don't have a reference to the project during the constructor, so we need to defer expansion - * with a Provider. - */ - private final Provider projectProvider = new Provider() { - @Override - public Project get() { - return getProject(); - } - }; - - public ComputeTask(@Nullable Map computeMap) { - this.computeMap = computeMap != null ? computeMap : buildComputeMap(projectProvider); - } - - public ComputeTask() throws IOException { - this(null); - } - - public static enum Action { - CREATE, GET, LIST, LIST_DETAILS, DESTROY, LIST_IMAGES, LIST_SIZES, LIST_LOCATIONS - } - - /** - * makes a connection to the compute service and invokes - */ - public void execute() throws BuildException { - ComputeServiceContext context = computeMap.get(HttpUtils.createUri(provider)); - - try { - for (String action : Splitter.on(',').split(actions)) { - Action act = Action.valueOf(CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_UNDERSCORE, - action)); - invokeActionOnService(act, context.getComputeService()); - } - } finally { - context.close(); - } - } - - private void invokeActionOnService(Action action, ComputeService computeService) { - switch (action) { - case CREATE: - case GET: - case DESTROY: - if (nodeElement != null) { - switch (action) { - case CREATE: - create(computeService); - break; - case GET: - get(computeService); - break; - case DESTROY: - destroy(computeService); - break; - } - } else { - this.log("missing node element for action: " + action, Project.MSG_ERR); - } - break; - case LIST: - list(computeService); - break; - case LIST_DETAILS: - listDetails(computeService); - break; - case LIST_IMAGES: - listImages(computeService); - break; - case LIST_SIZES: - listSizes(computeService); - break; - case LIST_LOCATIONS: - listLocations(computeService); - break; - default: - this.log("bad action: " + action, Project.MSG_ERR); - } - } - - private void listDetails(ComputeService computeService) { - log("list details"); - for (ComputeMetadata node : computeService.getNodes().values()) {// TODO - // parallel - logDetails(computeService, node); - } - } - - private void listImages(ComputeService computeService) { - log("list images"); - for (Image image : computeService.getImages().values()) {// TODO - log(String - .format( - " image location=%s, id=%s, name=%s, version=%s, arch=%s, osfam=%s, osdesc=%s, desc=%s", - image.getLocationId(), image.getId(), image.getName(), image - .getVersion(), image.getArchitecture(), image.getOsFamily(), - image.getOsDescription(), image.getDescription())); - } - } - - private void listSizes(ComputeService computeService) { - log("list sizes"); - for (Size size : computeService.getSizes().values()) {// TODO - log(String.format(" size id=%s, cores=%s, ram=%s, disk=%s", size.getId(), size - .getCores(), size.getRam(), size.getDisk())); - } - } - - private void listLocations(ComputeService computeService) { - log("list locations"); - for (Location location : computeService.getLocations().values()) {// TODO - log(String.format(" location id=%s, scope=%s, description=%s, parent=%s, assignable=%s", - location.getId(), location.getScope(), location.getDescription(), location - .getParent(), location.isAssignable())); - } - } - - private void list(ComputeService computeService) { - log("list"); - for (ComputeMetadata node : computeService.getNodes().values()) { - log(String.format(" location=%s, id=%s, tag=%s", node.getLocationId(), node.getId(), - node.getName())); - } - } - - private void create(ComputeService computeService) { - String tag = nodeElement.getTag(); - - log(String.format("create tag: %s, count: %d, size: %s, os: %s", tag, nodeElement.getCount(), - nodeElement.getSize(), nodeElement.getOs())); - - Template template = createTemplateFromElement(nodeElement, computeService); - - for (NodeMetadata createdNode : computeService.runNodesWithTag(tag, nodeElement.getCount(), - template).values()) { - logDetails(computeService, createdNode); - addNodeDetailsAsProjectProperties(createdNode); - } - } - - private void addNodeDetailsAsProjectProperties(NodeMetadata createdNode) { - if (nodeElement.getIdproperty() != null) - getProject().setProperty(nodeElement.getIdproperty(), createdNode.getId()); - if (nodeElement.getHostproperty() != null) - getProject().setProperty(nodeElement.getHostproperty(), - ipOrEmptyString(createdNode.getPublicAddresses())); - if (nodeElement.getPasswordproperty() != null && !isKeyAuth(createdNode)) - getProject().setProperty(nodeElement.getPasswordproperty(), - createdNode.getCredentials().key); - if (nodeElement.getUsernameproperty() != null) - getProject().setProperty(nodeElement.getUsernameproperty(), - createdNode.getCredentials().account); - } - - private void destroy(ComputeService computeService) { - log(String.format("destroy tag: %s", nodeElement.getTag())); - computeService.destroyNodesWithTag(nodeElement.getTag()); - } - - private void get(ComputeService computeService) { - log(String.format("get tag: %s", nodeElement.getTag())); - for (ComputeMetadata node : computeService.getNodesWithTag(nodeElement.getTag()).values()) { - logDetails(computeService, node); - } - } - - private void logDetails(ComputeService computeService, ComputeMetadata node) { - NodeMetadata metadata = node instanceof NodeMetadata ? NodeMetadata.class.cast(node) - : computeService.getNodeMetadata(node); - log(String - .format( - " node id=%s, name=%s, tag=%s, location=%s, state=%s, publicIp=%s, privateIp=%s, extra=%s", - metadata.getId(), metadata.getName(), metadata.getTag(), metadata - .getLocationId(), metadata.getState(), ComputeTaskUtils - .ipOrEmptyString(metadata.getPublicAddresses()), - ipOrEmptyString(metadata.getPrivateAddresses()), metadata.getExtra())); - } - - /** - * @return the configured {@link NodeElement} element - */ - public final NodeElement createNodes() { - if (getNodes() == null) { - this.nodeElement = new NodeElement(); - } - return this.nodeElement; - } - - public NodeElement getNodes() { - return this.nodeElement; - } - - public String getActions() { - return actions; - } - - public void setActions(String actions) { - this.actions = actions; - } - - public NodeElement getNodeElement() { - return nodeElement; - } - - public void setNodeElement(NodeElement nodeElement) { - this.nodeElement = nodeElement; - } - - public void setProvider(String provider) { - this.provider = provider; - } - - public String getProvider() { - return provider; - } -} +/** + * + * Copyright (C) 2009 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ +package org.jclouds.tools.ant.taskdefs.compute; + +import static org.jclouds.compute.util.ComputeUtils.isKeyAuth; +import static org.jclouds.tools.ant.taskdefs.compute.ComputeTaskUtils.buildComputeMap; +import static org.jclouds.tools.ant.taskdefs.compute.ComputeTaskUtils.createTemplateFromElement; +import static org.jclouds.tools.ant.taskdefs.compute.ComputeTaskUtils.ipOrEmptyString; + +import java.io.IOException; +import java.net.URI; +import java.util.Map; + +import javax.annotation.Nullable; + +import org.apache.tools.ant.BuildException; +import org.apache.tools.ant.Project; +import org.apache.tools.ant.Task; +import org.jclouds.compute.ComputeService; +import org.jclouds.compute.ComputeServiceContext; +import org.jclouds.compute.domain.ComputeMetadata; +import org.jclouds.compute.domain.Image; +import org.jclouds.compute.domain.NodeMetadata; +import org.jclouds.compute.domain.Size; +import org.jclouds.compute.domain.Template; +import org.jclouds.domain.Location; +import org.jclouds.http.HttpUtils; + +import com.google.common.base.CaseFormat; +import com.google.common.base.Splitter; +import com.google.inject.Provider; + +/** + * @author Adrian Cole + * @author Ivan Meredith + */ +public class ComputeTask extends Task { + + private final Map computeMap; + private String provider; + private String actions; + private NodeElement nodeElement; + + /** + * we don't have a reference to the project during the constructor, so we need to defer expansion + * with a Provider. + */ + private final Provider projectProvider = new Provider() { + @Override + public Project get() { + return getProject(); + } + }; + + public ComputeTask(@Nullable Map computeMap) { + this.computeMap = computeMap != null ? computeMap : buildComputeMap(projectProvider); + } + + public ComputeTask() throws IOException { + this(null); + } + + public static enum Action { + CREATE, GET, LIST, LIST_DETAILS, DESTROY, LIST_IMAGES, LIST_SIZES, LIST_LOCATIONS + } + + /** + * makes a connection to the compute service and invokes + */ + public void execute() throws BuildException { + ComputeServiceContext context = computeMap.get(HttpUtils.createUri(provider)); + + try { + for (String action : Splitter.on(',').split(actions)) { + Action act = Action.valueOf(CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_UNDERSCORE, + action)); + invokeActionOnService(act, context.getComputeService()); + } + } finally { + context.close(); + } + } + + private void invokeActionOnService(Action action, ComputeService computeService) { + switch (action) { + case CREATE: + case GET: + case DESTROY: + if (nodeElement != null) { + switch (action) { + case CREATE: + create(computeService); + break; + case GET: + get(computeService); + break; + case DESTROY: + destroy(computeService); + break; + } + } else { + this.log("missing node element for action: " + action, Project.MSG_ERR); + } + break; + case LIST: + list(computeService); + break; + case LIST_DETAILS: + listDetails(computeService); + break; + case LIST_IMAGES: + listImages(computeService); + break; + case LIST_SIZES: + listSizes(computeService); + break; + case LIST_LOCATIONS: + listLocations(computeService); + break; + default: + this.log("bad action: " + action, Project.MSG_ERR); + } + } + + private void listDetails(ComputeService computeService) { + log("list details"); + for (ComputeMetadata node : computeService.getNodes().values()) {// TODO + // parallel + logDetails(computeService, node); + } + } + + private void listImages(ComputeService computeService) { + log("list images"); + for (Image image : computeService.getImages().values()) {// TODO + log(String + .format( + " image location=%s, id=%s, name=%s, version=%s, arch=%s, osfam=%s, osdesc=%s, desc=%s", + image.getLocationId(), image.getId(), image.getName(), image + .getVersion(), image.getArchitecture(), image.getOsFamily(), + image.getOsDescription(), image.getDescription())); + } + } + + private void listSizes(ComputeService computeService) { + log("list sizes"); + for (Size size : computeService.getSizes().values()) {// TODO + log(String.format(" size id=%s, cores=%s, ram=%s, disk=%s", size.getId(), size + .getCores(), size.getRam(), size.getDisk())); + } + } + + private void listLocations(ComputeService computeService) { + log("list locations"); + for (Location location : computeService.getLocations().values()) {// TODO + log(String.format(" location id=%s, scope=%s, description=%s, parent=%s, assignable=%s", + location.getId(), location.getScope(), location.getDescription(), location + .getParent(), location.isAssignable())); + } + } + + private void list(ComputeService computeService) { + log("list"); + for (ComputeMetadata node : computeService.getNodes().values()) { + log(String.format(" location=%s, id=%s, tag=%s", node.getLocationId(), node.getId(), + node.getName())); + } + } + + private void create(ComputeService computeService) { + String tag = nodeElement.getTag(); + + log(String.format("create tag: %s, count: %d, size: %s, os: %s", tag, nodeElement.getCount(), + nodeElement.getSize(), nodeElement.getOs())); + + Template template = createTemplateFromElement(nodeElement, computeService); + + for (NodeMetadata createdNode : computeService.runNodesWithTag(tag, nodeElement.getCount(), + template).values()) { + logDetails(computeService, createdNode); + addNodeDetailsAsProjectProperties(createdNode); + } + } + + private void addNodeDetailsAsProjectProperties(NodeMetadata createdNode) { + if (nodeElement.getIdproperty() != null) + getProject().setProperty(nodeElement.getIdproperty(), createdNode.getId()); + if (nodeElement.getHostproperty() != null) + getProject().setProperty(nodeElement.getHostproperty(), + ipOrEmptyString(createdNode.getPublicAddresses())); + if (nodeElement.getPasswordproperty() != null && !isKeyAuth(createdNode)) + getProject().setProperty(nodeElement.getPasswordproperty(), + createdNode.getCredentials().key); + if (nodeElement.getUsernameproperty() != null) + getProject().setProperty(nodeElement.getUsernameproperty(), + createdNode.getCredentials().account); + } + + private void destroy(ComputeService computeService) { + log(String.format("destroy tag: %s", nodeElement.getTag())); + computeService.destroyNodesWithTag(nodeElement.getTag()); + } + + private void get(ComputeService computeService) { + log(String.format("get tag: %s", nodeElement.getTag())); + for (ComputeMetadata node : computeService.getNodesWithTag(nodeElement.getTag()).values()) { + logDetails(computeService, node); + } + } + + private void logDetails(ComputeService computeService, ComputeMetadata node) { + NodeMetadata metadata = node instanceof NodeMetadata ? NodeMetadata.class.cast(node) + : computeService.getNodeMetadata(node); + log(String + .format( + " node id=%s, name=%s, tag=%s, location=%s, state=%s, publicIp=%s, privateIp=%s, extra=%s", + metadata.getId(), metadata.getName(), metadata.getTag(), metadata + .getLocationId(), metadata.getState(), ComputeTaskUtils + .ipOrEmptyString(metadata.getPublicAddresses()), + ipOrEmptyString(metadata.getPrivateAddresses()), metadata.getExtra())); + } + + /** + * @return the configured {@link NodeElement} element + */ + public final NodeElement createNodes() { + if (getNodes() == null) { + this.nodeElement = new NodeElement(); + } + return this.nodeElement; + } + + public NodeElement getNodes() { + return this.nodeElement; + } + + public String getActions() { + return actions; + } + + public void setActions(String actions) { + this.actions = actions; + } + + public NodeElement getNodeElement() { + return nodeElement; + } + + public void setNodeElement(NodeElement nodeElement) { + this.nodeElement = nodeElement; + } + + public void setProvider(String provider) { + this.provider = provider; + } + + public String getProvider() { + return provider; + } +} diff --git a/vcloud/core/src/main/java/org/jclouds/vcloud/compute/BaseVCloudComputeClient.java b/vcloud/core/src/main/java/org/jclouds/vcloud/compute/BaseVCloudComputeClient.java index fd0fb3fdd1..f0453273e4 100644 --- a/vcloud/core/src/main/java/org/jclouds/vcloud/compute/BaseVCloudComputeClient.java +++ b/vcloud/core/src/main/java/org/jclouds/vcloud/compute/BaseVCloudComputeClient.java @@ -1,202 +1,202 @@ -/** - * - * Copyright (C) 2009 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ -package org.jclouds.vcloud.compute; - -import static com.google.common.base.Preconditions.checkState; -import static org.jclouds.vcloud.options.InstantiateVAppTemplateOptions.Builder.processorCount; - -import java.net.InetAddress; -import java.util.Map; -import java.util.Set; - -import javax.annotation.Resource; -import javax.inject.Named; -import javax.inject.Singleton; - -import org.jclouds.compute.domain.NodeState; -import org.jclouds.compute.reference.ComputeServiceConstants; -import org.jclouds.http.HttpResponseException; -import org.jclouds.logging.Logger; -import org.jclouds.vcloud.VCloudClient; -import org.jclouds.vcloud.domain.Task; -import org.jclouds.vcloud.domain.VApp; -import org.jclouds.vcloud.domain.VAppStatus; -import org.jclouds.vcloud.options.InstantiateVAppTemplateOptions; - -import com.google.common.base.Predicate; -import com.google.common.collect.ImmutableSet; -import com.google.common.collect.Maps; -import com.google.common.collect.Sets; -import com.google.inject.Inject; - -/** - * @author Adrian Cole - */ -@Singleton -public class BaseVCloudComputeClient implements VCloudComputeClient { - @Resource - @Named(ComputeServiceConstants.COMPUTE_LOGGER) - protected Logger logger = Logger.NULL; - - protected final VCloudClient client; - protected final Predicate taskTester; - protected final Predicate notFoundTester; - protected final Map vAppStatusToNodeState; - - @Inject - public BaseVCloudComputeClient(VCloudClient client, Predicate successTester, - @Named("NOT_FOUND") Predicate notFoundTester, - Map vAppStatusToNodeState) { - this.client = client; - this.taskTester = successTester; - this.notFoundTester = notFoundTester; - this.vAppStatusToNodeState = vAppStatusToNodeState; - } - - public Map start(String vDCId, String name, String templateId, int minCores, - int minMegs, Long diskSize, Map properties, int... portsToOpen) { - logger - .debug( - ">> instantiating vApp vDC(%s) name(%s) template(%s) minCores(%d) minMegs(%d) diskSize(%d) properties(%s) ", - vDCId, name, templateId, minCores, minMegs, diskSize, properties); - InstantiateVAppTemplateOptions options = processorCount(minCores).memory(minMegs) - .productProperties(properties); - if (diskSize != null) - options.disk(diskSize); - VApp vAppResponse = client.instantiateVAppTemplateInVDC(vDCId, name, templateId, options); - logger.debug("<< instantiated VApp(%s)", vAppResponse.getId()); - - logger.debug(">> deploying vApp(%s)", vAppResponse.getId()); - - Task task = client.deployVApp(vAppResponse.getId()); - if (!taskTester.apply(task.getId())) { - throw new TaskException("deploy", vAppResponse, task); - } - - logger.debug("<< deployed vApp(%s)", vAppResponse.getId()); - - logger.debug(">> powering vApp(%s)", vAppResponse.getId()); - try { - task = client.powerOnVApp(vAppResponse.getId()); - if (!taskTester.apply(task.getId())) { - throw new TaskException("powerOn", vAppResponse, task); - } - } catch (HttpResponseException e) { - if (e.getResponse().getStatusCode() == 400 - && client.getVApp(vAppResponse.getId()).getStatus() == VAppStatus.ON) { - // TODO temporary hack because some vcloud implementations automatically transition to - // powerOn from deploy - } else { - throw e; - } - - } - logger.debug("<< on vApp(%s)", vAppResponse.getId()); - - Map response = parseResponse(vAppResponse); - checkState(response.containsKey("id"), "bad configuration: [id] should be in response"); - checkState(response.containsKey("username"), - "bad configuration: [username] should be in response"); - checkState(response.containsKey("password"), - "bad configuration: [password] should be in response"); - return response; - } - - protected Map parseResponse(VApp vAppResponse) { - Map config = Maps.newLinkedHashMap();// Allows nulls - config.put("id", vAppResponse.getId()); - config.put("username", null); - config.put("password", null); - return config; - } - - public void reboot(String id) { - VApp vApp = client.getVApp(id); - logger.debug(">> resetting vApp(%s)", vApp.getId()); - Task task = client.resetVApp(vApp.getId()); - if (!taskTester.apply(task.getId())) { - throw new TaskException("resetVApp", vApp, task); - } - logger.debug("<< on vApp(%s)", vApp.getId()); - } - - public void stop(String id) { - VApp vApp = client.getVApp(id); - if (vApp.getStatus() != VAppStatus.OFF) { - logger.debug(">> powering off vApp(%s), current status: %s", vApp.getId(), vApp - .getStatus()); - Task task = client.powerOffVApp(vApp.getId()); - if (!taskTester.apply(task.getId())) { - throw new TaskException("powerOff", vApp, task); - } - logger.debug("<< off vApp(%s)", vApp.getId()); - } - logger.debug(">> deleting vApp(%s)", vApp.getId()); - client.deleteVApp(id); - boolean successful = notFoundTester.apply(vApp); - logger.debug("<< deleted vApp(%s) completed(%s)", vApp.getId(), successful); - } - - public static class TaskException extends VAppException { - - private final Task task; - /** The serialVersionUID */ - private static final long serialVersionUID = 251801929573211256L; - - public TaskException(String type, VApp vApp, Task task) { - super(String.format("failed to %s vApp %s status %s;task %s status %s", type, - vApp.getId(), vApp.getStatus(), task.getLocation(), task.getStatus()), vApp); - this.task = task; - } - - public Task getTask() { - return task; - } - - } - - public static class VAppException extends RuntimeException { - - private final VApp vApp; - /** The serialVersionUID */ - private static final long serialVersionUID = 251801929573211256L; - - public VAppException(String message, VApp vApp) { - super(message); - this.vApp = vApp; - } - - public VApp getvApp() { - return vApp; - } - - } - - @Override - public Set getPrivateAddresses(String id) { - return ImmutableSet.of(); - } - - @Override - public Set getPublicAddresses(String id) { - VApp vApp = client.getVApp(id); - return Sets.newHashSet(vApp.getNetworkToAddresses().values()); - } - +/** + * + * Copyright (C) 2009 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ +package org.jclouds.vcloud.compute; + +import static com.google.common.base.Preconditions.checkState; +import static org.jclouds.vcloud.options.InstantiateVAppTemplateOptions.Builder.processorCount; + +import java.net.InetAddress; +import java.util.Map; +import java.util.Set; + +import javax.annotation.Resource; +import javax.inject.Named; +import javax.inject.Singleton; + +import org.jclouds.compute.domain.NodeState; +import org.jclouds.compute.reference.ComputeServiceConstants; +import org.jclouds.http.HttpResponseException; +import org.jclouds.logging.Logger; +import org.jclouds.vcloud.VCloudClient; +import org.jclouds.vcloud.domain.Task; +import org.jclouds.vcloud.domain.VApp; +import org.jclouds.vcloud.domain.VAppStatus; +import org.jclouds.vcloud.options.InstantiateVAppTemplateOptions; + +import com.google.common.base.Predicate; +import com.google.common.collect.ImmutableSet; +import com.google.common.collect.Maps; +import com.google.common.collect.Sets; +import com.google.inject.Inject; + +/** + * @author Adrian Cole + */ +@Singleton +public class BaseVCloudComputeClient implements VCloudComputeClient { + @Resource + @Named(ComputeServiceConstants.COMPUTE_LOGGER) + protected Logger logger = Logger.NULL; + + protected final VCloudClient client; + protected final Predicate taskTester; + protected final Predicate notFoundTester; + protected final Map vAppStatusToNodeState; + + @Inject + public BaseVCloudComputeClient(VCloudClient client, Predicate successTester, + @Named("NOT_FOUND") Predicate notFoundTester, + Map vAppStatusToNodeState) { + this.client = client; + this.taskTester = successTester; + this.notFoundTester = notFoundTester; + this.vAppStatusToNodeState = vAppStatusToNodeState; + } + + public Map start(String vDCId, String name, String templateId, int minCores, + int minMegs, Long diskSize, Map properties, int... portsToOpen) { + logger + .debug( + ">> instantiating vApp vDC(%s) name(%s) template(%s) minCores(%d) minMegs(%d) diskSize(%d) properties(%s) ", + vDCId, name, templateId, minCores, minMegs, diskSize, properties); + InstantiateVAppTemplateOptions options = processorCount(minCores).memory(minMegs) + .productProperties(properties); + if (diskSize != null) + options.disk(diskSize); + VApp vAppResponse = client.instantiateVAppTemplateInVDC(vDCId, name, templateId, options); + logger.debug("<< instantiated VApp(%s)", vAppResponse.getId()); + + logger.debug(">> deploying vApp(%s)", vAppResponse.getId()); + + Task task = client.deployVApp(vAppResponse.getId()); + if (!taskTester.apply(task.getId())) { + throw new TaskException("deploy", vAppResponse, task); + } + + logger.debug("<< deployed vApp(%s)", vAppResponse.getId()); + + logger.debug(">> powering vApp(%s)", vAppResponse.getId()); + try { + task = client.powerOnVApp(vAppResponse.getId()); + if (!taskTester.apply(task.getId())) { + throw new TaskException("powerOn", vAppResponse, task); + } + } catch (HttpResponseException e) { + if (e.getResponse().getStatusCode() == 400 + && client.getVApp(vAppResponse.getId()).getStatus() == VAppStatus.ON) { + // TODO temporary hack because some vcloud implementations automatically transition to + // powerOn from deploy + } else { + throw e; + } + + } + logger.debug("<< on vApp(%s)", vAppResponse.getId()); + + Map response = parseResponse(vAppResponse); + checkState(response.containsKey("id"), "bad configuration: [id] should be in response"); + checkState(response.containsKey("username"), + "bad configuration: [username] should be in response"); + checkState(response.containsKey("password"), + "bad configuration: [password] should be in response"); + return response; + } + + protected Map parseResponse(VApp vAppResponse) { + Map config = Maps.newLinkedHashMap();// Allows nulls + config.put("id", vAppResponse.getId()); + config.put("username", null); + config.put("password", null); + return config; + } + + public void reboot(String id) { + VApp vApp = client.getVApp(id); + logger.debug(">> resetting vApp(%s)", vApp.getId()); + Task task = client.resetVApp(vApp.getId()); + if (!taskTester.apply(task.getId())) { + throw new TaskException("resetVApp", vApp, task); + } + logger.debug("<< on vApp(%s)", vApp.getId()); + } + + public void stop(String id) { + VApp vApp = client.getVApp(id); + if (vApp.getStatus() != VAppStatus.OFF) { + logger.debug(">> powering off vApp(%s), current status: %s", vApp.getId(), vApp + .getStatus()); + Task task = client.powerOffVApp(vApp.getId()); + if (!taskTester.apply(task.getId())) { + throw new TaskException("powerOff", vApp, task); + } + logger.debug("<< off vApp(%s)", vApp.getId()); + } + logger.debug(">> deleting vApp(%s)", vApp.getId()); + client.deleteVApp(id); + boolean successful = notFoundTester.apply(vApp); + logger.debug("<< deleted vApp(%s) completed(%s)", vApp.getId(), successful); + } + + public static class TaskException extends VAppException { + + private final Task task; + /** The serialVersionUID */ + private static final long serialVersionUID = 251801929573211256L; + + public TaskException(String type, VApp vApp, Task task) { + super(String.format("failed to %s vApp %s status %s;task %s status %s", type, + vApp.getId(), vApp.getStatus(), task.getLocation(), task.getStatus()), vApp); + this.task = task; + } + + public Task getTask() { + return task; + } + + } + + public static class VAppException extends RuntimeException { + + private final VApp vApp; + /** The serialVersionUID */ + private static final long serialVersionUID = 251801929573211256L; + + public VAppException(String message, VApp vApp) { + super(message); + this.vApp = vApp; + } + + public VApp getvApp() { + return vApp; + } + + } + + @Override + public Set getPrivateAddresses(String id) { + return ImmutableSet.of(); + } + + @Override + public Set getPublicAddresses(String id) { + VApp vApp = client.getVApp(id); + return Sets.newHashSet(vApp.getNetworkToAddresses().values()); + } + } \ No newline at end of file