* 'master' of https://github.com/dmitri-b/jclouds: (51 commits)
  Copyrignt header added, warnings in test are supressed of fixed
  Update maven surefire plugin for live tests
  test for integer references in json
  reboot type is set to soft
  Update maven surefire plugin for live tests
  Fix for support maven surefire plugin test runner
  Fix env to properties
  Fix for support maven surefire plugin test runner
  Fixes in live tests
  Fixes in live tests
  Fix after merge
  Live tests fix
  Fixes in live tests
  unit test fixes
  test classes for development
  Fixes in live tests
  Fixes in live tests
  Fixes in live tests
  Unit test fixes
  Fixes in live tests
  ...
This commit is contained in:
Adrian Cole 2011-04-27 07:54:07 -07:00
commit 8c644108db
86 changed files with 3455 additions and 3372 deletions

View File

@ -21,7 +21,7 @@
--> -->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" <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> <modelVersion>4.0.0</modelVersion>
<parent> <parent>
<groupId>org.jclouds</groupId> <groupId>org.jclouds</groupId>
@ -35,10 +35,7 @@
<description>jclouds components to access an implementation of OpenStack Nova</description> <description>jclouds components to access an implementation of OpenStack Nova</description>
<properties> <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> </properties>
<dependencies> <dependencies>
@ -79,25 +76,42 @@
<version>${project.version}</version> <version>${project.version}</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<scope>test</scope>
</dependency>
<dependency> <dependency>
<groupId>org.jclouds.driver</groupId> <groupId>org.jclouds.driver</groupId>
<artifactId>jclouds-log4j</artifactId> <artifactId>jclouds-slf4j</artifactId>
<version>${project.version}</version> <version>${project.version}</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>log4j</groupId> <artifactId>slf4j-api</artifactId>
<artifactId>log4j</artifactId> <groupId>org.slf4j</groupId>
<version>1.2.16</version> <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> <scope>test</scope>
</dependency> </dependency>
</dependencies> </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> <profiles>
<profile> <profile>
<id>live</id> <id>live</id>
@ -106,6 +120,14 @@
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId> <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> <executions>
<execution> <execution>
<id>integration</id> <id>integration</id>
@ -131,6 +153,14 @@
<name>test.nova.credential</name> <name>test.nova.credential</name>
<value>${test.nova.credential}</value> <value>${test.nova.credential}</value>
</property> </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> <property>
<name>test.initializer</name> <name>test.initializer</name>
<value>${test.initializer}</value> <value>${test.initializer}</value>
@ -147,4 +177,3 @@
</project> </project>

View File

@ -18,50 +18,22 @@
*/ */
package org.jclouds.openstack.nova; package org.jclouds.openstack.nova;
import java.util.Set; import com.google.common.util.concurrent.ListenableFuture;
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 org.jclouds.openstack.filters.AddTimestampQuery; import org.jclouds.openstack.filters.AddTimestampQuery;
import org.jclouds.openstack.filters.AuthenticateRequest; import org.jclouds.openstack.filters.AuthenticateRequest;
import org.jclouds.rest.annotations.BinderParam; import org.jclouds.openstack.nova.domain.*;
import org.jclouds.rest.annotations.Endpoint; import org.jclouds.openstack.nova.options.CreateServerOptions;
import org.jclouds.rest.annotations.ExceptionParser; import org.jclouds.openstack.nova.options.ListOptions;
import org.jclouds.rest.annotations.MapBinder; import org.jclouds.openstack.nova.options.RebuildServerOptions;
import org.jclouds.rest.annotations.Payload; import org.jclouds.rest.annotations.*;
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.rest.functions.ReturnEmptySetOnNotFoundOr404; import org.jclouds.rest.functions.ReturnEmptySetOnNotFoundOr404;
import org.jclouds.rest.functions.ReturnFalseOnNotFoundOr404; import org.jclouds.rest.functions.ReturnFalseOnNotFoundOr404;
import org.jclouds.rest.functions.ReturnNullOnNotFoundOr404; 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. * 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 * during processing will be wrapped in an {@link ExecutionException} as documented in
* {@link ListenableFuture#get()}. * {@link ListenableFuture#get()}.
* *
* @author Adrian Cole
* @see NovaClient * @see NovaClient
* @see <a href="http://wiki.openstack.org/OpenStackAPI_1-1" /> * @see <a href="http://wiki.openstack.org/OpenStackAPI_1-1" />
* @author Adrian Cole
*/ */
@SkipEncoding({'/', '='}) @SkipEncoding({'/', '='})
@RequestFilters({AuthenticateRequest.class, AddTimestampQuery.class}) @RequestFilters({AuthenticateRequest.class, AddTimestampQuery.class})
@ -158,8 +130,8 @@ public interface NovaAsyncClient {
@QueryParams(keys = "format", values = "json") @QueryParams(keys = "format", values = "json")
@Path("/servers") @Path("/servers")
@MapBinder(CreateServerOptions.class) @MapBinder(CreateServerOptions.class)
ListenableFuture<Server> createServer(@PayloadParam("name") String name, @PayloadParam("imageId") int imageId, ListenableFuture<Server> createServer(@PayloadParam("name") String name, @PayloadParam("imageRef") String imageRef,
@PayloadParam("flavorId") int flavorId, CreateServerOptions... options); @PayloadParam("flavorRef") String flavorRef, CreateServerOptions... options);
/** /**
* @see NovaClient#rebuildServer * @see NovaClient#rebuildServer
@ -170,33 +142,14 @@ public interface NovaAsyncClient {
@MapBinder(RebuildServerOptions.class) @MapBinder(RebuildServerOptions.class)
ListenableFuture<Void> rebuildServer(@PathParam("id") int id, RebuildServerOptions... options); 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 * @see NovaClient#changeAdminPass
*/ */
@PUT @POST
@Path("/servers/{id}") @Path("/servers/{id}/action")
@Produces(MediaType.APPLICATION_JSON) @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); 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, ListenableFuture<Image> createImageFromServer(@PayloadParam("name") String imageName,
@PayloadParam("serverId") int serverId); @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 * @see NovaClient#listAddresses
*/ */

View File

@ -26,14 +26,11 @@ import javax.ws.rs.PathParam;
import org.jclouds.concurrent.Timeout; import org.jclouds.concurrent.Timeout;
import org.jclouds.openstack.nova.domain.Addresses; 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.Flavor;
import org.jclouds.openstack.nova.domain.Image; import org.jclouds.openstack.nova.domain.Image;
import org.jclouds.openstack.nova.domain.RebootType; import org.jclouds.openstack.nova.domain.RebootType;
import org.jclouds.openstack.nova.domain.Server; 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.CreateServerOptions;
import org.jclouds.openstack.nova.options.CreateSharedIpGroupOptions;
import org.jclouds.openstack.nova.options.ListOptions; import org.jclouds.openstack.nova.options.ListOptions;
import org.jclouds.openstack.nova.options.RebuildServerOptions; import org.jclouds.openstack.nova.options.RebuildServerOptions;
import org.jclouds.rest.ResourceNotFoundException; import org.jclouds.rest.ResourceNotFoundException;
@ -154,7 +151,7 @@ public interface NovaClient {
* @param options * @param options
* - used to specify extra files, metadata, or ip parameters during server creation. * - 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. * 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); 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. * This operation allows you to change the administrative password.
* <p/> * <p/>
@ -295,66 +258,6 @@ public interface NovaClient {
*/ */
Image createImageFromServer(String imageName, int serverId); 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 * List all server addresses
* *

View File

@ -0,0 +1,48 @@
/**
*
* 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.
* ====================================================================
*/
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

@ -1,53 +0,0 @@
/**
*
* 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.binders;
import static com.google.common.base.Preconditions.checkArgument;
import java.util.Map;
import javax.inject.Singleton;
import org.jclouds.http.HttpRequest;
import org.jclouds.openstack.nova.domain.BackupSchedule;
import org.jclouds.rest.binders.BindToJsonPayload;
import com.google.common.collect.ImmutableMap;
/**
*
* @author Adrian Cole
*
*/
@Singleton
public class BindBackupScheduleToJsonPayload extends BindToJsonPayload {
@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");
}
@Override
public <R extends HttpRequest> R bindToRequest(R request, Object toBind) {
checkArgument(toBind instanceof BackupSchedule,
"this binder is only valid for BackupSchedules!");
return super.bindToRequest(request, ImmutableMap.of("backupSchedule", toBind));
}
}

View File

@ -89,19 +89,11 @@ public class NovaComputeServiceDependenciesModule extends AbstractModule {
.put(ServerStatus.PREP_RESIZE, NodeState.PENDING)// .put(ServerStatus.PREP_RESIZE, NodeState.PENDING)//
.put(ServerStatus.RESIZE, NodeState.PENDING)// .put(ServerStatus.RESIZE, NodeState.PENDING)//
.put(ServerStatus.VERIFY_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.RESCUE, NodeState.PENDING)//
.put(ServerStatus.ERROR, NodeState.ERROR)//
.put(ServerStatus.BUILD, NodeState.PENDING)// .put(ServerStatus.BUILD, NodeState.PENDING)//
.put(ServerStatus.RESTORING, NodeState.PENDING)//
.put(ServerStatus.PASSWORD, NodeState.PENDING)// .put(ServerStatus.PASSWORD, NodeState.PENDING)//
.put(ServerStatus.REBUILD, NodeState.PENDING)// .put(ServerStatus.REBUILD, NodeState.PENDING)//
.put(ServerStatus.DELETE_IP, 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.REBOOT, NodeState.PENDING)//
.put(ServerStatus.HARD_REBOOT, NodeState.PENDING)// .put(ServerStatus.HARD_REBOOT, NodeState.PENDING)//
.put(ServerStatus.UNKNOWN, NodeState.UNRECOGNIZED)// .put(ServerStatus.UNKNOWN, NodeState.UNRECOGNIZED)//

View File

@ -36,8 +36,13 @@ import com.google.common.collect.ImmutableList;
@Singleton @Singleton
public class FlavorToHardware implements Function<Flavor, Hardware> { public class FlavorToHardware implements Function<Flavor, Hardware> {
public Hardware apply(Flavor from) { public Hardware apply(Flavor from) {
return new HardwareBuilder().ids(from.getId() + "").name(from.getName()) return new HardwareBuilder()
.processors(ImmutableList.of(new Processor(from.getDisk() / 10.0, 1.0))).ram(from.getRam()) .ids(from.getId() + "")
.volumes(ImmutableList.<Volume> of(new VolumeImpl((float) from.getDisk(), true, true))).build(); .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) { public Image apply(org.jclouds.openstack.nova.domain.Image from) {
ImageBuilder builder = new ImageBuilder(); ImageBuilder builder = new ImageBuilder();
builder.ids(from.getId() + ""); builder.ids(from.getId() + "");
builder.name(from.getName()); builder.name(from.getName() != null ? from.getName() : "unspecified");
builder.description(from.getName()); builder.description(from.getName() != null ? from.getName() : "unspecified");
builder.version(from.getUpdated().getTime() + ""); 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.defaultCredentials(new Credentials("root", null));
builder.uri(from.getURI());
Image image = builder.build(); Image image = builder.build();
return image; return image;
} }

View File

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

View File

@ -18,38 +18,32 @@
*/ */
package org.jclouds.openstack.nova.compute.functions; package org.jclouds.openstack.nova.compute.functions;
import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.base.Function;
import static org.jclouds.compute.util.ComputeServiceUtils.parseGroupFromName; import com.google.common.base.Predicate;
import com.google.common.base.Supplier;
import java.util.Map; import com.google.common.collect.Iterables;
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 org.jclouds.collect.Memoized; import org.jclouds.collect.Memoized;
import org.jclouds.compute.domain.Hardware; import org.jclouds.compute.domain.*;
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.reference.ComputeServiceConstants; import org.jclouds.compute.reference.ComputeServiceConstants;
import org.jclouds.domain.Credentials; import org.jclouds.domain.Credentials;
import org.jclouds.domain.Location; import org.jclouds.domain.Location;
import org.jclouds.domain.LocationBuilder; import org.jclouds.domain.LocationBuilder;
import org.jclouds.domain.LocationScope; import org.jclouds.domain.LocationScope;
import org.jclouds.logging.Logger; 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 javax.annotation.Resource;
import com.google.common.base.Predicate; import javax.inject.Inject;
import com.google.common.base.Supplier; import javax.inject.Named;
import com.google.common.collect.Iterables; 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 * @author Adrian Cole
@ -75,7 +69,7 @@ public class ServerToNodeMetadata implements Function<Server, NodeMetadata> {
@Override @Override
public boolean apply(Image input) { 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 @Override
public boolean apply(Hardware input) { 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()); from.getHostId()).parent(location.get()).build());
builder.userMetadata(from.getMetadata()); builder.userMetadata(from.getMetadata());
builder.group(parseGroupFromName(from.getName())); builder.group(parseGroupFromName(from.getName()));
builder.imageId(from.getImageId() + ""); Image image = parseImage(from);
builder.operatingSystem(parseOperatingSystem(from)); if (image != null) {
builder.imageId(image.getId());
builder.operatingSystem(image.getOperatingSystem());
}
builder.hardware(parseHardware(from)); builder.hardware(parseHardware(from));
builder.state(serverToNodeState.get(from.getStatus())); builder.state(serverToNodeState.get(from.getStatus()));
builder.publicAddresses(from.getAddresses().getPublicAddresses()); builder.publicAddresses(Iterables.transform(from.getAddresses().getPublicAddresses(), Address.newAddress2StringFunction()));
builder.privateAddresses(from.getAddresses().getPrivateAddresses()); builder.privateAddresses(Iterables.transform(from.getAddresses().getPrivateAddresses(), Address.newAddress2StringFunction()));
builder.credentials(credentialStore.get("node#" + from.getId())); builder.credentials(credentialStore.get("node#" + from.getId()));
builder.uri(from.getURI());
return builder.build(); return builder.build();
} }
@ -131,9 +129,9 @@ public class ServerToNodeMetadata implements Function<Server, NodeMetadata> {
return null; return null;
} }
protected OperatingSystem parseOperatingSystem(Server from) { protected Image parseImage(Server from) {
try { try {
return Iterables.find(images.get(), new FindImageForServer(from)).getOperatingSystem(); return Iterables.find(images.get(), new FindImageForServer(from));
} catch (NoSuchElementException e) { } catch (NoSuchElementException e) {
logger.warn("could not find a matching image for server %s in location %s", from, location); 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 @Override
public NodeMetadata createNodeWithGroupEncodedIntoName(String group, String name, Template template) { public NodeMetadata createNodeWithGroupEncodedIntoName(String group, String name, Template template) {
Server from = client.createServer(name, Integer.parseInt(template.getImage().getProviderId()), Integer Server from = client.createServer(name, template.getImage().getId(), template.getHardware().getId());
.parseInt(template.getHardware().getProviderId()));
credentialStore.put("node#" + from.getId(), new Credentials("root", from.getAdminPass())); credentialStore.put("node#" + from.getId(), new Credentials("root", from.getAdminPass()));
return serverToNodeMetadata.apply(from); return serverToNodeMetadata.apply(from);
} }

View File

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

View File

@ -0,0 +1,80 @@
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 { public class Addresses {
@SerializedName("public") @SerializedName("public")
private Set<String> publicAddresses = Sets.newLinkedHashSet(); private Set<Address> publicAddresses = Sets.newLinkedHashSet();
@SerializedName("private") @SerializedName("private")
private Set<String> privateAddresses = Sets.newLinkedHashSet(); private Set<Address> privateAddresses = Sets.newLinkedHashSet();
public Addresses() { public Addresses() {
} }
public Addresses(Set<String> publicAddresses, Set<String> privateAddresses) { public Addresses(Set<Address> publicAddresses, Set<Address> privateAddresses) {
this.publicAddresses = publicAddresses; this.publicAddresses = publicAddresses;
this.privateAddresses = privateAddresses; this.privateAddresses = privateAddresses;
} }
public void setPublicAddresses(Set<String> publicAddresses) { public void setPublicAddresses(Set<Address> publicAddresses) {
this.publicAddresses = publicAddresses; this.publicAddresses = publicAddresses;
} }
public Set<String> getPublicAddresses() { public Set<Address> getPublicAddresses() {
return publicAddresses; return publicAddresses;
} }
public void setPrivateAddresses(Set<String> privateAddresses) { public void setPrivateAddresses(Set<Address> privateAddresses) {
this.privateAddresses = privateAddresses; this.privateAddresses = privateAddresses;
} }
public Set<String> getPrivateAddresses() { public Set<Address> getPrivateAddresses() {
return privateAddresses; return privateAddresses;
} }

View File

@ -1,104 +0,0 @@
/**
*
* 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;
/**
* A backup schedule can be defined to create server images at regular intervals (daily and weekly).
* Backup schedules are configurable per server.
*
* @author Adrian Cole
*/
public class BackupSchedule {
protected DailyBackup daily = DailyBackup.DISABLED;
protected boolean enabled;
protected WeeklyBackup weekly = WeeklyBackup.DISABLED;
public BackupSchedule() {
}
public BackupSchedule(WeeklyBackup weekly, DailyBackup daily, boolean enabled) {
this.weekly = weekly;
this.daily = daily;
this.enabled = enabled;
}
public DailyBackup getDaily() {
return daily;
}
public void setDaily(DailyBackup value) {
this.daily = value;
}
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean value) {
this.enabled = value;
}
public WeeklyBackup getWeekly() {
return weekly;
}
public void setWeekly(WeeklyBackup value) {
this.weekly = value;
}
@Override
public String toString() {
return "[daily=" + daily + ", enabled=" + enabled + ", weekly=" + weekly + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((daily == null) ? 0 : daily.hashCode());
result = prime * result + (enabled ? 1231 : 1237);
result = prime * result + ((weekly == null) ? 0 : weekly.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
BackupSchedule other = (BackupSchedule) obj;
if (daily == null) {
if (other.daily != null)
return false;
} else if (!daily.equals(other.daily))
return false;
if (enabled != other.enabled)
return false;
if (weekly == null) {
if (other.weekly != null)
return false;
} else if (!weekly.equals(other.weekly))
return false;
return true;
}
}

View File

@ -1,37 +0,0 @@
/**
*
* 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;
public enum DailyBackup {
DISABLED, H_0000_0200, H_0200_0400, H_0400_0600, H_0600_0800, H_0800_1000, H_1000_1200, H_1200_1400, H_1400_1600, H_1600_1800, H_1800_2000, H_2000_2200, H_2200_0000, UNRECOGNIZED;
public String value() {
return name();
}
public static DailyBackup fromValue(String v) {
try {
return valueOf(v);
} catch (IllegalArgumentException e) {
return UNRECOGNIZED;
}
}
}

View File

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

View File

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

View File

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

View File

@ -37,7 +37,7 @@ package org.jclouds.openstack.nova.domain;
*/ */
public enum ServerStatus { 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() { public String value() {
return name(); return name();

View File

@ -1,42 +0,0 @@
/**
*
* 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;
public class ShareIp {
private boolean configureServer;
private int sharedIpGroupId;
public void setConfigureServer(boolean configureServer) {
this.configureServer = configureServer;
}
public boolean isConfigureServer() {
return configureServer;
}
public void setSharedIpGroupId(int sharedIpGroupId) {
this.sharedIpGroupId = sharedIpGroupId;
}
public int getSharedIpGroupId() {
return sharedIpGroupId;
}
}

View File

@ -1,111 +0,0 @@
/**
*
* 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.util.List;
import com.google.common.collect.Lists;
/**
* 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.
*
* @author Adrian Cole
*/
public class SharedIpGroup {
private int id;
private String name;
private List<Integer> servers = Lists.newArrayList();
public SharedIpGroup() {
}
public SharedIpGroup(int id, String name) {
this.id = id;
this.name = name;
}
public void setId(int id) {
this.id = id;
}
public int getId() {
return id;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setServers(List<Integer> servers) {
this.servers = servers;
}
public List<Integer> getServers() {
return servers;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + id;
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((servers == null) ? 0 : servers.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
SharedIpGroup other = (SharedIpGroup) obj;
if (id != other.id)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (servers == null) {
if (other.servers != null)
return false;
} else if (!servers.equals(other.servers))
return false;
return true;
}
@Override
public String toString() {
return "SharedIpGroup [id=" + id + ", name=" + name + ", servers=" + servers + "]";
}
}

View File

@ -1,59 +0,0 @@
/**
*
* 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;
public class Version {
private String docURL;
private String id = "v1.0";
private VersionStatus status;
private String wadl;
public void setDocURL(String docURL) {
this.docURL = docURL;
}
public String getDocURL() {
return docURL;
}
public void setId(String id) {
this.id = id;
}
public String getId() {
return id;
}
public void setStatus(VersionStatus status) {
this.status = status;
}
public VersionStatus getStatus() {
return status;
}
public void setWadl(String wadl) {
this.wadl = wadl;
}
public String getWadl() {
return wadl;
}
}

View File

@ -1,37 +0,0 @@
/**
*
* 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;
public enum VersionStatus {
BETA, CURRENT, DEPRECATED, UNRECOGNIZED;
public String value() {
return name();
}
public static VersionStatus fromValue(String v) {
try {
return valueOf(v);
} catch (IllegalArgumentException e) {
return UNRECOGNIZED;
}
}
}

View File

@ -1,37 +0,0 @@
/**
*
* 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;
public enum WeeklyBackup {
DISABLED, SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, UNRECOGNIZED;
public String value() {
return name();
}
public static WeeklyBackup fromValue(String v) {
try {
return valueOf(v);
} catch (IllegalArgumentException e) {
return UNRECOGNIZED;
}
}
}

View File

@ -28,7 +28,6 @@ import java.util.Map.Entry;
import org.jclouds.encryption.internal.Base64; import org.jclouds.encryption.internal.Base64;
import org.jclouds.http.HttpRequest; import org.jclouds.http.HttpRequest;
import org.jclouds.openstack.nova.domain.Addresses;
import org.jclouds.rest.binders.BindToJsonPayload; import org.jclouds.rest.binders.BindToJsonPayload;
import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
@ -70,43 +69,33 @@ public class CreateServerOptions extends BindToJsonPayload {
@SuppressWarnings("unused") @SuppressWarnings("unused")
private class ServerRequest { private class ServerRequest {
final String name; final String name;
final int imageId; final String imageRef;
final int flavorId; final String flavorRef;
Map<String, String> metadata; Map<String, String> metadata;
List<File> personality; 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.name = name;
this.imageId = imageId; this.imageRef = imageRef;
this.flavorId = flavorId; this.flavorRef = flavorRef;
} }
} }
private Map<String, String> metadata = Maps.newHashMap(); private Map<String, String> metadata = Maps.newHashMap();
private List<File> files = Lists.newArrayList(); private List<File> files = Lists.newArrayList();
private Integer sharedIpGroupId;
private String publicIp;
@Override @Override
public <R extends HttpRequest> R bindToRequest(R request, Map<String, String> postParams) { public <R extends HttpRequest> R bindToRequest(R request, Map<String, String> postParams) {
ServerRequest server = new ServerRequest(checkNotNull(postParams.get("name"), ServerRequest server = new ServerRequest(checkNotNull(postParams.get("name"),
"name parameter not present"), Integer.parseInt(checkNotNull(postParams "name parameter not present"), checkNotNull(postParams
.get("imageId"), "imageId parameter not present")), Integer.parseInt(checkNotNull( .get("imageRef"), "imageRef parameter not present"), checkNotNull(
postParams.get("flavorId"), "flavorId parameter not present"))); postParams.get("flavorRef"), "flavorRef parameter not present"));
if (metadata.size() > 0) if (metadata.size() > 0)
server.metadata = metadata; server.metadata = metadata;
if (files.size() > 0) if (files.size() > 0)
server.personality = files; 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)); return bindToRequest(request, ImmutableMap.of("server", server));
} }
@ -131,29 +120,6 @@ public class CreateServerOptions extends BindToJsonPayload {
return this; 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 * 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 * the API system where it is retrievable by querying the API for server status. The maximum size
@ -180,28 +146,6 @@ public class CreateServerOptions extends BindToJsonPayload {
return this; 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 { public static class Builder {
/** /**
@ -212,14 +156,6 @@ public class CreateServerOptions extends BindToJsonPayload {
return options.withFile(path, contents); 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>) * @see CreateServerOptions#withMetadata(Map<String, String>)
*/ */
@ -227,14 +163,5 @@ public class CreateServerOptions extends BindToJsonPayload {
CreateServerOptions options = new CreateServerOptions(); CreateServerOptions options = new CreateServerOptions();
return options.withMetadata(metadata); return options.withMetadata(metadata);
} }
/**
* @see CreateServerOptions#withSharedIp(String)
*/
public static CreateServerOptions withSharedIp(String publicIp) {
CreateServerOptions options = new CreateServerOptions();
return options.withSharedIp(publicIp);
}
} }
} }

View File

@ -1,87 +0,0 @@
/**
*
* 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.options;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import java.util.Map;
import javax.annotation.Nullable;
import org.jclouds.http.HttpRequest;
import org.jclouds.rest.binders.BindToJsonPayload;
import com.google.common.collect.ImmutableMap;
/**
*
*
* @author Adrian Cole
*
*/
public class CreateSharedIpGroupOptions extends BindToJsonPayload {
Integer serverId;
@SuppressWarnings("unused")
private static class SharedIpGroupRequest {
final String name;
Integer server;
private SharedIpGroupRequest(String name, @Nullable Integer serverId) {
this.name = name;
this.server = serverId;
}
}
@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));
}
@Override
public <R extends HttpRequest> R bindToRequest(R request, Object toBind) {
throw new IllegalStateException("CreateSharedIpGroup is a POST operation");
}
/**
*
* @param id
* of the server to include with this request.
*/
public CreateSharedIpGroupOptions withServer(int id) {
checkArgument(id > 0, "server id must be a positive number");
this.serverId = id;
return this;
}
public static class Builder {
/**
* @see CreateSharedIpGroupOptions#withServer(int)
*/
public static CreateSharedIpGroupOptions withServer(int id) {
CreateSharedIpGroupOptions options = new CreateSharedIpGroupOptions();
return options.withServer(id);
}
}
}

View File

@ -19,6 +19,7 @@
package org.jclouds.openstack.nova.options; package org.jclouds.openstack.nova.options;
import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import java.util.Map; import java.util.Map;
@ -35,13 +36,13 @@ import com.google.common.collect.Maps;
* *
*/ */
public class RebuildServerOptions extends BindToJsonPayload { public class RebuildServerOptions extends BindToJsonPayload {
Integer imageId; String imageRef;
@Override @Override
public <R extends HttpRequest> R bindToRequest(R request, Map<String, String> postParams) { public <R extends HttpRequest> R bindToRequest(R request, Map<String, String> postParams) {
Map<String, Integer> image = Maps.newHashMap(); Map<String, String> image = Maps.newHashMap();
if (imageId != null) if (imageRef != null)
image.put("imageId", imageId); image.put("imageRef", imageRef);
return super.bindToRequest(request, ImmutableMap.of("rebuild", image)); return super.bindToRequest(request, ImmutableMap.of("rebuild", image));
} }
@ -51,24 +52,23 @@ public class RebuildServerOptions extends BindToJsonPayload {
} }
/** /**
* * @param ref - reference of the image to rebuild the server with.
* @param id
* of the image to rebuild the server with.
*/ */
public RebuildServerOptions withImage(int id) { public RebuildServerOptions withImage(String ref) {
checkArgument(id > 0, "server id must be a positive number"); checkNotNull(ref, "image reference should not be null");
this.imageId = id; checkArgument(!ref.isEmpty(), "image reference should not be empty");
this.imageRef = ref;
return this; return this;
} }
public static class Builder { 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(); RebuildServerOptions options = new RebuildServerOptions();
return options.withImage(id); return options.withImage(ref);
} }
} }
} }

View File

@ -18,60 +18,47 @@
*/ */
package org.jclouds.openstack.nova; package org.jclouds.openstack.nova;
import static org.jclouds.Constants.PROPERTY_API_VERSION; import com.google.common.collect.ImmutableMap;
import static org.jclouds.openstack.nova.options.CreateServerOptions.Builder.withFile; import com.google.inject.Module;
import static org.jclouds.openstack.nova.options.CreateServerOptions.Builder.withMetadata; import com.google.inject.TypeLiteral;
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 org.jclouds.http.HttpRequest; import org.jclouds.http.HttpRequest;
import org.jclouds.http.RequiresHttp; import org.jclouds.http.RequiresHttp;
import org.jclouds.http.functions.ReleasePayloadAndReturn; import org.jclouds.http.functions.ReleasePayloadAndReturn;
import org.jclouds.http.functions.ReturnFalseOn404;
import org.jclouds.http.functions.ReturnTrueIf2xx; import org.jclouds.http.functions.ReturnTrueIf2xx;
import org.jclouds.http.functions.UnwrapOnlyJsonValue; import org.jclouds.http.functions.UnwrapOnlyJsonValue;
import org.jclouds.openstack.OpenStackAuthAsyncClient.AuthenticationResponse; import org.jclouds.openstack.OpenStackAuthAsyncClient.AuthenticationResponse;
import org.jclouds.openstack.TestOpenStackAuthenticationModule; import org.jclouds.openstack.TestOpenStackAuthenticationModule;
import org.jclouds.openstack.filters.AddTimestampQuery; import org.jclouds.openstack.filters.AddTimestampQuery;
import org.jclouds.openstack.filters.AuthenticateRequest; 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.ConfiguresRestClient;
import org.jclouds.rest.RestClientTest; import org.jclouds.rest.RestClientTest;
import org.jclouds.rest.RestContextFactory; import org.jclouds.rest.RestContextFactory;
import org.jclouds.rest.RestContextSpec; import org.jclouds.rest.RestContextSpec;
import org.jclouds.rest.functions.MapHttp4xxCodesToExceptions;
import org.jclouds.rest.functions.ReturnEmptySetOnNotFoundOr404; import org.jclouds.rest.functions.ReturnEmptySetOnNotFoundOr404;
import org.jclouds.rest.functions.ReturnFalseOnNotFoundOr404; import org.jclouds.rest.functions.ReturnFalseOnNotFoundOr404;
import org.jclouds.rest.functions.ReturnNullOnNotFoundOr404; import org.jclouds.rest.functions.ReturnNullOnNotFoundOr404;
import org.jclouds.rest.functions.ReturnVoidOnNotFoundOr404;
import org.jclouds.rest.internal.RestAnnotationProcessor; import org.jclouds.rest.internal.RestAnnotationProcessor;
import org.testng.annotations.Test; import org.testng.annotations.Test;
import com.google.common.collect.ImmutableMap; import javax.ws.rs.core.MediaType;
import com.google.inject.Module; import java.io.IOException;
import com.google.inject.TypeLiteral; 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} * Tests behavior of {@code NovaAsyncClient}
@ -85,14 +72,15 @@ public class NovaAsyncClientTest extends RestClientTest<NovaAsyncClient> {
private static final Class<? extends CreateServerOptions[]> createServerOptionsVarargsClass = new CreateServerOptions[]{} private static final Class<? extends CreateServerOptions[]> createServerOptionsVarargsClass = new CreateServerOptions[]{}
.getClass(); .getClass();
@Test
public void testCreateServer() throws IOException, SecurityException, NoSuchMethodException { 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); createServerOptionsVarargsClass);
HttpRequest request = processor.createRequest(method, "ralphie", 2, 1); 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"); 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); "application/json", false);
assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class); assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class);
@ -103,35 +91,18 @@ public class NovaAsyncClientTest extends RestClientTest<NovaAsyncClient> {
} }
public void testCreateServerWithIpGroup() throws IOException, SecurityException, NoSuchMethodException { @Test
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);
}
public void testCreateServerWithFile() throws IOException, SecurityException, NoSuchMethodException { 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); createServerOptionsVarargsClass);
HttpRequest request = processor HttpRequest request = processor
.createRequest(method, "ralphie", 2, 1, withFile("/etc/jclouds", "foo".getBytes())); .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"); assertNonPayloadHeadersEqual(request, "Accept: application/json\n");
assertPayloadEquals( assertPayloadEquals(
request, 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); "application/json", false);
assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class); assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class);
@ -142,16 +113,17 @@ public class NovaAsyncClientTest extends RestClientTest<NovaAsyncClient> {
} }
@Test
public void testCreateServerWithMetadata() throws IOException, SecurityException, NoSuchMethodException { 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); createServerOptionsVarargsClass);
HttpRequest request = processor.createRequest(method, "ralphie", 2, 1, HttpRequest request = processor.createRequest(method, "ralphie", 2, 1,
withMetadata(ImmutableMap.of("foo", "bar"))); 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"); assertNonPayloadHeadersEqual(request, "Accept: application/json\n");
assertPayloadEquals(request, 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); "application/json", false);
assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class); 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 { public void testDeleteImage() throws IOException, SecurityException, NoSuchMethodException {
Method method = NovaAsyncClient.class.getMethod("deleteImage", int.class); Method method = NovaAsyncClient.class.getMethod("deleteImage", int.class);
HttpRequest request = processor.createRequest(method, 2); 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, ""); assertNonPayloadHeadersEqual(request, "");
assertPayloadEquals(request, null, null, false); assertPayloadEquals(request, null, null, false);
@ -202,7 +153,7 @@ public class NovaAsyncClientTest extends RestClientTest<NovaAsyncClient> {
Method method = NovaAsyncClient.class.getMethod("listServers", listOptionsVarargsClass); Method method = NovaAsyncClient.class.getMethod("listServers", listOptionsVarargsClass);
HttpRequest request = processor.createRequest(method); 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"); assertNonPayloadHeadersEqual(request, "Accept: application/json\n");
assertPayloadEquals(request, null, null, false); 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)); HttpRequest request = processor.createRequest(method, changesSince(now).maxResults(1).startAt(2));
assertRequestLineEquals(request, 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"); assertNonPayloadHeadersEqual(request, "Accept: application/json\n");
assertPayloadEquals(request, null, null, false); assertPayloadEquals(request, null, null, false);
@ -235,7 +186,7 @@ public class NovaAsyncClientTest extends RestClientTest<NovaAsyncClient> {
Method method = NovaAsyncClient.class.getMethod("listServers", listOptionsVarargsClass); Method method = NovaAsyncClient.class.getMethod("listServers", listOptionsVarargsClass);
HttpRequest request = processor.createRequest(method, withDetails()); 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"); assertNonPayloadHeadersEqual(request, "Accept: application/json\n");
assertPayloadEquals(request, null, null, false); assertPayloadEquals(request, null, null, false);
@ -250,7 +201,7 @@ public class NovaAsyncClientTest extends RestClientTest<NovaAsyncClient> {
Method method = NovaAsyncClient.class.getMethod("getServer", int.class); Method method = NovaAsyncClient.class.getMethod("getServer", int.class);
HttpRequest request = processor.createRequest(method, 2); 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"); assertNonPayloadHeadersEqual(request, "Accept: application/json\n");
assertPayloadEquals(request, null, null, false); assertPayloadEquals(request, null, null, false);
@ -265,7 +216,7 @@ public class NovaAsyncClientTest extends RestClientTest<NovaAsyncClient> {
Method method = NovaAsyncClient.class.getMethod("listFlavors", listOptionsVarargsClass); Method method = NovaAsyncClient.class.getMethod("listFlavors", listOptionsVarargsClass);
HttpRequest request = processor.createRequest(method); 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"); assertNonPayloadHeadersEqual(request, "Accept: application/json\n");
assertPayloadEquals(request, null, null, false); 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)); HttpRequest request = processor.createRequest(method, changesSince(now).maxResults(1).startAt(2));
assertRequestLineEquals(request, 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"); assertNonPayloadHeadersEqual(request, "Accept: application/json\n");
assertPayloadEquals(request, null, null, false); assertPayloadEquals(request, null, null, false);
@ -296,7 +247,7 @@ public class NovaAsyncClientTest extends RestClientTest<NovaAsyncClient> {
Method method = NovaAsyncClient.class.getMethod("listFlavors", listOptionsVarargsClass); Method method = NovaAsyncClient.class.getMethod("listFlavors", listOptionsVarargsClass);
HttpRequest request = processor.createRequest(method, withDetails()); 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"); assertNonPayloadHeadersEqual(request, "Accept: application/json\n");
assertPayloadEquals(request, null, null, false); 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)); HttpRequest request = processor.createRequest(method, withDetails().changesSince(now).maxResults(1).startAt(2));
assertRequestLineEquals(request, 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"); assertNonPayloadHeadersEqual(request, "Accept: application/json\n");
assertPayloadEquals(request, null, null, false); assertPayloadEquals(request, null, null, false);
@ -327,7 +278,7 @@ public class NovaAsyncClientTest extends RestClientTest<NovaAsyncClient> {
Method method = NovaAsyncClient.class.getMethod("getFlavor", int.class); Method method = NovaAsyncClient.class.getMethod("getFlavor", int.class);
HttpRequest request = processor.createRequest(method, 2); 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"); assertNonPayloadHeadersEqual(request, "Accept: application/json\n");
assertPayloadEquals(request, null, null, false); assertPayloadEquals(request, null, null, false);
@ -342,7 +293,7 @@ public class NovaAsyncClientTest extends RestClientTest<NovaAsyncClient> {
Method method = NovaAsyncClient.class.getMethod("listImages", listOptionsVarargsClass); Method method = NovaAsyncClient.class.getMethod("listImages", listOptionsVarargsClass);
HttpRequest request = processor.createRequest(method); 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"); assertNonPayloadHeadersEqual(request, "Accept: application/json\n");
assertPayloadEquals(request, null, null, false); assertPayloadEquals(request, null, null, false);
@ -357,7 +308,7 @@ public class NovaAsyncClientTest extends RestClientTest<NovaAsyncClient> {
Method method = NovaAsyncClient.class.getMethod("listImages", listOptionsVarargsClass); Method method = NovaAsyncClient.class.getMethod("listImages", listOptionsVarargsClass);
HttpRequest request = processor.createRequest(method, withDetails()); 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"); assertNonPayloadHeadersEqual(request, "Accept: application/json\n");
assertPayloadEquals(request, null, null, false); 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)); HttpRequest request = processor.createRequest(method, changesSince(now).maxResults(1).startAt(2));
assertRequestLineEquals(request, 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"); assertNonPayloadHeadersEqual(request, "Accept: application/json\n");
assertPayloadEquals(request, null, null, false); 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)); HttpRequest request = processor.createRequest(method, withDetails().changesSince(now).maxResults(1).startAt(2));
assertRequestLineEquals(request, 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"); assertNonPayloadHeadersEqual(request, "Accept: application/json\n");
assertPayloadEquals(request, null, null, false); assertPayloadEquals(request, null, null, false);
@ -404,7 +355,7 @@ public class NovaAsyncClientTest extends RestClientTest<NovaAsyncClient> {
Method method = NovaAsyncClient.class.getMethod("getImage", int.class); Method method = NovaAsyncClient.class.getMethod("getImage", int.class);
HttpRequest request = processor.createRequest(method, 2); 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"); assertNonPayloadHeadersEqual(request, "Accept: application/json\n");
assertPayloadEquals(request, null, null, false); assertPayloadEquals(request, null, null, false);
@ -419,7 +370,7 @@ public class NovaAsyncClientTest extends RestClientTest<NovaAsyncClient> {
Method method = NovaAsyncClient.class.getMethod("deleteServer", int.class); Method method = NovaAsyncClient.class.getMethod("deleteServer", int.class);
HttpRequest request = processor.createRequest(method, 2); 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, ""); assertNonPayloadHeadersEqual(request, "");
assertPayloadEquals(request, null, null, false); assertPayloadEquals(request, null, null, false);
@ -430,101 +381,13 @@ public class NovaAsyncClientTest extends RestClientTest<NovaAsyncClient> {
checkFilters(request); 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 { public void testChangeAdminPass() throws IOException, SecurityException, NoSuchMethodException {
Method method = NovaAsyncClient.class.getMethod("changeAdminPass", int.class, String.class); Method method = NovaAsyncClient.class.getMethod("changeAdminPass", int.class, String.class);
HttpRequest request = processor.createRequest(method, 2, "foo"); 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, ""); 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); assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class);
assertSaxResponseParserClassEquals(method, null); assertSaxResponseParserClassEquals(method, null);
@ -538,7 +401,7 @@ public class NovaAsyncClientTest extends RestClientTest<NovaAsyncClient> {
Method method = NovaAsyncClient.class.getMethod("renameServer", int.class, String.class); Method method = NovaAsyncClient.class.getMethod("renameServer", int.class, String.class);
HttpRequest request = processor.createRequest(method, 2, "foo"); 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, ""); assertNonPayloadHeadersEqual(request, "");
assertPayloadEquals(request, "{\"server\":{\"name\":\"foo\"}}", MediaType.APPLICATION_JSON, false); 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 { public void testListAddresses() throws IOException, SecurityException, NoSuchMethodException {
Method method = NovaAsyncClient.class.getMethod("getAddresses", int.class); Method method = NovaAsyncClient.class.getMethod("getAddresses", int.class);
HttpRequest request = processor.createRequest(method, 2); 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"); assertNonPayloadHeadersEqual(request, "Accept: application/json\n");
assertPayloadEquals(request, null, null, false); assertPayloadEquals(request, null, null, false);
@ -698,7 +432,7 @@ public class NovaAsyncClientTest extends RestClientTest<NovaAsyncClient> {
Method method = NovaAsyncClient.class.getMethod("listPublicAddresses", int.class); Method method = NovaAsyncClient.class.getMethod("listPublicAddresses", int.class);
HttpRequest request = processor.createRequest(method, 2); 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"); assertNonPayloadHeadersEqual(request, "Accept: application/json\n");
assertPayloadEquals(request, null, null, false); assertPayloadEquals(request, null, null, false);
@ -709,11 +443,12 @@ public class NovaAsyncClientTest extends RestClientTest<NovaAsyncClient> {
checkFilters(request); checkFilters(request);
} }
@Test
public void testListPrivateAddresses() throws IOException, SecurityException, NoSuchMethodException { public void testListPrivateAddresses() throws IOException, SecurityException, NoSuchMethodException {
Method method = NovaAsyncClient.class.getMethod("listPrivateAddresses", int.class); Method method = NovaAsyncClient.class.getMethod("listPrivateAddresses", int.class);
HttpRequest request = processor.createRequest(method, 2); 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"); assertNonPayloadHeadersEqual(request, "Accept: application/json\n");
assertPayloadEquals(request, null, null, false); assertPayloadEquals(request, null, null, false);
@ -724,26 +459,12 @@ public class NovaAsyncClientTest extends RestClientTest<NovaAsyncClient> {
checkFilters(request); checkFilters(request);
} }
public void testListBackupSchedule() throws IOException, SecurityException, NoSuchMethodException { @Test
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);
}
public void testCreateImageWithIpGroup() throws IOException, SecurityException, NoSuchMethodException { public void testCreateImageWithIpGroup() throws IOException, SecurityException, NoSuchMethodException {
Method method = NovaAsyncClient.class.getMethod("createImageFromServer", String.class, int.class); Method method = NovaAsyncClient.class.getMethod("createImageFromServer", String.class, int.class);
HttpRequest request = processor.createRequest(method, "ralphie", 2); 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"); assertNonPayloadHeadersEqual(request, "Accept: application/json\n");
assertPayloadEquals(request, "{\"image\":{\"serverId\":2,\"name\":\"ralphie\"}}", MediaType.APPLICATION_JSON, assertPayloadEquals(request, "{\"image\":{\"serverId\":2,\"name\":\"ralphie\"}}", MediaType.APPLICATION_JSON,
false); false);
@ -759,12 +480,13 @@ public class NovaAsyncClientTest extends RestClientTest<NovaAsyncClient> {
private static final Class<? extends RebuildServerOptions[]> rebuildServerOptionsVarargsClass = new RebuildServerOptions[]{} private static final Class<? extends RebuildServerOptions[]> rebuildServerOptionsVarargsClass = new RebuildServerOptions[]{}
.getClass(); .getClass();
@Test
public void testRebuildServer() throws IOException, SecurityException, NoSuchMethodException { public void testRebuildServer() throws IOException, SecurityException, NoSuchMethodException {
Method method = NovaAsyncClient.class.getMethod("rebuildServer", int.class, Method method = NovaAsyncClient.class.getMethod("rebuildServer", int.class,
rebuildServerOptionsVarargsClass); rebuildServerOptionsVarargsClass);
HttpRequest request = processor.createRequest(method, 3); 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, ""); assertNonPayloadHeadersEqual(request, "");
assertPayloadEquals(request, "{\"rebuild\":{}}", MediaType.APPLICATION_JSON, false); assertPayloadEquals(request, "{\"rebuild\":{}}", MediaType.APPLICATION_JSON, false);
@ -775,14 +497,15 @@ public class NovaAsyncClientTest extends RestClientTest<NovaAsyncClient> {
checkFilters(request); checkFilters(request);
} }
@Test
public void testRebuildServerWithImage() throws IOException, SecurityException, NoSuchMethodException { public void testRebuildServerWithImage() throws IOException, SecurityException, NoSuchMethodException {
Method method = NovaAsyncClient.class.getMethod("rebuildServer", int.class, Method method = NovaAsyncClient.class.getMethod("rebuildServer", int.class,
rebuildServerOptionsVarargsClass); 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, ""); 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); assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class);
assertSaxResponseParserClassEquals(method, null); assertSaxResponseParserClassEquals(method, null);
@ -791,11 +514,12 @@ public class NovaAsyncClientTest extends RestClientTest<NovaAsyncClient> {
checkFilters(request); checkFilters(request);
} }
@Test
public void testReboot() throws IOException, SecurityException, NoSuchMethodException { public void testReboot() throws IOException, SecurityException, NoSuchMethodException {
Method method = NovaAsyncClient.class.getMethod("rebootServer", int.class, RebootType.class); Method method = NovaAsyncClient.class.getMethod("rebootServer", int.class, RebootType.class);
HttpRequest request = processor.createRequest(method, 2, RebootType.HARD); 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, ""); assertNonPayloadHeadersEqual(request, "");
assertPayloadEquals(request, "{\"reboot\":{\"type\":\"HARD\"}}", MediaType.APPLICATION_JSON, false); assertPayloadEquals(request, "{\"reboot\":{\"type\":\"HARD\"}}", MediaType.APPLICATION_JSON, false);
@ -806,11 +530,12 @@ public class NovaAsyncClientTest extends RestClientTest<NovaAsyncClient> {
checkFilters(request); checkFilters(request);
} }
@Test
public void testResize() throws IOException, SecurityException, NoSuchMethodException { public void testResize() throws IOException, SecurityException, NoSuchMethodException {
Method method = NovaAsyncClient.class.getMethod("resizeServer", int.class, int.class); Method method = NovaAsyncClient.class.getMethod("resizeServer", int.class, int.class);
HttpRequest request = processor.createRequest(method, 2, 3); 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, ""); assertNonPayloadHeadersEqual(request, "");
assertPayloadEquals(request, "{\"resize\":{\"flavorId\":3}}", MediaType.APPLICATION_JSON, false); 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); Method method = NovaAsyncClient.class.getMethod("confirmResizeServer", int.class);
HttpRequest request = processor.createRequest(method, 2); 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, ""); assertNonPayloadHeadersEqual(request, "");
assertPayloadEquals(request, "{\"confirmResize\":null}", MediaType.APPLICATION_JSON, false); 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); Method method = NovaAsyncClient.class.getMethod("revertResizeServer", int.class);
HttpRequest request = processor.createRequest(method, 2); 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, ""); assertNonPayloadHeadersEqual(request, "");
assertPayloadEquals(request, "{\"revertResize\":null}", MediaType.APPLICATION_JSON, false); assertPayloadEquals(request, "{\"revertResize\":null}", MediaType.APPLICATION_JSON, false);
@ -880,7 +605,7 @@ public class NovaAsyncClientTest extends RestClientTest<NovaAsyncClient> {
@Override @Override
protected URI provideServerUrl(AuthenticationResponse response) { 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 @Override
protected Properties getProperties() { protected Properties getProperties() {
Properties overrides = new Properties(); Properties overrides = new Properties();
overrides.setProperty(PROPERTY_REGIONS, "US"); overrides.setProperty(PROPERTY_API_VERSION, "apiversion");
overrides.setProperty(PROPERTY_API_VERSION, "1"); overrides.setProperty(provider + ".endpoint", "http://endpoint");
overrides.setProperty(provider + ".endpoint", "https://auth");
overrides.setProperty(provider + ".contextbuilder", NovaContextBuilder.class.getName()); overrides.setProperty(provider + ".contextbuilder", NovaContextBuilder.class.getName());
return overrides; return overrides;
} }

View File

@ -1,638 +0,0 @@
/**
*
* 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 static com.google.common.base.Preconditions.checkNotNull;
import static org.jclouds.openstack.nova.options.CreateServerOptions.Builder.withFile;
import static org.jclouds.openstack.nova.options.CreateSharedIpGroupOptions.Builder.withServer;
import static org.jclouds.openstack.nova.options.ListOptions.Builder.withDetails;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertTrue;
import java.io.IOException;
import java.lang.reflect.UndeclaredThrowableException;
import java.security.SecureRandom;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.jclouds.Constants;
import org.jclouds.openstack.nova.domain.BackupSchedule;
import org.jclouds.openstack.nova.domain.DailyBackup;
import org.jclouds.openstack.nova.domain.Flavor;
import org.jclouds.openstack.nova.domain.Image;
import org.jclouds.openstack.nova.domain.ImageStatus;
import org.jclouds.openstack.nova.domain.RebootType;
import org.jclouds.openstack.nova.domain.Server;
import org.jclouds.openstack.nova.domain.ServerStatus;
import org.jclouds.openstack.nova.domain.SharedIpGroup;
import org.jclouds.openstack.nova.domain.WeeklyBackup;
import org.jclouds.openstack.nova.options.RebuildServerOptions;
import org.jclouds.compute.domain.ExecResponse;
import org.jclouds.domain.Credentials;
import org.jclouds.http.HttpResponseException;
import org.jclouds.io.Payload;
import org.jclouds.logging.log4j.config.Log4JLoggingModule;
import org.jclouds.net.IPSocket;
import org.jclouds.predicates.RetryablePredicate;
import org.jclouds.predicates.SocketOpen;
import org.jclouds.rest.RestContextFactory;
import org.jclouds.ssh.SshClient;
import org.jclouds.ssh.SshException;
import org.jclouds.ssh.jsch.config.JschSshClientModule;
import org.jclouds.util.Strings2;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeGroups;
import org.testng.annotations.Test;
import com.google.common.base.Predicate;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.inject.Injector;
import com.google.inject.Module;
/**
* Tests behavior of {@code NovaClient}
*
* @author Adrian Cole
*/
// disabled [Web Hosting #129069
@Test(groups = "live", sequential = true)
public class NovaClientLiveTest {
protected NovaClient client;
protected SshClient.Factory sshFactory;
private Predicate<IPSocket> socketTester;
protected String provider = "nova";
protected String identity;
protected String credential;
protected String endpoint;
protected String apiversion;
protected void setupCredentials() {
identity = checkNotNull(System.getProperty("test." + provider + ".identity"), "test." + provider + ".identity");
credential = checkNotNull(System.getProperty("test." + provider + ".credential"), "test." + provider
+ ".credential");
endpoint = System.getProperty("test." + provider + ".endpoint");
apiversion = System.getProperty("test." + provider + ".apiversion");
}
protected Properties setupProperties() {
Properties overrides = new Properties();
overrides.setProperty(Constants.PROPERTY_TRUST_ALL_CERTS, "true");
overrides.setProperty(Constants.PROPERTY_RELAX_HOSTNAME, "true");
overrides.setProperty(provider + ".identity", identity);
overrides.setProperty(provider + ".credential", credential);
if (endpoint != null)
overrides.setProperty(provider + ".endpoint", endpoint);
if (apiversion != null)
overrides.setProperty(provider + ".apiversion", apiversion);
return overrides;
}
@BeforeGroups(groups = { "live" })
public void setupClient() {
setupCredentials();
Properties overrides = setupProperties();
Injector injector = new RestContextFactory().createContextBuilder(provider,
ImmutableSet.<Module> of(new Log4JLoggingModule(), new JschSshClientModule()), overrides)
.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
}
public void testListServers() throws Exception {
Set<Server> response = client.listServers();
assert null != response;
long initialContainerCount = response.size();
assertTrue(initialContainerCount >= 0);
}
public void testListServersDetail() throws Exception {
Set<Server> response = client.listServers(withDetails());
assert null != response;
long initialContainerCount = response.size();
assertTrue(initialContainerCount >= 0);
}
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;
}
}
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;
}
}
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;
}
public void testGetServersDetail() throws Exception {
Set<Server> response = client.listServers(withDetails());
assert null != response;
long serverCount = response.size();
assertTrue(serverCount >= 0);
for (Server server : response) {
Server newDetails = client.getServer(server.getId());
assertEquals(server, newDetails);
}
}
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;
}
}
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;
}
}
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;
}
public void testListSharedIpGroups() throws Exception {
Set<SharedIpGroup> response = client.listSharedIpGroups();
assert null != response;
long sharedIpGroupCount = response.size();
assertTrue(sharedIpGroupCount >= 0);
for (SharedIpGroup sharedIpGroup : response) {
assertTrue(sharedIpGroup.getId() >= 0);
assert null != sharedIpGroup.getName() : sharedIpGroup;
}
}
public void testListSharedIpGroupsDetail() throws Exception {
Set<SharedIpGroup> response = client.listSharedIpGroups(withDetails());
assert null != response;
long sharedIpGroupCount = response.size();
assertTrue(sharedIpGroupCount >= 0);
for (SharedIpGroup sharedIpGroup : response) {
assertTrue(sharedIpGroup.getId() >= 1);
assert null != sharedIpGroup.getName() : sharedIpGroup;
assert null != sharedIpGroup.getServers() : sharedIpGroup;
}
}
public void testGetSharedIpGroupsDetail() throws Exception {
Set<SharedIpGroup> response = client.listSharedIpGroups(withDetails());
assert null != response;
long sharedIpGroupCount = response.size();
assertTrue(sharedIpGroupCount >= 0);
for (SharedIpGroup sharedIpGroup : response) {
SharedIpGroup newDetails = client.getSharedIpGroup(sharedIpGroup.getId());
assertEquals(sharedIpGroup, newDetails);
}
}
@Test
public void testGetSharedIpGroupDetailsNotFound() throws Exception {
assert client.getSharedIpGroup(12312987) == null;
}
@Test(enabled = false, timeOut = 5 * 60 * 1000, dependsOnMethods = "testCreateServer")
public void testCreateSharedIpGroup() throws Exception {
SharedIpGroup sharedIpGroup = null;
while (sharedIpGroup == null) {
String sharedIpGroupName = serverPrefix + "createSharedIpGroup" + new SecureRandom().nextInt();
try {
sharedIpGroup = client.createSharedIpGroup(sharedIpGroupName, withServer(serverId));
} catch (UndeclaredThrowableException e) {
HttpResponseException htpe = (HttpResponseException) e.getCause().getCause();
if (htpe.getResponse().getStatusCode() == 400)
continue;
throw e;
}
}
assertNotNull(sharedIpGroup.getName());
sharedIpGroupId = sharedIpGroup.getId();
// Response doesn't include the server id Web Hosting #119311
// assertEquals(sharedIpGroup.getServers(), ImmutableList.of(serverId));
}
private int sharedIpGroupId;
private String serverPrefix = System.getProperty("user.name") + ".cs";
private int serverId;
private String adminPass;
Map<String, String> metadata = ImmutableMap.of("jclouds", "rackspace");
private String ip;
private int serverId2;
private String adminPass2;
private int imageId;
@Test(enabled = false)
public void testCreateServer() throws Exception {
int imageId = 14362;
int flavorId = 1;
Server server = null;
while (server == null) {
String serverName = serverPrefix + "createserver" + new SecureRandom().nextInt();
try {
server = client.createServer(serverName, imageId, flavorId, withFile("/etc/jclouds.txt",
"rackspace".getBytes()).withMetadata(metadata));
} catch (UndeclaredThrowableException e) {
HttpResponseException htpe = (HttpResponseException) e.getCause().getCause();
if (htpe.getResponse().getStatusCode() == 400)
continue;
throw e;
}
}
assertNotNull(server.getAdminPass());
serverId = server.getId();
adminPass = server.getAdminPass();
ip = server.getAddresses().getPublicAddresses().iterator().next();
assertEquals(server.getStatus(), ServerStatus.BUILD);
blockUntilServerActive(serverId);
}
private void blockUntilServerActive(int serverId) throws InterruptedException {
Server currentDetails = null;
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 = null;
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 imageId) throws InterruptedException {
Image currentDetails = null;
for (currentDetails = client.getImage(imageId); currentDetails.getStatus() != ImageStatus.ACTIVE; currentDetails = client
.getImage(imageId)) {
System.out.printf("blocking on status active%n%s%n", currentDetails);
Thread.sleep(5 * 1000);
}
}
@Test(enabled = false, timeOut = 5 * 60 * 1000, dependsOnMethods = "testCreateServer")
public void testServerDetails() throws Exception {
Server server = client.getServer(serverId);
assertNotNull(server.getHostId());
assertEquals(server.getStatus(), ServerStatus.ACTIVE);
assert server.getProgress() >= 0 : "newDetails.getProgress()" + server.getProgress();
assertEquals(new Integer(14362), server.getImageId());
assertEquals(new Integer(1), server.getFlavorId());
assertNotNull(server.getAddresses());
// listAddresses tests..
assertEquals(client.getAddresses(serverId), server.getAddresses());
assertEquals(server.getAddresses().getPublicAddresses().size(), 1);
assertEquals(client.listPublicAddresses(serverId), server.getAddresses().getPublicAddresses());
assertEquals(server.getAddresses().getPrivateAddresses().size(), 1);
assertEquals(client.listPrivateAddresses(serverId), server.getAddresses().getPrivateAddresses());
// check metadata
assertEquals(server.getMetadata(), metadata);
checkPassOk(server, adminPass);
}
/**
* this tests "personality" as the file looked up was sent during server creation
*/
private void checkPassOk(Server newDetails, String pass) throws IOException {
try {
doCheckPass(newDetails, pass);
} catch (SshException e) {// try twice in case there is a network timeout
try {
Thread.sleep(10 * 1000);
} catch (InterruptedException e1) {
}
doCheckPass(newDetails, pass);
}
}
private void doCheckPass(Server newDetails, String pass) throws IOException {
IPSocket socket = new IPSocket(Iterables.get(newDetails.getAddresses().getPublicAddresses(), 0), 22);
socketTester.apply(socket);
SshClient client = sshFactory.create(socket, new Credentials("root", pass));
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();
}
}
private ExecResponse exec(Server details, String pass, String command) throws IOException {
IPSocket socket = new IPSocket(Iterables.get(details.getAddresses().getPublicAddresses(), 0), 22);
socketTester.apply(socket);
SshClient client = sshFactory.create(socket, new Credentials("root", pass));
try {
client.connect();
return client.exec(command);
} finally {
if (client != null)
client.disconnect();
}
}
@Test(enabled = false, timeOut = 5 * 60 * 1000, dependsOnMethods = "testCreateServer")
public void testRenameServer() throws Exception {
Server server = client.getServer(serverId);
String oldName = server.getName();
client.renameServer(serverId, oldName + "new");
blockUntilServerActive(serverId);
assertEquals(oldName + "new", client.getServer(serverId).getName());
}
@Test(enabled = false, timeOut = 5 * 60 * 1000, dependsOnMethods = "testCreateServer")
public void testChangePassword() throws Exception {
client.changeAdminPass(serverId, "elmo");
blockUntilServerActive(serverId);
checkPassOk(client.getServer(serverId), "elmo");
this.adminPass = "elmo";
}
@Test(enabled = false, timeOut = 5 * 60 * 1000, dependsOnMethods = "testCreateSharedIpGroup")
public void testCreateServerIp() throws Exception {
int imageId = 14362;
int flavorId = 1;
Server server = null;
while (server == null) {
String serverName = serverPrefix + "createserver" + new SecureRandom().nextInt();
try {
server = client
.createServer(serverName, imageId, flavorId, withFile("/etc/jclouds.txt", "rackspace".getBytes())
.withMetadata(metadata).withSharedIpGroup(sharedIpGroupId).withSharedIp(ip));
} catch (UndeclaredThrowableException e) {
HttpResponseException htpe = (HttpResponseException) e.getCause().getCause();
if (htpe.getResponse().getStatusCode() == 400)
continue;
throw e;
}
}
assertNotNull(server.getAdminPass());
serverId2 = server.getId();
adminPass2 = server.getAdminPass();
blockUntilServerActive(serverId2);
assertIpConfigured(server, adminPass2);
assert server.getAddresses().getPublicAddresses().contains(ip) : server.getAddresses() + " doesn't contain " + ip;
assertEquals(server.getSharedIpGroupId(), new Integer(sharedIpGroupId));
}
private void assertIpConfigured(Server server, String password) {
try {
ExecResponse response = exec(server, password, "ifconfig -a");
assert response.getOutput().indexOf(ip) > 0 : String.format("server %s didn't get ip %s%n%s", server, ip,
response);
} catch (Exception e) {
e.printStackTrace();
} catch (AssertionError e) {
e.printStackTrace();
}
}
@Test(enabled = false, timeOut = 10 * 60 * 1000, dependsOnMethods = "testCreateServerIp")
public void testUnshare() throws Exception {
client.unshareIp(ip, serverId2);
blockUntilServerActive(serverId2);
Server server = client.getServer(serverId2);
assert !server.getAddresses().getPublicAddresses().contains(ip) : server.getAddresses();
assertIpNotConfigured(server, adminPass2);
}
private void assertIpNotConfigured(Server server, String password) {
try {
ExecResponse response = exec(server, password, "ifconfig -a");
assert response.getOutput().indexOf(ip) == -1 : String.format("server %s still has get ip %s%n%s", server, ip,
response);
} catch (Exception e) {
e.printStackTrace();
} catch (AssertionError e) {
e.printStackTrace();
}
}
@Test(enabled = false, timeOut = 10 * 60 * 1000, dependsOnMethods = "testUnshare")
public void testShareConfig() throws Exception {
client.shareIp(ip, serverId2, sharedIpGroupId, true);
blockUntilServerActive(serverId2);
Server server = client.getServer(serverId2);
assert server.getAddresses().getPublicAddresses().contains(ip) : server.getAddresses();
assertIpConfigured(server, adminPass2);
testUnshare();
}
@Test(enabled = false, timeOut = 10 * 60 * 1000, dependsOnMethods = "testShareConfig")
public void testShareNoConfig() throws Exception {
client.shareIp(ip, serverId2, sharedIpGroupId, false);
blockUntilServerActive(serverId2);
Server server = client.getServer(serverId2);
assert server.getAddresses().getPublicAddresses().contains(ip) : server.getAddresses();
assertIpNotConfigured(server, adminPass2);
testUnshare();
}
@Test(enabled = false, timeOut = 10 * 60 * 1000, dependsOnMethods = "testShareNoConfig")
public void testBackup() throws Exception {
assertEquals(new BackupSchedule(), client.getBackupSchedule(serverId));
BackupSchedule dailyWeekly = new BackupSchedule();
dailyWeekly.setEnabled(true);
dailyWeekly.setWeekly(WeeklyBackup.FRIDAY);
dailyWeekly.setDaily(DailyBackup.H_0400_0600);
client.replaceBackupSchedule(serverId, dailyWeekly);
client.deleteBackupSchedule(serverId);
// disables, doesn't delete: Web Hosting #119571
assertEquals(client.getBackupSchedule(serverId).isEnabled(), false);
}
@Test(enabled = false, timeOut = 10 * 60 * 1000, dependsOnMethods = "testBackup")
public void testCreateImage() throws Exception {
Image image = client.createImageFromServer("hoofie", serverId);
assertEquals("hoofie", image.getName());
assertEquals(new Integer(serverId), image.getServerId());
imageId = image.getId();
blockUntilImageActive(imageId);
}
@Test(enabled = false, timeOut = 10 * 60 * 1000, dependsOnMethods = "testCreateImage")
public void testRebuildServer() throws Exception {
client.rebuildServer(serverId, new RebuildServerOptions().withImage(imageId));
blockUntilServerActive(serverId);
// issue Web Hosting #119580 imageId comes back incorrect after rebuild
// assertEquals(new Integer(imageId), client.getServer(serverId).getImageId());
}
@Test(enabled = false, timeOut = 10 * 60 * 1000, dependsOnMethods = "testRebuildServer")
public void testRebootHard() throws Exception {
client.rebootServer(serverId, RebootType.HARD);
blockUntilServerActive(serverId);
}
@Test(enabled = false, timeOut = 10 * 60 * 1000, dependsOnMethods = "testRebootHard")
public void testRebootSoft() throws Exception {
client.rebootServer(serverId, RebootType.SOFT);
blockUntilServerActive(serverId);
}
@Test(enabled = false, timeOut = 10 * 60 * 1000, dependsOnMethods = "testRebootSoft")
public void testRevertResize() throws Exception {
client.resizeServer(serverId, 2);
blockUntilServerVerifyResize(serverId);
client.revertResizeServer(serverId);
blockUntilServerActive(serverId);
assertEquals(new Integer(1), client.getServer(serverId).getFlavorId());
}
@Test(enabled = false, timeOut = 10 * 60 * 1000, dependsOnMethods = "testRebootSoft")
public void testConfirmResize() throws Exception {
client.resizeServer(serverId2, 2);
blockUntilServerVerifyResize(serverId2);
client.confirmResizeServer(serverId2);
blockUntilServerActive(serverId2);
assertEquals(new Integer(2), client.getServer(serverId2).getFlavorId());
}
@Test(enabled = false, timeOut = 10 * 60 * 1000, dependsOnMethods = { "testRebootSoft", "testRevertResize",
"testConfirmResize" })
void deleteServer2() {
if (serverId2 > 0) {
client.deleteServer(serverId2);
assert client.getServer(serverId2) == null;
}
}
@Test(enabled = false, timeOut = 10 * 60 * 1000, dependsOnMethods = "deleteServer2")
void testDeleteImage() {
if (imageId > 0) {
client.deleteImage(imageId);
assert client.getImage(imageId) == null;
}
}
@Test(enabled = false, timeOut = 10 * 60 * 1000, dependsOnMethods = "testDeleteImage")
void deleteServer1() {
if (serverId > 0) {
client.deleteServer(serverId);
assert client.getServer(serverId) == null;
}
}
@Test(enabled = false, timeOut = 10 * 60 * 1000, dependsOnMethods = { "deleteServer1" })
void testDeleteSharedIpGroup() {
if (sharedIpGroupId > 0) {
client.deleteSharedIpGroup(sharedIpGroupId);
assert client.getSharedIpGroup(sharedIpGroupId) == null;
}
}
@AfterTest
void deleteServersOnEnd() {
if (serverId > 0) {
client.deleteServer(serverId);
}
if (serverId2 > 0) {
client.deleteServer(serverId2);
}
if (sharedIpGroupId > 0) {
client.deleteSharedIpGroup(sharedIpGroupId);
}
}
}

View File

@ -1,88 +0,0 @@
/**
*
* 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;
import static org.testng.Assert.assertEquals;
import java.io.IOException;
import org.jclouds.openstack.nova.NovaAsyncClient;
import org.jclouds.openstack.nova.NovaClient;
import org.jclouds.compute.BaseComputeServiceLiveTest;
import org.jclouds.compute.ComputeServiceContextFactory;
import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.domain.LocationScope;
import org.jclouds.rest.RestContext;
import org.jclouds.ssh.jsch.config.JschSshClientModule;
import org.testng.annotations.Test;
/**
*
* Generally disabled, as it incurs higher fees.
*
* @author Adrian Cole
*/
@Test(groups = "live", enabled = true, sequential = true)
public class NovaComputeServiceLiveTest extends BaseComputeServiceLiveTest {
public NovaComputeServiceLiveTest() {
provider = "nova";
}
@Override
protected JschSshClientModule getSshModule() {
return new JschSshClientModule();
}
public void testAssignability() throws Exception {
@SuppressWarnings("unused")
RestContext<NovaClient, NovaAsyncClient> tmContext = new ComputeServiceContextFactory()
.createContext(provider, identity, credential).getProviderSpecificContext();
}
@Override
protected void checkNodes(Iterable<? extends NodeMetadata> nodes, String tag) throws IOException {
super.checkNodes(nodes, tag);
for (NodeMetadata node : nodes) {
assertEquals(node.getLocation().getScope(), LocationScope.HOST);
}
}
@Test(enabled = true, dependsOnMethods = "testReboot", expectedExceptions = UnsupportedOperationException.class)
public void testSuspendResume() throws Exception {
super.testSuspendResume();
}
@Test(enabled = true, dependsOnMethods = "testSuspendResume")
@Override
public void testGetNodesWithDetails() throws Exception {
super.testGetNodesWithDetails();
}
@Test(enabled = true, dependsOnMethods = "testSuspendResume")
@Override
public void testListNodes() throws Exception {
super.testListNodes();
}
@Test(enabled = true, dependsOnMethods = { "testListNodes", "testGetNodesWithDetails" })
@Override
public void testDestroyNodes() {
super.testDestroyNodes();
}
}

View File

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

View File

@ -18,14 +18,11 @@
*/ */
package org.jclouds.openstack.nova.compute.functions; package org.jclouds.openstack.nova.compute.functions;
import static org.testng.Assert.assertEquals; import com.google.inject.Guice;
import java.net.UnknownHostException;
import org.jclouds.compute.config.BaseComputeServiceContextModule; import org.jclouds.compute.config.BaseComputeServiceContextModule;
import org.jclouds.compute.domain.Image; import org.jclouds.compute.domain.Image;
import org.jclouds.compute.domain.ImageBuilder; 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.domain.OsFamily;
import org.jclouds.compute.reference.ComputeServiceConstants; import org.jclouds.compute.reference.ComputeServiceConstants;
import org.jclouds.domain.Credentials; import org.jclouds.domain.Credentials;
@ -34,7 +31,11 @@ import org.jclouds.json.config.GsonModule;
import org.jclouds.openstack.nova.functions.ParseImageFromJsonResponseTest; import org.jclouds.openstack.nova.functions.ParseImageFromJsonResponseTest;
import org.testng.annotations.Test; 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 * @author Adrian Cole
@ -43,15 +44,16 @@ import com.google.inject.Guice;
public class NovaImageToImageTest { public class NovaImageToImageTest {
@Test @Test
public void testApplyWhereImageNotFound() throws UnknownHostException { public void testApplyWhereImageNotFound() throws UnknownHostException, URISyntaxException {
assertEquals( Image image = new ImageBuilder()
convertImage(),
new ImageBuilder()
.name("CentOS 5.2") .name("CentOS 5.2")
.operatingSystem( .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)) .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() { public static Image convertImage() {

View File

@ -18,37 +18,28 @@
*/ */
package org.jclouds.openstack.nova.compute.functions; package org.jclouds.openstack.nova.compute.functions;
import static org.testng.Assert.assertEquals;
import java.net.UnknownHostException;
import java.util.Map;
import java.util.Set;
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.jclouds.compute.domain.Hardware;
import org.jclouds.compute.domain.HardwareBuilder;
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.OperatingSystemBuilder;
import org.jclouds.compute.domain.OsFamily;
import org.jclouds.compute.domain.Processor;
import org.jclouds.compute.domain.Volume;
import org.jclouds.compute.domain.VolumeBuilder;
import org.jclouds.domain.Credentials;
import org.jclouds.domain.Location;
import org.jclouds.domain.LocationBuilder;
import org.jclouds.domain.LocationScope;
import org.testng.annotations.Test;
import com.google.common.base.Suppliers; import com.google.common.base.Suppliers;
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet; 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 * @author Adrian Cole
@ -58,7 +49,7 @@ public class ServerToNodeMetadataTest {
Location provider = new LocationBuilder().scope(LocationScope.ZONE).id("dallas").description("description").build(); Location provider = new LocationBuilder().scope(LocationScope.ZONE).id("dallas").description("description").build();
@Test @Test
public void testApplyWhereImageAndHardwareNotFoundButCredentialsFound() throws UnknownHostException { public void testApplyWhereImageAndHardwareNotFoundButCredentialsFound() throws UnknownHostException, NoSuchMethodException, ClassNotFoundException, URISyntaxException {
Credentials creds = new Credentials("root", "abdce"); Credentials creds = new Credentials("root", "abdce");
Map<ServerStatus, NodeState> serverStateToNodeState = NovaComputeServiceDependenciesModule.serverToNodeState; Map<ServerStatus, NodeState> serverStateToNodeState = NovaComputeServiceDependenciesModule.serverToNodeState;
@ -72,16 +63,13 @@ public class ServerToNodeMetadataTest {
NodeMetadata metadata = parser.apply(server); NodeMetadata metadata = parser.apply(server);
assertEquals(metadata, new NodeMetadataBuilder().state(NodeState.PENDING).publicAddresses( NodeMetadata constructedMetadata = newNodeMetadataBuilder()
ImmutableSet.of("67.23.10.132", "67.23.10.131")).privateAddresses(ImmutableSet.of("10.176.42.16")) .credentials(creds).build();
.imageId("2").id("1234").providerId("1234").name("sample-server").credentials(creds).location( assertEquals(metadata, constructedMetadata);
new LocationBuilder().scope(LocationScope.HOST).id("e4d909c290d0fb1ca068ffaddf22cbd0")
.description("e4d909c290d0fb1ca068ffaddf22cbd0").parent(provider).build())
.userMetadata(ImmutableMap.of("Server Label", "Web Head 1", "Image Version", "2.1")).build());
} }
@Test @Test
public void testApplyWhereImageAndHardwareNotFound() throws UnknownHostException { public void testApplyWhereImageAndHardwareNotFound() throws UnknownHostException, NoSuchMethodException, ClassNotFoundException, URISyntaxException {
Map<ServerStatus, NodeState> serverStateToNodeState = NovaComputeServiceDependenciesModule.serverToNodeState; Map<ServerStatus, NodeState> serverStateToNodeState = NovaComputeServiceDependenciesModule.serverToNodeState;
Set<org.jclouds.compute.domain.Image> images = ImmutableSet.of(); Set<org.jclouds.compute.domain.Image> images = ImmutableSet.of();
Set<org.jclouds.compute.domain.Hardware> hardwares = ImmutableSet.of(); Set<org.jclouds.compute.domain.Hardware> hardwares = ImmutableSet.of();
@ -93,17 +81,31 @@ public class ServerToNodeMetadataTest {
NodeMetadata metadata = parser.apply(server); NodeMetadata metadata = parser.apply(server);
assertEquals(metadata, new NodeMetadataBuilder().state(NodeState.PENDING).publicAddresses( NodeMetadata constructedMetadata = newNodeMetadataBuilder().build();
ImmutableSet.of("67.23.10.132", "67.23.10.131")).privateAddresses(ImmutableSet.of("10.176.42.16"))
.imageId("2").id("1234").providerId("1234").name("sample-server").location( assertEquals(metadata, constructedMetadata);
new LocationBuilder().scope(LocationScope.HOST).id("e4d909c290d0fb1ca068ffaddf22cbd0")
.description("e4d909c290d0fb1ca068ffaddf22cbd0").parent(provider).build())
.userMetadata(ImmutableMap.of("Server Label", "Web Head 1", "Image Version", "2.1")).build());
} }
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 @Test
public void testApplyWhereImageFoundAndHardwareNotFound() throws UnknownHostException { public void testApplyWhereImageFoundAndHardwareNotFound() throws UnknownHostException, NoSuchMethodException, ClassNotFoundException, URISyntaxException {
Map<ServerStatus, NodeState> serverStateToNodeState = NovaComputeServiceDependenciesModule.serverToNodeState; Map<ServerStatus, NodeState> serverStateToNodeState = NovaComputeServiceDependenciesModule.serverToNodeState;
org.jclouds.compute.domain.Image jcImage = NovaImageToImageTest.convertImage(); org.jclouds.compute.domain.Image jcImage = NovaImageToImageTest.convertImage();
Set<org.jclouds.compute.domain.Image> images = ImmutableSet.of(jcImage); Set<org.jclouds.compute.domain.Image> images = ImmutableSet.of(jcImage);
@ -116,19 +118,21 @@ public class ServerToNodeMetadataTest {
NodeMetadata metadata = parser.apply(server); NodeMetadata metadata = parser.apply(server);
assertEquals(metadata, new NodeMetadataBuilder().state(NodeState.PENDING).publicAddresses( NodeMetadata constructedMetadata = newNodeMetadataBuilder()
ImmutableSet.of("67.23.10.132", "67.23.10.131")).privateAddresses(ImmutableSet.of("10.176.42.16")) .imageId("2")
.imageId("2").operatingSystem( .operatingSystem(new OperatingSystem.Builder()
new OperatingSystemBuilder().family(OsFamily.CENTOS).description("CentOS 5.2").version("5.2") .family(OsFamily.CENTOS)
.is64Bit(true).build()).id("1234").providerId("1234").name("sample-server").location( .description("CentOS 5.2")
new LocationBuilder().scope(LocationScope.HOST).id("e4d909c290d0fb1ca068ffaddf22cbd0") .version("5.2")
.description("e4d909c290d0fb1ca068ffaddf22cbd0").parent(provider).build()) .is64Bit(true).build())
.userMetadata(ImmutableMap.of("Server Label", "Web Head 1", "Image Version", "2.1")).build()); .build();
assertEquals(metadata, constructedMetadata);
} }
@Test @Test
public void testApplyWhereImageAndHardwareFound() throws UnknownHostException { public void testApplyWhereImageAndHardwareFound() throws UnknownHostException, NoSuchMethodException, ClassNotFoundException, URISyntaxException {
Map<ServerStatus, NodeState> serverStateToNodeState = NovaComputeServiceDependenciesModule.serverToNodeState; Map<ServerStatus, NodeState> serverStateToNodeState = NovaComputeServiceDependenciesModule.serverToNodeState;
Set<org.jclouds.compute.domain.Image> images = ImmutableSet.of(NovaImageToImageTest.convertImage()); Set<org.jclouds.compute.domain.Image> images = ImmutableSet.of(NovaImageToImageTest.convertImage());
Set<org.jclouds.compute.domain.Hardware> hardwares = ImmutableSet.of(FlavorToHardwareTest.convertFlavor()); Set<org.jclouds.compute.domain.Hardware> hardwares = ImmutableSet.of(FlavorToHardwareTest.convertFlavor());
@ -140,17 +144,27 @@ public class ServerToNodeMetadataTest {
NodeMetadata metadata = parser.apply(server); NodeMetadata metadata = parser.apply(server);
assertEquals(metadata, new NodeMetadataBuilder().state(NodeState.PENDING).publicAddresses( NodeMetadata constructedMetadata = newNodeMetadataBuilder()
ImmutableSet.of("67.23.10.132", "67.23.10.131")).privateAddresses(ImmutableSet.of("10.176.42.16")) .imageId("2")
.imageId("2").hardware( .operatingSystem(new OperatingSystem.Builder()
new HardwareBuilder().ids("1").name("256 MB Server").processors( .family(OsFamily.CENTOS)
ImmutableList.of(new Processor(1.0, 1.0))).ram(256).volumes( .description("CentOS 5.2")
ImmutableList.of(new VolumeBuilder().type(Volume.Type.LOCAL).size(10.0f).durable(true) .version("5.2")
.bootDevice(true).build())).build()).operatingSystem( .is64Bit(true).build())
new OperatingSystemBuilder().family(OsFamily.CENTOS).description("CentOS 5.2").version("5.2") .hardware(new HardwareBuilder()
.is64Bit(true).build()).id("1234").providerId("1234").name("sample-server").location( .ids("1")
new LocationBuilder().scope(LocationScope.HOST).id("e4d909c290d0fb1ca068ffaddf22cbd0") .name("256 MB Server")
.description("e4d909c290d0fb1ca068ffaddf22cbd0").parent(provider).build()) .processors(ImmutableList.of(new Processor(1.0, 1.0)))
.userMetadata(ImmutableMap.of("Server Label", "Web Head 1", "Image Version", "2.1")).build()); .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,66 @@
/**
*
* 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.
* ====================================================================
*/
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; package org.jclouds.openstack.nova.domain;
import static org.testng.Assert.assertEquals;
import org.testng.annotations.Test; import org.testng.annotations.Test;
import static org.testng.Assert.assertEquals;
/** /**
* Tests behavior of {@code CreateImageBinder} * Tests behavior of {@code CreateImageBinder}
* *

View File

@ -18,24 +18,26 @@
*/ */
package org.jclouds.openstack.nova.functions; 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.io.InputStream;
import java.net.UnknownHostException; import java.net.UnknownHostException;
import java.util.List; import java.util.List;
import org.jclouds.openstack.nova.domain.Addresses; import static org.testng.Assert.assertTrue;
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;
/** /**
* Tests behavior of {@code ParseAddressesFromJsonResponse} * Tests behavior of {@code ParseAddressesFromJsonResponse}
@ -46,17 +48,23 @@ import com.google.inject.TypeLiteral;
public class ParseAddressesFromJsonResponseTest { public class ParseAddressesFromJsonResponseTest {
Injector i = Guice.createInjector(new GsonModule()); Injector i = Guice.createInjector(new GsonModule());
@Test
public void testApplyInputStreamDetails() throws UnknownHostException { public void testApplyInputStreamDetails() throws UnknownHostException {
InputStream is = getClass().getResourceAsStream("/test_list_addresses.json"); InputStream is = getClass().getResourceAsStream("/test_list_addresses.json");
UnwrapOnlyJsonValue<Addresses> parser = i.getInstance(Key.get(new TypeLiteral<UnwrapOnlyJsonValue<Addresses>>() { UnwrapOnlyJsonValue<Addresses> parser = i.getInstance(Key.get(new TypeLiteral<UnwrapOnlyJsonValue<Addresses>>() {
})); }));
Addresses response = parser.apply(new HttpResponse(200, "ok", Payloads.newInputStreamPayload(is))); 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); List<Address> privateAddresses = ImmutableList.copyOf(
assertEquals(response.getPrivateAddresses(), privateAddresses); 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

@ -1,68 +0,0 @@
/**
*
* 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 static org.testng.Assert.assertEquals;
import java.io.InputStream;
import java.net.UnknownHostException;
import org.jclouds.openstack.nova.domain.BackupSchedule;
import org.jclouds.openstack.nova.domain.DailyBackup;
import org.jclouds.openstack.nova.domain.WeeklyBackup;
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.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Key;
import com.google.inject.TypeLiteral;
/**
* Tests behavior of {@code ParseBackupScheduleFromJsonResponse}
*
* @author Adrian Cole
*/
@Test(groups = "unit")
public class ParseBackupScheduleFromJsonResponseTest {
Injector i = Guice.createInjector(new GsonModule());
public void testApplyInputStreamDetails() throws UnknownHostException {
InputStream is = getClass().getResourceAsStream("/test_list_backupschedule.json");
UnwrapOnlyJsonValue<BackupSchedule> parser = i.getInstance(Key
.get(new TypeLiteral<UnwrapOnlyJsonValue<BackupSchedule>>() {
}));
BackupSchedule response = parser.apply(new HttpResponse(200, "ok", Payloads.newInputStreamPayload(is)));
assertEquals(new BackupSchedule(WeeklyBackup.THURSDAY, DailyBackup.H_0400_0600, true), response);
}
public void testNoSchedule() throws UnknownHostException {
UnwrapOnlyJsonValue<BackupSchedule> parser = i.getInstance(Key
.get(new TypeLiteral<UnwrapOnlyJsonValue<BackupSchedule>>() {
}));
BackupSchedule response = parser.apply(new HttpResponse(200, "ok", Payloads
.newStringPayload("{\"backupSchedule\":{\"enabled\" : false}}")));
assertEquals(new BackupSchedule(), response);
}
}

View File

@ -0,0 +1,150 @@
/**
*
* 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.
* ====================================================================
*/
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; 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.gson.Gson;
import com.google.inject.Guice; import com.google.inject.Guice;
import com.google.inject.Injector; import com.google.inject.Injector;
import com.google.inject.Key; import com.google.inject.Key;
import com.google.inject.TypeLiteral; 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} * Tests behavior of {@code ParseFlavorFromJsonResponse}
@ -42,12 +43,18 @@ import com.google.inject.TypeLiteral;
*/ */
@Test(groups = "unit") @Test(groups = "unit")
public class ParseFlavorFromJsonResponseTest { public class ParseFlavorFromJsonResponseTest {
public void test() {
@Test
public void testParseFlavorFromJsonResponseTest() throws IOException {
Flavor response = parseFlavor(); Flavor response = parseFlavor();
String json = new Gson().toJson(response); 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() { public static Flavor parseFlavor() {
@ -57,8 +64,7 @@ public class ParseFlavorFromJsonResponseTest {
UnwrapOnlyJsonValue<Flavor> parser = i.getInstance(Key.get(new TypeLiteral<UnwrapOnlyJsonValue<Flavor>>() { UnwrapOnlyJsonValue<Flavor> parser = i.getInstance(Key.get(new TypeLiteral<UnwrapOnlyJsonValue<Flavor>>() {
})); }));
Flavor response = parser.apply(new HttpResponse(200, "ok", Payloads.newInputStreamPayload(is))); return parser.apply(new HttpResponse(200, "ok", Payloads.newInputStreamPayload(is)));
return response;
} }
} }

View File

@ -18,24 +18,23 @@
*/ */
package org.jclouds.openstack.nova.functions; 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.common.collect.ImmutableList;
import com.google.inject.Guice; import com.google.inject.Guice;
import com.google.inject.Injector; import com.google.inject.Injector;
import com.google.inject.Key; import com.google.inject.Key;
import com.google.inject.TypeLiteral; 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} * Tests behavior of {@code ParseFlavorListFromJsonResponse}
@ -47,6 +46,7 @@ public class ParseFlavorListFromJsonResponseTest {
Injector i = Guice.createInjector(new GsonModule()); Injector i = Guice.createInjector(new GsonModule());
@Test
public void testApplyInputStream() { public void testApplyInputStream() {
InputStream is = getClass().getResourceAsStream("/test_list_flavors.json"); InputStream is = getClass().getResourceAsStream("/test_list_flavors.json");
@ -59,6 +59,7 @@ public class ParseFlavorListFromJsonResponseTest {
assertEquals(response, expects); assertEquals(response, expects);
} }
@Test
public void testApplyInputStreamDetails() throws UnknownHostException { public void testApplyInputStreamDetails() throws UnknownHostException {
InputStream is = getClass().getResourceAsStream("/test_list_flavors_detail.json"); InputStream is = getClass().getResourceAsStream("/test_list_flavors_detail.json");

View File

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

View File

@ -18,14 +18,8 @@
*/ */
package org.jclouds.openstack.nova.functions; package org.jclouds.openstack.nova.functions;
import static org.testng.Assert.assertEquals; import com.google.common.collect.ImmutableList;
import com.google.inject.*;
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 org.jclouds.date.DateService; import org.jclouds.date.DateService;
import org.jclouds.http.HttpResponse; import org.jclouds.http.HttpResponse;
import org.jclouds.http.functions.UnwrapOnlyJsonValue; 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;
import org.jclouds.json.config.GsonModule.DateAdapter; import org.jclouds.json.config.GsonModule.DateAdapter;
import org.jclouds.json.config.GsonModule.Iso8601DateAdapter; 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 org.testng.annotations.Test;
import com.google.common.collect.ImmutableList; import java.io.InputStream;
import com.google.inject.AbstractModule; import java.net.UnknownHostException;
import com.google.inject.Guice; import java.util.List;
import com.google.inject.Injector;
import com.google.inject.Key; import static org.testng.Assert.assertEquals;
import com.google.inject.TypeLiteral;
/** /**
* Tests behavior of {@code ParseImageListFromJsonResponse} * Tests behavior of {@code ParseImageListFromJsonResponse}
@ -59,10 +54,11 @@ public class ParseImageListFromJsonResponseTest {
}, new GsonModule()); }, new GsonModule());
DateService dateService = i.getInstance(DateService.class); DateService dateService = i.getInstance(DateService.class);
@Test
public void testApplyInputStream() { public void testApplyInputStream() {
InputStream is = getClass().getResourceAsStream("/test_list_images.json"); 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 UnwrapOnlyJsonValue<List<Image>> parser = i.getInstance(Key
.get(new TypeLiteral<UnwrapOnlyJsonValue<List<Image>>>() { .get(new TypeLiteral<UnwrapOnlyJsonValue<List<Image>>>() {
@ -72,6 +68,7 @@ public class ParseImageListFromJsonResponseTest {
assertEquals(response, expects); assertEquals(response, expects);
} }
@Test
public void testApplyInputStreamDetails() throws UnknownHostException { public void testApplyInputStreamDetails() throws UnknownHostException {
InputStream is = getClass().getResourceAsStream("/test_list_images_detail.json"); 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))); 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).getName(), "CentOS 5.2");
assertEquals(response.get(0).getCreated(), dateService.iso8601SecondsDateParse("2010-08-10T12:00:00Z")); assertEquals(response.get(0).getCreated(), dateService.iso8601SecondsDateParse("2010-08-10T12:00:00Z"));
assertEquals(response.get(0).getProgress(), null); 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).getStatus(), ImageStatus.ACTIVE);
assertEquals(response.get(0).getUpdated(), dateService.iso8601SecondsDateParse("2010-10-10T12:00:00Z")); 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).getId(), 743);
assertEquals(response.get(1).getName(), "My Server Backup"); 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).getProgress(), new Integer(80));
assertEquals(response.get(1).getServerId(), new Integer(12));
assertEquals(response.get(1).getStatus(), ImageStatus.SAVING); assertEquals(response.get(1).getStatus(), ImageStatus.SAVING);
assertEquals(response.get(1).getUpdated(), dateService.iso8601SecondsDateParse("2010-10-10T12:00:00Z")); 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; 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.common.collect.ImmutableList;
import com.google.inject.Guice; import com.google.inject.Guice;
import com.google.inject.Injector; import com.google.inject.Injector;
import com.google.inject.Key; import com.google.inject.Key;
import com.google.inject.TypeLiteral; 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} * Tests behavior of {@code ParseInetAddressListFromJsonResponse}
@ -46,25 +46,33 @@ public class ParseInetAddressListFromJsonResponseTest {
Injector i = Guice.createInjector(new GsonModule()); Injector i = Guice.createInjector(new GsonModule());
@Test
public void testPublic() throws UnknownHostException { public void testPublic() throws UnknownHostException {
InputStream is = getClass().getResourceAsStream("/test_list_addresses_public.json"); InputStream is = getClass().getResourceAsStream("/test_list_addresses_public.json");
UnwrapOnlyJsonValue<List<String>> parser = i.getInstance(Key UnwrapOnlyJsonValue<List<Address>> parser = i.getInstance(Key
.get(new TypeLiteral<UnwrapOnlyJsonValue<List<String>>>() { .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 { public void testPrivate() throws UnknownHostException {
InputStream is = getClass().getResourceAsStream("/test_list_addresses_private.json"); InputStream is = getClass().getResourceAsStream("/test_list_addresses_private.json");
UnwrapOnlyJsonValue<List<String>> parser = i.getInstance(Key UnwrapOnlyJsonValue<List<Address>> parser = i.getInstance(Key
.get(new TypeLiteral<UnwrapOnlyJsonValue<List<String>>>() { .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; package org.jclouds.openstack.nova.functions;
import static org.testng.Assert.assertEquals; import com.google.common.collect.ImmutableList;
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.ImmutableMap; 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.Guice;
import com.google.inject.Injector; import com.google.inject.Injector;
import com.google.inject.Key; import com.google.inject.Key;
import com.google.inject.TypeLiteral; 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} * Tests behavior of {@code ParseServerFromJsonResponse}
@ -48,35 +54,54 @@ import com.google.inject.TypeLiteral;
@Test(groups = "unit") @Test(groups = "unit")
public class ParseServerFromJsonResponseTest { public class ParseServerFromJsonResponseTest {
public void testApplyInputStreamDetails() throws UnknownHostException { @Test
public void testApplyInputStreamDetails() throws UnknownHostException, NoSuchMethodException, ClassNotFoundException, ParseException {
Server response = parseServer(); Server response = parseServer();
assertEquals(response.getId(), 1234); assertEquals(response.getId(), 1234);
assertEquals(response.getName(), "sample-server"); assertEquals(response.getName(), "sample-server");
assertEquals(response.getImageId(), new Integer(2)); assertEquals(response.getImageRef(), "https://servers.api.rackspacecloud.com/v1.1/1234/images/1");
assertEquals(response.getFlavorId(), new Integer(1)); assertEquals(response.getFlavorRef(), "http://servers.api.openstack.org/1234/flavors/1");
assertEquals(response.getHostId(), "e4d909c290d0fb1ca068ffaddf22cbd0"); assertEquals(response.getHostId(), "e4d909c290d0fb1ca068ffaddf22cbd0");
assertEquals(response.getStatus(), ServerStatus.BUILD); assertEquals(response.getStatus(), ServerStatus.BUILD);
assertEquals(response.getProgress(), new Integer(60)); assertEquals(response.getProgress(), new Integer(60));
List<String> publicAddresses = Lists.newArrayList("67.23.10.132", "67.23.10.131"); SimpleDateFormat dateFormat = new SimpleDateFormat(
List<String> privateAddresses = Lists.newArrayList("10.176.42.16"); "yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.US);
Addresses addresses1 = new Addresses(); dateFormat.setTimeZone(new SimpleTimeZone(0, "GMT"));
addresses1.getPrivateAddresses().addAll(privateAddresses); assertEquals(response.getCreated(),
addresses1.getPublicAddresses().addAll(publicAddresses); 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.getAddresses(), addresses1);
assertEquals(response.getMetadata(), ImmutableMap.of("Server Label", "Web Head 1", "Image Version", "2.1")); 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"); InputStream is = ParseServerFromJsonResponseTest.class.getResourceAsStream("/test_get_server_detail.json");
UnwrapOnlyJsonValue<Server> parser = i.getInstance(Key.get(new TypeLiteral<UnwrapOnlyJsonValue<Server>>() { 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.io.InputStream;
import java.net.UnknownHostException; import java.net.UnknownHostException;
import java.util.HashSet;
import java.util.List; 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.HttpResponse;
import org.jclouds.http.functions.UnwrapOnlyJsonValue; import org.jclouds.http.functions.UnwrapOnlyJsonValue;
import org.jclouds.io.Payloads; import org.jclouds.io.Payloads;
import org.jclouds.json.config.GsonModule; 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 org.testng.annotations.Test;
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap; 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.Guice;
import com.google.inject.Injector; import com.google.inject.Injector;
import com.google.inject.Key; import com.google.inject.Key;
@ -49,8 +51,15 @@ import com.google.inject.TypeLiteral;
@Test(groups = "unit") @Test(groups = "unit")
public class ParseServerListFromJsonResponseTest { 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() { public void testApplyInputStream() {
InputStream is = getClass().getResourceAsStream("/test_list_servers.json"); InputStream is = getClass().getResourceAsStream("/test_list_servers.json");
@ -64,6 +73,7 @@ public class ParseServerListFromJsonResponseTest {
assertEquals(response, expects); assertEquals(response, expects);
} }
@Test
public void testApplyInputStreamDetails() throws UnknownHostException { public void testApplyInputStreamDetails() throws UnknownHostException {
InputStream is = getClass().getResourceAsStream("/test_list_servers_detail.json"); 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).getId(), 1234);
assertEquals(response.get(0).getName(), "sample-server"); assertEquals(response.get(0).getName(), "sample-server");
assertEquals(response.get(0).getImageId(), new Integer(2)); assertEquals(response.get(0).getImageRef(), "https://servers.api.rackspacecloud.com/v1.1/32278/images/1234");
assertEquals(response.get(0).getFlavorId(), new Integer(1)); 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).getHostId(), "e4d909c290d0fb1ca068ffaddf22cbd0");
assertEquals(response.get(0).getStatus(), ServerStatus.BUILD); assertEquals(response.get(0).getStatus(), ServerStatus.BUILD);
assertEquals(response.get(0).getProgress(), new Integer(60)); 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"); List<Address> publicAddresses = ImmutableList.copyOf(Iterables.transform(
Addresses addresses1 = new Addresses(); ImmutableList.of("67.23.10.132", "::babe:67.23.10.132", "67.23.10.131", "::babe:4317:0A83"),
addresses1.getPrivateAddresses().addAll(privateAddresses); Address.newString2AddressFunction()));
addresses1.getPublicAddresses().addAll(publicAddresses); 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).getAddresses(), addresses1);
assertEquals(response.get(0).getMetadata(), ImmutableMap.of("Server Label", "Web Head 1", "Image Version", "2.1")); 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).getId(), 5678);
assertEquals(response.get(1).getName(), "sample-server2"); assertEquals(response.get(1).getName(), "sample-server2");
assertEquals(response.get(1).getImageId(), new Integer(2)); assertEquals(response.get(1).getImageRef(), "https://servers.api.rackspacecloud.com/v1.1/32278/images/1");
assertEquals(response.get(1).getFlavorId(), new Integer(1)); assertEquals(response.get(1).getFlavorRef(), "1");
assertEquals(response.get(1).getAffinityId(), "b414fa41cb37b97dcb58d6c76112af1258e9eae2");
assertEquals(response.get(1).getHostId(), "9e107d9d372bb6826bd81d3542a419d6"); assertEquals(response.get(1).getHostId(), "9e107d9d372bb6826bd81d3542a419d6");
assertEquals(response.get(1).getStatus(), ServerStatus.ACTIVE); assertEquals(response.get(1).getStatus(), ServerStatus.ACTIVE);
assertEquals(response.get(1).getProgress(), null); assertEquals(response.get(1).getProgress(), null);
List<String> publicAddresses2 = Lists.newArrayList("67.23.10.133");
List<String> privateAddresses2 = Lists.newArrayList("10.176.42.17"); List<Address> publicAddresses2 = ImmutableList.copyOf(Iterables.transform(
Addresses addresses2 = new Addresses(); ImmutableList.of("67.23.10.133", "::babe:67.23.10.133"),
addresses2.getPrivateAddresses().addAll(privateAddresses2); Address.newString2AddressFunction()));
addresses2.getPublicAddresses().addAll(publicAddresses2); 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).getAddresses(), addresses2);
assertEquals(response.get(1).getMetadata(), ImmutableMap.of("Server Label", "DB 1")); 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

@ -1,61 +0,0 @@
/**
*
* 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 static org.testng.Assert.assertEquals;
import java.io.InputStream;
import java.net.UnknownHostException;
import org.jclouds.openstack.nova.domain.SharedIpGroup;
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;
/**
* Tests behavior of {@code ParseSharedIpGroupFromJsonResponse}
*
* @author Adrian Cole
*/
@Test(groups = "unit")
public class ParseSharedIpGroupFromJsonResponseTest {
Injector i = Guice.createInjector(new GsonModule());
public void testApplyInputStreamDetails() throws UnknownHostException {
InputStream is = getClass().getResourceAsStream("/test_get_sharedipgroup_details.json");
UnwrapOnlyJsonValue<SharedIpGroup> parser = i.getInstance(Key
.get(new TypeLiteral<UnwrapOnlyJsonValue<SharedIpGroup>>() {
}));
SharedIpGroup response = parser.apply(new HttpResponse(200, "ok", Payloads.newInputStreamPayload(is)));
assertEquals(response.getId(), 1234);
assertEquals(response.getName(), "Shared IP Group 1");
assertEquals(response.getServers(), ImmutableList.of(422));
}
}

View File

@ -1,83 +0,0 @@
/**
*
* 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 static org.testng.Assert.assertEquals;
import java.io.InputStream;
import java.net.UnknownHostException;
import java.util.List;
import org.jclouds.openstack.nova.domain.SharedIpGroup;
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;
/**
* Tests behavior of {@code ParseSharedIpGroupListFromJsonResponse}
*
* @author Adrian Cole
*/
@Test(groups = "unit")
public class ParseSharedIpGroupListFromJsonResponseTest {
Injector i = Guice.createInjector(new GsonModule());
public void testApplyInputStream() {
InputStream is = getClass().getResourceAsStream("/test_list_sharedipgroups.json");
List<SharedIpGroup> expects = ImmutableList.of(new SharedIpGroup(1234, "Shared IP Group 1"), new SharedIpGroup(
5678, "Shared IP Group 2"));
UnwrapOnlyJsonValue<List<SharedIpGroup>> parser = i.getInstance(Key
.get(new TypeLiteral<UnwrapOnlyJsonValue<List<SharedIpGroup>>>() {
}));
List<SharedIpGroup> response = parser.apply(new HttpResponse(200, "ok", Payloads.newInputStreamPayload(is)));
assertEquals(response, expects);
}
public void testApplyInputStreamDetails() throws UnknownHostException {
InputStream is = getClass().getResourceAsStream("/test_list_sharedipgroups_detail.json");
UnwrapOnlyJsonValue<List<SharedIpGroup>> parser = i.getInstance(Key
.get(new TypeLiteral<UnwrapOnlyJsonValue<List<SharedIpGroup>>>() {
}));
List<SharedIpGroup> response = parser.apply(new HttpResponse(200, "ok", Payloads.newInputStreamPayload(is)));
assertEquals(response.get(0).getId(), 1234);
assertEquals(response.get(0).getName(), "Shared IP Group 1");
assertEquals(response.get(0).getServers(), ImmutableList.of(422, 3445));
assertEquals(response.get(1).getId(), 5678);
assertEquals(response.get(1).getName(), "Shared IP Group 2");
assertEquals(response.get(1).getServers(), ImmutableList.of(23203, 2456, 9891));
}
}

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,455 @@
/**
*
* 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.
* ====================================================================
*/
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,69 @@
/**
*
* 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.
* ====================================================================
*/
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,135 @@
/**
*
* 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.
* ====================================================================
*/
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,22 +18,18 @@
*/ */
package org.jclouds.openstack.nova.options; package org.jclouds.openstack.nova.options;
import static org.jclouds.openstack.nova.options.CreateServerOptions.Builder.withFile; import com.google.common.collect.ImmutableMap;
import static org.jclouds.openstack.nova.options.CreateServerOptions.Builder.withSharedIp; import com.google.inject.Guice;
import static org.jclouds.openstack.nova.options.CreateServerOptions.Builder.withSharedIpGroup; import com.google.inject.Injector;
import static org.testng.Assert.assertEquals;
import java.net.URI;
import javax.ws.rs.HttpMethod;
import org.jclouds.http.HttpRequest; import org.jclouds.http.HttpRequest;
import org.jclouds.json.config.GsonModule; import org.jclouds.json.config.GsonModule;
import org.testng.annotations.Test; import org.testng.annotations.Test;
import com.google.common.collect.ImmutableMap; import javax.ws.rs.HttpMethod;
import com.google.inject.Guice; import java.net.URI;
import com.google.inject.Injector;
import static org.jclouds.openstack.nova.options.CreateServerOptions.Builder.withFile;
import static org.testng.Assert.assertEquals;
/** /**
* Tests behavior of {@code ParseFlavorFromJsonResponse} * Tests behavior of {@code ParseFlavorFromJsonResponse}
@ -49,13 +45,13 @@ public class CreateServerOptionsTest {
public void testAddPayloadToRequestMapOfStringStringHttpRequest() { public void testAddPayloadToRequestMapOfStringStringHttpRequest() {
CreateServerOptions options = new CreateServerOptions(); CreateServerOptions options = new CreateServerOptions();
HttpRequest request = buildRequest(options); HttpRequest request = buildRequest(options);
assertEquals("{\"server\":{\"name\":\"foo\",\"imageId\":1,\"flavorId\":2}}", request.getPayload().getRawContent()); assertEquals("{\"server\":{\"name\":\"foo\",\"imageRef\":\"1\",\"flavorRef\":\"2\"}}", request.getPayload().getRawContent());
} }
private HttpRequest buildRequest(CreateServerOptions options) { private HttpRequest buildRequest(CreateServerOptions options) {
injector.injectMembers(options); injector.injectMembers(options);
HttpRequest request = new HttpRequest(HttpMethod.POST, URI.create("http://localhost")); HttpRequest request = new HttpRequest(HttpMethod.POST, URI.create("http://localhost"));
options.bindToRequest(request, ImmutableMap.of("name", "foo", "imageId", "1", "flavorId", "2")); options.bindToRequest(request, ImmutableMap.of("name", "foo", "imageRef", "1", "flavorRef", "2"));
return request; return request;
} }
@ -75,66 +71,11 @@ public class CreateServerOptionsTest {
} }
private void assertFile(HttpRequest request) { private void assertFile(HttpRequest request) {
assertEquals( assertEquals(request.getPayload().getRawContent(),
"{\"server\":{\"name\":\"foo\",\"imageId\":1,\"flavorId\":2,\"personality\":[{\"path\":\"/tmp/rhubarb\",\"contents\":\"Zm9v\"}]}}", "{\"server\":{\"name\":\"foo\",\"imageRef\":\"1\",\"flavorRef\":\"2\",\"personality\":[{\"path\":\"/tmp/rhubarb\",\"contents\":\"Zm9v\"}]}}");
request.getPayload().getRawContent());
}
@Test
public void testWithSharedIpGroup() {
CreateServerOptions options = new CreateServerOptions();
options.withSharedIpGroup(3);
HttpRequest request = buildRequest(options);
assertSharedIpGroup(request);
}
@Test
public void testWithSharedIpGroupStatic() {
CreateServerOptions options = withSharedIpGroup(3);
HttpRequest request = buildRequest(options);
assertSharedIpGroup(request);
}
private void assertSharedIpGroup(HttpRequest request) {
assertEquals("{\"server\":{\"name\":\"foo\",\"imageId\":1,\"flavorId\":2,\"sharedIpGroupId\":3}}", request
.getPayload().getRawContent());
} }
@Test @Test
public void testWithMetadata() { public void testWithMetadata() {
} }
@Test
public void testWithSharedIp() {
CreateServerOptions options = new CreateServerOptions();
options.withSharedIpGroup(3).withSharedIp("127.0.0.1");
HttpRequest request = buildRequest(options);
assertSharedIp(request);
}
@Test
public void testWithSharedIpStatic() {
CreateServerOptions options = withSharedIpGroup(3).withSharedIp("127.0.0.1");
HttpRequest request = buildRequest(options);
assertSharedIp(request);
}
private void assertSharedIp(HttpRequest request) {
assertEquals(
"{\"server\":{\"name\":\"foo\",\"imageId\":1,\"flavorId\":2,\"sharedIpGroupId\":3,\"addresses\":{\"public\":[\"127.0.0.1\"]}}}",
request.getPayload().getRawContent());
}
@Test(expectedExceptions = IllegalStateException.class)
public void testWithSharedIpNoGroup() {
CreateServerOptions options = new CreateServerOptions();
options.withSharedIp("127.0.0.1");
buildRequest(options);
}
@Test(expectedExceptions = IllegalStateException.class)
public void testWithSharedIpNoGroupStatic() {
CreateServerOptions options = withSharedIp("127.0.0.1");
buildRequest(options);
}
} }

View File

@ -1,79 +0,0 @@
/**
*
* 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.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 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;
/**
* Tests behavior of {@code ParseFlavorFromJsonResponse}
*
* @author Adrian Cole
*/
@Test(groups = "unit")
public class CreateSharedIpGroupOptionsTest {
Injector injector = Guice.createInjector(new GsonModule());
@Test
public void testAddPayloadToRequestMapOfStringStringHttpRequest() {
CreateSharedIpGroupOptions options = new CreateSharedIpGroupOptions();
HttpRequest request = buildRequest(options);
assertEquals("{\"sharedIpGroup\":{\"name\":\"foo\"}}", request.getPayload().getRawContent());
}
private HttpRequest buildRequest(CreateSharedIpGroupOptions options) {
injector.injectMembers(options);
HttpRequest request = new HttpRequest(HttpMethod.POST, URI.create("http://localhost"));
options.bindToRequest(request, ImmutableMap.of("name", "foo"));
return request;
}
@Test
public void testWithServer() {
CreateSharedIpGroupOptions options = new CreateSharedIpGroupOptions();
options.withServer(3);
HttpRequest request = buildRequest(options);
assertSharedIpGroup(request);
}
@Test
public void testWithServerStatic() {
CreateSharedIpGroupOptions options = withServer(3);
HttpRequest request = buildRequest(options);
assertSharedIpGroup(request);
}
private void assertSharedIpGroup(HttpRequest request) {
assertEquals("{\"sharedIpGroup\":{\"name\":\"foo\",\"server\":3}}", request.getPayload().getRawContent());
}
}

View File

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

View File

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

@ -1,185 +0,0 @@
<?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.
====================================================================
-->
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<!--
For more configuration infromation and examples see the Apache
Log4j website: http://logging.apache.org/log4j/
-->
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/"
debug="false">
<!-- A time/date based rolling appender -->
<appender name="WIREFILE" class="org.apache.log4j.DailyRollingFileAppender">
<param name="File" value="target/test-data/jclouds-wire.log" />
<param name="Append" value="true" />
<!-- Rollover at midnight each day -->
<param name="DatePattern" value="'.'yyyy-MM-dd" />
<param name="Threshold" value="TRACE" />
<layout class="org.apache.log4j.PatternLayout">
<!-- The default pattern: Date Priority [Category] Message\n -->
<param name="ConversionPattern" value="%d %-5p [%c] (%t) %m%n" />
<!--
The full pattern: Date MS Priority [Category]
(Thread:NDC) Message\n <param name="ConversionPattern"
value="%d %-5r %-5p [%c] (%t:%x) %m%n"/>
-->
</layout>
</appender>
<!-- A time/date based rolling appender -->
<appender name="FILE" class="org.apache.log4j.DailyRollingFileAppender">
<param name="File" value="target/test-data/jclouds.log" />
<param name="Append" value="true" />
<!-- Rollover at midnight each day -->
<param name="DatePattern" value="'.'yyyy-MM-dd" />
<param name="Threshold" value="TRACE" />
<layout class="org.apache.log4j.PatternLayout">
<!-- The default pattern: Date Priority [Category] Message\n -->
<param name="ConversionPattern" value="%d %-5p [%c] (%t) %m%n" />
<!--
The full pattern: Date MS Priority [Category]
(Thread:NDC) Message\n <param name="ConversionPattern"
value="%d %-5r %-5p [%c] (%t:%x) %m%n"/>
-->
</layout>
</appender>
<!-- A time/date based rolling appender -->
<appender name="BLOBSTOREFILE" class="org.apache.log4j.DailyRollingFileAppender">
<param name="File" value="target/test-data/jclouds-blobstore.log" />
<param name="Append" value="true" />
<param name="DatePattern" value="'.'yyyy-MM-dd" />
<param name="Threshold" value="TRACE" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d %-5p [%c] (%t) %m%n" />
</layout>
</appender>
<!-- A time/date based rolling appender -->
<appender name="COMPUTEFILE" class="org.apache.log4j.DailyRollingFileAppender">
<param name="File" value="target/test-data/jclouds-compute.log" />
<param name="Append" value="true" />
<!-- Rollover at midnight each day -->
<param name="DatePattern" value="'.'yyyy-MM-dd" />
<param name="Threshold" value="TRACE" />
<layout class="org.apache.log4j.PatternLayout">
<!-- The default pattern: Date Priority [Category] Message\n -->
<param name="ConversionPattern" value="%d %-5p [%c] (%t) %m%n" />
<!--
The full pattern: Date MS Priority [Category]
(Thread:NDC) Message\n <param name="ConversionPattern"
value="%d %-5r %-5p [%c] (%t:%x) %m%n"/>
-->
</layout>
</appender>
<!-- A time/date based rolling appender -->
<appender name="SSHFILE" class="org.apache.log4j.DailyRollingFileAppender">
<param name="File" value="target/test-data/jclouds-ssh.log" />
<param name="Append" value="true" />
<!-- Rollover at midnight each day -->
<param name="DatePattern" value="'.'yyyy-MM-dd" />
<param name="Threshold" value="TRACE" />
<layout class="org.apache.log4j.PatternLayout">
<!-- The default pattern: Date Priority [Category] Message\n -->
<param name="ConversionPattern" value="%d %-5p [%c] (%t) %m%n" />
<!--
The full pattern: Date MS Priority [Category]
(Thread:NDC) Message\n <param name="ConversionPattern"
value="%d %-5r %-5p [%c] (%t:%x) %m%n"/>
-->
</layout>
</appender>
<appender name="ASYNCCOMPUTE" class="org.apache.log4j.AsyncAppender">
<appender-ref ref="COMPUTEFILE" />
</appender>
<appender name="ASYNCSSH" class="org.apache.log4j.AsyncAppender">
<appender-ref ref="SSHFILE" />
</appender>
<appender name="ASYNC" class="org.apache.log4j.AsyncAppender">
<appender-ref ref="FILE" />
</appender>
<appender name="ASYNCWIRE" class="org.apache.log4j.AsyncAppender">
<appender-ref ref="WIREFILE" />
</appender>
<appender name="ASYNCBLOBSTORE" class="org.apache.log4j.AsyncAppender">
<appender-ref ref="BLOBSTOREFILE" />
</appender>
<!-- ================ -->
<!-- Limit categories -->
<!-- ================ -->
<category name="org.jclouds">
<priority value="DEBUG" />
<appender-ref ref="ASYNC" />
</category>
<category name="jclouds.headers">
<priority value="DEBUG" />
<appender-ref ref="ASYNCWIRE" />
</category>
<category name="jclouds.ssh">
<priority value="DEBUG" />
<appender-ref ref="ASYNCSSH" />
</category>
<category name="jclouds.wire">
<priority value="DEBUG" />
<appender-ref ref="ASYNCWIRE" />
</category>
<category name="jclouds.blobstore">
<priority value="DEBUG" />
<appender-ref ref="ASYNCBLOBSTORE" />
</category>
<category name="jclouds.compute">
<priority value="TRACE" />
<appender-ref ref="ASYNCCOMPUTE" />
</category>
<!-- ======================= -->
<!-- Setup the Root category -->
<!-- ======================= -->
<root>
<priority value="WARN" />
</root>
</log4j:configuration>

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

@ -3,6 +3,22 @@
"id" : 1, "id" : 1,
"name" : "256 MB Server", "name" : "256 MB Server",
"ram" : 256, "ram" : 256,
"disk" : 10 "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

@ -2,10 +2,30 @@
"image" : { "image" : {
"id" : 2, "id" : 2,
"name" : "CentOS 5.2", "name" : "CentOS 5.2",
"serverId" : 12, "serverRef" : "http://servers.api.openstack.org/v1.1/1234/servers/12",
"updated" : "2010-10-10T12:00:00Z", "updated" : "2010-10-10T12:00:00Z",
"created" : "2010-08-10T12:00:00Z", "created" : "2010-08-10T12:00:00Z",
"status" : "SAVING", "status" : "SAVING",
"progress" : 80 "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

@ -2,24 +2,45 @@
"server" : { "server" : {
"id" : 1234, "id" : 1234,
"name" : "sample-server", "name" : "sample-server",
"imageId" : 2, "imageRef" : "https://servers.api.rackspacecloud.com/v1.1/1234/images/1",
"flavorId" : 1, "flavorRef" : "http://servers.api.openstack.org/1234/flavors/1",
"updated" : "2010-10-10T12:00:00Z",
"created" : "2010-08-10T12:00:00Z",
"hostId" : "e4d909c290d0fb1ca068ffaddf22cbd0", "hostId" : "e4d909c290d0fb1ca068ffaddf22cbd0",
"affinityId" : "fc88bcf8394db9c8d0564e08ca6a9724188a84d1",
"status" : "BUILD", "status" : "BUILD",
"progress" : 60, "progress" : 60,
"addresses" : { "addresses" : {
"public": [ "public": [
"67.23.10.132", {"version" : 4, "addr" : "67.23.10.132"},
"67.23.10.131" {"version" : 6, "addr" : "::babe:67.23.10.132"},
{"version" : 4, "addr" : "67.23.10.131"},
{"version" : 6, "addr" : "::babe:4317:0A83"}
], ],
"private" : [ "private" : [
"10.176.42.16" {"version" : 4, "addr" : "10.176.42.16"},
{"version" : 6, "addr" : "::babe:10.176.42.16"}
] ]
}, },
"metadata" : { "metadata" : {
"Server Label" : "Web Head 1", "Server Label" : "Web Head 1",
"Image Version" : "2.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

@ -1,7 +0,0 @@
{
"sharedIpGroup" : {
"id" : 1234,
"name" : "Shared IP Group 1",
"servers" : [422]
}
}

View File

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

View File

@ -1,8 +1,8 @@
{ {
"private":[ "private":[
"10.176.42.16" {"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

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

View File

@ -1,7 +0,0 @@
{
"backupSchedule" : {
"enabled" : true,
"weekly" : "THURSDAY",
"daily" : "H_0400_0600"
}
}

View File

@ -2,11 +2,45 @@
"flavors" : [ "flavors" : [
{ {
"id" : 1, "id" : 1,
"name" : "256 MB Server" "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, "id" : 2,
"name" : "512 MB Server" "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

@ -4,13 +4,45 @@
"id" : 1, "id" : 1,
"name" : "256 MB Server", "name" : "256 MB Server",
"ram" : 256, "ram" : 256,
"disk" : 10 "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, "id" : 2,
"name" : "512 MB Server", "name" : "512 MB Server",
"ram" : 512, "ram" : 512,
"disk" : 20 "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

@ -1,12 +1,44 @@
{ {
"images" : [ "images" : [
{ {
"id" : 2, "id" : 1,
"name" : "CentOS 5.2" "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, "id" : 743,
"name" : "My Server Backup" "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

@ -1,20 +1,84 @@
{ {
"images" : [ "images" : [
{ {
"id" : 2, "id" : 1,
"name" : "CentOS 5.2", "name" : "CentOS 5.2",
"updated" : "2010-10-10T12:00:00Z", "updated" : "2010-10-10T12:00:00Z",
"created" : "2010-08-10T12:00:00Z", "created" : "2010-08-10T12:00:00Z",
"status" : "ACTIVE" "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, "id" : 743,
"name" : "My Server Backup", "name" : "My Server Backup",
"serverId" : 12, "serverRef" : "http://servers.api.openstack.org/v1.1/1234/servers/12",
"updated" : "2010-10-10T12:00:00Z", "updated" : "2010-10-10T12:00:00Z",
"created" : "2009-07-07T09:56:16-05:00", "created" : "2009-07-07T09:56:16Z",
"status" : "SAVING", "status" : "SAVING",
"progress" : 80 "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

@ -2,11 +2,44 @@
"servers" : [ "servers" : [
{ {
"id" : 1234, "id" : 1234,
"name" : "sample-server" "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, "id" : 5678,
"name" : "sample-server2" "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

@ -3,43 +3,87 @@
{ {
"id" : 1234, "id" : 1234,
"name" : "sample-server", "name" : "sample-server",
"imageId" : 2, "imageRef" : "https://servers.api.rackspacecloud.com/v1.1/32278/images/1234",
"flavorId" : 1, "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", "hostId" : "e4d909c290d0fb1ca068ffaddf22cbd0",
"affinityId" : "fc88bcf8394db9c8d0564e08ca6a9724188a84d1",
"status" : "BUILD", "status" : "BUILD",
"progress" : 60, "progress" : 60,
"addresses" : { "addresses" : {
"public" : [ "public" : [
"67.23.10.132", {"version" : 4, "addr" : "67.23.10.132"},
"67.23.10.131" {"version" : 6, "addr" : "::babe:67.23.10.132"},
{"version" : 4, "addr" : "67.23.10.131"},
{"version" : 6, "addr" : "::babe:4317:0A83"}
], ],
"private" : [ "private" : [
"10.176.42.16" {"version" : 4, "addr" : "10.176.42.16"},
{"version" : 6, "addr" : "::babe:10.176.42.16"}
] ]
}, },
"metadata" : { "metadata" : {
"Server Label" : "Web Head 1", "Server Label" : "Web Head 1",
"Image Version" : "2.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, "id" : 5678,
"name" : "sample-server2", "name" : "sample-server2",
"imageId" : 2, "imageRef" : "https://servers.api.rackspacecloud.com/v1.1/32278/images/1",
"flavorId" : 1, "flavorRef" : 1,
"updated" : "2010-10-10T12:00:00Z",
"created" : "2010-08-10T12:00:00Z",
"hostId" : "9e107d9d372bb6826bd81d3542a419d6", "hostId" : "9e107d9d372bb6826bd81d3542a419d6",
"affinityId" : "b414fa41cb37b97dcb58d6c76112af1258e9eae2",
"status" : "ACTIVE", "status" : "ACTIVE",
"addresses" : { "addresses" : {
"public" : [ "public" : [
"67.23.10.133" {"version" : 4, "addr" : "67.23.10.133"},
{"version" : 6, "addr" : "::babe:67.23.10.133"}
], ],
"private" : [ "private" : [
"10.176.42.17" {"version" : 4, "addr" : "10.176.42.17"},
{"version" : 6, "addr" : "::babe:10.176.42.17"}
] ]
}, },
"metadata" : { "metadata" : {
"Server Label" : "DB 1" "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

@ -1,12 +0,0 @@
{
"sharedIpGroups" : [
{
"id" : 1234,
"name" : "Shared IP Group 1"
},
{
"id" : 5678,
"name" : "Shared IP Group 2"
}
]
}

View File

@ -1,14 +0,0 @@
{
"sharedIpGroups" : [
{
"id" : 1234,
"name" : "Shared IP Group 1",
"servers" : [422, 3445]
},
{
"id" : 5678,
"name" : "Shared IP Group 2",
"servers" : [23203, 2456, 9891]
}
]
}

View File

@ -2,7 +2,7 @@
<!-- <!--
Copyright (C) 2009 Cloud Conscious, LLC. Copyright (C) 2010 Cloud Conscious, LLC.
<info@cloudconscious.com> <info@cloudconscious.com>
==================================================================== ====================================================================
@ -27,6 +27,29 @@
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/" <log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/"
debug="false"> debug="false">
<appender name="S" class="org.apache.log4j.ConsoleAppender">
<param name="Append" value="true"/>
<!-- Rollover at midnight each day -->
<param name="DatePattern" value="'.'yyyy-MM-dd"/>
<param name="Threshold" value="TRACE"/>
<layout class="org.apache.log4j.PatternLayout">
<!-- The default pattern: Date Priority [Category] Message\n -->
<param name="ConversionPattern" value="%d %-5p [%c] (%t) %m%n"/>
<!--
The full pattern: Date MS Priority [Category]
(Thread:NDC) Message\n <param name="ConversionPattern"
value="%d %-5r %-5p [%c] (%t:%x) %m%n"/>
-->
</layout>
</appender>
<!-- A time/date based rolling appender --> <!-- A time/date based rolling appender -->
<appender name="WIREFILE" class="org.apache.log4j.DailyRollingFileAppender"> <appender name="WIREFILE" class="org.apache.log4j.DailyRollingFileAppender">
<param name="File" value="target/test-data/jclouds-wire.log"/> <param name="File" value="target/test-data/jclouds-wire.log"/>
@ -70,6 +93,17 @@
--> -->
</layout> </layout>
</appender> </appender>
<!-- A time/date based rolling appender -->
<appender name="BLOBSTOREFILE" class="org.apache.log4j.DailyRollingFileAppender">
<param name="File" value="target/test-data/jclouds-blobstore.log"/>
<param name="Append" value="true"/>
<param name="DatePattern" value="'.'yyyy-MM-dd"/>
<param name="Threshold" value="TRACE"/>
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d %-5p [%c] (%t) %m%n"/>
</layout>
</appender>
<!-- A time/date based rolling appender --> <!-- A time/date based rolling appender -->
<appender name="COMPUTEFILE" class="org.apache.log4j.DailyRollingFileAppender"> <appender name="COMPUTEFILE" class="org.apache.log4j.DailyRollingFileAppender">
<param name="File" value="target/test-data/jclouds-compute.log"/> <param name="File" value="target/test-data/jclouds-compute.log"/>
@ -92,9 +126,36 @@
</layout> </layout>
</appender> </appender>
<!-- A time/date based rolling appender -->
<appender name="SSHFILE" class="org.apache.log4j.DailyRollingFileAppender">
<param name="File" value="target/test-data/jclouds-ssh.log"/>
<param name="Append" value="true"/>
<!-- Rollover at midnight each day -->
<param name="DatePattern" value="'.'yyyy-MM-dd"/>
<param name="Threshold" value="TRACE"/>
<layout class="org.apache.log4j.PatternLayout">
<!-- The default pattern: Date Priority [Category] Message\n -->
<param name="ConversionPattern" value="%d %-5p [%c] (%t) %m%n"/>
<!--
The full pattern: Date MS Priority [Category]
(Thread:NDC) Message\n <param name="ConversionPattern"
value="%d %-5r %-5p [%c] (%t:%x) %m%n"/>
-->
</layout>
</appender>
<appender name="ASYNCCOMPUTE" class="org.apache.log4j.AsyncAppender"> <appender name="ASYNCCOMPUTE" class="org.apache.log4j.AsyncAppender">
<appender-ref ref="COMPUTEFILE"/> <appender-ref ref="COMPUTEFILE"/>
</appender> </appender>
<appender name="ASYNCSSH" class="org.apache.log4j.AsyncAppender">
<appender-ref ref="SSHFILE"/>
</appender>
<appender name="ASYNC" class="org.apache.log4j.AsyncAppender"> <appender name="ASYNC" class="org.apache.log4j.AsyncAppender">
<appender-ref ref="FILE"/> <appender-ref ref="FILE"/>
</appender> </appender>
@ -103,6 +164,9 @@
<appender-ref ref="WIREFILE"/> <appender-ref ref="WIREFILE"/>
</appender> </appender>
<appender name="ASYNCBLOBSTORE" class="org.apache.log4j.AsyncAppender">
<appender-ref ref="BLOBSTOREFILE"/>
</appender>
<!-- ================ --> <!-- ================ -->
<!-- Limit categories --> <!-- Limit categories -->
<!-- ================ --> <!-- ================ -->
@ -116,11 +180,19 @@
<priority value="DEBUG"/> <priority value="DEBUG"/>
<appender-ref ref="ASYNCWIRE"/> <appender-ref ref="ASYNCWIRE"/>
</category> </category>
<category name="jclouds.ssh">
<priority value="DEBUG"/>
<appender-ref ref="ASYNCSSH"/>
</category>
<category name="jclouds.wire"> <category name="jclouds.wire">
<priority value="DEBUG"/> <priority value="DEBUG"/>
<appender-ref ref="ASYNCWIRE"/> <appender-ref ref="ASYNCWIRE"/>
</category> </category>
<category name="jclouds.blobstore">
<priority value="DEBUG"/>
<appender-ref ref="ASYNCBLOBSTORE"/>
</category>
<category name="jclouds.compute"> <category name="jclouds.compute">
<priority value="TRACE"/> <priority value="TRACE"/>
<appender-ref ref="ASYNCCOMPUTE"/> <appender-ref ref="ASYNCCOMPUTE"/>
@ -130,7 +202,8 @@
<!-- ======================= --> <!-- ======================= -->
<root> <root>
<priority value="WARN" /> <priority value="TRACE"/>
<appender-ref ref="S"/>
</root> </root>
</log4j:configuration> </log4j:configuration>