def FetchSoap(self, moid, version, prop): # Lookup moid try: mo = GetMoManager().LookupObject(moid) except KeyError: raise vmodl.fault.InvalidArgument(invalidProperty="moid") # Get the version string from version uri. urn:vim25/5.5 -> vim.version.version9 try: version = GetVersionFromVersionUri(version) except KeyError: raise vmodl.fault.InvalidArgument(invalidProperty="version") # Lookup property try: moProp = mo._GetPropertyInfo(p.name) except AttributeError: raise vmodl.fault.InvalidArgument(invalidProperty="prop") if not IsChildVersion(version, moProp.version): raise vmodl.fault.InvalidArgument(invalidProperty="prop") # Using local adapter to invoke method instead of direct method call as # it can provide additional vmomi functions like privilege validation, localization, etc localStub = SoapServerStubAdapter(version, GetMoManager()) # Invoke the property accessor return self._ExecuteCommon(localStub.InvokeAccessor, mo, moProp)
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 server(): '''Dummy pyVmomi server that implements the minimal vim API for logging in and calling a couple of methods.''' nullfd = os.open("/dev/null", os.O_RDONLY) os.dup2(nullfd, 1) os.dup2(nullfd, 2) moman = GetMoManager() si = ServiceInstanceImpl("ServiceInstance") moman.RegisterObject(si) sm = SessionManagerImpl("SessionManager") moman.RegisterObject(sm) rf = FolderImpl("RootFolder") moman.RegisterObject(rf) SoapHttpServer.allow_reuse_address = True soapHttpd = SoapHttpServer(("127.0.0.1", PORT), GeneralHttpHandler) soapHttpd.timeout = 300 soapHttpd.soapStubs = None soapHttpd.serve_forever()
if len(match) == 0: raise Errors.NoMatchError( nameid, "No VIB matching '%s' is installed." % (nameid)) elif len(match) > 1: raise Errors.NoMatchError( nameid, "More than one VIB matches '%s'. " "Please try specifying <vendor>:<name> " "to narrow down to one VIB." % (nameid)) vibs.append(match.pop()) t.RemoveVibs(vibs, skipvalidation=force, forcebootbank=noliveinstall) except Exception as e: log.exception(e) DefsImpl.ReformatEsximageErr(e) return "Successfully removed %s" % (', '.join(vibs)) # # Register implementation managed object class # if HAVE_ESXIMAGE: GetMoManager().RegisterObjects([VibCommandImpl("ha-pyesxcli-image-vib")]) else: log.warning( "Unable to import esximage library; esxcli image commands not available." )
''' def StopProactiveRebalance(self): cmd = CLOMTOOLCMD % 'stop-proactive-rebalance' self._RunCommand(cmd) return True ''' # Retrieve CLOM proactive rebalance status by calling clom tool ''' def GetProactiveRebalanceInfo(self): cmd = CLOMTOOLCMD % 'info-proactive-rebalance' info = json.loads(self._RunCommand(cmd)) if info['Running']: start = datetime.fromtimestamp(info["StartTS"]) stop = datetime.fromtimestamp(info["StopTS"]) return vim.host.VsanProactiveRebalanceInfo( running=info["Running"], startTs=start, stopTs=stop, varianceThreshold=info["Variance_Threshold"], timeThreshold=info["Time_Threshold"], rateThreshold=info["Rate_Threshold"]) else: return vim.host.VsanProactiveRebalanceInfo(running=info["Running"]) # Add managed objects during import GetMoManager().RegisterObjects([VsanAsyncSystemImpl("ha-vsan-async-system")])
prof = h.GetProfile() except Exception as e: log.exception(e) DefsImpl.ReformatEsximageErr(e) # error out if no host image profile defined if not prof: msg = "No host image profile defined, cannot continue" raise DefsImpl.EsxcliImageException(errMsg=[msg]) vdata = Vim.EsxCLI.imagex.ValidationData() onlyhost, onlyvprof = prof.Diff(vprof) vdata.compliant = len(onlyhost) == 0 and len(onlyvprof) == 0 vdata.hostProfileName = prof.name vdata.validationProfileName = vprof.name vdata.onlyInHost = list(onlyhost) vdata.onlyInValidationProfile = list(onlyvprof) return [vdata] # # Register implementation managed object class # if HAVE_ESXIMAGE: GetMoManager().RegisterObjects( [ProfileCommandImpl("ha-pyesxcli-image-profile")]) else: log.warning( "Unable to import esximage library; esxcli image commands not available." )
def ExecuteSoap(self, moid, version, method, argument): # Lookup moid try: mo = GetMoManager().LookupObject(moid) except KeyError: raise vmodl.fault.InvalidArgument(invalidProperty="moid") # Get the version string from version uri. urn:vim25/5.5 -> vim.version.version9 try: version = GetVersionFromVersionUri(version) except KeyError: raise vmodl.fault.InvalidArgument(invalidProperty="version") # Cannot invoke method on ManagedMethodExecuter if isinstance(mo, type(self)): raise vmodl.fault.InvalidArgument(invalidProperty="moid") # Lookup Vmodl method methodName = method.rsplit(".", 1)[-1] try: methodInfo = mo._GetMethodInfo(methodName) except AttributeError: # Try again with uncapitalized method name in case of older Python clients try: methodInfo = mo._GetMethodInfo(Uncapitalize(methodName)) except AttributeError: raise vmodl.fault.InvalidArgument(invalidProperty="method") if not IsChildVersion(version, methodInfo.version): raise vmodl.fault.InvalidArgument(invalidProperty="method") # Verify and deserialize args if len(argument) > methodInfo.params: raise vmodl.fault.InvalidArgument(invalidProperty="argument") params = [] iArg = 0 for i in range(0, len(methodInfo.params)): paramInfo = methodInfo.params[i] # Add None param if param is not visible to this version if not IsChildVersion(version, paramInfo.version): params.append(None) continue if iArg >= len(argument): # No incoming args left # Ok if param is optional if paramInfo.flags & F_OPTIONAL: params.append(None) continue # Missing required param raise vmodl.fault.InvalidArgument(invalidProperty="argument") if paramInfo.name != argument[iArg].name: # Check if param is optional if paramInfo.flags & F_OPTIONAL: params.append(None) continue # Name mismatch *** raise vmodl.fault.InvalidArgument(invalidProperty="argument") # Deserialize soap arg to pyVmomi Object try: obj = Deserialize(argument[iArg].val, paramInfo.type) except Exception: raise vmodl.fault.InvalidArgument(invalidProperty="argument") params.append(obj) iArg = iArg + 1 # Using local adapter to invoke method instead of direct method call as # it can provide additional vmomi functions like privilege validation, localization, etc localStub = SoapServerStubAdapter(version, GetMoManager()) # Invoke the method return self._ExecuteCommon(localStub.InvokeMethod, mo, methodInfo, params)
def RegisterManagedMethodExecuter(moId="ha-managed-method-executer-python"): GetMoManager().RegisterObjects([ManagedMethodExecuter(moId)])
except Exception as e: log.exception(e) DefsImpl.ReformatEsximageErr(e) profiles = [] for prof in six.itervalues(allprofiles): imgprof = Vim.EsxCLI.imagex.ImageProfileData() imgprof.name = prof.name imgprof.creator = prof.creator imgprof.acceptanceLevel = Defs.ACCEPTANCE_LEVELS.get( prof.acceptancelevel, 'unknown') # creationtime and modifiedtime are always initialized to DateTime imgprof.created = DefsImpl.FormatDateString(prof.creationtime) imgprof.modified = DefsImpl.FormatDateString(prof.modifiedtime) profiles.append(imgprof) return profiles # # Register implementation managed object class # if HAVE_ESXIMAGE: GetMoManager().RegisterObjects( [DepotCommandImpl("ha-pyesxcli-image-depot")]) else: log.warning( "Unable to import esximage library; esxcli image commands not available." )
def RegisterMoFactory(moFactory, moType, serverGuid=None): GetMoManager().RegisterMoFactory(moFactory, moType, serverGuid)
def RegisterObject(obj, moId=None, serverGuid=None): GetMoManager().RegisterObject(obj, moId, serverGuid)
from MoManager import GetMoManager from . import CLIInfoMgr ## The Vim.CLIManager implementation class # class CLIInfoImpl(Vim.CLIInfo): """ Vim.CLIInfo implementation """ # Fetch cli info for a type name def FetchCLIInfo(self, typeName): try: return CLIInfoMgr.GetCLIInfoMgr().FetchCLIInfo(typeName) except KeyError: message = str(typeName) + " not found" raise Vim.Fault.NotFound(message=message) # Fetch cli info form display name def FetchCLIInfoFromDisplayName(self, name): try: return CLIInfoMgr.GetCLIInfoMgr().FetchCLIInfoFromDisplayName(name) except KeyError: message = str(name) + " not found" raise Vim.Fault.NotFound(message=message) # Add managed objects during import GetMoManager().RegisterObjects([CLIInfoImpl("ha-cli-info-python")])
""" annotations = vmodl.reflect.DynamicTypeManager.Annotation.Array() if flags != 0: if flags & VmomiSupport.F_OPTIONAL: flags &= ~VmomiSupport.F_OPTIONAL annotations.append(self._CreateAnnotation("optional")) if flags & VmomiSupport.F_SECRET: flags &= ~VmomiSupport.F_SECRET annotations.append(self._CreateAnnotation("secret")) if flags & VmomiSupport.F_LINKABLE: flags &= ~VmomiSupport.F_LINKABLE annotations.append(self._CreateAnnotation("linkable")) if flags & VmomiSupport.F_LINK: flags &= ~VmomiSupport.F_LINK annotations.append(self._CreateAnnotation("link")) if flags: # Unknown flag exists assert (False) return annotations # Add managed objects during import GetMoManager().RegisterObjects( [DynamicTypeManager("ha-dynamic-type-manager-python")])
def GetTenantManager(self): return GetMoManager().LookupObject("vcs-tenant-manager")
ErrorCode.VMODL_TENANT_NAME_EMPTY] logging.error("Failed to update tenant: %s", error_msg) raise vmodl.fault.InvalidArgument(invalidProperty="new_name") if len(new_name) > TENANT_NAME_MAX_LEN: error_msg = error_code.error_code_to_message[ ErrorCode.VMODL_TENANT_NAME_TOO_LONG].format(name) logging.error("Failed to update tenant: %s", error_msg) raise vmodl.fault.InvalidArgument(invalidProperty="new_name") if description and len(description) > TENANT_DESC_MAX_LEN: error_msg = error_code.error_code_to_message[ ErrorCode.VMODL_TENANT_DESC_TOO_LONG].format(name) logging.error("Failed to update tenant: %s", error_msg) raise vmodl.fault.InvalidArgument(invalidProperty="description") class VsphereContainerServiceImpl(vim.vcs.VsphereContainerService): '''Implementation of Vsphere Container Serivce''' def __init__(self, moId): vim.vcs.VsphereContainerService.__init__(self, moId) def GetTenantManager(self): return GetMoManager().LookupObject("vcs-tenant-manager") GetMoManager().RegisterObjects([ VsphereContainerServiceImpl("vsphere-container-service"), TenantManagerImpl("vcs-tenant-manager") ])