def _connect_request(self, vdi_ref):
# request connection to xapi url service for VDI export
try:
# create task for VDI export
label = 'VDI_EXPORT_for_' + self.instance['name']
desc = 'Exporting VDI for instance: %s' % self.instance['name']
self.task_ref = self.session.task.create(label, desc)
LOG.debug("task_ref is %s" % self.task_ref)
# connect to XS
xs_url = urlparse.urlparse(self.host_url)
if xs_url.scheme == 'http':
conn = httplib.HTTPConnection(xs_url.netloc)
LOG.debug("using http")
elif xs_url.scheme == 'https':
conn = httplib.HTTPSConnection(xs_url.netloc)
LOG.debug("using https")
vdi_export_path = utils.get_vdi_export_path(
self.session, self.task_ref, vdi_ref)
conn.request('GET', vdi_export_path)
conn_resp = conn.getresponse()
except Exception:
LOG.debug('request connect for vdi export failed')
raise
return conn_resp
python类HTTPSConnection()的实例源码
def connect(self, method, content_length, cookie):
try:
if self._scheme == 'http':
conn = httplib.HTTPConnection(self._server)
elif self._scheme == 'https':
# TODO(browne): This needs to be changed to use python requests
conn = httplib.HTTPSConnection(self._server) # nosec
else:
excep_msg = _("Invalid scheme: %s.") % self._scheme
LOG.error(excep_msg)
raise ValueError(excep_msg)
conn.putrequest(method, '/folder/%s?%s' % (self.path, self._query))
conn.putheader('User-Agent', constants.USER_AGENT)
conn.putheader('Content-Length', content_length)
conn.putheader('Cookie', cookie)
conn.endheaders()
LOG.debug("Created HTTP connection to transfer the file with "
"URL = %s.", str(self))
return conn
except (httplib.InvalidURL, httplib.CannotSendRequest,
httplib.CannotSendHeader) as excep:
excep_msg = _("Error occurred while creating HTTP connection "
"to write to file with URL = %s.") % str(self)
LOG.exception(excep_msg)
raise exceptions.VimConnectionException(excep_msg, excep)
def OpenPathWithStub(path, stub):
"""
Open the specified path using HTTP, using the host/port/protocol
associated with the specified stub. If the stub has a session cookie,
it is included with the HTTP request. Returns the response as a
file-like object.
"""
from six.moves import http_client
if not hasattr(stub, 'scheme'):
raise vmodl.fault.NotSupported()
elif stub.scheme == http_client.HTTPConnection:
protocol = 'http'
elif stub.scheme == http_client.HTTPSConnection:
protocol = 'https'
else:
raise vmodl.fault.NotSupported()
hostPort = stub.host
url = '%s://%s%s' % (protocol, hostPort, path)
headers = {}
if stub.cookie:
headers["Cookie"] = stub.cookie
return requests.get(url, headers=headers, verify=False)
def __call__(self, path, key_file=None, cert_file=None, **kwargs):
# Only pass in the named arguments that HTTPConnection constructor
# understands
tmpKwargs = {}
for key in http_client.HTTPConnection.__init__.__code__.co_varnames:
if key in kwargs and key != 'self':
tmpKwargs[key] = kwargs[key]
tunnel = http_client.HTTPConnection(path, **tmpKwargs)
tunnel.request('CONNECT', self.proxyPath)
resp = tunnel.getresponse()
if resp.status != 200:
raise http_client.HTTPException("{0} {1}".format(resp.status, resp.reason))
retval = http_client.HTTPSConnection(path)
retval.sock = _SocketWrapper(tunnel.sock,
keyfile=key_file, certfile=cert_file)
return retval
def _create_connection(scheme, netloc):
if scheme == 'https':
conn = httplib.HTTPSConnection(netloc)
else:
conn = httplib.HTTPConnection(netloc)
conn.connect()
return conn
def http_connection(self):
conn = None
xs_url = urllib.parse.urlparse(self.url)
LOG.debug("Creating http(s) connection to %s", self.url)
if xs_url.scheme == 'http':
conn = http_client.HTTPConnection(xs_url.netloc)
elif xs_url.scheme == 'https':
conn = http_client.HTTPSConnection(xs_url.netloc)
conn.connect()
try:
yield conn
finally:
conn.close()
def __init__(self, host, ca_bundle, **kw):
HTTPSConnection.__init__(self, host, **kw)
self.ca_bundle = ca_bundle
def __init__(self, host, ca_bundle, **kw):
HTTPSConnection.__init__(self, host, **kw)
self.ca_bundle = ca_bundle
def __init__(self, host, ca_bundle, **kw):
HTTPSConnection.__init__(self, host, **kw)
self.ca_bundle = ca_bundle
def __init__(self, host, ca_bundle, **kw):
HTTPSConnection.__init__(self, host, **kw)
self.ca_bundle = ca_bundle
def __init__(self, host, ca_bundle, **kw):
HTTPSConnection.__init__(self, host, **kw)
self.ca_bundle = ca_bundle
def __init__(self, host, ca_bundle, **kw):
HTTPSConnection.__init__(self, host, **kw)
self.ca_bundle = ca_bundle
def __init__(self, host, ca_bundle, **kw):
HTTPSConnection.__init__(self, host, **kw)
self.ca_bundle = ca_bundle
def __init__(self, host, ca_bundle, **kw):
HTTPSConnection.__init__(self, host, **kw)
self.ca_bundle = ca_bundle
def __init__(self, host, ca_bundle, **kw):
HTTPSConnection.__init__(self, host, **kw)
self.ca_bundle = ca_bundle
def __init__(self, host, ca_bundle, **kw):
HTTPSConnection.__init__(self, host, **kw)
self.ca_bundle = ca_bundle
def __init__(self, host, ca_bundle, **kw):
HTTPSConnection.__init__(self, host, **kw)
self.ca_bundle = ca_bundle
def __init__(self, host, ca_bundle, **kw):
HTTPSConnection.__init__(self, host, **kw)
self.ca_bundle = ca_bundle
def __GetElementTree(protocol, server, port, path, sslContext):
"""
Private method that returns a root from ElementTree for a remote XML document.
@param protocol: What protocol to use for the connection (e.g. https or http).
@type protocol: string
@param server: Which server to connect to.
@type server: string
@param port: Port
@type port: int
@param path: Path
@type path: string
@param sslContext: SSL Context describing the various SSL options. It is only
supported in Python 2.7.9 or higher.
@type sslContext: SSL.Context
"""
if protocol == "https":
kwargs = {"context": sslContext} if sslContext else {}
conn = http_client.HTTPSConnection(server, port=port, **kwargs)
elif protocol == "http":
conn = http_client.HTTPConnection(server, port=port)
else:
raise Exception("Protocol " + protocol + " not supported.")
conn.request("GET", path)
response = conn.getresponse()
if response.status == 200:
try:
tree = ElementTree.fromstring(response.read())
return tree
except ExpatError:
pass
return None
## Private method that returns an ElementTree describing the API versions
## supported by the specified server. The result will be vimServiceVersions.xml
## if it exists, otherwise vimService.wsdl if it exists, otherwise None.
def _VerifyThumbprint(thumbprint, connection):
'''If there is a thumbprint, connect to the server and verify that the
SSL certificate matches the given thumbprint. An exception is thrown
if there is a mismatch.'''
if thumbprint and isinstance(connection, http_client.HTTPSConnection):
if not connection.sock:
connection.connect()
derCert = connection.sock.getpeercert(True)
sha1 = hashlib.sha1()
sha1.update(derCert)
sha1Digest = sha1.hexdigest().lower()
if sha1Digest != thumbprint:
raise ThumbprintMismatchException(thumbprint, sha1Digest)
# Function used to wrap sockets with SSL
def _VerifyThumbprint(thumbprint, connection):
if thumbprint and isinstance(connection, http_client.HTTPSConnection):
raise Exception(
"Thumbprint verification not supported on python < 2.6")
def _SocketWrapper(rawSocket, keyfile, certfile, *args, **kwargs):
wrappedSocket = socket.ssl(rawSocket, keyfile, certfile)
return http_client.FakeSocket(rawSocket, wrappedSocket)
## Internal version of https connection
#
# Support ssl.wrap_socket params which are missing from httplib
# HTTPSConnection (e.g. ca_certs)
# Note: Only works if the ssl params are passing in as kwargs
def connect(self):
if len(self._sslArgs) == 0:
# No override
http_client.HTTPSConnection.connect(self)
return
# Big hack. We have to copy and paste the httplib connect fn for
# each python version in order to handle extra ssl paramters. Yuk!
if hasattr(self, "source_address"):
# Python 2.7
sock = socket.create_connection((self.host, self.port),
self.timeout, self.source_address)
if self._tunnel_host:
self.sock = sock
self._tunnel()
self.sock = ssl.wrap_socket(sock, self.key_file, self.cert_file,
**self._sslArgs)
elif hasattr(self, "timeout"):
# Python 2.6
sock = socket.create_connection((self.host, self.port), self.timeout)
self.sock = ssl.wrap_socket(sock, self.key_file, self.cert_file,
**self._sslArgs)
else:
# Unknown python version. Do nothing
http_client.HTTPSConnection.connect(self)
return
# TODO: Additional verification of peer cert if needed
# cert_reqs = self._sslArgs.get("cert_reqs", ssl.CERT_NONE)
# ca_certs = self._sslArgs.get("ca_certs", None)
# if cert_reqs != ssl.CERT_NONE and ca_certs:
# if hasattr(self.sock, "getpeercert"):
# # TODO: verify peer cert
# dercert = self.sock.getpeercert(False)
# # pemcert = ssl.DER_cert_to_PEM_cert(dercert)
## Stand-in for the HTTPSConnection class that will connect to a proxy and
## issue a CONNECT command to start an SSL tunnel.
def __init__(self, proxyPath):
self.proxyPath = proxyPath
# Connects to a proxy server and initiates a tunnel to the destination
# specified by proxyPath. If successful, a new HTTPSConnection is returned.
#
# @param path The destination URL path.
# @param key_file The SSL key file to use when wrapping the socket.
# @param cert_file The SSL certificate file to use when wrapping the socket.
# @param kwargs In case caller passed in extra parameters not handled by
# SSLTunnelConnection
def __init__(self, host, ca_bundle, **kw):
HTTPSConnection.__init__(self, host, **kw)
self.ca_bundle = ca_bundle
def __init__(self, host, ca_bundle, **kw):
HTTPSConnection.__init__(self, host, **kw)
self.ca_bundle = ca_bundle
def __init__(self, host, ca_bundle, **kw):
HTTPSConnection.__init__(self, host, **kw)
self.ca_bundle = ca_bundle
def connect(self):
httplib.HTTPSConnection.connect(self)
timeout = getattr(self, "_timeout", 0)
if timeout:
self.sock.settimeout(timeout)
def __init__(self, host, ca_bundle, **kw):
HTTPSConnection.__init__(self, host, **kw)
self.ca_bundle = ca_bundle
def __init__(self, host, ca_bundle, **kw):
HTTPSConnection.__init__(self, host, **kw)
self.ca_bundle = ca_bundle