Exemple #1
0
  private static void createAndShowGUI(String firstColumnName, List<String> statNames) {
    try {
      String lookAndFeel = UIManager.getSystemLookAndFeelClassName();
      UIManager.setLookAndFeel(lookAndFeel);
      JFrame.setDefaultLookAndFeelDecorated(true);
    } catch (SOAPFaultException sfe) {
      printSoapFaultException(sfe);
    } catch (Exception e) {
      e.printStackTrace();
    }

    JFrame frame = new JFrame("VITop");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    String[] columnNamesArray = new String[statNames.size() + 1];
    columnNamesArray[0] = firstColumnName;
    for (int i = 0; i < statNames.size(); i++) {
      columnNamesArray[i + 1] = statNames.get(i);
    }
    statsTable = new StatsTable(columnNamesArray);
    statsTable.setOpaque(true);
    frame.setContentPane(statsTable);

    frame.pack();
    frame.setVisible(true);
  }
Exemple #2
0
 public static void main(String[] args) {
   try {
     getConnectionParameters(args);
     if (help) {
       printUsage();
       return;
     }
     long bTime = System.currentTimeMillis();
     connect();
     printHostProductDetails();
     long eTime = System.currentTimeMillis();
     System.out.println("Total time in milli secs to get the product line id: " + (eTime - bTime));
   } catch (IllegalArgumentException e) {
     System.out.println(e.getMessage());
     printUsage();
   } catch (SOAPFaultException sfe) {
     printSoapFaultException(sfe);
   } catch (Exception e) {
     e.printStackTrace();
   } finally {
     try {
       disconnect();
     } catch (SOAPFaultException sfe) {
       printSoapFaultException(sfe);
     } catch (Exception e) {
       System.out.println("Failed to disconnect - " + e.getMessage());
       e.printStackTrace();
     }
   }
 }
Exemple #3
0
 public static void main(String[] args) {
   try {
     getConnectionParameters(args);
     getInputParameters(args);
     if (help) {
       printUsage();
       return;
     }
     connect();
     displayStats();
   } catch (IllegalArgumentException e) {
     System.out.println(e.getMessage());
     printUsage();
   } catch (SOAPFaultException sfe) {
     printSoapFaultException(sfe);
   } catch (Exception e) {
     e.printStackTrace();
   } finally {
     try {
       disconnect();
     } catch (SOAPFaultException sfe) {
       printSoapFaultException(sfe);
     } catch (Exception e) {
       System.out.println("Failed to disconnect - " + e.getMessage());
       e.printStackTrace();
     }
   }
 }
  public void suspendPoweredOnGuestVMs(ManagedObjectReference attachHostMoref)
      throws InvalidPropertyFaultMsg, RuntimeFaultFaultMsg {
    Map<ManagedObjectReference, Map<String, Object>> vms =
        getMOREFs.inContainerByType(
            attachHostMoref,
            "VirtualMachine",
            new String[] {"name", "runtime.powerState"},
            new RetrieveOptions());
    suspendedVMList = new ArrayList<ManagedObjectReference>();
    for (ManagedObjectReference vm : vms.keySet()) {
      Map<String, Object> vmProp = vms.get(vm);
      VirtualMachinePowerState vmPowerState =
          (VirtualMachinePowerState) vmProp.get("runtime.powerState");
      String vmName = (String) vmProp.get("name");
      if ((vmPowerState.equals(VirtualMachinePowerState.POWERED_ON))) {
        try {
          ManagedObjectReference taskmor = vimPort.suspendVMTask(vm);
          if (getTaskResultAfterDone(taskmor)) {
            System.out.println(vmName + "[" + vm.getValue() + "] suspended successfully");
            suspendedVMList.add(vm);
          }

        } catch (Exception e) {
          System.out.println(vmName + "Unable to suspend vm : " + vm + "[" + vm.getValue() + "]");
          System.err.println("Reason :" + e.getLocalizedMessage());
        }
      }
    }
  }
  /**
   * @param args arg[0] - URL of the Virtual Center Server / ESX host https://<Server host name /
   *     ip>/sdk arg[1] - User name arg[2] - Password arg[3] - One of vminfo, hostvminfo, or vmmor
   *     arg[4] - If vmmor is arg[3], then vmname argument is mandatory
   */
  public static void main(String[] args) {
    // This is to accept all SSL certifcates by default.
    System.setProperty(
        "org.apache.axis.components.net.SecureSocketFactory",
        "org.apache.axis.components.net.SunFakeTrustSocketFactory");
    if (args.length < 3) {
      printUsage();
    } else {
      try {
        /**
         * ****************************** ******************************* ** *** ** Your code goes
         * here *** ** (fill-in 1 of 1) *** ** *** *******************************
         * *******************************
         */
        VIM_HOST = args[0];
        USER_NAME = args[1];
        PASSWORD = args[2];
        initAll();
        System.out.println("***************************************************************");

        long st = System.currentTimeMillis();
        getVMInfo();
        long et = System.currentTimeMillis();
        System.out.println(
            "\nTotal time (msec) to retrieve the properties of all VMs in one call: " + (et - st));
        System.out.println("\n***************************************************************");
        System.out.println("\n***************************************************************");
        st = System.currentTimeMillis();
        initVMMorList();
        Iterator<ManagedObjectReference> iter = VM_MOR_LIST.iterator();
        StringBuilder sb = new StringBuilder();
        String name = "name";
        String powerState = "runtime.powerState";
        while (iter.hasNext()) {
          ManagedObjectReference vmMor = iter.next();
          String vmName = (String) getVMProperty(vmMor, name);
          sb.append(vmName);
          VirtualMachinePowerState vmPs =
              (VirtualMachinePowerState) getVMProperty(vmMor, powerState);
          sb.append(" : ");
          sb.append(vmPs);
          sb.append("\n");
        }
        et = System.currentTimeMillis();
        System.out.println(sb.toString());
        System.out.println(
            "\nTotal time (msec) to retrieve the properties of all VMs individually: " + (et - st));
        System.out.println("\n***************************************************************");
      } catch (Exception e) {
        e.printStackTrace();
      } finally {
        try {
          disconnect();
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
    }
  }
 private static void initRootFolder() {
   if (ROOT_FOLDER == null) {
     try {
       ROOT_FOLDER = SERVICE_CONTENT.getRootFolder();
     } catch (Exception e) {
       e.printStackTrace();
     }
   }
 }
 private static void initServiceContent() {
   if (SERVICE_CONTENT == null) {
     try {
       SERVICE_CONTENT = VIM_PORT.retrieveServiceContent(SIMO_REF);
     } catch (Exception e) {
       e.printStackTrace();
     }
   }
 }
 private static void initPropertyCollector() {
   if (PROP_COLLECTOR == null) {
     try {
       PROP_COLLECTOR = SERVICE_CONTENT.getPropertyCollector();
     } catch (Exception e) {
       e.printStackTrace();
     }
   }
 }
Exemple #9
0
  /**
   * @param datacenterName The name of the Datacenter
   * @return ManagedObjectReference to the Datacenter
   */
  private static ManagedObjectReference getDatacenterByName(String datacenterName) {
    ManagedObjectReference retVal = null;
    ManagedObjectReference rootFolder = serviceContent.getRootFolder();
    ManagedObjectReference propCollector = serviceContent.getPropertyCollector();
    try {
      TraversalSpec tSpec = getDatacenterTraversalSpec();
      // Create Property Spec
      PropertySpec propertySpec = new PropertySpec();
      propertySpec.setAll(Boolean.FALSE);
      propertySpec.getPathSet().add("name");
      propertySpec.setType("Datacenter");

      // Now create Object Spec
      ObjectSpec objectSpec = new ObjectSpec();
      objectSpec.setObj(rootFolder);
      objectSpec.setSkip(Boolean.TRUE);
      objectSpec.getSelectSet().add(tSpec);

      // Create PropertyFilterSpec using the PropertySpec and ObjectPec
      // created above.
      PropertyFilterSpec propertyFilterSpec = new PropertyFilterSpec();
      propertyFilterSpec.getPropSet().add(propertySpec);
      propertyFilterSpec.getObjectSet().add(objectSpec);

      List<PropertyFilterSpec> listpfs = new ArrayList<PropertyFilterSpec>(1);
      listpfs.add(propertyFilterSpec);
      List<ObjectContent> listobjcont = retrievePropertiesAllObjects(listpfs);

      if (listobjcont != null) {
        for (ObjectContent oc : listobjcont) {
          ManagedObjectReference mr = oc.getObj();
          String dcnm = null;
          List<DynamicProperty> dps = oc.getPropSet();
          if (dps != null) {
            // Since there is only one property PropertySpec pathset
            // this array contains only one value
            for (DynamicProperty dp : dps) {
              dcnm = (String) dp.getVal();
            }
          }
          // This is done outside of the previous for loop to break
          // out of the loop as soon as the required datacenter is found.
          if (dcnm != null && dcnm.equals(datacenterName)) {
            retVal = mr;
            break;
          }
        }
      }
    } catch (SOAPFaultException sfe) {
      printSoapFaultException(sfe);
    } catch (Exception e) {
      e.printStackTrace();
    }
    return retVal;
  }
 /**
  * @param url The URL of the Virtual Center Server
  *     <p>https://<Server IP / host name>/sdk
  *     <p>The method establishes connection with the web service port on the server. This is not
  *     to be confused with the session connection.
  */
 private static void initVimPort(String url) {
   VimServiceLocator locator = new VimServiceLocator();
   locator.setMaintainSession(true);
   try {
     VIM_PORT = locator.getVimPort(new URL(url));
   } catch (MalformedURLException mue) {
     mue.printStackTrace();
   } catch (Exception se) {
     se.printStackTrace();
   }
 }
 public Connection connect() {
   if (!isConnected()) {
     try {
       _connect();
     } catch (Exception e) {
       Throwable cause = (e.getCause() != null) ? e.getCause() : e;
       throw new BasicConnectionException(
           "failed to connect: " + e.getMessage() + " : " + cause.getMessage(), cause);
     }
   }
   return this;
 }
Exemple #12
0
  /**
   * Retrieves the MOREF of the host.
   *
   * @param hostName :
   * @return
   */
  private static ManagedObjectReference getHostByHostName(String hostName) {
    ManagedObjectReference retVal = null;
    ManagedObjectReference rootFolder = serviceContent.getRootFolder();
    try {
      TraversalSpec tSpec = getHostSystemTraversalSpec();
      // Create Property Spec
      PropertySpec propertySpec = new PropertySpec();
      propertySpec.setAll(Boolean.FALSE);
      propertySpec.getPathSet().add("name");
      propertySpec.setType("HostSystem");

      // Now create Object Spec
      ObjectSpec objectSpec = new ObjectSpec();
      objectSpec.setObj(rootFolder);
      objectSpec.setSkip(Boolean.TRUE);
      objectSpec.getSelectSet().add(tSpec);

      // Create PropertyFilterSpec using the PropertySpec and ObjectPec
      // created above.
      PropertyFilterSpec propertyFilterSpec = new PropertyFilterSpec();
      propertyFilterSpec.getPropSet().add(propertySpec);
      propertyFilterSpec.getObjectSet().add(objectSpec);
      List<PropertyFilterSpec> listpfs = new ArrayList<PropertyFilterSpec>(1);
      listpfs.add(propertyFilterSpec);
      List<ObjectContent> listobjcont = retrievePropertiesAllObjects(listpfs);

      if (listobjcont != null) {
        for (ObjectContent oc : listobjcont) {
          ManagedObjectReference mr = oc.getObj();
          String hostnm = null;
          List<DynamicProperty> listDynamicProps = oc.getPropSet();
          DynamicProperty[] dps =
              listDynamicProps.toArray(new DynamicProperty[listDynamicProps.size()]);
          if (dps != null) {
            for (DynamicProperty dp : dps) {
              hostnm = (String) dp.getVal();
            }
          }
          if (hostnm != null && hostnm.equals(hostName)) {
            retVal = mr;
            break;
          }
        }
      } else {
        System.out.println("The Object Content is Null");
      }
    } catch (SOAPFaultException sfe) {
      printSoapFaultException(sfe);
    } catch (Exception e) {
      e.printStackTrace();
    }
    return retVal;
  }
Exemple #13
0
 private static void refreshStats() {
   try {
     PerfCompositeMetric metric = vimPort.queryPerfComposite(perfManager, querySpec);
     XMLGregorianCalendar latestTs = displayStats(querySpec.getMetricId(), metric);
     if (latestTs != null) {
       querySpec.setStartTime(latestTs);
     }
   } catch (SOAPFaultException sfe) {
     printSoapFaultException(sfe);
   } catch (Exception ex) {
     ex.printStackTrace();
   }
 }
  /**
   * Demonstrate how to use the PropertyCollector to retrieve properties of a managed object.
   *
   * <p>Prints Virtual machine name and powerstate of all the VMs in the datacenter (Either VC or
   * ESX host).
   */
  public static void getVMInfo() {
    try {
      TraversalSpec tSpec = getVMTraversalSpec();
      // Create Property Spec
      PropertySpec propertySpec = new PropertySpec();
      propertySpec.setAll(Boolean.FALSE);
      propertySpec.setPathSet(new String[] {"name", "runtime.powerState"});
      propertySpec.setType("VirtualMachine");
      PropertySpec[] propertySpecs = new PropertySpec[] {propertySpec};

      // Now create Object Spec
      ObjectSpec objectSpec = new ObjectSpec();
      objectSpec.setObj(ROOT_FOLDER);
      objectSpec.setSkip(Boolean.TRUE);
      objectSpec.setSelectSet(new SelectionSpec[] {tSpec});
      ObjectSpec[] objectSpecs = new ObjectSpec[] {objectSpec};

      // Create PropertyFilterSpec using the PropertySpec and ObjectPec
      // created above.
      PropertyFilterSpec propertyFilterSpec = new PropertyFilterSpec();
      propertyFilterSpec.setPropSet(propertySpecs);
      propertyFilterSpec.setObjectSet(objectSpecs);

      PropertyFilterSpec[] propertyFilterSpecs = new PropertyFilterSpec[] {propertyFilterSpec};

      ObjectContent[] oCont = VIM_PORT.retrieveProperties(PROP_COLLECTOR, propertyFilterSpecs);
      if (oCont != null) {
        // System.out.println("ObjectContent Length : " + oCont.length);
        StringBuilder sb = new StringBuilder();
        for (ObjectContent oc : oCont) {
          DynamicProperty[] dps = oc.getPropSet();
          if (dps != null) {
            for (DynamicProperty dp : dps) {
              if (dp.getName().equalsIgnoreCase("name")) {
                sb.append(dp.getVal());
                sb.append(" : ");
              } else {
                sb.append(dp.getVal());
                sb.append("\n");
              }
              // System.out.println(dp.getName() + " : " +
              // dp.getVal());
            }
          }
        }
        System.out.println(sb.toString());
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  /*
   * This method calls all the initialization methods required in order.
   */
  private static void initAll() {
    // These following methods have to be called in this order.
    initSIMORef();
    initVimPort(VIM_HOST);
    initServiceContent();
    try {
      connect(VIM_HOST, USER_NAME, PASSWORD);
    } catch (Exception e) {
      e.printStackTrace();
    }

    initPropertyCollector();
    initRootFolder();
  }
Exemple #16
0
 /**
  * Determines of a method 'methodName' exists for the Object 'obj'.
  *
  * @param obj The Object to check
  * @param methodName The method name
  * @param parameterTypes Array of Class objects for the parameter types
  * @return true if the method exists, false otherwise
  */
 private static boolean methodExists(Object obj, String methodName, Class[] parameterTypes) {
   boolean exists = false;
   try {
     Method method = obj.getClass().getMethod(methodName, parameterTypes);
     if (method != null) {
       exists = true;
     }
   } catch (SOAPFaultException sfe) {
     printSoapFaultException(sfe);
   } catch (Exception e) {
     e.printStackTrace();
   }
   return exists;
 }
Exemple #17
0
  /**
   * Get the MOR of the Virtual Machine by its name.
   *
   * @param vmName The name of the Virtual Machine
   * @return The Managed Object reference for this VM
   */
  private static ManagedObjectReference getVmByVMname(String vmname) {
    ManagedObjectReference retVal = null;
    try {
      TraversalSpec tSpec = getVMTraversalSpec();
      // Create Property Spec
      PropertySpec propertySpec = new PropertySpec();
      propertySpec.setAll(Boolean.FALSE);
      propertySpec.getPathSet().add("name");
      propertySpec.setType("VirtualMachine");

      // Now create Object Spec
      ObjectSpec objectSpec = new ObjectSpec();
      objectSpec.setObj(rootRef);
      objectSpec.setSkip(Boolean.TRUE);
      objectSpec.getSelectSet().add(tSpec);

      // Create PropertyFilterSpec using the PropertySpec and ObjectPec
      // created above.
      PropertyFilterSpec propertyFilterSpec = new PropertyFilterSpec();
      propertyFilterSpec.getPropSet().add(propertySpec);
      propertyFilterSpec.getObjectSet().add(objectSpec);

      List<PropertyFilterSpec> listpfs = new ArrayList<PropertyFilterSpec>(1);
      listpfs.add(propertyFilterSpec);
      List<ObjectContent> listobjcont = retrievePropertiesAllObjects(listpfs);

      if (listobjcont != null) {
        for (ObjectContent oc : listobjcont) {
          ManagedObjectReference mr = oc.getObj();
          String vmnm = null;
          List<DynamicProperty> dps = oc.getPropSet();
          if (dps != null) {
            for (DynamicProperty dp : dps) {
              vmnm = (String) dp.getVal();
            }
          }
          if (vmnm != null && vmnm.equals(vmname)) {
            retVal = mr;
            break;
          }
        }
      }
    } catch (SOAPFaultException sfe) {
      printSoapFaultException(sfe);
    } catch (Exception e) {
      e.printStackTrace();
    }
    return retVal;
  }
 public void powerOnSuspendedGuestVMs(ManagedObjectReference attachHostMoref)
     throws InvalidPropertyFaultMsg, RuntimeFaultFaultMsg {
   for (ManagedObjectReference vmMor : suspendedVMList) {
     System.out.println("\nPowering ON virtual machine : " + "[" + vmMor.getValue() + "]");
     try {
       ManagedObjectReference taskmor = vimPort.powerOnVMTask(vmMor, null);
       if (getTaskResultAfterDone(taskmor)) {
         System.out.println("[" + vmMor.getValue() + "] powered on successfully");
       }
     } catch (Exception e) {
       System.out.println("Unable to power on vm : " + "[" + vmMor.getValue() + "]");
       System.err.println("Reason :" + e.getLocalizedMessage());
     }
   }
 }
  /**
   * Demonstrate how to use the PropertyCollector to retrieve properties of a managed object when
   * the managed object reference is known.
   *
   * <p>Retrieves the Virtual machine property.
   *
   * @return String property of the VirtualMachine.
   */
  public static Object getVMProperty(ManagedObjectReference mor, String prop) {
    Object retVal = null;
    try {
      // Create Property Spec
      PropertySpec propertySpec = new PropertySpec();
      propertySpec.setAll(Boolean.FALSE);
      // propertySpec.setPathSet(new String[]{"name"});
      propertySpec.setPathSet(new String[] {prop});
      propertySpec.setType("VirtualMachine");
      PropertySpec[] propertySpecs = new PropertySpec[] {propertySpec};

      // Now create Object Spec
      ObjectSpec objectSpec = new ObjectSpec();
      objectSpec.setObj(mor);
      ObjectSpec[] objectSpecs = new ObjectSpec[] {objectSpec};

      // Create PropertyFilterSpec using the PropertySpec and ObjectPec
      // created above.
      PropertyFilterSpec propertyFilterSpec = new PropertyFilterSpec();
      propertyFilterSpec.setPropSet(propertySpecs);
      propertyFilterSpec.setObjectSet(objectSpecs);

      PropertyFilterSpec[] propertyFilterSpecs = new PropertyFilterSpec[] {propertyFilterSpec};

      ObjectContent[] oCont = VIM_PORT.retrieveProperties(PROP_COLLECTOR, propertyFilterSpecs);
      if (oCont != null) {
        // System.out.println("ObjectContent Length : " + oCont.length);
        for (ObjectContent oc : oCont) {
          // DynamicProperty[] dps = oc.getPropSet();
          DynamicProperty[] dps = oc.getPropSet();
          if (dps != null) {
            for (DynamicProperty dp : dps) {
              // System.out.println(dp.getName() + " : " +
              // dp.getVal());
              retVal = dp.getVal();
            }
          }
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }

    return retVal;
  }
 public Connection disconnect() {
   if (this.isConnected()) {
     try {
       vimPort.logout(serviceContent.getSessionManager());
     } catch (Exception e) {
       Throwable cause = e.getCause();
       throw new BasicConnectionException(
           "failed to disconnect properly: " + e.getMessage() + " : " + cause.getMessage(), cause);
     } finally {
       // A connection is very memory intensive, I'm helping the garbage collector here
       userSession = null;
       serviceContent = null;
       vimPort = null;
       vimService = null;
     }
   }
   return this;
 }
Exemple #21
0
  /** Prints the Host names. */
  private static void printHostProductDetails() {
    try {
      setHostSystemAttributesList();
      TraversalSpec tSpec = getHostSystemTraversalSpec();
      // Create Property Spec
      PropertySpec propertySpec = new PropertySpec();
      propertySpec.setAll(Boolean.FALSE);
      propertySpec.getPathSet().addAll(hostSystemAttributesArr);
      propertySpec.setType("HostSystem");

      // Now create Object Spec
      ObjectSpec objectSpec = new ObjectSpec();
      objectSpec.setObj(rootRef);
      objectSpec.setSkip(Boolean.TRUE);
      objectSpec.getSelectSet().add(tSpec);

      // Create PropertyFilterSpec using the PropertySpec and ObjectPec
      // created above.
      PropertyFilterSpec propertyFilterSpec = new PropertyFilterSpec();
      propertyFilterSpec.getPropSet().add(propertySpec);
      propertyFilterSpec.getObjectSet().add(objectSpec);
      List<PropertyFilterSpec> pfSpecList = new ArrayList<PropertyFilterSpec>(1);
      pfSpecList.add(propertyFilterSpec);

      List<ObjectContent> listobjcont = retrievePropertiesAllObjects(pfSpecList);

      if (listobjcont != null) {
        for (ObjectContent oc : listobjcont) {
          List<DynamicProperty> dpList = oc.getPropSet();
          if (dpList != null) {
            for (DynamicProperty dp : dpList) {
              System.out.println(dp.getName() + " : " + dp.getVal());
            }
          }
          System.out.println("\n\n***************************************************************");
        }
      }
    } catch (SOAPFaultException sfe) {
      printSoapFaultException(sfe);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
 public static void main(String[] args) {
   try {
     getConnectionParameters(args);
     if (help) {
       printUsage();
       return;
     }
     connect();
     initEventManagerRef();
     createEventHistoryCollector();
     PropertyFilterSpec eventFilterSpec = createEventFilterSpec();
     monitorEvents(eventFilterSpec);
   } catch (IllegalArgumentException iae) {
     printUsage();
   } catch (SOAPFaultException sfe) {
     printSoapFaultException(sfe);
   } catch (Exception e) {
     System.out.println("Failed to Monitor Event History - " + e.getMessage());
     e.printStackTrace();
   } finally {
     try {
       disconnect();
     } catch (SOAPFaultException sfe) {
       printSoapFaultException(sfe);
     } catch (Exception e) {
       System.out.println("Failed to disconnect - " + e.getMessage());
       e.printStackTrace();
     }
   }
 }
 @Override
 public void run() {
   try {
     System.out.println(
         "---------------------- Thread for "
             + "Checking the HTTP NFCLEASE vmdkFlag: "
             + vmdkFlag
             + "----------------------");
     while (!vmdkFlag) {
       System.out.println("#### TOTAL_BYTES_WRITTEN " + TOTAL_BYTES_WRITTEN);
       System.out.println("#### TOTAL_BYTES " + TOTAL_BYTES);
       try {
         vimPort.httpNfcLeaseProgress(httpNfcLease, 0);
         Thread.sleep(290000000);
       } catch (InterruptedException e) {
         System.out.println(
             "---------------------- Thread interrupted " + "----------------------");
       }
     }
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
  /**
   * Demonstrate how to use the PropertyCollector to retrieve managed object reference.
   *
   * <p>Initializes the VM_MOR_LIST with the MOREFs to all the VMs.
   */
  public static void initVMMorList() {
    try {
      TraversalSpec tSpec = getVMTraversalSpec();
      // Create Property Spec
      PropertySpec propertySpec = new PropertySpec();
      propertySpec.setAll(Boolean.FALSE);
      propertySpec.setType("VirtualMachine");
      PropertySpec[] propertySpecs = new PropertySpec[] {propertySpec};

      // Now create Object Spec
      ObjectSpec objectSpec = new ObjectSpec();
      objectSpec.setObj(ROOT_FOLDER);
      objectSpec.setSkip(Boolean.TRUE);
      objectSpec.setSelectSet(new SelectionSpec[] {tSpec});
      ObjectSpec[] objectSpecs = new ObjectSpec[] {objectSpec};

      // Create PropertyFilterSpec using the PropertySpec and ObjectPec
      // created above.
      PropertyFilterSpec propertyFilterSpec = new PropertyFilterSpec();
      propertyFilterSpec.setPropSet(propertySpecs);
      propertyFilterSpec.setObjectSet(objectSpecs);

      PropertyFilterSpec[] propertyFilterSpecs = new PropertyFilterSpec[] {propertyFilterSpec};

      ObjectContent[] oCont = VIM_PORT.retrieveProperties(PROP_COLLECTOR, propertyFilterSpecs);
      if (oCont != null) {
        // System.out.println("ObjectContent Length : " + oCont.length);
        for (ObjectContent oc : oCont) {
          ManagedObjectReference mr = oc.getObj();
          // System.out.println("MOR Type : " + mr.getType());
          VM_MOR_LIST.add(mr);
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Exemple #25
0
  /**
   * Uses the new RetrievePropertiesEx method to emulate the now deprecated RetrieveProperties
   * method.
   *
   * @param listpfs
   * @return list of object content
   * @throws Exception
   */
  private static List<ObjectContent> retrievePropertiesAllObjects(List<PropertyFilterSpec> listpfs)
      throws Exception {

    RetrieveOptions propObjectRetrieveOpts = new RetrieveOptions();

    List<ObjectContent> listobjcontent = new ArrayList<ObjectContent>();

    try {
      RetrieveResult rslts =
          vimPort.retrievePropertiesEx(propCollectorRef, listpfs, propObjectRetrieveOpts);
      if (rslts != null && rslts.getObjects() != null && !rslts.getObjects().isEmpty()) {
        listobjcontent.addAll(rslts.getObjects());
      }
      String token = null;
      if (rslts != null && rslts.getToken() != null) {
        token = rslts.getToken();
      }
      while (token != null && !token.isEmpty()) {
        rslts = vimPort.continueRetrievePropertiesEx(propCollectorRef, token);
        token = null;
        if (rslts != null) {
          token = rslts.getToken();
          if (rslts.getObjects() != null && !rslts.getObjects().isEmpty()) {
            listobjcontent.addAll(rslts.getObjects());
          }
        }
      }
    } catch (SOAPFaultException sfe) {
      printSoapFaultException(sfe);
    } catch (Exception e) {
      System.out.println(" : Failed Getting Contents");
      e.printStackTrace();
    }

    return listobjcontent;
  }
Exemple #26
0
  /**
   * Wait for values.
   *
   * @param objmor the object mor
   * @param filterProps the filter props
   * @param endWaitProps the end wait props
   * @param expectedVals the expected vals
   * @return the object[]
   * @throws RemoteException the remote exception
   * @throws Exception the exception
   */
  private static Object[] waitForValues(
      ManagedObjectReference objmor,
      String[] filterProps,
      String[] endWaitProps,
      Object[][] expectedVals)
      throws RemoteException, Exception {
    // version string is initially null
    String version = "";
    Object[] endVals = new Object[endWaitProps.length];
    Object[] filterVals = new Object[filterProps.length];

    PropertyFilterSpec spec = new PropertyFilterSpec();

    spec.getObjectSet().add(new ObjectSpec());

    spec.getObjectSet().get(0).setObj(objmor);

    spec.getPropSet().addAll(Arrays.asList(new PropertySpec[] {new PropertySpec()}));

    spec.getPropSet().get(0).getPathSet().addAll(Arrays.asList(filterProps));

    spec.getPropSet().get(0).setType(objmor.getType());

    spec.getObjectSet().get(0).setSkip(Boolean.FALSE);

    ManagedObjectReference filterSpecRef = vimPort.createFilter(propCollectorRef, spec, true);

    boolean reached = false;

    UpdateSet updateset = null;
    PropertyFilterUpdate[] filtupary = null;
    PropertyFilterUpdate filtup = null;
    ObjectUpdate[] objupary = null;
    ObjectUpdate objup = null;
    PropertyChange[] propchgary = null;
    PropertyChange propchg = null;
    while (!reached) {
      boolean retry = true;
      while (retry) {
        try {
          updateset = vimPort.waitForUpdates(propCollectorRef, version);
          retry = false;
        } catch (SOAPFaultException sfe) {
          printSoapFaultException(sfe);
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
      if (updateset != null) {
        version = updateset.getVersion();
      }
      if (updateset == null || updateset.getFilterSet() == null) {
        continue;
      }
      List<PropertyFilterUpdate> listprfup = updateset.getFilterSet();
      filtupary = listprfup.toArray(new PropertyFilterUpdate[listprfup.size()]);
      filtup = null;
      for (int fi = 0; fi < filtupary.length; fi++) {
        filtup = filtupary[fi];
        List<ObjectUpdate> listobjup = filtup.getObjectSet();
        objupary = listobjup.toArray(new ObjectUpdate[listobjup.size()]);
        objup = null;
        propchgary = null;
        for (int oi = 0; oi < objupary.length; oi++) {
          objup = objupary[oi];
          if (objup.getKind() == ObjectUpdateKind.MODIFY
              || objup.getKind() == ObjectUpdateKind.ENTER
              || objup.getKind() == ObjectUpdateKind.LEAVE) {
            List<PropertyChange> listchset = objup.getChangeSet();
            propchgary = listchset.toArray(new PropertyChange[listchset.size()]);
            for (int ci = 0; ci < propchgary.length; ci++) {
              propchg = propchgary[ci];
              updateValues(endWaitProps, endVals, propchg);
              updateValues(filterProps, filterVals, propchg);
            }
          }
        }
      }
      Object expctdval = null;
      // Check if the expected values have been reached and exit the loop if done.
      // Also exit the WaitForUpdates loop if this is the case.
      for (int chgi = 0; chgi < endVals.length && !reached; chgi++) {
        for (int vali = 0; vali < expectedVals[chgi].length && !reached; vali++) {
          expctdval = expectedVals[chgi][vali];
          reached = expctdval.equals(endVals[chgi]) || reached;
        }
      }
    }

    // Destroy the filter when we are done.
    vimPort.destroyPropertyFilter(filterSpecRef);
    return filterVals;
  }
  void exportVM() throws RuntimeFaultFaultMsg, InvalidPropertyFaultMsg {
    File file = new File(localPath);
    if (!file.exists()) {
      System.out.println("Wrong or invalid path " + localPath);
      return;
    }
    ManagedObjectReference srcMOR =
        getMOREFs.inFolderByType(serviceContent.getRootFolder(), "HostSystem").get(host);
    if (srcMOR == null) {
      throw new RuntimeException(" Source Host " + host + " Not Found.");
    }
    ManagedObjectReference vmMoRef = getMOREFs.inFolderByType(srcMOR, "VirtualMachine").get(vmname);

    if (vmMoRef == null) {
      throw new RuntimeException("Virtual Machine " + vmname + " Not Found.");
    }
    System.out.println("Getting the HTTP NFCLEASE for the VM: " + vmname);
    try {
      ManagedObjectReference httpNfcLease = vimPort.exportVm(vmMoRef);

      Object[] result =
          waitForValues.wait(
              httpNfcLease,
              new String[] {"state"},
              new String[] {"state"},
              new Object[][] {new Object[] {HttpNfcLeaseState.READY, HttpNfcLeaseState.ERROR}});
      if (result[0].equals(HttpNfcLeaseState.READY)) {
        System.out.println("HttpNfcLeaseState: " + result[0]);
        HttpNfcLeaseInfo httpNfcLeaseInfo =
            (HttpNfcLeaseInfo)
                getMOREFs.entityProps(httpNfcLease, new String[] {"info"}).get("info");
        httpNfcLeaseInfo.setLeaseTimeout(300000000);
        printHttpNfcLeaseInfo(httpNfcLeaseInfo, host);
        long diskCapacity = (httpNfcLeaseInfo.getTotalDiskCapacityInKB()) * 1024;
        TOTAL_BYTES = diskCapacity;
        leaseExtender = new OVFManagerExportVMDK().new HttpNfcLeaseExtender(httpNfcLease, vimPort);
        Thread t = new Thread(leaseExtender);
        t.start();
        List<HttpNfcLeaseDeviceUrl> deviceUrlArr = httpNfcLeaseInfo.getDeviceUrl();
        for (HttpNfcLeaseDeviceUrl deviceUrl : deviceUrlArr) {
          System.out.println("Downloading Files:");
          String deviceUrlStr = deviceUrl.getUrl();
          String absoluteFile = deviceUrlStr.substring(deviceUrlStr.lastIndexOf("/") + 1);
          System.out.println("Absolute File Name: " + absoluteFile);
          System.out.println("VMDK URL: " + deviceUrlStr.replace("*", host));
          writeVMDKFile(absoluteFile, deviceUrlStr.replace("*", host), diskCapacity, vmname);
        }
        System.out.println("Completed Downloading the files");
        vmdkFlag = true;
        t.interrupt();
        vimPort.httpNfcLeaseProgress(httpNfcLease, 100);
        vimPort.httpNfcLeaseComplete(httpNfcLease);
      } else {
        System.out.println("HttpNfcLeaseState not ready");
        for (Object o : result) {
          System.out.println("HttpNfcLeaseState: " + o);
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }