Merge pull request #394 from andreaturli/dev

issue 384: NetworkSpec changed - Adrian comments addressed
This commit is contained in:
Adrian Cole 2012-03-03 07:57:37 -08:00
commit d5a9162348
18 changed files with 1212 additions and 627 deletions

1
.gitignore vendored
View File

@ -13,3 +13,4 @@ bin/
*.iws *.iws
*.DS_STORE *.DS_STORE
TAGS TAGS
.metadata/

View File

@ -0,0 +1,98 @@
/*
* 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.virtualbox.domain;
import com.google.common.base.Objects;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* A complete specification of a "clone" node with networking setup
* and the physical machine specification.
*/
public class CloneSpec {
private final VmSpec vmSpec;
private final NetworkSpec networkSpec;
public static Builder builder() {
return new Builder();
}
public static class Builder {
private VmSpec vmSpec;
private NetworkSpec networkSpec;
public Builder vm(VmSpec vmSpec) {
this.vmSpec = vmSpec;
return this;
}
public Builder network(NetworkSpec networkSpec) {
this.networkSpec = networkSpec;
return this;
}
public CloneSpec build() {
return new CloneSpec(vmSpec, networkSpec);
}
}
public CloneSpec(VmSpec vmSpec, NetworkSpec networkSpec) {
checkNotNull(vmSpec, "vmSpec");
checkNotNull(networkSpec, "networkSpec");
this.vmSpec = vmSpec;
this.networkSpec = networkSpec;
}
public VmSpec getVmSpec() {
return vmSpec;
}
public NetworkSpec getNetworkSpec() {
return networkSpec;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o instanceof VmSpec) {
CloneSpec other = (CloneSpec) o;
return Objects.equal(vmSpec, other.vmSpec) &&
Objects.equal(networkSpec, other.networkSpec);
}
return false;
}
@Override
public int hashCode() {
return Objects.hashCode(vmSpec,networkSpec);
}
@Override
public String toString() {
return "IMachineSpec{" +
"vmSpec= " + vmSpec +
", networkSpec= " + networkSpec +
'}';
}
}

View File

@ -0,0 +1,161 @@
/**
* 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.virtualbox.domain;
import static com.google.common.base.Preconditions.checkNotNull;
import java.util.Collections;
import java.util.Set;
import org.virtualbox_4_1.NATProtocol;
import org.virtualbox_4_1.NetworkAttachmentType;
import com.google.common.base.Objects;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets;
/**
* Represents a network adapter in VirtualBox.
* <p/>
* redirectRules are the redirect rules that are applied to the network adapter.
*/
public class NetworkAdapter {
private final NetworkAttachmentType networkAttachmentType;
private final String macAddress;
private final Set<RedirectRule> redirectRules;
public NetworkAdapter(NetworkAttachmentType networkAttachmentType,
String macAddress, Set<RedirectRule> redirectRules) {
this.networkAttachmentType = checkNotNull(networkAttachmentType,
"networkAttachmentType");
this.macAddress = macAddress;
this.redirectRules = ImmutableSet.<RedirectRule>copyOf(redirectRules);
}
public static Builder builder() {
return new Builder();
}
public static class Builder {
private NetworkAttachmentType networkAttachmentType;
private String macAddress;
private Set<RedirectRule> redirectRules = Sets.newLinkedHashSet();
/**
*
* @param networkAttachmentType
* @return
*/
public Builder networkAttachmentType(
NetworkAttachmentType networkAttachmentType) {
this.networkAttachmentType = networkAttachmentType;
return this;
}
/**
*
* @param macAddress
* @return
*/
public Builder macAddress(String macAddress) {
this.macAddress = macAddress;
return this;
}
/**
* @param host
* incoming address
* @param hostPort
* @param guest
* guest address or empty string for all addresses
* @param guestPort
* @return
*/
public Builder tcpRedirectRule(String host, int hostPort, String guest,
int guestPort) {
redirectRules.add(new RedirectRule(NATProtocol.TCP, host, hostPort,
guest, guestPort));
return this;
}
/**
* @param host
* incoming address
* @param hostPort
* @param guest
* guest address or empty string for all addresses
* @param guestPort
* @return
*/
public Builder udpRedirectRule(String host, int hostPort, String guest,
int guestPort) {
redirectRules.add(new RedirectRule(NATProtocol.UDP, host, hostPort,
guest, guestPort));
return this;
}
public NetworkAdapter build() {
return new NetworkAdapter(networkAttachmentType, macAddress,
redirectRules);
}
}
public NetworkAttachmentType getNetworkAttachmentType() {
return networkAttachmentType;
}
public Set<RedirectRule> getRedirectRules() {
return Collections.unmodifiableSet(redirectRules);
}
public String getMacAddress() {
return macAddress;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o instanceof NetworkAdapter) {
NetworkAdapter other = (NetworkAdapter) o;
return Objects.equal(networkAttachmentType,
other.networkAttachmentType) &&
Objects.equal(macAddress, other.macAddress) &&
Objects.equal(redirectRules, other.redirectRules);
}
return false;
}
@Override
public int hashCode() {
return Objects.hashCode(networkAttachmentType, macAddress, redirectRules);
}
@Override
public String toString() {
return "NetworkAdapter{" + "networkAttachmentType= "+
networkAttachmentType +
"macAddress= " + macAddress +
"redirectRules= " + redirectRules +
'}';
}
}

View File

@ -0,0 +1,108 @@
/**
* 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.virtualbox.domain;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.base.Objects;
public class NetworkInterfaceCard {
private final long slot;
private final NetworkAdapter networkAdapter;
private final String hostInterfaceName;
public NetworkInterfaceCard(long slot, NetworkAdapter networkAdapter, String hostInterfaceName) {
this.slot = checkNotNull(slot, "slot");
this.networkAdapter = checkNotNull(networkAdapter, "networkAdapter");
this.hostInterfaceName = hostInterfaceName;
}
public static Builder builder() {
return new Builder();
}
public static class Builder {
private long slot;
private NetworkAdapter networkAdapter;
private String hostInterfaceName;
public Builder slot(long slot) {
this.slot = slot;
return this;
}
public Builder addNetworkAdapter(
NetworkAdapter networkAdapter) {
this.networkAdapter = networkAdapter;
return this;
}
public Builder addHostInterfaceName(
String hostInterfaceName) {
this.hostInterfaceName = hostInterfaceName;
return this;
}
public NetworkInterfaceCard build() {
return new NetworkInterfaceCard(slot, networkAdapter, hostInterfaceName);
}
}
public long getSlot() {
return slot;
}
public NetworkAdapter getNetworkAdapter() {
return networkAdapter;
}
public String getHostInterfaceName() {
return hostInterfaceName;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o instanceof NetworkInterfaceCard) {
NetworkInterfaceCard other = (NetworkInterfaceCard) o;
return Objects.equal(slot,
other.slot) &&
Objects.equal(networkAdapter, other.networkAdapter);
}
return false;
}
@Override
public int hashCode() {
return Objects.hashCode(slot, networkAdapter);
}
@Override
public String toString() {
return "NetworkInterfaceCard{" + "slot= "+
slot +
"networkAdapter= " + networkAdapter +
'}';
}
}

View File

@ -16,26 +16,26 @@
* specific language governing permissions and limitations * specific language governing permissions and limitations
* under the License. * under the License.
*/ */
package org.jclouds.virtualbox.domain; package org.jclouds.virtualbox.domain;
import com.google.common.base.Objects; import static com.google.common.base.Preconditions.checkArgument;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkNotNull;
import java.util.ArrayList;
import java.util.List;
import com.google.common.base.Objects;
import com.google.common.collect.ImmutableList;
/** /**
* Describes the network configuration for a VirtualBox machine. * Describes the network configuration for a VirtualBox machine.
*/ */
public class NetworkSpec { public class NetworkSpec {
private final Map<Long, NatAdapter> natNetworkAdapters; private final List<NetworkInterfaceCard> networkInterfaceCards;
public NetworkSpec(final Map<Long, NatAdapter> natNetworkAdapters) { public NetworkSpec(final List<NetworkInterfaceCard> networkInterfaceCards) {
this.natNetworkAdapters = checkNotNull(natNetworkAdapters, "natNetworkAdapters"); this.networkInterfaceCards = ImmutableList.copyOf(checkNotNull(networkInterfaceCards, "networkInterfaceCards"));
} }
public static Builder builder() { public static Builder builder() {
@ -44,43 +44,42 @@ public class NetworkSpec {
public static class Builder { public static class Builder {
private Map<Long, NatAdapter> natNetworkAdapters = new HashMap<Long, NatAdapter>(); private List<NetworkInterfaceCard> networkInterfaceCards = new ArrayList<NetworkInterfaceCard>();
public Builder natNetworkAdapter(int slot, NatAdapter adapter) { public Builder addNIC(long slot, NetworkInterfaceCard networkInterfaceCard) {
this.natNetworkAdapters.put((long) slot, adapter); checkArgument(slot >= 0 && slot < 4, "must be 0, 1, 2, 3: %s", slot);
NetworkInterfaceCard nic = NetworkInterfaceCard.builder().slot(slot).addNetworkAdapter(networkInterfaceCard.getNetworkAdapter()).build();
this.networkInterfaceCards.add(nic);
return this; return this;
} }
public NetworkSpec build() { public NetworkSpec build() {
return new NetworkSpec(natNetworkAdapters); return new NetworkSpec(networkInterfaceCards);
} }
} }
public List<NetworkInterfaceCard> getNetworkInterfaceCards() {
public Map<Long, NatAdapter> getNatNetworkAdapters() { return networkInterfaceCards;
return Collections.unmodifiableMap(natNetworkAdapters);
} }
@Override @Override
public boolean equals(Object o) { public boolean equals(Object o) {
if (this == o) return true; if (this == o)
return true;
if (o instanceof VmSpec) { if (o instanceof VmSpec) {
NetworkSpec other = (NetworkSpec) o; NetworkSpec other = (NetworkSpec) o;
return Objects.equal(natNetworkAdapters, other.natNetworkAdapters); return Objects.equal(networkInterfaceCards, other.networkInterfaceCards);
} }
return false; return false;
} }
@Override @Override
public int hashCode() { public int hashCode() {
return Objects.hashCode(natNetworkAdapters); return Objects.hashCode(networkInterfaceCards);
} }
@Override @Override
public String toString() { public String toString() {
return "NetworkSpec{" + return "NetworkSpec{" + "networkInterfaceCards= " + networkInterfaceCards + '}';
"natNetworkAdapters=" + natNetworkAdapters +
'}';
} }
} }

View File

@ -23,6 +23,7 @@ import static org.virtualbox_4_1.NetworkAttachmentType.Bridged;
import javax.annotation.Nullable; import javax.annotation.Nullable;
import org.jclouds.virtualbox.domain.NetworkInterfaceCard;
import org.virtualbox_4_1.IMachine; import org.virtualbox_4_1.IMachine;
import org.virtualbox_4_1.INetworkAdapter; import org.virtualbox_4_1.INetworkAdapter;
@ -33,25 +34,21 @@ import com.google.common.base.Function;
*/ */
public class AttachBridgedAdapterToMachine implements Function<IMachine, Void> { public class AttachBridgedAdapterToMachine implements Function<IMachine, Void> {
private long adapterIndex; private NetworkInterfaceCard networkInterfaceCard;
private String macAddress;
private String hostInterface;
public AttachBridgedAdapterToMachine(long adapterSlot, String macAddress,
String hostInterface) { public AttachBridgedAdapterToMachine(NetworkInterfaceCard networkInterfaceCard) {
this.adapterIndex = adapterSlot; this.networkInterfaceCard = networkInterfaceCard;
this.macAddress = macAddress;
this.hostInterface = hostInterface;
} }
@Override @Override
public Void apply(@Nullable IMachine machine) { public Void apply(@Nullable IMachine machine) {
INetworkAdapter networkAdapter = machine.getNetworkAdapter(adapterIndex); INetworkAdapter iNetworkAdapter = machine.getNetworkAdapter(networkInterfaceCard.getSlot());
networkAdapter.setAttachmentType(Bridged); iNetworkAdapter.setAttachmentType(Bridged);
networkAdapter.setAdapterType(Am79C973); iNetworkAdapter.setAdapterType(Am79C973);
networkAdapter.setMACAddress(macAddress); iNetworkAdapter.setMACAddress(networkInterfaceCard.getNetworkAdapter().getMacAddress());
networkAdapter.setBridgedInterface(hostInterface); iNetworkAdapter.setBridgedInterface(networkInterfaceCard.getHostInterfaceName());
networkAdapter.setEnabled(true); iNetworkAdapter.setEnabled(true);
machine.saveSettings(); machine.saveSettings();
return null; return null;
} }

View File

@ -23,7 +23,7 @@ import static org.virtualbox_4_1.NetworkAttachmentType.NAT;
import javax.annotation.Nullable; import javax.annotation.Nullable;
import org.jclouds.virtualbox.domain.NatAdapter; import org.jclouds.virtualbox.domain.NetworkInterfaceCard;
import org.jclouds.virtualbox.domain.RedirectRule; import org.jclouds.virtualbox.domain.RedirectRule;
import org.virtualbox_4_1.IMachine; import org.virtualbox_4_1.IMachine;
import org.virtualbox_4_1.INetworkAdapter; import org.virtualbox_4_1.INetworkAdapter;
@ -32,34 +32,32 @@ import org.virtualbox_4_1.VBoxException;
import com.google.common.base.Function; import com.google.common.base.Function;
/** /**
* @author Mattias Holmqvist * @author Mattias Holmqvist, Andrea Turli
*/ */
public class AttachNATAdapterToMachineIfNotAlreadyExists implements Function<IMachine, Void> { public class AttachNATAdapterToMachineIfNotAlreadyExists implements Function<IMachine, Void> {
private long adapterSlot; private NetworkInterfaceCard networkInterfaceCard;
private NatAdapter natAdapter;
public AttachNATAdapterToMachineIfNotAlreadyExists(long adapterSlot, NatAdapter natAdapter) { public AttachNATAdapterToMachineIfNotAlreadyExists(NetworkInterfaceCard networkInterfaceCard) {
this.adapterSlot = adapterSlot; this.networkInterfaceCard = networkInterfaceCard;
this.natAdapter = natAdapter;
} }
@Override @Override
public Void apply(@Nullable IMachine machine) { public Void apply(@Nullable IMachine machine) {
INetworkAdapter networkAdapter = machine.getNetworkAdapter(adapterSlot); INetworkAdapter iNetworkAdapter = machine.getNetworkAdapter(networkInterfaceCard.getSlot());
networkAdapter.setAttachmentType(NAT); iNetworkAdapter.setAttachmentType(NAT);
for (RedirectRule rule : natAdapter.getRedirectRules()) { for (RedirectRule rule : networkInterfaceCard.getNetworkAdapter().getRedirectRules()) {
try { try {
String ruleName = String.format("%s@%s:%s->%s:%s",rule.getProtocol(), rule.getHost(), rule.getHostPort(), String ruleName = String.format("%s@%s:%s->%s:%s",rule.getProtocol(), rule.getHost(), rule.getHostPort(),
rule.getGuest(), rule.getGuestPort()); rule.getGuest(), rule.getGuestPort());
networkAdapter.getNatDriver().addRedirect(ruleName, rule.getProtocol(), rule.getHost(), rule.getHostPort(), iNetworkAdapter.getNatDriver().addRedirect(ruleName, rule.getProtocol(), rule.getHost(), rule.getHostPort(),
rule.getGuest(), rule.getGuestPort()); rule.getGuest(), rule.getGuestPort());
} catch (VBoxException e) { } catch (VBoxException e) {
if (!e.getMessage().contains("already exists")) if (!e.getMessage().contains("already exists"))
throw e; throw e;
} }
} }
networkAdapter.setEnabled(true); iNetworkAdapter.setEnabled(true);
machine.saveSettings(); machine.saveSettings();
return null; return null;
} }

View File

@ -0,0 +1,65 @@
/**
* 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.virtualbox.functions;
import static com.google.common.base.Preconditions.checkNotNull;
import javax.annotation.Nullable;
import org.jclouds.virtualbox.domain.NetworkInterfaceCard;
import org.jclouds.virtualbox.util.MachineUtils;
import org.virtualbox_4_1.NetworkAttachmentType;
import com.google.common.base.Function;
/**
* @author Andrea Turli
*/
public class AttachNicToMachine implements Function<NetworkInterfaceCard, Void> {
private final String vmName;
private final MachineUtils machineUtils;
public AttachNicToMachine(String vmName, MachineUtils machineUtils) {
this.vmName = checkNotNull(vmName, "vmName");
this.machineUtils = checkNotNull(machineUtils, "machineUtils");
}
@Override
public Void apply(@Nullable NetworkInterfaceCard nic) {
if(hasNatAdapter(nic)) {
return machineUtils.writeLockMachineAndApply(vmName, new AttachNATAdapterToMachineIfNotAlreadyExists(nic));
} else if (hasBridgedAdapter(nic)) {
return machineUtils.writeLockMachineAndApply(vmName, new AttachBridgedAdapterToMachine(nic));
} else
return null;
}
private boolean hasNatAdapter(NetworkInterfaceCard nic) {
return nic.getNetworkAdapter().getNetworkAttachmentType()
.equals(NetworkAttachmentType.NAT);
}
private boolean hasBridgedAdapter(NetworkInterfaceCard nic) {
return nic.getNetworkAdapter().getNetworkAttachmentType()
.equals(NetworkAttachmentType.Bridged);
}
}

View File

@ -29,7 +29,10 @@ import javax.inject.Named;
import org.jclouds.compute.reference.ComputeServiceConstants; import org.jclouds.compute.reference.ComputeServiceConstants;
import org.jclouds.logging.Logger; import org.jclouds.logging.Logger;
import org.jclouds.virtualbox.config.VirtualBoxConstants; import org.jclouds.virtualbox.config.VirtualBoxConstants;
import org.jclouds.virtualbox.domain.CloneSpec;
import org.jclouds.virtualbox.domain.NetworkInterfaceCard;
import org.jclouds.virtualbox.domain.VmSpec; import org.jclouds.virtualbox.domain.VmSpec;
import org.jclouds.virtualbox.util.MachineUtils;
import org.virtualbox_4_1.CloneMode; import org.virtualbox_4_1.CloneMode;
import org.virtualbox_4_1.CloneOptions; import org.virtualbox_4_1.CloneOptions;
import org.virtualbox_4_1.IMachine; import org.virtualbox_4_1.IMachine;
@ -43,70 +46,98 @@ import com.google.common.base.Supplier;
import com.google.inject.Inject; import com.google.inject.Inject;
/** /**
* CloneAndRegisterMachineFromIMachineIfNotAlreadyExists will take care of the followings: - cloning * CloneAndRegisterMachineFromIMachineIfNotAlreadyExists will take care of the
* the master - register the clone machine - * followings: - cloning the master - register the clone machine -
* *
* @author Andrea Turli * @author Andrea Turli
*/ */
public class CloneAndRegisterMachineFromIMachineIfNotAlreadyExists implements Function<IMachine, IMachine> { public class CloneAndRegisterMachineFromIMachineIfNotAlreadyExists implements
Function<IMachine, IMachine> {
@Resource @Resource
@Named(ComputeServiceConstants.COMPUTE_LOGGER) @Named(ComputeServiceConstants.COMPUTE_LOGGER)
protected Logger logger = Logger.NULL; protected Logger logger = Logger.NULL;
private final Supplier<VirtualBoxManager> manager; private final Supplier<VirtualBoxManager> manager;
private final String workingDir; private final String workingDir;
private final VmSpec vmSpec; private final CloneSpec cloneSpec;
private final boolean isLinkedClone; private final boolean isLinkedClone;
private final MachineUtils machineUtils;
@Inject @Inject
public CloneAndRegisterMachineFromIMachineIfNotAlreadyExists(Supplier<VirtualBoxManager> manager, public CloneAndRegisterMachineFromIMachineIfNotAlreadyExists(
@Named(VirtualBoxConstants.VIRTUALBOX_WORKINGDIR) String workingDir, VmSpec vmSpec, boolean isLinkedClone) { Supplier<VirtualBoxManager> manager,
this.manager = manager; @Named(VirtualBoxConstants.VIRTUALBOX_WORKINGDIR) String workingDir,
this.workingDir = workingDir; CloneSpec cloneSpec, boolean isLinkedClone, MachineUtils machineUtils) {
this.vmSpec = vmSpec; this.manager = manager;
this.isLinkedClone = isLinkedClone; this.workingDir = workingDir;
} this.cloneSpec = cloneSpec;
this.isLinkedClone = isLinkedClone;
this.machineUtils = machineUtils;
}
@Override @Override
public IMachine apply(@Nullable IMachine master) { public IMachine apply(@Nullable IMachine master) {
try { VmSpec vmSpec = cloneSpec.getVmSpec();
manager.get().getVBox().findMachine(vmSpec.getVmName()); try {
throw new IllegalStateException("Machine " + vmSpec.getVmName() + " is already registered."); manager.get().getVBox().findMachine(vmSpec.getVmName());
} catch (VBoxException e) { throw new IllegalStateException("Machine " + vmSpec.getVmName()
if (machineNotFoundException(e)) + " is already registered.");
return cloneMachine(vmSpec, master); } catch (VBoxException e) {
else if (machineNotFoundException(e))
throw e; return cloneMachine(vmSpec, master);
} else
} throw e;
}
}
private boolean machineNotFoundException(VBoxException e) { private boolean machineNotFoundException(VBoxException e) {
return e.getMessage().contains("VirtualBox error: Could not find a registered machine named ") || return e.getMessage().contains(
e.getMessage().contains("Could not find a registered machine with UUID {"); "VirtualBox error: Could not find a registered machine named ")
} || e.getMessage().contains(
"Could not find a registered machine with UUID {");
}
private IMachine cloneMachine(VmSpec vmSpec, IMachine master) { private IMachine cloneMachine(VmSpec vmSpec, IMachine master) {
String settingsFile = manager.get().getVBox().composeMachineFilename(vmSpec.getVmName(), workingDir); String settingsFile = manager.get().getVBox()
IMachine clonedMachine = manager.get().getVBox().createMachine(settingsFile, vmSpec.getVmName(), vmSpec.getOsTypeId(), .composeMachineFilename(vmSpec.getVmName(), workingDir);
vmSpec.getVmId(), vmSpec.isForceOverwrite()); IMachine clonedMachine = manager
List<CloneOptions> options = new ArrayList<CloneOptions>(); .get()
if (isLinkedClone) .getVBox()
options.add(CloneOptions.Link); .createMachine(settingsFile, vmSpec.getVmName(),
vmSpec.getOsTypeId(), vmSpec.getVmId(),
vmSpec.isForceOverwrite());
List<CloneOptions> options = new ArrayList<CloneOptions>();
if (isLinkedClone)
options.add(CloneOptions.Link);
// TODO snapshot name // TODO snapshot name
ISnapshot currentSnapshot = new TakeSnapshotIfNotAlreadyAttached(manager, "snapshotName", "snapshotDesc") ISnapshot currentSnapshot = new TakeSnapshotIfNotAlreadyAttached(
.apply(master); manager, "snapshotName", "snapshotDesc").apply(master);
// clone // clone
IProgress progress = currentSnapshot.getMachine().cloneTo(clonedMachine, CloneMode.MachineState, options); IProgress progress = currentSnapshot.getMachine().cloneTo(
clonedMachine, CloneMode.MachineState, options);
if (progress.getCompleted()) if (progress.getCompleted())
logger.debug("clone done"); logger.debug("clone done");
// registering
manager.get().getVBox().registerMachine(clonedMachine);
return clonedMachine;
}
// registering
manager.get().getVBox().registerMachine(clonedMachine);
// Bridged#
for (NetworkInterfaceCard nic : cloneSpec.getNetworkSpec().getNetworkInterfaceCards()){
ensureBridgedNetworkingIsAppliedToMachine(clonedMachine.getName(), nic);
}
return clonedMachine;
}
private void ensureBridgedNetworkingIsAppliedToMachine(String vmName,
NetworkInterfaceCard nic) {
machineUtils.writeLockMachineAndApply(vmName,
new AttachBridgedAdapterToMachine(nic));
}
} }

View File

@ -47,11 +47,13 @@ import org.virtualbox_4_1.IProgress;
import org.virtualbox_4_1.ISession; import org.virtualbox_4_1.ISession;
import org.virtualbox_4_1.LockType; import org.virtualbox_4_1.LockType;
import org.virtualbox_4_1.VirtualBoxManager; import org.virtualbox_4_1.VirtualBoxManager;
import org.virtualbox_4_1.jaxws.MachineState;
import com.google.common.base.Function; import com.google.common.base.Function;
import com.google.common.base.Predicate; import com.google.common.base.Predicate;
import com.google.common.base.Splitter; import com.google.common.base.Splitter;
import com.google.common.base.Supplier; import com.google.common.base.Supplier;
import com.google.common.base.Throwables;
import com.google.common.cache.LoadingCache; import com.google.common.cache.LoadingCache;
import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.ListenableFuture;
@ -137,8 +139,14 @@ public class CreateAndInstallVm implements Function<MasterSpec, IMachine> {
} }
} }
/**
* ensureMachineHasPowerDown needs to have this delay just to ensure that the machine is completely powered off
*
* @param vmName
*/
private void ensureMachineHasPowerDown(String vmName) { private void ensureMachineHasPowerDown(String vmName) {
machineUtils.lockSessionOnMachineAndApply(vmName, LockType.Shared, new Function<ISession, Void>() { while(!manager.get().getVBox().findMachine(vmName).getState().equals(MachineState.POWERED_OFF)) {
machineUtils.lockSessionOnMachineAndApply(vmName, LockType.Shared, new Function<ISession, Void>() {
@Override @Override
public Void apply(ISession session) { public Void apply(ISession session) {
IProgress powerDownProgress = session.getConsole().powerDown(); IProgress powerDownProgress = session.getConsole().powerDown();
@ -146,6 +154,12 @@ public class CreateAndInstallVm implements Function<MasterSpec, IMachine> {
return null; return null;
} }
}); });
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Throwables.propagate(e);
}
}
} }
private void ensureMachineIsLaunched(String vmName) { private void ensureMachineIsLaunched(String vmName) {

View File

@ -19,25 +19,39 @@
package org.jclouds.virtualbox.functions; package org.jclouds.virtualbox.functions;
import com.google.common.base.Function; import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.base.Supplier;
import org.jclouds.compute.reference.ComputeServiceConstants; import java.io.File;
import org.jclouds.logging.Logger; import java.util.Set;
import org.jclouds.virtualbox.config.VirtualBoxConstants;
import org.jclouds.virtualbox.domain.*;
import org.jclouds.virtualbox.util.MachineUtils;
import org.virtualbox_4_1.*;
import javax.annotation.Nullable; import javax.annotation.Nullable;
import javax.annotation.Resource; import javax.annotation.Resource;
import javax.inject.Inject; import javax.inject.Inject;
import javax.inject.Named; import javax.inject.Named;
import javax.inject.Singleton; import javax.inject.Singleton;
import java.io.File;
import java.util.Map;
import java.util.Set;
import static com.google.common.base.Preconditions.checkNotNull; import org.jclouds.compute.reference.ComputeServiceConstants;
import org.jclouds.logging.Logger;
import org.jclouds.virtualbox.config.VirtualBoxConstants;
import org.jclouds.virtualbox.domain.DeviceDetails;
import org.jclouds.virtualbox.domain.HardDisk;
import org.jclouds.virtualbox.domain.IsoImage;
import org.jclouds.virtualbox.domain.MasterSpec;
import org.jclouds.virtualbox.domain.NetworkInterfaceCard;
import org.jclouds.virtualbox.domain.NetworkSpec;
import org.jclouds.virtualbox.domain.StorageController;
import org.jclouds.virtualbox.domain.VmSpec;
import org.jclouds.virtualbox.util.MachineUtils;
import org.virtualbox_4_1.AccessMode;
import org.virtualbox_4_1.DeviceType;
import org.virtualbox_4_1.IMachine;
import org.virtualbox_4_1.IMedium;
import org.virtualbox_4_1.IVirtualBox;
import org.virtualbox_4_1.VBoxException;
import org.virtualbox_4_1.VirtualBoxManager;
import com.google.common.base.Function;
import com.google.common.base.Supplier;
/** /**
* @author Mattias Holmqvist * @author Mattias Holmqvist
@ -112,12 +126,9 @@ public class CreateAndRegisterMachineFromIsoIfNotAlreadyExists implements Functi
setupHardDisksForController(vmName, controller); setupHardDisksForController(vmName, controller);
setupDvdsForController(vmSpec, vmName, controller); setupDvdsForController(vmSpec, vmName, controller);
// NAT // Networking
Map<Long, NatAdapter> natNetworkAdapters = networkSpec.getNatNetworkAdapters(); for (NetworkInterfaceCard networkInterfaceCard : networkSpec.getNetworkInterfaceCards()) {
for (Map.Entry<Long, NatAdapter> natAdapterAndSlot : natNetworkAdapters.entrySet()) { new AttachNicToMachine(vmName, machineUtils).apply(networkInterfaceCard);
long slotId = natAdapterAndSlot.getKey();
NatAdapter natAdapter = natAdapterAndSlot.getValue();
ensureNATNetworkingIsAppliedToMachine(vmName, slotId, natAdapter);
} }
} }
@ -163,10 +174,6 @@ public class CreateAndRegisterMachineFromIsoIfNotAlreadyExists implements Functi
machineUtils.writeLockMachineAndApply(vmName, new ApplyMemoryToMachine(memorySize)); machineUtils.writeLockMachineAndApply(vmName, new ApplyMemoryToMachine(memorySize));
} }
private void ensureNATNetworkingIsAppliedToMachine(String vmName, long slotId, NatAdapter natAdapter) {
machineUtils.writeLockMachineAndApply(vmName, new AttachNATAdapterToMachineIfNotAlreadyExists(slotId, natAdapter));
}
public void ensureMachineHasStorageControllerNamed(String vmName, StorageController storageController) { public void ensureMachineHasStorageControllerNamed(String vmName, StorageController storageController) {
machineUtils.writeLockMachineAndApply(vmName, new AddIDEControllerIfNotExists(checkNotNull( machineUtils.writeLockMachineAndApply(vmName, new AddIDEControllerIfNotExists(checkNotNull(
storageController, "storageController"))); storageController, "storageController")));

View File

@ -18,18 +18,19 @@
*/ */
package org.jclouds.virtualbox.functions; package org.jclouds.virtualbox.functions;
import static org.easymock.EasyMock.createMock;
import static org.easymock.EasyMock.expect; import static org.easymock.EasyMock.expect;
import static org.easymock.classextension.EasyMock.createMock; import static org.easymock.EasyMock.replay;
import static org.easymock.classextension.EasyMock.createNiceMock; import static org.easymock.EasyMock.verify;
import static org.easymock.classextension.EasyMock.replay;
import static org.easymock.classextension.EasyMock.verify;
import static org.virtualbox_4_1.NetworkAdapterType.Am79C973; import static org.virtualbox_4_1.NetworkAdapterType.Am79C973;
import static org.virtualbox_4_1.NetworkAttachmentType.Bridged; import static org.virtualbox_4_1.NetworkAttachmentType.Bridged;
import org.jclouds.virtualbox.domain.NetworkAdapter;
import org.jclouds.virtualbox.domain.NetworkInterfaceCard;
import org.testng.annotations.Test; import org.testng.annotations.Test;
import org.virtualbox_4_1.IMachine; import org.virtualbox_4_1.IMachine;
import org.virtualbox_4_1.INetworkAdapter; import org.virtualbox_4_1.INetworkAdapter;
import org.virtualbox_4_1.VBoxException; import org.virtualbox_4_1.NetworkAttachmentType;
/** /**
* @author Andrea Turli * @author Andrea Turli
@ -37,51 +38,32 @@ import org.virtualbox_4_1.VBoxException;
@Test(groups = "unit", testName = "AttachBridgedAdapterToMachineTest") @Test(groups = "unit", testName = "AttachBridgedAdapterToMachineTest")
public class AttachBridgedAdapterToMachineTest { public class AttachBridgedAdapterToMachineTest {
private String macAddress; private String macAddress;
private String hostInterface; private String hostInterface;
@Test @Test
public void testApplyNetworkingToNonExistingAdapter() throws Exception { public void testApplyNetworkingToNonExistingAdapter() throws Exception {
Long adapterId = 0l; Long adapterId = 0l;
IMachine machine = createMock(IMachine.class); IMachine machine = createMock(IMachine.class);
INetworkAdapter networkAdapter = createMock(INetworkAdapter.class); INetworkAdapter iNetworkAdapter = createMock(INetworkAdapter.class);
expect(machine.getNetworkAdapter(adapterId)).andReturn(networkAdapter); expect(machine.getNetworkAdapter(adapterId)).andReturn(iNetworkAdapter);
networkAdapter.setAttachmentType(Bridged); iNetworkAdapter.setAttachmentType(Bridged);
networkAdapter.setAdapterType(Am79C973); iNetworkAdapter.setAdapterType(Am79C973);
networkAdapter.setMACAddress(macAddress); iNetworkAdapter.setMACAddress(macAddress);
networkAdapter.setBridgedInterface(hostInterface); iNetworkAdapter.setBridgedInterface(hostInterface);
networkAdapter.setEnabled(true); iNetworkAdapter.setEnabled(true);
machine.saveSettings(); machine.saveSettings();
replay(machine, networkAdapter); replay(machine, iNetworkAdapter);
NetworkAdapter networkAdapter = NetworkAdapter.builder()
.networkAttachmentType(NetworkAttachmentType.Bridged).build();
NetworkInterfaceCard networkInterfaceCard = NetworkInterfaceCard
.builder().addNetworkAdapter(networkAdapter).build();
new AttachBridgedAdapterToMachine(adapterId, macAddress, hostInterface) new AttachBridgedAdapterToMachine(networkInterfaceCard).apply(machine);
.apply(machine);
verify(machine, networkAdapter); verify(machine, iNetworkAdapter);
} }
@Test(expectedExceptions = VBoxException.class)
public void testRethrowInvalidAdapterSlotException() throws Exception {
Long adapterId = 30l;
IMachine machine = createMock(IMachine.class);
INetworkAdapter networkAdapter = createMock(INetworkAdapter.class);
String error = "VirtualBox error: Argument slot is invalid "
+ "(must be slot < RT_ELEMENTS(mNetworkAdapters)) (0x80070057)";
VBoxException invalidSlotException = new VBoxException(
createNiceMock(Throwable.class), error);
expect(machine.getNetworkAdapter(adapterId)).andThrow(
invalidSlotException);
replay(machine, networkAdapter);
new AttachBridgedAdapterToMachine(adapterId, macAddress, hostInterface)
.apply(machine);
verify(machine, networkAdapter);
}
} }

View File

@ -28,85 +28,108 @@ import static org.easymock.EasyMock.verify;
import static org.virtualbox_4_1.NATProtocol.TCP; import static org.virtualbox_4_1.NATProtocol.TCP;
import static org.virtualbox_4_1.NetworkAttachmentType.NAT; import static org.virtualbox_4_1.NetworkAttachmentType.NAT;
import org.jclouds.virtualbox.domain.NatAdapter; import org.jclouds.virtualbox.domain.NetworkAdapter;
import org.jclouds.virtualbox.domain.NetworkInterfaceCard;
import org.testng.annotations.Test; import org.testng.annotations.Test;
import org.virtualbox_4_1.IMachine; import org.virtualbox_4_1.IMachine;
import org.virtualbox_4_1.INATEngine; import org.virtualbox_4_1.INATEngine;
import org.virtualbox_4_1.INetworkAdapter; import org.virtualbox_4_1.INetworkAdapter;
import org.virtualbox_4_1.NetworkAttachmentType;
import org.virtualbox_4_1.VBoxException; import org.virtualbox_4_1.VBoxException;
/** /**
* @author Mattias Holmqvist * @author Mattias Holmqvist, Andrea Turli
*/ */
@Test(groups = "unit", testName = "AttachNATAdapterToMachineIfNotAlreadyExistsTest") @Test(groups = "unit", testName = "AttachNATAdapterToMachineIfNotAlreadyExistsTest")
public class AttachNATAdapterToMachineIfNotAlreadyExistsTest { public class AttachNATAdapterToMachineIfNotAlreadyExistsTest {
@Test @Test
public void testApplyNetworkingToNonExistingAdapter() throws Exception { public void testApplyNetworkingToNonExistingAdapter() throws Exception {
Long slotId = 0l; Long slotId = 0l;
IMachine machine = createMock(IMachine.class); IMachine machine = createMock(IMachine.class);
INetworkAdapter networkAdapter = createMock(INetworkAdapter.class); INetworkAdapter iNetworkAdapter = createMock(INetworkAdapter.class);
INATEngine natEngine = createMock(INATEngine.class); INATEngine natEngine = createMock(INATEngine.class);
expect(machine.getNetworkAdapter(slotId)).andReturn(networkAdapter); expect(machine.getNetworkAdapter(slotId)).andReturn(iNetworkAdapter);
networkAdapter.setAttachmentType(NAT); iNetworkAdapter.setAttachmentType(NAT);
expect(networkAdapter.getNatDriver()).andReturn(natEngine); expect(iNetworkAdapter.getNatDriver()).andReturn(natEngine);
natEngine.addRedirect("TCP@127.0.0.1:2222->:22", TCP, "127.0.0.1", 2222, "", 22); natEngine.addRedirect("TCP@127.0.0.1:2222->:22", TCP, "127.0.0.1",
networkAdapter.setEnabled(true); 2222, "", 22);
machine.saveSettings(); iNetworkAdapter.setEnabled(true);
machine.saveSettings();
replay(machine, networkAdapter, natEngine); replay(machine, iNetworkAdapter, natEngine);
NatAdapter natAdapter = NatAdapter.builder().tcpRedirectRule("127.0.0.1", 2222, "", 22).build(); NetworkAdapter networkAdapter = NetworkAdapter.builder()
new AttachNATAdapterToMachineIfNotAlreadyExists(slotId, natAdapter).apply(machine); .networkAttachmentType(NetworkAttachmentType.NAT)
.tcpRedirectRule("127.0.0.1", 2222, "", 22).build();
NetworkInterfaceCard networkInterfaceCard = NetworkInterfaceCard
.builder().addNetworkAdapter(networkAdapter).build();
verify(machine, networkAdapter, natEngine); new AttachNATAdapterToMachineIfNotAlreadyExists(networkInterfaceCard)
} .apply(machine);
@Test verify(machine, iNetworkAdapter, natEngine);
public void testApplySkipsWhenAlreadyExists() throws Exception { }
Long slotId = 0l;
IMachine machine = createMock(IMachine.class);
INetworkAdapter networkAdapter = createMock(INetworkAdapter.class);
INATEngine natEngine = createMock(INATEngine.class);
expect(machine.getNetworkAdapter(slotId)).andReturn(networkAdapter); @Test
networkAdapter.setAttachmentType(NAT); public void testApplySkipsWhenAlreadyExists() throws Exception {
expect(networkAdapter.getNatDriver()).andReturn(natEngine); Long slotId = 0l;
IMachine machine = createMock(IMachine.class);
INetworkAdapter iNetworkAdapter = createMock(INetworkAdapter.class);
INATEngine natEngine = createMock(INATEngine.class);
natEngine.addRedirect("TCP@127.0.0.1:2222->:22", TCP, "127.0.0.1", 2222, "", 22); expect(machine.getNetworkAdapter(slotId)).andReturn(iNetworkAdapter);
expectLastCall().andThrow( iNetworkAdapter.setAttachmentType(NAT);
new VBoxException(null, "VirtualBox error: A NAT rule of this name already exists (0x80070057)")); expect(iNetworkAdapter.getNatDriver()).andReturn(natEngine);
networkAdapter.setEnabled(true); natEngine.addRedirect("TCP@127.0.0.1:2222->:22", TCP, "127.0.0.1",
machine.saveSettings(); 2222, "", 22);
expectLastCall()
.andThrow(
new VBoxException(null,
"VirtualBox error: A NAT rule of this name already exists (0x80070057)"));
replay(machine, networkAdapter, natEngine); iNetworkAdapter.setEnabled(true);
NatAdapter natAdapter = NatAdapter.builder().tcpRedirectRule("127.0.0.1", 2222, "", 22).build(); machine.saveSettings();
new AttachNATAdapterToMachineIfNotAlreadyExists(slotId, natAdapter).apply(machine);
verify(machine, networkAdapter, natEngine); replay(machine, iNetworkAdapter, natEngine);
} NetworkAdapter networkAdapter = NetworkAdapter.builder()
.networkAttachmentType(NetworkAttachmentType.NAT)
.tcpRedirectRule("127.0.0.1", 2222, "", 22).build();
NetworkInterfaceCard networkInterfaceCard = NetworkInterfaceCard
.builder().addNetworkAdapter(networkAdapter).build();
new AttachNATAdapterToMachineIfNotAlreadyExists(networkInterfaceCard)
.apply(machine);
@Test(expectedExceptions = VBoxException.class) verify(machine, iNetworkAdapter, natEngine);
public void testRethrowInvalidAdapterSlotException() throws Exception { }
Long slotId = 30l;
IMachine machine = createMock(IMachine.class);
INetworkAdapter networkAdapter = createMock(INetworkAdapter.class);
INATEngine natEngine = createMock(INATEngine.class);
String error = "VirtualBox error: Argument slot is invalid " @Test(enabled=false, expectedExceptions = VBoxException.class)
+ "(must be slot < RT_ELEMENTS(mNetworkAdapters)) (0x80070057)"; public void testRethrowInvalidAdapterSlotException() throws Exception {
Long slotId = 30l;
IMachine machine = createMock(IMachine.class);
INetworkAdapter iNetworkAdapter = createMock(INetworkAdapter.class);
INATEngine natEngine = createMock(INATEngine.class);
VBoxException invalidSlotException = new VBoxException(createNiceMock(Throwable.class), error); String error = "VirtualBox error: Argument slot is invalid "
expect(machine.getNetworkAdapter(slotId)).andThrow(invalidSlotException); + "(must be slot < RT_ELEMENTS(mNetworkAdapters)) (0x80070057)";
replay(machine, networkAdapter, natEngine); VBoxException invalidSlotException = new VBoxException(
createNiceMock(Throwable.class), error);
expect(machine.getNetworkAdapter(slotId))
.andThrow(invalidSlotException);
NatAdapter natAdapter = NatAdapter.builder().tcpRedirectRule("127.0.0.1", 2222, "", 22).build(); replay(machine, iNetworkAdapter, natEngine);
new AttachNATAdapterToMachineIfNotAlreadyExists(slotId, natAdapter).apply(machine); NetworkAdapter networkAdapter = NetworkAdapter.builder()
.networkAttachmentType(NetworkAttachmentType.NAT)
.tcpRedirectRule("127.0.0.1", 2222, "", 22).build();
NetworkInterfaceCard networkInterfaceCard = NetworkInterfaceCard
.builder().addNetworkAdapter(networkAdapter).build();
new AttachNATAdapterToMachineIfNotAlreadyExists(networkInterfaceCard)
.apply(machine);
verify(machine, networkAdapter, natEngine); verify(machine, iNetworkAdapter, natEngine);
} }
} }

View File

@ -25,20 +25,21 @@ import static org.testng.Assert.assertEquals;
import org.jclouds.config.ValueOfConfigurationKeyOrNull; import org.jclouds.config.ValueOfConfigurationKeyOrNull;
import org.jclouds.virtualbox.BaseVirtualBoxClientLiveTest; import org.jclouds.virtualbox.BaseVirtualBoxClientLiveTest;
import org.jclouds.virtualbox.domain.CloneSpec;
import org.jclouds.virtualbox.domain.HardDisk; import org.jclouds.virtualbox.domain.HardDisk;
import org.jclouds.virtualbox.domain.IsoSpec; import org.jclouds.virtualbox.domain.IsoSpec;
import org.jclouds.virtualbox.domain.MasterSpec; import org.jclouds.virtualbox.domain.MasterSpec;
import org.jclouds.virtualbox.domain.NetworkAdapter;
import org.jclouds.virtualbox.domain.NetworkInterfaceCard;
import org.jclouds.virtualbox.domain.NetworkSpec; import org.jclouds.virtualbox.domain.NetworkSpec;
import org.jclouds.virtualbox.domain.StorageController; import org.jclouds.virtualbox.domain.StorageController;
import org.jclouds.virtualbox.domain.VmSpec; import org.jclouds.virtualbox.domain.VmSpec;
import org.jclouds.virtualbox.functions.CloneAndRegisterMachineFromIMachineIfNotAlreadyExists;
import org.jclouds.virtualbox.functions.CreateAndRegisterMachineFromIsoIfNotAlreadyExists;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test; import org.testng.annotations.Test;
import org.virtualbox_4_1.CleanupMode; import org.virtualbox_4_1.CleanupMode;
import org.virtualbox_4_1.IMachine; import org.virtualbox_4_1.IMachine;
import org.virtualbox_4_1.ISession; import org.virtualbox_4_1.ISession;
import org.virtualbox_4_1.NetworkAttachmentType;
import org.virtualbox_4_1.StorageBus; import org.virtualbox_4_1.StorageBus;
import com.google.common.base.CaseFormat; import com.google.common.base.CaseFormat;
@ -51,93 +52,105 @@ import com.google.inject.Injector;
*/ */
@Test(groups = "live", singleThreaded = true, testName = "CloneAndRegisterMachineFromIsoIfNotAlreadyExistsLiveTest") @Test(groups = "live", singleThreaded = true, testName = "CloneAndRegisterMachineFromIsoIfNotAlreadyExistsLiveTest")
public class CloneAndRegisterMachineFromIsoIfNotAlreadyExistsLiveTest extends public class CloneAndRegisterMachineFromIsoIfNotAlreadyExistsLiveTest extends
BaseVirtualBoxClientLiveTest { BaseVirtualBoxClientLiveTest {
private static final boolean IS_LINKED_CLONE = true; private static final boolean IS_LINKED_CLONE = true;
private VmSpec clonedVmSpec; private CloneSpec cloneSpec;
private MasterSpec sourceMachineSpec; private MasterSpec sourceMachineSpec;
private CleanupMode mode = CleanupMode.Full; private CleanupMode mode = CleanupMode.Full;
@Override @Override
@BeforeClass(groups = "live") @BeforeClass(groups = "live")
public void setupClient() { public void setupClient() {
super.setupClient(); super.setupClient();
String sourceName = VIRTUALBOX_IMAGE_PREFIX String sourceName = VIRTUALBOX_IMAGE_PREFIX
+ CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN, getClass() + CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN, getClass()
.getSimpleName()); .getSimpleName());
String cloneName = VIRTUALBOX_IMAGE_PREFIX String cloneName = VIRTUALBOX_IMAGE_PREFIX
+ "Clone#" + "Clone#"
+ CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN, getClass() + CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN, getClass()
.getSimpleName()); .getSimpleName());
StorageController ideController = StorageController StorageController ideController = StorageController
.builder() .builder()
.name("IDE Controller") .name("IDE Controller")
.bus(StorageBus.IDE) .bus(StorageBus.IDE)
.attachISO(0, 0, operatingSystemIso) .attachISO(0, 0, operatingSystemIso)
.attachHardDisk( .attachHardDisk(
HardDisk.builder().diskpath(adminDisk).controllerPort(0) HardDisk.builder().diskpath(adminDisk)
.deviceSlot(1).autoDelete(true).build()) .controllerPort(0).deviceSlot(1)
.attachISO(1, 1, guestAdditionsIso).build(); .autoDelete(true).build())
.attachISO(1, 1, guestAdditionsIso).build();
VmSpec sourceVmSpec = VmSpec.builder().id(sourceName).name(sourceName) VmSpec sourceVmSpec = VmSpec.builder().id(sourceName).name(sourceName)
.osTypeId("").memoryMB(512).cleanUpMode(CleanupMode.Full) .osTypeId("").memoryMB(512).cleanUpMode(CleanupMode.Full)
.controller(ideController).forceOverwrite(true).build(); .controller(ideController).forceOverwrite(true).build();
Injector injector = context.utils().injector(); Injector injector = context.utils().injector();
Function<String, String> configProperties = injector Function<String, String> configProperties = injector
.getInstance(ValueOfConfigurationKeyOrNull.class); .getInstance(ValueOfConfigurationKeyOrNull.class);
IsoSpec isoSpec = IsoSpec IsoSpec isoSpec = IsoSpec
.builder() .builder()
.sourcePath(operatingSystemIso) .sourcePath(operatingSystemIso)
.installationScript( .installationScript(
configProperties.apply(VIRTUALBOX_INSTALLATION_KEY_SEQUENCE) configProperties.apply(
.replace("HOSTNAME", sourceVmSpec.getVmName())).build(); VIRTUALBOX_INSTALLATION_KEY_SEQUENCE).replace(
"HOSTNAME", sourceVmSpec.getVmName())).build();
NetworkSpec networkSpec = NetworkSpec.builder().build(); NetworkAdapter networkAdapter = NetworkAdapter.builder()
sourceMachineSpec = MasterSpec.builder().iso(isoSpec).vm(sourceVmSpec).network(networkSpec).build(); .networkAttachmentType(NetworkAttachmentType.Bridged).build();
NetworkInterfaceCard networkInterfaceCard = NetworkInterfaceCard
.builder().addNetworkAdapter(networkAdapter).build();
clonedVmSpec = VmSpec.builder().id(cloneName).name(cloneName) NetworkSpec networkSpec = NetworkSpec.builder()
.memoryMB(512).cleanUpMode(mode).forceOverwrite(true).build(); .addNIC(0L, networkInterfaceCard).build();
} sourceMachineSpec = MasterSpec.builder().iso(isoSpec).vm(sourceVmSpec)
.network(networkSpec).build();
@Test VmSpec clonedVmSpec = VmSpec.builder().id(cloneName).name(cloneName)
public void testCloneMachineFromAnotherMachine() throws Exception { .memoryMB(512).cleanUpMode(mode).forceOverwrite(true).build();
try {
IMachine source = getSourceNode();
if (source.getCurrentSnapshot() != null) { cloneSpec = CloneSpec.builder().vm(clonedVmSpec).network(networkSpec)
ISession session = manager.get().openMachineSession(source); .build();
session.getConsole().deleteSnapshot(
source.getCurrentSnapshot().getId());
session.unlockMachine();
}
IMachine clone = new CloneAndRegisterMachineFromIMachineIfNotAlreadyExists( }
manager, workingDir, clonedVmSpec, IS_LINKED_CLONE)
.apply(source);
assertEquals(clone.getName(), clonedVmSpec.getVmName());
} finally {
for (VmSpec spec : ImmutableSet.of(clonedVmSpec,
sourceMachineSpec.getVmSpec()))
undoVm(spec);
}
} @Test
public void testCloneMachineFromAnotherMachine() throws Exception {
try {
IMachine source = getSourceNode();
private IMachine getSourceNode() { if (source.getCurrentSnapshot() != null) {
try { ISession session = manager.get().openMachineSession(source);
Injector injector = context.utils().injector(); session.getConsole().deleteSnapshot(
return injector.getInstance( source.getCurrentSnapshot().getId());
CreateAndRegisterMachineFromIsoIfNotAlreadyExists.class).apply( session.unlockMachine();
sourceMachineSpec); }
} catch (IllegalStateException e) {
// already created IMachine clone = new CloneAndRegisterMachineFromIMachineIfNotAlreadyExists(
return manager.get().getVBox() manager, workingDir, cloneSpec, IS_LINKED_CLONE,
.findMachine(sourceMachineSpec.getVmSpec().getVmId()); machineUtils).apply(source);
} assertEquals(clone.getName(), cloneSpec.getVmSpec().getVmName());
} } finally {
for (VmSpec spec : ImmutableSet.of(cloneSpec.getVmSpec(),
sourceMachineSpec.getVmSpec()))
undoVm(spec);
}
}
private IMachine getSourceNode() {
try {
Injector injector = context.utils().injector();
return injector.getInstance(
CreateAndRegisterMachineFromIsoIfNotAlreadyExists.class)
.apply(sourceMachineSpec);
} catch (IllegalStateException e) {
// already created
return manager.get().getVBox()
.findMachine(sourceMachineSpec.getVmSpec().getVmId());
}
}
} }

View File

@ -45,7 +45,8 @@ import org.jclouds.virtualbox.domain.ExecutionType;
import org.jclouds.virtualbox.domain.HardDisk; import org.jclouds.virtualbox.domain.HardDisk;
import org.jclouds.virtualbox.domain.IsoSpec; import org.jclouds.virtualbox.domain.IsoSpec;
import org.jclouds.virtualbox.domain.MasterSpec; import org.jclouds.virtualbox.domain.MasterSpec;
import org.jclouds.virtualbox.domain.NatAdapter; import org.jclouds.virtualbox.domain.NetworkAdapter;
import org.jclouds.virtualbox.domain.NetworkInterfaceCard;
import org.jclouds.virtualbox.domain.NetworkSpec; import org.jclouds.virtualbox.domain.NetworkSpec;
import org.jclouds.virtualbox.domain.StorageController; import org.jclouds.virtualbox.domain.StorageController;
import org.jclouds.virtualbox.domain.VmSpec; import org.jclouds.virtualbox.domain.VmSpec;
@ -58,12 +59,15 @@ import org.virtualbox_4_1.IMachine;
import org.virtualbox_4_1.IProgress; import org.virtualbox_4_1.IProgress;
import org.virtualbox_4_1.ISession; import org.virtualbox_4_1.ISession;
import org.virtualbox_4_1.LockType; import org.virtualbox_4_1.LockType;
import org.virtualbox_4_1.NetworkAttachmentType;
import org.virtualbox_4_1.StorageBus; import org.virtualbox_4_1.StorageBus;
import org.virtualbox_4_1.jaxws.MachineState;
import com.google.common.base.CaseFormat; import com.google.common.base.CaseFormat;
import com.google.common.base.Function; import com.google.common.base.Function;
import com.google.common.base.Predicate; import com.google.common.base.Predicate;
import com.google.common.base.Splitter; import com.google.common.base.Splitter;
import com.google.common.base.Throwables;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables; import com.google.common.collect.Iterables;
import com.google.inject.Guice; import com.google.inject.Guice;
@ -75,134 +79,166 @@ import com.google.inject.Injector;
@Test(groups = "live", singleThreaded = true, testName = "CreateAndInstallVmLiveTest") @Test(groups = "live", singleThreaded = true, testName = "CreateAndInstallVmLiveTest")
public class CreateAndInstallVmLiveTest extends BaseVirtualBoxClientLiveTest { public class CreateAndInstallVmLiveTest extends BaseVirtualBoxClientLiveTest {
Map<OsFamily, Map<String, String>> map = new BaseComputeServiceContextModule() { Map<OsFamily, Map<String, String>> map = new BaseComputeServiceContextModule() {
}.provideOsVersionMap(new ComputeServiceConstants.ReferenceData(), Guice }.provideOsVersionMap(new ComputeServiceConstants.ReferenceData(), Guice
.createInjector(new GsonModule()).getInstance(Json.class)); .createInjector(new GsonModule()).getInstance(Json.class));
private VmSpec vmSpecification; private VmSpec vmSpecification;
private MasterSpec masterSpec; private MasterSpec masterSpec;
private Injector injector; private Injector injector;
private Function<IMachine, SshClient> sshClientForIMachine; private Function<IMachine, SshClient> sshClientForIMachine;
private Predicate<SshClient> sshResponds; private Predicate<SshClient> sshResponds;
@Override
@BeforeClass(groups = "live")
public void setupClient() {
super.setupClient();
String vmName = VIRTUALBOX_IMAGE_PREFIX
+ CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN, getClass()
.getSimpleName());
@Override HardDisk hardDisk = HardDisk.builder().diskpath(adminDisk)
@BeforeClass(groups = "live") .autoDelete(true).controllerPort(0).deviceSlot(1).build();
public void setupClient() { StorageController ideController = StorageController.builder()
super.setupClient(); .name("IDE Controller").bus(StorageBus.IDE)
String vmName = VIRTUALBOX_IMAGE_PREFIX .attachISO(0, 0, operatingSystemIso).attachHardDisk(hardDisk)
+ CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN, getClass() .attachISO(1, 1, guestAdditionsIso).build();
.getSimpleName()); vmSpecification = VmSpec.builder().id(vmName).name(vmName)
.memoryMB(512).osTypeId("").controller(ideController)
.forceOverwrite(true).cleanUpMode(CleanupMode.Full).build();
HardDisk hardDisk = HardDisk.builder().diskpath(adminDisk).autoDelete(true) injector = context.utils().injector();
.controllerPort(0).deviceSlot(1).build(); Function<String, String> configProperties = injector
StorageController ideController = StorageController.builder().name("IDE Controller").bus(StorageBus.IDE) .getInstance(ValueOfConfigurationKeyOrNull.class);
.attachISO(0, 0, operatingSystemIso)
.attachHardDisk(hardDisk)
.attachISO(1, 1, guestAdditionsIso).build();
vmSpecification = VmSpec.builder().id(vmName).name(vmName).memoryMB(512).osTypeId("")
.controller(ideController)
.forceOverwrite(true)
.cleanUpMode(CleanupMode.Full).build();
injector = context.utils().injector(); NetworkAdapter networkAdapter = NetworkAdapter.builder()
Function<String, String> configProperties = injector .networkAttachmentType(NetworkAttachmentType.NAT)
.getInstance(ValueOfConfigurationKeyOrNull.class); .tcpRedirectRule("127.0.0.1", 2222, "", 22).build();
NetworkInterfaceCard networkInterfaceCard = NetworkInterfaceCard
.builder().addNetworkAdapter(networkAdapter).build();
masterSpec = MasterSpec.builder().vm(vmSpecification) NetworkSpec networkSpec = NetworkSpec.builder()
.iso(IsoSpec.builder() .addNIC(0L, networkInterfaceCard).build();
.sourcePath(operatingSystemIso)
.installationScript(configProperties
.apply(VIRTUALBOX_INSTALLATION_KEY_SEQUENCE)
.replace("HOSTNAME", vmSpecification.getVmName()))
.build())
.network(NetworkSpec.builder()
.natNetworkAdapter(0, NatAdapter.builder().tcpRedirectRule("127.0.0.1", 2222, "", 22).build())
.build()).build();
undoVm(vmSpecification); masterSpec = MasterSpec
} .builder()
.vm(vmSpecification)
.iso(IsoSpec
.builder()
.sourcePath(operatingSystemIso)
.installationScript(
configProperties.apply(
VIRTUALBOX_INSTALLATION_KEY_SEQUENCE)
.replace("HOSTNAME",
vmSpecification.getVmName()))
.build()).network(networkSpec).build();
public void testCreateImageMachineFromIso() throws Exception { undoVm(vmSpecification);
IMachine imageMachine = getVmWithGuestAdditionsInstalled(); }
IMachineToImage iMachineToImage = new IMachineToImage(manager, map); public void testCreateImageMachineFromIso() throws Exception {
Image newImage = iMachineToImage.apply(imageMachine); IMachine imageMachine = getVmWithGuestAdditionsInstalled();
// TODO add the description to the cache of the images or serialize to
// YAML the image desc
Set<? extends Image> images = context.getComputeService().listImages();
Iterable<String> imageIds = transform(images, extractId());
assertTrue(any(imageIds, equalTo(newImage.getId())));
}
@Test IMachineToImage iMachineToImage = new IMachineToImage(manager, map);
public void testGuestAdditionsAreInstalled() throws Exception { Image newImage = iMachineToImage.apply(imageMachine);
try { // TODO add the description to the cache of the images or serialize to
IMachine machine = getVmWithGuestAdditionsInstalled(); // YAML the image desc
Set<? extends Image> images = context.getComputeService().listImages();
Iterable<String> imageIds = transform(images, extractId());
assertTrue(any(imageIds, equalTo(newImage.getId())));
}
machineUtils.applyForMachine(machine.getName(), new LaunchMachineIfNotAlreadyRunning(manager.get(), ExecutionType.GUI, "")); @Test
sshClientForIMachine = injector.getInstance(IMachineToSshClient.class); public void testGuestAdditionsAreInstalled() throws Exception {
SshClient client = sshClientForIMachine.apply(machine); try {
IMachine machine = getVmWithGuestAdditionsInstalled();
sshResponds = injector.getInstance(SshResponds.class); machineUtils.applyForMachine(machine.getName(),
checkState(sshResponds.apply(client), "timed out waiting for guest %s to be accessible via ssh", machine.getName()); new LaunchMachineIfNotAlreadyRunning(manager.get(),
ExecutionType.GUI, ""));
sshClientForIMachine = injector
.getInstance(IMachineToSshClient.class);
SshClient client = sshClientForIMachine.apply(machine);
assertTrue(machineUtils.lockSessionOnMachineAndApply(machine.getName(), LockType.Shared, new Function<ISession, Boolean>() { sshResponds = injector.getInstance(SshResponds.class);
@Override checkState(sshResponds.apply(client),
public Boolean apply(ISession session) { "timed out waiting for guest %s to be accessible via ssh",
String vboxVersion = Iterables.get(Splitter.on('r').split(context.getProviderSpecificContext().getBuildVersion()), 0); machine.getName());
return session.getMachine().getGuestPropertyValue("/VirtualBox/GuestAdd/Version").equals(vboxVersion);
}
}));
} finally {
for (VmSpec spec : ImmutableSet.of(
vmSpecification)) {
ensureMachineHasPowerDown(spec.getVmName());
}
}
}
private Function<Image, String> extractId() { assertTrue(machineUtils.lockSessionOnMachineAndApply(
return new Function<Image, String>() { machine.getName(), LockType.Shared,
new Function<ISession, Boolean>() {
@Override
public Boolean apply(ISession session) {
String vboxVersion = Iterables
.get(Splitter
.on('r')
.split(context
.getProviderSpecificContext()
.getBuildVersion()), 0);
return session
.getMachine()
.getGuestPropertyValue(
"/VirtualBox/GuestAdd/Version")
.equals(vboxVersion);
}
}));
} finally {
for (VmSpec spec : ImmutableSet.of(vmSpecification)) {
ensureMachineHasPowerDown(spec.getVmName());
}
}
}
@Override private Function<Image, String> extractId() {
public String apply(@Nullable Image input) { return new Function<Image, String>() {
return input.getId();
}
};
}
private IMachine getVmWithGuestAdditionsInstalled() { @Override
try { public String apply(@Nullable Image input) {
Injector injector = context.utils().injector(); return input.getId();
return injector.getInstance( }
CreateAndInstallVm.class).apply( };
masterSpec); }
} catch (IllegalStateException e) {
// already created
return manager.get().getVBox()
.findMachine(masterSpec.getVmSpec().getVmId());
}
}
private void ensureMachineHasPowerDown(String vmName) { private IMachine getVmWithGuestAdditionsInstalled() {
machineUtils.lockSessionOnMachineAndApply(vmName, LockType.Shared, new Function<ISession, Void>() { try {
@Override Injector injector = context.utils().injector();
public Void apply(ISession session) { return injector.getInstance(CreateAndInstallVm.class).apply(
IProgress powerDownProgress = session.getConsole().powerDown(); masterSpec);
powerDownProgress.waitForCompletion(-1); } catch (IllegalStateException e) {
return null; // already created
} return manager.get().getVBox()
}); .findMachine(masterSpec.getVmSpec().getVmId());
} }
}
@Override private void ensureMachineHasPowerDown(String vmName) {
@AfterClass(groups = "live") while (!manager.get().getVBox().findMachine(vmName).getState()
protected void tearDown() throws Exception { .equals(MachineState.POWERED_OFF)) {
for (VmSpec spec : ImmutableSet.of( machineUtils.lockSessionOnMachineAndApply(vmName, LockType.Shared,
vmSpecification)) { new Function<ISession, Void>() {
undoVm(spec); @Override
} public Void apply(ISession session) {
super.tearDown(); IProgress powerDownProgress = session.getConsole()
} .powerDown();
powerDownProgress.waitForCompletion(-1);
return null;
}
});
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Throwables.propagate(e);
}
}
}
@Override
@AfterClass(groups = "live")
protected void tearDown() throws Exception {
for (VmSpec spec : ImmutableSet.of(vmSpecification)) {
undoVm(spec);
}
super.tearDown();
}
} }

View File

@ -29,6 +29,7 @@ import org.jclouds.virtualbox.domain.*;
import org.testng.annotations.Test; import org.testng.annotations.Test;
import org.virtualbox_4_1.CleanupMode; import org.virtualbox_4_1.CleanupMode;
import org.virtualbox_4_1.IMachine; import org.virtualbox_4_1.IMachine;
import org.virtualbox_4_1.NetworkAttachmentType;
import org.virtualbox_4_1.StorageBus; import org.virtualbox_4_1.StorageBus;
import org.virtualbox_4_1.VBoxException; import org.virtualbox_4_1.VBoxException;
@ -36,87 +37,95 @@ import org.virtualbox_4_1.VBoxException;
* @author Mattias Holmqvist * @author Mattias Holmqvist
*/ */
@Test(groups = "live", singleThreaded = true, testName = "CreateAndRegisterMachineFromIsoIfNotAlreadyExistsLiveTest") @Test(groups = "live", singleThreaded = true, testName = "CreateAndRegisterMachineFromIsoIfNotAlreadyExistsLiveTest")
public class CreateAndRegisterMachineFromIsoIfNotAlreadyExistsLiveTest extends BaseVirtualBoxClientLiveTest { public class CreateAndRegisterMachineFromIsoIfNotAlreadyExistsLiveTest extends
BaseVirtualBoxClientLiveTest {
private String ideControllerName; private String ideControllerName;
private CleanupMode mode; private CleanupMode mode;
private StorageController ideController; private StorageController ideController;
@Override @Override
public void setupClient() { public void setupClient() {
super.setupClient(); super.setupClient();
ideControllerName = "IDE Controller"; ideControllerName = "IDE Controller";
mode = CleanupMode.Full; mode = CleanupMode.Full;
ideController = StorageController.builder().name(ideControllerName).bus(StorageBus.IDE) ideController = StorageController
.attachISO(0, 0, operatingSystemIso) .builder()
.attachHardDisk(HardDisk.builder().diskpath(adminDisk).controllerPort(0).deviceSlot(1).build()).attachISO(1, 1, .name(ideControllerName)
guestAdditionsIso).build(); .bus(StorageBus.IDE)
} .attachISO(0, 0, operatingSystemIso)
.attachHardDisk(
HardDisk.builder().diskpath(adminDisk)
.controllerPort(0).deviceSlot(1).build())
.attachISO(1, 1, guestAdditionsIso).build();
}
@Test @Test
public void testCreateNewMachine() throws Exception { public void testCreateNewMachine() throws Exception {
String vmName = "jclouds-test-create-1-node"; String vmName = "jclouds-test-create-1-node";
String vmId = UUID.randomUUID().toString(); String vmId = UUID.randomUUID().toString();
VmSpec vmSpec = VmSpec.builder() VmSpec vmSpec = VmSpec.builder().id(vmId).name(vmName).memoryMB(512)
.id(vmId) .controller(ideController).cleanUpMode(mode).osTypeId("Debian")
.name(vmName) .forceOverwrite(true).build();
.memoryMB(512)
.controller(ideController)
.cleanUpMode(mode)
.osTypeId("Debian")
.forceOverwrite(true).build();
MasterSpec machineSpec = MasterSpec.builder()
.iso(IsoSpec.builder()
.sourcePath(operatingSystemIso)
.installationScript("")
.build())
.vm(vmSpec)
.network(NetworkSpec.builder().build()).build();
undoVm(vmSpec);
try {
IMachine debianNode = context.utils().injector().getInstance(
CreateAndRegisterMachineFromIsoIfNotAlreadyExists.class).apply(machineSpec);
IMachine machine = manager.get().getVBox().findMachine(vmName);
assertEquals(debianNode.getName(), machine.getName());
} finally {
undoVm(vmSpec);
}
}
@Test NetworkAdapter networkAdapter = NetworkAdapter.builder()
public void testCreateNewMachineWithBadOsType() throws Exception { .networkAttachmentType(NetworkAttachmentType.NAT)
String vmName = "jclouds-test-create-2-node"; .tcpRedirectRule("127.0.0.1", 2222, "", 22).build();
String vmId = UUID.randomUUID().toString(); NetworkInterfaceCard networkInterfaceCard = NetworkInterfaceCard
.builder().addNetworkAdapter(networkAdapter).build();
VmSpec vmSpec = VmSpec.builder() NetworkSpec networkSpec = NetworkSpec.builder()
.id(vmId) .addNIC(0L, networkInterfaceCard).build();
.name(vmName).memoryMB(512).controller(ideController)
.cleanUpMode(mode).osTypeId("SomeWeirdUnknownOs").forceOverwrite(true).build();
IsoSpec isoSpec = IsoSpec.builder()
.sourcePath(operatingSystemIso)
.installationScript("")
.build();
NetworkSpec networkSpec = NetworkSpec.builder().build();
MasterSpec machineSpec = MasterSpec.builder()
.iso(isoSpec)
.vm(vmSpec)
.network(networkSpec).build();
undoVm(vmSpec);
try {
Injector injector = context.utils().injector();
injector.getInstance(CreateAndRegisterMachineFromIsoIfNotAlreadyExists.class)
.apply(machineSpec);
fail();
} catch (VBoxException e) {
ErrorCode errorCode = ErrorCode.valueOf(e);
// According to the documentation VBOX_E_OBJECT_NOT_FOUND
// if osTypeId is not found.
assertEquals(errorCode, ErrorCode.VBOX_E_OBJECT_NOT_FOUND);
} finally {
undoVm(vmSpec);
}
} MasterSpec machineSpec = MasterSpec
.builder()
.iso(IsoSpec.builder().sourcePath(operatingSystemIso)
.installationScript("").build()).vm(vmSpec)
.network(networkSpec).build();
undoVm(vmSpec);
try {
IMachine debianNode = context.utils()
.injector()
.getInstance(
CreateAndRegisterMachineFromIsoIfNotAlreadyExists.class)
.apply(machineSpec);
IMachine machine = manager.get().getVBox().findMachine(vmName);
assertEquals(debianNode.getName(), machine.getName());
} finally {
undoVm(vmSpec);
}
}
@Test
public void testCreateNewMachineWithBadOsType() throws Exception {
String vmName = "jclouds-test-create-2-node";
String vmId = UUID.randomUUID().toString();
VmSpec vmSpec = VmSpec.builder().id(vmId).name(vmName).memoryMB(512)
.controller(ideController).cleanUpMode(mode)
.osTypeId("SomeWeirdUnknownOs").forceOverwrite(true).build();
IsoSpec isoSpec = IsoSpec.builder().sourcePath(operatingSystemIso)
.installationScript("").build();
NetworkSpec networkSpec = NetworkSpec.builder().build();
MasterSpec machineSpec = MasterSpec.builder().iso(isoSpec).vm(vmSpec)
.network(networkSpec).build();
undoVm(vmSpec);
try {
Injector injector = context.utils().injector();
injector.getInstance(
CreateAndRegisterMachineFromIsoIfNotAlreadyExists.class)
.apply(machineSpec);
fail();
} catch (VBoxException e) {
ErrorCode errorCode = ErrorCode.valueOf(e);
// According to the documentation VBOX_E_OBJECT_NOT_FOUND
// if osTypeId is not found.
assertEquals(errorCode, ErrorCode.VBOX_E_OBJECT_NOT_FOUND);
} finally {
undoVm(vmSpec);
}
}
} }

View File

@ -25,14 +25,17 @@ import static org.testng.Assert.assertTrue;
import org.jclouds.config.ValueOfConfigurationKeyOrNull; import org.jclouds.config.ValueOfConfigurationKeyOrNull;
import org.jclouds.virtualbox.BaseVirtualBoxClientLiveTest; import org.jclouds.virtualbox.BaseVirtualBoxClientLiveTest;
import org.jclouds.virtualbox.domain.ExecutionType;
import org.jclouds.virtualbox.domain.HardDisk; import org.jclouds.virtualbox.domain.HardDisk;
import org.jclouds.virtualbox.domain.IsoSpec; import org.jclouds.virtualbox.domain.IsoSpec;
import org.jclouds.virtualbox.domain.MasterSpec; import org.jclouds.virtualbox.domain.MasterSpec;
import org.jclouds.virtualbox.domain.NatAdapter; import org.jclouds.virtualbox.domain.NetworkAdapter;
import org.jclouds.virtualbox.domain.NetworkInterfaceCard;
import org.jclouds.virtualbox.domain.NetworkSpec; import org.jclouds.virtualbox.domain.NetworkSpec;
import org.jclouds.virtualbox.domain.StorageController; import org.jclouds.virtualbox.domain.StorageController;
import org.jclouds.virtualbox.domain.VmSpec; import org.jclouds.virtualbox.domain.VmSpec;
import org.jclouds.virtualbox.functions.CreateAndInstallVm; import org.jclouds.virtualbox.functions.CreateAndInstallVm;
import org.jclouds.virtualbox.functions.LaunchMachineIfNotAlreadyRunning;
import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test; import org.testng.annotations.Test;
import org.virtualbox_4_1.CleanupMode; import org.virtualbox_4_1.CleanupMode;
@ -40,11 +43,11 @@ import org.virtualbox_4_1.IMachine;
import org.virtualbox_4_1.IProgress; import org.virtualbox_4_1.IProgress;
import org.virtualbox_4_1.ISession; import org.virtualbox_4_1.ISession;
import org.virtualbox_4_1.LockType; import org.virtualbox_4_1.LockType;
import org.virtualbox_4_1.NetworkAttachmentType;
import org.virtualbox_4_1.StorageBus; import org.virtualbox_4_1.StorageBus;
import com.google.common.base.CaseFormat; import com.google.common.base.CaseFormat;
import com.google.common.base.Function; import com.google.common.base.Function;
import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
import com.google.inject.Injector; import com.google.inject.Injector;
@ -53,91 +56,104 @@ import com.google.inject.Injector;
*/ */
@Test(groups = "live", singleThreaded = true, testName = "GuestAdditionsInstallerLiveTest") @Test(groups = "live", singleThreaded = true, testName = "GuestAdditionsInstallerLiveTest")
public class GuestAdditionsInstallerLiveTest extends public class GuestAdditionsInstallerLiveTest extends
BaseVirtualBoxClientLiveTest { BaseVirtualBoxClientLiveTest {
private MasterSpec sourceMachineSpec; private MasterSpec sourceMachineSpec;
@Override @Override
@BeforeClass(groups = "live") @BeforeClass(groups = "live")
public void setupClient() { public void setupClient() {
super.setupClient(); super.setupClient();
String sourceName = VIRTUALBOX_IMAGE_PREFIX String sourceName = VIRTUALBOX_IMAGE_PREFIX
+ CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN, getClass() + CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN, getClass()
.getSimpleName()); .getSimpleName());
StorageController ideController = StorageController StorageController ideController = StorageController
.builder() .builder()
.name("IDE Controller") .name("IDE Controller")
.bus(StorageBus.IDE) .bus(StorageBus.IDE)
.attachISO(0, 0, operatingSystemIso) .attachISO(0, 0, operatingSystemIso)
.attachHardDisk( .attachHardDisk(
HardDisk.builder().diskpath(adminDisk).controllerPort(0) HardDisk.builder().diskpath(adminDisk)
.deviceSlot(1).autoDelete(true).build()) .controllerPort(0).deviceSlot(1)
.attachISO(1, 1, guestAdditionsIso).build(); .autoDelete(true).build())
.attachISO(1, 1, guestAdditionsIso).build();
VmSpec sourceVmSpec = VmSpec.builder().id(sourceName).name(sourceName) VmSpec sourceVmSpec = VmSpec.builder().id(sourceName).name(sourceName)
.osTypeId("").memoryMB(512).cleanUpMode(CleanupMode.Full) .osTypeId("").memoryMB(512).cleanUpMode(CleanupMode.Full)
.controller(ideController).forceOverwrite(true).build(); .controller(ideController).forceOverwrite(true).build();
Injector injector = context.utils().injector(); Injector injector = context.utils().injector();
Function<String, String> configProperties = injector Function<String, String> configProperties = injector
.getInstance(ValueOfConfigurationKeyOrNull.class); .getInstance(ValueOfConfigurationKeyOrNull.class);
IsoSpec isoSpec = IsoSpec IsoSpec isoSpec = IsoSpec
.builder() .builder()
.sourcePath(operatingSystemIso) .sourcePath(operatingSystemIso)
.installationScript( .installationScript(
configProperties.apply(VIRTUALBOX_INSTALLATION_KEY_SEQUENCE) configProperties.apply(
.replace("HOSTNAME", sourceVmSpec.getVmName())).build(); VIRTUALBOX_INSTALLATION_KEY_SEQUENCE).replace(
"HOSTNAME", sourceVmSpec.getVmName())).build();
NetworkSpec networkSpec = //NetworkSpec.builder().build(); NetworkAdapter networkAdapter = NetworkAdapter.builder()
NetworkSpec.builder() .networkAttachmentType(NetworkAttachmentType.NAT)
.natNetworkAdapter(0, NatAdapter.builder().tcpRedirectRule("127.0.0.1", 2222, "", 22).build()) .tcpRedirectRule("127.0.0.1", 2222, "", 22).build();
.build(); NetworkInterfaceCard networkInterfaceCard = NetworkInterfaceCard
sourceMachineSpec = MasterSpec.builder().iso(isoSpec).vm(sourceVmSpec).network(networkSpec).build(); .builder().addNetworkAdapter(networkAdapter).build();
} NetworkSpec networkSpec = NetworkSpec.builder()
.addNIC(0L, networkInterfaceCard).build();
sourceMachineSpec = MasterSpec.builder().iso(isoSpec).vm(sourceVmSpec)
.network(networkSpec).build();
@Test }
public void testGuestAdditionsAreInstalled() throws Exception {
try {
IMachine machine = getVmWithGuestAdditionsInstalled();
assertTrue(machineUtils.lockSessionOnMachineAndApply(machine.getName(), LockType.Shared, new Function<ISession, Boolean>() {
@Override
public Boolean apply(ISession session) {
return session.getMachine().getGuestPropertyValue("/VirtualBox/GuestAdd/Version") != null;
}
}));
} finally {
for (VmSpec spec : ImmutableSet.of(
sourceMachineSpec.getVmSpec())) {
ensureMachineHasPowerDown(spec.getVmName());
undoVm(spec);
}
}
} @Test
public void testGuestAdditionsAreInstalled() throws Exception {
try {
IMachine machine = getVmWithGuestAdditionsInstalled();
machineUtils.applyForMachine(machine.getName(),
new LaunchMachineIfNotAlreadyRunning(manager.get(),
ExecutionType.GUI, ""));
assertTrue(machineUtils.lockSessionOnMachineAndApply(
machine.getName(), LockType.Shared,
new Function<ISession, Boolean>() {
@Override
public Boolean apply(ISession session) {
return session.getMachine().getGuestPropertyValue(
"/VirtualBox/GuestAdd/Version") != null;
}
}));
} finally {
for (VmSpec spec : ImmutableSet.of(sourceMachineSpec.getVmSpec())) {
ensureMachineHasPowerDown(spec.getVmName());
undoVm(spec);
}
}
private IMachine getVmWithGuestAdditionsInstalled() { }
try {
Injector injector = context.utils().injector();
return injector.getInstance(
CreateAndInstallVm.class).apply(
sourceMachineSpec);
} catch (IllegalStateException e) {
// already created
return manager.get().getVBox()
.findMachine(sourceMachineSpec.getVmSpec().getVmId());
}
}
private void ensureMachineHasPowerDown(String vmName) { private IMachine getVmWithGuestAdditionsInstalled() {
machineUtils.lockSessionOnMachineAndApply(vmName, LockType.Shared, new Function<ISession, Void>() { try {
@Override Injector injector = context.utils().injector();
public Void apply(ISession session) { return injector.getInstance(CreateAndInstallVm.class).apply(
IProgress powerDownProgress = session.getConsole().powerDown(); sourceMachineSpec);
powerDownProgress.waitForCompletion(-1); } catch (IllegalStateException e) {
return null; // already created
} return manager.get().getVBox()
}); .findMachine(sourceMachineSpec.getVmSpec().getVmId());
} }
}
private void ensureMachineHasPowerDown(String vmName) {
machineUtils.lockSessionOnMachineAndApply(vmName, LockType.Shared,
new Function<ISession, Void>() {
@Override
public Void apply(ISession session) {
IProgress powerDownProgress = session.getConsole()
.powerDown();
powerDownProgress.waitForCompletion(-1);
return null;
}
});
}
} }

View File

@ -16,6 +16,7 @@
* specific language governing permissions and limitations * specific language governing permissions and limitations
* under the License. * under the License.
*/ */
package org.jclouds.virtualbox.predicates; package org.jclouds.virtualbox.predicates;
import static org.jclouds.virtualbox.config.VirtualBoxConstants.VIRTUALBOX_IMAGE_PREFIX; import static org.jclouds.virtualbox.config.VirtualBoxConstants.VIRTUALBOX_IMAGE_PREFIX;
@ -23,9 +24,12 @@ import static org.jclouds.virtualbox.predicates.IMachinePredicates.isLinkedClone
import static org.testng.Assert.assertTrue; import static org.testng.Assert.assertTrue;
import org.jclouds.virtualbox.BaseVirtualBoxClientLiveTest; import org.jclouds.virtualbox.BaseVirtualBoxClientLiveTest;
import org.jclouds.virtualbox.domain.CloneSpec;
import org.jclouds.virtualbox.domain.HardDisk; import org.jclouds.virtualbox.domain.HardDisk;
import org.jclouds.virtualbox.domain.IsoSpec; import org.jclouds.virtualbox.domain.IsoSpec;
import org.jclouds.virtualbox.domain.MasterSpec; import org.jclouds.virtualbox.domain.MasterSpec;
import org.jclouds.virtualbox.domain.NetworkAdapter;
import org.jclouds.virtualbox.domain.NetworkInterfaceCard;
import org.jclouds.virtualbox.domain.NetworkSpec; import org.jclouds.virtualbox.domain.NetworkSpec;
import org.jclouds.virtualbox.domain.StorageController; import org.jclouds.virtualbox.domain.StorageController;
import org.jclouds.virtualbox.domain.VmSpec; import org.jclouds.virtualbox.domain.VmSpec;
@ -37,6 +41,7 @@ import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test; import org.testng.annotations.Test;
import org.virtualbox_4_1.CleanupMode; import org.virtualbox_4_1.CleanupMode;
import org.virtualbox_4_1.IMachine; import org.virtualbox_4_1.IMachine;
import org.virtualbox_4_1.NetworkAttachmentType;
import org.virtualbox_4_1.StorageBus; import org.virtualbox_4_1.StorageBus;
import com.google.common.base.CaseFormat; import com.google.common.base.CaseFormat;
@ -50,56 +55,78 @@ import com.google.inject.Injector;
@Test(groups = "live", singleThreaded = true, testName = "IMachinePredicatesLiveTest") @Test(groups = "live", singleThreaded = true, testName = "IMachinePredicatesLiveTest")
public class IMachinePredicatesLiveTest extends BaseVirtualBoxClientLiveTest { public class IMachinePredicatesLiveTest extends BaseVirtualBoxClientLiveTest {
private String osTypeId = ""; private String osTypeId = "";
private String ideControllerName = "IDE Controller"; private String ideControllerName = "IDE Controller";
private String cloneName; private String cloneName;
private String vmName; private String vmName;
private StorageController masterStorageController; private StorageController masterStorageController;
private MasterSpec masterMachineSpec; private MasterSpec masterMachineSpec;
private VmSpec cloneSpec; private CloneSpec cloneSpec;
@Override @Override
@BeforeClass(groups = "live") @BeforeClass(groups = "live")
public void setupClient() { public void setupClient() {
super.setupClient(); super.setupClient();
vmName = VIRTUALBOX_IMAGE_PREFIX + CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN, getClass().getSimpleName()); vmName = VIRTUALBOX_IMAGE_PREFIX
+ CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN, getClass()
.getSimpleName());
cloneName = VIRTUALBOX_IMAGE_PREFIX + "Clone#" cloneName = VIRTUALBOX_IMAGE_PREFIX
+ CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN, getClass().getSimpleName()); + "Clone#"
+ CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN, getClass()
.getSimpleName());
HardDisk hardDisk = HardDisk.builder().diskpath(adminDisk).autoDelete(true).controllerPort(0).deviceSlot(1) HardDisk hardDisk = HardDisk.builder().diskpath(adminDisk)
.build(); .autoDelete(true).controllerPort(0).deviceSlot(1).build();
masterStorageController = StorageController.builder().name(ideControllerName).bus(StorageBus.IDE).attachISO(0, 0, masterStorageController = StorageController.builder()
operatingSystemIso).attachHardDisk(hardDisk).attachISO(1, 1, guestAdditionsIso).build(); .name(ideControllerName).bus(StorageBus.IDE)
VmSpec masterSpec = VmSpec.builder().id(vmName).name(vmName).memoryMB(512).osTypeId(osTypeId).controller( .attachISO(0, 0, operatingSystemIso).attachHardDisk(hardDisk)
masterStorageController).forceOverwrite(true).cleanUpMode(CleanupMode.Full).build(); .attachISO(1, 1, guestAdditionsIso).build();
masterMachineSpec = MasterSpec.builder() VmSpec masterSpec = VmSpec.builder().id(vmName).name(vmName)
.iso(IsoSpec.builder() .memoryMB(512).osTypeId(osTypeId)
.sourcePath(operatingSystemIso) .controller(masterStorageController).forceOverwrite(true)
.installationScript("").build()) .cleanUpMode(CleanupMode.Full).build();
.vm(masterSpec) masterMachineSpec = MasterSpec
.network(NetworkSpec.builder().build()).build(); .builder()
.iso(IsoSpec.builder().sourcePath(operatingSystemIso)
.installationScript("").build()).vm(masterSpec)
.network(NetworkSpec.builder().build()).build();
cloneSpec = VmSpec.builder().id(cloneName).name(cloneName).memoryMB(512).cleanUpMode(CleanupMode.Full) NetworkAdapter networkAdapter = NetworkAdapter.builder()
.forceOverwrite(true).build(); .networkAttachmentType(NetworkAttachmentType.Bridged).build();
} NetworkInterfaceCard networkInterfaceCard = NetworkInterfaceCard
.builder().addNetworkAdapter(networkAdapter).build();
@Test NetworkSpec networkSpec = NetworkSpec.builder()
public void testLinkedClone() { .addNIC(0L, networkInterfaceCard).build();
Injector injector = context.utils().injector(); VmSpec clonedVmSpec = VmSpec.builder().id(cloneName).name(cloneName)
IMachine master = injector.getInstance(CreateAndRegisterMachineFromIsoIfNotAlreadyExists.class).apply( .memoryMB(512).cleanUpMode(CleanupMode.Full)
masterMachineSpec); .forceOverwrite(true).build();
IMachine clone = new CloneAndRegisterMachineFromIMachineIfNotAlreadyExists(manager, workingDir, cloneSpec, true)
.apply(master);
assertTrue(isLinkedClone().apply(clone)); cloneSpec = CloneSpec.builder().vm(clonedVmSpec).network(networkSpec)
} .build();
}
@BeforeMethod @Test
@AfterMethod public void testLinkedClone() {
void cleanUpVms() {
for (VmSpec spec : ImmutableSet.of(cloneSpec, masterMachineSpec.getVmSpec())) Injector injector = context.utils().injector();
this.undoVm(spec); IMachine master = injector.getInstance(
} CreateAndRegisterMachineFromIsoIfNotAlreadyExists.class).apply(
masterMachineSpec);
IMachine clone = new CloneAndRegisterMachineFromIMachineIfNotAlreadyExists(
manager, workingDir, cloneSpec, true, machineUtils)
.apply(master);
assertTrue(isLinkedClone().apply(clone));
}
@BeforeMethod
@AfterMethod
void cleanUpVms() {
for (VmSpec spec : ImmutableSet.of(cloneSpec.getVmSpec(),
masterMachineSpec.getVmSpec()))
this.undoVm(spec);
}
} }