@Test
  public void testCloneMachineFromAnotherMachine() throws Exception {
    VirtualBoxManager manager = (VirtualBoxManager) context.getProviderSpecificContext().getApi();
    ComputeServiceContext localHostContext =
        computeServiceForLocalhostAndGuest(
            hostId, "localhost", guestId, "localhost", new Credentials("toor", "password"));

    IMachine master = getMasterNode(manager, localHostContext);

    if (master.getCurrentSnapshot() != null) {
      ISession session = manager.openMachineSession(master);
      session.getConsole().deleteSnapshot(master.getCurrentSnapshot().getId());
      session.unlockMachine();
    }

    IMachine clone =
        new CloneAndRegisterMachineFromIMachineIfNotAlreadyExists(
                manager,
                localHostContext,
                settingsFile,
                osTypeId,
                vmId,
                forceOverwrite,
                cloneName,
                hostId,
                snapshotName,
                snapshotDesc,
                controllerIDE)
            .apply(master);
    assertEquals(clone.getNetworkAdapter(0L).getAttachmentType(), Bridged);
  }
Пример #2
0
  @Test(dependsOnMethods = "testStartAndValidateVirtualMachines")
  public void testStopVirtualMachines() {
    for (int i = 1; i < numberOfVirtualMachine + 1; i++) {
      String instanceName = vmName + "_" + i;
      IMachine machine = manager.getVBox().findMachine(instanceName);

      try {
        ISession machineSession = manager.openMachineSession(machine);
        IProgress progress = machineSession.getConsole().powerDown();
        progress.waitForCompletion(-1);
        machineSession.unlockMachine();

        while (!machine.getSessionState().equals(SessionState.Unlocked)) {
          try {
            System.out.println(
                "waiting for unlocking session - session state: " + machine.getSessionState());
            Thread.sleep(1000);
          } catch (InterruptedException e) {
            e.printStackTrace();
          }
        }
        assertEquals(machine.getState(), MachineState.PoweredOff);
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
  }
Пример #3
0
  private void createAndLaunchVirtualMachine(int i) throws InterruptedException {
    String instanceName = vmName + "_" + i;
    IMachine adminNode = manager.getVBox().findMachine(adminNodeName);

    IMachine clonedVM =
        manager.getVBox().createMachine(settingsFile, instanceName, osTypeId, vmId, forceOverwrite);
    List<CloneOptions> options = new ArrayList<CloneOptions>();
    options.add(CloneOptions.Link);
    IProgress progress =
        adminNode
            .getCurrentSnapshot()
            .getMachine()
            .cloneTo(clonedVM, CloneMode.MachineState, options);
    if (progress.getCompleted()) logger().debug("clone done");

    manager.getVBox().registerMachine(clonedVM);

    System.out.println("\nLaunching VM named " + clonedVM.getName() + " ...");
    launchVMProcess(clonedVM, manager.getSessionObject());
    String ipAddress = null;
    while (ipAddress == null || ipAddress.equals("")) {
      try {
        ipAddress = clonedVM.getGuestPropertyValue("/VirtualBox/GuestInfo/Net/0/V4/IP");
        Thread.sleep(1000);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }
    System.out.println(ipAddress + " is the IP address of " + clonedVM.getName());

    // TODO
    // IPSocket socket = new IPSocket(ipAddress, 22);
    // checkSSH(IPSocket socket)

  }
Пример #4
0
  @Override
  public Hardware apply(@Nullable IMachine vm) {
    String osTypeId = vm.getOSTypeId();

    IGuestOSType guestOSType = virtualBoxManager.getVBox().getGuestOSType(osTypeId);
    Boolean is64Bit = guestOSType.getIs64Bit();
    HardwareBuilder hardwareBuilder = new HardwareBuilder();
    hardwareBuilder.ids(vm.getId());
    hardwareBuilder.supportsImage(ImagePredicates.idEquals(vm.getId()));
    hardwareBuilder.is64Bit(is64Bit);
    hardwareBuilder.supportsImage(ImagePredicates.idEquals(vm.getId()));
    return hardwareBuilder.build();
  }
 private IMachine getMasterNode(
     VirtualBoxManager manager, ComputeServiceContext localHostContext) {
   try {
     Predicate<IPSocket> socketTester =
         new RetryablePredicate<IPSocket>(new InetSocketAddressConnect(), 10, 1, TimeUnit.SECONDS);
     String workingDir = PropertyUtils.getWorkingDirFromProperty();
     StorageController ideController =
         StorageController.builder()
             .name(controllerIDE)
             .bus(StorageBus.IDE)
             .attachISO(0, 0, workingDir + "/ubuntu-11.04-server-i386.iso")
             .attachHardDisk(
                 HardDisk.builder()
                     .diskpath(workingDir + "/testadmin.vdi")
                     .controllerPort(0)
                     .deviceSlot(1)
                     .build())
             .attachISO(1, 1, workingDir + "/VBoxGuestAdditions_4.1.2.iso")
             .build();
     VmSpec vmSpecification =
         VmSpec.builder()
             .id(vmId)
             .name(vmName)
             .osTypeId(osTypeId)
             .memoryMB(512)
             .cleanUpMode(CleanupMode.Full)
             .controller(ideController)
             .forceOverwrite(true)
             .build();
     return new CreateAndInstallVm(
             manager, guestId, localHostContext, hostId, socketTester, "127.0.0.1", 8080, HEADLESS)
         .apply(vmSpecification);
   } catch (IllegalStateException e) {
     // already created
     return manager.getVBox().findMachine(vmName);
   }
 }
Пример #6
0
@Test(groups = "live", testName = "virtualbox.VirtualboxLiveTest")
public class VirtualboxLiveTest {

  protected String provider = "virtualbox";
  protected String identity;
  protected String credential;
  protected URI endpoint;
  protected String apiversion;
  protected String vmName;

  VirtualBoxManager manager = VirtualBoxManager.createInstance("");

  protected Injector injector;
  protected Predicate<IPSocket> socketTester;
  protected SshClient.Factory sshFactory;

  protected String osUsername;
  protected String osPassword;
  protected String controller;
  protected String diskFormat;

  protected String settingsFile;
  protected String osTypeId;
  protected String vmId;
  protected boolean forceOverwrite;
  protected String workingDir;
  protected String clonedDiskPath;
  protected String format = "vdi";
  protected int numberOfVirtualMachine;
  protected String originalDisk;
  private String clonedDisk;
  private ComputeServiceContext context;

  private String hostId = "host";
  private String guestId = "guest";
  private String majorVersion;
  private String minorVersion;
  private String apiVersion;
  private String adminNodeName;
  private String snapshotDescription;
  private String originalDiskPath;

  protected Logger logger() {
    return context.utils().loggerFactory().getLogger("jclouds.compute");
  }

  protected void setupCredentials() {
    identity = System.getProperty("test." + provider + ".identity", "administrator");
    credential = System.getProperty("test." + provider + ".credential", "12345");
    endpoint =
        URI.create(System.getProperty("test." + provider + ".endpoint", "http://*****:*****@BeforeGroups(groups = "live")
  protected void setupClient() throws Exception {
    context = TestUtils.computeServiceForLocalhost();
    socketTester =
        new RetryablePredicate<IPSocket>(new InetSocketAddressConnect(), 130, 10, TimeUnit.SECONDS);
    setupCredentials();
    setupConfigurationProperties();
    if (!new InetSocketAddressConnect().apply(new IPSocket(endpoint.getHost(), endpoint.getPort())))
      startupVboxWebServer();
  }

  @BeforeMethod
  protected void setupManager() throws RemoteException, MalformedURLException {
    manager.connect(endpoint.toASCIIString(), identity, credential);
  }

  @AfterMethod
  protected void disconnectAndClenaupManager() throws RemoteException, MalformedURLException {
    manager.disconnect();
    manager.cleanup();
  }

  @Test
  public void testStartAndValidateVirtualMachines() throws InterruptedException {
    for (int i = 1; i < numberOfVirtualMachine + 1; i++) {
      createAndLaunchVirtualMachine(i);
    }
  }

  private void createAndLaunchVirtualMachine(int i) throws InterruptedException {
    String instanceName = vmName + "_" + i;
    IMachine adminNode = manager.getVBox().findMachine(adminNodeName);

    IMachine clonedVM =
        manager.getVBox().createMachine(settingsFile, instanceName, osTypeId, vmId, forceOverwrite);
    List<CloneOptions> options = new ArrayList<CloneOptions>();
    options.add(CloneOptions.Link);
    IProgress progress =
        adminNode
            .getCurrentSnapshot()
            .getMachine()
            .cloneTo(clonedVM, CloneMode.MachineState, options);
    if (progress.getCompleted()) logger().debug("clone done");

    manager.getVBox().registerMachine(clonedVM);

    System.out.println("\nLaunching VM named " + clonedVM.getName() + " ...");
    launchVMProcess(clonedVM, manager.getSessionObject());
    String ipAddress = null;
    while (ipAddress == null || ipAddress.equals("")) {
      try {
        ipAddress = clonedVM.getGuestPropertyValue("/VirtualBox/GuestInfo/Net/0/V4/IP");
        Thread.sleep(1000);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }
    System.out.println(ipAddress + " is the IP address of " + clonedVM.getName());

    // TODO
    // IPSocket socket = new IPSocket(ipAddress, 22);
    // checkSSH(IPSocket socket)

  }

  private void launchVMProcess(IMachine machine, ISession session) {
    IProgress prog = machine.launchVMProcess(session, "gui", "");
    prog.waitForCompletion(-1);
    session.unlockMachine();
  }

  protected void checkSSH(IPSocket socket) {
    socketTester.apply(socket);
    SshClient client = sshFactory.create(socket, new Credentials(osUsername, osPassword));
    try {
      client.connect();
      ExecResponse exec = client.exec("touch /tmp/hello_" + System.currentTimeMillis());
      exec = client.exec("echo hello");
      System.out.println(exec);
      assertEquals(exec.getOutput().trim(), "hello");
    } finally {
      if (client != null) client.disconnect();
    }
  }

  @Test(dependsOnMethods = "testStartAndValidateVirtualMachines")
  public void testStopVirtualMachines() {
    for (int i = 1; i < numberOfVirtualMachine + 1; i++) {
      String instanceName = vmName + "_" + i;
      IMachine machine = manager.getVBox().findMachine(instanceName);

      try {
        ISession machineSession = manager.openMachineSession(machine);
        IProgress progress = machineSession.getConsole().powerDown();
        progress.waitForCompletion(-1);
        machineSession.unlockMachine();

        while (!machine.getSessionState().equals(SessionState.Unlocked)) {
          try {
            System.out.println(
                "waiting for unlocking session - session state: " + machine.getSessionState());
            Thread.sleep(1000);
          } catch (InterruptedException e) {
            e.printStackTrace();
          }
        }
        assertEquals(machine.getState(), MachineState.PoweredOff);
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
  }

  protected ExecResponse runScriptOnNode(String nodeId, String command, RunScriptOptions options) {
    ExecResponse toReturn = context.getComputeService().runScriptOnNode(nodeId, command, options);
    assert toReturn.getExitCode() == 0 : toReturn;
    return toReturn;
  }

  protected ExecResponse runScriptOnNode(String nodeId, String command) {
    return runScriptOnNode(nodeId, command, wrapInInitScript(false));
  }

  protected boolean isOSX(String id) {
    return context
        .getComputeService()
        .getNodeMetadata(hostId)
        .getOperatingSystem()
        .getDescription()
        .equals("Mac OS X");
  }

  void startupVboxWebServer() {
    logger().debug("disabling password access");
    runScriptOnNode(
        hostId,
        "VBoxManage setproperty websrvauthlibrary null",
        runAsRoot(false).wrapInInitScript(false));
    logger().debug("starting vboxwebsrv");
    String vboxwebsrv = "vboxwebsrv -t 10000 -v -b";
    if (isOSX(hostId))
      vboxwebsrv = "cd /Applications/VirtualBox.app/Contents/MacOS/ && " + vboxwebsrv;

    runScriptOnNode(
        hostId,
        vboxwebsrv,
        runAsRoot(false)
            .wrapInInitScript(false)
            .blockOnPort(endpoint.getPort(), 10)
            .blockOnComplete(false)
            .nameTask("vboxwebsrv"));
  }
}
Пример #7
0
 @AfterMethod
 protected void disconnectAndClenaupManager() throws RemoteException, MalformedURLException {
   manager.disconnect();
   manager.cleanup();
 }
Пример #8
0
 @BeforeMethod
 protected void setupManager() throws RemoteException, MalformedURLException {
   manager.connect(endpoint.toASCIIString(), identity, credential);
 }