Exemple #1
0
def create_pbm_session(stub):
    """
    Creates a session with the VMware Storage Policy API

    Sample Usage:

    create_pbm_session(service_instance._stub)
    """
    import pyVmomi
    import ssl
    # Make compatible with both Python2/3
    try:
        from http import cookies
    except ImportError:
        import Cookie as cookies

    session_cookie = stub.cookie.split('"')[1]
    http_context = VmomiSupport.GetHttpContext()
    cookie = cookies.SimpleCookie()
    cookie["vmware_soap_session"] = session_cookie
    http_context["cookies"] = cookie
    VmomiSupport.GetRequestContext()["vcSessionCookie"] = session_cookie
    hostname = stub.host.split(":")[0]

    context = None
    if hasattr(ssl, "_create_unverified_context"):
        context = ssl._create_unverified_context()
    pbm_stub = pyVmomi.SoapStubAdapter(host=hostname,
                                       version="pbm.version.version1",
                                       path="/pbm/sdk",
                                       poolSize=0,
                                       sslContext=context)
    pbm_si = pbm.ServiceInstance("ServiceInstance", pbm_stub)

    return pbm_si
Exemple #2
0
 def Login(self, userName, password, locale=None):
    #Set the Http SessionCookie for the mob to work correctly.
    sessionCookie = str(uuid.uuid1())
    httpContext = VmomiSupport.GetHttpContext()
    if "cookies" in httpContext:
       httpContext["cookies"]["vmware_soap_session"] = sessionCookie
    else:
       cookie = SimpleCookie()
       cookie["vmware_soap_session"] = sessionCookie
       httpContext["cookies"] = cookie
    return self.currentSession
Exemple #3
0
def GetStorageManager(vcHost):
   smsStub = None
   vpxdStub = connect.GetStub()
   sessionCookie = vpxdStub.cookie.split('"')[1]
   httpContext = VmomiSupport.GetHttpContext()
   cookie = Cookie.SimpleCookie()
   cookie["vmware_soap_session"] = sessionCookie
   httpContext["cookies"] = cookie

   VmomiSupport.GetRequestContext()["vcSessionCookie"] = sessionCookie
   smsStub = SoapStubAdapter(host=vcHost, ns = "sms/4.0",
                                path = "/sms/sdk",
                                poolSize=0)

   si = Sms.ServiceInstance("ServiceInstance", smsStub)
   return si.QueryStorageManager()
Exemple #4
0
def GetPbmConnection(stub, context=None):
    sessionCookie = stub.cookie.split('"')[1]
    httpContext = VmomiSupport.GetHttpContext()
    cookie = Cookie.SimpleCookie()
    cookie["vmware_soap_session"] = sessionCookie
    httpContext["cookies"] = cookie
    VmomiSupport.GetRequestContext()["vcSessionCookie"] = sessionCookie
    hostname = stub.host.split(":")[0]

    pbmStub = pyVmomi.SoapStubAdapter(
        host=hostname,
        version="pbm.version.version1",
        path="/pbm/sdk",
        poolSize=0,
        sslContext=context)
    pbmSi = pbm.ServiceInstance("ServiceInstance", pbmStub)
    pbmContent = pbmSi.RetrieveContent()

    return (pbmSi, pbmContent)
def GetPbmConnection(vpxdStub):
    import Cookie
    import pyVmomi
    sessionCookie = vpxdStub.cookie.split('"')[1]
    httpContext = VmomiSupport.GetHttpContext()
    cookie = Cookie.SimpleCookie()
    cookie["vmware_soap_session"] = sessionCookie
    httpContext["cookies"] = cookie
    VmomiSupport.GetRequestContext()["vcSessionCookie"] = sessionCookie
    hostname = vpxdStub.host.split(":")[0]

    context = None
    if hasattr(ssl, "_create_unverified_context"):
        context = ssl._create_unverified_context()
    pbmStub = pyVmomi.SoapStubAdapter(host=hostname,
                                      version="pbm.version.version1",
                                      path="/pbm/sdk",
                                      poolSize=0,
                                      sslContext=context)
    pbmSi = pbm.ServiceInstance("ServiceInstance", pbmStub)
    pbmContent = pbmSi.RetrieveContent()

    return (pbmSi, pbmContent)
Exemple #6
0
    def do_POST(self):
        """ Handle HTTP Post """
        logging.debug("In do_POST: %s" % str(self.client_address))
        responseCode = 500
        response = ""
        closeConnection = False
        httpVersion = float(self.request_version.split("/")[1])

        # Handle SOAPAction (for request version in SOAPAction)
        # Can we have multiple SOAPAction??? No. I guess it is not valid
        soapAction = self.headers.get(_STR_SOAP_ACTION, "")
        version = GetVersion(soapAction)

        cookies = SimpleCookie(self.headers.get('cookie'))
        VmomiSupport.GetHttpContext()['cookies'] = cookies

        # Look for non-identity transfer-encoding before content-length
        reqChunking = False
        gzipResponse = False
        deflateResponse = False
        respChunking = False
        if httpVersion >= 1.1:
            # Request chunking
            xferEncoding = self.headers.get("transfer-encoding", "")
            reqChunking = (self._FindToken(xferEncoding, "chunked")
                           is not None)

            # Accept-Encoding
            acceptEncoding = self.headers.get("accept-encoding", "")
            # Support gzip only for now
            gzipResponse = (self._FindToken(acceptEncoding, "gzip")
                            is not None)
            if not gzipResponse:
                deflateResponse = (self._FindToken(acceptEncoding, "deflate")
                                   is not None)

            # Response chunking
            te = self.headers.get("TE", "chunked")
            respChunking = (self._FindToken(te, "chunked") is not None)

        if reqChunking:
            request = self._ChunkedMessageBodyReader(self.rfile)
        else:
            # Get content length. Max is 16 M
            maxContentLen = 16 * 1024 * 1024
            content_len = maxContentLen

            # Get content length from header
            contentLength = self.headers.get("content-length")
            if contentLength:
                try:
                    contentLength = int(contentLength)
                    if contentLength > maxContentLen:
                        # Larger than max content length allowed. Truncate length
                        logging.warn("Request content length %d > %d" % \
                                                   (contentLength, maxContentLen))
                        contentLength = maxContentLen
                    content_len = contentLength
                except TypeError:
                    pass
            request = _MessageBodyReader(self.rfile, content_len)

        try:
            # Invoke handler
            responseCode, response = self.server.InvokeHandler(
                request, version)
            DebugLogFilteredXML(response)
        except Exception as err:
            assert (responseCode == 500)

        try:
            # Char encoding
            encoding = "utf-8"

            # Determine if response is string or not
            isStringResponse = isinstance(response, six.text_type) or \
                               isinstance(response, six.binary_type)
            if isinstance(response, six.text_type):
                response = response.encode(encoding)

            # Send Header
            self.send_response(responseCode)
            self.send_header("content-type", "text/xml; charset=" + encoding)
            self.send_header("cache-control", "no-cache")
            cookies = VmomiSupport.GetHttpContext()['cookies']
            for cookie in cookies:
                headerValue = cookies[cookie].output(header='')
                self.send_header("set-cookie", headerValue)

            hasContentLength = isStringResponse and not (gzipResponse or \
                                                         deflateResponse or \
                                                         respChunking)
            if hasContentLength:
                # Content length
                responseLen = len(response)
                self.send_header("content-length", str(responseLen))
            else:
                if not respChunking:
                    closeConnection = True

            if httpVersion >= 1.1:
                # Chunking?
                if respChunking:
                    self.send_header("transfer-encoding", "chunked")

                # Gzip content?
                if gzipResponse:
                    self.send_header("content-encoding", "gzip")
                elif deflateResponse:
                    self.send_header("content-encoding", "deflate")

                # Close connection?
                if closeConnection:
                    self.send_header("connection", "close")
            else:
                if closeConnection:
                    self.close_connection = 1

            # End headers
            self.end_headers()

            # Send response
            wfile = self.wfile
            needClose = False
            chunkSize = 8192

            # Work around the partial write bug in python 3 versions up to 3.5
            if sys.version_info.major == 3 and sys.version_info < (3, 6):
                wfile = self._SafeWriter(wfile=wfile)

            # Handle chunking
            if respChunking:
                wfile = self._ChunkedMessageBodyWriter(wfile, chunkSize)
                # Need explicit close for chunked response
                needClose = True

            # Handle compression
            if gzipResponse:
                import gzip
                wfile = gzip.GzipFile(fileobj=wfile, mode="wb")
                needClose = True
            elif deflateResponse:
                wfile = self.DeflateWriter(wfile=wfile)
                needClose = True

            if response:
                if isStringResponse:
                    wfile.write(response)
                else:
                    while True:
                        chunk = response.read(chunkSize)
                        if not chunk:
                            break
                        wfile.write(chunk)
                wfile.flush()

            if needClose:
                wfile.close()

            # Cleanup
            if wfile != self.wfile:
                del wfile

            if not isStringResponse:
                response.close()
            del response

            logging.debug("Done do_POST: %s" % str(self.client_address))
        except Exception as err:
            LogException("Error: Send response exception: ", err)
            self.close_connection = 1