Code Samples

Discussion about using the VirtualBox API, Tutorials, Samples.
Post Reply
noteirak
Site Moderator
Posts: 5229
Joined: 13. Jan 2012, 11:14
Primary OS: Debian other
VBox Version: OSE Debian
Guest OSses: Debian, Win 2k8, Win 7
Contact:

Code Samples

Post by noteirak »

Place holder for exemples of API usage
Hyperbox - Virtual Infrastructure Manager - https://apps.kamax.lu/hyperbox/
Manage your VirtualBox infrastructure the free way!
noteirak
Site Moderator
Posts: 5229
Joined: 13. Jan 2012, 11:14
Primary OS: Debian other
VBox Version: OSE Debian
Guest OSses: Debian, Win 2k8, Win 7
Contact:

Re: Code Samples

Post by noteirak »

API 5.x

5.1
List all snapshots for a VM

Code: Select all

/*
 * 
 * Written in 2017 by Maxime Dor
 * 
 * https://kamax.io/
 * 
 * To the extent possible under law, the author(s) have dedicated all copyright and related and neighboring rights to this software to the public
 * domain worldwide. This software is distributed without any warranty. Full license can be found at http://creativecommons.org/publicdomain/zero/1.0/
 */

import org.virtualbox_5_1.IMachine;
import org.virtualbox_5_1.ISnapshot;
import org.virtualbox_5_1.IVirtualBox;
import org.virtualbox_5_1.VirtualBoxManager;

public class SnapshotList {

    private static void printChilds(ISnapshot snapshot) {
        System.out.println("\"" + snapshot.getName() + "\" {" + snapshot.getId() + "}");
        for (ISnapshot snapChild : snapshot.getChildren()) {
            printChilds(snapChild);
        }
    }

    public static void main(String[] args) {
        /*
         * WebServices info
         */
        String wsHost = "http://localhost:18083";
        String wsUser = "user";
        String wsPass = "password";

        if (args.length < 1 || args[0] == null || args[0].length() < 1) {
            System.err.println("Specify the VM name/UUID as first parameter");
            System.exit(1);
        }

        String vmName = args[0];

        VirtualBoxManager vboxManager = VirtualBoxManager.createInstance(null);
        vboxManager.connect(wsHost, wsUser, wsPass);

        try {
            IVirtualBox vbox = vboxManager.getVBox();
            IMachine vm = vbox.findMachine(vmName);
            if (vm.getSnapshotCount() < 1) {
                System.out.println("The machine + " + vmName + " has no snapshot");
                System.exit(0);
            }

            // The magic is here: null will give you the root snapshot
            printChilds(vm.findSnapshot(null));
        } finally {
            vboxManager.disconnect();
            vboxManager.cleanup();
        }
    }

}
Export a VM to a OVA appliance

Code: Select all

/*
 * 
 * Written in 2016 by Maxime Dor
 * 
 * https://kamax.io/
 * 
 * To the extent possible under law, the author(s) have dedicated all copyright and related and neighboring rights to this software to the public
 * domain worldwide. This software is distributed without any warranty. Full license can be found at http://creativecommons.org/publicdomain/zero/1.0/
 */

import java.util.ArrayList;
import java.util.List;
import org.virtualbox_5_1.ExportOptions;
import org.virtualbox_5_1.IAppliance;
import org.virtualbox_5_1.IMachine;
import org.virtualbox_5_1.IVirtualBox;
import org.virtualbox_5_1.VirtualBoxManager;


/*
 * For more detailed, step-by-step:
 * https://www.virtualbox.org/sdkref/interface_i_appliance.html#details
 */
public class VBox_5_1_VmExport {

    public static void main(String[] args) {
        /*
         * WebServices info
         */
        String wsHost = "http://localhost:18083";
        String wsUser = "user";
        String wsPass = "password";

        /*
         * VM to export
         */
        String vmToExport = "test";

        /*
         * Available formats are:
         * - ovf-0.9
         * - ovf-1.0
         * - ovf-2.0
         * 
         * For more details: http://www.dmtf.org/standards/ovf
         */
        String exportFormat = "ovf-2.0";

        /*
         * Path where to write the appliance.
         * Filename extension will decide the expected appliance format on disk.
         * If ending in .ova, a single OVA file is created at the path given, which is a TAR archive with all files within.
         * If ending in .ovf, all files are written to disk directly in the same folder as the appliance file.
         */
        String exportPath = "/tmp/test-export.ova";

        /*
         * This is used as the base filename of the exported VM disks.
         * In this case, if the VM had 3 disks, the following files would be created within the OVA:
         * - test-disk1.vmdk
         * - test-disk2.vmdk
         * - test-disk3.vmdk
         */
        String exportDiskBasename = vmToExport;

        /* 
         * Add whatever options you want for the export. By default, there is no need of special options.
         * See https://www.virtualbox.org/sdkref/_virtual_box_8idl.html#adcba962dac19e8095de80a2a792402aa for the list
         */
        List<ExportOptions> opts = new ArrayList<>();


        System.out.println("Started");
        VirtualBoxManager vboxManager = VirtualBoxManager.createInstance(null);
        vboxManager.connect(wsHost, wsUser, wsPass); // only if you are using Web Services
        System.out.println("Connected");

        try {
            IVirtualBox vbox = vboxManager.getVBox();
            IMachine vm = vbox.findMachine(vmToExport);
            IAppliance app = vbox.createAppliance();

            System.out.println("Writting VM to appliance");
            vm.exportTo(app, exportDiskBasename);

            System.out.println("Writting appliance to disk");
            app.write(exportFormat, opts, exportPath);

            System.out.println("Done");
        } finally {
            vboxManager.disconnect(); // only if you are using Web Services
            vboxManager.cleanup();
            System.out.println("Disconnected");
        }

        System.out.println("Finished");
    }

}
5.0
Detach a disk from one VM and attach to another - Java

Code: Select all

/*
 * 
 * Written in 2015 by Maxime Dor
 * 
 * http://kamax.io/
 * 
 * To the extent possible under law, the author(s) have dedicated all copyright and related and neighboring rights to this software to the public
 * domain worldwide. This software is distributed without any warranty. Full license can be found at http://creativecommons.org/publicdomain/zero/1.0/
 */

import org.virtualbox_5_0.DeviceType;
import org.virtualbox_5_0.IMachine;
import org.virtualbox_5_0.IMedium;
import org.virtualbox_5_0.ISession;
import org.virtualbox_5_0.IVirtualBox;
import org.virtualbox_5_0.LockType;
import org.virtualbox_5_0.VirtualBoxManager;


public class VBox_5_0_MoveDriveBetweenVM {

    public static void main(String[] args) throws InterruptedException {
        String vmSourceName = "sourceMachine";
        String vmDestName = "sourceMachine";
        String controllerSourceName = "SATA";
        String controllerDestName = "SATA";
        int controllerSourcePortIndex = 0;
        int controllerSourceDeviceIndex = 0;
        int controllerDestPortIndex = 0;
        int controllerDestDeviceIndex = 0;

        System.out.println("Started");
        VirtualBoxManager vboxManager = VirtualBoxManager.createInstance(null);
        vboxManager.connect("http://localhost:18083", "user", "password"); // only if you are using Web Services
        System.out.println("Connected");
        try {
            IVirtualBox vbox = vboxManager.getVBox();
            IMachine vmSource = vbox.findMachine(vmSourceName);
            ISession sessionSource = vboxManager.getSessionObject();
            vmSource.lockMachine(sessionSource, LockType.Write); // We ensure VM is not in use
            try {
                IMachine vmDest = vbox.findMachine(vmDestName);
                ISession sessionDest = vboxManager.getSessionObject();
                vmDest.lockMachine(sessionDest, LockType.Shared); // only if controller support hotplug, else use Write
                try {
                    IMedium medium = sessionSource.getMachine().getMedium(controllerSourceName, controllerSourcePortIndex, controllerSourceDeviceIndex);
                    sessionSource.getMachine().detachDevice(controllerSourceName, controllerSourcePortIndex, controllerSourceDeviceIndex);
                    sessionSource.getMachine().saveSettings();

                    sessionDest.getMachine().attachDevice(controllerDestName, controllerDestPortIndex, controllerDestDeviceIndex, DeviceType.HardDisk, medium);
                    sessionDest.getMachine().saveSettings();
                } finally {
                    sessionDest.unlockMachine();
                }
            } finally {
                sessionSource.unlockMachine();
            }
        } finally {
            vboxManager.disconnect(); // only if you are using Web Services
            vboxManager.cleanup();
            System.out.println("Disconnected");
        }

        System.out.println("Finished");
    }

}
Catch events using passive mode - Java

Code: Select all

/*
 * Copyright (c) 2017 Maxime Dor
 *
 * https://max.kamax.io/
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
 */

package io.kamax.vbox5_1;

import org.virtualbox_5_1.*;

import java.util.Arrays;
import java.util.List;


public class CatchEvents_5_1 {

    static VirtualBoxManager mgr;
    static Thread listener;

    public static void main(String args[]) {
        String vmName = Long.toString(System.currentTimeMillis()); // get a random VM name to use later

        System.out.println("Creating VirtualBox client instance");
        mgr = VirtualBoxManager.createInstance(null);
        try {
            /*
             * This line is only required if you are using the WebServices to connect.
             * Also, change "user" and "password" to local credentials on the machine running the web services, or set authentication to null.
             * To do so, you can start vboxwevsrv with "-A null" argument or use vboxmanage to make it permanent.
             */
            System.out.println("Connecting to VirtualBox using Web Services");
            mgr.connect("http://localhost:18083", "user", "password"); // only if you are using WebServices Bindings
            System.out.println("Connected to VirtualBox using Web Services");

            /*
             * We will run the event worker in a separate thread like it would normally be done.
             */
            listener = new EventWorker();
            listener.start();

            try {
                /*
                 * We create an empty machine, we save its settings to disk (to actually make it really exist) than we register it.
                 * This will trigger IMachineRegisteredEvent.
                 */
                IMachine vm = mgr.getVBox().createMachine(null, vmName, null, "Other", null);
                vm.saveSettings();
                mgr.getVBox().registerMachine(vm);

                vm = mgr.getVBox().findMachine(vmName); // we fetch the machine object again just to be safe
                ISession session = mgr.getSessionObject();
                IProgress p = vm.launchVMProcess(session, "headless", null);
                p.waitForCompletion(-1); // we wait until the starting process has finished
                try {
                    if (p.getResultCode() != 0) { // error when starting the VM, we don't continue further
                        throw new RuntimeException(p.getErrorInfo().getText());
                    } else { // VM got started, OnMachineStateChanged triggered two times at this point
                        // let's now power down the VM
                        p = session.getConsole().powerDown();
                        p.waitForCompletion(-1);
                        if (p.getResultCode() != 0) { // we failed to stop the VM
                            throw new RuntimeException(p.getErrorInfo().getText());
                        } else {
                            // VM got stopped, OnMachineStateChanged triggered several times at this point
                        }
                    }
                } finally {
                    // we do not need the lock any further and is required for for IMachine::unregister()
                    session.unlockMachine();

                    // since unlock is not instant, we need to wait until the unlock is done or unregister() will fail.
                    while (!SessionState.Unlocked.equals(vm.getSessionState())) {
                        try {
                            System.out.println("Waiting for session unlock...");
                            Thread.sleep(1000L);
                        } catch (InterruptedException e) {
                            System.err.println("Interrupted while waiting for session to be unlocked");
                        }
                    }

                    // vm.unregister() will trigger IMachineRegisteredEvent.
                    System.out.println("Deleting machine");
                    vm.deleteConfig(vm.unregister(CleanupMode.DetachAllReturnHardDisksOnly));
                }
            } finally { // we instruct the Event Worker to stop and wait 5 sec for it to do so
                listener.interrupt();
                try {
                    listener.join(5000); // we wait on the thread
                } catch (InterruptedException e) {
                    System.err.println("Interrupted while waiting for EventWorker to stop");
                }

                if (listener.isAlive()) {
                    System.err.println("Event worked did not stop in a timely fashion");
                } else {
                    System.out.println("Event worked stopped");
                }
            }
        } finally {
            mgr.disconnect(); // only if you are using WebServices Bindings
            mgr.cleanup();
            System.out.println("Disconnected from VirtualBox - bye bye!");
        }
    }

    static class EventWorker extends Thread {

        IEventListener el;

        @Override
        public void run() {
            System.out.println("EventWorker started");
            el = mgr.getVBox().getEventSource().createListener(); // we create the object that will fetch and queue the events for us

            /*
             * We register for the events that we are interested in.
             * If we wanted all of them, we would use VBoxEventType.Any
             * 
             * Not all events will be visible here. If we want events for a specific machine (like Clipboard mode change),
             * we need to use the event source of that specific machine - see IMachine::getEventSource()
             */
            List<VBoxEventType> types = Arrays.asList(VBoxEventType.OnSessionStateChanged, VBoxEventType.OnMachineStateChanged,
                    VBoxEventType.OnMachineRegistered);
            mgr.getVBox().getEventSource().registerListener(el, types, false);

            try {
                while (!isInterrupted()) {
                    mgr.waitForEvents(0); // Needed to clear the internal event queue, see https://www.virtualbox.org/ticket/13647
                    IEvent rawEvent = mgr.getVBox().getEventSource().getEvent(el, 1000);
                    if (rawEvent == null) { // we waited but no event came
                        continue; // we loop again and skip the code below
                    }

                    try {
                        System.out.println("Got event of type " + rawEvent.getType());

                        if (VBoxEventType.OnSessionStateChanged.equals(rawEvent.getType())) {
                            // It is important to use the queryInterface() on the expected class, simple casting will not work.
                            ISessionStateChangedEvent event = ISessionStateChangedEvent.queryInterface(rawEvent);
                            System.out.println("Session state changed to " + event.getState() + " for machine " + event.getMachineId());
                        }

                        if (VBoxEventType.OnMachineRegistered.equals(rawEvent.getType())) { // we check the event type
                            // It is important to use the queryInterface() on the expected class, simple casting will not work.
                            IMachineRegisteredEvent event = IMachineRegisteredEvent.queryInterface(rawEvent);
                            System.out.println("Machine " + event.getMachineId() + " has been " + (event.getRegistered() ? "registered" : "unregistered"));
                        }

                        if (VBoxEventType.OnMachineStateChanged.equals(rawEvent.getType())) {
                            // It is important to use the queryInterface() on the expected class, simple casting will not work.
                            IMachineStateChangedEvent event = IMachineStateChangedEvent.queryInterface(rawEvent);
                            System.out.println("Machine " + event.getMachineId() + " state changed to " + event.getState());
                        }
                    } finally {
                        // We mark the event as processed so ressources can be released. We do this in a finally block to ensure it is done no matter what.
                        mgr.getVBox().getEventSource().eventProcessed(el, rawEvent);
                    }
                }
            } catch (Throwable t) {
                t.printStackTrace();
            } finally {
                mgr.getVBox().getEventSource().unregisterListener(el); // we are done fetching events, so we free the listener
                System.out.println("EventWorker finished");
            }
        }

    }

}
Last edited by noteirak on 28. Sep 2017, 16:04, edited 7 times in total.
Reason: Included the code locally.
Hyperbox - Virtual Infrastructure Manager - https://apps.kamax.lu/hyperbox/
Manage your VirtualBox infrastructure the free way!
noteirak
Site Moderator
Posts: 5229
Joined: 13. Jan 2012, 11:14
Primary OS: Debian other
VBox Version: OSE Debian
Guest OSses: Debian, Win 2k8, Win 7
Contact:

Re: Code Samples

Post by noteirak »

API 4.x

4.3

List running VMs - Java

Code: Select all

/*
 * DO WHAT THE SPAM_SEARCH YOU WANT TO PUBLIC LICENSE
 * Version 2, December 2004
 *
 * Everyone is permitted to copy and distribute verbatim or modified
 * copies of this license document, and changing it is allowed as long
 * as the name is changed.
 *
 * DO WHAT THE SPAM_SEARCH YOU WANT TO PUBLIC LICENSE
 * TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
 *
 * 0. You just DO WHAT THE SPAM_SEARCH YOU WANT TO.
 */

public class ListRunningVms {
   
   public static void main(String[] args) {
     
      VirtualBoxManager vboxManager = VirtualBoxManager.createInstance(null);
      try {
         vboxManager.connect("http://localhost:18083", "user", "password"); // only if you are using WebServices Bindings
         IVirtualBox vbox = vboxManager.getVBox();
         for (IMachine vm : vbox.getMachines()) {
            if (MachineState.Running.equals(vm.getState())) {
               System.out.println(vm.getName()+ " "+vm.getId());
            }
         }
      } finally {
         vboxManager.disconnect(); // only if you are using WebServices Bindings
         vboxManager.cleanup();
      }
   }
   
}
Start VM in Headless mode - Java

Code: Select all

/*
 * DO WHAT THE SPAM_SEARCH YOU WANT TO PUBLIC LICENSE
 * Version 2, December 2004
 *
 * Everyone is permitted to copy and distribute verbatim or modified
 * copies of this license document, and changing it is allowed as long
 * as the name is changed.
 *
 * DO WHAT THE SPAM_SEARCH YOU WANT TO PUBLIC LICENSE
 * TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
 *
 * 0. You just DO WHAT THE SPAM_SEARCH YOU WANT TO.
 */

import org.virtualbox_4_3.IMachine;
import org.virtualbox_4_3.IProgress;
import org.virtualbox_4_3.ISession;
import org.virtualbox_4_3.VirtualBoxManager;

/**
 * The following piece of code assume that
 * - WebServices server is running
 * - Authentication is disabled
 *
 * To disable authentication, run on the host before starting the server:
 * 
 * vboxmanage setproperty websrvauthlibrary null
 * 
 */
public class StartVM {

   public static void main(String[] args) {
      VirtualBoxManager vboxManager = VirtualBoxManager.createInstance(null);
      vboxManager.connect("http://localhost:18083", "", "");

      try {
         IMachine machine = vboxManager.getVBox().findMachine("machineName");
         ISession session = vboxManager.getSessionObject();
         IProgress p = machine.launchVMProcess(session, "headless", null);
         try {
            p.waitForCompletion(-1);
            if (p.getResultCode() != 0) {
               System.out.println("Machine failed to start: " + p.getErrorInfo().getText());
            }
         } finally {
            session.unlockMachine();
         }
      } finally {
         vboxManager.disconnect();
         vboxManager.cleanup();
      }
   }

}
Run Guest Process and Read Stdout - Java

Code: Select all

/*
 *            DO WHAT THE SPAM_SEARCH YOU WANT TO PUBLIC LICENSE
 *                     Version 2, December 2004
 *
 * Everyone is permitted to copy and distribute verbatim or modified
 *  copies of this license document, and changing it is allowed as long
 * as the name is changed.
 *
 *            DO WHAT THE SPAM_SEARCH YOU WANT TO PUBLIC LICENSE
 *   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
 *
 *  0. You just DO WHAT THE SPAM_SEARCH YOU WANT TO.
 */

import java.util.Arrays;
import org.virtualbox_4_3.GuestSessionStatus;
import org.virtualbox_4_3.IEvent;
import org.virtualbox_4_3.IEventListener;
import org.virtualbox_4_3.IEventSource;
import org.virtualbox_4_3.IGuestProcess;
import org.virtualbox_4_3.IGuestSession;
import org.virtualbox_4_3.IMachine;
import org.virtualbox_4_3.ISession;
import org.virtualbox_4_3.LockType;
import org.virtualbox_4_3.ProcessCreateFlag;
import org.virtualbox_4_3.ProcessWaitForFlag;
import org.virtualbox_4_3.ProcessWaitResult;
import org.virtualbox_4_3.VBoxEventType;
import org.virtualbox_4_3.VirtualBoxManager;

public class GuestSessionProcess {

   private static String errorIfNull(String systemProperty) {
      String value = System.getProperty(systemProperty);
      if (value != null) {
         return value;
      } else {
         throw new RuntimeException(systemProperty + " is not set");
      }
   }
   
   public static void main(String[] args) {
      String vmId = errorIfNull("vbox.vm");
      String guestUser = errorIfNull("vbox.guest.user");
      String guestPass = errorIfNull("vbox.guest.pass");
      String exec = errorIfNull("vbox.guest.exec");
      
      System.out.println("Starting");
      VirtualBoxManager vboxManager = VirtualBoxManager.createInstance(null);
      try {
         if (System.getProperty("vbox.ws") != null) {
            String host = System.getProperty("vbox.ws.host", "http://localhost:18083");
            String user = System.getProperty("vbox.ws.user", "");
            String pass = System.getProperty("vbox.ws.pass", "");
            vboxManager.connect(host, user, pass);
         }
         System.out.println("Connected");
         try {
            ISession session = vboxManager.getSessionObject();
            IMachine vm = vboxManager.getVBox().findMachine(vmId);
            vm.lockMachine(session, LockType.Shared);
            try {
               System.out.println("Machine locked");
               IGuestSession guestSess = session.getConsole().getGuest().createSession(guestUser, guestPass, null, null);
               try {
                  System.out.println("Session created");

                  guestSess.waitFor(1L, 30 * 1000L);
                  if (!guestSess.getStatus().equals(GuestSessionStatus.Started)) {
                     throw new RuntimeException("Guest session did not start after 30 sec");
                  }
                  IGuestProcess process = guestSess.processCreate(exec, null, null, Arrays.asList(ProcessCreateFlag.WaitForStdOut), 0L);

                  IEventSource es = process.getEventSource();
                  IEventListener el = es.createListener();
                  es.registerListener(el, Arrays.asList(VBoxEventType.Any), false);

                  try {
                     System.out.println("Guest process created");
                     ProcessWaitResult pwr = process.waitFor((long) ProcessWaitForFlag.Start.value(), 30 * 1000L);
                     System.out.println("Process wait result: " + pwr);
                     boolean keepLooping = true;
                     do {
                        IEvent ev = es.getEvent(el, 200);
                        if (ev != null) {
                           es.eventProcessed(el, ev);
                        }
                        /* This is how you should normally do it, but waiting for Stdout is not currently implemented - see http://hyperbox.altherian.org/kb/guessProcessHandling.txt
                        ProcessWaitResult wr = process.waitForArray(Arrays.asList(ProcessWaitForFlag.StdOut, ProcessWaitForFlag.Terminate), 200L);
                        System.out.println("Process wait result: " + wr);
                         */
                        byte[] stdOut = process.read(1L, 64L, 0L);
                        System.out.print(new String(stdOut));
                        keepLooping = !process.getStatus().toString().contains("Terminated");
                     } while (keepLooping);
                     System.out.println("Process exit code: " + process.getExitCode());
                  } finally {
                     es.unregisterListener(el);
                     if (!process.getStatus().toString().contains("Terminated")) {
                        process.terminate();
                     }
                  }
               } finally {
                  System.out.println("Session close");
                  guestSess.close();
               }
            } catch (Throwable t) {
               t.printStackTrace();
            } finally {
               System.out.println("Machine unlock");
               session.unlockMachine();
            }
         } finally {
            if (System.getProperty("vbox.ws") != null) {
               vboxManager.disconnect();
            }
            System.out.println("Disconnected");
         }
      } finally {
         vboxManager.cleanup();
         System.out.println("Closing");
      }
   }
   
}
Catch events using passive mode - Java

Code: Select all

/*
 *
 *  Written in 2015 by Maxime Dor
 *
 *  http://kamax.io/
 *
 *  To the extent possible under law, the author(s) have dedicated all copyright and related and neighboring rights to this software to the public domain worldwide. This software is distributed without any warranty.
 *  Full license can be found at http://creativecommons.org/publicdomain/zero/1.0/
 *
 */


import java.util.Arrays;
import java.util.List;
import org.virtualbox_4_3.CleanupMode;
import org.virtualbox_4_3.IEvent;
import org.virtualbox_4_3.IEventListener;
import org.virtualbox_4_3.IMachine;
import org.virtualbox_4_3.IMachineRegisteredEvent;
import org.virtualbox_4_3.IMachineStateChangedEvent;
import org.virtualbox_4_3.IProgress;
import org.virtualbox_4_3.ISession;
import org.virtualbox_4_3.ISessionStateChangedEvent;
import org.virtualbox_4_3.SessionState;
import org.virtualbox_4_3.VBoxEventType;
import org.virtualbox_4_3.VirtualBoxManager;


public class CatchEvents_4_3 {

    static VirtualBoxManager mgr;
    static Thread listener;

    public static void main(String args[]) {
        String vmName = Long.toString(System.currentTimeMillis()); // get a random VM name to use later

        System.out.println("Creating VirtualBox client instance");
        mgr = VirtualBoxManager.createInstance(null);
        try {
            /*
             * This line is only required if you are using the WebServices to connect.
             * Also, change "user" and "password" to local credentials on the machine running the web services, or set authentication to null.
             * To do so, you can start vboxwevsrv with "-A null" argument or use vboxmanage to make it permanent.
             */
            System.out.println("Connecting to VirtualBox using Web Services");
            mgr.connect("http://localhost:18083", "user", "password"); // only if you are using WebServices Bindings
            System.out.println("Connected to VirtualBox using Web Services");

            /*
             * We will run the event worker in a separate thread like it would normally be done.
             */
            listener = new EventWorker();
            listener.start();

            try {
                /*
                 * We create an empty machine, we save its settings to disk (to actually make it really exist) than we register it.
                 * This will trigger IMachineRegisteredEvent.
                 */
                IMachine vm = mgr.getVBox().createMachine(null, vmName, null, "Other", null);
                vm.saveSettings();
                mgr.getVBox().registerMachine(vm);

                vm = mgr.getVBox().findMachine(vmName); // we fetch the machine object again just to be safe
                ISession session = mgr.getSessionObject();
                IProgress p = vm.launchVMProcess(session, "headless", null);
                p.waitForCompletion(-1); // we wait until the starting process has finished
                try {
                    if (p.getResultCode() != 0) { // error when starting the VM, we don't continue further
                        throw new RuntimeException(p.getErrorInfo().getText());
                    } else { // VM got started, OnMachineStateChanged triggered two times at this point
                        // let's now power down the VM
                        p = session.getConsole().powerDown();
                        p.waitForCompletion(-1);
                        if (p.getResultCode() != 0) { // we failed to stop the VM
                            throw new RuntimeException(p.getErrorInfo().getText());
                        } else {
                            // VM got stopped, OnMachineStateChanged triggered several times at this point
                        }
                    }
                } finally {
                    // we do not need the lock any further and is required for for IMachine::unregister()
                    session.unlockMachine();

                    // since unlock is not instant, we need to wait until the unlock is done or unregister() will fail.
                    while (!SessionState.Unlocked.equals(vm.getSessionState())) {
                        try {
                            System.out.println("Waiting for session unlock...");
                            Thread.sleep(1000L);
                        } catch (InterruptedException e) {
                            System.err.println("Interrupted while waiting for session to be unlocked");
                        }
                    }

                    // vm.unregister() will trigger IMachineRegisteredEvent.
                    System.out.println("Deleting machine");
                    vm.deleteConfig(vm.unregister(CleanupMode.DetachAllReturnHardDisksOnly));
                }
            } finally { // we instruct the Event Worker to stop and wait 5 sec for it to do so
                listener.interrupt();
                try {
                    listener.join(5000); // we wait on the thread
                } catch (InterruptedException e) {
                    System.err.println("Interrupted while waiting for EventWorker to stop");
                }

                if (listener.isAlive()) {
                    System.err.println("Event worked did not stop in a timely fashion");
                } else {
                    System.out.println("Event worked stopped");
                }
            }
        } finally {
            mgr.disconnect(); // only if you are using WebServices Bindings
            mgr.cleanup();
            System.out.println("Disconnected from VirtualBox - bye bye!");
        }
    }

    static class EventWorker extends Thread {

        IEventListener el;

        @Override
        public void run() {
            System.out.println("EventWorker started");
            el = mgr.getVBox().getEventSource().createListener(); // we create the object that will fetch and queue the events for us

            /*
             * We register for the events that we are interested in.
             * If we wanted all of them, we would use VBoxEventType.Any
             * 
             * Not all events will be visible here. If we want events for a specific machine (like Clipboard mode change),
             * we need to use the event source of that specific machine - see IMachine::getEventSource()
             */
            List<VBoxEventType> types = Arrays.asList(VBoxEventType.OnSessionStateChanged, VBoxEventType.OnMachineStateChanged,
                    VBoxEventType.OnMachineRegistered);
            mgr.getVBox().getEventSource().registerListener(el, types, false);

            try {
                while(!isInterrupted()) {
                    mgr.waitForEvents(0); // Needed to clear the internal event queue, see https://www.virtualbox.org/ticket/13647
                    IEvent rawEvent = mgr.getVBox().getEventSource().getEvent(el, 1000);
                    if (rawEvent == null) { // we waited but no event came
                        continue; // we loop again and skip the code below
                    }

                    try {
                        System.out.println("Got event of type " + rawEvent.getType());

                        if (VBoxEventType.OnSessionStateChanged.equals(rawEvent.getType())) {
                            // It is important to use the queryInterface() on the expected class, simple casting will not work.
                            ISessionStateChangedEvent event = ISessionStateChangedEvent.queryInterface(rawEvent);
                            System.out.println("Session state changed to " + event.getState() + " for machine " + event.getMachineId());
                        }

                        if (VBoxEventType.OnMachineRegistered.equals(rawEvent.getType())) { // we check the event type
                            // It is important to use the queryInterface() on the expected class, simple casting will not work.
                            IMachineRegisteredEvent event = IMachineRegisteredEvent.queryInterface(rawEvent);
                            System.out.println("Machine " + event.getMachineId() + " has been " + (event.getRegistered() ? "registered" : "unregistered"));
                        }

                        if (VBoxEventType.OnMachineStateChanged.equals(rawEvent.getType())) {
                            // It is important to use the queryInterface() on the expected class, simple casting will not work.
                            IMachineStateChangedEvent event = IMachineStateChangedEvent.queryInterface(rawEvent);
                            System.out.println("Machine " + event.getMachineId() + " state changed to " + event.getState());
                        }
                    } finally {
                        // We mark the event as processed so ressources can be released. We do this in a finally block to ensure it is done no matter what.
                        mgr.getVBox().getEventSource().eventProcessed(el, rawEvent);
                    }
                }
            } catch (Throwable t) {
                t.printStackTrace();
            } finally {
                mgr.getVBox().getEventSource().unregisterListener(el); // we are done fetching events, so we free the listener
                System.out.println("EventWorker finished");
            }
        }

    }

}
Last edited by socratis on 8. Nov 2016, 07:47, edited 1 time in total.
Reason: Included the code locally.
Hyperbox - Virtual Infrastructure Manager - https://apps.kamax.lu/hyperbox/
Manage your VirtualBox infrastructure the free way!
AdityaM
Posts: 31
Joined: 8. Nov 2016, 06:12

Re: Code Samples

Post by AdityaM »

Hello,
I am not able to access the Link for Code samples listed here. Can you share the code samples through updated links or let me know if there is any other means to get the Code samples. It would be more helpful to get some sample codes for using SDK APIs in C++.
Thanks
socratis
Site Moderator
Posts: 27330
Joined: 22. Oct 2010, 11:03
Primary OS: Mac OS X other
VBox Version: PUEL
Guest OSses: Win(*>98), Linux*, OSX>10.5
Location: Greece

Re: Code Samples

Post by socratis »

I had no problem accessing the code (since I just copied/pasted here), but, you're right in a way. The code should be here, not in a 3rd party site. I edited the posts to make it so. I left the links in case there is an update to the code.
AdityaM wrote:It would be more helpful to get some sample codes for using SDK APIs in C++.
This is a user discussion site, so I guess that the only contributor felt more comfortable in Java. If you manage to get something working in C++, please feel free to include your sample code here as well. The more "generic", the better.
Do NOT send me Personal Messages (PMs) for troubleshooting, they are simply deleted.
Do NOT reply with the "QUOTE" button, please use the "POST REPLY", at the bottom of the form.
If you obfuscate any information requested, I will obfuscate my response. These are virtual UUIDs, not real ones.
RRomano001
Posts: 4
Joined: 14. Jun 2020, 16:20

Hardware emulator Code Samples

Post by RRomano001 »

Hello all, I suppose this is the first time I write here.
I am struggling looking for an example of some skeleton of hardware emulator.. I gave up without success. I found programming manual, I browsed along code source...

I am in trouble with some industrial hardware ISA based, so I need develop a new interface to circumvent obsolescence. OS run fine but now need access hardware otherwise never run.

Idea was to use some sort of FPGA + uController hardware to substitute old ISA FPGA based interface. Software emulator and FPGA VHDL are ready.
To do so, I need intercept IO space at some address then move to external interface thru TCP/IP. Also from same interface IRQ must be fired on external request. This was simple on old hardware, new one tend to have no other bus than USB.

Can someone kindly guide me where this is managed on Virtualbox?

I also browsed Qemu, I found an example but not sure can apply to VBox too.

Thank in advance
Roberto
mpack
Site Moderator
Posts: 39156
Joined: 4. Sep 2008, 17:09
Primary OS: MS Windows 10
VBox Version: PUEL
Guest OSses: Mostly XP

Re: Code Samples

Post by mpack »

There is no feature in VirtualBox for accessing physical hardware in that way. All hardware is virtual. Even in the case of serial or USB devices you are in reality talking about a network, while the actual hardware directly used by the VM (e.g. the USB controller) is virtual. The only physical hardware touched by a virtual machine is the CPU.
RRomano001
Posts: 4
Joined: 14. Jun 2020, 16:20

Re: Code Samples

Post by RRomano001 »

mpack wrote:There is no feature in VirtualBox for accessing physical hardware in that way. All hardware is virtual. Even in the case of serial or USB devices you are in reality talking about a network, while the actual hardware directly used by the VM (e.g. the USB controller) is virtual. The only physical hardware touched by a virtual machine is the CPU.
Hello Mpack, I know how virtual work from old times of virtualization.
I understand device are virtualized too.
My virtual device driver are actually used attached to a Z80 simulator/emulator and run on PC side/FPGA or intermixed. (I wrote in it entirety so I know how to transport service)

More recent hardware use ISA PC instead of processor so need write virtual driver (At almost done) and attach to virtual machine.
Where I need hint is how can add virtualized hardware to VBox.
My experience in virtual machines is from old mainframes and 68K 88K machines, old AMD slices. No experience on writing code on Intel arch.

As I wrote I found this hint on Qemu:
https://www.programmersought.com/articl ... 627927072A
not sure as I wrote if this can also apply to VBox. How to use too, I found source of virtual hardware, resemble my drivers but no idea how to attach to virtual box core.

Thank you
Roberto
mpack
Site Moderator
Posts: 39156
Joined: 4. Sep 2008, 17:09
Primary OS: MS Windows 10
VBox Version: PUEL
Guest OSses: Mostly XP

Re: Code Samples

Post by mpack »

As I said, there is no feature in VirtualBox - and certainly not in the API - to do what you want to do. The only way to add a new hardware simulation is by adding new modules to the source code. I'm not aware of any detailed guides on how to write a VirtualBox hardware simulation.

It also isn't clear to me what exactly is the relationship you expect between simulated hardware and the physical hardware that you also seem to be talking about. No such relationship exists in a VM, though some simulations do implement a "passthrough" mode in which the virtualization layer is thin and closely resembles the physical layer.
RRomano001
Posts: 4
Joined: 14. Jun 2020, 16:20

Re: Code Samples

Post by RRomano001 »

mpack wrote:As I said, there is no feature in VirtualBox - and certainly not in the API - to do what you want to do. The only way to add a new hardware simulation is by adding new modules to the source code. I'm not aware of any detailed guides on how to write a VirtualBox hardware simulation.
Hello Mpack, before asking for help I browsed a lot of source files.
I found device drivers, I seen are close to my virtualization so can be reused with few changes or as they are. Just a simple wrapper HAL module adapt to VBOX.
I DON'T found where and how these device drivers are hooked to VMBox.
I found an hint on QEmu, can this applied to VBox? If answer is yes how to use port attach?
I am using Vbox since version 1, I use external hardware attached to virtual, How can I write my own driver?
Manual are hidden, I found them but what I need is too less documented to use.
It also isn't clear to me what exactly is the relationship you expect between simulated hardware and the physical hardware that you also seem to be talking about. No such relationship exists in a VM, though some simulations do implement a "passthrough" mode in which the virtualization layer is thin and closely resembles the physical layer.
This is a looping question, tell me how to attach a virtual device and all layer is on my virtualized software too. s not your task.
I cannot attach to a bare hardware emulator, I need a virtualization of base pc hardware.

--> What I wish is how to attach virtual device to vbox. <--
Regards
mpack
Site Moderator
Posts: 39156
Joined: 4. Sep 2008, 17:09
Primary OS: MS Windows 10
VBox Version: PUEL
Guest OSses: Mostly XP

Re: Code Samples

Post by mpack »

RRomano001 wrote: What I wish is how to attach virtual device to vbox. <--
See the source code. To my knowledge it is the only documentation that exists on this subject.
RRomano001
Posts: 4
Joined: 14. Jun 2020, 16:20

Re: Code Samples

Post by RRomano001 »

mpack wrote:
RRomano001 wrote: What I wish is how to attach virtual device to vbox. <--
See the source code. To my knowledge it is the only documentation that exists on this subject.

Beautiful, I seen your task is admin, maybe you are good here but IMHO i feel your understanding about development and virtualization very low.
So open your mind, 'm not a simple user nor an unexperienced programmer.
I am able read large source code too, this way I cannot start develop nothing in Vbox.

--> No documentation nor knowledge sound as **STRONG BUG**. <--

Are here someone that know about device drivers?
This way I am just evaluating QEMU, too much newbie in front of VBox but promise more documentation and help from community.
I am now understanding this point of view was sounding harsh in first.
https://drewdevault.com/2018/09/10/Gett ... -qemu.html
Thank you for scaring about clarifiing POV.
mpack
Site Moderator
Posts: 39156
Joined: 4. Sep 2008, 17:09
Primary OS: MS Windows 10
VBox Version: PUEL
Guest OSses: Mostly XP

Re: Code Samples

Post by mpack »

This is a user discussion forum: to my knowledge you are not a client and for certain I am not an Oracle employee.

As it happens I've been a full time software developer for 40 years, so I'd hazard a guess that my knowledge is at least equal to yours.

I've now pointed you towards the only available information at least three different ways, so I see no value in prolonging this discussion any further. If you believe you are entitled to support then please contact your Oracle rep and quote your support reference number.
Post Reply