-
Notifications
You must be signed in to change notification settings - Fork 26
/
run_central_instances.py
executable file
·1987 lines (1671 loc) · 76.8 KB
/
run_central_instances.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 python
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this program; if not, write to the Free Software
# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#
"""
This is a script that executes a number of tests on servers defined in
a file of servers to test the characteristics of the servers themselves
and the pybem algorithms for the get_central_instances() method. It
gets the servers for which tests are to be executed from a file, allows the
user to select particular servers, and then executes all of the defined tests
and display methods or just those selected on the command line.
Output is sent to stdout.
It is not publically supported but to be used as apywbem project internal test
tool.
NOTE: Since this is a development support tool, in includes an import that
is not part of the pywbem install imports (tabulate). This package must
be manually imported for this script to execute correctly
"""
from __future__ import absolute_import, print_function
import sys
import os
import argparse as _argparse
from collections import namedtuple
from collections import defaultdict
import textwrap
import threading
import datetime
import traceback
import yaml
from operator import itemgetter
try:
import tabulate
except ImportError as ie:
raise ImportError('tabulate is not part of pywbem install and must be '
'manually installed: %s' % ie)
import six
import pywbem
from pywbem._nocasedict import NocaseDict
from pywbem._cliutils import SmartFormatter as _SmartFormatter
from pywbem import __version__
from tests.end2endtest.utils.server_definition_file import \
ServerDefinitionFile
VERBOSE = False
TABLE_FORMAT = 'simple'
SERVER_FILE = 'server_file.yml'
SERVER_EXAMPLE_FILE = 'server_file_example.yml'
SCRIPT_DIR = os.path.dirname(__file__)
# Named tuple to define Central Class, Scoping Class, ScopingPath.
ProfileDef = namedtuple('ProfileDef', ['central_class', 'scoping_class',
'scoping_path', 'type',
'comments'])
# TODO: Most of these varaiables should be within the main and test servers
# methods
# if not empty this is a list of profiles found in the test but not in the
# all_profiles_dict or where the definitions are incomplete in the
# all_profiles_dict
PROFILES_WITH_NO_DEFINITIONS = defaultdict(list)
SERVERS_FOR_PROFILE = defaultdict(list)
# summary info on profiles, etc. for each server. A row is added for each
# server tested.
GET_CENTRAL_INST_ROWS = []
# results dictionary for Central instance error.
GET_CENTRAL_INST_ERRS = {}
# Global set of rows to create a table of the assoc property counts for all
# servers.
ASSOC_PROPERTY_COUNTS = []
# Results of the direction test for each server. This dictionary has
# server name as key and the string defining the direction for CIM_Referenced
# profile as the value for each server tested.
SVR_DIRECTION = {}
# results from the fast test for direction.
FAST_TEST_RESULTS = []
PROD_TEST_RESULTS = []
SDF_DIR = os.path.join('tests', 'server_definitions')
DEFAULT_SERVER_FILE = os.path.join(SDF_DIR, 'server_definition_file.yml')
class _WbemcliCustomFormatter(_SmartFormatter,
_argparse.RawDescriptionHelpFormatter):
"""
Define a custom Formatter to allow formatting help and epilog.
argparse formatter specifically allows multiple inheritance for the
formatter customization and actually recommends this in a discussion
in one of the issues:
https://bugs.python.org/issue13023
Also recommended in a StackOverflow discussion:
https://stackoverflow.com/questions/18462610/argumentparser-epilog-and-description-formatting-in-conjunction-with-argumentdef
"""
pass
class ElapsedTimer(object):
"""
Set up elapsed time timer. Calculates time between initiation
and access.
"""
def __init__(self):
""" Initiate the object with current time"""
self.start_time = datetime.datetime.now()
def reset(self):
""" Reset the start time for the timer"""
self.start_time = datetime.datetime.now()
def elapsed_ms(self):
""" Get the elapsed time in milliseconds. returns floating
point representation of elapsed time in seconds.
"""
dt = datetime.datetime.now() - self.start_time
return ((dt.days * 24 * 3600) + dt.seconds) * 1000 \
+ dt.microseconds / 1000.0
def elapsed_sec(self):
""" get the elapsed time in seconds. Returns floating
point representation of time in seconds
"""
return self.elapsed_ms() / 1000
def elapsed_time(self):
"""
Return elapsed time as min:sec:ms. The .split separates out the
millisecond
"""
td = (datetime.datetime.now() - self.start_time)
sec = td.seconds
ms = int(td.microseconds / 1000)
return '{:02}:{:02}.{:03}'.format(sec % 3600 // 60, sec % 60, ms)
def print_table(title, headers, rows, sort_columns=None):
"""
Print a table of rows with headers using tabulate.
Parameters:
title (:term: string):
String that will be output before the Table.
headers (list or tuple):
List of strings that defines the header for each row. Each string
in this list may be multiline by inserting EOL in the string
rows (iterable of iterables)
The outer iterable is the rows. The inner iterables are the colums
for each row
args (int or list of int that defines sort)
Defines the cols that will be sorted. If int, it defines the column
that will be sorted. If list of int, the sort is in sort order of
cols in the list (i.e. minor sorts to the left, major sorts to the
right)
"""
if sort_columns is not None:
if isinstance(sort_columns, int):
rows = sorted(rows, key=itemgetter(sort_columns))
elif isinstance(sort_columns, (list, tuple)):
rows = sorted(rows, key=itemgetter(*sort_columns))
else:
assert False, "Sort_columns must be int or list/tuple of int"
if title:
print('\n%s:' % title)
else:
print('')
print(tabulate.tabulate(rows, headers, tablefmt='simple'))
print('')
def fold_list(input_list, max_width=None):
"""
Fold the entries in input_list. If max_width is not None, fold only if it
is longer than max_width. Otherwise fold each entry.
"""
if not input_list:
return ""
if not isinstance(input_list[0], six.string_types):
input_list = [str(item) for item in input_list]
if max_width:
mystr = ", ".join(input_list)
return fold_string(mystr, max_width)
return "\n".join(input_list)
def fold_string(input_string, max_width):
"""
Fold a string within a maximum width.
Parameters:
input_string:
The string of data to go into the cell
max_width:
Maximum width of cell. Data is folded into multiple lines to
fit into this width.
Return:
String representing the folded string
"""
new_string = input_string
if isinstance(input_string, six.string_types):
if max_width < len(input_string):
# use textwrap to fold the string
new_string = textwrap.fill(input_string, max_width)
return new_string
def get_profile_name(org_vm, profile_inst):
"""
Get the org, name, and version from the profile instance and
return them as a tuple.
Returns: tuple of org, name, vers
Raises:
TypeError: if invalid property type
ValueError: If property value outside range
"""
try:
org = org_vm.tovalues(profile_inst['RegisteredOrganization'])
name = profile_inst['RegisteredName']
vers = profile_inst['RegisteredVersion']
return org, name, vers
except TypeError as te:
print('ORG_VM.TOVALUES FAILED. inst=%s, Exception %s' %
(profile_inst, te))
except ValueError as ve:
print('ORG_VM.TOVALUES FAILED. inst=%s, Exception %s' %
(profile_inst, ve))
return 'ERR', 'ERR', 'ERR'
def profile_name(org_vm, profile_inst, short=False):
"""
Return Org, Profile, Version as a string from the properties in the
profile instance. The returned form is the form Org:Name:Version or
Org:Name if the optional argument short is TRUE
"""
try:
name_tuple = get_profile_name(org_vm, profile_inst)
except Exception as ex: # pylint: disable=broad-except
print('GET_FULL_PROFILE_NAME exception %sm tuple=%r inst=%s' %
(ex, name_tuple, profile_inst))
return("UNKNOWN")
if short:
return "%s:%s" % (name_tuple[0], name_tuple[1])
return "%s:%s:%s" % (name_tuple[0], name_tuple[1], name_tuple[2])
def path_wo_ns(obj):
"""
Return path of an instance or instance path without host or namespace.
Creates copy of the object so the original is not changed.
"""
if isinstance(obj, pywbem.CIMInstance):
path = obj.path.copy()
elif isinstance(obj, pywbem.CIMInstanceName):
path = obj.copy()
else:
assert False
path.host = None
path.namespace = None
return path
class ServerDefinitionFile2(ServerDefinitionFile):
"""
Encapsulation of the WBEM server definition file.
This extends ServerDefinitionFile by using a different implementation
of list_servers that expands the capability slightly of this method.
"""
def __init__(self, filepath=DEFAULT_SERVER_FILE):
super(ServerDefinitionFile2, self).__init__(filepath=filepath)
def list_servers(self, nicknames=None):
"""
Iterate through the servers of the server group with the specified
nicknames, or the single server with the specified nickname, and yield
a `ServerDefinition` object for each server.
nicknames may be: None, string defining a nickname or list of nicknames
"""
if not nicknames:
return self.list_all_servers()
if isinstance(nicknames, six.string_types):
nicknames = [nicknames]
sd_list = []
sd_nick_list = []
for nickname in nicknames:
if nickname in self._servers:
sd_list.append(self.get_server(nickname))
elif nickname in self._server_groups:
for item_nick in self._server_groups[nickname]:
for sd in self.list_servers(item_nick):
if sd.nickname not in sd_nick_list:
sd_nick_list.append(sd.nickname)
sd_list.append(sd)
else:
raise ValueError(
"Server group or server nickname {0!r} not found in WBEM "
"server definition file {1!r}".
format(nickname, self._filepath))
return sd_list
def connect(nickname, server_def, debug=None, timeout=10):
"""
Connect and confirm server works by testing for a known class in
the default namespace or if there is no default namespace defined,
in all the possible interop namespaces.
returns a WBEMConnection object or None if the connection fails.
"""
url = server_def.url
conn = pywbem.WBEMConnection(
url,
(server_def.user, server_def.password),
default_namespace=server_def.implementation_namespace,
no_verification=server_def.no_verification,
timeout=timeout)
if debug:
conn.debug = True
ns = server_def.implementation_namespace if \
server_def.implementation_namespace \
else 'interop'
try:
conn.GetQualifier('Association', namespace=ns)
return conn
except pywbem.ConnectionError as exc:
print("Test server {0} at {1!r} cannot be reached. {2}: {3}".
format(nickname, url, exc.__class__.__name__, exc))
return None
except pywbem.AuthError as exc:
print("Test server {0} at {1!r} cannot be authenticated with. "
"{2}: {3}". format(nickname, url,
exc.__class__.__name__, exc))
return None
except pywbem.CIMError as ce:
if ce.status_code == pywbem.CIM_ERR_NAMESPACE_NOT_FOUND or \
ce.status.code == pywbem.CIM_ERR_NOT_FOUND:
return conn
else:
return None
except pywbem.Error as exc:
print("Test server {0} at {1!r} returned exception. {2}: {3}".
format(nickname, url, exc.__class__.__name__, exc))
return None
RESULTS = []
def test_server(url, principal, credential, no_verification, timeout=10):
"""
Test a single server to determine if it is alive. Connects and gets a
single class. Returns True if the sever is alive.
"""
try:
conn = pywbem.WBEMConnection(url, (principal, credential),
no_verification=no_verification,
timeout=timeout)
server = pywbem.WBEMServer(conn)
server.namespaces # pylint: disable=pointless-statement
RESULTS.append((url, principal, credential))
except pywbem.Error as er:
print('URL %s failed %s' % (url, er))
# TODO possibly activate this in the future. It parallelizes the location
# of live servers saving test time. The other alternative would be to
# just paralize the whole test and that might be a lot of work.
def test_live_servers(servers):
"""
Test for live servers. gets list of all servers and returns list of
live servers. This just weeds out the dead servers from the test. This is
a threaded test so whole test should not take longer than a single
timeout.
Input is list of tuples where each tuple is url, credential,
"""
live_servers = []
threads_ = []
for server in servers:
url = server[0]
principal = server[1]
credential = server[1]
no_verification = True
timeout = 10
process = threading.Thread(target=test_server,
args=(url, principal, credential,
no_verification, timeout))
threads_.append(process)
for process in threads_:
process.start()
for process in threads_:
process.join()
for result in RESULTS:
servers.append(result)
return live_servers
def overview(name, server):
"""
Overview of the server as seen through the properties of the server
class.
"""
print('%s OVERVIEW' % name)
print(" Interop namespace: %s" % server.interop_ns)
print(" Brand: %s" % server.brand)
print(" Version: %s" % server.version)
print(" Namespaces: %s" % ", ".join(server.namespaces))
print(' namespace_classname: %s' % server.namespace_classname)
if VERBOSE:
print('cimom_inst:\n%s' % server.cimom_inst.tomof())
print('server__str__: %s' % server)
print('server__repr__: %r' % server)
try:
insts = server.conn.EnumerateInstances('CIM_Namespace',
namespace=server.interop_ns)
print('%s: Instances of CIM_Namespace' % name)
for inst in insts:
print('%r' % inst)
except pywbem.Error as er:
print('ERROR: %s: Enum CIM_Namespace failed %s' % (name, er))
try:
insts = server.conn.EnumerateInstances('__Namespace',
namespace=server.interop_ns)
print('%s: Instances of __Namespace' % name)
for inst in insts:
print('%r' % inst)
except pywbem.Error as er:
print('ERROR: %s: Enum __Namespace failed %s' % (name, er))
def get_associated_profiles(profile_path, result_role, server):
"""
Get the associated CIM_ReferencedProfile (i.e. the Reference) for the
profile defined by profile_path. This allows the ResultRolefor the
association to be set as part of the call to either "Dependent" or
"Antecedent".
"""
associated_profiles = server.conn.Associators(
ObjectName=profile_path,
AssocClass="CIM_ReferencedProfile",
ResultRole=result_role)
if VERBOSE:
print('GET_ASSICIATED_PROFILES path=%r, result_role=%s\nReturns %s' %
(profile_path, result_role, associated_profiles))
if server.conn.debug:
print('LAST_REQUEST\n%s' % server.conn.last_request)
print('LAST_REPLY\n%s' % server.conn.last_reply)
return associated_profiles
def get_associated_profile_names(profile_path, result_role, org_vm, server,
include_classnames=False):
"""
Get the Associated profiles and return the string names (org:name:version)
for each profile as a list.
"""
insts = get_associated_profiles(profile_path, result_role, server)
names = []
for inst in insts:
if include_classnames:
names.append("(%s)%s" % (inst.classname,
profile_name(org_vm, inst)))
else:
names.append(profile_name(org_vm, inst))
return names
def get_references(profile_path, role, profile_name, server):
"""
Get display and return the References for the path provided, ResultClass
CIM_ReferencedProfile, and the role provided.
"""
references_for_profile = server.conn.References(
ObjectName=profile_path,
ResultClass="CIM_ReferencedProfile",
Role=role)
if VERBOSE:
print('References for profile=%s, path=%s, ResultClass='
'CIM_ReferencedProfile, Role=%s' % (profile_name, profile_path,
role))
for ref in references_for_profile:
print('Reference for %s get_role=%s cn=%s\n antecedent=%s\n '
'dependent=%s' % (profile_name, role, ref.classname,
ref['Antecedent'], ref['Dependent']))
return references_for_profile
def show_profiles(name, server, org_vm):
"""
Create a table of info about the profiles based on getting the
references, etc. both in the dependent and antecedent direction.
The resulting table is printed.
"""
rows = []
for profile_inst in server.profiles:
pn = profile_name(org_vm, profile_inst)
deps = get_associated_profile_names(
profile_inst.path, "dependent", org_vm, server,
include_classnames=False)
dep_refs = get_references(profile_inst.path, "antecedent", pn, server)
ants = get_associated_profile_names(
profile_inst.path, "antecedent", org_vm, server,
include_classnames=False)
ant_refs = get_references(profile_inst.path, "dependent",
profile_name, server)
# get unique class names
dep_ref_clns = set([ref.classname for ref in dep_refs])
ant_ref_clns = set([ref.classname for ref in ant_refs])
row = (pn,
fold_list(deps),
fold_list(list(dep_ref_clns)),
fold_list(ants),
fold_list(list(ant_ref_clns)))
rows.append(row)
# append this server to the dict of servers for this profile
SERVERS_FOR_PROFILE[profile_name].append(name)
title = '%s: Advertised profiles showing Profiles associations' \
'Dependencies are Associators, AssocClass=CIM_ReferencedProfile' \
'This table shows the results for ' % name
headers = ['Profile',
'Assoc CIMReferencedProfile\nResultRole\nDependent',
'Ref classes References\nRole=Dependent',
'Assoc CIMReferencedProfile\nResultRole\nAntecedent',
'Ref classesReferences\nRole=Dependent']
print_table(title, headers, rows, sort_columns=[1, 0])
def fold_path(path, width=30):
"""
Fold a string form of a path so that each element is on separate line
"""
assert isinstance(path, six.string_types)
if len(path) > width:
path.replace(".", ".\n ")
return path
def count_ref_associators(nickname, server, profile_insts, org_vm):
"""
Get dict of counts of associator returns for ResultRole == Dependent and
ResultRole == Antecedent for profiles in list. This method counts by
executing repeated AssociationName calls on CIM_ReferencedProfile for each
profile instance in profile_insts with the result Role set to Dependent and
then Antecedent to get the count of objects returned.
Returns a dictionary where keys are profile name and value are a tuple of
the number of associator instances for each of the AssociatorName calls.
NOTE: This can take a long time because it executes 2 server requests for
each profile in profile_insts.
"""
def get_assoc_count(server, profile_inst):
"""
Execute Associator names with ResultRole as 'Dependent' and then as
'Antecedent' and return the count of associations returned for each
operation
"""
deps = server.conn.AssociatorNames(
ObjectName=profile_inst.path,
AssocClass="CIM_ReferencedProfile",
ResultRole='Dependent')
ants = server.conn.AssociatorNames(
ObjectName=profile_inst.path,
AssocClass="CIM_ReferencedProfile",
ResultRole='Antecedent')
return (len(deps), len(ants))
assoc_dict = {}
for profile_inst in profile_insts:
deps_count, ants_count = get_assoc_count(server, profile_inst)
pn = profile_name(org_vm, profile_inst)
assoc_dict[pn] = (deps_count, ants_count)
title = 'Display antecedent and dependent counts for possible ' \
'autonomous profiles using slow algorithm.\n' \
'Displays the number of instances returned by\n' \
'Associators request on profile for possible autonomous profiles'
rows = [(key, value[0], value[1]) for key, value in assoc_dict.items()]
print_table(title, ['profile', 'Dependent\nCount', 'Antecedent\nCount'],
rows, sort_columns=0)
# add rows to the global list for table of
g_rows = [(nickname, key, value[0], value[1])
for key, value in assoc_dict.items()]
ASSOC_PROPERTY_COUNTS.extend(g_rows)
return assoc_dict
def determine_reference_direction_slow(nickname, server, org_vm,
possible_autonomous_profiles=None):
"""
Determine the antecedent/dependent direction for the CIM_ReferencedProfile
class for this server by testing possible autonomous top level profiles for
their direction. This method may be required because there is an
issue between implementations in the usage of the dependent and antecedent
reference properties. Typically SNIA profiles defined them with:
Antecedent = referenced profile = component profile
Dependent = referencing profile = autonomous profile
and many SMI implementations defined them with:
Antecedent = autonomous profile
Dependent = component (= sub) profile
This method processes the CIM_RegisteredProfiles associatorNames
witht ResultRole set to 'Dependent' and then to 'Antecedent'to find any
profile returns associations for one of the ResultRole settings but not
the other. If such an association can be found, that determines the
implementation of the antecedent/dependent direction.
parameters:
server:
org_vm:
possible_autonomous_profiles (instances of CIM_profile):
list of autonomous profiles that are possible.
Returns:
If a direction is found it returns a string defining that direction.
'dmtf' means that is is the direction defined by dmtf. 'snia' means
it is the direction defined by 'snia'. None means that the algorithm
could not figure out the direction
"""
# Get list of possible autonomous profiles or use all server profiles
# as basis. However, extending to use all server profiles really does not
# work because you cannot tell which are top level autonomous profiles and
# which are component profiles with no referenced subprofiles.
if possible_autonomous_profiles:
prof_list = possible_autonomous_profiles
else:
prof_list = server.profiles
# This function executes associator names calls for each profile and
# captures the result in a dictionary where the key is the profile name and
# the value is a tuple of the count of names returned for each associators
# call both for the call with ResultRole='Dependent and
# ResultRole='Antecedent'.
assoc_dict = count_ref_associators(nickname, server, prof_list, org_vm)
# find profiles with either ant or dep == 0 and the other != 0
possible_top_profiles = []
for key, value in assoc_dict.items():
# Look for entries in the dictionary returned by count_ref_assoc
# that have combination of 0 in one entry and non-zero in the other
# i.e.
if (not value[0] and value[1]) or (value[0] and not value[1]):
possible_top_profiles.append((key, value))
if not possible_top_profiles:
raise ValueError('Name=%s;, Server:\n %s]nwith list of possible '
'profiles\n %s '
'could not find any possible top level autonomous '
'profiles.\nassoc_dict=%s' %
(nickname, server, prof_list, assoc_dict))
# Test that all possibles autonomous profiles have the zero entry
# (No associations) in the same position (dependent or antecedent). This
# means that these are all top level autonomous profiles.
# Note that I am not sure about autonomous profiles not being top
# level but apparently SNIA sllows profiles that are autonomous
# and may also component.
zero_count_pos = None
for key, value in possible_top_profiles:
if not zero_count_pos:
if not value[0]:
zero_count_pos = 0
elif not value[1]:
zero_count_pos = 1
else:
if value[zero_count_pos]:
SVR_DIRECTION[nickname] = "undefined"
raise ValueError('Name: %s; Server=%s; Cannot determine '
'possible CIM_ReferencedProfile direction\n'
'%s', (nickname, possible_top_profiles))
dir_type = 'dmtf' if not zero_count_pos else 'snia'
if VERBOSE:
print('DIR_TYPE=%s' % (dir_type))
SVR_DIRECTION[nickname] = dir_type
return dir_type
def fast_count_associators(server):
"""
Create count of associators for CIM_ReferencedProfile using the
antecedent and dependent reference properties as ResultRole for each profile
defined in server.profiles and return a dictionary of the count. This
code does a shortcut in executing EnumerateInstances to get
CIM_ReferencedProfile and processing the association locally.
Returns
Dictionary where the keys are the profile names and the value for
each key is a dictionary with two keys ('dep' and 'ant')
and the value is the count of associator paths when the key value is
used as the ResultRole
"""
try:
ref_insts = server.conn.EnumerateInstances("CIM_ReferencedProfile",
namespace=server.interop_ns)
# Remove host from responses since the host causes confusion
# with the enum of registered profile. Enums do not return host but
# the associator properties contain host
for ref_inst in ref_insts:
for prop in ref_inst.values():
prop.host = None
except pywbem.Error as er:
print('CIM_ReferencedProfile failed for conn=%s\nexception=%s'
% (server, er))
raise
# Create dict with the following characteristics:
# key = associator source object path
# value = {'dep' : count of associations,
# 'ant' : count of associations}
# where: an association is a reference property that does not have same
# value as the source object path but for which the source object
# path is the value of one of the properties
association_dict = {}
# We are counting too many. Have same properties for class and subclass
# but appear to count that one twice. Looks like we need one more piece.
# for each. If association_dict[profile_key] not in some list
for profile in server.profiles:
profile_key = profile.path
ant_dict = {}
dep_dict = {}
for ref_inst in ref_insts:
# These dictionaries insure that there are no duplicates in
# the result. Some servers duplicate the references in subclasses.
if profile_key not in association_dict:
association_dict[profile_key] = {'dep': 0, 'ant': 0}
ant = ref_inst['antecedent']
dep = ref_inst['dependent']
if profile_key != ant and profile_key != dep:
continue
if dep != profile_key:
if dep not in dep_dict:
dep_dict[dep] = True
association_dict[profile_key]['dep'] += 1
if ant != profile_key:
if ant not in ant_dict:
ant_dict[ant] = True
association_dict[profile_key]['ant'] += 1
return association_dict
def determine_reference_direction_fast(nickname, server,
possible_autonomous_profiles=None,
possible_component_profiles=None):
"""
Determine CIM_ReferenceProfile Antecedent/Dependent direction from
server data and a list of known autonomous and/or component profiles
using the algorithm defined for the _server. This is the prototype for
the code that was reimplemented in pywbem.
Parameters:
org_vm
possible_autonomous_profiles ()
"""
def _determine_type(profilepaths, v0_dict, v1_dict, autonomous):
"""
Determine type from data in the two dictionaries and the profile_list.
Returns string defining type ('snia' or 'dmtf'). Returns None if
the profile list is None or None of the profilepaths exist in either
v0_dict or v1_dict
"""
if not profilepaths:
return None
t = ['snia', 'dmtf']
if not autonomous:
t.reverse()
dir_type = None
v0_paths = []
v1_paths = []
for ppath in profilepaths:
if ppath in v0_dict:
v0_paths.append(ppath)
if VERBOSE:
print('DETERMINED_TYPE v0 %s %s' % (ppath, t[0]))
elif ppath in v1_dict:
v1_paths.append(ppath)
if VERBOSE:
print('DETERMINED_TYPE v1 %s %s' % (ppath, t[1]))
if v0_paths and not v1_paths:
dir_type = t[0]
elif v1_paths and not v0_paths:
dir_type = t[1]
elif not v0_paths and not v1_paths:
dir_type = None
else:
ps = 'possible %s' % ('autonomous' if autonomous else 'component')
print('ERROR VALUERROR %s\n%s:%s\n%s: %s' % (ps, t[0], v0_paths,
t[1], v1_paths))
raise ValueError("Cannot determine type. "
"determine_cimrefrence_direction shows "
"conflicts in %s profile list. %s; %s\n%s; %s" %
(ps, t[0], v0_paths, t[1], v1_paths))
return dir_type
if VERBOSE:
print('POSSIBLE_AUTONOMOUS_PROFILES:\n%s' %
possible_autonomous_profiles)
if not possible_autonomous_profiles and not possible_component_profiles:
raise ValueError("Either possible_autonomous_profiles or "
"possible_component_profiles must have a value")
assoc_dict = fast_count_associators(server)
# returns dictionary where key is profile name and value is dict of
# ant: dep: with value count
# Reduce to dictionary where ant/dep are 0 and non-zero, i.e. top and bottom
new_dict = {}
for key, value in assoc_dict.items():
if (not value['dep'] and value['ant']) \
or (value['dep'] and not value['ant']):
new_dict[key] = (value['dep'], value['ant'])
if not value['dep'] and not value['ant']:
print('ERROR key %s value %s' % (key, value))
# print('NEW_DICT %s' % new_dict)
# create a dictionary with entry for each new_dict itme that has data in
# one of the value items.
v0_dict = {key: value for key, value in new_dict.items() if value[0]}
v1_dict = {key: value for key, value in new_dict.items() if value[1]}
if VERBOSE:
print('V0_DICT %s' % v0_dict)
print('V1_DICT %s' % v1_dict)
print('POSSIBLE_AUTONOMOUS_PROFILES %s' % possible_autonomous_profiles)
auto_dir_type = _determine_type(possible_autonomous_profiles, v0_dict,
v1_dict, True)
comp_dir_type = _determine_type(possible_component_profiles, v0_dict,
v1_dict, False)
if VERBOSE:
print('AUTO_DIR %s %s' % (auto_dir_type, comp_dir_type))
if auto_dir_type and comp_dir_type:
if auto_dir_type == comp_dir_type:
return auto_dir_type
elif not auto_dir_type and not comp_dir_type:
return None
else:
if auto_dir_type:
return auto_dir_type
elif comp_dir_type:
return comp_dir_type
if VERBOSE:
print('RAISE VALUERR %s %s' % (auto_dir_type, comp_dir_type))
raise ValueError('Name: %s; Cannot determine '
'possible CIM_ReferencedProfile direction. '
'Autonomous and componentTests do not match. '
'auto_dir_type=%s, '
'comp_dir_type=%s\nServer=%s; ' %
(nickname, auto_dir_type, comp_dir_type, server))
def show_count_associators(nickname, server, org_vm):
"""
Display results of fast_count_associators(...)). Generates a table showing
the results of the call. This is just a test tool.
"""
d_assoc = fast_count_associators(server)
svr_profiles_dict = {prof.path: prof for prof in server.profiles}
headers = ('profile', 'ants', 'deps')
rows = []
assoc_dict = {}
for prof_key, values in d_assoc.items():
pn = profile_name(org_vm, svr_profiles_dict[prof_key])
assoc_dict[pn] = (values['ant'], values['dep'])
rows = []
title = 'Display antecedent and dependent counts for possible ' \
'autonomous and component profiles using fast method.\nDisplays the ' \
'number of instances returned by\nAssociators request on profile for ' \
'possible autonomous profiles. Algorithm is to enumerate ' \
'ReferencedProfile and count Dependents/Antecedents with target path'
headers = ('profile', 'Dependent\nCount', 'Antecedent\nCount')
for pn, value in assoc_dict.items():
rows.append((pn, value[1], value[0]))
print_table(title, headers, rows, sort_columns=[0])
g_rows = [(nickname, key, value[0], value[1])
for key, value in assoc_dict.items()]
ASSOC_PROPERTY_COUNTS.extend(g_rows)
def test_get_central_instances(nickname, server, all_profiles_dict, org_vm,
reference_direction='dmtf'):
"""Test get central instances"""
good_rtns = []
error_rtns = []
for inst in server.profiles:
try:
prof = profile_name(org_vm, inst, short=True)
prof_long = profile_name(org_vm, inst)
if prof not in all_profiles_dict:
PROFILES_WITH_NO_DEFINITIONS[nickname] = prof
continue
prof_def = all_profiles_dict[prof]
print('%s: PROFILE get_central_instances: %s inst.path=%s\n '
'central_class=%s,scoping_class=%s, scoping_path=%s' %
(nickname, prof_long, inst.path, prof_def.central_class,
prof_def.scoping_class, prof_def.scoping_path))
# If profile has ElementConformsToProfile, ignore other
# definition parameters
ci_paths = server.conn.AssociatorNames(
ObjectName=inst.path,
AssocClass="CIM_ElementConformsToProfile",
ResultRole="ManagedElement")
if ci_paths:
try:
central_paths = server.get_central_instances(
inst.path,
central_class=prof_def.central_class,
scoping_class=prof_def.scoping_class,