Example #1
0
 public void createSnapshot() {
   try {
     ServiceInstance si =
         new ServiceInstance(new URL("https://130.65.132.214/sdk"), "root", "12!@qwQW", true);
     VirtualMachine vm =
         (VirtualMachine)
             new InventoryNavigator(si.getRootFolder())
                 .searchManagedEntity("VirtualMachine", VM_NAME);
     Task task =
         vm.createSnapshot_Task(
             "snapshot1", "Nachu's first snapshot", false /* memory */, false /* quiesce */);
     System.out.println("Snapshot created");
   } catch (InvalidProperty e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   } catch (RuntimeFault e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   } catch (RemoteException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   } catch (MalformedURLException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   }
 }
  public static void main(String[] args) throws Exception {
    ServiceInstance si =
        new ServiceInstance(new URL("http://10.20.143.205/sdk"), "root", "password", true);
    Folder rootFolder = si.getRootFolder();
    ManagedEntity[] vms =
        new InventoryNavigator(rootFolder).searchManagedEntities("VirtualMachine");
    ManagedEntity[] hosts = new InventoryNavigator(rootFolder).searchManagedEntities("HostSystem");

    CacheInstance vicf = new CacheInstance(si);
    vicf.watch(vms, new String[] {"name", "runtime.powerState", "summary"});
    vicf.watch(hosts, new String[] {"name", "summary"});
    vicf.start();

    // check if the caching is ready to use; otherwise wait
    while (!vicf.isReady()) {
      Thread.sleep(1000);
    }

    Thread[] vrs = new VimReader[2];

    for (int i = 0; i < vrs.length; i++) {
      vrs[i] = new VimReader("Thread " + i, vicf, vms, hosts);
      vrs[i].start();
    }

    for (int i = 0; i < vrs.length; i++) {
      vrs[i].join();
    }
    si.getServerConnection().logout();
  }
  public static void main(String[] args) throws Exception {
    ServiceInstance si = new ServiceInstance(new URL(VCENTERURL), USERNAME, PASSWORD, true);
    Folder rootFolder = si.getRootFolder();
    ManagedEntity[] hosts = new InventoryNavigator(rootFolder).searchManagedEntities("HostSystem");
    if (hosts == null || hosts.length == 0) {
      return;
    }
    for (int i = 0; i < hosts.length; i++) { // get all vm in Vhost
      System.out.println("vHost loop ******************");
      System.out.println("HostName: " + hosts[i].getName());
      ManagedEntity[] mes =
          new InventoryNavigator(rootFolder).searchManagedEntities("VirtualMachine");
      for (int j = 0; j < mes.length; j++) {
        VirtualMachine vm = (VirtualMachine) mes[j];
        VirtualMachineConfigInfo vminfo = vm.getConfig();
        vm.getResourcePool();
        System.out.println("vHost: " + vm.getParent().getName());
        System.out.println("Guest: " + vm.getName());
        System.out.println("GuestOS: " + vminfo.getGuestFullName());
        System.out.println("GuestState: " + vm.getGuest().guestState);
        System.out.println("Guest Ip address: " + vm.getGuest().getIpAddress());

        pingByIP(vm.getGuest().getIpAddress()); // ping VM
      }

      HostSystem newHost = (HostSystem) hosts[i];
      String vHost_IP =
          newHost.getConfig().getNetwork().getVnic()[0].getSpec().getIp().getIpAddress();
      System.out.println("vHost IP address: " + vHost_IP);

      // test for ping vHost
      pingByIP(vHost_IP); // ping vHost
    }
  } // end of main
  public static void main(String[] args) throws Exception {
    if (args.length != 5) {
      System.out.println("Usage: java VMpowerOps <url> " + "<username> <password> <vmname> <op>");
      System.out.println("op - reboot|poweron|poweroff" + "|reset|standby|suspend|shutdown");
      System.exit(0);
    }

    String vmname = args[3];
    String op = args[4];

    ServiceInstance si = new ServiceInstance(new URL(args[0]), args[1], args[2], true);

    Folder rootFolder = si.getRootFolder();
    VirtualMachine vm =
        (VirtualMachine)
            new InventoryNavigator(rootFolder).searchManagedEntity("VirtualMachine", vmname);

    if (vm == null) {
      System.out.println("No VM " + vmname + " found");
      si.getServerConnection().logout();
      return;
    }

    if ("reboot".equalsIgnoreCase(op)) {
      vm.rebootGuest();
      System.out.println(vmname + " guest OS rebooted");
    } else if ("poweron".equalsIgnoreCase(op)) {
      Task task = vm.powerOnVM_Task(null);
      if (task.waitForMe() == Task.SUCCESS) {
        System.out.println(vmname + " powered on");
      }
    } else if ("poweroff".equalsIgnoreCase(op)) {
      Task task = vm.powerOffVM_Task();
      if (task.waitForMe() == Task.SUCCESS) {
        System.out.println(vmname + " powered off");
      }
    } else if ("reset".equalsIgnoreCase(op)) {
      Task task = vm.resetVM_Task();
      if (task.waitForMe() == Task.SUCCESS) {
        System.out.println(vmname + " reset");
      }
    } else if ("standby".equalsIgnoreCase(op)) {
      vm.standbyGuest();
      System.out.println(vmname + " guest OS stoodby");
    } else if ("suspend".equalsIgnoreCase(op)) {
      Task task = vm.suspendVM_Task();
      if (task.waitForMe() == Task.SUCCESS) {
        System.out.println(vmname + " suspended");
      }
    } else if ("shutdown".equalsIgnoreCase(op)) {
      Task task = vm.suspendVM_Task();
      if (task.waitForMe() == Task.SUCCESS) {
        System.out.println(vmname + " suspended");
      }
    } else {
      System.out.println("Invalid operation. Exiting...");
    }
    si.getServerConnection().logout();
  }
Example #5
0
  /**
   * Main Constructor Takes a ServiceInstance object created by the login splash
   *
   * @param ServiceInstance si
   * @see LoginSplash
   */
  public CommandEngine(ServiceInstance si, Main main) {
    super(si);
    this.main = main;
    vmTemplates = new ArrayList<Template>();
    vmRootEntities = new ArrayList<VirtualMachineExt>();
    vmFolders = new ArrayList<FolderExt>();
    networks = new ArrayList<Network>();

    try {
      Folder rootFolder = si.getRootFolder();
      ManagedEntity[] datacenters = rootFolder.getChildEntity();
      for (int i = 0; i < datacenters.length; i++) {
        if (datacenters[i] instanceof Datacenter
            && datacenters[i].getName().equalsIgnoreCase(DATACENTER)) {
          dc = (Datacenter) datacenters[i];
        }
      }

      // Set the template directory and the project directory
      for (ManagedEntity each : dc.getVmFolder().getChildEntity()) {
        if (each instanceof Folder && each.getName().equalsIgnoreCase(TEMPLATE_FOLDER)) {
          templateDir = (Folder) each;
        } else if (each instanceof Folder && each.getName().equalsIgnoreCase(ROOT_FOLDER)) {
          rootDir = (Folder) each;
        }
      }

      // Set the target datastore for new VM deployments
      for (ManagedEntity each : dc.getDatastoreFolder().getChildEntity()) {
        if (each instanceof Datastore && each.getName().equalsIgnoreCase(TARGET_DATASTORE)) {
          targetDatastore = (Datastore) each;
        }
      }

      // Get Networks - only happens once per load
      for (ManagedEntity each : dc.getNetworkFolder().getChildEntity()) {
        if (each instanceof Network) {
          networks.add(((Network) each));
        }
      }

      refresh();
    } catch (RemoteException e) {
      disconnect();
      LOG.printStackTrace(e);
    } catch (Exception e) {
      LOG.printStackTrace(e);
    }
  }
  @Override
  public void configNetworks(Node node) throws Exception {
    VirtualMachine vm = VmUtil.getVirtualMachine(serviceInstance, node.getVmName());
    VcNetwork vcNet = null;
    String operation = null;
    String network = null;
    String newNetwork = null;

    for (NetworkResource networkResource : node.getTargetHost().getNetworks()) {
      // the setting network for Cloudera director exists in Esx hosts netowrk which the node vm is
      // located in
      if (node.getNetwork().equals(networkResource.getName())) {
        vcNet = new VcNetwork();
        vcNet.update(
            serviceInstance.getRootFolder().getServerConnection(),
            networkResource.toVim25Network(serviceInstance));

        if (vm.getNetworks().length == 0) {
          operation = "add";
          network = node.getNetwork();
        } else {
          operation = "edit";
          network = vm.getNetworks()[0].getName();
          newNetwork = node.getNetwork();
        }
        break;
      }
    }

    if (vcNet == null) {
      throw new Exception("Network " + node.getNetwork() + " is not defined on ESX hosts");
    }

    VmNicOperationService vmNicOperationService =
        new VmNicOperationService(vm, operation, vcNet, network, newNetwork);
    vmNicOperationService.run();
  }
Example #7
0
 public void deleteSnapshot() {
   try {
     ServiceInstance si =
         new ServiceInstance(new URL("https://130.65.132.214/sdk"), "root", "12!@qwQW", true);
     VirtualMachine vm =
         (VirtualMachine)
             new InventoryNavigator(si.getRootFolder())
                 .searchManagedEntity("VirtualMachine", VM_NAME);
     vm.removeAllSnapshots_Task();
     System.out.println("Snapshot deleted");
   } catch (InvalidProperty e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   } catch (RuntimeFault e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   } catch (RemoteException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   } catch (MalformedURLException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   }
 }
  public static void main(String[] args)
      throws InvalidProperty, RuntimeFault, RemoteException, MalformedURLException {
    ServiceInstance si =
        new ServiceInstance(
            new URL(args[0]),
            args[1],
            args[2],
            true); // Pass 3 argument as vCenterIP/username/password
    String ClusterName = "Cluster"; // Cluster Name
    String VMToBeRemoved = "VM1";
    String VMToBeAdded = "VM3";
    Folder rootFolder = si.getRootFolder();
    VirtualMachine vm1 =
        (VirtualMachine)
            new InventoryNavigator(rootFolder).searchManagedEntity("VirtualMachine", VMToBeRemoved);
    VirtualMachine vm2 =
        (VirtualMachine)
            new InventoryNavigator(rootFolder).searchManagedEntity("VirtualMachine", VMToBeAdded);
    ManagedObjectReference vmMor1 = vm1.getMOR();
    ManagedObjectReference vmMor2 = vm2.getMOR();

    ClusterComputeResource cluster = null;
    cluster =
        (ClusterComputeResource)
            new InventoryNavigator(rootFolder)
                .searchManagedEntity("ClusterComputeResource", ClusterName);

    // Number of rules in a cluster
    ClusterRuleInfo[] ruleinfo = ((ClusterConfigInfoEx) cluster.getConfigurationEx()).getRule();

    if (ruleinfo == null || ruleinfo.length == 0) {
      System.out.println("There is no DRS rule in the cluster:: " + cluster.getName());
    }

    for (ClusterRuleInfo rule : ruleinfo) {
      if (((rule instanceof ClusterAffinityRuleSpec)) && (rule.getName().equals("VM VM Rule"))) {
        ManagedObjectReference[] vms = ((ClusterAffinityRuleSpec) rule).getVm();
        for (ManagedObjectReference vm : vms) {
          if (vm.getVal().equals(vmMor1.getVal())) {
            // Removed the VM from rule
            vms = (ManagedObjectReference[]) ArrayUtils.removeElement(vms, vm);
            break;
          }
        }
        // Added the new VM to the rule
        vms = (ManagedObjectReference[]) ArrayUtils.add(vms, vmMor2);

        ClusterAffinityRuleSpec cars = (ClusterAffinityRuleSpec) rule;
        cars.setVm(vms);

        ClusterRuleSpec crs1 = new ClusterRuleSpec();
        crs1.setInfo(cars);
        crs1.setOperation(ArrayUpdateOperation.edit);

        ClusterConfigSpec ccs = new ClusterConfigSpec();
        ccs.setRulesSpec(new ClusterRuleSpec[] {crs1});

        cluster.reconfigureCluster_Task(ccs, true);
        System.out.println("Rule reconfigured successfully ");
        si.getServerConnection().logout();
      }
    }
  }
 /**
  * Searches for a managed entity by a given type.
  *
  * @param type the type string to search for
  * @return the list of managed entities found
  * @throws RemoteException
  */
 public ManagedEntity[] searchManagedEntities(String type) throws RemoteException {
   return (new InventoryNavigator(m_serviceInstance.getRootFolder())).searchManagedEntities(type);
 }
  @Override
  public void run() {
    try {
      ServiceDetails sd = ServiceDetails.getInstance();
      ServiceInstance si = sd.getSi();
      Folder rootFolder = si.getRootFolder();
      String name = rootFolder.getName();
      System.out.println("root:" + name);

      System.out.println("\n============ Data Centers ============");
      ManagedEntity[] dcs = new InventoryNavigator(rootFolder).searchManagedEntities("Datacenter");
      for (int i = 0; i < dcs.length; i++) {
        System.out.println("Datacenter[" + i + "]=" + dcs[i].getName());
        sd.setDc((Datacenter) dcs[i]);
      }

      System.out.println("\n\n============ Hosts ============");
      ManagedEntity[] hostsArray =
          new InventoryNavigator(rootFolder).searchManagedEntities("HostSystem");
      for (int i = 0; i < hostsArray.length; i++) {
        System.out.println("host[" + i + "]=" + hostsArray[i].getName());
      }

      System.out.println("\n\n============ Virtual Machines ============");
      ManagedEntity[] vms =
          new InventoryNavigator(rootFolder).searchManagedEntities("VirtualMachine");
      VirtualMachine vm = null;

      System.out.println(
          " VM Name"
              + "\t\t Guest OS"
              + "\t\t VM Version"
              + "\t\t CPU \t"
              + "\t\t Memory "
              + "\t\t VMware Tools"
              + "\t\t IP Addresses"
              + "\tState");
      for (int i = 0; i < vms.length; i++) {

        vm = (VirtualMachine) vms[i];

        System.out.println(
            vms[i].getName()
                + "\t\t"
                + vm.getSummary().getConfig().guestFullName
                + "\t"
                + vm.getConfig().version
                + "\t\t\t"
                + vm.getConfig().getHardware().numCPU
                + "vCPU \t\t\t"
                + vm.getConfig().getHardware().memoryMB
                + " MB \t"
                + "\t"
                + vm.getGuest().toolsRunningStatus
                + "\t"
                + vm.getSummary().getGuest().getIpAddress()
                + "\t \t "
                + vm.getGuest().guestState
                + "\n");
        /*		        System.out.println("VM Version:"+vm.getConfig().version);
        System.out.println("CPU:"+vm.getConfig().getHardware().numCPU+" vCPU");
        System.out.println("Memory:"+vm.getConfig().getHardware().memoryMB+" MB");
        System.out.println("VMware Tools:"+vm.getGuest().toolsRunningStatus);
        System.out.println("IP Addresses:"+vm.getSummary().getGuest().getIpAddress());
        System.out.println("State:"+vm.getGuest().guestState);*/
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  @Override
  public void run() {

    try {

      while (true) {

        URL url = new URL(SJSULabConfig.getvCenterURL());
        try {

          ServiceInstance si =
              new ServiceInstance(
                  url, SJSULabConfig.getvCenterUsername(), SJSULabConfig.getPassword(), true);
          HostSystem host =
              (HostSystem)
                  new InventoryNavigator(si.getRootFolder())
                      .searchManagedEntity("HostSystem", ip); //
          System.out.println("host value" + host);
          PerformanceManager perfMgr = si.getPerformanceManager();

          PerfProviderSummary summary = perfMgr.queryPerfProviderSummary(host); // vm

          int perfInterval = summary.getRefreshRate();

          PerfMetricId[] queryAvailablePerfMetric =
              perfMgr.queryAvailablePerfMetric(host, null, null, perfInterval);
          PerfCounterInfo[] pci = perfMgr.getPerfCounter();
          ArrayList<PerfMetricId> list = new ArrayList<PerfMetricId>();
          for (int i2 = 0; i2 < queryAvailablePerfMetric.length; i2++) {
            PerfMetricId perfMetricId = queryAvailablePerfMetric[i2];
            if (SELECTED_COUNTER_ID == perfMetricId.getCounterId()) {
              list.add(perfMetricId);
            }
          }
          PerfMetricId[] pmis = list.toArray(new PerfMetricId[list.size()]);
          PerfQuerySpec qSpec = new PerfQuerySpec();
          qSpec.setEntity(host.getMOR());
          qSpec.setMetricId(pmis);

          qSpec.intervalId = perfInterval;
          PerfEntityMetricBase[] pembs = perfMgr.queryPerf(new PerfQuerySpec[] {qSpec});

          for (int i = 0; pembs != null && i < pembs.length; i++) {

            PerfEntityMetricBase val = pembs[i];
            PerfEntityMetric pem = (PerfEntityMetric) val;
            PerfMetricSeries[] vals = pem.getValue();
            PerfSampleInfo[] infos = pem.getSampleInfo();

            Date date1 = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yyyy h:mm:ss");
            String formattedDate = sdf.format(date1);

            infoList.put(aName[counter], formattedDate);

            for (int j = 0; vals != null && j < vals.length; ++j) {
              PerfMetricIntSeries val1 = (PerfMetricIntSeries) vals[j];
              long[] longs = val1.getValue();
              System.out.println("Host CPU :" + longs[5]);
              infoList.put(aName[0], String.valueOf(longs[5]));
              /*
              for (int k : a) {

              	infoList.put(aName[counter+1],
              			String.valueOf(longs[k]));
              	counter++;
              }
              counter = 0;
              */
            }
          }
          si.getServerConnection().logout();
        } catch (InvalidProperty e) {
          e.printStackTrace();
        } catch (RuntimeFault e) {
          e.printStackTrace();
        } catch (RemoteException e) {
          e.printStackTrace();
        } catch (MalformedURLException e) {
          e.printStackTrace();
        }

        //	infoList.put("vmIP", ip);

        counter = 0;

        try {

          StringBuilder sb = new StringBuilder();
          sb.append("vmname:" + ip + ",");
          int countTest = 0;
          for (String str : aName) {
            sb.append(aName[countTest] + ":" + infoList.get(str).toString() + ",");
            countTest++;
          }
          String out = sb.toString();
          out = out.substring(0, out.length() - 1);
          writer.write(out + "\n");
          System.out.println(out);
        } catch (Exception e) {
          e.printStackTrace();
        }

        Thread.sleep(5000);
      }

    } catch (Exception e) {
      e.printStackTrace();
    }
  }