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
*.DS_STORE
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
* under the License.
*/
package org.jclouds.virtualbox.domain;
import com.google.common.base.Objects;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import static com.google.common.base.Preconditions.checkArgument;
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.
*/
public class NetworkSpec {
private final Map<Long, NatAdapter> natNetworkAdapters;
private final List<NetworkInterfaceCard> networkInterfaceCards;
public NetworkSpec(final Map<Long, NatAdapter> natNetworkAdapters) {
this.natNetworkAdapters = checkNotNull(natNetworkAdapters, "natNetworkAdapters");
public NetworkSpec(final List<NetworkInterfaceCard> networkInterfaceCards) {
this.networkInterfaceCards = ImmutableList.copyOf(checkNotNull(networkInterfaceCards, "networkInterfaceCards"));
}
public static Builder builder() {
@ -44,43 +44,42 @@ public class NetworkSpec {
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) {
this.natNetworkAdapters.put((long) slot, adapter);
public Builder addNIC(long slot, NetworkInterfaceCard networkInterfaceCard) {
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;
}
public NetworkSpec build() {
return new NetworkSpec(natNetworkAdapters);
return new NetworkSpec(networkInterfaceCards);
}
}
public Map<Long, NatAdapter> getNatNetworkAdapters() {
return Collections.unmodifiableMap(natNetworkAdapters);
public List<NetworkInterfaceCard> getNetworkInterfaceCards() {
return networkInterfaceCards;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (this == o)
return true;
if (o instanceof VmSpec) {
NetworkSpec other = (NetworkSpec) o;
return Objects.equal(natNetworkAdapters, other.natNetworkAdapters);
return Objects.equal(networkInterfaceCards, other.networkInterfaceCards);
}
return false;
}
@Override
public int hashCode() {
return Objects.hashCode(natNetworkAdapters);
return Objects.hashCode(networkInterfaceCards);
}
@Override
public String toString() {
return "NetworkSpec{" +
"natNetworkAdapters=" + natNetworkAdapters +
'}';
return "NetworkSpec{" + "networkInterfaceCards= " + networkInterfaceCards + '}';
}
}

View File

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

View File

@ -23,7 +23,7 @@ import static org.virtualbox_4_1.NetworkAttachmentType.NAT;
import javax.annotation.Nullable;
import org.jclouds.virtualbox.domain.NatAdapter;
import org.jclouds.virtualbox.domain.NetworkInterfaceCard;
import org.jclouds.virtualbox.domain.RedirectRule;
import org.virtualbox_4_1.IMachine;
import org.virtualbox_4_1.INetworkAdapter;
@ -32,34 +32,32 @@ import org.virtualbox_4_1.VBoxException;
import com.google.common.base.Function;
/**
* @author Mattias Holmqvist
* @author Mattias Holmqvist, Andrea Turli
*/
public class AttachNATAdapterToMachineIfNotAlreadyExists implements Function<IMachine, Void> {
private long adapterSlot;
private NatAdapter natAdapter;
private NetworkInterfaceCard networkInterfaceCard;
public AttachNATAdapterToMachineIfNotAlreadyExists(long adapterSlot, NatAdapter natAdapter) {
this.adapterSlot = adapterSlot;
this.natAdapter = natAdapter;
public AttachNATAdapterToMachineIfNotAlreadyExists(NetworkInterfaceCard networkInterfaceCard) {
this.networkInterfaceCard = networkInterfaceCard;
}
@Override
public Void apply(@Nullable IMachine machine) {
INetworkAdapter networkAdapter = machine.getNetworkAdapter(adapterSlot);
networkAdapter.setAttachmentType(NAT);
for (RedirectRule rule : natAdapter.getRedirectRules()) {
INetworkAdapter iNetworkAdapter = machine.getNetworkAdapter(networkInterfaceCard.getSlot());
iNetworkAdapter.setAttachmentType(NAT);
for (RedirectRule rule : networkInterfaceCard.getNetworkAdapter().getRedirectRules()) {
try {
String ruleName = String.format("%s@%s:%s->%s:%s",rule.getProtocol(), rule.getHost(), rule.getHostPort(),
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());
} catch (VBoxException e) {
if (!e.getMessage().contains("already exists"))
throw e;
}
}
networkAdapter.setEnabled(true);
iNetworkAdapter.setEnabled(true);
machine.saveSettings();
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.logging.Logger;
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.util.MachineUtils;
import org.virtualbox_4_1.CloneMode;
import org.virtualbox_4_1.CloneOptions;
import org.virtualbox_4_1.IMachine;
@ -43,12 +46,13 @@ import com.google.common.base.Supplier;
import com.google.inject.Inject;
/**
* CloneAndRegisterMachineFromIMachineIfNotAlreadyExists will take care of the followings: - cloning
* the master - register the clone machine -
* CloneAndRegisterMachineFromIMachineIfNotAlreadyExists will take care of the
* followings: - cloning the master - register the clone machine -
*
* @author Andrea Turli
*/
public class CloneAndRegisterMachineFromIMachineIfNotAlreadyExists implements Function<IMachine, IMachine> {
public class CloneAndRegisterMachineFromIMachineIfNotAlreadyExists implements
Function<IMachine, IMachine> {
@Resource
@Named(ComputeServiceConstants.COMPUTE_LOGGER)
@ -56,23 +60,29 @@ public class CloneAndRegisterMachineFromIMachineIfNotAlreadyExists implements Fu
private final Supplier<VirtualBoxManager> manager;
private final String workingDir;
private final VmSpec vmSpec;
private final CloneSpec cloneSpec;
private final boolean isLinkedClone;
private final MachineUtils machineUtils;
@Inject
public CloneAndRegisterMachineFromIMachineIfNotAlreadyExists(Supplier<VirtualBoxManager> manager,
@Named(VirtualBoxConstants.VIRTUALBOX_WORKINGDIR) String workingDir, VmSpec vmSpec, boolean isLinkedClone) {
public CloneAndRegisterMachineFromIMachineIfNotAlreadyExists(
Supplier<VirtualBoxManager> manager,
@Named(VirtualBoxConstants.VIRTUALBOX_WORKINGDIR) String workingDir,
CloneSpec cloneSpec, boolean isLinkedClone, MachineUtils machineUtils) {
this.manager = manager;
this.workingDir = workingDir;
this.vmSpec = vmSpec;
this.cloneSpec = cloneSpec;
this.isLinkedClone = isLinkedClone;
this.machineUtils = machineUtils;
}
@Override
public IMachine apply(@Nullable IMachine master) {
VmSpec vmSpec = cloneSpec.getVmSpec();
try {
manager.get().getVBox().findMachine(vmSpec.getVmName());
throw new IllegalStateException("Machine " + vmSpec.getVmName() + " is already registered.");
throw new IllegalStateException("Machine " + vmSpec.getVmName()
+ " is already registered.");
} catch (VBoxException e) {
if (machineNotFoundException(e))
return cloneMachine(vmSpec, master);
@ -82,31 +92,52 @@ public class CloneAndRegisterMachineFromIMachineIfNotAlreadyExists implements Fu
}
private boolean machineNotFoundException(VBoxException e) {
return e.getMessage().contains("VirtualBox error: Could not find a registered machine named ") ||
e.getMessage().contains("Could not find a registered machine with UUID {");
return e.getMessage().contains(
"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) {
String settingsFile = manager.get().getVBox().composeMachineFilename(vmSpec.getVmName(), workingDir);
IMachine clonedMachine = manager.get().getVBox().createMachine(settingsFile, vmSpec.getVmName(), vmSpec.getOsTypeId(),
vmSpec.getVmId(), vmSpec.isForceOverwrite());
String settingsFile = manager.get().getVBox()
.composeMachineFilename(vmSpec.getVmName(), workingDir);
IMachine clonedMachine = manager
.get()
.getVBox()
.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
ISnapshot currentSnapshot = new TakeSnapshotIfNotAlreadyAttached(manager, "snapshotName", "snapshotDesc")
.apply(master);
ISnapshot currentSnapshot = new TakeSnapshotIfNotAlreadyAttached(
manager, "snapshotName", "snapshotDesc").apply(master);
// clone
IProgress progress = currentSnapshot.getMachine().cloneTo(clonedMachine, CloneMode.MachineState, options);
IProgress progress = currentSnapshot.getMachine().cloneTo(
clonedMachine, CloneMode.MachineState, options);
if (progress.getCompleted())
logger.debug("clone done");
// 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.LockType;
import org.virtualbox_4_1.VirtualBoxManager;
import org.virtualbox_4_1.jaxws.MachineState;
import com.google.common.base.Function;
import com.google.common.base.Predicate;
import com.google.common.base.Splitter;
import com.google.common.base.Supplier;
import com.google.common.base.Throwables;
import com.google.common.cache.LoadingCache;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
@ -137,7 +139,13 @@ 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) {
while(!manager.get().getVBox().findMachine(vmName).getState().equals(MachineState.POWERED_OFF)) {
machineUtils.lockSessionOnMachineAndApply(vmName, LockType.Shared, new Function<ISession, Void>() {
@Override
public Void apply(ISession session) {
@ -146,6 +154,12 @@ public class CreateAndInstallVm implements Function<MasterSpec, IMachine> {
return null;
}
});
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Throwables.propagate(e);
}
}
}
private void ensureMachineIsLaunched(String vmName) {

View File

@ -19,25 +19,39 @@
package org.jclouds.virtualbox.functions;
import com.google.common.base.Function;
import com.google.common.base.Supplier;
import org.jclouds.compute.reference.ComputeServiceConstants;
import org.jclouds.logging.Logger;
import org.jclouds.virtualbox.config.VirtualBoxConstants;
import org.jclouds.virtualbox.domain.*;
import org.jclouds.virtualbox.util.MachineUtils;
import org.virtualbox_4_1.*;
import static com.google.common.base.Preconditions.checkNotNull;
import java.io.File;
import java.util.Set;
import javax.annotation.Nullable;
import javax.annotation.Resource;
import javax.inject.Inject;
import javax.inject.Named;
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
@ -112,12 +126,9 @@ public class CreateAndRegisterMachineFromIsoIfNotAlreadyExists implements Functi
setupHardDisksForController(vmName, controller);
setupDvdsForController(vmSpec, vmName, controller);
// NAT
Map<Long, NatAdapter> natNetworkAdapters = networkSpec.getNatNetworkAdapters();
for (Map.Entry<Long, NatAdapter> natAdapterAndSlot : natNetworkAdapters.entrySet()) {
long slotId = natAdapterAndSlot.getKey();
NatAdapter natAdapter = natAdapterAndSlot.getValue();
ensureNATNetworkingIsAppliedToMachine(vmName, slotId, natAdapter);
// Networking
for (NetworkInterfaceCard networkInterfaceCard : networkSpec.getNetworkInterfaceCards()) {
new AttachNicToMachine(vmName, machineUtils).apply(networkInterfaceCard);
}
}
@ -163,10 +174,6 @@ public class CreateAndRegisterMachineFromIsoIfNotAlreadyExists implements Functi
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) {
machineUtils.writeLockMachineAndApply(vmName, new AddIDEControllerIfNotExists(checkNotNull(
storageController, "storageController")));

View File

@ -18,18 +18,19 @@
*/
package org.jclouds.virtualbox.functions;
import static org.easymock.EasyMock.createMock;
import static org.easymock.EasyMock.expect;
import static org.easymock.classextension.EasyMock.createMock;
import static org.easymock.classextension.EasyMock.createNiceMock;
import static org.easymock.classextension.EasyMock.replay;
import static org.easymock.classextension.EasyMock.verify;
import static org.easymock.EasyMock.replay;
import static org.easymock.EasyMock.verify;
import static org.virtualbox_4_1.NetworkAdapterType.Am79C973;
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.virtualbox_4_1.IMachine;
import org.virtualbox_4_1.INetworkAdapter;
import org.virtualbox_4_1.VBoxException;
import org.virtualbox_4_1.NetworkAttachmentType;
/**
* @author Andrea Turli
@ -44,44 +45,25 @@ public class AttachBridgedAdapterToMachineTest {
public void testApplyNetworkingToNonExistingAdapter() throws Exception {
Long adapterId = 0l;
IMachine machine = createMock(IMachine.class);
INetworkAdapter networkAdapter = createMock(INetworkAdapter.class);
INetworkAdapter iNetworkAdapter = createMock(INetworkAdapter.class);
expect(machine.getNetworkAdapter(adapterId)).andReturn(networkAdapter);
networkAdapter.setAttachmentType(Bridged);
networkAdapter.setAdapterType(Am79C973);
networkAdapter.setMACAddress(macAddress);
networkAdapter.setBridgedInterface(hostInterface);
networkAdapter.setEnabled(true);
expect(machine.getNetworkAdapter(adapterId)).andReturn(iNetworkAdapter);
iNetworkAdapter.setAttachmentType(Bridged);
iNetworkAdapter.setAdapterType(Am79C973);
iNetworkAdapter.setMACAddress(macAddress);
iNetworkAdapter.setBridgedInterface(hostInterface);
iNetworkAdapter.setEnabled(true);
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)
.apply(machine);
new AttachBridgedAdapterToMachine(networkInterfaceCard).apply(machine);
verify(machine, networkAdapter);
}
@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);
verify(machine, iNetworkAdapter);
}
}

View File

@ -28,15 +28,17 @@ import static org.easymock.EasyMock.verify;
import static org.virtualbox_4_1.NATProtocol.TCP;
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.virtualbox_4_1.IMachine;
import org.virtualbox_4_1.INATEngine;
import org.virtualbox_4_1.INetworkAdapter;
import org.virtualbox_4_1.NetworkAttachmentType;
import org.virtualbox_4_1.VBoxException;
/**
* @author Mattias Holmqvist
* @author Mattias Holmqvist, Andrea Turli
*/
@Test(groups = "unit", testName = "AttachNATAdapterToMachineIfNotAlreadyExistsTest")
public class AttachNATAdapterToMachineIfNotAlreadyExistsTest {
@ -45,68 +47,89 @@ public class AttachNATAdapterToMachineIfNotAlreadyExistsTest {
public void testApplyNetworkingToNonExistingAdapter() throws Exception {
Long slotId = 0l;
IMachine machine = createMock(IMachine.class);
INetworkAdapter networkAdapter = createMock(INetworkAdapter.class);
INetworkAdapter iNetworkAdapter = createMock(INetworkAdapter.class);
INATEngine natEngine = createMock(INATEngine.class);
expect(machine.getNetworkAdapter(slotId)).andReturn(networkAdapter);
networkAdapter.setAttachmentType(NAT);
expect(networkAdapter.getNatDriver()).andReturn(natEngine);
expect(machine.getNetworkAdapter(slotId)).andReturn(iNetworkAdapter);
iNetworkAdapter.setAttachmentType(NAT);
expect(iNetworkAdapter.getNatDriver()).andReturn(natEngine);
natEngine.addRedirect("TCP@127.0.0.1:2222->:22", TCP, "127.0.0.1", 2222, "", 22);
networkAdapter.setEnabled(true);
natEngine.addRedirect("TCP@127.0.0.1:2222->:22", TCP, "127.0.0.1",
2222, "", 22);
iNetworkAdapter.setEnabled(true);
machine.saveSettings();
replay(machine, networkAdapter, natEngine);
NatAdapter natAdapter = NatAdapter.builder().tcpRedirectRule("127.0.0.1", 2222, "", 22).build();
new AttachNATAdapterToMachineIfNotAlreadyExists(slotId, natAdapter).apply(machine);
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();
verify(machine, networkAdapter, natEngine);
new AttachNATAdapterToMachineIfNotAlreadyExists(networkInterfaceCard)
.apply(machine);
verify(machine, iNetworkAdapter, natEngine);
}
@Test
public void testApplySkipsWhenAlreadyExists() throws Exception {
Long slotId = 0l;
IMachine machine = createMock(IMachine.class);
INetworkAdapter networkAdapter = createMock(INetworkAdapter.class);
INetworkAdapter iNetworkAdapter = createMock(INetworkAdapter.class);
INATEngine natEngine = createMock(INATEngine.class);
expect(machine.getNetworkAdapter(slotId)).andReturn(networkAdapter);
networkAdapter.setAttachmentType(NAT);
expect(networkAdapter.getNatDriver()).andReturn(natEngine);
expect(machine.getNetworkAdapter(slotId)).andReturn(iNetworkAdapter);
iNetworkAdapter.setAttachmentType(NAT);
expect(iNetworkAdapter.getNatDriver()).andReturn(natEngine);
natEngine.addRedirect("TCP@127.0.0.1:2222->:22", TCP, "127.0.0.1", 2222, "", 22);
expectLastCall().andThrow(
new VBoxException(null, "VirtualBox error: A NAT rule of this name already exists (0x80070057)"));
natEngine.addRedirect("TCP@127.0.0.1:2222->:22", TCP, "127.0.0.1",
2222, "", 22);
expectLastCall()
.andThrow(
new VBoxException(null,
"VirtualBox error: A NAT rule of this name already exists (0x80070057)"));
networkAdapter.setEnabled(true);
iNetworkAdapter.setEnabled(true);
machine.saveSettings();
replay(machine, networkAdapter, natEngine);
NatAdapter natAdapter = NatAdapter.builder().tcpRedirectRule("127.0.0.1", 2222, "", 22).build();
new AttachNATAdapterToMachineIfNotAlreadyExists(slotId, natAdapter).apply(machine);
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);
verify(machine, networkAdapter, natEngine);
verify(machine, iNetworkAdapter, natEngine);
}
@Test(expectedExceptions = VBoxException.class)
@Test(enabled=false, expectedExceptions = VBoxException.class)
public void testRethrowInvalidAdapterSlotException() throws Exception {
Long slotId = 30l;
IMachine machine = createMock(IMachine.class);
INetworkAdapter networkAdapter = createMock(INetworkAdapter.class);
INetworkAdapter iNetworkAdapter = createMock(INetworkAdapter.class);
INATEngine natEngine = createMock(INATEngine.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(slotId)).andThrow(invalidSlotException);
VBoxException invalidSlotException = new VBoxException(
createNiceMock(Throwable.class), error);
expect(machine.getNetworkAdapter(slotId))
.andThrow(invalidSlotException);
replay(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);
NatAdapter natAdapter = NatAdapter.builder().tcpRedirectRule("127.0.0.1", 2222, "", 22).build();
new AttachNATAdapterToMachineIfNotAlreadyExists(slotId, natAdapter).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.virtualbox.BaseVirtualBoxClientLiveTest;
import org.jclouds.virtualbox.domain.CloneSpec;
import org.jclouds.virtualbox.domain.HardDisk;
import org.jclouds.virtualbox.domain.IsoSpec;
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.StorageController;
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.Test;
import org.virtualbox_4_1.CleanupMode;
import org.virtualbox_4_1.IMachine;
import org.virtualbox_4_1.ISession;
import org.virtualbox_4_1.NetworkAttachmentType;
import org.virtualbox_4_1.StorageBus;
import com.google.common.base.CaseFormat;
@ -55,7 +56,7 @@ public class CloneAndRegisterMachineFromIsoIfNotAlreadyExistsLiveTest extends
private static final boolean IS_LINKED_CLONE = true;
private VmSpec clonedVmSpec;
private CloneSpec cloneSpec;
private MasterSpec sourceMachineSpec;
private CleanupMode mode = CleanupMode.Full;
@ -78,8 +79,9 @@ public class CloneAndRegisterMachineFromIsoIfNotAlreadyExistsLiveTest extends
.bus(StorageBus.IDE)
.attachISO(0, 0, operatingSystemIso)
.attachHardDisk(
HardDisk.builder().diskpath(adminDisk).controllerPort(0)
.deviceSlot(1).autoDelete(true).build())
HardDisk.builder().diskpath(adminDisk)
.controllerPort(0).deviceSlot(1)
.autoDelete(true).build())
.attachISO(1, 1, guestAdditionsIso).build();
VmSpec sourceVmSpec = VmSpec.builder().id(sourceName).name(sourceName)
@ -93,14 +95,26 @@ public class CloneAndRegisterMachineFromIsoIfNotAlreadyExistsLiveTest extends
.builder()
.sourcePath(operatingSystemIso)
.installationScript(
configProperties.apply(VIRTUALBOX_INSTALLATION_KEY_SEQUENCE)
.replace("HOSTNAME", sourceVmSpec.getVmName())).build();
configProperties.apply(
VIRTUALBOX_INSTALLATION_KEY_SEQUENCE).replace(
"HOSTNAME", sourceVmSpec.getVmName())).build();
NetworkSpec networkSpec = NetworkSpec.builder().build();
sourceMachineSpec = MasterSpec.builder().iso(isoSpec).vm(sourceVmSpec).network(networkSpec).build();
NetworkAdapter networkAdapter = NetworkAdapter.builder()
.networkAttachmentType(NetworkAttachmentType.Bridged).build();
NetworkInterfaceCard networkInterfaceCard = NetworkInterfaceCard
.builder().addNetworkAdapter(networkAdapter).build();
clonedVmSpec = VmSpec.builder().id(cloneName).name(cloneName)
NetworkSpec networkSpec = NetworkSpec.builder()
.addNIC(0L, networkInterfaceCard).build();
sourceMachineSpec = MasterSpec.builder().iso(isoSpec).vm(sourceVmSpec)
.network(networkSpec).build();
VmSpec clonedVmSpec = VmSpec.builder().id(cloneName).name(cloneName)
.memoryMB(512).cleanUpMode(mode).forceOverwrite(true).build();
cloneSpec = CloneSpec.builder().vm(clonedVmSpec).network(networkSpec)
.build();
}
@Test
@ -116,23 +130,22 @@ public class CloneAndRegisterMachineFromIsoIfNotAlreadyExistsLiveTest extends
}
IMachine clone = new CloneAndRegisterMachineFromIMachineIfNotAlreadyExists(
manager, workingDir, clonedVmSpec, IS_LINKED_CLONE)
.apply(source);
assertEquals(clone.getName(), clonedVmSpec.getVmName());
manager, workingDir, cloneSpec, IS_LINKED_CLONE,
machineUtils).apply(source);
assertEquals(clone.getName(), cloneSpec.getVmSpec().getVmName());
} finally {
for (VmSpec spec : ImmutableSet.of(clonedVmSpec,
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);
CreateAndRegisterMachineFromIsoIfNotAlreadyExists.class)
.apply(sourceMachineSpec);
} catch (IllegalStateException e) {
// already created
return manager.get().getVBox()

View File

@ -45,7 +45,8 @@ import org.jclouds.virtualbox.domain.ExecutionType;
import org.jclouds.virtualbox.domain.HardDisk;
import org.jclouds.virtualbox.domain.IsoSpec;
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.StorageController;
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.ISession;
import org.virtualbox_4_1.LockType;
import org.virtualbox_4_1.NetworkAttachmentType;
import org.virtualbox_4_1.StorageBus;
import org.virtualbox_4_1.jaxws.MachineState;
import com.google.common.base.CaseFormat;
import com.google.common.base.Function;
import com.google.common.base.Predicate;
import com.google.common.base.Splitter;
import com.google.common.base.Throwables;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.inject.Guice;
@ -85,7 +89,6 @@ public class CreateAndInstallVmLiveTest extends BaseVirtualBoxClientLiveTest {
private Function<IMachine, SshClient> sshClientForIMachine;
private Predicate<SshClient> sshResponds;
@Override
@BeforeClass(groups = "live")
public void setupClient() {
@ -94,31 +97,41 @@ public class CreateAndInstallVmLiveTest extends BaseVirtualBoxClientLiveTest {
+ CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN, getClass()
.getSimpleName());
HardDisk hardDisk = HardDisk.builder().diskpath(adminDisk).autoDelete(true)
.controllerPort(0).deviceSlot(1).build();
StorageController ideController = StorageController.builder().name("IDE Controller").bus(StorageBus.IDE)
.attachISO(0, 0, operatingSystemIso)
.attachHardDisk(hardDisk)
HardDisk hardDisk = HardDisk.builder().diskpath(adminDisk)
.autoDelete(true).controllerPort(0).deviceSlot(1).build();
StorageController ideController = StorageController.builder()
.name("IDE Controller").bus(StorageBus.IDE)
.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();
vmSpecification = VmSpec.builder().id(vmName).name(vmName)
.memoryMB(512).osTypeId("").controller(ideController)
.forceOverwrite(true).cleanUpMode(CleanupMode.Full).build();
injector = context.utils().injector();
Function<String, String> configProperties = injector
.getInstance(ValueOfConfigurationKeyOrNull.class);
masterSpec = MasterSpec.builder().vm(vmSpecification)
.iso(IsoSpec.builder()
NetworkAdapter networkAdapter = NetworkAdapter.builder()
.networkAttachmentType(NetworkAttachmentType.NAT)
.tcpRedirectRule("127.0.0.1", 2222, "", 22).build();
NetworkInterfaceCard networkInterfaceCard = NetworkInterfaceCard
.builder().addNetworkAdapter(networkAdapter).build();
NetworkSpec networkSpec = NetworkSpec.builder()
.addNIC(0L, networkInterfaceCard).build();
masterSpec = MasterSpec
.builder()
.vm(vmSpecification)
.iso(IsoSpec
.builder()
.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();
.installationScript(
configProperties.apply(
VIRTUALBOX_INSTALLATION_KEY_SEQUENCE)
.replace("HOSTNAME",
vmSpecification.getVmName()))
.build()).network(networkSpec).build();
undoVm(vmSpecification);
}
@ -140,23 +153,38 @@ public class CreateAndInstallVmLiveTest extends BaseVirtualBoxClientLiveTest {
try {
IMachine machine = getVmWithGuestAdditionsInstalled();
machineUtils.applyForMachine(machine.getName(), new LaunchMachineIfNotAlreadyRunning(manager.get(), ExecutionType.GUI, ""));
sshClientForIMachine = injector.getInstance(IMachineToSshClient.class);
machineUtils.applyForMachine(machine.getName(),
new LaunchMachineIfNotAlreadyRunning(manager.get(),
ExecutionType.GUI, ""));
sshClientForIMachine = injector
.getInstance(IMachineToSshClient.class);
SshClient client = sshClientForIMachine.apply(machine);
sshResponds = injector.getInstance(SshResponds.class);
checkState(sshResponds.apply(client), "timed out waiting for guest %s to be accessible via ssh", machine.getName());
checkState(sshResponds.apply(client),
"timed out waiting for guest %s to be accessible via ssh",
machine.getName());
assertTrue(machineUtils.lockSessionOnMachineAndApply(machine.getName(), LockType.Shared, new Function<ISession, Boolean>() {
assertTrue(machineUtils.lockSessionOnMachineAndApply(
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);
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)) {
for (VmSpec spec : ImmutableSet.of(vmSpecification)) {
ensureMachineHasPowerDown(spec.getVmName());
}
}
@ -175,8 +203,7 @@ public class CreateAndInstallVmLiveTest extends BaseVirtualBoxClientLiveTest {
private IMachine getVmWithGuestAdditionsInstalled() {
try {
Injector injector = context.utils().injector();
return injector.getInstance(
CreateAndInstallVm.class).apply(
return injector.getInstance(CreateAndInstallVm.class).apply(
masterSpec);
} catch (IllegalStateException e) {
// already created
@ -186,21 +213,30 @@ public class CreateAndInstallVmLiveTest extends BaseVirtualBoxClientLiveTest {
}
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
public Void apply(ISession session) {
IProgress powerDownProgress = session.getConsole().powerDown();
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)) {
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.virtualbox_4_1.CleanupMode;
import org.virtualbox_4_1.IMachine;
import org.virtualbox_4_1.NetworkAttachmentType;
import org.virtualbox_4_1.StorageBus;
import org.virtualbox_4_1.VBoxException;
@ -36,7 +37,8 @@ import org.virtualbox_4_1.VBoxException;
* @author Mattias Holmqvist
*/
@Test(groups = "live", singleThreaded = true, testName = "CreateAndRegisterMachineFromIsoIfNotAlreadyExistsLiveTest")
public class CreateAndRegisterMachineFromIsoIfNotAlreadyExistsLiveTest extends BaseVirtualBoxClientLiveTest {
public class CreateAndRegisterMachineFromIsoIfNotAlreadyExistsLiveTest extends
BaseVirtualBoxClientLiveTest {
private String ideControllerName;
private CleanupMode mode;
@ -47,10 +49,15 @@ public class CreateAndRegisterMachineFromIsoIfNotAlreadyExistsLiveTest extends B
super.setupClient();
ideControllerName = "IDE Controller";
mode = CleanupMode.Full;
ideController = StorageController.builder().name(ideControllerName).bus(StorageBus.IDE)
ideController = StorageController
.builder()
.name(ideControllerName)
.bus(StorageBus.IDE)
.attachISO(0, 0, operatingSystemIso)
.attachHardDisk(HardDisk.builder().diskpath(adminDisk).controllerPort(0).deviceSlot(1).build()).attachISO(1, 1,
guestAdditionsIso).build();
.attachHardDisk(
HardDisk.builder().diskpath(adminDisk)
.controllerPort(0).deviceSlot(1).build())
.attachISO(1, 1, guestAdditionsIso).build();
}
@Test
@ -58,25 +65,31 @@ public class CreateAndRegisterMachineFromIsoIfNotAlreadyExistsLiveTest extends B
String vmName = "jclouds-test-create-1-node";
String vmId = UUID.randomUUID().toString();
VmSpec vmSpec = VmSpec.builder()
.id(vmId)
.name(vmName)
.memoryMB(512)
.controller(ideController)
.cleanUpMode(mode)
.osTypeId("Debian")
VmSpec vmSpec = VmSpec.builder().id(vmId).name(vmName).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();
NetworkAdapter networkAdapter = NetworkAdapter.builder()
.networkAttachmentType(NetworkAttachmentType.NAT)
.tcpRedirectRule("127.0.0.1", 2222, "", 22).build();
NetworkInterfaceCard networkInterfaceCard = NetworkInterfaceCard
.builder().addNetworkAdapter(networkAdapter).build();
NetworkSpec networkSpec = NetworkSpec.builder()
.addNIC(0L, networkInterfaceCard).build();
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 debianNode = context.utils()
.injector()
.getInstance(
CreateAndRegisterMachineFromIsoIfNotAlreadyExists.class)
.apply(machineSpec);
IMachine machine = manager.get().getVBox().findMachine(vmName);
assertEquals(debianNode.getName(), machine.getName());
} finally {
@ -89,23 +102,19 @@ public class CreateAndRegisterMachineFromIsoIfNotAlreadyExistsLiveTest extends B
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();
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)
MasterSpec machineSpec = MasterSpec.builder().iso(isoSpec).vm(vmSpec)
.network(networkSpec).build();
undoVm(vmSpec);
try {
Injector injector = context.utils().injector();
injector.getInstance(CreateAndRegisterMachineFromIsoIfNotAlreadyExists.class)
injector.getInstance(
CreateAndRegisterMachineFromIsoIfNotAlreadyExists.class)
.apply(machineSpec);
fail();
} catch (VBoxException e) {

View File

@ -25,14 +25,17 @@ import static org.testng.Assert.assertTrue;
import org.jclouds.config.ValueOfConfigurationKeyOrNull;
import org.jclouds.virtualbox.BaseVirtualBoxClientLiveTest;
import org.jclouds.virtualbox.domain.ExecutionType;
import org.jclouds.virtualbox.domain.HardDisk;
import org.jclouds.virtualbox.domain.IsoSpec;
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.StorageController;
import org.jclouds.virtualbox.domain.VmSpec;
import org.jclouds.virtualbox.functions.CreateAndInstallVm;
import org.jclouds.virtualbox.functions.LaunchMachineIfNotAlreadyRunning;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
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.ISession;
import org.virtualbox_4_1.LockType;
import org.virtualbox_4_1.NetworkAttachmentType;
import org.virtualbox_4_1.StorageBus;
import com.google.common.base.CaseFormat;
import com.google.common.base.Function;
import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableSet;
import com.google.inject.Injector;
@ -71,8 +74,9 @@ public class GuestAdditionsInstallerLiveTest extends
.bus(StorageBus.IDE)
.attachISO(0, 0, operatingSystemIso)
.attachHardDisk(
HardDisk.builder().diskpath(adminDisk).controllerPort(0)
.deviceSlot(1).autoDelete(true).build())
HardDisk.builder().diskpath(adminDisk)
.controllerPort(0).deviceSlot(1)
.autoDelete(true).build())
.attachISO(1, 1, guestAdditionsIso).build();
VmSpec sourceVmSpec = VmSpec.builder().id(sourceName).name(sourceName)
@ -86,14 +90,20 @@ public class GuestAdditionsInstallerLiveTest extends
.builder()
.sourcePath(operatingSystemIso)
.installationScript(
configProperties.apply(VIRTUALBOX_INSTALLATION_KEY_SEQUENCE)
.replace("HOSTNAME", sourceVmSpec.getVmName())).build();
configProperties.apply(
VIRTUALBOX_INSTALLATION_KEY_SEQUENCE).replace(
"HOSTNAME", sourceVmSpec.getVmName())).build();
NetworkSpec networkSpec = //NetworkSpec.builder().build();
NetworkSpec.builder()
.natNetworkAdapter(0, NatAdapter.builder().tcpRedirectRule("127.0.0.1", 2222, "", 22).build())
.build();
sourceMachineSpec = MasterSpec.builder().iso(isoSpec).vm(sourceVmSpec).network(networkSpec).build();
NetworkAdapter networkAdapter = NetworkAdapter.builder()
.networkAttachmentType(NetworkAttachmentType.NAT)
.tcpRedirectRule("127.0.0.1", 2222, "", 22).build();
NetworkInterfaceCard networkInterfaceCard = NetworkInterfaceCard
.builder().addNetworkAdapter(networkAdapter).build();
NetworkSpec networkSpec = NetworkSpec.builder()
.addNIC(0L, networkInterfaceCard).build();
sourceMachineSpec = MasterSpec.builder().iso(isoSpec).vm(sourceVmSpec)
.network(networkSpec).build();
}
@ -101,15 +111,20 @@ public class GuestAdditionsInstallerLiveTest extends
public void testGuestAdditionsAreInstalled() throws Exception {
try {
IMachine machine = getVmWithGuestAdditionsInstalled();
assertTrue(machineUtils.lockSessionOnMachineAndApply(machine.getName(), LockType.Shared, new Function<ISession, Boolean>() {
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;
return session.getMachine().getGuestPropertyValue(
"/VirtualBox/GuestAdd/Version") != null;
}
}));
} finally {
for (VmSpec spec : ImmutableSet.of(
sourceMachineSpec.getVmSpec())) {
for (VmSpec spec : ImmutableSet.of(sourceMachineSpec.getVmSpec())) {
ensureMachineHasPowerDown(spec.getVmName());
undoVm(spec);
}
@ -120,8 +135,7 @@ public class GuestAdditionsInstallerLiveTest extends
private IMachine getVmWithGuestAdditionsInstalled() {
try {
Injector injector = context.utils().injector();
return injector.getInstance(
CreateAndInstallVm.class).apply(
return injector.getInstance(CreateAndInstallVm.class).apply(
sourceMachineSpec);
} catch (IllegalStateException e) {
// already created
@ -131,10 +145,12 @@ public class GuestAdditionsInstallerLiveTest extends
}
private void ensureMachineHasPowerDown(String vmName) {
machineUtils.lockSessionOnMachineAndApply(vmName, LockType.Shared, new Function<ISession, Void>() {
machineUtils.lockSessionOnMachineAndApply(vmName, LockType.Shared,
new Function<ISession, Void>() {
@Override
public Void apply(ISession session) {
IProgress powerDownProgress = session.getConsole().powerDown();
IProgress powerDownProgress = session.getConsole()
.powerDown();
powerDownProgress.waitForCompletion(-1);
return null;
}

View File

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