This repository has been archived by the owner on Dec 2, 2022. It is now read-only.
/
foocenter.py
executable file
·2293 lines (1944 loc) · 86.7 KB
/
foocenter.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
#!/usr/bin/env python3.5.2
#############################################
# REFERENCES #
#############################################
# http://pubs.vmware.com/vsphere-60/topic/com.vmware.wssdk.apiref.doc/right-pane.html
# https://pubs.vmware.com/vsphere-50/index.jsp#com.vmware.wssdk.pg.doc_50/PG_ChB_Using_MOB.20.2.html?path=5_0_1_17_0_0#994707
# http://velemental.com/2012/03/09/a-deep-dive-doing-it-the-manual-way-with-vmware-vim-and-powershell/
# https://github.com/vmware/pyvmomi/blob/master/tests/fixtures/basic_connection.yaml
# https://pubs.vmware.com/vsphere-50/index.jsp#com.vmware.wssdk.pg.doc_50/PG_Ch4_Introduction_Inventory.6.3.html
#############################################
# SSLCERT #
#############################################
# mkdir keys
# cd keys
# openssl genrsa -des3 -out server.key 1024
# openssl req -new -key server.key -out server.csr
# openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt
# openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout mycert.pem -out mycert.pem
import argparse
import datetime
import json
import logging
import lxml
import ssl
import subprocess
import uuid
import xml.etree.ElementTree as ET
from xml.etree.ElementTree import Element as E
from xml.etree.ElementTree import SubElement as SE
from xml.etree.ElementTree import tostring as TS
import xml.dom.minidom
from collections import OrderedDict
from http.server import BaseHTTPRequestHandler, HTTPServer
from pprint import pprint
from lib.utils import *
from lib.datasets.vm import *
USERNAME = 'administrator@vsphere.local'
PASSWORD = 'vmware1234'
#PORT = 443
# https://192.168.121.129/mob/?moid=domain-s44
INVENTORY = {
'datacenters': {
'datacenter-2': {
'name': "datacenter1",
'hosts': ['host-9',
'host-16'],
'vmFolder': 'group-v3',
'folders': {
'group-d1': ['datacenter-2'],
'group-h4': ['domain-s42',
'domain-s44'],
'group-n6': ['network-11'],
'group-s5': ['datastore-10',
'datastore-17'],
'group-v3': ['group-v15',
'group-v12',
'group-v49',
'vm-20']
}
}
},
'clusters': {},
'clustercomputeresources': {},
'computeresources': {
'domain-s42': {
'name': '192.168.121.130',
'host': 'host-16',
},
'domain-s44': {
'name': '192.168.121.128',
'host': 'host-9',
'resourcePool': 'resgroup-45'
}
},
'folders': {
'group-v3': {
'name': 'vm',
'parent': 'datacenter-2',
'children': [
'vm-20',
'group-v12',
'group-v49'
]
},
'group-v12': {
'name': 'testvms',
'parent': 'group-v3',
'children': [
]
},
'group-v49': {
'name': 'testvms2',
'parent': 'group-v3',
},
'group-v50': {
'name': 'testvms1',
'parent': 'group-v3',
},
'group-v154': {
'name': 'testvms2_1',
'parent': 'group-v50',
}
},
'hosts':{
'host-9': {
'name': '192.168.121.128',
'vms': [],
'datastores': ['datastore-10']
},
'host-16': {
'name': '192.168.121.130',
'vms': [],
'datastores': ['datastore-17']
},
},
'resourcepool': {
'resgroup-43': {
'name': 'Resources',
'owner': 'domain-s42',
'vm': []
},
'resgroup-45': {
'name': 'Resources',
'owner': 'domain-s44',
'vm': []
},
},
'datastores': {
'datastore-10': {'name': 'datastore1'},
'datastore-17': {'name': 'datastore2'},
},
'networks': {
'network-11': {
'name': 'VM Network'
}
},
'vm': {
'vm-20': {
'_meta': {
'guestState': 'notrunning',
'powerState': 'poweredOff',
'ipAddress': '',
'uuid': '4211dc52-25bf-981a-7ba8-729436f9b699',
'template': True
},
'parent': 'group-v3',
'name': "template_el7",
'guest': {},
'network': ['network-11'],
'resourcePool': None,
'datastore': ["datastore-10"]
}
}
}
'''
INVENTORY = {
'datacenters': {
'datacenter-2': {
'name': "DC2",
'hosts': ['host-2', 'host-3'],
'folders': {
'group-v0': {}
}
},
'datacenter-1': {
'name': "DC1",
'hosts': ['host-0', 'host-1'],
'folders': {
'group-v0': {
'name': 'vm',
'id': 'group-v0',
'group-v1': {
'name': 'folder1',
'id': 'group-v1',
'vms': ['vm-0', 'vm-1'],
},
'group-v2': {
'name': 'folder2',
'id': 'group-v2',
'vms': ['vm-2'],
},
'group-v3': {
'name': 'testvms',
'id': 'group-v3',
'vms': ['vm-3']
}
}
}
}
},
'clusters': {},
'computeresources': {
'domain-s0': {
'hosts': ['host-0', 'host-1', 'host-2']
}
},
'hosts':{
'host-0': {
'name': '10.10.10.1',
'vms': ['vm-0', 'vm-2', 'vm-5'],
'datastores': ['datastore-0']
},
'host-1': {
'name': '10.10.10.2',
'vms': ['vm-1', 'vm-3'],
'datastores': ['datastore-1']
},
'host-2': {
'name': '10.10.10.3',
'vms': [],
'datastores': ['datastore-2']
},
'host-3': {
'name': '10.10.10.4',
'vms': [],
'datastores': ['datastore-3']
}
},
'resourcepool': {
'resgroup-0': {
'name': 'Resources'
}
},
'datastores': {
'datastore-0': {'name': "data_store_0"},
'datastore-1': {'name': "data_store_1"},
},
'networks': {
'network-0': {
'name': 'VM Network'
}
},
'vm': {
'vm-0': {
'_meta': {
'guestState': 'running',
'ipAddress': '',
'uuid': '421061cd-ae1b-a90a-9c2b-05a2df878849',
'template': True
},
'name': "template_el7",
'guest': {},
'network': ['network-0'],
'resourcePool': 'resgroup-0',
'datastore': ["datastore-0"]
},
'vm-1': {
'_meta': {'guestState': 'running', 'ipAddress': '10.0.0.101', 'uuid': '421061cd-ae1b-a90a-9c2b-05a2df878851'},
'name': "testvm1",
'guest': {},
'network': ['network-0'],
'resourcePool': 'resgroup-0',
'datastore': ["datastore-0"]
},
'vm-2': {
'_meta': {'guestState': 'running', 'ipAddress': '10.0.0.102', 'uuid': '421061cd-ae1b-a90a-9c2b-05a2df878852'},
'name': "testvm2",
'guest': {},
'network': ['network-0'],
'resourcePool': 'resgroup-0',
'datastore': ["datastore-0"]
},
'vm-3': {
'_meta': {'guestState': 'running', 'ipAddress': '10.0.0.103', 'uuid': '421061cd-ae1b-a90a-9c2b-05a2df878853'},
'name': "testvm3",
'guest': {},
'network': ['network-0'],
'resourcePool': 'resgroup-0',
'datastore': ["datastore-1"]
},
'vm-4': {
'_meta': {'guestState': 'running', 'ipAddress': '10.0.0.104', 'uuid': '421061cd-ae1b-a90a-9c2b-05a2df878854'},
'name': "testvm4",
'guest': {},
'network': ['network-0'],
'resourcePool': 'resgroup-0',
'datastore': ["datastore-1"]
}
}
}
'''
#############################################
# CLIENT SESSIONS #
#############################################
EVENTCHAINS = {}
TASKS = {}
VIEWMANAGERS = {}
CONTAINERVIEWS = {}
class VCenter(BaseHTTPRequestHandler):
def do_REST(self, method, path, data=None):
# ['POST', '/xapi/inventory', 'HTTP/1.1']
# default empty response
resp = json.dumps({})
# what is the resource being called?
xparts = path.split('/')
xparts = [x for x in xparts if x]
print(xparts)
if len(xparts) == 1 and method == 'GET':
resp = json.dumps(INVENTORY)
elif xparts[1] == 'inventory':
if method == 'POST':
# assume the caller wants to increase the inventory size
pdict = json.loads(data)
extend_inventory(**pdict)
elif method == 'GET':
if len(xparts) == 2:
resp = json.dumps(INVENTORY)
else:
import pdb; pdb.set_trace()
else:
pass
else:
print('%s not yet handled in REST api' % xparts)
import pdb; pdb.set_trace()
rc = 200
self.send_response(rc)
self.send_header("Content-type", "text/json")
self.send_header("msg", "OK")
self.end_headers()
self.wfile.write(bytes(resp, 'utf-8'))
def do_GET(self):
# 'GET /sdk/vimServiceVersions.xml HTTP/1.1'
requestline = self.requestline
rparts = requestline.split()
url = rparts[1]
if url.startswith('/xapi'):
self.do_REST('GET', url)
elif url == '/sdk/vimServiceVersions.xml':
self.send_response(200)
self.send_header("Content-type", "text/xml")
f = open('fixtures/vc550_vimServiceVersions.xml', 'r')
fdata = f.read()
f.close()
self.wfile.write(bytes(fdata, 'utf-8'))
#self.wfile.write(bytes(vimServiceVersions, 'utf-8'))
else:
print("#######################################")
print(" UNKNOWN PATH: %s" % url)
print("#######################################")
import pdb; pdb.set_trace()
self.send_response(200)
self.send_header("Content-type", "text/html")
self.end_headers()
self.wfile.write(bytes("<html><head><title>Title goes here.</title></head>", "utf-8"))
self.wfile.write(bytes("<body><p>This is a test.</p>", "utf-8"))
self.wfile.write(bytes("<p>You accessed path: %s</p>" % self.path, "utf-8"))
self.wfile.write(bytes("</body></html>", "utf-8"))
def do_POST(self):
requestline = self.requestline
rparts = requestline.split()
url = rparts[1]
postdata = self.rfile.read(int(self.headers['Content-Length']))
postdata = postdata.decode("utf-8")
# REST SHIM ...
if url.startswith('/xapi'):
logging.debug('REST POST %s' % url)
self.do_REST('POST', url, data=postdata)
return None
# Convert POST XML to dict
query = xml2dict(postdata)
logging.debug("# QUERY START")
logging.debug(json.dumps(query, indent=2))
logging.debug("# QUERY END")
rc = 200 #http returncode
# What is the method being called?
methodCalled = list(query['Body'].keys())[0]
logging.debug('methodCalled: %s' % methodCalled)
if hasattr(self, methodCalled):
# call the method
caller = getattr(self, methodCalled)
resp = caller(postdata, query)
if type(resp) == tuple:
rc = resp[1]
resp = resp[0]
else:
print('##################################################')
print('UNKNOWN METHOD: %s' % methodCalled)
print('##################################################')
import pdb; pdb.set_trace()
logging.debug("# RESPONSE START")
splitxml(resp)
logging.debug("# RESPONSE END")
self.send_response(rc)
self.send_header("Content-type", "text/xml")
if rc == 200:
self.send_header("msg", "OK")
else:
self.send_header("msg", "Internal Server Error")
self.end_headers()
#try:
# bytes(resp, 'utf-8')
#except TypeError:
# import pdb; pdb.set_trace()
if type(resp) == bytes:
self.wfile.write(resp)
else:
self.wfile.write(bytes(resp, 'utf-8'))
def __combine_soap_resp(self, rtype, urn, rval):
# <LoginResponse xmlns=\"urn:vim25\">
resp = ''
resp += "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
resp += envelope_header + '\n'
resp += "<soapenv:Body>" + '\n'
resp += "<%s xmlns=\"urn:%s\">" % (rtype, urn)+ '\n'
resp += rval
resp += "</%s>" % rtype + '\n'
resp += "</soapenv:Body>" + '\n'
resp += envelope_footer + '\n'
return resp
def RetrieveServiceContent(self, postdata, query):
f = open('fixtures/vc550_RetrieveServiceContentResponse.xml', 'r')
fdata = f.read()
f.close()
return fdata
def Login(self, postdata, query):
inusername = query.get('Body').get('Login').get('userName')
inpassword = query.get('Body').get('Login').get('password')
rc = 200
if inusername == USERNAME and inpassword == PASSWORD:
f = open('fixtures/vc550_LoginResponse.xml', 'r')
xml = f.read()
f.close()
else:
rc = 500
xml = '''<?xml version=\"1.0\" encoding=\"UTF-8\"?>
<soapenv:Envelope
xmlns:soapenc=\"http://schemas.xmlsoap.org/soap/encoding/\"
xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\"
xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"
xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">
<soapenv:Body>
<soapenv:Fault>
<faultcode>ServerFaultCode</faultcode>
<faultstring>Cannot complete login due to an incorrect user name or password.</faultstring>
<detail>
<InvalidLoginFault xmlns=\"urn:vim25\" xsi:type=\"InvalidLogin\">
</InvalidLoginFault>
</detail>
</soapenv:Fault>
</soapenv:Body>
</soapenv:Envelope>'''
return (xml, rc)
def Logout(self, postdata, query):
X = self._get_soap_element()
Body = SE(X, 'soapenv:Body')
LResponse = SE(Body, 'LogoutResponse')
LResponse.set('xmlns', "urn:vim25")
fdata = TS(X).decode("utf-8")
return (fdata, 200)
def DestroyView(self, postdata, query):
global CONTAINERVIEWS
print("DESTROYVIEW")
print(postdata)
print(query)
key = query.get('Body', {}).get('DestroyView', {}).get('_this', None)
if key:
CONTAINERVIEWS.pop(key, None)
X = self._get_soap_element()
Body = SE(X, 'soapenv:Body')
destroyResponse = SE(Body, 'DestroyViewResponse')
destroyResponse.set('xmlns', 'urn:vim25')
fdata = TS(X).decode("utf-8")
return fdata
def CreateContainerView(self, postdata, query):
# A container view is a request for some type of object
# The response should be a session number which the
# client will later request the results for.
global CONTAINERVIEWS
# What is the sessionid going to be?
# session[0bc77834-77fc-7422-e2cd-81d4e5127926]52ef3fa7-892d-d0c0-d12d-7f16d61aa6e2
sessionid = uuid.uuid4()
sessionid2 = uuid.uuid4()
sessionid = 'session[' + str(sessionid) + ']' + str(sessionid2)
# What does the requester want?
qobject = query.get('Body').get('CreateContainerView').get('container')
qtype = query.get('Body').get('CreateContainerView').get('type')
# Store this for future reference ...
CONTAINERVIEWS[sessionid] = {'container': qobject, 'type': qtype}
# Build the SOAP response ...
X = self._get_soap_element()
Body = SE(X, 'soapenv:Body')
CreateContainerViewResponse = SE(Body, 'CreateContainerViewResponse')
CreateContainerViewResponse.set('xmlns', 'urn:vim25')
returnval = SE(CreateContainerViewResponse, 'returnval')
returnval.set('type', 'ContainerView')
returnval.text = sessionid
fdata = TS(X).decode("utf-8")
return fdata
def RetrieveProperties(self, postdata, query):
## SOMETIMES A SELECTSET IS GIVEN
# 'specSet': {'objectSet': {'obj': 'group-d1',
# 'selectSet': {'name': 'resource_pool_vm_traversal_spec',
# 'path': 'vm',
# 'type': 'ResourcePool'}},
# 'propSet': {'type': 'HostSystem'}
## SOMETIMES JUST A PROPSET
# specSet': {'objectSet': {'obj': 'host-28'}
# 'propSet': {'type': 'HostSystem'}
requested = None
select_path = None
propset_path = None
propset_type = None
try:
requested = query.get('Body').get('RetrieveProperties').get('specSet').get('objectSet').get('obj')
except:
pass
try:
select_path = query.get('Body').get('RetrieveProperties').get('specSet')\
.get('objectSet').get('selectSet').get('path')
except:
pass
try:
propset_path = query.get('Body').get('RetrieveProperties').get('specSet').get('propSet').get('pathSet')
except:
pass
try:
propset_type = query.get('Body').get('RetrieveProperties').get('specSet').get('propSet').get('type')
except:
pass
if 'TraversalSpec' in postdata:
#print("# TRAVERSALSPEC ...")
# https://www.vmware.com/support/developer/vc-sdk/visdk2xpubs/ReferenceGuide/vmodl.query.PropertyCollector.TraversalSpec.html
#root = ET.fromstring(postdata)
#body = root[1]
#rprops = body.getchildren()
#import pdb; pdb.set_trace()
# Just return a list of HostSystems with VM properties?
X = self._get_soap_element()
Body = SE(X, 'soapenv:Body')
RPResponse = SE(Body, 'RetrievePropertiesResponse')
RPResponse.set('xmlns', "urn:vim25")
for k,v in INVENTORY['hosts'].items():
this_rval = E("returnval")
this_obj = SE(this_rval, 'obj')
this_obj.set('type', 'HostSystem')
this_obj.text = k
this_propset = SE(this_rval, 'propSet')
this_name = SE(this_propset, 'name')
this_name.text = 'name'
this_val = SE(this_propset, 'val')
this_val.set('xsi:type', 'ArrayOfManagedObjectReference')
for vm in v['vms']:
MO = E('ManagedObjectReference')
MO.set('type', 'VirtualMachine')
MO.set('xsi:type', 'ManagedObjectReference')
MO.text = vm
this_val.append(MO)
RPResponse.append(this_rval)
fdata = TS(X).decode("utf-8")
elif requested == 'group-d1':
# This is a request for the known datacenters
print("# DATACENTERS ...")
if propset_type == 'HostSystem' and propset_path == 'name':
# FIXME - is this asking for a list of VMs or hostsystems?
# What host's VMs does it want?
print("# DATACENTERS :: HOSTSYSTEM :: NAME ...")
X = self._get_soap_element()
Body = SE(X, 'soapenv:Body')
RPResponse = SE(Body, 'RetrievePropertiesResponse')
RPResponse.set('xmlns', "urn:vim25")
ReturnVal = SE(RPResponse, "returnval")
if select_path == 'vm':
# This req wants a list of VMs for a the given host (whch host?)
import pdb; pdb.set_trace()
else:
OType = SE(ReturnVal, 'obj')
OType.set('type', "HostSystem")
OType.text = 'group-d1'
PropSet = SE(ReturnVal, 'propSet')
PName = SE(PropSet, 'name')
PName.text = 'name'
PVal = SE(PropSet, 'val')
PVal.set('xsi:type', "xsd:ArrayOfManagedObjectReference")
for k,v in INVENTORY['datacenters'].items():
MO = E('ManagedObjectReference')
MO.set('type', 'Datacenter')
MO.set('xsi:type', 'ManagedObjectReference')
MO.text = k
PVal.append(MO)
# Make into string
fdata = TS(X).decode("utf-8")
elif propset_type == 'HostSystem' and propset_path == 'vm':
print("# DATACENTERS :: HOSTSYSTEM :: VM ...")
X = self._get_soap_element()
Body = SE(X, 'soapenv:Body')
RPResponse = SE(Body, 'RetrievePropertiesResponse')
RPResponse.set('xmlns', "urn:vim25")
for k,v in INVENTORY['hosts'].items():
ReturnVal = E("returnval")
OType = SE(ReturnVal, 'obj')
OType.set('type', "HostSystem")
OType.text = k
PropSet = SE(ReturnVal, 'propSet')
PName = SE(PropSet, 'name')
PName.text = 'name'
PVal = SE(PropSet, 'val')
PVal.set('xsi:type', "xsd:string")
PVal.text = v['name']
RPResponse.append(ReturnVal)
# Make into string
fdata = TS(X).decode("utf-8")
elif propset_type == 'Folder' and propset_path == 'name':
print("# DATACENTERS :: FOLDER :: NAME ...")
print("# ROOT Folder ...")
X = self._get_soap_element()
Body = SE(X, 'soapenv:Body')
RPResponse = SE(Body, 'RetrievePropertiesResponse')
RPResponse.set('xmlns', "urn:vim25")
ReturnVal = SE(RPResponse, "returnval")
OType = SE(ReturnVal, 'obj')
OType.set('type', "Folder")
OType.text = 'group-d1'
PropSet = SE(ReturnVal, 'propSet')
PName = SE(PropSet, 'name')
PName.text = 'name'
PVal = SE(PropSet, 'val')
PVal.set('xsi:type', "xsd:string")
PVal.text = 'Datacenters'
# Make into string
fdata = TS(X).decode("utf-8")
elif propset_type == 'Datacenter' and propset_path == 'name':
print("# ROOT Folder ...")
X = self._get_soap_element()
Body = SE(X, 'soapenv:Body')
RPResponse = SE(Body, 'RetrievePropertiesResponse')
RPResponse.set('xmlns', "urn:vim25")
for k,v in INVENTORY['datacenters'].items():
ReturnVal = E("returnval")
OType = SE(ReturnVal, 'obj')
OType.set('type', "Datacenter")
OType.text = k
PropSet = SE(ReturnVal, 'propSet')
PName = SE(PropSet, 'name')
PName.text = 'name'
PVal = SE(PropSet, 'val')
PVal.set('xsi:type', "xsd:string")
PVal.text = v['name']
RPResponse.append(ReturnVal)
# Make into string
fdata = TS(X).decode("utf-8")
else:
import pdb; pdb.set_trace()
elif propset_type == 'ServiceInstance' and propset_path == 'content':
#print("# (1) USING DEFAULT PROPERTIES RESP")
#f = open('fixtures/vc550_RetrievePropertiesResponse.xml', 'r')
#f = open('fixtures/vc550_RetrieveServiceContentResponse.xml.bak', 'r')
f = open('fixtures/vc550_RetrievePropertiesResponse_ServiceInstance_ServiceContent.xml', 'r')
fdata = f.read()
f.close()
elif propset_type == 'HostSystem' and propset_path == 'vm':
# make list of VMs for the host
host = requested
#print("# MAKING HOST W/ VMLIST")
X = self._get_soap_element()
Body = SE(X, 'soapenv:Body')
RPResponse = SE(Body, 'RetrievePropertiesResponse')
RPResponse.set('xmlns', "urn:vim25")
ReturnVal = SE(RPResponse, "returnval")
OType = SE(ReturnVal, 'obj')
OType.set('type', "HostSystem")
OType.text = "host-28"
PropSet = SE(ReturnVal, 'propSet')
PName = SE(PropSet, 'name')
PName.text = 'vm'
PVal = SE(PropSet, 'val')
PVal.set('xsi:type', "ArrayOfManagedObjectReference")
# Iterate through the VMs and add them as children to the Val
for vm in INVENTORY['hosts'][host]['vms']:
MO = E('ManagedObjectReference')
MO.set('type', 'VirtualMachine')
MO.set('xsi:type', 'ManagedObjectReference')
MO.text = vm
PVal.append(MO)
# Make into string
fdata = TS(X).decode("utf-8")
elif propset_type == 'HostSystem' and propset_path == 'name':
#print("# MAKING NAME PROP FOR HOST:%s" % requested)
host = requested
X = self._get_soap_element()
Body = SE(X, 'soapenv:Body')
RPResponse = SE(Body, 'RetrievePropertiesResponse')
RPResponse.set('xmlns', "urn:vim25")
ReturnVal = SE(RPResponse, "returnval")
OType = SE(ReturnVal, 'obj')
OType.set('type', "HostSystem")
OType.text = host
PropSet = SE(ReturnVal, 'propSet')
PName = SE(PropSet, 'name')
PName.text = 'name'
PVal = SE(PropSet, 'val')
PVal.set('xsi:type', "xsd:string")
PVal.text = INVENTORY['hosts'][host]['name']
# Make into string
fdata = TS(X).decode("utf-8")
elif propset_type == 'VirtualMachine' and propset_path == 'name':
# need to return the name of the object
#print("# MAKING NAME PROP FOR VM:%s" % requested)
vm = requested
X = self._get_soap_element()
Body = SE(X, 'soapenv:Body')
RPResponse = SE(Body, 'RetrievePropertiesResponse')
RPResponse.set('xmlns', "urn:vim25")
ReturnVal = SE(RPResponse, "returnval")
OType = SE(ReturnVal, 'obj')
OType.set('type', "VirtualMachine")
OType.text = vm
PropSet = SE(ReturnVal, 'propSet')
PName = SE(PropSet, 'name')
PName.text = 'name'
PVal = SE(PropSet, 'val')
PVal.set('xsi:type', "xsd:string")
PVal.text = INVENTORY['vm'][vm]['name']
# Make into string
fdata = TS(X).decode("utf-8")
elif propset_type == 'ResourcePool' and propset_path == 'name':
X = self.get_soap_properties_response('resourcepool', propset_type, requested, 'name', 'Resources')
fdata = TS(X).decode("utf-8")
elif propset_type == 'VirtualMachine' and propset_path == 'summary':
X = self.get_soap_properties_response('vm', propset_type, requested, 'summary', 'VirtualMachineSummary')
fdata = TS(X).decode("utf-8")
elif propset_type == 'VirtualMachine' and propset_path == 'guest':
X = self.get_soap_properties_response('vm', propset_type, requested, 'guest', 'GuestInfo')
fdata = TS(X).decode("utf-8")
elif propset_type == 'VirtualMachine' and propset_path == 'datastore':
X = self.get_soap_properties_response('vm', propset_type, requested, 'datastore', 'Datastore')
fdata = TS(X).decode("utf-8")
elif propset_type == 'VirtualMachine' and propset_path == 'network':
X = self.get_soap_properties_response('vm', propset_type, requested, 'network', 'Network')
fdata = TS(X).decode("utf-8")
elif propset_type == 'VirtualMachine' and propset_path == 'resourcePool':
X = self.get_soap_properties_response('vm', propset_type, requested,
'resourcePool', 'ResourcePool', xsitype='Resources')
fdata = TS(X).decode("utf-8")
#import pdb; pdb.set_trace()
elif propset_type == 'VirtualMachine' and propset_path == 'alarmActionsEnabled':
import pdb; pdb.set_trace()
X = self.get_soap_properties_response('vm', propset_type, requested, 'alarmActionsEnabled', 'alarmActionsEnabled')
fdata = TS(X).decode("utf-8")
elif requested.startswith('host-'):
# return the list of VMs for the host
print("# HOST: %s" % requested)
X = self._get_soap_element()
Body = SE(X, 'soapenv:Body')
RPResponse = SE(Body, 'RetrievePropertiesResponse')
RPResponse.set('xmlns', "urn:vim25")
for vm in INVENTORY['hosts'][requested]['vms']:
this_rval = E("returnval")
this_obj = SE(this_rval, 'obj')
this_obj.set('type', 'VirtualMachine')
this_obj.text = vm
this_propset = SE(this_rval, 'propSet')
this_name = SE(this_propset, 'name')
this_name.text = 'name'
this_val = SE(this_propset, 'val')
this_val.set('xsi:type', 'xsd:string')
this_val.text = INVENTORY['vms'][vm]['name']
RPResponse.append(this_rval)
fdata = TS(X).decode("utf-8")
else:
#print("# USING DEFAULT PROPERTIES RESP")
f = open('fixtures/vc550_RetrievePropertiesResponse.xml', 'r')
fdata = f.read()
f.close()
return fdata
def FindByInventoryPath(self, postdata, query):
# inventoryPath': 'DC1/vm/testvms'}
'''
<?xml version="1.0" encoding="UTF-8"?>
<soapenv:Envelope ...">
<soapenv:Body>
<FindByInventoryPathResponse xmlns="urn:vim25">
<returnval type="Folder">group-v61</returnval>
</FindByInventoryPathResponse>
</soapenv:Body>
</soapenv:Envelope>
'''
splitxml(postdata)
searchpath = query.get('Body', {}).\
get('FindByInventoryPath', {}).\
get('inventoryPath', None)
parts = searchpath.split('/')
dcname = parts[0]
dcid = None
folder = None
# find the datacenter id based on name
for k,v in INVENTORY['datacenters'].items():
if v['name'] == dcname:
dcid = k
break
# find the folder id based on dc and path
if dcid:
folders = INVENTORY['datacenters'][dcid]['folders']
lastfolder = None
for idx,x in enumerate(parts):
if not lastfolder:
lastfolder = folders
continue
found = False
for k,v in lastfolder.items():
if k == 'name' or k == 'id':
continue
if type(v) != dict:
continue
if not 'name' in x:
continue
if v['name'] == x:
found = True
lastfolder = v
continue
#if not found:
# raise "ERROR: folder path not found"
X = self._get_soap_element()
Body = SE(X, 'soapenv:Body')
FIPR = SE(Body, 'FindByInventoryPathResponse')
FIPR.set('xmlns', 'urn:vim25')
if found:
RVAL = SE(FIPR, 'returnval')
RVAL.set('type', 'Folder')
RVAL.text = lastfolder['id']
fdata = TS(X).decode("utf-8")
return fdata
def RetrievePropertiesEx(self, postdata, query):
requested = None
select_path = None
propset_path = None
propset_type = None
try:
requested = query.get('Body').get('RetrievePropertiesEx').get('specSet').get('objectSet').get('obj')
except: