Merged from upstream

This commit is contained in:
Mattias Holmqvist 2011-05-13 00:07:33 +02:00
commit 484f2dd7e2
403 changed files with 17988 additions and 5279 deletions

1
.gitignore vendored
View File

@ -9,3 +9,4 @@ test-output/
*.iml
*.ipr
*.iws
TAGS

View File

@ -30,7 +30,7 @@ our current version is 1.0-beta-9c
our dev version is 1.0-SNAPSHOT
our compute api supports: aws-ec2, gogrid, cloudservers-us, stub (in-memory), deltacloud,
cloudservers-uk, vcloud (generic), ec2 (generic), byon,
cloudservers-uk, vcloud (generic), ec2 (generic), byon, nova,
trmk-ecloud, trmk-vcloudexpress, eucalyptus (generic),
cloudsigma-zrh, elasticstack(generic), bluelock-vclouddirector,
slicehost, eucalyptus-partnercloud-ec2, elastichosts-lon-p (Peer 1),
@ -49,6 +49,11 @@ our blobstore api supports: aws-s3, cloudfiles-us, cloudfiles-uk, filesystem,
* note * the pom dependency org.jclouds/jclouds-allblobstore gives you access to
to all of these providers
our loadbalancer api supports: cloudloadbalancers-us
* note * the pom dependency org.jclouds/jclouds-allloadbalancer gives you access to
to all of these providers
we also have support for: ibmdev, mezeo, nirvanix, boxdotnet, rimuhosting, openstack nova,
azurequeue, simpledb, cloudstack as well as a async-http-client
driver in the sandbox

View File

@ -29,6 +29,11 @@
<artifactId>jclouds-all</artifactId>
<name>all</name>
<dependencies>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>jclouds-allloadbalancer</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>jclouds-allcompute</artifactId>

View File

@ -44,6 +44,11 @@
<artifactId>aws-ec2</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.jclouds.api</groupId>
<artifactId>nova</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.jclouds.api</groupId>
<artifactId>byon</artifactId>

38
allloadbalancer/pom.xml Normal file
View File

@ -0,0 +1,38 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
Copyright (C) 2010 Cloud Conscious, LLC. <info@cloudconscious.com>
====================================================================
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.
====================================================================
--><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.jclouds</groupId>
<artifactId>jclouds-project</artifactId>
<version>1.0-SNAPSHOT</version>
<relativePath>../project/pom.xml</relativePath>
</parent>
<artifactId>jclouds-allloadbalancer</artifactId>
<name>allloadbalancer</name>
<dependencies>
<dependency>
<groupId>org.jclouds.provider</groupId>
<artifactId>cloudloadbalancers-us</artifactId>
<version>${project.version}</version>
</dependency>
</dependencies>
</project>

View File

@ -22,9 +22,11 @@ import static com.google.common.base.Preconditions.checkArgument;
import java.util.Map;
import javax.inject.Inject;
import javax.inject.Singleton;
import org.jclouds.http.HttpRequest;
import org.jclouds.json.Json;
import org.jclouds.cloudservers.domain.BackupSchedule;
import org.jclouds.rest.binders.BindToJsonPayload;
@ -37,17 +39,19 @@ import com.google.common.collect.ImmutableMap;
*/
@Singleton
public class BindBackupScheduleToJsonPayload extends BindToJsonPayload {
@Inject
public BindBackupScheduleToJsonPayload(Json jsonBinder) {
super(jsonBinder);
}
@Override
public <R extends HttpRequest> R bindToRequest(R request, Map<String, String> postParams) {
throw new IllegalStateException(
"Replace Backup Schedule needs an BackupSchedule object, not a Map");
throw new IllegalStateException("Replace Backup Schedule needs an BackupSchedule object, not a Map");
}
@Override
public <R extends HttpRequest> R bindToRequest(R request, Object toBind) {
checkArgument(toBind instanceof BackupSchedule,
"this binder is only valid for BackupSchedules!");
checkArgument(toBind instanceof BackupSchedule, "this binder is only valid for BackupSchedules!");
return super.bindToRequest(request, ImmutableMap.of("backupSchedule", toBind));
}
}

View File

@ -26,9 +26,12 @@ import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import javax.inject.Inject;
import org.jclouds.cloudservers.domain.Addresses;
import org.jclouds.encryption.internal.Base64;
import org.jclouds.http.HttpRequest;
import org.jclouds.cloudservers.domain.Addresses;
import org.jclouds.rest.MapBinder;
import org.jclouds.rest.binders.BindToJsonPayload;
import com.google.common.collect.ImmutableMap;
@ -40,7 +43,9 @@ import com.google.common.collect.Maps;
* @author Adrian Cole
*
*/
public class CreateServerOptions extends BindToJsonPayload {
public class CreateServerOptions implements MapBinder {
@Inject
private BindToJsonPayload jsonBinder;
static class File {
private final String path;
@ -50,11 +55,9 @@ public class CreateServerOptions extends BindToJsonPayload {
this.path = checkNotNull(path, "path");
this.contents = Base64.encodeBytes(checkNotNull(contents, "contents"));
checkArgument(path.getBytes().length < 255, String.format(
"maximum length of path is 255 bytes. Path specified %s is %d bytes", path, path
.getBytes().length));
"maximum length of path is 255 bytes. Path specified %s is %d bytes", path, path.getBytes().length));
checkArgument(contents.length < 10 * 1024, String.format(
"maximum size of the file is 10KB. Contents specified is %d bytes",
contents.length));
"maximum size of the file is 10KB. Contents specified is %d bytes", contents.length));
}
public String getContents() {
@ -92,10 +95,9 @@ public class CreateServerOptions extends BindToJsonPayload {
@Override
public <R extends HttpRequest> R bindToRequest(R request, Map<String, String> postParams) {
ServerRequest server = new ServerRequest(checkNotNull(postParams.get("name"),
"name parameter not present"), Integer.parseInt(checkNotNull(postParams
.get("imageId"), "imageId parameter not present")), Integer.parseInt(checkNotNull(
postParams.get("flavorId"), "flavorId parameter not present")));
ServerRequest server = new ServerRequest(checkNotNull(postParams.get("name"), "name parameter not present"),
Integer.parseInt(checkNotNull(postParams.get("imageId"), "imageId parameter not present")), Integer
.parseInt(checkNotNull(postParams.get("flavorId"), "flavorId parameter not present")));
if (metadata.size() > 0)
server.metadata = metadata;
if (files.size() > 0)
@ -162,19 +164,15 @@ public class CreateServerOptions extends BindToJsonPayload {
*/
public CreateServerOptions withMetadata(Map<String, String> metadata) {
checkNotNull(metadata, "metadata");
checkArgument(metadata.size() <= 5,
"you cannot have more then 5 metadata values. You specified: " + metadata.size());
checkArgument(metadata.size() <= 5, "you cannot have more then 5 metadata values. You specified: "
+ metadata.size());
for (Entry<String, String> entry : metadata.entrySet()) {
checkArgument(entry.getKey().getBytes().length < 255, String.format(
"maximum length of metadata key is 255 bytes. Key specified %s is %d bytes",
entry.getKey(), entry.getKey().getBytes().length));
checkArgument(
entry.getKey().getBytes().length < 255,
String
.format(
"maximum length of metadata value is 255 bytes. Value specified for %s (%s) is %d bytes",
entry.getKey(), entry.getValue(),
entry.getValue().getBytes().length));
"maximum length of metadata key is 255 bytes. Key specified %s is %d bytes", entry.getKey(), entry
.getKey().getBytes().length));
checkArgument(entry.getKey().getBytes().length < 255, String.format(
"maximum length of metadata value is 255 bytes. Value specified for %s (%s) is %d bytes", entry
.getKey(), entry.getValue(), entry.getValue().getBytes().length));
}
this.metadata = metadata;
return this;
@ -196,8 +194,7 @@ public class CreateServerOptions extends BindToJsonPayload {
* sharedIpGroupId is also supplied.
*/
public CreateServerOptions withSharedIp(String publicIp) {
checkState(sharedIpGroupId != null,
"sharedIp is invalid unless a shared ip group is specified.");
checkState(sharedIpGroupId != null, "sharedIp is invalid unless a shared ip group is specified.");
this.publicIp = checkNotNull(publicIp, "ip");
return this;
}
@ -237,4 +234,9 @@ public class CreateServerOptions extends BindToJsonPayload {
}
}
@Override
public <R extends HttpRequest> R bindToRequest(R request, Object input) {
return jsonBinder.bindToRequest(request, input);
}
}

View File

@ -24,8 +24,10 @@ import static com.google.common.base.Preconditions.checkNotNull;
import java.util.Map;
import javax.annotation.Nullable;
import javax.inject.Inject;
import org.jclouds.http.HttpRequest;
import org.jclouds.rest.MapBinder;
import org.jclouds.rest.binders.BindToJsonPayload;
import com.google.common.collect.ImmutableMap;
@ -36,7 +38,10 @@ import com.google.common.collect.ImmutableMap;
* @author Adrian Cole
*
*/
public class CreateSharedIpGroupOptions extends BindToJsonPayload {
public class CreateSharedIpGroupOptions implements MapBinder {
@Inject
private BindToJsonPayload jsonBinder;
Integer serverId;
@SuppressWarnings("unused")
@ -53,9 +58,8 @@ public class CreateSharedIpGroupOptions extends BindToJsonPayload {
@Override
public <R extends HttpRequest> R bindToRequest(R request, Map<String, String> postParams) {
SharedIpGroupRequest createRequest = new SharedIpGroupRequest(checkNotNull(postParams
.get("name")), serverId);
return super.bindToRequest(request, ImmutableMap.of("sharedIpGroup", createRequest));
SharedIpGroupRequest createRequest = new SharedIpGroupRequest(checkNotNull(postParams.get("name")), serverId);
return jsonBinder.bindToRequest(request, ImmutableMap.of("sharedIpGroup", createRequest));
}
@Override
@ -84,4 +88,5 @@ public class CreateSharedIpGroupOptions extends BindToJsonPayload {
return options.withServer(id);
}
}
}

View File

@ -22,7 +22,10 @@ import static com.google.common.base.Preconditions.checkArgument;
import java.util.Map;
import javax.inject.Inject;
import org.jclouds.http.HttpRequest;
import org.jclouds.rest.MapBinder;
import org.jclouds.rest.binders.BindToJsonPayload;
import com.google.common.collect.ImmutableMap;
@ -34,7 +37,9 @@ import com.google.common.collect.Maps;
* @author Adrian Cole
*
*/
public class RebuildServerOptions extends BindToJsonPayload {
public class RebuildServerOptions implements MapBinder {
@Inject
private BindToJsonPayload jsonBinder;
Integer imageId;
@Override
@ -42,7 +47,7 @@ public class RebuildServerOptions extends BindToJsonPayload {
Map<String, Integer> image = Maps.newHashMap();
if (imageId != null)
image.put("imageId", imageId);
return super.bindToRequest(request, ImmutableMap.of("rebuild", image));
return jsonBinder.bindToRequest(request, ImmutableMap.of("rebuild", image));
}
@Override

View File

@ -25,6 +25,9 @@ import static org.easymock.classextension.EasyMock.verify;
import java.net.URI;
import javax.inject.Named;
import javax.inject.Singleton;
import org.jclouds.http.HttpCommand;
import org.jclouds.http.HttpRequest;
import org.jclouds.http.HttpResponse;
@ -32,7 +35,12 @@ import org.jclouds.rest.BaseRestClientTest.MockModule;
import org.jclouds.rest.config.RestModule;
import org.testng.annotations.Test;
import com.google.common.collect.LinkedHashMultimap;
import com.google.common.collect.Multimap;
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Provides;
/**
* Tests behavior of {@code DeltacloudRedirectionRetry}
@ -41,6 +49,19 @@ import com.google.inject.Guice;
*/
@Test(groups = "unit")
public class DeltacloudRedirectionRetryHandlerTest {
Injector injector = Guice.createInjector(new MockModule(), new RestModule(), new AbstractModule() {
@SuppressWarnings("unused")
@Provides
@Singleton
@Named("CONSTANTS")
protected Multimap<String, String> constants() {
return LinkedHashMultimap.create();
}
@Override
protected void configure() {
}
});
@Test
public void test302DoesNotRetryOnDelete() {
@ -53,7 +74,7 @@ public class DeltacloudRedirectionRetryHandlerTest {
replay(command);
DeltacloudRedirectionRetryHandler retry = Guice.createInjector(new MockModule(), new RestModule()).getInstance(
DeltacloudRedirectionRetryHandler retry = injector.getInstance(
DeltacloudRedirectionRetryHandler.class);
assert !retry.shouldRetryRequest(command, response);
@ -74,7 +95,7 @@ public class DeltacloudRedirectionRetryHandlerTest {
replay(command);
DeltacloudRedirectionRetryHandler retry = Guice.createInjector(new MockModule(), new RestModule()).getInstance(
DeltacloudRedirectionRetryHandler retry = injector.getInstance(
DeltacloudRedirectionRetryHandler.class);
assert !retry.shouldRetryRequest(command, response);

View File

@ -42,6 +42,7 @@ import org.jclouds.compute.domain.Image;
import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.domain.TemplateBuilder;
import org.jclouds.compute.internal.BaseComputeService;
import org.jclouds.compute.internal.PersistNodeCredentials;
import org.jclouds.compute.options.TemplateOptions;
import org.jclouds.compute.reference.ComputeServiceConstants.Timeouts;
import org.jclouds.compute.strategy.CreateNodesInGroupThenAddToSet;
@ -60,6 +61,7 @@ import org.jclouds.ec2.compute.domain.RegionNameAndIngressRules;
import org.jclouds.ec2.compute.options.EC2TemplateOptions;
import org.jclouds.ec2.domain.KeyPair;
import org.jclouds.ec2.domain.RunningInstance;
import org.jclouds.scriptbuilder.functions.InitAdminAccess;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Function;
@ -89,13 +91,14 @@ public class EC2ComputeService extends BaseComputeService {
@Named("NODE_RUNNING") Predicate<NodeMetadata> nodeRunning,
@Named("NODE_TERMINATED") Predicate<NodeMetadata> nodeTerminated,
@Named("NODE_SUSPENDED") Predicate<NodeMetadata> nodeSuspended,
InitializeRunScriptOnNodeOrPlaceInBadMap.Factory initScriptRunnerFactory, Timeouts timeouts,
InitializeRunScriptOnNodeOrPlaceInBadMap.Factory initScriptRunnerFactory, InitAdminAccess initAdminAccess,
PersistNodeCredentials persistNodeCredentials, Timeouts timeouts,
@Named(Constants.PROPERTY_USER_THREADS) ExecutorService executor, EC2Client ec2Client,
Map<RegionAndName, KeyPair> credentialsMap, @Named("SECURITY") Map<RegionAndName, String> securityGroupMap) {
super(context, credentialStore, images, sizes, locations, listNodesStrategy, getNodeMetadataStrategy,
runNodesAndAddToSetStrategy, rebootNodeStrategy, destroyNodeStrategy, startNodeStrategy, stopNodeStrategy,
templateBuilderProvider, templateOptionsProvider, nodeRunning, nodeTerminated, nodeSuspended,
initScriptRunnerFactory, timeouts, executor);
initScriptRunnerFactory, initAdminAccess, persistNodeCredentials, timeouts, executor);
this.ec2Client = ec2Client;
this.credentialsMap = credentialsMap;
this.securityGroupMap = securityGroupMap;
@ -125,7 +128,8 @@ public class EC2ComputeService extends BaseComputeService {
// when the keypair is unique per group
keyPair.getKeyName().equals("jclouds#" + group)
|| keyPair.getKeyName().matches(String.format("jclouds#%s#%s", group, "[0-9a-f]+"))
// old keypair pattern too verbose as it has an unnecessary region qualifier
// old keypair pattern too verbose as it has an unnecessary
// region qualifier
|| keyPair.getKeyName().matches(String.format("jclouds#%s#%s#%s", group, region, "[0-9a-f]+"))) {
Set<String> instancesUsingKeyPair = extractIdsFromInstances(filter(concat(ec2Client.getInstanceServices()
.describeInstancesInRegion(region)), usingKeyPairAndNotDead(keyPair)));
@ -170,8 +174,8 @@ public class EC2ComputeService extends BaseComputeService {
}
/**
* like {@link BaseComputeService#destroyNodesMatching} except that this will clean implicit
* keypairs and security groups.
* like {@link BaseComputeService#destroyNodesMatching} except that this will
* clean implicit keypairs and security groups.
*/
@Override
public Set<? extends NodeMetadata> destroyNodesMatching(Predicate<NodeMetadata> filter) {

View File

@ -2,7 +2,7 @@
<!--
Copyright (C) 2010 Cloud Conscious, LLC. <info@cloudconscious.com>
Copyright (C) 2011 Cloud Conscious, LLC. <info@cloudconscious.com>
====================================================================
Licensed under the Apache License, Version 2.0 (the "License");
@ -21,7 +21,7 @@
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4.0.0.xsd" >
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.jclouds</groupId>
@ -35,10 +35,7 @@
<description>jclouds components to access an implementation of OpenStack Nova</description>
<properties>
<test.nova.endpoint>https://auth.api.rackspacecloud.com</test.nova.endpoint>
<test.nova.apiversion>1.1</test.nova.apiversion>
<test.nova.identity>FIXME</test.nova.identity>
<test.nova.credential>FIXME</test.nova.credential>
</properties>
<dependencies>
@ -79,25 +76,42 @@
<version>${project.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jclouds.driver</groupId>
<artifactId>jclouds-log4j</artifactId>
<artifactId>jclouds-slf4j</artifactId>
<version>${project.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.16</version>
<artifactId>slf4j-api</artifactId>
<groupId>org.slf4j</groupId>
<version>1.6.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>0.9.28</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-remote-resources-plugin</artifactId>
<version>1.2</version>
<executions>
<execution>
<id>process-remote-resources</id>
<!-- plugin is tuned off due to incorrect work in Eclipse-->
<phase></phase>
</execution>
</executions>
</plugin>
</plugins>
</build>
<profiles>
<profile>
<id>live</id>
@ -106,6 +120,14 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.8.1</version>
<dependencies>
<dependency>
<groupId>org.apache.maven.surefire</groupId>
<artifactId>surefire-testng</artifactId>
<version>2.8.1</version>
</dependency>
</dependencies>
<executions>
<execution>
<id>integration</id>
@ -131,6 +153,14 @@
<name>test.nova.credential</name>
<value>${test.nova.credential}</value>
</property>
<property>
<name>test.ssh.keyfile.public</name>
<value>${test.ssh.keyfile.public}</value>
</property>
<property>
<name>test.ssh.keyfile.private</name>
<value>${test.ssh.keyfile.private}</value>
</property>
<property>
<name>test.initializer</name>
<value>${test.initializer}</value>
@ -147,4 +177,3 @@
</project>

View File

@ -18,50 +18,22 @@
*/
package org.jclouds.openstack.nova;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import org.jclouds.openstack.nova.binders.BindBackupScheduleToJsonPayload;
import org.jclouds.openstack.nova.domain.Addresses;
import org.jclouds.openstack.nova.domain.BackupSchedule;
import org.jclouds.openstack.nova.domain.Flavor;
import org.jclouds.openstack.nova.domain.Image;
import org.jclouds.openstack.nova.domain.RebootType;
import org.jclouds.openstack.nova.domain.Server;
import org.jclouds.openstack.nova.domain.SharedIpGroup;
import org.jclouds.openstack.nova.options.CreateServerOptions;
import org.jclouds.openstack.nova.options.CreateSharedIpGroupOptions;
import org.jclouds.openstack.nova.options.ListOptions;
import org.jclouds.openstack.nova.options.RebuildServerOptions;
import org.jclouds.http.functions.ReturnFalseOn404;
import com.google.common.util.concurrent.ListenableFuture;
import org.jclouds.openstack.filters.AddTimestampQuery;
import org.jclouds.openstack.filters.AuthenticateRequest;
import org.jclouds.rest.annotations.BinderParam;
import org.jclouds.rest.annotations.Endpoint;
import org.jclouds.rest.annotations.ExceptionParser;
import org.jclouds.rest.annotations.MapBinder;
import org.jclouds.rest.annotations.Payload;
import org.jclouds.rest.annotations.PayloadParam;
import org.jclouds.rest.annotations.QueryParams;
import org.jclouds.rest.annotations.RequestFilters;
import org.jclouds.rest.annotations.SkipEncoding;
import org.jclouds.rest.annotations.Unwrap;
import org.jclouds.openstack.nova.domain.*;
import org.jclouds.openstack.nova.options.CreateServerOptions;
import org.jclouds.openstack.nova.options.ListOptions;
import org.jclouds.openstack.nova.options.RebuildServerOptions;
import org.jclouds.rest.annotations.*;
import org.jclouds.rest.functions.ReturnEmptySetOnNotFoundOr404;
import org.jclouds.rest.functions.ReturnFalseOnNotFoundOr404;
import org.jclouds.rest.functions.ReturnNullOnNotFoundOr404;
import org.jclouds.rest.functions.ReturnVoidOnNotFoundOr404;
import com.google.common.util.concurrent.ListenableFuture;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import java.util.Set;
import java.util.concurrent.ExecutionException;
/**
* Provides asynchronous access to OpenStack Nova via their REST API.
@ -70,9 +42,9 @@ import com.google.common.util.concurrent.ListenableFuture;
* during processing will be wrapped in an {@link ExecutionException} as documented in
* {@link ListenableFuture#get()}.
*
* @author Adrian Cole
* @see NovaClient
* @see <a href="http://wiki.openstack.org/OpenStackAPI_1-1" />
* @author Adrian Cole
*/
@SkipEncoding({'/', '='})
@RequestFilters({AuthenticateRequest.class, AddTimestampQuery.class})
@ -158,8 +130,8 @@ public interface NovaAsyncClient {
@QueryParams(keys = "format", values = "json")
@Path("/servers")
@MapBinder(CreateServerOptions.class)
ListenableFuture<Server> createServer(@PayloadParam("name") String name, @PayloadParam("imageId") int imageId,
@PayloadParam("flavorId") int flavorId, CreateServerOptions... options);
ListenableFuture<Server> createServer(@PayloadParam("name") String name, @PayloadParam("imageRef") String imageRef,
@PayloadParam("flavorRef") String flavorRef, CreateServerOptions... options);
/**
* @see NovaClient#rebuildServer
@ -170,33 +142,14 @@ public interface NovaAsyncClient {
@MapBinder(RebuildServerOptions.class)
ListenableFuture<Void> rebuildServer(@PathParam("id") int id, RebuildServerOptions... options);
/**
* @see NovaClient#shareIp
*/
@PUT
@Path("/servers/{id}/ips/public/{address}")
@Produces(MediaType.APPLICATION_JSON)
@Payload("%7B\"shareIp\":%7B\"sharedIpGroupId\":{sharedIpGroupId},\"configureServer\":{configureServer}%7D%7D")
ListenableFuture<Void> shareIp(@PathParam("address") String addressToShare,
@PathParam("id") int serverToTosignBindressTo, @PayloadParam("sharedIpGroupId") int sharedIpGroup,
@PayloadParam("configureServer") boolean configureServer);
/**
* @see NovaClient#unshareIp
*/
@DELETE
@Path("/servers/{id}/ips/public/{address}")
@ExceptionParser(ReturnVoidOnNotFoundOr404.class)
ListenableFuture<Void> unshareIp(@PathParam("address") String addressToShare,
@PathParam("id") int serverToTosignBindressTo);
/**
* @see NovaClient#changeAdminPass
*/
@PUT
@Path("/servers/{id}")
@POST
@Path("/servers/{id}/action")
@Produces(MediaType.APPLICATION_JSON)
@Payload("%7B\"server\":%7B\"adminPass\":\"{adminPass}\"%7D%7D")
@Payload("%7B\"changePassword\":%7B\"adminPass\":\"{adminPass}\"%7D%7D")
ListenableFuture<Void> changeAdminPass(@PathParam("id") int id, @PayloadParam("adminPass") String adminPass);
/**
@ -273,75 +226,6 @@ public interface NovaAsyncClient {
ListenableFuture<Image> createImageFromServer(@PayloadParam("name") String imageName,
@PayloadParam("serverId") int serverId);
/**
* @see NovaClient#listSharedIpGroups
*/
@GET
@Unwrap
@Consumes(MediaType.APPLICATION_JSON)
@QueryParams(keys = "format", values = "json")
@Path("/shared_ip_groups")
@ExceptionParser(ReturnEmptySetOnNotFoundOr404.class)
ListenableFuture<? extends Set<SharedIpGroup>> listSharedIpGroups(ListOptions... options);
/**
* @see NovaClient#getSharedIpGroup
*/
@GET
@Unwrap
@Consumes(MediaType.APPLICATION_JSON)
@QueryParams(keys = "format", values = "json")
@Path("/shared_ip_groups/{id}")
@ExceptionParser(ReturnNullOnNotFoundOr404.class)
ListenableFuture<SharedIpGroup> getSharedIpGroup(@PathParam("id") int id);
/**
* @see NovaClient#createSharedIpGroup
*/
@POST
@Unwrap
@Consumes(MediaType.APPLICATION_JSON)
@QueryParams(keys = "format", values = "json")
@Path("/shared_ip_groups")
@MapBinder(CreateSharedIpGroupOptions.class)
ListenableFuture<SharedIpGroup> createSharedIpGroup(@PayloadParam("name") String name,
CreateSharedIpGroupOptions... options);
/**
* @see NovaClient#deleteSharedIpGroup
*/
@DELETE
@ExceptionParser(ReturnFalseOnNotFoundOr404.class)
@Path("/shared_ip_groups/{id}")
ListenableFuture<Boolean> deleteSharedIpGroup(@PathParam("id") int id);
/**
* @see NovaClient#listBackupSchedule
*/
@GET
@Unwrap
@Consumes(MediaType.APPLICATION_JSON)
@QueryParams(keys = "format", values = "json")
@Path("/servers/{id}/backup_schedule")
ListenableFuture<BackupSchedule> getBackupSchedule(@PathParam("id") int serverId);
/**
* @see NovaClient#deleteBackupSchedule
*/
@DELETE
@ExceptionParser(ReturnFalseOnNotFoundOr404.class)
@Path("/servers/{id}/backup_schedule")
ListenableFuture<Boolean> deleteBackupSchedule(@PathParam("id") int serverId);
/**
* @see NovaClient#replaceBackupSchedule
*/
@POST
@ExceptionParser(ReturnFalseOn404.class)
@Path("/servers/{id}/backup_schedule")
ListenableFuture<Void> replaceBackupSchedule(@PathParam("id") int id,
@BinderParam(BindBackupScheduleToJsonPayload.class) BackupSchedule backupSchedule);
/**
* @see NovaClient#listAddresses
*/

View File

@ -26,14 +26,11 @@ import javax.ws.rs.PathParam;
import org.jclouds.concurrent.Timeout;
import org.jclouds.openstack.nova.domain.Addresses;
import org.jclouds.openstack.nova.domain.BackupSchedule;
import org.jclouds.openstack.nova.domain.Flavor;
import org.jclouds.openstack.nova.domain.Image;
import org.jclouds.openstack.nova.domain.RebootType;
import org.jclouds.openstack.nova.domain.Server;
import org.jclouds.openstack.nova.domain.SharedIpGroup;
import org.jclouds.openstack.nova.options.CreateServerOptions;
import org.jclouds.openstack.nova.options.CreateSharedIpGroupOptions;
import org.jclouds.openstack.nova.options.ListOptions;
import org.jclouds.openstack.nova.options.RebuildServerOptions;
import org.jclouds.rest.ResourceNotFoundException;
@ -154,7 +151,7 @@ public interface NovaClient {
* @param options
* - used to specify extra files, metadata, or ip parameters during server creation.
*/
Server createServer(String name, int imageId, int flavorId, CreateServerOptions... options);
Server createServer(String name, String imageRef, String flavorRef, CreateServerOptions... options);
/**
* The rebuild function removes all data on the server and replaces it with the specified image.
@ -173,40 +170,6 @@ public interface NovaClient {
*/
void rebuildServer(int id, RebuildServerOptions... options);
/**
* /** This operation allows you share an IP address to the specified server
* <p/>
* This operation shares an IP from an existing server in the specified shared IP group to
* another specified server in the same group. The operation modifies cloud network restrictions
* to allow IP traffic for the given IP to/from the server specified.
*
* <p/>
* Status Transition: ACTIVE - SHARE_IP - ACTIVE (if configureServer is true) ACTIVE -
* SHARE_IP_NO_CONFIG - ACTIVE
*
* @param configureServer
* <p/>
* if set to true, the server is configured with the new address, though the address is
* not enabled. Note that configuring the server does require a reboot.
* <p/>
* If set to false, does not bind the IP to the server itself. A heartbeat facility
* (e.g. keepalived) can then be used within the servers to perform health checks and
* manage IP failover.
*/
void shareIp(String addressToShare, int serverToTosignBindressTo, int sharedIpGroup,
boolean configureServer);
/**
* This operation removes a shared IP address from the specified server.
* <p/>
* Status Transition: ACTIVE - DELETE_IP - ACTIVE
*
* @param addressToShare
* @param serverToTosignBindressTo
* @return
*/
void unshareIp(String addressToShare, int serverToTosignBindressTo);
/**
* This operation allows you to change the administrative password.
* <p/>
@ -295,66 +258,6 @@ public interface NovaClient {
*/
Image createImageFromServer(String imageName, int serverId);
/**
*
* List shared IP groups (IDs and names only)
*
* in order to retrieve all details, pass the option {@link ListOptions#withDetails()
* withDetails()}
*/
Set<SharedIpGroup> listSharedIpGroups(ListOptions... options);
/**
*
* This operation returns details of the specified shared IP group.
*
* @return null, if the shared ip group is not found
*
* @see SharedIpGroup
*/
SharedIpGroup getSharedIpGroup(int id);
/**
* This operation creates a new shared IP group. Please note, all responses to requests for
* shared_ip_groups return an array of servers. However, on a create request, the shared IP group
* can be created empty or can be initially populated with a single server. Use
* {@link CreateSharedIpGroupOptions} to specify an server.
*/
SharedIpGroup createSharedIpGroup(String name, CreateSharedIpGroupOptions... options);
/**
* This operation deletes the specified shared IP group. This operation will ONLY succeed if 1)
* there are no active servers in the group (i.e. they have all been terminated) or 2) no servers
* in the group are actively sharing IPs.
*
* @return false if the shared ip group is not found
* @see SharedIpGroup
*/
boolean deleteSharedIpGroup(int id);
/**
* List the backup schedule for the specified server
*
* @throws ResourceNotFoundException
* , if the server doesn't exist
*/
BackupSchedule getBackupSchedule(int serverId);
/**
* Delete backup schedule for the specified server.
* <p/>
* Web Hosting #119571 currently disables the schedule, not deletes it.
*
* @return false if the schedule is not found
*/
boolean deleteBackupSchedule(int serverId);
/**
* Enable/update the backup schedule for the specified server
*
*/
void replaceBackupSchedule(int id, BackupSchedule backupSchedule);
/**
* List all server addresses
*

View File

@ -0,0 +1,47 @@
/**
*
* Copyright (C) 2011 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* 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.openstack.nova;
import org.jclouds.PropertiesBuilder;
import java.util.Properties;
import static org.jclouds.Constants.PROPERTY_API_VERSION;
/**
* Builds properties used in Openstack Nova Clients
*
* @author Dmitri Babaev
*/
public class NovaPropertiesBuilder extends PropertiesBuilder {
@Override
protected Properties defaultProperties() {
Properties properties = super.defaultProperties();
properties.setProperty(PROPERTY_API_VERSION, "1.1");
return properties;
}
public NovaPropertiesBuilder(Properties properties) {
super(properties);
}
public NovaPropertiesBuilder() {
super();
}
}

View File

@ -89,19 +89,11 @@ public class NovaComputeServiceDependenciesModule extends AbstractModule {
.put(ServerStatus.PREP_RESIZE, NodeState.PENDING)//
.put(ServerStatus.RESIZE, NodeState.PENDING)//
.put(ServerStatus.VERIFY_RESIZE, NodeState.PENDING)//
.put(ServerStatus.QUEUE_MOVE, NodeState.PENDING)//
.put(ServerStatus.PREP_MOVE, NodeState.PENDING)//
.put(ServerStatus.MOVE, NodeState.PENDING)//
.put(ServerStatus.VERIFY_MOVE, NodeState.PENDING)//
.put(ServerStatus.RESCUE, NodeState.PENDING)//
.put(ServerStatus.ERROR, NodeState.ERROR)//
.put(ServerStatus.BUILD, NodeState.PENDING)//
.put(ServerStatus.RESTORING, NodeState.PENDING)//
.put(ServerStatus.PASSWORD, NodeState.PENDING)//
.put(ServerStatus.REBUILD, NodeState.PENDING)//
.put(ServerStatus.DELETE_IP, NodeState.PENDING)//
.put(ServerStatus.SHARE_IP_NO_CONFIG, NodeState.PENDING)//
.put(ServerStatus.SHARE_IP, NodeState.PENDING)//
.put(ServerStatus.REBOOT, NodeState.PENDING)//
.put(ServerStatus.HARD_REBOOT, NodeState.PENDING)//
.put(ServerStatus.UNKNOWN, NodeState.UNRECOGNIZED)//

View File

@ -36,8 +36,13 @@ import com.google.common.collect.ImmutableList;
@Singleton
public class FlavorToHardware implements Function<Flavor, Hardware> {
public Hardware apply(Flavor from) {
return new HardwareBuilder().ids(from.getId() + "").name(from.getName())
.processors(ImmutableList.of(new Processor(from.getDisk() / 10.0, 1.0))).ram(from.getRam())
.volumes(ImmutableList.<Volume> of(new VolumeImpl((float) from.getDisk(), true, true))).build();
return new HardwareBuilder()
.ids(from.getId() + "")
.name(from.getName())
.processors(ImmutableList.of(new Processor(from.getDisk() / 10.0, 1.0)))
.ram(from.getRam())
.volumes(ImmutableList.<Volume> of(new VolumeImpl((float) from.getDisk(), true, true)))
.uri(from.getURI())
.build();
}
}

View File

@ -44,11 +44,12 @@ public class NovaImageToImage implements Function<org.jclouds.openstack.nova.dom
public Image apply(org.jclouds.openstack.nova.domain.Image from) {
ImageBuilder builder = new ImageBuilder();
builder.ids(from.getId() + "");
builder.name(from.getName());
builder.description(from.getName());
builder.name(from.getName() != null ? from.getName() : "unspecified");
builder.description(from.getName() != null ? from.getName() : "unspecified");
builder.version(from.getUpdated().getTime() + "");
builder.operatingSystem(imageToOs.apply(from));
builder.operatingSystem(imageToOs.apply(from)); //image name may not represent the OS type
builder.defaultCredentials(new Credentials("root", null));
builder.uri(from.getURI());
Image image = builder.build();
return image;
}

View File

@ -62,13 +62,15 @@ public class NovaImageToOperatingSystem implements
String osName = null;
String osArch = null;
String osVersion = null;
String osDescription = from.getName();
String osDescription = from.getName() != null ? from.getName() : "unspecified";
String name = from.getName() != null ? from.getName() : "unspecified";
boolean is64Bit = true;
if (from.getName().indexOf("Red Hat EL") != -1) {
if (name.indexOf("Red Hat EL") != -1) {
osFamily = OsFamily.RHEL;
} else if (from.getName().indexOf("Oracle EL") != -1) {
} else if (name.indexOf("Oracle EL") != -1) {
osFamily = OsFamily.OEL;
} else if (from.getName().indexOf("Windows") != -1) {
} else if (name.indexOf("Windows") != -1) {
osFamily = OsFamily.WINDOWS;
Matcher matcher = WINDOWS_PATTERN.matcher(from.getName());
if (matcher.find()) {
@ -76,7 +78,7 @@ public class NovaImageToOperatingSystem implements
is64Bit = matcher.group(2).equals("x64");
}
} else {
Matcher matcher = DEFAULT_PATTERN.matcher(from.getName());
Matcher matcher = DEFAULT_PATTERN.matcher(name);
if (matcher.find()) {
try {
osFamily = OsFamily.fromValue(matcher.group(2).toLowerCase());

View File

@ -18,38 +18,32 @@
*/
package org.jclouds.openstack.nova.compute.functions;
import static com.google.common.base.Preconditions.checkNotNull;
import static org.jclouds.compute.util.ComputeServiceUtils.parseGroupFromName;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
import javax.annotation.Resource;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
import org.jclouds.openstack.nova.domain.Server;
import org.jclouds.openstack.nova.domain.ServerStatus;
import com.google.common.base.Function;
import com.google.common.base.Predicate;
import com.google.common.base.Supplier;
import com.google.common.collect.Iterables;
import org.jclouds.collect.Memoized;
import org.jclouds.compute.domain.Hardware;
import org.jclouds.compute.domain.Image;
import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.domain.NodeMetadataBuilder;
import org.jclouds.compute.domain.NodeState;
import org.jclouds.compute.domain.OperatingSystem;
import org.jclouds.compute.domain.*;
import org.jclouds.compute.reference.ComputeServiceConstants;
import org.jclouds.domain.Credentials;
import org.jclouds.domain.Location;
import org.jclouds.domain.LocationBuilder;
import org.jclouds.domain.LocationScope;
import org.jclouds.logging.Logger;
import org.jclouds.openstack.nova.domain.Address;
import org.jclouds.openstack.nova.domain.Server;
import org.jclouds.openstack.nova.domain.ServerStatus;
import com.google.common.base.Function;
import com.google.common.base.Predicate;
import com.google.common.base.Supplier;
import com.google.common.collect.Iterables;
import javax.annotation.Resource;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
import static com.google.common.base.Preconditions.checkNotNull;
import static org.jclouds.compute.util.ComputeServiceUtils.parseGroupFromName;
/**
* @author Adrian Cole
@ -75,7 +69,7 @@ public class ServerToNodeMetadata implements Function<Server, NodeMetadata> {
@Override
public boolean apply(Image input) {
return input.getProviderId().equals(instance.getImageId() + "");
return input.getUri().toString().equals(instance.getImageRef() + "");
}
}
@ -88,7 +82,7 @@ public class ServerToNodeMetadata implements Function<Server, NodeMetadata> {
@Override
public boolean apply(Hardware input) {
return input.getProviderId().equals(instance.getFlavorId() + "");
return input.getUri().toString().equals(instance.getFlavorRef() + "");
}
}
@ -112,13 +106,17 @@ public class ServerToNodeMetadata implements Function<Server, NodeMetadata> {
from.getHostId()).parent(location.get()).build());
builder.userMetadata(from.getMetadata());
builder.group(parseGroupFromName(from.getName()));
builder.imageId(from.getImageId() + "");
builder.operatingSystem(parseOperatingSystem(from));
Image image = parseImage(from);
if (image != null) {
builder.imageId(image.getId());
builder.operatingSystem(image.getOperatingSystem());
}
builder.hardware(parseHardware(from));
builder.state(serverToNodeState.get(from.getStatus()));
builder.publicAddresses(from.getAddresses().getPublicAddresses());
builder.privateAddresses(from.getAddresses().getPrivateAddresses());
builder.publicAddresses(Iterables.transform(from.getAddresses().getPublicAddresses(), Address.newAddress2StringFunction()));
builder.privateAddresses(Iterables.transform(from.getAddresses().getPrivateAddresses(), Address.newAddress2StringFunction()));
builder.credentials(credentialStore.get("node#" + from.getId()));
builder.uri(from.getURI());
return builder.build();
}
@ -131,9 +129,9 @@ public class ServerToNodeMetadata implements Function<Server, NodeMetadata> {
return null;
}
protected OperatingSystem parseOperatingSystem(Server from) {
protected Image parseImage(Server from) {
try {
return Iterables.find(images.get(), new FindImageForServer(from)).getOperatingSystem();
return Iterables.find(images.get(), new FindImageForServer(from));
} catch (NoSuchElementException e) {
logger.warn("could not find a matching image for server %s in location %s", from, location);
}

View File

@ -53,8 +53,7 @@ public class NovaCreateNodeWithGroupEncodedIntoName implements CreateNodeWithGro
@Override
public NodeMetadata createNodeWithGroupEncodedIntoName(String group, String name, Template template) {
Server from = client.createServer(name, Integer.parseInt(template.getImage().getProviderId()), Integer
.parseInt(template.getHardware().getProviderId()));
Server from = client.createServer(name, template.getImage().getId(), template.getHardware().getId());
credentialStore.put("node#" + from.getId(), new Credentials("root", from.getAdminPass()));
return serverToNodeMetadata.apply(from);
}

View File

@ -47,7 +47,7 @@ public class NovaLifeCycleStrategy implements RebootNodeStrategy, SuspendNodeStr
public NodeMetadata rebootNode(String id) {
int serverId = Integer.parseInt(id);
// if false server wasn't around in the first place
client.rebootServer(serverId, RebootType.HARD);
client.rebootServer(serverId, RebootType.SOFT);
return getNode.getNode(id);
}

View File

@ -0,0 +1,98 @@
/**
*
* Copyright (C) 2011 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* 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.openstack.nova.domain;
import com.google.common.base.Function;
import com.google.gson.annotations.SerializedName;
import javax.annotation.Nullable;
/**
* @author Dmitri Babaev
*/
public class Address {
@SerializedName("addr")
private String address;
private int version;
//for de-serialization
@SuppressWarnings("unused")
private Address() {
}
public Address(String address, int version) {
this.address = address;
this.version = version;
}
public String getAddress() {
return address;
}
public int getVersion() {
return version;
}
@Override
public String toString() {
return address;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Address address1 = (Address) o;
if (version != address1.version) return false;
if (address != null ? !address.equals(address1.address) : address1.address != null) return false;
return true;
}
@Override
public int hashCode() {
int result = address != null ? address.hashCode() : 0;
result = 31 * result + version;
return result;
}
public static Function<Address, String> newAddress2StringFunction() {
return new Function<Address, String>() {
@Override
public String apply(@Nullable Address input) {
return input.getAddress();
}
};
}
public static Address valueOf(String address) {
return new Address(address, address.startsWith("::") ? 6 : 4);
}
public static Function<String, Address> newString2AddressFunction() {
return new Function<String, Address>() {
@Override
public Address apply(@Nullable String input) {
return valueOf(input);
}
};
}
}

View File

@ -30,31 +30,31 @@ import com.google.gson.annotations.SerializedName;
public class Addresses {
@SerializedName("public")
private Set<String> publicAddresses = Sets.newLinkedHashSet();
private Set<Address> publicAddresses = Sets.newLinkedHashSet();
@SerializedName("private")
private Set<String> privateAddresses = Sets.newLinkedHashSet();
private Set<Address> privateAddresses = Sets.newLinkedHashSet();
public Addresses() {
}
public Addresses(Set<String> publicAddresses, Set<String> privateAddresses) {
public Addresses(Set<Address> publicAddresses, Set<Address> privateAddresses) {
this.publicAddresses = publicAddresses;
this.privateAddresses = privateAddresses;
}
public void setPublicAddresses(Set<String> publicAddresses) {
public void setPublicAddresses(Set<Address> publicAddresses) {
this.publicAddresses = publicAddresses;
}
public Set<String> getPublicAddresses() {
public Set<Address> getPublicAddresses() {
return publicAddresses;
}
public void setPrivateAddresses(Set<String> privateAddresses) {
public void setPrivateAddresses(Set<Address> privateAddresses) {
this.privateAddresses = privateAddresses;
}
public Set<String> getPrivateAddresses() {
public Set<Address> getPrivateAddresses() {
return privateAddresses;
}

View File

@ -25,7 +25,7 @@ package org.jclouds.openstack.nova.domain;
*
* @author Adrian Cole
*/
public class Flavor {
public class Flavor extends Resource {
public Flavor() {
}

View File

@ -18,7 +18,11 @@
*/
package org.jclouds.openstack.nova.domain;
import com.google.common.collect.Maps;
import java.util.Collections;
import java.util.Date;
import java.util.Map;
/**
* An image is a collection of files used to create or rebuild a server. Rackspace provides a number
@ -28,16 +32,27 @@ import java.util.Date;
*
* @author Adrian Cole
*/
public class Image {
public class Image extends Resource {
private Date created;
private int id;
private String name;
private Integer progress;
private Integer serverId;
private String serverRef;
private ImageStatus status;
private Map<String, String> metadata = Maps.newHashMap();
private Date created;
private Date updated;
public Date getCreated() {
return created;
}
public Date getUpdated() {
return updated;
}
public Image() {
}
@ -46,13 +61,6 @@ public class Image {
this.name = name;
}
public void setCreated(Date created) {
this.created = created;
}
public Date getCreated() {
return created;
}
public void setId(int id) {
this.id = id;
@ -78,12 +86,12 @@ public class Image {
return progress;
}
public void setServerId(Integer serverId) {
this.serverId = serverId;
public void setServerRef(String serverRef) {
this.serverRef = serverRef;
}
public Integer getServerId() {
return serverId;
public String getServerRef() {
return serverRef;
}
public void setStatus(ImageStatus status) {
@ -94,15 +102,17 @@ public class Image {
return status;
}
public void setUpdated(Date updated) {
this.updated = updated;
public Map<String, String> getMetadata() {
return Collections.unmodifiableMap(metadata);
}
public Date getUpdated() {
return updated;
public void setMetadata(Map<String, String> metadata) {
this.metadata = Maps.newHashMap(metadata);
}
/**
* note that this ignores the create time
* note that this ignores some fields
*/
@Override
public int hashCode() {
@ -110,12 +120,12 @@ public class Image {
int result = 1;
result = prime * result + id;
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((serverId == null) ? 0 : serverId.hashCode());
result = prime * result + ((serverRef == null) ? 0 : serverRef.hashCode());
return result;
}
/**
* note that this ignores the serverid and create time.
* note that this ignores some fields
*/
@Override
public boolean equals(Object obj) {
@ -138,8 +148,8 @@ public class Image {
@Override
public String toString() {
return "Image [created=" + created + ", id=" + id + ", name=" + name + ", serverId="
+ serverId + "]";
return "Image [created=" + getCreated() + ", id=" + id + ", name=" + name + ", serverRef="
+ serverRef + "]";
}
}

View File

@ -0,0 +1,52 @@
/**
*
* Copyright (C) 2011 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* 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.openstack.nova.domain;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import java.util.Map;
import com.google.common.base.Functions;
import com.google.common.collect.Lists;
/**
* @author Dmitri Babaev
*/
public class Resource {
private List<Map<String, String>> links = Lists.newArrayList();
public URI getURI() {
for (Map<String, String> linkProperties : links) {
try {
if (!Functions.forMap(linkProperties, "").apply("rel").equals("bookmark"))
continue;
if (!Functions.forMap(linkProperties, "").apply("type").contains("json"))
continue;
return new URI(linkProperties.get("href"));
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
}
throw new IllegalStateException("URI is not available");
}
}

View File

@ -18,17 +18,18 @@
*/
package org.jclouds.openstack.nova.domain;
import java.util.Map;
import com.google.common.collect.Maps;
import java.util.Date;
import java.util.Map;
/**
* A server is a virtual machine instance in the OpenStack Nova system. Flavor and image are
* requisite elements when creating a server.
*
* @author Adrian Cole
*/
public class Server {
public class Server extends Resource {
private int id;
private String name;
@ -36,10 +37,22 @@ public class Server {
private Addresses addresses;
private String adminPass;
private Integer flavorId;
private String flavorRef;
private String hostId;
private Integer imageId;
private Integer sharedIpGroupId;
private String imageRef;
private String affinityId;
private Date created;
private Date updated;
public Date getCreated() {
return created;
}
public Date getUpdated() {
return updated;
}
private Integer progress;
private ServerStatus status;
@ -52,6 +65,14 @@ public class Server {
this.name = name;
}
public String getAffinityId() {
return affinityId;
}
public void setAffinityId(String affinityId) {
this.affinityId = affinityId;
}
public void setMetadata(Map<String, String> metadata) {
this.metadata = metadata;
}
@ -76,12 +97,12 @@ public class Server {
return adminPass;
}
public void setFlavorId(Integer flavorId) {
this.flavorId = flavorId;
public void setFlavorRef(String flavorRef) {
this.flavorRef = flavorRef;
}
public Integer getFlavorId() {
return flavorId;
public String getFlavorRef() {
return flavorRef;
}
public void setHostId(String hostId) {
@ -104,12 +125,12 @@ public class Server {
return id;
}
public void setImageId(Integer imageId) {
this.imageId = imageId;
public void setImageRef(String imageRef) {
this.imageRef = imageRef;
}
public Integer getImageId() {
return imageId;
public String getImageRef() {
return imageRef;
}
public String getName() {
@ -124,14 +145,6 @@ public class Server {
return progress;
}
public void setSharedIpGroupId(Integer sharedIpGroupId) {
this.sharedIpGroupId = sharedIpGroupId;
}
public Integer getSharedIpGroupId() {
return sharedIpGroupId;
}
public void setStatus(ServerStatus status) {
this.status = status;
}
@ -150,13 +163,12 @@ public class Server {
int result = 1;
result = prime * result + ((addresses == null) ? 0 : addresses.hashCode());
result = prime * result + ((adminPass == null) ? 0 : adminPass.hashCode());
result = prime * result + ((flavorId == null) ? 0 : flavorId.hashCode());
result = prime * result + ((flavorRef == null) ? 0 : flavorRef.hashCode());
result = prime * result + ((hostId == null) ? 0 : hostId.hashCode());
result = prime * result + id;
result = prime * result + ((imageId == null) ? 0 : imageId.hashCode());
result = prime * result + ((imageRef == null) ? 0 : imageRef.hashCode());
result = prime * result + ((metadata == null) ? 0 : metadata.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((sharedIpGroupId == null) ? 0 : sharedIpGroupId.hashCode());
return result;
}
@ -179,10 +191,10 @@ public class Server {
return false;
} else if (!adminPass.equals(other.adminPass))
return false;
if (flavorId == null) {
if (other.flavorId != null)
if (flavorRef == null) {
if (other.flavorRef != null)
return false;
} else if (!flavorId.equals(other.flavorId))
} else if (!flavorRef.equals(other.flavorRef))
return false;
if (hostId == null) {
if (other.hostId != null)
@ -191,10 +203,10 @@ public class Server {
return false;
if (id != other.id)
return false;
if (imageId == null) {
if (other.imageId != null)
if (imageRef == null) {
if (other.imageRef != null)
return false;
} else if (!imageId.equals(other.imageId))
} else if (!imageRef.equals(other.imageRef))
return false;
if (metadata == null) {
if (other.metadata != null)
@ -206,11 +218,6 @@ public class Server {
return false;
} else if (!name.equals(other.name))
return false;
if (sharedIpGroupId == null) {
if (other.sharedIpGroupId != null)
return false;
} else if (!sharedIpGroupId.equals(other.sharedIpGroupId))
return false;
return true;
}
@ -220,10 +227,9 @@ public class Server {
@Override
public String toString() {
return "Server [addresses=" + addresses + ", adminPass=" + adminPass + ", flavorId="
+ flavorId + ", hostId=" + hostId + ", id=" + id + ", imageId=" + imageId
+ ", metadata=" + metadata + ", name=" + name + ", sharedIpGroupId="
+ sharedIpGroupId + "]";
return "Server [addresses=" + addresses + ", adminPass=" + adminPass + ", flavorRef="
+ flavorRef + ", hostId=" + hostId + ", id=" + id + ", imageRef=" + imageRef
+ ", metadata=" + metadata + ", name=" + name + "]";
}
}

View File

@ -37,7 +37,7 @@ package org.jclouds.openstack.nova.domain;
*/
public enum ServerStatus {
ACTIVE, SUSPENDED, DELETED, QUEUE_RESIZE, PREP_RESIZE, RESIZE, VERIFY_RESIZE, QUEUE_MOVE, PREP_MOVE, MOVE, VERIFY_MOVE, RESCUE, ERROR, BUILD, RESTORING, PASSWORD, REBUILD, DELETE_IP, SHARE_IP_NO_CONFIG, SHARE_IP, REBOOT, HARD_REBOOT, UNKNOWN, UNRECOGNIZED;
ACTIVE, SUSPENDED, QUEUE_RESIZE, PREP_RESIZE, RESIZE, VERIFY_RESIZE, RESCUE, BUILD, PASSWORD, REBUILD, REBOOT, HARD_REBOOT, UNKNOWN, DELETE_IP, UNRECOGNIZED, DELETED;
public String value() {
return name();

View File

@ -26,9 +26,11 @@ import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import javax.inject.Inject;
import org.jclouds.encryption.internal.Base64;
import org.jclouds.http.HttpRequest;
import org.jclouds.openstack.nova.domain.Addresses;
import org.jclouds.rest.MapBinder;
import org.jclouds.rest.binders.BindToJsonPayload;
import com.google.common.collect.ImmutableMap;
@ -40,7 +42,9 @@ import com.google.common.collect.Maps;
* @author Adrian Cole
*
*/
public class CreateServerOptions extends BindToJsonPayload {
public class CreateServerOptions implements MapBinder {
@Inject
private BindToJsonPayload jsonBinder;
static class File {
private final String path;
@ -50,11 +54,9 @@ public class CreateServerOptions extends BindToJsonPayload {
this.path = checkNotNull(path, "path");
this.contents = Base64.encodeBytes(checkNotNull(contents, "contents"));
checkArgument(path.getBytes().length < 255, String.format(
"maximum length of path is 255 bytes. Path specified %s is %d bytes", path, path
.getBytes().length));
"maximum length of path is 255 bytes. Path specified %s is %d bytes", path, path.getBytes().length));
checkArgument(contents.length < 10 * 1024, String.format(
"maximum size of the file is 10KB. Contents specified is %d bytes",
contents.length));
"maximum size of the file is 10KB. Contents specified is %d bytes", contents.length));
}
public String getContents() {
@ -70,43 +72,32 @@ public class CreateServerOptions extends BindToJsonPayload {
@SuppressWarnings("unused")
private class ServerRequest {
final String name;
final int imageId;
final int flavorId;
final String imageRef;
final String flavorRef;
Map<String, String> metadata;
List<File> personality;
Integer sharedIpGroupId;
Addresses addresses;
private ServerRequest(String name, int imageId, int flavorId) {
private ServerRequest(String name, String imageRef, String flavorRef) {
this.name = name;
this.imageId = imageId;
this.flavorId = flavorId;
this.imageRef = imageRef;
this.flavorRef = flavorRef;
}
}
private Map<String, String> metadata = Maps.newHashMap();
private List<File> files = Lists.newArrayList();
private Integer sharedIpGroupId;
private String publicIp;
@Override
public <R extends HttpRequest> R bindToRequest(R request, Map<String, String> postParams) {
ServerRequest server = new ServerRequest(checkNotNull(postParams.get("name"),
"name parameter not present"), Integer.parseInt(checkNotNull(postParams
.get("imageId"), "imageId parameter not present")), Integer.parseInt(checkNotNull(
postParams.get("flavorId"), "flavorId parameter not present")));
ServerRequest server = new ServerRequest(checkNotNull(postParams.get("name"), "name parameter not present"),
checkNotNull(postParams.get("imageRef"), "imageRef parameter not present"), checkNotNull(postParams
.get("flavorRef"), "flavorRef parameter not present"));
if (metadata.size() > 0)
server.metadata = metadata;
if (files.size() > 0)
server.personality = files;
if (sharedIpGroupId != null)
server.sharedIpGroupId = this.sharedIpGroupId;
if (publicIp != null) {
server.addresses = new Addresses();
server.addresses.getPublicAddresses().add(publicIp);
server.addresses.setPrivateAddresses(null);
}
return bindToRequest(request, ImmutableMap.of("server", server));
}
@ -131,29 +122,6 @@ public class CreateServerOptions extends BindToJsonPayload {
return this;
}
/**
* A shared IP group is a collection of servers that can share IPs with other members of the
* group. Any server in a group can share one or more public IPs with any other server in the
* group. With the exception of the first server in a shared IP group, servers must be launched
* into shared IP groups. A server may only be a member of one shared IP group.
*
* <p/>
* Servers in the same shared IP group can share public IPs for various high availability and
* load balancing configurations. To launch an HA server, include the optional sharedIpGroupId
* element and the server will be launched into that shared IP group.
* <p />
*
* Note: sharedIpGroupId is an optional parameter and for optimal performance, should ONLY be
* specified when intending to share IPs between servers.
*
* @see #withSharedIp(String)
*/
public CreateServerOptions withSharedIpGroup(int id) {
checkArgument(id > 0, "id must be positive or zero. was: " + id);
this.sharedIpGroupId = id;
return this;
}
/**
* Custom cloud server metadata can also be supplied at launch time. This metadata is stored in
* the API system where it is retrievable by querying the API for server status. The maximum size
@ -162,46 +130,20 @@ public class CreateServerOptions extends BindToJsonPayload {
*/
public CreateServerOptions withMetadata(Map<String, String> metadata) {
checkNotNull(metadata, "metadata");
checkArgument(metadata.size() <= 5,
"you cannot have more then 5 metadata values. You specified: " + metadata.size());
checkArgument(metadata.size() <= 5, "you cannot have more then 5 metadata values. You specified: "
+ metadata.size());
for (Entry<String, String> entry : metadata.entrySet()) {
checkArgument(entry.getKey().getBytes().length < 255, String.format(
"maximum length of metadata key is 255 bytes. Key specified %s is %d bytes",
entry.getKey(), entry.getKey().getBytes().length));
checkArgument(
entry.getKey().getBytes().length < 255,
String
.format(
"maximum length of metadata value is 255 bytes. Value specified for %s (%s) is %d bytes",
entry.getKey(), entry.getValue(),
entry.getValue().getBytes().length));
"maximum length of metadata key is 255 bytes. Key specified %s is %d bytes", entry.getKey(), entry
.getKey().getBytes().length));
checkArgument(entry.getKey().getBytes().length < 255, String.format(
"maximum length of metadata value is 255 bytes. Value specified for %s (%s) is %d bytes", entry
.getKey(), entry.getValue(), entry.getValue().getBytes().length));
}
this.metadata = metadata;
return this;
}
/**
* Public IP addresses can be shared across multiple servers for use in various high availability
* scenarios. When an IP address is shared to another server, the cloud network restrictions are
* modified to allow each server to listen to and respond on that IP address (you may optionally
* specify that the target server network configuration be modified). Shared IP addresses can be
* used with many standard heartbeat facilities (e.g. keepalived) that monitor for failure and
* manage IP failover.
*
* <p/>
* If you intend to use a shared IP on the server being created and have no need for a separate
* public IP address, you may launch the server into a shared IP group and specify an IP address
* from that shared IP group to be used as its public IP. You can accomplish this by specifying
* the public shared IP address in your request. This is optional and is only valid if
* sharedIpGroupId is also supplied.
*/
public CreateServerOptions withSharedIp(String publicIp) {
checkState(sharedIpGroupId != null,
"sharedIp is invalid unless a shared ip group is specified.");
this.publicIp = checkNotNull(publicIp, "ip");
return this;
}
public static class Builder {
/**
@ -212,14 +154,6 @@ public class CreateServerOptions extends BindToJsonPayload {
return options.withFile(path, contents);
}
/**
* @see CreateServerOptions#withSharedIpGroup(int)
*/
public static CreateServerOptions withSharedIpGroup(int id) {
CreateServerOptions options = new CreateServerOptions();
return options.withSharedIpGroup(id);
}
/**
* @see CreateServerOptions#withMetadata(Map<String, String>)
*/
@ -227,14 +161,10 @@ public class CreateServerOptions extends BindToJsonPayload {
CreateServerOptions options = new CreateServerOptions();
return options.withMetadata(metadata);
}
/**
* @see CreateServerOptions#withSharedIp(String)
*/
public static CreateServerOptions withSharedIp(String publicIp) {
CreateServerOptions options = new CreateServerOptions();
return options.withSharedIp(publicIp);
}
@Override
public <R extends HttpRequest> R bindToRequest(R request, Object input) {
return jsonBinder.bindToRequest(request, input);
}
}

View File

@ -19,10 +19,14 @@
package org.jclouds.openstack.nova.options;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import java.util.Map;
import javax.inject.Inject;
import org.jclouds.http.HttpRequest;
import org.jclouds.rest.MapBinder;
import org.jclouds.rest.binders.BindToJsonPayload;
import com.google.common.collect.ImmutableMap;
@ -34,15 +38,17 @@ import com.google.common.collect.Maps;
* @author Adrian Cole
*
*/
public class RebuildServerOptions extends BindToJsonPayload {
Integer imageId;
public class RebuildServerOptions implements MapBinder {
@Inject
private BindToJsonPayload jsonBinder;
String imageRef;
@Override
public <R extends HttpRequest> R bindToRequest(R request, Map<String, String> postParams) {
Map<String, Integer> image = Maps.newHashMap();
if (imageId != null)
image.put("imageId", imageId);
return super.bindToRequest(request, ImmutableMap.of("rebuild", image));
Map<String, String> image = Maps.newHashMap();
if (imageRef != null)
image.put("imageRef", imageRef);
return jsonBinder.bindToRequest(request, ImmutableMap.of("rebuild", image));
}
@Override
@ -51,24 +57,24 @@ public class RebuildServerOptions extends BindToJsonPayload {
}
/**
*
* @param id
* of the image to rebuild the server with.
* @param ref
* - reference of the image to rebuild the server with.
*/
public RebuildServerOptions withImage(int id) {
checkArgument(id > 0, "server id must be a positive number");
this.imageId = id;
public RebuildServerOptions withImage(String ref) {
checkNotNull(ref, "image reference should not be null");
checkArgument(!ref.isEmpty(), "image reference should not be empty");
this.imageRef = ref;
return this;
}
public static class Builder {
/**
* @see RebuildServerOptions#withImage(int)
* @see RebuildServerOptions#withImage(String)
*/
public static RebuildServerOptions withImage(int id) {
public static RebuildServerOptions withImage(String ref) {
RebuildServerOptions options = new RebuildServerOptions();
return options.withImage(id);
return options.withImage(ref);
}
}
}

View File

@ -18,60 +18,47 @@
*/
package org.jclouds.openstack.nova;
import static org.jclouds.Constants.PROPERTY_API_VERSION;
import static org.jclouds.openstack.nova.options.CreateServerOptions.Builder.withFile;
import static org.jclouds.openstack.nova.options.CreateServerOptions.Builder.withMetadata;
import static org.jclouds.openstack.nova.options.CreateServerOptions.Builder.withSharedIpGroup;
import static org.jclouds.openstack.nova.options.CreateSharedIpGroupOptions.Builder.withServer;
import static org.jclouds.openstack.nova.options.ListOptions.Builder.changesSince;
import static org.jclouds.openstack.nova.options.ListOptions.Builder.withDetails;
import static org.jclouds.openstack.nova.options.RebuildServerOptions.Builder.withImage;
import static org.jclouds.location.reference.LocationConstants.PROPERTY_REGIONS;
import static org.testng.Assert.assertEquals;
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.URI;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.Properties;
import javax.ws.rs.core.MediaType;
import org.jclouds.openstack.nova.config.NovaRestClientModule;
import org.jclouds.openstack.nova.domain.BackupSchedule;
import org.jclouds.openstack.nova.domain.DailyBackup;
import org.jclouds.openstack.nova.domain.RebootType;
import org.jclouds.openstack.nova.domain.WeeklyBackup;
import org.jclouds.openstack.nova.options.CreateServerOptions;
import org.jclouds.openstack.nova.options.CreateSharedIpGroupOptions;
import org.jclouds.openstack.nova.options.ListOptions;
import org.jclouds.openstack.nova.options.RebuildServerOptions;
import com.google.common.collect.ImmutableMap;
import com.google.inject.Module;
import com.google.inject.TypeLiteral;
import org.jclouds.http.HttpRequest;
import org.jclouds.http.RequiresHttp;
import org.jclouds.http.functions.ReleasePayloadAndReturn;
import org.jclouds.http.functions.ReturnFalseOn404;
import org.jclouds.http.functions.ReturnTrueIf2xx;
import org.jclouds.http.functions.UnwrapOnlyJsonValue;
import org.jclouds.openstack.OpenStackAuthAsyncClient.AuthenticationResponse;
import org.jclouds.openstack.TestOpenStackAuthenticationModule;
import org.jclouds.openstack.filters.AddTimestampQuery;
import org.jclouds.openstack.filters.AuthenticateRequest;
import org.jclouds.openstack.nova.config.NovaRestClientModule;
import org.jclouds.openstack.nova.domain.RebootType;
import org.jclouds.openstack.nova.options.CreateServerOptions;
import org.jclouds.openstack.nova.options.ListOptions;
import org.jclouds.openstack.nova.options.RebuildServerOptions;
import org.jclouds.rest.ConfiguresRestClient;
import org.jclouds.rest.RestClientTest;
import org.jclouds.rest.RestContextFactory;
import org.jclouds.rest.RestContextSpec;
import org.jclouds.rest.functions.MapHttp4xxCodesToExceptions;
import org.jclouds.rest.functions.ReturnEmptySetOnNotFoundOr404;
import org.jclouds.rest.functions.ReturnFalseOnNotFoundOr404;
import org.jclouds.rest.functions.ReturnNullOnNotFoundOr404;
import org.jclouds.rest.functions.ReturnVoidOnNotFoundOr404;
import org.jclouds.rest.internal.RestAnnotationProcessor;
import org.testng.annotations.Test;
import com.google.common.collect.ImmutableMap;
import com.google.inject.Module;
import com.google.inject.TypeLiteral;
import javax.ws.rs.core.MediaType;
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.URI;
import java.util.Date;
import java.util.Properties;
import static org.jclouds.Constants.PROPERTY_API_VERSION;
import static org.jclouds.openstack.nova.options.CreateServerOptions.Builder.withFile;
import static org.jclouds.openstack.nova.options.CreateServerOptions.Builder.withMetadata;
import static org.jclouds.openstack.nova.options.ListOptions.Builder.changesSince;
import static org.jclouds.openstack.nova.options.ListOptions.Builder.withDetails;
import static org.jclouds.openstack.nova.options.RebuildServerOptions.Builder.withImage;
import static org.testng.Assert.assertEquals;
/**
* Tests behavior of {@code NovaAsyncClient}
@ -85,14 +72,15 @@ public class NovaAsyncClientTest extends RestClientTest<NovaAsyncClient> {
private static final Class<? extends CreateServerOptions[]> createServerOptionsVarargsClass = new CreateServerOptions[]{}
.getClass();
@Test
public void testCreateServer() throws IOException, SecurityException, NoSuchMethodException {
Method method = NovaAsyncClient.class.getMethod("createServer", String.class, int.class, int.class,
Method method = NovaAsyncClient.class.getMethod("createServer", String.class, String.class, String.class,
createServerOptionsVarargsClass);
HttpRequest request = processor.createRequest(method, "ralphie", 2, 1);
assertRequestLineEquals(request, "POST http://serverManagementUrl/servers?format=json HTTP/1.1");
assertRequestLineEquals(request, "POST http://endpoint/vapiversion/servers?format=json HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Accept: application/json\n");
assertPayloadEquals(request, "{\"server\":{\"name\":\"ralphie\",\"imageId\":2,\"flavorId\":1}}",
assertPayloadEquals(request, "{\"server\":{\"name\":\"ralphie\",\"imageRef\":\"2\",\"flavorRef\":\"1\"}}",
"application/json", false);
assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class);
@ -103,35 +91,18 @@ public class NovaAsyncClientTest extends RestClientTest<NovaAsyncClient> {
}
public void testCreateServerWithIpGroup() throws IOException, SecurityException, NoSuchMethodException {
Method method = NovaAsyncClient.class.getMethod("createServer", String.class, int.class, int.class,
createServerOptionsVarargsClass);
HttpRequest request = processor.createRequest(method, "ralphie", 2, 1, withSharedIpGroup(2));
assertRequestLineEquals(request, "POST http://serverManagementUrl/servers?format=json HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Accept: application/json\n");
assertPayloadEquals(request,
"{\"server\":{\"name\":\"ralphie\",\"imageId\":2,\"flavorId\":1,\"sharedIpGroupId\":2}}",
"application/json", false);
assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class);
assertSaxResponseParserClassEquals(method, null);
assertExceptionParserClassEquals(method, null);
checkFilters(request);
}
@Test
public void testCreateServerWithFile() throws IOException, SecurityException, NoSuchMethodException {
Method method = NovaAsyncClient.class.getMethod("createServer", String.class, int.class, int.class,
Method method = NovaAsyncClient.class.getMethod("createServer", String.class, String.class, String.class,
createServerOptionsVarargsClass);
HttpRequest request = processor
.createRequest(method, "ralphie", 2, 1, withFile("/etc/jclouds", "foo".getBytes()));
assertRequestLineEquals(request, "POST http://serverManagementUrl/servers?format=json HTTP/1.1");
assertRequestLineEquals(request, "POST http://endpoint/vapiversion/servers?format=json HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Accept: application/json\n");
assertPayloadEquals(
request,
"{\"server\":{\"name\":\"ralphie\",\"imageId\":2,\"flavorId\":1,\"personality\":[{\"path\":\"/etc/jclouds\",\"contents\":\"Zm9v\"}]}}",
"{\"server\":{\"name\":\"ralphie\",\"imageRef\":\"2\",\"flavorRef\":\"1\",\"personality\":[{\"path\":\"/etc/jclouds\",\"contents\":\"Zm9v\"}]}}",
"application/json", false);
assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class);
@ -142,16 +113,17 @@ public class NovaAsyncClientTest extends RestClientTest<NovaAsyncClient> {
}
@Test
public void testCreateServerWithMetadata() throws IOException, SecurityException, NoSuchMethodException {
Method method = NovaAsyncClient.class.getMethod("createServer", String.class, int.class, int.class,
Method method = NovaAsyncClient.class.getMethod("createServer", String.class, String.class, String.class,
createServerOptionsVarargsClass);
HttpRequest request = processor.createRequest(method, "ralphie", 2, 1,
withMetadata(ImmutableMap.of("foo", "bar")));
assertRequestLineEquals(request, "POST http://serverManagementUrl/servers?format=json HTTP/1.1");
assertRequestLineEquals(request, "POST http://endpoint/vapiversion/servers?format=json HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Accept: application/json\n");
assertPayloadEquals(request,
"{\"server\":{\"name\":\"ralphie\",\"imageId\":2,\"flavorId\":1,\"metadata\":{\"foo\":\"bar\"}}}",
"{\"server\":{\"name\":\"ralphie\",\"imageRef\":\"2\",\"flavorRef\":\"1\",\"metadata\":{\"foo\":\"bar\"}}}",
"application/json", false);
assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class);
@ -162,32 +134,11 @@ public class NovaAsyncClientTest extends RestClientTest<NovaAsyncClient> {
}
public void testCreateServerWithIpGroupAndSharedIp() throws IOException, SecurityException, NoSuchMethodException,
UnknownHostException {
Method method = NovaAsyncClient.class.getMethod("createServer", String.class, int.class, int.class,
createServerOptionsVarargsClass);
HttpRequest request = processor.createRequest(method, "ralphie", 2, 1,
withSharedIpGroup(2).withSharedIp("127.0.0.1"));
assertRequestLineEquals(request, "POST http://serverManagementUrl/servers?format=json HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Accept: application/json\n");
assertPayloadEquals(
request,
"{\"server\":{\"name\":\"ralphie\",\"imageId\":2,\"flavorId\":1,\"sharedIpGroupId\":2,\"addresses\":{\"public\":[\"127.0.0.1\"]}}}",
"application/json", false);
assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class);
assertSaxResponseParserClassEquals(method, null);
assertExceptionParserClassEquals(method, null);
checkFilters(request);
}
public void testDeleteImage() throws IOException, SecurityException, NoSuchMethodException {
Method method = NovaAsyncClient.class.getMethod("deleteImage", int.class);
HttpRequest request = processor.createRequest(method, 2);
assertRequestLineEquals(request, "DELETE http://serverManagementUrl/images/2 HTTP/1.1");
assertRequestLineEquals(request, "DELETE http://endpoint/vapiversion/images/2 HTTP/1.1");
assertNonPayloadHeadersEqual(request, "");
assertPayloadEquals(request, null, null, false);
@ -202,7 +153,7 @@ public class NovaAsyncClientTest extends RestClientTest<NovaAsyncClient> {
Method method = NovaAsyncClient.class.getMethod("listServers", listOptionsVarargsClass);
HttpRequest request = processor.createRequest(method);
assertRequestLineEquals(request, "GET http://serverManagementUrl/servers?format=json HTTP/1.1");
assertRequestLineEquals(request, "GET http://endpoint/vapiversion/servers?format=json HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Accept: application/json\n");
assertPayloadEquals(request, null, null, false);
@ -220,7 +171,7 @@ public class NovaAsyncClientTest extends RestClientTest<NovaAsyncClient> {
HttpRequest request = processor.createRequest(method, changesSince(now).maxResults(1).startAt(2));
assertRequestLineEquals(request,
"GET http://serverManagementUrl/servers?format=json&changes-since=10000&limit=1&offset=2 HTTP/1.1");
"GET http://endpoint/vapiversion/servers?format=json&changes-since=10000&limit=1&offset=2 HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Accept: application/json\n");
assertPayloadEquals(request, null, null, false);
@ -235,7 +186,7 @@ public class NovaAsyncClientTest extends RestClientTest<NovaAsyncClient> {
Method method = NovaAsyncClient.class.getMethod("listServers", listOptionsVarargsClass);
HttpRequest request = processor.createRequest(method, withDetails());
assertRequestLineEquals(request, "GET http://serverManagementUrl/servers/detail?format=json HTTP/1.1");
assertRequestLineEquals(request, "GET http://endpoint/vapiversion/servers/detail?format=json HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Accept: application/json\n");
assertPayloadEquals(request, null, null, false);
@ -250,7 +201,7 @@ public class NovaAsyncClientTest extends RestClientTest<NovaAsyncClient> {
Method method = NovaAsyncClient.class.getMethod("getServer", int.class);
HttpRequest request = processor.createRequest(method, 2);
assertRequestLineEquals(request, "GET http://serverManagementUrl/servers/2?format=json HTTP/1.1");
assertRequestLineEquals(request, "GET http://endpoint/vapiversion/servers/2?format=json HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Accept: application/json\n");
assertPayloadEquals(request, null, null, false);
@ -265,7 +216,7 @@ public class NovaAsyncClientTest extends RestClientTest<NovaAsyncClient> {
Method method = NovaAsyncClient.class.getMethod("listFlavors", listOptionsVarargsClass);
HttpRequest request = processor.createRequest(method);
assertRequestLineEquals(request, "GET http://serverManagementUrl/flavors?format=json HTTP/1.1");
assertRequestLineEquals(request, "GET http://endpoint/vapiversion/flavors?format=json HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Accept: application/json\n");
assertPayloadEquals(request, null, null, false);
@ -281,7 +232,7 @@ public class NovaAsyncClientTest extends RestClientTest<NovaAsyncClient> {
HttpRequest request = processor.createRequest(method, changesSince(now).maxResults(1).startAt(2));
assertRequestLineEquals(request,
"GET http://serverManagementUrl/flavors?format=json&changes-since=10000&limit=1&offset=2 HTTP/1.1");
"GET http://endpoint/vapiversion/flavors?format=json&changes-since=10000&limit=1&offset=2 HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Accept: application/json\n");
assertPayloadEquals(request, null, null, false);
@ -296,7 +247,7 @@ public class NovaAsyncClientTest extends RestClientTest<NovaAsyncClient> {
Method method = NovaAsyncClient.class.getMethod("listFlavors", listOptionsVarargsClass);
HttpRequest request = processor.createRequest(method, withDetails());
assertRequestLineEquals(request, "GET http://serverManagementUrl/flavors/detail?format=json HTTP/1.1");
assertRequestLineEquals(request, "GET http://endpoint/vapiversion/flavors/detail?format=json HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Accept: application/json\n");
assertPayloadEquals(request, null, null, false);
@ -312,7 +263,7 @@ public class NovaAsyncClientTest extends RestClientTest<NovaAsyncClient> {
HttpRequest request = processor.createRequest(method, withDetails().changesSince(now).maxResults(1).startAt(2));
assertRequestLineEquals(request,
"GET http://serverManagementUrl/flavors/detail?format=json&changes-since=10000&limit=1&offset=2 HTTP/1.1");
"GET http://endpoint/vapiversion/flavors/detail?format=json&changes-since=10000&limit=1&offset=2 HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Accept: application/json\n");
assertPayloadEquals(request, null, null, false);
@ -327,7 +278,7 @@ public class NovaAsyncClientTest extends RestClientTest<NovaAsyncClient> {
Method method = NovaAsyncClient.class.getMethod("getFlavor", int.class);
HttpRequest request = processor.createRequest(method, 2);
assertRequestLineEquals(request, "GET http://serverManagementUrl/flavors/2?format=json HTTP/1.1");
assertRequestLineEquals(request, "GET http://endpoint/vapiversion/flavors/2?format=json HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Accept: application/json\n");
assertPayloadEquals(request, null, null, false);
@ -342,7 +293,7 @@ public class NovaAsyncClientTest extends RestClientTest<NovaAsyncClient> {
Method method = NovaAsyncClient.class.getMethod("listImages", listOptionsVarargsClass);
HttpRequest request = processor.createRequest(method);
assertRequestLineEquals(request, "GET http://serverManagementUrl/images?format=json HTTP/1.1");
assertRequestLineEquals(request, "GET http://endpoint/vapiversion/images?format=json HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Accept: application/json\n");
assertPayloadEquals(request, null, null, false);
@ -357,7 +308,7 @@ public class NovaAsyncClientTest extends RestClientTest<NovaAsyncClient> {
Method method = NovaAsyncClient.class.getMethod("listImages", listOptionsVarargsClass);
HttpRequest request = processor.createRequest(method, withDetails());
assertRequestLineEquals(request, "GET http://serverManagementUrl/images/detail?format=json HTTP/1.1");
assertRequestLineEquals(request, "GET http://endpoint/vapiversion/images/detail?format=json HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Accept: application/json\n");
assertPayloadEquals(request, null, null, false);
@ -373,7 +324,7 @@ public class NovaAsyncClientTest extends RestClientTest<NovaAsyncClient> {
HttpRequest request = processor.createRequest(method, changesSince(now).maxResults(1).startAt(2));
assertRequestLineEquals(request,
"GET http://serverManagementUrl/images?format=json&changes-since=10000&limit=1&offset=2 HTTP/1.1");
"GET http://endpoint/vapiversion/images?format=json&changes-since=10000&limit=1&offset=2 HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Accept: application/json\n");
assertPayloadEquals(request, null, null, false);
@ -389,7 +340,7 @@ public class NovaAsyncClientTest extends RestClientTest<NovaAsyncClient> {
HttpRequest request = processor.createRequest(method, withDetails().changesSince(now).maxResults(1).startAt(2));
assertRequestLineEquals(request,
"GET http://serverManagementUrl/images/detail?format=json&changes-since=10000&limit=1&offset=2 HTTP/1.1");
"GET http://endpoint/vapiversion/images/detail?format=json&changes-since=10000&limit=1&offset=2 HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Accept: application/json\n");
assertPayloadEquals(request, null, null, false);
@ -404,7 +355,7 @@ public class NovaAsyncClientTest extends RestClientTest<NovaAsyncClient> {
Method method = NovaAsyncClient.class.getMethod("getImage", int.class);
HttpRequest request = processor.createRequest(method, 2);
assertRequestLineEquals(request, "GET http://serverManagementUrl/images/2?format=json HTTP/1.1");
assertRequestLineEquals(request, "GET http://endpoint/vapiversion/images/2?format=json HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Accept: application/json\n");
assertPayloadEquals(request, null, null, false);
@ -419,7 +370,7 @@ public class NovaAsyncClientTest extends RestClientTest<NovaAsyncClient> {
Method method = NovaAsyncClient.class.getMethod("deleteServer", int.class);
HttpRequest request = processor.createRequest(method, 2);
assertRequestLineEquals(request, "DELETE http://serverManagementUrl/servers/2 HTTP/1.1");
assertRequestLineEquals(request, "DELETE http://endpoint/vapiversion/servers/2 HTTP/1.1");
assertNonPayloadHeadersEqual(request, "");
assertPayloadEquals(request, null, null, false);
@ -430,101 +381,13 @@ public class NovaAsyncClientTest extends RestClientTest<NovaAsyncClient> {
checkFilters(request);
}
public void testShareIpNoConfig() throws IOException, SecurityException, NoSuchMethodException, UnknownHostException {
Method method = NovaAsyncClient.class.getMethod("shareIp", String.class, int.class, int.class,
boolean.class);
HttpRequest request = processor.createRequest(method, "127.0.0.1", 2, 3, false);
assertRequestLineEquals(request, "PUT http://serverManagementUrl/servers/2/ips/public/127.0.0.1 HTTP/1.1");
assertNonPayloadHeadersEqual(request, "");
assertPayloadEquals(request, "{\"shareIp\":{\"sharedIpGroupId\":3,\"configureServer\":false}}",
MediaType.APPLICATION_JSON, false);
assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class);
assertSaxResponseParserClassEquals(method, null);
assertExceptionParserClassEquals(method, null);
checkFilters(request);
}
public void testShareIpConfig() throws IOException, SecurityException, NoSuchMethodException, UnknownHostException {
Method method = NovaAsyncClient.class.getMethod("shareIp", String.class, int.class, int.class,
boolean.class);
HttpRequest request = processor.createRequest(method, "127.0.0.1", 2, 3, true);
assertRequestLineEquals(request, "PUT http://serverManagementUrl/servers/2/ips/public/127.0.0.1 HTTP/1.1");
assertNonPayloadHeadersEqual(request, "");
assertPayloadEquals(request, "{\"shareIp\":{\"sharedIpGroupId\":3,\"configureServer\":true}}",
MediaType.APPLICATION_JSON, false);
assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class);
assertSaxResponseParserClassEquals(method, null);
assertExceptionParserClassEquals(method, null);
checkFilters(request);
}
public void testUnshareIpNoConfig() throws IOException, SecurityException, NoSuchMethodException,
UnknownHostException {
Method method = NovaAsyncClient.class.getMethod("unshareIp", String.class, int.class);
HttpRequest request = processor.createRequest(method, "127.0.0.1", 2, 3, false);
assertRequestLineEquals(request, "DELETE http://serverManagementUrl/servers/2/ips/public/127.0.0.1 HTTP/1.1");
assertNonPayloadHeadersEqual(request, "");
assertPayloadEquals(request, null, null, false);
assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class);
assertSaxResponseParserClassEquals(method, null);
assertExceptionParserClassEquals(method, ReturnVoidOnNotFoundOr404.class);
checkFilters(request);
}
public void testReplaceBackupSchedule() throws IOException, SecurityException, NoSuchMethodException {
Method method = NovaAsyncClient.class.getMethod("replaceBackupSchedule", int.class, BackupSchedule.class);
HttpRequest request = processor.createRequest(method, 2, new BackupSchedule(WeeklyBackup.MONDAY,
DailyBackup.H_0800_1000, true));
assertRequestLineEquals(request, "POST http://serverManagementUrl/servers/2/backup_schedule HTTP/1.1");
assertNonPayloadHeadersEqual(request, "");
assertPayloadEquals(request,
"{\"backupSchedule\":{\"daily\":\"H_0800_1000\",\"enabled\":true,\"weekly\":\"MONDAY\"}}",
MediaType.APPLICATION_JSON, false);
assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class);
assertSaxResponseParserClassEquals(method, null);
assertExceptionParserClassEquals(method, ReturnFalseOn404.class);
checkFilters(request);
}
public void testDeleteBackupSchedule() throws IOException, SecurityException, NoSuchMethodException {
Method method = NovaAsyncClient.class.getMethod("deleteBackupSchedule", int.class);
HttpRequest request = processor.createRequest(method, 2);
assertRequestLineEquals(request, "DELETE http://serverManagementUrl/servers/2/backup_schedule HTTP/1.1");
assertNonPayloadHeadersEqual(request, "");
assertPayloadEquals(request, null, MediaType.APPLICATION_JSON, false);
assertResponseParserClassEquals(method, request, ReturnTrueIf2xx.class);
assertSaxResponseParserClassEquals(method, null);
assertExceptionParserClassEquals(method, ReturnFalseOnNotFoundOr404.class);
checkFilters(request);
}
public void testChangeAdminPass() throws IOException, SecurityException, NoSuchMethodException {
Method method = NovaAsyncClient.class.getMethod("changeAdminPass", int.class, String.class);
HttpRequest request = processor.createRequest(method, 2, "foo");
assertRequestLineEquals(request, "PUT http://serverManagementUrl/servers/2 HTTP/1.1");
assertRequestLineEquals(request, "POST http://endpoint/vapiversion/servers/2/action HTTP/1.1");
assertNonPayloadHeadersEqual(request, "");
assertPayloadEquals(request, "{\"server\":{\"adminPass\":\"foo\"}}", MediaType.APPLICATION_JSON, false);
assertPayloadEquals(request, "{\"changePassword\":{\"adminPass\":\"foo\"}}", MediaType.APPLICATION_JSON, false);
assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class);
assertSaxResponseParserClassEquals(method, null);
@ -538,7 +401,7 @@ public class NovaAsyncClientTest extends RestClientTest<NovaAsyncClient> {
Method method = NovaAsyncClient.class.getMethod("renameServer", int.class, String.class);
HttpRequest request = processor.createRequest(method, 2, "foo");
assertRequestLineEquals(request, "PUT http://serverManagementUrl/servers/2 HTTP/1.1");
assertRequestLineEquals(request, "PUT http://endpoint/vapiversion/servers/2 HTTP/1.1");
assertNonPayloadHeadersEqual(request, "");
assertPayloadEquals(request, "{\"server\":{\"name\":\"foo\"}}", MediaType.APPLICATION_JSON, false);
@ -550,140 +413,11 @@ public class NovaAsyncClientTest extends RestClientTest<NovaAsyncClient> {
}
public void testListSharedIpGroups() throws IOException, SecurityException, NoSuchMethodException {
Method method = NovaAsyncClient.class.getMethod("listSharedIpGroups", listOptionsVarargsClass);
HttpRequest request = processor.createRequest(method);
assertRequestLineEquals(request, "GET http://serverManagementUrl/shared_ip_groups?format=json HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Accept: application/json\n");
assertPayloadEquals(request, null, null, false);
assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class);
assertSaxResponseParserClassEquals(method, null);
assertExceptionParserClassEquals(method, ReturnEmptySetOnNotFoundOr404.class);
checkFilters(request);
}
public void testListSharedIpGroupsOptions() throws IOException, SecurityException, NoSuchMethodException {
Method method = NovaAsyncClient.class.getMethod("listSharedIpGroups", listOptionsVarargsClass);
HttpRequest request = processor.createRequest(method, changesSince(now).maxResults(1).startAt(2));
assertRequestLineEquals(request,
"GET http://serverManagementUrl/shared_ip_groups?format=json&changes-since=10000&limit=1&offset=2 HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Accept: application/json\n");
assertPayloadEquals(request, null, null, false);
assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class);
assertSaxResponseParserClassEquals(method, null);
assertExceptionParserClassEquals(method, ReturnEmptySetOnNotFoundOr404.class);
checkFilters(request);
}
public void testListSharedIpGroupsDetail() throws IOException, SecurityException, NoSuchMethodException {
Method method = NovaAsyncClient.class.getMethod("listSharedIpGroups", listOptionsVarargsClass);
HttpRequest request = processor.createRequest(method, withDetails());
assertRequestLineEquals(request, "GET http://serverManagementUrl/shared_ip_groups/detail?format=json HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Accept: application/json\n");
assertPayloadEquals(request, null, null, false);
assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class);
assertSaxResponseParserClassEquals(method, null);
assertExceptionParserClassEquals(method, ReturnEmptySetOnNotFoundOr404.class);
checkFilters(request);
}
public void testListSharedIpGroupsDetailOptions() throws IOException, SecurityException, NoSuchMethodException {
Method method = NovaAsyncClient.class.getMethod("listSharedIpGroups", listOptionsVarargsClass);
HttpRequest request = processor.createRequest(method, withDetails().changesSince(now).maxResults(1).startAt(2));
assertRequestLineEquals(request,
"GET http://serverManagementUrl/shared_ip_groups/detail?format=json&changes-since=10000&limit=1&offset=2 HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Accept: application/json\n");
assertPayloadEquals(request, null, null, false);
assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class);
assertSaxResponseParserClassEquals(method, null);
assertExceptionParserClassEquals(method, ReturnEmptySetOnNotFoundOr404.class);
checkFilters(request);
}
public void testGetSharedIpGroup() throws IOException, SecurityException, NoSuchMethodException {
Method method = NovaAsyncClient.class.getMethod("getSharedIpGroup", int.class);
HttpRequest request = processor.createRequest(method, 2);
assertRequestLineEquals(request, "GET http://serverManagementUrl/shared_ip_groups/2?format=json HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Accept: application/json\n");
assertPayloadEquals(request, null, null, false);
assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class);
assertSaxResponseParserClassEquals(method, null);
assertExceptionParserClassEquals(method, ReturnNullOnNotFoundOr404.class);
checkFilters(request);
}
private static final Class<? extends CreateSharedIpGroupOptions[]> createSharedIpGroupOptionsVarargsClass = new CreateSharedIpGroupOptions[] {}
.getClass();
public void testCreateSharedIpGroup() throws IOException, SecurityException, NoSuchMethodException {
Method method = NovaAsyncClient.class.getMethod("createSharedIpGroup", String.class,
createSharedIpGroupOptionsVarargsClass);
HttpRequest request = processor.createRequest(method, "ralphie");
assertRequestLineEquals(request, "POST http://serverManagementUrl/shared_ip_groups?format=json HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Accept: application/json\n");
assertPayloadEquals(request, "{\"sharedIpGroup\":{\"name\":\"ralphie\"}}", MediaType.APPLICATION_JSON, false);
assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class);
assertSaxResponseParserClassEquals(method, null);
assertExceptionParserClassEquals(method, null);
checkFilters(request);
}
public void testCreateSharedIpGroupWithIpGroup() throws IOException, SecurityException, NoSuchMethodException {
Method method = NovaAsyncClient.class.getMethod("createSharedIpGroup", String.class,
createSharedIpGroupOptionsVarargsClass);
HttpRequest request = processor.createRequest(method, "ralphie", withServer(2));
assertRequestLineEquals(request, "POST http://serverManagementUrl/shared_ip_groups?format=json HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Accept: application/json\n");
assertPayloadEquals(request, "{\"sharedIpGroup\":{\"name\":\"ralphie\",\"server\":2}}",
MediaType.APPLICATION_JSON, false);
assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class);
assertSaxResponseParserClassEquals(method, null);
assertExceptionParserClassEquals(method, null);
checkFilters(request);
}
public void testDeleteSharedIpGroup() throws IOException, SecurityException, NoSuchMethodException {
Method method = NovaAsyncClient.class.getMethod("deleteSharedIpGroup", int.class);
HttpRequest request = processor.createRequest(method, 2);
assertRequestLineEquals(request, "DELETE http://serverManagementUrl/shared_ip_groups/2 HTTP/1.1");
assertNonPayloadHeadersEqual(request, "");
assertPayloadEquals(request, null, null, false);
assertResponseParserClassEquals(method, request, ReturnTrueIf2xx.class);
assertSaxResponseParserClassEquals(method, null);
assertExceptionParserClassEquals(method, ReturnFalseOnNotFoundOr404.class);
checkFilters(request);
}
public void testListAddresses() throws IOException, SecurityException, NoSuchMethodException {
Method method = NovaAsyncClient.class.getMethod("getAddresses", int.class);
HttpRequest request = processor.createRequest(method, 2);
assertRequestLineEquals(request, "GET http://serverManagementUrl/servers/2/ips?format=json HTTP/1.1");
assertRequestLineEquals(request, "GET http://endpoint/vapiversion/servers/2/ips?format=json HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Accept: application/json\n");
assertPayloadEquals(request, null, null, false);
@ -698,7 +432,7 @@ public class NovaAsyncClientTest extends RestClientTest<NovaAsyncClient> {
Method method = NovaAsyncClient.class.getMethod("listPublicAddresses", int.class);
HttpRequest request = processor.createRequest(method, 2);
assertRequestLineEquals(request, "GET http://serverManagementUrl/servers/2/ips/public?format=json HTTP/1.1");
assertRequestLineEquals(request, "GET http://endpoint/vapiversion/servers/2/ips/public?format=json HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Accept: application/json\n");
assertPayloadEquals(request, null, null, false);
@ -709,11 +443,12 @@ public class NovaAsyncClientTest extends RestClientTest<NovaAsyncClient> {
checkFilters(request);
}
@Test
public void testListPrivateAddresses() throws IOException, SecurityException, NoSuchMethodException {
Method method = NovaAsyncClient.class.getMethod("listPrivateAddresses", int.class);
HttpRequest request = processor.createRequest(method, 2);
assertRequestLineEquals(request, "GET http://serverManagementUrl/servers/2/ips/private?format=json HTTP/1.1");
assertRequestLineEquals(request, "GET http://endpoint/vapiversion/servers/2/ips/private?format=json HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Accept: application/json\n");
assertPayloadEquals(request, null, null, false);
@ -724,26 +459,12 @@ public class NovaAsyncClientTest extends RestClientTest<NovaAsyncClient> {
checkFilters(request);
}
public void testListBackupSchedule() throws IOException, SecurityException, NoSuchMethodException {
Method method = NovaAsyncClient.class.getMethod("getBackupSchedule", int.class);
HttpRequest request = processor.createRequest(method, 2);
assertRequestLineEquals(request, "GET http://serverManagementUrl/servers/2/backup_schedule?format=json HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Accept: application/json\n");
assertPayloadEquals(request, null, null, false);
assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class);
assertSaxResponseParserClassEquals(method, null);
assertExceptionParserClassEquals(method, MapHttp4xxCodesToExceptions.class);
checkFilters(request);
}
@Test
public void testCreateImageWithIpGroup() throws IOException, SecurityException, NoSuchMethodException {
Method method = NovaAsyncClient.class.getMethod("createImageFromServer", String.class, int.class);
HttpRequest request = processor.createRequest(method, "ralphie", 2);
assertRequestLineEquals(request, "POST http://serverManagementUrl/images?format=json HTTP/1.1");
assertRequestLineEquals(request, "POST http://endpoint/vapiversion/images?format=json HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Accept: application/json\n");
assertPayloadEquals(request, "{\"image\":{\"serverId\":2,\"name\":\"ralphie\"}}", MediaType.APPLICATION_JSON,
false);
@ -759,12 +480,13 @@ public class NovaAsyncClientTest extends RestClientTest<NovaAsyncClient> {
private static final Class<? extends RebuildServerOptions[]> rebuildServerOptionsVarargsClass = new RebuildServerOptions[]{}
.getClass();
@Test
public void testRebuildServer() throws IOException, SecurityException, NoSuchMethodException {
Method method = NovaAsyncClient.class.getMethod("rebuildServer", int.class,
rebuildServerOptionsVarargsClass);
HttpRequest request = processor.createRequest(method, 3);
assertRequestLineEquals(request, "POST http://serverManagementUrl/servers/3/action?format=json HTTP/1.1");
assertRequestLineEquals(request, "POST http://endpoint/vapiversion/servers/3/action?format=json HTTP/1.1");
assertNonPayloadHeadersEqual(request, "");
assertPayloadEquals(request, "{\"rebuild\":{}}", MediaType.APPLICATION_JSON, false);
@ -775,14 +497,15 @@ public class NovaAsyncClientTest extends RestClientTest<NovaAsyncClient> {
checkFilters(request);
}
@Test
public void testRebuildServerWithImage() throws IOException, SecurityException, NoSuchMethodException {
Method method = NovaAsyncClient.class.getMethod("rebuildServer", int.class,
rebuildServerOptionsVarargsClass);
HttpRequest request = processor.createRequest(method, 3, withImage(2));
HttpRequest request = processor.createRequest(method, 3, withImage("2"));
assertRequestLineEquals(request, "POST http://serverManagementUrl/servers/3/action?format=json HTTP/1.1");
assertRequestLineEquals(request, "POST http://endpoint/vapiversion/servers/3/action?format=json HTTP/1.1");
assertNonPayloadHeadersEqual(request, "");
assertPayloadEquals(request, "{\"rebuild\":{\"imageId\":2}}", MediaType.APPLICATION_JSON, false);
assertPayloadEquals(request, "{\"rebuild\":{\"imageRef\":\"2\"}}", MediaType.APPLICATION_JSON, false);
assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class);
assertSaxResponseParserClassEquals(method, null);
@ -791,11 +514,12 @@ public class NovaAsyncClientTest extends RestClientTest<NovaAsyncClient> {
checkFilters(request);
}
@Test
public void testReboot() throws IOException, SecurityException, NoSuchMethodException {
Method method = NovaAsyncClient.class.getMethod("rebootServer", int.class, RebootType.class);
HttpRequest request = processor.createRequest(method, 2, RebootType.HARD);
assertRequestLineEquals(request, "POST http://serverManagementUrl/servers/2/action?format=json HTTP/1.1");
assertRequestLineEquals(request, "POST http://endpoint/vapiversion/servers/2/action?format=json HTTP/1.1");
assertNonPayloadHeadersEqual(request, "");
assertPayloadEquals(request, "{\"reboot\":{\"type\":\"HARD\"}}", MediaType.APPLICATION_JSON, false);
@ -806,11 +530,12 @@ public class NovaAsyncClientTest extends RestClientTest<NovaAsyncClient> {
checkFilters(request);
}
@Test
public void testResize() throws IOException, SecurityException, NoSuchMethodException {
Method method = NovaAsyncClient.class.getMethod("resizeServer", int.class, int.class);
HttpRequest request = processor.createRequest(method, 2, 3);
assertRequestLineEquals(request, "POST http://serverManagementUrl/servers/2/action?format=json HTTP/1.1");
assertRequestLineEquals(request, "POST http://endpoint/vapiversion/servers/2/action?format=json HTTP/1.1");
assertNonPayloadHeadersEqual(request, "");
assertPayloadEquals(request, "{\"resize\":{\"flavorId\":3}}", MediaType.APPLICATION_JSON, false);
@ -826,7 +551,7 @@ public class NovaAsyncClientTest extends RestClientTest<NovaAsyncClient> {
Method method = NovaAsyncClient.class.getMethod("confirmResizeServer", int.class);
HttpRequest request = processor.createRequest(method, 2);
assertRequestLineEquals(request, "POST http://serverManagementUrl/servers/2/action?format=json HTTP/1.1");
assertRequestLineEquals(request, "POST http://endpoint/vapiversion/servers/2/action?format=json HTTP/1.1");
assertNonPayloadHeadersEqual(request, "");
assertPayloadEquals(request, "{\"confirmResize\":null}", MediaType.APPLICATION_JSON, false);
@ -841,7 +566,7 @@ public class NovaAsyncClientTest extends RestClientTest<NovaAsyncClient> {
Method method = NovaAsyncClient.class.getMethod("revertResizeServer", int.class);
HttpRequest request = processor.createRequest(method, 2);
assertRequestLineEquals(request, "POST http://serverManagementUrl/servers/2/action?format=json HTTP/1.1");
assertRequestLineEquals(request, "POST http://endpoint/vapiversion/servers/2/action?format=json HTTP/1.1");
assertNonPayloadHeadersEqual(request, "");
assertPayloadEquals(request, "{\"revertResize\":null}", MediaType.APPLICATION_JSON, false);
@ -880,7 +605,7 @@ public class NovaAsyncClientTest extends RestClientTest<NovaAsyncClient> {
@Override
protected URI provideServerUrl(AuthenticationResponse response) {
return URI.create("http://serverManagementUrl");
return URI.create("http://endpoint/vapiversion");
}
}
@ -895,9 +620,8 @@ public class NovaAsyncClientTest extends RestClientTest<NovaAsyncClient> {
@Override
protected Properties getProperties() {
Properties overrides = new Properties();
overrides.setProperty(PROPERTY_REGIONS, "US");
overrides.setProperty(PROPERTY_API_VERSION, "1");
overrides.setProperty(provider + ".endpoint", "https://auth");
overrides.setProperty(PROPERTY_API_VERSION, "apiversion");
overrides.setProperty(provider + ".endpoint", "http://endpoint");
overrides.setProperty(provider + ".contextbuilder", NovaContextBuilder.class.getName());
return overrides;
}

View File

@ -16,25 +16,23 @@
* limitations under the License.
* ====================================================================
*/
package org.jclouds.openstack.nova.compute.functions;
import static org.testng.Assert.assertEquals;
import java.net.UnknownHostException;
import org.jclouds.openstack.nova.domain.Flavor;
import org.jclouds.openstack.nova.functions.ParseFlavorFromJsonResponseTest;
import org.jclouds.compute.domain.Hardware;
import org.jclouds.compute.domain.HardwareBuilder;
import org.jclouds.compute.domain.Processor;
import org.jclouds.compute.domain.Volume;
import org.jclouds.compute.domain.VolumeBuilder;
import com.google.common.collect.ImmutableList;
import org.jclouds.compute.domain.*;
import org.jclouds.domain.Location;
import org.jclouds.domain.LocationBuilder;
import org.jclouds.domain.LocationScope;
import org.jclouds.openstack.nova.domain.Flavor;
import org.jclouds.openstack.nova.functions.ParseFlavorFromJsonResponseTest;
import org.testng.annotations.Test;
import com.google.common.collect.ImmutableList;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.UnknownHostException;
import static org.testng.Assert.assertEquals;
/**
* @author Adrian Cole
@ -44,11 +42,16 @@ public class FlavorToHardwareTest {
Location provider = new LocationBuilder().scope(LocationScope.ZONE).id("dallas").description("description").build();
@Test
public void test() throws UnknownHostException {
assertEquals(convertFlavor(), new HardwareBuilder().ids("1").name("256 MB Server").processors(
ImmutableList.of(new Processor(1.0, 1.0))).ram(256).volumes(
ImmutableList.of(new VolumeBuilder().type(Volume.Type.LOCAL).size(10.0f).durable(true).bootDevice(true)
.build())).build());
public void test() throws UnknownHostException, URISyntaxException {
Hardware flavor = convertFlavor();
Hardware tempFlavor = new HardwareBuilder().ids("1").name("256 MB Server")
.processors(ImmutableList.of(new Processor(1.0, 1.0)))
.ram(256)
.volumes(ImmutableList.of(
new VolumeBuilder().type(Volume.Type.LOCAL).size(10.0f).durable(true).bootDevice(true).build()))
.uri(new URI("http://servers.api.openstack.org/1234/flavors/1"))
.build();
assertEquals(flavor, tempFlavor);
}
public static Hardware convertFlavor() {

View File

@ -18,14 +18,11 @@
*/
package org.jclouds.openstack.nova.compute.functions;
import static org.testng.Assert.assertEquals;
import java.net.UnknownHostException;
import com.google.inject.Guice;
import org.jclouds.compute.config.BaseComputeServiceContextModule;
import org.jclouds.compute.domain.Image;
import org.jclouds.compute.domain.ImageBuilder;
import org.jclouds.compute.domain.OperatingSystemBuilder;
import org.jclouds.compute.domain.OperatingSystem;
import org.jclouds.compute.domain.OsFamily;
import org.jclouds.compute.reference.ComputeServiceConstants;
import org.jclouds.domain.Credentials;
@ -34,7 +31,11 @@ import org.jclouds.json.config.GsonModule;
import org.jclouds.openstack.nova.functions.ParseImageFromJsonResponseTest;
import org.testng.annotations.Test;
import com.google.inject.Guice;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.UnknownHostException;
import static org.testng.Assert.assertEquals;
/**
* @author Adrian Cole
@ -43,15 +44,16 @@ import com.google.inject.Guice;
public class NovaImageToImageTest {
@Test
public void testApplyWhereImageNotFound() throws UnknownHostException {
assertEquals(
convertImage(),
new ImageBuilder()
public void testApplyWhereImageNotFound() throws UnknownHostException, URISyntaxException {
Image image = new ImageBuilder()
.name("CentOS 5.2")
.operatingSystem(
new OperatingSystemBuilder().family(OsFamily.CENTOS).version("5.2").description("CentOS 5.2").is64Bit(true)
new OperatingSystem.Builder().family(OsFamily.CENTOS).version("5.2").description("CentOS 5.2").is64Bit(true)
.build()).description("CentOS 5.2").defaultCredentials(new Credentials("root", null))
.ids("2").version("1286712000000").build());
.ids("2").version("1286712000000").uri(new URI("https://servers.api.rackspacecloud.com/v1.1/1234/images/1")).build();
Image parsedImage = convertImage();
assertEquals(parsedImage, image);
}
public static Image convertImage() {

View File

@ -0,0 +1,170 @@
/**
*
* Copyright (C) 2011 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* 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.openstack.nova.compute.functions;
import com.google.common.base.Suppliers;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import org.jclouds.compute.domain.*;
import org.jclouds.domain.Credentials;
import org.jclouds.domain.Location;
import org.jclouds.domain.LocationBuilder;
import org.jclouds.domain.LocationScope;
import org.jclouds.openstack.nova.compute.config.NovaComputeServiceDependenciesModule;
import org.jclouds.openstack.nova.domain.Server;
import org.jclouds.openstack.nova.domain.ServerStatus;
import org.jclouds.openstack.nova.functions.ParseServerFromJsonResponseTest;
import org.testng.annotations.Test;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.UnknownHostException;
import java.util.Map;
import java.util.Set;
import static org.testng.Assert.assertEquals;
/**
* @author Adrian Cole
*/
@Test(groups = "unit")
public class ServerToNodeMetadataTest {
Location provider = new LocationBuilder().scope(LocationScope.ZONE).id("dallas").description("description").build();
@Test
public void testApplyWhereImageAndHardwareNotFoundButCredentialsFound() throws UnknownHostException, NoSuchMethodException, ClassNotFoundException, URISyntaxException {
Credentials creds = new Credentials("root", "abdce");
Map<ServerStatus, NodeState> serverStateToNodeState = NovaComputeServiceDependenciesModule.serverToNodeState;
Set<org.jclouds.compute.domain.Image> images = ImmutableSet.of();
Set<org.jclouds.compute.domain.Hardware> hardwares = ImmutableSet.of();
Server server = ParseServerFromJsonResponseTest.parseServer();
ServerToNodeMetadata parser = new ServerToNodeMetadata(serverStateToNodeState, ImmutableMap
.<String, Credentials>of("node#1234", creds), Suppliers.<Set<? extends Image>>ofInstance(images),
Suppliers.ofInstance(provider), Suppliers.<Set<? extends Hardware>>ofInstance(hardwares));
NodeMetadata metadata = parser.apply(server);
NodeMetadata constructedMetadata = newNodeMetadataBuilder()
.credentials(creds).build();
assertEquals(metadata, constructedMetadata);
}
@Test
public void testApplyWhereImageAndHardwareNotFound() throws UnknownHostException, NoSuchMethodException, ClassNotFoundException, URISyntaxException {
Map<ServerStatus, NodeState> serverStateToNodeState = NovaComputeServiceDependenciesModule.serverToNodeState;
Set<org.jclouds.compute.domain.Image> images = ImmutableSet.of();
Set<org.jclouds.compute.domain.Hardware> hardwares = ImmutableSet.of();
Server server = ParseServerFromJsonResponseTest.parseServer();
ServerToNodeMetadata parser = new ServerToNodeMetadata(serverStateToNodeState, ImmutableMap
.<String, Credentials>of(), Suppliers.<Set<? extends Image>>ofInstance(images), Suppliers
.ofInstance(provider), Suppliers.<Set<? extends Hardware>>ofInstance(hardwares));
NodeMetadata metadata = parser.apply(server);
NodeMetadata constructedMetadata = newNodeMetadataBuilder().build();
assertEquals(metadata, constructedMetadata);
}
private NodeMetadataBuilder newNodeMetadataBuilder() throws URISyntaxException {
return new NodeMetadataBuilder()
.state(NodeState.PENDING)
.publicAddresses(ImmutableSet.of("67.23.10.132", "::babe:67.23.10.132", "67.23.10.131", "::babe:4317:0A83"))
.privateAddresses(ImmutableSet.of("10.176.42.16", "::babe:10.176.42.16"))
.id("1234")
.providerId("1234")
.name("sample-server")
.location(new LocationBuilder()
.scope(LocationScope.HOST)
.id("e4d909c290d0fb1ca068ffaddf22cbd0")
.description("e4d909c290d0fb1ca068ffaddf22cbd0")
.parent(provider).build())
.userMetadata(ImmutableMap.of("Server Label", "Web Head 1", "Image Version", "2.1"))
.uri(new URI("http://servers.api.openstack.org/1234/servers/1234"));
}
@Test
public void testApplyWhereImageFoundAndHardwareNotFound() throws UnknownHostException, NoSuchMethodException, ClassNotFoundException, URISyntaxException {
Map<ServerStatus, NodeState> serverStateToNodeState = NovaComputeServiceDependenciesModule.serverToNodeState;
org.jclouds.compute.domain.Image jcImage = NovaImageToImageTest.convertImage();
Set<org.jclouds.compute.domain.Image> images = ImmutableSet.of(jcImage);
Set<org.jclouds.compute.domain.Hardware> hardwares = ImmutableSet.of();
Server server = ParseServerFromJsonResponseTest.parseServer();
ServerToNodeMetadata parser = new ServerToNodeMetadata(serverStateToNodeState, ImmutableMap
.<String, Credentials>of(), Suppliers.<Set<? extends Image>>ofInstance(images), Suppliers
.ofInstance(provider), Suppliers.<Set<? extends Hardware>>ofInstance(hardwares));
NodeMetadata metadata = parser.apply(server);
NodeMetadata constructedMetadata = newNodeMetadataBuilder()
.imageId("2")
.operatingSystem(new OperatingSystem.Builder()
.family(OsFamily.CENTOS)
.description("CentOS 5.2")
.version("5.2")
.is64Bit(true).build())
.build();
assertEquals(metadata, constructedMetadata);
}
@Test
public void testApplyWhereImageAndHardwareFound() throws UnknownHostException, NoSuchMethodException, ClassNotFoundException, URISyntaxException {
Map<ServerStatus, NodeState> serverStateToNodeState = NovaComputeServiceDependenciesModule.serverToNodeState;
Set<org.jclouds.compute.domain.Image> images = ImmutableSet.of(NovaImageToImageTest.convertImage());
Set<org.jclouds.compute.domain.Hardware> hardwares = ImmutableSet.of(FlavorToHardwareTest.convertFlavor());
Server server = ParseServerFromJsonResponseTest.parseServer();
ServerToNodeMetadata parser = new ServerToNodeMetadata(serverStateToNodeState, ImmutableMap
.<String, Credentials>of(), Suppliers.<Set<? extends Image>>ofInstance(images), Suppliers
.ofInstance(provider), Suppliers.<Set<? extends Hardware>>ofInstance(hardwares));
NodeMetadata metadata = parser.apply(server);
NodeMetadata constructedMetadata = newNodeMetadataBuilder()
.imageId("2")
.operatingSystem(new OperatingSystem.Builder()
.family(OsFamily.CENTOS)
.description("CentOS 5.2")
.version("5.2")
.is64Bit(true).build())
.hardware(new HardwareBuilder()
.ids("1")
.name("256 MB Server")
.processors(ImmutableList.of(new Processor(1.0, 1.0)))
.ram(256)
.volumes(ImmutableList.of(new VolumeBuilder()
.type(Volume.Type.LOCAL)
.size(10.0f)
.durable(true)
.bootDevice(true).build()))
.uri(new URI("http://servers.api.openstack.org/1234/flavors/1"))
.build())
.build();
assertEquals(metadata, constructedMetadata);
}
}

View File

@ -0,0 +1,65 @@
/**
*
* Copyright (C) 2011 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* 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.openstack.nova.domain;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import org.testng.annotations.Test;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import static junit.framework.Assert.assertTrue;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
/**
* Tests behavior of {@code CreateImageBinder}
*
* @author Adrian Cole
*/
@Test(groups = "unit")
public class ServerStatusTest {
@Test
public void testAllKnownStatusesIsRecognized() {
List<String> knownStatuses = Arrays.asList(
"ACTIVE", "BUILD", "REBUILD", "SUSPENDED", "QUEUE_RESIZE",
"PREP_RESIZE", "RESIZE", "VERIFY_RESIZE",
"PASSWORD", "RESCUE", "REBOOT",
"HARD_REBOOT", "DELETE_IP", "UNKNOWN", "DELETED");
for (String status : knownStatuses) {
assertFalse(ServerStatus.fromValue(status).equals(ServerStatus.UNRECOGNIZED));
}
List<String> allStatuses = Lists.newArrayList(knownStatuses);
allStatuses.add("UNRECOGNIZED");
Set<ServerStatus> enumValues = Sets.newHashSet(ServerStatus.values());
assertEquals(enumValues.size(), allStatuses.size());
for (String status : allStatuses) {
assertTrue(enumValues.contains(ServerStatus.valueOf(status)));
}
}
}

View File

@ -18,10 +18,10 @@
*/
package org.jclouds.openstack.nova.domain;
import static org.testng.Assert.assertEquals;
import org.testng.annotations.Test;
import static org.testng.Assert.assertEquals;
/**
* Tests behavior of {@code CreateImageBinder}
*

View File

@ -18,24 +18,26 @@
*/
package org.jclouds.openstack.nova.functions;
import static org.testng.Assert.assertEquals;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.common.collect.Sets;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Key;
import com.google.inject.TypeLiteral;
import org.jclouds.http.HttpResponse;
import org.jclouds.http.functions.UnwrapOnlyJsonValue;
import org.jclouds.io.Payloads;
import org.jclouds.json.config.GsonModule;
import org.jclouds.openstack.nova.domain.Address;
import org.jclouds.openstack.nova.domain.Addresses;
import org.testng.annotations.Test;
import java.io.InputStream;
import java.net.UnknownHostException;
import java.util.List;
import org.jclouds.openstack.nova.domain.Addresses;
import org.jclouds.http.HttpResponse;
import org.jclouds.http.functions.UnwrapOnlyJsonValue;
import org.jclouds.io.Payloads;
import org.jclouds.json.config.GsonModule;
import org.testng.annotations.Test;
import com.google.common.collect.ImmutableList;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Key;
import com.google.inject.TypeLiteral;
import static org.testng.Assert.assertTrue;
/**
* Tests behavior of {@code ParseAddressesFromJsonResponse}
@ -46,17 +48,23 @@ import com.google.inject.TypeLiteral;
public class ParseAddressesFromJsonResponseTest {
Injector i = Guice.createInjector(new GsonModule());
@Test
public void testApplyInputStreamDetails() throws UnknownHostException {
InputStream is = getClass().getResourceAsStream("/test_list_addresses.json");
UnwrapOnlyJsonValue<Addresses> parser = i.getInstance(Key.get(new TypeLiteral<UnwrapOnlyJsonValue<Addresses>>() {
}));
Addresses response = parser.apply(new HttpResponse(200, "ok", Payloads.newInputStreamPayload(is)));
List<String> publicAddresses = ImmutableList.of("67.23.10.132", "67.23.10.131");
List<String> privateAddresses = ImmutableList.of("10.176.42.16");
List<Address> publicAddresses = ImmutableList.copyOf(
Iterables.transform(ImmutableList.of("67.23.10.132", "::babe:67.23.10.132", "67.23.10.131", "::babe:4317:0A83"),
Address.newString2AddressFunction()));
assertEquals(response.getPublicAddresses(), publicAddresses);
assertEquals(response.getPrivateAddresses(), privateAddresses);
List<Address> privateAddresses = ImmutableList.copyOf(
Iterables.transform(ImmutableList.of("10.176.42.16", "::babe:10.176.42.16"),
Address.newString2AddressFunction()));
assertTrue(response.getPublicAddresses().equals(Sets.newHashSet(publicAddresses)));
assertTrue(response.getPrivateAddresses().equals(Sets.newHashSet(privateAddresses)));
}
}

View File

@ -0,0 +1,149 @@
/**
*
* Copyright (C) 2011 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* 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.openstack.nova.functions;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Key;
import com.google.inject.TypeLiteral;
import org.jclouds.http.HttpCommand;
import org.jclouds.http.HttpRequest;
import org.jclouds.http.HttpResponse;
import org.jclouds.http.functions.UnwrapOnlyJsonValue;
import org.jclouds.io.Payloads;
import org.jclouds.json.config.GsonModule;
import org.jclouds.openstack.nova.domain.Server;
import org.jclouds.openstack.nova.handlers.ParseNovaErrorFromHttpResponse;
import org.testng.annotations.Test;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
/**
* Tests behavior of {@code ParseServerListFromJsonResponse}
*
* @author Adrian Cole
*/
@Test(groups = "unit")
public class ParseFaultFromJsonResponseTest {
Injector i = Guice.createInjector(new GsonModule());
@Test
public void testApplyInputStream() {
InputStream is = getClass().getResourceAsStream("/test_list_servers.json");
@SuppressWarnings("unused")
UnwrapOnlyJsonValue<List<Server>> parser = i.getInstance(Key
.get(new TypeLiteral<UnwrapOnlyJsonValue<List<Server>>>() {
}));
//List<Server> response = parser.apply(new HttpResponse(413, "Over limit", Payloads.newInputStreamPayload(is)));
new ParseNovaErrorFromHttpResponse().handleError(createHttpCommand(), new HttpResponse(413, "Over limit", Payloads.newInputStreamPayload(is)));
//assertEquals(response, expects);
}
@Test
public void testHandler() {
//InputStream is = getClass().getResourceAsStream("/test_error_handler.json");
//
//
// NovaErrorHandler handler = Guice.createInjector(new GsonModule()).getInstance(GoGridErrorHandler.class);
//
// HttpCommand command = createHttpCommand();
// handler.handleError(command, new HttpResponse(200, "ok", Payloads.newInputStreamPayload(is)));
//
// Exception createdException = command.getException();
//
// assertNotNull(createdException, "There should've been an exception generated");
// String message = createdException.getMessage();
// assertTrue(message.contains("No object found that matches your input criteria."),
// "Didn't find the expected error cause in the exception message");
// assertTrue(message.contains("IllegalArgumentException"),
// "Didn't find the expected error code in the exception message");
//
// // make sure the InputStream is closed
// try {
// is.available();
// throw new TestException("Stream wasn't closed by the GoGridErrorHandler when it should've");
// } catch (IOException e) {
// // this is the excepted output
// }
}
HttpCommand createHttpCommand() {
return new HttpCommand() {
private Exception exception;
@Override
public int incrementRedirectCount() {
return 0; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public int getRedirectCount() {
return 0; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public boolean isReplayable() {
return false; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public int incrementFailureCount() {
return 0; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public int getFailureCount() {
return 0; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public HttpRequest getCurrentRequest() {
try {
return new HttpRequest("method", new URI("http://endpoint"));
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
}
@Override
public void setCurrentRequest(HttpRequest request) {
//To change body of implemented methods use File | Settings | File Templates.
}
@Override
public void setException(Exception exception) {
this.exception = exception;
}
@Override
public Exception getException() {
return exception;
}
};
}
}

View File

@ -18,22 +18,23 @@
*/
package org.jclouds.openstack.nova.functions;
import static org.testng.Assert.assertEquals;
import java.io.InputStream;
import org.jclouds.openstack.nova.domain.Flavor;
import org.jclouds.http.HttpResponse;
import org.jclouds.http.functions.UnwrapOnlyJsonValue;
import org.jclouds.io.Payloads;
import org.jclouds.json.config.GsonModule;
import org.testng.annotations.Test;
import com.google.gson.Gson;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Key;
import com.google.inject.TypeLiteral;
import org.jclouds.http.HttpResponse;
import org.jclouds.http.functions.UnwrapOnlyJsonValue;
import org.jclouds.io.Payloads;
import org.jclouds.json.config.GsonModule;
import org.jclouds.openstack.nova.domain.Flavor;
import org.testng.annotations.Test;
import java.io.IOException;
import java.io.InputStream;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
/**
* Tests behavior of {@code ParseFlavorFromJsonResponse}
@ -42,12 +43,18 @@ import com.google.inject.TypeLiteral;
*/
@Test(groups = "unit")
public class ParseFlavorFromJsonResponseTest {
public void test() {
@Test
public void testParseFlavorFromJsonResponseTest() throws IOException {
Flavor response = parseFlavor();
String json = new Gson().toJson(response);
assertNotNull(json);
assertEquals(json, "{\"id\":1,\"name\":\"256 MB Server\",\"disk\":10,\"ram\":256}");
assertEquals(response.getId(), 1);
assertEquals(response.getName(), "256 MB Server");
assertEquals(response.getDisk().intValue(), 10);
assertEquals(response.getRam().intValue(), 256);
}
public static Flavor parseFlavor() {
@ -57,8 +64,7 @@ public class ParseFlavorFromJsonResponseTest {
UnwrapOnlyJsonValue<Flavor> parser = i.getInstance(Key.get(new TypeLiteral<UnwrapOnlyJsonValue<Flavor>>() {
}));
Flavor response = parser.apply(new HttpResponse(200, "ok", Payloads.newInputStreamPayload(is)));
return response;
return parser.apply(new HttpResponse(200, "ok", Payloads.newInputStreamPayload(is)));
}
}

View File

@ -18,24 +18,23 @@
*/
package org.jclouds.openstack.nova.functions;
import static org.testng.Assert.assertEquals;
import java.io.InputStream;
import java.net.UnknownHostException;
import java.util.List;
import org.jclouds.openstack.nova.domain.Flavor;
import org.jclouds.http.HttpResponse;
import org.jclouds.http.functions.UnwrapOnlyJsonValue;
import org.jclouds.io.Payloads;
import org.jclouds.json.config.GsonModule;
import org.testng.annotations.Test;
import com.google.common.collect.ImmutableList;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Key;
import com.google.inject.TypeLiteral;
import org.jclouds.http.HttpResponse;
import org.jclouds.http.functions.UnwrapOnlyJsonValue;
import org.jclouds.io.Payloads;
import org.jclouds.json.config.GsonModule;
import org.jclouds.openstack.nova.domain.Flavor;
import org.testng.annotations.Test;
import java.io.InputStream;
import java.net.UnknownHostException;
import java.util.List;
import static org.testng.Assert.assertEquals;
/**
* Tests behavior of {@code ParseFlavorListFromJsonResponse}
@ -47,6 +46,7 @@ public class ParseFlavorListFromJsonResponseTest {
Injector i = Guice.createInjector(new GsonModule());
@Test
public void testApplyInputStream() {
InputStream is = getClass().getResourceAsStream("/test_list_flavors.json");
@ -59,6 +59,7 @@ public class ParseFlavorListFromJsonResponseTest {
assertEquals(response, expects);
}
@Test
public void testApplyInputStreamDetails() throws UnknownHostException {
InputStream is = getClass().getResourceAsStream("/test_list_flavors_detail.json");

View File

@ -18,13 +18,7 @@
*/
package org.jclouds.openstack.nova.functions;
import static org.testng.Assert.assertEquals;
import java.io.InputStream;
import java.net.UnknownHostException;
import org.jclouds.openstack.nova.domain.Image;
import org.jclouds.openstack.nova.domain.ImageStatus;
import com.google.inject.*;
import org.jclouds.date.DateService;
import org.jclouds.http.HttpResponse;
import org.jclouds.http.functions.UnwrapOnlyJsonValue;
@ -32,13 +26,14 @@ import org.jclouds.io.Payloads;
import org.jclouds.json.config.GsonModule;
import org.jclouds.json.config.GsonModule.DateAdapter;
import org.jclouds.json.config.GsonModule.Iso8601DateAdapter;
import org.jclouds.openstack.nova.domain.Image;
import org.jclouds.openstack.nova.domain.ImageStatus;
import org.testng.annotations.Test;
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Key;
import com.google.inject.TypeLiteral;
import java.io.InputStream;
import java.net.UnknownHostException;
import static org.testng.Assert.assertEquals;
/**
* Tests behavior of {@code ParseImageFromJsonResponse}
@ -58,6 +53,7 @@ public class ParseImageFromJsonResponseTest {
DateService dateService = i.getInstance(DateService.class);
@Test
public void testApplyInputStreamDetails() throws UnknownHostException {
Image response = parseImage();
@ -65,10 +61,12 @@ public class ParseImageFromJsonResponseTest {
assertEquals(response.getName(), "CentOS 5.2");
assertEquals(response.getCreated(), dateService.iso8601SecondsDateParse("2010-08-10T12:00:00Z"));
assertEquals(response.getProgress(), new Integer(80));
assertEquals(response.getServerId(), new Integer(12));
assertEquals(response.getStatus(), ImageStatus.SAVING);
assertEquals(response.getUpdated(), dateService.iso8601SecondsDateParse(("2010-10-10T12:00:00Z")));
assertEquals(response.getServerRef(), "http://servers.api.openstack.org/v1.1/1234/servers/12");
assertEquals(response.getMetadata().get("ImageVersion"), "1.5");
assertEquals(response.getMetadata().get("ImageType"), "Gold");
assertEquals(response.getMetadata().size(), 2);
}
public static Image parseImage() {

View File

@ -18,14 +18,8 @@
*/
package org.jclouds.openstack.nova.functions;
import static org.testng.Assert.assertEquals;
import java.io.InputStream;
import java.net.UnknownHostException;
import java.util.List;
import org.jclouds.openstack.nova.domain.Image;
import org.jclouds.openstack.nova.domain.ImageStatus;
import com.google.common.collect.ImmutableList;
import com.google.inject.*;
import org.jclouds.date.DateService;
import org.jclouds.http.HttpResponse;
import org.jclouds.http.functions.UnwrapOnlyJsonValue;
@ -33,14 +27,15 @@ import org.jclouds.io.Payloads;
import org.jclouds.json.config.GsonModule;
import org.jclouds.json.config.GsonModule.DateAdapter;
import org.jclouds.json.config.GsonModule.Iso8601DateAdapter;
import org.jclouds.openstack.nova.domain.Image;
import org.jclouds.openstack.nova.domain.ImageStatus;
import org.testng.annotations.Test;
import com.google.common.collect.ImmutableList;
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Key;
import com.google.inject.TypeLiteral;
import java.io.InputStream;
import java.net.UnknownHostException;
import java.util.List;
import static org.testng.Assert.assertEquals;
/**
* Tests behavior of {@code ParseImageListFromJsonResponse}
@ -59,10 +54,11 @@ public class ParseImageListFromJsonResponseTest {
}, new GsonModule());
DateService dateService = i.getInstance(DateService.class);
@Test
public void testApplyInputStream() {
InputStream is = getClass().getResourceAsStream("/test_list_images.json");
List<Image> expects = ImmutableList.of(new Image(2, "CentOS 5.2"), new Image(743, "My Server Backup"));
List<Image> expects = ImmutableList.of(new Image(1, "CentOS 5.2"), new Image(743, "My Server Backup"));
UnwrapOnlyJsonValue<List<Image>> parser = i.getInstance(Key
.get(new TypeLiteral<UnwrapOnlyJsonValue<List<Image>>>() {
@ -72,6 +68,7 @@ public class ParseImageListFromJsonResponseTest {
assertEquals(response, expects);
}
@Test
public void testApplyInputStreamDetails() throws UnknownHostException {
InputStream is = getClass().getResourceAsStream("/test_list_images_detail.json");
@ -80,22 +77,29 @@ public class ParseImageListFromJsonResponseTest {
}));
List<Image> response = parser.apply(new HttpResponse(200, "ok", Payloads.newInputStreamPayload(is)));
assertEquals(response.get(0).getId(), 2);
assertEquals(response.get(0).getId(), 1);
assertEquals(response.get(0).getName(), "CentOS 5.2");
assertEquals(response.get(0).getCreated(), dateService.iso8601SecondsDateParse("2010-08-10T12:00:00Z"));
assertEquals(response.get(0).getProgress(), null);
assertEquals(response.get(0).getServerId(), null);
assertEquals(response.get(0).getServerRef(), null);
assertEquals(response.get(0).getStatus(), ImageStatus.ACTIVE);
assertEquals(response.get(0).getUpdated(), dateService.iso8601SecondsDateParse("2010-10-10T12:00:00Z"));
assertEquals(response.get(0).getMetadata().get("ImageType"), "Gold");
assertEquals(response.get(0).getMetadata().get("ImageVersion"), "1.5");
assertEquals(response.get(0).getMetadata().size(), 2);
assertEquals(response.get(1).getId(), 743);
assertEquals(response.get(1).getName(), "My Server Backup");
assertEquals(response.get(1).getCreated(), dateService.iso8601SecondsDateParse("2009-07-07T09:56:16-05:00"));
;
assertEquals(response.get(1).getCreated(), dateService.iso8601SecondsDateParse("2009-07-07T09:56:16Z"));
assertEquals(response.get(1).getProgress(), new Integer(80));
assertEquals(response.get(1).getServerId(), new Integer(12));
assertEquals(response.get(1).getStatus(), ImageStatus.SAVING);
assertEquals(response.get(1).getUpdated(), dateService.iso8601SecondsDateParse("2010-10-10T12:00:00Z"));
assertEquals(response.get(1).getServerRef(), "http://servers.api.openstack.org/v1.1/1234/servers/12");
//short form of reference
assertEquals(response.get(2).getServerRef(), "12");
}
}

View File

@ -18,23 +18,23 @@
*/
package org.jclouds.openstack.nova.functions;
import static org.testng.Assert.assertEquals;
import java.io.InputStream;
import java.net.UnknownHostException;
import java.util.List;
import org.jclouds.http.HttpResponse;
import org.jclouds.http.functions.UnwrapOnlyJsonValue;
import org.jclouds.io.Payloads;
import org.jclouds.json.config.GsonModule;
import org.testng.annotations.Test;
import com.google.common.collect.ImmutableList;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Key;
import com.google.inject.TypeLiteral;
import org.jclouds.http.HttpResponse;
import org.jclouds.http.functions.UnwrapOnlyJsonValue;
import org.jclouds.io.Payloads;
import org.jclouds.json.config.GsonModule;
import org.jclouds.openstack.nova.domain.Address;
import org.testng.annotations.Test;
import java.io.InputStream;
import java.net.UnknownHostException;
import java.util.List;
import static org.testng.Assert.assertEquals;
/**
* Tests behavior of {@code ParseInetAddressListFromJsonResponse}
@ -46,25 +46,33 @@ public class ParseInetAddressListFromJsonResponseTest {
Injector i = Guice.createInjector(new GsonModule());
@Test
public void testPublic() throws UnknownHostException {
InputStream is = getClass().getResourceAsStream("/test_list_addresses_public.json");
UnwrapOnlyJsonValue<List<String>> parser = i.getInstance(Key
.get(new TypeLiteral<UnwrapOnlyJsonValue<List<String>>>() {
UnwrapOnlyJsonValue<List<Address>> parser = i.getInstance(Key
.get(new TypeLiteral<UnwrapOnlyJsonValue<List<Address>>>() {
}));
List<String> response = parser.apply(new HttpResponse(200, "ok", Payloads.newInputStreamPayload(is)));
List<Address> response = parser.apply(new HttpResponse(200, "ok", Payloads.newInputStreamPayload(is)));
assertEquals(response, ImmutableList.of("67.23.10.132", "67.23.10.131"));
assertEquals(response, ImmutableList.of(Address.valueOf("67.23.10.132"),
Address.valueOf("::babe:67.23.10.132"),
Address.valueOf("67.23.10.131"), Address.valueOf("::babe:4317:0A83")));
}
@Test
public void testPrivate() throws UnknownHostException {
InputStream is = getClass().getResourceAsStream("/test_list_addresses_private.json");
UnwrapOnlyJsonValue<List<String>> parser = i.getInstance(Key
.get(new TypeLiteral<UnwrapOnlyJsonValue<List<String>>>() {
UnwrapOnlyJsonValue<List<Address>> parser = i.getInstance(Key
.get(new TypeLiteral<UnwrapOnlyJsonValue<List<Address>>>() {
}));
List<String> response = parser.apply(new HttpResponse(200, "ok", Payloads.newInputStreamPayload(is)));
List<Address> response = parser.apply(new HttpResponse(200, "ok", Payloads.newInputStreamPayload(is)));
assertEquals(response, ImmutableList.of(Address.valueOf("67.23.10.132"),
Address.valueOf("::babe:67.23.10.132"),
Address.valueOf("67.23.10.131"), Address.valueOf("::babe:4317:0A83")));
assertEquals(response, ImmutableList.of("10.176.42.16"));
}
}

View File

@ -18,27 +18,33 @@
*/
package org.jclouds.openstack.nova.functions;
import static org.testng.Assert.assertEquals;
import java.io.InputStream;
import java.net.UnknownHostException;
import java.util.List;
import org.jclouds.openstack.nova.domain.Addresses;
import org.jclouds.openstack.nova.domain.Server;
import org.jclouds.openstack.nova.domain.ServerStatus;
import org.jclouds.http.HttpResponse;
import org.jclouds.http.functions.UnwrapOnlyJsonValue;
import org.jclouds.io.Payloads;
import org.jclouds.json.config.GsonModule;
import org.testng.annotations.Test;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.collect.Iterables;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Key;
import com.google.inject.TypeLiteral;
import org.jclouds.http.HttpResponse;
import org.jclouds.http.functions.UnwrapOnlyJsonValue;
import org.jclouds.io.Payloads;
import org.jclouds.json.config.GsonModule;
import org.jclouds.openstack.nova.domain.Address;
import org.jclouds.openstack.nova.domain.Addresses;
import org.jclouds.openstack.nova.domain.Server;
import org.jclouds.openstack.nova.domain.ServerStatus;
import org.testng.annotations.Test;
import java.io.InputStream;
import java.net.UnknownHostException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.SimpleTimeZone;
import static org.testng.Assert.assertEquals;
/**
* Tests behavior of {@code ParseServerFromJsonResponse}
@ -48,35 +54,54 @@ import com.google.inject.TypeLiteral;
@Test(groups = "unit")
public class ParseServerFromJsonResponseTest {
public void testApplyInputStreamDetails() throws UnknownHostException {
@Test
public void testApplyInputStreamDetails() throws UnknownHostException, NoSuchMethodException, ClassNotFoundException, ParseException {
Server response = parseServer();
assertEquals(response.getId(), 1234);
assertEquals(response.getName(), "sample-server");
assertEquals(response.getImageId(), new Integer(2));
assertEquals(response.getFlavorId(), new Integer(1));
assertEquals(response.getImageRef(), "https://servers.api.rackspacecloud.com/v1.1/1234/images/1");
assertEquals(response.getFlavorRef(), "http://servers.api.openstack.org/1234/flavors/1");
assertEquals(response.getHostId(), "e4d909c290d0fb1ca068ffaddf22cbd0");
assertEquals(response.getStatus(), ServerStatus.BUILD);
assertEquals(response.getProgress(), new Integer(60));
List<String> publicAddresses = Lists.newArrayList("67.23.10.132", "67.23.10.131");
List<String> privateAddresses = Lists.newArrayList("10.176.42.16");
Addresses addresses1 = new Addresses();
addresses1.getPrivateAddresses().addAll(privateAddresses);
addresses1.getPublicAddresses().addAll(publicAddresses);
SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.US);
dateFormat.setTimeZone(new SimpleTimeZone(0, "GMT"));
assertEquals(response.getCreated(),
dateFormat.parse("2010-08-10T12:00:00Z"));
assertEquals(response.getUpdated(),
dateFormat.parse("2010-10-10T12:00:00Z"));
List<Address> publicAddresses = ImmutableList.copyOf(Iterables.transform(
ImmutableList.of("67.23.10.132", "::babe:67.23.10.132", "67.23.10.131", "::babe:4317:0A83"),
Address.newString2AddressFunction()));
List<Address> privateAddresses = ImmutableList.copyOf(Iterables.transform(
ImmutableList.of("10.176.42.16", "::babe:10.176.42.16"),
Address.newString2AddressFunction()));
Addresses addresses1 = new Addresses(new HashSet<Address>(publicAddresses), new HashSet<Address>(privateAddresses));
assertEquals(response.getAddresses(), addresses1);
assertEquals(response.getMetadata(), ImmutableMap.of("Server Label", "Web Head 1", "Image Version", "2.1"));
assertEquals(response.getAddresses(), addresses1);
}
public static Server parseServer() {
Injector i = Guice.createInjector(new GsonModule());
public static Server parseServer() throws NoSuchMethodException, ClassNotFoundException {
Injector i = Guice.createInjector(new GsonModule() {
@Override
protected void configure() {
super.configure();
bind(DateAdapter.class).to(Iso8601DateAdapter.class);
}
});
InputStream is = ParseServerFromJsonResponseTest.class.getResourceAsStream("/test_get_server_detail.json");
UnwrapOnlyJsonValue<Server> parser = i.getInstance(Key.get(new TypeLiteral<UnwrapOnlyJsonValue<Server>>() {
}));
Server response = parser.apply(new HttpResponse(200, "ok", Payloads.newInputStreamPayload(is)));
return response;
return (Server) parser.apply(new HttpResponse(200, "ok", Payloads.newInputStreamPayload(is)));
}
}

View File

@ -22,20 +22,22 @@ import static org.testng.Assert.assertEquals;
import java.io.InputStream;
import java.net.UnknownHostException;
import java.util.HashSet;
import java.util.List;
import org.jclouds.openstack.nova.domain.Addresses;
import org.jclouds.openstack.nova.domain.Server;
import org.jclouds.openstack.nova.domain.ServerStatus;
import org.jclouds.http.HttpResponse;
import org.jclouds.http.functions.UnwrapOnlyJsonValue;
import org.jclouds.io.Payloads;
import org.jclouds.json.config.GsonModule;
import org.jclouds.openstack.nova.domain.Address;
import org.jclouds.openstack.nova.domain.Addresses;
import org.jclouds.openstack.nova.domain.Server;
import org.jclouds.openstack.nova.domain.ServerStatus;
import org.testng.annotations.Test;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.collect.Iterables;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Key;
@ -49,8 +51,15 @@ import com.google.inject.TypeLiteral;
@Test(groups = "unit")
public class ParseServerListFromJsonResponseTest {
Injector i = Guice.createInjector(new GsonModule());
Injector i = Guice.createInjector(new GsonModule() {
@Override
protected void configure() {
super.configure();
bind(DateAdapter.class).to(Iso8601DateAdapter.class);
}
});
@Test
public void testApplyInputStream() {
InputStream is = getClass().getResourceAsStream("/test_list_servers.json");
@ -64,6 +73,7 @@ public class ParseServerListFromJsonResponseTest {
assertEquals(response, expects);
}
@Test
public void testApplyInputStreamDetails() throws UnknownHostException {
InputStream is = getClass().getResourceAsStream("/test_list_servers_detail.json");
@ -74,32 +84,42 @@ public class ParseServerListFromJsonResponseTest {
assertEquals(response.get(0).getId(), 1234);
assertEquals(response.get(0).getName(), "sample-server");
assertEquals(response.get(0).getImageId(), new Integer(2));
assertEquals(response.get(0).getFlavorId(), new Integer(1));
assertEquals(response.get(0).getImageRef(), "https://servers.api.rackspacecloud.com/v1.1/32278/images/1234");
assertEquals(response.get(0).getFlavorRef(), "https://servers.api.rackspacecloud.com/v1.1/32278/flavors/1");
assertEquals(response.get(0).getHostId(), "e4d909c290d0fb1ca068ffaddf22cbd0");
assertEquals(response.get(0).getStatus(), ServerStatus.BUILD);
assertEquals(response.get(0).getProgress(), new Integer(60));
List<String> publicAddresses = Lists.newArrayList("67.23.10.132", "67.23.10.131");
List<String> privateAddresses = Lists.newArrayList("10.176.42.16");
Addresses addresses1 = new Addresses();
addresses1.getPrivateAddresses().addAll(privateAddresses);
addresses1.getPublicAddresses().addAll(publicAddresses);
List<Address> publicAddresses = ImmutableList.copyOf(Iterables.transform(
ImmutableList.of("67.23.10.132", "::babe:67.23.10.132", "67.23.10.131", "::babe:4317:0A83"),
Address.newString2AddressFunction()));
List<Address> privateAddresses = ImmutableList.copyOf(Iterables.transform(
ImmutableList.of("10.176.42.16", "::babe:10.176.42.16"),
Address.newString2AddressFunction()));
Addresses addresses1 = new Addresses(new HashSet<Address>(publicAddresses), new HashSet<Address>(privateAddresses));
assertEquals(response.get(0).getAddresses(), addresses1);
assertEquals(response.get(0).getMetadata(), ImmutableMap.of("Server Label", "Web Head 1", "Image Version", "2.1"));
assertEquals(response.get(1).getId(), 5678);
assertEquals(response.get(1).getName(), "sample-server2");
assertEquals(response.get(1).getImageId(), new Integer(2));
assertEquals(response.get(1).getFlavorId(), new Integer(1));
assertEquals(response.get(1).getImageRef(), "https://servers.api.rackspacecloud.com/v1.1/32278/images/1");
assertEquals(response.get(1).getFlavorRef(), "1");
assertEquals(response.get(1).getAffinityId(), "b414fa41cb37b97dcb58d6c76112af1258e9eae2");
assertEquals(response.get(1).getHostId(), "9e107d9d372bb6826bd81d3542a419d6");
assertEquals(response.get(1).getStatus(), ServerStatus.ACTIVE);
assertEquals(response.get(1).getProgress(), null);
List<String> publicAddresses2 = Lists.newArrayList("67.23.10.133");
List<String> privateAddresses2 = Lists.newArrayList("10.176.42.17");
Addresses addresses2 = new Addresses();
addresses2.getPrivateAddresses().addAll(privateAddresses2);
addresses2.getPublicAddresses().addAll(publicAddresses2);
List<Address> publicAddresses2 = ImmutableList.copyOf(Iterables.transform(
ImmutableList.of("67.23.10.133", "::babe:67.23.10.133"),
Address.newString2AddressFunction()));
List<Address> privateAddresses2 = ImmutableList.copyOf(Iterables.transform(
ImmutableList.of("10.176.42.17", "::babe:10.176.42.17"),
Address.newString2AddressFunction()));
Addresses addresses2 = new Addresses(new HashSet<Address>(publicAddresses2), new HashSet<Address>(privateAddresses2));
assertEquals(response.get(1).getAddresses(), addresses2);
assertEquals(response.get(1).getMetadata(), ImmutableMap.of("Server Label", "DB 1"));
assertEquals(response.get(1).getURI().toString(), "http://servers.api.openstack.org/1234/servers/56789");
}

View File

@ -0,0 +1,78 @@
/**
*
* Copyright (C) 2011 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* 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.openstack.nova.live;
import com.google.common.base.Charsets;
import com.google.common.collect.ImmutableMap;
import com.google.common.io.Files;
import org.jclouds.Constants;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.Properties;
/**
* @author Victor Galkin
*/
public class PropertyHelper {
private static String provider = "nova";
public static void overridePropertyFromSystemProperty(final Properties properties, String propertyName) {
if ((System.getProperty(propertyName) != null) && !System.getProperty(propertyName).equals("${" + propertyName + "}"))
properties.setProperty(propertyName, System.getProperty(propertyName));
}
public static Map<String, String> setupKeyPair(Properties properties) throws FileNotFoundException, IOException {
return ImmutableMap.<String, String>of(
"private", Files.toString(new File(properties.getProperty("test.ssh.keyfile.private")), Charsets.UTF_8),
"public", Files.toString(new File(properties.getProperty("test.ssh.keyfile.public")), Charsets.UTF_8));
}
public static Properties setupProperties(Class<?> clazz) throws IOException {
Properties properties = new Properties();
InputStream propertiesStream = clazz.getResourceAsStream("/test.properties");
if (propertiesStream != null)
properties.load(propertiesStream);
overridePropertyFromSystemProperty(properties, "test." + provider + ".endpoint");
overridePropertyFromSystemProperty(properties, "test." + provider + ".apiversion");
overridePropertyFromSystemProperty(properties, "test." + provider + ".identity");
overridePropertyFromSystemProperty(properties, "test." + provider + ".credential");
overridePropertyFromSystemProperty(properties, "test.ssh.keyfile.private");
overridePropertyFromSystemProperty(properties, "test.ssh.keyfile.public");
overridePropertyFromSystemProperty(properties, "test.initializer");
return properties;
}
public static Properties setupOverrides(final Properties properties) {
properties.setProperty(provider + ".identity", properties.getProperty("test." + provider + ".identity"));
properties.setProperty(provider + ".credential", properties.getProperty("test." + provider + ".credential"));
properties.setProperty(provider + ".endpoint", properties.getProperty("test." + provider + ".endpoint"));
properties.setProperty(provider + ".apiversion", properties.getProperty("test." + provider + ".apiversion"));
properties.setProperty(Constants.PROPERTY_TRUST_ALL_CERTS, "true");
properties.setProperty(Constants.PROPERTY_RELAX_HOSTNAME, "true");
return properties;
}
}

View File

@ -0,0 +1,173 @@
/**
*
* Copyright (C) 2011 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* 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.openstack.nova.live.compute;
import static com.google.common.base.Predicates.and;
import static com.google.common.base.Predicates.not;
import static com.google.common.collect.Sets.filter;
import static org.jclouds.compute.predicates.NodePredicates.TERMINATED;
import static org.jclouds.compute.predicates.NodePredicates.all;
import static org.jclouds.compute.predicates.NodePredicates.inGroup;
import static org.jclouds.openstack.nova.live.PropertyHelper.setupKeyPair;
import static org.jclouds.openstack.nova.live.PropertyHelper.setupOverrides;
import static org.jclouds.openstack.nova.live.PropertyHelper.setupProperties;
import static org.testng.Assert.assertEquals;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.jclouds.compute.ComputeService;
import org.jclouds.compute.ComputeServiceContext;
import org.jclouds.compute.ComputeServiceContextFactory;
import org.jclouds.compute.RunNodesException;
import org.jclouds.compute.domain.ComputeMetadata;
import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.domain.NodeState;
import org.jclouds.compute.domain.TemplateBuilder;
import org.jclouds.compute.options.TemplateOptions;
import org.jclouds.domain.Credentials;
import org.jclouds.domain.Location;
import org.jclouds.http.handlers.BackoffLimitedRetryHandler;
import org.jclouds.logging.slf4j.config.SLF4JLoggingModule;
import org.jclouds.net.IPSocket;
import org.jclouds.predicates.RetryablePredicate;
import org.jclouds.predicates.SocketOpen;
import org.jclouds.ssh.SshException;
import org.jclouds.ssh.jsch.JschSshClient;
import org.jclouds.ssh.jsch.config.JschSshClientModule;
import org.testng.annotations.BeforeTest;
import com.google.common.collect.ImmutableSet;
import com.google.inject.Guice;
/**
* @author Victor Galkin
*/
public class ComputeBase {
protected ComputeServiceContext context;
protected ComputeService computeService;
protected String provider = "nova";
protected Map<String, String> keyPair;
protected Properties overrides;
@BeforeTest
public void before() throws InterruptedException, ExecutionException, TimeoutException, IOException {
Properties properties = setupProperties(this.getClass());
setupOverrides(properties);
overrides = properties;
keyPair = setupKeyPair(properties);
initializeContextAndComputeService(properties);
}
@SuppressWarnings("unused")
private RetryablePredicate<IPSocket> buildSocket() {
SocketOpen socketOpen = Guice.createInjector(getSshModule()).getInstance(SocketOpen.class);
return new RetryablePredicate<IPSocket>(socketOpen, 60, 1, TimeUnit.SECONDS);
}
private JschSshClientModule getSshModule() {
return new JschSshClientModule();
}
protected TemplateBuilder getDefaultTemplateBuilder() {
return computeService.templateBuilder().imageId("95").options(getDefaultTemplateOptions());
}
private TemplateOptions getDefaultTemplateOptions() {
return TemplateOptions.Builder.blockUntilRunning(false);
//.installPrivateKey(Payloads.newStringPayload(keyPair.get("private")));
}
protected NodeMetadata getDefaultNodeImmediately(String group) throws RunNodesException {
for (ComputeMetadata node : computeService.listNodes()) {
if (((NodeMetadata) node).getGroup() != null)
if (((NodeMetadata) node).getGroup().equals(group))
if (((NodeMetadata) node).getState().equals(NodeState.PENDING)
|| ((NodeMetadata) node).getState().equals(NodeState.RUNNING)) return (NodeMetadata) node;
}
return createDefaultNode(group);
}
protected NodeMetadata createDefaultNode(TemplateOptions options, String group) throws RunNodesException {
return computeService.createNodesInGroup(group, 1, getDefaultTemplateBuilder().options(options).build())
.iterator().next();
}
protected NodeMetadata createDefaultNode(String group) throws RunNodesException {
return createDefaultNode(getDefaultTemplateOptions(), group);
}
protected void initializeContextAndComputeService(Properties properties) throws IOException {
if (context != null)
context.close();
context = new ComputeServiceContextFactory().createContext(provider, ImmutableSet.of(
new SLF4JLoggingModule(), getSshModule()), properties);
computeService = context.getComputeService();
}
protected String awaitForPublicAddressAssigned(String nodeId) throws InterruptedException {
while (true) {
Set<String> addresses = computeService.getNodeMetadata(nodeId).getPublicAddresses();
System.out.println(addresses);
System.out.println(computeService.getNodeMetadata(nodeId).getState());
if (addresses != null)
if (!addresses.isEmpty()) return addresses.iterator().next();
Thread.sleep(1000);
}
}
protected Set<? extends NodeMetadata> getFreshNodes(String group) {
return filter(computeService.listNodesDetailsMatching(all()), and(inGroup(group), not(TERMINATED)));
}
protected void awaitForSshPort(String address, Credentials credentials) throws URISyntaxException {
IPSocket socket = new IPSocket(address, 22);
JschSshClient ssh = new JschSshClient(
new BackoffLimitedRetryHandler(), socket, 10000, credentials.identity, null, credentials.credential.getBytes());
while (true) {
try {
System.out.println("ping: " + socket);
ssh.connect();
return;
} catch (SshException ignore) {
}
}
}
protected void assertLocationSameOrChild(Location test, Location expected) {
if (!test.equals(expected)) {
assertEquals(test.getParent().getId(), expected.getId());
} else {
assertEquals(test, expected);
}
}
}

View File

@ -0,0 +1,95 @@
/**
*
* Copyright (C) 2011 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* 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.openstack.nova.live.compute;
import com.google.common.collect.ImmutableSet;
import org.jclouds.compute.ComputeService;
import org.jclouds.compute.ComputeServiceContext;
import org.jclouds.compute.ComputeServiceContextFactory;
import org.jclouds.compute.RunNodesException;
import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.domain.Template;
import org.jclouds.compute.options.TemplateOptions;
import org.jclouds.logging.slf4j.config.SLF4JLoggingModule;
import org.jclouds.ssh.jsch.config.JschSshClientModule;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import java.io.IOException;
import java.util.NoSuchElementException;
import java.util.Properties;
import java.util.Set;
import static org.jclouds.openstack.nova.live.PropertyHelper.setupOverrides;
import static org.jclouds.openstack.nova.live.PropertyHelper.setupProperties;
/**
* Not intended to be run with maven and does not performs a cleanup after tests
*
* @author Dmitri Babaev
*/
public class ComputeServiceCheck {
private ComputeServiceContextFactory contextFactory;
private ComputeServiceContext context;
@BeforeTest
public void setupClient() throws IOException {
contextFactory = new ComputeServiceContextFactory();
Properties properties = setupOverrides(setupProperties(this.getClass()));
context = contextFactory.createContext("nova",
ImmutableSet.of(new JschSshClientModule(), new SLF4JLoggingModule()), properties);
}
@Test
public void testLists() {
ComputeService cs = context.getComputeService();
System.out.println(cs.listImages());
System.out.println(cs.listHardwareProfiles());
System.out.println(cs.listAssignableLocations());
System.out.println(cs.listNodes());
}
@Test
public void testCreateServer() throws RunNodesException {
ComputeService cs = context.getComputeService();
TemplateOptions options = new TemplateOptions().blockUntilRunning(false);
Template template = cs.templateBuilder().imageId("95").hardwareId("2").options(options).build();
Set<? extends NodeMetadata> metedata = cs.createNodesInGroup("test", 1, template);
System.out.println(metedata);
}
@Test(expectedExceptions = NoSuchElementException.class)
public void testDefaultTempateDoesNotSpecifyTheOS() {
ComputeService cs = context.getComputeService();
Template template = cs.templateBuilder().build();
System.out.println(template);
}
@AfterTest
public void after() {
context.close();
}
//curl -v -H "X-Auth-User:admin" -H "X-Auth-Key: d744752f-20d3-4d75-979f-f62f16033b07" http://dragon004.hw.griddynamics.net:8774/v1.0/
//curl -v -H "X-Auth-Token: c97b10659008d5a9ce91462f8c6a5c2c80439762" http://dragon004.hw.griddynamics.net:8774/v1.0/images/detail?format=json
}

View File

@ -0,0 +1,454 @@
/**
*
* Copyright (C) 2011 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* 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.openstack.nova.live.compute;
import com.google.common.base.Function;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets;
import com.google.inject.Module;
import com.jcraft.jsch.JSchException;
import org.jclouds.compute.ComputeServiceContext;
import org.jclouds.compute.ComputeServiceContextFactory;
import org.jclouds.compute.RunNodesException;
import org.jclouds.compute.RunScriptOnNodesException;
import org.jclouds.compute.domain.*;
import org.jclouds.compute.options.TemplateOptions;
import org.jclouds.domain.Credentials;
import org.jclouds.domain.Location;
import org.jclouds.domain.LocationScope;
import org.jclouds.logging.slf4j.config.SLF4JLoggingModule;
import org.jclouds.rest.AuthorizationException;
import org.jclouds.scriptbuilder.domain.Statements;
import org.jclouds.ssh.SshClient;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.*;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;
import static com.google.common.base.Predicates.and;
import static com.google.common.base.Predicates.not;
import static com.google.common.collect.Iterables.getOnlyElement;
import static com.google.common.collect.Maps.newLinkedHashMap;
import static com.google.common.collect.Maps.uniqueIndex;
import static com.google.common.collect.Sets.filter;
import static com.google.common.collect.Sets.newTreeSet;
import static org.jclouds.compute.ComputeTestUtils.buildScript;
import static org.jclouds.compute.options.TemplateOptions.Builder.overrideCredentialsWith;
import static org.jclouds.compute.predicates.NodePredicates.*;
import static org.jclouds.compute.util.ComputeServiceUtils.getCores;
import static org.jclouds.compute.util.ComputeServiceUtils.parseGroupFromName;
import static org.testng.Assert.*;
/**
* Generally disabled, as it incurs higher fees.
*
* @author Adrian Cole
*/
@Test(groups = "novalive", enabled = true, sequential = true)
public class NovaComputeServiceLiveTest extends ComputeBase {
private static String group = "compute service test group";
protected void checkNodes(Iterable<? extends NodeMetadata> nodes, String tag) throws IOException {
for (NodeMetadata node : nodes) {
assertNotNull(node.getProviderId());
assertNotNull(node.getGroup());
assertEquals(node.getGroup(), group);
//assertEquals(node.getState(), NodeState.RUNNING);
Credentials fromStore = context.getCredentialStore().get("node#" + node.getId());
assertEquals(fromStore, node.getCredentials());
assert node.getPublicAddresses().size() >= 1 || node.getPrivateAddresses().size() >= 1 : "no ips in" + node;
// assertNotNull(node.getCredentials());
// if (node.getCredentials().identity != null) {
// assertNotNull(node.getCredentials().identity);
// assertNotNull(node.getCredentials().credential);
// doCheckJavaIsInstalledViaSsh(node);
// }
assertEquals(node.getLocation().getScope(), LocationScope.HOST);
}
}
@BeforeTest
@Override
public void before() throws IOException, ExecutionException, TimeoutException, InterruptedException {
super.before();
computeService.destroyNodesMatching(inGroup(group));
}
@Test(enabled = true, expectedExceptions = AuthorizationException.class, timeOut = 60000)
public void testCorrectAuthException() throws Exception {
Properties properties = new Properties();
properties.putAll(overrides);
properties.remove(provider + ".identity");
ComputeServiceContext context = null;
try {
context = new ComputeServiceContextFactory().createContext(provider, "MOMMA", "MIA", ImmutableSet
.<Module>of(new SLF4JLoggingModule()), properties);
context.getComputeService().listNodes();
} finally {
if (context != null)
context.close();
}
}
@Test(timeOut = 60000)
public void testImagesCache() throws Exception {
computeService.listImages();
long time = System.currentTimeMillis();
computeService.listImages();
long duration = System.currentTimeMillis() - time;
assert duration < 1000 : String.format("%dms to get images", duration);
}
@Test(enabled = true, expectedExceptions = NoSuchElementException.class, timeOut = 60000)
public void testCorrectExceptionRunningNodesNotFound() throws Exception {
computeService.runScriptOnNodesMatching(runningInGroup("zebras-are-awesome"), buildScript(new OperatingSystem.Builder()
.family(OsFamily.UBUNTU).description("ffoo").build()));
}
@Test(expectedExceptions = JSchException.class, expectedExceptionsMessageRegExp = "Auth fail", timeOut = 60000)
void testScriptExecutionWithWrongCredentials() throws Throwable, RunScriptOnNodesException, URISyntaxException, InterruptedException {
NodeMetadata node = getDefaultNodeImmediately(group);
String address = awaitForPublicAddressAssigned(node.getId());
awaitForSshPort(address, new Credentials("root", keyPair.get("private")));
OperatingSystem os = node.getOperatingSystem();
try {
@SuppressWarnings("unused")
Map<? extends NodeMetadata, ExecResponse> responses = runJavaInstallationScriptWithCreds(group, os, new Credentials(
"root", "romeo"));
} catch (RunScriptOnNodesException e) {
throw e.getNodeErrors().values().iterator().next().getCause();
}
}
@Test(timeOut = 60000)
public void testScriptExecutionAfterBootWithBasicTemplate() throws InterruptedException, RunNodesException, RunScriptOnNodesException, URISyntaxException, IOException {
NodeMetadata node = getDefaultNodeImmediately(group);
String address = awaitForPublicAddressAssigned(node.getId());
awaitForSshPort(address, new Credentials("root", keyPair.get("private")));
for (Map.Entry<? extends NodeMetadata, ExecResponse> response : computeService.runScriptOnNodesMatching(
runningInGroup(group), Statements.exec("echo hello"),
overrideCredentialsWith(new Credentials("root", keyPair.get("private"))).wrapInInitScript(false).runAsRoot(false)).entrySet())
assert response.getValue().getOutput().trim().equals("hello") : response.getKey() + ": "
+ response.getValue();
//TODO runJavaInstallationScriptWithCreds(group, os, new Credentials("root", keyPair.get("private")));
//TODO no response? if os is null (ZYPPER)
checkNodes(Sets.<NodeMetadata>newHashSet(node), group);
@SuppressWarnings("unused")
Credentials good = node.getCredentials();
//TODO check good is being private key .overrideCredentialsWith
//TODO test for .blockOnPort
}
@Test(timeOut = 60000)
public void testTemplateMatch() throws Exception {
Template template = buildTemplate(getDefaultTemplateBuilder());
Template toMatch = computeService.templateBuilder().imageId(template.getImage().getId()).build();
assertEquals(toMatch.getImage(), template.getImage());
}
// protected void checkHttpGet(NodeMetadata node) {
// ComputeTestUtils.checkHttpGet(context.utils().http(), node, 8080);
// }
@Test(timeOut = 60000)
public void testCreateTwoNodesWithRunScript() throws Exception {
computeService.destroyNodesMatching(inGroup(group));
Template template = getDefaultTemplateBuilder().options(TemplateOptions.Builder.blockUntilRunning(true)).build();
SortedSet<NodeMetadata> nodes = newTreeSet(computeService.createNodesInGroup(group, 2, template));
assertEquals(nodes.size(), 2);
checkNodes(nodes, group);
NodeMetadata node1 = nodes.first();
NodeMetadata node2 = nodes.last();
// credentials aren't always the same
// assertEquals(node1.getCredentials(), node2.getCredentials());
assertLocationSameOrChild(node1.getLocation(), template.getLocation());
assertLocationSameOrChild(node2.getLocation(), template.getLocation());
assertEquals(node1.getImageId(), template.getImage().getId());
assertEquals(node2.getImageId(), template.getImage().getId());
// checkOsMatchesTemplate(node1);
// checkOsMatchesTemplate(node2);
//TODO add with script;
}
// protected void checkOsMatchesTemplate(NodeMetadata node) {
// if (node.getOperatingSystem() != null)
// assert node.getOperatingSystem().getFamily().equals(getDefaultTemplateBuilder().build().getImage().getOperatingSystem().getFamily()) : String
// .format("expecting family %s but got %s", getDefaultTemplateBuilder().build().getImage().getOperatingSystem().getFamily(), node
// .getOperatingSystem());
// }
@Test(timeOut = 60000)
public void testCreateAnotherNodeWithNewContextToEnsureSharedMemIsntRequired() throws Exception {
getDefaultNodeImmediately(group);
initializeContextAndComputeService(overrides);
NodeMetadata node = createDefaultNode(TemplateOptions.Builder.blockUntilRunning(true), group);
checkNodes(Sets.<NodeMetadata>newHashSet(node), group);
assertLocationSameOrChild(node.getLocation(), getDefaultTemplateBuilder().build().getLocation());
// checkOsMatchesTemplate(node);
}
@Test(timeOut = 60000)
public void testCredentialsCache() throws Exception {
LinkedList<NodeMetadata> nodes = new LinkedList<NodeMetadata>();
nodes.add(getDefaultNodeImmediately(group));
initializeContextAndComputeService(overrides);
nodes.add(createDefaultNode(group));
initializeContextAndComputeService(overrides);
for (NodeMetadata node : nodes)
assert (context.getCredentialStore().get("node#" + node.getId()) != null) : "credentials for " + node.getId();
}
protected Map<? extends NodeMetadata, ExecResponse> runJavaInstallationScriptWithCreds(final String group, OperatingSystem os,
Credentials creds) throws RunScriptOnNodesException {
return computeService.runScriptOnNodesMatching(runningInGroup(group), buildScript(os), overrideCredentialsWith(creds)
.nameTask("runJavaInstallationScriptWithCreds"));
}
protected Template buildTemplate(TemplateBuilder templateBuilder) {
return templateBuilder.build();
}
@Test(timeOut = 60000)
public void testGetNodeMetadata() throws Exception {
Set<NodeMetadata> nodes = Sets.newHashSet(getDefaultNodeImmediately(group));
awaitForPublicAddressAssigned(nodes.iterator().next().getId());
Map<String, ? extends NodeMetadata> metadataMap = newLinkedHashMap(uniqueIndex(filter(computeService
.listNodesDetailsMatching(all()), and(inGroup(group), not(TERMINATED))),
new Function<NodeMetadata, String>() {
@Override
public String apply(NodeMetadata from) {
return from.getId();
}
}));
for (NodeMetadata node : nodes) {
metadataMap.remove(node.getId());
NodeMetadata nodeMetadata = computeService.getNodeMetadata(node.getId());
assertEquals(parseGroupFromName(nodeMetadata.getName()), group);
assertEquals(nodeMetadata.getProviderId(), node.getProviderId());
assertEquals(nodeMetadata.getGroup(), node.getGroup());
assertLocationSameOrChild(nodeMetadata.getLocation(), getDefaultTemplateBuilder().build().getLocation());
assertEquals(nodeMetadata.getImageId(), getDefaultTemplateBuilder().build().getImage().getId());
// checkOsMatchesTemplate(metadata);
assertEquals(nodeMetadata.getState(), NodeState.RUNNING);
// due to DHCP the addresses can actually change in-between runs.
assertTrue(nodeMetadata.getPrivateAddresses().size() > 0);
assertTrue(nodeMetadata.getPublicAddresses().size() > 0);
}
assertNodeZero(metadataMap.values(), nodes);
}
protected void assertNodeZero(Collection<? extends NodeMetadata> metadataSet, Set<NodeMetadata> nodes) {
assert metadataSet.size() == 0 : String.format("nodes left in set: [%s] which didn't match set: [%s]",
metadataSet, nodes);
}
@Test(timeOut = 60000)
public void testListNodes() throws Exception {
for (ComputeMetadata node : computeService.listNodes()) {
assert node.getProviderId() != null;
assert node.getLocation() != null;
assertEquals(node.getType(), ComputeType.NODE);
}
}
@Test(timeOut = 60000)
public void testGetNodesWithDetails() throws Exception {
for (NodeMetadata node : computeService.listNodesDetailsMatching(all())) {
assert node.getProviderId() != null : node;
assert node.getLocation() != null : node;
assertEquals(node.getType(), ComputeType.NODE);
assert node.getProviderId() != null : node;
// nullable
// assert nodeMetadata.getImage() != null : node;
// user specified name is not always supported
// assert nodeMetadata.getName().parseGroupFromName() != null : nodeMetadata;
if (node.getState() == NodeState.RUNNING) {
assert node.getPublicAddresses() != null : node;
assert node.getPublicAddresses().size() > 0 || node.getPrivateAddresses().size() > 0 : node;
assertNotNull(node.getPrivateAddresses());
}
}
}
@Test(timeOut = 60000)
public void testDestroyNodes() {
int toDestroy = getFreshNodes(group).size();
Set<? extends NodeMetadata> destroyed = computeService.destroyNodesMatching(inGroup(group));
assertEquals(toDestroy, destroyed.size());
for (NodeMetadata node : filter(computeService.listNodesDetailsMatching(all()), inGroup(group))) {
assert node.getState() == NodeState.TERMINATED : node;
assertEquals(context.getCredentialStore().get("node#" + node.getId()), null);
}
}
@Test(timeOut = 60000)
public void testCreateAndRunService() throws Exception {
@SuppressWarnings("unused")
NodeMetadata node = getDefaultNodeImmediately(group);
//TODO .inboundPorts
//checkHttpGet(node);
}
@Test(timeOut = 60000)
public void testTemplateOptions() throws Exception {
TemplateOptions options = new TemplateOptions().withMetadata();
Template t = getDefaultTemplateBuilder().smallest().options(options).build();
assert t.getOptions().isIncludeMetadata() : "The metadata option should be 'true' " + "for the created template";
}
public void testListImages() throws Exception {
for (Image image : computeService.listImages()) {
assert image.getProviderId() != null : image;
// image.getLocationId() can be null, if it is a location-free image
assertEquals(image.getType(), ComputeType.IMAGE);
}
}
@Test(timeOut = 60000)
public void testGetAssignableLocations() throws Exception {
for (Location location : computeService.listAssignableLocations()) {
System.err.printf("location %s%n", location);
assert location.getId() != null : location;
assert location != location.getParent() : location;
assert location.getScope() != null : location;
switch (location.getScope()) {
case PROVIDER:
assertProvider(location);
break;
case REGION:
assertProvider(location.getParent());
break;
case ZONE:
Location provider = location.getParent().getParent();
// zone can be a direct descendant of provider
if (provider == null)
provider = location.getParent();
assertProvider(provider);
break;
case HOST:
Location provider2 = location.getParent().getParent().getParent();
// zone can be a direct descendant of provider
if (provider2 == null)
provider2 = location.getParent().getParent();
assertProvider(provider2);
break;
}
}
}
public void testOptionToNotBlock() throws Exception {
//TODO no inbound ports
//TemplateOptions options = computeService.templateOptions().blockUntilRunning(false).inboundPorts();
long time = System.currentTimeMillis();
NodeMetadata node = getOnlyElement(computeService.createNodesInGroup(group, 1, getDefaultTemplateBuilder().build()));
assert node.getState() != NodeState.RUNNING;
long duration = System.currentTimeMillis() - time;
assert duration < 30 * 1000 : "duration longer than 30 seconds!: " + duration / 1000;
}
private void assertProvider(Location provider) {
assertEquals(provider.getScope(), LocationScope.PROVIDER);
assertEquals(provider.getParent(), null);
}
@Test(timeOut = 60000)
public void testListHardwareProfiles() throws Exception {
for (Hardware hardware : computeService.listHardwareProfiles()) {
assert hardware.getProviderId() != null;
assert getCores(hardware) > 0;
assert hardware.getVolumes().size() >= 0;
assert hardware.getRam() > 0;
assertEquals(hardware.getType(), ComputeType.HARDWARE);
}
}
@Test(timeOut = 60000)
public void testCompareSizes() throws Exception {
TemplateBuilder templateBuilder = getDefaultTemplateBuilder();
Hardware defaultSize = templateBuilder.build().getHardware();
Hardware smallest = templateBuilder.smallest().build().getHardware();
Hardware fastest = templateBuilder.fastest().build().getHardware();
Hardware biggest = templateBuilder.biggest().build().getHardware();
System.out.printf("smallest %s%n", smallest);
System.out.printf("fastest %s%n", fastest);
System.out.printf("biggest %s%n", biggest);
assertEquals(defaultSize, smallest);
assert getCores(smallest) <= getCores(fastest);
assert getCores(biggest) <= getCores(fastest);
assert biggest.getRam() >= fastest.getRam();
assert biggest.getRam() >= smallest.getRam();
assert getCores(fastest) >= getCores(biggest);
assert getCores(fastest) >= getCores(smallest);
}
protected void doCheckJavaIsInstalledViaSsh(NodeMetadata node) throws IOException {
SshClient ssh = context.utils().sshForNode().apply(node);
try {
ssh.connect();
ExecResponse hello = ssh.exec("echo hello");
assertEquals(hello.getOutput().trim(), "hello");
ExecResponse exec = ssh.exec("java -version");
assert exec.getError().indexOf("1.6") != -1 || exec.getOutput().indexOf("1.6") != -1 : exec + "\n"
+ ssh.exec("cat /tmp/bootstrap/stdout.log /tmp/bootstrap/stderr.log");
} finally {
if (ssh != null)
ssh.disconnect();
}
}
@AfterTest
protected void cleanup() throws InterruptedException, ExecutionException, TimeoutException {
computeService.destroyNodesMatching(inGroup(group));
context.close();
}
}

View File

@ -0,0 +1,88 @@
/**
*
* Copyright (C) 2011 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* 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.openstack.nova.live.compute;
import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;
import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.domain.NodeState;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import java.io.IOException;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;
import static org.jclouds.compute.predicates.NodePredicates.inGroup;
/**
* @author Victor Galkin
*/
public class ServiceActionsLiveTest extends ComputeBase {
static private String group = "ServiceActionsLiveTest";
@BeforeTest
@Override
public void before() throws IOException, ExecutionException, TimeoutException, InterruptedException {
super.before();
computeService.destroyNodesMatching(inGroup(group));
}
@Test
public void testReboot() throws Exception {
getDefaultNodeImmediately(group);
computeService.rebootNodesMatching(inGroup(group));// TODO test
Thread.sleep(5000);
// // validation
//testGetNodeMetadata();
}
@Test
public void testSuspendResume() throws Exception {
getDefaultNodeImmediately(group);
computeService.suspendNodesMatching(inGroup(group));
Set<? extends NodeMetadata> stoppedNodes = getFreshNodes(group);
assert Iterables.all(stoppedNodes, new Predicate<NodeMetadata>() {
@Override
public boolean apply(NodeMetadata input) {
boolean returnVal = input.getState() == NodeState.SUSPENDED;
if (!returnVal)
System.err.printf("warning: node %s in state %s%n", input.getId(), input.getState());
return returnVal;
}
}) : stoppedNodes;
computeService.resumeNodesMatching(inGroup(group));
//testGetNodeMetadata();
}
@AfterTest
protected void cleanup() throws InterruptedException, ExecutionException, TimeoutException {
computeService.destroyNodesMatching(inGroup(group));
context.close();
}
}

View File

@ -0,0 +1,115 @@
/**
*
* Copyright (C) 2011 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* 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.openstack.nova.live.novaclient;
import com.google.common.base.Predicate;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.inject.Injector;
import com.google.inject.Module;
import org.jclouds.logging.slf4j.config.SLF4JLoggingModule;
import org.jclouds.net.IPSocket;
import org.jclouds.openstack.nova.NovaClient;
import org.jclouds.openstack.nova.domain.Image;
import org.jclouds.openstack.nova.domain.Server;
import org.jclouds.predicates.RetryablePredicate;
import org.jclouds.predicates.SocketOpen;
import org.jclouds.rest.RestContextFactory;
import org.jclouds.ssh.SshClient;
import org.jclouds.ssh.jsch.config.JschSshClientModule;
import org.testng.annotations.BeforeTest;
import java.io.IOException;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import static org.jclouds.openstack.nova.live.PropertyHelper.*;
import static org.jclouds.openstack.nova.options.CreateServerOptions.Builder.withFile;
/**
* @author Victor Galkin
*/
public class ClientBase {
protected int testImageId = 95;
protected NovaClient client;
protected SshClient.Factory sshFactory;
@SuppressWarnings("unused")
private Predicate<IPSocket> socketTester;
protected String provider = "nova";
protected String serverPrefix = System.getProperty("user.name") + ".cs";
protected Map<String, String> keyPair;
Map<String, String> metadata = ImmutableMap.of("jclouds", "rackspace");
@BeforeTest
public void before() throws IOException {
Properties properties = setupOverrides(setupProperties(this.getClass()));
Injector injector = new RestContextFactory().createContextBuilder(provider,
ImmutableSet.<Module>of(new SLF4JLoggingModule(), new JschSshClientModule()), properties)
.buildInjector();
client = injector.getInstance(NovaClient.class);
sshFactory = injector.getInstance(SshClient.Factory.class);
SocketOpen socketOpen = injector.getInstance(SocketOpen.class);
socketTester = new RetryablePredicate<IPSocket>(socketOpen, 120, 1, TimeUnit.SECONDS);
injector.injectMembers(socketOpen); // add logger
keyPair = setupKeyPair(properties);
}
protected Server getDefaultServerImmediately() {
String defaultName = serverPrefix + "default";
for (Server server : client.listServers()) {
if (server.getName().equals(defaultName))
return server;
}
return createDefaultServer(defaultName);
}
private Server createDefaultServer(String serverName) {
String imageRef = client.getImage(testImageId).getURI().toASCIIString();
String flavorRef = client.getFlavor(1).getURI().toASCIIString();
return client.createServer(serverName, imageRef, flavorRef, withFile("/etc/jclouds.txt",
"rackspace".getBytes()).withMetadata(metadata));
}
protected Image getDefaultImageImmediately(Server server) {
String defaultName = "hoofie";
for (Image image : client.listImages()) {
if (image.getName() != null)
if (image.getName().equals(defaultName))
return image;
}
return createDefaultImage("hoofie", server);
}
private Image createDefaultImage(String name, Server server) {
return client.createImageFromServer("hoofie", server.getId());
}
protected void waitServerDeleted(int serverId) throws InterruptedException {
while (null != client.getServer(serverId)) {
System.out.println("Await deleted server" + serverId);
Thread.sleep(1000);
}
}
}

View File

@ -0,0 +1,67 @@
/**
*
* Copyright (C) 2011 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* 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.openstack.nova.live.novaclient;
import com.google.common.base.Predicate;
import com.google.common.collect.ImmutableMap;
import org.jclouds.net.IPSocket;
import org.jclouds.openstack.nova.NovaClient;
import org.jclouds.openstack.nova.domain.Server;
import org.jclouds.openstack.nova.domain.ServerStatus;
import org.jclouds.ssh.SshClient;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.Test;
import java.util.Map;
/**
* @author Victor Galkin
*/
@Test(groups = "live", sequential = true)
public class DeleteServersInVariousStatesLiveTest {
protected NovaClient client;
protected SshClient.Factory sshFactory;
@SuppressWarnings("unused")
private Predicate<IPSocket> socketTester;
protected String provider = "nova";
Map<String, String> metadata = ImmutableMap.of("jclouds", "rackspace");
Server server = null;
@AfterMethod
public void after() {
if (server != null) client.deleteServer(server.getId());
}
@Test(enabled = true)
public void testDeleteAfterCreate() throws Exception {
}
@SuppressWarnings("unused")
private void blockUntilServerActive(int serverId) throws InterruptedException {
Server currentDetails;
for (currentDetails = client.getServer(serverId); currentDetails.getStatus() != ServerStatus.ACTIVE; currentDetails = client
.getServer(serverId)) {
System.out.printf("blocking on status active%n%s%n", currentDetails);
Thread.sleep(5 * 1000);
}
}
}

View File

@ -0,0 +1,382 @@
/**
*
* Copyright (C) 2011 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* 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.openstack.nova.live.novaclient;
import com.google.common.collect.Iterables;
import org.jclouds.domain.Credentials;
import org.jclouds.http.HttpResponseException;
import org.jclouds.io.Payload;
import org.jclouds.net.IPSocket;
import org.jclouds.openstack.nova.domain.*;
import org.jclouds.openstack.nova.options.RebuildServerOptions;
import org.jclouds.ssh.SshClient;
import org.jclouds.util.Strings2;
import org.testng.annotations.AfterTest;
import org.testng.annotations.Test;
import java.io.IOException;
import java.util.Set;
import static org.jclouds.openstack.nova.options.ListOptions.Builder.withDetails;
import static org.testng.Assert.*;
/**
* Tests behavior of {@code NovaClient}
*
* @author Adrian Cole
*/
// disabled [Web Hosting #129069
@Test(groups = "live", sequential = true)
public class NovaClientLiveTest extends ClientBase {
@Test
public void testListServers() throws Exception {
Set<Server> response = client.listServers();
assert null != response;
long initialContainerCount = response.size();
assertTrue(initialContainerCount >= 0);
}
@Test
public void testListServersDetail() throws Exception {
Set<Server> response = client.listServers(withDetails());
assert null != response;
long initialContainerCount = response.size();
assertTrue(initialContainerCount >= 0);
}
@Test
public void testListImages() throws Exception {
Set<Image> response = client.listImages();
assert null != response;
long imageCount = response.size();
assertTrue(imageCount >= 1);
for (Image image : response) {
assertTrue(image.getId() >= 0);
assert null != image.getName() : image;
}
}
@Test
public void testListImagesDetail() throws Exception {
Set<Image> response = client.listImages(withDetails());
assert null != response;
long imageCount = response.size();
assertTrue(imageCount >= 0);
for (Image image : response) {
assertTrue(image.getId() >= 1);
assert null != image.getName() : image;
assert null != image.getStatus() : image;
}
}
@Test
public void testGetImagesDetail() throws Exception {
Set<Image> response = client.listImages(withDetails());
assert null != response;
long imageCount = response.size();
assertTrue(imageCount >= 0);
for (Image image : response) {
try {
Image newDetails = client.getImage(image.getId());
assertEquals(image, newDetails);
} catch (HttpResponseException e) {// Ticket #9867
if (e.getResponse().getStatusCode() != 400)
throw e;
}
}
}
@Test
public void testGetImageDetailsNotFound() throws Exception {
assert client.getImage(12312987) == null;
}
@Test
public void testGetServerDetailsNotFound() throws Exception {
assert client.getServer(12312987) == null;
}
@Test
public void testGetServersDetail() throws Exception {
Set<Server> response = client.listServers(withDetails());
assert null != response;
assertTrue(response.size() >= 0);
for (Server server : response) {
Server newDetails = client.getServer(server.getId());
System.out.println("====");
System.out.println(server);
System.out.println(newDetails);
System.out.println("====");
}
for (Server server : response) {
Server newDetails = client.getServer(server.getId());
assertEquals(server, newDetails);
}
}
@Test
public void testListFlavors() throws Exception {
Set<Flavor> response = client.listFlavors();
assert null != response;
long flavorCount = response.size();
assertTrue(flavorCount >= 1);
for (Flavor flavor : response) {
assertTrue(flavor.getId() >= 0);
assert null != flavor.getName() : flavor;
}
}
@Test
public void testListFlavorsDetail() throws Exception {
Set<Flavor> response = client.listFlavors(withDetails());
assert null != response;
long flavorCount = response.size();
assertTrue(flavorCount >= 0);
for (Flavor flavor : response) {
assertTrue(flavor.getId() >= 1);
assert null != flavor.getName() : flavor;
assert null != flavor.getDisk() : flavor;
assert null != flavor.getRam() : flavor;
}
}
@Test
public void testGetFlavorsDetail() throws Exception {
Set<Flavor> response = client.listFlavors(withDetails());
assert null != response;
long flavorCount = response.size();
assertTrue(flavorCount >= 0);
for (Flavor flavor : response) {
Flavor newDetails = client.getFlavor(flavor.getId());
assertEquals(flavor, newDetails);
}
}
@Test
public void testGetFlavorDetailsNotFound() throws Exception {
assert client.getFlavor(12312987) == null;
}
@Test(enabled = true)
public void testCreateServer() throws Exception {
Server server = getDefaultServerImmediately();
assertNotNull(server.getAdminPass());
assertEquals(server.getStatus(), ServerStatus.BUILD);
int serverId = server.getId();
@SuppressWarnings("unused")
String adminPass = server.getAdminPass();
blockUntilServerActive(serverId);
blockUntilPublicAddress(serverId);
client.getServer(serverId).getAddresses().getPublicAddresses().iterator().next().getAddress();
}
private void blockUntilPublicAddress(int serverId) throws InterruptedException {
while (client.getServer(serverId).getAddresses().getPublicAddresses().isEmpty()) {
System.out.println("Awaiting public address");
Thread.sleep(1000);
}
}
private void blockUntilServerActive(int serverId) throws InterruptedException {
Server currentDetails;
for (currentDetails = client.getServer(serverId); currentDetails.getStatus() != ServerStatus.ACTIVE; currentDetails = client
.getServer(serverId)) {
System.out.printf("blocking on status active%n%s%n", currentDetails);
Thread.sleep(5 * 1000);
}
}
private void blockUntilServerVerifyResize(int serverId) throws InterruptedException {
Server currentDetails;
for (currentDetails = client.getServer(serverId); currentDetails.getStatus() != ServerStatus.VERIFY_RESIZE; currentDetails = client
.getServer(serverId)) {
System.out.printf("blocking on status verify resize%n%s%n", currentDetails);
Thread.sleep(5 * 1000);
}
}
private void blockUntilImageActive(int createdImageId) throws InterruptedException {
Image currentDetails;
for (currentDetails = client.getImage(createdImageId); currentDetails.getStatus() != ImageStatus.ACTIVE; currentDetails = client
.getImage(createdImageId)) {
System.out.printf("blocking on status active%n%s%n", currentDetails);
Thread.sleep(5 * 1000);
}
}
@Test(enabled = true, timeOut = 300000)
public void testServerDetails() throws Exception {
Server server = getDefaultServerImmediately();
assertNotNull(server.getHostId(), "Host id: ");
assertEquals(server.getStatus(), ServerStatus.ACTIVE);
assertNotNull(server.getAddresses());
// check metadata
assertEquals(server.getMetadata(), metadata);
assertTrue(server.getImageRef().endsWith(String.valueOf(testImageId)));
// listAddresses tests..
assertEquals(client.getAddresses(server.getId()), server.getAddresses());
assertEquals(server.getAddresses().getPublicAddresses().size(), 1);
assertEquals(client.listPublicAddresses(server.getId()), server.getAddresses().getPublicAddresses());
assertEquals(server.getAddresses().getPrivateAddresses().size(), 1);
assertEquals(client.listPrivateAddresses(server.getId()), server.getAddresses().getPrivateAddresses());
assertPassword(server, server.getAdminPass());
assertTrue(server.getFlavorRef().endsWith("1"));
assert server.getProgress() >= 0 : "newDetails.getProgress()" + server.getProgress();
}
private void assertPassword(Server server, String pass) throws IOException {
IPSocket socket = new IPSocket(Iterables.get(server.getAddresses().getPublicAddresses(), 0).getAddress(), 22);
//socketTester.apply(socket);
SshClient client = sshFactory.create(socket, new Credentials("root", keyPair.get("private")));
try {
client.connect();
Payload etcPasswd = client.get("/etc/jclouds.txt");
String etcPasswdContents = Strings2.toStringAndClose(etcPasswd.getInput());
assertEquals("rackspace", etcPasswdContents.trim());
} finally {
if (client != null)
client.disconnect();
}
}
@Test(enabled = true, timeOut = 5 * 60 * 1000)
public void testRenameServer() throws Exception {
Server server = getDefaultServerImmediately();
int serverId = server.getId();
String oldName = server.getName();
client.renameServer(serverId, oldName + "new");
blockUntilServerActive(serverId);
assertEquals(oldName + "new", client.getServer(serverId).getName());
}
@Test(enabled = true, timeOut = 5 * 60 * 1000)
public void testChangePassword() throws Exception {
int serverId = getDefaultServerImmediately().getId();
blockUntilServerActive(serverId);
client.changeAdminPass(serverId, "elmo");
assertPassword(client.getServer(serverId), "elmo");
}
@Test(enabled = true, timeOut = 10 * 600 * 1000)
public void testCreateImage() throws Exception {
Server server = getDefaultServerImmediately();
Image image = getDefaultImageImmediately(server);
blockUntilImageActive(image.getId());
assertEquals("hoofie", image.getName());
assertEquals(image.getServerRef(), "");
}
@Test(enabled = true, timeOut = 10 * 60 * 1000)
public void testRebuildServer() throws Exception {
Server server = getDefaultServerImmediately();
Image image = getDefaultImageImmediately(server);
client.rebuildServer(server.getId(), new RebuildServerOptions().withImage(String.valueOf(image.getId())));
blockUntilServerActive(server.getId());
// issue Web Hosting #119580 createdImageId comes back incorrect after rebuild
assertEquals(image.getURI(), client.getServer(server.getId()).getImageRef());
}
@Test(enabled = true, timeOut = 10 * 60 * 1000)
public void testRebootHard() throws Exception {
Server server = getDefaultServerImmediately();
client.rebootServer(server.getId(), RebootType.HARD);
blockUntilServerActive(server.getId());
//TODO check
}
@Test(enabled = true, timeOut = 10 * 60 * 1000)
public void testRebootSoft() throws Exception {
Server server = getDefaultServerImmediately();
client.rebootServer(server.getId(), RebootType.SOFT);
blockUntilServerActive(server.getId());
//TODO check
}
@Test(enabled = false, timeOut = 60000, dependsOnMethods = "testRebootSoft")
public void testRevertResize() throws Exception {
Server server = getDefaultServerImmediately();
int serverId = server.getId();
client.resizeServer(serverId, 2);
blockUntilServerVerifyResize(serverId);
client.revertResizeServer(serverId);
blockUntilServerActive(serverId);
assertEquals(1, client.getServer(serverId).getFlavorRef());
}
@Test(enabled = false, timeOut = 10 * 60 * 1000)
public void testConfirmResize() throws Exception {
Server server = getDefaultServerImmediately();
int serverId = server.getId();
client.resizeServer(serverId, 2);
blockUntilServerVerifyResize(serverId);
client.confirmResizeServer(serverId);
blockUntilServerActive(serverId);
assertEquals(2, client.getServer(serverId).getFlavorRef());
}
@Test(enabled = true, timeOut = 60000)
void deleteServer2() throws Exception {
Server server = getDefaultServerImmediately();
int serverId = server.getId();
client.deleteServer(serverId);
waitServerDeleted(serverId);
}
@Test(enabled = true, timeOut = 60000)
void testDeleteImage() throws Exception {
Image image = getDefaultImageImmediately(getDefaultServerImmediately());
client.deleteImage(image.getId());
assert client.getImage(image.getId()) == null;
}
@Test(enabled = true, timeOut = 60000)
void deleteServer1() throws Exception {
Server server = getDefaultServerImmediately();
int serverId = server.getId();
client.deleteServer(serverId);
waitServerDeleted(serverId);
}
@Test
public void testDeleteAllCreatedServers() {
for (Server server : client.listServers()) {
if (server.getName().startsWith(serverPrefix)) {
client.deleteServer(server.getId());
System.out.println("Deleted server: " + server);
}
}
}
@AfterTest
void deleteServersOnEnd() {
testDeleteAllCreatedServers();
}
}

View File

@ -0,0 +1,133 @@
/**
*
* Copyright (C) 2011 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* 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.openstack.nova.live.novaclient;
import com.google.common.base.Predicate;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.inject.Injector;
import com.google.inject.Module;
import org.jclouds.http.HttpResponseException;
import org.jclouds.logging.slf4j.config.SLF4JLoggingModule;
import org.jclouds.net.IPSocket;
import org.jclouds.openstack.nova.NovaClient;
import org.jclouds.openstack.nova.domain.Server;
import org.jclouds.openstack.nova.domain.ServerStatus;
import org.jclouds.predicates.RetryablePredicate;
import org.jclouds.predicates.SocketOpen;
import org.jclouds.rest.RestContextFactory;
import org.jclouds.ssh.SshClient;
import org.jclouds.ssh.jsch.config.JschSshClientModule;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import java.io.IOException;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import static org.jclouds.openstack.nova.live.PropertyHelper.*;
import static org.jclouds.openstack.nova.options.CreateServerOptions.Builder.withFile;
/**
* @author Victor Galkin
*/
@Test(groups = "live", sequential = true)
public class ServerCreateLiveTest {
protected NovaClient client;
protected SshClient.Factory sshFactory;
@SuppressWarnings("unused")
private Predicate<IPSocket> socketTester;
protected String provider = "nova";
Map<String, String> metadata = ImmutableMap.of("jclouds", "rackspace");
Server server = null;
Map<String, String> keyPair;
@BeforeTest
public void setupClient() throws IOException {
Properties properties = setupOverrides(setupProperties(this.getClass()));
Injector injector = new RestContextFactory().createContextBuilder(provider,
ImmutableSet.<Module>of(new SLF4JLoggingModule(), new JschSshClientModule()), properties)
.buildInjector();
client = injector.getInstance(NovaClient.class);
sshFactory = injector.getInstance(SshClient.Factory.class);
SocketOpen socketOpen = injector.getInstance(SocketOpen.class);
socketTester = new RetryablePredicate<IPSocket>(socketOpen, 120, 1, TimeUnit.SECONDS);
injector.injectMembers(socketOpen); // add logger
keyPair = setupKeyPair(properties);
}
@Test(expectedExceptions = HttpResponseException.class, expectedExceptionsMessageRegExp = ".*Internal Server Error.*")
public void testCreateServerWithUnknownImage() throws Exception {
try {
server = client.createServer("serverName", String.valueOf(88888888), "1", withFile("/etc/jclouds.txt",
"rackspace".getBytes()).withMetadata(metadata));
} catch (HttpResponseException e) {
throw e;
}
}
@Test(expectedExceptions = HttpResponseException.class, expectedExceptionsMessageRegExp = ".*Internal Server Error.*")
public void testCreateServerWithUnknownFlavor() throws Exception {
try {
server = client.createServer("serverName", String.valueOf(13), "88888888", withFile("/etc/jclouds.txt",
"rackspace".getBytes()).withMetadata(metadata));
} catch (HttpResponseException e) {
throw e;
}
}
@AfterMethod
public void after() {
if (server != null) client.deleteServer(server.getId());
}
@Test(enabled = true)
public void testCreateServer() throws Exception {
// String imageRef = client.getImage(13).getURI().toASCIIString();
// String flavorRef = client.getFlavor(1).getURI().toASCIIString();
// String serverName = serverPrefix + "createserver" + new SecureRandom().nextInt();
// Server server = client.createServer(serverName, imageRef, flavorRef, withFile("/etc/jclouds.txt",
// "rackspace".getBytes()).withMetadata(metadata));
//
// assertNotNull(server.getAdminPass());
// assertEquals(server.getStatus(), ServerStatus.BUILD);
// serverId = server.getId();
// adminPass = server.getAdminPass();
// blockUntilServerActive(serverId);
// client.getServer(serverId).getAddresses().getPublicAddresses().iterator().next().getAddress();
}
@SuppressWarnings("unused")
private void blockUntilServerActive(int serverId) throws InterruptedException {
Server currentDetails;
for (currentDetails = client.getServer(serverId); currentDetails.getStatus() != ServerStatus.ACTIVE; currentDetails = client
.getServer(serverId)) {
System.out.printf("blocking on status active%n%s%n", currentDetails);
Thread.sleep(5 * 1000);
}
}
}

View File

@ -18,20 +18,18 @@
*/
package org.jclouds.openstack.nova.options;
import static org.jclouds.openstack.nova.options.CreateSharedIpGroupOptions.Builder.withServer;
import static org.testng.Assert.assertEquals;
import java.net.URI;
import javax.ws.rs.HttpMethod;
import com.google.common.collect.ImmutableMap;
import com.google.inject.Guice;
import com.google.inject.Injector;
import org.jclouds.http.HttpRequest;
import org.jclouds.json.config.GsonModule;
import org.testng.annotations.Test;
import com.google.common.collect.ImmutableMap;
import com.google.inject.Guice;
import com.google.inject.Injector;
import javax.ws.rs.HttpMethod;
import java.net.URI;
import static org.jclouds.openstack.nova.options.CreateServerOptions.Builder.withFile;
import static org.testng.Assert.assertEquals;
/**
* Tests behavior of {@code ParseFlavorFromJsonResponse}
@ -39,41 +37,45 @@ import com.google.inject.Injector;
* @author Adrian Cole
*/
@Test(groups = "unit")
public class CreateSharedIpGroupOptionsTest {
public class CreateServerOptionsTest {
Injector injector = Guice.createInjector(new GsonModule());
@Test
public void testAddPayloadToRequestMapOfStringStringHttpRequest() {
CreateSharedIpGroupOptions options = new CreateSharedIpGroupOptions();
CreateServerOptions options = new CreateServerOptions();
HttpRequest request = buildRequest(options);
assertEquals("{\"sharedIpGroup\":{\"name\":\"foo\"}}", request.getPayload().getRawContent());
assertEquals("{\"server\":{\"name\":\"foo\",\"imageRef\":\"1\",\"flavorRef\":\"2\"}}", request.getPayload().getRawContent());
}
private HttpRequest buildRequest(CreateSharedIpGroupOptions options) {
private HttpRequest buildRequest(CreateServerOptions options) {
injector.injectMembers(options);
HttpRequest request = new HttpRequest(HttpMethod.POST, URI.create("http://localhost"));
options.bindToRequest(request, ImmutableMap.of("name", "foo"));
options.bindToRequest(request, ImmutableMap.of("name", "foo", "imageRef", "1", "flavorRef", "2"));
return request;
}
@Test
public void testWithServer() {
CreateSharedIpGroupOptions options = new CreateSharedIpGroupOptions();
options.withServer(3);
public void testWithFile() {
CreateServerOptions options = new CreateServerOptions();
options.withFile("/tmp/rhubarb", "foo".getBytes());
HttpRequest request = buildRequest(options);
assertSharedIpGroup(request);
assertFile(request);
}
@Test
public void testWithServerStatic() {
CreateSharedIpGroupOptions options = withServer(3);
public void testWithFileStatic() {
CreateServerOptions options = withFile("/tmp/rhubarb", "foo".getBytes());
HttpRequest request = buildRequest(options);
assertSharedIpGroup(request);
assertFile(request);
}
private void assertSharedIpGroup(HttpRequest request) {
assertEquals("{\"sharedIpGroup\":{\"name\":\"foo\",\"server\":3}}", request.getPayload().getRawContent());
private void assertFile(HttpRequest request) {
assertEquals(request.getPayload().getRawContent(),
"{\"server\":{\"name\":\"foo\",\"imageRef\":\"1\",\"flavorRef\":\"2\",\"personality\":[{\"path\":\"/tmp/rhubarb\",\"contents\":\"Zm9v\"}]}}");
}
@Test
public void testWithMetadata() {
}
}

View File

@ -18,17 +18,13 @@
*/
package org.jclouds.openstack.nova.options;
import static org.jclouds.openstack.nova.options.ListOptions.Builder.changesSince;
import static org.jclouds.openstack.nova.options.ListOptions.Builder.maxResults;
import static org.jclouds.openstack.nova.options.ListOptions.Builder.startAt;
import static org.jclouds.openstack.nova.options.ListOptions.Builder.withDetails;
import static org.testng.Assert.assertEquals;
import com.google.common.collect.ImmutableList;
import org.testng.annotations.Test;
import java.util.Date;
import org.testng.annotations.Test;
import com.google.common.collect.ImmutableList;
import static org.jclouds.openstack.nova.options.ListOptions.Builder.*;
import static org.testng.Assert.assertEquals;
/**
* Tests behavior of {@code ListOptions}

View File

@ -18,20 +18,18 @@
*/
package org.jclouds.openstack.nova.options;
import static org.jclouds.openstack.nova.options.RebuildServerOptions.Builder.withImage;
import static org.testng.Assert.assertEquals;
import java.net.URI;
import java.util.HashMap;
import javax.ws.rs.HttpMethod;
import com.google.inject.Guice;
import com.google.inject.Injector;
import org.jclouds.http.HttpRequest;
import org.jclouds.json.config.GsonModule;
import org.testng.annotations.Test;
import com.google.inject.Guice;
import com.google.inject.Injector;
import javax.ws.rs.HttpMethod;
import java.net.URI;
import java.util.HashMap;
import static org.jclouds.openstack.nova.options.RebuildServerOptions.Builder.withImage;
import static org.testng.Assert.assertEquals;
/**
* Tests behavior of {@code ParseFlavorFromJsonResponse}
@ -60,20 +58,20 @@ public class RebuildServerOptionsTest {
@Test
public void testWithServer() {
RebuildServerOptions options = new RebuildServerOptions();
options.withImage(3);
options.withImage("3");
HttpRequest request = buildRequest(options);
assertRebuild(request);
}
@Test
public void testWithServerStatic() {
RebuildServerOptions options = withImage(3);
RebuildServerOptions options = withImage("3");
HttpRequest request = buildRequest(options);
assertRebuild(request);
}
private void assertRebuild(HttpRequest request) {
assertEquals("{\"rebuild\":{\"imageId\":3}}", request.getPayload().getRawContent());
assertEquals("{\"rebuild\":{\"imageRef\":\"3\"}}", request.getPayload().getRawContent());
}
}

View File

@ -0,0 +1 @@
/test.properties

View File

@ -0,0 +1,15 @@
-----BEGIN RSA PRIVATE KEY-----
MIICWgIBAAKBgQDItJzHxyFVPZwjE2Wl+17OLJotFruaMaoKLOH8yOr0WnKFYDCs
AiN88AvwH2YKaF6SQR3gmMTE8SbuKSXR/PVUZfWfhvDinVbAi8gn8A6P5xkym5A6
uBnJn1Mb0rZAKCJT/nN62vomGGO/3VYkpQcKAWgfSpaB7F1BIebaWR/CgQIBIwKB
gQCa1Hjx4sHxTMjn28NxaiSQa4zg9EeUNPDjRzH9hQ0FpNwAfWdgHugtLjUYUrxu
bcVMQNyIsF1HeDP5jXTycq6e01EYDODnuPC3a06u6Drep0xm/8XuODwekApN811r
kfx9AsgRL9ZwkLqMY8E+OXUmsGVXzEM9jUO3iwA4CCBb/wJBAO0klCumLDm9rYXX
m3YHuwqcgFPnwSodTWX4tIzHKM0tn3PwajJ1x9kCVxsj9uFzz4LXNrxVrUKcYnVx
e/d7sksCQQDYqkr+vt9XaoQSio1M/OOkzc3ynmqtYrNrq9xM1M5IYY2/y5IVLAU3
6tiyqXTObSTJT+iFd+OwQymi8FgeN77jAkBzLwYj1F6fs+aRd1ojYtcxCi+zubWY
HNxzW4rlSsqszQROQZKqy35TdipPAtb/yolczu6zP46rU0XEA+vBWVaZAkB1nkX4
ATdp9/6NuO2e0mzzEKMADNrTJvOveo2Iy0tpHwPOhHPfm43N5eNZrHKb8htItlmn
ijnGFdTGKrN+HkMNAkAqh8ulNxVBAK5E0VzzzC2zAh2UFRe3J5K0SgzFkR8W9aM1
Vb+iZvj4tVlbFtFLGv0ssty8Q0jS7+Hy75XMatry
-----END RSA PRIVATE KEY-----

View File

@ -0,0 +1,15 @@
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="info">
<appender-ref ref="STDOUT" />
</root>
<logger name="org.jclouds" level="debug" />
</configuration>

View File

@ -0,0 +1,7 @@
test.nova.endpoint=http://dragon004.hw.griddynamics.net:8774
test.nova.apiversion=1.1
test.nova.identity=admin
test.nova.credential=d744752f-20d3-4d75-979f-f62f16033b07
test.initializer=
test.ssh.keyfile.private=f:/gigaspace/distr/gigaspaces.pem
test.ssh.keyfile.public=f:/gigaspace/distr/gigaspaces.pem

View File

@ -0,0 +1,9 @@
{
"overLimit" : {
"code" : 413,
"message" : "OverLimit Retry...",
"details" : "Error Details...",
"retryAt" : "2010-08-01T00:00:00Z"
}
}

View File

@ -0,0 +1,24 @@
{
"flavor" : {
"id" : 1,
"name" : "256 MB Server",
"ram" : 256,
"disk" : 10,
"links": [
{
"rel" : "self",
"href" : "http://servers.api.openstack.org/v1.1/1234/flavors/1"
},
{
"rel" : "bookmark",
"type" : "application/vnd.openstack.computev1.1+xml",
"href" : "http://servers.api.openstack.org/1234/flavors/1"
},
{
"rel" : "bookmark",
"type" : "application/vnd.openstack.computev1.1+json",
"href" : "http://servers.api.openstack.org/1234/flavors/1"
}
]
}
}

View File

@ -0,0 +1,31 @@
{
"image" : {
"id" : 2,
"name" : "CentOS 5.2",
"serverRef" : "http://servers.api.openstack.org/v1.1/1234/servers/12",
"updated" : "2010-10-10T12:00:00Z",
"created" : "2010-08-10T12:00:00Z",
"status" : "SAVING",
"progress" : 80,
"metadata" : {
"ImageVersion" : "1.5",
"ImageType" : "Gold"
},
"links": [
{
"rel" : "self",
"href" : "http://servers.api.openstack.org/v1.1/1234/images/1"
},
{
"rel" : "bookmark",
"type" : "application/vnd.openstack.computev1.1+xml",
"href" : "http://servers.api.openstack.org/1234/images/1"
},
{
"rel" : "bookmark",
"type" : "application/vnd.openstack.computev1.1+json",
"href" : "https://servers.api.rackspacecloud.com/v1.1/1234/images/1"
}
]
}
}

View File

@ -0,0 +1,46 @@
{
"server" : {
"id" : 1234,
"name" : "sample-server",
"imageRef" : "https://servers.api.rackspacecloud.com/v1.1/1234/images/1",
"flavorRef" : "http://servers.api.openstack.org/1234/flavors/1",
"updated" : "2010-10-10T12:00:00Z",
"created" : "2010-08-10T12:00:00Z",
"hostId" : "e4d909c290d0fb1ca068ffaddf22cbd0",
"affinityId" : "fc88bcf8394db9c8d0564e08ca6a9724188a84d1",
"status" : "BUILD",
"progress" : 60,
"addresses" : {
"public": [
{"version" : 4, "addr" : "67.23.10.132"},
{"version" : 6, "addr" : "::babe:67.23.10.132"},
{"version" : 4, "addr" : "67.23.10.131"},
{"version" : 6, "addr" : "::babe:4317:0A83"}
],
"private" : [
{"version" : 4, "addr" : "10.176.42.16"},
{"version" : 6, "addr" : "::babe:10.176.42.16"}
]
},
"metadata" : {
"Server Label" : "Web Head 1",
"Image Version" : "2.1"
},
"links": [
{
"rel" : "self",
"href" : "http://servers.api.openstack.org/v1.1/1234/servers/1234"
},
{
"rel" : "bookmark",
"type" : "application/vnd.openstack.compute-v1.1+xml",
"href" : "http://servers.api.openstack.org/1234/servers/1234"
},
{
"rel" : "bookmark",
"type" : "application/vnd.openstack.compute-v1.1+json",
"href" : "http://servers.api.openstack.org/1234/servers/1234"
}
]
}
}

View File

@ -0,0 +1,15 @@
{
"addresses" : {
"public" : [
{"version" : 4, "addr" : "67.23.10.132"},
{"version" : 6, "addr" : "::babe:67.23.10.132"},
{"version" : 4, "addr" : "67.23.10.131"},
{"version" : 6, "addr" : "::babe:4317:0A83"}
],
"private" : [
{"version" : 4, "addr" : "10.176.42.16"},
{"version" : 6, "addr" : "::babe:10.176.42.16"}
]
}
}

View File

@ -0,0 +1,8 @@
{
"private":[
{"version" : 4, "addr" : "67.23.10.132"},
{"version" : 6, "addr" : "::babe:67.23.10.132"},
{"version" : 4, "addr" : "67.23.10.131"},
{"version" : 6, "addr" : "::babe:4317:0A83"}
]
}

View File

@ -0,0 +1,8 @@
{
"public" : [
{"version" : 4, "addr" : "67.23.10.132"},
{"version" : 6, "addr" : "::babe:67.23.10.132"},
{"version" : 4, "addr" : "67.23.10.131"},
{"version" : 6, "addr" : "::babe:4317:0A83"}
]
}

View File

@ -0,0 +1,46 @@
{
"flavors" : [
{
"id" : 1,
"name" : "256 MB Server",
"links": [
{
"rel" : "self",
"href" : "http://servers.api.openstack.org/v1.1/1234/flavors/1"
},
{
"rel" : "bookmark",
"type" : "application/vnd.openstack.compute-v1.1+xml",
"href" : "http://servers.api.openstack.org/1234/flavors/1"
},
{
"rel" : "bookmark",
"type" : "application/vnd.openstack.compute-v1.1+json",
"href" : "http://servers.api.openstack.org/1234/flavors/1"
}
]
},
{
"id" : 2,
"name" : "512 MB Server",
"links": [
{
"rel" : "self",
"href" : "http://servers.api.openstack.org/v1.1/1234/flavors/2"
},
{
"rel" : "bookmark",
"type" : "application/vnd.openstack.compute-v1.1+xml",
"href" : "http://servers.api.openstack.org/1234/flavors/2"
},
{
"rel" : "bookmark",
"type" : "application/vnd.openstack.compute-v1.1+json",
"href" : "http://servers.api.openstack.org/1234/flavors/2"
}
]
}
]
}

View File

@ -0,0 +1,48 @@
{
"flavors" : [
{
"id" : 1,
"name" : "256 MB Server",
"ram" : 256,
"disk" : 10,
"links": [
{
"rel" : "self",
"href" : "http://servers.api.openstack.org/v1.1/1234/flavors/1"
},
{
"rel" : "bookmark",
"type" : "application/vnd.openstack.compute-v1.1+xml",
"href" : "http://servers.api.openstack.org/1234/flavors/1"
},
{
"rel" : "bookmark",
"type" : "application/vnd.openstack.compute-v1.1+json",
"href" : "http://servers.api.openstack.org/1234/flavors/1"
}
]
},
{
"id" : 2,
"name" : "512 MB Server",
"ram" : 512,
"disk" : 20,
"links": [
{
"rel" : "self",
"href" : "http://servers.api.openstack.org/v1.1/1234/flavors/2"
},
{
"rel" : "bookmark",
"type" : "application/vnd.openstack.compute-v1.1+xml",
"href" : "http://servers.api.openstack.org/1234/flavors/2"
},
{
"rel" : "bookmark",
"type" : "application/vnd.openstack.compute-v1.1+json",
"href" : "http://servers.api.openstack.org/1234/flavors/2"
}
]
}
]
}

View File

@ -0,0 +1,44 @@
{
"images" : [
{
"id" : 1,
"name" : "CentOS 5.2",
"links": [
{
"rel" : "self",
"href" : "http://servers.api.openstack.org/v1.1/1234/images/1"
},
{
"rel" : "bookmark",
"type" : "application/vnd.openstack.compute-v1.1+xml",
"href" : "http://servers.api.openstack.org/1234/images/1"
},
{
"rel" : "bookmark",
"type" : "application/vnd.openstack.compute-v1.1+json",
"href" : "http://servers.api.openstack.org/1234/images/1"
}
]
},
{
"id" : 743,
"name" : "My Server Backup",
"links": [
{
"rel" : "self",
"href" : "http://servers.api.openstack.org/v1.1/1234/images/743"
},
{
"rel" : "bookmark",
"type" : "application/vnd.openstack.compute-v1.1+xml",
"href" : "http://servers.api.openstack.org/1234/images/743"
},
{
"rel" : "bookmark",
"type" : "application/vnd.openstack.compute-v1.1+json",
"href" : "http://servers.api.openstack.org/1234/images/743"
}
]
}
]
}

View File

@ -0,0 +1,84 @@
{
"images" : [
{
"id" : 1,
"name" : "CentOS 5.2",
"updated" : "2010-10-10T12:00:00Z",
"created" : "2010-08-10T12:00:00Z",
"status" : "ACTIVE",
"metadata" : {
"ImageType" : "Gold",
"ImageVersion" : "1.5"
},
"links": [
{
"rel" : "self",
"href" : "http://servers.api.openstack.org/v1.1/1234/images/1"
},
{
"rel" : "bookmark",
"type" : "application/vnd.openstack.compute-v1.1+xml",
"href" : "http://servers.api.openstack.org/1234/images/1"
},
{
"rel" : "bookmark",
"type" : "application/vnd.openstack.compute-v1.1+json",
"href" : "http://servers.api.openstack.org/1234/images/1"
}
]
},
{
"id" : 743,
"name" : "My Server Backup",
"serverRef" : "http://servers.api.openstack.org/v1.1/1234/servers/12",
"updated" : "2010-10-10T12:00:00Z",
"created" : "2009-07-07T09:56:16Z",
"status" : "SAVING",
"progress" : 80,
"links": [
{
"rel" : "self",
"href" : "http://servers.api.openstack.org/v1.1/1234/images/743"
},
{
"rel" : "bookmark",
"type" : "application/vnd.openstack.compute-v1.1+xml",
"href" : "http://servers.api.openstack.org/1234/images/743"
},
{
"rel" : "bookmark",
"type" : "application/vnd.openstack.compute-v1.1+json",
"href" : "http://servers.api.openstack.org/1234/images/743"
}
]
},
{
"id" : 5,
"name" : "CentOS 5.2",
"serverRef" : 12,
"updated" : "2010-10-10T12:00:00Z",
"created" : "2010-08-10T12:00:00Z",
"status" : "ACTIVE",
"metadata" : {
"ImageType" : "Gold",
"ImageVersion" : "1.5"
},
"links": [
{
"rel" : "self",
"href" : "http://servers.api.openstack.org/v1.1/1234/images/1"
},
{
"rel" : "bookmark",
"type" : "application/vnd.openstack.compute-v1.1+xml",
"href" : "http://servers.api.openstack.org/1234/images/1"
},
{
"rel" : "bookmark",
"type" : "application/vnd.openstack.compute-v1.1+json",
"href" : "http://servers.api.openstack.org/1234/images/1"
}
]
}
]
}

View File

@ -0,0 +1,45 @@
{
"servers" : [
{
"id" : 1234,
"name" : "sample-server",
"links": [
{
"rel" : "self",
"href" : "http://servers.api.openstack.org/v1.1/1234/servers/1234"
},
{
"rel" : "bookmark",
"type" : "application/vnd.openstack.compute-v1.1+xml",
"href" : "http://servers.api.openstack.org/1234/servers/1234"
},
{
"rel" : "bookmark",
"type" : "application/vnd.openstack.compute-v1.1+json",
"href" : "http://servers.api.openstack.org/1234/servers/1234"
}
]
},
{
"id" : 5678,
"name" : "sample-server2",
"links": [
{
"rel" : "self",
"href" : "http://servers.api.openstack.org/v1.1/1234/servers/5678"
},
{
"rel" : "bookmark",
"type" : "application/vnd.openstack.compute-v1.1+xml",
"href" : "http://servers.api.openstack.org/1234/servers/5678"
},
{
"rel" : "bookmark",
"type" : "application/vnd.openstack.compute-v1.1+json",
"href" : "http://servers.api.openstack.org/1234/servers/5678"
}
]
}
]
}

View File

@ -0,0 +1,89 @@
{
"servers" : [
{
"id" : 1234,
"name" : "sample-server",
"imageRef" : "https://servers.api.rackspacecloud.com/v1.1/32278/images/1234",
"flavorRef" : "https://servers.api.rackspacecloud.com/v1.1/32278/flavors/1",
"updated" : "2010-10-10T12:00:00Z",
"created" : "2010-08-10T12:00:00Z",
"hostId" : "e4d909c290d0fb1ca068ffaddf22cbd0",
"affinityId" : "fc88bcf8394db9c8d0564e08ca6a9724188a84d1",
"status" : "BUILD",
"progress" : 60,
"addresses" : {
"public" : [
{"version" : 4, "addr" : "67.23.10.132"},
{"version" : 6, "addr" : "::babe:67.23.10.132"},
{"version" : 4, "addr" : "67.23.10.131"},
{"version" : 6, "addr" : "::babe:4317:0A83"}
],
"private" : [
{"version" : 4, "addr" : "10.176.42.16"},
{"version" : 6, "addr" : "::babe:10.176.42.16"}
]
},
"metadata" : {
"Server Label" : "Web Head 1",
"Image Version" : "2.1"
},
"links": [
{
"rel" : "self",
"href" : "http://servers.api.openstack.org/v1.1/1234/servers/1234"
},
{
"rel" : "bookmark",
"type" : "application/vnd.openstack.compute-v1.1+xml",
"href" : "http://servers.api.openstack.org/1234/servers/1234"
},
{
"rel" : "bookmark",
"type" : "application/vnd.openstack.compute-v1.1+json",
"href" : "http://servers.api.openstack.org/1234/servers/1234"
}
]
},
{
"id" : 5678,
"name" : "sample-server2",
"imageRef" : "https://servers.api.rackspacecloud.com/v1.1/32278/images/1",
"flavorRef" : 1,
"updated" : "2010-10-10T12:00:00Z",
"created" : "2010-08-10T12:00:00Z",
"hostId" : "9e107d9d372bb6826bd81d3542a419d6",
"affinityId" : "b414fa41cb37b97dcb58d6c76112af1258e9eae2",
"status" : "ACTIVE",
"addresses" : {
"public" : [
{"version" : 4, "addr" : "67.23.10.133"},
{"version" : 6, "addr" : "::babe:67.23.10.133"}
],
"private" : [
{"version" : 4, "addr" : "10.176.42.17"},
{"version" : 6, "addr" : "::babe:10.176.42.17"}
]
},
"metadata" : {
"Server Label" : "DB 1"
},
"links": [
{
"rel" : "self",
"href" : "http://servers.api.openstack.org/v1.1/1234/servers/5678"
},
{
"rel" : "bookmark",
"type" : "application/vnd.openstack.compute-v1.1+xml",
"href" : "http://servers.api.openstack.org/1234/servers/5678"
},
{
"rel" : "bookmark",
"type" : "application/vnd.openstack.compute-v1.1+json",
"href" : "http://servers.api.openstack.org/1234/servers/56789"
}
]
}
]
}

View File

@ -48,5 +48,6 @@
<module>vcloudexpress</module>
<module>elasticstack</module>
<module>atmos</module>
<module>nova</module>
</modules>
</project>

Some files were not shown because too many files have changed in this diff Show More