pax_global_header00006660000000000000000000000064121274342220014511gustar00rootroot0000000000000052 comment=bb72e53de43e9fac79547ecaf91292edb7614db0 psphere-0.5.2/000077500000000000000000000000001212743422200131635ustar00rootroot00000000000000psphere-0.5.2/.gitignore000066400000000000000000000001451212743422200151530ustar00rootroot00000000000000*.pyc *.egg *.so build/ dist/ psphere.egg-info/ doc/_build/ .project .pydevproject *.sw* project.vim psphere-0.5.2/.hgignore000066400000000000000000000001601212743422200147630ustar00rootroot00000000000000.*\.pyc .*\.egg .*\.so ^build/ ^dist/ ^psphere.egg-info/ ^doc/_build/ .project .pydevproject .*.swp project.vim psphere-0.5.2/.hgtags000066400000000000000000000004321212743422200144400ustar00rootroot00000000000000a81cc8d74e300463918cdc1d2fafed1f2cc3e355 0.1.1 c66ae77f58d18b25037e76e3005ec0682adacf59 0.1.2 ccb327d9aa6717c2b7880c1264d9c0ab99207454 0.1.3 334103c89097d776d585118a8bbeca4a22b49c25 0.1.4 18873b761cc562900c0eb40522c6aea6067c0ab8 0.5.0 7e7de3a7f030351e241a3d1a3724a39df5df6ea5 0.5.1 psphere-0.5.2/.settings/000077500000000000000000000000001212743422200151015ustar00rootroot00000000000000psphere-0.5.2/.settings/org.eclipse.core.resources.prefs000066400000000000000000000001301212743422200233060ustar00rootroot00000000000000#Wed May 11 00:48:51 EST 2011 eclipse.preferences.version=1 encoding//doc/conf.py=utf-8 psphere-0.5.2/CHANGES000066400000000000000000000031361212743422200141610ustar00rootroot00000000000000Version 0.5.2 ------------- (bugfix release, released on April 5th 2013) - Add an example showing how to list VMs on a host - Add a new example of powering on many VMs at once - Fix regression that calls _init_logging() and remove the function for good. - Update references from bitbucket to github - Merge bitbucket pull request: Pierre-Yves D Fixed error when setting extraOptions on VM creation - Merge bitbucket pull request: Saju M 3cbdf636d068 Adding example get_filesize_by_path - MANIFEST.in: s/README/README.rst - Updated managed objects to include new objects in sphere 5.0 - When pre-loading objects, don't try and pre-load them when the requested attributed contains an empty list. fixes #7 - Replace print calls with logging calls. fixes issue 8 - Remove use of sys.exit and raise exceptions instead. fixes issue 8 - Use *args to pass log strings (efficiency, as log mesages won't be string formatted unless they're actually logged). Remove _init_logging to mak - Convert Windows path to WSDL file to URI format - Documentation updates Version 0.5.1 ------------- (bugfix release, released on August 19th 2011) Version 0.5.0 ------------- (major release, released on August 11th 2011) - The API has completely changed, programs written for 0.1.4 will not work in 0.5.0 or later versions. - Implements vSphere SDK 4.1 - All vSphere Managed Object's are implemented including all properties. - Object properties are now lazily loaded on first access and cached for 5 minutes. Version 0.1.4 ------------- Released on July 15th 2011 - Primitive release of psphere for Aeolus Project to package into Fedora. psphere-0.5.2/LICENSE000066400000000000000000000261341212743422200141760ustar00rootroot00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.psphere-0.5.2/MANIFEST.in000066400000000000000000000002711212743422200147210ustar00rootroot00000000000000include CHANGES include LICENSE include README.rst include psphere/wsdl/* include examples/*.py include examples/sample_config.yaml include examples/templates/* recursive-include doc * psphere-0.5.2/Makefile000066400000000000000000000010561212743422200146250ustar00rootroot00000000000000version: git describe --tags > version.txt perl -p -i -e 's/-/_/g' version.txt sdist: python setup.py sdist signed-rpm: sdist version rpmbuild -ba python-psphere.spec --sign --define "_sourcedir `pwd`/dist" rpm: sdist version rpmbuild -ba python-psphere.spec --define "_sourcedir `pwd`/dist" srpm: sdist version rpmbuild -bs python-psphere.spec --define "_sourcedir `pwd`/dist" pylint: pylint --rcfile=pylint.conf imagefactory imgfac unittests: python -m unittest discover -v clean: rm -rf MANIFEST build dist python-psphere.spec version.txt psphere-0.5.2/README.rst000066400000000000000000000021641212743422200146550ustar00rootroot00000000000000Introduction ============ psphere is a Python interface for the `VMware vSphere Web Services SDK`_, a powerful API for programatically managing your VMware infrastructure: * Provision, clone and snapshot virtual machines * Query and configure clusters, host systems and datastores * Programatically configure ESXi hosts (i.e. for automation) psphere can be used to create standalone Python scripts or used as a library in larger Python applications (e.g. Django). Usage ===== >>> from psphere.client import Client >>> client = Client("your.esxserver.com", "Administrator", "strongpass") >>> servertime = client.si.CurrentTime() >>> print(servertime) 2010-09-04 18:35:12.062575 >>> client.logout() Installation ============ The latest stable version of psphere can be installed from PyPi: # pip install -U psphere Community ========= Discussion and support can be found on the `psphere Google Group`_. .. _psphere Google Group: https://groups.google.com/group/psphere .. _VMware vSphere Web Services SDK: http://pubs.vmware.com/vsphere-50/index.jsp?topic=/com.vmware.wssdk.apiref.doc_50/right-pane.html psphere-0.5.2/doc/000077500000000000000000000000001212743422200137305ustar00rootroot00000000000000psphere-0.5.2/doc/Makefile000066400000000000000000000060701212743422200153730ustar00rootroot00000000000000# Makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = sphinx-build PAPER = BUILDDIR = _build # Internal variables. PAPEROPT_a4 = -D latex_paper_size=a4 PAPEROPT_letter = -D latex_paper_size=letter ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . .PHONY: help clean html dirhtml pickle json htmlhelp qthelp latex changes linkcheck doctest help: @echo "Please use \`make ' where is one of" @echo " html to make standalone HTML files" @echo " dirhtml to make HTML files named index.html in directories" @echo " pickle to make pickle files" @echo " json to make JSON files" @echo " htmlhelp to make HTML files and a HTML help project" @echo " qthelp to make HTML files and a qthelp project" @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" @echo " changes to make an overview of all changed/added/deprecated items" @echo " linkcheck to check all external links for integrity" @echo " doctest to run all doctests embedded in the documentation (if enabled)" clean: -rm -rf $(BUILDDIR)/* html: $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." dirhtml: $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." pickle: $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle @echo @echo "Build finished; now you can process the pickle files." json: $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json @echo @echo "Build finished; now you can process the JSON files." htmlhelp: $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp @echo @echo "Build finished; now you can run HTML Help Workshop with the" \ ".hhp project file in $(BUILDDIR)/htmlhelp." qthelp: $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp @echo @echo "Build finished; now you can run "qcollectiongenerator" with the" \ ".qhcp project file in $(BUILDDIR)/qthelp, like this:" @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/psphere.qhcp" @echo "To view the help file:" @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/psphere.qhc" latex: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." @echo "Run \`make all-pdf' or \`make all-ps' in that directory to" \ "run these through (pdf)latex." changes: $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes @echo @echo "The overview file is in $(BUILDDIR)/changes." linkcheck: $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck @echo @echo "Link check complete; look for any errors in the above output " \ "or in $(BUILDDIR)/linkcheck/output.txt." doctest: $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest @echo "Testing of doctests in the sources finished, look at the " \ "results in $(BUILDDIR)/doctest/output.txt." psphere-0.5.2/doc/_templates/000077500000000000000000000000001212743422200160655ustar00rootroot00000000000000psphere-0.5.2/doc/_templates/index.html000066400000000000000000000040461212743422200200660ustar00rootroot00000000000000{% extends "layout.html" %} {% set title = 'Overview' %} {% block body %}

Welcome

psphere provides native Python bindings for the vSphere Web Services SDK (formerly known as VMware Infrastructure SDK). The project is in its early phases but can already perform most query operations and virtual machine creation.

psphere is in no way affiliated with VMware Inc.

Documentation

Get psphere

psphere is available as an easy-installable package on the Python Package Index.

Contribute

The code can be found on GitHub

Get in touch via GitHub if you would like to contribute to psphere. This is my first Python and open-source project so I would appreciate any feedback or advice!

{% endblock %} psphere-0.5.2/doc/_templates/indexsidebar.html000066400000000000000000000016461212743422200214230ustar00rootroot00000000000000

Download

{% if version.endswith('(hg)') %}

This documentation is for version {{ version }}, which is not released yet.

You can use it from the Git repo or look for released versions in the Python Package Index.

{% else %}

Current version: {{ version }}

Get psphere from the Python Package Index, or install it with:

pip install -U psphere

Latest development version docs are also available.

{% endif %}

Questions? Suggestions? Issues?

Open an issue in the tracker.

Join the discussion on the Google group:

psphere-0.5.2/doc/_templates/layout.html000066400000000000000000000012141212743422200202660ustar00rootroot00000000000000{% extends "!layout.html" %} {% block extrahead %} {{ super() }} {%- if not embedded %} {%- endif %} {% endblock %} {% block rootrellink %}
  • psphere home | 
  • Documentation »
  • {% endblock %} {% block header %}
    psphere logo
    {% endblock %} psphere-0.5.2/doc/api.rst000066400000000000000000000001671212743422200152370ustar00rootroot00000000000000API Documentation ================= This page documents the psphere API. .. automodule:: psphere.client :members: psphere-0.5.2/doc/conf.py000066400000000000000000000150671212743422200152400ustar00rootroot00000000000000# -*- coding: utf-8 -*- # # psphere documentation build configuration file, created by # sphinx-quickstart on Sat Jul 31 16:51:35 2010. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. #sys.path.append(os.path.abspath('.')) # -- General configuration ----------------------------------------------------- # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. import psphere extensions = ['sphinx.ext.autodoc', 'sphinx.ext.doctest', 'sphinx.ext.todo', 'sphinx.ext.coverage', 'sphinx.ext.autosummary'] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8' # The master toctree document. master_doc = 'contents' # General information about the project. project = u'psphere' copyright = u'2010, Jonathan Kinred' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = psphere.__released__ # The full version, including alpha/beta/rc tags. release = version # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of documents that shouldn't be included in the build. #unused_docs = [] # List of directories, relative to source directory, that shouldn't be searched # for source files. exclude_trees = ['_build'] # The reST default role (used for this markup: `text`) to use for all documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. show_authors = True # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. modindex_common_prefix = ['psphere.'] # -- Options for HTML output --------------------------------------------------- # The theme to use for HTML and HTML Help pages. Major themes that come with # Sphinx are currently 'default' and 'sphinxdoc'. html_theme = 'sphinxdoc' html_index = 'index.html' html_sidebars = {'index': ['indexsidebar.html']} html_additional_pages = {'index': 'index.html'} #extlinks = {'vsphere': ('http://www.vmware.com/support/developer/vc-sdk/' # 'visdk41pubs/ApiReference/%s', '')} # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # " v documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_use_modindex = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, an OpenSearch description file will be output, and all pages will # contain a tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # If nonempty, this is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = '' # Output file base name for HTML help builder. htmlhelp_basename = 'pspheredoc' # -- Options for LaTeX output -------------------------------------------------- # The paper size ('letter' or 'a4'). #latex_paper_size = 'letter' # The font size ('10pt', '11pt' or '12pt'). #latex_font_size = '10pt' # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ ('index', 'psphere.tex', u'psphere Documentation', u'Jonathan Kinred', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # Additional stuff for the LaTeX preamble. #latex_preamble = '' # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_use_modindex = True psphere-0.5.2/doc/contents.rst000066400000000000000000000004261212743422200163210ustar00rootroot00000000000000.. _contents: psphere documentation contents ============================== .. toctree:: :maxdepth: 2 intro tutorial errors datastore hostsystem api Indices and tables ================== * :ref:`genindex` * :ref:`modindex` * :ref:`search` psphere-0.5.2/doc/datastore.rst000066400000000000000000000023161212743422200164520ustar00rootroot00000000000000Datastore examples ================== WARNING!!!! Not updated for new API! This page provides examples for working with datastores. Finding a datastore ------------------- You can find a datastore in a ComputeResource using the **find_datastore** convenience method:: >>> from psphere.client import Client >>> from psphere.managedobjects import Datastore >>> client = Client("server.esx.com", "Administrator", "strongpass") >>> datastore = Datastore.get(name="nas03") >>> print(datastore.summary.name) nas03 >>> print("%iGB" % (datastore.summary.freeSpace/1073741824)) 13203GB Finding all VMs attached to a datastore --------------------------------------- Just look at the vm property of the Datastore managed object:: >>> for vm in datastore.vm: >>> try: >>> print(vm.name) >>> print(vm.summary.config.guestId) >>> except AttributeError: >>> print("Unknown") >>> print("----------") sdi3extapp01 sles10_64Guest ---------- sdi3ppcapp01 sles10_64Guest ---------- sdi3oamapp01 sles10_64Guest ---------- hudmas01 rhel5Guest ---------- sandbox5 rhel5Guest ---------- psphere-0.5.2/doc/errors.rst000066400000000000000000000013261212743422200160000ustar00rootroot00000000000000Error handling ============== At time of writing, the vSphere SDK raises 435 types of exception. Rather than duplicate these in psphere, the API instead raises a single fault called `VimFault` when any vSphere related fault is detected. The `VimFault` exception contains the following attributes: * fault: The fault object * fault_type: The class name of the fault (the name you will find in the vSphere documentation) All other properties which are listed in the API reference will be available as attributes of the fault object. Handling exceptions ------------------- :: >>> try: >>> operation() >>> except VimFault, e: >>> e.fault_code InvalidProperty >>> e.fault.name name psphere-0.5.2/doc/hostsystem.rst000066400000000000000000000033311212743422200167040ustar00rootroot00000000000000HostSystem examples =================== This page provides examples for working with **HostSystem** views. The examples accumulate as they go so make sure you reference the previous examples. Finding a single HostSystem by name ----------------------------------- Connect to the server and find the **HostSystem** view:: >>> from psphere.client import Client >>> from psphere.managedobjects import HostSystem >>> client = Client("server.esx.com", "Administrator", "strongpass") >>> hs = HostSystem.get(client, name="k2") >>> print(hs.name) k2 >>> print(hs.summary.hardware.model) Sun Fire X4440 Finding all HostSystem's ------------------------ Use the .all() method which can be found on all objects extending ManagedEntity:: >>> hs_list = HostSystem.all(client) >>> len(hs_list) 3 >>> for hs in hs_list: >>> print(hs.name) host1 host2 host3 How many VirtualMachine's on a HostSystem? ---------------------------------------------- Just count the number of **VirtualMachine**'s objects in the vm property:: >>> len(host_system.vm) 40 Listing VirtualMachine's on a HostSystem ---------------------------------------- The **HostSystem.vm** attribute contains a list of **VirtualMachine** objects. >>> for vm in host_system.vm: >>> try: >>> print(vm.name) >>> print(vm.summary.config.memorySizeMB) >>> except AttributeError: >>> print('No value') >>> print('---------') genesis 2048 --------- sdv1sdfsas04 'No value' --------- pelmo 4096 --------- sdi2brmapp01 4096 --------- ssi5oamapp01 4096 --------- twynam 1024 --------- psphere-0.5.2/doc/intro.rst000066400000000000000000000032261212743422200156200ustar00rootroot00000000000000Introduction ============ This is the documentation for psphere, native Python bindings for the vSphere Web Services SDK/VMware Infrastructure SDK. Notes ----- psphere implements the following VMware SDKs: * VMware Infrastructure SDK 2.5 * VMware vSphere Web Services SDK 4.0 and later I'm currently developing against vCenter 4.1 so please raise any bugs for other versions. See the vSphere Web Services SDK Documentation for further information on VMware SDKs at http://www.vmware.com/support/developer/vc-sdk/. Installing psphere ------------------ # pip install -U psphere Developing psphere ------------------ If you want to use the latest development branch:: $ git clone https://github.com/jkinred/psphere $ cd psphere $ sudo python setup.py install $ ./examples/connect.py --server yourserver.esx.com --username youruser --password yourpass Successfully connected to https://yourserver.esx.com/sdk Server time is 2010-09-05 00:14:06.037575 Usage ----- See :doc:`tutorial` for an introductory tutorial. It also contains links to more advanced sections in this manual. Examples -------- * :doc:`hostsystem` * :doc:`datastore` Alternatives ------------ - `VMware VI Java API`_ - `VMware VI Java API with Jython`_ - `VMware vSphere SDK for Perl`_ - `VMware vSphere PowerCLI`_ .. _VMware VI Java API: http://vijava.sourceforge.net/ .. _VMware VI Java API with Jython: http://www.doublecloud.org/2010/03/using-vsphere-java-api-in-jython-and-other-jvm-languages/ .. _VMware vSphere SDK for Perl: http://www.vmware.com/support/developer/viperltoolkit/ .. _VMware vSphere PowerCLI: http://www.vmware.com/support/pubs/ps_pubs.html psphere-0.5.2/doc/more.png000066400000000000000000000027361212743422200154100ustar00rootroot00000000000000PNG  IHDR szzsBIT|dtEXtSoftwarewww.inkscape.org<pIDATXŖ[lUߙٝݶR)޸GBT MVcFYD|GQLLKb$5ATB@*ZJwv/s;nn|9̜93Aqx|ڗvܳB~PpUB)O+yX<sY:h9]@ڪze/ *Fn,Rǧ5" <_Ϫ7r5.mmǧh WYf. لrbgO[MfWkO(<9|RMH6a ȃ{f(p%69mOsg- _vW-D B0L)08 lf1;XTrYEoe^=tVN,{lC5:&$[H։'EMҵt\{WO0ԩV/|tGWkTB0nm6OԔr$d '4-X§Uŵݠ> ?${0w$(q@ qnoѿHd ۣX Rf@!Gy0dP98rJmglij@tHMZ|G;X99'@Dw s4ɍKSFPHiQl:ysKoOm:H)ʁƑΎ`aq(|Dpr&wN AMȤ>ND$aJ(i[XtlCN @id6aO$pj{EU_c΋MW0%3(4vz9s;7N tYf<ȔK63ۓ>H2܆D$3!QPuQ݊JW'Dҥ,f@e։U?V!R%lf'$ˤ eS|LI8gM`. The Client object ----------------- The Client object is the entry point into psphere. Through it you can login to a vSphere server and obtain Python objects representing managed objects. You can then access information about and execute methods on those objects. |more| Read more about the :ref:`Vim attributes and methods `. Hello World in psphere ---------------------- Not quite, but logging into the server and printing the current time is close:: >>> from psphere.client import Client >>> client = Client("your.esxserver.com", "Administrator", "strongpass") >>> servertime = client.si.CurrentTime() >>> print(servertime) 2010-09-04 18:35:12.062575 >>> client.logout() General programming pattern --------------------------- Create a new Client:: >>> from psphere.client import Client >>> client = Client("your.esxserver.com", "Administrator", "strongpass") ...check out the rootFolder of the content attribute, it's a Python object:: >>> client.si.content.rootFolder.__class__ ...access properties of it:: >>> print(client.si.content.rootFolder.name) Datacenters ...invoke a method:: >>> new_folder = client.si.content.rootFolder.CreateFolder(name="New") >>> print(new_folder.name) New >>> task = new_folder.Destroy_Task() >>> print(task.info.state) success ...log out of the server:: >>> client.logout() Finding a ManagedEntity ----------------------- Managed Object's which extend the **ManagedEntity** class are the most commonly used objects in the vSphere API. These include Managed Object's such as HostSystem's and VirtualMachine's. psphere makes it easy to find Managed Entity's by providing a get() classmethod to find them:: >>> from psphere.client import Client >>> from psphere.managedobjects import VirtualMachine >>> client = Client("your.esxserver.com", "Administrator", "strongpass") >>> vm = VirtualMachine.get(client, name="genesis") >>> vm.__class__ >>> vm.name bennevis >>> vm.summary.guest.ipAddress 10.183.11.85 >>> vm.config.hardware.memoryMB 4096 There is also the all() method to get all entities of that type:: >>> vms = VirtualMachine.all(client) Lazy loading of properties and pre-loading properties ----------------------------------------------------- At this point we have to delve into a more complicated aspect of vSphere and how psphere handles it. You do not need to worry about this, psphere will just work for you -- albeit inefficiently in some cases. The vSphere SDK architecture provides abstract "views" of server side objects, some of these objects can be quite substantial, both in size and server resources required to collect them. If you retrieve substantial objects then your scripts will be slow and you will generate load on your vSphere server. psphere deals with this by lazily loading objects on access. In most cases this is fine, but you can achieve substantial speed-ups -- especially for lists of managed objects -- by pre-loading objects you know that you are going to access. For example, a HostSystem has a "vm" property which is a list of VirtualMachine objects on that host. If you know you are going to loop over all those VM's and print their name, you can preload the name property using the preload method:: >>> hs = HostSystem.get(client, name="myhost") >>> hs.preload("vm", properties=["name"]) >>> for vm in hs.vm: >>> print(vm.name) >>> ... Caching ------- Once lazily loaded or pre-loaded, attributes will be cached for a pre-defined time (5 minutes, which is not configurable but will be in the next release). To update the cache for a specific property of an object, use the update() method with the properties parameter:: >>> hs.update(properties=["name"]) To update the cache for all cached properties of an object, use the update() method with no parameters:: >>> hs.update() To clear the property cache for an object, use the flush_cache() method:: >>> hs.flush_cache() .. |more| image:: more.png :align: middle :alt: more info psphere-0.5.2/examples/000077500000000000000000000000001212743422200150015ustar00rootroot00000000000000psphere-0.5.2/examples/connect.py000077500000000000000000000027611212743422200170150ustar00rootroot00000000000000#!/usr/bin/python # Copyright 2010 Jonathan Kinred # # Licensed under the Apache License, Version 2.0 (the "License"); you may not # use this file except in compliance with the License. You may obtain a copy # of the License at: # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from psphere.client import Client def main(options): """A simple connection test to login and print the server time.""" client = Client(server=options.server, username=options.username, password=options.password) print('Successfully connected to %s' % client.server) print(client.si.CurrentTime()) client.logout() if __name__ == "__main__": from optparse import OptionParser usage = "Usage: %prog [options]" parser = OptionParser(usage=usage) parser.add_option("--server", dest="server", help="The server to connect to for provisioning") parser.add_option("--username", dest="username", help="The username used to connect to the server") parser.add_option("--password", dest="password", help="The password used to connect to the server") (options, args) = parser.parse_args() main(options) psphere-0.5.2/examples/dsfiles.py000077500000000000000000000040151212743422200170070ustar00rootroot00000000000000#!/usr/bin/env python # Copyright 2010 Jonathan Kinred # # Licensed under the Apache License, Version 2.0 (the "License"); you may not # use this file except in compliance with the License. You may obtain a copy # of the License at: # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """Lists all files on all datastores attached to managed datacenters.""" import time from psphere.scripting import BaseScript from psphere.client import Client class DatastoreFiles(BaseScript): def list_files(self): for dc in self.client.find_entity_views("Datacenter"): print("Datacenter: %s" % dc.name) for ds in dc.datastore: print("Datastore: %s" % ds.info.name) for ds in dc.datastore: print("Datastore: %s" % ds.info.name) root_folder = "[%s] /" % ds.info.name task = ds.browser.SearchDatastoreSubFolders_Task(datastorePath=root_folder) while task.info.state == "running": time.sleep(3) task.update() for array_of_results in task.info.result: # The first entry in this array is a type descriptor # not a data object, so skip over it for result in array_of_results[1:]: for r in result: try: for f in r.file: print("%s%s" % (r.folderPath, f.path)) except AttributeError: pass def main(): client = Client() dsf = DatastoreFiles(client) dsf.list_files() client.logout() if __name__ == '__main__': main() psphere-0.5.2/examples/find_vms_by_regex.py000077500000000000000000000012171212743422200210500ustar00rootroot00000000000000#!/usr/bin/python """A script which generates DHCP configuration for hosts matching a regex. Usage: find_vms_by_regex.py e.g. find_vms_by_regex.py 'ssi2+' 'Online Engineering' """ import re import sys from psphere.client import Client from psphere.managedobjects import ComputeResource client = Client() vm_regex = sys.argv[1] p = re.compile(vm_regex) compute_resource = sys.argv[2] cr = ComputeResource.get(client, name=compute_resource) cr.resourcePool.preload("vm", properties=["name"]) for vm in sorted(cr.resourcePool.vm): if p.match(vm.name) is None: continue print(vm.name) client.logout() psphere-0.5.2/examples/gen_dhcpconf.py000077500000000000000000000022571212743422200200010ustar00rootroot00000000000000#!/usr/bin/python """A script which generates DHCP configuration for hosts matching a regex. Usage: gen_dhcpconf.py e.g. gen_dhcpconf.py 'ssi2+' 'Online Engineering' """ import re import sys from psphere.client import Client client = Client() host_regex = sys.argv[1] p = re.compile(host_regex) compute_resource = sys.argv[2] cr = client.find_entity_view("ComputeResource", filter={"name": compute_resource}) cr.resourcePool.preload("vm", properties=["name"]) for vm in sorted(cr.resourcePool.vm): if p.match(vm.name) is None: continue print("host %s {" % vm.name) print(" option host-name \"%s\";" % vm.name) nic_found = False for device in vm.config.hardware.device: if "macAddress" in device: print(" hardware ethernet %s;" % device["macAddress"]) nic_found = True if nic_found is False: print("ERROR: Did not find a NIC to get MAC address from.") sys.exit(1) try: print(" fixed-address %s;" % vm.guest.ipAddress) except AttributeError: print(" fixed-address ;") print("}") client.logout() psphere-0.5.2/examples/get_filesize_by_path.py000066400000000000000000000015721212743422200215370ustar00rootroot00000000000000import psphere from psphere.client import Client from psphere.managedobjects import HostSystem client = Client("192.168.0.116", "root", "xxxxx") hosts = HostSystem.all(client) host = hosts[0] db = host.datastoreBrowser mor = db.SearchDatastore_Task(datastorePath="[datastore1] vCenter/", searchSpec={"matchPattern":"vCenter.vmx", "details":{"fileType":True, "fileSize":True, "modification":True, "fileOwner":True}, "searchCaseInsensitive":False, "sortFoldersFirst":False, "query":None }) while True: info = mor.info if info.state in ["success"]: break mor.update(properties=["info"]) result = info.result files = result.file for file in files: print "FileName:%s, FileSize:%s" %(file.path, file.fileSize) psphere-0.5.2/examples/list_vms_on_host.py000077500000000000000000000052471212743422200207570ustar00rootroot00000000000000#!/usr/bin/python # Copyright 2010 Jonathan Kinred # # Licensed under the Apache License, Version 2.0 (the "License"); you may not # use this file except in compliance with the License. You may obtain a copy # of the License at: # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. # # A simple script to list the VMs on a host # # Example usage: # python ./examples/list_vms_on_host.py --server --username --password --hostsystem import sys from psphere.client import Client from psphere.managedobjects import HostSystem def main(options): client = Client(server=options.server, username=options.username, password=options.password) print('Successfully connected to %s' % client.server) # Get a HostSystem object representing the host host = HostSystem.get(client, name=options.hostsystem) # Preload the name attribute of all items in the vm attribute. Read the # manual as this significantly speeds up queries for ManagedObject's host.preload("vm", properties=["name"]) # Iterate over the items in host.vm and print their names for vm in sorted(host.vm): print(vm.name) # Close the connection client.logout() if __name__ == "__main__": from optparse import OptionParser usage = "Usage: %prog [options]" parser = OptionParser(usage=usage) parser.add_option("--server", dest="server", help="The server to connect to") parser.add_option("--username", dest="username", help="The username used to connect to the server") parser.add_option("--password", dest="password", help="The password used to connect to the server") parser.add_option("--hostsystem", dest="hostsystem", help="The host from which to list VMs") (options, args) = parser.parse_args() if options.server is None: print("You must specify a server") parser.print_help() sys.exit(1) if options.username is None: print("You must specify a username") parser.print_help() sys.exit(1) if options.password is None: print("You must specify a password") parser.print_help() sys.exit(1) if options.hostsystem is None: print("You must specify a host system") parser.print_help() sys.exit(1) main(options) psphere-0.5.2/examples/new_style.py000066400000000000000000000011131212743422200173600ustar00rootroot00000000000000#!/usr/bin/python import sys from psphere.client import Client from psphere.managedobjects import HostSystem, VirtualMachine client = Client(sys.argv[1], sys.argv[2], sys.argv[3]) host_systems = HostSystem.all(client) print("HostSystem.all(client) finds these hosts") for host_system in host_systems: print(host_system.name) vm = VirtualMachine.get(client, name="genesis", overallStatus="green") print('VirtualMachine.get(client, name="genesis", overallStatus="green")' ' got the following host:') print("Name: %s" % vm.name) print("overallStatus: %s" % vm.overallStatus) psphere-0.5.2/examples/power_on_swarm.py000077500000000000000000000014241212743422200204200ustar00rootroot00000000000000#!/usr/bin/python import time import sys from psphere.client import Client from psphere.managedobjects import VirtualMachine scatter_secs = 8 nodes = sys.argv[1:] client = Client() print("Powering on %s VMs" % len(nodes)) print("Estimated run time with %s seconds sleep between each power on: %s" % (scatter_secs, scatter_secs*len(nodes))) for node in nodes: try: vm = VirtualMachine.get(client, name=node, properties=["name", "runtime"]) except ObjectNotFoundError: print("WARNING: Could not find VM with name %s" % node) pass print("Powering on %s" % vm.name) if vm.runtime.powerState == "poweredOn": print("%s is already powered on." % vm.name) continue task = vm.PowerOnVM_Task() time.sleep(scatter_secs) psphere-0.5.2/examples/reconfig_vm.py000077500000000000000000000032141212743422200176540ustar00rootroot00000000000000#!/usr/bin/python """A script which demonstrates how to reconfigure a VM. Usage: reconfig_vm.py e.g. reconfig_vm test """ import sys import time from psphere.client import Client from psphere.soap import VimFault from psphere.managedobjects import VirtualMachine from psphere.errors import ObjectNotFoundError vm_name = sys.argv[1] client = Client() new_config = client.create("VirtualMachineConfigSpec") new_config.numCPUs = 2 try: vm = VirtualMachine.get(client, name=vm_name) except ObjectNotFoundError: print("ERROR: No VM found with name %s" % vm_name) print("Reconfiguring %s" % vm_name) if vm.config.hardware.numCPU == 2: print("Not reconfiguring %s as it already has 2 CPUs" % vm_name) sys.exit() try: task = vm.ReconfigVM_Task(spec=new_config) except VimFault, e: print("Failed to reconfigure %s: " % e) sys.exit() while task.info.state in ["queued", "running"]: print("Waiting 5 more seconds for VM creation") time.sleep(5) task.update() if task.info.state == "success": elapsed_time = task.info.completeTime - task.info.startTime print("Successfully reconfigured VM %s. Server took %s seconds." % (vm_name, elapsed_time.seconds)) elif task.info.state == "error": print("ERROR: The task for reconfiguring the VM has finished with" " an error. If an error was reported it will follow.") try: print("ERROR: %s" % task.info.error.localizedMessage) except AttributeError: print("ERROR: There is no error message available.") else: print("UNKNOWN: The task reports an unknown state %s" % task.info.state) # All done client.logout() psphere-0.5.2/examples/sample_config.yaml000066400000000000000000000004421212743422200204730ustar00rootroot00000000000000# Copy this file into ~/.psphree/config.yaml and edit to your liking general: server: your.esxserver.com username: Administrator password: strongpassword template_dir: ~/.psphere/templates/ logging: destination: ~/.psphere/psphere.log level: INFO # DEBUG, INFO, etc psphere-0.5.2/examples/templates/000077500000000000000000000000001212743422200167775ustar00rootroot00000000000000psphere-0.5.2/examples/templates/default.yaml000066400000000000000000000003061212743422200213060ustar00rootroot00000000000000# Place values in here which you want all templates to inherit description: The default template which all templates implicitly inherit from memory: 1024 compute_resource: :q :q host: null psphere-0.5.2/examples/templates/sdf.yaml000066400000000000000000000002761212743422200204440ustar00rootroot00000000000000description: General SDF SOE template extends: default nics: - {type: VirtualE1000, network_name: None} datastore: "nas03" disksize: 12GB memory: 4096MB num_cpus: 1 guest_id: sles10_64Guest psphere-0.5.2/examples/templates/sdf_bpm_sdi.yaml000066400000000000000000000001751212743422200221370ustar00rootroot00000000000000# BPM servers run greedy Oracle software description: SDF SOE template for BPM servers in SDI extends: sdf_sdi memory: 8096M psphere-0.5.2/examples/templates/sdf_sdi.yaml000066400000000000000000000002261212743422200212760ustar00rootroot00000000000000# Ensure these servers get the right VLAN description: SDF SOE VM in SDI VLAN extends: sdf nics: - {type: VirtualE1000, network_name: AE_SDFDIE VLAN} psphere-0.5.2/examples/templates/sdf_ssi.yaml000066400000000000000000000002261212743422200213150ustar00rootroot00000000000000# Ensure these servers get the right VLAN description: SDF SOE VM in SSI VLAN extends: sdf nics: - {type: VirtualE1000, network_name: AE_SDFSIE VLAN} psphere-0.5.2/examples/vidiscovery.py000077500000000000000000000040201212743422200177200ustar00rootroot00000000000000#!/usr/bin/env python # Copyright 2010 Jonathan Kinred # # Licensed under the Apache License, Version 2.0 (the "License"); you may not # use this file except in compliance with the License. You may obtain a copy # of the License at: # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import sys from psphere.scripting import BaseScript from psphere.client import Client from psphere.managedobjects import ComputeResource from psphere.errors import ObjectNotFoundError class Discovery(BaseScript): def discovery(self, compute_resource): """An example that discovers hosts and VMs in the inventory.""" # Find the first ClusterComputeResource if compute_resource is None: cr_list = ComputeResource.all(self.client) print("ERROR: You must specify a ComputeResource.") print("Available ComputeResource's:") for cr in cr_list: print(cr.name) sys.exit(1) try: ccr = ComputeResource.get(self.client, name=compute_resource) except ObjectNotFoundError: print("ERROR: Could not find ComputeResource with name %s" % compute_resource) sys.exit(1) print('Cluster: %s (%s hosts)' % (ccr.name, len(ccr.host))) ccr.preload("host", properties=["name", "vm"]) for host in ccr.host: print(' Host: %s (%s VMs)' % (host.name, len(host.vm))) # Get the vm views in one fell swoop host.preload("vm", properties=["name"]) for vm in host.vm: print(' VM: %s' % vm.name) def main(): client = Client() vd = Discovery(client) vd.discovery(sys.argv[1]) if __name__ == '__main__': main() psphere-0.5.2/examples/vm_info.yaml000066400000000000000000000002671212743422200173270ustar00rootroot00000000000000name: test compute_resource: Online Engineering datastore: nas03 disksize: 12 nics: - {network_name: AE_SDFDIE VLAN, type: VirtualE1000} memory: 1024 num_cpus: 1 guest_id: rhel5Guest psphere-0.5.2/examples/vmcreate.py000077500000000000000000000320031212743422200171620ustar00rootroot00000000000000#!/usr/bin/env python # Copyright 2011 Jonathan Kinred # # Licensed under the Apache License, Version 2.0 (the "License"); you may not # use this file except in compliance with the License. You may obtain a copy # of the License at: # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import re import sys import time from psphere import config, template from psphere.client import Client from psphere.errors import TemplateNotFoundError from psphere.soap import VimFault def create_vm(client, name, compute_resource, datastore, disksize, nics, memory, num_cpus, guest_id, host=None): """Create a virtual machine using the specified values. :param name: The name of the VM to create. :type name: str :param compute_resource: The name of a ComputeResource in which to \ create the VM. :type compute_resource: str :param datastore: The name of the datastore on which to create the VM. :type datastore: str :param disksize: The size of the disk, specified in KB, MB or GB. e.g. \ 20971520KB, 20480MB, 20GB. :type disksize: str :param nics: The NICs to create, specified in a list of dict's which \ contain a "network_name" and "type" key. e.g. \ {"network_name": "VM Network", "type": "VirtualE1000"} :type nics: list of dict's :param memory: The amount of memory for the VM. Specified in KB, MB or \ GB. e.g. 2097152KB, 2048MB, 2GB. :type memory: str :param num_cpus: The number of CPUs the VM will have. :type num_cpus: int :param guest_id: The vSphere string of the VM guest you are creating. \ The list of VMs can be found at \ http://pubs.vmware.com/vsphere-50/index.jsp?topic=/com.vmware.wssdk.apiref.doc_50/right-pane.html :type guest_id: str :param host: The name of the host (default: None), if you want to \ provision the VM on a \ specific host. :type host: str """ print("Creating VM %s" % name) # If the host is not set, use the ComputeResource as the target if host is None: target = client.find_entity_view("ComputeResource", filter={"name": compute_resource}) resource_pool = target.resourcePool else: target = client.find_entity_view("HostSystem", filter={"name": host}) resource_pool = target.parent.resourcePool disksize_pattern = re.compile("^\d+[KMG]B") if disksize_pattern.match(disksize) is None: print("Disk size %s is invalid. Try \"12G\" or similar" % disksize) sys.exit(1) if disksize.endswith("GB"): disksize_kb = int(disksize[:-2]) * 1024 * 1024 elif disksize.endswith("MB"): disksize_kb = int(disksize[:-2]) * 1024 elif disksize.endswith("KB"): disksize_kb = int(disksize[:-2]) else: print("Disk size %s is invalid. Try \"12G\" or similar" % disksize) memory_pattern = re.compile("^\d+[KMG]B") if memory_pattern.match(memory) is None: print("Memory size %s is invalid. Try \"12G\" or similar" % memory) sys.exit(1) if memory.endswith("GB"): memory_mb = int(memory[:-2]) * 1024 elif memory.endswith("MB"): memory_mb = int(memory[:-2]) elif memory.endswith("KB"): memory_mb = int(memory[:-2]) / 1024 else: print("Memory size %s is invalid. Try \"12G\" or similar" % memory) # A list of devices to be assigned to the VM vm_devices = [] # Create a disk controller controller = create_controller(client, "VirtualLsiLogicController") vm_devices.append(controller) ds_to_use = None for ds in target.datastore: if ds.name == datastore: ds_to_use = ds break if ds_to_use is None: print("Could not find datastore on %s with name %s" % (target.name, datastore)) sys.exit(1) # Ensure the datastore is accessible and has enough space if ds_to_use.summary.accessible is not True: print("Datastore (%s) exists, but is not accessible" % ds_to_use.summary.name) sys.exit(1) if ds_to_use.summary.freeSpace < disksize_kb * 1024: print("Datastore (%s) exists, but does not have sufficient" " free space." % ds_to_use.summary.name) sys.exit(1) disk = create_disk(client, datastore=ds_to_use, disksize_kb=disksize_kb) vm_devices.append(disk) for nic in nics: nic_spec = create_nic(client, target, nic) if nic_spec is None: print("Could not create spec for NIC") sys.exit(1) # Append the nic spec to the vm_devices list vm_devices.append(nic_spec) vmfi = client.create("VirtualMachineFileInfo") vmfi.vmPathName = "[%s]" % ds_to_use.summary.name vm_config_spec = client.create("VirtualMachineConfigSpec") vm_config_spec.name = name vm_config_spec.memoryMB = memory_mb vm_config_spec.files = vmfi vm_config_spec.annotation = "Auto-provisioned by psphere" vm_config_spec.numCPUs = num_cpus vm_config_spec.guestId = guest_id vm_config_spec.deviceChange = vm_devices # Find the datacenter of the target if target.__class__.__name__ == "HostSystem": datacenter = target.parent.parent.parent else: datacenter = target.parent.parent try: task = datacenter.vmFolder.CreateVM_Task(config=vm_config_spec, pool=resource_pool) except VimFault, e: print("Failed to create %s: " % e) sys.exit() while task.info.state in ["queued", "running"]: time.sleep(5) task.update() print("Waiting 5 more seconds for VM creation") if task.info.state == "success": elapsed_time = task.info.completeTime - task.info.startTime print("Successfully created new VM %s. Server took %s seconds." % (name, elapsed_time.seconds)) elif task.info.state == "error": print("ERROR: The task for creating the VM has finished with" " an error. If an error was reported it will follow.") try: print("ERROR: %s" % task.info.error.localizedMessage) except AttributeError: print("ERROR: There is no error message available.") else: print("UNKNOWN: The task reports an unknown state %s" % task.info.state) def create_nic(client, target, nic): """Return a NIC spec""" # Iterate through the networks and look for one matching # the requested name for network in target.network: if network.name == nic["network_name"]: net = network break else: return None # Success! Create a nic attached to this network backing = client.create("VirtualEthernetCardNetworkBackingInfo") backing.deviceName = nic["network_name"] backing.network = net connect_info = client.create("VirtualDeviceConnectInfo") connect_info.allowGuestControl = True connect_info.connected = False connect_info.startConnected = True new_nic = client.create(nic["type"]) new_nic.backing = backing new_nic.key = 2 # TODO: Work out a way to automatically increment this new_nic.unitNumber = 1 new_nic.addressType = "generated" new_nic.connectable = connect_info nic_spec = client.create("VirtualDeviceConfigSpec") nic_spec.device = new_nic nic_spec.fileOperation = None operation = client.create("VirtualDeviceConfigSpecOperation") nic_spec.operation = (operation.add) return nic_spec def create_controller(client, controller_type): controller = client.create(controller_type) controller.key = 0 controller.device = [0] controller.busNumber = 0, controller.sharedBus = client.create("VirtualSCSISharing").noSharing spec = client.create("VirtualDeviceConfigSpec") spec.device = controller spec.fileOperation = None spec.operation = client.create("VirtualDeviceConfigSpecOperation").add return spec def create_disk(client, datastore, disksize_kb): backing = client.create("VirtualDiskFlatVer2BackingInfo") backing.datastore = None backing.diskMode = "persistent" backing.fileName = "[%s]" % datastore.summary.name backing.thinProvisioned = True disk = client.create("VirtualDisk") disk.backing = backing disk.controllerKey = 0 disk.key = 0 disk.unitNumber = 0 disk.capacityInKB = disksize_kb disk_spec = client.create("VirtualDeviceConfigSpec") disk_spec.device = disk file_op = client.create("VirtualDeviceConfigSpecFileOperation") disk_spec.fileOperation = file_op.create operation = client.create("VirtualDeviceConfigSpecOperation") disk_spec.operation = operation.add return disk_spec def main(name, options): """The main method for this script. :param name: The name of the VM to create. :type name: str :param template_name: The name of the template to use for creating \ the VM. :type template_name: str """ server = config._config_value("general", "server", options.server) if server is None: raise ValueError("server must be supplied on command line" " or in configuration file.") username = config._config_value("general", "username", options.username) if username is None: raise ValueError("username must be supplied on command line" " or in configuration file.") password = config._config_value("general", "password", options.password) if password is None: raise ValueError("password must be supplied on command line" " or in configuration file.") vm_template = None if options.template is not None: try: vm_template = template.load_template(options.template) except TemplateNotFoundError: print("ERROR: Template \"%s\" could not be found." % options.template) sys.exit(1) expected_opts = ["compute_resource", "datastore", "disksize", "nics", "memory", "num_cpus", "guest_id", "host"] vm_opts = {} for opt in expected_opts: vm_opts[opt] = getattr(options, opt) if vm_opts[opt] is None: if vm_template is None: raise ValueError("%s not specified on the command line and" " you have not specified any template to" " inherit the value from." % opt) try: vm_opts[opt] = vm_template[opt] except AttributeError: raise ValueError("%s not specified on the command line and" " no value is provided in the specified" " template." % opt) client = Client(server=server, username=username, password=password) create_vm(client, name, vm_opts["compute_resource"], vm_opts["datastore"], vm_opts["disksize"], vm_opts["nics"], vm_opts["memory"], vm_opts["num_cpus"], vm_opts["guest_id"], host=vm_opts["host"]) client.logout() if __name__ == "__main__": from optparse import OptionParser usage = "Usage: %prog [options] name" parser = OptionParser(usage=usage) parser.add_option("--server", dest="server", help="The server to connect to for provisioning") parser.add_option("--username", dest="username", help="The username used to connect to the server") parser.add_option("--password", dest="password", help="The password used to connect to the server") parser.add_option("--template", dest="template", help="The template used to create the VM") parser.add_option("--compute_resource", dest="compute_resource", help="The ComputeResource in which to provision the VM") parser.add_option("--datastore", dest="datastore", help="The datastore on which to provision the VM") parser.add_option("--disksize", dest="disksize", help="The size of the VM disk") parser.add_option("--nics", dest="nics", help="The nics for the VM") parser.add_option("--memory", dest="memory", help="The amount of memory for the VM") parser.add_option("--num_cpus", dest="num_cpus", help="The number of CPUs for the VM") parser.add_option("--guest_id", dest="guest_id", help="The guest_id of the VM (see vSphere doco)") parser.add_option("--host", dest="host", help="Specify this if you want to provision the VM on a" " specific host in the ComputeResource") (options, args) = parser.parse_args() if len(args) != 1: parser.print_help() sys.exit(1) main(args[0], options) psphere-0.5.2/psphere/000077500000000000000000000000001212743422200146315ustar00rootroot00000000000000psphere-0.5.2/psphere/__init__.py000066400000000000000000000342631212743422200167520ustar00rootroot00000000000000# Copyright 2010 Jonathan Kinred # # Licensed under the Apache License, Version 2.0 (the "License"); you may not # use this file except in compliance with the License. You may obtain a copy # of the License at: # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import logging import time from suds import MethodNotFound logger = logging.getLogger(__name__) __version__ = '0.5.2' __released__ = '0.5.2' class cached_property(object): """Decorator for read-only properties evaluated only once within TTL period. It can be used to created a cached property like this:: import random # the class containing the property must be a new-style class class MyClass(object): # create property whose value is cached for ten minutes @cached_property(ttl=600) def randint(self): # will only be evaluated every 10 min. at maximum. return random.randint(0, 100) The value is cached in the '_cache' attribute of the object instance that has the property getter method wrapped by this decorator. The '_cache' attribute value is a dictionary which has a key for every property of the object which is wrapped by this decorator. Each entry in the cache is created only when the property is accessed for the first time and is a two-element tuple with the last computed property value and the last time it was updated in seconds since the epoch. The default time-to-live (TTL) is 300 seconds (5 minutes). Set the TTL to zero for the cached value to never expire. To expire a cached property value manually just do:: del instance._cache[] """ def __init__(self, fget, doc=None): self.ttl = 300 self.fget = fget self.__doc__ = doc or fget.__doc__ self.__name__ = fget.__name__ self.__module__ = fget.__module__ def __get__(self, inst, owner): now = time.time() try: # Get the value from the cache value, last_update = inst._cache[self.__name__] logger.info("Found cached value for %s", self.__name__) # If the value in the cache exceeds the TTL then raise # AttributeError so that we retrieve the value again below if self.ttl > 0 and now - last_update > self.ttl: logger.info("Cached value has exceeded TTL") raise AttributeError except (KeyError, AttributeError): # We end up here if the value hasn't been cached # or the value exceeds the TTL. We call the decorated # function to get the value. logger.info("%s is not cached.", self.__name__) value = self.fget(inst) try: # See if the instance has a cache attribute cache = inst._cache except AttributeError: # If it doesn't, initialise the attribute and use it cache = inst._cache = {} # Set the value in the cache dict to our values cache[self.__name__] = (value, now) # Finally, return either the value from the cache or the # newly retrieved value return value class ManagedObject(object): """The base class which all managed object's derive from. :param mo_ref: The managed object reference used to create this instance :type mo_ref: ManagedObjectReference :param client: A reference back to the psphere client object, which \ we use to make calls. :type client: Client """ _valid_attrs = set([]) def __init__(self, mo_ref, client): self._cache = {} logger.debug("===== Have been passed %s as mo_ref: ", mo_ref) self._mo_ref = mo_ref self._client = client def _get_dataobject(self, name, multivalued): """This function only gets called if the decorated property doesn't have a value in the cache.""" logger.debug("Querying server for uncached data object %s", name) # This will retrieve the value and inject it into the cache self.update_view_data(properties=[name]) return self._cache[name][0] def _get_mor(self, name, multivalued): """This function only gets called if the decorated property doesn't have a value in the cache.""" logger.debug("Querying server for uncached MOR %s", name) # This will retrieve the value and inject it into the cache logger.debug("Getting view for MOR") self.update(properties=[name]) return self._cache[name][0] # return self._cache[name][0] # if multivalued is True: # logger.debug("Getting views for MOR") # self.update(properties=[name]) # views = self._client.get_views(self._cache[name][0]) # return views # else: # logger.debug("Getting view for MOR") # self.update(properties=[name]) # return self._cache[name][0] def flush_cache(self, properties=None): """Flushes the cache being held for this instance. :param properties: The list of properties to flush from the cache. :type properties: list or None (default). If None, flush entire cache. """ if hasattr(self, '_cache'): if properties is None: del(self._cache) else: for prop in properties: if prop in self._cache: del(self._cache[prop]) def update(self, properties=None): """Updates the properties being held for this instance. :param properties: The list of properties to update. :type properties: list or None (default). If None, update all currently cached properties. """ if properties is None: try: self.update_view_data(properties=self._cache.keys()) except AttributeError: # We end up here and ignore it self._cache doesn't exist pass else: self.update_view_data(properties=properties) def _get_properties(self, properties=None): """Retrieve the requested properties from the server. :param properties: The list of properties to update. :type properties: list or None (default). """ pass def update_view_data(self, properties=None): """Update the local object from the server-side object. >>> vm = VirtualMachine.find_one(client, filter={"name": "genesis"}) >>> # Update all properties >>> vm.update_view_data() >>> # Update the config and summary properties >>> vm.update_view_data(properties=["config", "summary"] :param properties: A list of properties to update. :type properties: list """ if properties is None: properties = [] logger.info("Updating view data for object of type %s", self._mo_ref._type) property_spec = self._client.create('PropertySpec') property_spec.type = str(self._mo_ref._type) # Determine which properties to retrieve from the server if properties is None: properties = [] else: if properties == "all": logger.debug("Retrieving all properties") property_spec.all = True else: logger.debug("Retrieving %s properties", len(properties)) property_spec.all = False property_spec.pathSet = properties object_spec = self._client.create('ObjectSpec') object_spec.obj = self._mo_ref pfs = self._client.create('PropertyFilterSpec') pfs.propSet = [property_spec] pfs.objectSet = [object_spec] # Create a copy of the property collector and call the method pc = self._client.sc.propertyCollector object_content = pc.RetrieveProperties(specSet=pfs)[0] if not object_content: # TODO: Improve error checking and reporting logger.error("Nothing returned from RetrieveProperties!") self._set_view_data(object_content) def preload(self, name, properties=None): """Pre-loads the requested properties for each object in the "name" attribute. :param name: The name of the attribute containing the list to preload. :type name: str :param properties: The properties to preload on the objects or the string all to preload all properties. :type properties: list or the string "all" """ if properties is None: raise ValueError("You must specify some properties to preload. To" " preload all properties use the string \"all\".") # Don't do anything if the attribute contains an empty list if not getattr(self, name): return mo_refs = [] # Iterate over each item and collect the mo_ref for item in getattr(self, name): # Make sure the items are ManagedObjectReference's if isinstance(item, ManagedObject) is False: raise ValueError("Only ManagedObject's can be pre-loaded.") mo_refs.append(item._mo_ref) # Send a single query to the server which gets views views = self._client.get_views(mo_refs, properties) # Populate the inst.attr item with the retrieved object/properties self._cache[name] = (views, time.time()) def _set_view_data(self, object_content): """Update the local object from the passed in object_content.""" # A debugging convenience, allows inspection of the object_content # that was used to create the object logger.info("Setting view data for a %s", self.__class__) self._object_content = object_content for dynprop in object_content.propSet: # If the class hasn't defined the property, don't use it if dynprop.name not in self._valid_attrs: logger.error("Server returned a property '%s' but the object" " hasn't defined it so it is being ignored." % dynprop.name) continue try: if not len(dynprop.val): logger.info("Server returned empty value for %s", dynprop.name) except TypeError: # This except allows us to pass over: # TypeError: object of type 'datetime.datetime' has no len() # It will be processed in the next code block logger.info("%s of type %s has no len!", dynprop.name, type(dynprop.val)) pass try: # See if we have a cache attribute cache = self._cache except AttributeError: # If we don't create one and use it cache = self._cache = {} # Values which contain classes starting with Array need # to be converted into a nicer Python list if dynprop.val.__class__.__name__.startswith('Array'): # suds returns a list containing a single item, which # is another list. Use the first item which is the real list logger.info("Setting value of an Array* property") logger.debug("%s being set to %s", dynprop.name, dynprop.val[0]) now = time.time() cache[dynprop.name] = (dynprop.val[0], now) else: logger.info("Setting value of a single-valued property") logger.debug("DynamicProperty value is a %s: ", dynprop.val.__class__.__name__) logger.debug("%s being set to %s", dynprop.name, dynprop.val) now = time.time() cache[dynprop.name] = (dynprop.val, now) def __getattr__(self, name): """Overridden so that SOAP methods can be proxied. The magic contained here allows us to automatically access vSphere SOAP methods through the Python object, like: >>> client.si.content.rootFolder.CreateFolder(name="foo") This is achieved by asking the underlying SOAP service if the requested name is a valid method. If the method name is not valid then we pass the attribute retrieval back to __getattribute__ which will use the default behaviour (i.e. just get the attribute). TODO: There's no checking if the SOAP method is valid for the type of object being called. e.g. You could do folder.Login() which would be totally bogus. :param name: The name of the method to call. :param type: str """ logger.debug("Entering overridden built-in __getattr__" " with %s" % name) # Built-ins always use the default behaviour # if name.startswith("__"): # logger.debug("Returning built-in attribute %s", name) # return object.__getattribute__(self, name) # Here we must access _client through __getattribute__, if we were # to use "self._client" we'd call recursively through __getattr__ client = object.__getattribute__(self, "_client") try: getattr(client.service, name) except MethodNotFound: # It doesn't, so we let the object check if it's a standard # attribute. This is cool because it return object.__getattribute__(self, name) # Caller has requested a valid SOAP reference logger.debug("Constructing proxy method %s for a %s", name, self._mo_ref._type) def func(**kwargs): result = self._client.invoke(name, _this=self._mo_ref, **kwargs) logger.debug("Invoke returned %s", result) return result return func psphere-0.5.2/psphere/client.py000066400000000000000000000603331212743422200164660ustar00rootroot00000000000000""" :mod:`psphere.client` - A client for communicating with a vSphere server ======================================================================== .. module:: client The main module for accessing a vSphere server. .. moduleauthor:: Jonathan Kinred """ # Copyright 2010 Jonathan Kinred # # Licensed under the Apache License, Version 2.0 (the "License"); you may not # use this file except in compliance with the License. You may obtain a copy # of the License at: # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import logging import os import suds import time from urllib2 import URLError from suds.plugin import MessagePlugin from suds.transport import TransportError from psphere import soap, ManagedObject from psphere.config import _config_value from psphere.errors import (ConfigError, ObjectNotFoundError, TaskFailedError, NotLoggedInError) from psphere.managedobjects import ServiceInstance, Task, classmapper logger = logging.getLogger(__name__) class Client(suds.client.Client): """A client for communicating with a VirtualCenter/ESX/ESXi server >>> from psphere.client import Client >>> Client = Client(server="esx.foo.com", username="me", password="pass") :param server: The server of the server. e.g. https://esx.foo.com/sdk :type server: str :param username: The username to connect with :type username: str :param password: The password to connect with :type password: str :param wsdl_location: Whether to use the provided WSDL or load the server WSDL :type wsdl_location: The string "local" (default) or "remote" :param timeout: The timeout to use when connecting to the server :type timeout: int (default=30) :param plugins: The plugins classes that will be used to process messages before send them to the web service :type plugins: list of classes """ def __init__(self, server=None, username=None, password=None, wsdl_location="local", timeout=30, plugins=[]): self._logged_in = False if server is None: server = _config_value("general", "server") if username is None: username = _config_value("general", "username") if password is None: password = _config_value("general", "password") if server is None: raise ConfigError("server must be set in config file or Client()") if username is None: raise ConfigError("username must be set in config file or Client()") if password is None: raise ConfigError("password must be set in config file or Client()") self.server = server self.username = username self.password = password url = "https://%s/sdk" % self.server if wsdl_location == "local": current_path = os.path.abspath(os.path.dirname(__file__)) current_path = current_path.replace('\\', '/') if not current_path.startswith('/') : current_path = '/' + current_path if current_path.endswith('/') : current_path = current_path[:-1] wsdl_uri = ("file://%s/wsdl/vimService.wsdl" % current_path) elif wsdl_location == "remote": wsdl_uri = url + "/vimService.wsdl" else: raise ValueError("wsdl_location must be \"local\" or \"remote\"") # Init the base class try: # Add ExtraConfigPlugin to the plugins plugins.append(ExtraConfigPlugin()) suds.client.Client.__init__(self, wsdl_uri, plugins=plugins) except URLError: logger.critical("Failed to connect to %s", self.server) raise except IOError: logger.critical("Failed to load the local WSDL from %s", wsdl_uri) raise except TransportError: logger.critical("Failed to load the remote WSDL from %s", wsdl_uri) raise self.options.transport.options.timeout = timeout self.set_options(location=url) mo_ref = soap.ManagedObjectReference("ServiceInstance", "ServiceInstance") self.si = ServiceInstance(mo_ref, self) try: self.sc = self.si.RetrieveServiceContent() except URLError, e: logger.critical("Failed to connect to %s" % self.server) logger.critical("urllib2 said: %s" % e.reason) raise if self._logged_in is False: self.login(self.username, self.password) def login(self, username=None, password=None): """Login to a vSphere server. >>> client.login(username='Administrator', password='strongpass') :param username: The username to authenticate as. :type username: str :param password: The password to authenticate with. :type password: str """ if username is None: username = self.username if password is None: password = self.password logger.debug("Logging into server") self.sc.sessionManager.Login(userName=username, password=password) self._logged_in = True def logout(self): """Logout of a vSphere server.""" if self._logged_in is True: self.si.flush_cache() self.sc.sessionManager.Logout() self._logged_in = False def invoke(self, method, _this, **kwargs): """Invoke a method on the server. >>> client.invoke('CurrentTime', client.si) :param method: The method to invoke, as found in the SDK. :type method: str :param _this: The managed object reference against which to invoke \ the method. :type _this: ManagedObject :param kwargs: The arguments to pass to the method, as \ found in the SDK. :type kwargs: TODO """ if (self._logged_in is False and method not in ["Login", "RetrieveServiceContent"]): logger.critical("Cannot exec %s unless logged in", method) raise NotLoggedInError("Cannot exec %s unless logged in" % method) for kwarg in kwargs: kwargs[kwarg] = self._marshal(kwargs[kwarg]) result = getattr(self.service, method)(_this=_this, **kwargs) if hasattr(result, '__iter__') is False: logger.debug("Returning non-iterable result") return result # We must traverse the result and convert any ManagedObjectReference # to a psphere class, this will then be lazy initialised on use logger.debug(result.__class__) logger.debug("Result: %s", result) logger.debug("Length: %s", len(result)) if type(result) == list: new_result = [] for item in result: new_result.append(self._unmarshal(item)) else: new_result = self._unmarshal(result) logger.debug("Finished in invoke.") #property = self.find_and_destroy(property) #print result # Return the modified result to the caller return new_result def _mor_to_pobject(self, mo_ref): """Converts a MOR to a psphere object.""" kls = classmapper(mo_ref._type) new_object = kls(mo_ref, self) return new_object def _marshal(self, obj): """Walks an object and marshals any psphere object into MORs.""" logger.debug("Checking if %s needs to be marshalled", obj) if isinstance(obj, ManagedObject): logger.debug("obj is a psphere object, converting to MOR") return obj._mo_ref if isinstance(obj, list): logger.debug("obj is a list, recursing it") new_list = [] for item in obj: new_list.append(self._marshal(item)) return new_list if not isinstance(obj, suds.sudsobject.Object): logger.debug("%s is not a sudsobject subclass, skipping", obj) return obj if hasattr(obj, '__iter__'): logger.debug("obj is iterable, recursing it") for (name, value) in obj: setattr(obj, name, self._marshal(value)) return obj # The obj has nothing that we want to marshal or traverse, return it logger.debug("obj doesn't need to be marshalled") return obj def _unmarshal(self, obj): """Walks an object and unmarshals any MORs into psphere objects.""" if isinstance(obj, suds.sudsobject.Object) is False: logger.debug("%s is not a suds instance, skipping", obj) return obj logger.debug("Processing:") logger.debug(obj) logger.debug("...with keylist:") logger.debug(obj.__keylist__) # If the obj that we're looking at has a _type key # then create a class of that type and return it immediately if "_type" in obj.__keylist__: logger.debug("obj is a MOR, converting to psphere class") return self._mor_to_pobject(obj) new_object = obj.__class__() for sub_obj in obj: logger.debug("Looking at %s of type %s", sub_obj, type(sub_obj)) if isinstance(sub_obj[1], list): new_embedded_objs = [] for emb_obj in sub_obj[1]: new_emb_obj = self._unmarshal(emb_obj) new_embedded_objs.append(new_emb_obj) setattr(new_object, sub_obj[0], new_embedded_objs) continue if not issubclass(sub_obj[1].__class__, suds.sudsobject.Object): logger.debug("%s is not a sudsobject subclass, skipping", sub_obj[1].__class__) setattr(new_object, sub_obj[0], sub_obj[1]) continue logger.debug("Obj keylist: %s", sub_obj[1].__keylist__) if "_type" in sub_obj[1].__keylist__: logger.debug("Converting nested MOR to psphere class:") logger.debug(sub_obj[1]) kls = classmapper(sub_obj[1]._type) logger.debug("Setting %s.%s to %s", new_object.__class__.__name__, sub_obj[0], sub_obj[1]) setattr(new_object, sub_obj[0], kls(sub_obj[1], self)) else: logger.debug("Didn't find _type in:") logger.debug(sub_obj[1]) setattr(new_object, sub_obj[0], self._unmarshal(sub_obj[1])) return new_object def create(self, type_, **kwargs): """Create a SOAP object of the requested type. >>> client.create('VirtualE1000') :param type_: The type of SOAP object to create. :type type_: str :param kwargs: TODO :type kwargs: TODO """ obj = self.factory.create("ns0:%s" % type_) for key, value in kwargs.items(): setattr(obj, key, value) return obj # Notes # ----- # A view is a local, static representation of a managed object in # the inventory. The view is not automatically synchronised with # the server-side object and can therefore be out of date a moment # after it is retrieved. # # Retrieval of only the properties you intend to use -- through # the use of the properties parameter -- is considered best # practise as the properties of some managed objects can be # costly to retrieve. def get_view(self, mo_ref, properties=None): """Get a view of a vSphere managed object. :param mo_ref: The MOR to get a view of :type mo_ref: ManagedObjectReference :param properties: A list of properties to retrieve from the \ server :type properties: list :returns: A view representing the ManagedObjectReference. :rtype: ManagedObject """ # This maps the mo_ref into a psphere class and then instantiates it kls = classmapper(mo_ref._type) view = kls(mo_ref, self) # Update the requested properties of the instance #view.update_view_data(properties=properties) return view def get_views(self, mo_refs, properties=None): """Get a list of local view's for multiple managed objects. :param mo_refs: The list of ManagedObjectReference's that views are \ to be created for. :type mo_refs: ManagedObjectReference :param properties: The properties to retrieve in the views. :type properties: list :returns: A list of local instances representing the server-side \ managed objects. :rtype: list of ManagedObject's """ property_specs = [] for mo_ref in mo_refs: property_spec = self.create('PropertySpec') property_spec.type = str(mo_ref._type) if properties is None: properties = [] else: # Only retrieve the requested properties if properties == "all": property_spec.all = True else: property_spec.all = False property_spec.pathSet = properties property_specs.append(property_spec) object_specs = [] for mo_ref in mo_refs: object_spec = self.create('ObjectSpec') object_spec.obj = mo_ref object_specs.append(object_spec) pfs = self.create('PropertyFilterSpec') pfs.propSet = property_specs pfs.objectSet = object_specs object_contents = self.sc.propertyCollector.RetrieveProperties( specSet=pfs) views = [] for object_content in object_contents: # Update the instance with the data in object_content object_content.obj._set_view_data(object_content=object_content) views.append(object_content.obj) return views def get_search_filter_spec(self, begin_entity, property_spec): """Build a PropertyFilterSpec capable of full inventory traversal. By specifying all valid traversal specs we are creating a PFS that can recursively select any object under the given entity. :param begin_entity: The place in the MOB to start the search. :type begin_entity: ManagedEntity :param property_spec: TODO :type property_spec: TODO :returns: A PropertyFilterSpec, suitable for recursively searching \ under the given ManagedEntity. :rtype: PropertyFilterSpec """ # The selection spec for additional objects we want to filter ss_strings = ['resource_pool_traversal_spec', 'resource_pool_vm_traversal_spec', 'folder_traversal_spec', 'datacenter_host_traversal_spec', 'datacenter_vm_traversal_spec', 'compute_resource_rp_traversal_spec', 'compute_resource_host_traversal_spec', 'host_vm_traversal_spec'] # Create a selection spec for each of the strings specified above selection_specs = [ self.create('SelectionSpec', name=ss_string) for ss_string in ss_strings ] # A traversal spec for deriving ResourcePool's from found VMs rpts = self.create('TraversalSpec') rpts.name = 'resource_pool_traversal_spec' rpts.type = 'ResourcePool' rpts.path = 'resourcePool' rpts.selectSet = [selection_specs[0], selection_specs[1]] # A traversal spec for deriving ResourcePool's from found VMs rpvts = self.create('TraversalSpec') rpvts.name = 'resource_pool_vm_traversal_spec' rpvts.type = 'ResourcePool' rpvts.path = 'vm' crrts = self.create('TraversalSpec') crrts.name = 'compute_resource_rp_traversal_spec' crrts.type = 'ComputeResource' crrts.path = 'resourcePool' crrts.selectSet = [selection_specs[0], selection_specs[1]] crhts = self.create('TraversalSpec') crhts.name = 'compute_resource_host_traversal_spec' crhts.type = 'ComputeResource' crhts.path = 'host' dhts = self.create('TraversalSpec') dhts.name = 'datacenter_host_traversal_spec' dhts.type = 'Datacenter' dhts.path = 'hostFolder' dhts.selectSet = [selection_specs[2]] dvts = self.create('TraversalSpec') dvts.name = 'datacenter_vm_traversal_spec' dvts.type = 'Datacenter' dvts.path = 'vmFolder' dvts.selectSet = [selection_specs[2]] hvts = self.create('TraversalSpec') hvts.name = 'host_vm_traversal_spec' hvts.type = 'HostSystem' hvts.path = 'vm' hvts.selectSet = [selection_specs[2]] fts = self.create('TraversalSpec') fts.name = 'folder_traversal_spec' fts.type = 'Folder' fts.path = 'childEntity' fts.selectSet = [selection_specs[2], selection_specs[3], selection_specs[4], selection_specs[5], selection_specs[6], selection_specs[7], selection_specs[1]] obj_spec = self.create('ObjectSpec') obj_spec.obj = begin_entity obj_spec.selectSet = [fts, dvts, dhts, crhts, crrts, rpts, hvts, rpvts] pfs = self.create('PropertyFilterSpec') pfs.propSet = [property_spec] pfs.objectSet = [obj_spec] return pfs def invoke_task(self, method, **kwargs): """Execute a \*_Task method and wait for it to complete. :param method: The \*_Task method to invoke. :type method: str :param kwargs: The arguments to pass to the method. :type kwargs: TODO """ # Don't execute methods which don't return a Task object if not method.endswith('_Task'): logger.error('invoke_task can only be used for methods which ' 'return a ManagedObjectReference to a Task.') return None task_mo_ref = self.invoke(method=method, **kwargs) task = Task(task_mo_ref, self) task.update_view_data(properties=['info']) # TODO: This returns true when there is an error while True: if task.info.state == 'success': return task elif task.info.state == 'error': # TODO: Handle error checking properly raise TaskFailedError(task.info.error.localizedMessage) # TODO: Implement progresscallbackfunc # Sleep two seconds and then refresh the data from the server time.sleep(2) task.update_view_data(properties=['info']) def find_entity_views(self, view_type, begin_entity=None, properties=None): """Find all ManagedEntity's of the requested type. :param view_type: The type of ManagedEntity's to find. :type view_type: str :param begin_entity: The MOR to start searching for the entity. \ The default is to start the search at the root folder. :type begin_entity: ManagedObjectReference or None :returns: A list of ManagedEntity's :rtype: list """ if properties is None: properties = [] # Start the search at the root folder if no begin_entity was given if not begin_entity: begin_entity = self.sc.rootFolder._mo_ref property_spec = self.create('PropertySpec') property_spec.type = view_type property_spec.all = False property_spec.pathSet = properties pfs = self.get_search_filter_spec(begin_entity, property_spec) # Retrieve properties from server and update entity obj_contents = self.sc.propertyCollector.RetrieveProperties(specSet=pfs) views = [] for obj_content in obj_contents: logger.debug("In find_entity_view with object of type %s", obj_content.obj.__class__.__name__) obj_content.obj.update_view_data(properties=properties) views.append(obj_content.obj) return views def find_entity_view(self, view_type, begin_entity=None, filter={}, properties=None): """Find a ManagedEntity of the requested type. Traverses the MOB looking for an entity matching the filter. :param view_type: The type of ManagedEntity to find. :type view_type: str :param begin_entity: The MOR to start searching for the entity. \ The default is to start the search at the root folder. :type begin_entity: ManagedObjectReference or None :param filter: Key/value pairs to filter the results. The key is \ a valid parameter of the ManagedEntity type. The value is what \ that parameter should match. :type filter: dict :returns: If an entity is found, a ManagedEntity matching the search. :rtype: ManagedEntity """ if properties is None: properties = [] kls = classmapper(view_type) # Start the search at the root folder if no begin_entity was given if not begin_entity: begin_entity = self.sc.rootFolder._mo_ref logger.debug("Using %s", self.sc.rootFolder._mo_ref) property_spec = self.create('PropertySpec') property_spec.type = view_type property_spec.all = False property_spec.pathSet = filter.keys() pfs = self.get_search_filter_spec(begin_entity, property_spec) # Retrieve properties from server and update entity #obj_contents = self.propertyCollector.RetrieveProperties(specSet=pfs) obj_contents = self.sc.propertyCollector.RetrieveProperties(specSet=pfs) # TODO: Implement filtering if not filter: logger.warning('No filter specified, returning first match.') # If no filter is specified we just return the first item # in the list of returned objects logger.debug("Creating class in find_entity_view (filter)") view = kls(obj_contents[0].obj, self) logger.debug("Completed creating class in find_entity_view (filter)") #view.update_view_data(properties) return view matched = False # Iterate through obj_contents retrieved for obj_content in obj_contents: # If there are is no propSet, skip this one if not obj_content.propSet: continue matches = 0 # Iterate through each property in the set for prop in obj_content.propSet: for key in filter.keys(): # If the property name is in the defined filter if prop.name == key: # ...and it matches the value specified # TODO: Regex this? if prop.val == filter[prop.name]: # We've found a match matches += 1 else: break else: continue if matches == len(filter): filtered_obj_content = obj_content matched = True break else: continue if matched is not True: # There were no matches raise ObjectNotFoundError("No matching objects for filter") logger.debug("Creating class in find_entity_view") view = kls(filtered_obj_content.obj._mo_ref, self) logger.debug("Completed creating class in find_entity_view") #view.update_view_data(properties=properties) return view class ExtraConfigPlugin(MessagePlugin): def addAttributeForValue(self, node): if node.parent.name == 'extraConfig' and node.name == 'value': node.set('xsi:type', 'xsd:string') def marshalled(self, context): context.envelope.walk(self.addAttributeForValue) psphere-0.5.2/psphere/config.py000066400000000000000000000012751212743422200164550ustar00rootroot00000000000000import os import yaml import logging logger = logging.getLogger(__name__) config_path = os.path.expanduser('~/.psphere/config.yaml') try: config_file = open(config_path, "r") PSPHERE_CONFIG = yaml.load(config_file) config_file.close() except IOError: logger.warning("Configuration file %s could not be opened, perhaps you" " haven't created one?" % config_path) PSPHERE_CONFIG = {"general": {}, "logging": {}} pass def _config_value(section, name, default=None): file_value = None if name in PSPHERE_CONFIG[section]: file_value = PSPHERE_CONFIG[section][name] if file_value: return file_value else: return default psphere-0.5.2/psphere/errors.py000066400000000000000000000015321212743422200165200ustar00rootroot00000000000000# Copyright 2010 Jonathan Kinred # # Licensed under the Apache License, Version 2.0 (the "License"); you may not # use this file except in compliance with the License. You may obtain a copy # of the License at: # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. class ConfigError(Exception): pass class NotLoggedInError(Exception): pass class ObjectNotFoundError(Exception): pass class TaskFailedError(Exception): pass class TemplateNotFoundError(Exception): pass class NotImplementedError(Exception): pass psphere-0.5.2/psphere/managedobjects.py000066400000000000000000001517031212743422200201600ustar00rootroot00000000000000from psphere import ManagedObject, cached_property class ExtensibleManagedObject(ManagedObject): _valid_attrs = set(['availableField', 'value']) def __init__(self, mo_ref, client): ManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObject._valid_attrs) @cached_property def availableField(self): return self._get_dataobject("availableField", True) @cached_property def value(self): return self._get_dataobject("value", True) class Alarm(ExtensibleManagedObject): _valid_attrs = set(['info']) def __init__(self, mo_ref, client): ExtensibleManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ExtensibleManagedObject._valid_attrs) @cached_property def info(self): return self._get_dataobject("info", False) class AlarmManager(ManagedObject): _valid_attrs = set(['defaultExpression', 'description']) def __init__(self, mo_ref, client): ManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObject._valid_attrs) @cached_property def defaultExpression(self): return self._get_dataobject("defaultExpression", True) @cached_property def description(self): return self._get_dataobject("description", False) class AuthorizationManager(ManagedObject): _valid_attrs = set(['description', 'privilegeList', 'roleList']) def __init__(self, mo_ref, client): ManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObject._valid_attrs) @cached_property def description(self): return self._get_dataobject("description", False) @cached_property def privilegeList(self): return self._get_dataobject("privilegeList", True) @cached_property def roleList(self): return self._get_dataobject("roleList", True) class ManagedEntity(ExtensibleManagedObject): _valid_attrs = set(['alarmActionsEnabled', 'configIssue', 'configStatus', 'customValue', 'declaredAlarmState', 'disabledMethod', 'effectiveRole', 'name', 'overallStatus', 'parent', 'permission', 'recentTask', 'tag', 'triggeredAlarmState']) def __init__(self, mo_ref, client): ExtensibleManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ExtensibleManagedObject._valid_attrs) @cached_property def alarmActionsEnabled(self): return self._get_dataobject("alarmActionsEnabled", False) @cached_property def configIssue(self): return self._get_dataobject("configIssue", True) @cached_property def configStatus(self): return self._get_dataobject("configStatus", False) @cached_property def customValue(self): return self._get_dataobject("customValue", True) @cached_property def declaredAlarmState(self): return self._get_dataobject("declaredAlarmState", True) @cached_property def disabledMethod(self): return self._get_dataobject("disabledMethod", True) @cached_property def effectiveRole(self): return self._get_dataobject("effectiveRole", True) @cached_property def name(self): return self._get_dataobject("name", False) @cached_property def overallStatus(self): return self._get_dataobject("overallStatus", False) @cached_property def parent(self): return self._get_mor("parent", False) @cached_property def permission(self): return self._get_dataobject("permission", True) @cached_property def recentTask(self): return self._get_mor("recentTask", True) @cached_property def tag(self): return self._get_dataobject("tag", True) @cached_property def triggeredAlarmState(self): return self._get_dataobject("triggeredAlarmState", True) @classmethod def all(cls, client, properties=None): if properties is None: properties = [] if "name" not in properties: properties.append("name") return client.find_entity_views(cls.__name__, properties=properties) @classmethod def get(cls, client, **kwargs): if "properties" in kwargs.keys(): properties = kwargs["properties"] # Delete properties key so it doesn't get filtered del kwargs["properties"] else: properties = None if properties is None: properties = [] # Automatically get the name property for every ManagedEntity if "name" not in properties: properties.append("name") filter = {} for key in kwargs.keys(): filter[key] = kwargs[key] return client.find_entity_view(cls.__name__, filter=filter, properties=properties) def __cmp__(self, other): if self.name == other.name: return 0 if self.name < other.name: return -1 if self.name > other.name: return 1 # def __str__(self): # return self.name class ComputeResource(ManagedEntity): _valid_attrs = set(['configurationEx', 'datastore', 'environmentBrowser', 'host', 'network', 'resourcePool', 'summary']) def __init__(self, mo_ref, client): ManagedEntity.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedEntity._valid_attrs) @cached_property def configurationEx(self): return self._get_dataobject("configurationEx", False) @cached_property def datastore(self): return self._get_mor("datastore", True) @cached_property def environmentBrowser(self): return self._get_mor("environmentBrowser", False) @cached_property def host(self): return self._get_mor("host", True) @cached_property def network(self): return self._get_mor("network", True) @cached_property def resourcePool(self): return self._get_mor("resourcePool", False) @cached_property def summary(self): return self._get_dataobject("summary", False) class ClusterComputeResource(ComputeResource): _valid_attrs = set(['actionHistory', 'configuration', 'drsFault', 'drsRecommendation', 'migrationHistory', 'recommendation']) def __init__(self, mo_ref, client): ComputeResource.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ComputeResource._valid_attrs) @cached_property def actionHistory(self): return self._get_dataobject("actionHistory", True) @cached_property def configuration(self): return self._get_dataobject("configuration", False) @cached_property def drsFault(self): return self._get_dataobject("drsFault", True) @cached_property def drsRecommendation(self): return self._get_dataobject("drsRecommendation", True) @cached_property def migrationHistory(self): return self._get_dataobject("migrationHistory", True) @cached_property def recommendation(self): return self._get_dataobject("recommendation", True) class Profile(ManagedObject): _valid_attrs = set(['complianceStatus', 'config', 'createdTime', 'description', 'entity', 'modifiedTime', 'name']) def __init__(self, mo_ref, client): ManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObject._valid_attrs) @cached_property def complianceStatus(self): return self._get_dataobject("complianceStatus", False) @cached_property def config(self): return self._get_dataobject("config", False) @cached_property def createdTime(self): return self._get_dataobject("createdTime", False) @cached_property def description(self): return self._get_dataobject("description", False) @cached_property def entity(self): return self._get_mor("entity", True) @cached_property def modifiedTime(self): return self._get_dataobject("modifiedTime", False) @cached_property def name(self): return self._get_dataobject("name", False) class ClusterProfile(Profile): _valid_attrs = set([]) def __init__(self, mo_ref, client): Profile.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, Profile._valid_attrs) class ProfileManager(ManagedObject): _valid_attrs = set(['profile']) def __init__(self, mo_ref, client): ManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObject._valid_attrs) @cached_property def profile(self): return self._get_mor("profile", True) class ClusterProfileManager(ProfileManager): _valid_attrs = set([]) def __init__(self, mo_ref, client): ProfileManager.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ProfileManager._valid_attrs) class View(ManagedObject): _valid_attrs = set([]) def __init__(self, mo_ref, client): ManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObject._valid_attrs) class ManagedObjectView(View): _valid_attrs = set(['view']) def __init__(self, mo_ref, client): View.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, View._valid_attrs) @cached_property def view(self): return self._get_mor("view", True) class ContainerView(ManagedObjectView): _valid_attrs = set(['container', 'recursive', 'type']) def __init__(self, mo_ref, client): ManagedObjectView.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObjectView._valid_attrs) @cached_property def container(self): return self._get_mor("container", False) @cached_property def recursive(self): return self._get_dataobject("recursive", False) @cached_property def type(self): return self._get_dataobject("type", True) class CustomFieldsManager(ManagedObject): _valid_attrs = set(['field']) def __init__(self, mo_ref, client): ManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObject._valid_attrs) @cached_property def field(self): return self._get_dataobject("field", True) class CustomizationSpecManager(ManagedObject): _valid_attrs = set(['encryptionKey', 'info']) def __init__(self, mo_ref, client): ManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObject._valid_attrs) @cached_property def encryptionKey(self): return self._get_dataobject("encryptionKey", True) @cached_property def info(self): return self._get_dataobject("info", True) class Datacenter(ManagedEntity): _valid_attrs = set(['datastore', 'datastoreFolder', 'hostFolder', 'network', 'networkFolder', 'vmFolder']) def __init__(self, mo_ref, client): ManagedEntity.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedEntity._valid_attrs) @cached_property def datastore(self): return self._get_mor("datastore", True) @cached_property def datastoreFolder(self): return self._get_mor("datastoreFolder", False) @cached_property def hostFolder(self): return self._get_mor("hostFolder", False) @cached_property def network(self): return self._get_mor("network", True) @cached_property def networkFolder(self): return self._get_mor("networkFolder", False) @cached_property def vmFolder(self): return self._get_mor("vmFolder", False) class Datastore(ManagedEntity): _valid_attrs = set(['browser', 'capability', 'host', 'info', 'iormConfiguration', 'summary', 'vm']) def __init__(self, mo_ref, client): ManagedEntity.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedEntity._valid_attrs) @cached_property def browser(self): return self._get_mor("browser", False) @cached_property def capability(self): return self._get_dataobject("capability", False) @cached_property def host(self): return self._get_dataobject("host", True) @cached_property def info(self): return self._get_dataobject("info", False) @cached_property def iormConfiguration(self): return self._get_dataobject("iormConfiguration", False) @cached_property def summary(self): return self._get_dataobject("summary", False) @cached_property def vm(self): return self._get_mor("vm", True) class DiagnosticManager(ManagedObject): _valid_attrs = set([]) def __init__(self, mo_ref, client): ManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObject._valid_attrs) class Network(ManagedEntity): _valid_attrs = set(['host', 'name', 'summary', 'vm']) def __init__(self, mo_ref, client): ManagedEntity.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedEntity._valid_attrs) @cached_property def host(self): return self._get_mor("host", True) @cached_property def name(self): return self._get_dataobject("name", False) @cached_property def summary(self): return self._get_dataobject("summary", False) @cached_property def vm(self): return self._get_mor("vm", True) class DistributedVirtualPortgroup(Network): _valid_attrs = set(['config', 'key', 'portKeys']) def __init__(self, mo_ref, client): Network.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, Network._valid_attrs) @cached_property def config(self): return self._get_dataobject("config", False) @cached_property def key(self): return self._get_dataobject("key", False) @cached_property def portKeys(self): return self._get_dataobject("portKeys", True) class DistributedVirtualSwitch(ManagedEntity): _valid_attrs = set(['capability', 'config', 'networkResourcePool', 'portgroup', 'summary', 'uuid']) def __init__(self, mo_ref, client): ManagedEntity.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedEntity._valid_attrs) @cached_property def capability(self): return self._get_dataobject("capability", False) @cached_property def config(self): return self._get_dataobject("config", False) @cached_property def networkResourcePool(self): return self._get_dataobject("networkResourcePool", True) @cached_property def portgroup(self): return self._get_mor("portgroup", True) @cached_property def summary(self): return self._get_dataobject("summary", False) @cached_property def uuid(self): return self._get_dataobject("uuid", False) class DistributedVirtualSwitchManager(ManagedObject): _valid_attrs = set([]) def __init__(self, mo_ref, client): ManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObject._valid_attrs) class EnvironmentBrowser(ManagedObject): _valid_attrs = set(['datastoreBrowser']) def __init__(self, mo_ref, client): ManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObject._valid_attrs) @cached_property def datastoreBrowser(self): return self._get_mor("datastoreBrowser", False) class HistoryCollector(ManagedObject): _valid_attrs = set(['filter']) def __init__(self, mo_ref, client): ManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObject._valid_attrs) @cached_property def filter(self): return self._get_dataobject("filter", False) class EventHistoryCollector(HistoryCollector): _valid_attrs = set(['latestPage']) def __init__(self, mo_ref, client): HistoryCollector.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, HistoryCollector._valid_attrs) @cached_property def latestPage(self): return self._get_dataobject("latestPage", True) class EventManager(ManagedObject): _valid_attrs = set(['description', 'latestEvent', 'maxCollector']) def __init__(self, mo_ref, client): ManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObject._valid_attrs) @cached_property def description(self): return self._get_dataobject("description", False) @cached_property def latestEvent(self): return self._get_dataobject("latestEvent", False) @cached_property def maxCollector(self): return self._get_dataobject("maxCollector", False) class ExtensionManager(ManagedObject): _valid_attrs = set(['extensionList']) def __init__(self, mo_ref, client): ManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObject._valid_attrs) @cached_property def extensionList(self): return self._get_dataobject("extensionList", True) class FileManager(ManagedObject): _valid_attrs = set([]) def __init__(self, mo_ref, client): ManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObject._valid_attrs) class Folder(ManagedEntity): _valid_attrs = set(['childEntity', 'childType']) def __init__(self, mo_ref, client): ManagedEntity.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedEntity._valid_attrs) @cached_property def childEntity(self): return self._get_mor("childEntity", True) @cached_property def childType(self): return self._get_dataobject("childType", True) class GuestAuthManager(ManagedObject): _valid_attrs = set([]) def __init__(self, mo_ref, client): ManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObject._valid_attrs) class GuestFileManager(ManagedObject): _valid_attrs = set([]) def __init__(self, mo_ref, client): ManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObject._valid_attrs) class GuestOperationsManager(ManagedObject): _valid_attrs = set(['authManager', 'fileManager', 'processManager']) def __init__(self, mo_ref, client): ManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObject._valid_attrs) @cached_property def authManager(self): return self._get_mor("authManager", False) @cached_property def fileManager(self): return self._get_mor("fileManager", False) @cached_property def processManager(self): return self._get_mor("processManager", False) class GuestProcessManager(ManagedObject): _valid_attrs = set([]) def __init__(self, mo_ref, client): ManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObject._valid_attrs) class HostAuthenticationStore(ManagedObject): _valid_attrs = set(['info']) def __init__(self, mo_ref, client): ManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObject._valid_attrs) @cached_property def info(self): return self._get_dataobject("info", False) class HostDirectoryStore(HostAuthenticationStore): _valid_attrs = set([]) def __init__(self, mo_ref, client): HostAuthenticationStore.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, HostAuthenticationStore._valid_attrs) class HostActiveDirectoryAuthentication(HostDirectoryStore): _valid_attrs = set([]) def __init__(self, mo_ref, client): HostDirectoryStore.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, HostDirectoryStore._valid_attrs) class HostAuthenticationManager(ManagedObject): _valid_attrs = set(['info', 'supportedStore']) def __init__(self, mo_ref, client): ManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObject._valid_attrs) @cached_property def info(self): return self._get_dataobject("info", False) @cached_property def supportedStore(self): return self._get_mor("supportedStore", True) class HostAutoStartManager(ManagedObject): _valid_attrs = set(['config']) def __init__(self, mo_ref, client): ManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObject._valid_attrs) @cached_property def config(self): return self._get_dataobject("config", False) class HostBootDeviceSystem(ManagedObject): _valid_attrs = set([]) def __init__(self, mo_ref, client): ManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObject._valid_attrs) class HostCacheConfigurationManager(ManagedObject): _valid_attrs = set(['cacheConfigurationInfo']) def __init__(self, mo_ref, client): ManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObject._valid_attrs) @cached_property def cacheConfigurationInfo(self): return self._get_dataobject("cacheConfigurationInfo", True) class HostCpuSchedulerSystem(ExtensibleManagedObject): _valid_attrs = set(['hyperthreadInfo']) def __init__(self, mo_ref, client): ExtensibleManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ExtensibleManagedObject._valid_attrs) @cached_property def hyperthreadInfo(self): return self._get_dataobject("hyperthreadInfo", False) class HostDatastoreBrowser(ManagedObject): _valid_attrs = set(['datastore', 'supportedType']) def __init__(self, mo_ref, client): ManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObject._valid_attrs) @cached_property def datastore(self): return self._get_mor("datastore", True) @cached_property def supportedType(self): return self._get_dataobject("supportedType", True) class HostDatastoreSystem(ManagedObject): _valid_attrs = set(['capabilities', 'datastore']) def __init__(self, mo_ref, client): ManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObject._valid_attrs) @cached_property def capabilities(self): return self._get_dataobject("capabilities", False) @cached_property def datastore(self): return self._get_mor("datastore", True) class HostDateTimeSystem(ManagedObject): _valid_attrs = set(['dateTimeInfo']) def __init__(self, mo_ref, client): ManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObject._valid_attrs) @cached_property def dateTimeInfo(self): return self._get_dataobject("dateTimeInfo", False) class HostDiagnosticSystem(ManagedObject): _valid_attrs = set(['activePartition']) def __init__(self, mo_ref, client): ManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObject._valid_attrs) @cached_property def activePartition(self): return self._get_dataobject("activePartition", False) class HostEsxAgentHostManager(ManagedObject): _valid_attrs = set(['configInfo']) def __init__(self, mo_ref, client): ManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObject._valid_attrs) @cached_property def configInfo(self): return self._get_dataobject("configInfo", False) class HostFirewallSystem(ExtensibleManagedObject): _valid_attrs = set(['firewallInfo']) def __init__(self, mo_ref, client): ExtensibleManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ExtensibleManagedObject._valid_attrs) @cached_property def firewallInfo(self): return self._get_dataobject("firewallInfo", False) class HostFirmwareSystem(ManagedObject): _valid_attrs = set([]) def __init__(self, mo_ref, client): ManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObject._valid_attrs) class HostHealthStatusSystem(ManagedObject): _valid_attrs = set(['runtime']) def __init__(self, mo_ref, client): ManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObject._valid_attrs) @cached_property def runtime(self): return self._get_dataobject("runtime", False) class HostImageConfigManager(ManagedObject): _valid_attrs = set([]) def __init__(self, mo_ref, client): ManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObject._valid_attrs) class HostKernelModuleSystem(ManagedObject): _valid_attrs = set([]) def __init__(self, mo_ref, client): ManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObject._valid_attrs) class HostLocalAccountManager(ManagedObject): _valid_attrs = set([]) def __init__(self, mo_ref, client): ManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObject._valid_attrs) class HostLocalAuthentication(HostAuthenticationStore): _valid_attrs = set([]) def __init__(self, mo_ref, client): HostAuthenticationStore.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, HostAuthenticationStore._valid_attrs) class HostMemorySystem(ExtensibleManagedObject): _valid_attrs = set(['consoleReservationInfo', 'virtualMachineReservationInfo']) def __init__(self, mo_ref, client): ExtensibleManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ExtensibleManagedObject._valid_attrs) @cached_property def consoleReservationInfo(self): return self._get_dataobject("consoleReservationInfo", False) @cached_property def virtualMachineReservationInfo(self): return self._get_dataobject("virtualMachineReservationInfo", False) class HostNetworkSystem(ExtensibleManagedObject): _valid_attrs = set(['capabilities', 'consoleIpRouteConfig', 'dnsConfig', 'ipRouteConfig', 'networkConfig', 'networkInfo', 'offloadCapabilities']) def __init__(self, mo_ref, client): ExtensibleManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ExtensibleManagedObject._valid_attrs) @cached_property def capabilities(self): return self._get_dataobject("capabilities", False) @cached_property def consoleIpRouteConfig(self): return self._get_dataobject("consoleIpRouteConfig", False) @cached_property def dnsConfig(self): return self._get_dataobject("dnsConfig", False) @cached_property def ipRouteConfig(self): return self._get_dataobject("ipRouteConfig", False) @cached_property def networkConfig(self): return self._get_dataobject("networkConfig", False) @cached_property def networkInfo(self): return self._get_dataobject("networkInfo", False) @cached_property def offloadCapabilities(self): return self._get_dataobject("offloadCapabilities", False) class HostPatchManager(ManagedObject): _valid_attrs = set([]) def __init__(self, mo_ref, client): ManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObject._valid_attrs) class HostPciPassthruSystem(ExtensibleManagedObject): _valid_attrs = set(['pciPassthruInfo']) def __init__(self, mo_ref, client): ExtensibleManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ExtensibleManagedObject._valid_attrs) @cached_property def pciPassthruInfo(self): return self._get_dataobject("pciPassthruInfo", True) class HostPowerSystem(ManagedObject): _valid_attrs = set(['capability', 'info']) def __init__(self, mo_ref, client): ManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObject._valid_attrs) @cached_property def capability(self): return self._get_dataobject("capability", False) @cached_property def info(self): return self._get_dataobject("info", False) class HostProfile(Profile): _valid_attrs = set(['referenceHost']) def __init__(self, mo_ref, client): Profile.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, Profile._valid_attrs) @cached_property def referenceHost(self): return self._get_mor("referenceHost", False) class HostProfileManager(ProfileManager): _valid_attrs = set([]) def __init__(self, mo_ref, client): ProfileManager.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ProfileManager._valid_attrs) class HostServiceSystem(ExtensibleManagedObject): _valid_attrs = set(['serviceInfo']) def __init__(self, mo_ref, client): ExtensibleManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ExtensibleManagedObject._valid_attrs) @cached_property def serviceInfo(self): return self._get_dataobject("serviceInfo", False) class HostSnmpSystem(ManagedObject): _valid_attrs = set(['configuration', 'limits']) def __init__(self, mo_ref, client): ManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObject._valid_attrs) @cached_property def configuration(self): return self._get_dataobject("configuration", False) @cached_property def limits(self): return self._get_dataobject("limits", False) class HostStorageSystem(ExtensibleManagedObject): _valid_attrs = set(['fileSystemVolumeInfo', 'multipathStateInfo', 'storageDeviceInfo', 'systemFile']) def __init__(self, mo_ref, client): ExtensibleManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ExtensibleManagedObject._valid_attrs) @cached_property def fileSystemVolumeInfo(self): return self._get_dataobject("fileSystemVolumeInfo", False) @cached_property def multipathStateInfo(self): return self._get_dataobject("multipathStateInfo", False) @cached_property def storageDeviceInfo(self): return self._get_dataobject("storageDeviceInfo", False) @cached_property def systemFile(self): return self._get_dataobject("systemFile", True) class HostSystem(ManagedEntity): _valid_attrs = set(['capability', 'config', 'configManager', 'datastore', 'datastoreBrowser', 'hardware', 'licensableResource', 'network', 'runtime', 'summary', 'systemResources', 'vm']) def __init__(self, mo_ref, client): ManagedEntity.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedEntity._valid_attrs) @cached_property def capability(self): return self._get_dataobject("capability", False) @cached_property def config(self): return self._get_dataobject("config", False) @cached_property def configManager(self): return self._get_dataobject("configManager", False) @cached_property def datastore(self): return self._get_mor("datastore", True) @cached_property def datastoreBrowser(self): return self._get_mor("datastoreBrowser", False) @cached_property def licensableResource(self): return self._get_dataobject("licensableResource", False) @cached_property def hardware(self): return self._get_dataobject("hardware", False) @cached_property def network(self): return self._get_mor("network", True) @cached_property def runtime(self): return self._get_dataobject("runtime", False) @cached_property def summary(self): return self._get_dataobject("summary", False) @cached_property def systemResources(self): return self._get_dataobject("systemResources", False) @cached_property def vm(self): return self._get_mor("vm", True) class HostVirtualNicManager(ExtensibleManagedObject): _valid_attrs = set(['info']) def __init__(self, mo_ref, client): ExtensibleManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ExtensibleManagedObject._valid_attrs) @cached_property def info(self): return self._get_dataobject("info", False) class HostVMotionSystem(ExtensibleManagedObject): _valid_attrs = set(['ipConfig', 'netConfig']) def __init__(self, mo_ref, client): ExtensibleManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ExtensibleManagedObject._valid_attrs) @cached_property def ipConfig(self): return self._get_dataobject("ipConfig", False) @cached_property def netConfig(self): return self._get_dataobject("netConfig", False) class HttpNfcLease(ManagedObject): _valid_attrs = set(['error', 'info', 'initializeProgress', 'state']) def __init__(self, mo_ref, client): ManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObject._valid_attrs) @cached_property def error(self): return self._get_dataobject("error", False) @cached_property def info(self): return self._get_dataobject("info", False) @cached_property def initializeProgress(self): return self._get_dataobject("initializeProgress", False) @cached_property def state(self): return self._get_dataobject("state", False) class InventoryView(ManagedObjectView): _valid_attrs = set([]) def __init__(self, mo_ref, client): ManagedObjectView.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObjectView._valid_attrs) class IpPoolManager(ManagedObject): _valid_attrs = set([]) def __init__(self, mo_ref, client): ManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObject._valid_attrs) class IscsiManager(ManagedObject): _valid_attrs = set([]) def __init__(self, mo_ref, client): ManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObject._valid_attrs) class LicenseAssignmentManager(ManagedObject): _valid_attrs = set([]) def __init__(self, mo_ref, client): ManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObject._valid_attrs) class LicenseManager(ManagedObject): _valid_attrs = set(['diagnostics', 'evaluation', 'featureInfo', 'licenseAssignmentManager', 'licensedEdition', 'licenses', 'source', 'sourceAvailable']) def __init__(self, mo_ref, client): ManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObject._valid_attrs) @cached_property def diagnostics(self): return self._get_dataobject("diagnostics", False) @cached_property def evaluation(self): return self._get_dataobject("evaluation", False) @cached_property def featureInfo(self): return self._get_dataobject("featureInfo", True) @cached_property def licenseAssignmentManager(self): return self._get_mor("licenseAssignmentManager", False) @cached_property def licensedEdition(self): return self._get_dataobject("licensedEdition", False) @cached_property def licenses(self): return self._get_dataobject("licenses", True) @cached_property def source(self): return self._get_dataobject("source", False) @cached_property def sourceAvailable(self): return self._get_dataobject("sourceAvailable", False) class ListView(ManagedObjectView): _valid_attrs = set([]) def __init__(self, mo_ref, client): ManagedObjectView.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObjectView._valid_attrs) class LocalizationManager(ManagedObject): _valid_attrs = set(['catalog']) def __init__(self, mo_ref, client): ManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObject._valid_attrs) @cached_property def catalog(self): return self._get_dataobject("catalog", True) class OptionManager(ManagedObject): _valid_attrs = set(['setting', 'supportedOption']) def __init__(self, mo_ref, client): ManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObject._valid_attrs) @cached_property def setting(self): return self._get_dataobject("setting", True) @cached_property def supportedOption(self): return self._get_dataobject("supportedOption", True) class OvfManager(ManagedObject): _valid_attrs = set([]) def __init__(self, mo_ref, client): ManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObject._valid_attrs) class PerformanceManager(ManagedObject): _valid_attrs = set(['description', 'historicalInterval', 'perfCounter']) def __init__(self, mo_ref, client): ManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObject._valid_attrs) @cached_property def description(self): return self._get_dataobject("description", False) @cached_property def historicalInterval(self): return self._get_dataobject("historicalInterval", True) @cached_property def perfCounter(self): return self._get_dataobject("perfCounter", True) class ProfileComplianceManager(ManagedObject): _valid_attrs = set([]) def __init__(self, mo_ref, client): ManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObject._valid_attrs) class PropertyCollector(ManagedObject): _valid_attrs = set(['filter']) def __init__(self, mo_ref, client): ManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObject._valid_attrs) @cached_property def filter(self): return self._get_mor("filter", True) class PropertyFilter(ManagedObject): _valid_attrs = set(['partialUpdates', 'spec']) def __init__(self, mo_ref, client): ManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObject._valid_attrs) @cached_property def partialUpdates(self): return self._get_dataobject("partialUpdates", False) @cached_property def spec(self): return self._get_dataobject("spec", False) class ResourcePlanningManager(ManagedObject): _valid_attrs = set([]) def __init__(self, mo_ref, client): ManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObject._valid_attrs) class ResourcePool(ManagedEntity): _valid_attrs = set(['childConfiguration', 'config', 'owner', 'resourcePool', 'runtime', 'summary', 'vm']) def __init__(self, mo_ref, client): ManagedEntity.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedEntity._valid_attrs) @cached_property def childConfiguration(self): return self._get_dataobject("childConfiguration", True) @cached_property def config(self): return self._get_dataobject("config", False) @cached_property def owner(self): return self._get_mor("owner", False) @cached_property def resourcePool(self): return self._get_mor("resourcePool", True) @cached_property def runtime(self): return self._get_dataobject("runtime", False) @cached_property def summary(self): return self._get_dataobject("summary", False) @cached_property def vm(self): return self._get_mor("vm", True) class ScheduledTask(ExtensibleManagedObject): _valid_attrs = set(['info']) def __init__(self, mo_ref, client): ExtensibleManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ExtensibleManagedObject._valid_attrs) @cached_property def info(self): return self._get_dataobject("info", False) class ScheduledTaskManager(ManagedObject): _valid_attrs = set(['description', 'scheduledTask']) def __init__(self, mo_ref, client): ManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObject._valid_attrs) @cached_property def description(self): return self._get_dataobject("description", False) @cached_property def scheduledTask(self): return self._get_mor("scheduledTask", True) class SearchIndex(ManagedObject): _valid_attrs = set([]) def __init__(self, mo_ref, client): ManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObject._valid_attrs) class ServiceInstance(ManagedObject): _valid_attrs = set(['capability', 'content', 'serverClock']) def __init__(self, mo_ref, client): ManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObject._valid_attrs) @cached_property def capability(self): return self._get_dataobject("capability", False) @cached_property def content(self): return self._get_dataobject("content", False) @cached_property def serverClock(self): return self._get_dataobject("serverClock", False) class SessionManager(ManagedObject): _valid_attrs = set(['currentSession', 'defaultLocale', 'message', 'messageLocaleList', 'sessionList', 'supportedLocaleList']) def __init__(self, mo_ref, client): ManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObject._valid_attrs) @cached_property def currentSession(self): return self._get_dataobject("currentSession", False) @cached_property def defaultLocale(self): return self._get_dataobject("defaultLocale", False) @cached_property def message(self): return self._get_dataobject("message", False) @cached_property def messageLocaleList(self): return self._get_dataobject("messageLocaleList", True) @cached_property def sessionList(self): return self._get_dataobject("sessionList", True) @cached_property def supportedLocaleList(self): return self._get_dataobject("supportedLocaleList", True) class StoragePod(Folder): _valid_attrs = set(['podStorageDrsEntry', 'summary']) def __init__(self, mo_ref, client): Folder.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, Folder._valid_attrs) @cached_property def podStorageDrsEntry(self): return self._get_dataobject("podStorageDrsEntry", False) @cached_property def summary(self): return self._get_dataobject("summary", False) class StorageResourceManager(ManagedObject): _valid_attrs = set([]) def __init__(self, mo_ref, client): ManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObject._valid_attrs) class Task(ExtensibleManagedObject): _valid_attrs = set(['info']) def __init__(self, mo_ref, client): ExtensibleManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ExtensibleManagedObject._valid_attrs) @cached_property def info(self): return self._get_dataobject("info", False) class TaskHistoryCollector(HistoryCollector): _valid_attrs = set(['latestPage']) def __init__(self, mo_ref, client): HistoryCollector.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, HistoryCollector._valid_attrs) @cached_property def latestPage(self): return self._get_dataobject("latestPage", True) class TaskManager(ManagedObject): _valid_attrs = set(['description', 'maxCollector', 'recentTask']) def __init__(self, mo_ref, client): ManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObject._valid_attrs) @cached_property def description(self): return self._get_dataobject("description", False) @cached_property def maxCollector(self): return self._get_dataobject("maxCollector", False) @cached_property def recentTask(self): return self._get_mor("recentTask", True) class UserDirectory(ManagedObject): _valid_attrs = set(['domainList']) def __init__(self, mo_ref, client): ManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObject._valid_attrs) @cached_property def domainList(self): return self._get_dataobject("domainList", True) class ViewManager(ManagedObject): _valid_attrs = set(['viewList']) def __init__(self, mo_ref, client): ManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObject._valid_attrs) @cached_property def viewList(self): return self._get_mor("viewList", True) class VirtualApp(ResourcePool): _valid_attrs = set(['childLink', 'datastore', 'network', 'parentFolder', 'parentVApp', 'vAppConfig']) def __init__(self, mo_ref, client): ResourcePool.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ResourcePool._valid_attrs) @cached_property def childLink(self): return self._get_dataobject("childLink", True) @cached_property def datastore(self): return self._get_mor("datastore", True) @cached_property def network(self): return self._get_mor("network", True) @cached_property def parentFolder(self): return self._get_mor("parentFolder", False) @cached_property def parentVApp(self): return self._get_mor("parentVApp", False) @cached_property def vAppConfig(self): return self._get_dataobject("vAppConfig", False) class VirtualDiskManager(ManagedObject): _valid_attrs = set([]) def __init__(self, mo_ref, client): ManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObject._valid_attrs) class VirtualizationManager(ManagedObject): _valid_attrs = set([]) def __init__(self, mo_ref, client): ManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObject._valid_attrs) class VirtualMachine(ManagedEntity): _valid_attrs = set(['capability', 'config', 'datastore', 'environmentBrowser', 'guest', 'guestHeartbeatStatus', 'layout', 'layoutEx', 'network', 'parentVApp', 'resourceConfig', 'resourcePool', 'rootSnapshot', 'runtime', 'snapshot', 'storage', 'summary']) def __init__(self, mo_ref, client): ManagedEntity.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedEntity._valid_attrs) @cached_property def capability(self): return self._get_dataobject("capability", False) @cached_property def config(self): return self._get_dataobject("config", False) @cached_property def datastore(self): return self._get_mor("datastore", True) @cached_property def environmentBrowser(self): return self._get_mor("environmentBrowser", False) @cached_property def guest(self): return self._get_dataobject("guest", False) @cached_property def guestHeartbeatStatus(self): return self._get_dataobject("guestHeartbeatStatus", False) @cached_property def layout(self): return self._get_dataobject("layout", False) @cached_property def layoutEx(self): return self._get_dataobject("layoutEx", False) @cached_property def network(self): return self._get_mor("network", True) @cached_property def parentVApp(self): return self._get_mor("parentVApp", False) @cached_property def resourceConfig(self): return self._get_dataobject("resourceConfig", False) @cached_property def resourcePool(self): return self._get_mor("resourcePool", False) @cached_property def rootSnapshot(self): return self._get_mor("rootSnapshot", True) @cached_property def runtime(self): return self._get_dataobject("runtime", False) @cached_property def snapshot(self): return self._get_dataobject("snapshot", False) @cached_property def storage(self): return self._get_dataobject("storage", False) @cached_property def summary(self): return self._get_dataobject("summary", False) class VirtualMachineCompatibilityChecker(ManagedObject): _valid_attrs = set([]) def __init__(self, mo_ref, client): ManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObject._valid_attrs) class VirtualMachineProvisioningChecker(ManagedObject): _valid_attrs = set([]) def __init__(self, mo_ref, client): ManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObject._valid_attrs) class VirtualMachineSnapshot(ExtensibleManagedObject): _valid_attrs = set(['childSnapshot', 'config']) def __init__(self, mo_ref, client): ExtensibleManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ExtensibleManagedObject._valid_attrs) @cached_property def childSnapshot(self): return self._get_mor("childSnapshot", True) @cached_property def config(self): return self._get_dataobject("config", False) class VmwareDistributedVirtualSwitch(DistributedVirtualSwitch): _valid_attrs = set([]) def __init__(self, mo_ref, client): DistributedVirtualSwitch.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, DistributedVirtualSwitch._valid_attrs) classmap = dict((x.__name__, x) for x in ( ExtensibleManagedObject, Alarm, AlarmManager, AuthorizationManager, ManagedEntity, ComputeResource, ClusterComputeResource, Profile, ClusterProfile, ProfileManager, ClusterProfileManager, View, ManagedObjectView, ContainerView, CustomFieldsManager, CustomizationSpecManager, Datacenter, Datastore, DiagnosticManager, Network, DistributedVirtualPortgroup, DistributedVirtualSwitch, DistributedVirtualSwitchManager, EnvironmentBrowser, HistoryCollector, EventHistoryCollector, EventManager, ExtensionManager, FileManager, Folder, GuestAuthManager, GuestFileManager, GuestOperationsManager, GuestProcessManager, HostAuthenticationStore, HostDirectoryStore, HostActiveDirectoryAuthentication, HostAuthenticationManager, HostAutoStartManager, HostBootDeviceSystem, HostCacheConfigurationManager, HostCpuSchedulerSystem, HostDatastoreBrowser, HostDatastoreSystem, HostDateTimeSystem, HostDiagnosticSystem, HostEsxAgentHostManager, HostFirewallSystem, HostFirmwareSystem, HostHealthStatusSystem, HostImageConfigManager, HostKernelModuleSystem, HostLocalAccountManager, HostLocalAuthentication, HostMemorySystem, HostNetworkSystem, HostPatchManager, HostPciPassthruSystem, HostPowerSystem, HostProfile, HostProfileManager, HostServiceSystem, HostSnmpSystem, HostStorageSystem, HostSystem, HostVirtualNicManager, HostVMotionSystem, HttpNfcLease, InventoryView, IpPoolManager, IscsiManager, LicenseAssignmentManager, LicenseManager, ListView, LocalizationManager, OptionManager, OvfManager, PerformanceManager, ProfileComplianceManager, PropertyCollector, PropertyFilter, ResourcePlanningManager, ResourcePool, ScheduledTask, ScheduledTaskManager, SearchIndex, ServiceInstance, SessionManager, StoragePod, StorageResourceManager, Task, TaskHistoryCollector, TaskManager, UserDirectory, ViewManager, VirtualApp, VirtualDiskManager, VirtualizationManager, VirtualMachine, VirtualMachineCompatibilityChecker, VirtualMachineProvisioningChecker, VirtualMachineSnapshot, VmwareDistributedVirtualSwitch )) def classmapper(name): return classmap[name] psphere-0.5.2/psphere/scripting.py000066400000000000000000000074401212743422200172120ustar00rootroot00000000000000 """ Parse command line options, allow users to append their own options and read predefined configuration from the users .visdkrc file. """ # Copyright 2010 Jonathan Kinred # # Licensed under the Apache License, Version 2.0 (the "License"); you may not # use this file except in compliance with the License. You may obtain a copy # of the License at: # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import optparse class BaseScript(object): def __init__(self, client): self.client = client self.required_opts = [] usage = ('usage: %prog --url https:///sdk --username ' '--password ') self.parser = optparse.OptionParser(usage) self.parser.add_option('--url', dest='url', help='the url of the vSphere server') self.parser.add_option('--username', dest='username', help='the username to connnect with') self.parser.add_option('--password', dest='password', help='the password to connect with') def add_option(self, opt, dest, help, required): self.parser.add_option(opt, dest=dest, help=help) # TODO: Append to usage # Add to the list of required options which we'll use later if required: self.required_opts.append(dest) def get_options(self): """Get the options that have been set. Called after the user has added all their own options and is ready to use the variables. """ (options, args) = self.parser.parse_args() # Set values from .visdkrc, but only if they haven't already been set visdkrc_opts = self.read_visdkrc() for opt in self.config_vars: if not getattr(options, opt): # Try and use value from visdkrc if visdkrc_opts: if opt in visdkrc_opts: setattr(options, opt, visdkrc_opts[opt]) # Ensure all the required options are set for opt in self.required_opts: if opt not in dir(options) or getattr(options, opt) == None: self.parser.error('%s must be set!' % opt) return options def read_visdkrc(self): try: config = open(self.visdkrc) except IOError, e: if e.errno == 2: # Doesn't exist, ignore it return None elif e.errno == 13: print('ERROR: Permission denied opening %s' % self.visdkrc) return None else: print('ERROR: Could not open %s: %s' % (self.visdkrc, e.strerror)) return None lines = config.readlines() config.close() parsed_opts = {} for line in lines: (key, value) = line.split('=') parsed_opts[key] = value.rstrip('\n') visdkrc_opts = {} if('VI_PROTOCOL' in parsed_opts and 'VI_SERVER' in parsed_opts and 'VI_SERVICEPATH' in parsed_opts): visdkrc_opts['url'] = '%s://%s%s' % (parsed_opts['VI_PROTOCOL'], parsed_opts['VI_SERVER'], parsed_opts['VI_SERVICEPATH']) if 'VI_USERNAME' in parsed_opts: visdkrc_opts['username'] = parsed_opts['VI_USERNAME'] if 'VI_PASSWORD' in parsed_opts: visdkrc_opts['password'] = parsed_opts['VI_PASSWORD'] return visdkrc_opts psphere-0.5.2/psphere/soap.py000066400000000000000000000057671212743422200161640ustar00rootroot00000000000000""" A leaky wrapper for the underlying suds library. """ # Copyright 2010 Jonathan Kinred # # Licensed under the Apache License, Version 2.0 (the "License"); you may not # use this file except in compliance with the License. You may obtain a copy # of the License at: # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import logging import urllib2 import suds from pprint import pprint logger = logging.getLogger(__name__) class VimFault(Exception): def __init__(self, fault): self.fault = fault self.fault_type = fault.__class__.__name__ self._fault_dict = {} for attr in fault: self._fault_dict[attr[0]] = attr[1] Exception.__init__(self, "%s: %s" % (self.fault_type, self._fault_dict)) def get_client(url): client = suds.client.Client(url + "/vimService.wsdl") client.set_options(location=url) return client def create(client, _type, **kwargs): """Create a suds object of the requested _type.""" obj = client.factory.create("ns0:%s" % _type) for key, value in kwargs.items(): setattr(obj, key, value) return obj def invoke(client, method, **kwargs): """Invoke a method on the underlying soap service.""" try: # Proxy the method to the suds service result = getattr(client.service, method)(**kwargs) except AttributeError, e: logger.critical("Unknown method: %s", method) raise except urllib2.URLError, e: logger.debug(pprint(e)) logger.debug("A URL related error occurred while invoking the '%s' " "method on the VIM server, this can be caused by " "name resolution or connection problems.", method) logger.debug("The underlying error is: %s", e.reason[1]) raise except suds.client.TransportError, e: logger.debug(pprint(e)) logger.debug("TransportError: %s", e) except suds.WebFault, e: # Get the type of fault logger.critical("SUDS Fault: %s" % e.fault.faultstring) if len(e.fault.faultstring) > 0: raise detail = e.document.childAtPath("/Envelope/Body/Fault/detail") fault_type = detail.getChildren()[0].name fault = create(fault_type) if isinstance(e.fault.detail[0], list): for attr in e.fault.detail[0]: setattr(fault, attr[0], attr[1]) else: fault["text"] = e.fault.detail[0] raise VimFault(fault) return result class ManagedObjectReference(suds.sudsobject.Property): """Custom class to replace the suds generated class, which lacks _type.""" def __init__(self, _type, value): suds.sudsobject.Property.__init__(self, value) self._type = _type psphere-0.5.2/psphere/template.py000066400000000000000000000032021212743422200170130ustar00rootroot00000000000000import glob import os import yaml import logging from psphere import config from psphere.errors import TemplateNotFoundError logger = logging.getLogger(__name__) template_path = os.path.expanduser(config._config_value("general", "template_dir")) def _merge(first, second): """Merge a list of templates. The templates will be merged with values in higher templates taking precedence. :param templates: The templates to merge. :type templates: list """ return dict(first.items() + second.items()) def load_template(name=None): """Loads a template of the specified name. Templates are placed in the directory in YAML format with a .yaml extension. If no name is specified then the function will return the default template (/default.yaml) if it exists. :param name: The name of the template to load. :type name: str or None (default) """ if name is None: name = "default" logger.info("Loading template with name %s", name) try: template_file = open("%s/%s.yaml" % (template_path, name)) except IOError: raise TemplateNotFoundError template = yaml.safe_load(template_file) template_file.close() if "extends" in template: logger.debug("Merging %s with %s", name, template["extends"]) template = _merge(load_template(template["extends"]), template) return template def list_templates(): """Returns a list of all templates.""" templates = [f for f in glob.glob(os.path.join(template_path, '*.yaml'))] return templates psphere-0.5.2/psphere/wsdl/000077500000000000000000000000001212743422200156025ustar00rootroot00000000000000psphere-0.5.2/psphere/wsdl/core-types.xsd000066400000000000000000000222141212743422200204150ustar00rootroot00000000000000 psphere-0.5.2/psphere/wsdl/query-messagetypes.xsd000066400000000000000000000064771212743422200222140ustar00rootroot00000000000000 psphere-0.5.2/psphere/wsdl/query-types.xsd000066400000000000000000000236501212743422200206370ustar00rootroot00000000000000 psphere-0.5.2/psphere/wsdl/vim-messagetypes.xsd000066400000000000000000004104041212743422200216270ustar00rootroot00000000000000 psphere-0.5.2/psphere/wsdl/vim-types.xsd000066400000000000000000033462031212743422200202720ustar00rootroot00000000000000 psphere-0.5.2/psphere/wsdl/vim.wsdl000066400000000000000000033545471212743422200173150ustar00rootroot00000000000000 psphere-0.5.2/psphere/wsdl/vimService.wsdl000066400000000000000000000010611212743422200206070ustar00rootroot00000000000000 psphere-0.5.2/python-psphere.spec.in000066400000000000000000000020101212743422200174220ustar00rootroot00000000000000Summary: vSphere SDK for Python Name: python-psphere Version: @VERSION@ Release: 1%{?dist} Source0: %{name}-%{version}.tar.gz License: ASL 2.0 Group: Development/Libraries BuildRoot: %{_tmppath}/%{name}-%{version}-%{release}-buildroot Prefix: %{_prefix} BuildArch: noarch Url: http://jkinred.bitbucket.org/psphere BuildRequires: python-setuptools Requires: python-suds %description This is a simple Python binding for elements of the vsphere SOAP-API %prep %setup -n %{name}-%{version} -n %{name}-%{version} %build python setup.py build %install python setup.py install -O1 --root=$RPM_BUILD_ROOT --record=INSTALLED_FILES %clean rm -rf $RPM_BUILD_ROOT %files -f INSTALLED_FILES %defattr(-,root,root) %changelog * Thu Mar 15 2012 Ian McLeod - 0.1-5 - Remove Vendor field from SPEC file * Fri Jan 20 2012 Ian McLeod - 0.1-4 - Add DistributedVirtualPortgroup to support new style distributed switches * Wed Jun 08 2011 Richard Su - 0.1-3 - pull new upstream version psphere-0.5.2/requirements.txt000066400000000000000000000000141212743422200164420ustar00rootroot00000000000000suds PyYAML psphere-0.5.2/resources/000077500000000000000000000000001212743422200151755ustar00rootroot00000000000000psphere-0.5.2/resources/class_generator.py000066400000000000000000000033261212743422200207260ustar00rootroot00000000000000import yaml managed_objects = yaml.safe_load(open("managed_object_graph.yaml")) header_text = "from psphere import ManagedObject, cached_property\n\n" footer_text = "classmap = dict((x.__name__, x) for x in (\n" # Basic text to import these base classes from psphere body_text = "" for i, mo in enumerate(managed_objects): if mo["extends"] is None: mo["extends"] = "ManagedObject" body_text += "class %s(%s):\n" % (mo["name"], mo["extends"]) props = [] for prop in mo["properties"]: props.append("%s" % prop["name"]) body_text += " _valid_attrs = set(%s)\n" % props body_text += " def __init__(self, mo_ref, client):\n" body_text += " %s.__init__(self, mo_ref, client)\n" % (mo["extends"]) body_text += (" self._valid_attrs = set.union(self._valid_attrs, %s._valid_attrs)\n" % mo["extends"]) for prop in mo["properties"]: body_text += " @cached_property\n" body_text += " def %s(self):\n" % prop["name"] if prop["mor"] is True: body_text += (" return self._get_mor(\"%s\", %s)\n" % (prop["name"], prop["multivalue"])) else: body_text += (" return self._get_dataobject(\"%s\", %s)\n" % (prop["name"], prop["multivalue"])) body_text += "\n\n" footer_text += " %s" % mo["name"] # Put a comma at the end of every line but the last if i < (len(managed_objects) - 1): footer_text += ",\n" else: footer_text += "\n" footer_text += "))\n" footer_text += "def classmapper(name):\n" footer_text += " return classmap[name]" f = open("output.py", "w") f.write(header_text) f.write(body_text) f.write(footer_text) f.close() psphere-0.5.2/resources/generate_managedobjects.py000077500000000000000000000146421212743422200224010ustar00rootroot00000000000000#!/usr/bin/python """A script that parses vSphere API documentation and generates a YAML dump of the Managed Object's and their properties. It expects to run from the SDK/doc/ReferenceGuide/ directory and is quite kludgy so I expect that it is highly version dependent. """ # Copyright 2010 Jonathan Kinred from BeautifulSoup import BeautifulSoup import yaml # This file is the starting point for managed objects f = open("index-mo_types.html") contents = BeautifulSoup(f.read()) f.close() #
    's with these attributes are the ones that contain managed objects mo_divs = contents.findAll(name="div", attrs={"id": ["AE", "FJ", "KO", "PT", "UZ"]}) # Collect the parsed managed object's in this list unordered_managed_objects = [] # Here, we look at all the
    's, find the file which it links to, # opens it and parses the information inside for div in mo_divs: # The node contain the stuff we want for a in div.findAll("a"): # Collect the parsed managed object in this dict mo = {} mo["name"] = str(a.string) print("Generating information for %s" % mo["name"]) # Open up the HTML page for the MO and load a new BS data structure print("Opening %s for parsing" % a["href"]) f = open(a["href"]) mo_contents = BeautifulSoup(f.read()) f.close() # Search through all the
    's at the top of the page and # see if any of them refer to MO's that this MO extends for dt in mo_contents.findAll("dt"): # Set the extends key to the name of the MO this MO # extends, otherwise set it to None if dt.string == "Extends": mo["extends"] = str(dt.nextSibling.nextSibling.a.string) print("%s extends %s" % (mo["name"], mo["extends"])) # No need to process any further
    tags break else: mo["extends"] = None # Locate the table that contains the properties for p in mo_contents.findAll("p", attrs={"class": "table-title"}): if p.string == "Properties": prop_table = p.nextSibling.nextSibling # Collect the properties of this MO in this list mo["properties"] = [] for tr in prop_table.findAll("tr", attrs={"class": ["r0", "r1"]}): # Arrgh! Use this kludge to skip over the # "Properties inherited from" rows at the bottom of the table if tr.td.attrs[0][1] == u"3": continue # The with the nowrap attribute set to 1 is what we want prop_td = tr.findAll("td", attrs={"nowrap": 1})[0] # Collect the info about the property in this dict property = {} property["name"] = str(prop_td.strong.string) print("Parsing %s property" % property["name"]) # If the nextSibling along has a string, it should # be a string like xsd:xxxx, in which case there won't # be any tag linking somewhere else. In this case # we use it as our mo_type otherwise we get the string # of the nextSibling's tag as our mo_type if prop_td.nextSibling.string is not None: mo_type = prop_td.nextSibling.string else: mo_type = prop_td.nextSibling.a.string # If the mo_type starts with this, then it's a # MOR, otherwise it's a DataObject, Enum or complexType if mo_type.startswith("ManagedObjectReference"): property["mor"] = True else: property["mor"] = False # If the mo_type ends with [] then it's a list if mo_type.endswith("[]"): property["multivalue"] = True else: property["multivalue"] = False # Append this property to the MO's property list mo["properties"].append(property) # Append this MO to the list of MO's unordered_managed_objects.append(mo) print("\n") managed_objects = [] added_mos = [] for mo in unordered_managed_objects: print("Looking at %s" % mo["name"]) # If this MO has already been added (by a dependent MO) then # just skip over it here if mo["name"] in added_mos: print("%s is already added" % mo["name"]) continue # If this MO doesn't extend another or the MO that it extends # has already been added to the list, then this MO can be added # and report that it has been added if mo["extends"] is None or mo["extends"] in added_mos: print("MO has no dependencies or dependency %s already added" % mo["extends"]) managed_objects.append(mo) added_mos.append(mo["name"]) continue print("%s has unadded dependency %s" % (mo["name"], mo["extends"])) # We have an MO that extends another and the one that it extends # hasn't been added yet, so here we must add the extended MO for mo2 in unordered_managed_objects: print("Seeing if %s is the dependency" % mo2["name"]) if mo2["name"] == mo["extends"]: print("%s is the dependency, seeing if it has a dependency" % mo2["name"]) if mo2["extends"] is None or mo2["extends"] in added_mos: managed_objects.append(mo2) added_mos.append(mo2["name"]) break else: print("Dependency of dependency not added, adding it") for mo3 in unordered_managed_objects: print("Seeing if %s is the dependency" % mo3["name"]) if mo3["name"] == mo2["extends"]: print("%s is the dependency" % mo3["name"]) if mo3["extends"] is not None and mo3["extends"] not in added_mos: print("ERROR: Uncaptured 3rd level dependency!") exit() managed_objects.append(mo3) added_mos.append(mo3["name"]) break if mo2["extends"] is None or mo2["extends"] in added_mos: managed_objects.append(mo2) added_mos.append(mo2["name"]) break # Now that we've added our dependency we can add ourself managed_objects.append(mo) added_mos.append(mo["name"]) outfile = open("managed_object_graph.yaml", "w") yaml.dump(managed_objects, outfile) outfile.close() psphere-0.5.2/resources/managed_object_graph.yaml000066400000000000000000000426401212743422200221720ustar00rootroot00000000000000- extends: null name: ExtensibleManagedObject properties: - {mor: false, multivalue: true, name: availableField} - {mor: false, multivalue: true, name: value} - extends: ExtensibleManagedObject name: Alarm properties: - {mor: false, multivalue: false, name: info} - extends: null name: AlarmManager properties: - {mor: false, multivalue: true, name: defaultExpression} - {mor: false, multivalue: false, name: description} - extends: null name: AuthorizationManager properties: - {mor: false, multivalue: false, name: description} - {mor: false, multivalue: true, name: privilegeList} - {mor: false, multivalue: true, name: roleList} - extends: ExtensibleManagedObject name: ManagedEntity properties: - {mor: false, multivalue: false, name: alarmActionsEnabled} - {mor: false, multivalue: true, name: configIssue} - {mor: false, multivalue: false, name: configStatus} - {mor: false, multivalue: true, name: customValue} - {mor: false, multivalue: true, name: declaredAlarmState} - {mor: false, multivalue: true, name: disabledMethod} - {mor: false, multivalue: true, name: effectiveRole} - {mor: false, multivalue: false, name: name} - {mor: false, multivalue: false, name: overallStatus} - {mor: true, multivalue: false, name: parent} - {mor: false, multivalue: true, name: permission} - {mor: true, multivalue: true, name: recentTask} - {mor: false, multivalue: true, name: tag} - {mor: false, multivalue: true, name: triggeredAlarmState} - extends: ManagedEntity name: ComputeResource properties: - {mor: false, multivalue: false, name: configurationEx} - {mor: true, multivalue: true, name: datastore} - {mor: true, multivalue: false, name: environmentBrowser} - {mor: true, multivalue: true, name: host} - {mor: true, multivalue: true, name: network} - {mor: true, multivalue: false, name: resourcePool} - {mor: false, multivalue: false, name: summary} - extends: ComputeResource name: ClusterComputeResource properties: - {mor: false, multivalue: true, name: actionHistory} - {mor: false, multivalue: false, name: configuration} - {mor: false, multivalue: true, name: drsFault} - {mor: false, multivalue: true, name: drsRecommendation} - {mor: false, multivalue: true, name: migrationHistory} - {mor: false, multivalue: true, name: recommendation} - extends: null name: Profile properties: - {mor: false, multivalue: false, name: complianceStatus} - {mor: false, multivalue: false, name: config} - {mor: false, multivalue: false, name: createdTime} - {mor: false, multivalue: false, name: description} - {mor: true, multivalue: true, name: entity} - {mor: false, multivalue: false, name: modifiedTime} - {mor: false, multivalue: false, name: name} - extends: Profile name: ClusterProfile properties: [] - extends: null name: ProfileManager properties: - {mor: true, multivalue: true, name: profile} - extends: ProfileManager name: ClusterProfileManager properties: [] - extends: null name: View properties: [] - extends: View name: ManagedObjectView properties: - {mor: true, multivalue: true, name: view} - extends: ManagedObjectView name: ContainerView properties: - {mor: true, multivalue: false, name: container} - {mor: false, multivalue: false, name: recursive} - {mor: false, multivalue: true, name: type} - extends: null name: CustomFieldsManager properties: - {mor: false, multivalue: true, name: field} - extends: null name: CustomizationSpecManager properties: - {mor: false, multivalue: true, name: encryptionKey} - {mor: false, multivalue: true, name: info} - extends: ManagedEntity name: Datacenter properties: - {mor: true, multivalue: true, name: datastore} - {mor: true, multivalue: false, name: datastoreFolder} - {mor: true, multivalue: false, name: hostFolder} - {mor: true, multivalue: true, name: network} - {mor: true, multivalue: false, name: networkFolder} - {mor: true, multivalue: false, name: vmFolder} - extends: ManagedEntity name: Datastore properties: - {mor: true, multivalue: false, name: browser} - {mor: false, multivalue: false, name: capability} - {mor: false, multivalue: true, name: host} - {mor: false, multivalue: false, name: info} - {mor: false, multivalue: false, name: iormConfiguration} - {mor: false, multivalue: false, name: summary} - {mor: true, multivalue: true, name: vm} - extends: null name: DiagnosticManager properties: [] - extends: ManagedEntity name: Network properties: - {mor: true, multivalue: true, name: host} - {mor: false, multivalue: false, name: name} - {mor: false, multivalue: false, name: summary} - {mor: true, multivalue: true, name: vm} - extends: Network name: DistributedVirtualPortgroup properties: - {mor: false, multivalue: false, name: config} - {mor: false, multivalue: false, name: key} - {mor: false, multivalue: true, name: portKeys} - extends: ManagedEntity name: DistributedVirtualSwitch properties: - {mor: false, multivalue: false, name: capability} - {mor: false, multivalue: false, name: config} - {mor: false, multivalue: true, name: networkResourcePool} - {mor: true, multivalue: true, name: portgroup} - {mor: false, multivalue: false, name: summary} - {mor: false, multivalue: false, name: uuid} - extends: null name: DistributedVirtualSwitchManager properties: [] - extends: null name: EnvironmentBrowser properties: - {mor: true, multivalue: false, name: datastoreBrowser} - extends: null name: HistoryCollector properties: - {mor: false, multivalue: false, name: filter} - extends: HistoryCollector name: EventHistoryCollector properties: - {mor: false, multivalue: true, name: latestPage} - extends: null name: EventManager properties: - {mor: false, multivalue: false, name: description} - {mor: false, multivalue: false, name: latestEvent} - {mor: false, multivalue: false, name: maxCollector} - extends: null name: ExtensionManager properties: - {mor: false, multivalue: true, name: extensionList} - extends: null name: FileManager properties: [] - extends: ManagedEntity name: Folder properties: - {mor: true, multivalue: true, name: childEntity} - {mor: false, multivalue: true, name: childType} - extends: null name: GuestAuthManager properties: [] - extends: null name: GuestFileManager properties: [] - extends: null name: GuestOperationsManager properties: - {mor: true, multivalue: false, name: authManager} - {mor: true, multivalue: false, name: fileManager} - {mor: true, multivalue: false, name: processManager} - extends: null name: GuestProcessManager properties: [] - extends: null name: HostAuthenticationStore properties: - {mor: false, multivalue: false, name: info} - extends: HostAuthenticationStore name: HostDirectoryStore properties: [] - extends: HostDirectoryStore name: HostActiveDirectoryAuthentication properties: [] - extends: null name: HostAuthenticationManager properties: - {mor: false, multivalue: false, name: info} - {mor: true, multivalue: true, name: supportedStore} - extends: null name: HostAutoStartManager properties: - {mor: false, multivalue: false, name: config} - extends: null name: HostBootDeviceSystem properties: [] - extends: null name: HostCacheConfigurationManager properties: - {mor: false, multivalue: true, name: cacheConfigurationInfo} - extends: ExtensibleManagedObject name: HostCpuSchedulerSystem properties: - {mor: false, multivalue: false, name: hyperthreadInfo} - extends: null name: HostDatastoreBrowser properties: - {mor: true, multivalue: true, name: datastore} - {mor: false, multivalue: true, name: supportedType} - extends: null name: HostDatastoreSystem properties: - {mor: false, multivalue: false, name: capabilities} - {mor: true, multivalue: true, name: datastore} - extends: null name: HostDateTimeSystem properties: - {mor: false, multivalue: false, name: dateTimeInfo} - extends: null name: HostDiagnosticSystem properties: - {mor: false, multivalue: false, name: activePartition} - extends: null name: HostEsxAgentHostManager properties: - {mor: false, multivalue: false, name: configInfo} - extends: ExtensibleManagedObject name: HostFirewallSystem properties: - {mor: false, multivalue: false, name: firewallInfo} - extends: null name: HostFirmwareSystem properties: [] - extends: null name: HostHealthStatusSystem properties: - {mor: false, multivalue: false, name: runtime} - extends: null name: HostImageConfigManager properties: [] - extends: null name: HostKernelModuleSystem properties: [] - extends: null name: HostLocalAccountManager properties: [] - extends: HostAuthenticationStore name: HostLocalAuthentication properties: [] - extends: ExtensibleManagedObject name: HostMemorySystem properties: - {mor: false, multivalue: false, name: consoleReservationInfo} - {mor: false, multivalue: false, name: virtualMachineReservationInfo} - extends: ExtensibleManagedObject name: HostNetworkSystem properties: - {mor: false, multivalue: false, name: capabilities} - {mor: false, multivalue: false, name: consoleIpRouteConfig} - {mor: false, multivalue: false, name: dnsConfig} - {mor: false, multivalue: false, name: ipRouteConfig} - {mor: false, multivalue: false, name: networkConfig} - {mor: false, multivalue: false, name: networkInfo} - {mor: false, multivalue: false, name: offloadCapabilities} - extends: null name: HostPatchManager properties: [] - extends: ExtensibleManagedObject name: HostPciPassthruSystem properties: - {mor: false, multivalue: true, name: pciPassthruInfo} - extends: null name: HostPowerSystem properties: - {mor: false, multivalue: false, name: capability} - {mor: false, multivalue: false, name: info} - extends: Profile name: HostProfile properties: - {mor: true, multivalue: false, name: referenceHost} - extends: ProfileManager name: HostProfileManager properties: [] - extends: ExtensibleManagedObject name: HostServiceSystem properties: - {mor: false, multivalue: false, name: serviceInfo} - extends: null name: HostSnmpSystem properties: - {mor: false, multivalue: false, name: configuration} - {mor: false, multivalue: false, name: limits} - extends: ExtensibleManagedObject name: HostStorageSystem properties: - {mor: false, multivalue: false, name: fileSystemVolumeInfo} - {mor: false, multivalue: false, name: multipathStateInfo} - {mor: false, multivalue: false, name: storageDeviceInfo} - {mor: false, multivalue: true, name: systemFile} - extends: ManagedEntity name: HostSystem properties: - {mor: false, multivalue: false, name: capability} - {mor: false, multivalue: false, name: config} - {mor: false, multivalue: false, name: configManager} - {mor: true, multivalue: true, name: datastore} - {mor: true, multivalue: false, name: datastoreBrowser} - {mor: false, multivalue: false, name: hardware} - {mor: false, multivalue: false, name: licensableResource} - {mor: true, multivalue: true, name: network} - {mor: false, multivalue: false, name: runtime} - {mor: false, multivalue: false, name: summary} - {mor: false, multivalue: false, name: systemResources} - {mor: true, multivalue: true, name: vm} - extends: ExtensibleManagedObject name: HostVirtualNicManager properties: - {mor: false, multivalue: false, name: info} - extends: ExtensibleManagedObject name: HostVMotionSystem properties: - {mor: false, multivalue: false, name: ipConfig} - {mor: false, multivalue: false, name: netConfig} - extends: null name: HttpNfcLease properties: - {mor: false, multivalue: false, name: error} - {mor: false, multivalue: false, name: info} - {mor: false, multivalue: false, name: initializeProgress} - {mor: false, multivalue: false, name: state} - extends: ManagedObjectView name: InventoryView properties: [] - extends: null name: IpPoolManager properties: [] - extends: null name: IscsiManager properties: [] - extends: null name: LicenseAssignmentManager properties: [] - extends: null name: LicenseManager properties: - {mor: false, multivalue: false, name: diagnostics} - {mor: false, multivalue: false, name: evaluation} - {mor: false, multivalue: true, name: featureInfo} - {mor: true, multivalue: false, name: licenseAssignmentManager} - {mor: false, multivalue: false, name: licensedEdition} - {mor: false, multivalue: true, name: licenses} - {mor: false, multivalue: false, name: source} - {mor: false, multivalue: false, name: sourceAvailable} - extends: ManagedObjectView name: ListView properties: [] - extends: null name: LocalizationManager properties: - {mor: false, multivalue: true, name: catalog} - extends: null name: OptionManager properties: - {mor: false, multivalue: true, name: setting} - {mor: false, multivalue: true, name: supportedOption} - extends: null name: OvfManager properties: [] - extends: null name: PerformanceManager properties: - {mor: false, multivalue: false, name: description} - {mor: false, multivalue: true, name: historicalInterval} - {mor: false, multivalue: true, name: perfCounter} - extends: null name: ProfileComplianceManager properties: [] - extends: null name: PropertyCollector properties: - {mor: true, multivalue: true, name: filter} - extends: null name: PropertyFilter properties: - {mor: false, multivalue: false, name: partialUpdates} - {mor: false, multivalue: false, name: spec} - extends: null name: ResourcePlanningManager properties: [] - extends: ManagedEntity name: ResourcePool properties: - {mor: false, multivalue: true, name: childConfiguration} - {mor: false, multivalue: false, name: config} - {mor: true, multivalue: false, name: owner} - {mor: true, multivalue: true, name: resourcePool} - {mor: false, multivalue: false, name: runtime} - {mor: false, multivalue: false, name: summary} - {mor: true, multivalue: true, name: vm} - extends: ExtensibleManagedObject name: ScheduledTask properties: - {mor: false, multivalue: false, name: info} - extends: null name: ScheduledTaskManager properties: - {mor: false, multivalue: false, name: description} - {mor: true, multivalue: true, name: scheduledTask} - extends: null name: SearchIndex properties: [] - extends: null name: ServiceInstance properties: - {mor: false, multivalue: false, name: capability} - {mor: false, multivalue: false, name: content} - {mor: false, multivalue: false, name: serverClock} - extends: null name: SessionManager properties: - {mor: false, multivalue: false, name: currentSession} - {mor: false, multivalue: false, name: defaultLocale} - {mor: false, multivalue: false, name: message} - {mor: false, multivalue: true, name: messageLocaleList} - {mor: false, multivalue: true, name: sessionList} - {mor: false, multivalue: true, name: supportedLocaleList} - extends: Folder name: StoragePod properties: - {mor: false, multivalue: false, name: podStorageDrsEntry} - {mor: false, multivalue: false, name: summary} - extends: null name: StorageResourceManager properties: [] - extends: ExtensibleManagedObject name: Task properties: - {mor: false, multivalue: false, name: info} - extends: HistoryCollector name: TaskHistoryCollector properties: - {mor: false, multivalue: true, name: latestPage} - extends: null name: TaskManager properties: - {mor: false, multivalue: false, name: description} - {mor: false, multivalue: false, name: maxCollector} - {mor: true, multivalue: true, name: recentTask} - extends: null name: UserDirectory properties: - {mor: false, multivalue: true, name: domainList} - extends: null name: ViewManager properties: - {mor: true, multivalue: true, name: viewList} - extends: ResourcePool name: VirtualApp properties: - {mor: false, multivalue: true, name: childLink} - {mor: true, multivalue: true, name: datastore} - {mor: true, multivalue: true, name: network} - {mor: true, multivalue: false, name: parentFolder} - {mor: true, multivalue: false, name: parentVApp} - {mor: false, multivalue: false, name: vAppConfig} - extends: null name: VirtualDiskManager properties: [] - extends: null name: VirtualizationManager properties: [] - extends: ManagedEntity name: VirtualMachine properties: - {mor: false, multivalue: false, name: capability} - {mor: false, multivalue: false, name: config} - {mor: true, multivalue: true, name: datastore} - {mor: true, multivalue: false, name: environmentBrowser} - {mor: false, multivalue: false, name: guest} - {mor: false, multivalue: false, name: guestHeartbeatStatus} - {mor: false, multivalue: false, name: layout} - {mor: false, multivalue: false, name: layoutEx} - {mor: true, multivalue: true, name: network} - {mor: true, multivalue: false, name: parentVApp} - {mor: false, multivalue: false, name: resourceConfig} - {mor: true, multivalue: false, name: resourcePool} - {mor: true, multivalue: true, name: rootSnapshot} - {mor: false, multivalue: false, name: runtime} - {mor: false, multivalue: false, name: snapshot} - {mor: false, multivalue: false, name: storage} - {mor: false, multivalue: false, name: summary} - extends: null name: VirtualMachineCompatibilityChecker properties: [] - extends: null name: VirtualMachineProvisioningChecker properties: [] - extends: ExtensibleManagedObject name: VirtualMachineSnapshot properties: - {mor: true, multivalue: true, name: childSnapshot} - {mor: false, multivalue: false, name: config} - extends: DistributedVirtualSwitch name: VmwareDistributedVirtualSwitch properties: [] psphere-0.5.2/resources/output.py000066400000000000000000001473161212743422200171230ustar00rootroot00000000000000from psphere import ManagedObject, cached_property class ExtensibleManagedObject(ManagedObject): _valid_attrs = set(['availableField', 'value']) def __init__(self, mo_ref, client): ManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObject._valid_attrs) @cached_property def availableField(self): return self._get_dataobject("availableField", True) @cached_property def value(self): return self._get_dataobject("value", True) class Alarm(ExtensibleManagedObject): _valid_attrs = set(['info']) def __init__(self, mo_ref, client): ExtensibleManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ExtensibleManagedObject._valid_attrs) @cached_property def info(self): return self._get_dataobject("info", False) class AlarmManager(ManagedObject): _valid_attrs = set(['defaultExpression', 'description']) def __init__(self, mo_ref, client): ManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObject._valid_attrs) @cached_property def defaultExpression(self): return self._get_dataobject("defaultExpression", True) @cached_property def description(self): return self._get_dataobject("description", False) class AuthorizationManager(ManagedObject): _valid_attrs = set(['description', 'privilegeList', 'roleList']) def __init__(self, mo_ref, client): ManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObject._valid_attrs) @cached_property def description(self): return self._get_dataobject("description", False) @cached_property def privilegeList(self): return self._get_dataobject("privilegeList", True) @cached_property def roleList(self): return self._get_dataobject("roleList", True) class ManagedEntity(ExtensibleManagedObject): _valid_attrs = set(['alarmActionsEnabled', 'configIssue', 'configStatus', 'customValue', 'declaredAlarmState', 'disabledMethod', 'effectiveRole', 'name', 'overallStatus', 'parent', 'permission', 'recentTask', 'tag', 'triggeredAlarmState']) def __init__(self, mo_ref, client): ExtensibleManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ExtensibleManagedObject._valid_attrs) @cached_property def alarmActionsEnabled(self): return self._get_dataobject("alarmActionsEnabled", False) @cached_property def configIssue(self): return self._get_dataobject("configIssue", True) @cached_property def configStatus(self): return self._get_dataobject("configStatus", False) @cached_property def customValue(self): return self._get_dataobject("customValue", True) @cached_property def declaredAlarmState(self): return self._get_dataobject("declaredAlarmState", True) @cached_property def disabledMethod(self): return self._get_dataobject("disabledMethod", True) @cached_property def effectiveRole(self): return self._get_dataobject("effectiveRole", True) @cached_property def name(self): return self._get_dataobject("name", False) @cached_property def overallStatus(self): return self._get_dataobject("overallStatus", False) @cached_property def parent(self): return self._get_mor("parent", False) @cached_property def permission(self): return self._get_dataobject("permission", True) @cached_property def recentTask(self): return self._get_mor("recentTask", True) @cached_property def tag(self): return self._get_dataobject("tag", True) @cached_property def triggeredAlarmState(self): return self._get_dataobject("triggeredAlarmState", True) class ComputeResource(ManagedEntity): _valid_attrs = set(['configurationEx', 'datastore', 'environmentBrowser', 'host', 'network', 'resourcePool', 'summary']) def __init__(self, mo_ref, client): ManagedEntity.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedEntity._valid_attrs) @cached_property def configurationEx(self): return self._get_dataobject("configurationEx", False) @cached_property def datastore(self): return self._get_mor("datastore", True) @cached_property def environmentBrowser(self): return self._get_mor("environmentBrowser", False) @cached_property def host(self): return self._get_mor("host", True) @cached_property def network(self): return self._get_mor("network", True) @cached_property def resourcePool(self): return self._get_mor("resourcePool", False) @cached_property def summary(self): return self._get_dataobject("summary", False) class ClusterComputeResource(ComputeResource): _valid_attrs = set(['actionHistory', 'configuration', 'drsFault', 'drsRecommendation', 'migrationHistory', 'recommendation']) def __init__(self, mo_ref, client): ComputeResource.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ComputeResource._valid_attrs) @cached_property def actionHistory(self): return self._get_dataobject("actionHistory", True) @cached_property def configuration(self): return self._get_dataobject("configuration", False) @cached_property def drsFault(self): return self._get_dataobject("drsFault", True) @cached_property def drsRecommendation(self): return self._get_dataobject("drsRecommendation", True) @cached_property def migrationHistory(self): return self._get_dataobject("migrationHistory", True) @cached_property def recommendation(self): return self._get_dataobject("recommendation", True) class Profile(ManagedObject): _valid_attrs = set(['complianceStatus', 'config', 'createdTime', 'description', 'entity', 'modifiedTime', 'name']) def __init__(self, mo_ref, client): ManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObject._valid_attrs) @cached_property def complianceStatus(self): return self._get_dataobject("complianceStatus", False) @cached_property def config(self): return self._get_dataobject("config", False) @cached_property def createdTime(self): return self._get_dataobject("createdTime", False) @cached_property def description(self): return self._get_dataobject("description", False) @cached_property def entity(self): return self._get_mor("entity", True) @cached_property def modifiedTime(self): return self._get_dataobject("modifiedTime", False) @cached_property def name(self): return self._get_dataobject("name", False) class ClusterProfile(Profile): _valid_attrs = set([]) def __init__(self, mo_ref, client): Profile.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, Profile._valid_attrs) class ProfileManager(ManagedObject): _valid_attrs = set(['profile']) def __init__(self, mo_ref, client): ManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObject._valid_attrs) @cached_property def profile(self): return self._get_mor("profile", True) class ClusterProfileManager(ProfileManager): _valid_attrs = set([]) def __init__(self, mo_ref, client): ProfileManager.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ProfileManager._valid_attrs) class View(ManagedObject): _valid_attrs = set([]) def __init__(self, mo_ref, client): ManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObject._valid_attrs) class ManagedObjectView(View): _valid_attrs = set(['view']) def __init__(self, mo_ref, client): View.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, View._valid_attrs) @cached_property def view(self): return self._get_mor("view", True) class ContainerView(ManagedObjectView): _valid_attrs = set(['container', 'recursive', 'type']) def __init__(self, mo_ref, client): ManagedObjectView.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObjectView._valid_attrs) @cached_property def container(self): return self._get_mor("container", False) @cached_property def recursive(self): return self._get_dataobject("recursive", False) @cached_property def type(self): return self._get_dataobject("type", True) class CustomFieldsManager(ManagedObject): _valid_attrs = set(['field']) def __init__(self, mo_ref, client): ManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObject._valid_attrs) @cached_property def field(self): return self._get_dataobject("field", True) class CustomizationSpecManager(ManagedObject): _valid_attrs = set(['encryptionKey', 'info']) def __init__(self, mo_ref, client): ManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObject._valid_attrs) @cached_property def encryptionKey(self): return self._get_dataobject("encryptionKey", True) @cached_property def info(self): return self._get_dataobject("info", True) class Datacenter(ManagedEntity): _valid_attrs = set(['datastore', 'datastoreFolder', 'hostFolder', 'network', 'networkFolder', 'vmFolder']) def __init__(self, mo_ref, client): ManagedEntity.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedEntity._valid_attrs) @cached_property def datastore(self): return self._get_mor("datastore", True) @cached_property def datastoreFolder(self): return self._get_mor("datastoreFolder", False) @cached_property def hostFolder(self): return self._get_mor("hostFolder", False) @cached_property def network(self): return self._get_mor("network", True) @cached_property def networkFolder(self): return self._get_mor("networkFolder", False) @cached_property def vmFolder(self): return self._get_mor("vmFolder", False) class Datastore(ManagedEntity): _valid_attrs = set(['browser', 'capability', 'host', 'info', 'iormConfiguration', 'summary', 'vm']) def __init__(self, mo_ref, client): ManagedEntity.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedEntity._valid_attrs) @cached_property def browser(self): return self._get_mor("browser", False) @cached_property def capability(self): return self._get_dataobject("capability", False) @cached_property def host(self): return self._get_dataobject("host", True) @cached_property def info(self): return self._get_dataobject("info", False) @cached_property def iormConfiguration(self): return self._get_dataobject("iormConfiguration", False) @cached_property def summary(self): return self._get_dataobject("summary", False) @cached_property def vm(self): return self._get_mor("vm", True) class DiagnosticManager(ManagedObject): _valid_attrs = set([]) def __init__(self, mo_ref, client): ManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObject._valid_attrs) class Network(ManagedEntity): _valid_attrs = set(['host', 'name', 'summary', 'vm']) def __init__(self, mo_ref, client): ManagedEntity.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedEntity._valid_attrs) @cached_property def host(self): return self._get_mor("host", True) @cached_property def name(self): return self._get_dataobject("name", False) @cached_property def summary(self): return self._get_dataobject("summary", False) @cached_property def vm(self): return self._get_mor("vm", True) class DistributedVirtualPortgroup(Network): _valid_attrs = set(['config', 'key', 'portKeys']) def __init__(self, mo_ref, client): Network.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, Network._valid_attrs) @cached_property def config(self): return self._get_dataobject("config", False) @cached_property def key(self): return self._get_dataobject("key", False) @cached_property def portKeys(self): return self._get_dataobject("portKeys", True) class DistributedVirtualSwitch(ManagedEntity): _valid_attrs = set(['capability', 'config', 'networkResourcePool', 'portgroup', 'summary', 'uuid']) def __init__(self, mo_ref, client): ManagedEntity.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedEntity._valid_attrs) @cached_property def capability(self): return self._get_dataobject("capability", False) @cached_property def config(self): return self._get_dataobject("config", False) @cached_property def networkResourcePool(self): return self._get_dataobject("networkResourcePool", True) @cached_property def portgroup(self): return self._get_mor("portgroup", True) @cached_property def summary(self): return self._get_dataobject("summary", False) @cached_property def uuid(self): return self._get_dataobject("uuid", False) class DistributedVirtualSwitchManager(ManagedObject): _valid_attrs = set([]) def __init__(self, mo_ref, client): ManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObject._valid_attrs) class EnvironmentBrowser(ManagedObject): _valid_attrs = set(['datastoreBrowser']) def __init__(self, mo_ref, client): ManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObject._valid_attrs) @cached_property def datastoreBrowser(self): return self._get_mor("datastoreBrowser", False) class HistoryCollector(ManagedObject): _valid_attrs = set(['filter']) def __init__(self, mo_ref, client): ManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObject._valid_attrs) @cached_property def filter(self): return self._get_dataobject("filter", False) class EventHistoryCollector(HistoryCollector): _valid_attrs = set(['latestPage']) def __init__(self, mo_ref, client): HistoryCollector.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, HistoryCollector._valid_attrs) @cached_property def latestPage(self): return self._get_dataobject("latestPage", True) class EventManager(ManagedObject): _valid_attrs = set(['description', 'latestEvent', 'maxCollector']) def __init__(self, mo_ref, client): ManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObject._valid_attrs) @cached_property def description(self): return self._get_dataobject("description", False) @cached_property def latestEvent(self): return self._get_dataobject("latestEvent", False) @cached_property def maxCollector(self): return self._get_dataobject("maxCollector", False) class ExtensionManager(ManagedObject): _valid_attrs = set(['extensionList']) def __init__(self, mo_ref, client): ManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObject._valid_attrs) @cached_property def extensionList(self): return self._get_dataobject("extensionList", True) class FileManager(ManagedObject): _valid_attrs = set([]) def __init__(self, mo_ref, client): ManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObject._valid_attrs) class Folder(ManagedEntity): _valid_attrs = set(['childEntity', 'childType']) def __init__(self, mo_ref, client): ManagedEntity.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedEntity._valid_attrs) @cached_property def childEntity(self): return self._get_mor("childEntity", True) @cached_property def childType(self): return self._get_dataobject("childType", True) class GuestAuthManager(ManagedObject): _valid_attrs = set([]) def __init__(self, mo_ref, client): ManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObject._valid_attrs) class GuestFileManager(ManagedObject): _valid_attrs = set([]) def __init__(self, mo_ref, client): ManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObject._valid_attrs) class GuestOperationsManager(ManagedObject): _valid_attrs = set(['authManager', 'fileManager', 'processManager']) def __init__(self, mo_ref, client): ManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObject._valid_attrs) @cached_property def authManager(self): return self._get_mor("authManager", False) @cached_property def fileManager(self): return self._get_mor("fileManager", False) @cached_property def processManager(self): return self._get_mor("processManager", False) class GuestProcessManager(ManagedObject): _valid_attrs = set([]) def __init__(self, mo_ref, client): ManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObject._valid_attrs) class HostAuthenticationStore(ManagedObject): _valid_attrs = set(['info']) def __init__(self, mo_ref, client): ManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObject._valid_attrs) @cached_property def info(self): return self._get_dataobject("info", False) class HostDirectoryStore(HostAuthenticationStore): _valid_attrs = set([]) def __init__(self, mo_ref, client): HostAuthenticationStore.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, HostAuthenticationStore._valid_attrs) class HostActiveDirectoryAuthentication(HostDirectoryStore): _valid_attrs = set([]) def __init__(self, mo_ref, client): HostDirectoryStore.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, HostDirectoryStore._valid_attrs) class HostAuthenticationManager(ManagedObject): _valid_attrs = set(['info', 'supportedStore']) def __init__(self, mo_ref, client): ManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObject._valid_attrs) @cached_property def info(self): return self._get_dataobject("info", False) @cached_property def supportedStore(self): return self._get_mor("supportedStore", True) class HostAutoStartManager(ManagedObject): _valid_attrs = set(['config']) def __init__(self, mo_ref, client): ManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObject._valid_attrs) @cached_property def config(self): return self._get_dataobject("config", False) class HostBootDeviceSystem(ManagedObject): _valid_attrs = set([]) def __init__(self, mo_ref, client): ManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObject._valid_attrs) class HostCacheConfigurationManager(ManagedObject): _valid_attrs = set(['cacheConfigurationInfo']) def __init__(self, mo_ref, client): ManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObject._valid_attrs) @cached_property def cacheConfigurationInfo(self): return self._get_dataobject("cacheConfigurationInfo", True) class HostCpuSchedulerSystem(ExtensibleManagedObject): _valid_attrs = set(['hyperthreadInfo']) def __init__(self, mo_ref, client): ExtensibleManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ExtensibleManagedObject._valid_attrs) @cached_property def hyperthreadInfo(self): return self._get_dataobject("hyperthreadInfo", False) class HostDatastoreBrowser(ManagedObject): _valid_attrs = set(['datastore', 'supportedType']) def __init__(self, mo_ref, client): ManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObject._valid_attrs) @cached_property def datastore(self): return self._get_mor("datastore", True) @cached_property def supportedType(self): return self._get_dataobject("supportedType", True) class HostDatastoreSystem(ManagedObject): _valid_attrs = set(['capabilities', 'datastore']) def __init__(self, mo_ref, client): ManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObject._valid_attrs) @cached_property def capabilities(self): return self._get_dataobject("capabilities", False) @cached_property def datastore(self): return self._get_mor("datastore", True) class HostDateTimeSystem(ManagedObject): _valid_attrs = set(['dateTimeInfo']) def __init__(self, mo_ref, client): ManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObject._valid_attrs) @cached_property def dateTimeInfo(self): return self._get_dataobject("dateTimeInfo", False) class HostDiagnosticSystem(ManagedObject): _valid_attrs = set(['activePartition']) def __init__(self, mo_ref, client): ManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObject._valid_attrs) @cached_property def activePartition(self): return self._get_dataobject("activePartition", False) class HostEsxAgentHostManager(ManagedObject): _valid_attrs = set(['configInfo']) def __init__(self, mo_ref, client): ManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObject._valid_attrs) @cached_property def configInfo(self): return self._get_dataobject("configInfo", False) class HostFirewallSystem(ExtensibleManagedObject): _valid_attrs = set(['firewallInfo']) def __init__(self, mo_ref, client): ExtensibleManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ExtensibleManagedObject._valid_attrs) @cached_property def firewallInfo(self): return self._get_dataobject("firewallInfo", False) class HostFirmwareSystem(ManagedObject): _valid_attrs = set([]) def __init__(self, mo_ref, client): ManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObject._valid_attrs) class HostHealthStatusSystem(ManagedObject): _valid_attrs = set(['runtime']) def __init__(self, mo_ref, client): ManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObject._valid_attrs) @cached_property def runtime(self): return self._get_dataobject("runtime", False) class HostImageConfigManager(ManagedObject): _valid_attrs = set([]) def __init__(self, mo_ref, client): ManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObject._valid_attrs) class HostKernelModuleSystem(ManagedObject): _valid_attrs = set([]) def __init__(self, mo_ref, client): ManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObject._valid_attrs) class HostLocalAccountManager(ManagedObject): _valid_attrs = set([]) def __init__(self, mo_ref, client): ManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObject._valid_attrs) class HostLocalAuthentication(HostAuthenticationStore): _valid_attrs = set([]) def __init__(self, mo_ref, client): HostAuthenticationStore.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, HostAuthenticationStore._valid_attrs) class HostMemorySystem(ExtensibleManagedObject): _valid_attrs = set(['consoleReservationInfo', 'virtualMachineReservationInfo']) def __init__(self, mo_ref, client): ExtensibleManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ExtensibleManagedObject._valid_attrs) @cached_property def consoleReservationInfo(self): return self._get_dataobject("consoleReservationInfo", False) @cached_property def virtualMachineReservationInfo(self): return self._get_dataobject("virtualMachineReservationInfo", False) class HostNetworkSystem(ExtensibleManagedObject): _valid_attrs = set(['capabilities', 'consoleIpRouteConfig', 'dnsConfig', 'ipRouteConfig', 'networkConfig', 'networkInfo', 'offloadCapabilities']) def __init__(self, mo_ref, client): ExtensibleManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ExtensibleManagedObject._valid_attrs) @cached_property def capabilities(self): return self._get_dataobject("capabilities", False) @cached_property def consoleIpRouteConfig(self): return self._get_dataobject("consoleIpRouteConfig", False) @cached_property def dnsConfig(self): return self._get_dataobject("dnsConfig", False) @cached_property def ipRouteConfig(self): return self._get_dataobject("ipRouteConfig", False) @cached_property def networkConfig(self): return self._get_dataobject("networkConfig", False) @cached_property def networkInfo(self): return self._get_dataobject("networkInfo", False) @cached_property def offloadCapabilities(self): return self._get_dataobject("offloadCapabilities", False) class HostPatchManager(ManagedObject): _valid_attrs = set([]) def __init__(self, mo_ref, client): ManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObject._valid_attrs) class HostPciPassthruSystem(ExtensibleManagedObject): _valid_attrs = set(['pciPassthruInfo']) def __init__(self, mo_ref, client): ExtensibleManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ExtensibleManagedObject._valid_attrs) @cached_property def pciPassthruInfo(self): return self._get_dataobject("pciPassthruInfo", True) class HostPowerSystem(ManagedObject): _valid_attrs = set(['capability', 'info']) def __init__(self, mo_ref, client): ManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObject._valid_attrs) @cached_property def capability(self): return self._get_dataobject("capability", False) @cached_property def info(self): return self._get_dataobject("info", False) class HostProfile(Profile): _valid_attrs = set(['referenceHost']) def __init__(self, mo_ref, client): Profile.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, Profile._valid_attrs) @cached_property def referenceHost(self): return self._get_mor("referenceHost", False) class HostProfileManager(ProfileManager): _valid_attrs = set([]) def __init__(self, mo_ref, client): ProfileManager.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ProfileManager._valid_attrs) class HostServiceSystem(ExtensibleManagedObject): _valid_attrs = set(['serviceInfo']) def __init__(self, mo_ref, client): ExtensibleManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ExtensibleManagedObject._valid_attrs) @cached_property def serviceInfo(self): return self._get_dataobject("serviceInfo", False) class HostSnmpSystem(ManagedObject): _valid_attrs = set(['configuration', 'limits']) def __init__(self, mo_ref, client): ManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObject._valid_attrs) @cached_property def configuration(self): return self._get_dataobject("configuration", False) @cached_property def limits(self): return self._get_dataobject("limits", False) class HostStorageSystem(ExtensibleManagedObject): _valid_attrs = set(['fileSystemVolumeInfo', 'multipathStateInfo', 'storageDeviceInfo', 'systemFile']) def __init__(self, mo_ref, client): ExtensibleManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ExtensibleManagedObject._valid_attrs) @cached_property def fileSystemVolumeInfo(self): return self._get_dataobject("fileSystemVolumeInfo", False) @cached_property def multipathStateInfo(self): return self._get_dataobject("multipathStateInfo", False) @cached_property def storageDeviceInfo(self): return self._get_dataobject("storageDeviceInfo", False) @cached_property def systemFile(self): return self._get_dataobject("systemFile", True) class HostSystem(ManagedEntity): _valid_attrs = set(['capability', 'config', 'configManager', 'datastore', 'datastoreBrowser', 'hardware', 'licensableResource', 'network', 'runtime', 'summary', 'systemResources', 'vm']) def __init__(self, mo_ref, client): ManagedEntity.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedEntity._valid_attrs) @cached_property def capability(self): return self._get_dataobject("capability", False) @cached_property def config(self): return self._get_dataobject("config", False) @cached_property def configManager(self): return self._get_dataobject("configManager", False) @cached_property def datastore(self): return self._get_mor("datastore", True) @cached_property def datastoreBrowser(self): return self._get_mor("datastoreBrowser", False) @cached_property def hardware(self): return self._get_dataobject("hardware", False) @cached_property def licensableResource(self): return self._get_dataobject("licensableResource", False) @cached_property def network(self): return self._get_mor("network", True) @cached_property def runtime(self): return self._get_dataobject("runtime", False) @cached_property def summary(self): return self._get_dataobject("summary", False) @cached_property def systemResources(self): return self._get_dataobject("systemResources", False) @cached_property def vm(self): return self._get_mor("vm", True) class HostVirtualNicManager(ExtensibleManagedObject): _valid_attrs = set(['info']) def __init__(self, mo_ref, client): ExtensibleManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ExtensibleManagedObject._valid_attrs) @cached_property def info(self): return self._get_dataobject("info", False) class HostVMotionSystem(ExtensibleManagedObject): _valid_attrs = set(['ipConfig', 'netConfig']) def __init__(self, mo_ref, client): ExtensibleManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ExtensibleManagedObject._valid_attrs) @cached_property def ipConfig(self): return self._get_dataobject("ipConfig", False) @cached_property def netConfig(self): return self._get_dataobject("netConfig", False) class HttpNfcLease(ManagedObject): _valid_attrs = set(['error', 'info', 'initializeProgress', 'state']) def __init__(self, mo_ref, client): ManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObject._valid_attrs) @cached_property def error(self): return self._get_dataobject("error", False) @cached_property def info(self): return self._get_dataobject("info", False) @cached_property def initializeProgress(self): return self._get_dataobject("initializeProgress", False) @cached_property def state(self): return self._get_dataobject("state", False) class InventoryView(ManagedObjectView): _valid_attrs = set([]) def __init__(self, mo_ref, client): ManagedObjectView.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObjectView._valid_attrs) class IpPoolManager(ManagedObject): _valid_attrs = set([]) def __init__(self, mo_ref, client): ManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObject._valid_attrs) class IscsiManager(ManagedObject): _valid_attrs = set([]) def __init__(self, mo_ref, client): ManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObject._valid_attrs) class LicenseAssignmentManager(ManagedObject): _valid_attrs = set([]) def __init__(self, mo_ref, client): ManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObject._valid_attrs) class LicenseManager(ManagedObject): _valid_attrs = set(['diagnostics', 'evaluation', 'featureInfo', 'licenseAssignmentManager', 'licensedEdition', 'licenses', 'source', 'sourceAvailable']) def __init__(self, mo_ref, client): ManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObject._valid_attrs) @cached_property def diagnostics(self): return self._get_dataobject("diagnostics", False) @cached_property def evaluation(self): return self._get_dataobject("evaluation", False) @cached_property def featureInfo(self): return self._get_dataobject("featureInfo", True) @cached_property def licenseAssignmentManager(self): return self._get_mor("licenseAssignmentManager", False) @cached_property def licensedEdition(self): return self._get_dataobject("licensedEdition", False) @cached_property def licenses(self): return self._get_dataobject("licenses", True) @cached_property def source(self): return self._get_dataobject("source", False) @cached_property def sourceAvailable(self): return self._get_dataobject("sourceAvailable", False) class ListView(ManagedObjectView): _valid_attrs = set([]) def __init__(self, mo_ref, client): ManagedObjectView.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObjectView._valid_attrs) class LocalizationManager(ManagedObject): _valid_attrs = set(['catalog']) def __init__(self, mo_ref, client): ManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObject._valid_attrs) @cached_property def catalog(self): return self._get_dataobject("catalog", True) class OptionManager(ManagedObject): _valid_attrs = set(['setting', 'supportedOption']) def __init__(self, mo_ref, client): ManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObject._valid_attrs) @cached_property def setting(self): return self._get_dataobject("setting", True) @cached_property def supportedOption(self): return self._get_dataobject("supportedOption", True) class OvfManager(ManagedObject): _valid_attrs = set([]) def __init__(self, mo_ref, client): ManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObject._valid_attrs) class PerformanceManager(ManagedObject): _valid_attrs = set(['description', 'historicalInterval', 'perfCounter']) def __init__(self, mo_ref, client): ManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObject._valid_attrs) @cached_property def description(self): return self._get_dataobject("description", False) @cached_property def historicalInterval(self): return self._get_dataobject("historicalInterval", True) @cached_property def perfCounter(self): return self._get_dataobject("perfCounter", True) class ProfileComplianceManager(ManagedObject): _valid_attrs = set([]) def __init__(self, mo_ref, client): ManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObject._valid_attrs) class PropertyCollector(ManagedObject): _valid_attrs = set(['filter']) def __init__(self, mo_ref, client): ManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObject._valid_attrs) @cached_property def filter(self): return self._get_mor("filter", True) class PropertyFilter(ManagedObject): _valid_attrs = set(['partialUpdates', 'spec']) def __init__(self, mo_ref, client): ManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObject._valid_attrs) @cached_property def partialUpdates(self): return self._get_dataobject("partialUpdates", False) @cached_property def spec(self): return self._get_dataobject("spec", False) class ResourcePlanningManager(ManagedObject): _valid_attrs = set([]) def __init__(self, mo_ref, client): ManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObject._valid_attrs) class ResourcePool(ManagedEntity): _valid_attrs = set(['childConfiguration', 'config', 'owner', 'resourcePool', 'runtime', 'summary', 'vm']) def __init__(self, mo_ref, client): ManagedEntity.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedEntity._valid_attrs) @cached_property def childConfiguration(self): return self._get_dataobject("childConfiguration", True) @cached_property def config(self): return self._get_dataobject("config", False) @cached_property def owner(self): return self._get_mor("owner", False) @cached_property def resourcePool(self): return self._get_mor("resourcePool", True) @cached_property def runtime(self): return self._get_dataobject("runtime", False) @cached_property def summary(self): return self._get_dataobject("summary", False) @cached_property def vm(self): return self._get_mor("vm", True) class ScheduledTask(ExtensibleManagedObject): _valid_attrs = set(['info']) def __init__(self, mo_ref, client): ExtensibleManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ExtensibleManagedObject._valid_attrs) @cached_property def info(self): return self._get_dataobject("info", False) class ScheduledTaskManager(ManagedObject): _valid_attrs = set(['description', 'scheduledTask']) def __init__(self, mo_ref, client): ManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObject._valid_attrs) @cached_property def description(self): return self._get_dataobject("description", False) @cached_property def scheduledTask(self): return self._get_mor("scheduledTask", True) class SearchIndex(ManagedObject): _valid_attrs = set([]) def __init__(self, mo_ref, client): ManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObject._valid_attrs) class ServiceInstance(ManagedObject): _valid_attrs = set(['capability', 'content', 'serverClock']) def __init__(self, mo_ref, client): ManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObject._valid_attrs) @cached_property def capability(self): return self._get_dataobject("capability", False) @cached_property def content(self): return self._get_dataobject("content", False) @cached_property def serverClock(self): return self._get_dataobject("serverClock", False) class SessionManager(ManagedObject): _valid_attrs = set(['currentSession', 'defaultLocale', 'message', 'messageLocaleList', 'sessionList', 'supportedLocaleList']) def __init__(self, mo_ref, client): ManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObject._valid_attrs) @cached_property def currentSession(self): return self._get_dataobject("currentSession", False) @cached_property def defaultLocale(self): return self._get_dataobject("defaultLocale", False) @cached_property def message(self): return self._get_dataobject("message", False) @cached_property def messageLocaleList(self): return self._get_dataobject("messageLocaleList", True) @cached_property def sessionList(self): return self._get_dataobject("sessionList", True) @cached_property def supportedLocaleList(self): return self._get_dataobject("supportedLocaleList", True) class StoragePod(Folder): _valid_attrs = set(['podStorageDrsEntry', 'summary']) def __init__(self, mo_ref, client): Folder.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, Folder._valid_attrs) @cached_property def podStorageDrsEntry(self): return self._get_dataobject("podStorageDrsEntry", False) @cached_property def summary(self): return self._get_dataobject("summary", False) class StorageResourceManager(ManagedObject): _valid_attrs = set([]) def __init__(self, mo_ref, client): ManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObject._valid_attrs) class Task(ExtensibleManagedObject): _valid_attrs = set(['info']) def __init__(self, mo_ref, client): ExtensibleManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ExtensibleManagedObject._valid_attrs) @cached_property def info(self): return self._get_dataobject("info", False) class TaskHistoryCollector(HistoryCollector): _valid_attrs = set(['latestPage']) def __init__(self, mo_ref, client): HistoryCollector.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, HistoryCollector._valid_attrs) @cached_property def latestPage(self): return self._get_dataobject("latestPage", True) class TaskManager(ManagedObject): _valid_attrs = set(['description', 'maxCollector', 'recentTask']) def __init__(self, mo_ref, client): ManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObject._valid_attrs) @cached_property def description(self): return self._get_dataobject("description", False) @cached_property def maxCollector(self): return self._get_dataobject("maxCollector", False) @cached_property def recentTask(self): return self._get_mor("recentTask", True) class UserDirectory(ManagedObject): _valid_attrs = set(['domainList']) def __init__(self, mo_ref, client): ManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObject._valid_attrs) @cached_property def domainList(self): return self._get_dataobject("domainList", True) class ViewManager(ManagedObject): _valid_attrs = set(['viewList']) def __init__(self, mo_ref, client): ManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObject._valid_attrs) @cached_property def viewList(self): return self._get_mor("viewList", True) class VirtualApp(ResourcePool): _valid_attrs = set(['childLink', 'datastore', 'network', 'parentFolder', 'parentVApp', 'vAppConfig']) def __init__(self, mo_ref, client): ResourcePool.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ResourcePool._valid_attrs) @cached_property def childLink(self): return self._get_dataobject("childLink", True) @cached_property def datastore(self): return self._get_mor("datastore", True) @cached_property def network(self): return self._get_mor("network", True) @cached_property def parentFolder(self): return self._get_mor("parentFolder", False) @cached_property def parentVApp(self): return self._get_mor("parentVApp", False) @cached_property def vAppConfig(self): return self._get_dataobject("vAppConfig", False) class VirtualDiskManager(ManagedObject): _valid_attrs = set([]) def __init__(self, mo_ref, client): ManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObject._valid_attrs) class VirtualizationManager(ManagedObject): _valid_attrs = set([]) def __init__(self, mo_ref, client): ManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObject._valid_attrs) class VirtualMachine(ManagedEntity): _valid_attrs = set(['capability', 'config', 'datastore', 'environmentBrowser', 'guest', 'guestHeartbeatStatus', 'layout', 'layoutEx', 'network', 'parentVApp', 'resourceConfig', 'resourcePool', 'rootSnapshot', 'runtime', 'snapshot', 'storage', 'summary']) def __init__(self, mo_ref, client): ManagedEntity.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedEntity._valid_attrs) @cached_property def capability(self): return self._get_dataobject("capability", False) @cached_property def config(self): return self._get_dataobject("config", False) @cached_property def datastore(self): return self._get_mor("datastore", True) @cached_property def environmentBrowser(self): return self._get_mor("environmentBrowser", False) @cached_property def guest(self): return self._get_dataobject("guest", False) @cached_property def guestHeartbeatStatus(self): return self._get_dataobject("guestHeartbeatStatus", False) @cached_property def layout(self): return self._get_dataobject("layout", False) @cached_property def layoutEx(self): return self._get_dataobject("layoutEx", False) @cached_property def network(self): return self._get_mor("network", True) @cached_property def parentVApp(self): return self._get_mor("parentVApp", False) @cached_property def resourceConfig(self): return self._get_dataobject("resourceConfig", False) @cached_property def resourcePool(self): return self._get_mor("resourcePool", False) @cached_property def rootSnapshot(self): return self._get_mor("rootSnapshot", True) @cached_property def runtime(self): return self._get_dataobject("runtime", False) @cached_property def snapshot(self): return self._get_dataobject("snapshot", False) @cached_property def storage(self): return self._get_dataobject("storage", False) @cached_property def summary(self): return self._get_dataobject("summary", False) class VirtualMachineCompatibilityChecker(ManagedObject): _valid_attrs = set([]) def __init__(self, mo_ref, client): ManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObject._valid_attrs) class VirtualMachineProvisioningChecker(ManagedObject): _valid_attrs = set([]) def __init__(self, mo_ref, client): ManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ManagedObject._valid_attrs) class VirtualMachineSnapshot(ExtensibleManagedObject): _valid_attrs = set(['childSnapshot', 'config']) def __init__(self, mo_ref, client): ExtensibleManagedObject.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, ExtensibleManagedObject._valid_attrs) @cached_property def childSnapshot(self): return self._get_mor("childSnapshot", True) @cached_property def config(self): return self._get_dataobject("config", False) class VmwareDistributedVirtualSwitch(DistributedVirtualSwitch): _valid_attrs = set([]) def __init__(self, mo_ref, client): DistributedVirtualSwitch.__init__(self, mo_ref, client) self._valid_attrs = set.union(self._valid_attrs, DistributedVirtualSwitch._valid_attrs) classmap = dict((x.__name__, x) for x in ( ExtensibleManagedObject, Alarm, AlarmManager, AuthorizationManager, ManagedEntity, ComputeResource, ClusterComputeResource, Profile, ClusterProfile, ProfileManager, ClusterProfileManager, View, ManagedObjectView, ContainerView, CustomFieldsManager, CustomizationSpecManager, Datacenter, Datastore, DiagnosticManager, Network, DistributedVirtualPortgroup, DistributedVirtualSwitch, DistributedVirtualSwitchManager, EnvironmentBrowser, HistoryCollector, EventHistoryCollector, EventManager, ExtensionManager, FileManager, Folder, GuestAuthManager, GuestFileManager, GuestOperationsManager, GuestProcessManager, HostAuthenticationStore, HostDirectoryStore, HostActiveDirectoryAuthentication, HostAuthenticationManager, HostAutoStartManager, HostBootDeviceSystem, HostCacheConfigurationManager, HostCpuSchedulerSystem, HostDatastoreBrowser, HostDatastoreSystem, HostDateTimeSystem, HostDiagnosticSystem, HostEsxAgentHostManager, HostFirewallSystem, HostFirmwareSystem, HostHealthStatusSystem, HostImageConfigManager, HostKernelModuleSystem, HostLocalAccountManager, HostLocalAuthentication, HostMemorySystem, HostNetworkSystem, HostPatchManager, HostPciPassthruSystem, HostPowerSystem, HostProfile, HostProfileManager, HostServiceSystem, HostSnmpSystem, HostStorageSystem, HostSystem, HostVirtualNicManager, HostVMotionSystem, HttpNfcLease, InventoryView, IpPoolManager, IscsiManager, LicenseAssignmentManager, LicenseManager, ListView, LocalizationManager, OptionManager, OvfManager, PerformanceManager, ProfileComplianceManager, PropertyCollector, PropertyFilter, ResourcePlanningManager, ResourcePool, ScheduledTask, ScheduledTaskManager, SearchIndex, ServiceInstance, SessionManager, StoragePod, StorageResourceManager, Task, TaskHistoryCollector, TaskManager, UserDirectory, ViewManager, VirtualApp, VirtualDiskManager, VirtualizationManager, VirtualMachine, VirtualMachineCompatibilityChecker, VirtualMachineProvisioningChecker, VirtualMachineSnapshot, VmwareDistributedVirtualSwitch )) def classmapper(name): return classmap[name]psphere-0.5.2/resources/working.xml000066400000000000000000000056421212743422200174060ustar00rootroot00000000000000 group-v3 sdi6as1app01 sles10_64Guest Auto-provisioned by pSphere [owen:storage2] 1 4096 add 0 0 0 noSharing add create 0 [owen:storage2] persistent true 0 0 12582912 add 2 AE_SDFDIE VLAN network-18 true true false 1 generated resgroup-392 psphere-0.5.2/scripts/000077500000000000000000000000001212743422200146525ustar00rootroot00000000000000psphere-0.5.2/scripts/make_release.py000066400000000000000000000077101212743422200176460ustar00rootroot00000000000000#!/usr/bin/env python # -*- coding: utf-8 -*- """ make-release ~~~~~~~~~~~~ Helper script that performs a release. Does pretty much everything automatically for us. :copyright: (c) 2011 by Armin Ronacher. :license: BSD, see LICENSE for more details. """ import sys import os import re from datetime import datetime, date from subprocess import Popen, PIPE def parse_changelog(): with open('CHANGES') as f: lineiter = iter(f) for line in lineiter: match = re.search('^Version\s+(.*)', line.strip()) if match is None: continue length = len(match.group(1)) version = match.group(1).strip() if lineiter.next().count('-') != len(match.group(0)): continue while 1: change_info = lineiter.next().strip() if change_info: break match = re.search(r'released on (\w+\s+\d+\w+\s+\d+)', change_info) if match is None: continue datestr, _foo = match.groups() print(datestr) return version, parse_date(datestr) def bump_version(version): try: parts = map(int, version.split('.')) except ValueError: fail('Current version is not numeric') parts[-1] += 1 return '.'.join(map(str, parts)) def parse_date(string): string = string.replace('th ', ' ').replace('nd ', ' ') \ .replace('rd ', ' ').replace('st ', ' ') return datetime.strptime(string, '%B %d %Y') def set_filename_version(filename, version_number, pattern): changed = [] def inject_version(match): before, old, after = match.groups() changed.append(True) return before + version_number + after with open(filename) as f: contents = re.sub(r"^(\s*%s\s*=\s*')(.+?)(')(?sm)" % pattern, inject_version, f.read()) if not changed: fail('Could not find %s in %s', pattern, filename) with open(filename, 'w') as f: f.write(contents) def set_init_version(version): info('Setting __init__.py version to %s', version) set_filename_version('werkzeug/__init__.py', version, '__version__') def set_setup_version(version): info('Setting setup.py version to %s', version) set_filename_version('setup.py', version, 'version') def build_and_upload(): Popen([sys.executable, 'setup.py', 'release', 'sdist', 'upload']).wait() def fail(message, *args): print >> sys.stderr, 'Error:', message % args sys.exit(1) def info(message, *args): print >> sys.stderr, message % args def get_git_tags(): return set(Popen(['git', 'tag'], stdout=PIPE).communicate()[0].splitlines()) def git_is_clean(): return Popen(['git', 'diff', '--quiet']).wait() == 0 def make_git_commit(message, *args): message = message % args Popen(['git', 'commit', '-am', message]).wait() def make_git_tag(tag): info('Tagging "%s"', tag) Popen(['git', 'tag', tag]).wait() def main(): os.chdir(os.path.join(os.path.dirname(__file__), '..')) rv = parse_changelog() if rv is None: fail('Could not parse changelog') version, release_date, codename = rv dev_version = bump_version(version) + '-dev' info('Releasing %s (codename %s, release date %s)', version, codename, release_date.strftime('%d/%m/%Y')) tags = get_git_tags() if version in tags: fail('Version "%s" is already tagged', version) if release_date.date() != date.today(): fail('Release date is not today (%s != %s)') if not git_is_clean(): fail('You have uncommitted changes in git') set_init_version(version) set_setup_version(version) make_git_commit('Bump version number to %s', version) make_git_tag(version) build_and_upload() set_init_version(dev_version) set_setup_version(dev_version) if __name__ == '__main__': main() psphere-0.5.2/setup.cfg000066400000000000000000000000571212743422200150060ustar00rootroot00000000000000[upload_sphinx] upload-dir = build/sphinx/html psphere-0.5.2/setup.py000077500000000000000000000012741212743422200147040ustar00rootroot00000000000000#!/usr/bin/env python import os from setuptools import setup def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup(name="psphere", version="0.5.2", description="vSphere SDK for Python", long_description=read("README.rst"), author="Jonathan Kinred", author_email="jonathan.kinred@gmail.com", url="https://github.com/jkinred/psphere", packages=["psphere"], package_data={"psphere": ["wsdl/*"]}, install_requires=["suds", "PyYAML"], keywords=["vsphere", "vmware"], classifiers=["Development Status :: 4 - Beta", "License :: OSI Approved :: Apache Software License"], )