def QueryMoInstances(self, filterSpec=None): """ vmodl.reflect.DynamicTypeManager QueryMoInstances. Get a list of dynamic mo objs """ moInstances = vmodl.reflect.DynamicTypeManager.MoInstance.Array() objects = GetMoManager().GetObjects() for (moId, serverGuid), instance in six.iteritems(objects): si = vmodl.reflect.DynamicTypeManager.MoInstance() si.id = moId #TODO: serverGuid in QueryMoInstances? #si.serverGuid = serverGuid ns = VmomiSupport.GetWsdlNamespace(instance._version) aType = VmomiSupport.GetWsdlType(ns, instance._wsdlName) si.moType = self._GetTypeName(aType) # Filter if filterSpec: if filterSpec.id and filterSpec.id != si.id: continue if filterSpec.typeSubstr and si.moType.find( filterSpec.typeSubstr) == -1: continue moInstances.append(si) return moInstances
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
def _RegisterTypeAndArrayType(self, aType): """ Register both the type and the array type """ vmodlName = VmomiSupport.GetVmodlName(aType) arrayTypeVmodlName = vmodlName + "[]" arrayType = VmomiSupport.GetVmodlType(arrayTypeVmodlName) self._RegisterType(vmodlName, aType) self._RegisterType(arrayTypeVmodlName, arrayType)
def _FailIfWsdlTypeExists(self, version, wsdlName): """ Lookup wsdl type. Raise KeyError if type exists """ try: ns = VmomiSupport.GetWsdlNamespace(version) aType = VmomiSupport.GetWsdlType(ns, wsdlName) except KeyError: aType = None if aType: message = "Type '" + wsdlName + "' already exists" logging.error(message) raise KeyError(message)
def CLIConvertToVmodlClass(classToVmodls): """ Convert class to vmodl based class """ for cls, vmodlName in classToVmodls: try: vmodlType = VmomiSupport.GetVmodlType(vmodlName) except AttributeError: # Failed to find vmodl name logging.error("CLIConvertToVmodlClass: vmodl type %s not found" % vmodlName) raise # Patch the base if the class is not already based on this vmodl type if vmodlType not in cls.__bases__: cls.__bases__ = tuple(list(cls.__bases__) + [VmomiSupport.GetVmodlType(vmodlName)])
def InvokeMethod(self, mo, info, args): # Serialize parameters to soap parameters methodArgs = None if info.params: methodArgs = vmodl.Reflect.ManagedMethodExecutor.SoapArgument.Array() for param, arg in zip(info.params, args): if arg is not None: # Serialize parameters to soap snippets soapVal = SerializeToUnicode(val=arg, info=param, version=self.version) print(soapVal) # Insert argument soapArg = vmodl.Reflect.ManagedMethodExecutor.SoapArgument( name=param.name, val=soapVal) methodArgs.append(soapArg) moid = mo._GetMoId() version = self.versionId methodName = VmomiSupport.GetVmodlName(info.type) + "." + info.name # Execute method result = self.mme.ExecuteSoap(moid=moid, version=version, method=methodName, argument=methodArgs) return self._DeserializeExecutorResult(result, info.result)
def get_vm(self): """ Find unique virtual machine either by UUID or Name. Returns: virtual machine object if found, else None. """ vms = [] if self.vm_uuid: if not self.use_instance_uuid: vm_obj = find_vm_by_id(self.content, vm_id=self.params['vm_uuid'], vm_id_type="uuid") elif self.use_instance_uuid: vm_obj = find_vm_by_id(self.content, vm_id=self.params['vm_uuid'], vm_id_type="instance_uuid") vms = [vm_obj] elif self.vm_name: objects = self.get_managed_objects_properties(vim_type=vim.VirtualMachine, properties=['name']) for temp_vm_object in objects: if len(temp_vm_object.propSet) != 1: continue if temp_vm_object.obj.name == self.vm_name: vms.append(temp_vm_object.obj) break elif self.moid: vm_obj = VmomiSupport.templateOf('VirtualMachine')(self.moid, self.si._stub) if vm_obj: vms.append(vm_obj) if len(vms) > 1: self.module.fail_json(msg="Multiple virtual machines with same name %s found." " Please specify vm_uuid instead of vm_name." % self.vm_name) if vms: self.vm = vms[0]
def main(): if len(sys.argv) < 2: print("Usage: python -m scripts.generate <filename>") return VmomiSupport.populateVersions() [outputFilename] = sys.argv[1:] handle = open(outputFilename, "w") handle.write( json.dumps({ "breakingChanges": VmomiSupport.breakingChanges, "dataTypes": VmomiSupport.dataTypes, "enumTypes": VmomiSupport.enumTypes, "managedTypes": VmomiSupport.managedTypes, "versions": VmomiSupport.versions })) handle.close()
def TestEK(vm1, val, fault, expected=None): tpm = CreateVTPM(TPM_DEV_KEY) if val is not None: val = [VmomiSupport.binary(v) for v in val] tpm.endorsementKeyCertificate = val Log("Trying to set EK certificate to '%s'" % val) cspec = vim.vm.ConfigSpec() vmconfig.AddDeviceToSpec(cspec, tpm, vim.vm.device.VirtualDeviceSpec.Operation.edit) if fault is None: vm.Reconfigure(vm1, cspec) else: try: vm.Reconfigure(vm1, cspec) raise Exception("Reconfigure did not fail for %s" % cspec) except vim.fault.GenericVmConfigFault as e: ok = False for m in e.faultMessage: if m.key == fault: ok = True if not ok: raise except vmodl.fault.InvalidArgument as e: if e.invalidProperty != fault: raise tpm = CheckTPMPresent(vm1) if expected is None: expected = val ekc = tpm.endorsementKeyCertificate if len(expected) != len(ekc): raise Exception("After setting EK to '%s', it is '%s'" % (val, ekc)) for l, r in zip(expected, ekc): if l != r: raise Exception("After setting EK to '%s', it is '%s'" % (val, ekc))
def _get_vm(self): vms = [] if self.uuid: if self.use_instance_uuid: vm_obj = find_vm_by_id(self.content, vm_id=self.uuid, vm_id_type="instance_uuid") else: vm_obj = find_vm_by_id(self.content, vm_id=self.uuid, vm_id_type="uuid") if vm_obj is None: self.module.fail_json(msg="Failed to find the virtual machine with UUID : %s" % self.uuid) vms = [vm_obj] elif self.name: objects = self.get_managed_objects_properties(vim_type=vim.VirtualMachine, properties=['name']) for temp_vm_object in objects: if temp_vm_object.obj.name == self.name: vms.append(temp_vm_object.obj) elif self.moid: vm_obj = VmomiSupport.templateOf('VirtualMachine')(self.module.params['moid'], self.si._stub) if vm_obj: vms.append(vm_obj) if vms: if self.params.get('name_match') == 'first': self.vm = vms[0] elif self.params.get('name_match') == 'last': self.vm = vms[-1] else: self.module.fail_json(msg="Failed to find virtual machine using %s" % (self.name or self.uuid))
def pbm_connect(stub_adapter, disable_ssl_verification=False): """Connect to the VMware Storage Policy Server :param stub_adapter: The ServiceInstance stub adapter :type stub_adapter: SoapStubAdapter :param disable_ssl_verification: A flag used to skip ssl certificate verification (default is False) :type disable_ssl_verification: bool :returns: A VMware Storage Policy Service content object :rtype: ServiceContent """ if disable_ssl_verification: import ssl if hasattr(ssl, '_create_unverified_context'): ssl_context = ssl._create_unverified_context() else: ssl_context = None else: ssl_context = None VmomiSupport.GetRequestContext()["vcSessionCookie"] = \ stub_adapter.cookie.split('"')[1] hostname = stub_adapter.host.split(":")[0] pbm_stub = SoapStubAdapter(host=hostname, version="pbm.version.version1", path="/pbm/sdk", poolSize=0, sslContext=ssl_context) pbm_si = pbm.ServiceInstance("ServiceInstance", pbm_stub) pbm_content = pbm_si.RetrieveContent() return pbm_content
def Decorate(f): """ Param type decorator """ if not hasattr(f, "_params"): f._params = [] else: # Detect duplicated name for obj in f._params: if obj.name == name: message = "@Param duplicated name " + str(name) logging.error(message) raise VmodlDecoratorException(message) ## Verify type if not TypeExists(typ): message = "@Param unknown type " + str(typ) logging.error(message) raise VmodlDecoratorException(message) # Verify version if version and not VersionExists(version): message = "@Param unknown version " + version logging.error(message) raise VmodlDecoratorException(message) param = VmomiSupport.Object(name=name, type=typ, version=version, flags=flags, privId=privId) f._params.insert(0, param) return f
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()
def main(): """ Simple command-line program for dumping the contents of any managed object. """ args = GetArgs() if args.password: password = args.password else: password = getpass.getpass(prompt='Enter password for host %s and ' 'user %s: ' % (args.host,args.user)) context = None if hasattr(ssl, '_create_unverified_context'): context = ssl._create_unverified_context() si = SmartConnect(host=args.host, user=args.user, pwd=password, port=int(args.port), sslContext=context) if not si: print("Could not connect to the specified host using specified " "username and password") return -1 atexit.register(Disconnect, si) obj = VmomiSupport.templateOf(args.type)(args.id, si._stub) print(json.dumps(obj, cls=VmomiSupport.VmomiJSONEncoder, sort_keys=True, indent=4))
def GenerateClassWsdlName(dottedName): ret = dottedName.split(".") for i in range(len(ret)): if ret[i][0].isupper(): break else: ret[i] = VmomiSupport.Capitalize(ret[i]) return "".join(ret)
def TypeExists(name): """ Type exists? """ if VmomiSupport.TypeDefExists(name): return True else: if name.endswith("[]"): name = name[:-2] return name in _gDecoratorTypes
def Decorate(f): """ Attribute type decorator """ # Make sure parent exists try: aType = _gDecoratorTypes[parent] except KeyError: message = "@Attribute " + f.__name__ + \ " parent " + parent + " does not exist" logging.error(message) raise VmodlDecoratorException(message) # Parent is a managed type or data type if not isinstance(aType, ManagedTypeContainer) and \ not isinstance(aType, DataTypeContainer): message = "@Attribute " + f.__name__ + \ " parent " + parent + " is not managed / data type" logging.error(message) raise VmodlDecoratorException(message) # Verify that the property was not already defined if IsDuplicateProperty(aType, f.__name__): message = "@Attribute " + f.__name__ + \ " already defined" logging.error(message) raise VmodlDecoratorException(message) if isinstance(aType, DataTypeContainer): if privId != None: message = "@Attribute for DataObject " + f.__name__ + \ " cannot specify privId" logging.error(message) raise VmodlDecoratorException(message) # Verify type if not TypeExists(typ): message = "@Attribute " + f.__name__ + " unknown type " + str(typ) logging.error(message) raise VmodlDecoratorException(message) # Guess version try: attrVersion = GuessVersion(aType.version, version) except VmodlDecoratorException as err: err.message = "@Attribute " + f.__name__ + \ " " + UnCapitalize(err.message) logging.error(err.message) raise err # Add property to parent aType.properties.append(VmomiSupport.Object(name=f.__name__, type=typ, version=attrVersion, flags=flags, privId=privId, msgIdFormat=msgIdFormat)) return f
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 GetCmd(self, cmd): nsComps = cmd.split(NS_DELIM) if len(nsComps) != 3: raise KeyError apps = self._handler._GetApps(nsComps[0], nsComps[1]) if len(apps) == 0: raise NamespaceError('Command %s not found' % cmd) return (nsComps[0], apps[0], apps[0].methods.get(VmomiSupport.Capitalize(nsComps[2])))
def Decorate(f): """ Return type decorator """ # Verify type if not TypeExists(typ): message = "@Return unknown type " + str(typ) logging.error(message) raise VmodlDecoratorException(message) f._returns = VmomiSupport.Object(name="return", type=typ, flags=flags) return f
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
def CreateEnumType(self, vmodlName, wsdlName, version, values): """ Create enum type """ # Cannot add array type directly assert (not wsdlName.startswith("ArrayOf")) self._FailIfWsdlTypeExists(version, wsdlName) # The types created by this function are currently used at the bootup time of hostd # So, creating and loading them immediately without deferring the loading of the type aType = VmomiSupport.CreateAndLoadEnumType(vmodlName, wsdlName, version, values) return aType
def __init__(self, version=newestVersions.get('vim'), printRequest=False, printResponse=False): SoapAdapter.SoapStubAdapter.__init__(self, version=version) self.ns = VmomiSupport.GetVersionNamespace(version) self.soapHandler = SoapHandler.SoapHandler() self.soapDeserializer = SoapAdapter.SoapResponseDeserializer(self) self.printRequest = printRequest self.printResponse = printResponse ImportTypesAndManagedObjects()
def _CreateAllTypes(self, enumTypes, dataTypes, managedTypes): """ Create pyVmomi types from pyVmomi type definitions """ # Create versions for typeInfo in managedTypes: name = typeInfo[0] version = typeInfo[3] VmomiSupport.AddVersion(version, '', '1.0', 0, name) VmomiSupport.AddVersionParent(version, 'vmodl.version.version0') VmomiSupport.AddVersionParent(version, 'vmodl.version.version1') VmomiSupport.AddVersionParent(version, version) # Create partial types for fn, infos in (VmomiSupport.CreateEnumType, enumTypes), \ (VmomiSupport.CreateDataType, dataTypes), \ (VmomiSupport.CreateManagedType, managedTypes): for typeInfo in infos: try: fn(*typeInfo) except Exception, err: #Ignore errors due to duplicate importing pass
def get_pbm_connection(self, vpxd_stub): VmomiSupport.GetRequestContext()["vcSessionCookie"] = \ vpxd_stub.cookie.split('"')[1] hostname = vpxd_stub.host.split(":")[0] pbm_stub = SoapStubAdapter( host=hostname, version="pbm.version.version11", path="/pbm/sdk", poolSize=0, sslContext=ssl._create_unverified_context()) pbm_si = pbm.ServiceInstance("ServiceInstance", pbm_stub) pbm_content = pbm_si.RetrieveContent() return pbm_content
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)
def connectToSpbm(stub, context): hostname = stub.host.split(":")[0] sessionCookie = stub.cookie.split('"')[1] VmomiSupport.GetRequestContext()["vcSessionCookie"] = sessionCookie pbmStub = SoapStubAdapter( host=hostname, path="/pbm/sdk", version="pbm.version.version2", sslContext=context, ) pbmStub.cookie = stub.cookie pbmSi = pbm.ServiceInstance("ServiceInstance", pbmStub) return pbmSi
def GuessVersion(parentVersion, version): """ Verify version """ if version: # Make sure version exists if not VersionExists(version): message = "Unknown version " + version raise VmodlDecoratorException(message) # Make sure version is same or newer than parent version if not VmomiSupport.IsChildVersion(version, parentVersion): message = "Version " + version + " is not child of " + parentVersion raise VmodlDecoratorException(message) else: # Does not specify method version. Same as parent version version = parentVersion return version
def SetOpId(opId=None, prefix=None, show=False): ''' Set/Generate the opID that will show up in the logs of remote VMODL calls. ''' # If no opId is supplied, generate a new one if not opId: opId = "%x" % random.randint(0, (2**32) - 1) if prefix: opId = prefix + opId if show: print "Using opId: %s" % opId reqCtx = VmomiSupport.GetRequestContext() reqCtx["operationID"] = opId
def _CreateDynReturnTypeInfo(self, flags, aType): """ Create dynamic return type info """ # Get version from type try: version = aType._version except AttributeError: version = VmomiSupport.BASE_VERSION # TODO: Emitted stub missing return val flags. Change emit code info = VmomiSupport.Object(name="result", type=aType, version=version, flags=flags) return self._CreateParamTypeInfo(info)