-
Notifications
You must be signed in to change notification settings - Fork 767
/
Copy pathVmomiSupport.py
2174 lines (1864 loc) · 72.6 KB
/
VmomiSupport.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright (c) 2005-2024 Broadcom. All Rights Reserved.
# The term "Broadcom" refers to Broadcom Inc. and/or its subsidiaries.
# Support for VMOMI abstractions such as VMODL types, versions, etc.
import base64
import threading
from datetime import datetime
from functools import partial
from sys import version_info
import six
from six import PY3, binary_type, string_types
from six.moves import map, range
from . import Iso8601
from . import _allowGetSet
from . import _allowCapitalizedNames
from . import _binaryIsBytearray
if version_info[0] >= 3:
from functools import cmp_to_key
NoneType = type(None)
try:
from six.moves import intern
except ImportError:
# The old version of six package (< 1.8.0) doesn't have intern mapping so
# we need to tolerate the import error here.
def intern(s):
return s
(F_LINK, F_LINKABLE, F_OPTIONAL, F_SECRET) = [1 << x for x in range(4)]
BASE_VERSION = 'vmodl.version.version0'
VERSION1 = 'vmodl.version.version1'
XMLNS_XSD = "http://www.w3.org/2001/XMLSchema"
XMLNS_XSI = "http://www.w3.org/2001/XMLSchema-instance"
XMLNS_VMODL_BASE = "urn:vim25"
# The lock ensures that we serialize the lazy loading. In particular, we need
# to guard against multiple threads loading the same types on the same kind
# of objects at the same time
# The lock is protecting the following variables:
# _topLevelNames, _*DefMap, and _dependencyMap
_lazyLock = threading.RLock()
# Also referenced in __init__.py
_topLevelNames = set()
# Maps to store parameters to create the type for each vmodlName
_managedDefMap = {}
_dataDefMap = {}
_enumDefMap = {}
# Map to store parameters to create the type for each wsdlName
_wsdlDefMap = {}
# Map that stores the nested classes for a given class
# if a.b.c and a.b.d are the nested classes of a.b,
# then _dependencyMap[a.b] = {c,d}
_dependencyMap = {}
# TODO Use a more holistic/data(typeinfo)-driven for all namespaces
# Populate the map in init phase or use the existing maps if possible
# Map top level names to xml namespaces
_urnMap = {"vim": XMLNS_VMODL_BASE, "sms": "urn:sms", "pbm": "urn:pbm"}
# Update the dependency map
# Note: Must be holding the _lazyLock
#
# @param names VmodlName of the type
def _AddToDependencyMap(names):
""" Note: Must be holding the _lazyLock """
curName = names[0]
_topLevelNames.add(curName)
for name in names[1:]:
_dependencyMap.setdefault(curName, set()).add(name)
curName = ".".join([curName, name])
# Check if a particular name is dependent on another
# Note: Must be holding the _lazyLock
#
# @param parent Parent Vmodl name
# @param name Vmodl name to be checked for dependency
# @return True, if name depends on parent, False otherwise
def _CheckForDependency(parent, name):
""" Note: Must be holding the _lazyLock """
if _allowCapitalizedNames:
# If the flag is set, check for both capitalized and
# uncapitalized form. This is a temporary fix for handling
# vim.EsxCLI namespace.
# Ex: If we add vim.EsxCLI.vdisk, then
# _dependencyMap['vim.EsxCLI'] will have value ['vdisk'].
# When we try to check dependency for vdisk, since the flag
# is set, we will uncapitalize EsxCLI and this will result
# in attribute error
dependents = _dependencyMap.get(parent)
if not dependents:
uncapitalizedParent = UncapitalizeVmodlName(parent)
dependents = _dependencyMap.get(uncapitalizedParent)
if dependents:
if name in dependents or Uncapitalize(name) in dependents:
return True
else:
dependents = _dependencyMap.get(parent)
if dependents:
if name in dependents:
return True
return False
# Checks for the type definition in all the maps
# and loads it if it finds the definition
#
# @param name vmodl name of the type
# @return vmodl type
def _LoadVmodlType(name):
isArray = name.endswith("[]")
if isArray:
name = name[:-2]
if _allowCapitalizedNames:
name = UncapitalizeVmodlName(name)
with _lazyLock:
for defMap, loadFn in [(_dataDefMap, LoadDataType),
(_managedDefMap, LoadManagedType),
(_enumDefMap, LoadEnumType)]:
dic = defMap.get(name)
if dic:
typ = loadFn(*dic)
return isArray and typ.Array or typ
return None
# Simple class to store named attributes
class Object:
# Constructor
def __init__(self, **kwargs):
self.__dict__.update(kwargs)
# All properties and methods in vmodl types are created as LazyObject's
# in VmomiSupport. The attributes in these properties and methods that refer
# to vmodl types are "type", "result" and "methodResult". If a program tries
# to access any of these attributes, load the type. The vmodl name of the type
# can be retrieved by adding name to the attribute that is being accessed
# Creating a derived class of Object so that programs that want to use just
# Object are not affected
class LazyObject(Object):
def __getattr__(self, attr):
with _lazyLock:
# Check if another thread already initialized this
obj = self.__dict__.get(attr)
if obj:
return obj
if attr == "type" or attr == "result" or attr == "methodResult":
attrName = attr + "Name"
vmodlName = getattr(self, attrName)
vmodlType = GetVmodlType(vmodlName)
setattr(self, attr, vmodlType)
delattr(self, attrName)
return vmodlType
else:
raise AttributeError(attr)
class Link(six.text_type):
def __new__(cls, obj):
if isinstance(obj, string_types):
return six.text_type.__new__(cls, obj)
elif isinstance(obj, DataObject):
if obj.key:
return six.text_type.__new__(cls, obj.key)
raise AttributeError("DataObject does not have a key to link")
else:
raise ValueError
# LazyType to wrap around actual type
# This is used to intercept attribute accesses of a class
# and load the appropriate nested classes on-demand
class LazyType(type):
def __getattr__(self, attr):
if attr.endswith("[]"):
searchName = attr[:-2]
else:
searchName = attr
with _lazyLock:
nestedClasses = _dependencyMap.get(self.__name__, [])
if searchName in nestedClasses:
return GetVmodlType(self.__name__ + "." + attr)
else:
return super(LazyType, self).__getattribute__(attr)
# LazyModule class
# Used as a placeholder until the actual type is loaded
# If someone wants to use the type, then it is loaded on-demand
class LazyModule(object):
def __init__(self, name):
# name is used to save the current context of the object
# If it is created because of reference to a.b, name will
# be a.b
self.name = name
def __getattr__(self, attr):
# If someone tries to introspect the instance of this class
# using inspect.isclass(), the function will check if the object
# has __bases__ attr. So, throwing an AttributeError to make it work
if attr == "__bases__":
raise AttributeError
with _lazyLock:
# Check if we have already loaded the class or object
# corresponding to this attribute
obj = self.__dict__.get(attr)
if obj:
return obj
name = ".".join([self.name, attr])
# Get the actual vmodlName from the type dictionaries
actualName = _GetActualName(name)
if actualName:
typeObj = GetVmodlType(actualName)
else:
if _CheckForDependency(self.name, attr):
typeObj = LazyModule(name)
else:
urnNS = _urnMap.get(self.name)
if urnNS:
try:
typeObj = GetWsdlType(urnNS, attr)
except KeyError:
raise AttributeError(attr)
except:
import sys
import traceback
sys.exit(traceback.format_exc())
else:
raise AttributeError(attr)
setattr(self, attr, typeObj)
return typeObj
# If the lazy module is representing a data object,
# this will get triggered when some code tries to initialize it
# Load the actual type and pass the arguments to it's init.
def __call__(self, **kwargs):
typ = _LoadVmodlType(self.name)
if typ:
return typ.__call__(**kwargs)
else:
raise AttributeError("'{0}' does not exist".format(self.name))
# Format a python VMOMI object
#
# @param val the object
# @param info the field
# @param indent the level of indentation
# @return the formatted string
def FormatObject(val, info=Object(name="", type=object, flags=0), indent=0):
start = indent * " " + (info.name and "{0} = ".format(info.name) or "")
if val is None:
result = "<unset>"
elif isinstance(val, DataObject):
if info.flags & F_LINK:
result = "<{0}:{1}>".format(val.__class__.__name__, val.key)
else:
result = "({0}) {{\n{1}\n{2}}}".format(
val.__class__.__name__, ',\n'.join([
FormatObject(getattr(val, prop.name), prop, indent + 1)
for prop in val._GetPropertyList()
]), indent * " ")
elif isinstance(val, ManagedObject):
if val._serverGuid is None:
result = "'{0}:{1}'".format(val.__class__.__name__, val._moId)
else:
result = "'{0}:{1}:{2}'".format(val.__class__.__name__,
val._serverGuid, val._moId)
elif isinstance(val, list):
itemType = getattr(val, 'Item', getattr(info.type, 'Item', object))
if val:
item = Object(name="", type=itemType, flags=info.flags)
vmomiObjects = ',\n'.join(
[FormatObject(obj, item, indent + 1) for obj in val]
)
result = "({0}) [\n{1}\n{2}]".format(
itemType.__name__, vmomiObjects, indent * " ")
else:
result = "({0}) []".format(itemType.__name__)
elif isinstance(val, type):
result = val.__name__
elif isinstance(val, UnknownManagedMethod):
# TODO: reuse the base ManagedMethod
result = val.name
elif isinstance(val, ManagedMethod):
result = '{0}.{1}'.format(val.info.type.__name__, val.info.name)
elif isinstance(val, bool):
result = val and "true" or "false"
elif isinstance(val, datetime):
result = Iso8601.ISO8601Format(val)
elif isinstance(val, binary):
result = base64.b64encode(val)
if PY3:
# In python3 the bytes result after the base64 encoding has a
# leading 'b' which causes error when we use it to construct the
# soap message. Workaround the issue by converting the result to
# string. Since the result of base64 encoding contains only subset
# of ASCII chars, converting to string will not change the value.
result = str(result, 'utf-8')
else:
result = repr(val)
return start + result
# Lookup a property for a given object type
#
# @param type the type
# @param name the name of the property
def GetPropertyInfo(type, name):
try:
while name not in type._propInfo:
type = type.__bases__[0]
else:
return type._propInfo[name]
except Exception:
raise AttributeError(name)
# VMOMI Managed Object class
class ManagedObject(object):
_wsdlName = "ManagedObject"
_propInfo = {}
_propList = []
_methodInfo = {}
_version = BASE_VERSION
# Constructor
#
# @param[in] self self
# @param[in] moId The ID of this managed object
# @param[in] stub The stub adapter, if this is a client stub object
def __init__(self, moId, stub=None, serverGuid=None):
try:
moId = intern(moId)
except:
pass
object.__setattr__(self, "_moId", moId)
object.__setattr__(self, "_stub", stub)
object.__setattr__(self, "_serverGuid", serverGuid)
# Invoke a managed method
#
# @param info method info
# @param self The object pointer
# @param ... arguments
def _InvokeMethod(info, self, *posargs, **kwargs):
if len(posargs) > len(info.params):
s = "s" * (len(info.params) != 1)
raise TypeError(
"%s() takes at most %d argument%s (%d given)" %
(Capitalize(info.name), len(info.params), s, len(posargs)))
args = list(posargs) + [None] * (len(info.params) - len(posargs))
if len(kwargs) > 0:
paramNames = [param.name for param in info.params]
for (k, v) in list(kwargs.items()):
try:
idx = paramNames.index(k)
except ValueError:
raise TypeError(
"%s() got an unexpected keyword argument '%s'" %
(Capitalize(info.name), k))
if idx < len(posargs):
raise TypeError(
"%s() got multiple values for keyword argument '%s'" %
(Capitalize(info.name), k))
args[idx] = v
list(map(CheckField, info.params, args))
return self._stub.InvokeMethod(self, info, args)
_InvokeMethod = staticmethod(_InvokeMethod)
# Invoke a managed property accessor
#
# @param info property info
# @param self The object pointer
def _InvokeAccessor(info, self):
return self._stub.InvokeAccessor(self, info)
_InvokeAccessor = staticmethod(_InvokeAccessor)
# In contrast with the Python convention for "private" methods,
# the ManagedObject and DataObject method names beginning with
# an underscore denote public, officially supported system methods.
# The execution of these methods does not involve a remote call.
# Get the ID of a managed object
# Public non-remote method. Officially supported.
def _GetMoId(self):
return self._moId
# Get the serverGuid of a managed object
# Public non-remote method. Officially supported.
def _GetServerGuid(self):
return self._serverGuid
# Get the stub of a managed object
# Public non-remote method. Officially supported.
def _GetStub(self):
return self._stub
# Get a list of all properties of this type and base types
# Public non-remote method. Officially supported.
#
# @param cls The managed object type
@classmethod
def _GetPropertyList(cls, includeBaseClassProps=True):
if not includeBaseClassProps:
return cls._propList
prop = {}
result = []
while cls != ManagedObject:
# Iterate through props, add info for prop not found in
# derived class
result = [
info for info in cls._propList
if prop.setdefault(info.name, cls) == cls
] + result
cls = cls.__bases__[0]
return result
# Get a list of all methods of this type and base types
# Public non-remote method. Officially supported.
#
# @param cls The managed object type
@classmethod
def _GetMethodList(cls):
meth = {}
result = []
while cls != ManagedObject:
# Iterate through methods, add info for method not found in
# derived class
result = [
info for info in list(cls._methodInfo.values())
if meth.setdefault(info.name, cls) == cls
] + result
cls = cls.__bases__[0]
return result
# Lookup a method for a given managed object type
# Public non-remote method. Officially supported.
#
# @param type the type
# @param name the name of the property
@classmethod
def _GetMethodInfo(type, name):
while hasattr(type, "_methodInfo"):
try:
return type._methodInfo[name]
except KeyError:
type = type.__bases__[0]
raise AttributeError(name)
def __setattr__(self, *args):
if self._stub is not None:
raise Exception("Managed object attributes are read-only")
else:
object.__setattr__(self, *args)
__delattr__ = __setattr__
if _allowGetSet:
def __getattr__(self, name):
if name.startswith("Get"):
return lambda: getattr(self, name[3].lower() + name[4:])
elif name.startswith("Set"):
return lambda val: setattr(self, name[3].lower() + name[4:],
val)
raise AttributeError(name)
# The equality test of ManagedObject is for client side only and might
# not be appropriate for server side objects. The server side object has
# to override this function if it has a different equality logic
def __eq__(self, other):
if other is None:
return False
else:
return (self._moId == other._moId
and self.__class__ == other.__class__
and self._serverGuid == other._serverGuid)
def __ne__(self, other):
return not (self == other)
def __hash__(self):
return str(self).__hash__()
__str__ = __repr__ = FormatObject
# shared with DataObject
_GetPropertyInfo = classmethod(GetPropertyInfo)
# VMOMI Data Object class
class DataObject(object):
_wsdlName = "DataObject"
_propInfo = {}
_propList = []
_version = BASE_VERSION
# Constructor
#
# @param info property info
# @param ... keyword arguments indicate properties
def __init__(self, **kwargs):
for property in self._GetPropertyList():
ptype = property.type
if issubclass(ptype, list):
value = ptype()
elif property.flags & F_OPTIONAL:
value = None
elif ptype is bool:
value = False
elif issubclass(ptype, Enum):
value = None
elif issubclass(ptype, str):
value = ""
elif (ptype is long or issubclass(ptype, int)
or issubclass(ptype, float)):
# Take care of byte, short, int, long, float and double
value = ptype(0)
else:
value = None
object.__setattr__(self, property.name, value)
for (k, v) in list(kwargs.items()):
setattr(self, k, v)
# In contrast with the Python convention for "private" methods,
# the ManagedObject and DataObject method names beginning with
# an underscore denote public, officially supported system methods.
# The execution of these methods does not involve a remote call.
# Get a list of all properties of this type and base types
# Public non-remote method. Officially supported.
#
# @param cls the data object type
@classmethod
def _GetPropertyList(cls, includeBaseClassProps=True):
if not includeBaseClassProps:
return cls._propList
prop = {}
result = []
while cls != DataObject:
# Iterate through props, add info for prop not found in
# derived class
result = [
info for info in cls._propList
if prop.setdefault(info.name, cls) == cls
] + result
cls = cls.__bases__[0]
return result
def __setattr__(self, name, val):
CheckField(self._GetPropertyInfo(name), val)
object.__setattr__(self, name, val)
__str__ = __repr__ = FormatObject
# shared with ManagedObject
_GetPropertyInfo = classmethod(GetPropertyInfo)
# Base class for enum types
class Enum(str):
pass
# Base class for array types
class Array(list):
__str__ = __repr__ = FormatObject
# Class for curried function objects
#
# Instances of this class are curried python function objects.
# If g = Curry(f, a1,...,an), then g(b1,...,bm) = f(a1,...,an, b1,...,bm)
class Curry(object):
# Constructor
#
# @param self The object pointer
# @param f the function object
# @param args arguments to fix
def __init__(self, f, *args):
self.f = f
self.args = args
def __call__(self, *args, **kwargs):
args = self.args + args
return self.f(*args, **kwargs)
def __get__(self, obj, type):
if obj:
# curried methods will receive 'self' *after* any fixed arguments
return lambda *args, **kwargs: \
self.f(*(self.args + (obj,) + args), **kwargs)
return self
# Class for managed object methods
class ManagedMethod(Curry):
# Constructor
#
# @param self The object pointer
# @param info method info
def __init__(self, info):
Curry.__init__(self, ManagedObject._InvokeMethod, info)
self.info = info
# __setattr__ implementation for MethodFault object.
#
# Exceptions in python3 have __traceback__ attribute that can be
# (and is - by unittest) modified by exception users. So allow its
# modification although it is not a VMOMI property. Note that
# __traceback__ cannot be deleted.
def _MethodFaultSetAttr(self, name, value):
if name == '__traceback__':
# Call MethodFault.__bases__[1].__setattr__
Exception.__setattr__(self, name, value)
else:
# Call MethodFault.__bases__[0].__setattr__
DataObject.__setattr__(self, name, value)
# Generic method representing unknown API methods returned by the server.
# Server may return unknown method name due to server defects or newer version.
class UnknownManagedMethod(ManagedMethod):
def __init__(self, name):
self.name = name
def __call__(self, *args, **kwargs):
raise Exception("Managed method {} is not available".format(self.name))
# Create the vmodl.MethodFault type
#
# This type must be generated dynamically because it inherits from
# vmodl.DynamicData, which is created dynamically by the emitted code.
#
# @return the new type
def CreateAndLoadMethodFaultType():
with _lazyLock:
props = [
["msg", "string", BASE_VERSION, F_OPTIONAL],
[
"faultCause", "vmodl.MethodFault",
"vmodl.version.version1", F_OPTIONAL
],
[
"faultMessage", "vmodl.LocalizableMessage[]",
"vmodl.version.version1", F_OPTIONAL
]
]
propInfo = {}
propList = [
LazyObject(name=p[0], typeName=p[1], version=p[2], flags=p[3])
for p in props
]
dic = {
"_wsdlName": "MethodFault",
"_propInfo": propInfo,
"_propList": propList,
"_version": BASE_VERSION,
"__setattr__": _MethodFaultSetAttr,
}
for info in propList:
propInfo[info.name] = info
name = "vmodl.MethodFault"
CreateDataType("vmodl.MethodFault", "MethodFault", "vmodl.DynamicData",
BASE_VERSION, props)
return _AddType(
type(Exception)(
name,
(GetWsdlType(XMLNS_VMODL_BASE, "DynamicData"), Exception),
dic))
# If the name of nested class of vmodl type is same as one of the nested
# classes of its parent, then we have to replace it. Else it won't be possible
# to intercept it with LazyType class
# @param vmodl type
# @param parent of the vmodl type
# @return vmodl type
def _CheckNestedClasses(typ, parent):
with _lazyLock:
vmodlName = typ.__name__
nestedClasses = _dependencyMap.get(vmodlName, [])
for nestedClass in nestedClasses:
if hasattr(parent, nestedClass):
setattr(typ, nestedClass,
GetVmodlType(vmodlName + "." + nestedClass))
return typ
# A flag to control whether new type definitions will be frozen
_freezeDefintions = False
# Control whether new type definitions will be frozen. When True is passed,
# subsequent calls to CreateDataType, CreateManagedType and CreateEnumType will
# mark the new type definition as frozen. When False is passed, the usual
# mode will be restored.
def SetFreezeDefinitions(enabled):
global _freezeDefintions
_freezeDefintions = enabled
# The set of frozen names, specified as (namespace, name) pairs. This set is
# accessible only to the _TryFreezeName and _IsNameFrozen
# functions.
_frozenNames = set()
# If the _freezeDefinitions flag is True, adds the type to the set of frozen
# type definitions. Otherwise has no effect.
def _TryFreezeName(typeNs, name, frozenNames):
if _freezeDefintions:
frozenNames.add((typeNs, intern(name)))
_TryFreezeName = partial(_TryFreezeName, frozenNames = _frozenNames)
# Checks whether the specified type has been frozen
def _IsNameFrozen(typeNs, name, frozenNames):
return (typeNs, intern(name)) in frozenNames
_IsNameFrozen = partial(_IsNameFrozen, frozenNames = _frozenNames)
# Make the frozen types set inaccessible outside the two functions which use it
del _frozenNames
# Create and Load a data object type at once
#
# @param vmodlName the VMODL name of the type
# @param wsdlName the WSDL name of the type
# @param parent the VMODL name of the parent type
# @param version the version of the type
# @param props properties of the type
# @return vmodl type
def CreateAndLoadDataType(vmodlName, wsdlName, parent, version, props):
CreateDataType(vmodlName, wsdlName, parent, version, props)
return LoadDataType(vmodlName, wsdlName, parent, version, props)
# Create a data object type
#
# @param vmodlName the VMODL name of the type
# @param wsdlName the WSDL name of the type
# @param parent the VMODL name of the parent type
# @param version the version of the type
# @param props properties of the type
def CreateDataType(vmodlName, wsdlName, parent, version, props):
with _lazyLock:
typeNs = GetInternedWsdlNamespace(version)
if _IsNameFrozen(typeNs, wsdlName):
return
dic = [vmodlName, wsdlName, parent, version, props]
names = vmodlName.split(".")
if _allowCapitalizedNames:
vmodlName = ".".join(name[0].lower() + name[1:] for name in names)
_AddToDependencyMap(names)
_dataDefMap[vmodlName] = dic
_wsdlDefMap[(typeNs, wsdlName)] = dic
_wsdlTypeMapNSs.add(typeNs)
_TryFreezeName(typeNs, wsdlName)
# Load a data object type
# This function also loads the parent of the type if it's not loaded yet
#
# @param vmodlName the VMODL name of the type
# @param wsdlName the WSDL name of the type
# @param parent the VMODL name of the parent type
# @param version the version of the type
# @param props properties of the type
# @return the new data object type
def LoadDataType(vmodlName, wsdlName, parent, version, props):
with _lazyLock:
# Empty lists are saved as None in globals maps as it is much more
# memory efficient. PythonStubEmitter files emit empty lists as None.
if props is None:
props = []
propList = []
for p in props:
# DataObject Property does not contain the privilege for emitted
# types. However, DynamicTypeConstructor from
# DynamicTypeManagerHelper.py creates DataTypes with properties
# containing privilege id.
name, typeName, propVersion, flags = p[:4]
if flags & F_LINK:
if typeName.endswith("[]"):
linkType = "Link[]"
else:
linkType = "Link"
obj = LazyObject(name=name,
typeName=linkType,
version=propVersion,
flags=flags,
expectedType=typeName)
else:
obj = LazyObject(name=name,
typeName=typeName,
version=propVersion,
flags=flags)
propList.append(obj)
propInfo = {}
for info in propList:
propInfo[info.name] = info
dic = {
"_wsdlName": wsdlName,
"_propInfo": propInfo,
"_propList": propList,
"_version": version
}
if _allowGetSet:
for property in propList:
name = property.name
suffix = name[0].upper() + name[1:]
tGlobals = {}
exec(
'def Get%s(self): return getattr(self, "%s")' %
(suffix, name) + '\n' +
'def Set%s(self, v): setattr(self, "%s", v)' %
(suffix, name), tGlobals, dic)
vmodlParent = GetVmodlType(parent)
result = _AddType(LazyType(vmodlName, (vmodlParent, ), dic))
# MethodFault and RuntimeFault are builtin types, but MethodFault
# extends DynamicData, which is (erroneously?) an emitted type, so we
# can't create MethodFault and RuntimeFault until we have loaded
# DynamicData
if wsdlName == "DynamicData":
CreateAndLoadMethodFaultType()
CreateAndLoadDataType("vmodl.RuntimeFault", "RuntimeFault",
"vmodl.MethodFault", BASE_VERSION, [])
# Strictly speaking LocalizedMethodFault is not a data object type
# (it can't be used in VMODL) But it can be treated as a data
# object for (de)serialization purpose
CreateAndLoadDataType(
"vmodl.LocalizedMethodFault", "LocalizedMethodFault",
"vmodl.MethodFault", BASE_VERSION, [
("fault", "vmodl.MethodFault", BASE_VERSION, 0),
("localizedMessage", "string", BASE_VERSION, F_OPTIONAL),
])
return _CheckNestedClasses(result, vmodlParent)
# Create and Load a managed object type at once
#
# @param vmodlName the VMODL name of the type
# @param wsdlName the WSDL name of the type
# @param parent the VMODL name of the parent type
# @param version the version of the type
# @param props properties of the type
# @param methods methods of the type
# @return vmodl type
def CreateAndLoadManagedType(vmodlName, wsdlName, parent, version, props,
methods):
CreateManagedType(vmodlName, wsdlName, parent, version, props, methods)
return LoadManagedType(vmodlName, wsdlName, parent, version, props,
methods)
# Create a managed object type
#
# @param vmodlName the VMODL name of the type
# @param wsdlName the WSDL name of the type
# @param parent the VMODL name of the parent type
# @param version the version of the type
# @param props properties of the type
# @param methods methods of the type
def CreateManagedType(vmodlName, wsdlName, parent, version, props, methods):
with _lazyLock:
typeNs = GetInternedWsdlNamespace(version)
if _IsNameFrozen(typeNs, wsdlName):
return
dic = [vmodlName, wsdlName, parent, version, props, methods]
names = vmodlName.split(".")
if _allowCapitalizedNames:
vmodlName = ".".join(name[0].lower() + name[1:] for name in names)
_AddToDependencyMap(names)
if methods:
for meth in methods:
# We need to use method namespace to avoid duplicate wsdl
# method issue when to find wsdl method from managed type
# namespace for vSAN vmodls that can have different version
# namespaces for managed methods and managed object type.
methNs = GetInternedWsdlNamespace(meth[2])
_SetWsdlMethod(methNs, meth[1], dic)
_managedDefMap[vmodlName] = dic
_wsdlDefMap[(typeNs, wsdlName)] = dic
_wsdlTypeMapNSs.add(typeNs)
_TryFreezeName(typeNs, wsdlName)
# Load a managed object type
# This function also loads the parent of the type if it's not loaded yet
#
# @param vmodlName the VMODL name of the type
# @param wsdlName the WSDL name of the type
# @param parent the VMODL name of the parent type
# @param version the version of the type
# @param props properties of the type
# @param methods methods of the type
# @return the new managed object type
def LoadManagedType(vmodlName, wsdlName, parent, version, props, methods):
with _lazyLock:
# Empty lists are saved as None in globals maps as it is much more
# memory efficient. PythonStubEmitter files emit empty lists as None.
if props is None:
props = []
if methods is None:
methods = []
parent = GetVmodlType(parent)
propInfo = {}
methodInfo = {}
propList = [
LazyObject(name=p[0],
typeName=p[1],
version=p[2],
flags=p[3],
privId=p[4]) for p in props
]
dic = {
"_wsdlName": wsdlName,
"_propInfo": propInfo,
"_propList": propList,
"_methodInfo": methodInfo,
"_version": version
}
for info in propList:
propInfo[info.name] = info
getter = Curry(ManagedObject._InvokeAccessor, info)
dic[info.name] = property(getter)
for (mVmodl, mWsdl, mVersion, mParams, mResult, mPrivilege,
mFaults) in methods:
if mFaults is None:
mFaults = []
mName = Capitalize(mVmodl)
isTask = False
if mWsdl.endswith("_Task"):
isTask = True
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)
methodInfo[mName] = info
mm = ManagedMethod(info)
ns = GetInternedWsdlNamespace(info.version)
method = _SetWsdlMethod(ns, info.wsdlName, mm)
if method != mm:
raise RuntimeError("Duplicate wsdl method {0} {1} "
"(new class {2} vs existing {3})".format(
ns, info.wsdlName, mm.info.type, method.info.type))
dic[mWsdl] = mm
dic[mName] = mm
name = vmodlName
result = _AddType(LazyType(name, (parent, ), dic))