added security group options and offline tests to nova

This commit is contained in:
Adrian Cole 2012-03-20 14:45:09 -07:00
parent cdf87d57a2
commit 58ee8fa1a4
12 changed files with 627 additions and 144 deletions

View File

@ -74,7 +74,7 @@ public class HPCloudComputeTemplateBuilderLiveTest extends BaseTemplateBuilderLi
assertEquals(defaultTemplate.getImage().getOperatingSystem().getVersion(), "11.10"); assertEquals(defaultTemplate.getImage().getOperatingSystem().getVersion(), "11.10");
assertEquals(defaultTemplate.getImage().getOperatingSystem().getFamily(), OsFamily.UBUNTU); assertEquals(defaultTemplate.getImage().getOperatingSystem().getFamily(), OsFamily.UBUNTU);
assertEquals(defaultTemplate.getLocation().getId(), "az-1.region-a.geo-1"); assertEquals(defaultTemplate.getLocation().getId(), "az-1.region-a.geo-1");
assertEquals(defaultTemplate.getOptions().as(NovaTemplateOptions.class).isAutoAssignFloatingIp(), true); assertEquals(defaultTemplate.getOptions().as(NovaTemplateOptions.class).shouldAutoAssignFloatingIp(), true);
assertEquals(getCores(defaultTemplate.getHardware()), 1.0d); assertEquals(getCores(defaultTemplate.getHardware()), 1.0d);
} }

View File

@ -39,10 +39,13 @@ import org.jclouds.openstack.nova.v1_1.compute.domain.ImageInZone;
import org.jclouds.openstack.nova.v1_1.compute.domain.ServerInZone; import org.jclouds.openstack.nova.v1_1.compute.domain.ServerInZone;
import org.jclouds.openstack.nova.v1_1.compute.domain.ZoneAndId; import org.jclouds.openstack.nova.v1_1.compute.domain.ZoneAndId;
import org.jclouds.openstack.nova.v1_1.compute.functions.RemoveFloatingIpFromNodeAndDeallocate; import org.jclouds.openstack.nova.v1_1.compute.functions.RemoveFloatingIpFromNodeAndDeallocate;
import org.jclouds.openstack.nova.v1_1.compute.options.NovaTemplateOptions;
import org.jclouds.openstack.nova.v1_1.compute.strategy.ApplyNovaTemplateOptionsCreateNodesWithGroupEncodedIntoNameThenAddToSet;
import org.jclouds.openstack.nova.v1_1.domain.Flavor; import org.jclouds.openstack.nova.v1_1.domain.Flavor;
import org.jclouds.openstack.nova.v1_1.domain.Image; import org.jclouds.openstack.nova.v1_1.domain.Image;
import org.jclouds.openstack.nova.v1_1.domain.RebootType; import org.jclouds.openstack.nova.v1_1.domain.RebootType;
import org.jclouds.openstack.nova.v1_1.domain.Server; import org.jclouds.openstack.nova.v1_1.domain.Server;
import org.jclouds.openstack.nova.v1_1.options.CreateServerOptions;
import com.google.common.base.Function; import com.google.common.base.Function;
import com.google.common.base.Supplier; import com.google.common.base.Supplier;
@ -76,15 +79,24 @@ public class NovaComputeServiceAdapter implements
"removeFloatingIpFromNodeAndDeallocate"); "removeFloatingIpFromNodeAndDeallocate");
} }
/**
* Note that we do not validate extensions here, on basis that
* {@link ApplyNovaTemplateOptionsCreateNodesWithGroupEncodedIntoNameThenAddToSet} has already
* done so.
*/
@Override @Override
public NodeAndInitialCredentials<ServerInZone> createNodeWithGroupEncodedIntoName(String tag, String name, public NodeAndInitialCredentials<ServerInZone> createNodeWithGroupEncodedIntoName(String group, String name,
Template template) { Template template) {
CreateServerOptions options = new CreateServerOptions();
options.securityGroupNames(template.getOptions().as(NovaTemplateOptions.class).getSecurityGroupNames());
String zoneId = template.getLocation().getId(); String zoneId = template.getLocation().getId();
Server server = novaClient.getServerClientForZone(zoneId).createServer(name, template.getImage().getProviderId(), Server server = novaClient.getServerClientForZone(zoneId).createServer(name, template.getImage().getProviderId(),
template.getHardware().getProviderId()); template.getHardware().getProviderId(), options);
ServerInZone serverInZone = new ServerInZone(server, zoneId); ServerInZone serverInZone = new ServerInZone(server, zoneId);
return new NodeAndInitialCredentials<ServerInZone>(serverInZone, serverInZone.slashEncode(), return new NodeAndInitialCredentials<ServerInZone>(serverInZone, serverInZone.slashEncode(), LoginCredentials
LoginCredentials.builder().password(server.getAdminPass()).build()); .builder().password(server.getAdminPass()).build());
} }
@Override @Override

View File

@ -18,22 +18,28 @@
*/ */
package org.jclouds.openstack.nova.v1_1.compute.options; package org.jclouds.openstack.nova.v1_1.compute.options;
import static com.google.common.base.Preconditions.checkNotNull;
import java.util.Map; import java.util.Map;
import java.util.Set;
import org.jclouds.compute.options.TemplateOptions; import org.jclouds.compute.options.TemplateOptions;
import org.jclouds.domain.Credentials; import org.jclouds.domain.Credentials;
import org.jclouds.domain.LoginCredentials; import org.jclouds.domain.LoginCredentials;
import org.jclouds.io.Payload; import org.jclouds.io.Payload;
import org.jclouds.openstack.nova.v1_1.NovaClient;
import org.jclouds.scriptbuilder.domain.Statement; import org.jclouds.scriptbuilder.domain.Statement;
import org.jclouds.util.Preconditions2;
import com.google.common.base.Objects; import com.google.common.base.Objects;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableSet;
/** /**
* Contains options supported in the {@code ComputeService#runNode} operation on * Contains options supported in the {@code ComputeService#runNode} operation on the
* the "openstack-nova" provider. * "openstack-nova" provider. <h2>Usage</h2> The recommended way to instantiate a
* <h2>Usage</h2> The recommended way to instantiate a NovaTemplateOptions object is * NovaTemplateOptions object is to statically import NovaTemplateOptions.* and invoke a static
* to statically import NovaTemplateOptions.* and invoke a static creation method * creation method followed by an instance mutator (if needed):
* followed by an instance mutator (if needed):
* <p/> * <p/>
* <code> * <code>
* import static org.jclouds.aws.ec2.compute.options.NovaTemplateOptions.Builder.*; * import static org.jclouds.aws.ec2.compute.options.NovaTemplateOptions.Builder.*;
@ -42,7 +48,7 @@ import com.google.common.base.Objects;
* templateBuilder.options(inboundPorts(22, 80, 8080, 443)); * templateBuilder.options(inboundPorts(22, 80, 8080, 443));
* Set<? extends NodeMetadata> set = client.createNodesInGroup(tag, 2, templateBuilder.build()); * Set<? extends NodeMetadata> set = client.createNodesInGroup(tag, 2, templateBuilder.build());
* <code> * <code>
* *
* @author Adam Lowe * @author Adam Lowe
*/ */
public class NovaTemplateOptions extends TemplateOptions implements Cloneable { public class NovaTemplateOptions extends TemplateOptions implements Cloneable {
@ -58,38 +64,86 @@ public class NovaTemplateOptions extends TemplateOptions implements Cloneable {
super.copyTo(to); super.copyTo(to);
if (to instanceof NovaTemplateOptions) { if (to instanceof NovaTemplateOptions) {
NovaTemplateOptions eTo = NovaTemplateOptions.class.cast(to); NovaTemplateOptions eTo = NovaTemplateOptions.class.cast(to);
eTo.autoAssignFloatingIp(isAutoAssignFloatingIp()); eTo.autoAssignFloatingIp(shouldAutoAssignFloatingIp());
eTo.securityGroupNames(getSecurityGroupNames());
} }
} }
private boolean autoAssignFloatingIp = false; private boolean autoAssignFloatingIp = false;
private Set<String> securityGroupNames = ImmutableSet.of();
public static final NovaTemplateOptions NONE = new NovaTemplateOptions(); public static final NovaTemplateOptions NONE = new NovaTemplateOptions();
/** /**
* @see #isAutoAssignFloatingIp() * @see #shouldAutoAssignFloatingIp()
*/ */
public NovaTemplateOptions autoAssignFloatingIp(boolean enable) { public NovaTemplateOptions autoAssignFloatingIp(boolean enable) {
this.autoAssignFloatingIp = enable; this.autoAssignFloatingIp = enable;
return this; return this;
} }
/** /**
*
* @see CreateServerOptions#getSecurityGroupNames
*/
public NovaTemplateOptions securityGroupNames(String... securityGroupNames) {
return securityGroupNames(ImmutableSet.copyOf(checkNotNull(securityGroupNames, "securityGroupNames")));
}
/**
* @see CreateServerOptions#getSecurityGroupNames
*/
public NovaTemplateOptions securityGroupNames(Iterable<String> securityGroupNames) {
for (String groupName : checkNotNull(securityGroupNames, "securityGroupNames"))
Preconditions2.checkNotEmpty(groupName, "all security groups must be non-empty");
this.securityGroupNames = ImmutableSet.copyOf(securityGroupNames);
return this;
}
/**
* <h3>Note</h3>
*
* This requires that {@link NovaClient#getFloatingIPExtensionForZone(String)} to return
* {@link Optional#isPresent present}
*
* @return true if auto assignment of a floating ip to each vm is enabled * @return true if auto assignment of a floating ip to each vm is enabled
*/ */
public boolean isAutoAssignFloatingIp() { public boolean shouldAutoAssignFloatingIp() {
return autoAssignFloatingIp; return autoAssignFloatingIp;
} }
/**
* @see CreateServerOptions#getSecurityGroupNames
*/
public Set<String> getSecurityGroupNames() {
return securityGroupNames;
}
public static class Builder { public static class Builder {
/** /**
* @see NovaTemplateOptions#isAutoAssignFloatingIp() * @see NovaTemplateOptions#shouldAutoAssignFloatingIp()
*/ */
public static NovaTemplateOptions autoAssignFloatingIp(boolean enable) { public static NovaTemplateOptions autoAssignFloatingIp(boolean enable) {
return new NovaTemplateOptions().autoAssignFloatingIp(enable); return new NovaTemplateOptions().autoAssignFloatingIp(enable);
} }
/**
* @see CreateServerOptions#getSecurityGroupNames
*/
public static NovaTemplateOptions securityGroupNames(String... groupNames) {
NovaTemplateOptions options = new NovaTemplateOptions();
return NovaTemplateOptions.class.cast(options.securityGroupNames(groupNames));
}
/**
* @see CreateServerOptions#getSecurityGroupNames
*/
public static NovaTemplateOptions securityGroupNames(Iterable<String> groupNames) {
NovaTemplateOptions options = new NovaTemplateOptions();
return NovaTemplateOptions.class.cast(options.securityGroupNames(groupNames));
}
// methods that only facilitate returning the correct object type // methods that only facilitate returning the correct object type
/** /**
@ -147,7 +201,7 @@ public class NovaTemplateOptions extends TemplateOptions implements Cloneable {
NovaTemplateOptions options = new NovaTemplateOptions(); NovaTemplateOptions options = new NovaTemplateOptions();
return options.overrideLoginPassword(password); return options.overrideLoginPassword(password);
} }
/** /**
* @see TemplateOptions#overrideLoginPrivateKey * @see TemplateOptions#overrideLoginPrivateKey
*/ */
@ -155,7 +209,7 @@ public class NovaTemplateOptions extends TemplateOptions implements Cloneable {
NovaTemplateOptions options = new NovaTemplateOptions(); NovaTemplateOptions options = new NovaTemplateOptions();
return options.overrideLoginPrivateKey(privateKey); return options.overrideLoginPrivateKey(privateKey);
} }
/** /**
* @see TemplateOptions#overrideAuthenticateSudo * @see TemplateOptions#overrideAuthenticateSudo
*/ */

View File

@ -81,11 +81,16 @@ public class ApplyNovaTemplateOptionsCreateNodesWithGroupEncodedIntoNameThenAddT
String zone = template.getLocation().getId(); String zone = template.getLocation().getId();
if (templateOptions.isAutoAssignFloatingIp()) { if (templateOptions.shouldAutoAssignFloatingIp()) {
checkArgument(novaClient.getFloatingIPExtensionForZone(zone).isPresent(), checkArgument(novaClient.getFloatingIPExtensionForZone(zone).isPresent(),
"Floating IP settings are required by configuration, but the extension is not available!"); "Floating IPs are required by options, but the extension is not available! options: %s", templateOptions);
} }
if (templateOptions.getSecurityGroupNames().size() > 0) {
checkArgument(novaClient.getSecurityGroupExtensionForZone(zone).isPresent(),
"Security groups are required by options, but the extension is not available! options: %s", templateOptions);
}
return super.execute(group, count, template, goodNodes, badNodes, customizationResponses); return super.execute(group, count, template, goodNodes, badNodes, customizationResponses);
} }
@ -96,7 +101,7 @@ public class ApplyNovaTemplateOptionsCreateNodesWithGroupEncodedIntoNameThenAddT
Future<AtomicReference<NodeMetadata>> future = super.createNodeInGroupWithNameAndTemplate(group, name, template); Future<AtomicReference<NodeMetadata>> future = super.createNodeInGroupWithNameAndTemplate(group, name, template);
NovaTemplateOptions templateOptions = NovaTemplateOptions.class.cast(template.getOptions()); NovaTemplateOptions templateOptions = NovaTemplateOptions.class.cast(template.getOptions());
if (templateOptions.isAutoAssignFloatingIp()) { if (templateOptions.shouldAutoAssignFloatingIp()) {
return Futures.compose(future, allocateAndAddFloatingIpToNode, executor); return Futures.compose(future, allocateAndAddFloatingIpToNode, executor);
} else { } else {
return future; return future;

View File

@ -18,6 +18,7 @@
*/ */
package org.jclouds.openstack.nova.v1_1.domain; package org.jclouds.openstack.nova.v1_1.domain;
import static com.google.common.base.Objects.equal;
import static com.google.common.base.Objects.toStringHelper; import static com.google.common.base.Objects.toStringHelper;
import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkNotNull;
@ -25,6 +26,7 @@ import java.util.Set;
import org.jclouds.javax.annotation.Nullable; import org.jclouds.javax.annotation.Nullable;
import com.google.common.base.Objects;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
import com.google.gson.annotations.SerializedName; import com.google.gson.annotations.SerializedName;
@ -47,7 +49,7 @@ public class SecurityGroup {
private String tenantId; private String tenantId;
private String name; private String name;
private String description; private String description;
private Set<SecurityGroupRule> rules; private Set<SecurityGroupRule> rules = ImmutableSet.<SecurityGroupRule> of();
public Builder id(String id) { public Builder id(String id) {
this.id = id; this.id = id;
@ -69,6 +71,22 @@ public class SecurityGroup {
return this; return this;
} }
/**
*
* @see #getSecurityGroupNames
*/
public Builder rules(SecurityGroupRule... rules) {
return rules(ImmutableSet.copyOf(checkNotNull(rules, "rules")));
}
/**
* @see #getSecurityGroupNames
*/
public Builder rules(Iterable<SecurityGroupRule> rules) {
this.rules = ImmutableSet.copyOf(checkNotNull(rules, "rules"));
return this;
}
public Builder rules(Set<SecurityGroupRule> rules) { public Builder rules(Set<SecurityGroupRule> rules) {
this.rules = rules; this.rules = rules;
return this; return this;
@ -79,26 +97,27 @@ public class SecurityGroup {
} }
public Builder fromSecurityGroup(SecurityGroup in) { public Builder fromSecurityGroup(SecurityGroup in) {
return id(in.getId()).tenantId(in.getTenantId()).name(in.getName()).description(in.getDescription()) return id(in.getId()).tenantId(in.getTenantId()).name(in.getName()).description(in.getDescription()).rules(
.rules(in.getRules()); in.getRules());
} }
} }
protected String id; protected final String id;
@SerializedName("tenant_id") @SerializedName("tenant_id")
protected String tenantId; protected final String tenantId;
protected String name; protected final String name;
protected String description; protected final String description;
protected Set<SecurityGroupRule> rules; protected final Set<SecurityGroupRule> rules;
protected SecurityGroup(String id, String tenantId, @Nullable String name, @Nullable String description, protected SecurityGroup(String id, String tenantId, @Nullable String name, @Nullable String description,
Set<SecurityGroupRule> rules) { Set<SecurityGroupRule> rules) {
this.id = id; this.id = id;
this.tenantId = tenantId; this.tenantId = tenantId;
this.name = name; this.name = name;
this.description = description; this.description = description;
this.rules = ImmutableSet.copyOf(checkNotNull(rules, "rules")); // if empty, leave null so this doesn't serialize to json
this.rules = checkNotNull(rules, "rules").size() == 0 ? null : ImmutableSet.copyOf(rules);
} }
public String getId() { public String getId() {
@ -118,62 +137,31 @@ public class SecurityGroup {
} }
public Set<SecurityGroupRule> getRules() { public Set<SecurityGroupRule> getRules() {
return this.rules; return this.rules == null ? ImmutableSet.<SecurityGroupRule> of() : rules;
}
@Override
public boolean equals(Object object) {
if (this == object) {
return true;
}
if (object instanceof SecurityGroup) {
final SecurityGroup other = SecurityGroup.class.cast(object);
return equal(tenantId, other.tenantId) && equal(id, other.id) && equal(name, other.name);
} else {
return false;
}
} }
@Override @Override
public int hashCode() { public int hashCode() {
final int prime = 31; return Objects.hashCode(tenantId, id, name);
int result = 1;
result = prime * result + ((description == null) ? 0 : description.hashCode());
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((rules == null) ? 0 : rules.hashCode());
result = prime * result + ((tenantId == null) ? 0 : tenantId.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;
SecurityGroup other = (SecurityGroup) obj;
if (description == null) {
if (other.description != null)
return false;
} else if (!description.equals(other.description))
return false;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (rules == null) {
if (other.rules != null)
return false;
} else if (!rules.equals(other.rules))
return false;
if (tenantId == null) {
if (other.tenantId != null)
return false;
} else if (!tenantId.equals(other.tenantId))
return false;
return true;
} }
@Override @Override
public String toString() { public String toString() {
return toStringHelper("").add("id", id).add("name", name).add("tenantId", tenantId) return toStringHelper("").add("tenantId", getTenantId()).add("id", getId()).add("name", getName()).add(
.add("description", description).add("rules", rules).toString(); "description", description).add("rules", getRules()).toString();
} }
} }

View File

@ -24,18 +24,22 @@ import static com.google.common.base.Preconditions.checkState;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Map.Entry;
import java.util.Set; import java.util.Set;
import java.util.Map.Entry;
import javax.inject.Inject; import javax.inject.Inject;
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.v1_1.NovaClient;
import org.jclouds.openstack.nova.v1_1.domain.SecurityGroup; import org.jclouds.openstack.nova.v1_1.domain.SecurityGroup;
import org.jclouds.rest.MapBinder; import org.jclouds.rest.MapBinder;
import org.jclouds.rest.binders.BindToJsonPayload; import org.jclouds.rest.binders.BindToJsonPayload;
import org.jclouds.util.Preconditions2;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import com.google.common.collect.Maps; import com.google.common.collect.Maps;
import com.google.common.collect.Sets; import com.google.common.collect.Sets;
@ -85,7 +89,7 @@ public class CreateServerOptions implements MapBinder {
List<File> personality; List<File> personality;
String key_name; String key_name;
@SerializedName(value = "security_groups") @SerializedName(value = "security_groups")
Set<SecurityGroup> securityGroups; Set<SecurityGroup> securityGroupNames;
private ServerRequest(String name, String imageRef, String flavorRef) { private ServerRequest(String name, String imageRef, String flavorRef) {
this.name = name; this.name = name;
@ -97,7 +101,7 @@ public class CreateServerOptions implements MapBinder {
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 Set<String> securityGroups = Sets.newHashSet(); private Set<String> securityGroupNames = Sets.newHashSet();
private String keyName; private String keyName;
private String adminPass; private String adminPass;
@ -112,11 +116,11 @@ public class CreateServerOptions implements MapBinder {
server.personality = files; server.personality = files;
if (keyName != null) if (keyName != null)
server.key_name = keyName; server.key_name = keyName;
if (securityGroups.size() > 0) { if (securityGroupNames.size() > 0) {
server.securityGroups = Sets.newHashSet(); server.securityGroupNames = Sets.newHashSet();
for (String groupName : securityGroups) { for (String groupName : securityGroupNames) {
SecurityGroup group = SecurityGroup.builder().name(groupName).build(); SecurityGroup group = SecurityGroup.builder().name(groupName).build();
server.securityGroups.add(group); server.securityGroupNames.add(group);
} }
} }
if (adminPass != null) { if (adminPass != null) {
@ -192,19 +196,39 @@ public class CreateServerOptions implements MapBinder {
this.keyName = keyName; this.keyName = keyName;
return this; return this;
} }
/** /**
* Defines the security group name to be used when creating a server.
* *
* @param groupName * <h3>Note</h3>
* @return *
* This requires that {@link NovaClient#getSecurityGroupExtensionForZone(String)} to return
* {@link Optional#isPresent present}
*
* @return security groups the user specified to run servers with; zero length will create an
* implicit group starting with {@code jclouds#}
*/ */
public CreateServerOptions withSecurityGroup(String groupName) { public Set<String> getSecurityGroupNames() {
checkNotNull(groupName, "groupName"); return securityGroupNames;
this.securityGroups.add(groupName); }
return this;
/**
*
* @see #getSecurityGroupNames
*/
public CreateServerOptions securityGroupNames(String... securityGroupNames) {
return securityGroupNames(ImmutableSet.copyOf(checkNotNull(securityGroupNames, "securityGroupNames")));
} }
/**
* @see #getSecurityGroupNames
*/
public CreateServerOptions securityGroupNames(Iterable<String> securityGroupNames) {
for (String groupName : checkNotNull(securityGroupNames, "securityGroupNames"))
Preconditions2.checkNotEmpty(groupName, "all security groups must be non-empty");
this.securityGroupNames = ImmutableSet.copyOf(securityGroupNames);
return this;
}
public static class Builder { public static class Builder {
/** /**
@ -235,13 +259,21 @@ public class CreateServerOptions implements MapBinder {
CreateServerOptions options = new CreateServerOptions(); CreateServerOptions options = new CreateServerOptions();
return options.withKeyName(keyName); return options.withKeyName(keyName);
} }
/**
* @see CreateServerOptions#getSecurityGroupNames
*/
public static CreateServerOptions securityGroupNames(String... groupNames) {
CreateServerOptions options = new CreateServerOptions();
return CreateServerOptions.class.cast(options.securityGroupNames(groupNames));
}
/** /**
* @see CreateServerOptions#withGroupName(String) * @see CreateServerOptions#getSecurityGroupNames
*/ */
public static CreateServerOptions withSecurityGroup(String name) { public static CreateServerOptions securityGroupNames(Iterable<String> groupNames) {
CreateServerOptions options = new CreateServerOptions(); CreateServerOptions options = new CreateServerOptions();
return options.withSecurityGroup(name); return CreateServerOptions.class.cast(options.securityGroupNames(groupNames));
} }
} }

View File

@ -0,0 +1,90 @@
/**
* Licensed to jclouds, Inc. (jclouds) under one or more
* contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. jclouds licenses this file
* to you 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.v1_1.compute;
import static org.testng.Assert.assertNotNull;
import java.net.URI;
import java.util.Map;
import org.jclouds.compute.ComputeServiceContext;
import org.jclouds.compute.ComputeServiceAdapter.NodeAndInitialCredentials;
import org.jclouds.compute.domain.Template;
import org.jclouds.compute.domain.TemplateBuilder;
import org.jclouds.http.HttpRequest;
import org.jclouds.http.HttpResponse;
import org.jclouds.openstack.nova.v1_1.compute.domain.ServerInZone;
import org.jclouds.openstack.nova.v1_1.compute.options.NovaTemplateOptions;
import org.jclouds.openstack.nova.v1_1.internal.BaseNovaComputeServiceContextExpectTest;
import org.testng.annotations.Test;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableMultimap;
import com.google.inject.Injector;
/**
* Tests the compute service abstraction of the nova client.
*
* @author Adrian Cole
*/
@Test(groups = "unit", testName = "NovaComputeServiceAdapterExpectTest")
public class NovaComputeServiceAdapterExpectTest extends BaseNovaComputeServiceContextExpectTest<Injector> {
public void testCreateNodeWithGroupEncodedIntoNameWhenSecurityGroupsArePresent() throws Exception {
HttpRequest createServer = HttpRequest
.builder()
.method("POST")
.endpoint(URI.create("https://compute.north.host/v1.1/3456/servers"))
.headers(
ImmutableMultimap.<String, String> builder().put("Accept", "application/json")
.put("X-Auth-Token", authToken).build())
.payload(payloadFromStringWithContentType(
"{\"server\":{\"name\":\"test-e92\",\"imageRef\":\"1241\",\"flavorRef\":\"100\",\"security_groups\":[{\"name\":\"group2\"},{\"name\":\"group1\"}]}}","application/json"))
.build();
HttpResponse createServerResponse = HttpResponse.builder().statusCode(202).message("HTTP/1.1 202 Accepted")
.payload(payloadFromResourceWithContentType("/new_server.json","application/json; charset=UTF-8")).build();
Map<HttpRequest, HttpResponse> requestResponseMap = ImmutableMap.<HttpRequest, HttpResponse> builder()
.put(keystoneAuthWithAccessKeyAndSecretKey, responseWithKeystoneAccess)
.put(extensionsOfNovaRequest, extensionsOfNovaResponse)
.put(listImagesDetail, listImagesDetailResponse)
.put(listFlavorsDetail, listFlavorsDetailResponse)
.put(createServer, createServerResponse).build();
Injector forSecurityGroups = requestsSendResponses(requestResponseMap);
Template template = forSecurityGroups.getInstance(TemplateBuilder.class).build();
template.getOptions().as(NovaTemplateOptions.class).securityGroupNames("group1", "group2");
NovaComputeServiceAdapter adapter = forSecurityGroups.getInstance(NovaComputeServiceAdapter.class);
NodeAndInitialCredentials<ServerInZone> server = adapter.createNodeWithGroupEncodedIntoName("test", "test-e92",
template);
assertNotNull(server);
}
@Override
public Injector apply(ComputeServiceContext input) {
return input.utils().injector();
}
}

View File

@ -46,38 +46,7 @@ import com.google.common.collect.ImmutableMultimap;
*/ */
@Test(groups = "unit", testName = "NovaComputeServiceExpectTest") @Test(groups = "unit", testName = "NovaComputeServiceExpectTest")
public class NovaComputeServiceExpectTest extends BaseNovaComputeServiceExpectTest { public class NovaComputeServiceExpectTest extends BaseNovaComputeServiceExpectTest {
HttpRequest listImagesDetail = HttpRequest.builder().method("GET").endpoint(
URI.create("https://compute.north.host/v1.1/3456/images/detail")).headers(
ImmutableMultimap.<String, String> builder().put("Accept", "application/json").put("X-Auth-Token",
authToken).build()).build();
HttpResponse listImagesDetailResponse = HttpResponse.builder().statusCode(200).payload(
payloadFromResource("/image_list_detail.json")).build();
HttpRequest listFlavorsDetail = HttpRequest.builder().method("GET").endpoint(
URI.create("https://compute.north.host/v1.1/3456/flavors/detail")).headers(
ImmutableMultimap.<String, String> builder().put("Accept", "application/json").put("X-Auth-Token",
authToken).build()).build();
HttpResponse listFlavorsDetailResponse = HttpResponse.builder().statusCode(200).payload(
payloadFromResource("/flavor_list_detail.json")).build();
HttpRequest listServers = HttpRequest.builder().method("GET").endpoint(
URI.create("https://compute.north.host/v1.1/3456/servers/detail")).headers(
ImmutableMultimap.<String, String> builder().put("Accept", "application/json").put("X-Auth-Token",
authToken).build()).build();
HttpResponse listServersResponse = HttpResponse.builder().statusCode(200).payload(
payloadFromResource("/server_list_details.json")).build();
HttpRequest listFloatingIps = HttpRequest.builder().method("GET").endpoint(
URI.create("https://compute.north.host/v1.1/3456/os-floating-ips")).headers(
ImmutableMultimap.<String, String> builder().put("Accept", "application/json").put("X-Auth-Token",
authToken).build()).build();
HttpResponse listFloatingIpsResponse = HttpResponse.builder().statusCode(200).payload(
payloadFromResource("/floatingip_list.json")).build();
public void testListServersWhenResponseIs2xx() throws Exception { public void testListServersWhenResponseIs2xx() throws Exception {
Map<HttpRequest, HttpResponse> requestResponseMap = ImmutableMap.<HttpRequest, HttpResponse> builder().put( Map<HttpRequest, HttpResponse> requestResponseMap = ImmutableMap.<HttpRequest, HttpResponse> builder().put(

View File

@ -0,0 +1,230 @@
/**
* Licensed to jclouds, Inc. (jclouds) under one or more
* contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. jclouds licenses this file
* to you 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.v1_1.compute.options;
import static org.jclouds.openstack.nova.v1_1.compute.options.NovaTemplateOptions.Builder.authorizePublicKey;
import static org.jclouds.openstack.nova.v1_1.compute.options.NovaTemplateOptions.Builder.autoAssignFloatingIp;
import static org.jclouds.openstack.nova.v1_1.compute.options.NovaTemplateOptions.Builder.blockOnPort;
import static org.jclouds.openstack.nova.v1_1.compute.options.NovaTemplateOptions.Builder.inboundPorts;
import static org.jclouds.openstack.nova.v1_1.compute.options.NovaTemplateOptions.Builder.installPrivateKey;
import static org.jclouds.openstack.nova.v1_1.compute.options.NovaTemplateOptions.Builder.securityGroupNames;
import static org.testng.Assert.assertEquals;
import java.io.IOException;
import org.jclouds.compute.options.TemplateOptions;
import org.testng.annotations.Test;
import com.google.common.collect.ImmutableSet;
/**
* Tests possible uses of NovaTemplateOptions and NovaTemplateOptions.Builder.*
*
* @author Adrian Cole
*/
@Test(testName = "NovaTemplateOptionsTest")
public class NovaTemplateOptionsTest {
public void testAs() {
TemplateOptions options = new NovaTemplateOptions();
assertEquals(options.as(NovaTemplateOptions.class), options);
}
@Test(expectedExceptions = IllegalArgumentException.class)
public void testsecurityGroupNamesIterableBadFormat() {
NovaTemplateOptions options = new NovaTemplateOptions();
options.securityGroupNames(ImmutableSet.of("group1", ""));
}
@Test
public void testsecurityGroupNamesIterable() {
NovaTemplateOptions options = new NovaTemplateOptions();
options.securityGroupNames(ImmutableSet.of("group1", "group2"));
assertEquals(options.getSecurityGroupNames(), ImmutableSet.of("group1", "group2"));
}
@Test
public void testsecurityGroupNamesIterableStatic() {
NovaTemplateOptions options = securityGroupNames(ImmutableSet.of("group1", "group2"));
assertEquals(options.getSecurityGroupNames(), ImmutableSet.of("group1", "group2"));
}
@Test(expectedExceptions = IllegalArgumentException.class)
public void testsecurityGroupNamesVarArgsBadFormat() {
NovaTemplateOptions options = new NovaTemplateOptions();
options.securityGroupNames("mygroup", "");
}
@Test
public void testsecurityGroupNamesVarArgs() {
NovaTemplateOptions options = new NovaTemplateOptions();
options.securityGroupNames("group1", "group2");
assertEquals(options.getSecurityGroupNames(), ImmutableSet.of("group1", "group2"));
}
@Test
public void testDefaultGroupsVarArgsEmpty() {
NovaTemplateOptions options = new NovaTemplateOptions();
assertEquals(options.getSecurityGroupNames(), ImmutableSet.of());
}
@Test
public void testsecurityGroupNamesVarArgsStatic() {
NovaTemplateOptions options = securityGroupNames("group1", "group2");
assertEquals(options.getSecurityGroupNames(), ImmutableSet.of("group1", "group2"));
}
@Test
public void testautoAssignFloatingIpDefault() {
NovaTemplateOptions options = new NovaTemplateOptions();
assert !options.shouldAutoAssignFloatingIp();
}
@Test
public void testautoAssignFloatingIp() {
NovaTemplateOptions options = new NovaTemplateOptions().autoAssignFloatingIp(true);
assert options.shouldAutoAssignFloatingIp();
}
@Test
public void testautoAssignFloatingIpStatic() {
NovaTemplateOptions options = autoAssignFloatingIp(true);
assert options.shouldAutoAssignFloatingIp();
}
// superclass tests
@Test(expectedExceptions = IllegalArgumentException.class)
public void testinstallPrivateKeyBadFormat() {
NovaTemplateOptions options = new NovaTemplateOptions();
options.installPrivateKey("whompy");
}
@Test
public void testinstallPrivateKey() throws IOException {
NovaTemplateOptions options = new NovaTemplateOptions();
options.installPrivateKey("-----BEGIN RSA PRIVATE KEY-----");
assertEquals(options.getPrivateKey(), "-----BEGIN RSA PRIVATE KEY-----");
}
@Test
public void testNullinstallPrivateKey() {
NovaTemplateOptions options = new NovaTemplateOptions();
assertEquals(options.getPrivateKey(), null);
}
@Test
public void testinstallPrivateKeyStatic() throws IOException {
NovaTemplateOptions options = installPrivateKey("-----BEGIN RSA PRIVATE KEY-----");
assertEquals(options.getPrivateKey(), "-----BEGIN RSA PRIVATE KEY-----");
}
@Test(expectedExceptions = NullPointerException.class)
public void testinstallPrivateKeyNPE() {
installPrivateKey(null);
}
@Test(expectedExceptions = IllegalArgumentException.class)
public void testauthorizePublicKeyBadFormat() {
NovaTemplateOptions options = new NovaTemplateOptions();
options.authorizePublicKey("whompy");
}
@Test
public void testauthorizePublicKey() throws IOException {
NovaTemplateOptions options = new NovaTemplateOptions();
options.authorizePublicKey("ssh-rsa");
assertEquals(options.getPublicKey(), "ssh-rsa");
}
@Test
public void testNullauthorizePublicKey() {
NovaTemplateOptions options = new NovaTemplateOptions();
assertEquals(options.getPublicKey(), null);
}
@Test
public void testauthorizePublicKeyStatic() throws IOException {
NovaTemplateOptions options = authorizePublicKey("ssh-rsa");
assertEquals(options.getPublicKey(), "ssh-rsa");
}
@Test(expectedExceptions = NullPointerException.class)
public void testauthorizePublicKeyNPE() {
authorizePublicKey(null);
}
@Test(expectedExceptions = IllegalArgumentException.class)
public void testblockOnPortBadFormat() {
NovaTemplateOptions options = new NovaTemplateOptions();
options.blockOnPort(-1, -1);
}
@Test
public void testblockOnPort() {
NovaTemplateOptions options = new NovaTemplateOptions();
options.blockOnPort(22, 30);
assertEquals(options.getPort(), 22);
assertEquals(options.getSeconds(), 30);
}
@Test
public void testNullblockOnPort() {
NovaTemplateOptions options = new NovaTemplateOptions();
assertEquals(options.getPort(), -1);
assertEquals(options.getSeconds(), -1);
}
@Test
public void testblockOnPortStatic() {
NovaTemplateOptions options = blockOnPort(22, 30);
assertEquals(options.getPort(), 22);
assertEquals(options.getSeconds(), 30);
}
@Test(expectedExceptions = IllegalArgumentException.class)
public void testinboundPortsBadFormat() {
NovaTemplateOptions options = new NovaTemplateOptions();
options.inboundPorts(-1, -1);
}
@Test
public void testinboundPorts() {
NovaTemplateOptions options = new NovaTemplateOptions();
options.inboundPorts(22, 30);
assertEquals(options.getInboundPorts()[0], 22);
assertEquals(options.getInboundPorts()[1], 30);
}
@Test
public void testDefaultOpen22() {
NovaTemplateOptions options = new NovaTemplateOptions();
assertEquals(options.getInboundPorts()[0], 22);
}
@Test
public void testinboundPortsStatic() {
NovaTemplateOptions options = inboundPorts(22, 30);
assertEquals(options.getInboundPorts()[0], 22);
assertEquals(options.getInboundPorts()[1], 30);
}
}

View File

@ -27,6 +27,7 @@ import org.jclouds.http.HttpRequest;
import org.jclouds.http.HttpResponse; import org.jclouds.http.HttpResponse;
import org.jclouds.openstack.nova.v1_1.NovaClient; import org.jclouds.openstack.nova.v1_1.NovaClient;
import org.jclouds.openstack.nova.v1_1.internal.BaseNovaClientExpectTest; import org.jclouds.openstack.nova.v1_1.internal.BaseNovaClientExpectTest;
import org.jclouds.openstack.nova.v1_1.options.CreateServerOptions;
import org.jclouds.openstack.nova.v1_1.parse.ParseCreatedServerTest; import org.jclouds.openstack.nova.v1_1.parse.ParseCreatedServerTest;
import org.jclouds.openstack.nova.v1_1.parse.ParseServerListTest; import org.jclouds.openstack.nova.v1_1.parse.ParseServerListTest;
import org.testng.annotations.Test; import org.testng.annotations.Test;
@ -103,4 +104,30 @@ public class ServerClientExpectTest extends BaseNovaClientExpectTest {
new ParseCreatedServerTest().expected().toString()); new ParseCreatedServerTest().expected().toString());
} }
public void testCreateServerWithSecurityGroupsWhenResponseIs202() throws Exception {
HttpRequest createServer = HttpRequest
.builder()
.method("POST")
.endpoint(URI.create("https://compute.north.host/v1.1/3456/servers"))
.headers(
ImmutableMultimap.<String, String> builder().put("Accept", "application/json")
.put("X-Auth-Token", authToken).build())
.payload(payloadFromStringWithContentType(
"{\"server\":{\"name\":\"test-e92\",\"imageRef\":\"1241\",\"flavorRef\":\"100\",\"security_groups\":[{\"name\":\"group2\"},{\"name\":\"group1\"}]}}","application/json"))
.build();
HttpResponse createServerResponse = HttpResponse.builder().statusCode(202).message("HTTP/1.1 202 Accepted")
.payload(payloadFromResourceWithContentType("/new_server.json","application/json; charset=UTF-8")).build();
NovaClient clientWithNewServer = requestsSendResponses(keystoneAuthWithAccessKeyAndSecretKey,
responseWithKeystoneAccess, createServer, createServerResponse);
assertEquals(clientWithNewServer.getServerClientForZone("az-1.region-a.geo-1").createServer("test-e92", "1241",
"100", new CreateServerOptions().securityGroupNames("group1", "group2")).toString(),
new ParseCreatedServerTest().expected().toString());
}
} }

View File

@ -0,0 +1,85 @@
/**
* Licensed to jclouds, Inc. (jclouds) under one or more
* contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. jclouds licenses this file
* to you 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.v1_1.internal;
import java.net.URI;
import java.util.Properties;
import org.jclouds.compute.ComputeServiceContext;
import org.jclouds.compute.ComputeServiceContextFactory;
import org.jclouds.http.HttpRequest;
import org.jclouds.http.HttpResponse;
import org.jclouds.logging.config.NullLoggingModule;
import com.google.common.base.Function;
import com.google.common.collect.ImmutableMultimap;
import com.google.common.collect.ImmutableSet;
import com.google.inject.Module;
/**
* Base class for writing KeyStone Expect tests with the ComputeService abstraction
*
* @author Matt Stephenson
*/
public abstract class BaseNovaComputeServiceContextExpectTest<T> extends BaseNovaExpectTest<T> implements
Function<ComputeServiceContext, T> {
protected final HttpRequest listImagesDetail = HttpRequest.builder().method("GET").endpoint(
URI.create("https://compute.north.host/v1.1/3456/images/detail")).headers(
ImmutableMultimap.<String, String> builder().put("Accept", "application/json").put("X-Auth-Token",
authToken).build()).build();
protected final HttpResponse listImagesDetailResponse = HttpResponse.builder().statusCode(200).payload(
payloadFromResource("/image_list_detail.json")).build();
protected final HttpRequest listFlavorsDetail = HttpRequest.builder().method("GET").endpoint(
URI.create("https://compute.north.host/v1.1/3456/flavors/detail")).headers(
ImmutableMultimap.<String, String> builder().put("Accept", "application/json").put("X-Auth-Token",
authToken).build()).build();
protected final HttpResponse listFlavorsDetailResponse = HttpResponse.builder().statusCode(200).payload(
payloadFromResource("/flavor_list_detail.json")).build();
protected final HttpRequest listServers = HttpRequest.builder().method("GET").endpoint(
URI.create("https://compute.north.host/v1.1/3456/servers/detail")).headers(
ImmutableMultimap.<String, String> builder().put("Accept", "application/json").put("X-Auth-Token",
authToken).build()).build();
protected final HttpResponse listServersResponse = HttpResponse.builder().statusCode(200).payload(
payloadFromResource("/server_list_details.json")).build();
protected final HttpRequest listFloatingIps = HttpRequest.builder().method("GET").endpoint(
URI.create("https://compute.north.host/v1.1/3456/os-floating-ips")).headers(
ImmutableMultimap.<String, String> builder().put("Accept", "application/json").put("X-Auth-Token",
authToken).build()).build();
protected final HttpResponse listFloatingIpsResponse = HttpResponse.builder().statusCode(200).payload(
payloadFromResource("/floatingip_list.json")).build();
@Override
public T createClient(Function<HttpRequest, HttpResponse> fn, Module module, Properties props) {
return apply(createComputeServiceContext(fn, module, props));
}
private ComputeServiceContext createComputeServiceContext(Function<HttpRequest, HttpResponse> fn, Module module,
Properties props) {
return new ComputeServiceContextFactory(setupRestProperties()).createContext(provider, identity, credential,
ImmutableSet.<Module> of(new ExpectModule(fn), new NullLoggingModule(), module), props);
}
}

View File

@ -18,17 +18,8 @@
*/ */
package org.jclouds.openstack.nova.v1_1.internal; package org.jclouds.openstack.nova.v1_1.internal;
import java.util.Properties;
import org.jclouds.compute.ComputeService; import org.jclouds.compute.ComputeService;
import org.jclouds.compute.ComputeServiceContextFactory; import org.jclouds.compute.ComputeServiceContext;
import org.jclouds.http.HttpRequest;
import org.jclouds.http.HttpResponse;
import org.jclouds.logging.config.NullLoggingModule;
import com.google.common.base.Function;
import com.google.common.collect.ImmutableSet;
import com.google.inject.Module;
/** /**
* Base class for writing KeyStone Expect tests with the ComputeService * Base class for writing KeyStone Expect tests with the ComputeService
@ -36,11 +27,11 @@ import com.google.inject.Module;
* *
* @author Matt Stephenson * @author Matt Stephenson
*/ */
public class BaseNovaComputeServiceExpectTest extends BaseNovaExpectTest<ComputeService> { public class BaseNovaComputeServiceExpectTest extends BaseNovaComputeServiceContextExpectTest<ComputeService> {
@Override @Override
public ComputeService createClient(Function<HttpRequest, HttpResponse> fn, Module module, Properties props) { public ComputeService apply(ComputeServiceContext input) {
return new ComputeServiceContextFactory(setupRestProperties()).createContext(provider, identity, credential, return input.getComputeService();
ImmutableSet.<Module> of(new ExpectModule(fn), new NullLoggingModule(), module), props).getComputeService();
} }
} }