repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1 value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1 value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
pywbem/pywbem | pywbem/cim_operations.py | WBEMConnection._iparam_namespace_from_namespace | def _iparam_namespace_from_namespace(self, obj):
# pylint: disable=invalid-name,
"""
Determine the namespace from a namespace string, or `None`. The
default namespace of the connection object is used, if needed.
Return the so determined namespace for use as an argument to
imethodcall().
"""
if isinstance(obj, six.string_types):
namespace = obj.strip('/')
elif obj is None:
namespace = obj
else:
raise TypeError(
_format("The 'namespace' argument of the WBEMConnection "
"operation has invalid type {0} (must be None, or a "
"string)",
type(obj)))
if namespace is None:
namespace = self.default_namespace
return namespace | python | def _iparam_namespace_from_namespace(self, obj):
# pylint: disable=invalid-name,
"""
Determine the namespace from a namespace string, or `None`. The
default namespace of the connection object is used, if needed.
Return the so determined namespace for use as an argument to
imethodcall().
"""
if isinstance(obj, six.string_types):
namespace = obj.strip('/')
elif obj is None:
namespace = obj
else:
raise TypeError(
_format("The 'namespace' argument of the WBEMConnection "
"operation has invalid type {0} (must be None, or a "
"string)",
type(obj)))
if namespace is None:
namespace = self.default_namespace
return namespace | [
"def",
"_iparam_namespace_from_namespace",
"(",
"self",
",",
"obj",
")",
":",
"# pylint: disable=invalid-name,",
"if",
"isinstance",
"(",
"obj",
",",
"six",
".",
"string_types",
")",
":",
"namespace",
"=",
"obj",
".",
"strip",
"(",
"'/'",
")",
"elif",
"obj",
... | Determine the namespace from a namespace string, or `None`. The
default namespace of the connection object is used, if needed.
Return the so determined namespace for use as an argument to
imethodcall(). | [
"Determine",
"the",
"namespace",
"from",
"a",
"namespace",
"string",
"or",
"None",
".",
"The",
"default",
"namespace",
"of",
"the",
"connection",
"object",
"is",
"used",
"if",
"needed",
"."
] | e54ecb82c2211e289a268567443d60fdd489f1e4 | https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/cim_operations.py#L2134-L2156 | train | 28,400 |
pywbem/pywbem | pywbem/cim_operations.py | WBEMConnection._iparam_namespace_from_objectname | def _iparam_namespace_from_objectname(self, objectname, arg_name):
# pylint: disable=invalid-name,
"""
Determine the namespace from an object name, that can be a class
name string, a CIMClassName or CIMInstanceName object, or `None`.
The default namespace of the connection object is used, if needed.
Return the so determined namespace for use as an argument to
imethodcall().
"""
if isinstance(objectname, (CIMClassName, CIMInstanceName)):
namespace = objectname.namespace
elif isinstance(objectname, six.string_types):
namespace = None
elif objectname is None:
namespace = objectname
else:
raise TypeError(
_format("The {0!A} argument of the WBEMConnection operation "
"has invalid type {1} (must be None, a string, a "
"CIMClassName, or a CIMInstanceName)",
arg_name, type(objectname)))
if namespace is None:
namespace = self.default_namespace
return namespace | python | def _iparam_namespace_from_objectname(self, objectname, arg_name):
# pylint: disable=invalid-name,
"""
Determine the namespace from an object name, that can be a class
name string, a CIMClassName or CIMInstanceName object, or `None`.
The default namespace of the connection object is used, if needed.
Return the so determined namespace for use as an argument to
imethodcall().
"""
if isinstance(objectname, (CIMClassName, CIMInstanceName)):
namespace = objectname.namespace
elif isinstance(objectname, six.string_types):
namespace = None
elif objectname is None:
namespace = objectname
else:
raise TypeError(
_format("The {0!A} argument of the WBEMConnection operation "
"has invalid type {1} (must be None, a string, a "
"CIMClassName, or a CIMInstanceName)",
arg_name, type(objectname)))
if namespace is None:
namespace = self.default_namespace
return namespace | [
"def",
"_iparam_namespace_from_objectname",
"(",
"self",
",",
"objectname",
",",
"arg_name",
")",
":",
"# pylint: disable=invalid-name,",
"if",
"isinstance",
"(",
"objectname",
",",
"(",
"CIMClassName",
",",
"CIMInstanceName",
")",
")",
":",
"namespace",
"=",
"objec... | Determine the namespace from an object name, that can be a class
name string, a CIMClassName or CIMInstanceName object, or `None`.
The default namespace of the connection object is used, if needed.
Return the so determined namespace for use as an argument to
imethodcall(). | [
"Determine",
"the",
"namespace",
"from",
"an",
"object",
"name",
"that",
"can",
"be",
"a",
"class",
"name",
"string",
"a",
"CIMClassName",
"or",
"CIMInstanceName",
"object",
"or",
"None",
".",
"The",
"default",
"namespace",
"of",
"the",
"connection",
"object",... | e54ecb82c2211e289a268567443d60fdd489f1e4 | https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/cim_operations.py#L2158-L2183 | train | 28,401 |
pywbem/pywbem | pywbem/cim_operations.py | WBEMConnection._get_rslt_params | def _get_rslt_params(self, result, namespace):
"""
Common processing for pull results to separate end-of-sequence,
enum-context, and entities in IRETURNVALUE.
Returns tuple of entities in IRETURNVALUE, end_of_sequence,
and enumeration_context)
"""
rtn_objects = []
end_of_sequence = False
enumeration_context = None
end_of_sequence_found = False # flag True if found and valid value
enumeration_context_found = False # flag True if ec tuple found
for p in result:
if p[0] == 'EndOfSequence':
if isinstance(p[2], six.string_types):
p2 = p[2].lower()
if p2 in ['true', 'false']: # noqa: E125
end_of_sequence = True if p2 == 'true' else False
end_of_sequence_found = True
else:
raise CIMXMLParseError(
_format("EndOfSequence output parameter has an "
"invalid value: {0!A}", p[2]),
conn_id=self.conn_id)
elif p[0] == 'EnumerationContext':
enumeration_context_found = True
if isinstance(p[2], six.string_types):
enumeration_context = p[2]
elif p[0] == "IRETURNVALUE":
rtn_objects = p[2]
if not end_of_sequence_found and not enumeration_context_found:
raise CIMXMLParseError(
"Expected EndOfSequence or EnumerationContext output "
"parameter in open/pull response, but none received",
conn_id=self.conn_id)
if not end_of_sequence and enumeration_context is None:
raise CIMXMLParseError(
"Expected EnumerationContext output parameter because "
"EndOfSequence=False, but did not receive it.",
conn_id=self.conn_id)
# Drop enumeration_context if eos True
# Returns tuple of enumeration context and namespace
rtn_ctxt = None if end_of_sequence else (enumeration_context,
namespace)
return (rtn_objects, end_of_sequence, rtn_ctxt) | python | def _get_rslt_params(self, result, namespace):
"""
Common processing for pull results to separate end-of-sequence,
enum-context, and entities in IRETURNVALUE.
Returns tuple of entities in IRETURNVALUE, end_of_sequence,
and enumeration_context)
"""
rtn_objects = []
end_of_sequence = False
enumeration_context = None
end_of_sequence_found = False # flag True if found and valid value
enumeration_context_found = False # flag True if ec tuple found
for p in result:
if p[0] == 'EndOfSequence':
if isinstance(p[2], six.string_types):
p2 = p[2].lower()
if p2 in ['true', 'false']: # noqa: E125
end_of_sequence = True if p2 == 'true' else False
end_of_sequence_found = True
else:
raise CIMXMLParseError(
_format("EndOfSequence output parameter has an "
"invalid value: {0!A}", p[2]),
conn_id=self.conn_id)
elif p[0] == 'EnumerationContext':
enumeration_context_found = True
if isinstance(p[2], six.string_types):
enumeration_context = p[2]
elif p[0] == "IRETURNVALUE":
rtn_objects = p[2]
if not end_of_sequence_found and not enumeration_context_found:
raise CIMXMLParseError(
"Expected EndOfSequence or EnumerationContext output "
"parameter in open/pull response, but none received",
conn_id=self.conn_id)
if not end_of_sequence and enumeration_context is None:
raise CIMXMLParseError(
"Expected EnumerationContext output parameter because "
"EndOfSequence=False, but did not receive it.",
conn_id=self.conn_id)
# Drop enumeration_context if eos True
# Returns tuple of enumeration context and namespace
rtn_ctxt = None if end_of_sequence else (enumeration_context,
namespace)
return (rtn_objects, end_of_sequence, rtn_ctxt) | [
"def",
"_get_rslt_params",
"(",
"self",
",",
"result",
",",
"namespace",
")",
":",
"rtn_objects",
"=",
"[",
"]",
"end_of_sequence",
"=",
"False",
"enumeration_context",
"=",
"None",
"end_of_sequence_found",
"=",
"False",
"# flag True if found and valid value",
"enumer... | Common processing for pull results to separate end-of-sequence,
enum-context, and entities in IRETURNVALUE.
Returns tuple of entities in IRETURNVALUE, end_of_sequence,
and enumeration_context) | [
"Common",
"processing",
"for",
"pull",
"results",
"to",
"separate",
"end",
"-",
"of",
"-",
"sequence",
"enum",
"-",
"context",
"and",
"entities",
"in",
"IRETURNVALUE",
"."
] | e54ecb82c2211e289a268567443d60fdd489f1e4 | https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/cim_operations.py#L2253-L2303 | train | 28,402 |
pywbem/pywbem | pywbem/cim_operations.py | WBEMConnection.GetInstance | def GetInstance(self, InstanceName, LocalOnly=None, IncludeQualifiers=None,
IncludeClassOrigin=None, PropertyList=None, **extra):
# pylint: disable=invalid-name,line-too-long
"""
Retrieve an instance.
This method performs the GetInstance operation
(see :term:`DSP0200`). See :ref:`WBEM operations` for a list of all
methods performing such operations.
If the operation succeeds, this method returns.
Otherwise, this method raises an exception.
Parameters:
InstanceName (:class:`~pywbem.CIMInstanceName`):
The instance path of the instance to be retrieved.
If this object does not specify a namespace, the default namespace
of the connection is used.
Its `host` attribute will be ignored.
LocalOnly (:class:`py:bool`):
Controls the exclusion of inherited properties from the returned
instance, as follows:
* If `False`, inherited properties are not excluded.
* If `True`, inherited properties are basically excluded, but the
behavior may be WBEM server specific.
* If `None`, this parameter is not passed to the WBEM server, and
causes the server-implemented default to be used. :term:`DSP0200`
defines that the server-implemented default is `True`.
This parameter has been deprecated in :term:`DSP0200` and should be
set to `False` by the caller.
IncludeQualifiers (:class:`py:bool`):
Indicates that qualifiers are to be included in the returned
instance, as follows:
* If `False`, qualifiers are not included.
* If `True`, qualifiers are included if the WBEM server implements
support for this parameter.
* If `None`, this parameter is not passed to the WBEM server, and
causes the server-implemented default to be used. :term:`DSP0200`
defines that the server-implemented default is `False`.
This parameter has been deprecated in :term:`DSP0200`. Clients
cannot rely on qualifiers to be returned in this operation.
IncludeClassOrigin (:class:`py:bool`):
Indicates that class origin information is to be included on each
property in the returned instance, as follows:
* If `False`, class origin information is not included.
* If `True`, class origin information is included.
* If `None`, this parameter is not passed to the WBEM server, and
causes the server-implemented default to be used. :term:`DSP0200`
defines that the server-implemented default is `False`.
This parameter has been deprecated in :term:`DSP0200`. WBEM servers
may either implement this parameter as specified, or may treat any
specified value as `False`.
PropertyList (:term:`string` or :term:`py:iterable` of :term:`string`):
An iterable specifying the names of the properties (or a string
that defines a single property) to be included in the returned
instance (case independent).
An empty iterable indicates to include no properties.
If `None`, all properties are included.
**extra :
Additional keyword arguments are passed as additional operation
parameters to the WBEM server.
Note that :term:`DSP0200` does not define any additional parameters
for this operation.
Returns:
A :class:`~pywbem.CIMInstance` object that is a representation of
the retrieved instance.
Its `path` attribute is a :class:`~pywbem.CIMInstanceName` object
with its attributes set as follows:
* `classname`: Name of the creation class of the instance.
* `keybindings`: Keybindings of the instance.
* `namespace`: Name of the CIM namespace containing the instance.
* `host`: `None`, indicating the WBEM server is unspecified.
Raises:
Exceptions described in :class:`~pywbem.WBEMConnection`.
""" # noqa: E501
exc = None
instance = None
method_name = 'GetInstance'
if self._operation_recorders:
self.operation_recorder_reset()
self.operation_recorder_stage_pywbem_args(
method=method_name,
InstanceName=InstanceName,
LocalOnly=LocalOnly,
IncludeQualifiers=IncludeQualifiers,
IncludeClassOrigin=IncludeClassOrigin,
PropertyList=PropertyList,
**extra)
try:
stats = self.statistics.start_timer(method_name)
# Strip off host and namespace to make this a "local" object
namespace = self._iparam_namespace_from_objectname(
InstanceName, 'InstanceName')
instancename = self._iparam_instancename(InstanceName)
PropertyList = _iparam_propertylist(PropertyList)
result = self._imethodcall(
method_name,
namespace,
InstanceName=instancename,
LocalOnly=LocalOnly,
IncludeQualifiers=IncludeQualifiers,
IncludeClassOrigin=IncludeClassOrigin,
PropertyList=PropertyList,
**extra)
if result is None:
raise CIMXMLParseError(
"Expecting a child element below IMETHODRESPONSE, "
"got no child elements", conn_id=self.conn_id)
result = result[0][2] # List of children of IRETURNVALUE
if not result:
raise CIMXMLParseError(
"Expecting a child element below IRETURNVALUE, "
"got no child elements", conn_id=self.conn_id)
instance = result[0] # CIMInstance object
if not isinstance(instance, CIMInstance):
raise CIMXMLParseError(
_format("Expecting CIMInstance object in result, got {0} "
"object", instance.__class__.__name__),
conn_id=self.conn_id)
# The GetInstance CIM-XML operation returns the instance as an
# INSTANCE element, which does not contain an instance path. We
# want to return the instance with a path, so we set it to the
# input path. Because the namespace in the input path is optional,
# we set it to the effective target namespace (on a copy of the
# input path).
instance.path = instancename.copy()
instance.path.namespace = namespace
return instance
except (CIMXMLParseError, XMLParseError) as exce:
exce.request_data = self.last_raw_request
exce.response_data = self.last_raw_reply
exc = exce
raise
except Exception as exce:
exc = exce
raise
finally:
self._last_operation_time = stats.stop_timer(
self.last_request_len, self.last_reply_len,
self.last_server_response_time, exc)
if self._operation_recorders:
self.operation_recorder_stage_result(instance, exc) | python | def GetInstance(self, InstanceName, LocalOnly=None, IncludeQualifiers=None,
IncludeClassOrigin=None, PropertyList=None, **extra):
# pylint: disable=invalid-name,line-too-long
"""
Retrieve an instance.
This method performs the GetInstance operation
(see :term:`DSP0200`). See :ref:`WBEM operations` for a list of all
methods performing such operations.
If the operation succeeds, this method returns.
Otherwise, this method raises an exception.
Parameters:
InstanceName (:class:`~pywbem.CIMInstanceName`):
The instance path of the instance to be retrieved.
If this object does not specify a namespace, the default namespace
of the connection is used.
Its `host` attribute will be ignored.
LocalOnly (:class:`py:bool`):
Controls the exclusion of inherited properties from the returned
instance, as follows:
* If `False`, inherited properties are not excluded.
* If `True`, inherited properties are basically excluded, but the
behavior may be WBEM server specific.
* If `None`, this parameter is not passed to the WBEM server, and
causes the server-implemented default to be used. :term:`DSP0200`
defines that the server-implemented default is `True`.
This parameter has been deprecated in :term:`DSP0200` and should be
set to `False` by the caller.
IncludeQualifiers (:class:`py:bool`):
Indicates that qualifiers are to be included in the returned
instance, as follows:
* If `False`, qualifiers are not included.
* If `True`, qualifiers are included if the WBEM server implements
support for this parameter.
* If `None`, this parameter is not passed to the WBEM server, and
causes the server-implemented default to be used. :term:`DSP0200`
defines that the server-implemented default is `False`.
This parameter has been deprecated in :term:`DSP0200`. Clients
cannot rely on qualifiers to be returned in this operation.
IncludeClassOrigin (:class:`py:bool`):
Indicates that class origin information is to be included on each
property in the returned instance, as follows:
* If `False`, class origin information is not included.
* If `True`, class origin information is included.
* If `None`, this parameter is not passed to the WBEM server, and
causes the server-implemented default to be used. :term:`DSP0200`
defines that the server-implemented default is `False`.
This parameter has been deprecated in :term:`DSP0200`. WBEM servers
may either implement this parameter as specified, or may treat any
specified value as `False`.
PropertyList (:term:`string` or :term:`py:iterable` of :term:`string`):
An iterable specifying the names of the properties (or a string
that defines a single property) to be included in the returned
instance (case independent).
An empty iterable indicates to include no properties.
If `None`, all properties are included.
**extra :
Additional keyword arguments are passed as additional operation
parameters to the WBEM server.
Note that :term:`DSP0200` does not define any additional parameters
for this operation.
Returns:
A :class:`~pywbem.CIMInstance` object that is a representation of
the retrieved instance.
Its `path` attribute is a :class:`~pywbem.CIMInstanceName` object
with its attributes set as follows:
* `classname`: Name of the creation class of the instance.
* `keybindings`: Keybindings of the instance.
* `namespace`: Name of the CIM namespace containing the instance.
* `host`: `None`, indicating the WBEM server is unspecified.
Raises:
Exceptions described in :class:`~pywbem.WBEMConnection`.
""" # noqa: E501
exc = None
instance = None
method_name = 'GetInstance'
if self._operation_recorders:
self.operation_recorder_reset()
self.operation_recorder_stage_pywbem_args(
method=method_name,
InstanceName=InstanceName,
LocalOnly=LocalOnly,
IncludeQualifiers=IncludeQualifiers,
IncludeClassOrigin=IncludeClassOrigin,
PropertyList=PropertyList,
**extra)
try:
stats = self.statistics.start_timer(method_name)
# Strip off host and namespace to make this a "local" object
namespace = self._iparam_namespace_from_objectname(
InstanceName, 'InstanceName')
instancename = self._iparam_instancename(InstanceName)
PropertyList = _iparam_propertylist(PropertyList)
result = self._imethodcall(
method_name,
namespace,
InstanceName=instancename,
LocalOnly=LocalOnly,
IncludeQualifiers=IncludeQualifiers,
IncludeClassOrigin=IncludeClassOrigin,
PropertyList=PropertyList,
**extra)
if result is None:
raise CIMXMLParseError(
"Expecting a child element below IMETHODRESPONSE, "
"got no child elements", conn_id=self.conn_id)
result = result[0][2] # List of children of IRETURNVALUE
if not result:
raise CIMXMLParseError(
"Expecting a child element below IRETURNVALUE, "
"got no child elements", conn_id=self.conn_id)
instance = result[0] # CIMInstance object
if not isinstance(instance, CIMInstance):
raise CIMXMLParseError(
_format("Expecting CIMInstance object in result, got {0} "
"object", instance.__class__.__name__),
conn_id=self.conn_id)
# The GetInstance CIM-XML operation returns the instance as an
# INSTANCE element, which does not contain an instance path. We
# want to return the instance with a path, so we set it to the
# input path. Because the namespace in the input path is optional,
# we set it to the effective target namespace (on a copy of the
# input path).
instance.path = instancename.copy()
instance.path.namespace = namespace
return instance
except (CIMXMLParseError, XMLParseError) as exce:
exce.request_data = self.last_raw_request
exce.response_data = self.last_raw_reply
exc = exce
raise
except Exception as exce:
exc = exce
raise
finally:
self._last_operation_time = stats.stop_timer(
self.last_request_len, self.last_reply_len,
self.last_server_response_time, exc)
if self._operation_recorders:
self.operation_recorder_stage_result(instance, exc) | [
"def",
"GetInstance",
"(",
"self",
",",
"InstanceName",
",",
"LocalOnly",
"=",
"None",
",",
"IncludeQualifiers",
"=",
"None",
",",
"IncludeClassOrigin",
"=",
"None",
",",
"PropertyList",
"=",
"None",
",",
"*",
"*",
"extra",
")",
":",
"# pylint: disable=invalid... | Retrieve an instance.
This method performs the GetInstance operation
(see :term:`DSP0200`). See :ref:`WBEM operations` for a list of all
methods performing such operations.
If the operation succeeds, this method returns.
Otherwise, this method raises an exception.
Parameters:
InstanceName (:class:`~pywbem.CIMInstanceName`):
The instance path of the instance to be retrieved.
If this object does not specify a namespace, the default namespace
of the connection is used.
Its `host` attribute will be ignored.
LocalOnly (:class:`py:bool`):
Controls the exclusion of inherited properties from the returned
instance, as follows:
* If `False`, inherited properties are not excluded.
* If `True`, inherited properties are basically excluded, but the
behavior may be WBEM server specific.
* If `None`, this parameter is not passed to the WBEM server, and
causes the server-implemented default to be used. :term:`DSP0200`
defines that the server-implemented default is `True`.
This parameter has been deprecated in :term:`DSP0200` and should be
set to `False` by the caller.
IncludeQualifiers (:class:`py:bool`):
Indicates that qualifiers are to be included in the returned
instance, as follows:
* If `False`, qualifiers are not included.
* If `True`, qualifiers are included if the WBEM server implements
support for this parameter.
* If `None`, this parameter is not passed to the WBEM server, and
causes the server-implemented default to be used. :term:`DSP0200`
defines that the server-implemented default is `False`.
This parameter has been deprecated in :term:`DSP0200`. Clients
cannot rely on qualifiers to be returned in this operation.
IncludeClassOrigin (:class:`py:bool`):
Indicates that class origin information is to be included on each
property in the returned instance, as follows:
* If `False`, class origin information is not included.
* If `True`, class origin information is included.
* If `None`, this parameter is not passed to the WBEM server, and
causes the server-implemented default to be used. :term:`DSP0200`
defines that the server-implemented default is `False`.
This parameter has been deprecated in :term:`DSP0200`. WBEM servers
may either implement this parameter as specified, or may treat any
specified value as `False`.
PropertyList (:term:`string` or :term:`py:iterable` of :term:`string`):
An iterable specifying the names of the properties (or a string
that defines a single property) to be included in the returned
instance (case independent).
An empty iterable indicates to include no properties.
If `None`, all properties are included.
**extra :
Additional keyword arguments are passed as additional operation
parameters to the WBEM server.
Note that :term:`DSP0200` does not define any additional parameters
for this operation.
Returns:
A :class:`~pywbem.CIMInstance` object that is a representation of
the retrieved instance.
Its `path` attribute is a :class:`~pywbem.CIMInstanceName` object
with its attributes set as follows:
* `classname`: Name of the creation class of the instance.
* `keybindings`: Keybindings of the instance.
* `namespace`: Name of the CIM namespace containing the instance.
* `host`: `None`, indicating the WBEM server is unspecified.
Raises:
Exceptions described in :class:`~pywbem.WBEMConnection`. | [
"Retrieve",
"an",
"instance",
"."
] | e54ecb82c2211e289a268567443d60fdd489f1e4 | https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/cim_operations.py#L2620-L2791 | train | 28,403 |
pywbem/pywbem | pywbem/cim_operations.py | WBEMConnection.ModifyInstance | def ModifyInstance(self, ModifiedInstance, IncludeQualifiers=None,
PropertyList=None, **extra):
# pylint: disable=invalid-name,line-too-long
"""
Modify the property values of an instance.
This method performs the ModifyInstance operation
(see :term:`DSP0200`). See :ref:`WBEM operations` for a list of all
methods performing such operations.
The `PropertyList` parameter determines the set of properties that are
designated to be modified (see its description for details).
The properties provided in the `ModifiedInstance` parameter specify
the new property values for the properties that are designated to be
modified.
Pywbem sends the property values provided in the `ModifiedInstance`
parameter to the WBEM server as provided; it does not add any default
values for properties not provided but designated to be modified, nor
does it reduce the properties by those not designated to be modified.
The properties that are actually modified by the WBEM server as a result
of this operation depend on a number of things:
* The WBEM server will reject modification requests for key properties
and for properties that are not exposed by the creation class of the
target instance.
* The WBEM server may consider some properties as read-only, as a
result of requirements at the CIM modeling level (schema or
management profiles), or as a result of an implementation decision.
Note that the WRITE qualifier on a property is not a safe indicator
as to whether the property can actually be modified. It is an
expression at the level of the CIM schema that may or may not be
considered in DMTF management profiles or in implementations.
Specifically, a qualifier value of True on a property does not
guarantee modifiability of the property, and a value of False does
not prevent modifiability.
* The WBEM server may detect invalid new values or conflicts resulting
from the new property values and may reject modification of a property
for such reasons.
If the WBEM server rejects modification of a property for any reason,
it will cause this operation to fail and will not modify any property
on the target instance. If this operation succeeds, all properties
designated to be modified have their new values (see the description
of the `ModifiedInstance` parameter for details on how the new values
are determined).
Note that properties (including properties not designated to be
modified) may change their values as an indirect result of this
operation. For example, a property that was not designated to be
modified may be derived from another property that was modified, and
may show a changed value due to that.
If the operation succeeds, this method returns.
Otherwise, this method raises an exception.
Parameters:
ModifiedInstance (:class:`~pywbem.CIMInstance`):
A representation of the modified instance, also indicating its
instance path.
The `path` attribute of this object identifies the instance to be
modified. Its `keybindings` attribute is required. If its
`namespace` attribute is `None`, the default namespace of the
connection will be used. Its `host` attribute will be ignored.
The `classname` attribute of the instance path and the `classname`
attribute of the instance must specify the same class name.
The properties defined in this object specify the new property
values (including `None` for NULL). If a property is designated to
be modified but is not specified in this object, the WBEM server
will use the default value of the property declaration if specified
(including `None`), and otherwise may update the property to any
value (including `None`).
Typically, this object has been retrieved by other operations,
such as :meth:`~pywbem.WBEMConnection.GetInstance`.
IncludeQualifiers (:class:`py:bool`):
Indicates that qualifiers are to be modified as specified in the
`ModifiedInstance` parameter, as follows:
* If `False`, qualifiers not modified.
* If `True`, qualifiers are modified if the WBEM server implements
support for this parameter.
* If `None`, this parameter is not passed to the WBEM server, and
causes the server-implemented default to be used. :term:`DSP0200`
defines that the server-implemented default is `True`.
This parameter has been deprecated in :term:`DSP0200`. Clients
cannot rely on qualifiers to be modified.
PropertyList (:term:`string` or :term:`py:iterable` of :term:`string`):
This parameter defines which properties are designated to be
modified.
This parameter is an iterable specifying the names of the
properties, or a string that specifies a single property name. In
all cases, the property names are matched case insensitively.
The specified properties are designated to be modified. Properties
not specified are not designated to be modified.
An empty iterable indicates that no properties are designated to be
modified.
If `None`, DSP0200 states that the properties with values different
from the current values in the instance are designated to be
modified, but for all practical purposes this is equivalent to
stating that all properties exposed by the instance are designated
to be modified.
**extra :
Additional keyword arguments are passed as additional operation
parameters to the WBEM server.
Note that :term:`DSP0200` does not define any additional parameters
for this operation.
Raises:
Exceptions described in :class:`~pywbem.WBEMConnection`.
""" # noqa: E501
exc = None
method_name = 'ModifyInstance'
if self._operation_recorders:
self.operation_recorder_reset()
self.operation_recorder_stage_pywbem_args(
method=method_name,
ModifiedInstance=ModifiedInstance,
IncludeQualifiers=IncludeQualifiers,
PropertyList=PropertyList,
**extra)
try:
stats = self.statistics.start_timer('ModifyInstance')
# 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')
if ModifiedInstance.path.classname is None:
raise ValueError(
'ModifiedInstance parameter must have classname set in '
' path')
if ModifiedInstance.classname is None:
raise ValueError(
'ModifiedInstance parameter must have classname set in '
'instance')
namespace = self._iparam_namespace_from_objectname(
ModifiedInstance.path, 'ModifiedInstance.path')
PropertyList = _iparam_propertylist(PropertyList)
# Strip off host and namespace to avoid producing an INSTANCEPATH or
# LOCALINSTANCEPATH element instead of the desired INSTANCENAME
# element.
instance = ModifiedInstance.copy()
instance.path.namespace = None
instance.path.host = None
self._imethodcall(
method_name,
namespace,
ModifiedInstance=instance,
IncludeQualifiers=IncludeQualifiers,
PropertyList=PropertyList,
has_return_value=False,
**extra)
return
except (CIMXMLParseError, XMLParseError) as exce:
exce.request_data = self.last_raw_request
exce.response_data = self.last_raw_reply
exc = exce
raise
except Exception as exce:
exc = exce
raise
finally:
self._last_operation_time = stats.stop_timer(
self.last_request_len, self.last_reply_len,
self.last_server_response_time, exc)
if self._operation_recorders:
self.operation_recorder_stage_result(None, exc) | python | def ModifyInstance(self, ModifiedInstance, IncludeQualifiers=None,
PropertyList=None, **extra):
# pylint: disable=invalid-name,line-too-long
"""
Modify the property values of an instance.
This method performs the ModifyInstance operation
(see :term:`DSP0200`). See :ref:`WBEM operations` for a list of all
methods performing such operations.
The `PropertyList` parameter determines the set of properties that are
designated to be modified (see its description for details).
The properties provided in the `ModifiedInstance` parameter specify
the new property values for the properties that are designated to be
modified.
Pywbem sends the property values provided in the `ModifiedInstance`
parameter to the WBEM server as provided; it does not add any default
values for properties not provided but designated to be modified, nor
does it reduce the properties by those not designated to be modified.
The properties that are actually modified by the WBEM server as a result
of this operation depend on a number of things:
* The WBEM server will reject modification requests for key properties
and for properties that are not exposed by the creation class of the
target instance.
* The WBEM server may consider some properties as read-only, as a
result of requirements at the CIM modeling level (schema or
management profiles), or as a result of an implementation decision.
Note that the WRITE qualifier on a property is not a safe indicator
as to whether the property can actually be modified. It is an
expression at the level of the CIM schema that may or may not be
considered in DMTF management profiles or in implementations.
Specifically, a qualifier value of True on a property does not
guarantee modifiability of the property, and a value of False does
not prevent modifiability.
* The WBEM server may detect invalid new values or conflicts resulting
from the new property values and may reject modification of a property
for such reasons.
If the WBEM server rejects modification of a property for any reason,
it will cause this operation to fail and will not modify any property
on the target instance. If this operation succeeds, all properties
designated to be modified have their new values (see the description
of the `ModifiedInstance` parameter for details on how the new values
are determined).
Note that properties (including properties not designated to be
modified) may change their values as an indirect result of this
operation. For example, a property that was not designated to be
modified may be derived from another property that was modified, and
may show a changed value due to that.
If the operation succeeds, this method returns.
Otherwise, this method raises an exception.
Parameters:
ModifiedInstance (:class:`~pywbem.CIMInstance`):
A representation of the modified instance, also indicating its
instance path.
The `path` attribute of this object identifies the instance to be
modified. Its `keybindings` attribute is required. If its
`namespace` attribute is `None`, the default namespace of the
connection will be used. Its `host` attribute will be ignored.
The `classname` attribute of the instance path and the `classname`
attribute of the instance must specify the same class name.
The properties defined in this object specify the new property
values (including `None` for NULL). If a property is designated to
be modified but is not specified in this object, the WBEM server
will use the default value of the property declaration if specified
(including `None`), and otherwise may update the property to any
value (including `None`).
Typically, this object has been retrieved by other operations,
such as :meth:`~pywbem.WBEMConnection.GetInstance`.
IncludeQualifiers (:class:`py:bool`):
Indicates that qualifiers are to be modified as specified in the
`ModifiedInstance` parameter, as follows:
* If `False`, qualifiers not modified.
* If `True`, qualifiers are modified if the WBEM server implements
support for this parameter.
* If `None`, this parameter is not passed to the WBEM server, and
causes the server-implemented default to be used. :term:`DSP0200`
defines that the server-implemented default is `True`.
This parameter has been deprecated in :term:`DSP0200`. Clients
cannot rely on qualifiers to be modified.
PropertyList (:term:`string` or :term:`py:iterable` of :term:`string`):
This parameter defines which properties are designated to be
modified.
This parameter is an iterable specifying the names of the
properties, or a string that specifies a single property name. In
all cases, the property names are matched case insensitively.
The specified properties are designated to be modified. Properties
not specified are not designated to be modified.
An empty iterable indicates that no properties are designated to be
modified.
If `None`, DSP0200 states that the properties with values different
from the current values in the instance are designated to be
modified, but for all practical purposes this is equivalent to
stating that all properties exposed by the instance are designated
to be modified.
**extra :
Additional keyword arguments are passed as additional operation
parameters to the WBEM server.
Note that :term:`DSP0200` does not define any additional parameters
for this operation.
Raises:
Exceptions described in :class:`~pywbem.WBEMConnection`.
""" # noqa: E501
exc = None
method_name = 'ModifyInstance'
if self._operation_recorders:
self.operation_recorder_reset()
self.operation_recorder_stage_pywbem_args(
method=method_name,
ModifiedInstance=ModifiedInstance,
IncludeQualifiers=IncludeQualifiers,
PropertyList=PropertyList,
**extra)
try:
stats = self.statistics.start_timer('ModifyInstance')
# 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')
if ModifiedInstance.path.classname is None:
raise ValueError(
'ModifiedInstance parameter must have classname set in '
' path')
if ModifiedInstance.classname is None:
raise ValueError(
'ModifiedInstance parameter must have classname set in '
'instance')
namespace = self._iparam_namespace_from_objectname(
ModifiedInstance.path, 'ModifiedInstance.path')
PropertyList = _iparam_propertylist(PropertyList)
# Strip off host and namespace to avoid producing an INSTANCEPATH or
# LOCALINSTANCEPATH element instead of the desired INSTANCENAME
# element.
instance = ModifiedInstance.copy()
instance.path.namespace = None
instance.path.host = None
self._imethodcall(
method_name,
namespace,
ModifiedInstance=instance,
IncludeQualifiers=IncludeQualifiers,
PropertyList=PropertyList,
has_return_value=False,
**extra)
return
except (CIMXMLParseError, XMLParseError) as exce:
exce.request_data = self.last_raw_request
exce.response_data = self.last_raw_reply
exc = exce
raise
except Exception as exce:
exc = exce
raise
finally:
self._last_operation_time = stats.stop_timer(
self.last_request_len, self.last_reply_len,
self.last_server_response_time, exc)
if self._operation_recorders:
self.operation_recorder_stage_result(None, exc) | [
"def",
"ModifyInstance",
"(",
"self",
",",
"ModifiedInstance",
",",
"IncludeQualifiers",
"=",
"None",
",",
"PropertyList",
"=",
"None",
",",
"*",
"*",
"extra",
")",
":",
"# pylint: disable=invalid-name,line-too-long",
"# noqa: E501",
"exc",
"=",
"None",
"method_name... | Modify the property values of an instance.
This method performs the ModifyInstance operation
(see :term:`DSP0200`). See :ref:`WBEM operations` for a list of all
methods performing such operations.
The `PropertyList` parameter determines the set of properties that are
designated to be modified (see its description for details).
The properties provided in the `ModifiedInstance` parameter specify
the new property values for the properties that are designated to be
modified.
Pywbem sends the property values provided in the `ModifiedInstance`
parameter to the WBEM server as provided; it does not add any default
values for properties not provided but designated to be modified, nor
does it reduce the properties by those not designated to be modified.
The properties that are actually modified by the WBEM server as a result
of this operation depend on a number of things:
* The WBEM server will reject modification requests for key properties
and for properties that are not exposed by the creation class of the
target instance.
* The WBEM server may consider some properties as read-only, as a
result of requirements at the CIM modeling level (schema or
management profiles), or as a result of an implementation decision.
Note that the WRITE qualifier on a property is not a safe indicator
as to whether the property can actually be modified. It is an
expression at the level of the CIM schema that may or may not be
considered in DMTF management profiles or in implementations.
Specifically, a qualifier value of True on a property does not
guarantee modifiability of the property, and a value of False does
not prevent modifiability.
* The WBEM server may detect invalid new values or conflicts resulting
from the new property values and may reject modification of a property
for such reasons.
If the WBEM server rejects modification of a property for any reason,
it will cause this operation to fail and will not modify any property
on the target instance. If this operation succeeds, all properties
designated to be modified have their new values (see the description
of the `ModifiedInstance` parameter for details on how the new values
are determined).
Note that properties (including properties not designated to be
modified) may change their values as an indirect result of this
operation. For example, a property that was not designated to be
modified may be derived from another property that was modified, and
may show a changed value due to that.
If the operation succeeds, this method returns.
Otherwise, this method raises an exception.
Parameters:
ModifiedInstance (:class:`~pywbem.CIMInstance`):
A representation of the modified instance, also indicating its
instance path.
The `path` attribute of this object identifies the instance to be
modified. Its `keybindings` attribute is required. If its
`namespace` attribute is `None`, the default namespace of the
connection will be used. Its `host` attribute will be ignored.
The `classname` attribute of the instance path and the `classname`
attribute of the instance must specify the same class name.
The properties defined in this object specify the new property
values (including `None` for NULL). If a property is designated to
be modified but is not specified in this object, the WBEM server
will use the default value of the property declaration if specified
(including `None`), and otherwise may update the property to any
value (including `None`).
Typically, this object has been retrieved by other operations,
such as :meth:`~pywbem.WBEMConnection.GetInstance`.
IncludeQualifiers (:class:`py:bool`):
Indicates that qualifiers are to be modified as specified in the
`ModifiedInstance` parameter, as follows:
* If `False`, qualifiers not modified.
* If `True`, qualifiers are modified if the WBEM server implements
support for this parameter.
* If `None`, this parameter is not passed to the WBEM server, and
causes the server-implemented default to be used. :term:`DSP0200`
defines that the server-implemented default is `True`.
This parameter has been deprecated in :term:`DSP0200`. Clients
cannot rely on qualifiers to be modified.
PropertyList (:term:`string` or :term:`py:iterable` of :term:`string`):
This parameter defines which properties are designated to be
modified.
This parameter is an iterable specifying the names of the
properties, or a string that specifies a single property name. In
all cases, the property names are matched case insensitively.
The specified properties are designated to be modified. Properties
not specified are not designated to be modified.
An empty iterable indicates that no properties are designated to be
modified.
If `None`, DSP0200 states that the properties with values different
from the current values in the instance are designated to be
modified, but for all practical purposes this is equivalent to
stating that all properties exposed by the instance are designated
to be modified.
**extra :
Additional keyword arguments are passed as additional operation
parameters to the WBEM server.
Note that :term:`DSP0200` does not define any additional parameters
for this operation.
Raises:
Exceptions described in :class:`~pywbem.WBEMConnection`. | [
"Modify",
"the",
"property",
"values",
"of",
"an",
"instance",
"."
] | e54ecb82c2211e289a268567443d60fdd489f1e4 | https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/cim_operations.py#L2793-L2984 | train | 28,404 |
pywbem/pywbem | pywbem/cim_operations.py | WBEMConnection.CreateInstance | def CreateInstance(self, NewInstance, namespace=None, **extra):
# pylint: disable=invalid-name
"""
Create an instance in a namespace.
This method performs the CreateInstance operation
(see :term:`DSP0200`). See :ref:`WBEM operations` for a list of all
methods performing such operations.
If the operation succeeds, this method returns.
Otherwise, this method raises an exception.
The creation class for the new instance is taken from the `classname`
attribute of the `NewInstance` parameter.
The namespace for the new instance is taken from these sources, in
decreasing order of priority:
* `namespace` parameter of this method, if not `None`,
* namespace in `path` attribute of the `NewInstance` parameter, if
not `None`,
* default namespace of the connection.
Parameters:
NewInstance (:class:`~pywbem.CIMInstance`):
A representation of the CIM instance to be created.
The `classname` attribute of this object specifies the creation
class for the new instance.
Apart from utilizing its namespace, the `path` attribute is ignored.
The `properties` attribute of this object specifies initial
property values for the new CIM instance.
Instance-level qualifiers have been deprecated in CIM, so any
qualifier values specified using the `qualifiers` attribute
of this object will be ignored.
namespace (:term:`string`):
Name of the CIM namespace to be used (case independent).
*New in pywbem 0.9.*
If `None`, defaults to the namespace in the `path` attribute of the
`NewInstance` parameter, or to the default namespace of the
connection.
Leading and trailing slash characters will be stripped. The lexical
case will be preserved.
**extra :
Additional keyword arguments are passed as additional operation
parameters to the WBEM server.
Note that :term:`DSP0200` does not define any additional parameters
for this operation.
Returns:
A :class:`~pywbem.CIMInstanceName` object that is the instance
path of the new instance, with classname, keybindings and
namespace set.
Raises:
Exceptions described in :class:`~pywbem.WBEMConnection`.
"""
exc = None
instancename = None
method_name = 'CreateInstance'
if self._operation_recorders:
self.operation_recorder_reset()
self.operation_recorder_stage_pywbem_args(
method=method_name,
NewInstance=NewInstance,
namespace=namespace,
**extra)
try:
stats = self.statistics.start_timer(method_name)
if namespace is None and \
getattr(NewInstance.path, 'namespace', None) is not None:
namespace = NewInstance.path.namespace
namespace = self._iparam_namespace_from_namespace(namespace)
instance = NewInstance.copy()
# Strip off path to avoid producing a VALUE.NAMEDINSTANCE element
# instead of the desired INSTANCE element.
instance.path = None
result = self._imethodcall(
method_name,
namespace,
NewInstance=instance,
**extra)
if result is None:
raise CIMXMLParseError(
"Expecting a child element below IMETHODRESPONSE, "
"got no child elements", conn_id=self.conn_id)
result = result[0][2] # List of children of IRETURNVALUE
if not result:
raise CIMXMLParseError(
"Expecting a child element below IRETURNVALUE, "
"got no child elements", conn_id=self.conn_id)
instancename = result[0] # CIMInstanceName object
if not isinstance(instancename, CIMInstanceName):
raise CIMXMLParseError(
_format("Expecting CIMInstanceName object in result, got "
"{0} object", instancename.__class__.__name__),
conn_id=self.conn_id)
# The CreateInstance CIM-XML operation returns an INSTANCENAME
# element, so the resulting CIMInstanceName object does not have
# namespace or host. We want to return an instance path with
# namespace, so we set it to the effective target namespace.
instancename.namespace = namespace
return instancename
except (CIMXMLParseError, XMLParseError) as exce:
exce.request_data = self.last_raw_request
exce.response_data = self.last_raw_reply
exc = exce
raise
except Exception as exce:
exc = exce
raise
finally:
self._last_operation_time = stats.stop_timer(
self.last_request_len, self.last_reply_len,
self.last_server_response_time, exc)
if self._operation_recorders:
self.operation_recorder_stage_result(instancename, exc) | python | def CreateInstance(self, NewInstance, namespace=None, **extra):
# pylint: disable=invalid-name
"""
Create an instance in a namespace.
This method performs the CreateInstance operation
(see :term:`DSP0200`). See :ref:`WBEM operations` for a list of all
methods performing such operations.
If the operation succeeds, this method returns.
Otherwise, this method raises an exception.
The creation class for the new instance is taken from the `classname`
attribute of the `NewInstance` parameter.
The namespace for the new instance is taken from these sources, in
decreasing order of priority:
* `namespace` parameter of this method, if not `None`,
* namespace in `path` attribute of the `NewInstance` parameter, if
not `None`,
* default namespace of the connection.
Parameters:
NewInstance (:class:`~pywbem.CIMInstance`):
A representation of the CIM instance to be created.
The `classname` attribute of this object specifies the creation
class for the new instance.
Apart from utilizing its namespace, the `path` attribute is ignored.
The `properties` attribute of this object specifies initial
property values for the new CIM instance.
Instance-level qualifiers have been deprecated in CIM, so any
qualifier values specified using the `qualifiers` attribute
of this object will be ignored.
namespace (:term:`string`):
Name of the CIM namespace to be used (case independent).
*New in pywbem 0.9.*
If `None`, defaults to the namespace in the `path` attribute of the
`NewInstance` parameter, or to the default namespace of the
connection.
Leading and trailing slash characters will be stripped. The lexical
case will be preserved.
**extra :
Additional keyword arguments are passed as additional operation
parameters to the WBEM server.
Note that :term:`DSP0200` does not define any additional parameters
for this operation.
Returns:
A :class:`~pywbem.CIMInstanceName` object that is the instance
path of the new instance, with classname, keybindings and
namespace set.
Raises:
Exceptions described in :class:`~pywbem.WBEMConnection`.
"""
exc = None
instancename = None
method_name = 'CreateInstance'
if self._operation_recorders:
self.operation_recorder_reset()
self.operation_recorder_stage_pywbem_args(
method=method_name,
NewInstance=NewInstance,
namespace=namespace,
**extra)
try:
stats = self.statistics.start_timer(method_name)
if namespace is None and \
getattr(NewInstance.path, 'namespace', None) is not None:
namespace = NewInstance.path.namespace
namespace = self._iparam_namespace_from_namespace(namespace)
instance = NewInstance.copy()
# Strip off path to avoid producing a VALUE.NAMEDINSTANCE element
# instead of the desired INSTANCE element.
instance.path = None
result = self._imethodcall(
method_name,
namespace,
NewInstance=instance,
**extra)
if result is None:
raise CIMXMLParseError(
"Expecting a child element below IMETHODRESPONSE, "
"got no child elements", conn_id=self.conn_id)
result = result[0][2] # List of children of IRETURNVALUE
if not result:
raise CIMXMLParseError(
"Expecting a child element below IRETURNVALUE, "
"got no child elements", conn_id=self.conn_id)
instancename = result[0] # CIMInstanceName object
if not isinstance(instancename, CIMInstanceName):
raise CIMXMLParseError(
_format("Expecting CIMInstanceName object in result, got "
"{0} object", instancename.__class__.__name__),
conn_id=self.conn_id)
# The CreateInstance CIM-XML operation returns an INSTANCENAME
# element, so the resulting CIMInstanceName object does not have
# namespace or host. We want to return an instance path with
# namespace, so we set it to the effective target namespace.
instancename.namespace = namespace
return instancename
except (CIMXMLParseError, XMLParseError) as exce:
exce.request_data = self.last_raw_request
exce.response_data = self.last_raw_reply
exc = exce
raise
except Exception as exce:
exc = exce
raise
finally:
self._last_operation_time = stats.stop_timer(
self.last_request_len, self.last_reply_len,
self.last_server_response_time, exc)
if self._operation_recorders:
self.operation_recorder_stage_result(instancename, exc) | [
"def",
"CreateInstance",
"(",
"self",
",",
"NewInstance",
",",
"namespace",
"=",
"None",
",",
"*",
"*",
"extra",
")",
":",
"# pylint: disable=invalid-name",
"exc",
"=",
"None",
"instancename",
"=",
"None",
"method_name",
"=",
"'CreateInstance'",
"if",
"self",
... | Create an instance in a namespace.
This method performs the CreateInstance operation
(see :term:`DSP0200`). See :ref:`WBEM operations` for a list of all
methods performing such operations.
If the operation succeeds, this method returns.
Otherwise, this method raises an exception.
The creation class for the new instance is taken from the `classname`
attribute of the `NewInstance` parameter.
The namespace for the new instance is taken from these sources, in
decreasing order of priority:
* `namespace` parameter of this method, if not `None`,
* namespace in `path` attribute of the `NewInstance` parameter, if
not `None`,
* default namespace of the connection.
Parameters:
NewInstance (:class:`~pywbem.CIMInstance`):
A representation of the CIM instance to be created.
The `classname` attribute of this object specifies the creation
class for the new instance.
Apart from utilizing its namespace, the `path` attribute is ignored.
The `properties` attribute of this object specifies initial
property values for the new CIM instance.
Instance-level qualifiers have been deprecated in CIM, so any
qualifier values specified using the `qualifiers` attribute
of this object will be ignored.
namespace (:term:`string`):
Name of the CIM namespace to be used (case independent).
*New in pywbem 0.9.*
If `None`, defaults to the namespace in the `path` attribute of the
`NewInstance` parameter, or to the default namespace of the
connection.
Leading and trailing slash characters will be stripped. The lexical
case will be preserved.
**extra :
Additional keyword arguments are passed as additional operation
parameters to the WBEM server.
Note that :term:`DSP0200` does not define any additional parameters
for this operation.
Returns:
A :class:`~pywbem.CIMInstanceName` object that is the instance
path of the new instance, with classname, keybindings and
namespace set.
Raises:
Exceptions described in :class:`~pywbem.WBEMConnection`. | [
"Create",
"an",
"instance",
"in",
"a",
"namespace",
"."
] | e54ecb82c2211e289a268567443d60fdd489f1e4 | https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/cim_operations.py#L2986-L3126 | train | 28,405 |
pywbem/pywbem | pywbem/cim_operations.py | WBEMConnection.Associators | def Associators(self, ObjectName, AssocClass=None, ResultClass=None,
Role=None, ResultRole=None, IncludeQualifiers=None,
IncludeClassOrigin=None, PropertyList=None, **extra):
# pylint: disable=invalid-name, line-too-long
"""
Retrieve the instances associated to a source instance, or the classes
associated to a source class.
This method performs the Associators operation
(see :term:`DSP0200`). See :ref:`WBEM operations` for a list of all
methods performing such operations.
If the operation succeeds, this method returns.
Otherwise, this method raises an exception.
Parameters:
ObjectName:
The object path of the source object, selecting instance-level or
class-level use of this operation, as follows:
* For selecting instance-level use: The instance path of the
source instance, as a :class:`~pywbem.CIMInstanceName` object.
If this object does not specify a namespace, the default namespace
of the connection is used.
Its `host` attribute will be ignored.
* For selecting class-level use: The class path of the source
class, as a :term:`string` or :class:`~pywbem.CIMClassName` object:
If specified as a string, the string is interpreted as a class
name in the default namespace of the connection
(case independent).
If specified as a :class:`~pywbem.CIMClassName` object, its `host`
attribute will be ignored. If this object does not specify
a namespace, the default namespace of the connection is used.
AssocClass (:term:`string` or :class:`~pywbem.CIMClassName`):
Class name of an association class (case independent),
to filter the result to include only traversals of that association
class (or subclasses).
`None` means that no such filtering is peformed.
ResultClass (:term:`string` or :class:`~pywbem.CIMClassName`):
Class name of an associated class (case independent),
to filter the result to include only traversals to that associated
class (or subclasses).
`None` means that no such filtering is peformed.
Role (:term:`string`):
Role name (= property name) of the source end (case independent),
to filter the result to include only traversals from that source
role.
`None` means that no such filtering is peformed.
ResultRole (:term:`string`):
Role name (= property name) of the far end (case independent),
to filter the result to include only traversals to that far
role.
`None` means that no such filtering is peformed.
IncludeQualifiers (:class:`py:bool`):
Indicates that qualifiers are to be included in the returned
instances (or classes), as follows:
* If `False`, qualifiers are not included.
* If `True`, qualifiers are included if the WBEM server implements
support for this parameter.
* If `None`, this parameter is not passed to the WBEM server, and
causes the server-implemented default to be used. :term:`DSP0200`
defines that the server-implemented default is `False`.
This parameter has been deprecated in :term:`DSP0200`. Clients
cannot rely on qualifiers to be returned in this operation.
IncludeClassOrigin (:class:`py:bool`):
Indicates that class origin information is to be included on each
property or method in the returned instances (or classes), as
follows:
* If `False`, class origin information is not included.
* If `True`, class origin information is included.
* If `None`, this parameter is not passed to the WBEM server, and
causes the server-implemented default to be used. :term:`DSP0200`
defines that the server-implemented default is `False`.
This parameter has been deprecated in :term:`DSP0200` for
instance-level use. WBEM servers may either implement this
parameter as specified, or may treat any specified value as `False`.
PropertyList (:term:`string` or :term:`py:iterable` of :term:`string`):
An iterable specifying the names of the properties (or a string
that defines a single property) to be included in the returned
instances (or classes) (case independent).
An empty iterable indicates to include no properties.
If `None`, all properties are included.
**extra :
Additional keyword arguments are passed as additional operation
parameters to the WBEM server.
Note that :term:`DSP0200` does not define any additional parameters
for this operation.
Returns:
: The returned list of objects depend on the usage:
* For instance-level use: A list of
:class:`~pywbem.CIMInstance` objects that are representations
of the associated instances.
The `path` attribute of each :class:`~pywbem.CIMInstance`
object is a :class:`~pywbem.CIMInstanceName` object with its
attributes set as follows:
* `classname`: Name of the creation class of the instance.
* `keybindings`: Keybindings of the instance.
* `namespace`: Name of the CIM namespace containing the instance.
* `host`: Host and optionally port of the WBEM server containing
the CIM namespace, or `None` if the server did not return host
information.
* For class-level use: A list of :func:`py:tuple` of
(classpath, class) objects that are representations of the
associated classes.
Each tuple represents one class and has these items:
* classpath (:class:`~pywbem.CIMClassName`): The class
path of the class, with its attributes set as follows:
* `classname`: Name of the class.
* `namespace`: Name of the CIM namespace containing the class.
* `host`: Host and optionally port of the WBEM server containing
the CIM namespace, or `None` if the server did not return host
information.
* class (:class:`~pywbem.CIMClass`): The representation of the
class, with its `path` attribute set to the `classpath` tuple
item.
Raises:
Exceptions described in :class:`~pywbem.WBEMConnection`.
""" # noqa: E501
exc = None
objects = None
method_name = 'Associators'
if self._operation_recorders:
self.operation_recorder_reset()
self.operation_recorder_stage_pywbem_args(
method=method_name,
ObjectName=ObjectName,
AssocClass=AssocClass,
ResultClass=ResultClass,
Role=Role,
ResultRole=ResultRole,
IncludeQualifiers=IncludeQualifiers,
IncludeClassOrigin=IncludeClassOrigin,
PropertyList=PropertyList,
**extra)
try:
stats = self.statistics.start_timer(method_name)
namespace = self._iparam_namespace_from_objectname(
ObjectName, 'ObjectName')
objectname = self._iparam_objectname(ObjectName, 'ObjectName')
PropertyList = _iparam_propertylist(PropertyList)
result = self._imethodcall(
method_name,
namespace,
ObjectName=objectname,
AssocClass=self._iparam_classname(AssocClass, 'AssocClass'),
ResultClass=self._iparam_classname(ResultClass, 'ResultClass'),
Role=Role,
ResultRole=ResultRole,
IncludeQualifiers=IncludeQualifiers,
IncludeClassOrigin=IncludeClassOrigin,
PropertyList=PropertyList,
**extra)
# instance-level invocation: list of CIMInstance
# class-level invocation: list of CIMClass
if result is None:
objects = []
else:
objects = [x[2] for x in result[0][2]]
if isinstance(objectname, CIMInstanceName):
# instance-level invocation
for instance in objects:
if not isinstance(instance, CIMInstance):
raise CIMXMLParseError(
_format("Expecting CIMInstance object in result "
"list, got {0} object",
instance.__class__.__name__),
conn_id=self.conn_id)
# path and namespace are already set
else:
# class-level invocation
for classpath, klass in objects:
if not isinstance(classpath, CIMClassName) or \
not isinstance(klass, CIMClass):
raise CIMXMLParseError(
_format("Expecting tuple (CIMClassName, CIMClass) "
"in result list, got tuple ({0}, {1})",
classpath.__class__.__name__,
klass.__class__.__name__),
conn_id=self.conn_id)
# path and namespace are already set
return objects
except (CIMXMLParseError, XMLParseError) as exce:
exce.request_data = self.last_raw_request
exce.response_data = self.last_raw_reply
exc = exce
raise
except Exception as exce:
exc = exce
raise
finally:
self._last_operation_time = stats.stop_timer(
self.last_request_len, self.last_reply_len,
self.last_server_response_time, exc)
if self._operation_recorders:
self.operation_recorder_stage_result(objects, exc) | python | def Associators(self, ObjectName, AssocClass=None, ResultClass=None,
Role=None, ResultRole=None, IncludeQualifiers=None,
IncludeClassOrigin=None, PropertyList=None, **extra):
# pylint: disable=invalid-name, line-too-long
"""
Retrieve the instances associated to a source instance, or the classes
associated to a source class.
This method performs the Associators operation
(see :term:`DSP0200`). See :ref:`WBEM operations` for a list of all
methods performing such operations.
If the operation succeeds, this method returns.
Otherwise, this method raises an exception.
Parameters:
ObjectName:
The object path of the source object, selecting instance-level or
class-level use of this operation, as follows:
* For selecting instance-level use: The instance path of the
source instance, as a :class:`~pywbem.CIMInstanceName` object.
If this object does not specify a namespace, the default namespace
of the connection is used.
Its `host` attribute will be ignored.
* For selecting class-level use: The class path of the source
class, as a :term:`string` or :class:`~pywbem.CIMClassName` object:
If specified as a string, the string is interpreted as a class
name in the default namespace of the connection
(case independent).
If specified as a :class:`~pywbem.CIMClassName` object, its `host`
attribute will be ignored. If this object does not specify
a namespace, the default namespace of the connection is used.
AssocClass (:term:`string` or :class:`~pywbem.CIMClassName`):
Class name of an association class (case independent),
to filter the result to include only traversals of that association
class (or subclasses).
`None` means that no such filtering is peformed.
ResultClass (:term:`string` or :class:`~pywbem.CIMClassName`):
Class name of an associated class (case independent),
to filter the result to include only traversals to that associated
class (or subclasses).
`None` means that no such filtering is peformed.
Role (:term:`string`):
Role name (= property name) of the source end (case independent),
to filter the result to include only traversals from that source
role.
`None` means that no such filtering is peformed.
ResultRole (:term:`string`):
Role name (= property name) of the far end (case independent),
to filter the result to include only traversals to that far
role.
`None` means that no such filtering is peformed.
IncludeQualifiers (:class:`py:bool`):
Indicates that qualifiers are to be included in the returned
instances (or classes), as follows:
* If `False`, qualifiers are not included.
* If `True`, qualifiers are included if the WBEM server implements
support for this parameter.
* If `None`, this parameter is not passed to the WBEM server, and
causes the server-implemented default to be used. :term:`DSP0200`
defines that the server-implemented default is `False`.
This parameter has been deprecated in :term:`DSP0200`. Clients
cannot rely on qualifiers to be returned in this operation.
IncludeClassOrigin (:class:`py:bool`):
Indicates that class origin information is to be included on each
property or method in the returned instances (or classes), as
follows:
* If `False`, class origin information is not included.
* If `True`, class origin information is included.
* If `None`, this parameter is not passed to the WBEM server, and
causes the server-implemented default to be used. :term:`DSP0200`
defines that the server-implemented default is `False`.
This parameter has been deprecated in :term:`DSP0200` for
instance-level use. WBEM servers may either implement this
parameter as specified, or may treat any specified value as `False`.
PropertyList (:term:`string` or :term:`py:iterable` of :term:`string`):
An iterable specifying the names of the properties (or a string
that defines a single property) to be included in the returned
instances (or classes) (case independent).
An empty iterable indicates to include no properties.
If `None`, all properties are included.
**extra :
Additional keyword arguments are passed as additional operation
parameters to the WBEM server.
Note that :term:`DSP0200` does not define any additional parameters
for this operation.
Returns:
: The returned list of objects depend on the usage:
* For instance-level use: A list of
:class:`~pywbem.CIMInstance` objects that are representations
of the associated instances.
The `path` attribute of each :class:`~pywbem.CIMInstance`
object is a :class:`~pywbem.CIMInstanceName` object with its
attributes set as follows:
* `classname`: Name of the creation class of the instance.
* `keybindings`: Keybindings of the instance.
* `namespace`: Name of the CIM namespace containing the instance.
* `host`: Host and optionally port of the WBEM server containing
the CIM namespace, or `None` if the server did not return host
information.
* For class-level use: A list of :func:`py:tuple` of
(classpath, class) objects that are representations of the
associated classes.
Each tuple represents one class and has these items:
* classpath (:class:`~pywbem.CIMClassName`): The class
path of the class, with its attributes set as follows:
* `classname`: Name of the class.
* `namespace`: Name of the CIM namespace containing the class.
* `host`: Host and optionally port of the WBEM server containing
the CIM namespace, or `None` if the server did not return host
information.
* class (:class:`~pywbem.CIMClass`): The representation of the
class, with its `path` attribute set to the `classpath` tuple
item.
Raises:
Exceptions described in :class:`~pywbem.WBEMConnection`.
""" # noqa: E501
exc = None
objects = None
method_name = 'Associators'
if self._operation_recorders:
self.operation_recorder_reset()
self.operation_recorder_stage_pywbem_args(
method=method_name,
ObjectName=ObjectName,
AssocClass=AssocClass,
ResultClass=ResultClass,
Role=Role,
ResultRole=ResultRole,
IncludeQualifiers=IncludeQualifiers,
IncludeClassOrigin=IncludeClassOrigin,
PropertyList=PropertyList,
**extra)
try:
stats = self.statistics.start_timer(method_name)
namespace = self._iparam_namespace_from_objectname(
ObjectName, 'ObjectName')
objectname = self._iparam_objectname(ObjectName, 'ObjectName')
PropertyList = _iparam_propertylist(PropertyList)
result = self._imethodcall(
method_name,
namespace,
ObjectName=objectname,
AssocClass=self._iparam_classname(AssocClass, 'AssocClass'),
ResultClass=self._iparam_classname(ResultClass, 'ResultClass'),
Role=Role,
ResultRole=ResultRole,
IncludeQualifiers=IncludeQualifiers,
IncludeClassOrigin=IncludeClassOrigin,
PropertyList=PropertyList,
**extra)
# instance-level invocation: list of CIMInstance
# class-level invocation: list of CIMClass
if result is None:
objects = []
else:
objects = [x[2] for x in result[0][2]]
if isinstance(objectname, CIMInstanceName):
# instance-level invocation
for instance in objects:
if not isinstance(instance, CIMInstance):
raise CIMXMLParseError(
_format("Expecting CIMInstance object in result "
"list, got {0} object",
instance.__class__.__name__),
conn_id=self.conn_id)
# path and namespace are already set
else:
# class-level invocation
for classpath, klass in objects:
if not isinstance(classpath, CIMClassName) or \
not isinstance(klass, CIMClass):
raise CIMXMLParseError(
_format("Expecting tuple (CIMClassName, CIMClass) "
"in result list, got tuple ({0}, {1})",
classpath.__class__.__name__,
klass.__class__.__name__),
conn_id=self.conn_id)
# path and namespace are already set
return objects
except (CIMXMLParseError, XMLParseError) as exce:
exce.request_data = self.last_raw_request
exce.response_data = self.last_raw_reply
exc = exce
raise
except Exception as exce:
exc = exce
raise
finally:
self._last_operation_time = stats.stop_timer(
self.last_request_len, self.last_reply_len,
self.last_server_response_time, exc)
if self._operation_recorders:
self.operation_recorder_stage_result(objects, exc) | [
"def",
"Associators",
"(",
"self",
",",
"ObjectName",
",",
"AssocClass",
"=",
"None",
",",
"ResultClass",
"=",
"None",
",",
"Role",
"=",
"None",
",",
"ResultRole",
"=",
"None",
",",
"IncludeQualifiers",
"=",
"None",
",",
"IncludeClassOrigin",
"=",
"None",
... | Retrieve the instances associated to a source instance, or the classes
associated to a source class.
This method performs the Associators operation
(see :term:`DSP0200`). See :ref:`WBEM operations` for a list of all
methods performing such operations.
If the operation succeeds, this method returns.
Otherwise, this method raises an exception.
Parameters:
ObjectName:
The object path of the source object, selecting instance-level or
class-level use of this operation, as follows:
* For selecting instance-level use: The instance path of the
source instance, as a :class:`~pywbem.CIMInstanceName` object.
If this object does not specify a namespace, the default namespace
of the connection is used.
Its `host` attribute will be ignored.
* For selecting class-level use: The class path of the source
class, as a :term:`string` or :class:`~pywbem.CIMClassName` object:
If specified as a string, the string is interpreted as a class
name in the default namespace of the connection
(case independent).
If specified as a :class:`~pywbem.CIMClassName` object, its `host`
attribute will be ignored. If this object does not specify
a namespace, the default namespace of the connection is used.
AssocClass (:term:`string` or :class:`~pywbem.CIMClassName`):
Class name of an association class (case independent),
to filter the result to include only traversals of that association
class (or subclasses).
`None` means that no such filtering is peformed.
ResultClass (:term:`string` or :class:`~pywbem.CIMClassName`):
Class name of an associated class (case independent),
to filter the result to include only traversals to that associated
class (or subclasses).
`None` means that no such filtering is peformed.
Role (:term:`string`):
Role name (= property name) of the source end (case independent),
to filter the result to include only traversals from that source
role.
`None` means that no such filtering is peformed.
ResultRole (:term:`string`):
Role name (= property name) of the far end (case independent),
to filter the result to include only traversals to that far
role.
`None` means that no such filtering is peformed.
IncludeQualifiers (:class:`py:bool`):
Indicates that qualifiers are to be included in the returned
instances (or classes), as follows:
* If `False`, qualifiers are not included.
* If `True`, qualifiers are included if the WBEM server implements
support for this parameter.
* If `None`, this parameter is not passed to the WBEM server, and
causes the server-implemented default to be used. :term:`DSP0200`
defines that the server-implemented default is `False`.
This parameter has been deprecated in :term:`DSP0200`. Clients
cannot rely on qualifiers to be returned in this operation.
IncludeClassOrigin (:class:`py:bool`):
Indicates that class origin information is to be included on each
property or method in the returned instances (or classes), as
follows:
* If `False`, class origin information is not included.
* If `True`, class origin information is included.
* If `None`, this parameter is not passed to the WBEM server, and
causes the server-implemented default to be used. :term:`DSP0200`
defines that the server-implemented default is `False`.
This parameter has been deprecated in :term:`DSP0200` for
instance-level use. WBEM servers may either implement this
parameter as specified, or may treat any specified value as `False`.
PropertyList (:term:`string` or :term:`py:iterable` of :term:`string`):
An iterable specifying the names of the properties (or a string
that defines a single property) to be included in the returned
instances (or classes) (case independent).
An empty iterable indicates to include no properties.
If `None`, all properties are included.
**extra :
Additional keyword arguments are passed as additional operation
parameters to the WBEM server.
Note that :term:`DSP0200` does not define any additional parameters
for this operation.
Returns:
: The returned list of objects depend on the usage:
* For instance-level use: A list of
:class:`~pywbem.CIMInstance` objects that are representations
of the associated instances.
The `path` attribute of each :class:`~pywbem.CIMInstance`
object is a :class:`~pywbem.CIMInstanceName` object with its
attributes set as follows:
* `classname`: Name of the creation class of the instance.
* `keybindings`: Keybindings of the instance.
* `namespace`: Name of the CIM namespace containing the instance.
* `host`: Host and optionally port of the WBEM server containing
the CIM namespace, or `None` if the server did not return host
information.
* For class-level use: A list of :func:`py:tuple` of
(classpath, class) objects that are representations of the
associated classes.
Each tuple represents one class and has these items:
* classpath (:class:`~pywbem.CIMClassName`): The class
path of the class, with its attributes set as follows:
* `classname`: Name of the class.
* `namespace`: Name of the CIM namespace containing the class.
* `host`: Host and optionally port of the WBEM server containing
the CIM namespace, or `None` if the server did not return host
information.
* class (:class:`~pywbem.CIMClass`): The representation of the
class, with its `path` attribute set to the `classpath` tuple
item.
Raises:
Exceptions described in :class:`~pywbem.WBEMConnection`. | [
"Retrieve",
"the",
"instances",
"associated",
"to",
"a",
"source",
"instance",
"or",
"the",
"classes",
"associated",
"to",
"a",
"source",
"class",
"."
] | e54ecb82c2211e289a268567443d60fdd489f1e4 | https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/cim_operations.py#L3199-L3436 | train | 28,406 |
pywbem/pywbem | pywbem/cim_operations.py | WBEMConnection.InvokeMethod | def InvokeMethod(self, MethodName, ObjectName, Params=None, **params):
# pylint: disable=invalid-name
"""
Invoke a method on a target instance or on a target class.
The methods that can be invoked are static and non-static methods
defined in a class (also known as *extrinsic* methods).
Static methods can be invoked on instances and on classes.
Non-static methods can be invoked only on instances.
This method performs the extrinsic method invocation operation
(see :term:`DSP0200`). See :ref:`WBEM operations` for a list of all
methods performing such operations.
If the operation succeeds, this method returns.
Otherwise, this method raises an exception.
Input parameters for the CIM method can be specified using the
`Params` parameter, and using keyword parameters.
The overall list of input parameters is formed from the list of
parameters specified in `Params` (preserving their order), followed by
the set of keyword parameters (not preserving their order). There is no
checking for duplicate parameter names.
Parameters:
MethodName (:term:`string`):
Name of the method to be invoked (case independent).
ObjectName:
The object path of the target object, as follows:
* For instance-level use: The instance path of the target
instance, as a :class:`~pywbem.CIMInstanceName` object.
If this object does not specify a namespace, the default namespace
of the connection is used.
Its `host` attribute will be ignored.
* For class-level use: The class path of the target class, as a
:term:`string` or :class:`~pywbem.CIMClassName` object:
If specified as a string, the string is interpreted as a class
name in the default namespace of the connection
(case independent).
If specified as a :class:`~pywbem.CIMClassName` object, its `host`
attribute will be ignored. If this object does not specify
a namespace, the default namespace of the connection is used.
Params (:term:`py:iterable`):
An iterable of input parameter values for the CIM method. Each item
in the iterable is a single parameter value and can be any of:
* :class:`~pywbem.CIMParameter` representing a parameter value. The
`name`, `value`, `type` and `embedded_object` attributes of this
object are used.
* tuple of name, value, with:
- name (:term:`string`): Parameter name (case independent)
- value (:term:`CIM data type`): Parameter value
**params :
Each keyword parameter is an additional input parameter value for
the CIM method, with:
* key (:term:`string`): Parameter name (case independent)
* value (:term:`CIM data type`): Parameter value
Returns:
A :func:`py:tuple` of (returnvalue, outparams), with these
tuple items:
* returnvalue (:term:`CIM data type`):
Return value of the CIM method.
* outparams (:ref:`NocaseDict`):
Dictionary with all provided output parameters of the CIM method,
with:
* key (:term:`unicode string`):
Parameter name, preserving its lexical case
* value (:term:`CIM data type`):
Parameter value
Raises:
Exceptions described in :class:`~pywbem.WBEMConnection`.
"""
exc = None
result_tuple = None
if self._operation_recorders:
self.operation_recorder_reset()
self.operation_recorder_stage_pywbem_args(
method='InvokeMethod',
MethodName=MethodName,
ObjectName=ObjectName,
Params=Params,
**params)
try:
stats = self.statistics.start_timer('InvokeMethod')
# Make the method call
result = self._methodcall(MethodName, ObjectName, Params, **params)
return result
except (CIMXMLParseError, XMLParseError) as exce:
exce.request_data = self.last_raw_request
exce.response_data = self.last_raw_reply
exc = exce
raise
except Exception as exce:
exc = exce
raise
finally:
self._last_operation_time = stats.stop_timer(
self.last_request_len, self.last_reply_len,
self.last_server_response_time, exc)
if self._operation_recorders:
self.operation_recorder_stage_result(result_tuple, exc) | python | def InvokeMethod(self, MethodName, ObjectName, Params=None, **params):
# pylint: disable=invalid-name
"""
Invoke a method on a target instance or on a target class.
The methods that can be invoked are static and non-static methods
defined in a class (also known as *extrinsic* methods).
Static methods can be invoked on instances and on classes.
Non-static methods can be invoked only on instances.
This method performs the extrinsic method invocation operation
(see :term:`DSP0200`). See :ref:`WBEM operations` for a list of all
methods performing such operations.
If the operation succeeds, this method returns.
Otherwise, this method raises an exception.
Input parameters for the CIM method can be specified using the
`Params` parameter, and using keyword parameters.
The overall list of input parameters is formed from the list of
parameters specified in `Params` (preserving their order), followed by
the set of keyword parameters (not preserving their order). There is no
checking for duplicate parameter names.
Parameters:
MethodName (:term:`string`):
Name of the method to be invoked (case independent).
ObjectName:
The object path of the target object, as follows:
* For instance-level use: The instance path of the target
instance, as a :class:`~pywbem.CIMInstanceName` object.
If this object does not specify a namespace, the default namespace
of the connection is used.
Its `host` attribute will be ignored.
* For class-level use: The class path of the target class, as a
:term:`string` or :class:`~pywbem.CIMClassName` object:
If specified as a string, the string is interpreted as a class
name in the default namespace of the connection
(case independent).
If specified as a :class:`~pywbem.CIMClassName` object, its `host`
attribute will be ignored. If this object does not specify
a namespace, the default namespace of the connection is used.
Params (:term:`py:iterable`):
An iterable of input parameter values for the CIM method. Each item
in the iterable is a single parameter value and can be any of:
* :class:`~pywbem.CIMParameter` representing a parameter value. The
`name`, `value`, `type` and `embedded_object` attributes of this
object are used.
* tuple of name, value, with:
- name (:term:`string`): Parameter name (case independent)
- value (:term:`CIM data type`): Parameter value
**params :
Each keyword parameter is an additional input parameter value for
the CIM method, with:
* key (:term:`string`): Parameter name (case independent)
* value (:term:`CIM data type`): Parameter value
Returns:
A :func:`py:tuple` of (returnvalue, outparams), with these
tuple items:
* returnvalue (:term:`CIM data type`):
Return value of the CIM method.
* outparams (:ref:`NocaseDict`):
Dictionary with all provided output parameters of the CIM method,
with:
* key (:term:`unicode string`):
Parameter name, preserving its lexical case
* value (:term:`CIM data type`):
Parameter value
Raises:
Exceptions described in :class:`~pywbem.WBEMConnection`.
"""
exc = None
result_tuple = None
if self._operation_recorders:
self.operation_recorder_reset()
self.operation_recorder_stage_pywbem_args(
method='InvokeMethod',
MethodName=MethodName,
ObjectName=ObjectName,
Params=Params,
**params)
try:
stats = self.statistics.start_timer('InvokeMethod')
# Make the method call
result = self._methodcall(MethodName, ObjectName, Params, **params)
return result
except (CIMXMLParseError, XMLParseError) as exce:
exce.request_data = self.last_raw_request
exce.response_data = self.last_raw_reply
exc = exce
raise
except Exception as exce:
exc = exce
raise
finally:
self._last_operation_time = stats.stop_timer(
self.last_request_len, self.last_reply_len,
self.last_server_response_time, exc)
if self._operation_recorders:
self.operation_recorder_stage_result(result_tuple, exc) | [
"def",
"InvokeMethod",
"(",
"self",
",",
"MethodName",
",",
"ObjectName",
",",
"Params",
"=",
"None",
",",
"*",
"*",
"params",
")",
":",
"# pylint: disable=invalid-name",
"exc",
"=",
"None",
"result_tuple",
"=",
"None",
"if",
"self",
".",
"_operation_recorders... | Invoke a method on a target instance or on a target class.
The methods that can be invoked are static and non-static methods
defined in a class (also known as *extrinsic* methods).
Static methods can be invoked on instances and on classes.
Non-static methods can be invoked only on instances.
This method performs the extrinsic method invocation operation
(see :term:`DSP0200`). See :ref:`WBEM operations` for a list of all
methods performing such operations.
If the operation succeeds, this method returns.
Otherwise, this method raises an exception.
Input parameters for the CIM method can be specified using the
`Params` parameter, and using keyword parameters.
The overall list of input parameters is formed from the list of
parameters specified in `Params` (preserving their order), followed by
the set of keyword parameters (not preserving their order). There is no
checking for duplicate parameter names.
Parameters:
MethodName (:term:`string`):
Name of the method to be invoked (case independent).
ObjectName:
The object path of the target object, as follows:
* For instance-level use: The instance path of the target
instance, as a :class:`~pywbem.CIMInstanceName` object.
If this object does not specify a namespace, the default namespace
of the connection is used.
Its `host` attribute will be ignored.
* For class-level use: The class path of the target class, as a
:term:`string` or :class:`~pywbem.CIMClassName` object:
If specified as a string, the string is interpreted as a class
name in the default namespace of the connection
(case independent).
If specified as a :class:`~pywbem.CIMClassName` object, its `host`
attribute will be ignored. If this object does not specify
a namespace, the default namespace of the connection is used.
Params (:term:`py:iterable`):
An iterable of input parameter values for the CIM method. Each item
in the iterable is a single parameter value and can be any of:
* :class:`~pywbem.CIMParameter` representing a parameter value. The
`name`, `value`, `type` and `embedded_object` attributes of this
object are used.
* tuple of name, value, with:
- name (:term:`string`): Parameter name (case independent)
- value (:term:`CIM data type`): Parameter value
**params :
Each keyword parameter is an additional input parameter value for
the CIM method, with:
* key (:term:`string`): Parameter name (case independent)
* value (:term:`CIM data type`): Parameter value
Returns:
A :func:`py:tuple` of (returnvalue, outparams), with these
tuple items:
* returnvalue (:term:`CIM data type`):
Return value of the CIM method.
* outparams (:ref:`NocaseDict`):
Dictionary with all provided output parameters of the CIM method,
with:
* key (:term:`unicode string`):
Parameter name, preserving its lexical case
* value (:term:`CIM data type`):
Parameter value
Raises:
Exceptions described in :class:`~pywbem.WBEMConnection`. | [
"Invoke",
"a",
"method",
"on",
"a",
"target",
"instance",
"or",
"on",
"a",
"target",
"class",
"."
] | e54ecb82c2211e289a268567443d60fdd489f1e4 | https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/cim_operations.py#L3995-L4119 | train | 28,407 |
pywbem/pywbem | pywbem/cim_operations.py | WBEMConnection.ExecQuery | def ExecQuery(self, QueryLanguage, Query, namespace=None, **extra):
# pylint: disable=invalid-name
"""
Execute a query in a namespace.
This method performs the ExecQuery operation
(see :term:`DSP0200`). See :ref:`WBEM operations` for a list of all
methods performing such operations.
If the operation succeeds, this method returns.
Otherwise, this method raises an exception.
Parameters:
QueryLanguage (:term:`string`):
Name of the query language used in the `Query` parameter, e.g.
"DMTF:CQL" for CIM Query Language, and "WQL" for WBEM Query
Language.
Query (:term:`string`):
Query string in the query language specified in the `QueryLanguage`
parameter.
namespace (:term:`string`):
Name of the CIM namespace to be used (case independent).
Leading and trailing slash characters will be stripped. The lexical
case will be preserved.
If `None`, the default namespace of the connection object will be
used.
**extra :
Additional keyword arguments are passed as additional operation
parameters to the WBEM server.
Note that :term:`DSP0200` does not define any additional parameters
for this operation.
Returns:
A list of :class:`~pywbem.CIMInstance` objects that represents
the query result.
These instances have their `path` attribute set to identify
their creation class and the target namespace of the query, but
they are not addressable instances.
Raises:
Exceptions described in :class:`~pywbem.WBEMConnection`.
"""
exc = None
instances = None
method_name = 'ExecQuery'
if self._operation_recorders:
self.operation_recorder_reset()
self.operation_recorder_stage_pywbem_args(
method=method_name,
QueryLanguage=QueryLanguage,
Query=Query,
namespace=namespace,
**extra)
try:
stats = self.statistics.start_timer(method_name)
namespace = self._iparam_namespace_from_namespace(namespace)
result = self._imethodcall(
method_name,
namespace,
QueryLanguage=QueryLanguage,
Query=Query,
**extra)
if result is None:
instances = []
else:
instances = [x[2] for x in result[0][2]]
for instance in instances:
# The ExecQuery CIM-XML operation returns instances as any of
# (VALUE.OBJECT | VALUE.OBJECTWITHLOCALPATH |
# VALUE.OBJECTWITHPATH), i.e. classes or instances with or
# without path which may or may not contain a namespace.
# TODO: Fix current impl. that assumes instance with path.
instance.path.namespace = namespace
return instances
except (CIMXMLParseError, XMLParseError) as exce:
exce.request_data = self.last_raw_request
exce.response_data = self.last_raw_reply
exc = exce
raise
except Exception as exce:
exc = exce
raise
finally:
self._last_operation_time = stats.stop_timer(
self.last_request_len, self.last_reply_len,
self.last_server_response_time, exc)
if self._operation_recorders:
self.operation_recorder_stage_result(instances, exc) | python | def ExecQuery(self, QueryLanguage, Query, namespace=None, **extra):
# pylint: disable=invalid-name
"""
Execute a query in a namespace.
This method performs the ExecQuery operation
(see :term:`DSP0200`). See :ref:`WBEM operations` for a list of all
methods performing such operations.
If the operation succeeds, this method returns.
Otherwise, this method raises an exception.
Parameters:
QueryLanguage (:term:`string`):
Name of the query language used in the `Query` parameter, e.g.
"DMTF:CQL" for CIM Query Language, and "WQL" for WBEM Query
Language.
Query (:term:`string`):
Query string in the query language specified in the `QueryLanguage`
parameter.
namespace (:term:`string`):
Name of the CIM namespace to be used (case independent).
Leading and trailing slash characters will be stripped. The lexical
case will be preserved.
If `None`, the default namespace of the connection object will be
used.
**extra :
Additional keyword arguments are passed as additional operation
parameters to the WBEM server.
Note that :term:`DSP0200` does not define any additional parameters
for this operation.
Returns:
A list of :class:`~pywbem.CIMInstance` objects that represents
the query result.
These instances have their `path` attribute set to identify
their creation class and the target namespace of the query, but
they are not addressable instances.
Raises:
Exceptions described in :class:`~pywbem.WBEMConnection`.
"""
exc = None
instances = None
method_name = 'ExecQuery'
if self._operation_recorders:
self.operation_recorder_reset()
self.operation_recorder_stage_pywbem_args(
method=method_name,
QueryLanguage=QueryLanguage,
Query=Query,
namespace=namespace,
**extra)
try:
stats = self.statistics.start_timer(method_name)
namespace = self._iparam_namespace_from_namespace(namespace)
result = self._imethodcall(
method_name,
namespace,
QueryLanguage=QueryLanguage,
Query=Query,
**extra)
if result is None:
instances = []
else:
instances = [x[2] for x in result[0][2]]
for instance in instances:
# The ExecQuery CIM-XML operation returns instances as any of
# (VALUE.OBJECT | VALUE.OBJECTWITHLOCALPATH |
# VALUE.OBJECTWITHPATH), i.e. classes or instances with or
# without path which may or may not contain a namespace.
# TODO: Fix current impl. that assumes instance with path.
instance.path.namespace = namespace
return instances
except (CIMXMLParseError, XMLParseError) as exce:
exce.request_data = self.last_raw_request
exce.response_data = self.last_raw_reply
exc = exce
raise
except Exception as exce:
exc = exce
raise
finally:
self._last_operation_time = stats.stop_timer(
self.last_request_len, self.last_reply_len,
self.last_server_response_time, exc)
if self._operation_recorders:
self.operation_recorder_stage_result(instances, exc) | [
"def",
"ExecQuery",
"(",
"self",
",",
"QueryLanguage",
",",
"Query",
",",
"namespace",
"=",
"None",
",",
"*",
"*",
"extra",
")",
":",
"# pylint: disable=invalid-name",
"exc",
"=",
"None",
"instances",
"=",
"None",
"method_name",
"=",
"'ExecQuery'",
"if",
"se... | Execute a query in a namespace.
This method performs the ExecQuery operation
(see :term:`DSP0200`). See :ref:`WBEM operations` for a list of all
methods performing such operations.
If the operation succeeds, this method returns.
Otherwise, this method raises an exception.
Parameters:
QueryLanguage (:term:`string`):
Name of the query language used in the `Query` parameter, e.g.
"DMTF:CQL" for CIM Query Language, and "WQL" for WBEM Query
Language.
Query (:term:`string`):
Query string in the query language specified in the `QueryLanguage`
parameter.
namespace (:term:`string`):
Name of the CIM namespace to be used (case independent).
Leading and trailing slash characters will be stripped. The lexical
case will be preserved.
If `None`, the default namespace of the connection object will be
used.
**extra :
Additional keyword arguments are passed as additional operation
parameters to the WBEM server.
Note that :term:`DSP0200` does not define any additional parameters
for this operation.
Returns:
A list of :class:`~pywbem.CIMInstance` objects that represents
the query result.
These instances have their `path` attribute set to identify
their creation class and the target namespace of the query, but
they are not addressable instances.
Raises:
Exceptions described in :class:`~pywbem.WBEMConnection`. | [
"Execute",
"a",
"query",
"in",
"a",
"namespace",
"."
] | e54ecb82c2211e289a268567443d60fdd489f1e4 | https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/cim_operations.py#L4121-L4228 | train | 28,408 |
pywbem/pywbem | pywbem/cim_operations.py | WBEMConnection.OpenAssociatorInstancePaths | def OpenAssociatorInstancePaths(self, InstanceName, AssocClass=None,
ResultClass=None, Role=None,
ResultRole=None,
FilterQueryLanguage=None, FilterQuery=None,
OperationTimeout=None, ContinueOnError=None,
MaxObjectCount=None, **extra):
# pylint: disable=invalid-name
"""
Open an enumeration session to retrieve the instance paths of the
instances associated to a source instance.
*New in pywbem 0.9.*
This method does not support retrieving classes.
This method performs the OpenAssociatorInstancePaths operation
(see :term:`DSP0200`). See :ref:`WBEM operations` for a list of all
methods performing such operations.
If the operation succeeds, this method returns enumeration session
status and optionally instance paths.
Otherwise, this method raises an exception.
Use the :meth:`~pywbem.WBEMConnection.PullInstancePaths` method to
retrieve the next set of instance paths or the
:meth:`~pywbem.WBEMConnection.CloseEnumeration` method to close the
enumeration session before it is exhausted.
Parameters:
InstanceName (:class:`~pywbem.CIMInstanceName`):
The instance path of the source instance.
If this object does not specify a namespace, the default namespace
of the connection is used.
Its `host` attribute will be ignored.
AssocClass (:term:`string` or :class:`~pywbem.CIMClassName`):
Class name of an association class (case independent),
to filter the result to include only traversals of that association
class (or subclasses).
`None` means that no such filtering is peformed.
ResultClass (:term:`string` or :class:`~pywbem.CIMClassName`):
Class name of an associated class (case independent),
to filter the result to include only traversals to that associated
class (or subclasses).
`None` means that no such filtering is peformed.
Role (:term:`string`):
Role name (= property name) of the source end (case independent),
to filter the result to include only traversals from that source
role.
`None` means that no such filtering is peformed.
ResultRole (:term:`string`):
Role name (= property name) of the far end (case independent),
to filter the result to include only traversals to that far
role.
`None` means that no such filtering is peformed.
FilterQueryLanguage (:term:`string`):
The name of the filter query language used for the `FilterQuery`
parameter. The DMTF-defined Filter Query Language (see
:term:`DSP0212`) is specified as "DMTF:FQL".
Not all WBEM servers support filtering for this operation because
it returns instance paths and the act of the server filtering
requires that it generate instances just for that purpose and then
discard them.
FilterQuery (:term:`string`):
The filter query in the query language defined by the
`FilterQueryLanguage` parameter.
OperationTimeout (:class:`~pywbem.Uint32`):
Minimum time in seconds the WBEM Server shall maintain an open
enumeration session after a previous Open or Pull request is
sent to the client. Once this timeout time has expired, the
WBEM server may close the enumeration session.
* If not `None`, this parameter is sent to the WBEM server as the
proposed timeout for the enumeration session. A value of 0
indicates that the server is expected to never time out. The
server may reject the proposed value, causing a
:class:`~pywbem.CIMError` to be raised with status code
:attr:`~pywbem.CIM_ERR_INVALID_OPERATION_TIMEOUT`.
* If `None`, this parameter is not passed to the WBEM server, and
causes the server-implemented default timeout to be used.
ContinueOnError (:class:`py:bool`):
Indicates to the WBEM server to continue sending responses
after an error response has been sent.
* If `True`, the server is to continue sending responses after
sending an error response. Not all servers support continuation
on error; a server that does not support it must send an error
response if `True` was specified, causing
:class:`~pywbem.CIMError` to be raised with status code
:attr:`~pywbem.CIM_ERR_CONTINUATION_ON_ERROR_NOT_SUPPORTED`.
* If `False`, the server is requested to close the enumeration after
sending an error response.
* If `None`, this parameter is not passed to the WBEM server, and
causes the server-implemented default behaviour to be used.
:term:`DSP0200` defines that the server-implemented default is
`False`.
MaxObjectCount (:class:`~pywbem.Uint32`)
Maximum number of instances the WBEM server may return
for this request.
* If positive, the WBEM server is to return no more than the
specified number of instances.
* If zero, the WBEM server is to return no instances. This may
be used by a client to leave the handling of any returned
instances to a loop of Pull operations.
* If `None`, this parameter is not passed to the WBEM server, and
causes the server-implemented default behaviour to be used.
:term:`DSP0200` defines that the server-implemented default is
to return zero instances.
**extra :
Additional keyword arguments are passed as additional operation
parameters to the WBEM server.
Note that :term:`DSP0200` does not define any additional parameters
for this operation.
Returns:
A :func:`~py:collections.namedtuple` object containing the following
named items:
* **paths** (:class:`py:list` of :class:`~pywbem.CIMInstanceName`):
Representations of the retrieved instance paths, with their
attributes set as follows:
* `classname`: Name of the creation class of the instance.
* `keybindings`: Keybindings of the instance.
* `namespace`: Name of the CIM namespace containing the instance.
* `host`: Host and optionally port of the WBEM server containing
the CIM namespace.
* **eos** (:class:`py:bool`):
Indicates whether the enumeration session is exhausted after
this operation:
- If `True`, the enumeration session is exhausted, and the
server has closed the enumeration session.
- If `False`, the enumeration session is not exhausted and the
`context` item is the context object for the next operation on
the enumeration session.
* **context** (:func:`py:tuple` of server_context, namespace):
A context object identifying the open enumeration session,
including its current enumeration state, and the namespace. This
object must be supplied with the next pull or close operation for
this enumeration session.
The tuple items are:
* server_context (:term:`string`):
Enumeration context string returned by the server if
the session is not exhausted, or `None` otherwise. This string
is opaque for the client.
* namespace (:term:`string`):
Name of the CIM namespace that was used for this operation.
NOTE: This inner tuple hides the need for a CIM namespace
on subsequent operations in the enumeration session. CIM
operations always require target namespace, but it never
makes sense to specify a different one in subsequent
operations on the same enumeration session.
Raises:
Exceptions described in :class:`~pywbem.WBEMConnection`.
"""
exc = None
result_tuple = None
method_name = 'OpenAssociatorInstancePaths'
if self._operation_recorders:
self.operation_recorder_reset(pull_op=True)
self.operation_recorder_stage_pywbem_args(
method=method_name,
InstanceName=InstanceName,
AssocClass=AssocClass,
ResultClass=ResultClass,
Role=Role,
ResultRole=ResultRole,
FilterQueryLanguage=FilterQueryLanguage,
FilterQuery=FilterQuery,
OperationTimeout=OperationTimeout,
ContinueOnError=ContinueOnError,
MaxObjectCount=MaxObjectCount,
**extra)
try:
stats = self.statistics.start_timer(method_name)
namespace = self._iparam_namespace_from_objectname(
InstanceName, 'InstanceName')
instancename = self._iparam_instancename(InstanceName)
result = self._imethodcall(
method_name,
namespace,
InstanceName=instancename,
AssocClass=self._iparam_classname(AssocClass, 'AssocClass'),
ResultClass=self._iparam_classname(ResultClass, 'ResultClass'),
Role=Role,
ResultRole=ResultRole,
FilterQueryLanguage=FilterQueryLanguage,
FilterQuery=FilterQuery,
OperationTimeout=OperationTimeout,
ContinueOnError=ContinueOnError,
MaxObjectCount=MaxObjectCount,
has_out_params=True,
**extra)
result_tuple = pull_path_result_tuple(
*self._get_rslt_params(result, namespace))
return result_tuple
except (CIMXMLParseError, XMLParseError) as exce:
exce.request_data = self.last_raw_request
exce.response_data = self.last_raw_reply
exc = exce
raise
except Exception as exce:
exc = exce
raise
finally:
self._last_operation_time = stats.stop_timer(
self.last_request_len, self.last_reply_len,
self.last_server_response_time, exc)
if self._operation_recorders:
self.operation_recorder_stage_result(result_tuple, exc) | python | def OpenAssociatorInstancePaths(self, InstanceName, AssocClass=None,
ResultClass=None, Role=None,
ResultRole=None,
FilterQueryLanguage=None, FilterQuery=None,
OperationTimeout=None, ContinueOnError=None,
MaxObjectCount=None, **extra):
# pylint: disable=invalid-name
"""
Open an enumeration session to retrieve the instance paths of the
instances associated to a source instance.
*New in pywbem 0.9.*
This method does not support retrieving classes.
This method performs the OpenAssociatorInstancePaths operation
(see :term:`DSP0200`). See :ref:`WBEM operations` for a list of all
methods performing such operations.
If the operation succeeds, this method returns enumeration session
status and optionally instance paths.
Otherwise, this method raises an exception.
Use the :meth:`~pywbem.WBEMConnection.PullInstancePaths` method to
retrieve the next set of instance paths or the
:meth:`~pywbem.WBEMConnection.CloseEnumeration` method to close the
enumeration session before it is exhausted.
Parameters:
InstanceName (:class:`~pywbem.CIMInstanceName`):
The instance path of the source instance.
If this object does not specify a namespace, the default namespace
of the connection is used.
Its `host` attribute will be ignored.
AssocClass (:term:`string` or :class:`~pywbem.CIMClassName`):
Class name of an association class (case independent),
to filter the result to include only traversals of that association
class (or subclasses).
`None` means that no such filtering is peformed.
ResultClass (:term:`string` or :class:`~pywbem.CIMClassName`):
Class name of an associated class (case independent),
to filter the result to include only traversals to that associated
class (or subclasses).
`None` means that no such filtering is peformed.
Role (:term:`string`):
Role name (= property name) of the source end (case independent),
to filter the result to include only traversals from that source
role.
`None` means that no such filtering is peformed.
ResultRole (:term:`string`):
Role name (= property name) of the far end (case independent),
to filter the result to include only traversals to that far
role.
`None` means that no such filtering is peformed.
FilterQueryLanguage (:term:`string`):
The name of the filter query language used for the `FilterQuery`
parameter. The DMTF-defined Filter Query Language (see
:term:`DSP0212`) is specified as "DMTF:FQL".
Not all WBEM servers support filtering for this operation because
it returns instance paths and the act of the server filtering
requires that it generate instances just for that purpose and then
discard them.
FilterQuery (:term:`string`):
The filter query in the query language defined by the
`FilterQueryLanguage` parameter.
OperationTimeout (:class:`~pywbem.Uint32`):
Minimum time in seconds the WBEM Server shall maintain an open
enumeration session after a previous Open or Pull request is
sent to the client. Once this timeout time has expired, the
WBEM server may close the enumeration session.
* If not `None`, this parameter is sent to the WBEM server as the
proposed timeout for the enumeration session. A value of 0
indicates that the server is expected to never time out. The
server may reject the proposed value, causing a
:class:`~pywbem.CIMError` to be raised with status code
:attr:`~pywbem.CIM_ERR_INVALID_OPERATION_TIMEOUT`.
* If `None`, this parameter is not passed to the WBEM server, and
causes the server-implemented default timeout to be used.
ContinueOnError (:class:`py:bool`):
Indicates to the WBEM server to continue sending responses
after an error response has been sent.
* If `True`, the server is to continue sending responses after
sending an error response. Not all servers support continuation
on error; a server that does not support it must send an error
response if `True` was specified, causing
:class:`~pywbem.CIMError` to be raised with status code
:attr:`~pywbem.CIM_ERR_CONTINUATION_ON_ERROR_NOT_SUPPORTED`.
* If `False`, the server is requested to close the enumeration after
sending an error response.
* If `None`, this parameter is not passed to the WBEM server, and
causes the server-implemented default behaviour to be used.
:term:`DSP0200` defines that the server-implemented default is
`False`.
MaxObjectCount (:class:`~pywbem.Uint32`)
Maximum number of instances the WBEM server may return
for this request.
* If positive, the WBEM server is to return no more than the
specified number of instances.
* If zero, the WBEM server is to return no instances. This may
be used by a client to leave the handling of any returned
instances to a loop of Pull operations.
* If `None`, this parameter is not passed to the WBEM server, and
causes the server-implemented default behaviour to be used.
:term:`DSP0200` defines that the server-implemented default is
to return zero instances.
**extra :
Additional keyword arguments are passed as additional operation
parameters to the WBEM server.
Note that :term:`DSP0200` does not define any additional parameters
for this operation.
Returns:
A :func:`~py:collections.namedtuple` object containing the following
named items:
* **paths** (:class:`py:list` of :class:`~pywbem.CIMInstanceName`):
Representations of the retrieved instance paths, with their
attributes set as follows:
* `classname`: Name of the creation class of the instance.
* `keybindings`: Keybindings of the instance.
* `namespace`: Name of the CIM namespace containing the instance.
* `host`: Host and optionally port of the WBEM server containing
the CIM namespace.
* **eos** (:class:`py:bool`):
Indicates whether the enumeration session is exhausted after
this operation:
- If `True`, the enumeration session is exhausted, and the
server has closed the enumeration session.
- If `False`, the enumeration session is not exhausted and the
`context` item is the context object for the next operation on
the enumeration session.
* **context** (:func:`py:tuple` of server_context, namespace):
A context object identifying the open enumeration session,
including its current enumeration state, and the namespace. This
object must be supplied with the next pull or close operation for
this enumeration session.
The tuple items are:
* server_context (:term:`string`):
Enumeration context string returned by the server if
the session is not exhausted, or `None` otherwise. This string
is opaque for the client.
* namespace (:term:`string`):
Name of the CIM namespace that was used for this operation.
NOTE: This inner tuple hides the need for a CIM namespace
on subsequent operations in the enumeration session. CIM
operations always require target namespace, but it never
makes sense to specify a different one in subsequent
operations on the same enumeration session.
Raises:
Exceptions described in :class:`~pywbem.WBEMConnection`.
"""
exc = None
result_tuple = None
method_name = 'OpenAssociatorInstancePaths'
if self._operation_recorders:
self.operation_recorder_reset(pull_op=True)
self.operation_recorder_stage_pywbem_args(
method=method_name,
InstanceName=InstanceName,
AssocClass=AssocClass,
ResultClass=ResultClass,
Role=Role,
ResultRole=ResultRole,
FilterQueryLanguage=FilterQueryLanguage,
FilterQuery=FilterQuery,
OperationTimeout=OperationTimeout,
ContinueOnError=ContinueOnError,
MaxObjectCount=MaxObjectCount,
**extra)
try:
stats = self.statistics.start_timer(method_name)
namespace = self._iparam_namespace_from_objectname(
InstanceName, 'InstanceName')
instancename = self._iparam_instancename(InstanceName)
result = self._imethodcall(
method_name,
namespace,
InstanceName=instancename,
AssocClass=self._iparam_classname(AssocClass, 'AssocClass'),
ResultClass=self._iparam_classname(ResultClass, 'ResultClass'),
Role=Role,
ResultRole=ResultRole,
FilterQueryLanguage=FilterQueryLanguage,
FilterQuery=FilterQuery,
OperationTimeout=OperationTimeout,
ContinueOnError=ContinueOnError,
MaxObjectCount=MaxObjectCount,
has_out_params=True,
**extra)
result_tuple = pull_path_result_tuple(
*self._get_rslt_params(result, namespace))
return result_tuple
except (CIMXMLParseError, XMLParseError) as exce:
exce.request_data = self.last_raw_request
exce.response_data = self.last_raw_reply
exc = exce
raise
except Exception as exce:
exc = exce
raise
finally:
self._last_operation_time = stats.stop_timer(
self.last_request_len, self.last_reply_len,
self.last_server_response_time, exc)
if self._operation_recorders:
self.operation_recorder_stage_result(result_tuple, exc) | [
"def",
"OpenAssociatorInstancePaths",
"(",
"self",
",",
"InstanceName",
",",
"AssocClass",
"=",
"None",
",",
"ResultClass",
"=",
"None",
",",
"Role",
"=",
"None",
",",
"ResultRole",
"=",
"None",
",",
"FilterQueryLanguage",
"=",
"None",
",",
"FilterQuery",
"=",... | Open an enumeration session to retrieve the instance paths of the
instances associated to a source instance.
*New in pywbem 0.9.*
This method does not support retrieving classes.
This method performs the OpenAssociatorInstancePaths operation
(see :term:`DSP0200`). See :ref:`WBEM operations` for a list of all
methods performing such operations.
If the operation succeeds, this method returns enumeration session
status and optionally instance paths.
Otherwise, this method raises an exception.
Use the :meth:`~pywbem.WBEMConnection.PullInstancePaths` method to
retrieve the next set of instance paths or the
:meth:`~pywbem.WBEMConnection.CloseEnumeration` method to close the
enumeration session before it is exhausted.
Parameters:
InstanceName (:class:`~pywbem.CIMInstanceName`):
The instance path of the source instance.
If this object does not specify a namespace, the default namespace
of the connection is used.
Its `host` attribute will be ignored.
AssocClass (:term:`string` or :class:`~pywbem.CIMClassName`):
Class name of an association class (case independent),
to filter the result to include only traversals of that association
class (or subclasses).
`None` means that no such filtering is peformed.
ResultClass (:term:`string` or :class:`~pywbem.CIMClassName`):
Class name of an associated class (case independent),
to filter the result to include only traversals to that associated
class (or subclasses).
`None` means that no such filtering is peformed.
Role (:term:`string`):
Role name (= property name) of the source end (case independent),
to filter the result to include only traversals from that source
role.
`None` means that no such filtering is peformed.
ResultRole (:term:`string`):
Role name (= property name) of the far end (case independent),
to filter the result to include only traversals to that far
role.
`None` means that no such filtering is peformed.
FilterQueryLanguage (:term:`string`):
The name of the filter query language used for the `FilterQuery`
parameter. The DMTF-defined Filter Query Language (see
:term:`DSP0212`) is specified as "DMTF:FQL".
Not all WBEM servers support filtering for this operation because
it returns instance paths and the act of the server filtering
requires that it generate instances just for that purpose and then
discard them.
FilterQuery (:term:`string`):
The filter query in the query language defined by the
`FilterQueryLanguage` parameter.
OperationTimeout (:class:`~pywbem.Uint32`):
Minimum time in seconds the WBEM Server shall maintain an open
enumeration session after a previous Open or Pull request is
sent to the client. Once this timeout time has expired, the
WBEM server may close the enumeration session.
* If not `None`, this parameter is sent to the WBEM server as the
proposed timeout for the enumeration session. A value of 0
indicates that the server is expected to never time out. The
server may reject the proposed value, causing a
:class:`~pywbem.CIMError` to be raised with status code
:attr:`~pywbem.CIM_ERR_INVALID_OPERATION_TIMEOUT`.
* If `None`, this parameter is not passed to the WBEM server, and
causes the server-implemented default timeout to be used.
ContinueOnError (:class:`py:bool`):
Indicates to the WBEM server to continue sending responses
after an error response has been sent.
* If `True`, the server is to continue sending responses after
sending an error response. Not all servers support continuation
on error; a server that does not support it must send an error
response if `True` was specified, causing
:class:`~pywbem.CIMError` to be raised with status code
:attr:`~pywbem.CIM_ERR_CONTINUATION_ON_ERROR_NOT_SUPPORTED`.
* If `False`, the server is requested to close the enumeration after
sending an error response.
* If `None`, this parameter is not passed to the WBEM server, and
causes the server-implemented default behaviour to be used.
:term:`DSP0200` defines that the server-implemented default is
`False`.
MaxObjectCount (:class:`~pywbem.Uint32`)
Maximum number of instances the WBEM server may return
for this request.
* If positive, the WBEM server is to return no more than the
specified number of instances.
* If zero, the WBEM server is to return no instances. This may
be used by a client to leave the handling of any returned
instances to a loop of Pull operations.
* If `None`, this parameter is not passed to the WBEM server, and
causes the server-implemented default behaviour to be used.
:term:`DSP0200` defines that the server-implemented default is
to return zero instances.
**extra :
Additional keyword arguments are passed as additional operation
parameters to the WBEM server.
Note that :term:`DSP0200` does not define any additional parameters
for this operation.
Returns:
A :func:`~py:collections.namedtuple` object containing the following
named items:
* **paths** (:class:`py:list` of :class:`~pywbem.CIMInstanceName`):
Representations of the retrieved instance paths, with their
attributes set as follows:
* `classname`: Name of the creation class of the instance.
* `keybindings`: Keybindings of the instance.
* `namespace`: Name of the CIM namespace containing the instance.
* `host`: Host and optionally port of the WBEM server containing
the CIM namespace.
* **eos** (:class:`py:bool`):
Indicates whether the enumeration session is exhausted after
this operation:
- If `True`, the enumeration session is exhausted, and the
server has closed the enumeration session.
- If `False`, the enumeration session is not exhausted and the
`context` item is the context object for the next operation on
the enumeration session.
* **context** (:func:`py:tuple` of server_context, namespace):
A context object identifying the open enumeration session,
including its current enumeration state, and the namespace. This
object must be supplied with the next pull or close operation for
this enumeration session.
The tuple items are:
* server_context (:term:`string`):
Enumeration context string returned by the server if
the session is not exhausted, or `None` otherwise. This string
is opaque for the client.
* namespace (:term:`string`):
Name of the CIM namespace that was used for this operation.
NOTE: This inner tuple hides the need for a CIM namespace
on subsequent operations in the enumeration session. CIM
operations always require target namespace, but it never
makes sense to specify a different one in subsequent
operations on the same enumeration session.
Raises:
Exceptions described in :class:`~pywbem.WBEMConnection`. | [
"Open",
"an",
"enumeration",
"session",
"to",
"retrieve",
"the",
"instance",
"paths",
"of",
"the",
"instances",
"associated",
"to",
"a",
"source",
"instance",
"."
] | e54ecb82c2211e289a268567443d60fdd489f1e4 | https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/cim_operations.py#L7142-L7384 | train | 28,409 |
pywbem/pywbem | pywbem/cim_operations.py | WBEMConnection.OpenQueryInstances | def OpenQueryInstances(self, FilterQueryLanguage, FilterQuery,
namespace=None, ReturnQueryResultClass=None,
OperationTimeout=None, ContinueOnError=None,
MaxObjectCount=None, **extra):
# pylint: disable=invalid-name
"""
Open an enumeration session to execute a query in a namespace and to
retrieve the instances representing the query result.
*New in pywbem 0.9.*
This method performs the OpenQueryInstances operation
(see :term:`DSP0200`). See :ref:`WBEM operations` for a list of all
methods performing such operations.
If the operation succeeds, this method returns enumeration session
status and optionally CIM instances representing the query result.
Otherwise, this method raises an exception.
Use the :meth:`~pywbem.WBEMConnection.PullInstances` method to
retrieve the next set of instances or the
:meth:`~pywbem.WBEMConnection.CloseEnumeration` method to close the
enumeration session before it is exhausted.
Parameters:
FilterQueryLanguage (:term:`string`):
Name of the query language used in the `FilterQuery` parameter,
e.g. "DMTF:CQL" for CIM Query Language, and "WQL" for WBEM Query
Language. Because this is not a filter query, "DMTF:FQL" is not a
valid query language for this request.
FilterQuery (:term:`string`):
Query string in the query language specified in the
`FilterQueryLanguage` parameter.
namespace (:term:`string`):
Name of the CIM namespace to be used (case independent).
Leading and trailing slash characters will be stripped. The lexical
case will be preserved.
If `None`, the default namespace of the connection object will be
used.
ReturnQueryResultClass (:class:`py:bool`):
Controls whether a class definition describing the returned
instances will be returned.
`None` will cause the server to use its default of `False`.
OperationTimeout (:class:`~pywbem.Uint32`):
Minimum time in seconds the WBEM Server shall maintain an open
enumeration session after a previous Open or Pull request is
sent to the client. Once this timeout time has expired, the
WBEM server may close the enumeration session.
* If not `None`, this parameter is sent to the WBEM server as the
proposed timeout for the enumeration session. A value of 0
indicates that the server is expected to never time out. The
server may reject the proposed value, causing a
:class:`~pywbem.CIMError` to be raised with status code
:attr:`~pywbem.CIM_ERR_INVALID_OPERATION_TIMEOUT`.
* If `None`, this parameter is not passed to the WBEM server, and
causes the server-implemented default timeout to be used.
ContinueOnError (:class:`py:bool`):
Indicates to the WBEM server to continue sending responses
after an error response has been sent.
* If `True`, the server is to continue sending responses after
sending an error response. Not all servers support continuation
on error; a server that does not support it must send an error
response if `True` was specified, causing
:class:`~pywbem.CIMError` to be raised with status code
:attr:`~pywbem.CIM_ERR_CONTINUATION_ON_ERROR_NOT_SUPPORTED`.
* If `False`, the server is requested to close the enumeration after
sending an error response.
* If `None`, this parameter is not passed to the WBEM server, and
causes the server-implemented default behaviour to be used.
:term:`DSP0200` defines that the server-implemented default is
`False`.
MaxObjectCount (:class:`~pywbem.Uint32`)
Maximum number of instances the WBEM server may return
for this request.
* If positive, the WBEM server is to return no more than the
specified number of instances.
* If zero, the WBEM server is to return no instances. This may
be used by a client to leave the handling of any returned
instances to a loop of Pull operations.
* If `None`, this parameter is not passed to the WBEM server, and
causes the server-implemented default behaviour to be used.
:term:`DSP0200` defines that the server-implemented default is
to return zero instances.
**extra :
Additional keyword arguments are passed as additional operation
parameters to the WBEM server.
Note that :term:`DSP0200` does not define any additional parameters
for this operation.
Returns:
A :func:`~py:collections.namedtuple` object containing the following
named items:
* **instances** (:class:`py:list` of :class:`~pywbem.CIMInstance`):
Representations of the retrieved instances.
The `path` attribute of each :class:`~pywbem.CIMInstance`
object is `None`, because query results are not addressable
CIM instances.
* **eos** (:class:`py:bool`):
Indicates whether the enumeration session is exhausted after
this operation:
- If `True`, the enumeration session is exhausted, and the
server has closed the enumeration session.
- If `False`, the enumeration session is not exhausted and the
`context` item is the context object for the next operation on
the enumeration session.
* **context** (:func:`py:tuple` of server_context, namespace):
A context object identifying the open enumeration session,
including its current enumeration state, and the namespace. This
object must be supplied with the next pull or close operation for
this enumeration session.
The tuple items are:
* server_context (:term:`string`):
Enumeration context string returned by the server if
the session is not exhausted, or `None` otherwise. This string
is opaque for the client.
* namespace (:term:`string`):
Name of the CIM namespace that was used for this operation.
NOTE: The inner tuple hides the need for a CIM namespace
on subsequent operations in the enumeration session. CIM
operations always require target namespace, but it never
makes sense to specify a different one in subsequent
operations on the same enumeration session.
* **query_result_class** (:class:`~pywbem.CIMClass`):
If the `ReturnQueryResultClass` parameter is True, this tuple
item contains a class definition that defines the properties
of each row (instance) of the query result. Otherwise, `None`.
Raises:
Exceptions described in :class:`~pywbem.WBEMConnection`.
"""
@staticmethod
def _GetQueryRsltClass(result):
""" Get the QueryResultClass and return it or generate
exception.
"""
for p in result:
if p[0] == 'QueryResultClass':
class_obj = p[2]
if not isinstance(class_obj, CIMClass):
raise CIMXMLParseError(
_format("Expecting CIMClass object in "
"QueryResultClass output parameter, got "
"{0} object", class_obj.__class__.__name__),
conn_id=self.conn_id)
return class_obj
raise CIMXMLParseError(
"QueryResultClass output parameter is missing",
conn_id=self.conn_id)
exc = None
result_tuple = None
method_name = 'OpenQueryInstances'
if self._operation_recorders:
self.operation_recorder_reset(pull_op=True)
self.operation_recorder_stage_pywbem_args(
method=method_name,
FilterQueryLanguage=FilterQueryLanguage,
FilterQuery=FilterQuery,
namespace=namespace,
ReturnQueryResultClass=ReturnQueryResultClass,
OperationTimeout=OperationTimeout,
ContinueOnError=ContinueOnError,
MaxObjectCount=MaxObjectCount,
**extra)
try:
stats = self.statistics.start_timer(method_name)
namespace = self._iparam_namespace_from_namespace(namespace)
result = self._imethodcall(
method_name,
namespace,
FilterQuery=FilterQuery,
FilterQueryLanguage=FilterQueryLanguage,
ReturnQueryResultClass=ReturnQueryResultClass,
OperationTimeout=OperationTimeout,
ContinueOnError=ContinueOnError,
MaxObjectCount=MaxObjectCount,
has_out_params=True,
**extra)
insts, eos, enum_ctxt = self._get_rslt_params(result, namespace)
query_result_class = _GetQueryRsltClass(result) if \
ReturnQueryResultClass else None
result_tuple = pull_query_result_tuple(insts, eos, enum_ctxt,
query_result_class)
return result_tuple
except (CIMXMLParseError, XMLParseError) as exce:
exce.request_data = self.last_raw_request
exce.response_data = self.last_raw_reply
exc = exce
raise
except Exception as exce:
exc = exce
raise
finally:
self._last_operation_time = stats.stop_timer(
self.last_request_len, self.last_reply_len,
self.last_server_response_time, exc)
if self._operation_recorders:
self.operation_recorder_stage_result(result_tuple, exc) | python | def OpenQueryInstances(self, FilterQueryLanguage, FilterQuery,
namespace=None, ReturnQueryResultClass=None,
OperationTimeout=None, ContinueOnError=None,
MaxObjectCount=None, **extra):
# pylint: disable=invalid-name
"""
Open an enumeration session to execute a query in a namespace and to
retrieve the instances representing the query result.
*New in pywbem 0.9.*
This method performs the OpenQueryInstances operation
(see :term:`DSP0200`). See :ref:`WBEM operations` for a list of all
methods performing such operations.
If the operation succeeds, this method returns enumeration session
status and optionally CIM instances representing the query result.
Otherwise, this method raises an exception.
Use the :meth:`~pywbem.WBEMConnection.PullInstances` method to
retrieve the next set of instances or the
:meth:`~pywbem.WBEMConnection.CloseEnumeration` method to close the
enumeration session before it is exhausted.
Parameters:
FilterQueryLanguage (:term:`string`):
Name of the query language used in the `FilterQuery` parameter,
e.g. "DMTF:CQL" for CIM Query Language, and "WQL" for WBEM Query
Language. Because this is not a filter query, "DMTF:FQL" is not a
valid query language for this request.
FilterQuery (:term:`string`):
Query string in the query language specified in the
`FilterQueryLanguage` parameter.
namespace (:term:`string`):
Name of the CIM namespace to be used (case independent).
Leading and trailing slash characters will be stripped. The lexical
case will be preserved.
If `None`, the default namespace of the connection object will be
used.
ReturnQueryResultClass (:class:`py:bool`):
Controls whether a class definition describing the returned
instances will be returned.
`None` will cause the server to use its default of `False`.
OperationTimeout (:class:`~pywbem.Uint32`):
Minimum time in seconds the WBEM Server shall maintain an open
enumeration session after a previous Open or Pull request is
sent to the client. Once this timeout time has expired, the
WBEM server may close the enumeration session.
* If not `None`, this parameter is sent to the WBEM server as the
proposed timeout for the enumeration session. A value of 0
indicates that the server is expected to never time out. The
server may reject the proposed value, causing a
:class:`~pywbem.CIMError` to be raised with status code
:attr:`~pywbem.CIM_ERR_INVALID_OPERATION_TIMEOUT`.
* If `None`, this parameter is not passed to the WBEM server, and
causes the server-implemented default timeout to be used.
ContinueOnError (:class:`py:bool`):
Indicates to the WBEM server to continue sending responses
after an error response has been sent.
* If `True`, the server is to continue sending responses after
sending an error response. Not all servers support continuation
on error; a server that does not support it must send an error
response if `True` was specified, causing
:class:`~pywbem.CIMError` to be raised with status code
:attr:`~pywbem.CIM_ERR_CONTINUATION_ON_ERROR_NOT_SUPPORTED`.
* If `False`, the server is requested to close the enumeration after
sending an error response.
* If `None`, this parameter is not passed to the WBEM server, and
causes the server-implemented default behaviour to be used.
:term:`DSP0200` defines that the server-implemented default is
`False`.
MaxObjectCount (:class:`~pywbem.Uint32`)
Maximum number of instances the WBEM server may return
for this request.
* If positive, the WBEM server is to return no more than the
specified number of instances.
* If zero, the WBEM server is to return no instances. This may
be used by a client to leave the handling of any returned
instances to a loop of Pull operations.
* If `None`, this parameter is not passed to the WBEM server, and
causes the server-implemented default behaviour to be used.
:term:`DSP0200` defines that the server-implemented default is
to return zero instances.
**extra :
Additional keyword arguments are passed as additional operation
parameters to the WBEM server.
Note that :term:`DSP0200` does not define any additional parameters
for this operation.
Returns:
A :func:`~py:collections.namedtuple` object containing the following
named items:
* **instances** (:class:`py:list` of :class:`~pywbem.CIMInstance`):
Representations of the retrieved instances.
The `path` attribute of each :class:`~pywbem.CIMInstance`
object is `None`, because query results are not addressable
CIM instances.
* **eos** (:class:`py:bool`):
Indicates whether the enumeration session is exhausted after
this operation:
- If `True`, the enumeration session is exhausted, and the
server has closed the enumeration session.
- If `False`, the enumeration session is not exhausted and the
`context` item is the context object for the next operation on
the enumeration session.
* **context** (:func:`py:tuple` of server_context, namespace):
A context object identifying the open enumeration session,
including its current enumeration state, and the namespace. This
object must be supplied with the next pull or close operation for
this enumeration session.
The tuple items are:
* server_context (:term:`string`):
Enumeration context string returned by the server if
the session is not exhausted, or `None` otherwise. This string
is opaque for the client.
* namespace (:term:`string`):
Name of the CIM namespace that was used for this operation.
NOTE: The inner tuple hides the need for a CIM namespace
on subsequent operations in the enumeration session. CIM
operations always require target namespace, but it never
makes sense to specify a different one in subsequent
operations on the same enumeration session.
* **query_result_class** (:class:`~pywbem.CIMClass`):
If the `ReturnQueryResultClass` parameter is True, this tuple
item contains a class definition that defines the properties
of each row (instance) of the query result. Otherwise, `None`.
Raises:
Exceptions described in :class:`~pywbem.WBEMConnection`.
"""
@staticmethod
def _GetQueryRsltClass(result):
""" Get the QueryResultClass and return it or generate
exception.
"""
for p in result:
if p[0] == 'QueryResultClass':
class_obj = p[2]
if not isinstance(class_obj, CIMClass):
raise CIMXMLParseError(
_format("Expecting CIMClass object in "
"QueryResultClass output parameter, got "
"{0} object", class_obj.__class__.__name__),
conn_id=self.conn_id)
return class_obj
raise CIMXMLParseError(
"QueryResultClass output parameter is missing",
conn_id=self.conn_id)
exc = None
result_tuple = None
method_name = 'OpenQueryInstances'
if self._operation_recorders:
self.operation_recorder_reset(pull_op=True)
self.operation_recorder_stage_pywbem_args(
method=method_name,
FilterQueryLanguage=FilterQueryLanguage,
FilterQuery=FilterQuery,
namespace=namespace,
ReturnQueryResultClass=ReturnQueryResultClass,
OperationTimeout=OperationTimeout,
ContinueOnError=ContinueOnError,
MaxObjectCount=MaxObjectCount,
**extra)
try:
stats = self.statistics.start_timer(method_name)
namespace = self._iparam_namespace_from_namespace(namespace)
result = self._imethodcall(
method_name,
namespace,
FilterQuery=FilterQuery,
FilterQueryLanguage=FilterQueryLanguage,
ReturnQueryResultClass=ReturnQueryResultClass,
OperationTimeout=OperationTimeout,
ContinueOnError=ContinueOnError,
MaxObjectCount=MaxObjectCount,
has_out_params=True,
**extra)
insts, eos, enum_ctxt = self._get_rslt_params(result, namespace)
query_result_class = _GetQueryRsltClass(result) if \
ReturnQueryResultClass else None
result_tuple = pull_query_result_tuple(insts, eos, enum_ctxt,
query_result_class)
return result_tuple
except (CIMXMLParseError, XMLParseError) as exce:
exce.request_data = self.last_raw_request
exce.response_data = self.last_raw_reply
exc = exce
raise
except Exception as exce:
exc = exce
raise
finally:
self._last_operation_time = stats.stop_timer(
self.last_request_len, self.last_reply_len,
self.last_server_response_time, exc)
if self._operation_recorders:
self.operation_recorder_stage_result(result_tuple, exc) | [
"def",
"OpenQueryInstances",
"(",
"self",
",",
"FilterQueryLanguage",
",",
"FilterQuery",
",",
"namespace",
"=",
"None",
",",
"ReturnQueryResultClass",
"=",
"None",
",",
"OperationTimeout",
"=",
"None",
",",
"ContinueOnError",
"=",
"None",
",",
"MaxObjectCount",
"... | Open an enumeration session to execute a query in a namespace and to
retrieve the instances representing the query result.
*New in pywbem 0.9.*
This method performs the OpenQueryInstances operation
(see :term:`DSP0200`). See :ref:`WBEM operations` for a list of all
methods performing such operations.
If the operation succeeds, this method returns enumeration session
status and optionally CIM instances representing the query result.
Otherwise, this method raises an exception.
Use the :meth:`~pywbem.WBEMConnection.PullInstances` method to
retrieve the next set of instances or the
:meth:`~pywbem.WBEMConnection.CloseEnumeration` method to close the
enumeration session before it is exhausted.
Parameters:
FilterQueryLanguage (:term:`string`):
Name of the query language used in the `FilterQuery` parameter,
e.g. "DMTF:CQL" for CIM Query Language, and "WQL" for WBEM Query
Language. Because this is not a filter query, "DMTF:FQL" is not a
valid query language for this request.
FilterQuery (:term:`string`):
Query string in the query language specified in the
`FilterQueryLanguage` parameter.
namespace (:term:`string`):
Name of the CIM namespace to be used (case independent).
Leading and trailing slash characters will be stripped. The lexical
case will be preserved.
If `None`, the default namespace of the connection object will be
used.
ReturnQueryResultClass (:class:`py:bool`):
Controls whether a class definition describing the returned
instances will be returned.
`None` will cause the server to use its default of `False`.
OperationTimeout (:class:`~pywbem.Uint32`):
Minimum time in seconds the WBEM Server shall maintain an open
enumeration session after a previous Open or Pull request is
sent to the client. Once this timeout time has expired, the
WBEM server may close the enumeration session.
* If not `None`, this parameter is sent to the WBEM server as the
proposed timeout for the enumeration session. A value of 0
indicates that the server is expected to never time out. The
server may reject the proposed value, causing a
:class:`~pywbem.CIMError` to be raised with status code
:attr:`~pywbem.CIM_ERR_INVALID_OPERATION_TIMEOUT`.
* If `None`, this parameter is not passed to the WBEM server, and
causes the server-implemented default timeout to be used.
ContinueOnError (:class:`py:bool`):
Indicates to the WBEM server to continue sending responses
after an error response has been sent.
* If `True`, the server is to continue sending responses after
sending an error response. Not all servers support continuation
on error; a server that does not support it must send an error
response if `True` was specified, causing
:class:`~pywbem.CIMError` to be raised with status code
:attr:`~pywbem.CIM_ERR_CONTINUATION_ON_ERROR_NOT_SUPPORTED`.
* If `False`, the server is requested to close the enumeration after
sending an error response.
* If `None`, this parameter is not passed to the WBEM server, and
causes the server-implemented default behaviour to be used.
:term:`DSP0200` defines that the server-implemented default is
`False`.
MaxObjectCount (:class:`~pywbem.Uint32`)
Maximum number of instances the WBEM server may return
for this request.
* If positive, the WBEM server is to return no more than the
specified number of instances.
* If zero, the WBEM server is to return no instances. This may
be used by a client to leave the handling of any returned
instances to a loop of Pull operations.
* If `None`, this parameter is not passed to the WBEM server, and
causes the server-implemented default behaviour to be used.
:term:`DSP0200` defines that the server-implemented default is
to return zero instances.
**extra :
Additional keyword arguments are passed as additional operation
parameters to the WBEM server.
Note that :term:`DSP0200` does not define any additional parameters
for this operation.
Returns:
A :func:`~py:collections.namedtuple` object containing the following
named items:
* **instances** (:class:`py:list` of :class:`~pywbem.CIMInstance`):
Representations of the retrieved instances.
The `path` attribute of each :class:`~pywbem.CIMInstance`
object is `None`, because query results are not addressable
CIM instances.
* **eos** (:class:`py:bool`):
Indicates whether the enumeration session is exhausted after
this operation:
- If `True`, the enumeration session is exhausted, and the
server has closed the enumeration session.
- If `False`, the enumeration session is not exhausted and the
`context` item is the context object for the next operation on
the enumeration session.
* **context** (:func:`py:tuple` of server_context, namespace):
A context object identifying the open enumeration session,
including its current enumeration state, and the namespace. This
object must be supplied with the next pull or close operation for
this enumeration session.
The tuple items are:
* server_context (:term:`string`):
Enumeration context string returned by the server if
the session is not exhausted, or `None` otherwise. This string
is opaque for the client.
* namespace (:term:`string`):
Name of the CIM namespace that was used for this operation.
NOTE: The inner tuple hides the need for a CIM namespace
on subsequent operations in the enumeration session. CIM
operations always require target namespace, but it never
makes sense to specify a different one in subsequent
operations on the same enumeration session.
* **query_result_class** (:class:`~pywbem.CIMClass`):
If the `ReturnQueryResultClass` parameter is True, this tuple
item contains a class definition that defines the properties
of each row (instance) of the query result. Otherwise, `None`.
Raises:
Exceptions described in :class:`~pywbem.WBEMConnection`. | [
"Open",
"an",
"enumeration",
"session",
"to",
"execute",
"a",
"query",
"in",
"a",
"namespace",
"and",
"to",
"retrieve",
"the",
"instances",
"representing",
"the",
"query",
"result",
"."
] | e54ecb82c2211e289a268567443d60fdd489f1e4 | https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/cim_operations.py#L7883-L8115 | train | 28,410 |
pywbem/pywbem | pywbem/cim_operations.py | WBEMConnection.EnumerateClasses | def EnumerateClasses(self, namespace=None, ClassName=None,
DeepInheritance=None, LocalOnly=None,
IncludeQualifiers=None, IncludeClassOrigin=None,
**extra):
# pylint: disable=invalid-name,line-too-long
"""
Enumerate the subclasses of a class, or the top-level classes in a
namespace.
This method performs the EnumerateClasses operation
(see :term:`DSP0200`). See :ref:`WBEM operations` for a list of all
methods performing such operations.
If the operation succeeds, this method returns.
Otherwise, this method raises an exception.
Parameters:
namespace (:term:`string`):
Name of the namespace in which the classes are to be enumerated
(case independent).
Leading and trailing slash characters will be stripped. The lexical
case will be preserved.
If `None`, the namespace of the `ClassName` parameter will be used,
if specified as a :class:`~pywbem.CIMClassName` object. If that is
also `None`, the default namespace of the connection will be used.
ClassName (:term:`string` or :class:`~pywbem.CIMClassName`):
Name of the class whose subclasses are to be retrieved
(case independent).
If specified as a :class:`~pywbem.CIMClassName` object, its host
attribute will be ignored.
If `None`, the top-level classes in the namespace will be
retrieved.
DeepInheritance (:class:`py:bool`):
Indicates that all (direct and indirect) subclasses of the
specified class or of the top-level classes are to be included in
the result, as follows:
* If `False`, only direct subclasses of the specified class or only
top-level classes are included in the result.
* If `True`, all direct and indirect subclasses of the specified
class or the top-level classes and all of their direct and
indirect subclasses are included in the result.
* If `None`, this parameter is not passed to the WBEM server, and
causes the server-implemented default to be used. :term:`DSP0200`
defines that the server-implemented default is `False`.
Note, the semantics of the `DeepInheritance` parameter in
:meth:`~pywbem.WBEMConnection.EnumerateInstances` is different.
LocalOnly (:class:`py:bool`):
Indicates that inherited properties, methods, and qualifiers are to
be excluded from the returned classes, as follows.
* If `False`, inherited elements are not excluded.
* If `True`, inherited elements are excluded.
* If `None`, this parameter is not passed to the WBEM server, and
causes the server-implemented default to be used. :term:`DSP0200`
defines that the server-implemented default is `True`.
IncludeQualifiers (:class:`py:bool`):
Indicates that qualifiers are to be included in the returned
classes, as follows:
* If `False`, qualifiers are not included.
* If `True`, qualifiers are included.
* If `None`, this parameter is not passed to the WBEM server, and
causes the server-implemented default to be used. :term:`DSP0200`
defines that the server-implemented default is `True`.
IncludeClassOrigin (:class:`py:bool`):
Indicates that class origin information is to be included on each
property and method in the returned classes, as follows:
* If `False`, class origin information is not included.
* If `True`, class origin information is included.
* If `None`, this parameter is not passed to the WBEM server, and
causes the server-implemented default to be used. :term:`DSP0200`
defines that the server-implemented default is `False`.
**extra :
Additional keyword arguments are passed as additional operation
parameters to the WBEM server.
Note that :term:`DSP0200` does not define any additional parameters
for this operation.
Returns:
A list of :class:`~pywbem.CIMClass` objects that are
representations of the enumerated classes, with their `path`
attributes set.
Raises:
Exceptions described in :class:`~pywbem.WBEMConnection`.
"""
exc = None
classes = None
method_name = 'EnumerateClasses'
if self._operation_recorders:
self.operation_recorder_reset()
self.operation_recorder_stage_pywbem_args(
method=method_name,
namespace=namespace,
ClassName=ClassName,
DeepInheritance=DeepInheritance,
LocalOnly=LocalOnly,
IncludeQualifiers=IncludeQualifiers,
IncludeClassOrigin=IncludeClassOrigin,
**extra)
try:
stats = self.statistics.start_timer(method_name)
if namespace is None and isinstance(ClassName, CIMClassName):
namespace = ClassName.namespace
namespace = self._iparam_namespace_from_namespace(namespace)
classname = self._iparam_classname(ClassName, 'ClassName')
result = self._imethodcall(
method_name,
namespace,
ClassName=classname,
DeepInheritance=DeepInheritance,
LocalOnly=LocalOnly,
IncludeQualifiers=IncludeQualifiers,
IncludeClassOrigin=IncludeClassOrigin,
**extra)
if result is None:
classes = []
else:
classes = result[0][2]
for klass in classes:
if not isinstance(klass, CIMClass):
raise CIMXMLParseError(
_format("Expecting CIMClass object in result list, "
"got {0} object", klass.__class__.__name__),
conn_id=self.conn_id)
# The EnumerateClasses CIM-XML operation returns classes
# as CLASS elements, which do not contain a class path.
# We want to return classes with a path (that has a namespace),
# so we create the class path and set its namespace to the
# effective target namespace.
klass.path = CIMClassName(
classname=klass.classname, host=self.host,
namespace=namespace)
return classes
except (CIMXMLParseError, XMLParseError) as exce:
exce.request_data = self.last_raw_request
exce.response_data = self.last_raw_reply
exc = exce
raise
except Exception as exce:
exc = exce
raise
finally:
self._last_operation_time = stats.stop_timer(
self.last_request_len, self.last_reply_len,
self.last_server_response_time, exc)
if self._operation_recorders:
self.operation_recorder_stage_result(classes, exc) | python | def EnumerateClasses(self, namespace=None, ClassName=None,
DeepInheritance=None, LocalOnly=None,
IncludeQualifiers=None, IncludeClassOrigin=None,
**extra):
# pylint: disable=invalid-name,line-too-long
"""
Enumerate the subclasses of a class, or the top-level classes in a
namespace.
This method performs the EnumerateClasses operation
(see :term:`DSP0200`). See :ref:`WBEM operations` for a list of all
methods performing such operations.
If the operation succeeds, this method returns.
Otherwise, this method raises an exception.
Parameters:
namespace (:term:`string`):
Name of the namespace in which the classes are to be enumerated
(case independent).
Leading and trailing slash characters will be stripped. The lexical
case will be preserved.
If `None`, the namespace of the `ClassName` parameter will be used,
if specified as a :class:`~pywbem.CIMClassName` object. If that is
also `None`, the default namespace of the connection will be used.
ClassName (:term:`string` or :class:`~pywbem.CIMClassName`):
Name of the class whose subclasses are to be retrieved
(case independent).
If specified as a :class:`~pywbem.CIMClassName` object, its host
attribute will be ignored.
If `None`, the top-level classes in the namespace will be
retrieved.
DeepInheritance (:class:`py:bool`):
Indicates that all (direct and indirect) subclasses of the
specified class or of the top-level classes are to be included in
the result, as follows:
* If `False`, only direct subclasses of the specified class or only
top-level classes are included in the result.
* If `True`, all direct and indirect subclasses of the specified
class or the top-level classes and all of their direct and
indirect subclasses are included in the result.
* If `None`, this parameter is not passed to the WBEM server, and
causes the server-implemented default to be used. :term:`DSP0200`
defines that the server-implemented default is `False`.
Note, the semantics of the `DeepInheritance` parameter in
:meth:`~pywbem.WBEMConnection.EnumerateInstances` is different.
LocalOnly (:class:`py:bool`):
Indicates that inherited properties, methods, and qualifiers are to
be excluded from the returned classes, as follows.
* If `False`, inherited elements are not excluded.
* If `True`, inherited elements are excluded.
* If `None`, this parameter is not passed to the WBEM server, and
causes the server-implemented default to be used. :term:`DSP0200`
defines that the server-implemented default is `True`.
IncludeQualifiers (:class:`py:bool`):
Indicates that qualifiers are to be included in the returned
classes, as follows:
* If `False`, qualifiers are not included.
* If `True`, qualifiers are included.
* If `None`, this parameter is not passed to the WBEM server, and
causes the server-implemented default to be used. :term:`DSP0200`
defines that the server-implemented default is `True`.
IncludeClassOrigin (:class:`py:bool`):
Indicates that class origin information is to be included on each
property and method in the returned classes, as follows:
* If `False`, class origin information is not included.
* If `True`, class origin information is included.
* If `None`, this parameter is not passed to the WBEM server, and
causes the server-implemented default to be used. :term:`DSP0200`
defines that the server-implemented default is `False`.
**extra :
Additional keyword arguments are passed as additional operation
parameters to the WBEM server.
Note that :term:`DSP0200` does not define any additional parameters
for this operation.
Returns:
A list of :class:`~pywbem.CIMClass` objects that are
representations of the enumerated classes, with their `path`
attributes set.
Raises:
Exceptions described in :class:`~pywbem.WBEMConnection`.
"""
exc = None
classes = None
method_name = 'EnumerateClasses'
if self._operation_recorders:
self.operation_recorder_reset()
self.operation_recorder_stage_pywbem_args(
method=method_name,
namespace=namespace,
ClassName=ClassName,
DeepInheritance=DeepInheritance,
LocalOnly=LocalOnly,
IncludeQualifiers=IncludeQualifiers,
IncludeClassOrigin=IncludeClassOrigin,
**extra)
try:
stats = self.statistics.start_timer(method_name)
if namespace is None and isinstance(ClassName, CIMClassName):
namespace = ClassName.namespace
namespace = self._iparam_namespace_from_namespace(namespace)
classname = self._iparam_classname(ClassName, 'ClassName')
result = self._imethodcall(
method_name,
namespace,
ClassName=classname,
DeepInheritance=DeepInheritance,
LocalOnly=LocalOnly,
IncludeQualifiers=IncludeQualifiers,
IncludeClassOrigin=IncludeClassOrigin,
**extra)
if result is None:
classes = []
else:
classes = result[0][2]
for klass in classes:
if not isinstance(klass, CIMClass):
raise CIMXMLParseError(
_format("Expecting CIMClass object in result list, "
"got {0} object", klass.__class__.__name__),
conn_id=self.conn_id)
# The EnumerateClasses CIM-XML operation returns classes
# as CLASS elements, which do not contain a class path.
# We want to return classes with a path (that has a namespace),
# so we create the class path and set its namespace to the
# effective target namespace.
klass.path = CIMClassName(
classname=klass.classname, host=self.host,
namespace=namespace)
return classes
except (CIMXMLParseError, XMLParseError) as exce:
exce.request_data = self.last_raw_request
exce.response_data = self.last_raw_reply
exc = exce
raise
except Exception as exce:
exc = exce
raise
finally:
self._last_operation_time = stats.stop_timer(
self.last_request_len, self.last_reply_len,
self.last_server_response_time, exc)
if self._operation_recorders:
self.operation_recorder_stage_result(classes, exc) | [
"def",
"EnumerateClasses",
"(",
"self",
",",
"namespace",
"=",
"None",
",",
"ClassName",
"=",
"None",
",",
"DeepInheritance",
"=",
"None",
",",
"LocalOnly",
"=",
"None",
",",
"IncludeQualifiers",
"=",
"None",
",",
"IncludeClassOrigin",
"=",
"None",
",",
"*",... | Enumerate the subclasses of a class, or the top-level classes in a
namespace.
This method performs the EnumerateClasses operation
(see :term:`DSP0200`). See :ref:`WBEM operations` for a list of all
methods performing such operations.
If the operation succeeds, this method returns.
Otherwise, this method raises an exception.
Parameters:
namespace (:term:`string`):
Name of the namespace in which the classes are to be enumerated
(case independent).
Leading and trailing slash characters will be stripped. The lexical
case will be preserved.
If `None`, the namespace of the `ClassName` parameter will be used,
if specified as a :class:`~pywbem.CIMClassName` object. If that is
also `None`, the default namespace of the connection will be used.
ClassName (:term:`string` or :class:`~pywbem.CIMClassName`):
Name of the class whose subclasses are to be retrieved
(case independent).
If specified as a :class:`~pywbem.CIMClassName` object, its host
attribute will be ignored.
If `None`, the top-level classes in the namespace will be
retrieved.
DeepInheritance (:class:`py:bool`):
Indicates that all (direct and indirect) subclasses of the
specified class or of the top-level classes are to be included in
the result, as follows:
* If `False`, only direct subclasses of the specified class or only
top-level classes are included in the result.
* If `True`, all direct and indirect subclasses of the specified
class or the top-level classes and all of their direct and
indirect subclasses are included in the result.
* If `None`, this parameter is not passed to the WBEM server, and
causes the server-implemented default to be used. :term:`DSP0200`
defines that the server-implemented default is `False`.
Note, the semantics of the `DeepInheritance` parameter in
:meth:`~pywbem.WBEMConnection.EnumerateInstances` is different.
LocalOnly (:class:`py:bool`):
Indicates that inherited properties, methods, and qualifiers are to
be excluded from the returned classes, as follows.
* If `False`, inherited elements are not excluded.
* If `True`, inherited elements are excluded.
* If `None`, this parameter is not passed to the WBEM server, and
causes the server-implemented default to be used. :term:`DSP0200`
defines that the server-implemented default is `True`.
IncludeQualifiers (:class:`py:bool`):
Indicates that qualifiers are to be included in the returned
classes, as follows:
* If `False`, qualifiers are not included.
* If `True`, qualifiers are included.
* If `None`, this parameter is not passed to the WBEM server, and
causes the server-implemented default to be used. :term:`DSP0200`
defines that the server-implemented default is `True`.
IncludeClassOrigin (:class:`py:bool`):
Indicates that class origin information is to be included on each
property and method in the returned classes, as follows:
* If `False`, class origin information is not included.
* If `True`, class origin information is included.
* If `None`, this parameter is not passed to the WBEM server, and
causes the server-implemented default to be used. :term:`DSP0200`
defines that the server-implemented default is `False`.
**extra :
Additional keyword arguments are passed as additional operation
parameters to the WBEM server.
Note that :term:`DSP0200` does not define any additional parameters
for this operation.
Returns:
A list of :class:`~pywbem.CIMClass` objects that are
representations of the enumerated classes, with their `path`
attributes set.
Raises:
Exceptions described in :class:`~pywbem.WBEMConnection`. | [
"Enumerate",
"the",
"subclasses",
"of",
"a",
"class",
"or",
"the",
"top",
"-",
"level",
"classes",
"in",
"a",
"namespace",
"."
] | e54ecb82c2211e289a268567443d60fdd489f1e4 | https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/cim_operations.py#L8662-L8835 | train | 28,411 |
pywbem/pywbem | pywbem/cim_operations.py | WBEMConnection.EnumerateClassNames | def EnumerateClassNames(self, namespace=None, ClassName=None,
DeepInheritance=None, **extra):
# pylint: disable=invalid-name,line-too-long
"""
Enumerate the names of subclasses of a class, or of the top-level
classes in a namespace.
This method performs the EnumerateClassNames operation
(see :term:`DSP0200`). See :ref:`WBEM operations` for a list of all
methods performing such operations.
If the operation succeeds, this method returns.
Otherwise, this method raises an exception.
Parameters:
namespace (:term:`string`):
Name of the namespace in which the class names are to be
enumerated (case independent).
Leading and trailing slash characters will be stripped. The lexical
case will be preserved.
If `None`, the namespace of the `ClassName` parameter will be used,
if specified as a :class:`~pywbem.CIMClassName` object. If that is
also `None`, the default namespace of the connection will be used.
ClassName (:term:`string` or :class:`~pywbem.CIMClassName`):
Name of the class whose subclasses are to be retrieved
(case independent).
If specified as a :class:`~pywbem.CIMClassName` object, its host
attribute will be ignored.
If `None`, the top-level classes in the namespace will be
retrieved.
DeepInheritance (:class:`py:bool`):
Indicates that all (direct and indirect) subclasses of the
specified class or of the top-level classes are to be included in
the result, as follows:
* If `False`, only direct subclasses of the specified class or only
top-level classes are included in the result.
* If `True`, all direct and indirect subclasses of the specified
class or the top-level classes and all of their direct and
indirect subclasses are included in the result.
* If `None`, this parameter is not passed to the WBEM server, and
causes the server-implemented default to be used. :term:`DSP0200`
defines that the server-implemented default is `False`.
Note, the semantics of the `DeepInheritance` parameter in
:meth:`~pywbem.WBEMConnection.EnumerateInstances` is different.
**extra :
Additional keyword arguments are passed as additional operation
parameters to the WBEM server.
Note that :term:`DSP0200` does not define any additional parameters
for this operation.
Returns:
A list of :term:`unicode string` objects that are the class names
of the enumerated classes.
Raises:
Exceptions described in :class:`~pywbem.WBEMConnection`.
"""
exc = None
classnames = None
method_name = 'EnumerateClassNames'
if self._operation_recorders:
self.operation_recorder_reset()
self.operation_recorder_stage_pywbem_args(
method=method_name,
namespace=namespace,
ClassName=ClassName,
DeepInheritance=DeepInheritance,
**extra)
try:
stats = self.statistics.start_timer(method_name)
if namespace is None and isinstance(ClassName, CIMClassName):
namespace = ClassName.namespace
namespace = self._iparam_namespace_from_namespace(namespace)
classname = self._iparam_classname(ClassName, 'ClassName')
result = self._imethodcall(
method_name,
namespace,
ClassName=classname,
DeepInheritance=DeepInheritance,
**extra)
if result is None:
classpaths = []
else:
classpaths = result[0][2]
classnames = []
for classpath in classpaths:
if not isinstance(classpath, CIMClassName):
raise CIMXMLParseError(
_format("Expecting CIMClassName object in result "
"list, got {0} object",
classpath.__class__.__name__),
conn_id=self.conn_id)
# The EnumerateClassNames CIM-XML operation returns class
# paths as CLASSNAME elements.
# We want to return class names as strings.
classnames.append(classpath.classname)
return classnames
except (CIMXMLParseError, XMLParseError) as exce:
exce.request_data = self.last_raw_request
exce.response_data = self.last_raw_reply
exc = exce
raise
except Exception as exce:
exc = exce
raise
finally:
self._last_operation_time = stats.stop_timer(
self.last_request_len, self.last_reply_len,
self.last_server_response_time, exc)
if self._operation_recorders:
self.operation_recorder_stage_result(classnames, exc) | python | def EnumerateClassNames(self, namespace=None, ClassName=None,
DeepInheritance=None, **extra):
# pylint: disable=invalid-name,line-too-long
"""
Enumerate the names of subclasses of a class, or of the top-level
classes in a namespace.
This method performs the EnumerateClassNames operation
(see :term:`DSP0200`). See :ref:`WBEM operations` for a list of all
methods performing such operations.
If the operation succeeds, this method returns.
Otherwise, this method raises an exception.
Parameters:
namespace (:term:`string`):
Name of the namespace in which the class names are to be
enumerated (case independent).
Leading and trailing slash characters will be stripped. The lexical
case will be preserved.
If `None`, the namespace of the `ClassName` parameter will be used,
if specified as a :class:`~pywbem.CIMClassName` object. If that is
also `None`, the default namespace of the connection will be used.
ClassName (:term:`string` or :class:`~pywbem.CIMClassName`):
Name of the class whose subclasses are to be retrieved
(case independent).
If specified as a :class:`~pywbem.CIMClassName` object, its host
attribute will be ignored.
If `None`, the top-level classes in the namespace will be
retrieved.
DeepInheritance (:class:`py:bool`):
Indicates that all (direct and indirect) subclasses of the
specified class or of the top-level classes are to be included in
the result, as follows:
* If `False`, only direct subclasses of the specified class or only
top-level classes are included in the result.
* If `True`, all direct and indirect subclasses of the specified
class or the top-level classes and all of their direct and
indirect subclasses are included in the result.
* If `None`, this parameter is not passed to the WBEM server, and
causes the server-implemented default to be used. :term:`DSP0200`
defines that the server-implemented default is `False`.
Note, the semantics of the `DeepInheritance` parameter in
:meth:`~pywbem.WBEMConnection.EnumerateInstances` is different.
**extra :
Additional keyword arguments are passed as additional operation
parameters to the WBEM server.
Note that :term:`DSP0200` does not define any additional parameters
for this operation.
Returns:
A list of :term:`unicode string` objects that are the class names
of the enumerated classes.
Raises:
Exceptions described in :class:`~pywbem.WBEMConnection`.
"""
exc = None
classnames = None
method_name = 'EnumerateClassNames'
if self._operation_recorders:
self.operation_recorder_reset()
self.operation_recorder_stage_pywbem_args(
method=method_name,
namespace=namespace,
ClassName=ClassName,
DeepInheritance=DeepInheritance,
**extra)
try:
stats = self.statistics.start_timer(method_name)
if namespace is None and isinstance(ClassName, CIMClassName):
namespace = ClassName.namespace
namespace = self._iparam_namespace_from_namespace(namespace)
classname = self._iparam_classname(ClassName, 'ClassName')
result = self._imethodcall(
method_name,
namespace,
ClassName=classname,
DeepInheritance=DeepInheritance,
**extra)
if result is None:
classpaths = []
else:
classpaths = result[0][2]
classnames = []
for classpath in classpaths:
if not isinstance(classpath, CIMClassName):
raise CIMXMLParseError(
_format("Expecting CIMClassName object in result "
"list, got {0} object",
classpath.__class__.__name__),
conn_id=self.conn_id)
# The EnumerateClassNames CIM-XML operation returns class
# paths as CLASSNAME elements.
# We want to return class names as strings.
classnames.append(classpath.classname)
return classnames
except (CIMXMLParseError, XMLParseError) as exce:
exce.request_data = self.last_raw_request
exce.response_data = self.last_raw_reply
exc = exce
raise
except Exception as exce:
exc = exce
raise
finally:
self._last_operation_time = stats.stop_timer(
self.last_request_len, self.last_reply_len,
self.last_server_response_time, exc)
if self._operation_recorders:
self.operation_recorder_stage_result(classnames, exc) | [
"def",
"EnumerateClassNames",
"(",
"self",
",",
"namespace",
"=",
"None",
",",
"ClassName",
"=",
"None",
",",
"DeepInheritance",
"=",
"None",
",",
"*",
"*",
"extra",
")",
":",
"# pylint: disable=invalid-name,line-too-long",
"exc",
"=",
"None",
"classnames",
"=",... | Enumerate the names of subclasses of a class, or of the top-level
classes in a namespace.
This method performs the EnumerateClassNames operation
(see :term:`DSP0200`). See :ref:`WBEM operations` for a list of all
methods performing such operations.
If the operation succeeds, this method returns.
Otherwise, this method raises an exception.
Parameters:
namespace (:term:`string`):
Name of the namespace in which the class names are to be
enumerated (case independent).
Leading and trailing slash characters will be stripped. The lexical
case will be preserved.
If `None`, the namespace of the `ClassName` parameter will be used,
if specified as a :class:`~pywbem.CIMClassName` object. If that is
also `None`, the default namespace of the connection will be used.
ClassName (:term:`string` or :class:`~pywbem.CIMClassName`):
Name of the class whose subclasses are to be retrieved
(case independent).
If specified as a :class:`~pywbem.CIMClassName` object, its host
attribute will be ignored.
If `None`, the top-level classes in the namespace will be
retrieved.
DeepInheritance (:class:`py:bool`):
Indicates that all (direct and indirect) subclasses of the
specified class or of the top-level classes are to be included in
the result, as follows:
* If `False`, only direct subclasses of the specified class or only
top-level classes are included in the result.
* If `True`, all direct and indirect subclasses of the specified
class or the top-level classes and all of their direct and
indirect subclasses are included in the result.
* If `None`, this parameter is not passed to the WBEM server, and
causes the server-implemented default to be used. :term:`DSP0200`
defines that the server-implemented default is `False`.
Note, the semantics of the `DeepInheritance` parameter in
:meth:`~pywbem.WBEMConnection.EnumerateInstances` is different.
**extra :
Additional keyword arguments are passed as additional operation
parameters to the WBEM server.
Note that :term:`DSP0200` does not define any additional parameters
for this operation.
Returns:
A list of :term:`unicode string` objects that are the class names
of the enumerated classes.
Raises:
Exceptions described in :class:`~pywbem.WBEMConnection`. | [
"Enumerate",
"the",
"names",
"of",
"subclasses",
"of",
"a",
"class",
"or",
"of",
"the",
"top",
"-",
"level",
"classes",
"in",
"a",
"namespace",
"."
] | e54ecb82c2211e289a268567443d60fdd489f1e4 | https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/cim_operations.py#L8837-L8969 | train | 28,412 |
pywbem/pywbem | pywbem/cim_operations.py | WBEMConnection.ModifyClass | def ModifyClass(self, ModifiedClass, namespace=None, **extra):
# pylint: disable=invalid-name
"""
Modify a class.
This method performs the ModifyClass operation
(see :term:`DSP0200`). See :ref:`WBEM operations` for a list of all
methods performing such operations.
If the operation succeeds, this method returns.
Otherwise, this method raises an exception.
Parameters:
ModifiedClass (:class:`~pywbem.CIMClass`):
A representation of the modified class.
The properties, methods and qualifiers defined in this object
specify what is to be modified.
Typically, this object has been retrieved by other operations, such
as :meth:`~pywbem.WBEMConnection.GetClass`.
namespace (:term:`string`):
Name of the namespace in which the class is to be modified
(case independent).
Leading and trailing slash characters will be stripped. The lexical
case will be preserved.
If `None`, the default namespace of the connection object will be
used.
**extra :
Additional keyword arguments are passed as additional operation
parameters to the WBEM server.
Note that :term:`DSP0200` does not define any additional parameters
for this operation.
Raises:
Exceptions described in :class:`~pywbem.WBEMConnection`.
"""
exc = None
method_name = 'ModifyClass'
if self._operation_recorders:
self.operation_recorder_reset()
self.operation_recorder_stage_pywbem_args(
method=method_name,
ModifiedClass=ModifiedClass,
namespace=namespace,
**extra)
try:
stats = self.statistics.start_timer(method_name)
namespace = self._iparam_namespace_from_namespace(namespace)
klass = ModifiedClass.copy()
klass.path = None
self._imethodcall(
method_name,
namespace,
ModifiedClass=klass,
has_return_value=False,
**extra)
return
except (CIMXMLParseError, XMLParseError) as exce:
exce.request_data = self.last_raw_request
exce.response_data = self.last_raw_reply
exc = exce
raise
except Exception as exce:
exc = exce
raise
finally:
self._last_operation_time = stats.stop_timer(
self.last_request_len, self.last_reply_len,
self.last_server_response_time, exc)
if self._operation_recorders:
self.operation_recorder_stage_result(None, exc) | python | def ModifyClass(self, ModifiedClass, namespace=None, **extra):
# pylint: disable=invalid-name
"""
Modify a class.
This method performs the ModifyClass operation
(see :term:`DSP0200`). See :ref:`WBEM operations` for a list of all
methods performing such operations.
If the operation succeeds, this method returns.
Otherwise, this method raises an exception.
Parameters:
ModifiedClass (:class:`~pywbem.CIMClass`):
A representation of the modified class.
The properties, methods and qualifiers defined in this object
specify what is to be modified.
Typically, this object has been retrieved by other operations, such
as :meth:`~pywbem.WBEMConnection.GetClass`.
namespace (:term:`string`):
Name of the namespace in which the class is to be modified
(case independent).
Leading and trailing slash characters will be stripped. The lexical
case will be preserved.
If `None`, the default namespace of the connection object will be
used.
**extra :
Additional keyword arguments are passed as additional operation
parameters to the WBEM server.
Note that :term:`DSP0200` does not define any additional parameters
for this operation.
Raises:
Exceptions described in :class:`~pywbem.WBEMConnection`.
"""
exc = None
method_name = 'ModifyClass'
if self._operation_recorders:
self.operation_recorder_reset()
self.operation_recorder_stage_pywbem_args(
method=method_name,
ModifiedClass=ModifiedClass,
namespace=namespace,
**extra)
try:
stats = self.statistics.start_timer(method_name)
namespace = self._iparam_namespace_from_namespace(namespace)
klass = ModifiedClass.copy()
klass.path = None
self._imethodcall(
method_name,
namespace,
ModifiedClass=klass,
has_return_value=False,
**extra)
return
except (CIMXMLParseError, XMLParseError) as exce:
exce.request_data = self.last_raw_request
exce.response_data = self.last_raw_reply
exc = exce
raise
except Exception as exce:
exc = exce
raise
finally:
self._last_operation_time = stats.stop_timer(
self.last_request_len, self.last_reply_len,
self.last_server_response_time, exc)
if self._operation_recorders:
self.operation_recorder_stage_result(None, exc) | [
"def",
"ModifyClass",
"(",
"self",
",",
"ModifiedClass",
",",
"namespace",
"=",
"None",
",",
"*",
"*",
"extra",
")",
":",
"# pylint: disable=invalid-name",
"exc",
"=",
"None",
"method_name",
"=",
"'ModifyClass'",
"if",
"self",
".",
"_operation_recorders",
":",
... | Modify a class.
This method performs the ModifyClass operation
(see :term:`DSP0200`). See :ref:`WBEM operations` for a list of all
methods performing such operations.
If the operation succeeds, this method returns.
Otherwise, this method raises an exception.
Parameters:
ModifiedClass (:class:`~pywbem.CIMClass`):
A representation of the modified class.
The properties, methods and qualifiers defined in this object
specify what is to be modified.
Typically, this object has been retrieved by other operations, such
as :meth:`~pywbem.WBEMConnection.GetClass`.
namespace (:term:`string`):
Name of the namespace in which the class is to be modified
(case independent).
Leading and trailing slash characters will be stripped. The lexical
case will be preserved.
If `None`, the default namespace of the connection object will be
used.
**extra :
Additional keyword arguments are passed as additional operation
parameters to the WBEM server.
Note that :term:`DSP0200` does not define any additional parameters
for this operation.
Raises:
Exceptions described in :class:`~pywbem.WBEMConnection`. | [
"Modify",
"a",
"class",
"."
] | e54ecb82c2211e289a268567443d60fdd489f1e4 | https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/cim_operations.py#L9136-L9220 | train | 28,413 |
pywbem/pywbem | pywbem/cim_operations.py | WBEMConnection.DeleteClass | def DeleteClass(self, ClassName, namespace=None, **extra):
# pylint: disable=invalid-name,line-too-long
"""
Delete a class.
This method performs the DeleteClass operation
(see :term:`DSP0200`). See :ref:`WBEM operations` for a list of all
methods performing such operations.
If the operation succeeds, this method returns.
Otherwise, this method raises an exception.
Parameters:
ClassName (:term:`string` or :class:`~pywbem.CIMClassName`):
Name of the class to be deleted (case independent).
If specified as a :class:`~pywbem.CIMClassName` object, its `host`
attribute will be ignored.
namespace (:term:`string`):
Name of the namespace of the class to be deleted
(case independent).
Leading and trailing slash characters will be stripped. The lexical
case will be preserved.
If `None`, the namespace of the `ClassName` parameter will be used,
if specified as a :class:`~pywbem.CIMClassName` object. If that is
also `None`, the default namespace of the connection will be used.
**extra :
Additional keyword arguments are passed as additional operation
parameters to the WBEM server.
Note that :term:`DSP0200` does not define any additional parameters
for this operation.
Raises:
Exceptions described in :class:`~pywbem.WBEMConnection`.
"""
exc = None
method_name = 'DeleteClass'
if self._operation_recorders:
self.operation_recorder_reset()
self.operation_recorder_stage_pywbem_args(
method=method_name,
ClassName=ClassName,
namespace=namespace,
**extra)
try:
stats = self.statistics.start_timer(method_name)
if namespace is None and isinstance(ClassName, CIMClassName):
namespace = ClassName.namespace
namespace = self._iparam_namespace_from_namespace(namespace)
classname = self._iparam_classname(ClassName, 'ClassName')
self._imethodcall(
method_name,
namespace,
ClassName=classname,
has_return_value=False,
**extra)
return
except (CIMXMLParseError, XMLParseError) as exce:
exce.request_data = self.last_raw_request
exce.response_data = self.last_raw_reply
exc = exce
raise
except Exception as exce:
exc = exce
raise
finally:
self._last_operation_time = stats.stop_timer(
self.last_request_len, self.last_reply_len,
self.last_server_response_time, exc)
if self._operation_recorders:
self.operation_recorder_stage_result(None, exc) | python | def DeleteClass(self, ClassName, namespace=None, **extra):
# pylint: disable=invalid-name,line-too-long
"""
Delete a class.
This method performs the DeleteClass operation
(see :term:`DSP0200`). See :ref:`WBEM operations` for a list of all
methods performing such operations.
If the operation succeeds, this method returns.
Otherwise, this method raises an exception.
Parameters:
ClassName (:term:`string` or :class:`~pywbem.CIMClassName`):
Name of the class to be deleted (case independent).
If specified as a :class:`~pywbem.CIMClassName` object, its `host`
attribute will be ignored.
namespace (:term:`string`):
Name of the namespace of the class to be deleted
(case independent).
Leading and trailing slash characters will be stripped. The lexical
case will be preserved.
If `None`, the namespace of the `ClassName` parameter will be used,
if specified as a :class:`~pywbem.CIMClassName` object. If that is
also `None`, the default namespace of the connection will be used.
**extra :
Additional keyword arguments are passed as additional operation
parameters to the WBEM server.
Note that :term:`DSP0200` does not define any additional parameters
for this operation.
Raises:
Exceptions described in :class:`~pywbem.WBEMConnection`.
"""
exc = None
method_name = 'DeleteClass'
if self._operation_recorders:
self.operation_recorder_reset()
self.operation_recorder_stage_pywbem_args(
method=method_name,
ClassName=ClassName,
namespace=namespace,
**extra)
try:
stats = self.statistics.start_timer(method_name)
if namespace is None and isinstance(ClassName, CIMClassName):
namespace = ClassName.namespace
namespace = self._iparam_namespace_from_namespace(namespace)
classname = self._iparam_classname(ClassName, 'ClassName')
self._imethodcall(
method_name,
namespace,
ClassName=classname,
has_return_value=False,
**extra)
return
except (CIMXMLParseError, XMLParseError) as exce:
exce.request_data = self.last_raw_request
exce.response_data = self.last_raw_reply
exc = exce
raise
except Exception as exce:
exc = exce
raise
finally:
self._last_operation_time = stats.stop_timer(
self.last_request_len, self.last_reply_len,
self.last_server_response_time, exc)
if self._operation_recorders:
self.operation_recorder_stage_result(None, exc) | [
"def",
"DeleteClass",
"(",
"self",
",",
"ClassName",
",",
"namespace",
"=",
"None",
",",
"*",
"*",
"extra",
")",
":",
"# pylint: disable=invalid-name,line-too-long",
"exc",
"=",
"None",
"method_name",
"=",
"'DeleteClass'",
"if",
"self",
".",
"_operation_recorders"... | Delete a class.
This method performs the DeleteClass operation
(see :term:`DSP0200`). See :ref:`WBEM operations` for a list of all
methods performing such operations.
If the operation succeeds, this method returns.
Otherwise, this method raises an exception.
Parameters:
ClassName (:term:`string` or :class:`~pywbem.CIMClassName`):
Name of the class to be deleted (case independent).
If specified as a :class:`~pywbem.CIMClassName` object, its `host`
attribute will be ignored.
namespace (:term:`string`):
Name of the namespace of the class to be deleted
(case independent).
Leading and trailing slash characters will be stripped. The lexical
case will be preserved.
If `None`, the namespace of the `ClassName` parameter will be used,
if specified as a :class:`~pywbem.CIMClassName` object. If that is
also `None`, the default namespace of the connection will be used.
**extra :
Additional keyword arguments are passed as additional operation
parameters to the WBEM server.
Note that :term:`DSP0200` does not define any additional parameters
for this operation.
Raises:
Exceptions described in :class:`~pywbem.WBEMConnection`. | [
"Delete",
"a",
"class",
"."
] | e54ecb82c2211e289a268567443d60fdd489f1e4 | https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/cim_operations.py#L9306-L9387 | train | 28,414 |
pywbem/pywbem | attic/twisted_client.py | WBEMClient.connectionMade | 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')
if self.factory.creds:
auth = base64.b64encode('%s:%s' % (self.factory.creds[0],
self.factory.creds[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)) | python | 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')
if self.factory.creds:
auth = base64.b64encode('%s:%s' % (self.factory.creds[0],
self.factory.creds[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",
"connectionMade",
"(",
"self",
")",
":",
"self",
".",
"factory",
".",
"request_xml",
"=",
"str",
"(",
"self",
".",
"factory",
".",
"payload",
")",
"self",
".",
"sendCommand",
"(",
"'POST'",
",",
"'/cimom'",
")",
"self",
".",
"sendHeader",
"(",
"... | Send a HTTP POST command with the appropriate CIM over HTTP
headers and payload. | [
"Send",
"a",
"HTTP",
"POST",
"command",
"with",
"the",
"appropriate",
"CIM",
"over",
"HTTP",
"headers",
"and",
"payload",
"."
] | e54ecb82c2211e289a268567443d60fdd489f1e4 | https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/attic/twisted_client.py#L58-L88 | train | 28,415 |
pywbem/pywbem | attic/twisted_client.py | WBEMClient.handleResponse | 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() | python | 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",
"handleResponse",
"(",
"self",
",",
"data",
")",
":",
"self",
".",
"factory",
".",
"response_xml",
"=",
"data",
"if",
"self",
".",
"status",
"==",
"'200'",
":",
"self",
".",
"factory",
".",
"parseErrorAndResponse",
"(",
"data",
")",
"self",
".",
... | Called when all response data has been received. | [
"Called",
"when",
"all",
"response",
"data",
"has",
"been",
"received",
"."
] | e54ecb82c2211e289a268567443d60fdd489f1e4 | https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/attic/twisted_client.py#L90-L99 | train | 28,416 |
pywbem/pywbem | attic/twisted_client.py | WBEMClient.handleStatus | 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 | python | 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",
"handleStatus",
"(",
"self",
",",
"version",
",",
"status",
",",
"message",
")",
":",
"self",
".",
"status",
"=",
"status",
"self",
".",
"message",
"=",
"message"
] | Save the status code for processing when we get to the end
of the headers. | [
"Save",
"the",
"status",
"code",
"for",
"processing",
"when",
"we",
"get",
"to",
"the",
"end",
"of",
"the",
"headers",
"."
] | e54ecb82c2211e289a268567443d60fdd489f1e4 | https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/attic/twisted_client.py#L101-L106 | train | 28,417 |
pywbem/pywbem | attic/twisted_client.py | WBEMClient.handleHeader | def handleHeader(self, key, value):
"""Handle header values."""
if key == 'CIMError':
self.CIMError = urllib.parse.unquote(value)
if key == 'PGErrorDetail':
self.PGErrorDetail = urllib.parse.unquote(value) | python | def handleHeader(self, key, value):
"""Handle header values."""
if key == 'CIMError':
self.CIMError = urllib.parse.unquote(value)
if key == 'PGErrorDetail':
self.PGErrorDetail = urllib.parse.unquote(value) | [
"def",
"handleHeader",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"if",
"key",
"==",
"'CIMError'",
":",
"self",
".",
"CIMError",
"=",
"urllib",
".",
"parse",
".",
"unquote",
"(",
"value",
")",
"if",
"key",
"==",
"'PGErrorDetail'",
":",
"self",
... | Handle header values. | [
"Handle",
"header",
"values",
"."
] | e54ecb82c2211e289a268567443d60fdd489f1e4 | https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/attic/twisted_client.py#L108-L114 | train | 28,418 |
pywbem/pywbem | attic/twisted_client.py | WBEMClient.handleEndHeaders | 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))) | python | 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))) | [
"def",
"handleEndHeaders",
"(",
"self",
")",
":",
"if",
"self",
".",
"status",
"!=",
"'200'",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'cimerror'",
")",
"or",
"not",
"hasattr",
"(",
"self",
",",
"'errordetail'",
")",
":",
"self",
".",
"factory",... | Check whether the status was OK and raise an error if not
using previously saved header information. | [
"Check",
"whether",
"the",
"status",
"was",
"OK",
"and",
"raise",
"an",
"error",
"if",
"not",
"using",
"previously",
"saved",
"header",
"information",
"."
] | e54ecb82c2211e289a268567443d60fdd489f1e4 | https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/attic/twisted_client.py#L116-L132 | train | 28,419 |
pywbem/pywbem | attic/twisted_client.py | WBEMClientFactory.imethodcallPayload | 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 = cim_xml.CIM(
cim_xml.MESSAGE(
cim_xml.SIMPLEREQ(
cim_xml.IMETHODCALL(
methodname,
cim_xml.LOCALNAMESPACEPATH(
[cim_xml.NAMESPACE(ns)
for ns in localnsp.split('/')]),
param_list)),
'1001', '1.0'),
'2.0', '2.0')
return self.xml_header + payload.toxml() | python | 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 = cim_xml.CIM(
cim_xml.MESSAGE(
cim_xml.SIMPLEREQ(
cim_xml.IMETHODCALL(
methodname,
cim_xml.LOCALNAMESPACEPATH(
[cim_xml.NAMESPACE(ns)
for ns in localnsp.split('/')]),
param_list)),
'1001', '1.0'),
'2.0', '2.0')
return self.xml_header + payload.toxml() | [
"def",
"imethodcallPayload",
"(",
"self",
",",
"methodname",
",",
"localnsp",
",",
"*",
"*",
"kwargs",
")",
":",
"param_list",
"=",
"[",
"pywbem",
".",
"IPARAMVALUE",
"(",
"x",
"[",
"0",
"]",
",",
"pywbem",
".",
"tocimxml",
"(",
"x",
"[",
"1",
"]",
... | Generate the XML payload for an intrinsic methodcall. | [
"Generate",
"the",
"XML",
"payload",
"for",
"an",
"intrinsic",
"methodcall",
"."
] | e54ecb82c2211e289a268567443d60fdd489f1e4 | https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/attic/twisted_client.py#L158-L176 | train | 28,420 |
pywbem/pywbem | attic/twisted_client.py | WBEMClientFactory.methodcallPayload | 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 = cim_xml.LOCALINSTANCEPATH(
cim_xml.LOCALNAMESPACEPATH(
[cim_xml.NAMESPACE(ns)
for ns in namespace.split('/')]),
path.tocimxml())
else:
localpath = cim_xml.LOCALCLASSPATH(
cim_xml.LOCALNAMESPACEPATH(
[cim_xml.NAMESPACE(ns)
for ns in namespace.split('/')]),
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, six.string_types):
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, six.string_types)):
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 = [cim_xml.PARAMVALUE(x[0],
paramvalue(x[1]),
paramtype(x[1]))
for x in kwargs.items()]
payload = cim_xml.CIM(
cim_xml.MESSAGE(
cim_xml.SIMPLEREQ(
cim_xml.METHODCALL(methodname,
localpath,
param_list)),
'1001', '1.0'),
'2.0', '2.0')
return self.xml_header + payload.toxml() | python | 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 = cim_xml.LOCALINSTANCEPATH(
cim_xml.LOCALNAMESPACEPATH(
[cim_xml.NAMESPACE(ns)
for ns in namespace.split('/')]),
path.tocimxml())
else:
localpath = cim_xml.LOCALCLASSPATH(
cim_xml.LOCALNAMESPACEPATH(
[cim_xml.NAMESPACE(ns)
for ns in namespace.split('/')]),
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, six.string_types):
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, six.string_types)):
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 = [cim_xml.PARAMVALUE(x[0],
paramvalue(x[1]),
paramtype(x[1]))
for x in kwargs.items()]
payload = cim_xml.CIM(
cim_xml.MESSAGE(
cim_xml.SIMPLEREQ(
cim_xml.METHODCALL(methodname,
localpath,
param_list)),
'1001', '1.0'),
'2.0', '2.0')
return self.xml_header + payload.toxml() | [
"def",
"methodcallPayload",
"(",
"self",
",",
"methodname",
",",
"obj",
",",
"namespace",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"CIMInstanceName",
")",
":",
"path",
"=",
"obj",
".",
"copy",
"(",
")",
"path",
".",
"ho... | Generate the XML payload for an extrinsic methodcall. | [
"Generate",
"the",
"XML",
"payload",
"for",
"an",
"extrinsic",
"methodcall",
"."
] | e54ecb82c2211e289a268567443d60fdd489f1e4 | https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/attic/twisted_client.py#L178-L249 | train | 28,421 |
pywbem/pywbem | attic/twisted_client.py | WBEMClientFactory.parseErrorAndResponse | 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'])) | python | 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",
"parseErrorAndResponse",
"(",
"self",
",",
"data",
")",
":",
"xml",
"=",
"fromstring",
"(",
"data",
")",
"error",
"=",
"xml",
".",
"find",
"(",
"'.//ERROR'",
")",
"if",
"error",
"is",
"None",
":",
"self",
".",
"deferred",
".",
"callback",
"(",
... | Parse returned XML for errors, then convert into
appropriate Python objects. | [
"Parse",
"returned",
"XML",
"for",
"errors",
"then",
"convert",
"into",
"appropriate",
"Python",
"objects",
"."
] | e54ecb82c2211e289a268567443d60fdd489f1e4 | https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/attic/twisted_client.py#L251-L267 | train | 28,422 |
pywbem/pywbem | attic/irecv/irecv.py | CIMListener.start | def start(self):
''' doesn't work'''
thread = threading.Thread(target=reactor.run)
thread.start() | python | def start(self):
''' doesn't work'''
thread = threading.Thread(target=reactor.run)
thread.start() | [
"def",
"start",
"(",
"self",
")",
":",
"thread",
"=",
"threading",
".",
"Thread",
"(",
"target",
"=",
"reactor",
".",
"run",
")",
"thread",
".",
"start",
"(",
")"
] | doesn't work | [
"doesn",
"t",
"work"
] | e54ecb82c2211e289a268567443d60fdd489f1e4 | https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/attic/irecv/irecv.py#L57-L60 | train | 28,423 |
pywbem/pywbem | attic/cim_provider2.py | CIMProvider2.MI_associatorNames | def MI_associatorNames(self,
env,
objectName,
assocClassName,
resultClassName,
role,
resultRole):
# pylint: disable=invalid-name
"""Return instances names associated to a given object.
Implements the WBEM operation AssociatorNames in terms
of the references method. A derived class will not normally
override this method.
"""
logger = env.get_logger()
logger.log_debug('CIMProvider2 MI_associatorNames called. ' \
'assocClass: %s' % (assocClassName))
if not assocClassName:
raise pywbem.CIMError(
pywbem.CIM_ERR_FAILED,
"Empty assocClassName passed to AssociatorNames")
model = pywbem.CIMInstance(classname=assocClassName)
model.path = pywbem.CIMInstanceName(classname=assocClassName,
namespace=objectName.namespace)
gen = self.references(env=env,
object_name=objectName,
model=model,
result_class_name=resultClassName,
role=role,
result_role=None,
keys_only=False)
if gen is None:
logger.log_debug('references() returned None instead of ' \
'generator object')
return
for inst in gen:
for prop in inst.properties.values():
lpname = prop.name.lower()
if prop.type != 'reference':
continue
if role and role.lower() == lpname:
continue
if resultRole and resultRole.lower() != lpname:
continue
if self.paths_equal(prop.value, objectName):
continue
if resultClassName and \
resultClassName.lower() != prop.value.classname.lower():
continue
if prop.value.namespace is None:
prop.value.namespace = objectName.namespace
yield prop.value
logger.log_debug('CIMProvider2 MI_associatorNames returning') | python | def MI_associatorNames(self,
env,
objectName,
assocClassName,
resultClassName,
role,
resultRole):
# pylint: disable=invalid-name
"""Return instances names associated to a given object.
Implements the WBEM operation AssociatorNames in terms
of the references method. A derived class will not normally
override this method.
"""
logger = env.get_logger()
logger.log_debug('CIMProvider2 MI_associatorNames called. ' \
'assocClass: %s' % (assocClassName))
if not assocClassName:
raise pywbem.CIMError(
pywbem.CIM_ERR_FAILED,
"Empty assocClassName passed to AssociatorNames")
model = pywbem.CIMInstance(classname=assocClassName)
model.path = pywbem.CIMInstanceName(classname=assocClassName,
namespace=objectName.namespace)
gen = self.references(env=env,
object_name=objectName,
model=model,
result_class_name=resultClassName,
role=role,
result_role=None,
keys_only=False)
if gen is None:
logger.log_debug('references() returned None instead of ' \
'generator object')
return
for inst in gen:
for prop in inst.properties.values():
lpname = prop.name.lower()
if prop.type != 'reference':
continue
if role and role.lower() == lpname:
continue
if resultRole and resultRole.lower() != lpname:
continue
if self.paths_equal(prop.value, objectName):
continue
if resultClassName and \
resultClassName.lower() != prop.value.classname.lower():
continue
if prop.value.namespace is None:
prop.value.namespace = objectName.namespace
yield prop.value
logger.log_debug('CIMProvider2 MI_associatorNames returning') | [
"def",
"MI_associatorNames",
"(",
"self",
",",
"env",
",",
"objectName",
",",
"assocClassName",
",",
"resultClassName",
",",
"role",
",",
"resultRole",
")",
":",
"# pylint: disable=invalid-name",
"logger",
"=",
"env",
".",
"get_logger",
"(",
")",
"logger",
".",
... | Return instances names associated to a given object.
Implements the WBEM operation AssociatorNames in terms
of the references method. A derived class will not normally
override this method. | [
"Return",
"instances",
"names",
"associated",
"to",
"a",
"given",
"object",
"."
] | e54ecb82c2211e289a268567443d60fdd489f1e4 | https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/attic/cim_provider2.py#L707-L761 | train | 28,424 |
pywbem/pywbem | attic/cim_provider2.py | ProviderProxy._get_callable | def _get_callable(self, classname, cname):
"""Return a function or method object appropriate to fulfill a request
classname -- The CIM class name associated with the request.
cname -- The function or method name to look for.
"""
callable = None
if classname in self.provregs:
provClass = self.provregs[classname]
if hasattr(provClass, cname):
callable = getattr(provClass, cname)
elif hasattr(self.provmod, cname):
callable = getattr(self.provmod, cname)
if callable is None:
raise pywbem.CIMError(
pywbem.CIM_ERR_FAILED,
"No provider registered for %s or no callable for %s:%s on " \
"provider %s" % (classname, classname, cname, self.provid))
return callable | python | def _get_callable(self, classname, cname):
"""Return a function or method object appropriate to fulfill a request
classname -- The CIM class name associated with the request.
cname -- The function or method name to look for.
"""
callable = None
if classname in self.provregs:
provClass = self.provregs[classname]
if hasattr(provClass, cname):
callable = getattr(provClass, cname)
elif hasattr(self.provmod, cname):
callable = getattr(self.provmod, cname)
if callable is None:
raise pywbem.CIMError(
pywbem.CIM_ERR_FAILED,
"No provider registered for %s or no callable for %s:%s on " \
"provider %s" % (classname, classname, cname, self.provid))
return callable | [
"def",
"_get_callable",
"(",
"self",
",",
"classname",
",",
"cname",
")",
":",
"callable",
"=",
"None",
"if",
"classname",
"in",
"self",
".",
"provregs",
":",
"provClass",
"=",
"self",
".",
"provregs",
"[",
"classname",
"]",
"if",
"hasattr",
"(",
"provCl... | Return a function or method object appropriate to fulfill a request
classname -- The CIM class name associated with the request.
cname -- The function or method name to look for. | [
"Return",
"a",
"function",
"or",
"method",
"object",
"appropriate",
"to",
"fulfill",
"a",
"request"
] | e54ecb82c2211e289a268567443d60fdd489f1e4 | https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/attic/cim_provider2.py#L1739-L1759 | train | 28,425 |
pywbem/pywbem | attic/cim_provider2.py | ProviderProxy._reload_if_necessary | def _reload_if_necessary(self, env):
"""Check timestamp of loaded python provider module, and if it has
changed since load, then reload the provider module.
"""
try:
mod = sys.modules[self.provider_module_name]
except KeyError:
mod = None
if (mod is None or \
mod.provmod_timestamp != os.path.getmtime(self.provid)):
logger = env.get_logger()
logger.log_debug("Need to reload provider at %s" % self.provid)
#first unload the module
if self.provmod and hasattr(self.provmod, "shutdown"):
self.provmod.shutdown(env)
#now reload and reinit module
try:
del sys.modules[self.provider_module_name]
except KeyError:
pass
try:
self._load_provider_source(logger)
self._init_provider(env)
except IOError as exc:
raise pywbem.CIMError(
pywbem.CIM_ERR_FAILED,
"Error loading provider %s: %s" % (provid, exc)) | python | def _reload_if_necessary(self, env):
"""Check timestamp of loaded python provider module, and if it has
changed since load, then reload the provider module.
"""
try:
mod = sys.modules[self.provider_module_name]
except KeyError:
mod = None
if (mod is None or \
mod.provmod_timestamp != os.path.getmtime(self.provid)):
logger = env.get_logger()
logger.log_debug("Need to reload provider at %s" % self.provid)
#first unload the module
if self.provmod and hasattr(self.provmod, "shutdown"):
self.provmod.shutdown(env)
#now reload and reinit module
try:
del sys.modules[self.provider_module_name]
except KeyError:
pass
try:
self._load_provider_source(logger)
self._init_provider(env)
except IOError as exc:
raise pywbem.CIMError(
pywbem.CIM_ERR_FAILED,
"Error loading provider %s: %s" % (provid, exc)) | [
"def",
"_reload_if_necessary",
"(",
"self",
",",
"env",
")",
":",
"try",
":",
"mod",
"=",
"sys",
".",
"modules",
"[",
"self",
".",
"provider_module_name",
"]",
"except",
"KeyError",
":",
"mod",
"=",
"None",
"if",
"(",
"mod",
"is",
"None",
"or",
"mod",
... | Check timestamp of loaded python provider module, and if it has
changed since load, then reload the provider module. | [
"Check",
"timestamp",
"of",
"loaded",
"python",
"provider",
"module",
"and",
"if",
"it",
"has",
"changed",
"since",
"load",
"then",
"reload",
"the",
"provider",
"module",
"."
] | e54ecb82c2211e289a268567443d60fdd489f1e4 | https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/attic/cim_provider2.py#L1761-L1788 | train | 28,426 |
pywbem/pywbem | pywbem/_nocasedict.py | NocaseDict._real_key | def _real_key(self, key):
"""
Return the normalized key to be used for the internal dictionary,
from the input key.
"""
if key is not None:
try:
return key.lower()
except AttributeError:
raise TypeError(
_format("NocaseDict key {0!A} must be a string, "
"but is {1}", key, type(key)))
if self.allow_unnamed_keys:
return None
raise TypeError(
_format("NocaseDict key None (unnamed key) is not "
"allowed for this object")) | python | def _real_key(self, key):
"""
Return the normalized key to be used for the internal dictionary,
from the input key.
"""
if key is not None:
try:
return key.lower()
except AttributeError:
raise TypeError(
_format("NocaseDict key {0!A} must be a string, "
"but is {1}", key, type(key)))
if self.allow_unnamed_keys:
return None
raise TypeError(
_format("NocaseDict key None (unnamed key) is not "
"allowed for this object")) | [
"def",
"_real_key",
"(",
"self",
",",
"key",
")",
":",
"if",
"key",
"is",
"not",
"None",
":",
"try",
":",
"return",
"key",
".",
"lower",
"(",
")",
"except",
"AttributeError",
":",
"raise",
"TypeError",
"(",
"_format",
"(",
"\"NocaseDict key {0!A} must be a... | Return the normalized key to be used for the internal dictionary,
from the input key. | [
"Return",
"the",
"normalized",
"key",
"to",
"be",
"used",
"for",
"the",
"internal",
"dictionary",
"from",
"the",
"input",
"key",
"."
] | e54ecb82c2211e289a268567443d60fdd489f1e4 | https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/_nocasedict.py#L202-L220 | train | 28,427 |
pywbem/pywbem | pywbem/_nocasedict.py | NocaseDict.copy | def copy(self):
"""
Return a copy of the dictionary.
This is a middle-deep copy; the copy is independent of the original in
all attributes that have mutable types except for:
* The values in the dictionary
Note that the Python functions :func:`py:copy.copy` and
:func:`py:copy.deepcopy` can be used to create completely shallow or
completely deep copies of objects of this class.
"""
result = NocaseDict()
result._data = self._data.copy() # pylint: disable=protected-access
return result | python | def copy(self):
"""
Return a copy of the dictionary.
This is a middle-deep copy; the copy is independent of the original in
all attributes that have mutable types except for:
* The values in the dictionary
Note that the Python functions :func:`py:copy.copy` and
:func:`py:copy.deepcopy` can be used to create completely shallow or
completely deep copies of objects of this class.
"""
result = NocaseDict()
result._data = self._data.copy() # pylint: disable=protected-access
return result | [
"def",
"copy",
"(",
"self",
")",
":",
"result",
"=",
"NocaseDict",
"(",
")",
"result",
".",
"_data",
"=",
"self",
".",
"_data",
".",
"copy",
"(",
")",
"# pylint: disable=protected-access",
"return",
"result"
] | Return a copy of the dictionary.
This is a middle-deep copy; the copy is independent of the original in
all attributes that have mutable types except for:
* The values in the dictionary
Note that the Python functions :func:`py:copy.copy` and
:func:`py:copy.deepcopy` can be used to create completely shallow or
completely deep copies of objects of this class. | [
"Return",
"a",
"copy",
"of",
"the",
"dictionary",
"."
] | e54ecb82c2211e289a268567443d60fdd489f1e4 | https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/_nocasedict.py#L423-L438 | train | 28,428 |
pywbem/pywbem | pywbem/mof_compiler.py | t_error | 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 | python | 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 | [
"def",
"t_error",
"(",
"t",
")",
":",
"msg",
"=",
"_format",
"(",
"\"Illegal character {0!A}\"",
",",
"t",
".",
"value",
"[",
"0",
"]",
")",
"t",
".",
"lexer",
".",
"last_msg",
"=",
"msg",
"t",
".",
"lexer",
".",
"skip",
"(",
"1",
")",
"return",
... | Lexer error callback from PLY Lexer with token in error. | [
"Lexer",
"error",
"callback",
"from",
"PLY",
"Lexer",
"with",
"token",
"in",
"error",
"."
] | e54ecb82c2211e289a268567443d60fdd489f1e4 | https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/mof_compiler.py#L334-L340 | train | 28,429 |
pywbem/pywbem | pywbem/mof_compiler.py | p_error | 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 file')
msg = p.lexer.last_msg
p.lexer.last_msg = None
raise MOFParseError(parser_token=p, msg=msg) | python | 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 file')
msg = p.lexer.last_msg
p.lexer.last_msg = None
raise MOFParseError(parser_token=p, msg=msg) | [
"def",
"p_error",
"(",
"p",
")",
":",
"if",
"p",
"is",
"None",
":",
"raise",
"MOFParseError",
"(",
"msg",
"=",
"'Unexpected end of file'",
")",
"msg",
"=",
"p",
".",
"lexer",
".",
"last_msg",
"p",
".",
"lexer",
".",
"last_msg",
"=",
"None",
"raise",
... | 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. | [
"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",... | e54ecb82c2211e289a268567443d60fdd489f1e4 | https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/mof_compiler.py#L454-L466 | train | 28,430 |
pywbem/pywbem | pywbem/mof_compiler.py | _fixStringValue | def _fixStringValue(s, p):
"""Clean up string value including special characters, etc."""
# pylint: disable=too-many-branches
s = s[1:-1]
rv = ''
esc = False
i = -1
while i < len(s) - 1:
i += 1
ch = s[i]
if ch == '\\' and not esc:
esc = True
continue
if not esc:
rv += ch
continue
if ch == '"':
rv += '"'
elif ch == 'n':
rv += '\n'
elif ch == 't':
rv += '\t'
elif ch == 'b':
rv += '\b'
elif ch == 'f':
rv += '\f'
elif ch == 'r':
rv += '\r'
elif ch == '\\':
rv += '\\'
elif ch in ['x', 'X']:
hexc = 0
j = 0
i += 1
while j < 4:
c = s[i + j]
c = c.upper()
if not c.isdigit() and c not in 'ABCDEF':
break
hexc <<= 4
if c.isdigit():
hexc |= ord(c) - ord('0')
else:
hexc |= ord(c) - ord('A') + 0XA
j += 1
if j == 0:
# DSP0004 requires 1..4 hex chars - we have 0
raise MOFParseError(
parser_token=p,
msg="Unicode escape sequence (e.g. '\\x12AB') requires "
"at least one hex character")
rv += six.unichr(hexc)
i += j - 1
esc = False
return rv | python | def _fixStringValue(s, p):
"""Clean up string value including special characters, etc."""
# pylint: disable=too-many-branches
s = s[1:-1]
rv = ''
esc = False
i = -1
while i < len(s) - 1:
i += 1
ch = s[i]
if ch == '\\' and not esc:
esc = True
continue
if not esc:
rv += ch
continue
if ch == '"':
rv += '"'
elif ch == 'n':
rv += '\n'
elif ch == 't':
rv += '\t'
elif ch == 'b':
rv += '\b'
elif ch == 'f':
rv += '\f'
elif ch == 'r':
rv += '\r'
elif ch == '\\':
rv += '\\'
elif ch in ['x', 'X']:
hexc = 0
j = 0
i += 1
while j < 4:
c = s[i + j]
c = c.upper()
if not c.isdigit() and c not in 'ABCDEF':
break
hexc <<= 4
if c.isdigit():
hexc |= ord(c) - ord('0')
else:
hexc |= ord(c) - ord('A') + 0XA
j += 1
if j == 0:
# DSP0004 requires 1..4 hex chars - we have 0
raise MOFParseError(
parser_token=p,
msg="Unicode escape sequence (e.g. '\\x12AB') requires "
"at least one hex character")
rv += six.unichr(hexc)
i += j - 1
esc = False
return rv | [
"def",
"_fixStringValue",
"(",
"s",
",",
"p",
")",
":",
"# pylint: disable=too-many-branches",
"s",
"=",
"s",
"[",
"1",
":",
"-",
"1",
"]",
"rv",
"=",
"''",
"esc",
"=",
"False",
"i",
"=",
"-",
"1",
"while",
"i",
"<",
"len",
"(",
"s",
")",
"-",
... | Clean up string value including special characters, etc. | [
"Clean",
"up",
"string",
"value",
"including",
"special",
"characters",
"etc",
"."
] | e54ecb82c2211e289a268567443d60fdd489f1e4 | https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/mof_compiler.py#L1200-L1258 | train | 28,431 |
pywbem/pywbem | pywbem/mof_compiler.py | _build_flavors | def _build_flavors(p, flist, qualdecl=None):
"""
Build and return a dictionary defining the flavors from the
flist argument.
This function maps from the input keyword definitions for the flavors
(ex. EnableOverride) to the PyWBEM internal definitions
(ex. overridable)
Uses the qualdecl argument as a basis if it exists. This is to define
qualifier flavors if qualfier declaractions exist.
This applies the values from the qualifierDecl to the the qualifier
flavor list.
This function and the defaultflavor function insure that all
flavors are defined in the created dictionary that is returned. This
is important because the PyWBEM classes allow `None` as a flavor
definition.
"""
flavors = {}
if ('disableoverride' in flist and 'enableoverride' in flist) \
or \
('restricted' in flist and 'tosubclass' in flist): # noqa: E125
raise MOFParseError(parser_token=p, msg="Conflicting flavors are"
"invalid")
if qualdecl is not None:
flavors = {'overridable': qualdecl.overridable,
'translatable': qualdecl.translatable,
'tosubclass': qualdecl.tosubclass,
'toinstance': qualdecl.toinstance}
if 'disableoverride' in flist:
flavors['overridable'] = False
if 'enableoverride' in flist:
flavors['overridable'] = True
if 'translatable' in flist:
flavors['translatable'] = True
if 'restricted' in flist:
flavors['tosubclass'] = False
if 'tosubclass' in flist:
flavors['tosubclass'] = True
if 'toinstance' in flist:
flavors['toinstance'] = True
# issue #193 ks 5/16 removed tosubclass & set toinstance.
return flavors | python | def _build_flavors(p, flist, qualdecl=None):
"""
Build and return a dictionary defining the flavors from the
flist argument.
This function maps from the input keyword definitions for the flavors
(ex. EnableOverride) to the PyWBEM internal definitions
(ex. overridable)
Uses the qualdecl argument as a basis if it exists. This is to define
qualifier flavors if qualfier declaractions exist.
This applies the values from the qualifierDecl to the the qualifier
flavor list.
This function and the defaultflavor function insure that all
flavors are defined in the created dictionary that is returned. This
is important because the PyWBEM classes allow `None` as a flavor
definition.
"""
flavors = {}
if ('disableoverride' in flist and 'enableoverride' in flist) \
or \
('restricted' in flist and 'tosubclass' in flist): # noqa: E125
raise MOFParseError(parser_token=p, msg="Conflicting flavors are"
"invalid")
if qualdecl is not None:
flavors = {'overridable': qualdecl.overridable,
'translatable': qualdecl.translatable,
'tosubclass': qualdecl.tosubclass,
'toinstance': qualdecl.toinstance}
if 'disableoverride' in flist:
flavors['overridable'] = False
if 'enableoverride' in flist:
flavors['overridable'] = True
if 'translatable' in flist:
flavors['translatable'] = True
if 'restricted' in flist:
flavors['tosubclass'] = False
if 'tosubclass' in flist:
flavors['tosubclass'] = True
if 'toinstance' in flist:
flavors['toinstance'] = True
# issue #193 ks 5/16 removed tosubclass & set toinstance.
return flavors | [
"def",
"_build_flavors",
"(",
"p",
",",
"flist",
",",
"qualdecl",
"=",
"None",
")",
":",
"flavors",
"=",
"{",
"}",
"if",
"(",
"'disableoverride'",
"in",
"flist",
"and",
"'enableoverride'",
"in",
"flist",
")",
"or",
"(",
"'restricted'",
"in",
"flist",
"an... | Build and return a dictionary defining the flavors from the
flist argument.
This function maps from the input keyword definitions for the flavors
(ex. EnableOverride) to the PyWBEM internal definitions
(ex. overridable)
Uses the qualdecl argument as a basis if it exists. This is to define
qualifier flavors if qualfier declaractions exist.
This applies the values from the qualifierDecl to the the qualifier
flavor list.
This function and the defaultflavor function insure that all
flavors are defined in the created dictionary that is returned. This
is important because the PyWBEM classes allow `None` as a flavor
definition. | [
"Build",
"and",
"return",
"a",
"dictionary",
"defining",
"the",
"flavors",
"from",
"the",
"flist",
"argument",
"."
] | e54ecb82c2211e289a268567443d60fdd489f1e4 | https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/mof_compiler.py#L1336-L1384 | train | 28,432 |
pywbem/pywbem | pywbem/mof_compiler.py | _find_column | def _find_column(input_, token):
"""
Find the column in file where error occured. This is taken from
token.lexpos converted to the position on the current line by
finding the previous EOL.
"""
i = token.lexpos
while i > 0:
if input_[i] == '\n':
break
i -= 1
column = token.lexpos - i - 1
return column | python | def _find_column(input_, token):
"""
Find the column in file where error occured. This is taken from
token.lexpos converted to the position on the current line by
finding the previous EOL.
"""
i = token.lexpos
while i > 0:
if input_[i] == '\n':
break
i -= 1
column = token.lexpos - i - 1
return column | [
"def",
"_find_column",
"(",
"input_",
",",
"token",
")",
":",
"i",
"=",
"token",
".",
"lexpos",
"while",
"i",
">",
"0",
":",
"if",
"input_",
"[",
"i",
"]",
"==",
"'\\n'",
":",
"break",
"i",
"-=",
"1",
"column",
"=",
"token",
".",
"lexpos",
"-",
... | Find the column in file where error occured. This is taken from
token.lexpos converted to the position on the current line by
finding the previous EOL. | [
"Find",
"the",
"column",
"in",
"file",
"where",
"error",
"occured",
".",
"This",
"is",
"taken",
"from",
"token",
".",
"lexpos",
"converted",
"to",
"the",
"position",
"on",
"the",
"current",
"line",
"by",
"finding",
"the",
"previous",
"EOL",
"."
] | e54ecb82c2211e289a268567443d60fdd489f1e4 | https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/mof_compiler.py#L1663-L1676 | train | 28,433 |
pywbem/pywbem | pywbem/mof_compiler.py | _get_error_context | def _get_error_context(input_, token):
"""
Build a context string that defines where on the line the defined
error occurs. This consists of the characters ^ at the position
and for the length defined by the lexer position and token length
"""
try:
line = input_[token.lexpos: input_.index('\n', token.lexpos)]
except ValueError:
line = input_[token.lexpos:]
i = input_.rfind('\n', 0, token.lexpos)
if i < 0:
i = 0
line = input_[i:token.lexpos] + line
lines = [line.strip('\r\n')]
col = token.lexpos - i
while len(lines) < 5 and i > 0:
end = i
i = input_.rfind('\n', 0, i)
if i < 0:
i = 0
lines.insert(0, input_[i:end].strip('\r\n'))
pointer = ''
for dummy_ch in str(token.value):
pointer += '^'
pointline = ''
i = 0
while i < col - 1:
if lines[-1][i].isspace():
pointline += lines[-1][i]
# otherwise, tabs complicate the alignment
else:
pointline += ' '
i += 1
lines.append(pointline + pointer)
return lines | python | def _get_error_context(input_, token):
"""
Build a context string that defines where on the line the defined
error occurs. This consists of the characters ^ at the position
and for the length defined by the lexer position and token length
"""
try:
line = input_[token.lexpos: input_.index('\n', token.lexpos)]
except ValueError:
line = input_[token.lexpos:]
i = input_.rfind('\n', 0, token.lexpos)
if i < 0:
i = 0
line = input_[i:token.lexpos] + line
lines = [line.strip('\r\n')]
col = token.lexpos - i
while len(lines) < 5 and i > 0:
end = i
i = input_.rfind('\n', 0, i)
if i < 0:
i = 0
lines.insert(0, input_[i:end].strip('\r\n'))
pointer = ''
for dummy_ch in str(token.value):
pointer += '^'
pointline = ''
i = 0
while i < col - 1:
if lines[-1][i].isspace():
pointline += lines[-1][i]
# otherwise, tabs complicate the alignment
else:
pointline += ' '
i += 1
lines.append(pointline + pointer)
return lines | [
"def",
"_get_error_context",
"(",
"input_",
",",
"token",
")",
":",
"try",
":",
"line",
"=",
"input_",
"[",
"token",
".",
"lexpos",
":",
"input_",
".",
"index",
"(",
"'\\n'",
",",
"token",
".",
"lexpos",
")",
"]",
"except",
"ValueError",
":",
"line",
... | Build a context string that defines where on the line the defined
error occurs. This consists of the characters ^ at the position
and for the length defined by the lexer position and token length | [
"Build",
"a",
"context",
"string",
"that",
"defines",
"where",
"on",
"the",
"line",
"the",
"defined",
"error",
"occurs",
".",
"This",
"consists",
"of",
"the",
"characters",
"^",
"at",
"the",
"position",
"and",
"for",
"the",
"length",
"defined",
"by",
"the"... | e54ecb82c2211e289a268567443d60fdd489f1e4 | https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/mof_compiler.py#L1679-L1716 | train | 28,434 |
pywbem/pywbem | pywbem/mof_compiler.py | _build | def _build(verbose=False):
"""Build the LEX and YACC table modules for the MOF compiler, if they do
not exist yet, or if their table versions do not match the installed
version of the `ply` package.
"""
if verbose:
print(
_format("Building LEX/YACC modules for MOF compiler in: {0}",
_tabdir))
_yacc(verbose)
_lex(verbose) | python | def _build(verbose=False):
"""Build the LEX and YACC table modules for the MOF compiler, if they do
not exist yet, or if their table versions do not match the installed
version of the `ply` package.
"""
if verbose:
print(
_format("Building LEX/YACC modules for MOF compiler in: {0}",
_tabdir))
_yacc(verbose)
_lex(verbose) | [
"def",
"_build",
"(",
"verbose",
"=",
"False",
")",
":",
"if",
"verbose",
":",
"print",
"(",
"_format",
"(",
"\"Building LEX/YACC modules for MOF compiler in: {0}\"",
",",
"_tabdir",
")",
")",
"_yacc",
"(",
"verbose",
")",
"_lex",
"(",
"verbose",
")"
] | Build the LEX and YACC table modules for the MOF compiler, if they do
not exist yet, or if their table versions do not match the installed
version of the `ply` package. | [
"Build",
"the",
"LEX",
"and",
"YACC",
"table",
"modules",
"for",
"the",
"MOF",
"compiler",
"if",
"they",
"do",
"not",
"exist",
"yet",
"or",
"if",
"their",
"table",
"versions",
"do",
"not",
"match",
"the",
"installed",
"version",
"of",
"the",
"ply",
"pack... | e54ecb82c2211e289a268567443d60fdd489f1e4 | https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/mof_compiler.py#L2548-L2560 | train | 28,435 |
pywbem/pywbem | pywbem/mof_compiler.py | _yacc | def _yacc(verbose=False):
"""Return YACC parser object for the MOF compiler.
As a side effect, the YACC table module for the MOF compiler gets created
if it does not exist yet, or updated if its table version does not match
the installed version of the `ply` package.
"""
# In yacc(), the 'debug' parameter controls the main error
# messages to the 'errorlog' in addition to the debug messages
# to the 'debuglog'. Because we want to see the error messages,
# we enable debug but set the debuglog to the NullLogger.
# To enable debug logging, set debuglog to some other logger
# (ex. PlyLogger(sys.stdout) to generate log output.
return yacc.yacc(optimize=_optimize,
tabmodule=_tabmodule,
outputdir=_tabdir,
debug=True,
debuglog=yacc.NullLogger(),
errorlog=yacc.PlyLogger(sys.stdout)) | python | def _yacc(verbose=False):
"""Return YACC parser object for the MOF compiler.
As a side effect, the YACC table module for the MOF compiler gets created
if it does not exist yet, or updated if its table version does not match
the installed version of the `ply` package.
"""
# In yacc(), the 'debug' parameter controls the main error
# messages to the 'errorlog' in addition to the debug messages
# to the 'debuglog'. Because we want to see the error messages,
# we enable debug but set the debuglog to the NullLogger.
# To enable debug logging, set debuglog to some other logger
# (ex. PlyLogger(sys.stdout) to generate log output.
return yacc.yacc(optimize=_optimize,
tabmodule=_tabmodule,
outputdir=_tabdir,
debug=True,
debuglog=yacc.NullLogger(),
errorlog=yacc.PlyLogger(sys.stdout)) | [
"def",
"_yacc",
"(",
"verbose",
"=",
"False",
")",
":",
"# In yacc(), the 'debug' parameter controls the main error",
"# messages to the 'errorlog' in addition to the debug messages",
"# to the 'debuglog'. Because we want to see the error messages,",
"# we enable debug but set the debuglog to ... | Return YACC parser object for the MOF compiler.
As a side effect, the YACC table module for the MOF compiler gets created
if it does not exist yet, or updated if its table version does not match
the installed version of the `ply` package. | [
"Return",
"YACC",
"parser",
"object",
"for",
"the",
"MOF",
"compiler",
"."
] | e54ecb82c2211e289a268567443d60fdd489f1e4 | https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/mof_compiler.py#L2563-L2582 | train | 28,436 |
pywbem/pywbem | pywbem/mof_compiler.py | _lex | def _lex(verbose=False):
"""Return LEX analyzer object for the MOF Compiler.
As a side effect, the LEX table module for the MOF compiler gets created
if it does not exist yet, or updated if its table version does not match
the installed version of the `ply` package.
To debug lex you may set debug=True and enable the debuglog statement.
or other logger definition.
"""
return lex.lex(optimize=_optimize,
lextab=_lextab,
outputdir=_tabdir,
debug=False,
# debuglog = lex.PlyLogger(sys.stdout),
errorlog=lex.PlyLogger(sys.stdout)) | python | def _lex(verbose=False):
"""Return LEX analyzer object for the MOF Compiler.
As a side effect, the LEX table module for the MOF compiler gets created
if it does not exist yet, or updated if its table version does not match
the installed version of the `ply` package.
To debug lex you may set debug=True and enable the debuglog statement.
or other logger definition.
"""
return lex.lex(optimize=_optimize,
lextab=_lextab,
outputdir=_tabdir,
debug=False,
# debuglog = lex.PlyLogger(sys.stdout),
errorlog=lex.PlyLogger(sys.stdout)) | [
"def",
"_lex",
"(",
"verbose",
"=",
"False",
")",
":",
"return",
"lex",
".",
"lex",
"(",
"optimize",
"=",
"_optimize",
",",
"lextab",
"=",
"_lextab",
",",
"outputdir",
"=",
"_tabdir",
",",
"debug",
"=",
"False",
",",
"# debuglog = lex.PlyLogger(sys.stdout),"... | Return LEX analyzer object for the MOF Compiler.
As a side effect, the LEX table module for the MOF compiler gets created
if it does not exist yet, or updated if its table version does not match
the installed version of the `ply` package.
To debug lex you may set debug=True and enable the debuglog statement.
or other logger definition. | [
"Return",
"LEX",
"analyzer",
"object",
"for",
"the",
"MOF",
"Compiler",
"."
] | e54ecb82c2211e289a268567443d60fdd489f1e4 | https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/mof_compiler.py#L2585-L2601 | train | 28,437 |
pywbem/pywbem | pywbem/mof_compiler.py | MOFWBEMConnection._setns | def _setns(self, value):
"""
Set the default repository namespace to be used.
This method exists for compatibility. Use the :attr:`default_namespace`
property instead.
"""
if self.conn is not None:
self.conn.default_namespace = value
else:
self.__default_namespace = value | python | def _setns(self, value):
"""
Set the default repository namespace to be used.
This method exists for compatibility. Use the :attr:`default_namespace`
property instead.
"""
if self.conn is not None:
self.conn.default_namespace = value
else:
self.__default_namespace = value | [
"def",
"_setns",
"(",
"self",
",",
"value",
")",
":",
"if",
"self",
".",
"conn",
"is",
"not",
"None",
":",
"self",
".",
"conn",
".",
"default_namespace",
"=",
"value",
"else",
":",
"self",
".",
"__default_namespace",
"=",
"value"
] | Set the default repository namespace to be used.
This method exists for compatibility. Use the :attr:`default_namespace`
property instead. | [
"Set",
"the",
"default",
"repository",
"namespace",
"to",
"be",
"used",
"."
] | e54ecb82c2211e289a268567443d60fdd489f1e4 | https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/mof_compiler.py#L1955-L1965 | train | 28,438 |
pywbem/pywbem | pywbem/mof_compiler.py | MOFWBEMConnection.CreateInstance | def CreateInstance(self, *args, **kwargs):
"""Create a CIM instance in the local repository of this class.
For a description of the parameters, see
:meth:`pywbem.WBEMConnection.CreateInstance`.
"""
inst = args[0] if args else kwargs['NewInstance']
try:
self.instances[self.default_namespace].append(inst)
except KeyError:
self.instances[self.default_namespace] = [inst]
return inst.path | python | def CreateInstance(self, *args, **kwargs):
"""Create a CIM instance in the local repository of this class.
For a description of the parameters, see
:meth:`pywbem.WBEMConnection.CreateInstance`.
"""
inst = args[0] if args else kwargs['NewInstance']
try:
self.instances[self.default_namespace].append(inst)
except KeyError:
self.instances[self.default_namespace] = [inst]
return inst.path | [
"def",
"CreateInstance",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"inst",
"=",
"args",
"[",
"0",
"]",
"if",
"args",
"else",
"kwargs",
"[",
"'NewInstance'",
"]",
"try",
":",
"self",
".",
"instances",
"[",
"self",
".",
"defau... | Create a CIM instance in the local repository of this class.
For a description of the parameters, see
:meth:`pywbem.WBEMConnection.CreateInstance`. | [
"Create",
"a",
"CIM",
"instance",
"in",
"the",
"local",
"repository",
"of",
"this",
"class",
"."
] | e54ecb82c2211e289a268567443d60fdd489f1e4 | https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/mof_compiler.py#L2010-L2022 | train | 28,439 |
pywbem/pywbem | pywbem/mof_compiler.py | MOFWBEMConnection.GetClass | def GetClass(self, *args, **kwargs):
"""Retrieve a CIM class from the local repository of this class.
For a description of the parameters, see
:meth:`pywbem.WBEMConnection.GetClass`.
"""
cname = args[0] if args else kwargs['ClassName']
try:
cc = self.classes[self.default_namespace][cname]
except KeyError:
if self.conn is None:
ce = CIMError(CIM_ERR_NOT_FOUND, cname)
raise ce
cc = self.conn.GetClass(*args, **kwargs)
try:
self.classes[self.default_namespace][cc.classname] = cc
except KeyError:
self.classes[self.default_namespace] = \
NocaseDict({cc.classname: cc})
if 'LocalOnly' in kwargs and not kwargs['LocalOnly']:
if cc.superclass:
try:
del kwargs['ClassName']
except KeyError:
pass
if args:
args = args[1:]
super_ = self.GetClass(cc.superclass, *args, **kwargs)
for prop in super_.properties.values():
if prop.name not in cc.properties:
cc.properties[prop.name] = prop
for meth in super_.methods.values():
if meth.name not in cc.methods:
cc.methods[meth.name] = meth
return cc | python | def GetClass(self, *args, **kwargs):
"""Retrieve a CIM class from the local repository of this class.
For a description of the parameters, see
:meth:`pywbem.WBEMConnection.GetClass`.
"""
cname = args[0] if args else kwargs['ClassName']
try:
cc = self.classes[self.default_namespace][cname]
except KeyError:
if self.conn is None:
ce = CIMError(CIM_ERR_NOT_FOUND, cname)
raise ce
cc = self.conn.GetClass(*args, **kwargs)
try:
self.classes[self.default_namespace][cc.classname] = cc
except KeyError:
self.classes[self.default_namespace] = \
NocaseDict({cc.classname: cc})
if 'LocalOnly' in kwargs and not kwargs['LocalOnly']:
if cc.superclass:
try:
del kwargs['ClassName']
except KeyError:
pass
if args:
args = args[1:]
super_ = self.GetClass(cc.superclass, *args, **kwargs)
for prop in super_.properties.values():
if prop.name not in cc.properties:
cc.properties[prop.name] = prop
for meth in super_.methods.values():
if meth.name not in cc.methods:
cc.methods[meth.name] = meth
return cc | [
"def",
"GetClass",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"cname",
"=",
"args",
"[",
"0",
"]",
"if",
"args",
"else",
"kwargs",
"[",
"'ClassName'",
"]",
"try",
":",
"cc",
"=",
"self",
".",
"classes",
"[",
"self",
".",
... | Retrieve a CIM class from the local repository of this class.
For a description of the parameters, see
:meth:`pywbem.WBEMConnection.GetClass`. | [
"Retrieve",
"a",
"CIM",
"class",
"from",
"the",
"local",
"repository",
"of",
"this",
"class",
"."
] | e54ecb82c2211e289a268567443d60fdd489f1e4 | https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/mof_compiler.py#L2033-L2068 | train | 28,440 |
pywbem/pywbem | pywbem/mof_compiler.py | MOFWBEMConnection.EnumerateQualifiers | def EnumerateQualifiers(self, *args, **kwargs):
"""Enumerate the qualifier types in the local repository of this class.
For a description of the parameters, see
:meth:`pywbem.WBEMConnection.EnumerateQualifiers`.
"""
if self.conn is not None:
rv = self.conn.EnumerateQualifiers(*args, **kwargs)
else:
rv = []
try:
rv += list(self.qualifiers[self.default_namespace].values())
except KeyError:
pass
return rv | python | def EnumerateQualifiers(self, *args, **kwargs):
"""Enumerate the qualifier types in the local repository of this class.
For a description of the parameters, see
:meth:`pywbem.WBEMConnection.EnumerateQualifiers`.
"""
if self.conn is not None:
rv = self.conn.EnumerateQualifiers(*args, **kwargs)
else:
rv = []
try:
rv += list(self.qualifiers[self.default_namespace].values())
except KeyError:
pass
return rv | [
"def",
"EnumerateQualifiers",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"conn",
"is",
"not",
"None",
":",
"rv",
"=",
"self",
".",
"conn",
".",
"EnumerateQualifiers",
"(",
"*",
"args",
",",
"*",
"*",
"kwarg... | Enumerate the qualifier types in the local repository of this class.
For a description of the parameters, see
:meth:`pywbem.WBEMConnection.EnumerateQualifiers`. | [
"Enumerate",
"the",
"qualifier",
"types",
"in",
"the",
"local",
"repository",
"of",
"this",
"class",
"."
] | e54ecb82c2211e289a268567443d60fdd489f1e4 | https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/mof_compiler.py#L2164-L2179 | train | 28,441 |
pywbem/pywbem | pywbem/mof_compiler.py | MOFWBEMConnection.GetQualifier | def GetQualifier(self, *args, **kwargs):
"""Retrieve a qualifier type from the local repository of this class.
For a description of the parameters, see
:meth:`pywbem.WBEMConnection.GetQualifier`.
"""
qualname = args[0] if args else kwargs['QualifierName']
try:
qual = self.qualifiers[self.default_namespace][qualname]
except KeyError:
if self.conn is None:
raise CIMError(
CIM_ERR_NOT_FOUND, qualname, conn_id=self.conn_id)
qual = self.conn.GetQualifier(*args, **kwargs)
return qual | python | def GetQualifier(self, *args, **kwargs):
"""Retrieve a qualifier type from the local repository of this class.
For a description of the parameters, see
:meth:`pywbem.WBEMConnection.GetQualifier`.
"""
qualname = args[0] if args else kwargs['QualifierName']
try:
qual = self.qualifiers[self.default_namespace][qualname]
except KeyError:
if self.conn is None:
raise CIMError(
CIM_ERR_NOT_FOUND, qualname, conn_id=self.conn_id)
qual = self.conn.GetQualifier(*args, **kwargs)
return qual | [
"def",
"GetQualifier",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"qualname",
"=",
"args",
"[",
"0",
"]",
"if",
"args",
"else",
"kwargs",
"[",
"'QualifierName'",
"]",
"try",
":",
"qual",
"=",
"self",
".",
"qualifiers",
"[",
"... | Retrieve a qualifier type from the local repository of this class.
For a description of the parameters, see
:meth:`pywbem.WBEMConnection.GetQualifier`. | [
"Retrieve",
"a",
"qualifier",
"type",
"from",
"the",
"local",
"repository",
"of",
"this",
"class",
"."
] | e54ecb82c2211e289a268567443d60fdd489f1e4 | https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/mof_compiler.py#L2181-L2196 | train | 28,442 |
pywbem/pywbem | pywbem/mof_compiler.py | MOFWBEMConnection.SetQualifier | def SetQualifier(self, *args, **kwargs):
"""Create or modify a qualifier type in the local repository of this
class.
For a description of the parameters, see
:meth:`pywbem.WBEMConnection.SetQualifier`.
"""
qual = args[0] if args else kwargs['QualifierDeclaration']
try:
self.qualifiers[self.default_namespace][qual.name] = qual
except KeyError:
self.qualifiers[self.default_namespace] = \
NocaseDict({qual.name: qual}) | python | def SetQualifier(self, *args, **kwargs):
"""Create or modify a qualifier type in the local repository of this
class.
For a description of the parameters, see
:meth:`pywbem.WBEMConnection.SetQualifier`.
"""
qual = args[0] if args else kwargs['QualifierDeclaration']
try:
self.qualifiers[self.default_namespace][qual.name] = qual
except KeyError:
self.qualifiers[self.default_namespace] = \
NocaseDict({qual.name: qual}) | [
"def",
"SetQualifier",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"qual",
"=",
"args",
"[",
"0",
"]",
"if",
"args",
"else",
"kwargs",
"[",
"'QualifierDeclaration'",
"]",
"try",
":",
"self",
".",
"qualifiers",
"[",
"self",
".",
... | Create or modify a qualifier type in the local repository of this
class.
For a description of the parameters, see
:meth:`pywbem.WBEMConnection.SetQualifier`. | [
"Create",
"or",
"modify",
"a",
"qualifier",
"type",
"in",
"the",
"local",
"repository",
"of",
"this",
"class",
"."
] | e54ecb82c2211e289a268567443d60fdd489f1e4 | https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/mof_compiler.py#L2198-L2211 | train | 28,443 |
pywbem/pywbem | pywbem/mof_compiler.py | MOFWBEMConnection.rollback | def rollback(self, verbose=False):
"""
Remove classes and instances from the underlying repository, that have
been created in the local repository of this class.
Limitation: At this point, only classes and instances will be removed,
but not qualifiers.
"""
for ns, insts in self.instances.items():
insts.reverse()
for inst in insts:
try:
if verbose:
print(_format("Deleting instance {0}", inst.path))
self.conn.DeleteInstance(inst.path)
except CIMError as ce:
print(_format("Error deleting instance {0}", inst.path))
print(_format(" {0} {1}",
ce.status_code, ce.status_description))
for ns, cnames in self.class_names.items():
self.default_namespace = ns
cnames.reverse()
for cname in cnames:
try:
if verbose:
print(_format("Deleting class {0!A}:{1!A}",
ns, cname))
self.conn.DeleteClass(cname)
except CIMError as ce:
print(_format("Error deleting class {0!A}:{1!A}",
ns, cname))
print(_format(" {0} {1}",
ce.status_code, ce.status_description)) | python | def rollback(self, verbose=False):
"""
Remove classes and instances from the underlying repository, that have
been created in the local repository of this class.
Limitation: At this point, only classes and instances will be removed,
but not qualifiers.
"""
for ns, insts in self.instances.items():
insts.reverse()
for inst in insts:
try:
if verbose:
print(_format("Deleting instance {0}", inst.path))
self.conn.DeleteInstance(inst.path)
except CIMError as ce:
print(_format("Error deleting instance {0}", inst.path))
print(_format(" {0} {1}",
ce.status_code, ce.status_description))
for ns, cnames in self.class_names.items():
self.default_namespace = ns
cnames.reverse()
for cname in cnames:
try:
if verbose:
print(_format("Deleting class {0!A}:{1!A}",
ns, cname))
self.conn.DeleteClass(cname)
except CIMError as ce:
print(_format("Error deleting class {0!A}:{1!A}",
ns, cname))
print(_format(" {0} {1}",
ce.status_code, ce.status_description)) | [
"def",
"rollback",
"(",
"self",
",",
"verbose",
"=",
"False",
")",
":",
"for",
"ns",
",",
"insts",
"in",
"self",
".",
"instances",
".",
"items",
"(",
")",
":",
"insts",
".",
"reverse",
"(",
")",
"for",
"inst",
"in",
"insts",
":",
"try",
":",
"if"... | Remove classes and instances from the underlying repository, that have
been created in the local repository of this class.
Limitation: At this point, only classes and instances will be removed,
but not qualifiers. | [
"Remove",
"classes",
"and",
"instances",
"from",
"the",
"underlying",
"repository",
"that",
"have",
"been",
"created",
"in",
"the",
"local",
"repository",
"of",
"this",
"class",
"."
] | e54ecb82c2211e289a268567443d60fdd489f1e4 | https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/mof_compiler.py#L2222-L2254 | train | 28,444 |
pywbem/pywbem | pywbem/mof_compiler.py | MOFCompiler.compile_string | def compile_string(self, mof, ns, filename=None):
"""
Compile a string of MOF statements into a namespace of the associated
CIM repository.
Parameters:
mof (:term:`string`):
The string of MOF statements to be compiled.
ns (:term:`string`):
The name of the CIM namespace in the associated CIM repository
that is used for lookup of any dependent CIM elements, and that
is also the target of the compilation.
filename (:term:`string`):
The path name of the file that the MOF statements were read from.
This information is used only in compiler messages.
Raises:
IOError: MOF file not found.
MOFParseError: Syntax error in the MOF.
: Any exceptions that are raised by the repository connection class.
"""
lexer = self.lexer.clone()
lexer.parser = self.parser
try:
oldfile = self.parser.file
except AttributeError:
oldfile = None
self.parser.file = filename
try:
oldmof = self.parser.mof
except AttributeError:
oldmof = None
self.parser.mof = mof
self.parser.handle.default_namespace = ns
if ns not in self.parser.qualcache:
self.parser.qualcache[ns] = NocaseDict()
if ns not in self.parser.classnames:
self.parser.classnames[ns] = []
try:
# Call the parser. To generate detailed output of states
# add debug=... to following line where debug may be a
# constant (ex. 1) or may be a log definition, ex..
# log = logging.getLogger()
# logging.basicConfig(level=logging.DEBUG)
rv = self.parser.parse(mof, lexer=lexer)
self.parser.file = oldfile
self.parser.mof = oldmof
return rv
except MOFParseError as pe:
# Generate the error message into log and reraise error
self.parser.log(pe.get_err_msg())
raise
except CIMError as ce:
if hasattr(ce, 'file_line'):
self.parser.log(
_format("Fatal Error: {0}:{1}",
ce.file_line[0], ce.file_line[1]))
else:
self.parser.log("Fatal Error:")
description = _format(":{0}", ce.status_description) if \
ce.status_description else ""
self.parser.log(
_format("{0}{1}",
_statuscode2string(ce.status_code), description))
raise | python | def compile_string(self, mof, ns, filename=None):
"""
Compile a string of MOF statements into a namespace of the associated
CIM repository.
Parameters:
mof (:term:`string`):
The string of MOF statements to be compiled.
ns (:term:`string`):
The name of the CIM namespace in the associated CIM repository
that is used for lookup of any dependent CIM elements, and that
is also the target of the compilation.
filename (:term:`string`):
The path name of the file that the MOF statements were read from.
This information is used only in compiler messages.
Raises:
IOError: MOF file not found.
MOFParseError: Syntax error in the MOF.
: Any exceptions that are raised by the repository connection class.
"""
lexer = self.lexer.clone()
lexer.parser = self.parser
try:
oldfile = self.parser.file
except AttributeError:
oldfile = None
self.parser.file = filename
try:
oldmof = self.parser.mof
except AttributeError:
oldmof = None
self.parser.mof = mof
self.parser.handle.default_namespace = ns
if ns not in self.parser.qualcache:
self.parser.qualcache[ns] = NocaseDict()
if ns not in self.parser.classnames:
self.parser.classnames[ns] = []
try:
# Call the parser. To generate detailed output of states
# add debug=... to following line where debug may be a
# constant (ex. 1) or may be a log definition, ex..
# log = logging.getLogger()
# logging.basicConfig(level=logging.DEBUG)
rv = self.parser.parse(mof, lexer=lexer)
self.parser.file = oldfile
self.parser.mof = oldmof
return rv
except MOFParseError as pe:
# Generate the error message into log and reraise error
self.parser.log(pe.get_err_msg())
raise
except CIMError as ce:
if hasattr(ce, 'file_line'):
self.parser.log(
_format("Fatal Error: {0}:{1}",
ce.file_line[0], ce.file_line[1]))
else:
self.parser.log("Fatal Error:")
description = _format(":{0}", ce.status_description) if \
ce.status_description else ""
self.parser.log(
_format("{0}{1}",
_statuscode2string(ce.status_code), description))
raise | [
"def",
"compile_string",
"(",
"self",
",",
"mof",
",",
"ns",
",",
"filename",
"=",
"None",
")",
":",
"lexer",
"=",
"self",
".",
"lexer",
".",
"clone",
"(",
")",
"lexer",
".",
"parser",
"=",
"self",
".",
"parser",
"try",
":",
"oldfile",
"=",
"self",... | Compile a string of MOF statements into a namespace of the associated
CIM repository.
Parameters:
mof (:term:`string`):
The string of MOF statements to be compiled.
ns (:term:`string`):
The name of the CIM namespace in the associated CIM repository
that is used for lookup of any dependent CIM elements, and that
is also the target of the compilation.
filename (:term:`string`):
The path name of the file that the MOF statements were read from.
This information is used only in compiler messages.
Raises:
IOError: MOF file not found.
MOFParseError: Syntax error in the MOF.
: Any exceptions that are raised by the repository connection class. | [
"Compile",
"a",
"string",
"of",
"MOF",
"statements",
"into",
"a",
"namespace",
"of",
"the",
"associated",
"CIM",
"repository",
"."
] | e54ecb82c2211e289a268567443d60fdd489f1e4 | https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/mof_compiler.py#L2391-L2466 | train | 28,445 |
pywbem/pywbem | pywbem/mof_compiler.py | MOFCompiler.compile_file | def compile_file(self, filename, ns):
"""
Compile a MOF file into a namespace of the associated CIM repository.
Parameters:
filename (:term:`string`):
The path name of the MOF file containing the MOF statements to be
compiled.
ns (:term:`string`):
The name of the CIM namespace in the associated CIM repository
that is used for lookup of any dependent CIM elements, and that
is also the target of the compilation.
Raises:
IOError: MOF file not found.
MOFParseError: Syntax error in the MOF.
: Any exceptions that are raised by the repository connection class.
"""
if self.parser.verbose:
self.parser.log(
_format("Compiling file {0!A}", filename))
if not os.path.exists(filename):
# try to find in search path
rfilename = self.find_mof(os.path.basename(filename[:-4]).lower())
if rfilename is None:
raise IOError(
_format("No such file: {0!A}", filename))
filename = rfilename
with open(filename, "r") as f:
mof = f.read()
return self.compile_string(mof, ns, filename=filename) | python | def compile_file(self, filename, ns):
"""
Compile a MOF file into a namespace of the associated CIM repository.
Parameters:
filename (:term:`string`):
The path name of the MOF file containing the MOF statements to be
compiled.
ns (:term:`string`):
The name of the CIM namespace in the associated CIM repository
that is used for lookup of any dependent CIM elements, and that
is also the target of the compilation.
Raises:
IOError: MOF file not found.
MOFParseError: Syntax error in the MOF.
: Any exceptions that are raised by the repository connection class.
"""
if self.parser.verbose:
self.parser.log(
_format("Compiling file {0!A}", filename))
if not os.path.exists(filename):
# try to find in search path
rfilename = self.find_mof(os.path.basename(filename[:-4]).lower())
if rfilename is None:
raise IOError(
_format("No such file: {0!A}", filename))
filename = rfilename
with open(filename, "r") as f:
mof = f.read()
return self.compile_string(mof, ns, filename=filename) | [
"def",
"compile_file",
"(",
"self",
",",
"filename",
",",
"ns",
")",
":",
"if",
"self",
".",
"parser",
".",
"verbose",
":",
"self",
".",
"parser",
".",
"log",
"(",
"_format",
"(",
"\"Compiling file {0!A}\"",
",",
"filename",
")",
")",
"if",
"not",
"os"... | Compile a MOF file into a namespace of the associated CIM repository.
Parameters:
filename (:term:`string`):
The path name of the MOF file containing the MOF statements to be
compiled.
ns (:term:`string`):
The name of the CIM namespace in the associated CIM repository
that is used for lookup of any dependent CIM elements, and that
is also the target of the compilation.
Raises:
IOError: MOF file not found.
MOFParseError: Syntax error in the MOF.
: Any exceptions that are raised by the repository connection class. | [
"Compile",
"a",
"MOF",
"file",
"into",
"a",
"namespace",
"of",
"the",
"associated",
"CIM",
"repository",
"."
] | e54ecb82c2211e289a268567443d60fdd489f1e4 | https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/mof_compiler.py#L2468-L2505 | train | 28,446 |
pywbem/pywbem | pywbem/mof_compiler.py | MOFCompiler.find_mof | def find_mof(self, classname):
"""
Find the MOF file that defines a particular CIM class, in the search
path of the MOF compiler.
The MOF file is found based on its file name: It is assumed that the
base part of the file name is the CIM class name.
Example: The class "CIM_ComputerSystem" is expected to be in a file
"CIM_ComputerSystem.mof".
Parameters:
classame (:term:`string`):
The name of the CIM class to look up.
Returns:
:term:`string`: Path name of the MOF file defining the CIM class, if
it was found. `None`, if it was not found.
"""
classname = classname.lower()
for search in self.parser.search_paths:
for root, dummy_dirs, files in os.walk(search):
for file_ in files:
if file_.endswith('.mof') and \
file_[:-4].lower() == classname:
return os.path.join(root, file_)
return None | python | def find_mof(self, classname):
"""
Find the MOF file that defines a particular CIM class, in the search
path of the MOF compiler.
The MOF file is found based on its file name: It is assumed that the
base part of the file name is the CIM class name.
Example: The class "CIM_ComputerSystem" is expected to be in a file
"CIM_ComputerSystem.mof".
Parameters:
classame (:term:`string`):
The name of the CIM class to look up.
Returns:
:term:`string`: Path name of the MOF file defining the CIM class, if
it was found. `None`, if it was not found.
"""
classname = classname.lower()
for search in self.parser.search_paths:
for root, dummy_dirs, files in os.walk(search):
for file_ in files:
if file_.endswith('.mof') and \
file_[:-4].lower() == classname:
return os.path.join(root, file_)
return None | [
"def",
"find_mof",
"(",
"self",
",",
"classname",
")",
":",
"classname",
"=",
"classname",
".",
"lower",
"(",
")",
"for",
"search",
"in",
"self",
".",
"parser",
".",
"search_paths",
":",
"for",
"root",
",",
"dummy_dirs",
",",
"files",
"in",
"os",
".",
... | Find the MOF file that defines a particular CIM class, in the search
path of the MOF compiler.
The MOF file is found based on its file name: It is assumed that the
base part of the file name is the CIM class name.
Example: The class "CIM_ComputerSystem" is expected to be in a file
"CIM_ComputerSystem.mof".
Parameters:
classame (:term:`string`):
The name of the CIM class to look up.
Returns:
:term:`string`: Path name of the MOF file defining the CIM class, if
it was found. `None`, if it was not found. | [
"Find",
"the",
"MOF",
"file",
"that",
"defines",
"a",
"particular",
"CIM",
"class",
"in",
"the",
"search",
"path",
"of",
"the",
"MOF",
"compiler",
"."
] | e54ecb82c2211e289a268567443d60fdd489f1e4 | https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/mof_compiler.py#L2507-L2536 | train | 28,447 |
pywbem/pywbem | pywbem/_logging.py | configure_loggers_from_string | def configure_loggers_from_string(log_configuration_str,
log_filename=DEFAULT_LOG_FILENAME,
connection=None, propagate=False):
# pylint: disable=line-too-long
"""
Configure the pywbem loggers and optionally activate WBEM connections for
logging and setting a log detail level, from a log configuration string.
This is most useful in defining the loggers from a command line tool such
as pywbemcli so the complete logger configuration can be compressed into a
single command line string.
Parameters:
log_configuration_str (:term:`string`): The log configuration string, in
the following format::
log_specs := log_spec [ ',' log_spec ]
log_spec := logger_simple_name [ '=' [ log_dest ] [ ":" [ detail_level ]]]]
where:
* ``logger_simple_name``: Simple logger name. Must be one of the
strings in the :data:`~pywbem._logging.LOGGER_SIMPLE_NAMES` list.
* ``log_dest``: Log destination. Must be one of the strings in the
:data:`~pywbem._logging.LOG_DESTINATIONS` list. Default is
:data:`~pywbem._logging.DEFAULT_LOG_DESTINATION`.
* ``detail_level``: Log detail level. Must be one of the strings in the
:data:`~pywbem._logging.LOG_DETAIL_LEVELS` list. Default is
:data:`~pywbem._logging.DEFAULT_LOG_DETAIL_LEVEL`.
log_filename (:term:`string`):
Path name of the log file (required if any log destination is
`'file'`; otherwise ignored).
connection (:class:`~pywbem.WBEMConnection` or :class:`py:bool` or `None`):
WBEM connection(s) that should be affected for activation and for
setting the detail level.
If it is a :class:`py:bool`, the information for activating logging
and for the detail level of the affected loggers will be stored for
use by subsequently created :class:`~pywbem.WBEMConnection` objects.
A value of `True` will store the information to activate the
connections for logging, and will add the detail level for the
logger(s).
A value of `False` will reset the stored information for future
connections to be deactivated with no detail levels specified.
If it is a :class:`~pywbem.WBEMConnection` object, logging will be
activated for that WBEM connection only and the specified detail level
will be set for the affected pywbem loggers on the connection.
If `None`, no WBEM connection will be activated for logging.
propagate (:class:`py:bool`): Flag controlling whether the
affected pywbem logger should propagate log events to its
parent loggers.
Raises:
ValueError: Invalid input parameters (loggers remain unchanged).
Examples for `log_configuration_str`::
'api=stderr:summary' # Set 'pywbem.api' logger to stderr output with
# summary detail level.
'http=file' # Set 'pywbem.http' logger to file output with
# default detail level.
'api=stderr:summary' # Set 'pywbem.api' logger to file output with
# summary output level.
'all=file:1000' # Set both pywbem loggers to file output with
# a maximum of 1000 characters per log record.
'api=stderr,http=file' # Set 'pywbem.api' logger to stderr output and
# 'pywbem.http' logger to file output, both
# with default detail level.
""" # noqa: E501
# pylint: enable=line-too-long
log_specs = log_configuration_str.split(',')
for log_spec in log_specs:
spec_split = log_spec.strip('=').split("=")
simple_name = spec_split[0]
if not simple_name:
raise ValueError(
_format("Simple logger name missing in log spec: {0}",
log_spec))
if len(spec_split) == 1:
log_dest = DEFAULT_LOG_DESTINATION
detail_level = DEFAULT_LOG_DETAIL_LEVEL
elif len(spec_split) == 2:
val_split = spec_split[1].strip(':').split(':')
log_dest = val_split[0] or None
if len(val_split) == 1:
detail_level = DEFAULT_LOG_DETAIL_LEVEL
elif len(val_split) == 2:
detail_level = val_split[1] or None
else: # len(val_split) > 2
raise ValueError(
_format("Too many components separated by : in log spec: "
"{0}", log_spec))
else: # len(spec_split) > 2:
raise ValueError(
_format("Too many components separated by = in log spec: "
"{0}", log_spec))
# Convert to integer, if possible
if detail_level:
try:
detail_level = int(detail_level)
except ValueError:
pass
configure_logger(
simple_name,
log_dest=log_dest,
detail_level=detail_level,
log_filename=log_filename,
connection=connection,
propagate=propagate) | python | def configure_loggers_from_string(log_configuration_str,
log_filename=DEFAULT_LOG_FILENAME,
connection=None, propagate=False):
# pylint: disable=line-too-long
"""
Configure the pywbem loggers and optionally activate WBEM connections for
logging and setting a log detail level, from a log configuration string.
This is most useful in defining the loggers from a command line tool such
as pywbemcli so the complete logger configuration can be compressed into a
single command line string.
Parameters:
log_configuration_str (:term:`string`): The log configuration string, in
the following format::
log_specs := log_spec [ ',' log_spec ]
log_spec := logger_simple_name [ '=' [ log_dest ] [ ":" [ detail_level ]]]]
where:
* ``logger_simple_name``: Simple logger name. Must be one of the
strings in the :data:`~pywbem._logging.LOGGER_SIMPLE_NAMES` list.
* ``log_dest``: Log destination. Must be one of the strings in the
:data:`~pywbem._logging.LOG_DESTINATIONS` list. Default is
:data:`~pywbem._logging.DEFAULT_LOG_DESTINATION`.
* ``detail_level``: Log detail level. Must be one of the strings in the
:data:`~pywbem._logging.LOG_DETAIL_LEVELS` list. Default is
:data:`~pywbem._logging.DEFAULT_LOG_DETAIL_LEVEL`.
log_filename (:term:`string`):
Path name of the log file (required if any log destination is
`'file'`; otherwise ignored).
connection (:class:`~pywbem.WBEMConnection` or :class:`py:bool` or `None`):
WBEM connection(s) that should be affected for activation and for
setting the detail level.
If it is a :class:`py:bool`, the information for activating logging
and for the detail level of the affected loggers will be stored for
use by subsequently created :class:`~pywbem.WBEMConnection` objects.
A value of `True` will store the information to activate the
connections for logging, and will add the detail level for the
logger(s).
A value of `False` will reset the stored information for future
connections to be deactivated with no detail levels specified.
If it is a :class:`~pywbem.WBEMConnection` object, logging will be
activated for that WBEM connection only and the specified detail level
will be set for the affected pywbem loggers on the connection.
If `None`, no WBEM connection will be activated for logging.
propagate (:class:`py:bool`): Flag controlling whether the
affected pywbem logger should propagate log events to its
parent loggers.
Raises:
ValueError: Invalid input parameters (loggers remain unchanged).
Examples for `log_configuration_str`::
'api=stderr:summary' # Set 'pywbem.api' logger to stderr output with
# summary detail level.
'http=file' # Set 'pywbem.http' logger to file output with
# default detail level.
'api=stderr:summary' # Set 'pywbem.api' logger to file output with
# summary output level.
'all=file:1000' # Set both pywbem loggers to file output with
# a maximum of 1000 characters per log record.
'api=stderr,http=file' # Set 'pywbem.api' logger to stderr output and
# 'pywbem.http' logger to file output, both
# with default detail level.
""" # noqa: E501
# pylint: enable=line-too-long
log_specs = log_configuration_str.split(',')
for log_spec in log_specs:
spec_split = log_spec.strip('=').split("=")
simple_name = spec_split[0]
if not simple_name:
raise ValueError(
_format("Simple logger name missing in log spec: {0}",
log_spec))
if len(spec_split) == 1:
log_dest = DEFAULT_LOG_DESTINATION
detail_level = DEFAULT_LOG_DETAIL_LEVEL
elif len(spec_split) == 2:
val_split = spec_split[1].strip(':').split(':')
log_dest = val_split[0] or None
if len(val_split) == 1:
detail_level = DEFAULT_LOG_DETAIL_LEVEL
elif len(val_split) == 2:
detail_level = val_split[1] or None
else: # len(val_split) > 2
raise ValueError(
_format("Too many components separated by : in log spec: "
"{0}", log_spec))
else: # len(spec_split) > 2:
raise ValueError(
_format("Too many components separated by = in log spec: "
"{0}", log_spec))
# Convert to integer, if possible
if detail_level:
try:
detail_level = int(detail_level)
except ValueError:
pass
configure_logger(
simple_name,
log_dest=log_dest,
detail_level=detail_level,
log_filename=log_filename,
connection=connection,
propagate=propagate) | [
"def",
"configure_loggers_from_string",
"(",
"log_configuration_str",
",",
"log_filename",
"=",
"DEFAULT_LOG_FILENAME",
",",
"connection",
"=",
"None",
",",
"propagate",
"=",
"False",
")",
":",
"# pylint: disable=line-too-long",
"# noqa: E501",
"# pylint: enable=line-too-long... | Configure the pywbem loggers and optionally activate WBEM connections for
logging and setting a log detail level, from a log configuration string.
This is most useful in defining the loggers from a command line tool such
as pywbemcli so the complete logger configuration can be compressed into a
single command line string.
Parameters:
log_configuration_str (:term:`string`): The log configuration string, in
the following format::
log_specs := log_spec [ ',' log_spec ]
log_spec := logger_simple_name [ '=' [ log_dest ] [ ":" [ detail_level ]]]]
where:
* ``logger_simple_name``: Simple logger name. Must be one of the
strings in the :data:`~pywbem._logging.LOGGER_SIMPLE_NAMES` list.
* ``log_dest``: Log destination. Must be one of the strings in the
:data:`~pywbem._logging.LOG_DESTINATIONS` list. Default is
:data:`~pywbem._logging.DEFAULT_LOG_DESTINATION`.
* ``detail_level``: Log detail level. Must be one of the strings in the
:data:`~pywbem._logging.LOG_DETAIL_LEVELS` list. Default is
:data:`~pywbem._logging.DEFAULT_LOG_DETAIL_LEVEL`.
log_filename (:term:`string`):
Path name of the log file (required if any log destination is
`'file'`; otherwise ignored).
connection (:class:`~pywbem.WBEMConnection` or :class:`py:bool` or `None`):
WBEM connection(s) that should be affected for activation and for
setting the detail level.
If it is a :class:`py:bool`, the information for activating logging
and for the detail level of the affected loggers will be stored for
use by subsequently created :class:`~pywbem.WBEMConnection` objects.
A value of `True` will store the information to activate the
connections for logging, and will add the detail level for the
logger(s).
A value of `False` will reset the stored information for future
connections to be deactivated with no detail levels specified.
If it is a :class:`~pywbem.WBEMConnection` object, logging will be
activated for that WBEM connection only and the specified detail level
will be set for the affected pywbem loggers on the connection.
If `None`, no WBEM connection will be activated for logging.
propagate (:class:`py:bool`): Flag controlling whether the
affected pywbem logger should propagate log events to its
parent loggers.
Raises:
ValueError: Invalid input parameters (loggers remain unchanged).
Examples for `log_configuration_str`::
'api=stderr:summary' # Set 'pywbem.api' logger to stderr output with
# summary detail level.
'http=file' # Set 'pywbem.http' logger to file output with
# default detail level.
'api=stderr:summary' # Set 'pywbem.api' logger to file output with
# summary output level.
'all=file:1000' # Set both pywbem loggers to file output with
# a maximum of 1000 characters per log record.
'api=stderr,http=file' # Set 'pywbem.api' logger to stderr output and
# 'pywbem.http' logger to file output, both
# with default detail level. | [
"Configure",
"the",
"pywbem",
"loggers",
"and",
"optionally",
"activate",
"WBEM",
"connections",
"for",
"logging",
"and",
"setting",
"a",
"log",
"detail",
"level",
"from",
"a",
"log",
"configuration",
"string",
"."
] | e54ecb82c2211e289a268567443d60fdd489f1e4 | https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/_logging.py#L384-L506 | train | 28,448 |
pywbem/pywbem | examples/wbemcli_view_subscriptions.py | display_paths | def display_paths(instances, type_str):
"""Display the count and paths for the list of instances in instances."""
print('%ss: count=%s' % (type_str, len(instances),))
for path in [instance.path for instance in instances]:
print('%s: %s' % (type_str, path))
if len(instances):
print('') | python | def display_paths(instances, type_str):
"""Display the count and paths for the list of instances in instances."""
print('%ss: count=%s' % (type_str, len(instances),))
for path in [instance.path for instance in instances]:
print('%s: %s' % (type_str, path))
if len(instances):
print('') | [
"def",
"display_paths",
"(",
"instances",
",",
"type_str",
")",
":",
"print",
"(",
"'%ss: count=%s'",
"%",
"(",
"type_str",
",",
"len",
"(",
"instances",
")",
",",
")",
")",
"for",
"path",
"in",
"[",
"instance",
".",
"path",
"for",
"instance",
"in",
"i... | Display the count and paths for the list of instances in instances. | [
"Display",
"the",
"count",
"and",
"paths",
"for",
"the",
"list",
"of",
"instances",
"in",
"instances",
"."
] | e54ecb82c2211e289a268567443d60fdd489f1e4 | https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/examples/wbemcli_view_subscriptions.py#L9-L15 | train | 28,449 |
pywbem/pywbem | pywbem/cim_http.py | get_default_ca_certs | def get_default_ca_certs():
"""
Try to find out system path with ca certificates. This path is cached and
returned. If no path is found out, None is returned.
"""
# pylint: disable=protected-access
if not hasattr(get_default_ca_certs, '_path'):
for path in get_default_ca_cert_paths():
if os.path.exists(path):
get_default_ca_certs._path = path
break
else:
get_default_ca_certs._path = None
return get_default_ca_certs._path | python | def get_default_ca_certs():
"""
Try to find out system path with ca certificates. This path is cached and
returned. If no path is found out, None is returned.
"""
# pylint: disable=protected-access
if not hasattr(get_default_ca_certs, '_path'):
for path in get_default_ca_cert_paths():
if os.path.exists(path):
get_default_ca_certs._path = path
break
else:
get_default_ca_certs._path = None
return get_default_ca_certs._path | [
"def",
"get_default_ca_certs",
"(",
")",
":",
"# pylint: disable=protected-access",
"if",
"not",
"hasattr",
"(",
"get_default_ca_certs",
",",
"'_path'",
")",
":",
"for",
"path",
"in",
"get_default_ca_cert_paths",
"(",
")",
":",
"if",
"os",
".",
"path",
".",
"exi... | Try to find out system path with ca certificates. This path is cached and
returned. If no path is found out, None is returned. | [
"Try",
"to",
"find",
"out",
"system",
"path",
"with",
"ca",
"certificates",
".",
"This",
"path",
"is",
"cached",
"and",
"returned",
".",
"If",
"no",
"path",
"is",
"found",
"out",
"None",
"is",
"returned",
"."
] | e54ecb82c2211e289a268567443d60fdd489f1e4 | https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/cim_http.py#L342-L355 | train | 28,450 |
pywbem/pywbem | pywbem/cim_http.py | get_cimobject_header | def get_cimobject_header(obj):
"""
Return the value for the CIM-XML extension header field 'CIMObject', using
the given object.
This function implements the rules defined in DSP0200 section 6.3.7
"CIMObject". The format of the CIMObject value is similar but not identical
to a local WBEM URI (one without namespace type and authority), as defined
in DSP0207.
One difference is that DSP0207 requires a leading slash for a local WBEM
URI, e.g. '/root/cimv2:CIM_Class.k=1', while the CIMObject value has no
leading slash, e.g. 'root/cimv2:CIM_Class.k=1'.
Another difference is that the CIMObject value for instance paths has
provisions for an instance path without keys, while WBEM URIs do not have
that. Pywbem does not support that.
"""
# Local namespace path
if isinstance(obj, six.string_types):
return obj
# Local class path
if isinstance(obj, CIMClassName):
return obj.to_wbem_uri(format='cimobject')
# Local instance path
if isinstance(obj, CIMInstanceName):
return obj.to_wbem_uri(format='cimobject')
raise TypeError(
_format("Invalid object type {0} to generate CIMObject header value "
"from", type(obj))) | python | def get_cimobject_header(obj):
"""
Return the value for the CIM-XML extension header field 'CIMObject', using
the given object.
This function implements the rules defined in DSP0200 section 6.3.7
"CIMObject". The format of the CIMObject value is similar but not identical
to a local WBEM URI (one without namespace type and authority), as defined
in DSP0207.
One difference is that DSP0207 requires a leading slash for a local WBEM
URI, e.g. '/root/cimv2:CIM_Class.k=1', while the CIMObject value has no
leading slash, e.g. 'root/cimv2:CIM_Class.k=1'.
Another difference is that the CIMObject value for instance paths has
provisions for an instance path without keys, while WBEM URIs do not have
that. Pywbem does not support that.
"""
# Local namespace path
if isinstance(obj, six.string_types):
return obj
# Local class path
if isinstance(obj, CIMClassName):
return obj.to_wbem_uri(format='cimobject')
# Local instance path
if isinstance(obj, CIMInstanceName):
return obj.to_wbem_uri(format='cimobject')
raise TypeError(
_format("Invalid object type {0} to generate CIMObject header value "
"from", type(obj))) | [
"def",
"get_cimobject_header",
"(",
"obj",
")",
":",
"# Local namespace path",
"if",
"isinstance",
"(",
"obj",
",",
"six",
".",
"string_types",
")",
":",
"return",
"obj",
"# Local class path",
"if",
"isinstance",
"(",
"obj",
",",
"CIMClassName",
")",
":",
"ret... | Return the value for the CIM-XML extension header field 'CIMObject', using
the given object.
This function implements the rules defined in DSP0200 section 6.3.7
"CIMObject". The format of the CIMObject value is similar but not identical
to a local WBEM URI (one without namespace type and authority), as defined
in DSP0207.
One difference is that DSP0207 requires a leading slash for a local WBEM
URI, e.g. '/root/cimv2:CIM_Class.k=1', while the CIMObject value has no
leading slash, e.g. 'root/cimv2:CIM_Class.k=1'.
Another difference is that the CIMObject value for instance paths has
provisions for an instance path without keys, while WBEM URIs do not have
that. Pywbem does not support that. | [
"Return",
"the",
"value",
"for",
"the",
"CIM",
"-",
"XML",
"extension",
"header",
"field",
"CIMObject",
"using",
"the",
"given",
"object",
"."
] | e54ecb82c2211e289a268567443d60fdd489f1e4 | https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/cim_http.py#L1011-L1044 | train | 28,451 |
pywbem/pywbem | examples/explore.py | print_profile_info | def print_profile_info(org_vm, inst):
"""Print the registered org, name, version for the profile defined by
inst
"""
org = org_vm.tovalues(inst['RegisteredOrganization'])
name = inst['RegisteredName']
vers = inst['RegisteredVersion']
print(" %s %s Profile %s" % (org, name, vers)) | python | def print_profile_info(org_vm, inst):
"""Print the registered org, name, version for the profile defined by
inst
"""
org = org_vm.tovalues(inst['RegisteredOrganization'])
name = inst['RegisteredName']
vers = inst['RegisteredVersion']
print(" %s %s Profile %s" % (org, name, vers)) | [
"def",
"print_profile_info",
"(",
"org_vm",
",",
"inst",
")",
":",
"org",
"=",
"org_vm",
".",
"tovalues",
"(",
"inst",
"[",
"'RegisteredOrganization'",
"]",
")",
"name",
"=",
"inst",
"[",
"'RegisteredName'",
"]",
"vers",
"=",
"inst",
"[",
"'RegisteredVersion... | Print the registered org, name, version for the profile defined by
inst | [
"Print",
"the",
"registered",
"org",
"name",
"version",
"for",
"the",
"profile",
"defined",
"by",
"inst"
] | e54ecb82c2211e289a268567443d60fdd489f1e4 | https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/examples/explore.py#L8-L15 | train | 28,452 |
pywbem/pywbem | examples/explore.py | explore_server | def explore_server(server_url, username, password):
""" Demo of exploring a cim server for characteristics defined by
the server class
"""
print("WBEM server URL:\n %s" % server_url)
conn = WBEMConnection(server_url, (username, password),
no_verification=True)
server = WBEMServer(conn)
print("Brand:\n %s" % server.brand)
print("Version:\n %s" % server.version)
print("Interop namespace:\n %s" % server.interop_ns)
print("All namespaces:")
for ns in server.namespaces:
print(" %s" % ns)
print("Advertised management profiles:")
org_vm = ValueMapping.for_property(server, server.interop_ns,
'CIM_RegisteredProfile',
'RegisteredOrganization')
for inst in server.profiles:
print_profile_info(org_vm, inst)
indication_profiles = server.get_selected_profiles('DMTF', 'Indications')
print('Profiles for DMTF:Indications')
for inst in indication_profiles:
print_profile_info(org_vm, inst)
server_profiles = server.get_selected_profiles('SNIA', 'Server')
print('Profiles for SNIA:Server')
for inst in server_profiles:
print_profile_info(org_vm, inst)
# get Central Instances
for inst in indication_profiles:
org = org_vm.tovalues(inst['RegisteredOrganization'])
name = inst['RegisteredName']
vers = inst['RegisteredVersion']
print("Central instances for profile %s:%s:%s (component):" % \
(org, name, vers))
try:
ci_paths = server.get_central_instances(
inst.path,
"CIM_IndicationService", "CIM_System", ["CIM_HostedService"])
except Exception as exc:
print("Error: %s" % str(exc))
ci_paths = []
for ip in ci_paths:
print(" %s" % str(ip))
for inst in server_profiles:
org = org_vm.tovalues(inst['RegisteredOrganization'])
name = inst['RegisteredName']
vers = inst['RegisteredVersion']
print("Central instances for profile %s:%s:%s(autonomous):" %
(org, name, vers))
try:
ci_paths = server.get_central_instances(inst.path)
except Exception as exc:
print("Error: %s" % str(exc))
ci_paths = []
for ip in ci_paths:
print(" %s" % str(ip)) | python | def explore_server(server_url, username, password):
""" Demo of exploring a cim server for characteristics defined by
the server class
"""
print("WBEM server URL:\n %s" % server_url)
conn = WBEMConnection(server_url, (username, password),
no_verification=True)
server = WBEMServer(conn)
print("Brand:\n %s" % server.brand)
print("Version:\n %s" % server.version)
print("Interop namespace:\n %s" % server.interop_ns)
print("All namespaces:")
for ns in server.namespaces:
print(" %s" % ns)
print("Advertised management profiles:")
org_vm = ValueMapping.for_property(server, server.interop_ns,
'CIM_RegisteredProfile',
'RegisteredOrganization')
for inst in server.profiles:
print_profile_info(org_vm, inst)
indication_profiles = server.get_selected_profiles('DMTF', 'Indications')
print('Profiles for DMTF:Indications')
for inst in indication_profiles:
print_profile_info(org_vm, inst)
server_profiles = server.get_selected_profiles('SNIA', 'Server')
print('Profiles for SNIA:Server')
for inst in server_profiles:
print_profile_info(org_vm, inst)
# get Central Instances
for inst in indication_profiles:
org = org_vm.tovalues(inst['RegisteredOrganization'])
name = inst['RegisteredName']
vers = inst['RegisteredVersion']
print("Central instances for profile %s:%s:%s (component):" % \
(org, name, vers))
try:
ci_paths = server.get_central_instances(
inst.path,
"CIM_IndicationService", "CIM_System", ["CIM_HostedService"])
except Exception as exc:
print("Error: %s" % str(exc))
ci_paths = []
for ip in ci_paths:
print(" %s" % str(ip))
for inst in server_profiles:
org = org_vm.tovalues(inst['RegisteredOrganization'])
name = inst['RegisteredName']
vers = inst['RegisteredVersion']
print("Central instances for profile %s:%s:%s(autonomous):" %
(org, name, vers))
try:
ci_paths = server.get_central_instances(inst.path)
except Exception as exc:
print("Error: %s" % str(exc))
ci_paths = []
for ip in ci_paths:
print(" %s" % str(ip)) | [
"def",
"explore_server",
"(",
"server_url",
",",
"username",
",",
"password",
")",
":",
"print",
"(",
"\"WBEM server URL:\\n %s\"",
"%",
"server_url",
")",
"conn",
"=",
"WBEMConnection",
"(",
"server_url",
",",
"(",
"username",
",",
"password",
")",
",",
"no_... | Demo of exploring a cim server for characteristics defined by
the server class | [
"Demo",
"of",
"exploring",
"a",
"cim",
"server",
"for",
"characteristics",
"defined",
"by",
"the",
"server",
"class"
] | e54ecb82c2211e289a268567443d60fdd489f1e4 | https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/examples/explore.py#L17-L85 | train | 28,453 |
pywbem/pywbem | pywbem/_server.py | WBEMServer.create_namespace | def create_namespace(self, namespace):
"""
Create the specified CIM namespace in the WBEM server and
update this WBEMServer object to reflect the new namespace
there.
This method attempts the following approaches for creating the
namespace, in order, until an approach succeeds:
1. Namespace creation as described in the WBEM Server profile
(:term:`DSP1092`) via CIM method
`CIM_WBEMServer.CreateWBEMServerNamespace()`.
This is a new standard approach that is not likely to be
widely implemented yet.
2. Issuing the `CreateInstance` operation using the CIM class
representing namespaces ('PG_Namespace' for OpenPegasus,
and 'CIM_Namespace' otherwise), against the Interop namespace.
This approach is typically supported in WBEM servers that
support the creation of CIM namespaces. This approach is
similar to the approach described in :term:`DSP0200`.
Creating namespaces using the `__Namespace` pseudo-class has been
deprecated already in DSP0200 1.1.0 (released in 01/2003), and pywbem
does not implement that approach.
Parameters:
namespace (:term:`string`): CIM namespace name. Must not be `None`.
The namespace may contain leading and a trailing slash, both of
which will be ignored.
Returns:
:term:`unicode string`: The specified CIM namespace name in its
standard format (i.e. without leading or trailing slash characters).
Raises:
Exceptions raised by :class:`~pywbem.WBEMConnection`.
ModelError: An issue with the model implemented by the WBEM server.
CIMError: CIM_ERR_ALREADY_EXISTS, Specified namespace already
exists in the WBEM server.
CIMError: CIM_ERR_NOT_FOUND, Interop namespace could not be
determined.
CIMError: CIM_ERR_NOT_FOUND, Unexpected number of
`CIM_ObjectManager` instances.
CIMError: CIM_ERR_FAILED, Unexpected number of
central instances of WBEM Server profile.
"""
std_namespace = _ensure_unicode(namespace.strip('/'))
ws_profiles = self.get_selected_profiles('DMTF', 'WBEM Server')
if ws_profiles:
# Use approach 1: Method defined in WBEM Server profile
ws_profiles_sorted = sorted(
ws_profiles, key=lambda prof: prof['RegisteredVersion'])
ws_profile_inst = ws_profiles_sorted[-1] # latest version
ws_insts = self.get_central_instances(ws_profile_inst.path)
if len(ws_insts) != 1:
raise CIMError(
CIM_ERR_FAILED,
_format("Unexpected number of central instances of WBEM "
"Server profile: {0!A}",
[i.path for i in ws_insts]))
ws_inst = ws_insts[0]
ns_inst = CIMInstance('CIM_WBEMServerNamespace')
ns_inst['Name'] = std_namespace
try:
(ret_val, out_params) = self._conn.InvokeMethod(
MethodName="CreateWBEMServerNamespace",
ObjectName=ws_inst.path,
Params=[('NamespaceTemplate', ns_inst)])
except CIMError as exc:
if exc.status_code in (CIM_ERR_METHOD_NOT_FOUND,
CIM_ERR_METHOD_NOT_AVAILABLE,
CIM_ERR_NOT_SUPPORTED):
# Method is not implemented.
# CIM_ERR_NOT_SUPPORTED is not an official status code for
# this situation, but is used by some implementations.
pass # try next approach
else:
raise
else:
if ret_val != 0:
raise CIMError(
CIM_ERR_FAILED,
_format("The CreateWBEMServerNamespace() method is "
"implemented but failed: {0}",
out_params['Errors']))
else:
# Use approach 2: CreateInstance of CIM class for namespaces
# For OpenPegasus, use 'PG_Namespace' class to account for issue
# when using 'CIM_Namespace'. See OpenPegasus bug 10112:
# https://bugzilla.openpegasus.org/show_bug.cgi?id=10112
if self.brand == "OpenPegasus":
ns_classname = 'PG_Namespace'
else:
ns_classname = 'CIM_Namespace'
ns_inst = CIMInstance(ns_classname)
# OpenPegasus requires this property to be True, in order to
# allow schema updates in the namespace.
if self.brand == "OpenPegasus":
ns_inst['SchemaUpdatesAllowed'] = True
ns_inst['Name'] = std_namespace
# DSP0200 is not clear as to whether just "Name" or all key
# properties need to be provided. For now, we provide all key
# properties.
# OpenPegasus requires all key properties, and it re-creates the
# 5 key properties besides "Name" so that the returned instance
# path may differ from the key properties provided.
ns_inst['CreationClassName'] = ns_classname
ns_inst['ObjectManagerName'] = self.cimom_inst['Name']
ns_inst['ObjectManagerCreationClassName'] = \
self.cimom_inst['CreationClassName']
ns_inst['SystemName'] = self.cimom_inst['SystemName']
ns_inst['SystemCreationClassName'] = \
self.cimom_inst['SystemCreationClassName']
self.conn.CreateInstance(ns_inst, namespace=self.interop_ns)
# Refresh the list of namespaces in this object to include the one
# we just created.
# Namespace creation is such a rare operation that we can afford
# the extra namespace determination operations, to make sure we
# really have the new namespace.
self._determine_namespaces()
return std_namespace | python | def create_namespace(self, namespace):
"""
Create the specified CIM namespace in the WBEM server and
update this WBEMServer object to reflect the new namespace
there.
This method attempts the following approaches for creating the
namespace, in order, until an approach succeeds:
1. Namespace creation as described in the WBEM Server profile
(:term:`DSP1092`) via CIM method
`CIM_WBEMServer.CreateWBEMServerNamespace()`.
This is a new standard approach that is not likely to be
widely implemented yet.
2. Issuing the `CreateInstance` operation using the CIM class
representing namespaces ('PG_Namespace' for OpenPegasus,
and 'CIM_Namespace' otherwise), against the Interop namespace.
This approach is typically supported in WBEM servers that
support the creation of CIM namespaces. This approach is
similar to the approach described in :term:`DSP0200`.
Creating namespaces using the `__Namespace` pseudo-class has been
deprecated already in DSP0200 1.1.0 (released in 01/2003), and pywbem
does not implement that approach.
Parameters:
namespace (:term:`string`): CIM namespace name. Must not be `None`.
The namespace may contain leading and a trailing slash, both of
which will be ignored.
Returns:
:term:`unicode string`: The specified CIM namespace name in its
standard format (i.e. without leading or trailing slash characters).
Raises:
Exceptions raised by :class:`~pywbem.WBEMConnection`.
ModelError: An issue with the model implemented by the WBEM server.
CIMError: CIM_ERR_ALREADY_EXISTS, Specified namespace already
exists in the WBEM server.
CIMError: CIM_ERR_NOT_FOUND, Interop namespace could not be
determined.
CIMError: CIM_ERR_NOT_FOUND, Unexpected number of
`CIM_ObjectManager` instances.
CIMError: CIM_ERR_FAILED, Unexpected number of
central instances of WBEM Server profile.
"""
std_namespace = _ensure_unicode(namespace.strip('/'))
ws_profiles = self.get_selected_profiles('DMTF', 'WBEM Server')
if ws_profiles:
# Use approach 1: Method defined in WBEM Server profile
ws_profiles_sorted = sorted(
ws_profiles, key=lambda prof: prof['RegisteredVersion'])
ws_profile_inst = ws_profiles_sorted[-1] # latest version
ws_insts = self.get_central_instances(ws_profile_inst.path)
if len(ws_insts) != 1:
raise CIMError(
CIM_ERR_FAILED,
_format("Unexpected number of central instances of WBEM "
"Server profile: {0!A}",
[i.path for i in ws_insts]))
ws_inst = ws_insts[0]
ns_inst = CIMInstance('CIM_WBEMServerNamespace')
ns_inst['Name'] = std_namespace
try:
(ret_val, out_params) = self._conn.InvokeMethod(
MethodName="CreateWBEMServerNamespace",
ObjectName=ws_inst.path,
Params=[('NamespaceTemplate', ns_inst)])
except CIMError as exc:
if exc.status_code in (CIM_ERR_METHOD_NOT_FOUND,
CIM_ERR_METHOD_NOT_AVAILABLE,
CIM_ERR_NOT_SUPPORTED):
# Method is not implemented.
# CIM_ERR_NOT_SUPPORTED is not an official status code for
# this situation, but is used by some implementations.
pass # try next approach
else:
raise
else:
if ret_val != 0:
raise CIMError(
CIM_ERR_FAILED,
_format("The CreateWBEMServerNamespace() method is "
"implemented but failed: {0}",
out_params['Errors']))
else:
# Use approach 2: CreateInstance of CIM class for namespaces
# For OpenPegasus, use 'PG_Namespace' class to account for issue
# when using 'CIM_Namespace'. See OpenPegasus bug 10112:
# https://bugzilla.openpegasus.org/show_bug.cgi?id=10112
if self.brand == "OpenPegasus":
ns_classname = 'PG_Namespace'
else:
ns_classname = 'CIM_Namespace'
ns_inst = CIMInstance(ns_classname)
# OpenPegasus requires this property to be True, in order to
# allow schema updates in the namespace.
if self.brand == "OpenPegasus":
ns_inst['SchemaUpdatesAllowed'] = True
ns_inst['Name'] = std_namespace
# DSP0200 is not clear as to whether just "Name" or all key
# properties need to be provided. For now, we provide all key
# properties.
# OpenPegasus requires all key properties, and it re-creates the
# 5 key properties besides "Name" so that the returned instance
# path may differ from the key properties provided.
ns_inst['CreationClassName'] = ns_classname
ns_inst['ObjectManagerName'] = self.cimom_inst['Name']
ns_inst['ObjectManagerCreationClassName'] = \
self.cimom_inst['CreationClassName']
ns_inst['SystemName'] = self.cimom_inst['SystemName']
ns_inst['SystemCreationClassName'] = \
self.cimom_inst['SystemCreationClassName']
self.conn.CreateInstance(ns_inst, namespace=self.interop_ns)
# Refresh the list of namespaces in this object to include the one
# we just created.
# Namespace creation is such a rare operation that we can afford
# the extra namespace determination operations, to make sure we
# really have the new namespace.
self._determine_namespaces()
return std_namespace | [
"def",
"create_namespace",
"(",
"self",
",",
"namespace",
")",
":",
"std_namespace",
"=",
"_ensure_unicode",
"(",
"namespace",
".",
"strip",
"(",
"'/'",
")",
")",
"ws_profiles",
"=",
"self",
".",
"get_selected_profiles",
"(",
"'DMTF'",
",",
"'WBEM Server'",
")... | Create the specified CIM namespace in the WBEM server and
update this WBEMServer object to reflect the new namespace
there.
This method attempts the following approaches for creating the
namespace, in order, until an approach succeeds:
1. Namespace creation as described in the WBEM Server profile
(:term:`DSP1092`) via CIM method
`CIM_WBEMServer.CreateWBEMServerNamespace()`.
This is a new standard approach that is not likely to be
widely implemented yet.
2. Issuing the `CreateInstance` operation using the CIM class
representing namespaces ('PG_Namespace' for OpenPegasus,
and 'CIM_Namespace' otherwise), against the Interop namespace.
This approach is typically supported in WBEM servers that
support the creation of CIM namespaces. This approach is
similar to the approach described in :term:`DSP0200`.
Creating namespaces using the `__Namespace` pseudo-class has been
deprecated already in DSP0200 1.1.0 (released in 01/2003), and pywbem
does not implement that approach.
Parameters:
namespace (:term:`string`): CIM namespace name. Must not be `None`.
The namespace may contain leading and a trailing slash, both of
which will be ignored.
Returns:
:term:`unicode string`: The specified CIM namespace name in its
standard format (i.e. without leading or trailing slash characters).
Raises:
Exceptions raised by :class:`~pywbem.WBEMConnection`.
ModelError: An issue with the model implemented by the WBEM server.
CIMError: CIM_ERR_ALREADY_EXISTS, Specified namespace already
exists in the WBEM server.
CIMError: CIM_ERR_NOT_FOUND, Interop namespace could not be
determined.
CIMError: CIM_ERR_NOT_FOUND, Unexpected number of
`CIM_ObjectManager` instances.
CIMError: CIM_ERR_FAILED, Unexpected number of
central instances of WBEM Server profile. | [
"Create",
"the",
"specified",
"CIM",
"namespace",
"in",
"the",
"WBEM",
"server",
"and",
"update",
"this",
"WBEMServer",
"object",
"to",
"reflect",
"the",
"new",
"namespace",
"there",
"."
] | e54ecb82c2211e289a268567443d60fdd489f1e4 | https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/_server.py#L388-L531 | train | 28,454 |
pywbem/pywbem | pywbem/_server.py | WBEMServer.delete_namespace | def delete_namespace(self, namespace):
"""
Delete the specified CIM namespace in the WBEM server and
update this WBEMServer object to reflect the removed namespace
there.
The specified namespace must be empty (i.e. must not contain any
classes, instances, or qualifier types.
This method attempts the following approaches for deleting the
namespace, in order, until an approach succeeds:
1. Issuing the `DeleteInstance` operation using the CIM class
representing namespaces ('PG_Namespace' for OpenPegasus,
and 'CIM_Namespace' otherwise), against the Interop namespace.
This approach is typically supported in WBEM servers that
support the creation of CIM namespaces. This approach is
similar to the approach described in :term:`DSP0200`.
The approach described in the WBEM Server profile (:term:`DSP1092`) via
deleting the `CIM_WBEMServerNamespace` instance is not implemented
because that would also delete any classes, instances, and
qualifier types in the namespace.
Deleting namespaces using the `__Namespace` pseudo-class has been
deprecated already in DSP0200 1.1.0 (released in 01/2003), and pywbem
does not implement that approach.
Parameters:
namespace (:term:`string`): CIM namespace name. Must not be `None`.
The namespace may contain leading and a trailing slash, both of
which will be ignored.
Returns:
:term:`unicode string`: The specified CIM namespace name in its
standard format (i.e. without leading or trailing slash characters).
Raises:
Exceptions raised by :class:`~pywbem.WBEMConnection`.
ModelError: An issue with the model implemented by the WBEM server.
CIMError: CIM_ERR_NOT_FOUND, Specified namespace does not exist.
CIMError: CIM_ERR_NAMESPACE_NOT_EMPTY, Specified namespace is not
empty.
Additional CIM errors.
"""
std_namespace = _ensure_unicode(namespace.strip('/'))
# Use approach 1: DeleteInstance of CIM class for namespaces
# Refresh the list of namespaces in this object to make sure
# it is up to date.
self._determine_namespaces()
if std_namespace not in self.namespaces:
raise CIMError(
CIM_ERR_NOT_FOUND,
_format("Specified namespace does not exist: {0!A}",
std_namespace),
conn_id=self.conn.conn_id)
ns_path = None
for p in self.namespace_paths:
if p.keybindings['Name'] == std_namespace:
ns_path = p
assert ns_path is not None
# Ensure the namespace is empty. We do not check for instances, because
# classes are a prerequisite for instances, so if no classes exist,
# no instances will exist.
# WBEM servers that do not support class operations (e.g. SFCB) will
# raise a CIMError with status CIM_ERR_NOT_SUPPORTED.
class_paths = self.conn.EnumerateClassNames(
namespace=std_namespace, ClassName=None, DeepInheritance=False)
quals = self.conn.EnumerateQualifiers(namespace=std_namespace)
if class_paths or quals:
raise CIMError(
CIM_ERR_NAMESPACE_NOT_EMPTY,
_format("Specified namespace {0!A} is not empty; it contains "
"{1} top-level classes and {2} qualifier types",
std_namespace, len(class_paths), len(quals)),
conn_id=self.conn.conn_id)
self.conn.DeleteInstance(ns_path)
# Refresh the list of namespaces in this object to remove the one
# we just deleted.
self._determine_namespaces()
return std_namespace | python | def delete_namespace(self, namespace):
"""
Delete the specified CIM namespace in the WBEM server and
update this WBEMServer object to reflect the removed namespace
there.
The specified namespace must be empty (i.e. must not contain any
classes, instances, or qualifier types.
This method attempts the following approaches for deleting the
namespace, in order, until an approach succeeds:
1. Issuing the `DeleteInstance` operation using the CIM class
representing namespaces ('PG_Namespace' for OpenPegasus,
and 'CIM_Namespace' otherwise), against the Interop namespace.
This approach is typically supported in WBEM servers that
support the creation of CIM namespaces. This approach is
similar to the approach described in :term:`DSP0200`.
The approach described in the WBEM Server profile (:term:`DSP1092`) via
deleting the `CIM_WBEMServerNamespace` instance is not implemented
because that would also delete any classes, instances, and
qualifier types in the namespace.
Deleting namespaces using the `__Namespace` pseudo-class has been
deprecated already in DSP0200 1.1.0 (released in 01/2003), and pywbem
does not implement that approach.
Parameters:
namespace (:term:`string`): CIM namespace name. Must not be `None`.
The namespace may contain leading and a trailing slash, both of
which will be ignored.
Returns:
:term:`unicode string`: The specified CIM namespace name in its
standard format (i.e. without leading or trailing slash characters).
Raises:
Exceptions raised by :class:`~pywbem.WBEMConnection`.
ModelError: An issue with the model implemented by the WBEM server.
CIMError: CIM_ERR_NOT_FOUND, Specified namespace does not exist.
CIMError: CIM_ERR_NAMESPACE_NOT_EMPTY, Specified namespace is not
empty.
Additional CIM errors.
"""
std_namespace = _ensure_unicode(namespace.strip('/'))
# Use approach 1: DeleteInstance of CIM class for namespaces
# Refresh the list of namespaces in this object to make sure
# it is up to date.
self._determine_namespaces()
if std_namespace not in self.namespaces:
raise CIMError(
CIM_ERR_NOT_FOUND,
_format("Specified namespace does not exist: {0!A}",
std_namespace),
conn_id=self.conn.conn_id)
ns_path = None
for p in self.namespace_paths:
if p.keybindings['Name'] == std_namespace:
ns_path = p
assert ns_path is not None
# Ensure the namespace is empty. We do not check for instances, because
# classes are a prerequisite for instances, so if no classes exist,
# no instances will exist.
# WBEM servers that do not support class operations (e.g. SFCB) will
# raise a CIMError with status CIM_ERR_NOT_SUPPORTED.
class_paths = self.conn.EnumerateClassNames(
namespace=std_namespace, ClassName=None, DeepInheritance=False)
quals = self.conn.EnumerateQualifiers(namespace=std_namespace)
if class_paths or quals:
raise CIMError(
CIM_ERR_NAMESPACE_NOT_EMPTY,
_format("Specified namespace {0!A} is not empty; it contains "
"{1} top-level classes and {2} qualifier types",
std_namespace, len(class_paths), len(quals)),
conn_id=self.conn.conn_id)
self.conn.DeleteInstance(ns_path)
# Refresh the list of namespaces in this object to remove the one
# we just deleted.
self._determine_namespaces()
return std_namespace | [
"def",
"delete_namespace",
"(",
"self",
",",
"namespace",
")",
":",
"std_namespace",
"=",
"_ensure_unicode",
"(",
"namespace",
".",
"strip",
"(",
"'/'",
")",
")",
"# Use approach 1: DeleteInstance of CIM class for namespaces",
"# Refresh the list of namespaces in this object ... | Delete the specified CIM namespace in the WBEM server and
update this WBEMServer object to reflect the removed namespace
there.
The specified namespace must be empty (i.e. must not contain any
classes, instances, or qualifier types.
This method attempts the following approaches for deleting the
namespace, in order, until an approach succeeds:
1. Issuing the `DeleteInstance` operation using the CIM class
representing namespaces ('PG_Namespace' for OpenPegasus,
and 'CIM_Namespace' otherwise), against the Interop namespace.
This approach is typically supported in WBEM servers that
support the creation of CIM namespaces. This approach is
similar to the approach described in :term:`DSP0200`.
The approach described in the WBEM Server profile (:term:`DSP1092`) via
deleting the `CIM_WBEMServerNamespace` instance is not implemented
because that would also delete any classes, instances, and
qualifier types in the namespace.
Deleting namespaces using the `__Namespace` pseudo-class has been
deprecated already in DSP0200 1.1.0 (released in 01/2003), and pywbem
does not implement that approach.
Parameters:
namespace (:term:`string`): CIM namespace name. Must not be `None`.
The namespace may contain leading and a trailing slash, both of
which will be ignored.
Returns:
:term:`unicode string`: The specified CIM namespace name in its
standard format (i.e. without leading or trailing slash characters).
Raises:
Exceptions raised by :class:`~pywbem.WBEMConnection`.
ModelError: An issue with the model implemented by the WBEM server.
CIMError: CIM_ERR_NOT_FOUND, Specified namespace does not exist.
CIMError: CIM_ERR_NAMESPACE_NOT_EMPTY, Specified namespace is not
empty.
Additional CIM errors. | [
"Delete",
"the",
"specified",
"CIM",
"namespace",
"in",
"the",
"WBEM",
"server",
"and",
"update",
"this",
"WBEMServer",
"object",
"to",
"reflect",
"the",
"removed",
"namespace",
"there",
"."
] | e54ecb82c2211e289a268567443d60fdd489f1e4 | https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/_server.py#L533-L626 | train | 28,455 |
pywbem/pywbem | pywbem/_server.py | WBEMServer._traverse | def _traverse(self, start_paths, traversal_path):
"""
Traverse a multi-hop traversal path from a list of start instance
paths, and return the resulting list of instance paths.
Parameters:
start_paths (list of CIMInstanceName): Instance paths to start
traversal from.
traversal_path (list of string): Traversal hops, where the list
contains pairs of items: association class name, far end class
name. Example: a 2-hop traversal is represented as
`['A1', 'C1', 'A2', 'C2']`.
Returns:
List of CIMInstanceName: Instances at the far end of the traversal.
"""
assert len(traversal_path) >= 2
assoc_class = traversal_path[0]
far_class = traversal_path[1]
total_next_paths = []
for path in start_paths:
next_paths = self._conn.AssociatorNames(
ObjectName=path,
AssocClass=assoc_class,
ResultClass=far_class)
total_next_paths.extend(next_paths)
traversal_path = traversal_path[2:]
if traversal_path:
total_next_paths = self._traverse(total_next_paths, traversal_path)
return total_next_paths | python | def _traverse(self, start_paths, traversal_path):
"""
Traverse a multi-hop traversal path from a list of start instance
paths, and return the resulting list of instance paths.
Parameters:
start_paths (list of CIMInstanceName): Instance paths to start
traversal from.
traversal_path (list of string): Traversal hops, where the list
contains pairs of items: association class name, far end class
name. Example: a 2-hop traversal is represented as
`['A1', 'C1', 'A2', 'C2']`.
Returns:
List of CIMInstanceName: Instances at the far end of the traversal.
"""
assert len(traversal_path) >= 2
assoc_class = traversal_path[0]
far_class = traversal_path[1]
total_next_paths = []
for path in start_paths:
next_paths = self._conn.AssociatorNames(
ObjectName=path,
AssocClass=assoc_class,
ResultClass=far_class)
total_next_paths.extend(next_paths)
traversal_path = traversal_path[2:]
if traversal_path:
total_next_paths = self._traverse(total_next_paths, traversal_path)
return total_next_paths | [
"def",
"_traverse",
"(",
"self",
",",
"start_paths",
",",
"traversal_path",
")",
":",
"assert",
"len",
"(",
"traversal_path",
")",
">=",
"2",
"assoc_class",
"=",
"traversal_path",
"[",
"0",
"]",
"far_class",
"=",
"traversal_path",
"[",
"1",
"]",
"total_next_... | Traverse a multi-hop traversal path from a list of start instance
paths, and return the resulting list of instance paths.
Parameters:
start_paths (list of CIMInstanceName): Instance paths to start
traversal from.
traversal_path (list of string): Traversal hops, where the list
contains pairs of items: association class name, far end class
name. Example: a 2-hop traversal is represented as
`['A1', 'C1', 'A2', 'C2']`.
Returns:
List of CIMInstanceName: Instances at the far end of the traversal. | [
"Traverse",
"a",
"multi",
"-",
"hop",
"traversal",
"path",
"from",
"a",
"list",
"of",
"start",
"instance",
"paths",
"and",
"return",
"the",
"resulting",
"list",
"of",
"instance",
"paths",
"."
] | e54ecb82c2211e289a268567443d60fdd489f1e4 | https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/_server.py#L1031-L1060 | train | 28,456 |
pywbem/pywbem | pywbem/_server.py | WBEMServer._validate_interop_ns | def _validate_interop_ns(self, interop_ns):
"""
Validate whether the specified Interop namespace exists in the WBEM
server, by communicating with it.
If the specified Interop namespace exists, this method sets the
:attr:`interop_ns` property of this object to that namespace and
returns.
Otherwise, it raises an exception.
Parameters:
interop_ns (:term:`string`):
Name of the Interop namespace to be validated.
Raises:
Exceptions raised by :class:`~pywbem.WBEMConnection`.
"""
test_classname = 'CIM_Namespace'
try:
self._conn.EnumerateInstanceNames(test_classname,
namespace=interop_ns)
except CIMError as exc:
# We tolerate it if the WBEM server does not implement this class,
# as long as it does not return CIM_ERR_INVALID_NAMESPACE.
if exc.status_code in (CIM_ERR_INVALID_CLASS,
CIM_ERR_NOT_FOUND):
pass
else:
raise
self._interop_ns = interop_ns | python | def _validate_interop_ns(self, interop_ns):
"""
Validate whether the specified Interop namespace exists in the WBEM
server, by communicating with it.
If the specified Interop namespace exists, this method sets the
:attr:`interop_ns` property of this object to that namespace and
returns.
Otherwise, it raises an exception.
Parameters:
interop_ns (:term:`string`):
Name of the Interop namespace to be validated.
Raises:
Exceptions raised by :class:`~pywbem.WBEMConnection`.
"""
test_classname = 'CIM_Namespace'
try:
self._conn.EnumerateInstanceNames(test_classname,
namespace=interop_ns)
except CIMError as exc:
# We tolerate it if the WBEM server does not implement this class,
# as long as it does not return CIM_ERR_INVALID_NAMESPACE.
if exc.status_code in (CIM_ERR_INVALID_CLASS,
CIM_ERR_NOT_FOUND):
pass
else:
raise
self._interop_ns = interop_ns | [
"def",
"_validate_interop_ns",
"(",
"self",
",",
"interop_ns",
")",
":",
"test_classname",
"=",
"'CIM_Namespace'",
"try",
":",
"self",
".",
"_conn",
".",
"EnumerateInstanceNames",
"(",
"test_classname",
",",
"namespace",
"=",
"interop_ns",
")",
"except",
"CIMError... | Validate whether the specified Interop namespace exists in the WBEM
server, by communicating with it.
If the specified Interop namespace exists, this method sets the
:attr:`interop_ns` property of this object to that namespace and
returns.
Otherwise, it raises an exception.
Parameters:
interop_ns (:term:`string`):
Name of the Interop namespace to be validated.
Raises:
Exceptions raised by :class:`~pywbem.WBEMConnection`. | [
"Validate",
"whether",
"the",
"specified",
"Interop",
"namespace",
"exists",
"in",
"the",
"WBEM",
"server",
"by",
"communicating",
"with",
"it",
"."
] | e54ecb82c2211e289a268567443d60fdd489f1e4 | https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/_server.py#L1117-L1148 | train | 28,457 |
pywbem/pywbem | pywbem/_server.py | WBEMServer._determine_profiles | def _determine_profiles(self):
"""
Determine the WBEM management profiles advertised by the WBEM server,
by communicating with it and enumerating the instances of
`CIM_RegisteredProfile`.
If the profiles could be determined, this method sets the
:attr:`profiles` property of this object to the list of
`CIM_RegisteredProfile` instances (as :class:`~pywbem.CIMInstance`
objects), and returns.
Otherwise, it raises an exception.
Raises:
Exceptions raised by :class:`~pywbem.WBEMConnection`.
CIMError: CIM_ERR_NOT_FOUND, Interop namespace could not be
determined.
"""
mp_insts = self._conn.EnumerateInstances("CIM_RegisteredProfile",
namespace=self.interop_ns)
self._profiles = mp_insts | python | def _determine_profiles(self):
"""
Determine the WBEM management profiles advertised by the WBEM server,
by communicating with it and enumerating the instances of
`CIM_RegisteredProfile`.
If the profiles could be determined, this method sets the
:attr:`profiles` property of this object to the list of
`CIM_RegisteredProfile` instances (as :class:`~pywbem.CIMInstance`
objects), and returns.
Otherwise, it raises an exception.
Raises:
Exceptions raised by :class:`~pywbem.WBEMConnection`.
CIMError: CIM_ERR_NOT_FOUND, Interop namespace could not be
determined.
"""
mp_insts = self._conn.EnumerateInstances("CIM_RegisteredProfile",
namespace=self.interop_ns)
self._profiles = mp_insts | [
"def",
"_determine_profiles",
"(",
"self",
")",
":",
"mp_insts",
"=",
"self",
".",
"_conn",
".",
"EnumerateInstances",
"(",
"\"CIM_RegisteredProfile\"",
",",
"namespace",
"=",
"self",
".",
"interop_ns",
")",
"self",
".",
"_profiles",
"=",
"mp_insts"
] | Determine the WBEM management profiles advertised by the WBEM server,
by communicating with it and enumerating the instances of
`CIM_RegisteredProfile`.
If the profiles could be determined, this method sets the
:attr:`profiles` property of this object to the list of
`CIM_RegisteredProfile` instances (as :class:`~pywbem.CIMInstance`
objects), and returns.
Otherwise, it raises an exception.
Raises:
Exceptions raised by :class:`~pywbem.WBEMConnection`.
CIMError: CIM_ERR_NOT_FOUND, Interop namespace could not be
determined. | [
"Determine",
"the",
"WBEM",
"management",
"profiles",
"advertised",
"by",
"the",
"WBEM",
"server",
"by",
"communicating",
"with",
"it",
"and",
"enumerating",
"the",
"instances",
"of",
"CIM_RegisteredProfile",
"."
] | e54ecb82c2211e289a268567443d60fdd489f1e4 | https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/_server.py#L1300-L1320 | train | 28,458 |
pywbem/pywbem | pywbem/_recorder.py | _represent_undefined | def _represent_undefined(self, data):
"""Raises flag for objects that cannot be represented"""
raise RepresenterError(
_format("Cannot represent an object: {0!A} of type: {1}; "
"yaml_representers: {2!A}, "
"yaml_multi_representers: {3!A}",
data, type(data), self.yaml_representers.keys(),
self.yaml_multi_representers.keys())) | python | def _represent_undefined(self, data):
"""Raises flag for objects that cannot be represented"""
raise RepresenterError(
_format("Cannot represent an object: {0!A} of type: {1}; "
"yaml_representers: {2!A}, "
"yaml_multi_representers: {3!A}",
data, type(data), self.yaml_representers.keys(),
self.yaml_multi_representers.keys())) | [
"def",
"_represent_undefined",
"(",
"self",
",",
"data",
")",
":",
"raise",
"RepresenterError",
"(",
"_format",
"(",
"\"Cannot represent an object: {0!A} of type: {1}; \"",
"\"yaml_representers: {2!A}, \"",
"\"yaml_multi_representers: {3!A}\"",
",",
"data",
",",
"type",
"(",
... | Raises flag for objects that cannot be represented | [
"Raises",
"flag",
"for",
"objects",
"that",
"cannot",
"be",
"represented"
] | e54ecb82c2211e289a268567443d60fdd489f1e4 | https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/_recorder.py#L133-L140 | train | 28,459 |
pywbem/pywbem | pywbem/_recorder.py | BaseOperationRecorder.open_file | def open_file(filename, file_mode='w'):
"""
A static convenience function that performs the open of the recorder
file correctly for different versions of Python.
*New in pywbem 0.10.*
This covers the issue where the file should be opened in text mode but
that is done differently in Python 2 and Python 3.
The returned file-like object must be closed by the caller.
Parameters:
filename(:term:`string`):
Name of the file where the recorder output will be written
file_mode(:term:`string`):
Optional file mode. The default is 'w' which overwrites any
existing file. if 'a' is used, the data is appended to any
existing file.
Returns:
File-like object.
Example::
recorder = TestClientRecorder(...)
recorder_file = recorder.open_file('recorder.log')
. . . # Perform WBEM operations using the recorder
recorder_file.close()
"""
if six.PY2:
# Open with codecs to define text mode
return codecs.open(filename, mode=file_mode, encoding='utf-8')
return open(filename, file_mode, encoding='utf8') | python | def open_file(filename, file_mode='w'):
"""
A static convenience function that performs the open of the recorder
file correctly for different versions of Python.
*New in pywbem 0.10.*
This covers the issue where the file should be opened in text mode but
that is done differently in Python 2 and Python 3.
The returned file-like object must be closed by the caller.
Parameters:
filename(:term:`string`):
Name of the file where the recorder output will be written
file_mode(:term:`string`):
Optional file mode. The default is 'w' which overwrites any
existing file. if 'a' is used, the data is appended to any
existing file.
Returns:
File-like object.
Example::
recorder = TestClientRecorder(...)
recorder_file = recorder.open_file('recorder.log')
. . . # Perform WBEM operations using the recorder
recorder_file.close()
"""
if six.PY2:
# Open with codecs to define text mode
return codecs.open(filename, mode=file_mode, encoding='utf-8')
return open(filename, file_mode, encoding='utf8') | [
"def",
"open_file",
"(",
"filename",
",",
"file_mode",
"=",
"'w'",
")",
":",
"if",
"six",
".",
"PY2",
":",
"# Open with codecs to define text mode",
"return",
"codecs",
".",
"open",
"(",
"filename",
",",
"mode",
"=",
"file_mode",
",",
"encoding",
"=",
"'utf-... | A static convenience function that performs the open of the recorder
file correctly for different versions of Python.
*New in pywbem 0.10.*
This covers the issue where the file should be opened in text mode but
that is done differently in Python 2 and Python 3.
The returned file-like object must be closed by the caller.
Parameters:
filename(:term:`string`):
Name of the file where the recorder output will be written
file_mode(:term:`string`):
Optional file mode. The default is 'w' which overwrites any
existing file. if 'a' is used, the data is appended to any
existing file.
Returns:
File-like object.
Example::
recorder = TestClientRecorder(...)
recorder_file = recorder.open_file('recorder.log')
. . . # Perform WBEM operations using the recorder
recorder_file.close() | [
"A",
"static",
"convenience",
"function",
"that",
"performs",
"the",
"open",
"of",
"the",
"recorder",
"file",
"correctly",
"for",
"different",
"versions",
"of",
"Python",
"."
] | e54ecb82c2211e289a268567443d60fdd489f1e4 | https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/_recorder.py#L352-L391 | train | 28,460 |
pywbem/pywbem | pywbem/_recorder.py | BaseOperationRecorder.reset | def reset(self, pull_op=None):
"""Reset all the attributes in the class. This also allows setting
the pull_op attribute that defines whether the operation is to be
a traditional or pull operation.
This does NOT reset _conn.id as that exists through the life of
the connection.
"""
self._pywbem_method = None
self._pywbem_args = None
self._pywbem_result_ret = None
self._pywbem_result_exc = None
self._http_request_version = None
self._http_request_url = None
self._http_request_target = None
self._http_request_method = None
self._http_request_headers = None
self._http_request_payload = None
self._http_response_version = None
self._http_response_status = None
self._http_response_reason = None
self._http_response_headers = None
self._http_response_payload = None
self._pull_op = pull_op | python | def reset(self, pull_op=None):
"""Reset all the attributes in the class. This also allows setting
the pull_op attribute that defines whether the operation is to be
a traditional or pull operation.
This does NOT reset _conn.id as that exists through the life of
the connection.
"""
self._pywbem_method = None
self._pywbem_args = None
self._pywbem_result_ret = None
self._pywbem_result_exc = None
self._http_request_version = None
self._http_request_url = None
self._http_request_target = None
self._http_request_method = None
self._http_request_headers = None
self._http_request_payload = None
self._http_response_version = None
self._http_response_status = None
self._http_response_reason = None
self._http_response_headers = None
self._http_response_payload = None
self._pull_op = pull_op | [
"def",
"reset",
"(",
"self",
",",
"pull_op",
"=",
"None",
")",
":",
"self",
".",
"_pywbem_method",
"=",
"None",
"self",
".",
"_pywbem_args",
"=",
"None",
"self",
".",
"_pywbem_result_ret",
"=",
"None",
"self",
".",
"_pywbem_result_exc",
"=",
"None",
"self"... | Reset all the attributes in the class. This also allows setting
the pull_op attribute that defines whether the operation is to be
a traditional or pull operation.
This does NOT reset _conn.id as that exists through the life of
the connection. | [
"Reset",
"all",
"the",
"attributes",
"in",
"the",
"class",
".",
"This",
"also",
"allows",
"setting",
"the",
"pull_op",
"attribute",
"that",
"defines",
"whether",
"the",
"operation",
"is",
"to",
"be",
"a",
"traditional",
"or",
"pull",
"operation",
".",
"This"... | e54ecb82c2211e289a268567443d60fdd489f1e4 | https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/_recorder.py#L393-L418 | train | 28,461 |
pywbem/pywbem | pywbem/_recorder.py | BaseOperationRecorder.stage_pywbem_args | def stage_pywbem_args(self, method, **kwargs):
"""
Set requst method and all args.
Normally called before the cmd is executed to record request
parameters
"""
# pylint: disable=attribute-defined-outside-init
self._pywbem_method = method
self._pywbem_args = kwargs | python | def stage_pywbem_args(self, method, **kwargs):
"""
Set requst method and all args.
Normally called before the cmd is executed to record request
parameters
"""
# pylint: disable=attribute-defined-outside-init
self._pywbem_method = method
self._pywbem_args = kwargs | [
"def",
"stage_pywbem_args",
"(",
"self",
",",
"method",
",",
"*",
"*",
"kwargs",
")",
":",
"# pylint: disable=attribute-defined-outside-init",
"self",
".",
"_pywbem_method",
"=",
"method",
"self",
".",
"_pywbem_args",
"=",
"kwargs"
] | Set requst method and all args.
Normally called before the cmd is executed to record request
parameters | [
"Set",
"requst",
"method",
"and",
"all",
"args",
".",
"Normally",
"called",
"before",
"the",
"cmd",
"is",
"executed",
"to",
"record",
"request",
"parameters"
] | e54ecb82c2211e289a268567443d60fdd489f1e4 | https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/_recorder.py#L427-L435 | train | 28,462 |
pywbem/pywbem | pywbem/_recorder.py | BaseOperationRecorder.stage_pywbem_result | def stage_pywbem_result(self, ret, exc):
""" Set Result return info or exception info"""
# pylint: disable=attribute-defined-outside-init
self._pywbem_result_ret = ret
self._pywbem_result_exc = exc | python | def stage_pywbem_result(self, ret, exc):
""" Set Result return info or exception info"""
# pylint: disable=attribute-defined-outside-init
self._pywbem_result_ret = ret
self._pywbem_result_exc = exc | [
"def",
"stage_pywbem_result",
"(",
"self",
",",
"ret",
",",
"exc",
")",
":",
"# pylint: disable=attribute-defined-outside-init",
"self",
".",
"_pywbem_result_ret",
"=",
"ret",
"self",
".",
"_pywbem_result_exc",
"=",
"exc"
] | Set Result return info or exception info | [
"Set",
"Result",
"return",
"info",
"or",
"exception",
"info"
] | e54ecb82c2211e289a268567443d60fdd489f1e4 | https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/_recorder.py#L437-L441 | train | 28,463 |
pywbem/pywbem | pywbem/_recorder.py | BaseOperationRecorder.stage_http_request | def stage_http_request(self, conn_id, version, url, target, method, headers,
payload):
"""Set request HTTP information including url, headers, etc."""
# pylint: disable=attribute-defined-outside-init
self._http_request_version = version
self._http_request_conn_id = conn_id
self._http_request_url = url
self._http_request_target = target
self._http_request_method = method
self._http_request_headers = headers
self._http_request_payload = payload | python | def stage_http_request(self, conn_id, version, url, target, method, headers,
payload):
"""Set request HTTP information including url, headers, etc."""
# pylint: disable=attribute-defined-outside-init
self._http_request_version = version
self._http_request_conn_id = conn_id
self._http_request_url = url
self._http_request_target = target
self._http_request_method = method
self._http_request_headers = headers
self._http_request_payload = payload | [
"def",
"stage_http_request",
"(",
"self",
",",
"conn_id",
",",
"version",
",",
"url",
",",
"target",
",",
"method",
",",
"headers",
",",
"payload",
")",
":",
"# pylint: disable=attribute-defined-outside-init",
"self",
".",
"_http_request_version",
"=",
"version",
... | Set request HTTP information including url, headers, etc. | [
"Set",
"request",
"HTTP",
"information",
"including",
"url",
"headers",
"etc",
"."
] | e54ecb82c2211e289a268567443d60fdd489f1e4 | https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/_recorder.py#L443-L453 | train | 28,464 |
pywbem/pywbem | pywbem/_recorder.py | BaseOperationRecorder.stage_http_response1 | def stage_http_response1(self, conn_id, version, status, reason, headers):
"""Set response http info including headers, status, etc.
conn_id unused here. Used in log"""
# pylint: disable=attribute-defined-outside-init
self._http_response_version = version
self._http_response_status = status
self._http_response_reason = reason
self._http_response_headers = headers | python | def stage_http_response1(self, conn_id, version, status, reason, headers):
"""Set response http info including headers, status, etc.
conn_id unused here. Used in log"""
# pylint: disable=attribute-defined-outside-init
self._http_response_version = version
self._http_response_status = status
self._http_response_reason = reason
self._http_response_headers = headers | [
"def",
"stage_http_response1",
"(",
"self",
",",
"conn_id",
",",
"version",
",",
"status",
",",
"reason",
",",
"headers",
")",
":",
"# pylint: disable=attribute-defined-outside-init",
"self",
".",
"_http_response_version",
"=",
"version",
"self",
".",
"_http_response_... | Set response http info including headers, status, etc.
conn_id unused here. Used in log | [
"Set",
"response",
"http",
"info",
"including",
"headers",
"status",
"etc",
".",
"conn_id",
"unused",
"here",
".",
"Used",
"in",
"log"
] | e54ecb82c2211e289a268567443d60fdd489f1e4 | https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/_recorder.py#L456-L463 | train | 28,465 |
pywbem/pywbem | pywbem/_recorder.py | BaseOperationRecorder.record_staged | def record_staged(self):
"""Encode staged information on request and result to output"""
if self.enabled:
pwargs = OpArgs(
self._pywbem_method,
self._pywbem_args)
pwresult = OpResult(
self._pywbem_result_ret,
self._pywbem_result_exc)
httpreq = HttpRequest(
self._http_request_version,
self._http_request_url,
self._http_request_target,
self._http_request_method,
self._http_request_headers,
self._http_request_payload)
httpresp = HttpResponse(
self._http_response_version,
self._http_response_status,
self._http_response_reason,
self._http_response_headers,
self._http_response_payload)
self.record(pwargs, pwresult, httpreq, httpresp) | python | def record_staged(self):
"""Encode staged information on request and result to output"""
if self.enabled:
pwargs = OpArgs(
self._pywbem_method,
self._pywbem_args)
pwresult = OpResult(
self._pywbem_result_ret,
self._pywbem_result_exc)
httpreq = HttpRequest(
self._http_request_version,
self._http_request_url,
self._http_request_target,
self._http_request_method,
self._http_request_headers,
self._http_request_payload)
httpresp = HttpResponse(
self._http_response_version,
self._http_response_status,
self._http_response_reason,
self._http_response_headers,
self._http_response_payload)
self.record(pwargs, pwresult, httpreq, httpresp) | [
"def",
"record_staged",
"(",
"self",
")",
":",
"if",
"self",
".",
"enabled",
":",
"pwargs",
"=",
"OpArgs",
"(",
"self",
".",
"_pywbem_method",
",",
"self",
".",
"_pywbem_args",
")",
"pwresult",
"=",
"OpResult",
"(",
"self",
".",
"_pywbem_result_ret",
",",
... | Encode staged information on request and result to output | [
"Encode",
"staged",
"information",
"on",
"request",
"and",
"result",
"to",
"output"
] | e54ecb82c2211e289a268567443d60fdd489f1e4 | https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/_recorder.py#L470-L492 | train | 28,466 |
pywbem/pywbem | pywbem/_recorder.py | LogOperationRecorder.set_detail_level | def set_detail_level(self, detail_levels):
"""
Sets the detail levels from the input dictionary in detail_levels.
"""
if detail_levels is None:
return
self.detail_levels = detail_levels
if 'api' in detail_levels:
self.api_detail_level = detail_levels['api']
if 'http' in detail_levels:
self.http_detail_level = detail_levels['http']
if isinstance(self.api_detail_level, int):
self.api_maxlen = self.api_detail_level
if isinstance(self.http_detail_level, int):
self.http_maxlen = self.http_detail_level | python | def set_detail_level(self, detail_levels):
"""
Sets the detail levels from the input dictionary in detail_levels.
"""
if detail_levels is None:
return
self.detail_levels = detail_levels
if 'api' in detail_levels:
self.api_detail_level = detail_levels['api']
if 'http' in detail_levels:
self.http_detail_level = detail_levels['http']
if isinstance(self.api_detail_level, int):
self.api_maxlen = self.api_detail_level
if isinstance(self.http_detail_level, int):
self.http_maxlen = self.http_detail_level | [
"def",
"set_detail_level",
"(",
"self",
",",
"detail_levels",
")",
":",
"if",
"detail_levels",
"is",
"None",
":",
"return",
"self",
".",
"detail_levels",
"=",
"detail_levels",
"if",
"'api'",
"in",
"detail_levels",
":",
"self",
".",
"api_detail_level",
"=",
"de... | Sets the detail levels from the input dictionary in detail_levels. | [
"Sets",
"the",
"detail",
"levels",
"from",
"the",
"input",
"dictionary",
"in",
"detail_levels",
"."
] | e54ecb82c2211e289a268567443d60fdd489f1e4 | https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/_recorder.py#L596-L611 | train | 28,467 |
pywbem/pywbem | pywbem/_recorder.py | LogOperationRecorder.stage_pywbem_args | def stage_pywbem_args(self, method, **kwargs):
"""
Log request method and all args.
Normally called before the cmd is executed to record request
parameters.
This method does not support the summary detail_level because
that seems to add little info to the log that is not also in the
response.
"""
# pylint: disable=attribute-defined-outside-init
self._pywbem_method = method
if self.enabled and self.api_detail_level is not None and \
self.apilogger.isEnabledFor(logging.DEBUG):
# TODO: future bypassed code to only ouput name and method if the
# detail is summary. We are not doing this because this is
# effectively the same information in the response so the only
# additional infomation is the time stamp.
# if self.api_detail_level == summary:
# self.apilogger.debug('Request:%s %s', self._conn_id, method)
# return
# Order kwargs. Note that this is done automatically starting
# with python 3.6
kwstr = ', '.join([('{0}={1!r}'.format(key, kwargs[key]))
for key in sorted(six.iterkeys(kwargs))])
if self.api_maxlen and (len(kwstr) > self.api_maxlen):
kwstr = kwstr[:self.api_maxlen] + '...'
# pylint: disable=bad-continuation
self.apilogger.debug('Request:%s %s(%s)', self._conn_id, method,
kwstr) | python | def stage_pywbem_args(self, method, **kwargs):
"""
Log request method and all args.
Normally called before the cmd is executed to record request
parameters.
This method does not support the summary detail_level because
that seems to add little info to the log that is not also in the
response.
"""
# pylint: disable=attribute-defined-outside-init
self._pywbem_method = method
if self.enabled and self.api_detail_level is not None and \
self.apilogger.isEnabledFor(logging.DEBUG):
# TODO: future bypassed code to only ouput name and method if the
# detail is summary. We are not doing this because this is
# effectively the same information in the response so the only
# additional infomation is the time stamp.
# if self.api_detail_level == summary:
# self.apilogger.debug('Request:%s %s', self._conn_id, method)
# return
# Order kwargs. Note that this is done automatically starting
# with python 3.6
kwstr = ', '.join([('{0}={1!r}'.format(key, kwargs[key]))
for key in sorted(six.iterkeys(kwargs))])
if self.api_maxlen and (len(kwstr) > self.api_maxlen):
kwstr = kwstr[:self.api_maxlen] + '...'
# pylint: disable=bad-continuation
self.apilogger.debug('Request:%s %s(%s)', self._conn_id, method,
kwstr) | [
"def",
"stage_pywbem_args",
"(",
"self",
",",
"method",
",",
"*",
"*",
"kwargs",
")",
":",
"# pylint: disable=attribute-defined-outside-init",
"self",
".",
"_pywbem_method",
"=",
"method",
"if",
"self",
".",
"enabled",
"and",
"self",
".",
"api_detail_level",
"is",... | Log request method and all args.
Normally called before the cmd is executed to record request
parameters.
This method does not support the summary detail_level because
that seems to add little info to the log that is not also in the
response. | [
"Log",
"request",
"method",
"and",
"all",
"args",
".",
"Normally",
"called",
"before",
"the",
"cmd",
"is",
"executed",
"to",
"record",
"request",
"parameters",
".",
"This",
"method",
"does",
"not",
"support",
"the",
"summary",
"detail_level",
"because",
"that"... | e54ecb82c2211e289a268567443d60fdd489f1e4 | https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/_recorder.py#L645-L677 | train | 28,468 |
pywbem/pywbem | pywbem/_recorder.py | LogOperationRecorder.stage_pywbem_result | def stage_pywbem_result(self, ret, exc):
"""
Log result return or exception parameter. This method provides varied
type of formatting based on the detail_level parameter and the
data in ret.
"""
def format_result(ret, max_len):
""" format ret as repr while clipping it to max_len if
max_len is not None.
"""
# Format the 'summary' and 'paths' detail_levels
if self.api_detail_level == 'summary': # pylint: disable=R1705
if isinstance(ret, list):
if ret:
ret_type = type(ret[0]).__name__ if ret else ""
return _format("list of {0}; count={1}",
ret_type, len(ret))
return "Empty"
ret_type = type(ret).__name__
if hasattr(ret, 'classname'):
name = ret.classname
elif hasattr(ret, 'name'):
name = ret.name
else:
name = ""
return _format("{0} {1}", ret_type, name)
elif self.api_detail_level == 'paths':
if isinstance(ret, list):
if ret:
if hasattr(ret[0], 'path'):
result_fmt = ', '.join(
[_format("{0!A}", str(p.path)) for p in ret])
else:
result_fmt = _format("{0!A}", ret)
else:
result_fmt = ''
else:
if hasattr(ret, 'path'):
result_fmt = _format("{0!A}", str(ret.path))
else:
result_fmt = _format("{0!A}", ret)
else:
result_fmt = _format("{0!A}", ret)
if max_len and (len(result_fmt) > max_len):
result_fmt = result_fmt[:max_len] + '...'
return result_fmt
if self.enabled and self.api_detail_level is not None and \
self.apilogger.isEnabledFor(logging.DEBUG):
if exc: # format exception
# exceptions are always either all or reduced length
result = format_result(
_format("{0}({1})", exc.__class__.__name__, exc),
self.api_maxlen)
return_type = 'Exception'
else: # format result
# test if type is tuple (subclass of tuple but not type tuple)
# pylint: disable=unidiomatic-typecheck
qrc = ""
# format open/pull response
if isinstance(ret, tuple) and \
type(ret) is not tuple: # pylint: disable=C0123
try: # test if field instances or paths
rtn_data = ret.instances
data_str = 'instances'
except AttributeError:
rtn_data = ret.paths
data_str = 'paths'
try: # test for query_result_class
qrc = _format(
", query_result_class={0}",
ret.query_result_class)
except AttributeError:
pass
result = _format(
"{0}(context={1}, eos={2}{3}, {4}={5})",
type(ret).__name__, ret.context, ret.eos, qrc,
data_str, format_result(rtn_data, self.api_maxlen))
# format enumerate response except not open/pull
elif isinstance(ret, list):
try: # test for query_result_class
qrc = _format(
", query_result_class={0}",
ret.query_result_class)
except AttributeError:
pass
ret_fmtd = format_result(ret, self.api_maxlen)
result = _format("{0}{1}", qrc, ret_fmtd)
# format single return object
else:
result = format_result(ret, self.api_maxlen)
return_type = 'Return'
self.apilogger.debug('%s:%s %s(%s)', return_type, self._conn_id,
self._pywbem_method, result) | python | def stage_pywbem_result(self, ret, exc):
"""
Log result return or exception parameter. This method provides varied
type of formatting based on the detail_level parameter and the
data in ret.
"""
def format_result(ret, max_len):
""" format ret as repr while clipping it to max_len if
max_len is not None.
"""
# Format the 'summary' and 'paths' detail_levels
if self.api_detail_level == 'summary': # pylint: disable=R1705
if isinstance(ret, list):
if ret:
ret_type = type(ret[0]).__name__ if ret else ""
return _format("list of {0}; count={1}",
ret_type, len(ret))
return "Empty"
ret_type = type(ret).__name__
if hasattr(ret, 'classname'):
name = ret.classname
elif hasattr(ret, 'name'):
name = ret.name
else:
name = ""
return _format("{0} {1}", ret_type, name)
elif self.api_detail_level == 'paths':
if isinstance(ret, list):
if ret:
if hasattr(ret[0], 'path'):
result_fmt = ', '.join(
[_format("{0!A}", str(p.path)) for p in ret])
else:
result_fmt = _format("{0!A}", ret)
else:
result_fmt = ''
else:
if hasattr(ret, 'path'):
result_fmt = _format("{0!A}", str(ret.path))
else:
result_fmt = _format("{0!A}", ret)
else:
result_fmt = _format("{0!A}", ret)
if max_len and (len(result_fmt) > max_len):
result_fmt = result_fmt[:max_len] + '...'
return result_fmt
if self.enabled and self.api_detail_level is not None and \
self.apilogger.isEnabledFor(logging.DEBUG):
if exc: # format exception
# exceptions are always either all or reduced length
result = format_result(
_format("{0}({1})", exc.__class__.__name__, exc),
self.api_maxlen)
return_type = 'Exception'
else: # format result
# test if type is tuple (subclass of tuple but not type tuple)
# pylint: disable=unidiomatic-typecheck
qrc = ""
# format open/pull response
if isinstance(ret, tuple) and \
type(ret) is not tuple: # pylint: disable=C0123
try: # test if field instances or paths
rtn_data = ret.instances
data_str = 'instances'
except AttributeError:
rtn_data = ret.paths
data_str = 'paths'
try: # test for query_result_class
qrc = _format(
", query_result_class={0}",
ret.query_result_class)
except AttributeError:
pass
result = _format(
"{0}(context={1}, eos={2}{3}, {4}={5})",
type(ret).__name__, ret.context, ret.eos, qrc,
data_str, format_result(rtn_data, self.api_maxlen))
# format enumerate response except not open/pull
elif isinstance(ret, list):
try: # test for query_result_class
qrc = _format(
", query_result_class={0}",
ret.query_result_class)
except AttributeError:
pass
ret_fmtd = format_result(ret, self.api_maxlen)
result = _format("{0}{1}", qrc, ret_fmtd)
# format single return object
else:
result = format_result(ret, self.api_maxlen)
return_type = 'Return'
self.apilogger.debug('%s:%s %s(%s)', return_type, self._conn_id,
self._pywbem_method, result) | [
"def",
"stage_pywbem_result",
"(",
"self",
",",
"ret",
",",
"exc",
")",
":",
"def",
"format_result",
"(",
"ret",
",",
"max_len",
")",
":",
"\"\"\" format ret as repr while clipping it to max_len if\n max_len is not None.\n \"\"\"",
"# Format the 'summa... | Log result return or exception parameter. This method provides varied
type of formatting based on the detail_level parameter and the
data in ret. | [
"Log",
"result",
"return",
"or",
"exception",
"parameter",
".",
"This",
"method",
"provides",
"varied",
"type",
"of",
"formatting",
"based",
"on",
"the",
"detail_level",
"parameter",
"and",
"the",
"data",
"in",
"ret",
"."
] | e54ecb82c2211e289a268567443d60fdd489f1e4 | https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/_recorder.py#L679-L784 | train | 28,469 |
pywbem/pywbem | pywbem/_recorder.py | LogOperationRecorder.stage_http_request | def stage_http_request(self, conn_id, version, url, target, method, headers,
payload):
"""Log request HTTP information including url, headers, etc."""
if self.enabled and self.http_detail_level is not None and \
self.httplogger.isEnabledFor(logging.DEBUG):
# pylint: disable=attribute-defined-outside-init
# if Auth header, mask data
if 'Authorization' in headers:
authtype, cred = headers['Authorization'].split(' ')
headers['Authorization'] = _format(
"{0} {1}", authtype, 'X' * len(cred))
header_str = ' '.join('{0}:{1!r}'.format(k, v)
for k, v in headers.items())
if self.http_detail_level == 'summary':
upayload = ""
elif isinstance(payload, six.binary_type):
upayload = payload.decode('utf-8')
else:
upayload = payload
if self.http_maxlen and (len(payload) > self.http_maxlen):
upayload = upayload[:self.http_maxlen] + '...'
self.httplogger.debug('Request:%s %s %s %s %s %s\n %s',
conn_id, method, target, version, url,
header_str, upayload) | python | def stage_http_request(self, conn_id, version, url, target, method, headers,
payload):
"""Log request HTTP information including url, headers, etc."""
if self.enabled and self.http_detail_level is not None and \
self.httplogger.isEnabledFor(logging.DEBUG):
# pylint: disable=attribute-defined-outside-init
# if Auth header, mask data
if 'Authorization' in headers:
authtype, cred = headers['Authorization'].split(' ')
headers['Authorization'] = _format(
"{0} {1}", authtype, 'X' * len(cred))
header_str = ' '.join('{0}:{1!r}'.format(k, v)
for k, v in headers.items())
if self.http_detail_level == 'summary':
upayload = ""
elif isinstance(payload, six.binary_type):
upayload = payload.decode('utf-8')
else:
upayload = payload
if self.http_maxlen and (len(payload) > self.http_maxlen):
upayload = upayload[:self.http_maxlen] + '...'
self.httplogger.debug('Request:%s %s %s %s %s %s\n %s',
conn_id, method, target, version, url,
header_str, upayload) | [
"def",
"stage_http_request",
"(",
"self",
",",
"conn_id",
",",
"version",
",",
"url",
",",
"target",
",",
"method",
",",
"headers",
",",
"payload",
")",
":",
"if",
"self",
".",
"enabled",
"and",
"self",
".",
"http_detail_level",
"is",
"not",
"None",
"and... | Log request HTTP information including url, headers, etc. | [
"Log",
"request",
"HTTP",
"information",
"including",
"url",
"headers",
"etc",
"."
] | e54ecb82c2211e289a268567443d60fdd489f1e4 | https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/_recorder.py#L786-L811 | train | 28,470 |
pywbem/pywbem | pywbem/_recorder.py | LogOperationRecorder.stage_http_response2 | def stage_http_response2(self, payload):
"""Log complete http response, including response1 and payload"""
# required because http code uses sending all None to reset
# parameters. We ignore that
if not self._http_response_version and not payload:
return
if self.enabled and self.http_detail_level is not None and \
self.httplogger.isEnabledFor(logging.DEBUG):
if self._http_response_headers:
header_str = \
' '.join('{0}:{1!r}'.format(k, v)
for k, v in self._http_response_headers.items())
else:
header_str = ''
if self.http_detail_level == 'summary':
upayload = ""
elif self.http_maxlen and (len(payload) > self.http_maxlen):
upayload = (_ensure_unicode(payload[:self.http_maxlen]) +
'...')
else:
upayload = _ensure_unicode(payload)
self.httplogger.debug('Response:%s %s:%s %s %s\n %s',
self._http_response_conn_id,
self._http_response_status,
self._http_response_reason,
self._http_response_version,
header_str, upayload) | python | def stage_http_response2(self, payload):
"""Log complete http response, including response1 and payload"""
# required because http code uses sending all None to reset
# parameters. We ignore that
if not self._http_response_version and not payload:
return
if self.enabled and self.http_detail_level is not None and \
self.httplogger.isEnabledFor(logging.DEBUG):
if self._http_response_headers:
header_str = \
' '.join('{0}:{1!r}'.format(k, v)
for k, v in self._http_response_headers.items())
else:
header_str = ''
if self.http_detail_level == 'summary':
upayload = ""
elif self.http_maxlen and (len(payload) > self.http_maxlen):
upayload = (_ensure_unicode(payload[:self.http_maxlen]) +
'...')
else:
upayload = _ensure_unicode(payload)
self.httplogger.debug('Response:%s %s:%s %s %s\n %s',
self._http_response_conn_id,
self._http_response_status,
self._http_response_reason,
self._http_response_version,
header_str, upayload) | [
"def",
"stage_http_response2",
"(",
"self",
",",
"payload",
")",
":",
"# required because http code uses sending all None to reset",
"# parameters. We ignore that",
"if",
"not",
"self",
".",
"_http_response_version",
"and",
"not",
"payload",
":",
"return",
"if",
"self",
"... | Log complete http response, including response1 and payload | [
"Log",
"complete",
"http",
"response",
"including",
"response1",
"and",
"payload"
] | e54ecb82c2211e289a268567443d60fdd489f1e4 | https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/_recorder.py#L822-L851 | train | 28,471 |
pywbem/pywbem | pywbem/_valuemapping.py | ValueMapping._to_int | def _to_int(self, val_str):
"""Conver val_str to an integer or raise ValueError"""
val = _integerValue_to_int(val_str)
if val is None:
raise ValueError(
_format("The value-mapped {0} has an invalid integer "
"representation in a ValueMap entry: {1!A}",
self._element_str(), val_str))
return val | python | def _to_int(self, val_str):
"""Conver val_str to an integer or raise ValueError"""
val = _integerValue_to_int(val_str)
if val is None:
raise ValueError(
_format("The value-mapped {0} has an invalid integer "
"representation in a ValueMap entry: {1!A}",
self._element_str(), val_str))
return val | [
"def",
"_to_int",
"(",
"self",
",",
"val_str",
")",
":",
"val",
"=",
"_integerValue_to_int",
"(",
"val_str",
")",
"if",
"val",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"_format",
"(",
"\"The value-mapped {0} has an invalid integer \"",
"\"representation in a V... | Conver val_str to an integer or raise ValueError | [
"Conver",
"val_str",
"to",
"an",
"integer",
"or",
"raise",
"ValueError"
] | e54ecb82c2211e289a268567443d60fdd489f1e4 | https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/_valuemapping.py#L468-L476 | train | 28,472 |
pywbem/pywbem | pywbem/_valuemapping.py | ValueMapping._element_str | def _element_str(self):
"""
Return a string that identifies the value-mapped element.
"""
# pylint: disable=no-else-return
if isinstance(self.element, CIMProperty):
return _format("property {0!A} in class {1!A} (in {2!A})",
self.propname, self.classname, self.namespace)
elif isinstance(self.element, CIMMethod):
return _format("method {0!A} in class {1!A} (in {2!A})",
self.methodname, self.classname, self.namespace)
assert isinstance(self.element, CIMParameter)
return _format("parameter {0!A} of method {1!A} in class {2!A} "
"(in {3!A})",
self.parametername, self.methodname, self.classname,
self.namespace) | python | def _element_str(self):
"""
Return a string that identifies the value-mapped element.
"""
# pylint: disable=no-else-return
if isinstance(self.element, CIMProperty):
return _format("property {0!A} in class {1!A} (in {2!A})",
self.propname, self.classname, self.namespace)
elif isinstance(self.element, CIMMethod):
return _format("method {0!A} in class {1!A} (in {2!A})",
self.methodname, self.classname, self.namespace)
assert isinstance(self.element, CIMParameter)
return _format("parameter {0!A} of method {1!A} in class {2!A} "
"(in {3!A})",
self.parametername, self.methodname, self.classname,
self.namespace) | [
"def",
"_element_str",
"(",
"self",
")",
":",
"# pylint: disable=no-else-return",
"if",
"isinstance",
"(",
"self",
".",
"element",
",",
"CIMProperty",
")",
":",
"return",
"_format",
"(",
"\"property {0!A} in class {1!A} (in {2!A})\"",
",",
"self",
".",
"propname",
"... | Return a string that identifies the value-mapped element. | [
"Return",
"a",
"string",
"that",
"identifies",
"the",
"value",
"-",
"mapped",
"element",
"."
] | e54ecb82c2211e289a268567443d60fdd489f1e4 | https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/_valuemapping.py#L595-L610 | train | 28,473 |
pywbem/pywbem | pywbem/_valuemapping.py | ValueMapping.tovalues | def tovalues(self, element_value):
"""
Return the `Values` string for an element value, based upon this value
mapping.
Parameters:
element_value (:term:`integer` or :class:`~pywbem.CIMInt`):
The value of the CIM element (property, method, parameter).
Returns:
:term:`string`:
The `Values` string for the element value.
Raises:
ValueError: Element value outside of the set defined by `ValueMap`.
TypeError: Element value is not an integer type.
"""
if not isinstance(element_value, (six.integer_types, CIMInt)):
raise TypeError(
_format("The value for value-mapped {0} is not "
"integer-typed, but has Python type: {1}",
self._element_str(), type(element_value)))
# try single value
try:
return self._b2v_single_dict[element_value]
except KeyError:
pass
# try value ranges
for range_tuple in self._b2v_range_tuple_list:
lo, hi, values_str = range_tuple
if lo <= element_value <= hi:
return values_str
# try catch-all '..'
if self._b2v_unclaimed is not None:
return self._b2v_unclaimed
raise ValueError(
_format("The value for value-mapped {0} is outside of the set "
"defined by its ValueMap qualifier: {1!A}",
self._element_str(), element_value)) | python | def tovalues(self, element_value):
"""
Return the `Values` string for an element value, based upon this value
mapping.
Parameters:
element_value (:term:`integer` or :class:`~pywbem.CIMInt`):
The value of the CIM element (property, method, parameter).
Returns:
:term:`string`:
The `Values` string for the element value.
Raises:
ValueError: Element value outside of the set defined by `ValueMap`.
TypeError: Element value is not an integer type.
"""
if not isinstance(element_value, (six.integer_types, CIMInt)):
raise TypeError(
_format("The value for value-mapped {0} is not "
"integer-typed, but has Python type: {1}",
self._element_str(), type(element_value)))
# try single value
try:
return self._b2v_single_dict[element_value]
except KeyError:
pass
# try value ranges
for range_tuple in self._b2v_range_tuple_list:
lo, hi, values_str = range_tuple
if lo <= element_value <= hi:
return values_str
# try catch-all '..'
if self._b2v_unclaimed is not None:
return self._b2v_unclaimed
raise ValueError(
_format("The value for value-mapped {0} is outside of the set "
"defined by its ValueMap qualifier: {1!A}",
self._element_str(), element_value)) | [
"def",
"tovalues",
"(",
"self",
",",
"element_value",
")",
":",
"if",
"not",
"isinstance",
"(",
"element_value",
",",
"(",
"six",
".",
"integer_types",
",",
"CIMInt",
")",
")",
":",
"raise",
"TypeError",
"(",
"_format",
"(",
"\"The value for value-mapped {0} i... | Return the `Values` string for an element value, based upon this value
mapping.
Parameters:
element_value (:term:`integer` or :class:`~pywbem.CIMInt`):
The value of the CIM element (property, method, parameter).
Returns:
:term:`string`:
The `Values` string for the element value.
Raises:
ValueError: Element value outside of the set defined by `ValueMap`.
TypeError: Element value is not an integer type. | [
"Return",
"the",
"Values",
"string",
"for",
"an",
"element",
"value",
"based",
"upon",
"this",
"value",
"mapping",
"."
] | e54ecb82c2211e289a268567443d60fdd489f1e4 | https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/_valuemapping.py#L690-L736 | train | 28,474 |
pywbem/pywbem | pywbem/_valuemapping.py | ValueMapping.tobinary | def tobinary(self, values_str):
"""
Return the integer value or values for a `Values` string, based upon
this value mapping.
Any returned integer value is represented as the CIM type of the
element (e.g. :class:`~pywbem.Uint16`).
If the `Values` string corresponds to a single value, that single value
is returned as an integer.
If the `Values` string corresponds to a value range (e.g. "1.." or
"..2" or "3..4"), that value range is returned as a tuple with two items
that are the lowest and the highest value of the range. That is the
case also when the value range is open on the left side or right side.
If the `Values` string corresponds to the `unclaimed` indicator "..",
`None` is returned.
Parameters:
values_str (:term:`string`):
The `Values` string for the element value.
Returns:
:class:`~pywbem.CIMInt` or tuple of :class:`~pywbem.CIMInt` or `None`:
The element value or value range corresponding to the `Values`
string, or `None` for unclaimed.
Raises:
ValueError: `Values` string outside of the set defined by `Values`.
TypeError: `Values` string is not a string type.
"""
if not isinstance(values_str, six.string_types):
raise TypeError(
_format("The values string for value-mapped {0} is not "
"string-typed, but has Python type: {1}",
self._element_str(), type(values_str)))
try:
return self._v2b_dict[values_str]
except KeyError:
raise ValueError(
_format("The values string for value-mapped {0} is outside "
"of the set defined by its Values qualifier: {1!A}",
self._element_str(), values_str)) | python | def tobinary(self, values_str):
"""
Return the integer value or values for a `Values` string, based upon
this value mapping.
Any returned integer value is represented as the CIM type of the
element (e.g. :class:`~pywbem.Uint16`).
If the `Values` string corresponds to a single value, that single value
is returned as an integer.
If the `Values` string corresponds to a value range (e.g. "1.." or
"..2" or "3..4"), that value range is returned as a tuple with two items
that are the lowest and the highest value of the range. That is the
case also when the value range is open on the left side or right side.
If the `Values` string corresponds to the `unclaimed` indicator "..",
`None` is returned.
Parameters:
values_str (:term:`string`):
The `Values` string for the element value.
Returns:
:class:`~pywbem.CIMInt` or tuple of :class:`~pywbem.CIMInt` or `None`:
The element value or value range corresponding to the `Values`
string, or `None` for unclaimed.
Raises:
ValueError: `Values` string outside of the set defined by `Values`.
TypeError: `Values` string is not a string type.
"""
if not isinstance(values_str, six.string_types):
raise TypeError(
_format("The values string for value-mapped {0} is not "
"string-typed, but has Python type: {1}",
self._element_str(), type(values_str)))
try:
return self._v2b_dict[values_str]
except KeyError:
raise ValueError(
_format("The values string for value-mapped {0} is outside "
"of the set defined by its Values qualifier: {1!A}",
self._element_str(), values_str)) | [
"def",
"tobinary",
"(",
"self",
",",
"values_str",
")",
":",
"if",
"not",
"isinstance",
"(",
"values_str",
",",
"six",
".",
"string_types",
")",
":",
"raise",
"TypeError",
"(",
"_format",
"(",
"\"The values string for value-mapped {0} is not \"",
"\"string-typed, bu... | Return the integer value or values for a `Values` string, based upon
this value mapping.
Any returned integer value is represented as the CIM type of the
element (e.g. :class:`~pywbem.Uint16`).
If the `Values` string corresponds to a single value, that single value
is returned as an integer.
If the `Values` string corresponds to a value range (e.g. "1.." or
"..2" or "3..4"), that value range is returned as a tuple with two items
that are the lowest and the highest value of the range. That is the
case also when the value range is open on the left side or right side.
If the `Values` string corresponds to the `unclaimed` indicator "..",
`None` is returned.
Parameters:
values_str (:term:`string`):
The `Values` string for the element value.
Returns:
:class:`~pywbem.CIMInt` or tuple of :class:`~pywbem.CIMInt` or `None`:
The element value or value range corresponding to the `Values`
string, or `None` for unclaimed.
Raises:
ValueError: `Values` string outside of the set defined by `Values`.
TypeError: `Values` string is not a string type. | [
"Return",
"the",
"integer",
"value",
"or",
"values",
"for",
"a",
"Values",
"string",
"based",
"upon",
"this",
"value",
"mapping",
"."
] | e54ecb82c2211e289a268567443d60fdd489f1e4 | https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/_valuemapping.py#L738-L786 | train | 28,475 |
pywbem/pywbem | pywbem/_subscription_manager.py | WBEMSubscriptionManager._get_server | def _get_server(self, server_id):
"""
Internal method to get the server object, given a server_id.
Parameters:
server_id (:term:`string`):
The server ID of the WBEM server, returned by
:meth:`~pywbem.WBEMSubscriptionManager.add_server`.
Returns:
server (:class:`~pywbem.WBEMServer`):
The WBEM server.
Raises:
ValueError: server_id not known to subscription manager.
"""
if server_id not in self._servers:
raise ValueError(
_format("WBEM server {0!A} not known by subscription manager",
server_id))
return self._servers[server_id] | python | def _get_server(self, server_id):
"""
Internal method to get the server object, given a server_id.
Parameters:
server_id (:term:`string`):
The server ID of the WBEM server, returned by
:meth:`~pywbem.WBEMSubscriptionManager.add_server`.
Returns:
server (:class:`~pywbem.WBEMServer`):
The WBEM server.
Raises:
ValueError: server_id not known to subscription manager.
"""
if server_id not in self._servers:
raise ValueError(
_format("WBEM server {0!A} not known by subscription manager",
server_id))
return self._servers[server_id] | [
"def",
"_get_server",
"(",
"self",
",",
"server_id",
")",
":",
"if",
"server_id",
"not",
"in",
"self",
".",
"_servers",
":",
"raise",
"ValueError",
"(",
"_format",
"(",
"\"WBEM server {0!A} not known by subscription manager\"",
",",
"server_id",
")",
")",
"return"... | Internal method to get the server object, given a server_id.
Parameters:
server_id (:term:`string`):
The server ID of the WBEM server, returned by
:meth:`~pywbem.WBEMSubscriptionManager.add_server`.
Returns:
server (:class:`~pywbem.WBEMServer`):
The WBEM server.
Raises:
ValueError: server_id not known to subscription manager. | [
"Internal",
"method",
"to",
"get",
"the",
"server",
"object",
"given",
"a",
"server_id",
"."
] | e54ecb82c2211e289a268567443d60fdd489f1e4 | https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/_subscription_manager.py#L272-L297 | train | 28,476 |
pywbem/pywbem | pywbem/_subscription_manager.py | WBEMSubscriptionManager.add_server | def add_server(self, server):
"""
Register a WBEM server with the subscription manager. This is a
prerequisite for adding listener destinations, indication filters and
indication subscriptions to the server.
This method discovers listener destination, indication filter, and
subscription instances in the WBEM server owned by this subscription
manager, and registers them in the subscription manager as if they had
been created through it.
In this discovery process, listener destination and indication filter
instances are matched based upon the value of their `Name` property.
Subscription instances are matched based upon the ownership of the
referenced destination and filter instances: If a subscription
references a filter or a destination that is owned by this subscription
manager, it is considered owned by this subscription manager as well.
Parameters:
server (:class:`~pywbem.WBEMServer`):
The WBEM server.
Returns:
:term:`string`: An ID for the WBEM server, for use by other
methods of this class.
Raises:
Exceptions raised by :class:`~pywbem.WBEMConnection`.
ValueError: Incorrect input parameter values.
TypeError: Incorrect input parameter types.
"""
if not isinstance(server, WBEMServer):
raise TypeError("Server argument of add_server() must be a "
"WBEMServer object")
server_id = server.url
if server_id in self._servers:
raise ValueError(
_format("WBEM server already known by listener: {0!A}",
server_id))
# Create dictionary entries for this server
self._servers[server_id] = server
self._owned_subscriptions[server_id] = []
self._owned_filters[server_id] = []
self._owned_destinations[server_id] = []
# Recover any owned destination, filter, and subscription instances
# that exist on this server
this_host = getfqdn()
dest_name_pattern = re.compile(
_format(r'^pywbemdestination:owned:{0}:{1}:[^:]*$',
this_host, self._subscription_manager_id))
dest_insts = server.conn.EnumerateInstances(
DESTINATION_CLASSNAME, namespace=server.interop_ns)
for inst in dest_insts:
if re.match(dest_name_pattern, inst.path.keybindings['Name']) \
and inst.path.keybindings['SystemName'] == this_host:
self._owned_destinations[server_id].append(inst)
filter_name_pattern = re.compile(
_format(r'^pywbemfilter:owned:{0}:{1}:[^:]*:[^:]*$',
this_host, self._subscription_manager_id))
filter_insts = server.conn.EnumerateInstances(
FILTER_CLASSNAME, namespace=server.interop_ns)
for inst in filter_insts:
if re.match(filter_name_pattern, inst.path.keybindings['Name']) \
and inst.path.keybindings['SystemName'] == this_host:
self._owned_filters[server_id].append(inst)
sub_insts = server.conn.EnumerateInstances(
SUBSCRIPTION_CLASSNAME, namespace=server.interop_ns)
owned_filter_paths = [inst.path for inst in
self._owned_filters[server_id]]
owned_destination_paths = [inst.path for inst in
self._owned_destinations[server_id]]
for inst in sub_insts:
if inst.path.keybindings['Filter'] in \
owned_filter_paths \
or inst.path.keybindings['Handler'] in \
owned_destination_paths:
self._owned_subscriptions[server_id].append(inst)
return server_id | python | def add_server(self, server):
"""
Register a WBEM server with the subscription manager. This is a
prerequisite for adding listener destinations, indication filters and
indication subscriptions to the server.
This method discovers listener destination, indication filter, and
subscription instances in the WBEM server owned by this subscription
manager, and registers them in the subscription manager as if they had
been created through it.
In this discovery process, listener destination and indication filter
instances are matched based upon the value of their `Name` property.
Subscription instances are matched based upon the ownership of the
referenced destination and filter instances: If a subscription
references a filter or a destination that is owned by this subscription
manager, it is considered owned by this subscription manager as well.
Parameters:
server (:class:`~pywbem.WBEMServer`):
The WBEM server.
Returns:
:term:`string`: An ID for the WBEM server, for use by other
methods of this class.
Raises:
Exceptions raised by :class:`~pywbem.WBEMConnection`.
ValueError: Incorrect input parameter values.
TypeError: Incorrect input parameter types.
"""
if not isinstance(server, WBEMServer):
raise TypeError("Server argument of add_server() must be a "
"WBEMServer object")
server_id = server.url
if server_id in self._servers:
raise ValueError(
_format("WBEM server already known by listener: {0!A}",
server_id))
# Create dictionary entries for this server
self._servers[server_id] = server
self._owned_subscriptions[server_id] = []
self._owned_filters[server_id] = []
self._owned_destinations[server_id] = []
# Recover any owned destination, filter, and subscription instances
# that exist on this server
this_host = getfqdn()
dest_name_pattern = re.compile(
_format(r'^pywbemdestination:owned:{0}:{1}:[^:]*$',
this_host, self._subscription_manager_id))
dest_insts = server.conn.EnumerateInstances(
DESTINATION_CLASSNAME, namespace=server.interop_ns)
for inst in dest_insts:
if re.match(dest_name_pattern, inst.path.keybindings['Name']) \
and inst.path.keybindings['SystemName'] == this_host:
self._owned_destinations[server_id].append(inst)
filter_name_pattern = re.compile(
_format(r'^pywbemfilter:owned:{0}:{1}:[^:]*:[^:]*$',
this_host, self._subscription_manager_id))
filter_insts = server.conn.EnumerateInstances(
FILTER_CLASSNAME, namespace=server.interop_ns)
for inst in filter_insts:
if re.match(filter_name_pattern, inst.path.keybindings['Name']) \
and inst.path.keybindings['SystemName'] == this_host:
self._owned_filters[server_id].append(inst)
sub_insts = server.conn.EnumerateInstances(
SUBSCRIPTION_CLASSNAME, namespace=server.interop_ns)
owned_filter_paths = [inst.path for inst in
self._owned_filters[server_id]]
owned_destination_paths = [inst.path for inst in
self._owned_destinations[server_id]]
for inst in sub_insts:
if inst.path.keybindings['Filter'] in \
owned_filter_paths \
or inst.path.keybindings['Handler'] in \
owned_destination_paths:
self._owned_subscriptions[server_id].append(inst)
return server_id | [
"def",
"add_server",
"(",
"self",
",",
"server",
")",
":",
"if",
"not",
"isinstance",
"(",
"server",
",",
"WBEMServer",
")",
":",
"raise",
"TypeError",
"(",
"\"Server argument of add_server() must be a \"",
"\"WBEMServer object\"",
")",
"server_id",
"=",
"server",
... | Register a WBEM server with the subscription manager. This is a
prerequisite for adding listener destinations, indication filters and
indication subscriptions to the server.
This method discovers listener destination, indication filter, and
subscription instances in the WBEM server owned by this subscription
manager, and registers them in the subscription manager as if they had
been created through it.
In this discovery process, listener destination and indication filter
instances are matched based upon the value of their `Name` property.
Subscription instances are matched based upon the ownership of the
referenced destination and filter instances: If a subscription
references a filter or a destination that is owned by this subscription
manager, it is considered owned by this subscription manager as well.
Parameters:
server (:class:`~pywbem.WBEMServer`):
The WBEM server.
Returns:
:term:`string`: An ID for the WBEM server, for use by other
methods of this class.
Raises:
Exceptions raised by :class:`~pywbem.WBEMConnection`.
ValueError: Incorrect input parameter values.
TypeError: Incorrect input parameter types. | [
"Register",
"a",
"WBEM",
"server",
"with",
"the",
"subscription",
"manager",
".",
"This",
"is",
"a",
"prerequisite",
"for",
"adding",
"listener",
"destinations",
"indication",
"filters",
"and",
"indication",
"subscriptions",
"to",
"the",
"server",
"."
] | e54ecb82c2211e289a268567443d60fdd489f1e4 | https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/_subscription_manager.py#L299-L387 | train | 28,477 |
pywbem/pywbem | pywbem/_subscription_manager.py | WBEMSubscriptionManager.remove_server | def remove_server(self, server_id):
"""
Remove a registered WBEM server from the subscription manager. This
also unregisters listeners from that server and removes all owned
indication subscriptions, owned indication filters and owned listener
destinations.
Parameters:
server_id (:term:`string`):
The server ID of the WBEM server, returned by
:meth:`~pywbem.WBEMSubscriptionManager.add_server`.
Raises:
Exceptions raised by :class:`~pywbem.WBEMConnection`.
"""
# Validate server_id
server = self._get_server(server_id)
# Delete any instances we recorded to be cleaned up
if server_id in self._owned_subscriptions:
inst_list = self._owned_subscriptions[server_id]
# We iterate backwards because we change the list
for i in six.moves.range(len(inst_list) - 1, -1, -1):
inst = inst_list[i]
server.conn.DeleteInstance(inst.path)
del inst_list[i]
del self._owned_subscriptions[server_id]
if server_id in self._owned_filters:
inst_list = self._owned_filters[server_id]
# We iterate backwards because we change the list
for i in six.moves.range(len(inst_list) - 1, -1, -1):
inst = inst_list[i]
server.conn.DeleteInstance(inst.path)
del inst_list[i]
del self._owned_filters[server_id]
if server_id in self._owned_destinations:
inst_list = self._owned_destinations[server_id]
# We iterate backwards because we change the list
for i in six.moves.range(len(inst_list) - 1, -1, -1):
inst = inst_list[i]
server.conn.DeleteInstance(inst.path)
del inst_list[i]
del self._owned_destinations[server_id]
# Remove server from this listener
del self._servers[server_id] | python | def remove_server(self, server_id):
"""
Remove a registered WBEM server from the subscription manager. This
also unregisters listeners from that server and removes all owned
indication subscriptions, owned indication filters and owned listener
destinations.
Parameters:
server_id (:term:`string`):
The server ID of the WBEM server, returned by
:meth:`~pywbem.WBEMSubscriptionManager.add_server`.
Raises:
Exceptions raised by :class:`~pywbem.WBEMConnection`.
"""
# Validate server_id
server = self._get_server(server_id)
# Delete any instances we recorded to be cleaned up
if server_id in self._owned_subscriptions:
inst_list = self._owned_subscriptions[server_id]
# We iterate backwards because we change the list
for i in six.moves.range(len(inst_list) - 1, -1, -1):
inst = inst_list[i]
server.conn.DeleteInstance(inst.path)
del inst_list[i]
del self._owned_subscriptions[server_id]
if server_id in self._owned_filters:
inst_list = self._owned_filters[server_id]
# We iterate backwards because we change the list
for i in six.moves.range(len(inst_list) - 1, -1, -1):
inst = inst_list[i]
server.conn.DeleteInstance(inst.path)
del inst_list[i]
del self._owned_filters[server_id]
if server_id in self._owned_destinations:
inst_list = self._owned_destinations[server_id]
# We iterate backwards because we change the list
for i in six.moves.range(len(inst_list) - 1, -1, -1):
inst = inst_list[i]
server.conn.DeleteInstance(inst.path)
del inst_list[i]
del self._owned_destinations[server_id]
# Remove server from this listener
del self._servers[server_id] | [
"def",
"remove_server",
"(",
"self",
",",
"server_id",
")",
":",
"# Validate server_id",
"server",
"=",
"self",
".",
"_get_server",
"(",
"server_id",
")",
"# Delete any instances we recorded to be cleaned up",
"if",
"server_id",
"in",
"self",
".",
"_owned_subscriptions"... | Remove a registered WBEM server from the subscription manager. This
also unregisters listeners from that server and removes all owned
indication subscriptions, owned indication filters and owned listener
destinations.
Parameters:
server_id (:term:`string`):
The server ID of the WBEM server, returned by
:meth:`~pywbem.WBEMSubscriptionManager.add_server`.
Raises:
Exceptions raised by :class:`~pywbem.WBEMConnection`. | [
"Remove",
"a",
"registered",
"WBEM",
"server",
"from",
"the",
"subscription",
"manager",
".",
"This",
"also",
"unregisters",
"listeners",
"from",
"that",
"server",
"and",
"removes",
"all",
"owned",
"indication",
"subscriptions",
"owned",
"indication",
"filters",
"... | e54ecb82c2211e289a268567443d60fdd489f1e4 | https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/_subscription_manager.py#L389-L440 | train | 28,478 |
pywbem/pywbem | pywbem/_subscription_manager.py | WBEMSubscriptionManager.remove_all_servers | def remove_all_servers(self):
"""
Remove all registered WBEM servers from the subscription manager. This
also unregisters listeners from these servers and removes all owned
indication subscriptions, owned indication filters, and owned listener
destinations.
Raises:
Exceptions raised by :class:`~pywbem.WBEMConnection`.
"""
for server_id in list(self._servers.keys()):
self.remove_server(server_id) | python | def remove_all_servers(self):
"""
Remove all registered WBEM servers from the subscription manager. This
also unregisters listeners from these servers and removes all owned
indication subscriptions, owned indication filters, and owned listener
destinations.
Raises:
Exceptions raised by :class:`~pywbem.WBEMConnection`.
"""
for server_id in list(self._servers.keys()):
self.remove_server(server_id) | [
"def",
"remove_all_servers",
"(",
"self",
")",
":",
"for",
"server_id",
"in",
"list",
"(",
"self",
".",
"_servers",
".",
"keys",
"(",
")",
")",
":",
"self",
".",
"remove_server",
"(",
"server_id",
")"
] | Remove all registered WBEM servers from the subscription manager. This
also unregisters listeners from these servers and removes all owned
indication subscriptions, owned indication filters, and owned listener
destinations.
Raises:
Exceptions raised by :class:`~pywbem.WBEMConnection`. | [
"Remove",
"all",
"registered",
"WBEM",
"servers",
"from",
"the",
"subscription",
"manager",
".",
"This",
"also",
"unregisters",
"listeners",
"from",
"these",
"servers",
"and",
"removes",
"all",
"owned",
"indication",
"subscriptions",
"owned",
"indication",
"filters"... | e54ecb82c2211e289a268567443d60fdd489f1e4 | https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/_subscription_manager.py#L442-L455 | train | 28,479 |
pywbem/pywbem | pywbem/_subscription_manager.py | WBEMSubscriptionManager.add_listener_destinations | def add_listener_destinations(self, server_id, listener_urls, owned=True):
"""
Register WBEM listeners to be the target of indications sent by a
WBEM server.
This function automatically creates a listener destination instance
(of CIM class "CIM_ListenerDestinationCIMXML") for each specified
listener URL in the Interop namespace of the specified WBEM server.
The form of the `Name` property of the created destination instance is:
``"pywbemdestination:" {ownership} ":" {subscription_manager_id} ":"
{guid}``
where ``{ownership}`` is ``"owned"`` or ``"permanent"`` dependent on
the `owned` argument; ``{subscription_manager_id}`` is the
subscription manager ID; and ``{guid}`` is a globally unique
identifier.
Owned listener destinations are added or updated conditionally: If the
listener destination instance to be added is already registered with
this subscription manager and has the same property values, it is not
created or modified. If it has the same path but different property
values, it is modified to get the desired property values. If an
instance with this path does not exist yet (the normal case), it is
created.
Permanent listener destinations are created unconditionally, and it is
up to the user to ensure that such an instance does not exist yet.
Parameters:
server_id (:term:`string`):
The server ID of the WBEM server, returned by
:meth:`~pywbem.WBEMSubscriptionManager.add_server`.
listener_urls (:term:`string` or list of :term:`string`):
The URL or URLs of the WBEM listeners to be registered.
The WBEM listener may be a :class:`~pywbem.WBEMListener` object or
any external WBEM listener.
Each listener URL string must have the format:
``[{scheme}://]{host}:{port}``
The following URL schemes are supported:
* ``https``: Causes HTTPS to be used.
* ``http``: Causes HTTP to be used. This is the default
The host can be specified in any of the usual formats:
* a short or fully qualified DNS hostname
* a literal (= dotted) IPv4 address
* a literal IPv6 address, formatted as defined in :term:`RFC3986`
with the extensions for zone identifiers as defined in
:term:`RFC6874`, supporting ``-`` (minus) for the delimiter
before the zone ID string, as an additional choice to ``%25``.
Note that the port is required in listener URLs.
See :class:`~pywbem.WBEMConnection` for examples of valid URLs,
with the caveat that the port in server URLs is optional.
owned (:class:`py:bool`):
Defines the ownership type of the created listener destination
instances: If `True`, they will be owned. Otherwise, they will be
permanent. See :ref:`WBEMSubscriptionManager` for details about
these ownership types.
Returns:
:class:`py:list` of :class:`~pywbem.CIMInstance`: The created
listener destination instances for the defined listener URLs.
Raises:
Exceptions raised by :class:`~pywbem.WBEMConnection`.
"""
# server_id is validated in _create_...() method.
# If list, recursively call this function with each list item.
if isinstance(listener_urls, list):
dest_insts = []
for listener_url in listener_urls:
new_dest_insts = self.add_listener_destinations(
server_id, listener_url)
dest_insts.extend(new_dest_insts)
return dest_insts
# Here, the variable will be a single list item.
listener_url = listener_urls
dest_inst = self._create_destination(server_id, listener_url, owned)
return [dest_inst] | python | def add_listener_destinations(self, server_id, listener_urls, owned=True):
"""
Register WBEM listeners to be the target of indications sent by a
WBEM server.
This function automatically creates a listener destination instance
(of CIM class "CIM_ListenerDestinationCIMXML") for each specified
listener URL in the Interop namespace of the specified WBEM server.
The form of the `Name` property of the created destination instance is:
``"pywbemdestination:" {ownership} ":" {subscription_manager_id} ":"
{guid}``
where ``{ownership}`` is ``"owned"`` or ``"permanent"`` dependent on
the `owned` argument; ``{subscription_manager_id}`` is the
subscription manager ID; and ``{guid}`` is a globally unique
identifier.
Owned listener destinations are added or updated conditionally: If the
listener destination instance to be added is already registered with
this subscription manager and has the same property values, it is not
created or modified. If it has the same path but different property
values, it is modified to get the desired property values. If an
instance with this path does not exist yet (the normal case), it is
created.
Permanent listener destinations are created unconditionally, and it is
up to the user to ensure that such an instance does not exist yet.
Parameters:
server_id (:term:`string`):
The server ID of the WBEM server, returned by
:meth:`~pywbem.WBEMSubscriptionManager.add_server`.
listener_urls (:term:`string` or list of :term:`string`):
The URL or URLs of the WBEM listeners to be registered.
The WBEM listener may be a :class:`~pywbem.WBEMListener` object or
any external WBEM listener.
Each listener URL string must have the format:
``[{scheme}://]{host}:{port}``
The following URL schemes are supported:
* ``https``: Causes HTTPS to be used.
* ``http``: Causes HTTP to be used. This is the default
The host can be specified in any of the usual formats:
* a short or fully qualified DNS hostname
* a literal (= dotted) IPv4 address
* a literal IPv6 address, formatted as defined in :term:`RFC3986`
with the extensions for zone identifiers as defined in
:term:`RFC6874`, supporting ``-`` (minus) for the delimiter
before the zone ID string, as an additional choice to ``%25``.
Note that the port is required in listener URLs.
See :class:`~pywbem.WBEMConnection` for examples of valid URLs,
with the caveat that the port in server URLs is optional.
owned (:class:`py:bool`):
Defines the ownership type of the created listener destination
instances: If `True`, they will be owned. Otherwise, they will be
permanent. See :ref:`WBEMSubscriptionManager` for details about
these ownership types.
Returns:
:class:`py:list` of :class:`~pywbem.CIMInstance`: The created
listener destination instances for the defined listener URLs.
Raises:
Exceptions raised by :class:`~pywbem.WBEMConnection`.
"""
# server_id is validated in _create_...() method.
# If list, recursively call this function with each list item.
if isinstance(listener_urls, list):
dest_insts = []
for listener_url in listener_urls:
new_dest_insts = self.add_listener_destinations(
server_id, listener_url)
dest_insts.extend(new_dest_insts)
return dest_insts
# Here, the variable will be a single list item.
listener_url = listener_urls
dest_inst = self._create_destination(server_id, listener_url, owned)
return [dest_inst] | [
"def",
"add_listener_destinations",
"(",
"self",
",",
"server_id",
",",
"listener_urls",
",",
"owned",
"=",
"True",
")",
":",
"# server_id is validated in _create_...() method.",
"# If list, recursively call this function with each list item.",
"if",
"isinstance",
"(",
"listene... | Register WBEM listeners to be the target of indications sent by a
WBEM server.
This function automatically creates a listener destination instance
(of CIM class "CIM_ListenerDestinationCIMXML") for each specified
listener URL in the Interop namespace of the specified WBEM server.
The form of the `Name` property of the created destination instance is:
``"pywbemdestination:" {ownership} ":" {subscription_manager_id} ":"
{guid}``
where ``{ownership}`` is ``"owned"`` or ``"permanent"`` dependent on
the `owned` argument; ``{subscription_manager_id}`` is the
subscription manager ID; and ``{guid}`` is a globally unique
identifier.
Owned listener destinations are added or updated conditionally: If the
listener destination instance to be added is already registered with
this subscription manager and has the same property values, it is not
created or modified. If it has the same path but different property
values, it is modified to get the desired property values. If an
instance with this path does not exist yet (the normal case), it is
created.
Permanent listener destinations are created unconditionally, and it is
up to the user to ensure that such an instance does not exist yet.
Parameters:
server_id (:term:`string`):
The server ID of the WBEM server, returned by
:meth:`~pywbem.WBEMSubscriptionManager.add_server`.
listener_urls (:term:`string` or list of :term:`string`):
The URL or URLs of the WBEM listeners to be registered.
The WBEM listener may be a :class:`~pywbem.WBEMListener` object or
any external WBEM listener.
Each listener URL string must have the format:
``[{scheme}://]{host}:{port}``
The following URL schemes are supported:
* ``https``: Causes HTTPS to be used.
* ``http``: Causes HTTP to be used. This is the default
The host can be specified in any of the usual formats:
* a short or fully qualified DNS hostname
* a literal (= dotted) IPv4 address
* a literal IPv6 address, formatted as defined in :term:`RFC3986`
with the extensions for zone identifiers as defined in
:term:`RFC6874`, supporting ``-`` (minus) for the delimiter
before the zone ID string, as an additional choice to ``%25``.
Note that the port is required in listener URLs.
See :class:`~pywbem.WBEMConnection` for examples of valid URLs,
with the caveat that the port in server URLs is optional.
owned (:class:`py:bool`):
Defines the ownership type of the created listener destination
instances: If `True`, they will be owned. Otherwise, they will be
permanent. See :ref:`WBEMSubscriptionManager` for details about
these ownership types.
Returns:
:class:`py:list` of :class:`~pywbem.CIMInstance`: The created
listener destination instances for the defined listener URLs.
Raises:
Exceptions raised by :class:`~pywbem.WBEMConnection`. | [
"Register",
"WBEM",
"listeners",
"to",
"be",
"the",
"target",
"of",
"indications",
"sent",
"by",
"a",
"WBEM",
"server",
"."
] | e54ecb82c2211e289a268567443d60fdd489f1e4 | https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/_subscription_manager.py#L457-L554 | train | 28,480 |
pywbem/pywbem | pywbem/_subscription_manager.py | WBEMSubscriptionManager.get_owned_destinations | def get_owned_destinations(self, server_id):
"""
Return the listener destinations in a WBEM server owned by this
subscription manager.
This function accesses only the local list of owned destinations; it
does not contact the WBEM server. The local list of owned destinations
is discovered from the WBEM server when the server is registered with
the subscription manager, and is maintained from then on as changes
happen through this subscription manager.
Parameters:
server_id (:term:`string`):
The server ID of the WBEM server, returned by
:meth:`~pywbem.WBEMSubscriptionManager.add_server`.
Returns:
:class:`py:list` of :class:`~pywbem.CIMInstance`: The listener
destination instances.
"""
# Validate server_id
self._get_server(server_id)
return list(self._owned_destinations[server_id]) | python | def get_owned_destinations(self, server_id):
"""
Return the listener destinations in a WBEM server owned by this
subscription manager.
This function accesses only the local list of owned destinations; it
does not contact the WBEM server. The local list of owned destinations
is discovered from the WBEM server when the server is registered with
the subscription manager, and is maintained from then on as changes
happen through this subscription manager.
Parameters:
server_id (:term:`string`):
The server ID of the WBEM server, returned by
:meth:`~pywbem.WBEMSubscriptionManager.add_server`.
Returns:
:class:`py:list` of :class:`~pywbem.CIMInstance`: The listener
destination instances.
"""
# Validate server_id
self._get_server(server_id)
return list(self._owned_destinations[server_id]) | [
"def",
"get_owned_destinations",
"(",
"self",
",",
"server_id",
")",
":",
"# Validate server_id",
"self",
".",
"_get_server",
"(",
"server_id",
")",
"return",
"list",
"(",
"self",
".",
"_owned_destinations",
"[",
"server_id",
"]",
")"
] | Return the listener destinations in a WBEM server owned by this
subscription manager.
This function accesses only the local list of owned destinations; it
does not contact the WBEM server. The local list of owned destinations
is discovered from the WBEM server when the server is registered with
the subscription manager, and is maintained from then on as changes
happen through this subscription manager.
Parameters:
server_id (:term:`string`):
The server ID of the WBEM server, returned by
:meth:`~pywbem.WBEMSubscriptionManager.add_server`.
Returns:
:class:`py:list` of :class:`~pywbem.CIMInstance`: The listener
destination instances. | [
"Return",
"the",
"listener",
"destinations",
"in",
"a",
"WBEM",
"server",
"owned",
"by",
"this",
"subscription",
"manager",
"."
] | e54ecb82c2211e289a268567443d60fdd489f1e4 | https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/_subscription_manager.py#L556-L582 | train | 28,481 |
pywbem/pywbem | pywbem/_subscription_manager.py | WBEMSubscriptionManager.get_all_destinations | def get_all_destinations(self, server_id):
"""
Return all listener destinations in a WBEM server.
This function contacts the WBEM server and retrieves the listener
destinations by enumerating the instances of CIM class
"CIM_ListenerDestinationCIMXML" in the Interop namespace of the WBEM
server.
Parameters:
server_id (:term:`string`):
The server ID of the WBEM server, returned by
:meth:`~pywbem.WBEMSubscriptionManager.add_server`.
Returns:
:class:`py:list` of :class:`~pywbem.CIMInstance`: The listener
destination instances.
Raises:
Exceptions raised by :class:`~pywbem.WBEMConnection`.
"""
# Validate server_id
server = self._get_server(server_id)
return server.conn.EnumerateInstances(DESTINATION_CLASSNAME,
namespace=server.interop_ns) | python | def get_all_destinations(self, server_id):
"""
Return all listener destinations in a WBEM server.
This function contacts the WBEM server and retrieves the listener
destinations by enumerating the instances of CIM class
"CIM_ListenerDestinationCIMXML" in the Interop namespace of the WBEM
server.
Parameters:
server_id (:term:`string`):
The server ID of the WBEM server, returned by
:meth:`~pywbem.WBEMSubscriptionManager.add_server`.
Returns:
:class:`py:list` of :class:`~pywbem.CIMInstance`: The listener
destination instances.
Raises:
Exceptions raised by :class:`~pywbem.WBEMConnection`.
"""
# Validate server_id
server = self._get_server(server_id)
return server.conn.EnumerateInstances(DESTINATION_CLASSNAME,
namespace=server.interop_ns) | [
"def",
"get_all_destinations",
"(",
"self",
",",
"server_id",
")",
":",
"# Validate server_id",
"server",
"=",
"self",
".",
"_get_server",
"(",
"server_id",
")",
"return",
"server",
".",
"conn",
".",
"EnumerateInstances",
"(",
"DESTINATION_CLASSNAME",
",",
"namesp... | Return all listener destinations in a WBEM server.
This function contacts the WBEM server and retrieves the listener
destinations by enumerating the instances of CIM class
"CIM_ListenerDestinationCIMXML" in the Interop namespace of the WBEM
server.
Parameters:
server_id (:term:`string`):
The server ID of the WBEM server, returned by
:meth:`~pywbem.WBEMSubscriptionManager.add_server`.
Returns:
:class:`py:list` of :class:`~pywbem.CIMInstance`: The listener
destination instances.
Raises:
Exceptions raised by :class:`~pywbem.WBEMConnection`. | [
"Return",
"all",
"listener",
"destinations",
"in",
"a",
"WBEM",
"server",
"."
] | e54ecb82c2211e289a268567443d60fdd489f1e4 | https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/_subscription_manager.py#L584-L613 | train | 28,482 |
pywbem/pywbem | pywbem/_subscription_manager.py | WBEMSubscriptionManager.remove_destinations | def remove_destinations(self, server_id, destination_paths):
# pylint: disable=line-too-long
"""
Remove listener destinations from a WBEM server, by deleting the
listener destination instances in the server.
The listener destinations must be owned or permanent (i.e. not static).
This method verifies that there are not currently any subscriptions on
the listener destinations to be removed, in order to handle server
implementations that do not ensure that on the server side as required
by :term:`DSP1054`.
Parameters:
server_id (:term:`string`):
The server ID of the WBEM server, returned by
:meth:`~pywbem.WBEMSubscriptionManager.add_server`.
destination_paths (:class:`~pywbem.CIMInstanceName` or list of :class:`~pywbem.CIMInstanceName`):
Instance path(s) of the listener destination instance(s) in the
WBEM server.
Raises:
Exceptions raised by :class:`~pywbem.WBEMConnection`.
CIMError: CIM_ERR_FAILED, if there are referencing subscriptions.
""" # noqa: E501
# Validate server_id
server = self._get_server(server_id)
conn_id = server.conn.conn_id if server.conn is not None else None
# If list, recursively call this function with each list item.
if isinstance(destination_paths, list):
for dest_path in destination_paths:
self.remove_destinations(server_id, dest_path)
return
# Here, the variable will be a single list item.
dest_path = destination_paths
# Verify referencing subscriptions.
ref_paths = server.conn.ReferenceNames(
dest_path, ResultClass=SUBSCRIPTION_CLASSNAME)
if ref_paths:
# DSP1054 1.2 defines that this CIM error is raised by the server
# in that case, so we simulate that behavior on the client side.
raise CIMError(
CIM_ERR_FAILED,
"The listener destination is referenced by subscriptions.",
conn_id=conn_id)
server.conn.DeleteInstance(dest_path)
inst_list = self._owned_destinations[server_id]
# We iterate backwards because we change the list
for i in six.moves.range(len(inst_list) - 1, -1, -1):
inst = inst_list[i]
if inst.path == dest_path:
del inst_list[i] | python | def remove_destinations(self, server_id, destination_paths):
# pylint: disable=line-too-long
"""
Remove listener destinations from a WBEM server, by deleting the
listener destination instances in the server.
The listener destinations must be owned or permanent (i.e. not static).
This method verifies that there are not currently any subscriptions on
the listener destinations to be removed, in order to handle server
implementations that do not ensure that on the server side as required
by :term:`DSP1054`.
Parameters:
server_id (:term:`string`):
The server ID of the WBEM server, returned by
:meth:`~pywbem.WBEMSubscriptionManager.add_server`.
destination_paths (:class:`~pywbem.CIMInstanceName` or list of :class:`~pywbem.CIMInstanceName`):
Instance path(s) of the listener destination instance(s) in the
WBEM server.
Raises:
Exceptions raised by :class:`~pywbem.WBEMConnection`.
CIMError: CIM_ERR_FAILED, if there are referencing subscriptions.
""" # noqa: E501
# Validate server_id
server = self._get_server(server_id)
conn_id = server.conn.conn_id if server.conn is not None else None
# If list, recursively call this function with each list item.
if isinstance(destination_paths, list):
for dest_path in destination_paths:
self.remove_destinations(server_id, dest_path)
return
# Here, the variable will be a single list item.
dest_path = destination_paths
# Verify referencing subscriptions.
ref_paths = server.conn.ReferenceNames(
dest_path, ResultClass=SUBSCRIPTION_CLASSNAME)
if ref_paths:
# DSP1054 1.2 defines that this CIM error is raised by the server
# in that case, so we simulate that behavior on the client side.
raise CIMError(
CIM_ERR_FAILED,
"The listener destination is referenced by subscriptions.",
conn_id=conn_id)
server.conn.DeleteInstance(dest_path)
inst_list = self._owned_destinations[server_id]
# We iterate backwards because we change the list
for i in six.moves.range(len(inst_list) - 1, -1, -1):
inst = inst_list[i]
if inst.path == dest_path:
del inst_list[i] | [
"def",
"remove_destinations",
"(",
"self",
",",
"server_id",
",",
"destination_paths",
")",
":",
"# pylint: disable=line-too-long",
"# noqa: E501",
"# Validate server_id",
"server",
"=",
"self",
".",
"_get_server",
"(",
"server_id",
")",
"conn_id",
"=",
"server",
".",... | Remove listener destinations from a WBEM server, by deleting the
listener destination instances in the server.
The listener destinations must be owned or permanent (i.e. not static).
This method verifies that there are not currently any subscriptions on
the listener destinations to be removed, in order to handle server
implementations that do not ensure that on the server side as required
by :term:`DSP1054`.
Parameters:
server_id (:term:`string`):
The server ID of the WBEM server, returned by
:meth:`~pywbem.WBEMSubscriptionManager.add_server`.
destination_paths (:class:`~pywbem.CIMInstanceName` or list of :class:`~pywbem.CIMInstanceName`):
Instance path(s) of the listener destination instance(s) in the
WBEM server.
Raises:
Exceptions raised by :class:`~pywbem.WBEMConnection`.
CIMError: CIM_ERR_FAILED, if there are referencing subscriptions. | [
"Remove",
"listener",
"destinations",
"from",
"a",
"WBEM",
"server",
"by",
"deleting",
"the",
"listener",
"destination",
"instances",
"in",
"the",
"server",
"."
] | e54ecb82c2211e289a268567443d60fdd489f1e4 | https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/_subscription_manager.py#L615-L675 | train | 28,483 |
pywbem/pywbem | pywbem/_subscription_manager.py | WBEMSubscriptionManager.get_owned_filters | def get_owned_filters(self, server_id):
"""
Return the indication filters in a WBEM server owned by this
subscription manager.
This function accesses only the local list of owned filters; it does
not contact the WBEM server. The local list of owned filters is
discovered from the WBEM server when the server is registered with the
the subscription manager, and is maintained from then on as changes
happen through this subscription manager.
Parameters:
server_id (:term:`string`):
The server ID of the WBEM server, returned by
:meth:`~pywbem.WBEMSubscriptionManager.add_server`.
Returns:
:class:`py:list` of :class:`~pywbem.CIMInstance`: The indication
filter instances.
"""
# Validate server_id
self._get_server(server_id)
return list(self._owned_filters[server_id]) | python | def get_owned_filters(self, server_id):
"""
Return the indication filters in a WBEM server owned by this
subscription manager.
This function accesses only the local list of owned filters; it does
not contact the WBEM server. The local list of owned filters is
discovered from the WBEM server when the server is registered with the
the subscription manager, and is maintained from then on as changes
happen through this subscription manager.
Parameters:
server_id (:term:`string`):
The server ID of the WBEM server, returned by
:meth:`~pywbem.WBEMSubscriptionManager.add_server`.
Returns:
:class:`py:list` of :class:`~pywbem.CIMInstance`: The indication
filter instances.
"""
# Validate server_id
self._get_server(server_id)
return list(self._owned_filters[server_id]) | [
"def",
"get_owned_filters",
"(",
"self",
",",
"server_id",
")",
":",
"# Validate server_id",
"self",
".",
"_get_server",
"(",
"server_id",
")",
"return",
"list",
"(",
"self",
".",
"_owned_filters",
"[",
"server_id",
"]",
")"
] | Return the indication filters in a WBEM server owned by this
subscription manager.
This function accesses only the local list of owned filters; it does
not contact the WBEM server. The local list of owned filters is
discovered from the WBEM server when the server is registered with the
the subscription manager, and is maintained from then on as changes
happen through this subscription manager.
Parameters:
server_id (:term:`string`):
The server ID of the WBEM server, returned by
:meth:`~pywbem.WBEMSubscriptionManager.add_server`.
Returns:
:class:`py:list` of :class:`~pywbem.CIMInstance`: The indication
filter instances. | [
"Return",
"the",
"indication",
"filters",
"in",
"a",
"WBEM",
"server",
"owned",
"by",
"this",
"subscription",
"manager",
"."
] | e54ecb82c2211e289a268567443d60fdd489f1e4 | https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/_subscription_manager.py#L805-L831 | train | 28,484 |
pywbem/pywbem | pywbem/_subscription_manager.py | WBEMSubscriptionManager.get_all_filters | def get_all_filters(self, server_id):
"""
Return all indication filters in a WBEM server.
This function contacts the WBEM server and retrieves the indication
filters by enumerating the instances of CIM class
"CIM_IndicationFilter" in the Interop namespace of the WBEM server.
Parameters:
server_id (:term:`string`):
The server ID of the WBEM server, returned by
:meth:`~pywbem.WBEMSubscriptionManager.add_server`.
Returns:
:class:`py:list` of :class:`~pywbem.CIMInstance`: The indication
filter instances.
Raises:
Exceptions raised by :class:`~pywbem.WBEMConnection`.
"""
# Validate server_id
server = self._get_server(server_id)
return server.conn.EnumerateInstances('CIM_IndicationFilter',
namespace=server.interop_ns) | python | def get_all_filters(self, server_id):
"""
Return all indication filters in a WBEM server.
This function contacts the WBEM server and retrieves the indication
filters by enumerating the instances of CIM class
"CIM_IndicationFilter" in the Interop namespace of the WBEM server.
Parameters:
server_id (:term:`string`):
The server ID of the WBEM server, returned by
:meth:`~pywbem.WBEMSubscriptionManager.add_server`.
Returns:
:class:`py:list` of :class:`~pywbem.CIMInstance`: The indication
filter instances.
Raises:
Exceptions raised by :class:`~pywbem.WBEMConnection`.
"""
# Validate server_id
server = self._get_server(server_id)
return server.conn.EnumerateInstances('CIM_IndicationFilter',
namespace=server.interop_ns) | [
"def",
"get_all_filters",
"(",
"self",
",",
"server_id",
")",
":",
"# Validate server_id",
"server",
"=",
"self",
".",
"_get_server",
"(",
"server_id",
")",
"return",
"server",
".",
"conn",
".",
"EnumerateInstances",
"(",
"'CIM_IndicationFilter'",
",",
"namespace"... | Return all indication filters in a WBEM server.
This function contacts the WBEM server and retrieves the indication
filters by enumerating the instances of CIM class
"CIM_IndicationFilter" in the Interop namespace of the WBEM server.
Parameters:
server_id (:term:`string`):
The server ID of the WBEM server, returned by
:meth:`~pywbem.WBEMSubscriptionManager.add_server`.
Returns:
:class:`py:list` of :class:`~pywbem.CIMInstance`: The indication
filter instances.
Raises:
Exceptions raised by :class:`~pywbem.WBEMConnection`. | [
"Return",
"all",
"indication",
"filters",
"in",
"a",
"WBEM",
"server",
"."
] | e54ecb82c2211e289a268567443d60fdd489f1e4 | https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/_subscription_manager.py#L833-L861 | train | 28,485 |
pywbem/pywbem | pywbem/_subscription_manager.py | WBEMSubscriptionManager.remove_filter | def remove_filter(self, server_id, filter_path):
"""
Remove an indication filter from a WBEM server, by deleting the
indication filter instance in the WBEM server.
The indication filter must be owned or permanent (i.e. not static).
This method verifies that there are not currently any subscriptions on
the specified indication filter, in order to handle server
implementations that do not ensure that on the server side as required
by :term:`DSP1054`.
Parameters:
server_id (:term:`string`):
The server ID of the WBEM server, returned by
:meth:`~pywbem.WBEMSubscriptionManager.add_server`.
filter_path (:class:`~pywbem.CIMInstanceName`):
Instance path of the indication filter instance in the WBEM
server.
Raises:
Exceptions raised by :class:`~pywbem.WBEMConnection`.
CIMError: CIM_ERR_FAILED, if there are referencing subscriptions.
"""
# Validate server_id
server = self._get_server(server_id)
conn_id = server.conn.conn_id if server.conn is not None else None
# Verify referencing subscriptions.
ref_paths = server.conn.ReferenceNames(
filter_path, ResultClass=SUBSCRIPTION_CLASSNAME)
if ref_paths:
# DSP1054 1.2 defines that this CIM error is raised by the server
# in that case, so we simulate that behavior on the client side.
raise CIMError(
CIM_ERR_FAILED,
"The indication filter is referenced by subscriptions.",
conn_id=conn_id)
server.conn.DeleteInstance(filter_path)
inst_list = self._owned_filters[server_id]
# We iterate backwards because we change the list
for i in six.moves.range(len(inst_list) - 1, -1, -1):
inst = inst_list[i]
if inst.path == filter_path:
del inst_list[i] | python | def remove_filter(self, server_id, filter_path):
"""
Remove an indication filter from a WBEM server, by deleting the
indication filter instance in the WBEM server.
The indication filter must be owned or permanent (i.e. not static).
This method verifies that there are not currently any subscriptions on
the specified indication filter, in order to handle server
implementations that do not ensure that on the server side as required
by :term:`DSP1054`.
Parameters:
server_id (:term:`string`):
The server ID of the WBEM server, returned by
:meth:`~pywbem.WBEMSubscriptionManager.add_server`.
filter_path (:class:`~pywbem.CIMInstanceName`):
Instance path of the indication filter instance in the WBEM
server.
Raises:
Exceptions raised by :class:`~pywbem.WBEMConnection`.
CIMError: CIM_ERR_FAILED, if there are referencing subscriptions.
"""
# Validate server_id
server = self._get_server(server_id)
conn_id = server.conn.conn_id if server.conn is not None else None
# Verify referencing subscriptions.
ref_paths = server.conn.ReferenceNames(
filter_path, ResultClass=SUBSCRIPTION_CLASSNAME)
if ref_paths:
# DSP1054 1.2 defines that this CIM error is raised by the server
# in that case, so we simulate that behavior on the client side.
raise CIMError(
CIM_ERR_FAILED,
"The indication filter is referenced by subscriptions.",
conn_id=conn_id)
server.conn.DeleteInstance(filter_path)
inst_list = self._owned_filters[server_id]
# We iterate backwards because we change the list
for i in six.moves.range(len(inst_list) - 1, -1, -1):
inst = inst_list[i]
if inst.path == filter_path:
del inst_list[i] | [
"def",
"remove_filter",
"(",
"self",
",",
"server_id",
",",
"filter_path",
")",
":",
"# Validate server_id",
"server",
"=",
"self",
".",
"_get_server",
"(",
"server_id",
")",
"conn_id",
"=",
"server",
".",
"conn",
".",
"conn_id",
"if",
"server",
".",
"conn",... | Remove an indication filter from a WBEM server, by deleting the
indication filter instance in the WBEM server.
The indication filter must be owned or permanent (i.e. not static).
This method verifies that there are not currently any subscriptions on
the specified indication filter, in order to handle server
implementations that do not ensure that on the server side as required
by :term:`DSP1054`.
Parameters:
server_id (:term:`string`):
The server ID of the WBEM server, returned by
:meth:`~pywbem.WBEMSubscriptionManager.add_server`.
filter_path (:class:`~pywbem.CIMInstanceName`):
Instance path of the indication filter instance in the WBEM
server.
Raises:
Exceptions raised by :class:`~pywbem.WBEMConnection`.
CIMError: CIM_ERR_FAILED, if there are referencing subscriptions. | [
"Remove",
"an",
"indication",
"filter",
"from",
"a",
"WBEM",
"server",
"by",
"deleting",
"the",
"indication",
"filter",
"instance",
"in",
"the",
"WBEM",
"server",
"."
] | e54ecb82c2211e289a268567443d60fdd489f1e4 | https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/_subscription_manager.py#L863-L913 | train | 28,486 |
pywbem/pywbem | pywbem/_subscription_manager.py | WBEMSubscriptionManager.get_owned_subscriptions | def get_owned_subscriptions(self, server_id):
"""
Return the indication subscriptions in a WBEM server owned by this
subscription manager.
This function accesses only the local list of owned subscriptions; it
does not contact the WBEM server. The local list of owned subscriptions
is discovered from the WBEM server when the server is registered with
the subscription manager, and is maintained from then on as changes
happen through this subscription manager.
Parameters:
server_id (:term:`string`):
The server ID of the WBEM server, returned by
:meth:`~pywbem.WBEMSubscriptionManager.add_server`.
Returns:
:class:`py:list` of :class:`~pywbem.CIMInstance`: The indication
subscription instances.
"""
# Validate server_id
self._get_server(server_id)
return list(self._owned_subscriptions[server_id]) | python | def get_owned_subscriptions(self, server_id):
"""
Return the indication subscriptions in a WBEM server owned by this
subscription manager.
This function accesses only the local list of owned subscriptions; it
does not contact the WBEM server. The local list of owned subscriptions
is discovered from the WBEM server when the server is registered with
the subscription manager, and is maintained from then on as changes
happen through this subscription manager.
Parameters:
server_id (:term:`string`):
The server ID of the WBEM server, returned by
:meth:`~pywbem.WBEMSubscriptionManager.add_server`.
Returns:
:class:`py:list` of :class:`~pywbem.CIMInstance`: The indication
subscription instances.
"""
# Validate server_id
self._get_server(server_id)
return list(self._owned_subscriptions[server_id]) | [
"def",
"get_owned_subscriptions",
"(",
"self",
",",
"server_id",
")",
":",
"# Validate server_id",
"self",
".",
"_get_server",
"(",
"server_id",
")",
"return",
"list",
"(",
"self",
".",
"_owned_subscriptions",
"[",
"server_id",
"]",
")"
] | Return the indication subscriptions in a WBEM server owned by this
subscription manager.
This function accesses only the local list of owned subscriptions; it
does not contact the WBEM server. The local list of owned subscriptions
is discovered from the WBEM server when the server is registered with
the subscription manager, and is maintained from then on as changes
happen through this subscription manager.
Parameters:
server_id (:term:`string`):
The server ID of the WBEM server, returned by
:meth:`~pywbem.WBEMSubscriptionManager.add_server`.
Returns:
:class:`py:list` of :class:`~pywbem.CIMInstance`: The indication
subscription instances. | [
"Return",
"the",
"indication",
"subscriptions",
"in",
"a",
"WBEM",
"server",
"owned",
"by",
"this",
"subscription",
"manager",
"."
] | e54ecb82c2211e289a268567443d60fdd489f1e4 | https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/_subscription_manager.py#L1023-L1049 | train | 28,487 |
pywbem/pywbem | pywbem/_subscription_manager.py | WBEMSubscriptionManager.get_all_subscriptions | def get_all_subscriptions(self, server_id):
"""
Return all indication subscriptions in a WBEM server.
This function contacts the WBEM server and retrieves the indication
subscriptions by enumerating the instances of CIM class
"CIM_IndicationSubscription" in the Interop namespace of the WBEM
server.
Parameters:
server_id (:term:`string`):
The server ID of the WBEM server, returned by
:meth:`~pywbem.WBEMSubscriptionManager.add_server`.
Returns:
:class:`py:list` of :class:`~pywbem.CIMInstance`: The indication
subscription instances.
Raises:
Exceptions raised by :class:`~pywbem.WBEMConnection`.
"""
# Validate server_id
server = self._get_server(server_id)
return server.conn.EnumerateInstances(SUBSCRIPTION_CLASSNAME,
namespace=server.interop_ns) | python | def get_all_subscriptions(self, server_id):
"""
Return all indication subscriptions in a WBEM server.
This function contacts the WBEM server and retrieves the indication
subscriptions by enumerating the instances of CIM class
"CIM_IndicationSubscription" in the Interop namespace of the WBEM
server.
Parameters:
server_id (:term:`string`):
The server ID of the WBEM server, returned by
:meth:`~pywbem.WBEMSubscriptionManager.add_server`.
Returns:
:class:`py:list` of :class:`~pywbem.CIMInstance`: The indication
subscription instances.
Raises:
Exceptions raised by :class:`~pywbem.WBEMConnection`.
"""
# Validate server_id
server = self._get_server(server_id)
return server.conn.EnumerateInstances(SUBSCRIPTION_CLASSNAME,
namespace=server.interop_ns) | [
"def",
"get_all_subscriptions",
"(",
"self",
",",
"server_id",
")",
":",
"# Validate server_id",
"server",
"=",
"self",
".",
"_get_server",
"(",
"server_id",
")",
"return",
"server",
".",
"conn",
".",
"EnumerateInstances",
"(",
"SUBSCRIPTION_CLASSNAME",
",",
"name... | Return all indication subscriptions in a WBEM server.
This function contacts the WBEM server and retrieves the indication
subscriptions by enumerating the instances of CIM class
"CIM_IndicationSubscription" in the Interop namespace of the WBEM
server.
Parameters:
server_id (:term:`string`):
The server ID of the WBEM server, returned by
:meth:`~pywbem.WBEMSubscriptionManager.add_server`.
Returns:
:class:`py:list` of :class:`~pywbem.CIMInstance`: The indication
subscription instances.
Raises:
Exceptions raised by :class:`~pywbem.WBEMConnection`. | [
"Return",
"all",
"indication",
"subscriptions",
"in",
"a",
"WBEM",
"server",
"."
] | e54ecb82c2211e289a268567443d60fdd489f1e4 | https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/_subscription_manager.py#L1051-L1080 | train | 28,488 |
pywbem/pywbem | pywbem/_subscription_manager.py | WBEMSubscriptionManager._create_destination | def _create_destination(self, server_id, dest_url, owned):
"""
Create a listener destination instance in the Interop namespace of a
WBEM server and return that instance.
In order to catch any changes the server applies, the instance is
retrieved again using the instance path returned by instance creation.
Parameters:
server_id (:term:`string`):
The server ID of the WBEM server, returned by
:meth:`~pywbem.WBEMSubscriptionManager.add_server`.
dest_url (:term:`string`):
URL of the listener that is used by the WBEM server to send any
indications to.
The URL scheme (e.g. http/https) determines whether the WBEM server
uses HTTP or HTTPS for sending the indication. Host and port in the
URL specify the target location to be used by the WBEM server.
owned (:class:`py:bool`):
Defines whether or not the created instance is *owned* by the
subscription manager.
Returns:
:class:`~pywbem.CIMInstance`: The created instance, as retrieved
from the server.
Raises:
Exceptions raised by :class:`~pywbem.WBEMConnection`.
"""
# Validate server_id
server = self._get_server(server_id)
# validate the URL by reconstructing it. Do not allow defaults
host, port, ssl = parse_url(dest_url, allow_defaults=False)
schema = 'https' if ssl else 'http'
listener_url = '{0}://{1}:{2}'.format(schema, host, port)
this_host = getfqdn()
ownership = "owned" if owned else "permanent"
dest_path = CIMInstanceName(DESTINATION_CLASSNAME,
namespace=server.interop_ns)
dest_inst = CIMInstance(DESTINATION_CLASSNAME)
dest_inst.path = dest_path
dest_inst['CreationClassName'] = DESTINATION_CLASSNAME
dest_inst['SystemCreationClassName'] = SYSTEM_CREATION_CLASSNAME
dest_inst['SystemName'] = this_host
dest_inst['Name'] = _format(
'pywbemdestination:{0}:{1}:{2}',
ownership, self._subscription_manager_id, uuid.uuid4())
dest_inst['Destination'] = listener_url
if owned:
for i, inst in enumerate(self._owned_destinations[server_id]):
if inst.path == dest_path:
# It already exists, now check its properties
if inst != dest_inst:
server.conn.ModifyInstance(dest_inst)
dest_inst = server.conn.GetInstance(dest_path)
self._owned_destinations[server_id][i] = dest_inst
return dest_inst
dest_path = server.conn.CreateInstance(dest_inst)
dest_inst = server.conn.GetInstance(dest_path)
self._owned_destinations[server_id].append(dest_inst)
else:
# Responsibility to ensure it does not exist yet is with the user
dest_path = server.conn.CreateInstance(dest_inst)
dest_inst = server.conn.GetInstance(dest_path)
return dest_inst | python | def _create_destination(self, server_id, dest_url, owned):
"""
Create a listener destination instance in the Interop namespace of a
WBEM server and return that instance.
In order to catch any changes the server applies, the instance is
retrieved again using the instance path returned by instance creation.
Parameters:
server_id (:term:`string`):
The server ID of the WBEM server, returned by
:meth:`~pywbem.WBEMSubscriptionManager.add_server`.
dest_url (:term:`string`):
URL of the listener that is used by the WBEM server to send any
indications to.
The URL scheme (e.g. http/https) determines whether the WBEM server
uses HTTP or HTTPS for sending the indication. Host and port in the
URL specify the target location to be used by the WBEM server.
owned (:class:`py:bool`):
Defines whether or not the created instance is *owned* by the
subscription manager.
Returns:
:class:`~pywbem.CIMInstance`: The created instance, as retrieved
from the server.
Raises:
Exceptions raised by :class:`~pywbem.WBEMConnection`.
"""
# Validate server_id
server = self._get_server(server_id)
# validate the URL by reconstructing it. Do not allow defaults
host, port, ssl = parse_url(dest_url, allow_defaults=False)
schema = 'https' if ssl else 'http'
listener_url = '{0}://{1}:{2}'.format(schema, host, port)
this_host = getfqdn()
ownership = "owned" if owned else "permanent"
dest_path = CIMInstanceName(DESTINATION_CLASSNAME,
namespace=server.interop_ns)
dest_inst = CIMInstance(DESTINATION_CLASSNAME)
dest_inst.path = dest_path
dest_inst['CreationClassName'] = DESTINATION_CLASSNAME
dest_inst['SystemCreationClassName'] = SYSTEM_CREATION_CLASSNAME
dest_inst['SystemName'] = this_host
dest_inst['Name'] = _format(
'pywbemdestination:{0}:{1}:{2}',
ownership, self._subscription_manager_id, uuid.uuid4())
dest_inst['Destination'] = listener_url
if owned:
for i, inst in enumerate(self._owned_destinations[server_id]):
if inst.path == dest_path:
# It already exists, now check its properties
if inst != dest_inst:
server.conn.ModifyInstance(dest_inst)
dest_inst = server.conn.GetInstance(dest_path)
self._owned_destinations[server_id][i] = dest_inst
return dest_inst
dest_path = server.conn.CreateInstance(dest_inst)
dest_inst = server.conn.GetInstance(dest_path)
self._owned_destinations[server_id].append(dest_inst)
else:
# Responsibility to ensure it does not exist yet is with the user
dest_path = server.conn.CreateInstance(dest_inst)
dest_inst = server.conn.GetInstance(dest_path)
return dest_inst | [
"def",
"_create_destination",
"(",
"self",
",",
"server_id",
",",
"dest_url",
",",
"owned",
")",
":",
"# Validate server_id",
"server",
"=",
"self",
".",
"_get_server",
"(",
"server_id",
")",
"# validate the URL by reconstructing it. Do not allow defaults",
"host",
",",... | Create a listener destination instance in the Interop namespace of a
WBEM server and return that instance.
In order to catch any changes the server applies, the instance is
retrieved again using the instance path returned by instance creation.
Parameters:
server_id (:term:`string`):
The server ID of the WBEM server, returned by
:meth:`~pywbem.WBEMSubscriptionManager.add_server`.
dest_url (:term:`string`):
URL of the listener that is used by the WBEM server to send any
indications to.
The URL scheme (e.g. http/https) determines whether the WBEM server
uses HTTP or HTTPS for sending the indication. Host and port in the
URL specify the target location to be used by the WBEM server.
owned (:class:`py:bool`):
Defines whether or not the created instance is *owned* by the
subscription manager.
Returns:
:class:`~pywbem.CIMInstance`: The created instance, as retrieved
from the server.
Raises:
Exceptions raised by :class:`~pywbem.WBEMConnection`. | [
"Create",
"a",
"listener",
"destination",
"instance",
"in",
"the",
"Interop",
"namespace",
"of",
"a",
"WBEM",
"server",
"and",
"return",
"that",
"instance",
"."
] | e54ecb82c2211e289a268567443d60fdd489f1e4 | https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/_subscription_manager.py#L1128-L1205 | train | 28,489 |
pywbem/pywbem | pywbem/_subscription_manager.py | WBEMSubscriptionManager._create_subscription | def _create_subscription(self, server_id, dest_path, filter_path, owned):
"""
Create an indication subscription instance in the Interop namespace of
a WBEM server and return that instance.
In order to catch any changes the server applies, the instance is
retrieved again using the instance path returned by instance creation.
Parameters:
server_id (:term:`string`):
The server ID of the WBEM server, returned by
:meth:`~pywbem.WBEMSubscriptionManager.add_server`.
dest_path (:class:`~pywbem.CIMInstanceName`):
Instance path of the listener destination instance in the WBEM
server that references this listener.
filter_path (:class:`~pywbem.CIMInstanceName`):
Instance path of the indication filter instance in the WBEM
server that specifies the indications to be sent.
owned (:class:`py:bool`):
Defines whether or not the created instance is *owned* by the
subscription manager.
Returns:
:class:`~pywbem.CIMInstance`: The created instance, as retrieved
from the server.
Raises:
Exceptions raised by :class:`~pywbem.WBEMConnection`.
"""
# Validate server_id
server = self._get_server(server_id)
sub_path = CIMInstanceName(SUBSCRIPTION_CLASSNAME,
namespace=server.interop_ns)
sub_inst = CIMInstance(SUBSCRIPTION_CLASSNAME)
sub_inst.path = sub_path
sub_inst['Filter'] = filter_path
sub_inst['Handler'] = dest_path
if owned:
for inst in self._owned_subscriptions[server_id]:
if inst.path == sub_path:
# It does not have any properties besides its keys,
# so checking the path is sufficient.
return sub_inst
sub_path = server.conn.CreateInstance(sub_inst)
sub_inst = server.conn.GetInstance(sub_path)
self._owned_subscriptions[server_id].append(sub_inst)
else:
# Responsibility to ensure it does not exist yet is with the user
sub_path = server.conn.CreateInstance(sub_inst)
sub_inst = server.conn.GetInstance(sub_path)
return sub_inst | python | def _create_subscription(self, server_id, dest_path, filter_path, owned):
"""
Create an indication subscription instance in the Interop namespace of
a WBEM server and return that instance.
In order to catch any changes the server applies, the instance is
retrieved again using the instance path returned by instance creation.
Parameters:
server_id (:term:`string`):
The server ID of the WBEM server, returned by
:meth:`~pywbem.WBEMSubscriptionManager.add_server`.
dest_path (:class:`~pywbem.CIMInstanceName`):
Instance path of the listener destination instance in the WBEM
server that references this listener.
filter_path (:class:`~pywbem.CIMInstanceName`):
Instance path of the indication filter instance in the WBEM
server that specifies the indications to be sent.
owned (:class:`py:bool`):
Defines whether or not the created instance is *owned* by the
subscription manager.
Returns:
:class:`~pywbem.CIMInstance`: The created instance, as retrieved
from the server.
Raises:
Exceptions raised by :class:`~pywbem.WBEMConnection`.
"""
# Validate server_id
server = self._get_server(server_id)
sub_path = CIMInstanceName(SUBSCRIPTION_CLASSNAME,
namespace=server.interop_ns)
sub_inst = CIMInstance(SUBSCRIPTION_CLASSNAME)
sub_inst.path = sub_path
sub_inst['Filter'] = filter_path
sub_inst['Handler'] = dest_path
if owned:
for inst in self._owned_subscriptions[server_id]:
if inst.path == sub_path:
# It does not have any properties besides its keys,
# so checking the path is sufficient.
return sub_inst
sub_path = server.conn.CreateInstance(sub_inst)
sub_inst = server.conn.GetInstance(sub_path)
self._owned_subscriptions[server_id].append(sub_inst)
else:
# Responsibility to ensure it does not exist yet is with the user
sub_path = server.conn.CreateInstance(sub_inst)
sub_inst = server.conn.GetInstance(sub_path)
return sub_inst | [
"def",
"_create_subscription",
"(",
"self",
",",
"server_id",
",",
"dest_path",
",",
"filter_path",
",",
"owned",
")",
":",
"# Validate server_id",
"server",
"=",
"self",
".",
"_get_server",
"(",
"server_id",
")",
"sub_path",
"=",
"CIMInstanceName",
"(",
"SUBSCR... | Create an indication subscription instance in the Interop namespace of
a WBEM server and return that instance.
In order to catch any changes the server applies, the instance is
retrieved again using the instance path returned by instance creation.
Parameters:
server_id (:term:`string`):
The server ID of the WBEM server, returned by
:meth:`~pywbem.WBEMSubscriptionManager.add_server`.
dest_path (:class:`~pywbem.CIMInstanceName`):
Instance path of the listener destination instance in the WBEM
server that references this listener.
filter_path (:class:`~pywbem.CIMInstanceName`):
Instance path of the indication filter instance in the WBEM
server that specifies the indications to be sent.
owned (:class:`py:bool`):
Defines whether or not the created instance is *owned* by the
subscription manager.
Returns:
:class:`~pywbem.CIMInstance`: The created instance, as retrieved
from the server.
Raises:
Exceptions raised by :class:`~pywbem.WBEMConnection`. | [
"Create",
"an",
"indication",
"subscription",
"instance",
"in",
"the",
"Interop",
"namespace",
"of",
"a",
"WBEM",
"server",
"and",
"return",
"that",
"instance",
"."
] | e54ecb82c2211e289a268567443d60fdd489f1e4 | https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/_subscription_manager.py#L1301-L1362 | train | 28,490 |
pywbem/pywbem | pywbem_mock/_mockmofwbemconnection.py | _MockMOFWBEMConnection.CreateClass | def CreateClass(self, *args, **kwargs):
"""
Override the CreateClass method in MOFWBEMConnection
For a description of the parameters, see
:meth:`pywbem.WBEMConnection.CreateClass`.
"""
cc = args[0] if args else kwargs['NewClass']
namespace = self.getns()
try:
self.compile_ordered_classnames.append(cc.classname)
# The following generates an exception for each new ns
self.classes[self.default_namespace][cc.classname] = cc
except KeyError:
self.classes[namespace] = \
NocaseDict({cc.classname: cc})
# Validate that references and embedded instance properties, methods,
# etc. have classes that exist in repo. This also institates the
# mechanism that gets insures that prerequisite classes are inserted
# into the repo.
objects = list(cc.properties.values())
for meth in cc.methods.values():
objects += list(meth.parameters.values())
for obj in objects:
# Validate that reference_class exists in repo
if obj.type == 'reference':
try:
self.GetClass(obj.reference_class, LocalOnly=True,
IncludeQualifiers=True)
except CIMError as ce:
if ce.status_code == CIM_ERR_NOT_FOUND:
raise CIMError(
CIM_ERR_INVALID_PARAMETER,
_format("Class {0!A} referenced by element {1!A} "
"of class {2!A} in namespace {3!A} does "
"not exist",
obj.reference_class, obj.name,
cc.classname, self.getns()),
conn_id=self.conn_id)
raise
elif obj.type == 'string':
if 'EmbeddedInstance' in obj.qualifiers:
eiqualifier = obj.qualifiers['EmbeddedInstance']
try:
self.GetClass(eiqualifier.value, LocalOnly=True,
IncludeQualifiers=False)
except CIMError as ce:
if ce.status_code == CIM_ERR_NOT_FOUND:
raise CIMError(
CIM_ERR_INVALID_PARAMETER,
_format("Class {0!A} specified by "
"EmbeddInstance qualifier on element "
"{1!A} of class {2!A} in namespace "
"{3!A} does not exist",
eiqualifier.value, obj.name,
cc.classname, self.getns()),
conn_id=self.conn_id)
raise
ccr = self.conn._resolve_class( # pylint: disable=protected-access
cc, namespace, self.qualifiers[namespace])
if namespace not in self.classes:
self.classes[namespace] = NocaseDict()
self.classes[namespace][ccr.classname] = ccr
try:
self.class_names[namespace].append(ccr.classname)
except KeyError:
self.class_names[namespace] = [ccr.classname] | python | def CreateClass(self, *args, **kwargs):
"""
Override the CreateClass method in MOFWBEMConnection
For a description of the parameters, see
:meth:`pywbem.WBEMConnection.CreateClass`.
"""
cc = args[0] if args else kwargs['NewClass']
namespace = self.getns()
try:
self.compile_ordered_classnames.append(cc.classname)
# The following generates an exception for each new ns
self.classes[self.default_namespace][cc.classname] = cc
except KeyError:
self.classes[namespace] = \
NocaseDict({cc.classname: cc})
# Validate that references and embedded instance properties, methods,
# etc. have classes that exist in repo. This also institates the
# mechanism that gets insures that prerequisite classes are inserted
# into the repo.
objects = list(cc.properties.values())
for meth in cc.methods.values():
objects += list(meth.parameters.values())
for obj in objects:
# Validate that reference_class exists in repo
if obj.type == 'reference':
try:
self.GetClass(obj.reference_class, LocalOnly=True,
IncludeQualifiers=True)
except CIMError as ce:
if ce.status_code == CIM_ERR_NOT_FOUND:
raise CIMError(
CIM_ERR_INVALID_PARAMETER,
_format("Class {0!A} referenced by element {1!A} "
"of class {2!A} in namespace {3!A} does "
"not exist",
obj.reference_class, obj.name,
cc.classname, self.getns()),
conn_id=self.conn_id)
raise
elif obj.type == 'string':
if 'EmbeddedInstance' in obj.qualifiers:
eiqualifier = obj.qualifiers['EmbeddedInstance']
try:
self.GetClass(eiqualifier.value, LocalOnly=True,
IncludeQualifiers=False)
except CIMError as ce:
if ce.status_code == CIM_ERR_NOT_FOUND:
raise CIMError(
CIM_ERR_INVALID_PARAMETER,
_format("Class {0!A} specified by "
"EmbeddInstance qualifier on element "
"{1!A} of class {2!A} in namespace "
"{3!A} does not exist",
eiqualifier.value, obj.name,
cc.classname, self.getns()),
conn_id=self.conn_id)
raise
ccr = self.conn._resolve_class( # pylint: disable=protected-access
cc, namespace, self.qualifiers[namespace])
if namespace not in self.classes:
self.classes[namespace] = NocaseDict()
self.classes[namespace][ccr.classname] = ccr
try:
self.class_names[namespace].append(ccr.classname)
except KeyError:
self.class_names[namespace] = [ccr.classname] | [
"def",
"CreateClass",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"cc",
"=",
"args",
"[",
"0",
"]",
"if",
"args",
"else",
"kwargs",
"[",
"'NewClass'",
"]",
"namespace",
"=",
"self",
".",
"getns",
"(",
")",
"try",
":",
"self"... | Override the CreateClass method in MOFWBEMConnection
For a description of the parameters, see
:meth:`pywbem.WBEMConnection.CreateClass`. | [
"Override",
"the",
"CreateClass",
"method",
"in",
"MOFWBEMConnection"
] | e54ecb82c2211e289a268567443d60fdd489f1e4 | https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem_mock/_mockmofwbemconnection.py#L72-L145 | train | 28,491 |
pywbem/pywbem | pywbem_mock/_mockmofwbemconnection.py | _MockMOFWBEMConnection._get_class | def _get_class(self, superclass, namespace=None,
local_only=False, include_qualifiers=True,
include_classorigin=True):
"""
This method is just rename of GetClass to support same method
with both MOFWBEMConnection and FakedWBEMConnection
"""
return self.GetClass(superclass,
namespace=namespace,
local_only=local_only,
include_qualifiers=include_qualifiers,
include_classorigin=include_classorigin) | python | def _get_class(self, superclass, namespace=None,
local_only=False, include_qualifiers=True,
include_classorigin=True):
"""
This method is just rename of GetClass to support same method
with both MOFWBEMConnection and FakedWBEMConnection
"""
return self.GetClass(superclass,
namespace=namespace,
local_only=local_only,
include_qualifiers=include_qualifiers,
include_classorigin=include_classorigin) | [
"def",
"_get_class",
"(",
"self",
",",
"superclass",
",",
"namespace",
"=",
"None",
",",
"local_only",
"=",
"False",
",",
"include_qualifiers",
"=",
"True",
",",
"include_classorigin",
"=",
"True",
")",
":",
"return",
"self",
".",
"GetClass",
"(",
"superclas... | This method is just rename of GetClass to support same method
with both MOFWBEMConnection and FakedWBEMConnection | [
"This",
"method",
"is",
"just",
"rename",
"of",
"GetClass",
"to",
"support",
"same",
"method",
"with",
"both",
"MOFWBEMConnection",
"and",
"FakedWBEMConnection"
] | e54ecb82c2211e289a268567443d60fdd489f1e4 | https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem_mock/_mockmofwbemconnection.py#L147-L158 | train | 28,492 |
pywbem/pywbem | pywbem/tupletree.py | xml_to_tupletree_sax | def xml_to_tupletree_sax(xml_string, meaning, conn_id=None):
"""
Parse an XML string into tupletree with SAX parser.
Parses the string using the class CIMContentHandler and
returns the root element. As a SAX parser it uses minimal
memory.
This is a replacement for the previous parser (xml_to_tuple)
which used the dom parser.
Parameters:
xml_string (:term:`string`): A unicode string (when called for embedded
objects) or UTF-8 encoded byte string (when called for CIM-XML
replies) containing the XML to be parsed.
meaning (:term:`string`):
Short text with meaning of the XML string, for messages in exceptions.
conn_id (:term:`connection id`): Connection ID to be used in any
exceptions that may be raised.
Returns:
tupletree tuple with parsed XML tree
Raises:
pywbem.XMLParseError: Error detected by SAX parser or UTF-8/XML checkers
"""
handler = CIMContentHandler()
# The following conversion to a byte string is required for two reasons:
# 1. xml.sax.parseString() raises UnicodeEncodeError for unicode strings
# that contain any non-ASCII characters (despite its Python 2.7
# documentation which states that would be supported).
# 2. The SAX parser in Python 2.6 and 3.4 (pywbem does not support 3.1 -
# 3.3) does not accept unicode strings, raising:
# SAXParseException: "<unknown>:1:1: not well-formed (invalid token)"
# or:
# TypeError: 'str' does not support the buffer interface
xml_string = _ensure_bytes(xml_string)
try:
xml.sax.parseString(xml_string, handler, None)
except xml.sax.SAXParseException as exc:
# xml.sax.parse() is documented to only raise SAXParseException. In
# earlier versions of this code, xml.sax.parseString() has been found
# to raise UnicodeEncodeError when unicode strings were passed, but
# that is no longer done, so that exception is no longer caught.
# Other exception types are unexpected and will perculate upwards.
# Traceback of the exception that was caught
org_tb = sys.exc_info()[2]
# Improve quality of exception info (the check...() functions may
# raise XMLParseError):
_chk_str = check_invalid_utf8_sequences(xml_string, meaning, conn_id)
check_invalid_xml_chars(_chk_str, meaning, conn_id)
# If the checks above pass, re-raise the SAX exception info, with its
# original traceback info:
lineno, colno, new_colno, line = get_failing_line(xml_string, str(exc))
if lineno is not None:
marker_line = ' ' * (new_colno - 1) + '^'
xml_msg = _format(
"Line {0} column {1} of XML string (as binary UTF-8 string):\n"
"{2}\n"
"{3}",
lineno, colno, line, marker_line)
else:
xml_msg = _format(
"XML string (as binary UTF-8 string):\n"
"{0}",
line)
pe = XMLParseError(
_format("XML parsing error encountered in {0}: {1}\n{2}\n",
meaning, exc, xml_msg),
conn_id=conn_id)
six.reraise(type(pe), pe, org_tb) # ignore this call in traceback!
return handler.root | python | def xml_to_tupletree_sax(xml_string, meaning, conn_id=None):
"""
Parse an XML string into tupletree with SAX parser.
Parses the string using the class CIMContentHandler and
returns the root element. As a SAX parser it uses minimal
memory.
This is a replacement for the previous parser (xml_to_tuple)
which used the dom parser.
Parameters:
xml_string (:term:`string`): A unicode string (when called for embedded
objects) or UTF-8 encoded byte string (when called for CIM-XML
replies) containing the XML to be parsed.
meaning (:term:`string`):
Short text with meaning of the XML string, for messages in exceptions.
conn_id (:term:`connection id`): Connection ID to be used in any
exceptions that may be raised.
Returns:
tupletree tuple with parsed XML tree
Raises:
pywbem.XMLParseError: Error detected by SAX parser or UTF-8/XML checkers
"""
handler = CIMContentHandler()
# The following conversion to a byte string is required for two reasons:
# 1. xml.sax.parseString() raises UnicodeEncodeError for unicode strings
# that contain any non-ASCII characters (despite its Python 2.7
# documentation which states that would be supported).
# 2. The SAX parser in Python 2.6 and 3.4 (pywbem does not support 3.1 -
# 3.3) does not accept unicode strings, raising:
# SAXParseException: "<unknown>:1:1: not well-formed (invalid token)"
# or:
# TypeError: 'str' does not support the buffer interface
xml_string = _ensure_bytes(xml_string)
try:
xml.sax.parseString(xml_string, handler, None)
except xml.sax.SAXParseException as exc:
# xml.sax.parse() is documented to only raise SAXParseException. In
# earlier versions of this code, xml.sax.parseString() has been found
# to raise UnicodeEncodeError when unicode strings were passed, but
# that is no longer done, so that exception is no longer caught.
# Other exception types are unexpected and will perculate upwards.
# Traceback of the exception that was caught
org_tb = sys.exc_info()[2]
# Improve quality of exception info (the check...() functions may
# raise XMLParseError):
_chk_str = check_invalid_utf8_sequences(xml_string, meaning, conn_id)
check_invalid_xml_chars(_chk_str, meaning, conn_id)
# If the checks above pass, re-raise the SAX exception info, with its
# original traceback info:
lineno, colno, new_colno, line = get_failing_line(xml_string, str(exc))
if lineno is not None:
marker_line = ' ' * (new_colno - 1) + '^'
xml_msg = _format(
"Line {0} column {1} of XML string (as binary UTF-8 string):\n"
"{2}\n"
"{3}",
lineno, colno, line, marker_line)
else:
xml_msg = _format(
"XML string (as binary UTF-8 string):\n"
"{0}",
line)
pe = XMLParseError(
_format("XML parsing error encountered in {0}: {1}\n{2}\n",
meaning, exc, xml_msg),
conn_id=conn_id)
six.reraise(type(pe), pe, org_tb) # ignore this call in traceback!
return handler.root | [
"def",
"xml_to_tupletree_sax",
"(",
"xml_string",
",",
"meaning",
",",
"conn_id",
"=",
"None",
")",
":",
"handler",
"=",
"CIMContentHandler",
"(",
")",
"# The following conversion to a byte string is required for two reasons:",
"# 1. xml.sax.parseString() raises UnicodeEncodeErro... | Parse an XML string into tupletree with SAX parser.
Parses the string using the class CIMContentHandler and
returns the root element. As a SAX parser it uses minimal
memory.
This is a replacement for the previous parser (xml_to_tuple)
which used the dom parser.
Parameters:
xml_string (:term:`string`): A unicode string (when called for embedded
objects) or UTF-8 encoded byte string (when called for CIM-XML
replies) containing the XML to be parsed.
meaning (:term:`string`):
Short text with meaning of the XML string, for messages in exceptions.
conn_id (:term:`connection id`): Connection ID to be used in any
exceptions that may be raised.
Returns:
tupletree tuple with parsed XML tree
Raises:
pywbem.XMLParseError: Error detected by SAX parser or UTF-8/XML checkers | [
"Parse",
"an",
"XML",
"string",
"into",
"tupletree",
"with",
"SAX",
"parser",
"."
] | e54ecb82c2211e289a268567443d60fdd489f1e4 | https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/tupletree.py#L125-L210 | train | 28,493 |
pywbem/pywbem | pywbem/tupletree.py | check_invalid_xml_chars | def check_invalid_xml_chars(xml_string, meaning, conn_id=None):
"""
Examine an XML string and raise a `pywbem.XMLParseError` exception if the
string contains characters that cannot legally be represented as XML
characters.
This function is used to improve the error information raised from Python's
`xml.dom.minidom` and `xml.sax` packages and should be called only after
having catched an `ExpatError` from `xml.dom.minidom` or a
`SAXParseException` from `xml.sax` .
Parameters:
xml_string (:term:`unicode string`):
The XML string to be examined.
meaning (:term:`string`):
Short text with meaning of the XML string, for messages in exceptions.
conn_id (:term:`connection id`): Connection ID to be used in any
exceptions that may be raised.
Raises:
TypeError: Invoked with incorrect Python object type for `xml_string`.
pywbem.XMLParseError: `xml_string` contains invalid XML characters.
Notes on XML characters:
(1) The legal XML characters are defined in W3C XML 1.0 (Fith Edition):
::
Char ::= #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] |
[#x10000-#x10FFFF]
These are the code points of Unicode characters using a non-surrogate
representation.
"""
context_before = 16 # number of chars to print before any bad chars
context_after = 16 # number of chars to print after any bad chars
try:
assert isinstance(xml_string, six.text_type)
except AssertionError:
raise TypeError(
_format("xml_string parameter is not a unicode string, but has "
"type {0}", type(xml_string)))
# Check for Unicode characters that cannot legally be represented as XML
# characters.
ixc_list = list()
last_ixc_pos = -2
for m in _ILLEGAL_XML_CHARS_RE.finditer(xml_string):
ixc_pos = m.start(1)
ixc_char = m.group(1)
if ixc_pos > last_ixc_pos + 1:
ixc_list.append((ixc_pos, ixc_char))
last_ixc_pos = ixc_pos
if ixc_list:
exc_txt = "Invalid XML characters found in {0}:".format(meaning)
for (ixc_pos, ixc_char) in ixc_list:
cpos1 = max(ixc_pos - context_before, 0)
cpos2 = min(ixc_pos + context_after, len(xml_string))
exc_txt += _format("\n At offset {0}: U+{1:04X}, "
"CIM-XML snippet: {2!A}",
ixc_pos, ord(ixc_char), xml_string[cpos1:cpos2])
raise XMLParseError(exc_txt, conn_id=conn_id) | python | def check_invalid_xml_chars(xml_string, meaning, conn_id=None):
"""
Examine an XML string and raise a `pywbem.XMLParseError` exception if the
string contains characters that cannot legally be represented as XML
characters.
This function is used to improve the error information raised from Python's
`xml.dom.minidom` and `xml.sax` packages and should be called only after
having catched an `ExpatError` from `xml.dom.minidom` or a
`SAXParseException` from `xml.sax` .
Parameters:
xml_string (:term:`unicode string`):
The XML string to be examined.
meaning (:term:`string`):
Short text with meaning of the XML string, for messages in exceptions.
conn_id (:term:`connection id`): Connection ID to be used in any
exceptions that may be raised.
Raises:
TypeError: Invoked with incorrect Python object type for `xml_string`.
pywbem.XMLParseError: `xml_string` contains invalid XML characters.
Notes on XML characters:
(1) The legal XML characters are defined in W3C XML 1.0 (Fith Edition):
::
Char ::= #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] |
[#x10000-#x10FFFF]
These are the code points of Unicode characters using a non-surrogate
representation.
"""
context_before = 16 # number of chars to print before any bad chars
context_after = 16 # number of chars to print after any bad chars
try:
assert isinstance(xml_string, six.text_type)
except AssertionError:
raise TypeError(
_format("xml_string parameter is not a unicode string, but has "
"type {0}", type(xml_string)))
# Check for Unicode characters that cannot legally be represented as XML
# characters.
ixc_list = list()
last_ixc_pos = -2
for m in _ILLEGAL_XML_CHARS_RE.finditer(xml_string):
ixc_pos = m.start(1)
ixc_char = m.group(1)
if ixc_pos > last_ixc_pos + 1:
ixc_list.append((ixc_pos, ixc_char))
last_ixc_pos = ixc_pos
if ixc_list:
exc_txt = "Invalid XML characters found in {0}:".format(meaning)
for (ixc_pos, ixc_char) in ixc_list:
cpos1 = max(ixc_pos - context_before, 0)
cpos2 = min(ixc_pos + context_after, len(xml_string))
exc_txt += _format("\n At offset {0}: U+{1:04X}, "
"CIM-XML snippet: {2!A}",
ixc_pos, ord(ixc_char), xml_string[cpos1:cpos2])
raise XMLParseError(exc_txt, conn_id=conn_id) | [
"def",
"check_invalid_xml_chars",
"(",
"xml_string",
",",
"meaning",
",",
"conn_id",
"=",
"None",
")",
":",
"context_before",
"=",
"16",
"# number of chars to print before any bad chars",
"context_after",
"=",
"16",
"# number of chars to print after any bad chars",
"try",
"... | Examine an XML string and raise a `pywbem.XMLParseError` exception if the
string contains characters that cannot legally be represented as XML
characters.
This function is used to improve the error information raised from Python's
`xml.dom.minidom` and `xml.sax` packages and should be called only after
having catched an `ExpatError` from `xml.dom.minidom` or a
`SAXParseException` from `xml.sax` .
Parameters:
xml_string (:term:`unicode string`):
The XML string to be examined.
meaning (:term:`string`):
Short text with meaning of the XML string, for messages in exceptions.
conn_id (:term:`connection id`): Connection ID to be used in any
exceptions that may be raised.
Raises:
TypeError: Invoked with incorrect Python object type for `xml_string`.
pywbem.XMLParseError: `xml_string` contains invalid XML characters.
Notes on XML characters:
(1) The legal XML characters are defined in W3C XML 1.0 (Fith Edition):
::
Char ::= #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] |
[#x10000-#x10FFFF]
These are the code points of Unicode characters using a non-surrogate
representation. | [
"Examine",
"an",
"XML",
"string",
"and",
"raise",
"a",
"pywbem",
".",
"XMLParseError",
"exception",
"if",
"the",
"string",
"contains",
"characters",
"that",
"cannot",
"legally",
"be",
"represented",
"as",
"XML",
"characters",
"."
] | e54ecb82c2211e289a268567443d60fdd489f1e4 | https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/tupletree.py#L440-L509 | train | 28,494 |
ariovistus/pyd | dcompiler.py | wrapped_spawn | def wrapped_spawn(self, cmdElements, tag):
'''
wrap spawn with unique-ish travis fold prints
'''
import uuid
a = uuid.uuid1()
print("travis_fold:start:%s-%s" % (tag, a))
try:
spawn0(self, cmdElements)
finally:
print("travis_fold:end:%s-%s" % (tag, a)) | python | def wrapped_spawn(self, cmdElements, tag):
'''
wrap spawn with unique-ish travis fold prints
'''
import uuid
a = uuid.uuid1()
print("travis_fold:start:%s-%s" % (tag, a))
try:
spawn0(self, cmdElements)
finally:
print("travis_fold:end:%s-%s" % (tag, a)) | [
"def",
"wrapped_spawn",
"(",
"self",
",",
"cmdElements",
",",
"tag",
")",
":",
"import",
"uuid",
"a",
"=",
"uuid",
".",
"uuid1",
"(",
")",
"print",
"(",
"\"travis_fold:start:%s-%s\"",
"%",
"(",
"tag",
",",
"a",
")",
")",
"try",
":",
"spawn0",
"(",
"s... | wrap spawn with unique-ish travis fold prints | [
"wrap",
"spawn",
"with",
"unique",
"-",
"ish",
"travis",
"fold",
"prints"
] | 16421f437470b83b31c50ba962a7317ff3f64f79 | https://github.com/ariovistus/pyd/blob/16421f437470b83b31c50ba962a7317ff3f64f79/dcompiler.py#L182-L192 | train | 28,495 |
projectatomic/atomic-reactor | atomic_reactor/outer.py | BuildManager._build | def _build(self, build_method):
"""
build image from provided build_args
:return: BuildResults
"""
logger.info("building image '%s'", self.image)
self.ensure_not_built()
self.temp_dir = tempfile.mkdtemp()
temp_path = os.path.join(self.temp_dir, BUILD_JSON)
try:
with open(temp_path, 'w') as build_json:
json.dump(self.build_args, build_json)
self.build_container_id = build_method(self.build_image, self.temp_dir)
try:
logs_gen = self.dt.logs(self.build_container_id, stream=True)
wait_for_command(logs_gen)
return_code = self.dt.wait(self.build_container_id)
except KeyboardInterrupt:
logger.info("killing build container on user's request")
self.dt.remove_container(self.build_container_id, force=True)
results = BuildResults()
results.return_code = 1
return results
else:
results = self._load_results(self.build_container_id)
results.return_code = return_code
return results
finally:
shutil.rmtree(self.temp_dir) | python | def _build(self, build_method):
"""
build image from provided build_args
:return: BuildResults
"""
logger.info("building image '%s'", self.image)
self.ensure_not_built()
self.temp_dir = tempfile.mkdtemp()
temp_path = os.path.join(self.temp_dir, BUILD_JSON)
try:
with open(temp_path, 'w') as build_json:
json.dump(self.build_args, build_json)
self.build_container_id = build_method(self.build_image, self.temp_dir)
try:
logs_gen = self.dt.logs(self.build_container_id, stream=True)
wait_for_command(logs_gen)
return_code = self.dt.wait(self.build_container_id)
except KeyboardInterrupt:
logger.info("killing build container on user's request")
self.dt.remove_container(self.build_container_id, force=True)
results = BuildResults()
results.return_code = 1
return results
else:
results = self._load_results(self.build_container_id)
results.return_code = return_code
return results
finally:
shutil.rmtree(self.temp_dir) | [
"def",
"_build",
"(",
"self",
",",
"build_method",
")",
":",
"logger",
".",
"info",
"(",
"\"building image '%s'\"",
",",
"self",
".",
"image",
")",
"self",
".",
"ensure_not_built",
"(",
")",
"self",
".",
"temp_dir",
"=",
"tempfile",
".",
"mkdtemp",
"(",
... | build image from provided build_args
:return: BuildResults | [
"build",
"image",
"from",
"provided",
"build_args"
] | fd31c01b964097210bf169960d051e5f04019a80 | https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/outer.py#L45-L74 | train | 28,496 |
projectatomic/atomic-reactor | atomic_reactor/outer.py | BuildManager._load_results | def _load_results(self, container_id):
"""
load results from recent build
:return: BuildResults
"""
if self.temp_dir:
dt = DockerTasker()
# FIXME: load results only when requested
# results_path = os.path.join(self.temp_dir, RESULTS_JSON)
# df_path = os.path.join(self.temp_dir, 'Dockerfile')
# try:
# with open(results_path, 'r') as results_fp:
# results = json.load(results_fp, cls=BuildResultsJSONDecoder)
# except (IOError, OSError) as ex:
# logger.error("Can't open results: '%s'", repr(ex))
# for l in self.dt.logs(self.build_container_id, stream=False):
# logger.debug(l.strip())
# raise RuntimeError("Can't open results: '%s'" % repr(ex))
# results.dockerfile = open(df_path, 'r').read()
results = BuildResults()
results.build_logs = dt.logs(container_id, stream=False)
results.container_id = container_id
return results | python | def _load_results(self, container_id):
"""
load results from recent build
:return: BuildResults
"""
if self.temp_dir:
dt = DockerTasker()
# FIXME: load results only when requested
# results_path = os.path.join(self.temp_dir, RESULTS_JSON)
# df_path = os.path.join(self.temp_dir, 'Dockerfile')
# try:
# with open(results_path, 'r') as results_fp:
# results = json.load(results_fp, cls=BuildResultsJSONDecoder)
# except (IOError, OSError) as ex:
# logger.error("Can't open results: '%s'", repr(ex))
# for l in self.dt.logs(self.build_container_id, stream=False):
# logger.debug(l.strip())
# raise RuntimeError("Can't open results: '%s'" % repr(ex))
# results.dockerfile = open(df_path, 'r').read()
results = BuildResults()
results.build_logs = dt.logs(container_id, stream=False)
results.container_id = container_id
return results | [
"def",
"_load_results",
"(",
"self",
",",
"container_id",
")",
":",
"if",
"self",
".",
"temp_dir",
":",
"dt",
"=",
"DockerTasker",
"(",
")",
"# FIXME: load results only when requested",
"# results_path = os.path.join(self.temp_dir, RESULTS_JSON)",
"# df_path = os.path.join(se... | load results from recent build
:return: BuildResults | [
"load",
"results",
"from",
"recent",
"build"
] | fd31c01b964097210bf169960d051e5f04019a80 | https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/outer.py#L76-L99 | train | 28,497 |
projectatomic/atomic-reactor | atomic_reactor/outer.py | BuildManager.commit_buildroot | def commit_buildroot(self):
"""
create image from buildroot
:return:
"""
logger.info("committing buildroot")
self.ensure_is_built()
commit_message = "docker build of '%s' (%s)" % (self.image, self.uri)
self.buildroot_image_name = ImageName(
repo="buildroot-%s" % self.image,
# save the time when image was built
tag=datetime.datetime.now().strftime('%Y-%m-%d-%H-%M-%S'))
self.buildroot_image_id = self.dt.commit_container(self.build_container_id, commit_message)
return self.buildroot_image_id | python | def commit_buildroot(self):
"""
create image from buildroot
:return:
"""
logger.info("committing buildroot")
self.ensure_is_built()
commit_message = "docker build of '%s' (%s)" % (self.image, self.uri)
self.buildroot_image_name = ImageName(
repo="buildroot-%s" % self.image,
# save the time when image was built
tag=datetime.datetime.now().strftime('%Y-%m-%d-%H-%M-%S'))
self.buildroot_image_id = self.dt.commit_container(self.build_container_id, commit_message)
return self.buildroot_image_id | [
"def",
"commit_buildroot",
"(",
"self",
")",
":",
"logger",
".",
"info",
"(",
"\"committing buildroot\"",
")",
"self",
".",
"ensure_is_built",
"(",
")",
"commit_message",
"=",
"\"docker build of '%s' (%s)\"",
"%",
"(",
"self",
".",
"image",
",",
"self",
".",
"... | create image from buildroot
:return: | [
"create",
"image",
"from",
"buildroot"
] | fd31c01b964097210bf169960d051e5f04019a80 | https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/outer.py#L101-L116 | train | 28,498 |
projectatomic/atomic-reactor | docs/manpage/generate_manpage.py | ManPageFormatter.create_main_synopsis | def create_main_synopsis(self, parser):
""" create synopsis from main parser """
self.add_usage(parser.usage, parser._actions,
parser._mutually_exclusive_groups, prefix='')
usage = self._format_usage(None, parser._actions,
parser._mutually_exclusive_groups, '')
usage = usage.replace('%s ' % self._prog, '')
usage = '.SH SYNOPSIS\n \\fB%s\\fR %s\n' % (self._markup(self._prog),
usage)
return usage | python | def create_main_synopsis(self, parser):
""" create synopsis from main parser """
self.add_usage(parser.usage, parser._actions,
parser._mutually_exclusive_groups, prefix='')
usage = self._format_usage(None, parser._actions,
parser._mutually_exclusive_groups, '')
usage = usage.replace('%s ' % self._prog, '')
usage = '.SH SYNOPSIS\n \\fB%s\\fR %s\n' % (self._markup(self._prog),
usage)
return usage | [
"def",
"create_main_synopsis",
"(",
"self",
",",
"parser",
")",
":",
"self",
".",
"add_usage",
"(",
"parser",
".",
"usage",
",",
"parser",
".",
"_actions",
",",
"parser",
".",
"_mutually_exclusive_groups",
",",
"prefix",
"=",
"''",
")",
"usage",
"=",
"self... | create synopsis from main parser | [
"create",
"synopsis",
"from",
"main",
"parser"
] | fd31c01b964097210bf169960d051e5f04019a80 | https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/docs/manpage/generate_manpage.py#L77-L87 | train | 28,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.