Added domain model objects for VM and its parts. Reworked tests and IsoToIMachine accordingly. More work to be done.

This commit is contained in:
Mattias Holmqvist 2011-12-15 01:41:35 +01:00
parent 81d9a0afcd
commit 6712e661ce
26 changed files with 1021 additions and 606 deletions

View File

@ -0,0 +1,59 @@
/**
* 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 org.virtualbox_4_1.DeviceType;
/**
* Represents a specification for a device attachment.
* <p/>
* <p/>
* From the VirtualBox SDK:
* <p/>
* port:
* For an IDE controller, 0 specifies the primary controller and 1 specifies the secondary controller.
* For a SCSI controller, this must range from 0 to 15; for a SATA controller, from 0 to 29; for an SAS controller,
* from 0 to 7
*/
public class DeviceDetails {
private final int port;
private final int deviceSlot;
private final DeviceType deviceType;
public DeviceDetails(int port, int deviceSlot, DeviceType deviceType) {
this.port = port;
this.deviceSlot = deviceSlot;
this.deviceType = deviceType;
}
public int getPort() {
return port;
}
public int getDeviceSlot() {
return deviceSlot;
}
public DeviceType getDeviceType() {
return deviceType;
}
}

View File

@ -0,0 +1,79 @@
/**
* 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;
/**
* A representation of a hard disk in a VirtualBox VM.
*
* diskPath is an absolute path to the file that is the location of the storage for the hard disk.
* diskFormat is any of the formats supported by ISystemProperties.getMediumFormats() in the VirtualBox API.
* This call is platform-dependent so the supported formats differ from host to host. The default format used is VDI.
* deviceDetails contains information about how the HardDisk is attached to the StorageController.
*
*/
public class HardDisk {
public static final String DEFAULT_DISK_FORMAT = "vdi";
private final String diskFormat;
private final String diskPath;
private final DeviceDetails deviceDetails;
public HardDisk(DeviceDetails deviceDetails, String diskPath, String diskFormat) {
this.diskPath = diskPath;
this.diskFormat = diskFormat;
this.deviceDetails = deviceDetails;
}
public String getDiskPath() {
return diskPath;
}
public String getDiskFormat() {
return diskFormat;
}
public DeviceDetails getDeviceDetails() {
return deviceDetails;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
HardDisk hardDisk = (HardDisk) o;
if (deviceDetails != null ? !deviceDetails.equals(hardDisk.deviceDetails) : hardDisk.deviceDetails != null)
return false;
if (diskFormat != null ? !diskFormat.equals(hardDisk.diskFormat) : hardDisk.diskFormat != null) return false;
if (diskPath != null ? !diskPath.equals(hardDisk.diskPath) : hardDisk.diskPath != null) return false;
return true;
}
@Override
public int hashCode() {
int result = diskFormat != null ? diskFormat.hashCode() : 0;
result = 31 * result + (diskPath != null ? diskPath.hashCode() : 0);
result = 31 * result + (deviceDetails != null ? deviceDetails.hashCode() : 0);
return result;
}
}

View File

@ -0,0 +1,72 @@
/**
* 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;
/**
* Represents an optical medium (DVD) in a VirtualBox VM.
*
* sourcePath is the location of the .iso file to load the medium from.
* deviceDetails contains information about how the Dvd is attached to the StorageController.
*/
public class IsoImage {
private DeviceDetails deviceDetails;
private String sourcePath;
public IsoImage(DeviceDetails deviceDetails, String sourcePath) {
this.deviceDetails = deviceDetails;
this.sourcePath = sourcePath;
}
public DeviceDetails getDeviceDetails() {
return deviceDetails;
}
public String getSourcePath() {
return sourcePath;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
IsoImage dvd = (IsoImage) o;
if (deviceDetails != null ? !deviceDetails.equals(dvd.deviceDetails) : dvd.deviceDetails != null) return false;
if (sourcePath != null ? !sourcePath.equals(dvd.sourcePath) : dvd.sourcePath != null) return false;
return true;
}
@Override
public int hashCode() {
int result = deviceDetails != null ? deviceDetails.hashCode() : 0;
result = 31 * result + (sourcePath != null ? sourcePath.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "Dvd{" +
"deviceDetails=" + deviceDetails +
", sourcePath='" + sourcePath + '\'' +
'}';
}
}

View File

@ -0,0 +1,93 @@
/**
* 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 org.virtualbox_4_1.NATProtocol;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
/**
* Represents a NAT network adapter in VirtualBox.
*
* redirectRules are the redirect rules that are applied to the network adapter.
*/
public class NatAdapter {
private final Set<RedirectRule> redirectRules = new HashSet<RedirectRule>();
public NatAdapter(Set<RedirectRule> redirectRules) {
this.redirectRules.addAll(redirectRules);
}
public static Builder builder() {
return new Builder();
}
public static class Builder {
private Set<RedirectRule> redirectRules = new HashSet<RedirectRule>();
private long adapterSlot;
public Builder tcpRedirectRule(String host, int hostPort, String guest, int guestPort) {
redirectRules.add(new RedirectRule(NATProtocol.TCP, host, hostPort, guest, guestPort));
return this;
}
public Builder udpRedirectRule(String host, int hostPort, String guest, int guestPort) {
redirectRules.add(new RedirectRule(NATProtocol.UDP, host, hostPort, guest, guestPort));
return this;
}
public NatAdapter build() {
return new NatAdapter(redirectRules);
}
}
public Set<RedirectRule> getRedirectRules() {
return Collections.unmodifiableSet(redirectRules);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
NatAdapter that = (NatAdapter) o;
if (redirectRules != null ? !redirectRules.equals(that.redirectRules) : that.redirectRules != null) return false;
return true;
}
@Override
public int hashCode() {
return redirectRules != null ? redirectRules.hashCode() : 0;
}
@Override
public String toString() {
return "NatAdapter{" +
"redirectRules=" + redirectRules +
'}';
}
}

View File

@ -0,0 +1,147 @@
/*
* 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 org.virtualbox_4_1.DeviceType;
import org.virtualbox_4_1.StorageBus;
import java.util.HashSet;
import java.util.Set;
import static com.google.common.base.Preconditions.checkNotNull;
import static org.jclouds.virtualbox.domain.HardDisk.DEFAULT_DISK_FORMAT;
/**
* Represents a storage controller in a VirtualBox VM.
*
* name is the unique name of the controller.
* bus is the type of connection bus for the controller
* hardDisks contains the hard disks that are attached (or should be attached) to this controller
* isoImages contains the ISOs that are attached (or should be attached) to this controller
*
* @see StorageBus
*/
public class StorageController {
private final String name;
private final StorageBus bus;
private Set<HardDisk> hardDisks;
private Set<IsoImage> isoImages;
public StorageController(String name, StorageBus bus, Set<HardDisk> hardDisks, Set<IsoImage> isoImages) {
this.name = name;
this.bus = bus;
this.hardDisks = hardDisks;
this.isoImages = isoImages;
}
public String getName() {
return name;
}
public StorageBus getBus() {
return bus;
}
public Set<HardDisk> getHardDisks() {
return hardDisks;
}
public Set<IsoImage> getIsoImages() {
return isoImages;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
StorageController that = (StorageController) o;
if (bus != that.bus) return false;
if (isoImages != null ? !isoImages.equals(that.isoImages) : that.isoImages != null) return false;
if (hardDisks != null ? !hardDisks.equals(that.hardDisks) : that.hardDisks != null) return false;
if (name != null ? !name.equals(that.name) : that.name != null) return false;
return true;
}
@Override
public int hashCode() {
int result = name != null ? name.hashCode() : 0;
result = 31 * result + (bus != null ? bus.hashCode() : 0);
result = 31 * result + (hardDisks != null ? hardDisks.hashCode() : 0);
result = 31 * result + (isoImages != null ? isoImages.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "StorageController{" +
"name='" + name + '\'' +
", bus=" + bus +
", hardDisks=" + hardDisks +
", isoImages=" + isoImages +
'}';
}
public static Builder builder() {
return new Builder();
}
public static class Builder {
private String name;
private StorageBus bus;
private Set<HardDisk> hardDisks = new HashSet<HardDisk>();
private Set<IsoImage> dvds = new HashSet<IsoImage>();
public Builder name(String name) {
this.name = name;
return this;
}
public Builder bus(StorageBus bus) {
this.bus = bus;
return this;
}
public Builder attachISO(int controllerPort, int deviceSlot, String sourcePath) {
dvds.add(new IsoImage(new DeviceDetails(controllerPort, deviceSlot, DeviceType.DVD), sourcePath));
return this;
}
public Builder attachHardDisk(int controllerPort, int deviceSlot, String diskPath) {
hardDisks.add(new HardDisk(new DeviceDetails(controllerPort, deviceSlot, DeviceType.HardDisk), diskPath, DEFAULT_DISK_FORMAT));
return this;
}
public Builder attachHardDisk(int controllerPort, int deviceSlot, String diskPath, String diskFormat) {
hardDisks.add(new HardDisk(new DeviceDetails(controllerPort, deviceSlot, DeviceType.HardDisk), diskPath, diskFormat));
return this;
}
public StorageController build() {
checkNotNull(name);
checkNotNull(bus);
return new StorageController(name, bus, hardDisks, dvds);
}
}
}

View File

@ -0,0 +1,162 @@
/*
* 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 java.util.*;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* A description of a Virtual Machine in VirtualBox.
*/
public class VmSpecification {
private final String vmName;
private final String osTypeId;
private final String vmId;
private final boolean forceOverwrite;
private final Map<Long, NatAdapter> natNetworkAdapters;
private final Set<StorageController> controllers;
public VmSpecification(String vmId, String vmName, String osTypeId, boolean forceOverwrite, Set<StorageController> controllers, Map<Long, NatAdapter> natNetworkAdapters) {
this.vmId = vmId;
this.vmName = vmName;
this.osTypeId = osTypeId;
this.controllers = controllers;
this.forceOverwrite = forceOverwrite;
this.natNetworkAdapters = natNetworkAdapters;
}
public static Builder builder() {
return new Builder();
}
public static class Builder {
private Set<StorageController> controllers = new HashSet<StorageController>();
private String name;
private String id;
private String osTypeId = "";
private boolean forceOverwrite;
private Map<Long, NatAdapter> natNetworkAdapters = new HashMap<Long, NatAdapter>();
public Builder controller(StorageController controller) {
controllers.add(controller);
return this;
}
public Builder name(String name) {
this.name = name;
return this;
}
public Builder id(String id) {
this.id = id;
return this;
}
public Builder osTypeId(String osTypeId) {
this.osTypeId = osTypeId;
return this;
}
public Builder forceOverwrite(boolean forceOverwrite) {
this.forceOverwrite = forceOverwrite;
return this;
}
public Builder natNetworkAdapter(int slot, NatAdapter adapter) {
this.natNetworkAdapters.put((long) slot, adapter);
return this;
}
public VmSpecification build() {
checkNotNull(name, "name");
checkNotNull(id, "id");
return new VmSpecification(id, name, osTypeId, forceOverwrite, controllers, natNetworkAdapters);
}
}
public String getVmName() {
return vmName;
}
public String getOsTypeId() {
return osTypeId;
}
public String getVmId() {
return vmId;
}
public boolean isForceOverwrite() {
return forceOverwrite;
}
public Set<StorageController> getControllers() {
return Collections.unmodifiableSet(controllers);
}
public Map<Long, NatAdapter> getNatNetworkAdapters() {
return Collections.unmodifiableMap(natNetworkAdapters);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
VmSpecification that = (VmSpecification) o;
if (forceOverwrite != that.forceOverwrite) return false;
if (controllers != null ? !controllers.equals(that.controllers) : that.controllers != null) return false;
if (natNetworkAdapters != null ? !natNetworkAdapters.equals(that.natNetworkAdapters) : that.natNetworkAdapters != null)
return false;
if (osTypeId != null ? !osTypeId.equals(that.osTypeId) : that.osTypeId != null) return false;
if (vmId != null ? !vmId.equals(that.vmId) : that.vmId != null) return false;
if (vmName != null ? !vmName.equals(that.vmName) : that.vmName != null) return false;
return true;
}
@Override
public int hashCode() {
int result = vmName != null ? vmName.hashCode() : 0;
result = 31 * result + (osTypeId != null ? osTypeId.hashCode() : 0);
result = 31 * result + (vmId != null ? vmId.hashCode() : 0);
result = 31 * result + (forceOverwrite ? 1 : 0);
result = 31 * result + (natNetworkAdapters != null ? natNetworkAdapters.hashCode() : 0);
result = 31 * result + (controllers != null ? controllers.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "VmSpecification{" +
"vmName='" + vmName + '\'' +
", osTypeId='" + osTypeId + '\'' +
", vmId='" + vmId + '\'' +
", forceOverwrite=" + forceOverwrite +
", natNetworkAdapters=" + natNetworkAdapters +
", controllers=" + controllers +
'}';
}
}

View File

@ -21,6 +21,7 @@ package org.jclouds.virtualbox.functions;
import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkNotNull;
import org.jclouds.virtualbox.domain.StorageController;
import org.virtualbox_4_1.IMachine; import org.virtualbox_4_1.IMachine;
import org.virtualbox_4_1.StorageBus; import org.virtualbox_4_1.StorageBus;
import org.virtualbox_4_1.VBoxException; import org.virtualbox_4_1.VBoxException;
@ -33,16 +34,16 @@ import com.google.common.base.Function;
* *
*/ */
public class AddIDEControllerIfNotExists implements Function<IMachine, Void> { public class AddIDEControllerIfNotExists implements Function<IMachine, Void> {
private final String controllerName; private final StorageController storageController;
public AddIDEControllerIfNotExists(String controllerName) { public AddIDEControllerIfNotExists(StorageController storageController) {
this.controllerName = checkNotNull(controllerName, "controllerName"); this.storageController = checkNotNull(storageController, "storageController");
} }
@Override @Override
public Void apply(IMachine machine) { public Void apply(IMachine machine) {
try { try {
machine.addStorageController(controllerName, StorageBus.IDE); machine.addStorageController(storageController.getName(), storageController.getBus());
machine.saveSettings(); machine.saveSettings();
} catch (VBoxException e) { } catch (VBoxException e) {
if (!e.getMessage().contains("already exists")) if (!e.getMessage().contains("already exists"))
@ -53,6 +54,6 @@ public class AddIDEControllerIfNotExists implements Function<IMachine, Void> {
@Override @Override
public String toString() { public String toString() {
return String.format("addStorageController(%s, IDE)", controllerName); return String.format("addStorageController(%s)", storageController);
} }
} }

View File

@ -1,62 +0,0 @@
/**
* 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 javax.annotation.Nullable;
import org.virtualbox_4_1.DeviceType;
import org.virtualbox_4_1.IMachine;
import org.virtualbox_4_1.IMedium;
import org.virtualbox_4_1.VBoxException;
import com.google.common.base.Function;
/**
* @author Mattias Holmqvist
*/
public class AttachDistroMediumToMachine implements Function<IMachine, Void> {
private final String controllerIDE;
private final IMedium distroMedium;
public AttachDistroMediumToMachine(String controllerIDE, IMedium distroMedium) {
this.controllerIDE = controllerIDE;
this.distroMedium = distroMedium;
}
@Override
public Void apply(@Nullable IMachine machine) {
try {
int controllerPort = 0;
int device = 0;
machine.attachDevice(controllerIDE, controllerPort, device, DeviceType.DVD, distroMedium);
machine.saveSettings();
} catch (VBoxException e) {
if (!alreadyAttached(e))
throw e;
}
return null;
}
private boolean alreadyAttached(VBoxException e) {
return e.getMessage().contains("is already attached to port");
}
}

View File

@ -21,7 +21,7 @@ package org.jclouds.virtualbox.functions;
import javax.annotation.Nullable; import javax.annotation.Nullable;
import org.virtualbox_4_1.DeviceType; import org.jclouds.virtualbox.domain.DeviceDetails;
import org.virtualbox_4_1.IMachine; import org.virtualbox_4_1.IMachine;
import org.virtualbox_4_1.IMedium; import org.virtualbox_4_1.IMedium;
import org.virtualbox_4_1.VBoxException; import org.virtualbox_4_1.VBoxException;
@ -33,25 +33,20 @@ import com.google.common.base.Function;
*/ */
public class AttachMediumToMachineIfNotAlreadyAttached implements Function<IMachine, Void> { public class AttachMediumToMachineIfNotAlreadyAttached implements Function<IMachine, Void> {
private String controllerIDE; private final DeviceDetails device;
private IMedium medium; private final IMedium medium;
private int controllerPort; private final String controllerName;
private int device;
private DeviceType deviceType;
public AttachMediumToMachineIfNotAlreadyAttached(String controllerIDE, IMedium medium, int controllerPort, public AttachMediumToMachineIfNotAlreadyAttached(DeviceDetails device, IMedium medium, String controllerName) {
int device, DeviceType deviceType) {
this.controllerIDE = controllerIDE;
this.medium = medium;
this.controllerPort = controllerPort;
this.device = device; this.device = device;
this.deviceType = deviceType; this.medium = medium;
this.controllerName = controllerName;
} }
@Override @Override
public Void apply(@Nullable IMachine machine) { public Void apply(@Nullable IMachine machine) {
try { try {
machine.attachDevice(controllerIDE, controllerPort, device, deviceType, medium); machine.attachDevice(controllerName, device.getPort(), device.getDeviceSlot(), device.getDeviceType(), medium);
machine.saveSettings(); machine.saveSettings();
} catch (VBoxException e) { } catch (VBoxException e) {
if (!alreadyAttached(e)) if (!alreadyAttached(e))

View File

@ -19,11 +19,11 @@
package org.jclouds.virtualbox.functions; package org.jclouds.virtualbox.functions;
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 javax.annotation.Nullable; import javax.annotation.Nullable;
import org.jclouds.virtualbox.domain.NatAdapter;
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;
@ -33,26 +33,28 @@ import com.google.common.base.Function;
/** /**
* @author Mattias Holmqvist * @author Mattias Holmqvist
*/ */
public class AttachNATRedirectRuleToMachine implements Function<IMachine, Void> { public class AttachNATAdapterToMachine implements Function<IMachine, Void> {
private long adapterIndex; private long adapterSlot;
private RedirectRule redirectRule; private NatAdapter natAdapter;
public AttachNATRedirectRuleToMachine(long adapterSlot, RedirectRule redirectRule) { public AttachNATAdapterToMachine(long adapterSlot, NatAdapter natAdapter) {
this.adapterIndex = adapterSlot; this.adapterSlot = adapterSlot;
this.redirectRule = redirectRule; this.natAdapter = natAdapter;
} }
@Override @Override
public Void apply(@Nullable IMachine machine) { public Void apply(@Nullable IMachine machine) {
INetworkAdapter networkAdapter = machine.getNetworkAdapter(adapterIndex); INetworkAdapter networkAdapter = machine.getNetworkAdapter(adapterSlot);
networkAdapter.setAttachmentType(NAT); networkAdapter.setAttachmentType(NAT);
for (RedirectRule rule : natAdapter.getRedirectRules()) {
networkAdapter.getNatDriver().addRedirect("guestssh", networkAdapter.getNatDriver().addRedirect("guestssh",
redirectRule.getProtocol(), rule.getProtocol(),
redirectRule.getHost(), rule.getHost(),
redirectRule.getHostPort(), rule.getHostPort(),
redirectRule.getGuest(), rule.getGuest(),
redirectRule.getGuestPort()); rule.getGuestPort());
}
networkAdapter.setEnabled(true); networkAdapter.setEnabled(true);
machine.saveSettings(); machine.saveSettings();
return null; return null;

View File

@ -20,6 +20,7 @@
package org.jclouds.virtualbox.functions; package org.jclouds.virtualbox.functions;
import com.google.common.base.Function; import com.google.common.base.Function;
import org.jclouds.virtualbox.domain.VmSpecification;
import org.virtualbox_4_1.IMachine; import org.virtualbox_4_1.IMachine;
import org.virtualbox_4_1.IVirtualBox; import org.virtualbox_4_1.IVirtualBox;
import org.virtualbox_4_1.VBoxException; import org.virtualbox_4_1.VBoxException;
@ -30,31 +31,24 @@ import javax.annotation.Nullable;
/** /**
* @author Mattias Holmqvist * @author Mattias Holmqvist
*/ */
public class CreateAndRegisterMachineFromIsoIfNotAlreadyExists implements Function<String, IMachine> { public class CreateAndRegisterMachineFromIsoIfNotAlreadyExists implements Function<VmSpecification, IMachine> {
private String osTypeId;
private String vmId;
private boolean forceOverwrite;
private VirtualBoxManager manager; private VirtualBoxManager manager;
public CreateAndRegisterMachineFromIsoIfNotAlreadyExists(String osTypeId, String vmId, public CreateAndRegisterMachineFromIsoIfNotAlreadyExists(VirtualBoxManager manager) {
boolean forceOverwrite, VirtualBoxManager manager) {
this.osTypeId = osTypeId;
this.vmId = vmId;
this.forceOverwrite = forceOverwrite;
this.manager = manager; this.manager = manager;
} }
@Override @Override
public IMachine apply(@Nullable String vmName) { public IMachine apply(@Nullable VmSpecification launchSpecification) {
final IVirtualBox vBox = manager.getVBox(); final IVirtualBox vBox = manager.getVBox();
String vmName = launchSpecification.getVmName();
try { try {
vBox.findMachine(vmName); vBox.findMachine(vmName);
throw new IllegalStateException("Machine " + vmName + " is already registered."); throw new IllegalStateException("Machine " + vmName + " is already registered.");
} catch (VBoxException e) { } catch (VBoxException e) {
if (machineNotFoundException(e)) if (machineNotFoundException(e))
return createMachine(vBox, vmName); return createMachine(vBox, launchSpecification);
else else
throw e; throw e;
} }
@ -64,10 +58,11 @@ public class CreateAndRegisterMachineFromIsoIfNotAlreadyExists implements Functi
return e.getMessage().contains("VirtualBox error: Could not find a registered machine named "); return e.getMessage().contains("VirtualBox error: Could not find a registered machine named ");
} }
private IMachine createMachine(IVirtualBox vBox, String vmName) { private IMachine createMachine(IVirtualBox vBox, VmSpecification launchSpecification) {
// TODO: add support for settingsfile // TODO: add support for settingsfile
String settingsFile1 = null; String settingsFile1 = null;
IMachine newMachine = vBox.createMachine(settingsFile1, vmName, osTypeId, vmId, forceOverwrite); IMachine newMachine = vBox.createMachine(settingsFile1, launchSpecification.getVmName(),
launchSpecification.getOsTypeId(), launchSpecification.getVmId(), launchSpecification.isForceOverwrite());
manager.getVBox().registerMachine(newMachine); manager.getVBox().registerMachine(newMachine);
return newMachine; return newMachine;
} }

View File

@ -19,55 +19,49 @@
package org.jclouds.virtualbox.functions; package org.jclouds.virtualbox.functions;
import javax.annotation.Nullable;
import org.virtualbox_4_1.DeviceType;
import org.virtualbox_4_1.IMedium;
import org.virtualbox_4_1.IProgress;
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.Function;
import org.jclouds.virtualbox.domain.HardDisk;
import org.virtualbox_4_1.*;
import javax.annotation.Nullable;
/** /**
* @author Mattias Holmqvist * @author Mattias Holmqvist
*/ */
public class CreateMediumIfNotAlreadyExists implements Function<String, IMedium> { public class CreateMediumIfNotAlreadyExists implements Function<HardDisk, IMedium> {
private final VirtualBoxManager manager; private final VirtualBoxManager manager;
private final String diskFormat;
private boolean overwriteIfExists; private boolean overwriteIfExists;
public CreateMediumIfNotAlreadyExists(VirtualBoxManager manager, String diskFormat, boolean overwriteIfExists) { public CreateMediumIfNotAlreadyExists(VirtualBoxManager manager, boolean overwriteIfExists) {
this.manager = manager; this.manager = manager;
this.diskFormat = diskFormat;
this.overwriteIfExists = overwriteIfExists; this.overwriteIfExists = overwriteIfExists;
} }
@Override @Override
public IMedium apply(@Nullable String path) { public IMedium apply(@Nullable HardDisk hardDisk) {
IVirtualBox vBox = manager.getVBox(); IVirtualBox vBox = manager.getVBox();
try { try {
final IMedium medium = vBox.findMedium(path, DeviceType.HardDisk); String diskPath = hardDisk.getDiskPath();
final IMedium medium = vBox.findMedium(diskPath, DeviceType.HardDisk);
if (overwriteIfExists) { if (overwriteIfExists) {
final IProgress progress = medium.deleteStorage(); final IProgress progress = medium.deleteStorage();
progress.waitForCompletion(-1); progress.waitForCompletion(-1);
return createNewMedium(vBox, path); return createNewMedium(vBox, hardDisk);
} else { } else {
throw new IllegalStateException("Medium for path " + path + " already exists."); throw new IllegalStateException("Medium for path " + diskPath + " already exists.");
} }
} catch (VBoxException e) { } catch (VBoxException e) {
if (notFoundException(e)) if (notFoundException(e))
return createNewMedium(vBox, path); return createNewMedium(vBox, hardDisk);
throw e; throw e;
} }
} }
private IMedium createNewMedium(IVirtualBox vBox, String path) { private IMedium createNewMedium(IVirtualBox vBox, HardDisk hardDisk) {
IMedium hardDisk = vBox.createHardDisk(diskFormat, path); IMedium medium = vBox.createHardDisk(hardDisk.getDiskFormat(), hardDisk.getDiskPath());
createBaseStorage(hardDisk); createBaseStorage(medium);
return hardDisk; return medium;
} }
private boolean notFoundException(VBoxException e) { private boolean notFoundException(VBoxException e) {

View File

@ -30,27 +30,23 @@ import org.jclouds.javax.annotation.Nullable;
import org.jclouds.logging.Logger; import org.jclouds.logging.Logger;
import org.jclouds.net.IPSocket; import org.jclouds.net.IPSocket;
import org.jclouds.ssh.SshException; import org.jclouds.ssh.SshException;
import org.jclouds.virtualbox.domain.ExecutionType; import org.jclouds.virtualbox.domain.*;
import org.jclouds.virtualbox.domain.RedirectRule;
import org.jclouds.virtualbox.settings.KeyboardScancodes; import org.jclouds.virtualbox.settings.KeyboardScancodes;
import org.virtualbox_4_1.*; import org.virtualbox_4_1.*;
import javax.annotation.Resource; import javax.annotation.Resource;
import javax.inject.Named; import javax.inject.Named;
import java.io.File; import java.io.File;
import java.util.Map;
import java.util.Set;
import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkNotNull;
import static org.jclouds.compute.options.RunScriptOptions.Builder.runAsRoot; import static org.jclouds.compute.options.RunScriptOptions.Builder.runAsRoot;
import static org.jclouds.compute.options.RunScriptOptions.Builder.wrapInInitScript; import static org.jclouds.compute.options.RunScriptOptions.Builder.wrapInInitScript;
import static org.jclouds.virtualbox.util.MachineUtils.*;
import static org.jclouds.virtualbox.config.VirtualBoxConstants.VIRTUALBOX_INSTALLATION_KEY_SEQUENCE; import static org.jclouds.virtualbox.config.VirtualBoxConstants.VIRTUALBOX_INSTALLATION_KEY_SEQUENCE;
import static org.jclouds.virtualbox.config.VirtualBoxConstants.VIRTUALBOX_WORKINGDIR; import static org.jclouds.virtualbox.util.MachineUtils.*;
import static org.virtualbox_4_1.AccessMode.ReadOnly;
import static org.virtualbox_4_1.DeviceType.DVD;
import static org.virtualbox_4_1.DeviceType.HardDisk;
import static org.virtualbox_4_1.LockType.Shared; import static org.virtualbox_4_1.LockType.Shared;
import static org.virtualbox_4_1.LockType.Write; import static org.virtualbox_4_1.LockType.Write;
import static org.virtualbox_4_1.NATProtocol.TCP;
public class IsoToIMachine implements Function<String, IMachine> { public class IsoToIMachine implements Function<String, IMachine> {
@ -58,40 +54,30 @@ public class IsoToIMachine implements Function<String, IMachine> {
@Named(ComputeServiceConstants.COMPUTE_LOGGER) @Named(ComputeServiceConstants.COMPUTE_LOGGER)
protected Logger logger = Logger.NULL; protected Logger logger = Logger.NULL;
private VirtualBoxManager manager; private final VirtualBoxManager manager;
private String adminDisk;
private String diskFormat;
private String vmName;
private String osTypeId;
private String vmId;
private String controllerIDE;
private boolean forceOverwrite;
private ComputeServiceContext context;
private String hostId;
private String guestId; private String guestId;
private Predicate<IPSocket> socketTester; private final VmSpecification vmSpecification;
private String webServerHost; private final ComputeServiceContext context;
private int webServerPort; private final String hostId;
private final Predicate<IPSocket> socketTester;
private final String webServerHost;
private final int webServerPort;
private final ExecutionType executionType;
@Inject @Inject
public IsoToIMachine(VirtualBoxManager manager, String adminDisk, String diskFormat, public IsoToIMachine(VirtualBoxManager manager, String guestId,
String vmName, String osTypeId, String vmId, boolean forceOverwrite, String controllerIDE, VmSpecification vmSpecification, ComputeServiceContext context,
ComputeServiceContext context, String hostId, String guestId, Predicate<IPSocket> socketTester, String hostId, Predicate<IPSocket> socketTester,
String webServerHost, int webServerPort) { String webServerHost, int webServerPort, ExecutionType executionType) {
this.manager = manager; this.manager = manager;
this.adminDisk = adminDisk; this.guestId = guestId;
this.diskFormat = diskFormat; this.vmSpecification = vmSpecification;
this.vmName = vmName;
this.osTypeId = osTypeId;
this.vmId = vmId;
this.controllerIDE = controllerIDE;
this.forceOverwrite = forceOverwrite;
this.context = context; this.context = context;
this.hostId = hostId; this.hostId = hostId;
this.guestId = guestId;
this.socketTester = socketTester; this.socketTester = socketTester;
this.webServerHost = webServerHost; this.webServerHost = webServerHost;
this.webServerPort = webServerPort; this.webServerPort = webServerPort;
this.executionType = executionType;
} }
@Override @Override
@ -99,51 +85,37 @@ public class IsoToIMachine implements Function<String, IMachine> {
ensureWebServerIsRunning(); ensureWebServerIsRunning();
final IMachine vm = new CreateAndRegisterMachineFromIsoIfNotAlreadyExists(osTypeId, vmId, forceOverwrite, final IMachine vm = new CreateAndRegisterMachineFromIsoIfNotAlreadyExists(manager).apply(vmSpecification);
manager).apply(vmName);
final String defaultWorkingDir = System.getProperty("user.home") + "/jclouds-virtualbox-test"; String vmName = vmSpecification.getVmName();
final String workingDir = System.getProperty(VIRTUALBOX_WORKINGDIR, defaultWorkingDir);
// Change RAM // Change RAM
ensureMachineHasMemory(vmName, 1024l); ensureMachineHasMemory(vmName, 1024l);
// IDE Controller Set<StorageController> controllers = vmSpecification.getControllers();
ensureMachineHasIDEControllerNamed(vmName, controllerIDE); if (controllers.isEmpty()) {
throw new IllegalStateException(missingIDEControllersMessage());
// Distribution medium
ensureMachineHasAttachedDistroMedium(isoName, workingDir, controllerIDE);
// DISK
final String adminDiskPath = workingDir + "/" + adminDisk;
if (new File(adminDiskPath).exists()) {
boolean deleted = new File(adminDiskPath).delete();
if (!deleted) {
logger.error(String.format("File %s could not be deleted.", adminDiskPath));
}
} }
StorageController controller = controllers.iterator().next();
ensureMachineHasIDEControllerNamed(vmName, controller);
setupHardDisksForController(vmName, controller);
setupDvdsForController(vmName, controller);
missingIDEControllersMessage();
// Create hard disk
final IMedium hardDisk = new CreateMediumIfNotAlreadyExists(manager, diskFormat, true).apply(adminDiskPath);
// Attach hard disk to machine
ensureMachineHasHardDiskAttached(vmName, hardDisk);
// NAT // NAT
ensureNATNetworkingIsAppliedToMachine(vmName); Map<Long, NatAdapter> natNetworkAdapters = vmSpecification.getNatNetworkAdapters();
for (Map.Entry<Long, NatAdapter> natAdapterAndSlot : natNetworkAdapters.entrySet()) {
final String guestAdditionsDvd = workingDir + "/VBoxGuestAdditions_4.1.2.iso"; long slotId = natAdapterAndSlot.getKey();
final IMedium guestAdditionsDvdMedium = manager.getVBox().openMedium(guestAdditionsDvd, DeviceType.DVD, NatAdapter natAdapter = natAdapterAndSlot.getValue();
AccessMode.ReadOnly, forceOverwrite); ensureNATNetworkingIsAppliedToMachine(vmName, slotId, natAdapter);
}
// Guest additions
ensureGuestAdditionsMediumIsAttached(vmName, guestAdditionsDvdMedium);
// Launch machine and wait for it to come online // Launch machine and wait for it to come online
ensureMachineIsLaunched(vmName); ensureMachineIsLaunched(vmName);
final String installKeySequence = System.getProperty(VIRTUALBOX_INSTALLATION_KEY_SEQUENCE, defaultInstallSequence()); final String installKeySequence = System.getProperty(VIRTUALBOX_INSTALLATION_KEY_SEQUENCE, defaultInstallSequence(vmName));
sendKeyboardSequence(installKeySequence); sendKeyboardSequence(installKeySequence, vmName);
boolean sshDeamonIsRunning = false; boolean sshDeamonIsRunning = false;
while (!sshDeamonIsRunning) { while (!sshDeamonIsRunning) {
@ -171,6 +143,35 @@ public class IsoToIMachine implements Function<String, IMachine> {
return vm; return vm;
} }
private void setupDvdsForController(String vmName, StorageController controller) {
Set<IsoImage> dvds = controller.getIsoImages();
for (IsoImage dvd : dvds) {
String dvdSource = dvd.getSourcePath();
final IMedium dvdMedium = manager.getVBox().openMedium(dvdSource, DeviceType.DVD,
AccessMode.ReadOnly, vmSpecification.isForceOverwrite());
ensureMachineDevicesAttached(vmName, dvdMedium, dvd.getDeviceDetails(), controller.getName());
}
}
private void setupHardDisksForController(String vmName, StorageController controller) {
Set<HardDisk> hardDisks = controller.getHardDisks();
for (HardDisk hardDisk : hardDisks) {
String sourcePath = hardDisk.getDiskPath();
if (new File(sourcePath).exists()) {
boolean deleted = new File(sourcePath).delete();
if (!deleted) {
logger.error(String.format("File %s could not be deleted.", sourcePath));
}
}
IMedium medium = new CreateMediumIfNotAlreadyExists(manager, true).apply(hardDisk);
ensureMachineDevicesAttached(vmName, medium, hardDisk.getDeviceDetails(), controller.getName());
}
}
private String missingIDEControllersMessage() {
return String.format("First controller is not an IDE controller. Please verify that the VM spec is a correct master node: %s", vmSpecification);
}
private void ensureWebServerIsRunning() { private void ensureWebServerIsRunning() {
final IPSocket webServerSocket = new IPSocket(webServerHost, webServerPort); final IPSocket webServerSocket = new IPSocket(webServerHost, webServerPort);
if (!socketTester.apply(webServerSocket)) { if (!socketTester.apply(webServerSocket)) {
@ -179,52 +180,27 @@ public class IsoToIMachine implements Function<String, IMachine> {
} }
private void ensureMachineIsLaunched(String vmName) { private void ensureMachineIsLaunched(String vmName) {
applyForMachine(manager, vmName, new LaunchMachineIfNotAlreadyRunning(manager, ExecutionType.HEADLESS, "")); applyForMachine(manager, vmName, new LaunchMachineIfNotAlreadyRunning(manager, executionType, ""));
} }
private void ensureGuestAdditionsMediumIsAttached(String vmName, final IMedium guestAdditionsDvdMedium) { private void ensureMachineDevicesAttached(String vmName, IMedium medium, DeviceDetails deviceDetails, String controllerName) {
lockMachineAndApply(manager, Write, vmName, new AttachMediumToMachineIfNotAlreadyAttached(controllerIDE, lockMachineAndApply(manager, Write, vmName, new AttachMediumToMachineIfNotAlreadyAttached(deviceDetails, medium, controllerName));
guestAdditionsDvdMedium, 1, 1, DeviceType.DVD));
}
private void ensureMachineHasHardDiskAttached(String vmName, IMedium hardDisk) {
lockMachineAndApply(manager, Write, vmName, new AttachMediumToMachineIfNotAlreadyAttached(controllerIDE,
hardDisk, 0, 1, HardDisk));
} }
private void ensureMachineHasMemory(String vmName, final long memorySize) { private void ensureMachineHasMemory(String vmName, final long memorySize) {
lockMachineAndApply(manager, Write, vmName, new ApplyMemoryToMachine(memorySize)); lockMachineAndApply(manager, Write, vmName, new ApplyMemoryToMachine(memorySize));
} }
private void ensureNATNetworkingIsAppliedToMachine(String vmName) { private void ensureNATNetworkingIsAppliedToMachine(String vmName, long slotId, NatAdapter natAdapter) {
lockMachineAndApply(manager, Write, vmName, new AttachNATRedirectRuleToMachine(0l, new RedirectRule(TCP, "127.0.0.1", 2222, "", 22))); lockMachineAndApply(manager, Write, vmName, new AttachNATAdapterToMachine(slotId, natAdapter));
} }
private void ensureMachineHasAttachedDistroMedium(String isoName, String workingDir, String controllerIDE) { public void ensureMachineHasIDEControllerNamed(String vmName, StorageController storageController) {
final String pathToIsoFile = checkFileExists(workingDir + "/" + isoName);
final IMedium distroMedium = manager.getVBox().openMedium(pathToIsoFile, DVD, ReadOnly, forceOverwrite);
lockMachineAndApply(
manager,
Write,
vmName,
new AttachDistroMediumToMachine(checkNotNull(controllerIDE, "controllerIDE"), checkNotNull(distroMedium,
"distroMedium")));
}
public static String checkFileExists(String filePath) {
if (new File(filePath).exists()) {
return filePath;
}
throw new IllegalStateException("File " + filePath + " does not exist.");
}
public void ensureMachineHasIDEControllerNamed(String vmName, String controllerIDE) {
lockMachineAndApply(manager, Write, checkNotNull(vmName, "vmName"), lockMachineAndApply(manager, Write, checkNotNull(vmName, "vmName"),
new AddIDEControllerIfNotExists(checkNotNull(controllerIDE, "controllerIDE"))); new AddIDEControllerIfNotExists(checkNotNull(storageController, "storageController")));
} }
private String defaultInstallSequence(String vmName) {
private String defaultInstallSequence() {
return "<Esc><Esc><Enter> " return "<Esc><Esc><Enter> "
+ "/install/vmlinuz noapic preseed/url=http://10.0.2.2:" + webServerPort + "/src/test/resources/preseed.cfg " + "/install/vmlinuz noapic preseed/url=http://10.0.2.2:" + webServerPort + "/src/test/resources/preseed.cfg "
+ "debian-installer=en_US auto locale=en_US kbd-chooser/method=us " + "hostname=" + vmName + " " + "debian-installer=en_US auto locale=en_US kbd-chooser/method=us " + "hostname=" + vmName + " "
@ -233,7 +209,7 @@ public class IsoToIMachine implements Function<String, IMachine> {
+ "initrd=/install/initrd.gz -- <Enter>"; + "initrd=/install/initrd.gz -- <Enter>";
} }
private void sendKeyboardSequence(String keyboardSequence) { private void sendKeyboardSequence(String keyboardSequence, String vmName) {
String[] splitSequence = keyboardSequence.split(" "); String[] splitSequence = keyboardSequence.split(" ");
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
for (String line : splitSequence) { for (String line : splitSequence) {

View File

@ -0,0 +1,31 @@
/*
* 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.util;
import static org.jclouds.virtualbox.config.VirtualBoxConstants.VIRTUALBOX_WORKINGDIR;
public class PropertyUtils {
public static String getWorkingDirFromProperty() {
final String defaultWorkingDir = System.getProperty("user.home") + "/jclouds-virtualbox-test";
return System.getProperty(VIRTUALBOX_WORKINGDIR, defaultWorkingDir);
}
}

View File

@ -19,22 +19,18 @@
package org.jclouds.virtualbox.functions; package org.jclouds.virtualbox.functions;
import static org.easymock.EasyMock.expect; import org.jclouds.virtualbox.domain.StorageController;
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 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.IStorageController; import org.virtualbox_4_1.IStorageController;
import org.virtualbox_4_1.StorageBus; import org.virtualbox_4_1.StorageBus;
import org.virtualbox_4_1.VBoxException; import org.virtualbox_4_1.VBoxException;
import static org.easymock.EasyMock.expect;
import static org.easymock.classextension.EasyMock.*;
/** /**
*
* @author Adrian Cole * @author Adrian Cole
*
*/ */
@Test(groups = "unit", testName = "AddIDEControllerIfNotExistsTest") @Test(groups = "unit", testName = "AddIDEControllerIfNotExistsTest")
public class AddIDEControllerIfNotExistsTest { public class AddIDEControllerIfNotExistsTest {
@ -44,6 +40,7 @@ public class AddIDEControllerIfNotExistsTest {
IMachine vm = createMock(IMachine.class); IMachine vm = createMock(IMachine.class);
String controllerName = "IDE Controller"; String controllerName = "IDE Controller";
StorageController storageController = StorageController.builder().bus(StorageBus.IDE).name(controllerName).build();
expect(vm.addStorageController(controllerName, StorageBus.IDE)).andReturn( expect(vm.addStorageController(controllerName, StorageBus.IDE)).andReturn(
createNiceMock(IStorageController.class)); createNiceMock(IStorageController.class));
@ -51,7 +48,7 @@ public class AddIDEControllerIfNotExistsTest {
replay(vm); replay(vm);
new AddIDEControllerIfNotExists(controllerName).apply(vm); new AddIDEControllerIfNotExists(storageController).apply(vm);
verify(vm); verify(vm);
} }
@ -61,6 +58,7 @@ public class AddIDEControllerIfNotExistsTest {
IMachine vm = createMock(IMachine.class); IMachine vm = createMock(IMachine.class);
String controllerName = "IDE Controller"; String controllerName = "IDE Controller";
StorageController storageController = StorageController.builder().bus(StorageBus.IDE).name(controllerName).build();
expect(vm.addStorageController(controllerName, StorageBus.IDE)).andThrow( expect(vm.addStorageController(controllerName, StorageBus.IDE)).andThrow(
new VBoxException(createNiceMock(Throwable.class), new VBoxException(createNiceMock(Throwable.class),
@ -68,7 +66,7 @@ public class AddIDEControllerIfNotExistsTest {
replay(vm); replay(vm);
new AddIDEControllerIfNotExists(controllerName).apply(vm); new AddIDEControllerIfNotExists(storageController).apply(vm);
verify(vm); verify(vm);
} }
@ -78,13 +76,14 @@ public class AddIDEControllerIfNotExistsTest {
IMachine vm = createMock(IMachine.class); IMachine vm = createMock(IMachine.class);
String controllerName = "IDE Controller"; String controllerName = "IDE Controller";
StorageController storageController = StorageController.builder().bus(StorageBus.IDE).name(controllerName).build();
expect(vm.addStorageController(controllerName, StorageBus.IDE)).andThrow( expect(vm.addStorageController(controllerName, StorageBus.IDE)).andThrow(
new VBoxException(createNiceMock(Throwable.class), "VirtualBox error: General Error")); new VBoxException(createNiceMock(Throwable.class), "VirtualBox error: General Error"));
replay(vm); replay(vm);
new AddIDEControllerIfNotExists(controllerName).apply(vm); new AddIDEControllerIfNotExists(storageController).apply(vm);
verify(vm); verify(vm);
} }

View File

@ -1,80 +0,0 @@
/*
* 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 org.jclouds.virtualbox.BaseVirtualBoxClientLiveTest;
import org.jclouds.virtualbox.functions.admin.UnregisterMachineIfExists;
import org.jclouds.virtualbox.util.MachineUtils;
import org.testng.annotations.Test;
import org.virtualbox_4_1.CleanupMode;
import org.virtualbox_4_1.IMedium;
import org.virtualbox_4_1.LockType;
import java.io.File;
import static org.jclouds.virtualbox.util.MachineUtils.lockMachineAndApply;
import static org.testng.Assert.assertTrue;
/**
* @author Mattias Holmqvist
*/
public class AttachDistroMediumToMachineLiveTest extends BaseVirtualBoxClientLiveTest {
@Test
public void testAttachMediumToMachine() throws Exception {
String nodeName = "test-attach-medium-node-1";
String controllerName = "My Controller";
new UnregisterMachineIfExists(manager, CleanupMode.Full).apply(nodeName);
String path = System.getProperty("user.home") + "/jclouds-virtualbox-test/test-attach-medium-1.vdi";
new CreateAndRegisterMachineFromIsoIfNotAlreadyExists("Debian", nodeName, true, manager)
.apply(nodeName);
lockMachineAndApply(manager, LockType.Write, nodeName,
new AddIDEControllerIfNotExists(controllerName));
IMedium medium = new CreateMediumIfNotAlreadyExists(manager, "vdi", true).apply(path);
lockMachineAndApply(manager, LockType.Write, nodeName,
new AttachDistroMediumToMachine(controllerName, medium));
new UnregisterMachineIfExists(manager, CleanupMode.Full).apply(nodeName);
medium.close();
assertFileCanBeDeleted(path);
}
@Test
public void testAttachMediumToMachineTwice() throws Exception {
String nodeName = "test-attach-medium-node-2";
String controllerName = "My Controller";
new UnregisterMachineIfExists(manager, CleanupMode.Full).apply(nodeName);
String path = System.getProperty("user.home") + "/jclouds-virtualbox-test/test-attach-medium-2.vdi";
new CreateAndRegisterMachineFromIsoIfNotAlreadyExists("Debian", nodeName, true, manager)
.apply(nodeName);
lockMachineAndApply(manager, LockType.Write, nodeName, new AddIDEControllerIfNotExists(controllerName));
IMedium medium = new CreateMediumIfNotAlreadyExists(manager, "vdi", true).apply(path);
lockMachineAndApply(manager, LockType.Write, nodeName, new AttachDistroMediumToMachine(controllerName, medium));
lockMachineAndApply(manager, LockType.Write, nodeName, new AttachDistroMediumToMachine(controllerName, medium));
new UnregisterMachineIfExists(manager, CleanupMode.Full).apply(nodeName);
medium.close();
assertFileCanBeDeleted(path);
}
private void assertFileCanBeDeleted(String path) {
File file = new File(path);
boolean mediumDeleted = file.delete();
assertTrue(mediumDeleted);
}
}

View File

@ -1,110 +0,0 @@
/**
* 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 org.easymock.EasyMock.expectLastCall;
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 org.testng.annotations.Test;
import org.virtualbox_4_1.DeviceType;
import org.virtualbox_4_1.IMachine;
import org.virtualbox_4_1.IMedium;
import org.virtualbox_4_1.VBoxException;
/**
* @author Mattias Holmqvist
*/
@Test(groups = "unit", testName = "AttachDistroMediumToMachineTest")
public class AttachDistroMediumToMachineTest {
@Test
public void testAttachDistroMedium() throws Exception {
String controllerIDE = "IDE Controller";
IMedium distroMedium = createNiceMock(IMedium.class);
IMachine machine = createMock(IMachine.class);
machine.saveSettings();
machine.attachDevice(controllerIDE, 0, 0, DeviceType.DVD, distroMedium);
replay(machine, distroMedium);
new AttachDistroMediumToMachine(controllerIDE, distroMedium).apply(machine);
verify(machine);
}
@Test
public void testAcceptAlreadyAttachedDistroMedium() throws Exception {
String controllerIDE = "IDE Controller";
IMedium distroMedium = createNiceMock(IMedium.class);
IMachine machine = createNiceMock(IMachine.class);
final StringBuilder errorBuilder = new StringBuilder();
errorBuilder.append("VirtualBox error: ");
errorBuilder.append("Medium '/Users/johndoe/jclouds-virtualbox-test/ubuntu-11.04-server-i386.iso' ");
errorBuilder.append("is already attached to port 0, device 0 of controller 'IDE Controller' ");
errorBuilder.append("of this virtual machine (0x80BB000C)");
String isoAlreadyAttachedException = errorBuilder.toString();
VBoxException isoAttachedException = new VBoxException(createNiceMock(Throwable.class),
isoAlreadyAttachedException);
machine.attachDevice(controllerIDE, 0, 0, DeviceType.DVD, distroMedium);
expectLastCall().andThrow(isoAttachedException);
replay(machine, distroMedium);
new AttachDistroMediumToMachine(controllerIDE, distroMedium).apply(machine);
verify(machine);
}
@Test(expectedExceptions = VBoxException.class)
public void testFailOnOtherVBoxErrors() throws Exception {
String controllerIDE = "IDE Controller";
IMedium distroMedium = createNiceMock(IMedium.class);
IMachine machine = createNiceMock(IMachine.class);
final StringBuilder errorBuilder = new StringBuilder();
errorBuilder.append("VirtualBox error: ");
errorBuilder.append("Some other VBox error");
String isoAlreadyAttachedException = errorBuilder.toString();
VBoxException isoAttachedException = new VBoxException(createNiceMock(Throwable.class),
isoAlreadyAttachedException);
machine.attachDevice(controllerIDE, 0, 0, DeviceType.DVD, distroMedium);
expectLastCall().andThrow(isoAttachedException);
replay(machine, distroMedium);
new AttachDistroMediumToMachine(controllerIDE, distroMedium).apply(machine);
}
}

View File

@ -19,6 +19,14 @@
package org.jclouds.virtualbox.functions; package org.jclouds.virtualbox.functions;
import com.google.common.collect.Iterables;
import org.jclouds.virtualbox.domain.DeviceDetails;
import org.jclouds.virtualbox.domain.HardDisk;
import org.jclouds.virtualbox.domain.StorageController;
import org.testng.annotations.Test;
import org.virtualbox_4_1.*;
import static com.google.common.collect.Iterables.getOnlyElement;
import static org.easymock.EasyMock.anyLong; import static org.easymock.EasyMock.anyLong;
import static org.easymock.EasyMock.expect; import static org.easymock.EasyMock.expect;
import static org.easymock.EasyMock.expectLastCall; import static org.easymock.EasyMock.expectLastCall;
@ -28,14 +36,6 @@ import static org.easymock.classextension.EasyMock.replay;
import static org.easymock.classextension.EasyMock.verify; import static org.easymock.classextension.EasyMock.verify;
import static org.virtualbox_4_1.DeviceType.HardDisk; import static org.virtualbox_4_1.DeviceType.HardDisk;
import org.testng.annotations.Test;
import org.virtualbox_4_1.IMachine;
import org.virtualbox_4_1.IMedium;
import org.virtualbox_4_1.IProgress;
import org.virtualbox_4_1.IVirtualBox;
import org.virtualbox_4_1.VBoxException;
import org.virtualbox_4_1.VirtualBoxManager;
/** /**
* @author Mattias Holmqvist * @author Mattias Holmqvist
*/ */
@ -45,8 +45,8 @@ public class AttachMediumToMachineIfNotAlreadyAttachedTest {
@Test @Test
public void testAttachHardDiskIfNotAttached() throws Exception { public void testAttachHardDiskIfNotAttached() throws Exception {
String controllerIDE = "IDE Controller"; String controllerName = "IDE Controller";
String adminDiskPath = "/Users/johndoe/jclouds-virtualbox-images/admin.vdi"; String diskPath = "/Users/johndoe/jclouds-virtualbox-images/admin.vdi";
String diskFormat = "vdi"; String diskFormat = "vdi";
int controllerPort = 0; int controllerPort = 0;
int device = 1; int device = 1;
@ -58,15 +58,22 @@ public class AttachMediumToMachineIfNotAlreadyAttachedTest {
IProgress progress = createNiceMock(IProgress.class); IProgress progress = createNiceMock(IProgress.class);
expect(manager.getVBox()).andReturn(vBox).anyTimes(); expect(manager.getVBox()).andReturn(vBox).anyTimes();
expect(vBox.createHardDisk(diskFormat, adminDiskPath)).andReturn(hardDisk); expect(vBox.createHardDisk(diskFormat, diskPath)).andReturn(hardDisk);
expect(hardDisk.createBaseStorage(anyLong(), anyLong())).andReturn(progress); expect(hardDisk.createBaseStorage(anyLong(), anyLong())).andReturn(progress);
machine.attachDevice(controllerIDE, controllerPort, device, HardDisk, hardDisk); machine.attachDevice(controllerName, controllerPort, device, HardDisk, hardDisk);
machine.saveSettings(); machine.saveSettings();
replay(manager, machine, vBox, hardDisk); replay(manager, machine, vBox, hardDisk);
new AttachMediumToMachineIfNotAlreadyAttached(controllerIDE, hardDisk, controllerPort, device, HardDisk) StorageController controller = StorageController.builder()
.apply(machine); .name(controllerName)
.bus(StorageBus.IDE)
.attachHardDisk(controllerPort, device, diskPath)
.build();
DeviceDetails deviceDetails = getOnlyElement(controller.getHardDisks()).getDeviceDetails();
new AttachMediumToMachineIfNotAlreadyAttached(deviceDetails, hardDisk, controllerName).apply(machine);
verify(machine); verify(machine);
@ -75,9 +82,9 @@ public class AttachMediumToMachineIfNotAlreadyAttachedTest {
@Test @Test
public void testDoNothingIfAlreadyAttachedAttachHardDisk() throws Exception { public void testDoNothingIfAlreadyAttachedAttachHardDisk() throws Exception {
String controllerIDE = "IDE Controller"; String controllerName = "IDE Controller";
int controllerPort = 0; int controllerPort = 0;
int device = 1; int deviceSlot = 1;
VirtualBoxManager manager = createNiceMock(VirtualBoxManager.class); VirtualBoxManager manager = createNiceMock(VirtualBoxManager.class);
IMachine machine = createMock(IMachine.class); IMachine machine = createMock(IMachine.class);
@ -93,13 +100,19 @@ public class AttachMediumToMachineIfNotAlreadyAttachedTest {
VBoxException isoAttachedException = new VBoxException(createNiceMock(Throwable.class), VBoxException isoAttachedException = new VBoxException(createNiceMock(Throwable.class),
isoAlreadyAttachedException); isoAlreadyAttachedException);
machine.attachDevice(controllerIDE, controllerPort, device, HardDisk, hardDisk); machine.attachDevice(controllerName, controllerPort, deviceSlot, HardDisk, hardDisk);
expectLastCall().andThrow(isoAttachedException); expectLastCall().andThrow(isoAttachedException);
replay(manager, machine, vBox, hardDisk); replay(manager, machine, vBox, hardDisk);
new AttachMediumToMachineIfNotAlreadyAttached(controllerIDE, hardDisk, controllerPort, device, HardDisk) StorageController controller = StorageController.builder()
.apply(machine); .name(controllerName)
.bus(StorageBus.IDE)
.attachHardDisk(controllerPort, deviceSlot, "/Users/mattias/jclouds-virtualbox-test/testadmin.vdi")
.build();
DeviceDetails deviceDetails = getOnlyElement(controller.getHardDisks()).getDeviceDetails();
new AttachMediumToMachineIfNotAlreadyAttached(deviceDetails, hardDisk, controllerName).apply(machine);
verify(machine); verify(machine);
@ -108,9 +121,9 @@ public class AttachMediumToMachineIfNotAlreadyAttachedTest {
@Test(expectedExceptions = VBoxException.class) @Test(expectedExceptions = VBoxException.class)
public void testFailOnOtherVBoxError() throws Exception { public void testFailOnOtherVBoxError() throws Exception {
String controllerIDE = "IDE Controller"; String controllerName = "IDE Controller";
int controllerPort = 0; int controllerPort = 0;
int device = 1; int deviceSlot = 1;
VirtualBoxManager manager = createNiceMock(VirtualBoxManager.class); VirtualBoxManager manager = createNiceMock(VirtualBoxManager.class);
IMachine machine = createMock(IMachine.class); IMachine machine = createMock(IMachine.class);
@ -124,13 +137,20 @@ public class AttachMediumToMachineIfNotAlreadyAttachedTest {
VBoxException isoAttachedException = new VBoxException(createNiceMock(Throwable.class), VBoxException isoAttachedException = new VBoxException(createNiceMock(Throwable.class),
isoAlreadyAttachedException); isoAlreadyAttachedException);
machine.attachDevice(controllerIDE, controllerPort, device, HardDisk, hardDisk); machine.attachDevice(controllerName, controllerPort, deviceSlot, HardDisk, hardDisk);
expectLastCall().andThrow(isoAttachedException); expectLastCall().andThrow(isoAttachedException);
replay(manager, machine, vBox, hardDisk); replay(manager, machine, vBox, hardDisk);
new AttachMediumToMachineIfNotAlreadyAttached(controllerIDE, hardDisk, controllerPort, device, HardDisk)
.apply(machine); StorageController controller = StorageController.builder()
.name(controllerName)
.bus(StorageBus.IDE)
.attachHardDisk(controllerPort, deviceSlot, "/Users/mattias/jclouds-virtualbox-test/testadmin.vdi")
.build();
DeviceDetails deviceDetails = getOnlyElement(controller.getHardDisks()).getDeviceDetails();
new AttachMediumToMachineIfNotAlreadyAttached(deviceDetails, hardDisk, controllerName).apply(machine);
} }

View File

@ -19,35 +19,32 @@
package org.jclouds.virtualbox.functions; package org.jclouds.virtualbox.functions;
import static org.easymock.EasyMock.expect; import org.jclouds.virtualbox.domain.NatAdapter;
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.virtualbox_4_1.NATProtocol.TCP;
import static org.virtualbox_4_1.NetworkAttachmentType.NAT;
import org.jclouds.virtualbox.domain.RedirectRule;
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.VBoxException; import org.virtualbox_4_1.VBoxException;
import static org.easymock.EasyMock.expect;
import static org.easymock.classextension.EasyMock.*;
import static org.virtualbox_4_1.NATProtocol.TCP;
import static org.virtualbox_4_1.NetworkAttachmentType.NAT;
/** /**
* @author Mattias Holmqvist * @author Mattias Holmqvist
*/ */
@Test(groups = "unit", testName = "AttachNATRedirectRuleToMachineTest") @Test(groups = "unit", testName = "AttachNATAdapterToMachineTest")
public class AttachNATRedirectRuleToMachineTest { public class AttachNATAdapterToMachineTest {
@Test @Test
public void testApplyNetworkingToNonExistingAdapter() throws Exception { public void testApplyNetworkingToNonExistingAdapter() throws Exception {
Long adapterId = 0l; Long slotId = 0l;
IMachine machine = createMock(IMachine.class); IMachine machine = createMock(IMachine.class);
INetworkAdapter networkAdapter = createMock(INetworkAdapter.class); INetworkAdapter networkAdapter = createMock(INetworkAdapter.class);
INATEngine natEngine = createMock(INATEngine.class); INATEngine natEngine = createMock(INATEngine.class);
expect(machine.getNetworkAdapter(adapterId)).andReturn(networkAdapter); expect(machine.getNetworkAdapter(slotId)).andReturn(networkAdapter);
networkAdapter.setAttachmentType(NAT); networkAdapter.setAttachmentType(NAT);
expect(networkAdapter.getNatDriver()).andReturn(natEngine); expect(networkAdapter.getNatDriver()).andReturn(natEngine);
natEngine.addRedirect("guestssh", TCP, "127.0.0.1", 2222, "", 22); natEngine.addRedirect("guestssh", TCP, "127.0.0.1", 2222, "", 22);
@ -55,15 +52,15 @@ public class AttachNATRedirectRuleToMachineTest {
machine.saveSettings(); machine.saveSettings();
replay(machine, networkAdapter, natEngine); replay(machine, networkAdapter, natEngine);
NatAdapter natAdapter = NatAdapter.builder().tcpRedirectRule("127.0.0.1", 2222, "", 22).build();
new AttachNATRedirectRuleToMachine(adapterId, new RedirectRule(TCP, "127.0.0.1", 2222, "", 22)).apply(machine); new AttachNATAdapterToMachine(slotId, natAdapter).apply(machine);
verify(machine, networkAdapter, natEngine); verify(machine, networkAdapter, natEngine);
} }
@Test(expectedExceptions = VBoxException.class) @Test(expectedExceptions = VBoxException.class)
public void testRethrowInvalidAdapterSlotException() throws Exception { public void testRethrowInvalidAdapterSlotException() throws Exception {
Long adapterId = 30l; Long slotId = 30l;
IMachine machine = createMock(IMachine.class); IMachine machine = createMock(IMachine.class);
INetworkAdapter networkAdapter = createMock(INetworkAdapter.class); INetworkAdapter networkAdapter = createMock(INetworkAdapter.class);
INATEngine natEngine = createMock(INATEngine.class); INATEngine natEngine = createMock(INATEngine.class);
@ -72,11 +69,12 @@ public class AttachNATRedirectRuleToMachineTest {
+ "(must be slot < RT_ELEMENTS(mNetworkAdapters)) (0x80070057)"; + "(must be slot < RT_ELEMENTS(mNetworkAdapters)) (0x80070057)";
VBoxException invalidSlotException = new VBoxException(createNiceMock(Throwable.class), error); VBoxException invalidSlotException = new VBoxException(createNiceMock(Throwable.class), error);
expect(machine.getNetworkAdapter(adapterId)).andThrow(invalidSlotException); expect(machine.getNetworkAdapter(slotId)).andThrow(invalidSlotException);
replay(machine, networkAdapter, natEngine); replay(machine, networkAdapter, natEngine);
new AttachNATRedirectRuleToMachine(adapterId, new RedirectRule(TCP, "127.0.0.1", 2222, "", 22)).apply(machine); NatAdapter natAdapter = NatAdapter.builder().tcpRedirectRule("127.0.0.1", 2222, "", 22).build();
new AttachNATAdapterToMachine(slotId, natAdapter).apply(machine);
verify(machine, networkAdapter, natEngine); verify(machine, networkAdapter, natEngine);
} }

View File

@ -19,24 +19,26 @@
package org.jclouds.virtualbox.functions; package org.jclouds.virtualbox.functions;
import static org.jclouds.virtualbox.experiment.TestUtils.computeServiceForLocalhostAndGuest; import com.google.common.base.Predicate;
import static org.testng.Assert.assertEquals;
import static org.virtualbox_4_1.NetworkAttachmentType.Bridged;
import java.util.concurrent.TimeUnit;
import org.jclouds.compute.ComputeServiceContext; import org.jclouds.compute.ComputeServiceContext;
import org.jclouds.domain.Credentials; import org.jclouds.domain.Credentials;
import org.jclouds.net.IPSocket; import org.jclouds.net.IPSocket;
import org.jclouds.predicates.InetSocketAddressConnect; import org.jclouds.predicates.InetSocketAddressConnect;
import org.jclouds.predicates.RetryablePredicate; import org.jclouds.predicates.RetryablePredicate;
import org.jclouds.virtualbox.BaseVirtualBoxClientLiveTest; import org.jclouds.virtualbox.BaseVirtualBoxClientLiveTest;
import org.jclouds.virtualbox.domain.HardDisk;
import org.jclouds.virtualbox.domain.StorageController;
import org.jclouds.virtualbox.domain.VmSpecification;
import org.jclouds.virtualbox.util.PropertyUtils;
import org.testng.annotations.Test; import org.testng.annotations.Test;
import org.virtualbox_4_1.IMachine; import org.virtualbox_4_1.*;
import org.virtualbox_4_1.ISession;
import org.virtualbox_4_1.VirtualBoxManager;
import com.google.common.base.Predicate; import java.util.concurrent.TimeUnit;
import static org.jclouds.virtualbox.domain.ExecutionType.HEADLESS;
import static org.jclouds.virtualbox.experiment.TestUtils.computeServiceForLocalhostAndGuest;
import static org.testng.Assert.assertEquals;
import static org.virtualbox_4_1.NetworkAttachmentType.Bridged;
/** /**
* @author Andrea Turli * @author Andrea Turli
@ -49,8 +51,6 @@ public class CloneAndRegisterMachineFromIsoIfNotAlreadyExistsLiveTest extends Ba
private String vmId = "jclouds-image-iso-1"; private String vmId = "jclouds-image-iso-1";
private String osTypeId = ""; private String osTypeId = "";
private String controllerIDE = "IDE Controller"; private String controllerIDE = "IDE Controller";
private String diskFormat = "";
private String adminDisk = "testadmin.vdi";
private String guestId = "guest"; private String guestId = "guest";
private String hostId = "host"; private String hostId = "host";
private String snapshotName = "snap"; private String snapshotName = "snap";
@ -84,10 +84,17 @@ public class CloneAndRegisterMachineFromIsoIfNotAlreadyExistsLiveTest extends Ba
private IMachine getMasterNode(VirtualBoxManager manager, ComputeServiceContext localHostContext) { private IMachine getMasterNode(VirtualBoxManager manager, ComputeServiceContext localHostContext) {
try { try {
Predicate<IPSocket> socketTester = new RetryablePredicate<IPSocket>(new InetSocketAddressConnect(), 10, 1, TimeUnit.SECONDS); Predicate<IPSocket> socketTester = new RetryablePredicate<IPSocket>(new InetSocketAddressConnect(), 10, 1, TimeUnit.SECONDS);
return new IsoToIMachine(manager, adminDisk, diskFormat, String workingDir = PropertyUtils.getWorkingDirFromProperty();
vmName, osTypeId, vmId, forceOverwrite, StorageController ideController = StorageController.builder().name(controllerIDE).bus(StorageBus.IDE)
controllerIDE, localHostContext, hostId, guestId, socketTester, .attachISO(0, 0, workingDir + "/ubuntu-11.04-server-i386.iso")
"127.0.0.1", 8080).apply(isoName); .attachHardDisk(0, 1, workingDir + "/testadmin.vdi")
.attachISO(1, 1, workingDir + "/VBoxGuestAdditions_4.1.2.iso").build();
VmSpecification vmSpecification = VmSpecification.builder().id(vmId).name(vmName).osTypeId(osTypeId)
.controller(ideController)
.forceOverwrite(true).build();
return new IsoToIMachine(manager, guestId,
vmSpecification, localHostContext, hostId, socketTester,
"127.0.0.1", 8080, HEADLESS).apply(isoName);
} catch (IllegalStateException e) { } catch (IllegalStateException e) {
// already created // already created
return manager.getVBox().findMachine(vmName); return manager.getVBox().findMachine(vmName);

View File

@ -21,6 +21,7 @@ package org.jclouds.virtualbox.functions;
import org.jclouds.virtualbox.BaseVirtualBoxClientLiveTest; import org.jclouds.virtualbox.BaseVirtualBoxClientLiveTest;
import org.jclouds.virtualbox.domain.ErrorCode; import org.jclouds.virtualbox.domain.ErrorCode;
import org.jclouds.virtualbox.domain.VmSpecification;
import org.jclouds.virtualbox.functions.admin.UnregisterMachineIfExists; import org.jclouds.virtualbox.functions.admin.UnregisterMachineIfExists;
import org.testng.annotations.Test; import org.testng.annotations.Test;
import org.virtualbox_4_1.CleanupMode; import org.virtualbox_4_1.CleanupMode;
@ -37,20 +38,24 @@ public class CreateAndRegisterMachineFromIsoIfNotAlreadyExistsLiveTest extends B
@Test @Test
public void testCreateNewMachine() throws Exception { public void testCreateNewMachine() throws Exception {
new UnregisterMachineIfExists(manager, CleanupMode.Full).apply("jclouds-test-create-1-node"); String vmName = "jclouds-test-create-1-node";
IMachine debianNode = new CreateAndRegisterMachineFromIsoIfNotAlreadyExists("Debian", "jclouds-test-create-1", true, manager) new UnregisterMachineIfExists(manager, CleanupMode.Full).apply(vmName);
.apply("jclouds-test-create-1-node"); VmSpecification launchSpecification = VmSpecification.builder().id(vmName).name(vmName)
IMachine machine = manager.getVBox().findMachine("jclouds-test-create-1-node"); .osTypeId("Debian").forceOverwrite(true).build();
IMachine debianNode = new CreateAndRegisterMachineFromIsoIfNotAlreadyExists(manager).apply(launchSpecification);
IMachine machine = manager.getVBox().findMachine(vmName);
assertEquals(debianNode.getName(), machine.getName()); assertEquals(debianNode.getName(), machine.getName());
new UnregisterMachineIfExists(manager, CleanupMode.Full).apply("jclouds-test-create-1-node"); new UnregisterMachineIfExists(manager, CleanupMode.Full).apply(vmName);
} }
@Test @Test
public void testCreateNewMachineWithBadOsType() throws Exception { public void testCreateNewMachineWithBadOsType() throws Exception {
new UnregisterMachineIfExists(manager, CleanupMode.Full).apply("jclouds-test-create-2-node"); String vmName = "jclouds-test-create-2-node";
new UnregisterMachineIfExists(manager, CleanupMode.Full).apply(vmName);
VmSpecification launchSpecification = VmSpecification.builder().id(vmName).name(vmName)
.osTypeId("SomeWeirdUnknownOs").forceOverwrite(true).build();
try { try {
new CreateAndRegisterMachineFromIsoIfNotAlreadyExists("SomeWeirdUnknownOs", "jclouds-test-create-2", true, manager) new CreateAndRegisterMachineFromIsoIfNotAlreadyExists(manager).apply(launchSpecification);
.apply("jclouds-test-create-2-node");
fail(); fail();
} catch (VBoxException e) { } catch (VBoxException e) {
ErrorCode errorCode = ErrorCode.valueOf(e); ErrorCode errorCode = ErrorCode.valueOf(e);

View File

@ -29,6 +29,7 @@ import static org.easymock.classextension.EasyMock.replay;
import static org.easymock.classextension.EasyMock.verify; import static org.easymock.classextension.EasyMock.verify;
import org.easymock.EasyMock; import org.easymock.EasyMock;
import org.jclouds.virtualbox.domain.VmSpecification;
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.IVirtualBox; import org.virtualbox_4_1.IVirtualBox;
@ -48,6 +49,8 @@ public class CreateAndRegisterMachineFromIsoIfNotAlreadyExistsTest {
IVirtualBox vBox = createMock(IVirtualBox.class); IVirtualBox vBox = createMock(IVirtualBox.class);
String vmName = "jclouds-image-my-ubuntu-image"; String vmName = "jclouds-image-my-ubuntu-image";
VmSpecification launchSpecification = VmSpecification.builder().id(vmName).name(vmName).osTypeId("").build();
IMachine createdMachine = createMock(IMachine.class); IMachine createdMachine = createMock(IMachine.class);
expect(manager.getVBox()).andReturn(vBox).anyTimes(); expect(manager.getVBox()).andReturn(vBox).anyTimes();
@ -68,7 +71,7 @@ public class CreateAndRegisterMachineFromIsoIfNotAlreadyExistsTest {
replay(manager, vBox); replay(manager, vBox);
new CreateAndRegisterMachineFromIsoIfNotAlreadyExists("", "", false, manager).apply(vmName); new CreateAndRegisterMachineFromIsoIfNotAlreadyExists(manager).apply(launchSpecification);
verify(manager, vBox); verify(manager, vBox);
} }
@ -87,7 +90,8 @@ public class CreateAndRegisterMachineFromIsoIfNotAlreadyExistsTest {
replay(manager, vBox); replay(manager, vBox);
new CreateAndRegisterMachineFromIsoIfNotAlreadyExists("", "", false, manager).apply(vmName); VmSpecification launchSpecification = VmSpecification.builder().id("").name(vmName).osTypeId("").build();
new CreateAndRegisterMachineFromIsoIfNotAlreadyExists(manager).apply(launchSpecification);
} }
@Test(expectedExceptions = VBoxException.class) @Test(expectedExceptions = VBoxException.class)
@ -107,7 +111,8 @@ public class CreateAndRegisterMachineFromIsoIfNotAlreadyExistsTest {
replay(manager, vBox); replay(manager, vBox);
new CreateAndRegisterMachineFromIsoIfNotAlreadyExists("", "", false, manager).apply(vmName); VmSpecification launchSpecification = VmSpecification.builder().id("").name(vmName).osTypeId("").build();
new CreateAndRegisterMachineFromIsoIfNotAlreadyExists(manager).apply(launchSpecification);
} }

View File

@ -20,7 +20,9 @@
package org.jclouds.virtualbox.functions; package org.jclouds.virtualbox.functions;
import org.jclouds.virtualbox.BaseVirtualBoxClientLiveTest; import org.jclouds.virtualbox.BaseVirtualBoxClientLiveTest;
import org.jclouds.virtualbox.domain.DeviceDetails;
import org.jclouds.virtualbox.domain.ErrorCode; import org.jclouds.virtualbox.domain.ErrorCode;
import org.jclouds.virtualbox.domain.HardDisk;
import org.testng.annotations.Test; import org.testng.annotations.Test;
import org.virtualbox_4_1.DeviceType; import org.virtualbox_4_1.DeviceType;
import org.virtualbox_4_1.VBoxException; import org.virtualbox_4_1.VBoxException;
@ -39,7 +41,8 @@ public class CreateMediumIfNotAlreadyExistsLiveTest extends BaseVirtualBoxClient
@Test @Test
public void testCreateMedium() throws Exception { public void testCreateMedium() throws Exception {
String path = System.getProperty("user.home") + "/jclouds-virtualbox-test/test-medium-1.vdi"; String path = System.getProperty("user.home") + "/jclouds-virtualbox-test/test-medium-1.vdi";
new CreateMediumIfNotAlreadyExists(manager, "vdi", true).apply(path); HardDisk hardDisk = new HardDisk(new DeviceDetails(0, 0, DeviceType.HardDisk), path, "vdi");
new CreateMediumIfNotAlreadyExists(manager, true).apply(hardDisk);
manager.getVBox().findMedium(path, DeviceType.HardDisk); manager.getVBox().findMedium(path, DeviceType.HardDisk);
assertFileCanBeDeleted(path); assertFileCanBeDeleted(path);
} }
@ -47,8 +50,9 @@ public class CreateMediumIfNotAlreadyExistsLiveTest extends BaseVirtualBoxClient
@Test @Test
public void testCreateMediumFailWhenUsingNonFullyQualifiedPath() throws Exception { public void testCreateMediumFailWhenUsingNonFullyQualifiedPath() throws Exception {
String path = "test-medium-2.vdi"; String path = "test-medium-2.vdi";
HardDisk hardDisk = new HardDisk(new DeviceDetails(0, 0, DeviceType.HardDisk), path, "vdi");
try { try {
new CreateMediumIfNotAlreadyExists(manager, "vdi", true).apply(path); new CreateMediumIfNotAlreadyExists(manager, true).apply(hardDisk);
fail(); fail();
} catch (VBoxException e) { } catch (VBoxException e) {
ErrorCode errorCode = ErrorCode.valueOf(e); ErrorCode errorCode = ErrorCode.valueOf(e);
@ -59,8 +63,9 @@ public class CreateMediumIfNotAlreadyExistsLiveTest extends BaseVirtualBoxClient
@Test @Test
public void testCreateSameMediumTwiceWhenUsingOverwrite() throws Exception { public void testCreateSameMediumTwiceWhenUsingOverwrite() throws Exception {
String path = System.getProperty("user.home") + "/jclouds-virtualbox-test/test-medium-3.vdi"; String path = System.getProperty("user.home") + "/jclouds-virtualbox-test/test-medium-3.vdi";
new CreateMediumIfNotAlreadyExists(manager, "vdi", true).apply(path); HardDisk hardDisk = new HardDisk(new DeviceDetails(0, 0, DeviceType.HardDisk), path, "vdi");
new CreateMediumIfNotAlreadyExists(manager, "vdi", true).apply(path); new CreateMediumIfNotAlreadyExists(manager, true).apply(hardDisk);
new CreateMediumIfNotAlreadyExists(manager, true).apply(hardDisk);
manager.getVBox().findMedium(path, DeviceType.HardDisk); manager.getVBox().findMedium(path, DeviceType.HardDisk);
assertFileCanBeDeleted(path); assertFileCanBeDeleted(path);
} }

View File

@ -19,7 +19,9 @@
package org.jclouds.virtualbox.functions; package org.jclouds.virtualbox.functions;
import static com.google.common.collect.Iterables.getOnlyElement;
import static org.easymock.EasyMock.anyLong; import static org.easymock.EasyMock.anyLong;
import static org.easymock.EasyMock.eq;
import static org.easymock.EasyMock.expect; import static org.easymock.EasyMock.expect;
import static org.easymock.classextension.EasyMock.createMock; import static org.easymock.classextension.EasyMock.createMock;
import static org.easymock.classextension.EasyMock.createNiceMock; import static org.easymock.classextension.EasyMock.createNiceMock;
@ -27,6 +29,9 @@ import static org.easymock.classextension.EasyMock.replay;
import static org.easymock.classextension.EasyMock.verify; import static org.easymock.classextension.EasyMock.verify;
import static org.testng.Assert.assertNotSame; import static org.testng.Assert.assertNotSame;
import org.jclouds.virtualbox.domain.DeviceDetails;
import org.jclouds.virtualbox.domain.HardDisk;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test; import org.testng.annotations.Test;
import org.virtualbox_4_1.DeviceType; import org.virtualbox_4_1.DeviceType;
import org.virtualbox_4_1.IMachine; import org.virtualbox_4_1.IMachine;
@ -41,15 +46,24 @@ import org.virtualbox_4_1.VirtualBoxManager;
*/ */
public class CreateMediumIfNotAlreadyExistsTest { public class CreateMediumIfNotAlreadyExistsTest {
private String adminDiskPath;
private String diskFormat;
@BeforeMethod
public void setUp() throws Exception {
adminDiskPath = "/Users/johndoe/jclouds-virtualbox-images/admin.vdi";
diskFormat = "vdi";
}
@Test @Test
public void testCreateMediumWhenDiskDoesNotExists() throws Exception { public void testCreateMediumWhenDiskDoesNotExists() throws Exception {
String adminDiskPath = "/Users/johndoe/jclouds-virtualbox-images/admin.vdi";
String diskFormat = "vdi"; HardDisk hardDisk = createTestHardDisk();
VirtualBoxManager manager = createNiceMock(VirtualBoxManager.class); VirtualBoxManager manager = createNiceMock(VirtualBoxManager.class);
IMachine machine = createMock(IMachine.class); IMachine machine = createMock(IMachine.class);
IVirtualBox vBox = createMock(IVirtualBox.class); IVirtualBox vBox = createMock(IVirtualBox.class);
IMedium hardDisk = createMock(IMedium.class); IMedium medium = createMock(IMedium.class);
IProgress progress = createNiceMock(IProgress.class); IProgress progress = createNiceMock(IProgress.class);
StringBuilder errorBuilder = new StringBuilder(); StringBuilder errorBuilder = new StringBuilder();
@ -61,13 +75,13 @@ public class CreateMediumIfNotAlreadyExistsTest {
expect(manager.getVBox()).andReturn(vBox).anyTimes(); expect(manager.getVBox()).andReturn(vBox).anyTimes();
VBoxException notFoundException = new VBoxException(createNiceMock(Throwable.class), errorMessage); VBoxException notFoundException = new VBoxException(createNiceMock(Throwable.class), errorMessage);
expect(vBox.findMedium(adminDiskPath, DeviceType.HardDisk)).andThrow(notFoundException); expect(vBox.findMedium(eq(adminDiskPath), eq(DeviceType.HardDisk))).andThrow(notFoundException);
expect(vBox.createHardDisk(diskFormat, adminDiskPath)).andReturn(hardDisk); expect(vBox.createHardDisk(diskFormat, adminDiskPath)).andReturn(medium);
expect(hardDisk.createBaseStorage(anyLong(), anyLong())).andReturn(progress); expect(medium.createBaseStorage(anyLong(), anyLong())).andReturn(progress);
replay(manager, machine, vBox, hardDisk); replay(manager, machine, vBox, medium);
new CreateMediumIfNotAlreadyExists(manager, diskFormat, true).apply(adminDiskPath); new CreateMediumIfNotAlreadyExists(manager, true).apply(hardDisk);
verify(machine, vBox); verify(machine, vBox);
@ -75,61 +89,58 @@ public class CreateMediumIfNotAlreadyExistsTest {
@Test @Test
public void testDeleteAndCreateNewStorageWhenMediumExistsAndUsingOverwrite() throws Exception { public void testDeleteAndCreateNewStorageWhenMediumExistsAndUsingOverwrite() throws Exception {
String adminDiskPath = "/Users/johndoe/jclouds-virtualbox-images/admin.vdi"; HardDisk hardDisk = createTestHardDisk();
String diskFormat = "vdi";
VirtualBoxManager manager = createNiceMock(VirtualBoxManager.class); VirtualBoxManager manager = createNiceMock(VirtualBoxManager.class);
IMachine machine = createMock(IMachine.class); IMachine machine = createMock(IMachine.class);
IVirtualBox vBox = createMock(IVirtualBox.class); IVirtualBox vBox = createMock(IVirtualBox.class);
IMedium hardDisk = createMock(IMedium.class); IMedium medium = createMock(IMedium.class);
IMedium newHardDisk = createMock(IMedium.class); IMedium newHardDisk = createMock(IMedium.class);
IProgress progress = createNiceMock(IProgress.class); IProgress progress = createNiceMock(IProgress.class);
expect(manager.getVBox()).andReturn(vBox).anyTimes(); expect(manager.getVBox()).andReturn(vBox).anyTimes();
expect(vBox.findMedium(adminDiskPath, DeviceType.HardDisk)).andReturn(hardDisk); expect(vBox.findMedium(adminDiskPath, DeviceType.HardDisk)).andReturn(medium);
expect(hardDisk.deleteStorage()).andReturn(progress); expect(medium.deleteStorage()).andReturn(progress);
expect(vBox.createHardDisk(diskFormat, adminDiskPath)).andReturn(newHardDisk); expect(vBox.createHardDisk(diskFormat, adminDiskPath)).andReturn(newHardDisk);
expect(newHardDisk.createBaseStorage(anyLong(), anyLong())).andReturn(progress); expect(newHardDisk.createBaseStorage(anyLong(), anyLong())).andReturn(progress);
replay(manager, machine, vBox, hardDisk, newHardDisk, progress); replay(manager, machine, vBox, medium, newHardDisk, progress);
IMedium newDisk = new CreateMediumIfNotAlreadyExists(manager, diskFormat, true).apply(adminDiskPath); IMedium newDisk = new CreateMediumIfNotAlreadyExists(manager, true).apply(hardDisk);
verify(machine, vBox, hardDisk); verify(machine, vBox, medium);
assertNotSame(newDisk, hardDisk); assertNotSame(newDisk, medium);
} }
@Test(expectedExceptions = IllegalStateException.class) @Test(expectedExceptions = IllegalStateException.class)
public void testFailWhenMediumExistsAndNotUsingOverwrite() throws Exception { public void testFailWhenMediumExistsAndNotUsingOverwrite() throws Exception {
String adminDiskPath = "/Users/johndoe/jclouds-virtualbox-images/admin.vdi"; HardDisk hardDisk = createTestHardDisk();
String diskFormat = "vdi";
VirtualBoxManager manager = createNiceMock(VirtualBoxManager.class); VirtualBoxManager manager = createNiceMock(VirtualBoxManager.class);
IMachine machine = createMock(IMachine.class); IMachine machine = createMock(IMachine.class);
IVirtualBox vBox = createMock(IVirtualBox.class); IVirtualBox vBox = createMock(IVirtualBox.class);
IMedium hardDisk = createMock(IMedium.class); IMedium medium = createMock(IMedium.class);
IMedium newHardDisk = createMock(IMedium.class); IMedium newHardDisk = createMock(IMedium.class);
IProgress progress = createNiceMock(IProgress.class); IProgress progress = createNiceMock(IProgress.class);
expect(manager.getVBox()).andReturn(vBox).anyTimes(); expect(manager.getVBox()).andReturn(vBox).anyTimes();
expect(vBox.findMedium(adminDiskPath, DeviceType.HardDisk)).andReturn(hardDisk); expect(vBox.findMedium(adminDiskPath, DeviceType.HardDisk)).andReturn(medium);
replay(manager, machine, vBox, hardDisk, newHardDisk, progress); replay(manager, machine, vBox, medium, newHardDisk, progress);
new CreateMediumIfNotAlreadyExists(manager, diskFormat, false).apply(adminDiskPath); new CreateMediumIfNotAlreadyExists(manager, false).apply(hardDisk);
} }
@Test(expectedExceptions = VBoxException.class) @Test(expectedExceptions = VBoxException.class)
public void testFailOnOtherVBoxException() throws Exception { public void testFailOnOtherVBoxException() throws Exception {
String adminDiskPath = "/Users/johndoe/jclouds-virtualbox-images/admin.vdi"; HardDisk hardDisk = createTestHardDisk();
String diskFormat = "vdi";
VirtualBoxManager manager = createNiceMock(VirtualBoxManager.class); VirtualBoxManager manager = createNiceMock(VirtualBoxManager.class);
IMachine machine = createMock(IMachine.class); IMachine machine = createMock(IMachine.class);
IVirtualBox vBox = createMock(IVirtualBox.class); IVirtualBox vBox = createMock(IVirtualBox.class);
IMedium hardDisk = createMock(IMedium.class); IMedium medium = createMock(IMedium.class);
IProgress progress = createNiceMock(IProgress.class); IProgress progress = createNiceMock(IProgress.class);
String errorMessage = "VirtualBox error: Some other VBox error"; String errorMessage = "VirtualBox error: Some other VBox error";
@ -138,12 +149,16 @@ public class CreateMediumIfNotAlreadyExistsTest {
VBoxException notFoundException = new VBoxException(createNiceMock(Throwable.class), errorMessage); VBoxException notFoundException = new VBoxException(createNiceMock(Throwable.class), errorMessage);
expect(vBox.findMedium(adminDiskPath, DeviceType.HardDisk)).andThrow(notFoundException); expect(vBox.findMedium(adminDiskPath, DeviceType.HardDisk)).andThrow(notFoundException);
expect(vBox.createHardDisk(diskFormat, adminDiskPath)).andReturn(hardDisk); expect(vBox.createHardDisk(diskFormat, adminDiskPath)).andReturn(medium);
expect(hardDisk.createBaseStorage(anyLong(), anyLong())).andReturn(progress); expect(medium.createBaseStorage(anyLong(), anyLong())).andReturn(progress);
replay(manager, machine, vBox, hardDisk); replay(manager, machine, vBox, medium);
new CreateMediumIfNotAlreadyExists(manager, diskFormat, true).apply(adminDiskPath); new CreateMediumIfNotAlreadyExists(manager, true).apply(hardDisk);
}
private HardDisk createTestHardDisk() {
return new HardDisk(new DeviceDetails(0, 0, DeviceType.HardDisk), adminDiskPath, diskFormat);
} }
} }

View File

@ -19,18 +19,9 @@
package org.jclouds.virtualbox.functions; package org.jclouds.virtualbox.functions;
import static com.google.common.base.Predicates.equalTo;
import static com.google.common.collect.Iterables.any;
import static com.google.common.collect.Iterables.transform;
import static org.jclouds.virtualbox.experiment.TestUtils.computeServiceForLocalhostAndGuest;
import static org.testng.Assert.assertTrue;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
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.inject.Guice;
import org.jclouds.compute.ComputeServiceContext; import org.jclouds.compute.ComputeServiceContext;
import org.jclouds.compute.config.BaseComputeServiceContextModule; import org.jclouds.compute.config.BaseComputeServiceContextModule;
import org.jclouds.compute.domain.Image; import org.jclouds.compute.domain.Image;
@ -43,16 +34,25 @@ import org.jclouds.net.IPSocket;
import org.jclouds.predicates.InetSocketAddressConnect; import org.jclouds.predicates.InetSocketAddressConnect;
import org.jclouds.predicates.RetryablePredicate; import org.jclouds.predicates.RetryablePredicate;
import org.jclouds.virtualbox.BaseVirtualBoxClientLiveTest; import org.jclouds.virtualbox.BaseVirtualBoxClientLiveTest;
import org.jclouds.virtualbox.domain.*;
import org.jclouds.virtualbox.functions.admin.UnregisterMachineIfExists; import org.jclouds.virtualbox.functions.admin.UnregisterMachineIfExists;
import org.jclouds.virtualbox.util.PropertyUtils;
import org.testng.annotations.BeforeGroups; import org.testng.annotations.BeforeGroups;
import org.testng.annotations.Test; import org.testng.annotations.Test;
import org.virtualbox_4_1.CleanupMode; import org.virtualbox_4_1.*;
import org.virtualbox_4_1.IMachine;
import org.virtualbox_4_1.VirtualBoxManager;
import com.google.inject.Guice;
import javax.annotation.Nullable; import javax.annotation.Nullable;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import static com.google.common.base.Predicates.equalTo;
import static com.google.common.collect.Iterables.any;
import static com.google.common.collect.Iterables.transform;
import static org.jclouds.virtualbox.domain.ExecutionType.GUI;
import static org.jclouds.virtualbox.domain.ExecutionType.HEADLESS;
import static org.jclouds.virtualbox.experiment.TestUtils.computeServiceForLocalhostAndGuest;
import static org.testng.Assert.assertTrue;
/** /**
* @author Andrea Turli, Mattias Holmqvist * @author Andrea Turli, Mattias Holmqvist
@ -64,12 +64,9 @@ public class IsoToIMachineLiveTest extends BaseVirtualBoxClientLiveTest {
}.provideOsVersionMap(new ComputeServiceConstants.ReferenceData(), Guice.createInjector(new GsonModule()) }.provideOsVersionMap(new ComputeServiceConstants.ReferenceData(), Guice.createInjector(new GsonModule())
.getInstance(Json.class)); .getInstance(Json.class));
private boolean forceOverwrite = true;
private String vmId = "jclouds-image-iso-1"; private String vmId = "jclouds-image-iso-1";
private String osTypeId = ""; private String osTypeId = "";
private String controllerIDE = "IDE Controller"; private String ideControllerName = "IDE Controller";
private String diskFormat = "";
private String adminDisk = "testadmin.vdi";
private String guestId = "guest"; private String guestId = "guest";
private String hostId = "host"; private String hostId = "host";
@ -88,8 +85,18 @@ public class IsoToIMachineLiveTest extends BaseVirtualBoxClientLiveTest {
ComputeServiceContext localHostContext = computeServiceForLocalhostAndGuest(hostId, "localhost", guestId, ComputeServiceContext localHostContext = computeServiceForLocalhostAndGuest(hostId, "localhost", guestId,
"localhost", new Credentials("toor", "password")); "localhost", new Credentials("toor", "password"));
Predicate<IPSocket> socketTester = new RetryablePredicate<IPSocket>(new InetSocketAddressConnect(), 10, 1, TimeUnit.SECONDS); Predicate<IPSocket> socketTester = new RetryablePredicate<IPSocket>(new InetSocketAddressConnect(), 10, 1, TimeUnit.SECONDS);
IMachine imageMachine = new IsoToIMachine(manager, adminDisk, diskFormat, vmName, osTypeId, vmId,
forceOverwrite, controllerIDE, localHostContext, hostId, guestId, socketTester, "127.0.0.1", 8080) String workingDir = PropertyUtils.getWorkingDirFromProperty();
StorageController ideController = StorageController.builder().name(ideControllerName).bus(StorageBus.IDE)
.attachISO(0, 0, workingDir + "/ubuntu-11.04-server-i386.iso")
.attachHardDisk(0, 1, workingDir + "/testadmin.vdi")
.attachISO(1, 1, workingDir + "/VBoxGuestAdditions_4.1.2.iso").build();
VmSpecification vmSpecification = VmSpecification.builder().id(vmId).name(vmName).osTypeId(osTypeId)
.controller(ideController)
.forceOverwrite(true)
.natNetworkAdapter(0, NatAdapter.builder().tcpRedirectRule("127.0.0.1", 2222, "", 22).build()).build();
IMachine imageMachine = new IsoToIMachine(manager, guestId, vmSpecification, localHostContext, hostId,
socketTester, "127.0.0.1", 8080, HEADLESS)
.apply("ubuntu-11.04-server-i386.iso"); .apply("ubuntu-11.04-server-i386.iso");
IMachineToImage iMachineToImage = new IMachineToImage(manager, map); IMachineToImage iMachineToImage = new IMachineToImage(manager, map);

View File

@ -1,13 +1,7 @@
package org.jclouds.virtualbox.predicates; package org.jclouds.virtualbox.predicates;
import static org.jclouds.virtualbox.experiment.TestUtils.computeServiceForLocalhostAndGuest; import com.google.common.base.Function;
import static org.jclouds.virtualbox.util.MachineUtils.applyForMachine; import com.google.common.base.Predicate;
import static org.jclouds.virtualbox.util.MachineUtils.lockSessionOnMachineAndApply;
import static org.virtualbox_4_1.LockType.Shared;
import static org.testng.Assert.assertTrue;
import java.util.concurrent.TimeUnit;
import org.jclouds.compute.ComputeServiceContext; import org.jclouds.compute.ComputeServiceContext;
import org.jclouds.domain.Credentials; import org.jclouds.domain.Credentials;
import org.jclouds.net.IPSocket; import org.jclouds.net.IPSocket;
@ -15,39 +9,36 @@ import org.jclouds.predicates.InetSocketAddressConnect;
import org.jclouds.predicates.RetryablePredicate; import org.jclouds.predicates.RetryablePredicate;
import org.jclouds.virtualbox.BaseVirtualBoxClientLiveTest; import org.jclouds.virtualbox.BaseVirtualBoxClientLiveTest;
import org.jclouds.virtualbox.domain.ExecutionType; import org.jclouds.virtualbox.domain.ExecutionType;
import org.jclouds.virtualbox.domain.StorageController;
import org.jclouds.virtualbox.domain.VmSpecification;
import org.jclouds.virtualbox.functions.IsoToIMachine; import org.jclouds.virtualbox.functions.IsoToIMachine;
import org.jclouds.virtualbox.functions.LaunchMachineIfNotAlreadyRunning; import org.jclouds.virtualbox.functions.LaunchMachineIfNotAlreadyRunning;
import org.jclouds.virtualbox.util.PropertyUtils;
import org.testng.annotations.Test; import org.testng.annotations.Test;
import org.virtualbox_4_1.IMachine; import org.virtualbox_4_1.*;
import org.virtualbox_4_1.IProgress;
import org.virtualbox_4_1.ISession;
import org.virtualbox_4_1.VirtualBoxManager;
import com.google.common.base.Function; import java.util.concurrent.TimeUnit;
import com.google.common.base.Predicate;
@Test(groups = "live", singleThreaded = true, testName = "IsoToIMachineLiveTest") import static org.jclouds.virtualbox.domain.ExecutionType.HEADLESS;
import static org.jclouds.virtualbox.experiment.TestUtils.computeServiceForLocalhostAndGuest;
import static org.jclouds.virtualbox.util.MachineUtils.applyForMachine;
import static org.jclouds.virtualbox.util.MachineUtils.lockSessionOnMachineAndApply;
import static org.testng.Assert.assertTrue;
import static org.virtualbox_4_1.LockType.Shared;
@Test(groups = "live", singleThreaded = true, testName = "SshAvailableLiveTest")
public class SshAvailableLiveTest extends BaseVirtualBoxClientLiveTest { public class SshAvailableLiveTest extends BaseVirtualBoxClientLiveTest {
private boolean forceOverwrite = true;
private String vmId = "jclouds-image-iso-1";
private String osTypeId = "";
private String controllerIDE = "IDE Controller";
private String diskFormat = "";
private String adminDisk = "testadmin.vdi";
private String guestId = "guest"; private String guestId = "guest";
private String hostId = "host"; private String hostId = "host";
private String vmName = "jclouds-image-virtualbox-iso-to-machine-test"; private String vmName = "jclouds-image-virtualbox-iso-to-machine-sshtest";
private String isoName = "ubuntu-11.04-server-i386.iso";
@Test @Test
public void testSshDaemonIsRunning() { public void testSshDaemonIsRunning() {
VirtualBoxManager manager = (VirtualBoxManager) context VirtualBoxManager manager = (VirtualBoxManager) context.getProviderSpecificContext().getApi();
.getProviderSpecificContext().getApi();
ComputeServiceContext localHostContext = computeServiceForLocalhostAndGuest( ComputeServiceContext localHostContext = computeServiceForLocalhostAndGuest(
hostId, "localhost", guestId, "localhost", new Credentials("toor", hostId, "localhost", guestId, "localhost", new Credentials("toor","password"));
"password"));
getNodeWithSshDaemonRunning(manager, localHostContext); getNodeWithSshDaemonRunning(manager, localHostContext);
ensureMachineIsLaunched(vmName); ensureMachineIsLaunched(vmName);
@ -68,14 +59,23 @@ public class SshAvailableLiveTest extends BaseVirtualBoxClientLiveTest {
}); });
} }
private IMachine getNodeWithSshDaemonRunning(VirtualBoxManager manager, private IMachine getNodeWithSshDaemonRunning(VirtualBoxManager manager, ComputeServiceContext localHostContext) {
ComputeServiceContext localHostContext) {
try { try {
Predicate<IPSocket> socketTester = new RetryablePredicate<IPSocket>( Predicate<IPSocket> socketTester = new RetryablePredicate<IPSocket>(
new InetSocketAddressConnect(), 10, 1, TimeUnit.SECONDS); new InetSocketAddressConnect(), 10, 1, TimeUnit.SECONDS);
return new IsoToIMachine(manager, adminDisk, diskFormat, vmName, String vmId = "jclouds-image-iso-2";
osTypeId, vmId, forceOverwrite, controllerIDE, localHostContext, String isoName = "ubuntu-11.04-server-i386.iso";
hostId, guestId, socketTester, "127.0.0.1", 8080).apply(isoName);
String workingDir = PropertyUtils.getWorkingDirFromProperty();
StorageController ideController = StorageController.builder().name("IDE Controller").bus(StorageBus.IDE)
.attachISO(0, 0, workingDir + "/ubuntu-11.04-server-i386.iso")
.attachHardDisk(0, 1, workingDir + "/testadmin.vdi").build();
VmSpecification vmSpecification = VmSpecification.builder().id(vmId).name(vmName).osTypeId("")
.controller(ideController)
.forceOverwrite(true).build();
return new IsoToIMachine(manager, guestId, vmSpecification, localHostContext,
hostId, socketTester, "127.0.0.1", 8080, HEADLESS).apply(isoName);
} catch (IllegalStateException e) { } catch (IllegalStateException e) {
// already created // already created
return manager.getVBox().findMachine(vmName); return manager.getVBox().findMachine(vmName);