/
_mof_compiler.py
3031 lines (2521 loc) · 103 KB
/
_mof_compiler.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
#
# (C) Copyright 2006-2007 Novell, Inc.
#
# 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.
#
# Author: Bart Whiteley <bwhiteley suse.de>
# Author: Ross Peoples <ross.peoples@gmail.com>
#
"""
The language in which CIM classes, CIM Instances, etc. are specified, is
called `MOF` (for Managed Object Format). It is defined in :term:`DSP0004`.
MOF compilers take MOF files as input, compile them and use the result
(CIM classes, instances, and/or qualifier declarations) to update a target
CIM repository. The repository may initially be empty, or may contain CIM
classes, instances, and/or qualifier declarations that are used to resolve
dependencies the new MOF compilation may have.
The pywbem package includes a MOF compiler that is provided in two forms:
* as an API (described in this chapter)
* as a command (described in section :ref:`mof_compiler`)
The pywbem MOF compiler will compile MOF files whose syntax complies with
:term:`DSP0004`, with some limitations:
1. Although there is no formal keyword list of illegal words
for property/parameter.etc. names , there is a list of mof syntax tokens
in :term:`DSP0004` section A.3. Generally these should not be used as
property names. The pywbem MOF compiler largely enforces this so that words
like 'indication' are not allowed as property/parameter/etc. names.
2. The key properties of instances with aliases must be initialized in the
instance specification, or their default values must be non-NULL.
(See `pywbem issue #1079 <https://github.com/pywbem/pywbem/issues/1079>`_).
3. An alias must be defined before it is used. In :term:`DSP0004`, no such
requirement is documented.
(See `pywbem issue #1079 <https://github.com/pywbem/pywbem/issues/1079>`_).
The MOF compiler API provides for invoking the MOF compiler programmatically.
It consists of the following parts, which are described in the remaining
sections of this chapter:
* :ref:`MOFCompiler Class` - Describes the :class:`~pywbem.MOFCompiler`
class, which allows invoking the MOF compiler programmatically.
* :ref:`Repository connections` - Describes the
:class:`~pywbem.BaseRepositoryConnection` class that defines
the interface for connecting to a CIM repository. This is an extension point
where users can implement a CIM repository for use by the MOF compiler.
* :ref:`Exceptions <MOF compiler exceptions>` - Describes the exceptions
that can be raised by the MOF compiler API.
"""
from __future__ import print_function, absolute_import
import sys
import os
import re
import tempfile
# import logging
from abc import ABCMeta, abstractmethod
try:
from collections import OrderedDict
except ImportError:
from ordereddict import OrderedDict
import six
from ply import yacc, lex
from ._nocasedict import NocaseDict
from ._cim_obj import CIMInstance, CIMInstanceName, CIMClass, CIMProperty, \
CIMMethod, CIMParameter, CIMQualifier, CIMQualifierDeclaration, \
cimvalue
from ._cim_operations import WBEMConnection
from ._server import WBEMServer
from ._cim_constants import CIM_ERR_NOT_FOUND, CIM_ERR_FAILED, \
CIM_ERR_ALREADY_EXISTS, CIM_ERR_INVALID_NAMESPACE, \
CIM_ERR_INVALID_SUPERCLASS, CIM_ERR_INVALID_PARAMETER, \
CIM_ERR_NOT_SUPPORTED
from ._exceptions import Error, CIMError
from ._utils import _format
__all__ = ['MOFCompileError', 'MOFParseError', 'MOFDependencyError',
'MOFRepositoryError', 'MOFCompiler', 'BaseRepositoryConnection']
# The following pylint is applied for the complete file because invalid
# names are used throughout the file and about 200 flags generated if
# this is not applied and at least some # may be part of ply rules.
# pylint: disable=invalid-name
_optimize = 1
_tabmodule = '_mofparsetab'
_lextab = '_moflextab'
# Directory for _tabmodule and _lextab
_tabdir = os.path.dirname(os.path.abspath(__file__))
# -----------------------------------------------------------------------------
#
# IMPORTANT NOTE:
#
# This MOF compiler implementation is based on the PLY Python package.
# This module here contains LEX & YACC rules in docstrings of its functions.
# The formatting of these docstrings is critical in that it defines the parser
# functionality. These docstrings are processed by the LEX & YACC in PLY.
# Changing the strings or even the formatting breaks the PLY rule generation!
#
# In the YACC of PLY 2.3 (included in pywbem up to 0.7), the requirement was
# that each choice of a YACC rule needed to be on a single line, and the first
# choice needed to be on the same line as the rule name. Not sure what the
# requirements of the current PLY version are.
#
# The LEX token functions and strings are all named "t_*".
# Note the order of LEX token processing, described in:
# https://www.dabeaz.com/ply/ply.html#ply_nn6
#
# The YACC parser functions are all named "p_*".
#
# -----------------------------------------------------------------------------
reserved = {
'any': 'ANY',
'as': 'AS',
'association': 'ASSOCIATION',
'class': 'CLASS',
'disableoverride': 'DISABLEOVERRIDE',
'boolean': 'DT_BOOL',
'char16': 'DT_CHAR16',
'datetime': 'DT_DATETIME',
'pragma': 'PRAGMA',
'real32': 'DT_REAL32',
'real64': 'DT_REAL64',
'sint16': 'DT_SINT16',
'sint32': 'DT_SINT32',
'sint64': 'DT_SINT64',
'sint8': 'DT_SINT8',
'string': 'DT_STR',
'uint16': 'DT_UINT16',
'uint32': 'DT_UINT32',
'uint64': 'DT_UINT64',
'uint8': 'DT_UINT8',
'enableoverride': 'ENABLEOVERRIDE',
'false': 'FALSE',
'flavor': 'FLAVOR',
'indication': 'INDICATION',
'instance': 'INSTANCE',
'method': 'METHOD',
'null': 'NULL',
'of': 'OF',
'parameter': 'PARAMETER',
'property': 'PROPERTY',
'qualifier': 'QUALIFIER',
'ref': 'REF',
'reference': 'REFERENCE',
'restricted': 'RESTRICTED',
'schema': 'SCHEMA',
'scope': 'SCOPE',
'tosubclass': 'TOSUBCLASS',
'toinstance': 'TOINSTANCE',
'translatable': 'TRANSLATABLE',
'true': 'TRUE',
} # noqa: E123
tokens = list(reserved.values()) + [
'IDENTIFIER',
'stringValue',
'floatValue',
'charValue',
'binaryValue',
'octalValue',
'decimalValue',
'hexValue',
]
literals = '#(){};[],$:='
# UTF-8 (from Unicode 4.0.0 standard):
# Table 3-6. Well-Formed UTF-8 Byte Sequences Code Points
# 1st Byte 2nd Byte 3rd Byte 4th Byte
# U+0000..U+007F 00..7F
# U+0080..U+07FF C2..DF 80..BF
# U+0800..U+0FFF E0 A0..BF 80..BF
# U+1000..U+CFFF E1..EC 80..BF 80..BF
# U+D000..U+D7FF ED 80..9F 80..BF
# U+E000..U+FFFF EE..EF 80..BF 80..BF
# U+10000..U+3FFFF F0 90..BF 80..BF 80..BF
# U+40000..U+FFFFF F1..F3 80..BF 80..BF 80..BF
# U+100000..U+10FFFF F4 80..8F 80..BF 80..BF
utf8_2 = r'[\xC2-\xDF][\x80-\xBF]'
utf8_3_1 = r'\xE0[\xA0-\xBF][\x80-\xBF]'
utf8_3_2 = r'[\xE1-\xEC][\x80-\xBF][\x80-\xBF]'
utf8_3_3 = r'\xED[\x80-\x9F][\x80-\xBF]'
utf8_3_4 = r'[\xEE-\xEF][\x80-\xBF][\x80-\xBF]'
utf8_4_1 = r'\xF0[\x90-\xBF][\x80-\xBF][\x80-\xBF]'
utf8_4_2 = r'[\xF1-\xF3][\x80-\xBF][\x80-\xBF][\x80-\xBF]'
utf8_4_3 = r'\xF4[\x80-\x8F][\x80-\xBF][\x80-\xBF]'
utf8Char = r'({0})|({1})|({2})|({3})|({4})|({5})|({6})|({7})'.format(
utf8_2, utf8_3_1, utf8_3_2, utf8_3_3, utf8_3_4, utf8_4_1, utf8_4_2,
utf8_4_3)
# pylint: disable=unused-argument
def t_COMMENT(t):
r'//.*'
return # discard token
def t_MCOMMENT(t):
r'/\*(.|\n)*?\*/'
t.lineno += t.value.count('\n')
return # discard token
# These simple tokens must also be defined as functions, in order to control
# the order of evaluation.
def t_floatValue(t):
r'[+-]?[0-9]*\.[0-9]+([eE][+-]?[0-9]+)?'
t.value = float(t.value)
return t
def t_hexValue(t):
r'[+-]?0[xX][0-9a-fA-F]+'
t.value = int(t.value, 16)
return t
def t_binaryValue(t):
r'[+-]?[0-9]+[bB]'
# We must match [0-9], and then check the validity of the binary number.
# If we match [0-1], the invalid binary number "2b" would match
# 'decimalValue' 2 and 'IDENTIFIER 'b'.
if re.search(r'[2-9]', t.value) is not None:
msg = _format("Invalid binary number {0!A}", t.value)
t.lexer.last_msg = msg
t.type = 'error'
# Setting error causes the value to be automatically skipped
else:
t.value = int(t.value[0:-1], 2)
return t
def t_octalValue(t):
r'[+-]?0[0-9]+'
# We must match [0-9], and then check the validity of the octal number.
# If we match [0-7], the invalid octal number "08" would match
# 'decimalValue' 0 and 'decimalValue' 8.
if re.search(r'[8-9]', t.value) is not None:
msg = _format("Invalid octal number {0!A}", t.value)
t.lexer.last_msg = msg
t.type = 'error'
# Setting error causes the value to be automatically skipped
else:
t.value = int(t.value, 8)
return t
# Matching for decimal must be at the end of the other numerics because of
# the 0. If not at the end, 0 would match at the begin of e.g. an octal value.
def t_decimalValue(t):
r'[+-]?([1-9][0-9]*|0)'
t.value = int(t.value)
return t
simpleEscape = r"""[bfnrt'"\\]"""
hexEscape = r'[xX][0-9a-fA-F]{1,4}'
escapeSequence = r'[\\](({0})|({1}))'.format(simpleEscape, hexEscape)
cChar = r"[^'\\\n\r]|({0})".format(escapeSequence)
sChar = r'[^"\\\n\r]|({0})'.format(escapeSequence)
charvalue_re = r"'({0})'".format(cChar)
@lex.TOKEN(charvalue_re)
def t_charValue(t): # pylint: disable=missing-docstring
return t
stringvalue_re = r'"({0})*"'.format(sChar)
@lex.TOKEN(stringvalue_re)
def t_stringValue(t): # pylint: disable=missing-docstring
return t
identifier_re = r'([a-zA-Z_]|({0}))([0-9a-zA-Z_]|({0}))*'.format(
utf8Char)
@lex.TOKEN(identifier_re)
def t_IDENTIFIER(t): # pylint: disable=missing-docstring
t.type = reserved.get(t.value.lower(), 'IDENTIFIER')
return t
def t_newline(t): # pylint: disable=missing-docstring
r'\n+'
t.lexer.lineno += len(t.value)
t.lexer.linestart = t.lexpos
return # discard token
t_ignore = ' \r\t'
def t_error(t):
""" Lexer error callback from PLY Lexer with token in error.
"""
msg = _format("Illegal character {0!A}", t.value[0])
t.lexer.last_msg = msg
t.lexer.skip(1)
return t # Return the error token for the YACC parser to handle
class MOFCompileError(Error):
"""
Base class for exceptions indicating issues with compiling MOF.
Derived from :exc:`~pywbem.Error`.
"""
error_kind = "MOF compile error"
# pylint: disable=super-init-not-called
def __init__(self, msg, parser_token=None):
"""
Parameters:
msg (:term:`string`):
Message text describing the error.
parser_token (lex.LexToken or yacc.YaccProduction):
PLY lex or yacc parser token (that is, the ``p`` argument of a yacc
parser function or the ``t`` argument of a lex parser function).
This token is used to obtain the MOF source text and location
information.
`None` will result in no MOF source text and location information
to be obtained.
"""
assert msg is not None
self._msg = msg
if parser_token is None:
self.args = (None, None, None, None)
else:
assert isinstance(
parser_token,
(lex.LexToken, yacc.YaccProduction))
mof_ = parser_token.lexer.parser.mof
self.args = (parser_token.lexer.lineno,
_find_column(mof_, parser_token),
parser_token.lexer.parser.file,
_get_error_context(mof_, parser_token))
@property
def lineno(self):
"""
:term:`integer`: Line number in the MOF file or MOF string where the
error occurred (1-based).
"""
return self.args[0]
@property
def column(self):
"""
:term:`integer`: Position within the line in the MOF file or MOF string
where the error occurred (1-based).
"""
return self.args[1]
@property
def file(self):
"""
:term:`string`: File name of the MOF file where the error occurred.
`None` if the error occurred in a MOF string that was compiled.
"""
return self.args[2]
@property
def context(self):
"""
:term:`string`: MOF context, consisting of a first line that is the
MOF line in error, and a second line that uses the '^' character to
indicate the position of the token in error in the MOF line.
"""
return self.args[3]
@property
def msg(self):
"""
:term:`string`: Message text describing the error.
"""
return self._msg
def __str__(self):
return self.get_err_msg()
def get_err_msg(self):
"""
Return a multi-line error message for being printed, in the following
format. The text in angle brackets refers to the same-named properties
of the exception instance:
::
<error kind>:<file>:<lineno>:<colno>: <msg>
<context - MOF line>
<context - position indicator line>
Returns:
:term:`string`: Multi-line error message.
"""
ret_str = '{0}:'.format(self.error_kind)
disp_file = 'String' if not self.file else self.file
if self.lineno is not None:
ret_str += _format("{0}:{1}:{2}",
disp_file, self.lineno, self.column)
if self.msg:
ret_str += _format(" {0}", self.msg)
if self.context is not None:
ret_str += '\n'
ret_str += '\n'.join(self.context)
return ret_str
class MOFParseError(MOFCompileError):
"""
Exception indicating that MOF cannot be parsed correctly, e.g. for
syntax errors.
Derived from :exc:`~pywbem.MOFCompileError`.
"""
error_kind = "MOF parsing error"
class MOFDependencyError(MOFCompileError):
"""
Exception indicating that MOF cannot be compiled because of a missing
dependency. For example, the MOF to be compiled specifies a class but the
superclass of the class cannot be found.
Derived from :exc:`~pywbem.MOFCompileError`.
"""
error_kind = "MOF dependency error"
class MOFRepositoryError(MOFCompileError):
"""
Exception indicating that MOF cannot be compiled because of a CIM error
returned by the target CIM repository. The CIM error is attached to this
exception and is part of the exception message.
Derived from :exc:`~pywbem.MOFCompileError`.
"""
error_kind = "CIM repository error"
def __init__(self, msg, parser_token=None, cim_error=None):
"""
Parameters:
msg (:term:`string`):
Message text describing the error.
parser_token (lex.LexToken or yacc.YaccProduction):
PLY lex or yacc parser token (that is, the ``p`` argument of a yacc
parser function or the ``t`` argument of a lex parser function).
This token is used to obtain the MOF source text and location
information.
`None` will result in no MOF source text and location information
to be obtained.
cim_error (:class:`~pywbem.CIMError`):
CIM error returned by the CIM repository.
"""
super(MOFRepositoryError, self).__init__(msg, parser_token)
self._cim_error = cim_error
@property
def cim_error(self):
"""
:class:`~pywbem.CIMError`: CIM error returned by the CIM repository.
"""
return self._cim_error
def get_err_msg(self):
"""
Return a multi-line error message for being printed, in the following
format. The text in angle brackets refers to the same-named properties
of the exception instance:
::
<error kind>:<file>:<lineno>:<colno>: <msg>
<context - MOF line>
<context - position indicator line>
<CIM error>
Returns:
:term:`string`: Multi-line error message.
"""
ret_str = super(MOFRepositoryError, self).get_err_msg()
ret_str += "\n{0}".format(self.cim_error)
return ret_str
def p_error(p):
"""
YACC Error Callback from the parser. The parameter is the token
in error and contains information on the file and position of the
error. If p is `None`, PLY is returning eof error.
"""
if p is None:
raise MOFParseError(msg='Unexpected end of MOF')
msg = p.lexer.last_msg
p.lexer.last_msg = None
if not msg:
msg = "MOF grammar error"
raise MOFParseError(msg=msg, parser_token=p)
# pylint: disable=unused-argument
def p_mofSpecification(p):
"""mofSpecification : mofProductionList"""
# pylint: disable=unused-argument
def p_mofProductionList(p):
"""mofProductionList : empty
| mofProductionList mofProduction
"""
# pylint: disable=unused-argument
def p_mofProduction(p):
"""mofProduction : compilerDirective
| mp_createClass
| mp_setQualifier
| mp_createInstance
"""
def p_mp_createClass(p):
"""mp_createClass : classDeclaration
"""
# pylint: disable=too-many-branches,too-many-statements,too-many-locals
ns = p.parser.target_namespace
cc = p[1]
# Compile class invalid when in mode to compile embedded instance
if p.parser.embedded_objects is not None:
raise MOFParseError(
msg=_format(
"Invalid compile of CIMClass {0}. "
"Compiler in mode to compile embedded instance and"
"compile of other types is invalid", cc))
try:
fixedNS = fixedRefs = fixedSuper = False
while not fixedNS or not fixedRefs or not fixedSuper:
try:
if p.parser.verbose:
p.parser.log(
_format("Creating class {0!A}:{1!A}", ns, cc.classname))
p.parser.handle.CreateClass(cc, namespace=ns)
if p.parser.verbose:
p.parser.log(
_format("Created class {0!A}:{1!A}", ns, cc.classname))
p.parser.classnames[ns].append(cc.classname.lower())
break
except CIMError as ce:
errcode = ce.status_code
if errcode == CIM_ERR_INVALID_NAMESPACE:
assert not fixedNS # Should not happen if we created it
if p.parser.verbose:
p.parser.log(
_format("Creating namespace {0!A}", ns))
p.parser.server.create_namespace(ns)
fixedNS = True
continue # Try again to create the class
if errcode == CIM_ERR_INVALID_SUPERCLASS:
assert not fixedSuper # Should not happen if we fixed it
moffile = p.parser.mofcomp.find_mof(cc.superclass)
if not moffile:
raise MOFDependencyError(
msg=_format(
"Cannot compile class {0!A} because its "
"superclass {1!A} does not exist in the CIM "
"repository and a MOF file for it was not "
"found on the search path",
cc.classname, cc.superclass),
parser_token=p)
p.parser.mofcomp.compile_file(moffile, ns)
fixedSuper = True
continue # Try again to create the class
if errcode in [CIM_ERR_INVALID_PARAMETER,
CIM_ERR_NOT_FOUND,
CIM_ERR_FAILED]:
assert not fixedRefs # Should not happen if we fixed it
if not p.parser.qualcache[ns]:
for fname in ['qualifiers', 'qualifiers_optional']:
qualfile = p.parser.mofcomp.find_mof(fname)
if qualfile:
p.parser.mofcomp.compile_file(qualfile, ns)
if not p.parser.qualcache[ns]:
raise MOFDependencyError(
msg=_format(
"Cannot compile class {0!A} because the CIM "
"repository does not contain any qualifiers "
"and the qualifier files 'qualifiers.mof' and "
"'qualifiers_optional.mof' were not found on "
"the search path or did not specify any "
"qualifiers",
cc.classname),
parser_token=p)
objects = list(cc.properties.values())
for meth in cc.methods.values():
objects += list(meth.parameters.values())
dep_classnames = []
for obj in objects:
# TODO: The following does not process method parameters
if obj.type == 'reference':
if obj.reference_class not in dep_classnames:
dep_classnames.append(obj.reference_class)
elif obj.type == 'string':
try:
embedded_inst = \
obj.qualifiers['embeddedinstance']
except KeyError:
continue
if embedded_inst.value not in dep_classnames:
dep_classnames.append(embedded_inst.value)
for cln in dep_classnames:
if cln in p.parser.classnames[ns]:
continue
try:
# don't limit it with LocalOnly=True,
# PropertyList, IncludeQualifiers=False, ...
# because of caching in case we're using the
# special WBEMConnection subclass used for
# removing schema elements
p.parser.handle.GetClass(cln,
namespace=ns,
LocalOnly=False,
IncludeQualifiers=True)
except CIMError:
moffile = p.parser.mofcomp.find_mof(cln)
if not moffile:
raise MOFDependencyError(
msg=_format(
"Cannot compile class {0!A} because "
"its dependent class {1!A} does not "
"exist in the CIM repository and a "
"MOF file for it was not found on the "
"search path",
cc.classname, cln),
parser_token=p)
if p.parser.verbose:
p.parser.log(
_format("Class {0!A} namespace {1!A} "
"depends on class {2!A} which "
"is not in repository.",
cc.classname, ns, cln))
p.parser.mofcomp.compile_file(moffile, ns)
p.parser.classnames[ns].append(cln)
fixedRefs = True
continue # Try again to create the class
# The options for fixing dependency issues have been exhausted.
# Re-raise the CIMError from CreateClass.
raise
except CIMError as ce:
if ce.status_code != CIM_ERR_ALREADY_EXISTS:
raise MOFRepositoryError(
msg=_format(
"Cannot compile class {0!A} because the CIM repository "
"returned an error for CreateClass",
cc.classname),
parser_token=p,
cim_error=ce)
if p.parser.verbose:
p.parser.log(
_format("Class {0!A} already exist. Modifying...",
cc.classname))
try:
p.parser.handle.ModifyClass(cc, ns)
except CIMError as ce:
p.parser.log(
_format("Error modifying class {0!A}: {1}, {2}",
cc.classname, ce.status_code, ce.status_description))
raise MOFRepositoryError(
msg=_format(
"Cannot compile class {0!A} because the class already "
"existed and the CIM repository returned an error for "
"ModifyClass",
cc.classname),
parser_token=p,
cim_error=ce)
def p_mp_createInstance(p):
"""mp_createInstance : instanceDeclaration"""
# p[1] is a list of instance and any alias defined in instanceDeclaration
input_ = p[1]
inst = input_[0]
alias = input_[1] # alias may be valid alias or None
ns = p.parser.target_namespace
if p.parser.verbose:
p.parser.log(
_format("Creating instance of {0!A}.", inst.classname))
# If embedded_instances flag set, save instance to this
# variable to be set into instance value rather than inserting
# into repository.
if p.parser.embedded_objects is not None:
p.parser.embedded_objects.append(inst)
return
try:
instpath = p.parser.handle.CreateInstance(inst, namespace=ns)
# Set the returned instance path into the alias table
if alias:
p.parser.aliases[alias] = instpath
except CIMError as ce:
if ce.status_code == CIM_ERR_ALREADY_EXISTS:
if p.parser.verbose:
p.parser.log(
_format("Instance of class {0!A} already exist. "
"Modifying...", inst.classname))
try:
p.parser.handle.ModifyInstance(inst)
except CIMError as ce2:
# modify failed, output original error
raise MOFRepositoryError(
msg=_format(
"Cannot compile instance of {0!A} because the CIM "
"repository returned an error for ModifyInstance",
inst.classname),
parser_token=p,
cim_error=ce2)
else:
raise MOFRepositoryError(
msg=_format(
"Cannot compile instance of {0!A} because the CIM "
"repository returned an error for CreateInstance",
inst.classname),
parser_token=p,
cim_error=ce)
def p_mp_setQualifier(p):
"""mp_setQualifier : qualifierDeclaration"""
qualdecl = p[1]
if p.parser.embedded_objects is not None:
raise MOFParseError(
msg=_format(
"Invalid compile of CIMQualifierDeclaration {0}. "
"Compiler in mode to compile Embedded instance and"
"compile of other types is invalid", qualdecl))
ns = p.parser.target_namespace
if p.parser.verbose:
p.parser.log(
_format("Setting qualifier {0!A}", qualdecl.name))
try:
p.parser.handle.SetQualifier(qualdecl, namespace=ns)
except CIMError as ce:
if ce.status_code == CIM_ERR_INVALID_NAMESPACE:
if p.parser.verbose:
p.parser.log(
_format("Creating namespace {0!A}", ns))
p.parser.server.create_namespace(ns)
if p.parser.verbose:
p.parser.log(
_format("Setting qualifier {0!A}", qualdecl.name))
p.parser.handle.SetQualifier(qualdecl, namespace=ns)
elif ce.status_code == CIM_ERR_NOT_SUPPORTED:
if p.parser.verbose:
p.parser.log(
_format("Qualifier {0!A} already exists. Deleting...",
qualdecl.name))
p.parser.handle.DeleteQualifier(qualdecl.name)
if p.parser.verbose:
p.parser.log(
_format("Setting qualifier {0!A}", qualdecl.name))
p.parser.handle.SetQualifier(qualdecl, namespace=ns)
else:
raise MOFRepositoryError(
msg=_format(
"Cannot compile qualifier declaration {0!A} because the "
"CIM repository returned an error for SetQualifier",
qualdecl.name),
parser_token=p,
cim_error=ce)
p.parser.qualcache[ns][qualdecl.name] = qualdecl
def p_compilerDirective(p):
"""compilerDirective : '#' PRAGMA pragmaName '(' pragmaParameter ')'"""
directive = p[3].lower()
param = p[5]
if directive == 'include':
fname = param
if p.parser.file:
if os.path.dirname(p.parser.file):
fname = os.path.join(os.path.dirname(p.parser.file),
fname)
p.parser.mofcomp.compile_file(fname, p.parser.target_namespace)
elif directive == 'namespace':
p.parser.target_namespace = param
if param not in p.parser.qualcache:
p.parser.qualcache[param] = NocaseDict()
p[0] = None
def p_pragmaName(p):
"""pragmaName : identifier"""
p[0] = p[1]
def p_pragmaParameter(p):
"""pragmaParameter : stringValue"""
p[0] = _fixStringValue(p[1], p)
def p_classDeclaration(p):
# pylint: disable=line-too-long
"""classDeclaration : CLASS className '{' classFeatureList '}' ';'
| CLASS className superClass '{' classFeatureList '}' ';'
| CLASS className alias '{' classFeatureList '}' ';'
| CLASS className alias superClass '{' classFeatureList '}' ';'
| qualifierList CLASS className '{' classFeatureList '}' ';'
| qualifierList CLASS className superClass '{' classFeatureList '}' ';'
| qualifierList CLASS className alias '{' classFeatureList '}' ';'
| qualifierList CLASS className alias superClass '{' classFeatureList '}' ';'
""" # noqa: E501
superclass = None
alias = None
quals = []
if isinstance(p[1], six.string_types): # no class qualifiers
cname = p[2]
if p[3][0] == '$': # alias present
alias = p[3]
if p[4] == '{': # no superclass
cfl = p[5]
else: # superclass
superclass = p[4]
cfl = p[6]
else: # no alias
if p[3] == '{': # no superclass
cfl = p[4]
else: # superclass
superclass = p[3]
cfl = p[5]
else: # class qualifiers
quals = p[1]
cname = p[3]
if p[4][0] == '$': # alias present
alias = p[4]
if p[5] == '{': # no superclass
cfl = p[6]
else: # superclass
superclass = p[5]
cfl = p[7]
else: # no alias
if p[4] == '{': # no superclass
cfl = p[5]
else: # superclass
superclass = p[4]
cfl = p[6]
quals = OrderedDict([(x.name, x) for x in quals])
methods = OrderedDict()
props = OrderedDict()
for item in cfl:
item.class_origin = cname
if isinstance(item, CIMMethod):
methods[item.name] = item
else:
props[item.name] = item
p[0] = CIMClass(cname, properties=props, methods=methods,
superclass=superclass, qualifiers=quals)
if alias:
p.parser.aliases[alias] = p[0]
def p_classFeatureList(p):
"""classFeatureList : empty
| classFeatureList classFeature
"""
if len(p) == 2:
p[0] = []
else:
p[0] = p[1] + [p[2]]
def p_qualifierListEmpty(p):
"""qualifierListEmpty : empty
| qualifierListEmpty ',' qualifier
"""
if len(p) == 2:
p[0] = []
else:
p[0] = p[1] + [p[3]]
def p_className(p):
"""className : identifier"""
p[0] = p[1]
def p_alias(p):
"""alias : AS aliasIdentifier"""
p[0] = p[2]
def p_aliasIdentifier(p):
"""aliasIdentifier : '$' identifier"""
p[0] = '${0}'.format(p[2])
def p_superClass(p):
"""superClass : ':' className"""
p[0] = p[2]
def p_classFeature(p):
"""classFeature : propertyDeclaration
| methodDeclaration
| referenceDeclaration
"""
p[0] = p[1]
def p_qualifierList(p):
"""qualifierList : '[' qualifier qualifierListEmpty ']'"""
p[0] = [p[2]] + p[3]
def p_qualifier(p):
"""qualifier : qualifierName
| qualifierName ':' flavorList
| qualifierName qualifierParameter
| qualifierName qualifierParameter ':' flavorList
"""
# pylint: disable=too-many-branches
qname = p[1]
ns = p.parser.target_namespace
qval = None
flavorlist = []
if len(p) == 3:
qval = p[2]
elif len(p) == 4:
flavorlist = p[3]
elif len(p) == 5:
qval = p[2]
flavorlist = p[4]
try: