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();
  }
Exemplo n.º 2
0
  /** Disconnects from the server. */
  public void disconnect() {
    if (m_serviceInstance == null) {
      // not connected
      return;
    } else {
      ServerConnection serverConnection = m_serviceInstance.getServerConnection();

      if (serverConnection == null) {
        // not connected
        return;
      } else {
        m_serviceInstance.getServerConnection().logout();
      }
    }
  }
Exemplo n.º 3
0
  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();
  }
Exemplo n.º 4
0
  /**
   * Returns a managed entitiy for a given managed object Id.
   *
   * @param managedObjectId the managed object Id
   * @return the managed entity
   */
  public ManagedEntity getManagedEntityByManagedObjectId(String managedObjectId) {
    ManagedObjectReference managedObjectReference = new ManagedObjectReference();

    managedObjectReference.setType("ManagedEntity");
    managedObjectReference.setVal(managedObjectId);

    ManagedEntity managedEntity =
        MorUtil.createExactManagedEntity(
            m_serviceInstance.getServerConnection(), managedObjectReference);

    return managedEntity;
  }
Exemplo n.º 5
0
  /**
   * Returns a host system by a given managed object Id.
   *
   * @param managedObjectId the managed object Id
   * @return the host system object
   */
  public HostSystem getHostSystemByManagedObjectId(String managedObjectId) {
    ManagedObjectReference managedObjectReference = new ManagedObjectReference();

    managedObjectReference.setType("HostSystem");
    managedObjectReference.setVal(managedObjectId);

    HostSystem hostSystem =
        (HostSystem)
            MorUtil.createExactManagedEntity(
                m_serviceInstance.getServerConnection(), managedObjectReference);

    return hostSystem;
  }
Exemplo n.º 6
0
  /**
   * Returns a virtual machine by a given managed object Id.
   *
   * @param managedObjectId the managed object Id
   * @return the virtual machine object
   */
  public VirtualMachine getVirtualMachineByManagedObjectId(String managedObjectId) {
    ManagedObjectReference managedObjectReference = new ManagedObjectReference();

    managedObjectReference.setType("VirtualMachine");
    managedObjectReference.setVal(managedObjectId);

    VirtualMachine virtualMachine =
        (VirtualMachine)
            MorUtil.createExactManagedEntity(
                m_serviceInstance.getServerConnection(), managedObjectReference);

    return virtualMachine;
  }
Exemplo n.º 7
0
 /**
  * Sets the timeout for server connections.
  *
  * @param timeout the timeout to be used for connecting
  * @return true, if the operation was successful
  */
 public boolean setTimeout(int timeout) {
   if (m_serviceInstance != null) {
     ServerConnection serverConnection = m_serviceInstance.getServerConnection();
     if (serverConnection != null) {
       VimPortType vimService = serverConnection.getVimService();
       if (vimService != null) {
         WSClient wsClient = vimService.getWsc();
         if (wsClient != null) {
           wsClient.setConnectTimeout(timeout);
           wsClient.setReadTimeout(timeout);
           return true;
         }
       }
     }
   }
   return false;
 }
  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();
      }
    }
  }
Exemplo n.º 9
0
  @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();
    }
  }