/usr/share/pyshared/pywbem/twisted_client.py is in python-pywbem 0.7.0-4.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
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 | #
# (C) Copyright 2005,2007 Hewlett-Packard Development Company, L.P.
#
# 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; either 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>
"""pywbem.twisted - WBEM client bindings for Twisted Python.
This module contains factory classes that produce WBEMClient instances
that perform WBEM requests over HTTP using the
twisted.protocols.http.HTTPClient base class.
"""
from twisted.internet import reactor, protocol, defer
from twisted.web import http, client, error
from pywbem import CIMClass, CIMClassName, CIMInstance, CIMInstanceName, CIMError, cim_types, cim_xml
try:
from elementtree.ElementTree import fromstring, tostring
except ImportError, arg:
from xml.etree.ElementTree import fromstring, tostring
import string
from types import StringTypes
from datetime import datetime, timedelta
class WBEMClient(http.HTTPClient):
"""A HTTPClient subclass that handles WBEM requests."""
status = None
def connectionMade(self):
"""Send a HTTP POST command with the appropriate CIM over HTTP
headers and payload."""
self.factory.request_xml = str(self.factory.payload)
self.sendCommand('POST', '/cimom')
self.sendHeader('Host', '%s:%d' %
(self.transport.addr[0], self.transport.addr[1]))
self.sendHeader('User-Agent', 'pywbem/twisted')
self.sendHeader('Content-length', len(self.factory.payload))
self.sendHeader('Content-type', 'application/xml')
import base64
auth = base64.encodestring('%s:%s' % (self.factory.creds[0],
self.factory.creds[1]))[:-1]
self.sendHeader('Authorization', 'Basic %s' % auth)
self.sendHeader('CIMOperation', str(self.factory.operation))
self.sendHeader('CIMMethod', str(self.factory.method))
self.sendHeader('CIMObject', str(self.factory.object))
self.endHeaders()
# TODO: Figure out why twisted doesn't support unicode. An
# exception should be thrown by the str() call if the payload
# can't be converted to the current codepage.
self.transport.write(str(self.factory.payload))
def handleResponse(self, data):
"""Called when all response data has been received."""
self.factory.response_xml = data
if self.status == '200':
self.factory.parseErrorAndResponse(data)
self.factory.deferred = None
self.transport.loseConnection()
def handleStatus(self, version, status, message):
"""Save the status code for processing when we get to the end
of the headers."""
self.status = status
self.message = message
def handleHeader(self, key, value):
"""Handle header values."""
import urllib
if key == 'CIMError':
self.CIMError = urllib.unquote(value)
if key == 'PGErrorDetail':
self.PGErrorDetail = urllib.unquote(value)
def handleEndHeaders(self):
"""Check whether the status was OK and raise an error if not
using previously saved header information."""
if self.status != '200':
if not hasattr(self, 'cimerror') or \
not hasattr(self, 'errordetail'):
self.factory.deferred.errback(
CIMError(0, 'HTTP error %s: %s' %
(self.status, self.message)))
else:
self.factory.deferred.errback(
CIMError(0, '%s: %s' % (cimerror, errordetail)))
class WBEMClientFactory(protocol.ClientFactory):
"""Create instances of the WBEMClient class."""
request_xml = None
response_xml = None
xml_header = '<?xml version="1.0" encoding="utf-8" ?>'
def __init__(self, creds, operation, method, object, payload):
self.creds = creds
self.operation = operation
self.method = method
self.object = object
self.payload = payload
self.protocol = lambda: WBEMClient()
self.deferred = defer.Deferred()
def clientConnectionFailed(self, connector, reason):
if self.deferred is not None:
reactor.callLater(0, self.deferred.errback, reason)
def clientConnectionLost(self, connector, reason):
if self.deferred is not None:
reactor.callLater(0, self.deferred.errback, reason)
def imethodcallPayload(self, methodname, localnsp, **kwargs):
"""Generate the XML payload for an intrinsic methodcall."""
param_list = [pywbem.IPARAMVALUE(x[0], pywbem.tocimxml(x[1]))
for x in kwargs.items()]
payload = pywbem.CIM(
pywbem.MESSAGE(
pywbem.SIMPLEREQ(
pywbem.IMETHODCALL(
methodname,
pywbem.LOCALNAMESPACEPATH(
[pywbem.NAMESPACE(ns)
for ns in string.split(localnsp, '/')]),
param_list)),
'1001', '1.0'),
'2.0', '2.0')
return self.xml_header + payload.toxml()
def methodcallPayload(self, methodname, obj, namespace, **kwargs):
"""Generate the XML payload for an extrinsic methodcall."""
if isinstance(obj, CIMInstanceName):
path = obj.copy()
path.host = None
path.namespace = None
localpath = pywbem.LOCALINSTANCEPATH(
pywbem.LOCALNAMESPACEPATH(
[pywbem.NAMESPACE(ns)
for ns in string.split(namespace, '/')]),
path.tocimxml())
else:
localpath = pywbem.LOCALCLASSPATH(
pywbem.LOCALNAMESPACEPATH(
[pywbem.NAMESPACE(ns)
for ns in string.split(namespace, '/')]),
obj)
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):
return paramtype(obj[0])
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 = 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 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))
param_list = [pywbem.PARAMVALUE(x[0],
paramvalue(x[1]),
paramtype(x[1]))
for x in kwargs.items()]
payload = pywbem.CIM(
pywbem.MESSAGE(
pywbem.SIMPLEREQ(
pywbem.METHODCALL(methodname,
localpath,
param_list)),
'1001', '1.0'),
'2.0', '2.0')
return self.xml_header + payload.toxml()
def parseErrorAndResponse(self, data):
"""Parse returned XML for errors, then convert into
appropriate Python objects."""
xml = fromstring(data)
error = xml.find('.//ERROR')
if error is None:
self.deferred.callback(self.parseResponse(xml))
return
try:
code = int(error.attrib['CODE'])
except ValueError:
code = 0
self.deferred.errback(CIMError(code, error.attrib['DESCRIPTION']))
def parseResponse(self, xml):
"""Parse returned XML and convert into appropriate Python
objects. Override in subclass"""
pass
# TODO: Eww - we should get rid of the tupletree, tupleparse modules
# and replace with elementtree based code.
import pywbem.tupletree
class EnumerateInstances(WBEMClientFactory):
"""Factory to produce EnumerateInstances WBEM clients."""
def __init__(self, creds, classname, namespace = 'root/cimv2', **kwargs):
self.classname = classname
self.namespace = namespace
payload = self.imethodcallPayload(
'EnumerateInstances',
namespace,
ClassName = CIMClassName(classname),
**kwargs)
WBEMClientFactory.__init__(
self,
creds,
operation = 'MethodCall',
method = 'EnumerateInstances',
object = namespace,
payload = payload)
def __repr__(self):
return '<%s(/%s:%s) at 0x%x>' % \
(self.__class__, self.namespace, self.classname, id(self))
def parseResponse(self, xml):
tt = [pywbem.tupletree.xml_to_tupletree(tostring(x))
for x in xml.findall('.//VALUE.NAMEDINSTANCE')]
return [pywbem.tupleparse.parse_value_namedinstance(x) for x in tt]
class EnumerateInstanceNames(WBEMClientFactory):
"""Factory to produce EnumerateInstanceNames WBEM clients."""
def __init__(self, creds, classname, namespace = 'root/cimv2', **kwargs):
self.classname = classname
self.namespace = namespace
payload = self.imethodcallPayload(
'EnumerateInstanceNames',
namespace,
ClassName = CIMClassName(classname),
**kwargs)
WBEMClientFactory.__init__(
self,
creds,
operation = 'MethodCall',
method = 'EnumerateInstanceNames',
object = namespace,
payload = payload)
def __repr__(self):
return '<%s(/%s:%s) at 0x%x>' % \
(self.__class__, self.namespace, self.classname, id(self))
def parseResponse(self, xml):
tt = [pywbem.tupletree.xml_to_tupletree(tostring(x))
for x in xml.findall('.//INSTANCENAME')]
names = [pywbem.tupleparse.parse_instancename(x) for x in tt]
[setattr(n, 'namespace', self.namespace) for n in names]
return names
class GetInstance(WBEMClientFactory):
"""Factory to produce GetInstance WBEM clients."""
def __init__(self, creds, instancename, namespace = 'root/cimv2', **kwargs):
self.instancename = instancename
self.namespace = namespace
payload = self.imethodcallPayload(
'GetInstance',
namespace,
InstanceName = instancename,
**kwargs)
WBEMClientFactory.__init__(
self,
creds,
operation = 'MethodCall',
method = 'GetInstance',
object = namespace,
payload = payload)
def __repr__(self):
return '<%s(/%s:%s) at 0x%x>' % \
(self.__class__, self.namespace, self.instancename, id(self))
def parseResponse(self, xml):
tt = pywbem.tupletree.xml_to_tupletree(
tostring(xml.find('.//INSTANCE')))
return pywbem.tupleparse.parse_instance(tt)
class DeleteInstance(WBEMClientFactory):
"""Factory to produce DeleteInstance WBEM clients."""
def __init__(self, creds, instancename, namespace = 'root/cimv2', **kwargs):
self.instancename = instancename
self.namespace = namespace
payload = self.imethodcallPayload(
'DeleteInstance',
namespace,
InstanceName = instancename,
**kwargs)
WBEMClientFactory.__init__(
self,
creds,
operation = 'MethodCall',
method = 'DeleteInstance',
object = namespace,
payload = payload)
def __repr__(self):
return '<%s(/%s:%s) at 0x%x>' % \
(self.__class__, self.namespace, self.instancename, id(self))
class CreateInstance(WBEMClientFactory):
"""Factory to produce CreateInstance WBEM clients."""
# TODO: Implement __repr__ method
def __init__(self, creds, instance, namespace = 'root/cimv2', **kwargs):
payload = self.imethodcallPayload(
'CreateInstance',
namespace,
NewInstance = instance,
**kwargs)
WBEMClientFactory.__init__(
self,
creds,
operation = 'MethodCall',
method = 'CreateInstance',
object = namespace,
payload = payload)
def parseResponse(self, xml):
tt = pywbem.tupletree.xml_to_tupletree(
tostring(xml.find('.//INSTANCENAME')))
return pywbem.tupleparse.parse_instancename(tt)
class ModifyInstance(WBEMClientFactory):
"""Factory to produce ModifyInstance WBEM clients."""
# TODO: Implement __repr__ method
def __init__(self, creds, instancename, instance, namespace = 'root/cimv2',
**kwargs):
wrapped_instance = CIMNamedInstance(instancename, instance)
payload = self.imethodcallPayload(
'ModifyInstance',
namespace,
ModifiedInstance = wrapped_instance,
**kwargs)
WBEMClientFactory.__init__(
self,
creds,
operation = 'MethodCall',
method = 'ModifyInstance',
object = namespace,
payload = payload)
class EnumerateClassNames(WBEMClientFactory):
"""Factory to produce EnumerateClassNames WBEM clients."""
def __init__(self, creds, namespace = 'root/cimv2', **kwargs):
self.localnsp = LocalNamespacePath
payload = self.imethodcallPayload(
'EnumerateClassNames',
namespace,
**kwargs)
WBEMClientFactory.__init__(
self,
creds,
operation = 'MethodCall',
method = 'EnumerateClassNames',
object = LocalNamespacePath,
payload = payload)
def __repr__(self):
return '<%s(/%s) at 0x%x>' % \
(self.__class__, self.namespace, id(self))
def parseResponse(self, xml):
tt = [pywbem.tupletree.xml_to_tupletree(tostring(x))
for x in xml.findall('.//CLASSNAME')]
return [pywbem.tupleparse.parse_classname(x) for x in tt]
class EnumerateClasses(WBEMClientFactory):
"""Factory to produce EnumerateClasses WBEM clients."""
def __init__(self, creds, namespace = 'root/cimv2', **kwargs):
self.localnsp = LocalNamespacePath
payload = self.imethodcallPayload(
'EnumerateClasses',
namespace,
**kwargs)
WBEMClientFactory.__init__(
self,
creds,
operation = 'MethodCall',
method = 'EnumerateClasses',
object = namespace,
payload = payload)
def __repr__(self):
return '<%s(/%s) at 0x%x>' % \
(self.__class__, self.namespace, id(self))
def parseResponse(self, xml):
tt = [pywbem.tupletree.xml_to_tupletree(tostring(x))
for x in xml.findall('.//CLASS')]
return [pywbem.tupleparse.parse_class(x) for x in tt]
class GetClass(WBEMClientFactory):
"""Factory to produce GetClass WBEM clients."""
def __init__(self, creds, classname, namespace = 'root/cimv2', **kwargs):
self.classname = classname
self.namespace = namespace
payload = self.imethodcallPayload(
'GetClass',
namespace,
ClassName = CIMClassName(classname),
**kwargs)
WBEMClientFactory.__init__(
self,
creds,
operation = 'MethodCall',
method = 'GetClass',
object = namespace,
payload = payload)
def __repr__(self):
return '<%s(/%s:%s) at 0x%x>' % \
(self.__class__, self.namespace, self.classname, id(self))
def parseResponse(self, xml):
tt = pywbem.tupletree.xml_to_tupletree(
tostring(xml.find('.//CLASS')))
return pywbem.tupleparse.parse_class(tt)
class Associators(WBEMClientFactory):
"""Factory to produce Associators WBEM clients."""
# TODO: Implement __repr__ method
def __init__(self, creds, obj, namespace = 'root/cimv2', **kwargs):
if isinstance(obj, CIMInstanceName):
kwargs['ObjectName'] = obj
else:
kwargs['ObjectName'] = CIMClassName(obj)
payload = self.imethodcallPayload(
'Associators',
namespace,
**kwargs)
WBEMClientFactory.__init__(
self,
creds,
operation = 'MethodCall',
method = 'Associators',
object = namespace,
payload = payload)
class AssociatorNames(WBEMClientFactory):
"""Factory to produce AssociatorNames WBEM clients."""
# TODO: Implement __repr__ method
def __init__(self, creds, obj, namespace = 'root/cimv2', **kwargs):
if isinstance(obj, CIMInstanceName):
kwargs['ObjectName'] = obj
else:
kwargs['ObjectName'] = CIMClassName(obj)
payload = self.imethodcallPayload(
'AssociatorNames',
namespace,
**kwargs)
WBEMClientFactory.__init__(
self,
creds,
operation = 'MethodCall',
method = 'AssociatorNames',
object = namespace,
payload = payload)
def parseResponse(self, xml):
if len(xml.findall('.//INSTANCENAME')) > 0:
tt = [pywbem.tupletree.xml_to_tupletree(tostring(x))
for x in xml.findall('.//INSTANCENAME')]
return [pywbem.tupleparse.parse_instancename(x) for x in tt]
else:
tt = [pywbem.tupletree.xml_to_tupletree(tostring(x))
for x in xml.findall('.//OBJECTPATH')]
return [pywbem.tupleparse.parse_objectpath(x)[2] for x in tt]
class References(WBEMClientFactory):
"""Factory to produce References WBEM clients."""
def __init__(self, creds, obj, namespace = 'root/cimv2', **kwargs):
if isinstance(obj, CIMInstanceName):
kwargs['ObjectName'] = obj
else:
kwargs['ObjectName'] = CIMClassName(obj)
payload = self.imethodcallPayload(
'References',
namespace,
**kwargs)
WBEMClientFactory.__init__(
self,
creds,
operation = 'MethodCall',
method = 'References',
object = namespace,
payload = payload)
class ReferenceNames(WBEMClientFactory):
"""Factory to produce ReferenceNames WBEM clients."""
# TODO: Implement __repr__ method
def __init__(self, creds, obj, namespace = 'root/cimv2', **kwargs):
if isinstance(obj, CIMInstanceName):
kwargs['ObjectName'] = obj
else:
kwargs['ObjectName'] = CIMClassName(obj)
payload = self.imethodcallPayload(
'ReferenceNames',
namespace,
**kwargs)
WBEMClientFactory.__init__(
self,
creds,
operation = 'MethodCall',
method = 'ReferenceNames',
object = namespace,
payload = payload)
def parseResponse(self, xml):
if len(xml.findall('.//INSTANCENAME')) > 0:
tt = [pywbem.tupletree.xml_to_tupletree(tostring(x))
for x in xml.findall('.//INSTANCENAME')]
return [pywbem.tupleparse.parse_instancename(x) for x in tt]
else:
tt = [pywbem.tupletree.xml_to_tupletree(tostring(x))
for x in xml.findall('.//OBJECTPATH')]
return [pywbem.tupleparse.parse_objectpath(x)[2] for x in tt]
class InvokeMethod(WBEMClientFactory):
"""Factory to produce InvokeMethod WBEM clients."""
def __init__(self, creds, MethodName, ObjectName, namespace = 'root/cimv2',
**kwargs):
# Convert string to CIMClassName
obj = ObjectName
if isinstance(obj, StringTypes):
obj = CIMClassName(obj, namespace = namespace)
if isinstance(obj, CIMInstanceName) and obj.namespace is None:
obj = ObjectName.copy()
obj.namespace = namespace
# Make the method call
payload = self.methodcallPayload(
MethodName,
obj,
namespace,
**kwargs)
WBEMClientFactory.__init__(
self,
creds,
operation = 'MethodCall',
method = MethodName,
object = obj,
payload = payload)
|