PageRenderTime 57ms CodeModel.GetById 32ms RepoModel.GetById 0ms app.codeStats 0ms

/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/experiment/VirtualboxLiveTest.java

https://github.com/edwardt/jclouds
Java | 329 lines | 225 code | 48 blank | 56 comment | 16 complexity | aeea9357ba274e5aec29b990080ee4bc MD5 | raw file
  1. /**
  2. * Licensed to jclouds, Inc. (jclouds) under one or more
  3. * contributor license agreements. See the NOTICE file
  4. * distributed with this work for additional information
  5. * regarding copyright ownership. jclouds licenses this file
  6. * to you under the Apache License, Version 2.0 (the
  7. * "License"); you may not use this file except in compliance
  8. * with the License. You may obtain a copy of the License at
  9. *
  10. * http://www.apache.org/licenses/LICENSE-2.0
  11. *
  12. * Unless required by applicable law or agreed to in writing,
  13. * software distributed under the License is distributed on an
  14. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15. * KIND, either express or implied. See the License for the
  16. * specific language governing permissions and limitations
  17. * under the License.
  18. */
  19. package org.jclouds.virtualbox.experiment;
  20. import static com.google.common.base.Preconditions.checkNotNull;
  21. import static org.testng.Assert.assertEquals;
  22. import java.io.BufferedReader;
  23. import java.io.File;
  24. import java.io.IOException;
  25. import java.io.InputStreamReader;
  26. import java.net.MalformedURLException;
  27. import java.rmi.RemoteException;
  28. import java.util.concurrent.TimeUnit;
  29. import org.jclouds.compute.domain.ExecResponse;
  30. import org.jclouds.domain.Credentials;
  31. import org.jclouds.encryption.bouncycastle.config.BouncyCastleCryptoModule;
  32. import org.jclouds.logging.slf4j.config.SLF4JLoggingModule;
  33. import org.jclouds.net.IPSocket;
  34. import org.jclouds.predicates.InetSocketAddressConnect;
  35. import org.jclouds.predicates.RetryablePredicate;
  36. import org.jclouds.ssh.SshClient;
  37. import org.jclouds.sshj.config.SshjSshClientModule;
  38. import org.testng.annotations.AfterMethod;
  39. import org.testng.annotations.BeforeClass;
  40. import org.testng.annotations.BeforeMethod;
  41. import org.testng.annotations.Test;
  42. import org.virtualbox_4_1.AccessMode;
  43. import org.virtualbox_4_1.DeviceType;
  44. import org.virtualbox_4_1.IMachine;
  45. import org.virtualbox_4_1.IMedium;
  46. import org.virtualbox_4_1.IProgress;
  47. import org.virtualbox_4_1.ISession;
  48. import org.virtualbox_4_1.LockType;
  49. import org.virtualbox_4_1.MachineState;
  50. import org.virtualbox_4_1.MediumType;
  51. import org.virtualbox_4_1.SessionState;
  52. import org.virtualbox_4_1.StorageBus;
  53. import org.virtualbox_4_1.VirtualBoxManager;
  54. import org.virtualbox_4_1.jaxws.MediumState;
  55. import com.google.common.base.Predicate;
  56. import com.google.inject.Guice;
  57. import com.google.inject.Injector;
  58. @Test(groups = "live", testName = "virtualbox.VirtualboxLiveTest")
  59. public class VirtualboxLiveTest {
  60. protected String provider = "virtualbox";
  61. protected String identity;
  62. protected String credential;
  63. protected String endpoint;
  64. protected String apiversion;
  65. protected String vmName;
  66. VirtualBoxManager manager = VirtualBoxManager.createInstance(null);
  67. protected Injector injector;
  68. protected Predicate<IPSocket> socketTester;
  69. protected SshClient.Factory sshFactory;
  70. protected String osUsername;
  71. protected String osPassword;
  72. protected String controller;
  73. protected String diskFormat;
  74. protected String settingsFile; // Fully qualified path where the settings
  75. // file should be created, or NULL for a
  76. // default
  77. // folder and file based on the name argument (see composeMachineFilename()).
  78. protected String osTypeId; // Guest OS Type ID.
  79. protected String vmId; // Machine UUID (optional).
  80. protected boolean forceOverwrite; // If true, an existing machine settings
  81. // file will be overwritten.
  82. protected String workingDir;
  83. protected String originalDiskPath;
  84. protected String clonedDiskPath;
  85. // Create disk If the @a format attribute is empty or null then the default
  86. // storage format specified by ISystemProperties#defaultHardDiskFormat
  87. String format = "vdi";
  88. protected int numberOfVirtualMachine;
  89. @BeforeClass
  90. protected void setupConfigurationProperties() {
  91. // VBOX
  92. settingsFile = null; // Fully qualified path where the settings file
  93. // should be created, or NULL for a default
  94. // folder and file based on the name argument (see
  95. // composeMachineFilename()).
  96. osTypeId = System.getProperty("test." + provider + ".osTypeId", ""); // Guest
  97. // OS
  98. // Type
  99. // ID.
  100. vmId = System.getProperty("test." + provider + ".vmId", null); // Machine
  101. // UUID
  102. // (optional).
  103. forceOverwrite = true; // If true, an existing machine settings file will
  104. // be overwritten.
  105. // OS specific information
  106. vmName = checkNotNull(System.getProperty("test." + provider + ".vmname"));
  107. osUsername = System.getProperty("test." + provider + ".osusername", "root");
  108. osPassword = System.getProperty("test." + provider + ".ospassword", "toortoor");
  109. controller = System.getProperty("test." + provider + ".controller", "IDE Controller");
  110. diskFormat = System.getProperty("test." + provider + ".diskformat", "");
  111. workingDir = checkNotNull(System.getProperty("test." + provider + ".workingDir"));
  112. originalDiskPath = workingDir + File.separator
  113. + checkNotNull(System.getProperty("test." + provider + ".originalDisk"));
  114. numberOfVirtualMachine = Integer.parseInt(checkNotNull(System.getProperty("test." + provider
  115. + ".numberOfVirtualMachine")));
  116. }
  117. @BeforeClass
  118. protected void setupCredentials() throws RemoteException, MalformedURLException {
  119. identity = System.getProperty("test." + provider + ".identity", "administrator");
  120. credential = System.getProperty("test." + provider + ".credential", "12345");
  121. endpoint = System.getProperty("test." + provider + ".endpoint", "http://localhost:18083/");
  122. apiversion = System.getProperty("test." + provider + ".apiversion");
  123. injector = Guice.createInjector(new SshjSshClientModule(), new SLF4JLoggingModule(),
  124. new BouncyCastleCryptoModule());
  125. sshFactory = injector.getInstance(SshClient.Factory.class);
  126. socketTester = new RetryablePredicate<IPSocket>(new InetSocketAddressConnect(), 180, 1, TimeUnit.SECONDS);
  127. injector.injectMembers(socketTester);
  128. }
  129. @BeforeMethod
  130. protected void setupManager() throws RemoteException, MalformedURLException {
  131. manager.connect(endpoint, identity, credential);
  132. }
  133. @AfterMethod
  134. protected void disconnectAndClenaupManager() throws RemoteException, MalformedURLException {
  135. manager.disconnect();
  136. manager.cleanup();
  137. }
  138. @Test
  139. public void testStartVirtualMachines() {
  140. IMedium clonedHd = cloneDisk(MediumType.MultiAttach);
  141. for (int i = 1; i < numberOfVirtualMachine + 1; i++) {
  142. createVirtualMachine(i, clonedHd);
  143. }
  144. }
  145. private void createVirtualMachine(int i, IMedium clonedHd) {
  146. String instanceName = vmName + "_" + i;
  147. IMachine newVM = manager.getVBox().createMachine(settingsFile, instanceName, osTypeId, vmId, forceOverwrite);
  148. manager.getVBox().registerMachine(newVM);
  149. ISession session = manager.getSessionObject();
  150. IMachine machine = manager.getVBox().findMachine(instanceName);
  151. machine.lockMachine(session, LockType.Write);
  152. IMachine mutable = session.getMachine();
  153. // disk
  154. mutable.addStorageController(controller, StorageBus.IDE);
  155. mutable.attachDevice(controller, 0, 0, DeviceType.HardDisk, clonedHd);
  156. // network
  157. String hostInterface = null;
  158. String command = "vboxmanage list bridgedifs";
  159. try {
  160. Process child = Runtime.getRuntime().exec(command);
  161. BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(child.getInputStream()));
  162. String line = "";
  163. boolean found = false;
  164. while ((line = bufferedReader.readLine()) != null && !found) {
  165. if (line.split(":")[0].contains("Name")) {
  166. hostInterface = line.split(":")[1];
  167. }
  168. if (line.split(":")[0].contains("Status") && line.split(":")[1].contains("Up")) {
  169. System.out.println("bridge: " + hostInterface.trim());
  170. found = true;
  171. }
  172. }
  173. } catch (IOException e) {
  174. // TODO Auto-generated catch block
  175. e.printStackTrace();
  176. }
  177. // TODO: lookup translations for 4.1 for the below
  178. // mutable.getNetworkAdapter(new Long(0)).attachToBridgedInterface();
  179. // mutable.getNetworkAdapter(new
  180. // Long(0)).setHostInterface(hostInterface.trim());
  181. mutable.getNetworkAdapter(new Long(0)).setEnabled(true);
  182. mutable.saveSettings();
  183. session.unlockMachine();
  184. }
  185. /**
  186. * @param instanceName
  187. * @return
  188. */
  189. private IMedium cloneDisk(MediumType mediumType) {
  190. String clonedDisk = System.getProperty("test." + provider + ".clonedDisk");
  191. String instanceClonedDisk = clonedDisk.split("\\.")[0] + "." + clonedDisk.split("\\.")[1];
  192. clonedDiskPath = workingDir + File.separator + instanceClonedDisk;
  193. // use template disk in multiattach mode
  194. IMedium clonedHd = manager.getVBox().openMedium(originalDiskPath, DeviceType.HardDisk, AccessMode.ReadOnly,
  195. forceOverwrite);
  196. System.out.println("cloned HD state: " + clonedHd.getState());
  197. /*
  198. * An image in multiattach mode can be attached to more than one virtual
  199. * machine at the same time, even if these machines are running
  200. * simultaneously. For each virtual machine to which such an image is
  201. * attached, a differencing image is created. As a result, data that is
  202. * written to such a virtual disk by one machine is not seen by the other
  203. * machines to which the image is attached; each machine creates its own
  204. * write history of the multiattach image.
  205. */
  206. while (clonedHd.getState().equals(MediumState.NOT_CREATED)) {
  207. try {
  208. Thread.sleep(1500);
  209. } catch (InterruptedException e) {
  210. e.printStackTrace();
  211. }
  212. }
  213. clonedHd.setType(mediumType);
  214. return clonedHd;
  215. }
  216. private void launchVMProcess(IMachine machine, ISession session) {
  217. IProgress prog = machine.launchVMProcess(session, "gui", "");
  218. prog.waitForCompletion(-1);
  219. session.unlockMachine();
  220. }
  221. protected void checkSSH(IPSocket socket) {
  222. socketTester.apply(socket);
  223. SshClient client = sshFactory.create(socket, new Credentials(osUsername, osPassword));
  224. try {
  225. client.connect();
  226. ExecResponse exec = client.exec("touch /tmp/hello_" + System.currentTimeMillis());
  227. exec = client.exec("echo hello");
  228. System.out.println(exec);
  229. assertEquals(exec.getOutput().trim(), "hello");
  230. } finally {
  231. if (client != null)
  232. client.disconnect();
  233. }
  234. }
  235. @Test(dependsOnMethods = "testStartVirtualMachines")
  236. public void testSshLogin() {
  237. String ipAddress = null;
  238. for (int i = 1; i < numberOfVirtualMachine + 1; i++) {
  239. String instanceName = vmName + "_" + i;
  240. IMachine machine = manager.getVBox().findMachine(instanceName);
  241. System.out.println("\nLaunch VM named " + machine.getName() + " ...");
  242. launchVMProcess(machine, manager.getSessionObject());
  243. while (ipAddress == null || ipAddress.equals("")) {
  244. try {
  245. ipAddress = machine.getGuestPropertyValue("/VirtualBox/GuestInfo/Net/0/V4/IP");
  246. Thread.sleep(1000);
  247. } catch (InterruptedException e) {
  248. e.printStackTrace();
  249. }
  250. }
  251. System.out.println("VM " + instanceName + " started with IP " + ipAddress);
  252. IPSocket socket = new IPSocket(ipAddress, 22);
  253. System.out.println("Check SSH for " + instanceName + " ...");
  254. checkSSH(socket);
  255. }
  256. }
  257. @Test(dependsOnMethods = "testSshLogin")
  258. public void testStopVirtualMachine() {
  259. for (int i = 1; i < numberOfVirtualMachine + 1; i++) {
  260. String instanceName = vmName + "_" + i;
  261. IMachine machine = manager.getVBox().findMachine(instanceName);
  262. try {
  263. ISession machineSession = manager.openMachineSession(machine);
  264. IProgress progress = machineSession.getConsole().powerDown();
  265. progress.waitForCompletion(-1);
  266. machineSession.unlockMachine();
  267. while (!machine.getSessionState().equals(SessionState.Unlocked)) {
  268. try {
  269. System.out.println("waiting for unlocking session - session state: " + machine.getSessionState());
  270. Thread.sleep(1000);
  271. } catch (InterruptedException e) {
  272. e.printStackTrace();
  273. }
  274. }
  275. assertEquals(machine.getState(), MachineState.PoweredOff);
  276. } catch (Exception e) {
  277. e.printStackTrace();
  278. }
  279. }
  280. }
  281. }