Removed sharedIP. Renamed id to ref in tests.

This commit is contained in:
vicglarson 2011-04-14 17:32:15 +04:00 committed by Dmitri Babaev
parent 8d2d3e8088
commit 39c642964a
13 changed files with 799 additions and 978 deletions

View File

@ -18,49 +18,22 @@
*/
package org.jclouds.openstack.nova;
import java.net.URI;
import java.net.URL;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import org.jclouds.openstack.nova.domain.Addresses;
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.options.CreateServerOptions;
import org.jclouds.openstack.nova.options.CreateSharedIpGroupOptions;
import org.jclouds.openstack.nova.options.ListOptions;
import org.jclouds.openstack.nova.options.RebuildServerOptions;
import org.jclouds.http.functions.ReturnFalseOn404;
import com.google.common.util.concurrent.ListenableFuture;
import org.jclouds.openstack.filters.AddTimestampQuery;
import org.jclouds.openstack.filters.AuthenticateRequest;
import org.jclouds.rest.annotations.BinderParam;
import org.jclouds.rest.annotations.Endpoint;
import org.jclouds.rest.annotations.ExceptionParser;
import org.jclouds.rest.annotations.MapBinder;
import org.jclouds.rest.annotations.Payload;
import org.jclouds.rest.annotations.PayloadParam;
import org.jclouds.rest.annotations.QueryParams;
import org.jclouds.rest.annotations.RequestFilters;
import org.jclouds.rest.annotations.SkipEncoding;
import org.jclouds.rest.annotations.Unwrap;
import org.jclouds.openstack.nova.domain.*;
import org.jclouds.openstack.nova.options.CreateServerOptions;
import org.jclouds.openstack.nova.options.ListOptions;
import org.jclouds.openstack.nova.options.RebuildServerOptions;
import org.jclouds.rest.annotations.*;
import org.jclouds.rest.functions.ReturnEmptySetOnNotFoundOr404;
import org.jclouds.rest.functions.ReturnFalseOnNotFoundOr404;
import org.jclouds.rest.functions.ReturnNullOnNotFoundOr404;
import org.jclouds.rest.functions.ReturnVoidOnNotFoundOr404;
import com.google.common.util.concurrent.ListenableFuture;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import java.util.Set;
import java.util.concurrent.ExecutionException;
/**
* Provides asynchronous access to OpenStack Nova via their REST API.
@ -69,220 +42,220 @@ import com.google.common.util.concurrent.ListenableFuture;
* during processing will be wrapped in an {@link ExecutionException} as documented in
* {@link ListenableFuture#get()}.
*
* @author Adrian Cole
* @see NovaClient
* @see <a href="http://wiki.openstack.org/OpenStackAPI_1-1" />
* @author Adrian Cole
*/
@SkipEncoding({ '/', '=' })
@RequestFilters({ AuthenticateRequest.class, AddTimestampQuery.class })
@SkipEncoding({'/', '='})
@RequestFilters({AuthenticateRequest.class, AddTimestampQuery.class})
@Endpoint(ServerManagement.class)
public interface NovaAsyncClient {
/**
* @see NovaClient#listServers
*/
@GET
@Unwrap
@Consumes(MediaType.APPLICATION_JSON)
@QueryParams(keys = "format", values = "json")
@Path("/servers")
@ExceptionParser(ReturnEmptySetOnNotFoundOr404.class)
ListenableFuture<? extends Set<Server>> listServers(ListOptions... options);
/**
* @see NovaClient#listServers
*/
@GET
@Unwrap
@Consumes(MediaType.APPLICATION_JSON)
@QueryParams(keys = "format", values = "json")
@Path("/servers")
@ExceptionParser(ReturnEmptySetOnNotFoundOr404.class)
ListenableFuture<? extends Set<Server>> listServers(ListOptions... options);
/**
* @see NovaClient#getServer
*/
@GET
@Unwrap
@Consumes(MediaType.APPLICATION_JSON)
@QueryParams(keys = "format", values = "json")
@ExceptionParser(ReturnNullOnNotFoundOr404.class)
@Path("/servers/{id}")
ListenableFuture<Server> getServer(@PathParam("id") int id);
/**
* @see NovaClient#getServer
*/
@GET
@Unwrap
@Consumes(MediaType.APPLICATION_JSON)
@QueryParams(keys = "format", values = "json")
@ExceptionParser(ReturnNullOnNotFoundOr404.class)
@Path("/servers/{id}")
ListenableFuture<Server> getServer(@PathParam("id") int id);
/**
* @see NovaClient#deleteServer
*/
@DELETE
@ExceptionParser(ReturnFalseOnNotFoundOr404.class)
@Path("/servers/{id}")
ListenableFuture<Boolean> deleteServer(@PathParam("id") int id);
/**
* @see NovaClient#deleteServer
*/
@DELETE
@ExceptionParser(ReturnFalseOnNotFoundOr404.class)
@Path("/servers/{id}")
ListenableFuture<Boolean> deleteServer(@PathParam("id") int id);
/**
* @see NovaClient#rebootServer
*/
@POST
@QueryParams(keys = "format", values = "json")
@Path("/servers/{id}/action")
@Produces(MediaType.APPLICATION_JSON)
@Payload("%7B\"reboot\":%7B\"type\":\"{type}\"%7D%7D")
ListenableFuture<Void> rebootServer(@PathParam("id") int id, @PayloadParam("type") RebootType rebootType);
/**
* @see NovaClient#rebootServer
*/
@POST
@QueryParams(keys = "format", values = "json")
@Path("/servers/{id}/action")
@Produces(MediaType.APPLICATION_JSON)
@Payload("%7B\"reboot\":%7B\"type\":\"{type}\"%7D%7D")
ListenableFuture<Void> rebootServer(@PathParam("id") int id, @PayloadParam("type") RebootType rebootType);
/**
* @see NovaClient#resizeServer
*/
@POST
@QueryParams(keys = "format", values = "json")
@Path("/servers/{id}/action")
@Produces(MediaType.APPLICATION_JSON)
@Payload("%7B\"resize\":%7B\"flavorId\":{flavorId}%7D%7D")
ListenableFuture<Void> resizeServer(@PathParam("id") int id, @PayloadParam("flavorId") int flavorId);
/**
* @see NovaClient#resizeServer
*/
@POST
@QueryParams(keys = "format", values = "json")
@Path("/servers/{id}/action")
@Produces(MediaType.APPLICATION_JSON)
@Payload("%7B\"resize\":%7B\"flavorId\":{flavorId}%7D%7D")
ListenableFuture<Void> resizeServer(@PathParam("id") int id, @PayloadParam("flavorId") int flavorId);
/**
* @see NovaClient#confirmResizeServer
*/
@POST
@QueryParams(keys = "format", values = "json")
@Path("/servers/{id}/action")
@Produces(MediaType.APPLICATION_JSON)
@Payload("{\"confirmResize\":null}")
ListenableFuture<Void> confirmResizeServer(@PathParam("id") int id);
/**
* @see NovaClient#confirmResizeServer
*/
@POST
@QueryParams(keys = "format", values = "json")
@Path("/servers/{id}/action")
@Produces(MediaType.APPLICATION_JSON)
@Payload("{\"confirmResize\":null}")
ListenableFuture<Void> confirmResizeServer(@PathParam("id") int id);
/**
* @see NovaClient#revertResizeServer
*/
@POST
@QueryParams(keys = "format", values = "json")
@Path("/servers/{id}/action")
@Produces(MediaType.APPLICATION_JSON)
@Payload("{\"revertResize\":null}")
ListenableFuture<Void> revertResizeServer(@PathParam("id") int id);
/**
* @see NovaClient#revertResizeServer
*/
@POST
@QueryParams(keys = "format", values = "json")
@Path("/servers/{id}/action")
@Produces(MediaType.APPLICATION_JSON)
@Payload("{\"revertResize\":null}")
ListenableFuture<Void> revertResizeServer(@PathParam("id") int id);
/**
* @see NovaClient#createServer
*/
@POST
@Unwrap
@Consumes(MediaType.APPLICATION_JSON)
@QueryParams(keys = "format", values = "json")
@Path("/servers")
@MapBinder(CreateServerOptions.class)
ListenableFuture<Server> createServer(@PayloadParam("name") String name, @PayloadParam("imageRef") String imageRef,
@PayloadParam("flavorRef") String flavorRef, CreateServerOptions... options);
/**
* @see NovaClient#createServer
*/
@POST
@Unwrap
@Consumes(MediaType.APPLICATION_JSON)
@QueryParams(keys = "format", values = "json")
@Path("/servers")
@MapBinder(CreateServerOptions.class)
ListenableFuture<Server> createServer(@PayloadParam("name") String name, @PayloadParam("imageRef") String imageRef,
@PayloadParam("flavorRef") String flavorRef, CreateServerOptions... options);
/**
* @see NovaClient#rebuildServer
*/
@POST
@QueryParams(keys = "format", values = "json")
@Path("/servers/{id}/action")
@MapBinder(RebuildServerOptions.class)
ListenableFuture<Void> rebuildServer(@PathParam("id") int id, RebuildServerOptions... options);
/**
* @see NovaClient#rebuildServer
*/
@POST
@QueryParams(keys = "format", values = "json")
@Path("/servers/{id}/action")
@MapBinder(RebuildServerOptions.class)
ListenableFuture<Void> rebuildServer(@PathParam("id") int id, RebuildServerOptions... options);
/**
* @see NovaClient#changeAdminPass
*/
@PUT
@Path("/servers/{id}")
@Produces(MediaType.APPLICATION_JSON)
@Payload("%7B\"server\":%7B\"adminPass\":\"{adminPass}\"%7D%7D")
ListenableFuture<Void> changeAdminPass(@PathParam("id") int id, @PayloadParam("adminPass") String adminPass);
/**
* @see NovaClient#changeAdminPass
*/
@PUT
@Path("/servers/{id}")
@Produces(MediaType.APPLICATION_JSON)
@Payload("%7B\"server\":%7B\"adminPass\":\"{adminPass}\"%7D%7D")
ListenableFuture<Void> changeAdminPass(@PathParam("id") int id, @PayloadParam("adminPass") String adminPass);
/**
* @see NovaClient#renameServer
*/
@PUT
@Path("/servers/{id}")
@Produces(MediaType.APPLICATION_JSON)
@Payload("%7B\"server\":%7B\"name\":\"{name}\"%7D%7D")
ListenableFuture<Void> renameServer(@PathParam("id") int id, @PayloadParam("name") String newName);
/**
* @see NovaClient#renameServer
*/
@PUT
@Path("/servers/{id}")
@Produces(MediaType.APPLICATION_JSON)
@Payload("%7B\"server\":%7B\"name\":\"{name}\"%7D%7D")
ListenableFuture<Void> renameServer(@PathParam("id") int id, @PayloadParam("name") String newName);
/**
* @see NovaClient#listFlavors
*/
@GET
@Unwrap
@Consumes(MediaType.APPLICATION_JSON)
@QueryParams(keys = "format", values = "json")
@Path("/flavors")
@ExceptionParser(ReturnEmptySetOnNotFoundOr404.class)
ListenableFuture<? extends Set<Flavor>> listFlavors(ListOptions... options);
/**
* @see NovaClient#listFlavors
*/
@GET
@Unwrap
@Consumes(MediaType.APPLICATION_JSON)
@QueryParams(keys = "format", values = "json")
@Path("/flavors")
@ExceptionParser(ReturnEmptySetOnNotFoundOr404.class)
ListenableFuture<? extends Set<Flavor>> listFlavors(ListOptions... options);
/**
* @see NovaClient#getFlavor
*/
@GET
@Unwrap
@Consumes(MediaType.APPLICATION_JSON)
@QueryParams(keys = "format", values = "json")
@Path("/flavors/{id}")
@ExceptionParser(ReturnNullOnNotFoundOr404.class)
ListenableFuture<Flavor> getFlavor(@PathParam("id") int id);
/**
* @see NovaClient#getFlavor
*/
@GET
@Unwrap
@Consumes(MediaType.APPLICATION_JSON)
@QueryParams(keys = "format", values = "json")
@Path("/flavors/{id}")
@ExceptionParser(ReturnNullOnNotFoundOr404.class)
ListenableFuture<Flavor> getFlavor(@PathParam("id") int id);
/**
* @see NovaClient#listImages
*/
@GET
@Unwrap
@Consumes(MediaType.APPLICATION_JSON)
@QueryParams(keys = "format", values = "json")
@Path("/images")
@ExceptionParser(ReturnEmptySetOnNotFoundOr404.class)
ListenableFuture<? extends Set<Image>> listImages(ListOptions... options);
/**
* @see NovaClient#listImages
*/
@GET
@Unwrap
@Consumes(MediaType.APPLICATION_JSON)
@QueryParams(keys = "format", values = "json")
@Path("/images")
@ExceptionParser(ReturnEmptySetOnNotFoundOr404.class)
ListenableFuture<? extends Set<Image>> listImages(ListOptions... options);
/**
* @see NovaClient#getImage
*/
@GET
@Unwrap
@Consumes(MediaType.APPLICATION_JSON)
@ExceptionParser(ReturnNullOnNotFoundOr404.class)
@QueryParams(keys = "format", values = "json")
@Path("/images/{id}")
ListenableFuture<Image> getImage(@PathParam("id") int id);
/**
* @see NovaClient#getImage
*/
@GET
@Unwrap
@Consumes(MediaType.APPLICATION_JSON)
@ExceptionParser(ReturnNullOnNotFoundOr404.class)
@QueryParams(keys = "format", values = "json")
@Path("/images/{id}")
ListenableFuture<Image> getImage(@PathParam("id") int id);
/**
* @see NovaClient#deleteImage
*/
@DELETE
@ExceptionParser(ReturnFalseOnNotFoundOr404.class)
@Path("/images/{id}")
ListenableFuture<Boolean> deleteImage(@PathParam("id") int id);
/**
* @see NovaClient#deleteImage
*/
@DELETE
@ExceptionParser(ReturnFalseOnNotFoundOr404.class)
@Path("/images/{id}")
ListenableFuture<Boolean> deleteImage(@PathParam("id") int id);
/**
* @see NovaClient#createImageFromServer
*/
@POST
@Unwrap
@Consumes(MediaType.APPLICATION_JSON)
@QueryParams(keys = "format", values = "json")
@Path("/images")
@Produces(MediaType.APPLICATION_JSON)
@Payload("%7B\"image\":%7B\"serverId\":{serverId},\"name\":\"{name}\"%7D%7D")
ListenableFuture<Image> createImageFromServer(@PayloadParam("name") String imageName,
@PayloadParam("serverId") int serverId);
/**
* @see NovaClient#createImageFromServer
*/
@POST
@Unwrap
@Consumes(MediaType.APPLICATION_JSON)
@QueryParams(keys = "format", values = "json")
@Path("/images")
@Produces(MediaType.APPLICATION_JSON)
@Payload("%7B\"image\":%7B\"serverId\":{serverId},\"name\":\"{name}\"%7D%7D")
ListenableFuture<Image> createImageFromServer(@PayloadParam("name") String imageName,
@PayloadParam("serverId") int serverId);
/**
* @see NovaClient#listAddresses
*/
@GET
@Unwrap
@Consumes(MediaType.APPLICATION_JSON)
@QueryParams(keys = "format", values = "json")
@Path("/servers/{id}/ips")
ListenableFuture<Addresses> getAddresses(@PathParam("id") int serverId);
/**
* @see NovaClient#getAddresses(int)
*/
@GET
@Unwrap
@Consumes(MediaType.APPLICATION_JSON)
@QueryParams(keys = "format", values = "json")
@Path("/servers/{id}/ips")
ListenableFuture<Addresses> getAddresses(@PathParam("id") int serverId);
/**
* @see NovaClient#listPublicAddresses
*/
@GET
@Unwrap
@Consumes(MediaType.APPLICATION_JSON)
@QueryParams(keys = "format", values = "json")
@Path("/servers/{id}/ips/public")
@ExceptionParser(ReturnEmptySetOnNotFoundOr404.class)
ListenableFuture<? extends Set<String>> listPublicAddresses(@PathParam("id") int serverId);
/**
* @see NovaClient#listPublicAddresses(int)
*/
@GET
@Unwrap
@Consumes(MediaType.APPLICATION_JSON)
@QueryParams(keys = "format", values = "json")
@Path("/servers/{id}/ips/public")
@ExceptionParser(ReturnEmptySetOnNotFoundOr404.class)
ListenableFuture<? extends Set<String>> listPublicAddresses(@PathParam("id") int serverId);
/**
* @see NovaClient#listPrivateAddresses
*/
@GET
@Unwrap
@Consumes(MediaType.APPLICATION_JSON)
@QueryParams(keys = "format", values = "json")
@Path("/servers/{id}/ips/private")
@ExceptionParser(ReturnEmptySetOnNotFoundOr404.class)
ListenableFuture<? extends Set<String>> listPrivateAddresses(@PathParam("id") int serverId);
/**
* @see NovaClient#listPrivateAddresses
*/
@GET
@Unwrap
@Consumes(MediaType.APPLICATION_JSON)
@QueryParams(keys = "format", values = "json")
@Path("/servers/{id}/ips/private")
@ExceptionParser(ReturnEmptySetOnNotFoundOr404.class)
ListenableFuture<? extends Set<String>> listPrivateAddresses(@PathParam("id") int serverId);
}

View File

@ -18,27 +18,18 @@
*/
package org.jclouds.openstack.nova;
import java.net.URI;
import java.net.URL;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import javax.ws.rs.PathParam;
import org.jclouds.concurrent.Timeout;
import org.jclouds.openstack.nova.domain.Addresses;
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.*;
import org.jclouds.openstack.nova.options.CreateServerOptions;
import org.jclouds.openstack.nova.options.CreateSharedIpGroupOptions;
import org.jclouds.openstack.nova.options.ListOptions;
import org.jclouds.openstack.nova.options.RebuildServerOptions;
import org.jclouds.rest.ResourceNotFoundException;
import javax.ws.rs.PathParam;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
/**
* Provides access to OpenStack Nova via their REST API.
@ -47,239 +38,223 @@ import java.util.concurrent.Future;
* during processing will be wrapped in an {@link ExecutionException} as documented in
* {@link Future#get()}.
*
* @author Adrian Cole
* @see NovaAsyncClient
* @see <a href="http://wiki.openstack.org/OpenStackAPI_1-1" />
* @author Adrian Cole
*/
@Timeout(duration = 60, timeUnit = TimeUnit.SECONDS)
public interface NovaClient {
/**
*
* List all servers (IDs and names only)
*
* This operation provides a list of servers associated with your identity. Servers that have been
* deleted are not included in this list.
* <p/>
* in order to retrieve all details, pass the option {@link ListOptions#withDetails()
* withDetails()}
*/
Set<Server> listServers(ListOptions... options);
/**
* List all servers (IDs and names only)
* <p/>
* This operation provides a list of servers associated with your identity. Servers that have been
* deleted are not included in this list.
* <p/>
* in order to retrieve all details, pass the option {@link ListOptions#withDetails()
* withDetails()}
*/
Set<Server> listServers(ListOptions... options);
/**
*
* This operation returns details of the specified server.
*
* @return null, if the server is not found
* @see Server
*/
Server getServer(@PathParam("id") int id);
/**
* This operation returns details of the specified server.
*
* @return null, if the server is not found
* @see Server
*/
Server getServer(@PathParam("id") int id);
/**
*
* This operation deletes a cloud server instance from the system.
* <p/>
* Note: When a server is deleted, all images created from that server are also removed.
*
* @return false if the server is not found
* @see Server
*/
boolean deleteServer(@PathParam("id") int id);
/**
* This operation deletes a cloud server instance from the system.
* <p/>
* Note: When a server is deleted, all images created from that server are also removed.
*
* @return false if the server is not found
* @see Server
*/
boolean deleteServer(@PathParam("id") int id);
/**
* The reboot function allows for either a soft or hard reboot of a server.
* <p/>
* Status Transition:
* <p/>
* ACTIVE - REBOOT - ACTIVE (soft reboot)
* <p/>
* ACTIVE - HARD_REBOOT - ACTIVE (hard reboot)
*
* @param rebootType
* With a soft reboot, the operating system is signaled to restart, which allows for a
* graceful shutdown of all processes. A hard reboot is the equivalent of power cycling
* the server.
*/
void rebootServer(int id, RebootType rebootType);
/**
* The reboot function allows for either a soft or hard reboot of a server.
* <p/>
* Status Transition:
* <p/>
* ACTIVE - REBOOT - ACTIVE (soft reboot)
* <p/>
* ACTIVE - HARD_REBOOT - ACTIVE (hard reboot)
*
* @param rebootType With a soft reboot, the operating system is signaled to restart, which allows for a
* graceful shutdown of all processes. A hard reboot is the equivalent of power cycling
* the server.
*/
void rebootServer(int id, RebootType rebootType);
/**
* The resize function converts an existing server to a different flavor, in essence, scaling the
* server up or down. The original server is saved for a period of time to allow rollback if
* there is a problem. All resizes should be tested and explicitly confirmed, at which time the
* original server is removed. All resizes are automatically confirmed after 24 hours if they are
* not confirmed or reverted.
* <p/>
* Status Transition:
* <p/>
* ACTIVE - QUEUE_RESIZE - PREP_RESIZE - VERIFY_RESIZE
* <p/>
* ACTIVE - QUEUE_RESIZE - ACTIVE (on error)
*/
void resizeServer(int id, int flavorId);
/**
* The resize function converts an existing server to a different flavor, in essence, scaling the
* server up or down. The original server is saved for a period of time to allow rollback if
* there is a problem. All resizes should be tested and explicitly confirmed, at which time the
* original server is removed. All resizes are automatically confirmed after 24 hours if they are
* not confirmed or reverted.
* <p/>
* Status Transition:
* <p/>
* ACTIVE - QUEUE_RESIZE - PREP_RESIZE - VERIFY_RESIZE
* <p/>
* ACTIVE - QUEUE_RESIZE - ACTIVE (on error)
*/
void resizeServer(int id, int flavorId);
/**
* The resize function converts an existing server to a different flavor, in essence, scaling the
* server up or down. The original server is saved for a period of time to allow rollback if
* there is a problem. All resizes should be tested and explicitly confirmed, at which time the
* original server is removed. All resizes are automatically confirmed after 24 hours if they are
* not confirmed or reverted.
* <p/>
* Status Transition:
* <p/>
* VERIFY_RESIZE - ACTIVE
*/
void confirmResizeServer(int id);
/**
* The resize function converts an existing server to a different flavor, in essence, scaling the
* server up or down. The original server is saved for a period of time to allow rollback if
* there is a problem. All resizes should be tested and explicitly confirmed, at which time the
* original server is removed. All resizes are automatically confirmed after 24 hours if they are
* not confirmed or reverted.
* <p/>
* Status Transition:
* <p/>
* VERIFY_RESIZE - ACTIVE
*/
void confirmResizeServer(int id);
/**
* The resize function converts an existing server to a different flavor, in essence, scaling the
* server up or down. The original server is saved for a period of time to allow rollback if
* there is a problem. All resizes should be tested and explicitly reverted, at which time the
* original server is removed. All resizes are automatically reverted after 24 hours if they are
* not reverted or reverted.
* <p/>
* Status Transition:
* <p/>
* VERIFY_RESIZE - ACTIVE
*/
void revertResizeServer(int id);
/**
* The resize function converts an existing server to a different flavor, in essence, scaling the
* server up or down. The original server is saved for a period of time to allow rollback if
* there is a problem. All resizes should be tested and explicitly reverted, at which time the
* original server is removed. All resizes are automatically reverted after 24 hours if they are
* not reverted or reverted.
* <p/>
* Status Transition:
* <p/>
* VERIFY_RESIZE - ACTIVE
*/
void revertResizeServer(int id);
/**
* This operation asynchronously provisions a new server. The progress of this operation depends
* on several factors including location of the requested image, network i/o, host load, and the
* selected flavor. The progress of the request can be checked by performing a GET on /server/id,
* which will return a progress attribute (0-100% completion). A password will be randomly
* generated for you and returned in the response object. For security reasons, it will not be
* returned in subsequent GET calls against a given server ID.
*
* @param options
* - used to specify extra files, metadata, or ip parameters during server creation.
*/
Server createServer(String name, String imageRef, String flavorRef, CreateServerOptions... options);
/**
* This operation asynchronously provisions a new server. The progress of this operation depends
* on several factors including location of the requested image, network i/o, host load, and the
* selected flavor. The progress of the request can be checked by performing a GET on /server/id,
* which will return a progress attribute (0-100% completion). A password will be randomly
* generated for you and returned in the response object. For security reasons, it will not be
* returned in subsequent GET calls against a given server ID.
*
* @param options - used to specify extra files, metadata, or ip parameters during server creation.
*/
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.
* Server ID and IP addresses remain the same.
* <p/>
* Status Transition:
* <p/>
* ACTIVE - REBUILD - ACTIVE
* <p/>
* ACTIVE - REBUILD - ERROR (on error)
* <p/>
*
* @param options
* - imageId is an optional argument. If it is not specified, the server is rebuilt
* with the original imageId.
*/
void rebuildServer(int id, RebuildServerOptions... options);
/**
* The rebuild function removes all data on the server and replaces it with the specified image.
* Server ID and IP addresses remain the same.
* <p/>
* Status Transition:
* <p/>
* ACTIVE - REBUILD - ACTIVE
* <p/>
* ACTIVE - REBUILD - ERROR (on error)
* <p/>
*
* @param options - imageId is an optional argument. If it is not specified, the server is rebuilt
* with the original imageId.
*/
void rebuildServer(int id, RebuildServerOptions... options);
/**
* This operation allows you to change the administrative password.
* <p/>
* Status Transition: ACTIVE - PASSWORD - ACTIVE
*
*/
void changeAdminPass(int id, String adminPass);
/**
* This operation allows you to change the administrative password.
* <p/>
* Status Transition: ACTIVE - PASSWORD - ACTIVE
*/
void changeAdminPass(int id, String adminPass);
/**
* This operation allows you to update the name of the server. This operation changes the name of
* the server in the OpenStack Nova system and does not change the server host name itself.
* <p/>
* Status Transition: ACTIVE - PASSWORD - ACTIVE
*
*/
void renameServer(int id, String newName);
/**
* This operation allows you to update the name of the server. This operation changes the name of
* the server in the OpenStack Nova system and does not change the server host name itself.
* <p/>
* Status Transition: ACTIVE - PASSWORD - ACTIVE
*/
void renameServer(int id, String newName);
/**
*
* List available flavors (IDs and names only)
*
* in order to retrieve all details, pass the option {@link ListOptions#withDetails()
* withDetails()}
*/
Set<Flavor> listFlavors(ListOptions... options);
/**
* List available flavors (IDs and names only)
* <p/>
* in order to retrieve all details, pass the option {@link ListOptions#withDetails()
* withDetails()}
*/
Set<Flavor> listFlavors(ListOptions... options);
/**
*
* This operation returns details of the specified flavor.
*
* @return null, if the flavor is not found
* @see Flavor
*/
Flavor getFlavor(int id);
/**
* This operation returns details of the specified flavor.
*
* @return null, if the flavor is not found
* @see Flavor
*/
Flavor getFlavor(int id);
/**
*
* List available images (IDs and names only)
*
* in order to retrieve all details, pass the option {@link ListOptions#withDetails()
* withDetails()}
*/
Set<Image> listImages(ListOptions... options);
/**
* List available images (IDs and names only)
* <p/>
* in order to retrieve all details, pass the option {@link ListOptions#withDetails()
* withDetails()}
*/
Set<Image> listImages(ListOptions... options);
/**
*
* This operation returns details of the specified image.
*
* @return null, if the image is not found
*
* @see Image
*/
Image getImage(int id);
/**
* This operation returns details of the specified image.
*
* @return null, if the image is not found
* @see Image
*/
Image getImage(int id);
/**
*
* This operation deletes an image from the system.
* <p/>
* Note: Images are immediately removed. Currently, there are no state transitions to track the
* delete operation.
*
* @return false if the image is not found
* @see Image
*/
boolean deleteImage(int id);
/**
* This operation deletes an image from the system.
* <p/>
* Note: Images are immediately removed. Currently, there are no state transitions to track the
* delete operation.
*
* @return false if the image is not found
* @see Image
*/
boolean deleteImage(int id);
/**
*
* This operation creates a new image for the given server ID. Once complete, a new image will be
* available that can be used to rebuild or create servers. Specifying the same image name as an
* existing custom image replaces the image. The image creation status can be queried by
* performing a GET on /images/id and examining the status and progress attributes.
*
* Status Transition:
* <p/>
* QUEUED - PREPARING - SAVING - ACTIVE
* <p/>
* QUEUED - PREPARING - SAVING - FAILED (on error)
* <p/>
* Note: At present, image creation is an asynchronous operation, so coordinating the creation
* with data quiescence, etc. is currently not possible.
*
* @throws ResourceNotFoundException
* if the server is not found
* @see Image
*/
Image createImageFromServer(String imageName, int serverId);
/**
* This operation creates a new image for the given server ID. Once complete, a new image will be
* available that can be used to rebuild or create servers. Specifying the same image name as an
* existing custom image replaces the image. The image creation status can be queried by
* performing a GET on /images/id and examining the status and progress attributes.
* <p/>
* Status Transition:
* <p/>
* QUEUED - PREPARING - SAVING - ACTIVE
* <p/>
* QUEUED - PREPARING - SAVING - FAILED (on error)
* <p/>
* Note: At present, image creation is an asynchronous operation, so coordinating the creation
* with data quiescence, etc. is currently not possible.
*
* @throws ResourceNotFoundException if the server is not found
* @see Image
*/
Image createImageFromServer(String imageName, int serverId);
/**
* List all server addresses
*
* returns empty set if the server doesn't exist
*/
Addresses getAddresses(int serverId);
/**
* List all server addresses
* <p/>
* returns empty set if the server doesn't exist
*/
Addresses getAddresses(int serverId);
/**
* List all public server addresses
*
* returns empty set if the server doesn't exist
*/
Set<String> listPublicAddresses(int serverId);
/**
* List all public server addresses
* <p/>
* returns empty set if the server doesn't exist
*/
Set<String> listPublicAddresses(int serverId);
/**
* List all private server addresses
*
* returns empty set if the server doesn't exist
*/
Set<String> listPrivateAddresses(int serverId);
/**
* List all private server addresses
* <p/>
* returns empty set if the server doesn't exist
*/
Set<String> listPrivateAddresses(int serverId);
}

View File

@ -18,224 +18,154 @@
*/
package org.jclouds.openstack.nova.options;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import java.net.URI;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.jclouds.encryption.internal.Base64;
import org.jclouds.http.HttpRequest;
import org.jclouds.openstack.nova.domain.Addresses;
import org.jclouds.rest.binders.BindToJsonPayload;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import static com.google.common.base.Preconditions.*;
/**
*
* @author Adrian Cole
*
*/
public class CreateServerOptions extends BindToJsonPayload {
static class File {
private final String path;
private final String contents;
static class File {
private final String path;
private final String contents;
public File(String path, byte[] contents) {
this.path = checkNotNull(path, "path");
this.contents = Base64.encodeBytes(checkNotNull(contents, "contents"));
checkArgument(path.getBytes().length < 255, String.format(
"maximum length of path is 255 bytes. Path specified %s is %d bytes", path, path
.getBytes().length));
checkArgument(contents.length < 10 * 1024, String.format(
"maximum size of the file is 10KB. Contents specified is %d bytes",
contents.length));
}
public File(String path, byte[] contents) {
this.path = checkNotNull(path, "path");
this.contents = Base64.encodeBytes(checkNotNull(contents, "contents"));
checkArgument(path.getBytes().length < 255, String.format(
"maximum length of path is 255 bytes. Path specified %s is %d bytes", path, path
.getBytes().length));
checkArgument(contents.length < 10 * 1024, String.format(
"maximum size of the file is 10KB. Contents specified is %d bytes",
contents.length));
}
public String getContents() {
return contents;
}
public String getContents() {
return contents;
}
public String getPath() {
return path;
}
public String getPath() {
return path;
}
}
}
@SuppressWarnings("unused")
private class ServerRequest {
final String name;
final String imageRef;
final String flavorRef;
Map<String, String> metadata;
List<File> personality;
Integer sharedIpGroupId;
Addresses addresses;
@SuppressWarnings("unused")
private class ServerRequest {
final String name;
final String imageRef;
final String flavorRef;
Map<String, String> metadata;
List<File> personality;
Addresses addresses;
private ServerRequest(String name, String imageRef, String flavorRef) {
this.name = name;
this.imageRef = imageRef;
this.flavorRef = flavorRef;
}
private ServerRequest(String name, String imageRef, String flavorRef) {
this.name = name;
this.imageRef = imageRef;
this.flavorRef = flavorRef;
}
}
}
private Map<String, String> metadata = Maps.newHashMap();
private List<File> files = Lists.newArrayList();
private Integer sharedIpGroupId;
private String publicIp;
private Map<String, String> metadata = Maps.newHashMap();
private List<File> files = Lists.newArrayList();
private String publicIp;
@Override
public <R extends HttpRequest> R bindToRequest(R request, Map<String, String> postParams) {
ServerRequest server = new ServerRequest(checkNotNull(postParams.get("name"),
"name parameter not present"), checkNotNull(postParams
.get("imageRef"), "imageRef parameter not present"), checkNotNull(
postParams.get("flavorRef"), "flavorRef parameter not present"));
if (metadata.size() > 0)
server.metadata = metadata;
if (files.size() > 0)
server.personality = files;
if (sharedIpGroupId != null)
server.sharedIpGroupId = this.sharedIpGroupId;
if (publicIp != null) {
server.addresses = new Addresses();
server.addresses.getPublicAddresses().add(publicIp);
server.addresses.setPrivateAddresses(null);
}
return bindToRequest(request, ImmutableMap.of("server", server));
}
@Override
public <R extends HttpRequest> R bindToRequest(R request, Map<String, String> postParams) {
ServerRequest server = new ServerRequest(checkNotNull(postParams.get("name"),
"name parameter not present"), checkNotNull(postParams
.get("imageRef"), "imageRef parameter not present"), checkNotNull(
postParams.get("flavorRef"), "flavorRef parameter not present"));
if (metadata.size() > 0)
server.metadata = metadata;
if (files.size() > 0)
server.personality = files;
if (publicIp != null) {
server.addresses = new Addresses();
server.addresses.getPublicAddresses().add(publicIp);
server.addresses.setPrivateAddresses(null);
}
return bindToRequest(request, ImmutableMap.of("server", server));
}
/**
* You may further customize a cloud server by injecting data into the file system of the cloud
* server itself. This is useful, for example, for inserting ssh keys, setting configuration
* files, or storing data that you want to retrieve from within the instance itself. It is
* intended to provide a minimal amount of launch-time personalization. If significant
* customization is required, a custom image should be created. The max size of the file path
* data is 255 bytes while the max size of the file contents is 10KB. Note that the file contents
* should be encoded as a Base64 string and the 10KB limit refers to the number of bytes in the
* decoded data not the number of characters in the encoded data. The maximum number of file
* path/content pairs that can be supplied is 5. Any existing files that match the specified file
* will be renamed to include the extension bak followed by a time stamp. For example, the file
* /etc/passwd will be backed up as /etc/passwd.bak.1246036261.5785. All files will have root and
* the root group as owner and group owner, respectively and will allow user and group read
* access only (-r--r-----).
*/
public CreateServerOptions withFile(String path, byte[] contents) {
checkState(files.size() < 5, "maximum number of files allowed is 5");
files.add(new File(path, contents));
return this;
}
/**
* You may further customize a cloud server by injecting data into the file system of the cloud
* server itself. This is useful, for example, for inserting ssh keys, setting configuration
* files, or storing data that you want to retrieve from within the instance itself. It is
* intended to provide a minimal amount of launch-time personalization. If significant
* customization is required, a custom image should be created. The max size of the file path
* data is 255 bytes while the max size of the file contents is 10KB. Note that the file contents
* should be encoded as a Base64 string and the 10KB limit refers to the number of bytes in the
* decoded data not the number of characters in the encoded data. The maximum number of file
* path/content pairs that can be supplied is 5. Any existing files that match the specified file
* will be renamed to include the extension bak followed by a time stamp. For example, the file
* /etc/passwd will be backed up as /etc/passwd.bak.1246036261.5785. All files will have root and
* the root group as owner and group owner, respectively and will allow user and group read
* access only (-r--r-----).
*/
public CreateServerOptions withFile(String path, byte[] contents) {
checkState(files.size() < 5, "maximum number of files allowed is 5");
files.add(new File(path, contents));
return this;
}
/**
* A shared IP group is a collection of servers that can share IPs with other members of the
* group. Any server in a group can share one or more public IPs with any other server in the
* group. With the exception of the first server in a shared IP group, servers must be launched
* into shared IP groups. A server may only be a member of one shared IP group.
*
* <p/>
* Servers in the same shared IP group can share public IPs for various high availability and
* load balancing configurations. To launch an HA server, include the optional sharedIpGroupId
* element and the server will be launched into that shared IP group.
* <p />
*
* Note: sharedIpGroupId is an optional parameter and for optimal performance, should ONLY be
* specified when intending to share IPs between servers.
*
* @see #withSharedIp(String)
*/
public CreateServerOptions withSharedIpGroup(int id) {
checkArgument(id > 0, "id must be positive or zero. was: " + id);
this.sharedIpGroupId = id;
return this;
}
/**
* Custom cloud server metadata can also be supplied at launch time. This metadata is stored in
* the API system where it is retrievable by querying the API for server status. The maximum size
* of the metadata key and value is each 255 bytes and the maximum number of key-value pairs that
* can be supplied per server is 5.
*/
public CreateServerOptions withMetadata(Map<String, String> metadata) {
checkNotNull(metadata, "metadata");
checkArgument(metadata.size() <= 5,
"you cannot have more then 5 metadata values. You specified: " + metadata.size());
for (Entry<String, String> entry : metadata.entrySet()) {
checkArgument(entry.getKey().getBytes().length < 255, String.format(
"maximum length of metadata key is 255 bytes. Key specified %s is %d bytes",
entry.getKey(), entry.getKey().getBytes().length));
checkArgument(
entry.getKey().getBytes().length < 255,
String
.format(
/**
* 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
* of the metadata key and value is each 255 bytes and the maximum number of key-value pairs that
* can be supplied per server is 5.
*/
public CreateServerOptions withMetadata(Map<String, String> metadata) {
checkNotNull(metadata, "metadata");
checkArgument(metadata.size() <= 5,
"you cannot have more then 5 metadata values. You specified: " + metadata.size());
for (Entry<String, String> entry : metadata.entrySet()) {
checkArgument(entry.getKey().getBytes().length < 255, String.format(
"maximum length of metadata key is 255 bytes. Key specified %s is %d bytes",
entry.getKey(), entry.getKey().getBytes().length));
checkArgument(
entry.getKey().getBytes().length < 255,
String
.format(
"maximum length of metadata value is 255 bytes. Value specified for %s (%s) is %d bytes",
entry.getKey(), entry.getValue(),
entry.getValue().getBytes().length));
}
this.metadata = metadata;
return this;
}
}
this.metadata = metadata;
return this;
}
/**
* Public IP addresses can be shared across multiple servers for use in various high availability
* scenarios. When an IP address is shared to another server, the cloud network restrictions are
* modified to allow each server to listen to and respond on that IP address (you may optionally
* specify that the target server network configuration be modified). Shared IP addresses can be
* used with many standard heartbeat facilities (e.g. keepalived) that monitor for failure and
* manage IP failover.
*
* <p/>
* If you intend to use a shared IP on the server being created and have no need for a separate
* public IP address, you may launch the server into a shared IP group and specify an IP address
* from that shared IP group to be used as its public IP. You can accomplish this by specifying
* the public shared IP address in your request. This is optional and is only valid if
* sharedIpGroupId is also supplied.
*/
public CreateServerOptions withSharedIp(String publicIp) {
checkState(sharedIpGroupId != null,
"sharedIp is invalid unless a shared ip group is specified.");
this.publicIp = checkNotNull(publicIp, "ip");
return this;
}
public static class Builder {
public static class Builder {
/**
* @see CreateServerOptions#withFile(String,byte [])
*/
public static CreateServerOptions withFile(String path, byte[] contents) {
CreateServerOptions options = new CreateServerOptions();
return options.withFile(path, contents);
}
/**
* @see CreateServerOptions#withFile(String, byte[])
*/
public static CreateServerOptions withFile(String path, byte[] contents) {
CreateServerOptions options = new CreateServerOptions();
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>)
*/
public static CreateServerOptions withMetadata(Map<String, String> metadata) {
CreateServerOptions options = new CreateServerOptions();
return options.withMetadata(metadata);
}
/**
* @see CreateServerOptions#withMetadata(Map<String, String>)
*/
public static CreateServerOptions withMetadata(Map<String, String> metadata) {
CreateServerOptions options = new CreateServerOptions();
return options.withMetadata(metadata);
}
/**
* @see CreateServerOptions#withSharedIp(String)
*/
public static CreateServerOptions withSharedIp(String publicIp) {
CreateServerOptions options = new CreateServerOptions();
return options.withSharedIp(publicIp);
}
}
}
}

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

@ -24,7 +24,6 @@ import com.google.inject.TypeLiteral;
import org.jclouds.http.HttpRequest;
import org.jclouds.http.RequiresHttp;
import org.jclouds.http.functions.ReleasePayloadAndReturn;
import org.jclouds.http.functions.ReturnFalseOn404;
import org.jclouds.http.functions.ReturnTrueIf2xx;
import org.jclouds.http.functions.UnwrapOnlyJsonValue;
import org.jclouds.openstack.OpenStackAuthAsyncClient.AuthenticationResponse;
@ -34,14 +33,15 @@ 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.CreateSharedIpGroupOptions;
import org.jclouds.openstack.nova.options.ListOptions;
import org.jclouds.openstack.nova.options.RebuildServerOptions;
import org.jclouds.rest.ConfiguresRestClient;
import org.jclouds.rest.RestClientTest;
import org.jclouds.rest.RestContextFactory;
import org.jclouds.rest.RestContextSpec;
import org.jclouds.rest.functions.*;
import org.jclouds.rest.functions.ReturnEmptySetOnNotFoundOr404;
import org.jclouds.rest.functions.ReturnFalseOnNotFoundOr404;
import org.jclouds.rest.functions.ReturnNullOnNotFoundOr404;
import org.jclouds.rest.internal.RestAnnotationProcessor;
import org.testng.annotations.Test;
@ -49,14 +49,13 @@ import javax.ws.rs.core.MediaType;
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 static org.jclouds.Constants.PROPERTY_API_VERSION;
import static org.jclouds.location.reference.LocationConstants.PROPERTY_REGIONS;
import static org.jclouds.openstack.nova.options.CreateServerOptions.Builder.*;
import static org.jclouds.openstack.nova.options.CreateSharedIpGroupOptions.Builder.withServer;
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;
@ -82,7 +81,7 @@ public class NovaAsyncClientTest extends RestClientTest<NovaAsyncClient> {
assertRequestLineEquals(request, "POST http://endpoint/vapiversion/servers?format=json HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Accept: application/json\n");
assertPayloadEquals(request, "{\"server\":{\"name\":\"ralphie\",\"imageId\":2,\"flavorId\":1}}",
assertPayloadEquals(request, "{\"server\":{\"name\":\"ralphie\",\"imageRef\":2,\"flavorRef\":1}}",
"application/json", false);
assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class);
@ -104,7 +103,7 @@ public class NovaAsyncClientTest extends RestClientTest<NovaAsyncClient> {
assertNonPayloadHeadersEqual(request, "Accept: application/json\n");
assertPayloadEquals(
request,
"{\"server\":{\"name\":\"ralphie\",\"imageId\":2,\"flavorId\":1,\"personality\":[{\"path\":\"/etc/jclouds\",\"contents\":\"Zm9v\"}]}}",
"{\"server\":{\"name\":\"ralphie\",\"imageRef\":2,\"flavorRef\":1,\"personality\":[{\"path\":\"/etc/jclouds\",\"contents\":\"Zm9v\"}]}}",
"application/json", false);
assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class);
@ -125,7 +124,7 @@ public class NovaAsyncClientTest extends RestClientTest<NovaAsyncClient> {
assertRequestLineEquals(request, "POST http://endpoint/vapiversion/servers?format=json HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Accept: application/json\n");
assertPayloadEquals(request,
"{\"server\":{\"name\":\"ralphie\",\"imageId\":2,\"flavorId\":1,\"metadata\":{\"foo\":\"bar\"}}}",
"{\"server\":{\"name\":\"ralphie\",\"imageRef\":2,\"flavorRef\":1,\"metadata\":{\"foo\":\"bar\"}}}",
"application/json", false);
assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class);
@ -507,7 +506,7 @@ public class NovaAsyncClientTest extends RestClientTest<NovaAsyncClient> {
assertRequestLineEquals(request, "POST http://endpoint/vapiversion/servers/3/action?format=json HTTP/1.1");
assertNonPayloadHeadersEqual(request, "");
assertPayloadEquals(request, "{\"rebuild\":{\"imageId\":2}}", MediaType.APPLICATION_JSON, false);
assertPayloadEquals(request, "{\"rebuild\":{\"imageRef\":2}}", MediaType.APPLICATION_JSON, false);
assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class);
assertSaxResponseParserClassEquals(method, null);

View File

@ -51,6 +51,7 @@ import java.util.Set;
import java.util.concurrent.TimeUnit;
import static com.google.common.base.Preconditions.checkNotNull;
import static org.jclouds.openstack.nova.PropertyHelper.overridePropertyFromSystemProperty;
import static org.jclouds.openstack.nova.options.CreateServerOptions.Builder.withFile;
import static org.jclouds.openstack.nova.options.ListOptions.Builder.withDetails;
import static org.testng.Assert.*;
@ -73,11 +74,20 @@ public class NovaClientLiveTest {
protected String endpoint;
protected String apiversion;
private void overridePropertyFromSystemProperty(final Properties properties, String propertyName) {
if ((System.getProperty(propertyName) != null) && !System.getProperty(propertyName).equals("${" + propertyName + "}"))
properties.setProperty(propertyName, System.getProperty(propertyName));
}
protected Properties setupProperties() throws IOException {
Properties overrides = new Properties();
overrides.load(this.getClass().getResourceAsStream("/test.properties"));
overridePropertyFromSystemProperty(overrides, "test." + provider + ".endpoint");
overridePropertyFromSystemProperty(overrides, "test." + provider + ".apiversion");
overridePropertyFromSystemProperty(overrides, "test." + provider + ".identity");
overridePropertyFromSystemProperty(overrides, "test." + provider + ".credential");
overridePropertyFromSystemProperty(overrides, "test.initializer");
overrides.setProperty(Constants.PROPERTY_TRUST_ALL_CERTS, "true");
overrides.setProperty(Constants.PROPERTY_RELAX_HOSTNAME, "true");
return overrides;
}
protected void setupCredentials(Properties properties) {
identity = checkNotNull(properties.getProperty("test." + provider + ".identity"), "test." + provider + ".identity");
@ -96,19 +106,6 @@ public class NovaClientLiveTest {
properties.setProperty(provider + ".apiversion", apiversion);
}
protected Properties setupProperties() throws IOException {
Properties overrides = new Properties();
overrides.load(this.getClass().getResourceAsStream("/test.properties"));
overridePropertyFromSystemProperty(overrides, "test." + provider + ".endpoint");
overridePropertyFromSystemProperty(overrides, "test." + provider + ".apiversion");
overridePropertyFromSystemProperty(overrides, "test." + provider + ".identity");
overridePropertyFromSystemProperty(overrides, "test." + provider + ".credential");
overridePropertyFromSystemProperty(overrides, "test.initializer");
overrides.setProperty(Constants.PROPERTY_TRUST_ALL_CERTS, "true");
overrides.setProperty(Constants.PROPERTY_RELAX_HOSTNAME, "true");
return overrides;
}
@BeforeGroups(groups = {"live"})
public void setupClient() throws IOException {
@ -268,7 +265,7 @@ public class NovaClientLiveTest {
@Test(enabled = true)
public void testCreateServer() throws Exception {
String imageRef = "14362";
String imageRef = "3";
String flavorRef = "1";
String serverName = serverPrefix + "createserver" + new SecureRandom().nextInt();
Server server = client.createServer(serverName, imageRef, flavorRef, withFile("/etc/jclouds.txt",

View File

@ -0,0 +1,20 @@
package org.jclouds.openstack.nova;
import java.util.Properties;
/**
* Created by IntelliJ IDEA.
* User: VGalkin
* Date: 4/14/11
* Time: 4:32 PM
* To change this template use File | Settings | File Templates.
*/
public class PropertyHelper {
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));
}
}

View File

@ -1,59 +1,57 @@
package org.jclouds.openstack.nova;
import org.jclouds.compute.ComputeService;
import org.jclouds.compute.ComputeServiceContextFactory;
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.domain.TemplateBuilder;
import org.jclouds.compute.options.TemplateOptions;
import org.jclouds.logging.log4j.config.Log4JLoggingModule;
import org.jclouds.ssh.jsch.config.JschSshClientModule;
import java.util.Arrays;
import java.util.Collections;
import java.util.Properties;
import java.util.Set;
import static org.jclouds.Constants.PROPERTY_ENDPOINT;
public class _NovaClient {
static public void main(String[] args) {
//curl -v -H "X-Auth-User:admin" -H "X-Auth-Key: d744752f-20d3-4d75-979f-f62f16033b07" http://172.18.34.40:8774/v1.0/
//curl -v -H "X-Auth-Token: c97b10659008d5a9ce91462f8c6a5c2c80439762" http://172.18.34.40:8774/v1.0/images/detail?format=json
static public void main(String[] args) {
//curl -v -H "X-Auth-User:admin" -H "X-Auth-Key: d744752f-20d3-4d75-979f-f62f16033b07" http://172.18.34.40:8774/v1.0/
//curl -v -H "X-Auth-Token: 00cf93fd62df48f9fdc35fa16a7662447e48c513" http://dragon004.hw.griddynamics.net:8774/v1.1/images/detail?format=json
String identity = "admin";
String credential = "d744752f-20d3-4d75-979f-f62f16033b07";
String endpoint = "http://dragon004.hw.griddynamics.net:8774";
String identity = "admin";
String credential = "d744752f-20d3-4d75-979f-f62f16033b07";
String endpoint = "http://dragon004.hw.griddynamics.net:8774";
ComputeServiceContextFactory contextFactory = new ComputeServiceContextFactory();
ComputeServiceContextFactory contextFactory = new ComputeServiceContextFactory();
Properties overrides = new Properties();
overrides.setProperty(PROPERTY_ENDPOINT, endpoint);
ComputeServiceContext context = contextFactory.createContext("nova", identity, credential,
Arrays.asList(new JschSshClientModule(), new Log4JLoggingModule()), overrides);
Properties overrides = new Properties();
overrides.setProperty(PROPERTY_ENDPOINT, endpoint);
ComputeServiceContext context = contextFactory.createContext("nova", identity, credential,
Arrays.asList(new JschSshClientModule(), new Log4JLoggingModule()), overrides);
ComputeService cs = context.getComputeService();
ComputeService cs = context.getComputeService();
System.out.println(cs.listImages());
System.out.println(cs.listHardwareProfiles());
//System.out.println(cs.listNodes());
System.out.println(cs.listImages());
System.out.println(cs.listHardwareProfiles());
//System.out.println(cs.listNodes());
TemplateOptions options = new TemplateOptions();
//options.authorizePublicKey("");
Template template = cs.templateBuilder().imageId("13").options(options).build();
try {
Set<? extends NodeMetadata> metedata = cs.runNodesWithTag("test", 1, template);
System.out.println(metedata);
} catch (RunNodesException e) {
e.printStackTrace();
}
TemplateOptions options = new TemplateOptions();
//options.authorizePublicKey("");
Template template = cs.templateBuilder().imageId("3").options(options).build();
try {
Set<? extends NodeMetadata> metedata = cs.runNodesWithTag("test", 1, template);
System.out.println(metedata);
} catch (RunNodesException e) {
e.printStackTrace();
}
//System.out.println(cs.listNodes());
//System.out.println(cs.listImages());
//System.out.println(cs.listNodes());
//System.out.println(cs.listAssignableLocations());
//System.out.println(cs.listHardwareProfiles());
}
//System.out.println(cs.listNodes());
//System.out.println(cs.listImages());
//System.out.println(cs.listNodes());
//System.out.println(cs.listAssignableLocations());
//System.out.println(cs.listHardwareProfiles());
}
}

View File

@ -74,6 +74,7 @@ import static org.jclouds.compute.options.TemplateOptions.Builder.overrideCreden
import static org.jclouds.compute.predicates.NodePredicates.*;
import static org.jclouds.compute.predicates.NodePredicates.all;
import static org.jclouds.compute.util.ComputeServiceUtils.getCores;
import static org.jclouds.openstack.nova.PropertyHelper.overridePropertyFromSystemProperty;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
@ -108,11 +109,6 @@ public class NovaComputeServiceLiveTest {
}
private void overridePropertyFromSystemProperty(final Properties properties, String propertyName) {
if ((System.getProperty(propertyName) != null) && !System.getProperty(propertyName).equals("${" + propertyName + "}"))
properties.setProperty(propertyName, System.getProperty(propertyName));
}
protected void setupCredentials(Properties properties) {
identity = checkNotNull(properties.getProperty("test." + provider + ".identity"), "test." + provider + ".identity");
credential = checkNotNull(properties.getProperty("test." + provider + ".credential"), "test." + provider
@ -131,13 +127,10 @@ public class NovaComputeServiceLiveTest {
}
protected Properties setupProperties() {
protected Properties setupProperties() throws IOException {
Properties overrides = new Properties();
try {
overrides.load(this.getClass().getResourceAsStream("/test.properties"));
} catch (IOException e) {
throw new RuntimeException("Can't load properties");
}
overrides.load(this.getClass().getResourceAsStream("/test.properties"));
overridePropertyFromSystemProperty(overrides, "test." + provider + ".endpoint");
overridePropertyFromSystemProperty(overrides, "test." + provider + ".apiversion");
overridePropertyFromSystemProperty(overrides, "test." + provider + ".identity");

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");
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,18 @@
*/
package org.jclouds.openstack.nova.options;
import static org.jclouds.openstack.nova.options.CreateServerOptions.Builder.withFile;
import static org.jclouds.openstack.nova.options.CreateServerOptions.Builder.withSharedIp;
import static org.jclouds.openstack.nova.options.CreateServerOptions.Builder.withSharedIpGroup;
import static org.testng.Assert.assertEquals;
import java.net.URI;
import javax.ws.rs.HttpMethod;
import com.google.common.collect.ImmutableMap;
import com.google.inject.Guice;
import com.google.inject.Injector;
import org.jclouds.http.HttpRequest;
import org.jclouds.json.config.GsonModule;
import org.testng.annotations.Test;
import com.google.common.collect.ImmutableMap;
import com.google.inject.Guice;
import com.google.inject.Injector;
import javax.ws.rs.HttpMethod;
import java.net.URI;
import static org.jclouds.openstack.nova.options.CreateServerOptions.Builder.withFile;
import static org.testng.Assert.assertEquals;
/**
* Tests behavior of {@code ParseFlavorFromJsonResponse}
@ -43,98 +39,45 @@ import com.google.inject.Injector;
@Test(groups = "unit")
public class CreateServerOptionsTest {
Injector injector = Guice.createInjector(new GsonModule());
Injector injector = Guice.createInjector(new GsonModule());
@Test
public void testAddPayloadToRequestMapOfStringStringHttpRequest() {
CreateServerOptions options = new CreateServerOptions();
HttpRequest request = buildRequest(options);
assertEquals("{\"server\":{\"name\":\"foo\",\"imageId\":1,\"flavorId\":2}}", request.getPayload().getRawContent());
}
@Test
public void testAddPayloadToRequestMapOfStringStringHttpRequest() {
CreateServerOptions options = new CreateServerOptions();
HttpRequest request = buildRequest(options);
assertEquals("{\"server\":{\"name\":\"foo\",\"imageRef\":1,\"flavorRef\":2}}", request.getPayload().getRawContent());
}
private HttpRequest buildRequest(CreateServerOptions options) {
injector.injectMembers(options);
HttpRequest request = new HttpRequest(HttpMethod.POST, URI.create("http://localhost"));
options.bindToRequest(request, ImmutableMap.of("name", "foo", "imageId", "1", "flavorId", "2"));
return request;
}
private HttpRequest buildRequest(CreateServerOptions options) {
injector.injectMembers(options);
HttpRequest request = new HttpRequest(HttpMethod.POST, URI.create("http://localhost"));
options.bindToRequest(request, ImmutableMap.of("name", "foo", "imageRef", "1", "flavorRef", "2"));
return request;
}
@Test
public void testWithFile() {
CreateServerOptions options = new CreateServerOptions();
options.withFile("/tmp/rhubarb", "foo".getBytes());
HttpRequest request = buildRequest(options);
assertFile(request);
}
@Test
public void testWithFile() {
CreateServerOptions options = new CreateServerOptions();
options.withFile("/tmp/rhubarb", "foo".getBytes());
HttpRequest request = buildRequest(options);
assertFile(request);
}
@Test
public void testWithFileStatic() {
CreateServerOptions options = withFile("/tmp/rhubarb", "foo".getBytes());
HttpRequest request = buildRequest(options);
assertFile(request);
}
@Test
public void testWithFileStatic() {
CreateServerOptions options = withFile("/tmp/rhubarb", "foo".getBytes());
HttpRequest request = buildRequest(options);
assertFile(request);
}
private void assertFile(HttpRequest request) {
assertEquals(
"{\"server\":{\"name\":\"foo\",\"imageId\":1,\"flavorId\":2,\"personality\":[{\"path\":\"/tmp/rhubarb\",\"contents\":\"Zm9v\"}]}}",
request.getPayload().getRawContent());
}
private void assertFile(HttpRequest request) {
assertEquals(request.getPayload().getRawContent(),
"{\"server\":{\"name\":\"foo\",\"imageRef\":1,\"flavorRef\":2,\"personality\":[{\"path\":\"/tmp/rhubarb\",\"contents\":\"Zm9v\"}]}}");
}
@Test
public void testWithSharedIpGroup() {
CreateServerOptions options = new CreateServerOptions();
options.withSharedIpGroup(3);
HttpRequest request = buildRequest(options);
assertSharedIpGroup(request);
}
@Test
public void testWithMetadata() {
}
@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
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

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