python3: string formatting
remove all old style string formatting from Soapadapter.py and move to .format() syntax for python 3 compatibility partial https://github.com/vmware/pyvmomi/issues/55
This commit is contained in:
committed by
Shawn Hartsock
parent
05552044f6
commit
95c9a70471
@@ -1,11 +1,11 @@
|
||||
# VMware vSphere Python SDK
|
||||
# Copyright (c) 2008-2014 VMware, Inc. All Rights Reserved.
|
||||
# Copyright (c) 2008-2013 VMware, Inc. All Rights Reserved.
|
||||
#
|
||||
# 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
|
||||
# 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,
|
||||
@@ -19,10 +19,10 @@ from six import u
|
||||
|
||||
import sys
|
||||
import os
|
||||
import time
|
||||
import socket
|
||||
import subprocess
|
||||
import thread
|
||||
import time
|
||||
import urlparse
|
||||
from datetime import datetime
|
||||
from xml.parsers.expat import ParserCreate
|
||||
@@ -49,41 +49,41 @@ CONNECTION_POOL_IDLE_TIMEOUT_SEC = 900
|
||||
NS_SEP = " "
|
||||
|
||||
XML_ENCODING = 'UTF-8'
|
||||
XML_HEADER = '<?xml version="1.0" encoding="%s"?>' % XML_ENCODING
|
||||
XML_HEADER = '<?xml version="1.0" encoding="{0}"?>'.format(XML_ENCODING)
|
||||
|
||||
XMLNS_SOAPENC = "http://schemas.xmlsoap.org/soap/encoding/"
|
||||
XMLNS_SOAPENV = "http://schemas.xmlsoap.org/soap/envelope/"
|
||||
|
||||
XSI_TYPE = XMLNS_XSI + NS_SEP + u'type'
|
||||
XSI_TYPE = XMLNS_XSI + NS_SEP + u('type')
|
||||
|
||||
# Note: Must make a copy to use the SOAP_NSMAP
|
||||
# TODO: Change to frozendict, if available
|
||||
SOAP_NSMAP = { XMLNS_SOAPENC: 'soapenc', XMLNS_SOAPENV: 'soapenv',
|
||||
XMLNS_XSI: 'xsi', XMLNS_XSD: 'xsd' }
|
||||
|
||||
SOAP_ENVELOPE_TAG="%s:Envelope" % SOAP_NSMAP[XMLNS_SOAPENV]
|
||||
SOAP_HEADER_TAG="%s:Header" % SOAP_NSMAP[XMLNS_SOAPENV]
|
||||
SOAP_FAULT_TAG="%s:Fault" % SOAP_NSMAP[XMLNS_SOAPENV]
|
||||
SOAP_BODY_TAG="%s:Body" % SOAP_NSMAP[XMLNS_SOAPENV]
|
||||
SOAP_ENVELOPE_TAG = "{0}:Envelope".format(SOAP_NSMAP[XMLNS_SOAPENV])
|
||||
SOAP_HEADER_TAG = "{0}:Header".format(SOAP_NSMAP[XMLNS_SOAPENV])
|
||||
SOAP_FAULT_TAG = "{0}:Fault".format(SOAP_NSMAP[XMLNS_SOAPENV])
|
||||
SOAP_BODY_TAG = "{0}:Body".format(SOAP_NSMAP[XMLNS_SOAPENV])
|
||||
|
||||
SOAP_ENVELOPE_START = '<%s ' % SOAP_ENVELOPE_TAG + \
|
||||
' '.join(['xmlns:' + prefix + '="' + urn + '"' \
|
||||
for urn, prefix in SOAP_NSMAP.iteritems()]) + \
|
||||
SOAP_ENVELOPE_START = '<{0} '.format(SOAP_ENVELOPE_TAG) + \
|
||||
' '.join(['xmlns:' + prefix + '="' + urn + '"' \
|
||||
for urn, prefix in SOAP_NSMAP.iteritems()]) + \
|
||||
'>\n'
|
||||
SOAP_ENVELOPE_END = "\n</%s>" % (SOAP_ENVELOPE_TAG)
|
||||
SOAP_HEADER_START="<%s>" % SOAP_HEADER_TAG
|
||||
SOAP_HEADER_END="</%s>" % SOAP_HEADER_TAG
|
||||
SOAP_BODY_START="<%s>" % SOAP_BODY_TAG
|
||||
SOAP_BODY_END="</%s>" % SOAP_BODY_TAG
|
||||
SOAP_ENVELOPE_END = "\n</{0}>".format(SOAP_ENVELOPE_TAG)
|
||||
SOAP_HEADER_START = "<{0}>".format(SOAP_HEADER_TAG)
|
||||
SOAP_HEADER_END = "</{0}>".format(SOAP_HEADER_TAG)
|
||||
SOAP_BODY_START = "<{0}>".format(SOAP_BODY_TAG)
|
||||
SOAP_BODY_END = "</{0}>".format(SOAP_BODY_TAG)
|
||||
SOAP_START = SOAP_ENVELOPE_START + SOAP_BODY_START + '\n'
|
||||
SOAP_END = '\n' + SOAP_BODY_END + SOAP_ENVELOPE_END
|
||||
|
||||
WSSE_PREFIX="wsse"
|
||||
WSSE_HEADER_TAG="%s:Security" % WSSE_PREFIX
|
||||
WSSE_NS_URL="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"
|
||||
WSSE_NS='xmlns:%s="%s"' % (WSSE_PREFIX, WSSE_NS_URL)
|
||||
WSSE_HEADER_START="<%s %s>" % (WSSE_HEADER_TAG, WSSE_NS)
|
||||
WSSE_HEADER_END="</%s>" % WSSE_HEADER_TAG
|
||||
WSSE_PREFIX = "wsse"
|
||||
WSSE_HEADER_TAG = "{0}:Security".format(WSSE_PREFIX)
|
||||
WSSE_NS_URL = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"
|
||||
WSSE_NS = 'xmlns:{0}="{1}"'.format(WSSE_PREFIX, WSSE_NS_URL)
|
||||
WSSE_HEADER_START = "<{0} {1}>".format(WSSE_HEADER_TAG, WSSE_NS)
|
||||
WSSE_HEADER_END = "</{0}>".format(WSSE_HEADER_TAG)
|
||||
|
||||
## MethodFault type
|
||||
MethodFault = GetVmodlType("vmodl.MethodFault")
|
||||
@@ -155,7 +155,7 @@ def SerializeFaultDetail(val, info=None, version=None, nsMap=None, encoding=None
|
||||
if version is None:
|
||||
try:
|
||||
if not isinstance(val, MethodFault):
|
||||
raise TypeError('%s is not a MethodFault' % str(val))
|
||||
raise TypeError('{0} is not a MethodFault'.format(str(val)))
|
||||
version = val._version
|
||||
except AttributeError:
|
||||
version = BASE_VERSION
|
||||
@@ -197,7 +197,7 @@ class SoapSerializer:
|
||||
prefix = self.nsMap.get(ns)
|
||||
if not prefix:
|
||||
prefix = nsPrefix
|
||||
self.outermostAttrs += ' xmlns:%s="%s"' % (prefix, ns)
|
||||
self.outermostAttrs += ' xmlns:{0}="{1}"'.format(prefix, ns)
|
||||
self.nsMap = self.nsMap.copy()
|
||||
self.nsMap[ns] = prefix
|
||||
setattr(self, attrName, prefix + ":")
|
||||
@@ -243,7 +243,7 @@ class SoapSerializer:
|
||||
except KeyError:
|
||||
# We have not seen this ns before
|
||||
prefix = ns.split(':', 1)[-1]
|
||||
attr = ' xmlns:%s="%s"' % (prefix, ns)
|
||||
attr = ' xmlns:{0}="{1}"'.format(prefix, ns)
|
||||
return attr, prefix and prefix + ':' + name or name
|
||||
|
||||
## Serialize an object (internal)
|
||||
@@ -260,17 +260,17 @@ class SoapSerializer:
|
||||
if info.flags & F_OPTIONAL:
|
||||
return
|
||||
else:
|
||||
raise TypeError('Field "%s" is not optional' % info.name)
|
||||
raise TypeError('Field "{0}" is not optional'.format(info.name))
|
||||
elif isinstance(val, list) and len(val) == 0:
|
||||
if info.type is object:
|
||||
# Make sure an empty array assigned to Any is typed
|
||||
if not isinstance(val, Array):
|
||||
raise TypeError('Field "%s": Cannot assign empty native python array to an Any' % info.name)
|
||||
raise TypeError('Field "{0}": Cannot assign empty native python array to an Any'.format(info.name))
|
||||
elif info.flags & F_OPTIONAL:
|
||||
# Skip optional non-Any
|
||||
return
|
||||
else:
|
||||
raise TypeError('Field "%s" is not optional' % info.name)
|
||||
raise TypeError('Field "{0}" not optional'.format(info.name))
|
||||
|
||||
if self.outermostAttrs:
|
||||
attr = self.outermostAttrs
|
||||
@@ -281,7 +281,7 @@ class SoapSerializer:
|
||||
# Emit default ns if tag ns is not the same
|
||||
currTagNS = GetWsdlNamespace(info.version)
|
||||
if currTagNS != defNS:
|
||||
attr += ' xmlns="%s"' % currTagNS
|
||||
attr += ' xmlns="{0}"'.format(currTagNS)
|
||||
currDefNS = currTagNS
|
||||
|
||||
if isinstance(val, DataObject):
|
||||
@@ -299,14 +299,14 @@ class SoapSerializer:
|
||||
elif isinstance(val, ManagedObject):
|
||||
if info.type is object:
|
||||
nsattr, qName = self._QName(ManagedObject, currDefNS)
|
||||
attr += '%s %stype="%s"' % (nsattr, self.xsiPrefix, qName)
|
||||
attr += '{0} {1}type="{2}"'.format(nsattr, self.xsiPrefix, qName)
|
||||
if val._serverGuid is not None:
|
||||
attr += ' serverGuid="%s"' % (val._serverGuid)
|
||||
attr += ' serverGuid="{0}"'.format(val._serverGuid)
|
||||
# val in vim type attr is not namespace qualified
|
||||
# TODO: Add a new "typens" attr?
|
||||
ns, name = GetQualifiedWsdlName(Type(val))
|
||||
attr += ' type="%s"' % (name)
|
||||
self.writer.write('<%s%s>%s</%s>' % (info.name, attr,
|
||||
attr += ' type="{0}"'.format(name)
|
||||
self.writer.write('<{0}{1}>{2}</{3}>'.format(info.name, attr,
|
||||
val._moId.encode(self.encoding),
|
||||
info.name))
|
||||
elif isinstance(val, list):
|
||||
@@ -329,14 +329,14 @@ class SoapSerializer:
|
||||
if qName.endswith("ArrayOfManagedObject"):
|
||||
qName += "Reference"
|
||||
|
||||
attr += '%s %stype="%s"' % (nsattr, self.xsiPrefix, qName)
|
||||
self.writer.write('<%s%s>' % (info.name, attr))
|
||||
attr += '{0} {1}type="{2}"'.format(nsattr, self.xsiPrefix, qName)
|
||||
self.writer.write('<{0}{1}>'.format(info.name, attr))
|
||||
|
||||
itemInfo = Object(name=tag, type=itemType,
|
||||
version=info.version, flags=info.flags)
|
||||
for it in val:
|
||||
self._Serialize(it, itemInfo, currDefNS)
|
||||
self.writer.write('</%s>' % info.name)
|
||||
self.writer.write('</{0}>'.format(info.name))
|
||||
else:
|
||||
itemType = info.type.Item
|
||||
itemInfo = Object(name=info.name, type=itemType,
|
||||
@@ -345,42 +345,39 @@ class SoapSerializer:
|
||||
self._Serialize(it, itemInfo, defNS)
|
||||
elif isinstance(val, type) or isinstance(val, type(Exception)):
|
||||
if info.type is object:
|
||||
attr += ' %stype="%sstring"' % (self.xsiPrefix, self.xsdPrefix)
|
||||
self.writer.write('<%s%s>%s</%s>' %
|
||||
(info.name, attr, GetWsdlName(val), info.name))
|
||||
attr += ' {0}type="{1}string"'.format(self.xsiPrefix, self.xsdPrefix)
|
||||
self.writer.write('<{0}{1}>{2}</{0}>'.format(
|
||||
info.name, attr, GetWsdlName(val)))
|
||||
elif isinstance(val, ManagedMethod):
|
||||
if info.type is object:
|
||||
attr += ' %stype="%sstring"' % (self.xsiPrefix, self.xsdPrefix)
|
||||
self.writer.write('<%s%s>%s</%s>' %
|
||||
(info.name, attr, val.info.wsdlName, info.name))
|
||||
attr += ' {0}type="{1}string"'.format(self.xsiPrefix, self.xsdPrefix)
|
||||
self.writer.write('<{0}{1}>{2}</{0}>'.format(
|
||||
info.name, attr, val.info.wsdlName))
|
||||
elif isinstance(val, datetime):
|
||||
if info.type is object:
|
||||
nsattr, qName = self._QName(Type(val), currDefNS)
|
||||
attr += '%s %stype="%s"' % (nsattr, self.xsiPrefix, qName)
|
||||
attr += '{0} {1}type="{2}"'.format(nsattr, self.xsiPrefix, qName)
|
||||
result = Iso8601.ISO8601Format(val)
|
||||
self.writer.write('<%s%s>%s</%s>' % (info.name, attr, result,
|
||||
info.name))
|
||||
self.writer.write('<{0}{1}>{2}</{0}>'.format(info.name, attr, result))
|
||||
elif isinstance(val, binary):
|
||||
if info.type is object:
|
||||
nsattr, qName = self._QName(Type(val), currDefNS)
|
||||
attr += '%s %stype="%s"' % (nsattr, self.xsiPrefix, qName)
|
||||
attr += '{0} {1}type="{2}"'.format(nsattr, self.xsiPrefix, qName)
|
||||
result = base64.b64encode(val)
|
||||
self.writer.write('<%s%s>%s</%s>' % (info.name, attr, result,
|
||||
info.name))
|
||||
self.writer.write('<{0}{1}>{2}</{0}>'.format(info.name, attr, result))
|
||||
elif isinstance(val, bool):
|
||||
if info.type is object:
|
||||
nsattr, qName = self._QName(Type(val), currDefNS)
|
||||
attr += '%s %stype="%s"' % (nsattr, self.xsiPrefix, qName)
|
||||
attr += '{0} {1}type="{2}"'.format(nsattr, self.xsiPrefix, qName)
|
||||
result = val and "true" or "false"
|
||||
self.writer.write('<%s%s>%s</%s>' % (info.name, attr, result,
|
||||
info.name))
|
||||
self.writer.write('<{0}{1}>{2}</{0}>'.format(info.name, attr, result))
|
||||
else:
|
||||
if info.type is object:
|
||||
if isinstance(val, PropertyPath):
|
||||
attr += ' %stype="%sstring"' % (self.xsiPrefix, self.xsdPrefix)
|
||||
attr += ' {0}type="{1}string"'.format(self.xsiPrefix, self.xsdPrefix)
|
||||
else:
|
||||
nsattr, qName = self._QName(Type(val), currDefNS)
|
||||
attr += '%s %stype="%s"' % (nsattr, self.xsiPrefix, qName)
|
||||
attr += '{0} {1}type="{2}"'.format(nsattr, self.xsiPrefix, qName)
|
||||
if not isinstance(val, text_type):
|
||||
# Use UTF-8 rather than self.encoding. self.encoding is for
|
||||
# output of serializer, while 'val' is our input. And regardless
|
||||
@@ -390,9 +387,8 @@ class SoapSerializer:
|
||||
# a bug.
|
||||
val = str(val).decode('UTF-8')
|
||||
result = XmlEscape(val)
|
||||
self.writer.write('<%s%s>%s</%s>' % (info.name, attr,
|
||||
result.encode(self.encoding),
|
||||
info.name))
|
||||
self.writer.write('<{0}{1}>{2}</{0}>'.format(info.name, attr,
|
||||
result.encode(self.encoding)))
|
||||
|
||||
## Serialize a a data object (internal)
|
||||
#
|
||||
@@ -409,8 +405,8 @@ class SoapSerializer:
|
||||
dynType = GetCompatibleType(Type(val), self.version)
|
||||
if dynType != info.type:
|
||||
nsattr, qName = self._QName(dynType, currDefNS)
|
||||
attr += '%s %stype="%s"' % (nsattr, self.xsiPrefix, qName)
|
||||
self.writer.write('<%s%s>' % (info.name, attr))
|
||||
attr += '{0} {1}type="{2}"'.format(nsattr, self.xsiPrefix, qName)
|
||||
self.writer.write('<{0}{1}>'.format(info.name, attr))
|
||||
if dynType is LocalizedMethodFault:
|
||||
# Serialize a MethodFault as LocalizedMethodFault on wire
|
||||
# See PR 670229
|
||||
@@ -426,7 +422,7 @@ class SoapSerializer:
|
||||
for prop in val._GetPropertyList():
|
||||
self._Serialize(getattr(val, prop.name), prop, currDefNS)
|
||||
|
||||
self.writer.write('</%s>' % info.name)
|
||||
self.writer.write('</{0}>'.format(info.name))
|
||||
|
||||
|
||||
## Deserialize an object from a file or string
|
||||
@@ -585,7 +581,7 @@ class SoapDeserializer(ExpatDeserializerNSHandlers):
|
||||
if name == "fault" and isinstance(self.stack[-1], LocalizedMethodFault):
|
||||
deserializeAsLocalizedMethodFault = False
|
||||
else:
|
||||
raise TypeError("Invalid type for tag %s" % tag)
|
||||
raise TypeError("Invalid type for tag {0}".format(tag))
|
||||
|
||||
xsiType = attr.get(XSI_TYPE)
|
||||
if xsiType:
|
||||
@@ -607,13 +603,13 @@ class SoapDeserializer(ExpatDeserializerNSHandlers):
|
||||
if self.version:
|
||||
objType = GetCompatibleType(objType, self.version)
|
||||
if issubclass(objType, ManagedObject):
|
||||
typeAttr = attr[u'type']
|
||||
typeAttr = attr[u('type')]
|
||||
# val in vim type attr is not namespace qualified
|
||||
# However, this doesn't hurt to strip out namespace
|
||||
# TODO: Get the ns from "typens" attr?
|
||||
ns, name = self.GetNSAndWsdlname(typeAttr)
|
||||
if u'serverGuid' in attr:
|
||||
self.serverGuid = attr[u'serverGuid']
|
||||
if u('serverGuid') in attr:
|
||||
self.serverGuid = attr[u('serverGuid')]
|
||||
self.stack.append(GuessWsdlType(name))
|
||||
elif issubclass(objType, DataObject) or issubclass(objType, list):
|
||||
if deserializeAsLocalizedMethodFault and issubclass(objType, Exception):
|
||||
@@ -792,7 +788,7 @@ class StubAdapterBase(StubAdapterAccessorMixin):
|
||||
def ComputeVersionInfo(self, version):
|
||||
versionNS = GetVersionNamespace(version)
|
||||
if versionNS.find("/") >= 0:
|
||||
self.versionId = '"urn:%s"' % versionNS
|
||||
self.versionId = '"urn:{0}"'.format(versionNS)
|
||||
else:
|
||||
self.versionId = ''
|
||||
self.version = version
|
||||
@@ -828,30 +824,30 @@ class SoapStubAdapterBase(StubAdapterBase):
|
||||
for key, val in reqContexts.iteritems():
|
||||
# Note: Support req context of string type only
|
||||
if not isinstance(val, basestring):
|
||||
raise TypeError("Request context key (%s) has non-string value (%s) of %s" % (key, val, type(val)))
|
||||
raise TypeError("Request context key ({0}) has non-string value ({1}) of {2}".format(key, val, type(val)))
|
||||
ret = Serialize(val,
|
||||
Object(name=key, type=str, version=self.version),
|
||||
self.version,
|
||||
nsMap)
|
||||
result.append(ret)
|
||||
if samlToken:
|
||||
result.append('%s %s %s' % (WSSE_HEADER_START,
|
||||
samlToken,
|
||||
WSSE_HEADER_END))
|
||||
result.append('{0} {1} {2}'.format(WSSE_HEADER_START,
|
||||
samlToken,
|
||||
WSSE_HEADER_END))
|
||||
result.append(SOAP_HEADER_END)
|
||||
result.append('\n')
|
||||
|
||||
# Serialize soap body
|
||||
result.extend([SOAP_BODY_START,
|
||||
'<%s xmlns="%s">' % (info.wsdlName, defaultNS),
|
||||
Serialize(mo, Object(name="_this", type=ManagedObject,
|
||||
version=self.version),
|
||||
self.version, nsMap)])
|
||||
'<{0} xmlns="{1}">'.format(info.wsdlName, defaultNS),
|
||||
Serialize(mo, Object(name="_this", type=ManagedObject,
|
||||
version=self.version),
|
||||
self.version, nsMap)])
|
||||
|
||||
# Serialize soap request parameters
|
||||
for (param, arg) in zip(info.params, args):
|
||||
result.append(Serialize(arg, param, self.version, nsMap))
|
||||
result.extend(['</%s>' % info.wsdlName, SOAP_BODY_END, SOAP_ENVELOPE_END])
|
||||
result.extend(['</{0}>'.format(info.wsdlName), SOAP_BODY_END, SOAP_ENVELOPE_END])
|
||||
return ''.join(result)
|
||||
|
||||
## Subclass of HTTPConnection that connects over a Unix domain socket
|
||||
@@ -897,9 +893,9 @@ try:
|
||||
sha1.update(derCert)
|
||||
sha1Digest = sha1.hexdigest().lower()
|
||||
if sha1Digest != thumbprint:
|
||||
raise Exception("Server has wrong SHA1 thumbprint: %s "
|
||||
"(required) != %s (server)" % (
|
||||
thumbprint, sha1Digest))
|
||||
raise Exception("Server has wrong SHA1 thumbprint: {0} "
|
||||
"(required) != {1} (server)".format(
|
||||
thumbprint, sha1Digest))
|
||||
|
||||
# Function used to wrap sockets with SSL
|
||||
_SocketWrapper = ssl.wrap_socket
|
||||
@@ -1004,7 +1000,7 @@ class SSLTunnelConnection(object):
|
||||
resp = tunnel.getresponse()
|
||||
tunnelSocket = resp.fp
|
||||
if resp.status != 200:
|
||||
raise http_client.HTTPException("%d %s" % (resp.status, resp.reason))
|
||||
raise httplib.HTTPException("{0} {1}".format(resp.status, resp.reason))
|
||||
retval = http_client.HTTPSConnection(path)
|
||||
retval.sock = _SocketWrapper(tunnelSocket,
|
||||
keyfile=key_file, certfile=cert_file)
|
||||
@@ -1142,13 +1138,13 @@ class SoapStubAdapter(SoapStubAdapterBase):
|
||||
or (port, HTTPSConnectionWrapper)
|
||||
if host.find(':') != -1: # is IPv6?
|
||||
host = '[' + host + ']'
|
||||
self.host = '%s:%d' % (host, port)
|
||||
self.host = '{0}:{1}'.format(host, port)
|
||||
|
||||
self.path = path
|
||||
if thumbprint:
|
||||
self.thumbprint = thumbprint.replace(":", "").lower()
|
||||
if len(self.thumbprint) != 40:
|
||||
raise Exception("Invalid SHA1 thumbprint -- %s" % thumbprint)
|
||||
raise Exception("Invalid SHA1 thumbprint -- {0}".format(thumbprint))
|
||||
else:
|
||||
self.thumbprint = None
|
||||
|
||||
@@ -1161,9 +1157,9 @@ class SoapStubAdapter(SoapStubAdapterBase):
|
||||
if url:
|
||||
self.path = url
|
||||
else:
|
||||
self.path = "http://%s/%s" % (self.host, path)
|
||||
self.path = "http://{0}/{1}".format(self.host, path)
|
||||
# Swap the actual host with the proxy.
|
||||
self.host = "%s:%d" % (httpProxyHost, httpProxyPort)
|
||||
self.host = "{0}:{1}".format(httpProxyHost, httpProxyPort)
|
||||
self.poolSize = poolSize
|
||||
self.pool = []
|
||||
self.connectionPoolTimeout = connectionPoolTimeout
|
||||
@@ -1210,7 +1206,7 @@ class SoapStubAdapter(SoapStubAdapterBase):
|
||||
|
||||
headers = {'Cookie' : self.cookie,
|
||||
'SOAPAction' : self.versionId,
|
||||
'Content-Type' : 'text/xml; charset=%s' % XML_ENCODING}
|
||||
'Content-Type': 'text/xml; charset={0}'.format(XML_ENCODING)}
|
||||
if self._acceptCompressedResponses:
|
||||
headers['Accept-Encoding'] = 'gzip, deflate'
|
||||
req = self.SerializeRequest(mo, info, args)
|
||||
@@ -1254,7 +1250,7 @@ class SoapStubAdapter(SoapStubAdapterBase):
|
||||
raise obj # pylint: disable-msg=E0702
|
||||
else:
|
||||
conn.close()
|
||||
raise http_client.HTTPException("%d %s" % (resp.status, resp.reason))
|
||||
raise http_client.HTTPException("{0} {1}".format(resp.status, resp.reason))
|
||||
|
||||
## Clean up connection pool to throw away idle timed-out connections
|
||||
# SoapStubAdapter lock must be acquired before this method is called.
|
||||
@@ -1387,14 +1383,14 @@ class SoapCmdStubAdapter(SoapStubAdapterBase):
|
||||
(outText, errText) = p.communicate(req)
|
||||
if p.returncode < 0:
|
||||
# Process died with a signal
|
||||
errText = "Process terminated with signal %d\n%s" % (-p.returncode, errText)
|
||||
errText = "Process terminated with signal {0}\n{1}".format(-p.returncode, errText)
|
||||
raise self.systemError(msg=errText, reason=errText)
|
||||
|
||||
try:
|
||||
(responseHeaders, responseBody) = ParseHttpResponse(outText)
|
||||
obj = SoapResponseDeserializer(self).Deserialize(responseBody, info.result)
|
||||
except:
|
||||
errText = "Failure parsing SOAP response (%s)\n%s" % (outText, errText)
|
||||
errText = "Failure parsing SOAP response ({0})\n{1}}".format(outText, errText)
|
||||
raise self.systemError(msg=errText, reason=errText)
|
||||
|
||||
if p.returncode == 0:
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
#!/usr/bin/python
|
||||
# VMware vSphere Python SDK
|
||||
# Copyright (c) 2008-2014 VMware, Inc. All Rights Reserved.
|
||||
# Copyright (c) 2008-2013 VMware, Inc. All Rights Reserved.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
@@ -18,36 +18,48 @@
|
||||
Python program for listing the vms on an ESX / vCenter host
|
||||
"""
|
||||
|
||||
from optparse import OptionParser, make_option
|
||||
from __future__ import print_function
|
||||
|
||||
import pyVmomi
|
||||
|
||||
from pyVmomi import vim
|
||||
from pyVmomi import vmodl
|
||||
|
||||
from pyVim.connect import SmartConnect, Disconnect
|
||||
from pyVmomi import vmodl
|
||||
|
||||
import argparse
|
||||
import atexit
|
||||
import getpass
|
||||
import sys
|
||||
|
||||
|
||||
def GetArgs():
|
||||
"""
|
||||
Supports the command-line arguments listed below.
|
||||
"""
|
||||
parser = argparse.ArgumentParser(description='Process args for retrieving all the Virtual Machines')
|
||||
parser.add_argument('-s', '--host', required=True, action='store', help='Remote host to connect to')
|
||||
parser.add_argument('-o', '--port', type=int, default=443, action='store', help='Port to connect on')
|
||||
parser.add_argument('-u', '--user', required=True, action='store', help='User name to use when connecting to host')
|
||||
parser.add_argument('-p', '--password', required=False, action='store', help='Password to use when connecting to host')
|
||||
parser = argparse.ArgumentParser(
|
||||
description='Process args for retrieving all the Virtual Machines')
|
||||
parser.add_argument('-s', '--host', required=True, action='store',
|
||||
help='Remote host to connect to')
|
||||
parser.add_argument('-o', '--port', type=int, default=443, action='store',
|
||||
help='Port to connect on')
|
||||
parser.add_argument('-u', '--user', required=True, action='store',
|
||||
help='User name to use when connecting to host')
|
||||
parser.add_argument('-p', '--password', required=False, action='store',
|
||||
help='Password to use when connecting to host')
|
||||
args = parser.parse_args()
|
||||
return args
|
||||
|
||||
|
||||
def PrintVmInfo(vm, depth=1):
|
||||
"""
|
||||
Print information for a particular virtual machine or recurse into a folder with depth protection
|
||||
Print information for a particular virtual machine or recurse into a folder
|
||||
with depth protection
|
||||
"""
|
||||
maxdepth = 10
|
||||
|
||||
# if this is a group it will have children. if it does, recurse into them and then return
|
||||
# if this is a group it will have children. if it does, recurse into them
|
||||
# and then return
|
||||
if hasattr(vm, 'childEntity'):
|
||||
if depth > maxdepth:
|
||||
return
|
||||
@@ -57,23 +69,20 @@ def PrintVmInfo(vm, depth=1):
|
||||
return
|
||||
|
||||
summary = vm.summary
|
||||
print "Name : ", summary.config.name
|
||||
print "Path : ", summary.config.vmPathName
|
||||
print "Guest : ", summary.config.guestFullName
|
||||
print "Instance UUID : ", vm.summary.config.instanceUuid
|
||||
print "BIOS UUID : ", vm.summary.config.uuid
|
||||
|
||||
print("Name : ", summary.config.name)
|
||||
print("Path : ", summary.config.vmPathName)
|
||||
print("Guest : ", summary.config.guestFullName)
|
||||
annotation = summary.config.annotation
|
||||
if annotation != None and annotation != "":
|
||||
print "Annotation : ", annotation
|
||||
print "State : ", summary.runtime.powerState
|
||||
print("Annotation : ", annotation)
|
||||
print("State : ", summary.runtime.powerState)
|
||||
if summary.guest != None:
|
||||
ip = summary.guest.ipAddress
|
||||
if ip != None and ip != "":
|
||||
print "IP : ", ip
|
||||
print("IP : ", ip)
|
||||
if summary.runtime.question != None:
|
||||
print "Question : ", summary.runtime.question.text
|
||||
print ""
|
||||
print("Question : ", summary.runtime.question.text)
|
||||
print("")
|
||||
|
||||
def main():
|
||||
"""
|
||||
@@ -84,36 +93,28 @@ def main():
|
||||
if args.password:
|
||||
password = args.password
|
||||
else:
|
||||
password = getpass.getpass(prompt='Enter password for host %s and user %s: ' % (args.host,args.user))
|
||||
password = getpass.getpass(prompt='Enter password for host %s and '
|
||||
'user %s: ' % (args.host,args.user))
|
||||
|
||||
try:
|
||||
si = None
|
||||
try:
|
||||
si = SmartConnect(host=args.host,
|
||||
user=args.user,
|
||||
pwd=password,
|
||||
port=int(args.port))
|
||||
except IOError, e:
|
||||
pass
|
||||
if not si:
|
||||
print "Could not connect to the specified host using specified username and password"
|
||||
return -1
|
||||
si = SmartConnect(host=args.host,
|
||||
user=args.user,
|
||||
pwd=password,
|
||||
port=int(args.port))
|
||||
if not si:
|
||||
print("Could not connect to the specified host using specified "
|
||||
"username and password")
|
||||
return -1
|
||||
|
||||
atexit.register(Disconnect, si)
|
||||
|
||||
content = si.RetrieveContent()
|
||||
datacenter = content.rootFolder.childEntity[0]
|
||||
vmFolder = datacenter.vmFolder
|
||||
vmList = vmFolder.childEntity
|
||||
for vm in vmList:
|
||||
PrintVmInfo(vm)
|
||||
except vmodl.MethodFault, e:
|
||||
print "Caught vmodl fault : " + e.msg
|
||||
return -1
|
||||
except Exception, e:
|
||||
print "Caught exception : " + str(e)
|
||||
return -1
|
||||
atexit.register(Disconnect, si)
|
||||
|
||||
content = si.RetrieveContent()
|
||||
for child in content.rootFolder.childEntity:
|
||||
if hasattr(child, 'vmFolder'):
|
||||
datacenter = child
|
||||
vmFolder = datacenter.vmFolder
|
||||
vmList = vmFolder.childEntity
|
||||
for vm in vmList:
|
||||
PrintVmInfo(vm)
|
||||
return 0
|
||||
|
||||
# Start program
|
||||
|
||||
@@ -19,6 +19,8 @@
|
||||
Python program for powering on vms on a host on which hostd is running
|
||||
"""
|
||||
|
||||
from __future__ import print_function
|
||||
|
||||
from pyVim.connect import SmartConnect, Disconnect
|
||||
from pyVmomi import vim, vmodl
|
||||
|
||||
@@ -107,7 +109,7 @@ def main():
|
||||
try:
|
||||
vmnames = args.vmname
|
||||
if not len(vmnames):
|
||||
print "No virtual machine specified for poweron"
|
||||
print("No virtual machine specified for poweron")
|
||||
sys.exit()
|
||||
|
||||
si = None
|
||||
@@ -116,10 +118,10 @@ def main():
|
||||
user=args.user,
|
||||
pwd=password,
|
||||
port=int(args.port))
|
||||
except IOError, e:
|
||||
except IOError:
|
||||
pass
|
||||
if not si:
|
||||
print "Cannot connect to specified host using specified username and password"
|
||||
print("Cannot connect to specified host using specified username and password")
|
||||
sys.exit()
|
||||
|
||||
atexit.register(Disconnect, si)
|
||||
@@ -139,11 +141,11 @@ def main():
|
||||
# Wait for power on to complete
|
||||
WaitForTasks(tasks, si)
|
||||
|
||||
print "Virtual Machine(s) have been powered on successfully"
|
||||
except vmodl.MethodFault, e:
|
||||
print "Caught vmodl fault : " + e.msg
|
||||
except Exception, e:
|
||||
print "Caught Exception : " + str(e)
|
||||
print("Virtual Machine(s) have been powered on successfully")
|
||||
except vmodl.MethodFault as e:
|
||||
print("Caught vmodl fault : " + e.msg)
|
||||
except Exception as e:
|
||||
print("Caught Exception : " + str(e))
|
||||
|
||||
# Start program
|
||||
if __name__ == "__main__":
|
||||
|
||||
Reference in New Issue
Block a user