Ejemplo n.º 1
0
class StubAdapterAccessorMixin:
   def __init__(self):
      self._pc = None
      self._pcType = GetVmodlType("vmodl.query.PropertyCollector")
      self._siType = GetVmodlType("vim.ServiceInstance")

   ## Retrieve a managed property
   #
   # @param self self
   # @param mo managed object
   # @param info property info
   def InvokeAccessor(self, mo, info):
      filterSpec = self._pcType.FilterSpec(
         objectSet=[self._pcType.ObjectSpec(obj=mo, skip=False)],
         propSet=[self._pcType.PropertySpec(all=False, type=mo.__class__,
                                                 pathSet=[info.name])],
         )
      ## Cache the property collector if it isn't already
      #  No need to lock _pc since multiple instances of PropertyCollector on
      #  the client will talk to the same instance on the server.
      if not self._pc:
         si = self._siType("ServiceInstance", self)
         self._pc = si.RetrieveContent().propertyCollector
      result = self._pc.RetrievePropertiesEx(specSet=[filterSpec],
                                             options=self._pcType.RetrieveOptions(maxObjects=1))
      objectContent = result.objects[0]
      if len(objectContent.propSet) > 0:
         return objectContent.propSet[0].val
      if len(objectContent.missingSet) > 0 and objectContent.missingSet[0].fault:
         raise objectContent.missingSet[0].fault
      return None
def _AddManagedMethod(vmodlName, methods):
    vmodlType = GetVmodlType(vmodlName)
    for (mVmodl, mWsdl, mVersion, mParams, mResult, mPrivilege,
         mFaults) in methods:
        if mFaults is None:
            mFaults = []
        mName = Capitalize(mVmodl)
        isTask = False
        if mName.endswith("_Task"):
            mName = mName[:-5]
            isTask = True

        if mName in vmodlType._methodInfo:
            return

        params = tuple([
            LazyObject(name=p[0],
                       typeName=p[1],
                       version=p[2],
                       flags=p[3],
                       privId=p[4]) for p in mParams
        ])
        info = LazyObject(name=mName,
                          typeName=vmodlName,
                          wsdlName=mWsdl,
                          version=mVersion,
                          params=params,
                          isTask=isTask,
                          resultFlags=mResult[0],
                          resultName=mResult[1],
                          methodResultName=mResult[2],
                          privId=mPrivilege,
                          faults=mFaults)
        mm = ManagedMethod(info)
        vmodlType._methodInfo[mName] = info
        setattr(vmodlType, mWsdl, mm)
        setattr(vmodlType, mName, mm)
Ejemplo n.º 3
0
 def call_dict(self, val):
     if isinstance(val, dict):
         if val.get("_vimtype"):
             if val.get("_moId"):
                 moId = val.pop("_vimId")
                 if val.get("serverGuid"):
                     serverGuid = val.pop("serverGuid")
                     sub_ins = GetVmodlType(val.pop("_vimtype"))(
                         moId=moId, serverGuid=serverGuid)
                 else:
                     sub_ins = GetVmodlType(val.pop("_vimtype"))(moId=moId)
             else:
                 sub_ins = GetVmodlType(val.pop("_vimtype"))()
             for k, v in val.items():
                 cust_type = sub_ins._GetPropertyInfo(k).type
                 if isinstance(v, dict):
                     setattr(sub_ins, k, cust_type(self.call_dict(v)))
                 if isinstance(v, list):
                     if not v:
                         setattr(sub_ins, k, cust_type())
                     else:
                         mylocal_list = []
                         for each_item in v:
                             print(f"in v list {each_item}")
                             res = self.call_dict(each_item)
                             print(res)
                             mylocal_list.append(res)
                         setattr(sub_ins, k, cust_type(mylocal_list))
                 else:
                     if issubclass(cust_type, datetime):
                         setattr(sub_ins, k, ParseISO8601(v))
                     if issubclass(cust_type, binary):
                         if PY3:
                             v = str.encode(v)
                         data_encode = base64.b64decode(v)
                         setattr(sub_ins, k, cust_type(data_encode))
                     if issubclass(cust_type, type):
                         setattr(sub_ins, k, cust_type(v))
                     else:
                         setattr(sub_ins, k, v)
             return sub_ins
     if isinstance(val, list):
         myins_list = []
         for each_item in val:
             print(each_item)
             myins_list.append(self.call_dict(each_item))
         return myins_list
Ejemplo n.º 4
0
 def call_dict(self, val):
     print(f"val is {val}, type:{type(val)}")
     if isinstance(val, dict):
         if val.get("_vimtype"):
             if val.get("_moId"):
                 moId = val.pop("_vimId")
                 if val.get("serverGuid"):
                     serverGuid = val.pop("serverGuid")
                     sub_ins = GetVmodlType(val.pop("_vimtype"))(moId=moId, serverGuid=serverGuid)
                 else:
                     sub_ins = GetVmodlType(val.pop("_vimtype"))(moId=moId)
             else:
                 sub_ins = GetVmodlType(val.pop("_vimtype"))()
             for k,v in val.items():
                 cust_type = sub_ins._GetPropertyInfo(k).type
                 if isinstance(v, dict):
                     setattr(sub_ins, k, cust_type(self.call_dict(v)))
                 if isinstance(v, list):
                     if not v:
                         setattr(sub_ins, k, cust_type())
                     else:
                         mylocal_list = []
                         for each_item in v:
                             print(f"in v list {each_item}")
                             res=self.call_dict(each_item)
                             print(res)
                             mylocal_list.append(res)
                         setattr(sub_ins, k, cust_type(mylocal_list))
                 else:
                     print(f"cust type is {cust_type}")
                     ct = issubclass(cust_type, binary)
                     print(f"ct is {ct}")
                     if issubclass(cust_type, datetime):
                         print(f"i'm in datetime")
                         setattr(sub_ins, k, ParseISO8601(v))
                     elif issubclass(cust_type, binary):
                         print(f"i'm in binary, {k},{v}")
                         if PY3:
                             v = str.encode(v)
                         data_encode = base64.b64decode(v)
                         setattr(sub_ins, k, cust_type(data_encode))
                         print(f"i'm done")
                     elif issubclass(cust_type, type):
                         setattr(sub_ins, k, cust_type(v))
                     elif issubclass(cust_type, ManagedObject):
                         if isinstance(v, str):
                             mob = v.split(":")
                             print(f"mob {mob}")
                             if len(mob) == 3:
                                 mo_obj, serverGuid, moId = mob
                                 mo_ins = GetVmodlType(mo_obj)(moId=moId, serverGuid=serverGuid)
                             else:
                                 mo_obj,moId = mob
                                 mo_ins = GetVmodlType(mo_obj)(moId=moId)
                         else:
                             mo_ins = self.call_dict(v)
                         print(f"mo_ins {mo_ins}")
                         setattr(sub_ins, k, mo_ins)
                     else:
                         print(f"in else k:{k},v:{v}, cust_type:{cust_type}")
                         setattr(sub_ins, k, v)
             return sub_ins
     elif isinstance(val, list):
         myins_list = []
         for each_item in val:
             print(f"val in list {each_item}")
             myins_list.append(self.call_dict(each_item))
         return myins_list
     else:
         if isinstance(val, str) and ':' in val:
             mob = val.split(":")
             print(f"mob in list {mob}")
             if len(mob) == 3:
                 mo_obj, serverGuid, moId = mob
                 mo_ins = GetVmodlType(mo_obj)(moId=moId, serverGuid=serverGuid)
             else:
                 mo_obj,moId = mob
                 mo_ins = GetVmodlType(mo_obj)(moId=moId)
             return mo_ins
         else:
             return val
Ejemplo n.º 5
0
Archivo: mob.py Proyecto: free-Zen/pvc
 def GetMoType(self, moTypeName, moTypeNS):
     if self.UseWsdlNames():
         return GetWsdlType(moTypeNS, moTypeName)
     else:
         return GetVmodlType(moTypeName)
Ejemplo n.º 6
0
Archivo: mob.py Proyecto: free-Zen/pvc
def main():
    authMap = {'none': NullAuthenticator, 'vim': VimAuthenticator}
    parser = OptionParser()
    parser.add_option('-H',
                      '--soapHost',
                      dest='soapHost',
                      default='localhost',
                      help='Hostname of SOAP server')
    parser.add_option(
        '-S',
        '--soapPort',
        dest='soapPort',
        type='int',
        default=443,
        help='Port of SOAP server (positive for https, negative for http)')
    parser.add_option('-P',
                      '--httpPort',
                      dest='httpPort',
                      type='int',
                      default=8008,
                      help='HTTP port')
    parser.add_option('-n',
                      '--namespace',
                      dest='namespace',
                      default='vim25/5.5',
                      help='SOAP namespace')
    parser.add_option('-p',
                      '--package',
                      dest='package',
                      default='vim',
                      help='VMODL package')
    parser.add_option('--defaultType',
                      dest='defaultType',
                      default='ServiceInstance',
                      help='The default type to show')
    parser.add_option('--defaultMoid',
                      dest='defaultMoid',
                      default='ServiceInstance',
                      help='Moid of the default object')
    parser.add_option('-d',
                      '--dynamic',
                      dest='dynamic',
                      default=False,
                      help='Load dynamic types from server',
                      action="store_true")
    parser.add_option('-a',
                      '--authenticator',
                      dest='auth',
                      default='vim',
                      help='Authentication type %s' % authMap.keys())
    parser.add_option('-r',
                      '--refguide',
                      dest='refguide',
                      help='Reference guide base URL')
    parser.add_option('-f',
                      '--doNotfetchName',
                      dest='fetchNames',
                      default=True,
                      help='Do not fetch names of managed and data objects',
                      action="store_false")
    (options, args) = parser.parse_args()

    if options.auth in authMap.keys():
        auth = authMap[options.auth]()
    else:
        parser.error('Unknown authenticator type "%s"' % options.auth)

    ManagedObjectBrowser(
        siId=options.defaultMoid,
        siType=GetVmodlType('%s.%s' % (options.package, options.defaultType)),
        soapHost=options.soapHost,
        soapPort=options.soapPort,
        httpPort=options.httpPort,
        namespace=options.namespace,
        refGuide=options.refguide,
        auth=auth,
        fetchNames=options.fetchNames,
        dynamic=options.dynamic,
    )
Ejemplo n.º 7
0
Archivo: mob.py Proyecto: free-Zen/pvc
                           issubclass(param.type, ManagedObject) or \
                           issubclass(param.type, list):
                        # Attach namespace snippet for this param
                        tag = param.name + "Response"
                        response = "".join([
                            SoapAdapter.SOAP_START,
                            '<%s xmlns="%s">' %
                            (tag, GetWsdlNamespace(param.version)), value,
                            '</%s>' % tag, SoapAdapter.SOAP_END
                        ])
                        methodArgs[param.name] = \
                           SoapResponseDeserializer(moAdapter).Deserialize(response,
                                                                           param.type)
                    elif param.type is type:
                        methodArgs[param.name] = self.UseWsdlNames() and \
                            GuessWsdlType(value) or GetVmodlType(value)
                    elif param.type is bool:
                        if value.lower() in ('true', 'yes', 't', 'y', '1'):
                            methodArgs[param.name] = True
                        elif value.lower() in ('false', 'no', 'f', 'n', '0'):
                            methodArgs[param.name] = False
                        else:
                            # This should cause an TypeError
                            methodArgs[param.name] = value
                    else:
                        methodArgs[param.name] = param.type(value)

            methodObj = getattr(mo, method)
            try:
                result = methodObj(**methodArgs)
                fault = None
Ejemplo n.º 8
0
 def __init__(self):
     self._pc = None
     self._pcType = GetVmodlType("vmodl.query.PropertyCollector")
     self._siType = GetVmodlType("vim.ServiceInstance")