File: cim_operations.py

package info (click to toggle)
pywbem 0.8.0~dev650-1
  • links: PTS, VCS
  • area: main
  • in suites: buster, jessie, jessie-kfreebsd, stretch
  • size: 872 kB
  • ctags: 1,115
  • sloc: python: 10,652; xml: 101; makefile: 19
file content (964 lines) | stat: -rw-r--r-- 32,538 bytes parent folder | download
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
#
# (C) Copyright 2003-2007 Hewlett-Packard Development Company, L.P.
# (C) Copyright 2006-2007 Novell, Inc. 
#
# This program 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; version 2 of the License.
#   
# 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: Tim Potter <tpot@hp.com>
#         Martin Pool <mbp@hp.com>
#         Bart Whiteley <bwhiteley@suse.de>

# This is meant to be safe for import *; ie the only global names
# should be ones that all clients can see.

import sys, string
from types import StringTypes
from xml.dom import minidom
from datetime import datetime, timedelta

from pywbem import cim_obj, cim_xml, cim_http, cim_types
from pywbem.cim_obj import CIMClassName, CIMInstanceName, CIMInstance, CIMClass, NocaseDict
from pywbem.tupletree import dom_to_tupletree, xml_to_tupletree
from pywbem.tupleparse import parse_cim

"""CIM-XML/HTTP operations.

The WBEMConnection class opens a connection to a remote WBEM server.
Across this you can run various CIM operations.  Each method of this
object corresponds fairly directly to a single CIM method call.
"""

DEFAULT_NAMESPACE = 'root/cimv2'

# TODO: Many methods have more parameters that aren't set yet.

# helper functions for validating arguments

def _check_classname(val):
    if not isinstance(val, StringTypes):
        raise ValueError("string expected for classname, not %s" % `val`)


class CIMError(Exception):
    """Raised when something bad happens.  The associated value is a
    tuple of (error_code, description).  An error code of zero
    indicates an XML parsing error in PyWBEM."""

class WBEMConnection(object):
    """Class representing a client's connection to a WBEM server.
    
    At the moment there is no persistent TCP connection; the
    connectedness is only conceptual.

    After creating a connection, various methods may be called on the
    object, which causes a remote call to the server.  All these
    operations take regular Python or cim_types values for parameters,
    and return the same.  The caller should not need to know about
    the XML encoding.  (It should be possible to use a different
    transport below this layer without disturbing any clients.)

    The connection remembers the XML for the last request and last
    reply.  This may be useful in debugging: if a problem occurs, you
    can examine the last_request and last_reply fields of the
    connection.  These are the prettified request and response; the
    real request is sent without indents so as not to corrupt whitespace.

    The caller may also register callback functions which are passed
    the request before it is sent, and the reply before it is
    unpacked.

    verify_callback is used to verify the server certificate.  It is passed to
    M2Crypto.SSL.Context.set_verify, and is called during the SSL handshake.
    verify_callback should take five arguments: An SSL Context object, an X509
    object, and three integer variables, which are in turn potential error
    number, error depth and return code. verify_callback should return True if
    verification passes and False otherwise.

    The value of the x509 argument is used only when the url contains
    'https'. x509 must be a dictionary containing the keys 'cert_file' 
    and 'key_file'. The value of 'cert_file' must consist of the
    filename of an certificate and the value of 'key_file' must consist 
    of a filename containing the private key belonging to the public key 
    that is part of the certificate in cert_file. 

    ca_certs specifies where CA certificates for verification purposes are
    located. These are trusted certificates. Note that the certificates have to
    be in PEM format. Either it is a directory prepared using the c_rehash tool
    included with OpenSSL or an pemfile. If None, default system path will be
    used.

    no_verification allows to disable peer's verification. This is insecure and
    should be avoided. If True, peer's certificate is not verified and ca_certs
    argument is ignored.
    """
    
    def __init__(self, url, creds = None, default_namespace = DEFAULT_NAMESPACE,
                 x509 = None, verify_callback = None, ca_certs = None,
                 no_verification = False):
        self.url = url
        self.creds = creds
        self.x509 = x509
        self.verify_callback = verify_callback
        self.ca_certs = ca_certs
        self.no_verification = no_verification
        self.last_request = self.last_reply = ''
        self.default_namespace = default_namespace
        self.debug = False

    def __repr__(self):
        if self.creds is None:
            user = 'anonymous'
        else:
            user = 'user=%s' % `self.creds[0]`
        return "%s(%s, %s, namespace=%s)" % (self.__class__.__name__, `self.url`,
                                             user, `self.default_namespace`)

    def imethodcall(self, methodname, namespace, **params):
        """Make an intrinsic method call.

        Returns a tupletree with a IRETURNVALUE element at the root.
        A CIMError exception is thrown if there was an error parsing
        the call response, or an ERROR element was returned.

        The parameters are automatically converted to the right
        CIM_XML objects.

        In general clients should call one of the method-specific
        methods of the connection, such as EnumerateInstanceNames,
        etc."""

        # Create HTTP headers

        headers = ['CIMOperation: MethodCall',
                   'CIMMethod: %s' % methodname,
                   cim_http.get_object_header(namespace)]

        # Create parameter list

        plist = map(lambda x:
                    cim_xml.IPARAMVALUE(x[0], cim_obj.tocimxml(x[1])),
                    params.items())
        
        # Build XML request

        req_xml = cim_xml.CIM(
            cim_xml.MESSAGE(
                cim_xml.SIMPLEREQ(
                    cim_xml.IMETHODCALL(
                        methodname,
                        cim_xml.LOCALNAMESPACEPATH(
                            [cim_xml.NAMESPACE(ns)
                             for ns in string.split(namespace, '/')]),
                        plist)),
                '1001', '1.0'),
            '2.0', '2.0')

        if self.debug:
            self.last_raw_request = req_xml.toxml()
            self.last_request = req_xml.toprettyxml(indent='  ')
            # Reset replies in case we fail before they are set
            self.last_reply = None
            self.last_raw_reply = None
        
        # Get XML response

        try:
            resp_xml = cim_http.wbem_request(self.url, req_xml.toxml(),
                                             self.creds, headers,
                                             x509 = self.x509,
                                             verify_callback = self.verify_callback,
                                             ca_certs = self.ca_certs,
                                             no_verification = self.no_verification)
        except cim_http.AuthError:
            raise
        except cim_http.Error, arg:
            # Convert cim_http exceptions to CIMError exceptions
            raise CIMError(0, str(arg))

        ## TODO: Perhaps only compute this if it's required?  Should not be
        ## all that expensive.

        reply_dom = minidom.parseString(resp_xml)

        if self.debug:
            self.last_reply = reply_dom.toprettyxml(indent='  ')
            self.last_raw_reply = resp_xml

        # Parse response

        tt = parse_cim(dom_to_tupletree(reply_dom))

        if tt[0] != 'CIM':
            raise CIMError(0, 'Expecting CIM element, got %s' % tt[0])
        tt = tt[2]
        
        if tt[0] != 'MESSAGE':
            raise CIMError(0, 'Expecting MESSAGE element, got %s' % tt[0])
        tt = tt[2]

        if len(tt) != 1 or tt[0][0] != 'SIMPLERSP':
            raise CIMError(0, 'Expecting one SIMPLERSP element')
        tt = tt[0][2]
        
        if tt[0] != 'IMETHODRESPONSE':
            raise CIMError(
                0, 'Expecting IMETHODRESPONSE element, got %s' % tt[0])

        if tt[1]['NAME'] != methodname:
            raise CIMError(0, 'Expecting attribute NAME=%s, got %s' %
                           (methodname, tt[1]['NAME']))
        tt = tt[2]

        # At this point we either have a IRETURNVALUE, ERROR element
        # or None if there was no child nodes of the IMETHODRESPONSE
        # element.

        if tt is None:
            return None

        if tt[0] == 'ERROR':
            code = int(tt[1]['CODE'])
            if tt[1].has_key('DESCRIPTION'):
                raise CIMError(code, tt[1]['DESCRIPTION'])
            raise CIMError(code, 'Error code %s' % tt[1]['CODE'])

        if tt[0] != 'IRETURNVALUE':
            raise CIMError(0, 'Expecting IRETURNVALUE element, got %s' % tt[0])

        return tt

    def methodcall(self, methodname, localobject, **params):
        """Make an extrinsic method call.

        Returns a tupletree with a RETURNVALUE element at the root.
        A CIMError exception is thrown if there was an error parsing
        the call response, or an ERROR element was returned.

        The parameters are automatically converted to the right
        CIM_XML objects."""

        # METHODCALL only takes a LOCALCLASSPATH or LOCALINSTANCEPATH 
        if hasattr(localobject, 'host') and localobject.host is not None:
            localobject = localobject.copy()
            localobject.host = None

        # Create HTTP headers

        headers = ['CIMOperation: MethodCall',
                   'CIMMethod: %s' % methodname,
                   cim_http.get_object_header(localobject)]
            
        # Create parameter list

        def paramtype(obj):
            """Return a string to be used as the CIMTYPE for a parameter."""
            if isinstance(obj, cim_types.CIMType):
                return obj.cimtype
            elif type(obj) == bool:
                return 'boolean'
            elif isinstance(obj, StringTypes):
                return 'string'
            elif isinstance(obj, (datetime, timedelta)):
                return 'datetime'
            elif isinstance(obj, (CIMClassName, CIMInstanceName)):
                return 'reference'
            elif isinstance(obj, (CIMClass, CIMInstance)):
                return 'string'
            elif isinstance(obj, list):
                if obj:
                    return paramtype(obj[0])
                else:
                    return None
            raise TypeError('Unsupported parameter type "%s"' % type(obj))

        def paramvalue(obj):
            """Return a cim_xml node to be used as the value for a
            parameter."""
            if isinstance(obj, (datetime, timedelta)):
                obj = cim_types.CIMDateTime(obj)
            if isinstance(obj, (cim_types.CIMType, bool, StringTypes)):
                return cim_xml.VALUE(cim_types.atomic_to_cim_xml(obj))
            if isinstance(obj, (CIMClassName, CIMInstanceName)):
                return cim_xml.VALUE_REFERENCE(obj.tocimxml())
            if isinstance(obj, (CIMClass, CIMInstance)):
                return cim_xml.VALUE(obj.tocimxml().toxml())
            if isinstance(obj, list):
                if obj and isinstance(obj[0], (CIMClassName, CIMInstanceName)):
                    return cim_xml.VALUE_REFARRAY([paramvalue(x) for x in obj])
                return cim_xml.VALUE_ARRAY([paramvalue(x) for x in obj])
            raise TypeError('Unsupported parameter type "%s"' % type(obj))

        def is_embedded(obj):
            """Determine if an object requires an EmbeddedObject attribute"""
            if isinstance(obj,list) and obj:
                return is_embedded(obj[0])
            elif isinstance(obj, CIMClass):
                return 'object'
            elif isinstance(obj, CIMInstance):
                return 'instance'
            return None

        plist = [cim_xml.PARAMVALUE(x[0], 
                                    paramvalue(x[1]), 
                                    paramtype(x[1]),
                                    embedded_object=is_embedded(x[1]))
                 for x in params.items()]

        # Build XML request

        req_xml = cim_xml.CIM(
            cim_xml.MESSAGE(
                cim_xml.SIMPLEREQ(
                    cim_xml.METHODCALL(
                        methodname,
                        localobject.tocimxml(),
                        plist)),
                '1001', '1.0'),
            '2.0', '2.0')

        if self.debug:
            self.last_request = req_xml.toprettyxml(indent='  ')
            self.last_raw_request = req_xml.toxml()
            # Reset replies in case we fail before they are set
            self.last_reply = None
            self.last_raw_reply = None

        # Get XML response

        try:
            resp_xml = cim_http.wbem_request(self.url, req_xml.toxml(),
                                             self.creds, headers,
                                             x509 = self.x509,
                                             verify_callback = self.verify_callback,
                                             ca_certs = self.ca_certs,
                                             no_verification = self.no_verification)
        except cim_http.Error, arg:
            # Convert cim_http exceptions to CIMError exceptions
            raise CIMError(0, str(arg))

        if self.debug:
            self.last_raw_reply = resp_xml
            resp_dom = minidom.parseString(resp_xml)
            self.last_reply = resp_dom.toprettyxml(indent='  ')

        tt = parse_cim(xml_to_tupletree(resp_xml))

        if tt[0] != 'CIM':
            raise CIMError(0, 'Expecting CIM element, got %s' % tt[0])
        tt = tt[2]
        
        if tt[0] != 'MESSAGE':
            raise CIMError(0, 'Expecting MESSAGE element, got %s' % tt[0])
        tt = tt[2]

        if len(tt) != 1 or tt[0][0] != 'SIMPLERSP':
            raise CIMError(0, 'Expecting one SIMPLERSP element')
        tt = tt[0][2]
        
        if tt[0] != 'METHODRESPONSE':
            raise CIMError(
                0, 'Expecting METHODRESPONSE element, got %s' % tt[0])

        if tt[1]['NAME'] != methodname:
            raise CIMError(0, 'Expecting attribute NAME=%s, got %s' %
                           (methodname, tt[1]['NAME']))
        tt = tt[2]

        # At this point we have an optional RETURNVALUE and zero or
        # more PARAMVALUE elements representing output parameters.

        if len(tt) > 0 and tt[0][0] == 'ERROR':
            code = int(tt[0][1]['CODE'])
            if tt[0][1].has_key('DESCRIPTION'):
                raise CIMError(code, tt[0][1]['DESCRIPTION'])
            raise CIMError(code, 'Error code %s' % tt[0][1]['CODE'])

        return tt

    #
    # Instance provider API
    # 

    def EnumerateInstanceNames(self, ClassName, namespace = None, **params):
        """Enumerate instance names of a given classname.  Returns a
        list of CIMInstanceName objects."""
        
        if namespace is None:
            namespace = self.default_namespace

        result = self.imethodcall(
            'EnumerateInstanceNames',
            namespace,
            ClassName = CIMClassName(ClassName),
            **params)

        names = []

        if result is not None:
            names = result[2]

        [setattr(n, 'namespace', namespace) for n in names]

        return names

    def EnumerateInstances(self, ClassName, namespace = None, **params):
        """Enumerate instances of a given classname.  Returns a list
        of CIMInstance objects with paths."""

        if namespace is None:
            namespace = self.default_namespace

        result = self.imethodcall(
            'EnumerateInstances',
            namespace,
            ClassName = CIMClassName(ClassName),
            **params)

        instances = []

        if result is not None:
            instances = result[2]

        [setattr(i.path, 'namespace', namespace) for i in instances]

        return instances

    def GetInstance(self, InstanceName, **params):
        """Fetch an instance given by instancename.  Returns a
        CIMInstance object."""

        # Strip off host and namespace to make this a "local" object
        
        iname = InstanceName.copy()
        iname.host = None
        iname.namespace = None

        if InstanceName.namespace is None:
            namespace = self.default_namespace
        else:
            namespace = InstanceName.namespace

        result = self.imethodcall(
            'GetInstance',
            namespace,
            InstanceName = iname,
            **params)

        instance = result[2][0]
        instance.path = InstanceName
        instance.path.namespace = namespace

        return instance

    def DeleteInstance(self, InstanceName, **params):
        """Delete the instance given by instancename."""

        # Strip off host and namespace to make this a "local" object

        iname = InstanceName.copy()
        iname.host = None
        iname.namespace = None        

        if InstanceName.namespace is None:
            namespace = self.default_namespace
        else:
            namespace = InstanceName.namespace

        self.imethodcall(
            'DeleteInstance',
            namespace,
            InstanceName = iname,
            **params)

    def CreateInstance(self, NewInstance, **params):
        """Create an instance.  Returns the name for the instance."""

        # Take namespace path from object parameter

        if NewInstance.path is not None and \
           NewInstance.path.namespace is not None:
            namespace = NewInstance.path.namespace
        else:
            namespace = self.default_namespace

        # Strip off path to avoid producing a VALUE.NAMEDINSTANCE
        # element instead of an INSTANCE element.

        instance = NewInstance.copy()
        instance.path = None

        result = self.imethodcall(
            'CreateInstance',
            namespace,
            NewInstance = instance,
            **params)

        name = result[2][0]
        name.namespace = namespace

        return name

    def ModifyInstance(self, ModifiedInstance, **params):
        """Modify properties of a named instance."""

        # Must pass a named CIMInstance here (i.e path attribute set)

        if ModifiedInstance.path is None:
            raise ValueError(
                'ModifiedInstance parameter must have path attribute set')

        # Take namespace path from object parameter

        if ModifiedInstance.path.namespace is None:
            namespace = self.default_namespace
        else:
            namespace = ModifiedInstance.path.namespace        

        instance = ModifiedInstance.copy()
        instance.path.namespace = None

        self.imethodcall(
            'ModifyInstance',
            namespace,
            ModifiedInstance = instance,
            **params)

    def ExecQuery(self, QueryLanguage, Query, namespace = None):
        if namespace is None:
            namespace = self.default_namespace
        result = self.imethodcall(
            'ExecQuery',
            namespace, 
            QueryLanguage = QueryLanguage,
            Query = Query)

        instances = []

        if result is not None:
            instances = [tt[2] for tt in result[2]]

        [setattr(i.path, 'namespace', namespace) for i in instances]

        return instances

    #
    # Schema management API
    #

    def _map_classname_param(self, params):
        """Convert string ClassName parameter to a CIMClassName."""

        if params.has_key('ClassName') and \
           isinstance(params['ClassName'], StringTypes):
            params['ClassName'] = cim_obj.CIMClassName(params['ClassName'])

        return params

    def EnumerateClassNames(self, namespace = None, **params):
        """Return a list of CIM class names. Names are returned as strings."""
        
        params = self._map_classname_param(params)

        if namespace is None:
            namespace = self.default_namespace

        result = self.imethodcall(
            'EnumerateClassNames',
            namespace,
            **params)

        if result is None:
            return []
        else:
            return map(lambda x: x.classname, result[2])
        
    def EnumerateClasses(self, namespace = None, **params):
        """Return a list of CIM class objects."""

        params = self._map_classname_param(params)

        if namespace is None:
            namespace = self.default_namespace

        result = self.imethodcall(
            'EnumerateClasses',
            namespace,
            **params)

        if result is None:
            return []
        
        return result[2]

    def GetClass(self, ClassName, namespace = None, **params):
        """Return a CIMClass representing the named class."""

        params = self._map_classname_param(params)

        if namespace is None:
            namespace = self.default_namespace

        result = self.imethodcall(
            'GetClass',
            namespace,
            ClassName = CIMClassName(ClassName),
            **params)

        return result[2][0]

    def DeleteClass(self, ClassName, namespace = None, **params):
        """Delete a class by class name."""

        # UNSUPPORTED (but actually works)

        params = self._map_classname_param(params)

        if namespace is None:
            namespace = self.default_namespace

        self.imethodcall(
            'DeleteClass',
            namespace,
            ClassName = CIMClassName(ClassName),
            **params)            

    def ModifyClass(self, ModifiedClass, namespace = None, **params):
        """Modify a CIM class."""

        # UNSUPPORTED

        if namespace is None:
            namespace = self.default_namespace

        self.imethodcall(
            'ModifyClass',
            namespace,
            ModifiedClass = ModifiedClass,
            **params)

    def CreateClass(self, NewClass, namespace = None, **params):
        """Create a CIM class."""

        # UNSUPPORTED

        if namespace is None:
            namespace = self.default_namespace

        self.imethodcall(
            'CreateClass',
            namespace,
            NewClass = NewClass,
            **params)

    #
    # Association provider API
    # 

    def _add_objectname_param(self, params, object):
        """Add an object name (either a class name or an instance
        name) to a dictionary of parameter names."""

        if isinstance(object, (CIMClassName, CIMInstanceName)):
            params['ObjectName'] = object.copy()
            params['ObjectName'].namespace = None
        elif isinstance(object, StringTypes):
            params['ObjectName'] = CIMClassName(object)
        else:
            raise ValueError('Expecting a classname, CIMClassName or '
                             'CIMInstanceName object')

        return params

    def _map_association_params(self, params):
        """Convert various convenience parameters and types into their
        correct form for passing to the imethodcall() function."""

        # ResultClass and Role parameters that are strings should be
        # mapped to CIMClassName objects.

        if params.has_key('ResultClass') and \
           isinstance(params['ResultClass'], StringTypes):
            params['ResultClass'] = cim_obj.CIMClassName(params['ResultClass'])

        if params.has_key('AssocClass') and \
           isinstance(params['AssocClass'], StringTypes):
            params['AssocClass'] = cim_obj.CIMClassName(params['AssocClass'])

        return params

    def Associators(self, ObjectName, **params):
        """Enumerate CIM classes or instances that are associated to a
        particular source CIM Object.  Pass a keyword parameter of
        'ClassName' to return associators for a CIM class, pass
        'InstanceName' to return the associators for a CIM instance."""

        params = self._map_association_params(params)
        params = self._add_objectname_param(params, ObjectName)
        
        namespace = self.default_namespace
        
        if isinstance(ObjectName, CIMInstanceName) and \
           ObjectName.namespace is not None:
            namespace = ObjectName.namespace

        result = self.imethodcall(
            'Associators',
            namespace,
            **params)

        if result is None:
            return []

        return map(lambda x: x[2], result[2])

    def AssociatorNames(self, ObjectName, **params):
        """Enumerate the names of CIM classes or instances names that are
        associated to a particular source CIM Object.  Pass a keyword
        parameter of 'ClassName' to return associator names for a CIM
        class, pass 'InstanceName' to return the associator names for a CIM
        instance.  Returns a list of CIMInstanceName objects with the
        host and namespace attributes set."""

        params = self._map_association_params(params)
        params = self._add_objectname_param(params, ObjectName)

        namespace = self.default_namespace
        
        if isinstance(ObjectName, CIMInstanceName) and \
           ObjectName.namespace is not None:
            namespace = ObjectName.namespace

        result = self.imethodcall(
            'AssociatorNames',
            namespace,
            **params)

        if result is None:
            return []

        return map(lambda x: x[2], result[2])

    def References(self, ObjectName, **params):
        """Enumerate the association objects that refer to a
        particular target CIM class or instance.  Pass a keyword
        parameter of 'ClassName' to return associators for a CIM
        class, pass 'InstanceName' to return the associators for a CIM
        instance."""

        params = self._map_association_params(params)
        params = self._add_objectname_param(params, ObjectName)

        namespace = self.default_namespace
        
        if isinstance(ObjectName, CIMInstanceName) and \
           ObjectName.namespace is not None:
            namespace = ObjectName.namespace

        result = self.imethodcall(
            'References',
            namespace,
            **params)

        if result is None:
            return []

        return map(lambda x: x[2], result[2])

    def ReferenceNames(self, ObjectName, **params):
        """Enumerate the name of association objects that refer to a
        particular target CIM class or instance.  Pass a keyword
        parameter of 'ClassName' to return associators for a CIM
        class, pass 'InstanceName' to return the associators for a CIM
        instance."""

        params = self._map_association_params(params)
        params = self._add_objectname_param(params, ObjectName)
 
        namespace = self.default_namespace
        
        if isinstance(ObjectName, CIMInstanceName) and \
           ObjectName.namespace is not None:
            namespace = ObjectName.namespace

        result = self.imethodcall(
            'ReferenceNames',
            namespace,
            **params)

        if result is None:
            return []

        return map(lambda x: x[2], result[2])

    #
    # Method provider API
    #

    def InvokeMethod(self, MethodName, ObjectName, **params):

        # Convert string to CIMClassName

        obj = ObjectName

        if isinstance(obj, StringTypes):
            obj = CIMClassName(obj, namespace = self.default_namespace)

        if isinstance(obj, CIMInstanceName) and obj.namespace is None:
            obj = ObjectName.copy()
            obj.namespace = self.default_namespace

        # Make the method call

        result = self.methodcall(MethodName, obj, **params)

        # Convert optional RETURNVALUE into a Python object

        returnvalue = None

        if len(result) > 0 and result[0][0] == 'RETURNVALUE':

            returnvalue = cim_obj.tocimobj(result[0][1]['PARAMTYPE'],
                                           result[0][2])
            result = result[1:]

        # Convert zero or more PARAMVALUE elements into dictionary

        output_params = NocaseDict()

        for p in result:
            if p[1] == 'reference':
                output_params[p[0]] = p[2]
            else:
                output_params[p[0]] = cim_obj.tocimobj(p[1], p[2])

        return returnvalue, output_params

    #
    # Qualifiers API
    #

    def EnumerateQualifiers(self, namespace = None, **params):
        """Enumerate qualifier declarations.  Returns a list of
        CIMQualifier objects."""

        if namespace is None:
            namespace = self.default_namespace

        result = self.imethodcall(
            'EnumerateQualifiers',
            namespace,
            **params)

        qualifiers = []

        if result is not None:
            names = result[2]
        else:
            names = []

        return names

    def GetQualifier(self, QualifierName, namespace = None, **params):
        """Retrieve a qualifier by name.  Returns a CIMQualifier
        object."""

        if namespace is None:
            namespace = self.default_namespace

        result = self.imethodcall(
            'GetQualifier',
            namespace,
            QualifierName = QualifierName,
            **params)

        if result is not None:
            names = result[2][0]

        return names

    def SetQualifier(self, QualifierDeclaration, namespace = None,
                     **params):
        """Set a qualifier."""

        if namespace is None:
            namespace = self.default_namespace

        result = self.imethodcall(
            'SetQualifier',
            namespace,
            QualifierDeclaration = QualifierDeclaration,
            **params)

    def DeleteQualifier(self, QualifierName, namespace = None,
                        **params):
        """Delete a qualifier by name."""

        if namespace is None:
            namespace = self.default_namespace

        result = self.imethodcall(
            'DeleteQualifier',
            namespace,
            QualifierName = QualifierName,
            **params)

def is_subclass(ch, ns, super, sub):
    """Determine if one class is a subclass of another

    Keyword Arguments:
    ch -- A CIMOMHandle.  Either a pycimmb.CIMOMHandle or a 
        pywbem.WBEMConnection.
    ns -- Namespace.
    super -- A string containing the super class name.
    sub -- The subclass.  This can either be a string or a pywbem.CIMClass.

    """

    lsuper = super.lower()
    if isinstance(sub, CIMClass):
        subname = sub.classname
        subclass = sub
    else:
        subname = sub
        subclass = None
    if subname.lower() == lsuper:
        return True
    if subclass is None:
        subclass = ch.GetClass(subname,
                               ns,
                               LocalOnly=True, 
                               IncludeQualifiers=False,
                               PropertyList=[],
                               IncludeClassOrigin=False)
    while subclass.superclass is not None:
        if subclass.superclass.lower() == lsuper:
            return True
        subclass = ch.GetClass(subclass.superclass,
                               ns,
                               LocalOnly=True, 
                               IncludeQualifiers=False,
                               PropertyList=[],
                               IncludeClassOrigin=False)
    return False

def PegasusUDSConnection(creds = None, **kwargs):
    return WBEMConnection('/var/run/tog-pegasus/cimxml.socket', creds, **kwargs)

def SFCBUDSConnection(creds = None, **kwargs):
    return WBEMConnection('/tmp/sfcbHttpSocket', creds, **kwargs)

def OpenWBEMUDSConnection(creds = None, **kwargs):
    return WBEMConnection('/tmp/OW@LCL@APIIPC_72859_Xq47Bf_P9r761-5_J-7_Q', 
                          creds, **kwargs)