You can subscribe to this list here.
| 2006 |
Jan
|
Feb
|
Mar
|
Apr
|
May
|
Jun
|
Jul
|
Aug
|
Sep
|
Oct
|
Nov
(26) |
Dec
(13) |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 2007 |
Jan
(5) |
Feb
(16) |
Mar
(5) |
Apr
(5) |
May
(13) |
Jun
(12) |
Jul
(1) |
Aug
(2) |
Sep
(13) |
Oct
(6) |
Nov
(1) |
Dec
(29) |
| 2008 |
Jan
(2) |
Feb
(2) |
Mar
(2) |
Apr
(57) |
May
(35) |
Jun
(45) |
Jul
(132) |
Aug
(87) |
Sep
(141) |
Oct
(86) |
Nov
(17) |
Dec
(2) |
| 2009 |
Jan
(3) |
Feb
(2) |
Mar
(3) |
Apr
(3) |
May
(1) |
Jun
|
Jul
|
Aug
(1) |
Sep
|
Oct
|
Nov
(1) |
Dec
|
| 2010 |
Jan
(2) |
Feb
|
Mar
|
Apr
|
May
|
Jun
|
Jul
|
Aug
(1) |
Sep
|
Oct
|
Nov
|
Dec
|
|
From: <jc...@us...> - 2007-08-20 16:20:54
|
Revision: 482
http://omc.svn.sourceforge.net/omc/?rev=482&view=rev
Author: jcarey
Date: 2007-08-20 09:20:56 -0700 (Mon, 20 Aug 2007)
Log Message:
-----------
Bug fixes for typos and 64 bit issues. Thanks Mike Fritch :-)
Modified Paths:
--------------
omccmpi/trunk/src/lib/omc/cmpiTimeServiceUtils.c
omccmpi/trunk/src/lib/omc/exec.c
omccmpi/trunk/src/lib/omc/ntpServer.c
Modified: omccmpi/trunk/src/lib/omc/cmpiTimeServiceUtils.c
===================================================================
--- omccmpi/trunk/src/lib/omc/cmpiTimeServiceUtils.c 2007-07-01 05:20:37 UTC (rev 481)
+++ omccmpi/trunk/src/lib/omc/cmpiTimeServiceUtils.c 2007-08-20 16:20:56 UTC (rev 482)
@@ -468,7 +468,7 @@
int *utcHwClock)
{
FILE *file;
- unsigned int bfrLen = 0;
+ size_t bfrLen = 0;
char *p = NULL, *bufPtr = NULL;
//char* errMsgBfr = NULL;
//unsigned int errMsgBfrLen = 0;
Modified: omccmpi/trunk/src/lib/omc/exec.c
===================================================================
--- omccmpi/trunk/src/lib/omc/exec.c 2007-07-01 05:20:37 UTC (rev 481)
+++ omccmpi/trunk/src/lib/omc/exec.c 2007-08-20 16:20:56 UTC (rev 482)
@@ -259,6 +259,9 @@
i--;
}
+ /* Set this process and all of it's children in a new proces group */
+ setpgid(0, 0);
+
if (envp)
{
execve(argv[0], argv, envp);
@@ -291,7 +294,7 @@
/* For some reason the child never ran exec(). Must've deadlocked or
* the system is *really* buzy. Brutally kill it.
*/
- kill(forkrv, SIGKILL);
+ kill(-forkrv, SIGKILL); // send SIGKILL to all processes in the process group
errno = ETIMEDOUT;
cc = -1;
}
@@ -403,7 +406,8 @@
*/
rerrno = (wcc == 0) ? ETIMEDOUT : errno;
terminateChild(cpid, processStatus);
- cpid = cc = -1;
+ //cpid = cc = -1;
+ cpid = -1;
break;
}
@@ -611,7 +615,7 @@
uint32_t waitTime,
int sig)
{
- if (kill(pid, sig) == -1)
+ if (kill(-pid, sig) == -1) // send sig to all processes in the process group (pid of the process group leader)
{
/* don't trust waitpid, Format ctor, etc. to leave errno alone */
int errnum = errno;
@@ -665,7 +669,7 @@
memset(pfds, 0, sizeof(pfds));
pfds[0].fd = fd1;
pfds[0].events = POLLIN;
- pfds[1].fd = fd1;
+ pfds[1].fd = fd2;
pfds[1].events = POLLIN;
cc = poll(pfds, 2, toms);
} while (cc == -1 && (errno == EAGAIN || errno == EINTR));
@@ -773,7 +777,7 @@
{
return closePipe(fds, -1);
}
- fdflags &= !O_NONBLOCK;
+ fdflags &= O_NONBLOCK;
if (fcntl(fds[i], F_SETFL, fdflags) == -1)
{
return closePipe(fds, -1);
Modified: omccmpi/trunk/src/lib/omc/ntpServer.c
===================================================================
--- omccmpi/trunk/src/lib/omc/ntpServer.c 2007-07-01 05:20:37 UTC (rev 481)
+++ omccmpi/trunk/src/lib/omc/ntpServer.c 2007-08-20 16:20:56 UTC (rev 482)
@@ -133,7 +133,7 @@
DEBUGOUT(" into serverFromLine with line: %s\n", line);
unsigned int i = 0;
- unsigned int iTokenCount = 0;
+ size_t iTokenCount = 0;
char** tokens = omcStrTokenize(line, " ,", &iTokenCount);
for(i = 0; i < iTokenCount; i++)
@@ -152,7 +152,7 @@
omcStrRTrim(pServer->serverName);
if(iTokenCount > 2)
{
- DEBUGOUT(" iTokenCount: %d\n", iTokenCount);
+ DEBUGOUT(" iTokenCount: %d\n", (int)iTokenCount);
for(i = 2; i < iTokenCount; i++)
{
if(strcasecmp(tokens[i],"prefer") == 0)
@@ -227,7 +227,7 @@
static int myNTPServerModifyLine( const char* line,
FILE* const ostrm,
char* errMsgBfr,
- unsigned int errMsgBfrLen)
+ size_t errMsgBfrLen)
{
DEBUGOUT("myNTPServerModifyLine() called\n");
@@ -268,7 +268,7 @@
static int myNTPServerDeleteLine( const char* line,
FILE* const ostrm,
char* errMsgBfr,
- unsigned int errMsgBfrLen)
+ size_t errMsgBfrLen)
{
DEBUGOUT("myNTPServerDeleteLine() called\n");
@@ -364,7 +364,7 @@
NTPServer *getNTPServers(int *pCount)
{
FILE *file;
- unsigned int bfrLen = 0;
+ size_t bfrLen = 0;
char *p = NULL, *bufPtr = NULL;
NTPServer server = {{0},0,0,0,0};
char* errMsgBfr = NULL;
@@ -435,7 +435,7 @@
NTPServer *getNTPServer(const char *serverName)
{
FILE *file;
- unsigned int bfrLen = 0;
+ size_t bfrLen = 0;
char *p, *bufPtr = NULL;
NTPServer server = {{0},0,0,0,0};
char* errMsgBfr = NULL;
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ba...@us...> - 2007-07-01 05:20:38
|
Revision: 481
http://svn.sourceforge.net/omc/?rev=481&view=rev
Author: bartw
Date: 2007-06-30 22:20:37 -0700 (Sat, 30 Jun 2007)
Log Message:
-----------
added OMC_RPMContainsFile
Modified Paths:
--------------
pysoftware/trunk/MANIFEST
pysoftware/trunk/OMC_InstalledRPMSoftwareIdentity.mof
pysoftware/trunk/OMC_InstalledRPMSoftwareIdentity.py
pysoftware/trunk/OMC_RPMSoftwareIdentity.py
pysoftware/trunk/setup.py
Added Paths:
-----------
pysoftware/trunk/OMC_RPMContainsFile.mof
pysoftware/trunk/OMC_RPMContainsFile.py
pysoftware/trunk/OMC_RPMContainsFile.reg
Modified: pysoftware/trunk/MANIFEST
===================================================================
--- pysoftware/trunk/MANIFEST 2007-06-30 18:51:43 UTC (rev 480)
+++ pysoftware/trunk/MANIFEST 2007-07-01 05:20:37 UTC (rev 481)
@@ -5,4 +5,7 @@
OMC_InstalledRPMSoftwareIdentity.mof
OMC_InstalledRPMSoftwareIdentity.py
OMC_InstalledRPMSoftwareIdentity.reg
+OMC_RPMContainsFile.mof
+OMC_RPMContainsFile.py
+OMC_RPMContainsFile.reg
setup.py
Modified: pysoftware/trunk/OMC_InstalledRPMSoftwareIdentity.mof
===================================================================
--- pysoftware/trunk/OMC_InstalledRPMSoftwareIdentity.mof 2007-06-30 18:51:43 UTC (rev 480)
+++ pysoftware/trunk/OMC_InstalledRPMSoftwareIdentity.mof 2007-07-01 05:20:37 UTC (rev 481)
@@ -1,4 +1,11 @@
class OMC_InstalledRPMSoftwareIdentity : CIM_InstalledSoftwareIdentity
{
+ [Key, Description (
+ "The system on which the software is installed.")]
+ OMC_UnitaryComputerSystem REF System;
+
+ [Key, Description (
+ "The SoftwareIdentity that is installed.")]
+ OMC_RPMSoftwareIdentity REF InstalledSoftware;
};
Modified: pysoftware/trunk/OMC_InstalledRPMSoftwareIdentity.py
===================================================================
--- pysoftware/trunk/OMC_InstalledRPMSoftwareIdentity.py 2007-06-30 18:51:43 UTC (rev 480)
+++ pysoftware/trunk/OMC_InstalledRPMSoftwareIdentity.py 2007-07-01 05:20:37 UTC (rev 481)
@@ -237,7 +237,7 @@
if (not role or role.lower() == 'installedsoftware') and \
pywbem.is_subclass(ch, object_name.namespace,
sub=object_name.classname,
- super='CIM_SoftwareIdentity'):
+ super='OMC_RPMSoftwareIdentity'):
model['InstalledSoftware'] = object_name
cs = pywbem.CIMInstanceName(classname='OMC_UnitaryComputerSystem',
namespace=object_name.namespace,
@@ -249,7 +249,7 @@
if (not role or role.lower() == 'system') and \
pywbem.is_subclass(ch, object_name.namespace,
sub=object_name.classname,
- super='CIM_System'):
+ super='OMC_UnitaryComputerSystem'):
model['System'] = object_name
iname = pywbem.CIMInstanceName(classname='OMC_RPMSoftwareIdentity',
namespace=object_name.namespace)
Added: pysoftware/trunk/OMC_RPMContainsFile.mof
===================================================================
--- pysoftware/trunk/OMC_RPMContainsFile.mof (rev 0)
+++ pysoftware/trunk/OMC_RPMContainsFile.mof 2007-07-01 05:20:37 UTC (rev 481)
@@ -0,0 +1,18 @@
+
+// TODO is there a better superclass??
+ [Association, Aggregation,
+ Description (
+ "OMC_RPMContainsFile is used to associate RPMs with the files they "
+ "contain")]
+class OMC_RPMContainsFile : CIM_Component
+{
+ [Key, Aggregate, Description (
+ "The RPM.")]
+ OMC_RPMSoftwareIdentity REF GroupComponent;
+
+ [Key, Description (
+ "The file.")]
+ CIM_LogicalFile REF PartComponent;
+
+};
+
Added: pysoftware/trunk/OMC_RPMContainsFile.py
===================================================================
--- pysoftware/trunk/OMC_RPMContainsFile.py (rev 0)
+++ pysoftware/trunk/OMC_RPMContainsFile.py 2007-07-01 05:20:37 UTC (rev 481)
@@ -0,0 +1,263 @@
+"""Python Provider for OMC_RPMContainsFile
+
+Instruments the CIM class OMC_RPMContainsFile
+
+"""
+
+import pywbem
+import rpm
+import OMC_RPMSoftwareIdentity
+import OMC_LogicalFile
+
+class OMC_RPMContainsFileProvider(pywbem.CIMProvider):
+ """Instrument the CIM class OMC_RPMContainsFile
+
+ OMC_RPMContainsFile is used to associate RPMs with the files they
+ contain
+
+ """
+
+ def __init__ (self, env):
+ logger = env.get_logger()
+ logger.log_debug('Initializing provider %s from %s' \
+ % (self.__class__.__name__, __file__))
+ # If you will be filtering instances yourself according to
+ # property_list, role, result_role, and result_class_name
+ # parameters, set self.filter_results to False
+ # self.filter_results = False
+
+ def get_instance(self, env, model, cim_class):
+ """Return an instance.
+
+ Keyword arguments:
+ env -- Provider Environment (pycimmb.ProviderEnvironment)
+ model -- A template of the pywbem.CIMInstance to be returned. The
+ key properties are set on this instance to correspond to the
+ instanceName that was requested. The properties of the model
+ are already filtered according to the PropertyList from the
+ request. Only properties present in the model need to be
+ given values. If you prefer, you can set all of the
+ values, and the instance will be filtered for you.
+ cim_class -- The pywbem.CIMClass
+
+ Possible Errors:
+ CIM_ERR_ACCESS_DENIED
+ CIM_ERR_INVALID_PARAMETER (including missing, duplicate, unrecognized
+ or otherwise incorrect parameters)
+ CIM_ERR_NOT_FOUND (the CIM Class does exist, but the requested CIM
+ Instance does not exist in the specified namespace)
+ CIM_ERR_FAILED (some other unspecified error occurred)
+
+ """
+
+ logger = env.get_logger()
+ logger.log_debug('Entering %s.get_instance()' \
+ % self.__class__.__name__)
+
+ return model
+
+ def enum_instances(self, env, model, cim_class, keys_only):
+ """Enumerate instances.
+
+ The WBEM operations EnumerateInstances and EnumerateInstanceNames
+ are both mapped to this method.
+ This method is a python generator
+
+ Keyword arguments:
+ env -- Provider Environment (pycimmb.ProviderEnvironment)
+ model -- A template of the pywbem.CIMInstances to be generated.
+ The properties of the model are already filtered according to
+ the PropertyList from the request. Only properties present in
+ the model need to be given values. If you prefer, you can
+ always set all of the values, and the instance will be filtered
+ for you.
+ cim_class -- The pywbem.CIMClass
+ keys_only -- A boolean. True if only the key properties should be
+ set on the generated instances.
+
+ Possible Errors:
+ CIM_ERR_FAILED (some other unspecified error occurred)
+
+ """
+
+ logger = env.get_logger()
+ logger.log_debug('Entering %s.enum_instances()' \
+ % self.__class__.__name__)
+
+ while False: # TODO more instances?
+ # TODO fetch system resource
+ # Key properties
+ #model['GroupComponent'] = # TODO (type = REF (pywbem.CIMInstanceName(classname='OMC_RPMSoftwareIdentity', ...))
+ #model['PartComponent'] = # TODO (type = REF (pywbem.CIMInstanceName(classname='CIM_LogicalFile', ...))
+ if keys_only:
+ yield model
+ else:
+ try:
+ yield self.get_instance(env, model, cim_class)
+ except pywbem.CIMError, (num, msg):
+ if num not in (pywbem.CIM_ERR_NOT_FOUND,
+ pywbem.CIM_ERR_ACCESS_DENIED):
+ raise
+
+ def set_instance(self, env, instance, previous_instance, cim_class):
+ """Return a newly created or modified instance.
+
+ Keyword arguments:
+ env -- Provider Environment (pycimmb.ProviderEnvironment)
+ instance -- The new pywbem.CIMInstance. If modifying an existing
+ instance, the properties on this instance have been filtered by
+ the PropertyList from the request.
+ previous_instance -- The previous pywbem.CIMInstance if modifying
+ an existing instance. None if creating a new instance.
+ cim_class -- The pywbem.CIMClass
+
+ Return the new instance. The keys must be set on the new instance.
+
+ Possible Errors:
+ CIM_ERR_ACCESS_DENIED
+ CIM_ERR_NOT_SUPPORTED
+ CIM_ERR_INVALID_PARAMETER (including missing, duplicate, unrecognized
+ or otherwise incorrect parameters)
+ CIM_ERR_ALREADY_EXISTS (the CIM Instance already exists -- only
+ valid if previous_instance is None, indicating that the operation
+ was CreateInstance)
+ CIM_ERR_NOT_FOUND (the CIM Instance does not exist -- only valid
+ if previous_instance is not None, indicating that the operation
+ was ModifyInstance)
+ CIM_ERR_FAILED (some other unspecified error occurred)
+
+ """
+
+ logger = env.get_logger()
+ logger.log_debug('Entering %s.set_instance()' \
+ % self.__class__.__name__)
+ # TODO create or modify the instance
+ raise pywbem.CIMError(pywbem.CIM_ERR_NOT_SUPPORTED) # Remove to implement
+ return instance
+
+ def delete_instance(self, env, instance_name):
+ """Delete an instance.
+
+ Keyword arguments:
+ env -- Provider Environment (pycimmb.ProviderEnvironment)
+ instance_name -- A pywbem.CIMInstanceName specifying the instance
+ to delete.
+
+ Possible Errors:
+ CIM_ERR_ACCESS_DENIED
+ CIM_ERR_NOT_SUPPORTED
+ CIM_ERR_INVALID_NAMESPACE
+ CIM_ERR_INVALID_PARAMETER (including missing, duplicate, unrecognized
+ or otherwise incorrect parameters)
+ CIM_ERR_INVALID_CLASS (the CIM Class does not exist in the specified
+ namespace)
+ CIM_ERR_NOT_FOUND (the CIM Class does exist, but the requested CIM
+ Instance does not exist in the specified namespace)
+ CIM_ERR_FAILED (some other unspecified error occurred)
+
+ """
+
+ logger = env.get_logger()
+ logger.log_debug('Entering %s.delete_instance()' \
+ % self.__class__.__name__)
+
+ # TODO delete the resource
+ raise pywbem.CIMError(pywbem.CIM_ERR_NOT_SUPPORTED) # Remove to implement
+
+ def references(self, env, object_name, model, assoc_class,
+ result_class_name, role, result_role, keys_only):
+ """Instrument Associations.
+
+ All four association-related operations (Associators, AssociatorNames,
+ References, ReferenceNames) are mapped to this method.
+ This method is a python generator
+
+ Keyword arguments:
+ env -- Provider Environment (pycimmb.ProviderEnvironment)
+ object_name -- A pywbem.CIMInstanceName that defines the source
+ CIM Object whose associated Objects are to be returned.
+ model -- A template pywbem.CIMInstance to serve as a model
+ of the objects to be returned. Only properties present on this
+ model need to be set.
+ assoc_class -- The pywbem.CIMClass.
+ result_class_name -- If not empty, this string acts as a filter on
+ the returned set of Instances by mandating that each returned
+ Instances MUST represent an association between object_name
+ and an Instance of a Class whose name matches this parameter
+ or a subclass.
+ role -- If not empty, MUST be a valid Property name. It acts as a
+ filter on the returned set of Instances by mandating that each
+ returned Instance MUST refer to object_name via a Property
+ whose name matches the value of this parameter.
+ result_role -- If not empty, MUST be a valid Property name. It acts
+ as a filter on the returned set of Instances by mandating that
+ each returned Instance MUST represent associations of
+ object_name to other Instances, where the other Instances play
+ the specified result_role in the association (i.e. the
+ name of the Property in the Association Class that refers to
+ the Object related to object_name MUST match the value of this
+ parameter).
+ keys_only -- A boolean. True if only the key properties should be
+ set on the generated instances.
+
+ The following diagram may be helpful in understanding the role,
+ result_role, and result_class_name parameters.
+ +------------------------+ +-------------------+
+ | object_name.classname | | result_class_name |
+ | ~~~~~~~~~~~~~~~~~~~~~ | | ~~~~~~~~~~~~~~~~~ |
+ +------------------------+ +-------------------+
+ | +-----------------------------------+ |
+ | | [Association] assoc_class | |
+ | object_name | ~~~~~~~~~~~~~~~~~~~~~~~~~ | |
+ +--------------+ object_name.classname REF role | |
+ (CIMInstanceName) | result_class_name REF result_role +------+
+ | |(CIMInstanceName)
+ +-----------------------------------+
+
+ Possible Errors:
+ CIM_ERR_ACCESS_DENIED
+ CIM_ERR_NOT_SUPPORTED
+ CIM_ERR_INVALID_NAMESPACE
+ CIM_ERR_INVALID_PARAMETER (including missing, duplicate, unrecognized
+ or otherwise incorrect parameters)
+ CIM_ERR_FAILED (some other unspecified error occurred)
+
+ """
+
+ logger = env.get_logger()
+ logger.log_debug('Entering %s.references()' \
+ % self.__class__.__name__)
+ ch = env.get_cimom_handle()
+ if (not role or role.lower() == 'groupcomponent') and \
+ pywbem.is_subclass(ch, object_name.namespace,
+ sub=object_name.classname,
+ super='OMC_RPMSoftwareIdentity'):
+ model['GroupComponent'] = object_name
+ id = object_name['instanceid']
+ hdr = OMC_RPMSoftwareIdentity.get_rpm_hdr(id)
+ if hdr is None:
+ return
+ for fname in hdr[rpm.RPMTAG_FILENAMES]:
+ model['PartComponent'] = OMC_LogicalFile.get_file_path(fname)
+ yield model
+
+ if (not role or role.lower() == 'partcomponent') and \
+ pywbem.is_subclass(ch, object_name.namespace,
+ sub=object_name.classname,
+ super='CIM_LogicalFile'):
+ model['PartComponent'] = object_name
+ fname = object_name['name']
+ ts = rpm.ts()
+ mi = ts.dbMatch()
+ for hdr in mi:
+ if fname in hdr[rpm.RPMTAG_FILENAMES]:
+ iname = pywbem.CIMInstanceName(classname='OMC_RPMSoftwareIdentity', namespace=object_name.namespace)
+ iname['InstanceID'] = OMC_RPMSoftwareIdentity.get_rpm_instid(hdr)
+ model['GroupComponent'] = iname
+ yield model
+
+## end of class OMC_RPMContainsFileProvider
+
+def get_providers(env):
+ omc_rpmcontainsfile_prov = OMC_RPMContainsFileProvider(env)
+ return {'OMC_RPMContainsFile': omc_rpmcontainsfile_prov}
Added: pysoftware/trunk/OMC_RPMContainsFile.reg
===================================================================
--- pysoftware/trunk/OMC_RPMContainsFile.reg (rev 0)
+++ pysoftware/trunk/OMC_RPMContainsFile.reg 2007-07-01 05:20:37 UTC (rev 481)
@@ -0,0 +1,10 @@
+// Provider registration for OMC_RPMContainsFile
+instance of OpenWBEM_PyProviderRegistration
+{
+ InstanceID = "OMC:OMC_RPMContainsFile:01";
+ NamespaceNames = {"root/cimv2"};
+ ClassName = "OMC_RPMContainsFile";
+ ProviderTypes = {1,3}; // Instance, Associator
+ ModulePath = "/usr/lib/pycim/OMC_RPMContainsFile.py";
+};
+
Modified: pysoftware/trunk/OMC_RPMSoftwareIdentity.py
===================================================================
--- pysoftware/trunk/OMC_RPMSoftwareIdentity.py 2007-06-30 18:51:43 UTC (rev 480)
+++ pysoftware/trunk/OMC_RPMSoftwareIdentity.py 2007-07-01 05:20:37 UTC (rev 481)
@@ -7,6 +7,43 @@
import pywbem
import rpm
+def get_rpm_hdr(instid):
+ hdr = None
+ try:
+ adash = instid.rindex('-')
+ arch = instid[adash+1:]
+ edash = instid.rindex('-',0, adash)
+ epoch = instid[edash+1:adash]
+ rdash = instid.rindex('-',0, edash)
+ release = instid[rdash+1:edash]
+ vdash = instid.rindex('-',0, rdash)
+ version = instid[vdash+1:rdash]
+ name = instid[8:vdash]
+ ts = rpm.ts()
+ mi = ts.dbMatch('name', name)
+ if not epoch:
+ epoch = None
+ for tmp in mi:
+ if tmp[rpm.RPMTAG_VERSION] == version and \
+ tmp[rpm.RPMTAG_RELEASE] == release and \
+ tmp[rpm.RPMTAG_EPOCH] == epoch and \
+ tmp[rpm.RPMTAG_ARCH] == arch:
+ hdr = tmp
+ break
+ except ValueError:
+ return None
+ return hdr
+
+def get_rpm_instid(hdr):
+ epoch = hdr[rpm.RPMTAG_EPOCH]
+ if epoch is None:
+ epoch = ''
+ # Key properties
+ return 'OMC:RPM:%s-%s-%s-%s-%s' % \
+ (hdr[rpm.RPMTAG_NAME], hdr[rpm.RPMTAG_VERSION],
+ hdr[rpm.RPMTAG_RELEASE],
+ epoch, hdr[rpm.RPMTAG_ARCH])
+
class OMC_RPMSoftwareIdentityProvider(pywbem.CIMProvider):
r"""Instrument the CIM class OMC_RPMSoftwareIdentity
@@ -85,33 +122,9 @@
% self.__class__.__name__)
if hdr is None:
- id = model['instanceid']
- try:
- adash = id.rindex('-')
- arch = id[adash+1:]
- edash = id.rindex('-',0, adash)
- epoch = id[edash+1:adash]
- rdash = id.rindex('-',0, edash)
- release = id[rdash+1:edash]
- vdash = id.rindex('-',0, rdash)
- version = id[vdash+1:rdash]
- name = id[8:vdash]
- ts = rpm.ts()
- mi = ts.dbMatch('name', name)
- if not epoch:
- epoch = None
- for tmp in mi:
- if tmp[rpm.RPMTAG_VERSION] == version and \
- tmp[rpm.RPMTAG_RELEASE] == release and \
- tmp[rpm.RPMTAG_EPOCH] == epoch and \
- tmp[rpm.RPMTAG_ARCH] == arch:
- hdr = tmp
- break
- except ValueError:
- hdr = None
-
- if hdr is None:
- raise pywbem.CIMError(pywbem.CIM_ERR_NOT_FOUND, id)
+ hdr = get_rpm_hdr(model['instanceid'])
+ if hdr is None:
+ raise pywbem.CIMError(pywbem.CIM_ERR_NOT_FOUND, id)
#model['BuildNumber'] = # TODO (type = pywbem.Uint16)
model['Caption'] = hdr[rpm.RPMTAG_SUMMARY]
Modified: pysoftware/trunk/setup.py
===================================================================
--- pysoftware/trunk/setup.py 2007-06-30 18:51:43 UTC (rev 480)
+++ pysoftware/trunk/setup.py 2007-07-01 05:20:37 UTC (rev 481)
@@ -13,7 +13,8 @@
description='Software Inventory Providers',
url='http://omc-project.org/',
py_modules=['OMC_RPMSoftwareIdentity',
- 'OMC_InstalledRPMSoftwareIdentity'],
+ 'OMC_InstalledRPMSoftwareIdentity',
+ 'OMC_RPMContainsFile'],
#options={'install':{'--install-lib':'/usr/lib/pycim'}},
)
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ba...@us...> - 2007-06-30 18:51:50
|
Revision: 480
http://svn.sourceforge.net/omc/?rev=480&view=rev
Author: bartw
Date: 2007-06-30 11:51:43 -0700 (Sat, 30 Jun 2007)
Log Message:
-----------
added InstalledRPMSoftwareIdentity association
Modified Paths:
--------------
pysoftware/trunk/MANIFEST
pysoftware/trunk/OMC_RPMSoftwareIdentity.py
pysoftware/trunk/setup.py
Added Paths:
-----------
pysoftware/trunk/OMC_InstalledRPMSoftwareIdentity.mof
pysoftware/trunk/OMC_InstalledRPMSoftwareIdentity.py
pysoftware/trunk/OMC_InstalledRPMSoftwareIdentity.reg
Modified: pysoftware/trunk/MANIFEST
===================================================================
--- pysoftware/trunk/MANIFEST 2007-06-30 05:20:19 UTC (rev 479)
+++ pysoftware/trunk/MANIFEST 2007-06-30 18:51:43 UTC (rev 480)
@@ -2,4 +2,7 @@
OMC_RPMSoftwareIdentity.mof
OMC_RPMSoftwareIdentity.py
OMC_RPMSoftwareIdentity.reg
+OMC_InstalledRPMSoftwareIdentity.mof
+OMC_InstalledRPMSoftwareIdentity.py
+OMC_InstalledRPMSoftwareIdentity.reg
setup.py
Added: pysoftware/trunk/OMC_InstalledRPMSoftwareIdentity.mof
===================================================================
--- pysoftware/trunk/OMC_InstalledRPMSoftwareIdentity.mof (rev 0)
+++ pysoftware/trunk/OMC_InstalledRPMSoftwareIdentity.mof 2007-06-30 18:51:43 UTC (rev 480)
@@ -0,0 +1,4 @@
+
+class OMC_InstalledRPMSoftwareIdentity : CIM_InstalledSoftwareIdentity
+{
+};
Added: pysoftware/trunk/OMC_InstalledRPMSoftwareIdentity.py
===================================================================
--- pysoftware/trunk/OMC_InstalledRPMSoftwareIdentity.py (rev 0)
+++ pysoftware/trunk/OMC_InstalledRPMSoftwareIdentity.py 2007-06-30 18:51:43 UTC (rev 480)
@@ -0,0 +1,264 @@
+"""Python Provider for OMC_InstalledRPMSoftwareIdentity
+
+Instruments the CIM class OMC_InstalledRPMSoftwareIdentity
+
+"""
+
+import pywbem
+import OMC_RPMSoftwareIdentity
+from socket import getfqdn
+
+class OMC_InstalledRPMSoftwareIdentityProvider(pywbem.CIMProvider):
+ """Instrument the CIM class OMC_InstalledRPMSoftwareIdentity
+
+ The InstalledSoftwareIdentity association identifies the System on
+ which a SoftwareIdentity is installed. This class is a corollary to
+ InstalledSoftwareElement, but deals with the asset aspects of software
+ (as indicated by SoftwareIdentity), versus the deployment aspects (as
+ indicated by SoftwareElement).
+
+ """
+
+ def __init__ (self, env):
+ logger = env.get_logger()
+ logger.log_debug('Initializing provider %s from %s' \
+ % (self.__class__.__name__, __file__))
+ # If you will be filtering instances yourself according to
+ # property_list, role, result_role, and result_class_name
+ # parameters, set self.filter_results to False
+ # self.filter_results = False
+
+ def get_instance(self, env, model, cim_class):
+ """Return an instance.
+
+ Keyword arguments:
+ env -- Provider Environment (pycimmb.ProviderEnvironment)
+ model -- A template of the pywbem.CIMInstance to be returned. The
+ key properties are set on this instance to correspond to the
+ instanceName that was requested. The properties of the model
+ are already filtered according to the PropertyList from the
+ request. Only properties present in the model need to be
+ given values. If you prefer, you can set all of the
+ values, and the instance will be filtered for you.
+ cim_class -- The pywbem.CIMClass
+
+ Possible Errors:
+ CIM_ERR_ACCESS_DENIED
+ CIM_ERR_INVALID_PARAMETER (including missing, duplicate, unrecognized
+ or otherwise incorrect parameters)
+ CIM_ERR_NOT_FOUND (the CIM Class does exist, but the requested CIM
+ Instance does not exist in the specified namespace)
+ CIM_ERR_FAILED (some other unspecified error occurred)
+
+ """
+
+ logger = env.get_logger()
+ logger.log_debug('Entering %s.get_instance()' \
+ % self.__class__.__name__)
+
+ return model
+
+ def enum_instances(self, env, model, cim_class, keys_only):
+ """Enumerate instances.
+
+ The WBEM operations EnumerateInstances and EnumerateInstanceNames
+ are both mapped to this method.
+ This method is a python generator
+
+ Keyword arguments:
+ env -- Provider Environment (pycimmb.ProviderEnvironment)
+ model -- A template of the pywbem.CIMInstances to be generated.
+ The properties of the model are already filtered according to
+ the PropertyList from the request. Only properties present in
+ the model need to be given values. If you prefer, you can
+ always set all of the values, and the instance will be filtered
+ for you.
+ cim_class -- The pywbem.CIMClass
+ keys_only -- A boolean. True if only the key properties should be
+ set on the generated instances.
+
+ Possible Errors:
+ CIM_ERR_FAILED (some other unspecified error occurred)
+
+ """
+
+ logger = env.get_logger()
+ logger.log_debug('Entering %s.enum_instances()' \
+ % self.__class__.__name__)
+ cs = pywbem.CIMInstanceName(classname='OMC_UnitaryComputerSystem',
+ namespace=model.path.namespace,
+ keybindings={'CreationClassName':'OMC_UnitaryComputerSystem',
+ 'Name':getfqdn()})
+ model['System'] = cs
+ iname = pywbem.CIMInstanceName(classname='OMC_RPMSoftwareIdentity',
+ namespace=model.path.namespace)
+ for iname in OMC_RPMSoftwareIdentity.OMC_RPMSoftwareIdentityProvider.enum_instances(env, iname, None, True):
+ model['InstalledSoftware'] = iname
+ if keys_only:
+ yield model
+ else:
+ try:
+ yield self.get_instance(env, model, cim_class)
+ except pywbem.CIMError, (num, msg):
+ if num not in (pywbem.CIM_ERR_NOT_FOUND,
+ pywbem.CIM_ERR_ACCESS_DENIED):
+ raise
+
+ def set_instance(self, env, instance, previous_instance, cim_class):
+ """Return a newly created or modified instance.
+
+ Keyword arguments:
+ env -- Provider Environment (pycimmb.ProviderEnvironment)
+ instance -- The new pywbem.CIMInstance. If modifying an existing
+ instance, the properties on this instance have been filtered by
+ the PropertyList from the request.
+ previous_instance -- The previous pywbem.CIMInstance if modifying
+ an existing instance. None if creating a new instance.
+ cim_class -- The pywbem.CIMClass
+
+ Return the new instance. The keys must be set on the new instance.
+
+ Possible Errors:
+ CIM_ERR_ACCESS_DENIED
+ CIM_ERR_NOT_SUPPORTED
+ CIM_ERR_INVALID_PARAMETER (including missing, duplicate, unrecognized
+ or otherwise incorrect parameters)
+ CIM_ERR_ALREADY_EXISTS (the CIM Instance already exists -- only
+ valid if previous_instance is None, indicating that the operation
+ was CreateInstance)
+ CIM_ERR_NOT_FOUND (the CIM Instance does not exist -- only valid
+ if previous_instance is not None, indicating that the operation
+ was ModifyInstance)
+ CIM_ERR_FAILED (some other unspecified error occurred)
+
+ """
+
+ logger = env.get_logger()
+ logger.log_debug('Entering %s.set_instance()' \
+ % self.__class__.__name__)
+ # TODO create or modify the instance
+ raise pywbem.CIMError(pywbem.CIM_ERR_NOT_SUPPORTED) # Remove to implement
+ return instance
+
+ def delete_instance(self, env, instance_name):
+ """Delete an instance.
+
+ Keyword arguments:
+ env -- Provider Environment (pycimmb.ProviderEnvironment)
+ instance_name -- A pywbem.CIMInstanceName specifying the instance
+ to delete.
+
+ Possible Errors:
+ CIM_ERR_ACCESS_DENIED
+ CIM_ERR_NOT_SUPPORTED
+ CIM_ERR_INVALID_NAMESPACE
+ CIM_ERR_INVALID_PARAMETER (including missing, duplicate, unrecognized
+ or otherwise incorrect parameters)
+ CIM_ERR_INVALID_CLASS (the CIM Class does not exist in the specified
+ namespace)
+ CIM_ERR_NOT_FOUND (the CIM Class does exist, but the requested CIM
+ Instance does not exist in the specified namespace)
+ CIM_ERR_FAILED (some other unspecified error occurred)
+
+ """
+
+ logger = env.get_logger()
+ logger.log_debug('Entering %s.delete_instance()' \
+ % self.__class__.__name__)
+
+ # TODO delete the resource
+ raise pywbem.CIMError(pywbem.CIM_ERR_NOT_SUPPORTED) # Remove to implement
+
+ def references(self, env, object_name, model, assoc_class,
+ result_class_name, role, result_role, keys_only):
+ """Instrument Associations.
+
+ All four association-related operations (Associators, AssociatorNames,
+ References, ReferenceNames) are mapped to this method.
+ This method is a python generator
+
+ Keyword arguments:
+ env -- Provider Environment (pycimmb.ProviderEnvironment)
+ object_name -- A pywbem.CIMInstanceName that defines the source
+ CIM Object whose associated Objects are to be returned.
+ model -- A template pywbem.CIMInstance to serve as a model
+ of the objects to be returned. Only properties present on this
+ model need to be set.
+ assoc_class -- The pywbem.CIMClass.
+ result_class_name -- If not empty, this string acts as a filter on
+ the returned set of Instances by mandating that each returned
+ Instances MUST represent an association between object_name
+ and an Instance of a Class whose name matches this parameter
+ or a subclass.
+ role -- If not empty, MUST be a valid Property name. It acts as a
+ filter on the returned set of Instances by mandating that each
+ returned Instance MUST refer to object_name via a Property
+ whose name matches the value of this parameter.
+ result_role -- If not empty, MUST be a valid Property name. It acts
+ as a filter on the returned set of Instances by mandating that
+ each returned Instance MUST represent associations of
+ object_name to other Instances, where the other Instances play
+ the specified result_role in the association (i.e. the
+ name of the Property in the Association Class that refers to
+ the Object related to object_name MUST match the value of this
+ parameter).
+ keys_only -- A boolean. True if only the key properties should be
+ set on the generated instances.
+
+ The following diagram may be helpful in understanding the role,
+ result_role, and result_class_name parameters.
+ +------------------------+ +-------------------+
+ | object_name.classname | | result_class_name |
+ | ~~~~~~~~~~~~~~~~~~~~~ | | ~~~~~~~~~~~~~~~~~ |
+ +------------------------+ +-------------------+
+ | +-----------------------------------+ |
+ | | [Association] assoc_class | |
+ | object_name | ~~~~~~~~~~~~~~~~~~~~~~~~~ | |
+ +--------------+ object_name.classname REF role | |
+ (CIMInstanceName) | result_class_name REF result_role +------+
+ | |(CIMInstanceName)
+ +-----------------------------------+
+
+ Possible Errors:
+ CIM_ERR_ACCESS_DENIED
+ CIM_ERR_NOT_SUPPORTED
+ CIM_ERR_INVALID_NAMESPACE
+ CIM_ERR_INVALID_PARAMETER (including missing, duplicate, unrecognized
+ or otherwise incorrect parameters)
+ CIM_ERR_FAILED (some other unspecified error occurred)
+
+ """
+
+ logger = env.get_logger()
+ logger.log_debug('Entering %s.references()' \
+ % self.__class__.__name__)
+ ch = env.get_cimom_handle()
+ # This is a common pattern. YMMV
+ if (not role or role.lower() == 'installedsoftware') and \
+ pywbem.is_subclass(ch, object_name.namespace,
+ sub=object_name.classname,
+ super='CIM_SoftwareIdentity'):
+ model['InstalledSoftware'] = object_name
+ cs = pywbem.CIMInstanceName(classname='OMC_UnitaryComputerSystem',
+ namespace=object_name.namespace,
+ keybindings={'CreationClassName':'OMC_UnitaryComputerSystem' ,
+ 'Name':getfqdn()})
+ model['System'] = cs
+ yield model
+
+ if (not role or role.lower() == 'system') and \
+ pywbem.is_subclass(ch, object_name.namespace,
+ sub=object_name.classname,
+ super='CIM_System'):
+ model['System'] = object_name
+ iname = pywbem.CIMInstanceName(classname='OMC_RPMSoftwareIdentity',
+ namespace=object_name.namespace)
+ for iname in OMC_RPMSoftwareIdentity.OMC_RPMSoftwareIdentityProvider.enum_instances(env, iname, None, True):
+ model['InstalledSoftware'] = iname
+ yield model
+
+## end of class OMC_InstalledRPMSoftwareIdentityProvider
+
+def get_providers(env):
+ omc_installedrpmsoftwareidentity_prov = OMC_InstalledRPMSoftwareIdentityProvider(env)
+ return {'OMC_InstalledRPMSoftwareIdentity': omc_installedrpmsoftwareidentity_prov}
Added: pysoftware/trunk/OMC_InstalledRPMSoftwareIdentity.reg
===================================================================
--- pysoftware/trunk/OMC_InstalledRPMSoftwareIdentity.reg (rev 0)
+++ pysoftware/trunk/OMC_InstalledRPMSoftwareIdentity.reg 2007-06-30 18:51:43 UTC (rev 480)
@@ -0,0 +1,10 @@
+// Provider registration for OMC_InstalledRPMSoftwareIdentity
+instance of OpenWBEM_PyProviderRegistration
+{
+ InstanceID = "OMC:OMC_InstalledRPMSoftwareIdentity:01";
+ NamespaceNames = {"root/cimv2"};
+ ClassName = "OMC_InstalledRPMSoftwareIdentity";
+ ProviderTypes = {1,3}; // Instance, Associator
+ ModulePath = "/usr/lib/pycim/OMC_InstalledRPMSoftwareIdentity.py";
+};
+
Modified: pysoftware/trunk/OMC_RPMSoftwareIdentity.py
===================================================================
--- pysoftware/trunk/OMC_RPMSoftwareIdentity.py 2007-06-30 05:20:19 UTC (rev 479)
+++ pysoftware/trunk/OMC_RPMSoftwareIdentity.py 2007-06-30 18:51:43 UTC (rev 480)
@@ -152,7 +152,8 @@
model['VersionString'] = hdr['version']
return model
- def enum_instances(self, env, model, cim_class, keys_only):
+ @classmethod
+ def enum_instances(cls, env, model, cim_class, keys_only):
"""Enumerate instances.
The WBEM operations EnumerateInstances and EnumerateInstanceNames
@@ -178,7 +179,7 @@
logger = env.get_logger()
logger.log_debug('Entering %s.enum_instances()' \
- % self.__class__.__name__)
+ % cls.__class__.__name__)
ts = rpm.ts()
mi = ts.dbMatch()
@@ -195,7 +196,7 @@
yield model
else:
try:
- yield self.get_instance(env, model, cim_class, hdr)
+ yield cls.get_instance(env, model, cim_class, hdr)
except pywbem.CIMError, (num, msg):
if num not in (pywbem.CIM_ERR_NOT_FOUND,
pywbem.CIM_ERR_ACCESS_DENIED):
Modified: pysoftware/trunk/setup.py
===================================================================
--- pysoftware/trunk/setup.py 2007-06-30 05:20:19 UTC (rev 479)
+++ pysoftware/trunk/setup.py 2007-06-30 18:51:43 UTC (rev 480)
@@ -12,7 +12,8 @@
version='0.1.0',
description='Software Inventory Providers',
url='http://omc-project.org/',
- py_modules=['OMC_RPMSoftwareIdentity'],
+ py_modules=['OMC_RPMSoftwareIdentity',
+ 'OMC_InstalledRPMSoftwareIdentity'],
#options={'install':{'--install-lib':'/usr/lib/pycim'}},
)
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ba...@us...> - 2007-06-30 05:20:18
|
Revision: 479
http://svn.sourceforge.net/omc/?rev=479&view=rev
Author: bartw
Date: 2007-06-29 22:20:19 -0700 (Fri, 29 Jun 2007)
Log Message:
-----------
added
Added Paths:
-----------
pysoftware/
pysoftware/trunk/
pysoftware/trunk/MANIFEST
pysoftware/trunk/OMC_RPMSoftwareIdentity.mof
pysoftware/trunk/OMC_RPMSoftwareIdentity.py
pysoftware/trunk/OMC_RPMSoftwareIdentity.reg
pysoftware/trunk/OMC_Software.mof
pysoftware/trunk/omc-pysoftware-providers.spec
pysoftware/trunk/setup.py
Added: pysoftware/trunk/MANIFEST
===================================================================
--- pysoftware/trunk/MANIFEST (rev 0)
+++ pysoftware/trunk/MANIFEST 2007-06-30 05:20:19 UTC (rev 479)
@@ -0,0 +1,5 @@
+OMC_Software.mof
+OMC_RPMSoftwareIdentity.mof
+OMC_RPMSoftwareIdentity.py
+OMC_RPMSoftwareIdentity.reg
+setup.py
Added: pysoftware/trunk/OMC_RPMSoftwareIdentity.mof
===================================================================
--- pysoftware/trunk/OMC_RPMSoftwareIdentity.mof (rev 0)
+++ pysoftware/trunk/OMC_RPMSoftwareIdentity.mof 2007-06-30 05:20:19 UTC (rev 479)
@@ -0,0 +1,7 @@
+
+class OMC_RPMSoftwareIdentity : CIM_SoftwareIdentity
+{
+ [Description("The RPM release")]
+ string ReleaseString;
+};
+
Added: pysoftware/trunk/OMC_RPMSoftwareIdentity.py
===================================================================
--- pysoftware/trunk/OMC_RPMSoftwareIdentity.py (rev 0)
+++ pysoftware/trunk/OMC_RPMSoftwareIdentity.py 2007-06-30 05:20:19 UTC (rev 479)
@@ -0,0 +1,426 @@
+"""Python Provider for OMC_RPMSoftwareIdentity
+
+Instruments the CIM class OMC_RPMSoftwareIdentity
+
+"""
+
+import pywbem
+import rpm
+
+class OMC_RPMSoftwareIdentityProvider(pywbem.CIMProvider):
+ r"""Instrument the CIM class OMC_RPMSoftwareIdentity
+
+ SoftwareIdentity provides descriptive information about a software
+ component for asset tracking and/or installation dependency
+ management. When the IsEntity property has the value TRUE, the
+ instance of SoftwareIdentity represents an individually identifiable
+ entity similar to Physical Element. SoftwareIdentity does NOT indicate
+ whether the software is installed, executing, etc. This extra
+ information may be provided through specialized associations to
+ Software Identity. For instance, both InstalledSoftwareIdentity and
+ ElementSoftwareIdentity may be used to indicate that the software
+ identified by this class is installed. SoftwareIdentity is used when
+ managing the software components of a ManagedElement that is the
+ management focus. Since software may be acquired, SoftwareIdentity can
+ be associated with a Product using the ProductSoftwareComponent
+ relationship. The Application Model manages the deployment and
+ installation of software via the classes, SoftwareFeatures and
+ SoftwareElements. SoftwareFeature and SoftwareElement are used when
+ the software component is the management focus. The
+ deployment/installation concepts are related to the asset/identity
+ one. In fact, a SoftwareIdentity may correspond to a Product, or to
+ one or more SoftwareFeatures or SoftwareElements - depending on the
+ granularity of these classes and the deployment model. The
+ correspondence of Software Identity to Product, SoftwareFeature or
+ SoftwareElement is indicated using the ConcreteIdentity association.
+ Note that there may not be sufficient detail or instrumentation to
+ instantiate ConcreteIdentity. And, if the association is instantiated,
+ some duplication of information may result. For example, the Vendor
+ described in the instances of Product and SoftwareIdentity MAY be the
+ same. However, this is not necessarily true, and it is why vendor and
+ similar information are duplicated in this class. Note that
+ ConcreteIdentity can also be used to describe the relationship of the
+ software to any LogicalFiles that result from installing it. As above,
+ there may not be sufficient detail or instrumentation to instantiate
+ this association.
+
+ """
+
+ def __init__ (self, env):
+ logger = env.get_logger()
+ logger.log_debug('Initializing provider %s from %s' \
+ % (self.__class__.__name__, __file__))
+ # If you will be filtering instances yourself according to
+ # property_list, role, result_role, and result_class_name
+ # parameters, set self.filter_results to False
+ # self.filter_results = False
+
+ def get_instance(self, env, model, cim_class, hdr=None):
+ """Return an instance.
+
+ Keyword arguments:
+ env -- Provider Environment (pycimmb.ProviderEnvironment)
+ model -- A template of the pywbem.CIMInstance to be returned. The
+ key properties are set on this instance to correspond to the
+ instanceName that was requested. The properties of the model
+ are already filtered according to the PropertyList from the
+ request. Only properties present in the model need to be
+ given values. If you prefer, you can set all of the
+ values, and the instance will be filtered for you.
+ cim_class -- The pywbem.CIMClass
+ hdr -- rpm.hdr object, or None
+
+ Possible Errors:
+ CIM_ERR_ACCESS_DENIED
+ CIM_ERR_INVALID_PARAMETER (including missing, duplicate, unrecognized
+ or otherwise incorrect parameters)
+ CIM_ERR_NOT_FOUND (the CIM Class does exist, but the requested CIM
+ Instance does not exist in the specified namespace)
+ CIM_ERR_FAILED (some other unspecified error occurred)
+
+ """
+
+ logger = env.get_logger()
+ logger.log_debug('Entering %s.get_instance()' \
+ % self.__class__.__name__)
+
+ if hdr is None:
+ id = model['instanceid']
+ try:
+ adash = id.rindex('-')
+ arch = id[adash+1:]
+ edash = id.rindex('-',0, adash)
+ epoch = id[edash+1:adash]
+ rdash = id.rindex('-',0, edash)
+ release = id[rdash+1:edash]
+ vdash = id.rindex('-',0, rdash)
+ version = id[vdash+1:rdash]
+ name = id[8:vdash]
+ ts = rpm.ts()
+ mi = ts.dbMatch('name', name)
+ if not epoch:
+ epoch = None
+ for tmp in mi:
+ if tmp[rpm.RPMTAG_VERSION] == version and \
+ tmp[rpm.RPMTAG_RELEASE] == release and \
+ tmp[rpm.RPMTAG_EPOCH] == epoch and \
+ tmp[rpm.RPMTAG_ARCH] == arch:
+ hdr = tmp
+ break
+ except ValueError:
+ hdr = None
+
+ if hdr is None:
+ raise pywbem.CIMError(pywbem.CIM_ERR_NOT_FOUND, id)
+
+ #model['BuildNumber'] = # TODO (type = pywbem.Uint16)
+ model['Caption'] = hdr[rpm.RPMTAG_SUMMARY]
+ #model['ClassificationDescriptions'] = # TODO (type = [unicode,])
+ model['Classifications'] = [self.Values.Classifications.Application_Software]
+ model['Description'] = hdr[rpm.RPMTAG_DESCRIPTION]
+ model['ElementName'] = '%s-%s-%s' % (hdr[rpm.RPMTAG_NAME],
+ hdr[rpm.RPMTAG_VERSION],
+ hdr[rpm.RPMTAG_RELEASE])
+ #model['ExtendedResourceType'] = # TODO (type = pywbem.Uint16 self.Values.ExtendedResourceType)
+ #model['HealthState'] = # TODO (type = pywbem.Uint16 self.Values.HealthState)
+ #model['IdentityInfoType'] = # TODO (type = [unicode,])
+ #model['IdentityInfoValue'] = # TODO (type = [unicode,])
+ model['InstallDate'] = pywbem.CIMDateTime.fromtimestamp(hdr[rpm.RPMTAG_INSTALLTIME])
+ model['IsEntity'] = True
+ #model['Languages'] = # TODO (type = [unicode,])
+ #model['MajorVersion'] = # TODO (type = pywbem.Uint16)
+ model['Manufacturer'] = hdr[rpm.RPMTAG_VENDOR]
+ #model['MinExtendedResourceTypeBuildNumber'] = # TODO (type = pywbem.Uint16)
+ #model['MinExtendedResourceTypeMajorVersion'] = # TODO (type = pywbem.Uint16)
+ #model['MinExtendedResourceTypeMinorVersion'] = # TODO (type = pywbem.Uint16)
+ #model['MinExtendedResourceTypeRevisionNumber'] = # TODO (type = pywbem.Uint16)
+ #model['MinorVersion'] = # TODO (type = pywbem.Uint16)
+ model['Name'] = hdr['name']
+ model['OperationalStatus'] = [self.Values.OperationalStatus.In_Service]
+ #model['OtherExtendedResourceTypeDescription'] = # TODO (type = unicode)
+ model['ReleaseDate'] = pywbem.CIMDateTime.fromtimestamp(hdr[rpm.RPMTAG_BUILDTIME])
+ model['ReleaseString'] = hdr['release']
+ #model['RevisionNumber'] = # TODO (type = pywbem.Uint16)
+ serial = hdr[rpm.RPMTAG_SERIAL]
+ if serial:
+ model['SerialNumber'] = serial
+ #model['Status'] = # TODO (type = unicode self.Values.Status)
+ #model['StatusDescriptions'] = # TODO (type = [unicode,])
+ #model['TargetOperatingSystems'] = # TODO (type = [unicode,])
+ model['TargetOSTypes'] = [self.Values.TargetOSTypes.LINUX]
+ model['TargetTypes'] = ['RPM']
+ model['VersionString'] = hdr['version']
+ return model
+
+ def enum_instances(self, env, model, cim_class, keys_only):
+ """Enumerate instances.
+
+ The WBEM operations EnumerateInstances and EnumerateInstanceNames
+ are both mapped to this method.
+ This method is a python generator
+
+ Keyword arguments:
+ env -- Provider Environment (pycimmb.ProviderEnvironment)
+ model -- A template of the pywbem.CIMInstances to be generated.
+ The properties of the model are already filtered according to
+ the PropertyList from the request. Only properties present in
+ the model need to be given values. If you prefer, you can
+ always set all of the values, and the instance will be filtered
+ for you.
+ cim_class -- The pywbem.CIMClass
+ keys_only -- A boolean. True if only the key properties should be
+ set on the generated instances.
+
+ Possible Errors:
+ CIM_ERR_FAILED (some other unspecified error occurred)
+
+ """
+
+ logger = env.get_logger()
+ logger.log_debug('Entering %s.enum_instances()' \
+ % self.__class__.__name__)
+
+ ts = rpm.ts()
+ mi = ts.dbMatch()
+ for hdr in mi:
+ epoch = hdr[rpm.RPMTAG_EPOCH]
+ if epoch is None:
+ epoch = ''
+ # Key properties
+ model['InstanceID'] = 'OMC:RPM:%s-%s-%s-%s-%s' % \
+ (hdr[rpm.RPMTAG_NAME], hdr[rpm.RPMTAG_VERSION],
+ hdr[rpm.RPMTAG_RELEASE],
+ epoch, hdr[rpm.RPMTAG_ARCH])
+ if keys_only:
+ yield model
+ else:
+ try:
+ yield self.get_instance(env, model, cim_class, hdr)
+ except pywbem.CIMError, (num, msg):
+ if num not in (pywbem.CIM_ERR_NOT_FOUND,
+ pywbem.CIM_ERR_ACCESS_DENIED):
+ raise
+
+ def set_instance(self, env, instance, previous_instance, cim_class):
+ """Return a newly created or modified instance.
+
+ Keyword arguments:
+ env -- Provider Environment (pycimmb.ProviderEnvironment)
+ instance -- The new pywbem.CIMInstance. If modifying an existing
+ instance, the properties on this instance have been filtered by
+ the PropertyList from the request.
+ previous_instance -- The previous pywbem.CIMInstance if modifying
+ an existing instance. None if creating a new instance.
+ cim_class -- The pywbem.CIMClass
+
+ Return the new instance. The keys must be set on the new instance.
+
+ Possible Errors:
+ CIM_ERR_ACCESS_DENIED
+ CIM_ERR_NOT_SUPPORTED
+ CIM_ERR_INVALID_PARAMETER (including missing, duplicate, unrecognized
+ or otherwise incorrect parameters)
+ CIM_ERR_ALREADY_EXISTS (the CIM Instance already exists -- only
+ valid if previous_instance is None, indicating that the operation
+ was CreateInstance)
+ CIM_ERR_NOT_FOUND (the CIM Instance does not exist -- only valid
+ if previous_instance is not None, indicating that the operation
+ was ModifyInstance)
+ CIM_ERR_FAILED (some other unspecified error occurred)
+
+ """
+
+ logger = env.get_logger()
+ logger.log_debug('Entering %s.set_instance()' \
+ % self.__class__.__name__)
+ # TODO create or modify the instance
+ raise pywbem.CIMError(pywbem.CIM_ERR_NOT_SUPPORTED) # Remove to implement
+ return instance
+
+ def delete_instance(self, env, instance_name):
+ """Delete an instance.
+
+ Keyword arguments:
+ env -- Provider Environment (pycimmb.ProviderEnvironment)
+ instance_name -- A pywbem.CIMInstanceName specifying the instance
+ to delete.
+
+ Possible Errors:
+ CIM_ERR_ACCESS_DENIED
+ CIM_ERR_NOT_SUPPORTED
+ CIM_ERR_INVALID_NAMESPACE
+ CIM_ERR_INVALID_PARAMETER (including missing, duplicate, unrecognized
+ or otherwise incorrect parameters)
+ CIM_ERR_INVALID_CLASS (the CIM Class does not exist in the specified
+ namespace)
+ CIM_ERR_NOT_FOUND (the CIM Class does exist, but the requested CIM
+ Instance does not exist in the specified namespace)
+ CIM_ERR_FAILED (some other unspecified error occurred)
+
+ """
+
+ logger = env.get_logger()
+ logger.log_debug('Entering %s.delete_instance()' \
+ % self.__class__.__name__)
+
+ # TODO delete the resource
+ raise pywbem.CIMError(pywbem.CIM_ERR_NOT_SUPPORTED) # Remove to implement
+
+ class Values(object):
+ class Status(object):
+ OK = 'OK'
+ Error = 'Error'
+ Degraded = 'Degraded'
+ Unknown = 'Unknown'
+ Pred_Fail = 'Pred Fail'
+ Starting = 'Starting'
+ Stopping = 'Stopping'
+ Service = 'Service'
+ Stressed = 'Stressed'
+ NonRecover = 'NonRecover'
+ No_Contact = 'No Contact'
+ Lost_Comm = 'Lost Comm'
+ Stopped = 'Stopped'
+
+ class HealthState(object):
+ Unknown = pywbem.Uint16(0)
+ OK = pywbem.Uint16(5)
+ Degraded_Warning = pywbem.Uint16(10)
+ Minor_failure = pywbem.Uint16(15)
+ Major_failure = pywbem.Uint16(20)
+ Critical_failure = pywbem.Uint16(25)
+ Non_recoverable_error = pywbem.Uint16(30)
+ # DMTF_Reserved = ..
+
+ class Classifications(object):
+ Unknown = pywbem.Uint16(0)
+ Other = pywbem.Uint16(1)
+ Driver = pywbem.Uint16(2)
+ Configuration_Software = pywbem.Uint16(3)
+ Application_Software = pywbem.Uint16(4)
+ Instrumentation = pywbem.Uint16(5)
+ Firmware_BIOS = pywbem.Uint16(6)
+ Diagnostic_Software = pywbem.Uint16(7)
+ Operating_System = pywbem.Uint16(8)
+ Middleware = pywbem.Uint16(9)
+ Firmware = pywbem.Uint16(10)
+ BIOS_FCode = pywbem.Uint16(11)
+ Support_Service_Pack = pywbem.Uint16(12)
+ Software_Bundle = pywbem.Uint16(13)
+ # DMTF_Reserved = ..
+ # Vendor_Reserved = 0x8000..0xFFFF
+
+ class TargetOSTypes(object):
+ Unknown = pywbem.Uint16(0)
+ Other = pywbem.Uint16(1)
+ MACOS = pywbem.Uint16(2)
+ ATTUNIX = pywbem.Uint16(3)
+ DGUX = pywbem.Uint16(4)
+ DECNT = pywbem.Uint16(5)
+ Tru64_UNIX = pywbem.Uint16(6)
+ OpenVMS = pywbem.Uint16(7)
+ HPUX = pywbem.Uint16(8)
+ AIX = pywbem.Uint16(9)
+ MVS = pywbem.Uint16(10)
+ OS400 = pywbem.Uint16(11)
+ OS_2 = pywbem.Uint16(12)
+ JavaVM = pywbem.Uint16(13)
+ MSDOS = pywbem.Uint16(14)
+ WIN3x = pywbem.Uint16(15)
+ WIN95 = pywbem.Uint16(16)
+ WIN98 = pywbem.Uint16(17)
+ WINNT = pywbem.Uint16(18)
+ WINCE = pywbem.Uint16(19)
+ NCR3000 = pywbem.Uint16(20)
+ NetWare = pywbem.Uint16(21)
+ OSF = pywbem.Uint16(22)
+ DC_OS = pywbem.Uint16(23)
+ Reliant_UNIX = pywbem.Uint16(24)
+ SCO_UnixWare = pywbem.Uint16(25)
+ SCO_OpenServer = pywbem.Uint16(26)
+ Sequent = pywbem.Uint16(27)
+ IRIX = pywbem.Uint16(28)
+ Solaris = pywbem.Uint16(29)
+ SunOS = pywbem.Uint16(30)
+ U6000 = pywbem.Uint16(31)
+ ASERIES = pywbem.Uint16(32)
+ HP_NonStop_OS = pywbem.Uint16(33)
+ HP_NonStop_OSS = pywbem.Uint16(34)
+ BS2000 = pywbem.Uint16(35)
+ LINUX = pywbem.Uint16(36)
+ Lynx = pywbem.Uint16(37)
+ XENIX = pywbem.Uint16(38)
+ VM = pywbem.Uint16(39)
+ Interactive_UNIX = pywbem.Uint16(40)
+ BSDUNIX = pywbem.Uint16(41)
+ FreeBSD = pywbem.Uint16(42)
+ NetBSD = pywbem.Uint16(43)
+ GNU_Hurd = pywbem.Uint16(44)
+ OS9 = pywbem.Uint16(45)
+ MACH_Kernel = pywbem.Uint16(46)
+ Inferno = pywbem.Uint16(47)
+ QNX = pywbem.Uint16(48)
+ EPOC = pywbem.Uint16(49)
+ IxWorks = pywbem.Uint16(50)
+ VxWorks = pywbem.Uint16(51)
+ MiNT = pywbem.Uint16(52)
+ BeOS = pywbem.Uint16(53)
+ HP_MPE = pywbem.Uint16(54)
+ NextStep = pywbem.Uint16(55)
+ PalmPilot = pywbem.Uint16(56)
+ Rhapsody = pywbem.Uint16(57)
+ Windows_2000 = pywbem.Uint16(58)
+ Dedicated = pywbem.Uint16(59)
+ OS_390 = pywbem.Uint16(60)
+ VSE = pywbem.Uint16(61)
+ TPF = pywbem.Uint16(62)
+ Windows__R__Me = pywbem.Uint16(63)
+ Caldera_Open_UNIX = pywbem.Uint16(64)
+ OpenBSD = pywbem.Uint16(65)
+ Not_Applicable = pywbem.Uint16(66)
+ Windows_XP = pywbem.Uint16(67)
+ z_OS = pywbem.Uint16(68)
+ Microsoft_Windows_Server_2003 = pywbem.Uint16(69)
+ Microsoft_Windows_Server_2003_64_Bit = pywbem.Uint16(70)
+
+ class ExtendedResourceType(object):
+ Unknown = pywbem.Uint16(0)
+ Other = pywbem.Uint16(1)
+ Not_Applicable = pywbem.Uint16(2)
+ Linux_RPM = pywbem.Uint16(3)
+ HP_UX_Depot = pywbem.Uint16(4)
+ Windows_MSI = pywbem.Uint16(5)
+ Solaris_Package = pywbem.Uint16(6)
+ Macintosh_Disk_Image = pywbem.Uint16(7)
+ Debian_linux_Package = pywbem.Uint16(8)
+ # DMTF_Reserved = 9..0x7FFF
+ # Vendor_Reserved = 0x8000..
+
+ class OperationalStatus(object):
+ Unknown = pywbem.Uint16(0)
+ Other = pywbem.Uint16(1)
+ OK = pywbem.Uint16(2)
+ Degraded = pywbem.Uint16(3)
+ Stressed = pywbem.Uint16(4)
+ Predictive_Failure = pywbem.Uint16(5)
+ Error = pywbem.Uint16(6)
+ Non_Recoverable_Error = pywbem.Uint16(7)
+ Starting = pywbem.Uint16(8)
+ Stopping = pywbem.Uint16(9)
+ Stopped = pywbem.Uint16(10)
+ In_Service = pywbem.Uint16(11)
+ No_Contact = pywbem.Uint16(12)
+ Lost_Communication = pywbem.Uint16(13)
+ Aborted = pywbem.Uint16(14)
+ Dormant = pywbem.Uint16(15)
+ Supporting_Entity_in_Error = pywbem.Uint16(16)
+ Completed = pywbem.Uint16(17)
+ Power_Mode = pywbem.Uint16(18)
+ # DMTF_Reserved = ..
+ # Vendor_Reserved = 0x8000..
+
+## end of class OMC_RPMSoftwareIdentityProvider
+
+def get_providers(env):
+ omc_rpmsoftwareidentity_prov = OMC_RPMSoftwareIdentityProvider(env)
+ return {'OMC_RPMSoftwareIdentity': omc_rpmsoftwareidentity_prov}
Added: pysoftware/trunk/OMC_RPMSoftwareIdentity.reg
===================================================================
--- pysoftware/trunk/OMC_RPMSoftwareIdentity.reg (rev 0)
+++ pysoftware/trunk/OMC_RPMSoftwareIdentity.reg 2007-06-30 05:20:19 UTC (rev 479)
@@ -0,0 +1,10 @@
+// Provider registration for OMC_RPMSoftwareIdentity
+instance of OpenWBEM_PyProviderRegistration
+{
+ InstanceID = "OMC:OMC_RPMSoftwareIdentity:01";
+ NamespaceNames = {"root/cimv2"};
+ ClassName = "OMC_RPMSoftwareIdentity";
+ ProviderTypes = {1}; // Instance
+ ModulePath = "/usr/lib/pycim/OMC_RPMSoftwareIdentity.py";
+};
+
Added: pysoftware/trunk/OMC_Software.mof
===================================================================
--- pysoftware/trunk/OMC_Software.mof (rev 0)
+++ pysoftware/trunk/OMC_Software.mof 2007-06-30 05:20:19 UTC (rev 479)
@@ -0,0 +1,2 @@
+#pragma include ("OMC_RPMSoftwareIdentity.mof")
+
Added: pysoftware/trunk/omc-pysoftware-providers.spec
===================================================================
--- pysoftware/trunk/omc-pysoftware-providers.spec (rev 0)
+++ pysoftware/trunk/omc-pysoftware-providers.spec 2007-06-30 05:20:19 UTC (rev 479)
@@ -0,0 +1,69 @@
+#
+# spec file for package python-pywbem (Version 0.5)
+#
+# Copyright (c) 2007 SUSE LINUX Products GmbH, Nuernberg, Germany.
+# This file and all modifications and additions to the pristine
+# package are under the same license as the package itself.
+#
+# Please submit bugfixes or comments via http://bugs.opensuse.org/
+#
+
+# norootforbuild
+
+Name: omc-pysoftware-providers
+BuildRequires: python-devel openwbem omc-pybase-providers
+Version: 0.1.0
+Release: 2
+Group: System/Management
+Summary: Instrumentation for DMTF Software Inventory Profile (DSP1023)
+License: BSD
+URL: http://omc-project.org/
+BuildArch: noarch
+Source0: %{name}-%{version}.tar.gz
+PreReq: /usr/bin/loadmof.sh
+Requires: python-pywbem openwbem openwbem-python-providerifc
+Requires: omc-pybase-providers rpm-python
+BuildRoot: %{_tmppath}/%{name}-%{version}-build
+
+%description
+Instrumentation for DMTF Software Inventory Profile (DSP1023)
+
+
+Authors:
+--------
+ Bart Whiteley
+
+%prep
+%setup
+
+%build
+python setup.py build
+
+%install
+# http://lists.opensuse.org/opensuse-packaging/2007-02/msg00005.html
+%{__rm} -rf $RPM_BUILD_ROOT
+%{__mkdir} $RPM_BUILD_ROOT
+python setup.py install --prefix=%{_prefix} --root $RPM_BUILD_ROOT \
+ --install-lib=/usr/lib/pycim -O1
+%{__mkdir} -p $RPM_BUILD_ROOT/usr/share/mof/%{name}
+install *.{mof,reg} $RPM_BUILD_ROOT/usr/share/mof/%{name}/
+
+# END OF INSTALL
+
+%clean
+%{__rm} -rf $RPM_BUILD_ROOT
+
+%files
+%defattr(-,root,root,-)
+/usr/lib/pycim/*
+/usr/share/mof/%{name}/*.mof
+/usr/share/mof/%{name}/*.reg
+
+%post
+loadmof.sh -n root/cimv2 /usr/share/mof/%{name}/OMC_Software.mof
+loadmof.sh -n Interop /usr/share/mof/%{name}/*.reg
+
+%changelog -n omc-pysoftware-providers
+* Fri Jun 29 2007 - bwh...@su...
+- First build
+
Added: pysoftware/trunk/setup.py
===================================================================
--- pysoftware/trunk/setup.py (rev 0)
+++ pysoftware/trunk/setup.py 2007-06-30 05:20:19 UTC (rev 479)
@@ -0,0 +1,18 @@
+#!/usr/bin/env python
+
+# Note, you'll typically want to override where these get installed.
+# For example:
+# python setup.py install --install-lib=/usr/lib/pycim -O1
+
+from distutils.core import setup
+
+setup(name='omc-pysoftware-providers',
+ author='Bart Whiteley',
+ author_email='bwh...@su...',
+ version='0.1.0',
+ description='Software Inventory Providers',
+ url='http://omc-project.org/',
+ py_modules=['OMC_RPMSoftwareIdentity'],
+ #options={'install':{'--install-lib':'/usr/lib/pycim'}},
+ )
+
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ba...@us...> - 2007-06-30 04:49:48
|
Revision: 478
http://svn.sourceforge.net/omc/?rev=478&view=rev
Author: bartw
Date: 2007-06-29 21:49:50 -0700 (Fri, 29 Jun 2007)
Log Message:
-----------
fixed typo
Modified Paths:
--------------
pybase/trunk/OMC_UnixProcess.py
Modified: pybase/trunk/OMC_UnixProcess.py
===================================================================
--- pybase/trunk/OMC_UnixProcess.py 2007-06-20 22:39:59 UTC (rev 477)
+++ pybase/trunk/OMC_UnixProcess.py 2007-06-30 04:49:50 UTC (rev 478)
@@ -555,8 +555,8 @@
if user_name != 'root' and user_name != puser_name:
return ('Fail', {})
logger = env.get_logger()
- logger.log_info('User %s sending signal %s to process %d',
- user_name, str(param_signal), lp.pid)
+ logger.log_info('User %s sending signal %s to process %d' \
+ % (user_name, str(param_signal), lp.pid))
cc = lp.kill(param_signal)
if cc < 0:
return ('Fail', {})
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jc...@us...> - 2007-06-20 22:40:27
|
Revision: 477
http://svn.sourceforge.net/omc/?rev=477&view=rev
Author: jcarey
Date: 2007-06-20 15:39:59 -0700 (Wed, 20 Jun 2007)
Log Message:
-----------
Setting svn:ignore
Property Changed:
----------------
pybase/trunk/
Property changes on: pybase/trunk
___________________________________________________________________
Name: svn:ignore
+ *.pyc
*.pyo
Makefile
Makefile.in
*.swp
*.tmp
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ba...@us...> - 2007-06-20 18:10:14
|
Revision: 476
http://svn.sourceforge.net/omc/?rev=476&view=rev
Author: bartw
Date: 2007-06-20 11:10:17 -0700 (Wed, 20 Jun 2007)
Log Message:
-----------
CIMProvider no longer has an __init__
Modified Paths:
--------------
pybase/trunk/OMC_InitdService.py
pybase/trunk/OMC_LogicalFile.py
pybase/trunk/OMC_OperatingSystem.py
pybase/trunk/OMC_UnitaryComputerSystem.py
pybase/trunk/OMC_UnixProcess.py
Modified: pybase/trunk/OMC_InitdService.py
===================================================================
--- pybase/trunk/OMC_InitdService.py 2007-06-20 07:11:00 UTC (rev 475)
+++ pybase/trunk/OMC_InitdService.py 2007-06-20 18:10:17 UTC (rev 476)
@@ -55,9 +55,6 @@
"""
- def __init__ (self):
- CIMProvider.__init__(self)
-
def get_instance(self, env, model, cim_class):
"""Return an instance.
Modified: pybase/trunk/OMC_LogicalFile.py
===================================================================
--- pybase/trunk/OMC_LogicalFile.py 2007-06-20 07:11:00 UTC (rev 475)
+++ pybase/trunk/OMC_LogicalFile.py 2007-06-20 18:10:17 UTC (rev 476)
@@ -191,9 +191,6 @@
# DMTF_Reserved = ..
# Vendor_Reserved = 0x8000..
- def __init__ (self):
- pywbem.CIMProvider.__init__(self)
-
def get_instance (self, env, model, cim_class, stat=None):
"""Return an instance.
@@ -434,9 +431,6 @@
"""
- def __init__ (self):
- pywbem.CIMProvider.__init__(self)
-
def get_instance (self, env, model, cim_class, stat=None):
"""Return an instance.
@@ -599,9 +593,6 @@
"""
- def __init__ (self):
- pywbem.CIMProvider.__init__(self)
-
def get_instance (self, env, model, cim_class):
"""Return an instance.
@@ -729,9 +720,6 @@
"""
- def __init__ (self):
- pywbem.CIMProvider.__init__(self)
-
def get_instance (self, env, model, cim_class):
"""Return an instance.
Modified: pybase/trunk/OMC_OperatingSystem.py
===================================================================
--- pybase/trunk/OMC_OperatingSystem.py 2007-06-20 07:11:00 UTC (rev 475)
+++ pybase/trunk/OMC_OperatingSystem.py 2007-06-20 18:10:17 UTC (rev 476)
@@ -53,9 +53,6 @@
"""
- def __init__ (self):
- CIMProvider.__init__(self)
-
def get_instance(self, env, model, cim_class):
"""Return an instance.
@@ -569,9 +566,6 @@
"""
- def __init__ (self):
- CIMProvider.__init__(self)
-
def get_instance(self, env, model, cim_class):
"""Return an instance.
Modified: pybase/trunk/OMC_UnitaryComputerSystem.py
===================================================================
--- pybase/trunk/OMC_UnitaryComputerSystem.py 2007-06-20 07:11:00 UTC (rev 475)
+++ pybase/trunk/OMC_UnitaryComputerSystem.py 2007-06-20 18:10:17 UTC (rev 476)
@@ -45,9 +45,6 @@
"""
- def __init__ (self):
- CIMProvider.__init__(self)
-
def get_instance(self, env, model, cim_class):
"""Return an instance.
Modified: pybase/trunk/OMC_UnixProcess.py
===================================================================
--- pybase/trunk/OMC_UnixProcess.py 2007-06-20 07:11:00 UTC (rev 475)
+++ pybase/trunk/OMC_UnixProcess.py 2007-06-20 18:10:17 UTC (rev 476)
@@ -182,7 +182,6 @@
#####################################
class LinuxProcess(object):
-
def __init__(self, pid):
self.pid = int(pid)
@@ -457,9 +456,6 @@
"""
- def __init__ (self):
- pywbem.CIMProvider.__init__(self)
-
def fill_instance(self, model, lp, keys_only=False):
model['OSCreationClassName'] = 'OMC_LinuxOperatingSystem'
model['CreationClassName'] = 'OMC_UnixProcess'
@@ -725,9 +721,6 @@
context of this OperatingSystem.
"""
- def __init__ (self):
- pywbem.CIMProvider.__init__(self)
-
def get_instance(self, env, model, cim_class):
logger = env.get_logger()
logger.log_debug('Entering %s.get_instance()' \
@@ -805,9 +798,6 @@
participates in the execution of the Process.
"""
- def __init__ (self):
- pywbem.CIMProvider.__init__(self)
-
def get_instance(self, env, model, cim_class):
logger = env.get_logger()
logger.log_debug('Entering %s.get_instance()' \
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ba...@us...> - 2007-06-20 07:10:59
|
Revision: 475
http://svn.sourceforge.net/omc/?rev=475&view=rev
Author: bartw
Date: 2007-06-20 00:11:00 -0700 (Wed, 20 Jun 2007)
Log Message:
-----------
make provider classes call superclass __init__
Modified Paths:
--------------
pybase/trunk/OMC_InitdService.py
pybase/trunk/OMC_LogicalFile.py
pybase/trunk/OMC_OperatingSystem.py
pybase/trunk/OMC_UnitaryComputerSystem.py
pybase/trunk/OMC_UnixProcess.py
Modified: pybase/trunk/OMC_InitdService.py
===================================================================
--- pybase/trunk/OMC_InitdService.py 2007-06-19 22:13:52 UTC (rev 474)
+++ pybase/trunk/OMC_InitdService.py 2007-06-20 07:11:00 UTC (rev 475)
@@ -56,7 +56,7 @@
"""
def __init__ (self):
- pass
+ CIMProvider.__init__(self)
def get_instance(self, env, model, cim_class):
"""Return an instance.
Modified: pybase/trunk/OMC_LogicalFile.py
===================================================================
--- pybase/trunk/OMC_LogicalFile.py 2007-06-19 22:13:52 UTC (rev 474)
+++ pybase/trunk/OMC_LogicalFile.py 2007-06-20 07:11:00 UTC (rev 475)
@@ -35,7 +35,7 @@
"""
import pywbem
-from pywbem import CIMProvider
+#from pywbem import CIMProvider
from stat import *
from statvfs import *
from socket import getfqdn
@@ -138,7 +138,7 @@
-class OMC_LinuxFileProvider(CIMProvider):
+class OMC_LinuxFileProvider(pywbem.CIMProvider):
"""Instrument the CIM class OMC_LinuxFile
The UnixFile class holds properties that are valid for various
@@ -192,7 +192,7 @@
# Vendor_Reserved = 0x8000..
def __init__ (self):
- pass
+ pywbem.CIMProvider.__init__(self)
def get_instance (self, env, model, cim_class, stat=None):
"""Return an instance.
@@ -425,7 +425,7 @@
"""
raise pywbem.CIMError(pywbem.CIM_ERR_NOT_SUPPORTED, '')
-class CIM_LogicalFileProvider(CIMProvider):
+class CIM_LogicalFileProvider(pywbem.CIMProvider):
"""Instrument the CIM class CIM_LogicalFile
A LogicalFile is a named collection of data or executable code, or
@@ -435,7 +435,7 @@
"""
def __init__ (self):
- pass
+ pywbem.CIMProvider.__init__(self)
def get_instance (self, env, model, cim_class, stat=None):
"""Return an instance.
@@ -588,7 +588,7 @@
"""
raise pywbem.CIMError(pywbem.CIM_ERR_NOT_SUPPORTED, '')
-class OMC_LinuxFileIdentityProvider(CIMProvider):
+class OMC_LinuxFileIdentityProvider(pywbem.CIMProvider):
"""Instrument the CIM class OMC_LinuxFileIdentity
CIM_FileIdentity indicates that a UnixFile describes Unix-specific
@@ -600,7 +600,7 @@
"""
def __init__ (self):
- pass
+ pywbem.CIMProvider.__init__(self)
def get_instance (self, env, model, cim_class):
"""Return an instance.
@@ -722,7 +722,7 @@
yield model
-class OMC_LinuxDirectoryContainsFileProvider(CIMProvider):
+class OMC_LinuxDirectoryContainsFileProvider(pywbem.CIMProvider):
"""Instrument the CIM class OMC_LinuxDirectoryContainsFile
Specifies the hierarchical arrangement of LogicalFiles in a Directory.
@@ -730,7 +730,7 @@
"""
def __init__ (self):
- pass
+ pywbem.CIMProvider.__init__(self)
def get_instance (self, env, model, cim_class):
"""Return an instance.
Modified: pybase/trunk/OMC_OperatingSystem.py
===================================================================
--- pybase/trunk/OMC_OperatingSystem.py 2007-06-19 22:13:52 UTC (rev 474)
+++ pybase/trunk/OMC_OperatingSystem.py 2007-06-20 07:11:00 UTC (rev 475)
@@ -54,7 +54,7 @@
"""
def __init__ (self):
- pass
+ CIMProvider.__init__(self)
def get_instance(self, env, model, cim_class):
"""Return an instance.
@@ -570,7 +570,7 @@
"""
def __init__ (self):
- pass
+ CIMProvider.__init__(self)
def get_instance(self, env, model, cim_class):
"""Return an instance.
Modified: pybase/trunk/OMC_UnitaryComputerSystem.py
===================================================================
--- pybase/trunk/OMC_UnitaryComputerSystem.py 2007-06-19 22:13:52 UTC (rev 474)
+++ pybase/trunk/OMC_UnitaryComputerSystem.py 2007-06-20 07:11:00 UTC (rev 475)
@@ -46,7 +46,7 @@
"""
def __init__ (self):
- pass
+ CIMProvider.__init__(self)
def get_instance(self, env, model, cim_class):
"""Return an instance.
Modified: pybase/trunk/OMC_UnixProcess.py
===================================================================
--- pybase/trunk/OMC_UnixProcess.py 2007-06-19 22:13:52 UTC (rev 474)
+++ pybase/trunk/OMC_UnixProcess.py 2007-06-20 07:11:00 UTC (rev 475)
@@ -458,7 +458,7 @@
"""
def __init__ (self):
- pass
+ pywbem.CIMProvider.__init__(self)
def fill_instance(self, model, lp, keys_only=False):
model['OSCreationClassName'] = 'OMC_LinuxOperatingSystem'
@@ -726,7 +726,7 @@
"""
def __init__ (self):
- pass
+ pywbem.CIMProvider.__init__(self)
def get_instance(self, env, model, cim_class):
logger = env.get_logger()
@@ -806,7 +806,7 @@
"""
def __init__ (self):
- pass
+ pywbem.CIMProvider.__init__(self)
def get_instance(self, env, model, cim_class):
logger = env.get_logger()
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jc...@us...> - 2007-06-19 22:13:51
|
Revision: 474
http://svn.sourceforge.net/omc/?rev=474&view=rev
Author: jcarey
Date: 2007-06-19 15:13:52 -0700 (Tue, 19 Jun 2007)
Log Message:
-----------
Changes for pycim move to pywbem
Modified Paths:
--------------
pybase/trunk/OMC_InitdService.py
pybase/trunk/OMC_LogicalFile.py
pybase/trunk/OMC_OperatingSystem.py
pybase/trunk/OMC_UnitaryComputerSystem.py
pybase/trunk/OMC_UnixProcess.py
Modified: pybase/trunk/OMC_InitdService.py
===================================================================
--- pybase/trunk/OMC_InitdService.py 2007-06-18 17:54:23 UTC (rev 473)
+++ pybase/trunk/OMC_InitdService.py 2007-06-19 22:13:52 UTC (rev 474)
@@ -36,7 +36,7 @@
"""
import pywbem
-from pycim import CIMProvider
+from pywbem import CIMProvider
import os
from subprocess import call
from socket import getfqdn
Modified: pybase/trunk/OMC_LogicalFile.py
===================================================================
--- pybase/trunk/OMC_LogicalFile.py 2007-06-18 17:54:23 UTC (rev 473)
+++ pybase/trunk/OMC_LogicalFile.py 2007-06-19 22:13:52 UTC (rev 474)
@@ -35,7 +35,7 @@
"""
import pywbem
-from pycim import CIMProvider
+from pywbem import CIMProvider
from stat import *
from statvfs import *
from socket import getfqdn
Modified: pybase/trunk/OMC_OperatingSystem.py
===================================================================
--- pybase/trunk/OMC_OperatingSystem.py 2007-06-18 17:54:23 UTC (rev 473)
+++ pybase/trunk/OMC_OperatingSystem.py 2007-06-19 22:13:52 UTC (rev 474)
@@ -35,7 +35,7 @@
"""
import pywbem
-from pycim import CIMProvider
+from pywbem import CIMProvider
from socket import getfqdn
def get_os_path(ns):
Modified: pybase/trunk/OMC_UnitaryComputerSystem.py
===================================================================
--- pybase/trunk/OMC_UnitaryComputerSystem.py 2007-06-18 17:54:23 UTC (rev 473)
+++ pybase/trunk/OMC_UnitaryComputerSystem.py 2007-06-19 22:13:52 UTC (rev 474)
@@ -35,7 +35,7 @@
"""
import pywbem
-from pycim import CIMProvider
+from pywbem import CIMProvider
from socket import getfqdn
class OMC_UnitaryComputerSystemProvider(CIMProvider):
Modified: pybase/trunk/OMC_UnixProcess.py
===================================================================
--- pybase/trunk/OMC_UnixProcess.py 2007-06-18 17:54:23 UTC (rev 473)
+++ pybase/trunk/OMC_UnixProcess.py 2007-06-19 22:13:52 UTC (rev 474)
@@ -35,7 +35,6 @@
"""
import pywbem, os, sys, pwd, signal, time
-from pycim import CIMProvider, is_subclass
from socket import getfqdn
provdir = os.path.dirname(__file__)
@@ -451,7 +450,7 @@
kb += 1
return kb
-class OMC_UnixProcessProvider(CIMProvider):
+class OMC_UnixProcessProvider(pywbem.CIMProvider):
"""Instrument the CIM class OMC_UnixProcess
A Unix Process
@@ -719,7 +718,7 @@
## end of class OMC_UnixProcessProvider
-class OMC_OSProcessProvider(CIMProvider):
+class OMC_OSProcessProvider(pywbem.CIMProvider):
"""Instrument the CIM class OMC_OSProcess
The relationship between the OperatingSystem and Process(es) running in the
@@ -767,8 +766,9 @@
if result_role and result_role.lower() != 'partcomponent':
return
if result_class_name:
- if not is_subclass(env.get_cimom_handle(), object_name.namespace,
- sub='omc_unixprocess', super=result_class_name):
+ if not pywbem.is_subclass(env.get_cimom_handle(),
+ object_name.namespace, sub='omc_unixprocess',
+ super=result_class_name):
return
for lp in LinuxProcess.procs():
model['GroupComponent'] = object_name
@@ -785,8 +785,9 @@
if result_role and result_role.lower() != 'groupcomponent':
return
if result_class_name:
- if not is_subclass(env.get_cimom_handle(), object_name.namespace,
- sub='omc_operatingsystem', super=result_class_name):
+ if not pywbem.is_subclass(env.get_cimom_handle(),
+ object_name.namespace, sub='omc_operatingsystem',
+ super=result_class_name):
return
from OMC_OperatingSystem import get_os_path
lp = LinuxProcess.get_proc(object_name['handle'])
@@ -797,7 +798,7 @@
yield model
## end of class OMC_OSProcessProvider
-class OMC_ProcessExecutableProvider(CIMProvider):
+class OMC_ProcessExecutableProvider(pywbem.CIMProvider):
"""Instrument the CIM class OMC_ProcessExecutable
A link between a Process and a DataFile indicating that the File
@@ -855,10 +856,10 @@
if result_role and result_role.lower() != 'antecedent':
return
if result_class_name:
- if is_subclass(env.get_cimom_handle(), object_name.namespace,
+ if pywbem.is_subclass(env.get_cimom_handle(), object_name.namespace,
sub=result_class_name, super='omc_datafile'):
pass
- elif not is_subclass(env.get_cimom_handle(),
+ elif not pywbem.is_subclass(env.get_cimom_handle(),
object_name.namespace, sub='omc_datafile',
super=result_classname):
return
@@ -872,14 +873,14 @@
yield model
return
- if is_subclass(env.get_cimom_handle(), object_name.namespace,
+ if pywbem.is_subclass(env.get_cimom_handle(), object_name.namespace,
sub=object_name.classname, super='omc_datafile'):
if role and role.lower() != 'antecedent':
return
if result_role and result_role.lower() != 'dependent':
return
if result_class_name:
- if not is_subclass(env.get_cimom_handle(), object_name.namespace,
+ if not pywbem.is_subclass(env.get_cimom_handle(), object_name.namespace,
sub='omc_unixprocess', super=result_class_name):
return
model['Antecedent'] = object_name
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jc...@us...> - 2007-06-18 17:55:06
|
Revision: 473
http://svn.sourceforge.net/omc/?rev=473&view=rev
Author: jcarey
Date: 2007-06-18 10:54:23 -0700 (Mon, 18 Jun 2007)
Log Message:
-----------
Complete Linux Process provider
Modified Paths:
--------------
pybase/trunk/OMC_UnixProcess.py
Modified: pybase/trunk/OMC_UnixProcess.py
===================================================================
--- pybase/trunk/OMC_UnixProcess.py 2007-06-12 23:41:55 UTC (rev 472)
+++ pybase/trunk/OMC_UnixProcess.py 2007-06-18 17:54:23 UTC (rev 473)
@@ -34,346 +34,557 @@
"""
-import pywbem
+import pywbem, os, sys, pwd, signal, time
from pycim import CIMProvider, is_subclass
-import os
from socket import getfqdn
-import sys
-def get_proc_path(pid):
- return pywbem.CIMInstanceName(classname='OMC_UnixProcess',
- keybindings={'OSCreationClassName':'OMC_LinuxOperatingSystem',
- 'CreationClassName':'OMC_UnixProcess',
- 'Handle':pid,
- 'CSCreationClassName':'OMC_UnitaryComputerSystem',
- 'OSName':'Linux',
- 'CSName':getfqdn()})
+provdir = os.path.dirname(__file__)
+if provdir not in sys.path:
+ sys.path.append(provdir)
-class OMC_UnixProcessProvider(CIMProvider):
- """Instrument the CIM class OMC_UnixProcess
+import OMC_LogicalFile
- A Unix Process
-
- """
- def __init__ (self):
+PROC_STATE_DOESNT_EXIST = -1
+PROC_STATE_UNKNOWN = 0
+PROC_STATE_OTHER = 1
+PROC_STATE_READY = 2
+PROC_STATE_RUNNING = 3
+PROC_STATE_BLOCKED = 4
+PROC_STATE_SUSPENDED_BLOCKED = 5
+PROC_STATE_SUSPENDED_READY = 6
+PROC_STATE_TERMINATED = 7
+PROC_STATE_STOPPED = 8
+PROC_STATE_GROWING = 9
+
+_HERTZ = 100
+_system_boot_time = None
+
+###############################################################################
+def _set_system_boot_time():
+ global _system_boot_time
+ _system_boot_time = None
+ f = open('/proc/stat')
+ try:
+ for line in f:
+ if line.find('btime') == 0:
+ _system_boot_time = long(line.split()[1])
+ break
+ finally:
+ f.close()
+ return _system_boot_time
+
+
+# Set _system_boot_time on import
+_set_system_boot_time()
+
+###############################################################################
+def _get_proc_stat_field(pid, ndx):
+ f = open('/proc/%d/stat' % pid)
+ fields = f.readline().split()
+ f.close()
+ return fields[ndx]
+
+###############################################################################
+def _get_proc_stat_fields(pid):
+ f = open('/proc/%d/stat' % pid)
+ fields = f.readline().split()
+ f.close()
+ return fields
+
+###############################################################################
+def _get_task_state(pid, tid):
+ fname = '/proc/%s/task/%s/stat' % (str(pid), str(tid))
+ fd = open(fname, 'r')
+ fields = fd.readline().split()
+ fd.close()
+ if fields[2] == 'T':
+ cc = 1
+ elif fields[2] == 'R':
+ cc = 2
+ elif fields[2] == 'D':
+ cc = 3
+ elif fields[2] == 'Z':
+ cc = 4
+ elif fields[2] == 'S':
+ cc = 5
+ elif fields[2] == 'W':
+ cc = 6
+ else:
+ cc = 7
+ return cc
+
+#####################################
+def _stateThruTasks(pid):
+ psra = [
+ PROC_STATE_UNKNOWN,
+ PROC_STATE_STOPPED,
+ PROC_STATE_RUNNING,
+ PROC_STATE_BLOCKED,
+ PROC_STATE_TERMINATED,
+ PROC_STATE_SUSPENDED_READY,
+ PROC_STATE_OTHER,
+ PROC_STATE_UNKNOWN]
+ try:
+ tnames = os.listdir('/proc/%d/task' % int(pid))
+ except:
+ return PROC_STATE_DOESNT_EXIST
+ savedpriority = 7
+ for tname in tnames:
+ try:
+ tname = str(long(tname)) # verify its numeric
+ except:
+ continue
+ statepriority = _get_task_state(pid, tname)
+ if statepriority > -1 and statepriority < savedpriority:
+ savedpriority = statepriority
+ return psra[savedpriority]
+
+def get_proc_stats(pid):
+ sd = {}
+ sd['pid'] = pid
+ try:
+ fields = _get_proc_stat_fields(pid)
+ sd['exec_name'] = fields[1][1:len(fields[1])-1]
+ sd['state'] = _stateThruTasks(pid)
+ sd['parent_process_id'] = long(fields[3])
+ sd['process_group'] = long(fields[4])
+ sd['session_id'] = long(fields[5])
+ sd['tty_number'] = long(fields[6])
+ user_mode_time = long(fields[13])
+ sd['user_mode_time'] = user_mode_time
+ kernel_mode_time = long(fields[14])
+ sd['kernel_mode_time'] = kernel_mode_time
+ sd['priority'] = long(fields[17])
+ sd['nice_value'] = long(fields[18])
+ start_time = (long(fields[21]) / 100) + _system_boot_time
+ sd['start_time'] = pywbem.CIMDateTime.fromtimestamp(start_time)
+ sd['virtual_mem_size'] = long(fields[22])
+ tot_time = user_mode_time + kernel_mode_time
+ secs_since_boot = time.time() - _system_boot_time
+ seconds = secs_since_boot - start_time / _HERTZ
+ pcpu = int(0)
+ if seconds:
+ pcpu = int((tot_time * 1000 / _HERTZ) / seconds)
+ if pcpu > 999:
+ pcpu = 999
+ sd['percent_cpu'] = float(pcpu) / 10.0
+ except:
+ print '#### Exception caught in get_proc_stats %d' % pid
+ try:
+ f = open('/proc/%d/statm' % pid)
+ fields = f.readline().split()
+ f.close()
+ sd['resident_set_size'] = long(fields[1]) * 4096
+ sd['shared_mem_size'] = long(fields[2]) * 4096
+ except:
pass
+ return sd
- def get_instance(self, env, model, cim_class):
- """Return an instance.
+#####################################
+class LinuxProcess(object):
- Keyword arguments:
- env -- Provider Environment (pycimmb.ProviderEnvironment)
- model -- A template of the pywbem.CIMInstance to be returned. The
- key properties are set on this instance to correspond to the
- instanceName that was requested. The properties of the model
- are already filtered according to the PropertyList from the
- request. Only properties present in the model need to be
- given values. If you prefer, you can set all of the
- values, and the instance will be filtered for you.
- cim_class -- The pywbem.CIMClass
+ def __init__(self, pid):
+ self.pid = int(pid)
- Possible Errors:
- CIM_ERR_ACCESS_DENIED
- CIM_ERR_INVALID_PARAMETER (including missing, duplicate, unrecognized
- or otherwise incorrect parameters)
- CIM_ERR_NOT_FOUND (the CIM Class does exist, but the requested CIM
- Instance does not exist in the specified namespace)
- CIM_ERR_FAILED (some other unspecified error occurred)
+ def procs():
+ pids = os.listdir('/proc')
+ for spid in pids:
+ try:
+ ipid = int(spid) # verify numeric
+ yield LinuxProcess(ipid)
+ except:
+ pass # Not an all numeric file name
- """
-
- logger = env.get_logger()
- logger.log_debug('Entering %s.get_instance()' \
- % self.__class__.__name__)
-
- piddir = '/proc/' + model['handle']
- if not os.path.isdir(piddir):
- raise pywbem.CIMError(pywbem.CIM_ERR_NOT_FOUND)
+ procs = staticmethod(procs)
- #model['Caption'] = # TODO (type = unicode)
- #model['CreationDate'] = # TODO (type = pywbem.CIMDateTime)
- #model['Description'] = # TODO (type = unicode)
- #model['ElementName'] = # TODO (type = unicode)
- #model['EnabledDefault'] = # TODO (type = pywbem.Uint16 self.Values.EnabledDefault) (default=2L)
- #model['EnabledState'] = # TODO (type = pywbem.Uint16 self.Values.EnabledState) (default=5L)
- #model['ExecutionState'] = # TODO (type = pywbem.Uint16 self.Values.ExecutionState)
- #model['HealthState'] = # TODO (type = pywbem.Uint16 self.Values.HealthState)
- #model['InstallDate'] = # TODO (type = pywbem.CIMDateTime)
- #model['KernelModeTime'] = # TODO (type = pywbem.Uint64)
+ def get_proc(pid):
try:
- modpath = os.readlink(piddir + '/exe')
- model['ModulePath'] = modpath
- model['Name'] = os.path.basename(modpath)
+ ipid = int(pid) # verify numeric
+ except:
+ return None
+ if os.path.isdir('/proc/%d' % ipid):
+ return LinuxProcess(ipid)
+ return None
+
+ get_proc = staticmethod(get_proc)
+
+ def get_instance_name(self, ns):
+ return pywbem.CIMInstanceName(classname='OMC_UnixProcess', namespace=ns,
+ keybindings={'OSCreationClassName':'OMC_LinuxOperatingSystem',
+ 'CreationClassName':'OMC_UnixProcess',
+ 'Handle':str(self.pid),
+ 'CSCreationClassName':'OMC_UnitaryComputerSystem',
+ 'OSName':'Linux',
+ 'CSName':getfqdn()})
+
+ def get_real_uid(self):
+ ruid = -1L
+ f = open('/proc/%d/status' % self.pid)
+ try:
+ for line in f:
+ if line.find('Uid') == 0:
+ ruid = long(line.split()[1])
+ break
+ finally:
+ f.close()
+ return ruid
+
+ def get_percent_cpu(self, include_children = False):
+ try:
+ fields = _get_proc_stat_fields(self.pid)
+ utime = long(fields[13])
+ stime = long(fields[14])
+ cutime = long(fields[15])
+ cstime = long(fields[16])
+ start_time = long(fields[21])
+ tot_time = utime + stime
+ if include_children:
+ tot_time += cutime + cstime
+
+ secs_since_boot = time.time() - _system_boot_time
+ seconds = secs_since_boot - start_time / _HERTZ
+ pcpu = 0
+ if seconds:
+ pcpu = (tot_time * 1000 / _HERTZ) / seconds
+ if pcpu > 999:
+ pcpu = 999
+ except:
+ return None
+ return float(pcpu) / 10.0
+
+ def kill(self, sig):
+ try:
+ os.kill(self.pid, sig)
except OSError:
- pass
- #model['OperationalStatus'] = # TODO (type = [pywbem.Uint16,] self.Values.OperationalStatus)
- #model['OtherEnabledState'] = # TODO (type = unicode)
- #model['OtherExecutionDescription'] = # TODO (type = unicode)
- f = open(piddir + '/cmdline')
- parms = f.read().split('\0')[:-1]
- f.close()
- if parms:
- model['Parameters'] = parms
- #model['ParentProcessID'] = # TODO (type = unicode) (Required)
- #model['PercentCPU'] = # TODO (type = pywbem.Real32)
- #model['Priority'] = # TODO (type = pywbem.Uint32) (default=0L)
- #model['ProcessGroupID'] = # TODO (type = pywbem.Uint64) (Required)
- #model['ProcessNiceValue'] = # TODO (type = pywbem.Uint32)
- #model['ProcessSessionID'] = # TODO (type = pywbem.Uint64)
- #model['ProcessTTY'] = # TODO (type = unicode)
- #model['ProcessWaitingForEvent'] = # TODO (type = unicode)
- #model['RealUserID'] = # TODO (type = pywbem.Uint64) (Required)
- #model['RequestedState'] = # TODO (type = pywbem.Uint16 self.Values.RequestedState) (default=12L)
- #model['Status'] = # TODO (type = unicode self.Values.Status)
- #model['StatusDescriptions'] = # TODO (type = [unicode,])
- #model['TerminationDate'] = # TODO (type = pywbem.CIMDateTime)
- #model['TimeOfLastStateChange'] = # TODO (type = pywbem.CIMDateTime)
- #model['UnixPriority'] = # TODO (type = pywbem.Sint32)
- #model['UserModeTime'] = # TODO (type = pywbem.Uint64)
- #model['VirtualMemorySize'] = # TODO (type = pywbem.Uint32)
- #model['WorkingSetSize'] = # TODO (type = pywbem.Uint64)
- return model
+ return -1
+ return 0
- def enum_instances(self, env, model, cim_class, keys_only):
- """Enumerate instances.
+ def get_command_line(self):
+ try:
+ f = open('/proc/%d/cmdline' % self.pid)
+ l = f.readline()
+ f.close()
+ rl = []
+ for arg in l.split('\0'):
+ if arg:
+ rl.append(arg)
+ except:
+ return []
+ return rl
- The WBEM operations EnumerateInstances and EnumerateInstanceNames
- are both mapped to this method.
- This method is a python generator
+ def get_env(self):
+ try:
+ f = open('/proc/%d/environ' % self.pid)
+ l = f.readline()
+ f.close()
+ d = dict(i.split('=',1) for i in l.split('\0'))
+ except:
+ return {}
+ return d
- Keyword arguments:
- env -- Provider Environment (pycimmb.ProviderEnvironment)
- model -- A template of the pywbem.CIMInstances to be generated.
- The properties of the model are already filtered according to
- the PropertyList from the request. Only properties present in
- the model need to be given values. If you prefer, you can
- always set all of the values, and the instance will be filtered
- for you.
- cim_class -- The pywbem.CIMClass
- keys_only -- A boolean. True if only the key properties should be
- set on the generated instances.
+ def get_open_files(self):
+ try:
+ rv = []
+ dname = '/proc/%d/fd/' % self.pid
+ for fname in os.listdir(dname):
+ rv.append(os.readlink(dname + fname))
+ except:
+ return []
+ return rv
- Possible Errors:
- CIM_ERR_FAILED (some other unspecified error occurred)
+ def get_root(self):
+ try:
+ s = os.readlink('/proc/%d/root' % self.pid)
+ except:
+ return ''
+ return s
- """
+ def get_cwd(self):
+ try:
+ s = os.readlink('/proc/%d/cwd' % self.pid)
+ except:
+ return ''
+ return s
- logger = env.get_logger()
- logger.log_debug('Entering %s.enum_instances()' \
- % self.__class__.__name__)
+ def get_module_path(self):
+ try:
+ s = os.readlink('/proc/%d/exe' % self.pid)
+ except:
+ return ''
+ return s
- for pid in os.listdir('/proc'):
- if not pid.isdigit():
- continue
- # Key properties
- model['OSCreationClassName'] = 'OMC_LinuxOperatingSystem'
- model['CreationClassName'] = 'OMC_UnixProcess'
- model['Handle'] = pid
- model['CSCreationClassName'] = 'OMC_UnitaryComputerSystem'
- model['OSName'] = 'Linux'
- model['CSName'] = getfqdn()
- if keys_only:
- yield model
- else:
- try:
- yield self.get_instance(env, model, cim_class)
- except pywbem.CIMError, (num, msg):
- if num not in (pywbem.CIM_ERR_NOT_FOUND,
- pywbem.CIM_ERR_ACCESS_DENIED):
- raise
+ def get_exec_name(self):
+ try:
+ s = _get_proc_stat_field(self.pid, 1)
+ s = s[1:len(s)-1]
+ except:
+ s = ''
+ return s
- def set_instance(self, env, instance, previous_instance, cim_class):
- """Return a newly created or modified instance.
+ def get_state(self):
+ return _stateThruTasks(self.pid)
- Keyword arguments:
- env -- Provider Environment (pycimmb.ProviderEnvironment)
- instance -- The new pywbem.CIMInstance. If modifying an existing
- instance, the properties on this instance have been filtered by
- the PropertyList from the request.
- previous_instance -- The previous pywbem.CIMInstance if modifying
- an existing instance. None if creating a new instance.
- cim_class -- The pywbem.CIMClass
+ def get_parent_pid(self):
+ try:
+ s = _get_proc_stat_field(self.pid, 3)
+ except:
+ return -1
+ return int(s)
- Return the new instance. The keys must be set on the new instance.
+ def get_process_group(self):
+ try:
+ s = _get_proc_stat_field(self.pid, 4)
+ except:
+ return -1
+ return int(s)
- Possible Errors:
- CIM_ERR_ACCESS_DENIED
- CIM_ERR_NOT_SUPPORTED
- CIM_ERR_INVALID_PARAMETER (including missing, duplicate, unrecognized
- or otherwise incorrect parameters)
- CIM_ERR_ALREADY_EXISTS (the CIM Instance already exists -- only
- valid if previous_instance is None, indicating that the operation
- was CreateInstance)
- CIM_ERR_NOT_FOUND (the CIM Instance does not exist -- only valid
- if previous_instance is not None, indicating that the operation
- was ModifyInstance)
- CIM_ERR_FAILED (some other unspecified error occurred)
+ def get_tty_number(self):
+ try:
+ s = _get_proc_stat_field(self.pid, 6)
+ except:
+ return -1
+ return int(s)
- """
+ def get_session_id(self):
+ try:
+ s = _get_proc_stat_field(self.pid, 5)
+ except:
+ return -1
+ return int(s)
- logger = env.get_logger()
- logger.log_debug('Entering %s.set_instance()' \
- % self.__class__.__name__)
- # TODO create or modify the instance
- raise pywbem.CIMError(pywbem.CIM_ERR_NOT_SUPPORTED) # Remove to implement
- return instance
+ def get_owning_pgrp_of_tty(self):
+ try:
+ s = _get_proc_stat_field(self.pid, 7)
+ except:
+ return -1
+ return int(s)
- def delete_instance(self, env, instance_name):
- """Delete an instance.
+ def get_flags(self):
+ try:
+ s = _get_proc_stat_field(self.pid, 8)
+ except:
+ return long(-1)
+ return long(s)
- Keyword arguments:
- env -- Provider Environment (pycimmb.ProviderEnvironment)
- instance_name -- A pywbem.CIMInstanceName specifying the instance
- to delete.
+ def get_priority(self):
+ try:
+ s = _get_proc_stat_field(self.pid, 17)
+ except:
+ return long(-1)
+ return long(s) - 15
+
+ def get_kernel_mode_time(self):
+ try:
+ s = _get_proc_stat_field(self.pid, 14)
+ except:
+ return long(-1)
+ return long(s) * 10
- Possible Errors:
- CIM_ERR_ACCESS_DENIED
- CIM_ERR_NOT_SUPPORTED
- CIM_ERR_INVALID_NAMESPACE
- CIM_ERR_INVALID_PARAMETER (including missing, duplicate, unrecognized
- or otherwise incorrect parameters)
- CIM_ERR_INVALID_CLASS (the CIM Class does not exist in the specified
- namespace)
- CIM_ERR_NOT_FOUND (the CIM Class does exist, but the requested CIM
- Instance does not exist in the specified namespace)
- CIM_ERR_FAILED (some other unspecified error occurred)
+ def get_user_mode_time(self):
+ try:
+ s = _get_proc_stat_field(self.pid, 13)
+ except:
+ return long(-1)
+ return long(s) * 10
- """
+ def get_nice_value(self):
+ try:
+ s = _get_proc_stat_field(self.pid, 18)
+ except:
+ return long(-1)
+ return long(s)
- logger = env.get_logger()
- logger.log_debug('Entering %s.delete_instance()' \
- % self.__class__.__name__)
+ def get_start_time(self):
+ try:
+ s = _get_proc_stat_field(self.pid, 21)
+ st = (long(s) / 100) + _system_boot_time
+ start_time = pywbem.CIMDateTime.fromtimestamp(st)
+ except:
+ return None
+ return start_time
- # TODO delete the resource
- raise pywbem.CIMError(pywbem.CIM_ERR_NOT_SUPPORTED) # Remove to implement
-
- def cim_method_sendsignal(self, env, object_name, method,
- param_signal):
- """Implements OMC_UnixProcess.SendSignal()
+ def get_virtual_mem_size(self):
+ try:
+ s = _get_proc_stat_field(self.pid, 22)
+ except:
+ return long(-1)
+ return long(s)
- Send a signal to a running process
-
- Keyword arguments:
- env -- Provider Environment (pycimmb.ProviderEnvironment)
- object_name -- A pywbem.CIMInstanceName or pywbem.CIMCLassName
- specifying the object on which the method SendSignal()
- should be invoked.
- method -- A pywbem.CIMMethod representing the method meta-data
- param_signal -- The input parameter signal (type pywbem.Sint32)
+ def get_resident_set_size(self):
+ resident_set_size = long(0)
+ try:
+ f = open('/proc/%d/statm' % self.pid)
+ l = f.readline()
+ f.close()
+ fields = l.split()
+ resident_set_size = long(fields[1]) * 4096
+ except:
+ pass
+ return resident_set_size
- Returns a two-tuple containing the return value (type unicode)
- and a dictionary with the out-parameters
+ def get_shared_mem_size(self):
+ shared_mem_size = long(0)
+ try:
+ f = open('/proc/%d/statm' % self.pid)
+ l = f.readline()
+ f.close()
+ fields = l.split()
+ shared_mem_size = long(fields[2]) * 4096
+ except:
+ pass
+ return shared_mem_size
- Output parameters: none
+ def get_proc_stats(self):
+ return get_proc_stats(self.pid)
- """
+ def __str__(self):
+ return 'LinuxProcess object. pid: %d name: %s' \
+ % (self.pid, self.get_exec_name())
- logger = env.get_logger()
- logger.log_debug('Entering %s.cim_method_sendsignal()' \
- % self.__class__.__name__)
+ def _repr__(self):
+ return self.__str__()
- # TODO do something
- raise pywbem.CIMError(pywbem.CIM_ERR_METHOD_NOT_AVAILABLE) # Remove to implemented
- out_params = {}
- rval = None # TODO (type unicode)
- return (rval, out_params)
-
- def cim_method_requeststatechange(self, env, object_name, method,
- param_requestedstate,
- param_timeoutperiod):
- """Implements OMC_UnixProcess.RequestStateChange()
+def _bytes2KB(v):
+ kb = long(v) / 1024
+ if (v % 1024) >= (1024/2):
+ kb += 1
+ return kb
- Requests that the state of the element be changed to the value
- specified in the RequestedState parameter. When the requested
- state change takes place, the EnabledState and RequestedState of
- the element will be the same. Invoking the RequestStateChange
- method multiple times could result in earlier requests being
- overwritten or lost. If 0 is returned, then the task completed
- successfully and the use of ConcreteJob was not required. If 4096
- (0x1000) is returned, then the task will take some time to
- complete, ConcreteJob will be created, and its reference returned
- in the output parameter Job. Any other return code indicates an
- error condition.
-
- Keyword arguments:
- env -- Provider Environment (pycimmb.ProviderEnvironment)
- object_name -- A pywbem.CIMInstanceName or pywbem.CIMCLassName
- specifying the object on which the method RequestStateChange()
- should be invoked.
- method -- A pywbem.CIMMethod representing the method meta-data
- param_requestedstate -- The input parameter RequestedState (type pywbem.Uint16 self.Values.RequestStateChange.RequestedState)
- The state requested for the element. This information will be
- placed into the RequestedState property of the instance if the
- return code of the RequestStateChange method is 0 ('Completed
- with No Error'), 3 ('Timeout'), or 4096 (0x1000) ('Job
- Started'). Refer to the description of the EnabledState and
- RequestedState properties for the detailed explanations of the
- RequestedState values.
-
- param_timeoutperiod -- The input parameter TimeoutPeriod (type pywbem.CIMDateTime)
- A timeout period that specifies the maximum amount of time that
- the client expects the transition to the new state to take.
- The interval format must be used to specify the TimeoutPeriod.
- A value of 0 or a null parameter indicates that the client has
- no time requirements for the transition. If this property
- does not contain 0 or null and the implementation does not
- support this parameter, a return code of 'Use Of Timeout
- Parameter Not Supported' must be returned.
-
+class OMC_UnixProcessProvider(CIMProvider):
+ """Instrument the CIM class OMC_UnixProcess
- Returns a two-tuple containing the return value (type pywbem.Uint32 self.Values.RequestStateChange)
- and a dictionary with the out-parameters
+ A Unix Process
+
+ """
- Output parameters:
- Job -- (type REF (pywbem.CIMInstanceName(classname='CIM_ConcreteJob', ...))
- Reference to the job (can be null if the task is completed).
-
+ def __init__ (self):
+ pass
- """
+ def fill_instance(self, model, lp, keys_only=False):
+ model['OSCreationClassName'] = 'OMC_LinuxOperatingSystem'
+ model['CreationClassName'] = 'OMC_UnixProcess'
+ model['Handle'] = str(lp.pid)
+ model['CSCreationClassName'] = 'OMC_UnitaryComputerSystem'
+ model['OSName'] = 'Linux'
+ model['CSName'] = getfqdn()
+ if keys_only:
+ return model
+ pname = lp.get_exec_name()
+ model['Name'] = pname
+ model['Caption'] = 'Linux Process. Name:%s PID:%d' % (pname, lp.pid)
+ model['Description'] = 'Linux Process. Name:%s PID:%d' % (pname, lp.pid)
+ ps = lp.get_proc_stats()
+ model['ExecutionState'] = pywbem.Uint16(ps['state'])
+ model['ParentProcessID'] = str(ps['parent_process_id'])
+ model['ProcessGroupID'] = pywbem.Uint64(ps['process_group'])
+ model['ProcessSessionID'] = pywbem.Uint64(ps['session_id'])
+ model['ProcessTTY'] = str(ps['tty_number'])
+ model['Priority'] = pywbem.Uint32(ps['priority'])
+ model['ProcessNiceValue'] = pywbem.Uint32(ps['nice_value'])
+ model['CreationDate'] = ps['start_time']
+ model['VirtualMemorySize'] = pywbem.Uint32(_bytes2KB(ps['virtual_mem_size']))
+ model['PercentCPU'] = pywbem.Real32(ps['percent_cpu'])
+ model['KernelModeTime'] = pywbem.Uint64(ps['kernel_mode_time'])
+ model['UserModeTime'] = pywbem.Uint64(ps['user_mode_time'])
+ modpath = lp.get_module_path();
+ if modpath:
+ model['ModulePath'] = modpath
+ model['SharedMemorySize'] = pywbem.Uint64(_bytes2KB(ps['shared_mem_size']))
+ model['ResidentSetSize'] = pywbem.Uint64(_bytes2KB(ps['resident_set_size']))
+ cl = lp.get_command_line()
+ if cl:
+ model['Parameters'] = cl
+ ruid = lp.get_real_uid()
+ model['RealUserID'] = pywbem.Uint64(ruid)
+ try:
+ model['UserName'] = pwd.getpwuid(ruid)[0]
+ except:
+ pass
+ model['ElementName'] = model['Name']
+ model['HealthState'] = pywbem.Uint16(0)
+ model['OperationalStatus'] = [pywbem.Uint16(0)]
+ return model
+ def get_instance(self, env, model, cim_class):
logger = env.get_logger()
- logger.log_debug('Entering %s.cim_method_requeststatechange()' \
+ logger.log_debug('Entering %s.get_instance()' \
% self.__class__.__name__)
+ try:
+ pid = int(model['handle'])
+ except:
+ # Not a numeric pid
+ raise pywbem.CIMError(pywbem.CIM_ERR_NOT_FOUND)
+ lp = LinuxProcess.get_proc(pid)
+ if not lp:
+ raise pywbem.CIMError(pywbem.CIM_ERR_NOT_FOUND)
+ return self.fill_instance(model, lp)
- # TODO do something
- raise pywbem.CIMError(pywbem.CIM_ERR_METHOD_NOT_AVAILABLE) # Remove to implemented
- out_params = {}
- #out_params['job'] = # TODO (type REF (pywbem.CIMInstanceName(classname='CIM_ConcreteJob', ...))
- rval = None # TODO (type pywbem.Uint32 self.Values.RequestStateChange)
- return (rval, out_params)
-
- def cim_method_killall(self, env, object_name, method,
- param_arg):
- """Implements OMC_UnixProcess.KillAll()
+ def enum_instances(self, env, model, cim_class, keys_only):
+ logger = env.get_logger()
+ logger.log_debug('Entering %s.enum_instances()' \
+ % self.__class__.__name__)
- Send a signal to some running processes. Only the root/admin user
- is allowed to invoke this method
-
- Keyword arguments:
- env -- Provider Environment (pycimmb.ProviderEnvironment)
- object_name -- A pywbem.CIMInstanceName or pywbem.CIMCLassName
- specifying the object on which the method KillAll()
- should be invoked.
- method -- A pywbem.CIMMethod representing the method meta-data
- param_arg -- The input parameter arg (type unicode)
+ for lp in LinuxProcess.procs():
+ yield self.fill_instance(model, lp, keys_only)
- Returns a two-tuple containing the return value (type unicode)
- and a dictionary with the out-parameters
+ def set_instance(self, env, instance, previous_instance, cim_class):
+ logger = env.get_logger()
+ logger.log_debug('Entering %s.set_instance()' \
+ % self.__class__.__name__)
+ raise pywbem.CIMError(pywbem.CIM_ERR_NOT_SUPPORTED)
+ return instance
- Output parameters: none
-
- """
-
+ def delete_instance(self, env, instance_name):
logger = env.get_logger()
+ logger.log_debug('Entering %s.delete_instance()' \
+ % self.__class__.__name__)
+ raise pywbem.CIMError(pywbem.CIM_ERR_NOT_SUPPORTED)
+
+ def cim_method_sendsignal(self, env, object_name, method,
+ param_signal):
+ logger = env.get_logger()
+ logger.log_debug('Entering %s.cim_method_sendsignal()' \
+ % self.__class__.__name__)
+ try:
+ pid = int(object_name['handle'])
+ except:
+ # Not a numeric pid
+ raise pywbem.CIMError(pywbem.CIM_ERR_NOT_FOUND)
+ lp = LinuxProcess.get_proc(pid)
+ if not lp:
+ raise pywbem.CIMError(pywbem.CIM_ERR_NOT_FOUND)
+ user_name = env.get_user_name()
+ ruid = lp.get_real_uid()
+ puser_name = pwd.getpwuid(ruid)[0]
+ if user_name != 'root' and user_name != puser_name:
+ return ('Fail', {})
+ logger = env.get_logger()
+ logger.log_info('User %s sending signal %s to process %d',
+ user_name, str(param_signal), lp.pid)
+ cc = lp.kill(param_signal)
+ if cc < 0:
+ return ('Fail', {})
+ return ('Success', {})
+
+ def cim_method_requeststatechange(self, env, object_name, method,
+ param_requestedstate,
+ param_timeoutperiod):
+ # return 'not supported'
+ return (pywbem.Uint32(1), {})
+
+ def cim_method_killall(self, env, object_name, method,
+ param_arg):
+ logger = env.get_logger()
logger.log_debug('Entering %s.cim_method_killall()' \
% self.__class__.__name__)
-
- # TODO do something
- raise pywbem.CIMError(pywbem.CIM_ERR_METHOD_NOT_AVAILABLE) # Remove to implemented
- out_params = {}
- rval = None # TODO (type unicode)
- return (rval, out_params)
+ user_name = env.get_user_name()
+ if (user_name != 'root'):
+ return ('Fail', {})
+ for lp in LinuxProcess.procs():
+ if lp.get_exec_name() == param_arg:
+ lp.kill(signal.SIGTERM)
+ return ('Success', {})
class Values(object):
class Status(object):
@@ -511,220 +722,79 @@
class OMC_OSProcessProvider(CIMProvider):
"""Instrument the CIM class OMC_OSProcess
- A link between the OperatingSystem and Process(es) running in the
+ The relationship between the OperatingSystem and Process(es) running in the
context of this OperatingSystem.
-
"""
def __init__ (self):
pass
def get_instance(self, env, model, cim_class):
- """Return an instance.
-
- Keyword arguments:
- env -- Provider Environment (pycimmb.ProviderEnvironment)
- model -- A template of the pywbem.CIMInstance to be returned. The
- key properties are set on this instance to correspond to the
- instanceName that was requested. The properties of the model
- are already filtered according to the PropertyList from the
- request. Only properties present in the model need to be
- given values. If you prefer, you can set all of the
- values, and the instance will be filtered for you.
- cim_class -- The pywbem.CIMClass
-
- Possible Errors:
- CIM_ERR_ACCESS_DENIED
- CIM_ERR_INVALID_PARAMETER (including missing, duplicate, unrecognized
- or otherwise incorrect parameters)
- CIM_ERR_NOT_FOUND (the CIM Class does exist, but the requested CIM
- Instance does not exist in the specified namespace)
- CIM_ERR_FAILED (some other unspecified error occurred)
-
- """
-
logger = env.get_logger()
logger.log_debug('Entering %s.get_instance()' \
% self.__class__.__name__)
-
+ pc = model['PartComponent']
+ gc = model['GroupComponent']
+ lp = LinuxProcess.get_proc(pc['handle'])
+ if not lp:
+ raise pywbem.CIMError(pywbem.CIM_ERR_NOT_FOUND)
return model
def enum_instances(self, env, model, cim_class, keys_only):
- """Enumerate instances.
-
- The WBEM operations EnumerateInstances and EnumerateInstanceNames
- are both mapped to this method.
- This method is a python generator
-
- Keyword arguments:
- env -- Provider Environment (pycimmb.ProviderEnvironment)
- model -- A template of the pywbem.CIMInstances to be generated.
- The properties of the model are already filtered according to
- the PropertyList from the request. Only properties present in
- the model need to be given values. If you prefer, you can
- always set all of the values, and the instance will be filtered
- for you.
- cim_class -- The pywbem.CIMClass
- keys_only -- A boolean. True if only the key properties should be
- set on the generated instances.
-
- Possible Errors:
- CIM_ERR_FAILED (some other unspecified error occurred)
-
- """
-
logger = env.get_logger()
logger.log_debug('Entering %s.enum_instances()' \
% self.__class__.__name__)
+ for lp in LinuxProcess.procs():
+ model['PartComponent'] = lp.get_instance_name(
+ cim_class.namespace)
+ model['GroupComponent'] = get_os_path(cim_class.namespace)
+ yield model
- while False: # TODO more instances?
- # TODO fetch system resource
- # Key properties
- #model['GroupComponent'] = # TODO (type = REF (pywbem.CIMInstanceName(classname='OMC_OperatingSystem', ...))
- #model['PartComponent'] = # TODO (type = REF (pywbem.CIMInstanceName(classname='OMC_UnixProcess', ...))
- if keys_only:
- yield model
- else:
- try:
- yield self.get_instance(env, model, cim_class)
- except pywbem.CIMError, (num, msg):
- if num not in (pywbem.CIM_ERR_NOT_FOUND,
- pywbem.CIM_ERR_ACCESS_DENIED):
- raise
-
def set_instance(self, env, instance, previous_instance, cim_class):
- """Return a newly created or modified instance.
-
- Keyword arguments:
- env -- Provider Environment (pycimmb.ProviderEnvironment)
- instance -- The new pywbem.CIMInstance. If modifying an existing
- instance, the properties on this instance have been filtered by
- the PropertyList from the request.
- previous_instance -- The previous pywbem.CIMInstance if modifying
- an existing instance. None if creating a new instance.
- cim_class -- The pywbem.CIMClass
-
- Return the new instance. The keys must be set on the new instance.
-
- Possible Errors:
- CIM_ERR_ACCESS_DENIED
- CIM_ERR_NOT_SUPPORTED
- CIM_ERR_INVALID_PARAMETER (including missing, duplicate, unrecognized
- or otherwise incorrect parameters)
- CIM_ERR_ALREADY_EXISTS (the CIM Instance already exists -- only
- valid if previous_instance is None, indicating that the operation
- was CreateInstance)
- CIM_ERR_NOT_FOUND (the CIM Instance does not exist -- only valid
- if previous_instance is not None, indicating that the operation
- was ModifyInstance)
- CIM_ERR_FAILED (some other unspecified error occurred)
-
- """
-
- logger = env.get_logger()
- logger.log_debug('Entering %s.set_instance()' \
- % self.__class__.__name__)
- # TODO create or modify the instance
raise pywbem.CIMError(pywbem.CIM_ERR_NOT_SUPPORTED) # Remove to implement
- return instance
def delete_instance(self, env, instance_name):
- """Delete an instance.
-
- Keyword arguments:
- env -- Provider Environment (pycimmb.ProviderEnvironment)
- instance_name -- A pywbem.CIMInstanceName specifying the instance
- to delete.
-
- Possible Errors:
- CIM_ERR_ACCESS_DENIED
- CIM_ERR_NOT_SUPPORTED
- CIM_ERR_INVALID_NAMESPACE
- CIM_ERR_INVALID_PARAMETER (including missing, duplicate, unrecognized
- or otherwise incorrect parameters)
- CIM_ERR_INVALID_CLASS (the CIM Class does not exist in the specified
- namespace)
- CIM_ERR_NOT_FOUND (the CIM Class does exist, but the requested CIM
- Instance does not exist in the specified namespace)
- CIM_ERR_FAILED (some other unspecified error occurred)
-
- """
-
- logger = env.get_logger()
- logger.log_debug('Entering %s.delete_instance()' \
- % self.__class__.__name__)
-
- # TODO delete the resource
- raise pywbem.CIMError(pywbem.CIM_ERR_NOT_SUPPORTED) # Remove to implement
+ raise pywbem.CIMError(pywbem.CIM_ERR_NOT_SUPPORTED)
def references(self, env, object_name, model, assoc_class,
result_class_name, role, result_role, keys_only):
- """Instrument Associations.
-
- All four association-related operations (Associators, AssociatorNames,
- References, ReferenceNames) are mapped to this method.
- This method is a python generator
-
- Keyword arguments:
- env -- Provider Environment (pycimmb.ProviderEnvironment)
- object_name -- A pywbem.CIMInstanceName that defines the source
- CIM Object whose associated Objects are to be returned.
- model -- A template pywbem.CIMInstance to serve as a model
- of the objects to be returned. Only properties present on this
- model need to be set.
- assoc_class -- The pywbem.CIMClass.
- result_class_name -- If not None, this string acts as a filter on
- the returned set of Objects by mandating that each returned
- Object MUST be either an Instance of this Class (or one of its
- subclasses) or be this Class (or one of its subclasses).
- role -- If not None, this string acts as a filter on the returned
- set of Objects by mandating that each returned Object MUST be
- associated to the source Object via an Association in which the
- source Object plays the specified role (i.e. the name of the
- Property in the Association Class that refers to the source
- Object MUST match the value of this parameter).
- result_role -- If not None this string acts as a filter on the
- returned set of Objects by mandating that each returned Object
- MUST be associated to the source Object via an Association in
- which the returned Object plays the specified role (i.e. the
- name of the Property in the Association Class that refers to
- the returned Object MUST match the value of this parameter).
- keys_only -- A boolean. True if only the key properties should be
- set on the generated instances.
-
- Possible Errors:
- CIM_ERR_ACCESS_DENIED
- CIM_ERR_NOT_SUPPORTED
- CIM_ERR_INVALID_NAMESPACE
- CIM_ERR_INVALID_PARAMETER (including missing, duplicate, unrecognized
- or otherwise incorrect parameters)
- CIM_ERR_FAILED (some other unspecified error occurred)
-
- """
-
logger = env.get_logger()
logger.log_debug('Entering %s.references()' \
% self.__class__.__name__)
- # This is a common pattern. YMMV
- if not role or role.lower() == 'groupcomponent':
- if object_name.classname.lower() == 'omc_operatingsystem':
+ if object_name.classname.lower() == 'omc_operatingsystem':
+ if role and role.lower() != 'groupcomponent':
+ return
+ if result_role and result_role.lower() != 'partcomponent':
+ return
+ if result_class_name:
+ if not is_subclass(env.get_cimom_handle(), object_name.namespace,
+ sub='omc_unixprocess', super=result_class_name):
+ return
+ for lp in LinuxProcess.procs():
model['GroupComponent'] = object_name
- ch = env.get_cimom_handle()
- for proc in ch.EnumerateInstanceNames('omc_unixprocess',
- object_name.namespace):
- model['PartComponent'] = proc
- yield model
-
- if not role or role.lower() == 'partcomponent':
- provdir = os.path.dirname(__file__)
- if provdir not in sys.path:
- sys.path.append(provdir)
- from OMC_OperatingSystem import get_os_path
- if object_name.classname.lower() == 'omc_unixprocess':
- model['PartComponent'] = object_name
- model['GroupComponent'] = get_os_path(object_name.namespace)
+ model['PartComponent'] = lp.get_instance_name(
+ object_name.namespace)
yield model
+ return
+ if object_name.classname.lower() == 'omc_unixprocess':
+ if not 'handle' in object_name:
+ return
+ if role and role.lower() != 'partcomponent':
+ return
+ if result_role and result_role.lower() != 'groupcomponent':
+ return
+ if result_class_name:
+ if not is_subclass(env.get_cimom_handle(), object_name.namespace,
+ sub='omc_operatingsystem', super=result_class_name):
+ return
+ from OMC_OperatingSystem import get_os_path
+ lp = LinuxProcess.get_proc(object_name['handle'])
+ if not lp:
+ return
+ model['PartComponent'] = object_name
+ model['GroupComponent'] = get_os_path(object_name.namespace)
+ yield model
## end of class OMC_OSProcessProvider
class OMC_ProcessExecutableProvider(CIMProvider):
@@ -732,228 +802,95 @@
A link between a Process and a DataFile indicating that the File
participates in the execution of the Process.
-
"""
def __init__ (self):
pass
def get_instance(self, env, model, cim_class):
- """Return an instance.
-
- Keyword arguments:
- env -- Provider Environment (pycimmb.ProviderEnvironment)
- model -- A template of the pywbem.CIMInstance to be returned. The
- key properties are set on this instance to correspond to the
- instanceName that was requested. The properties of the model
- are already filtered according to the PropertyList from the
- request. Only properties present in the model need to be
- given values. If you prefer, you can set all of the
- values, and the instance will be filtered for you.
- cim_class -- The pywbem.CIMClass
-
- Possible Errors:
- CIM_ERR_ACCESS_DENIED
- CIM_ERR_INVALID_PARAMETER (including missing, duplicate, unrecognized
- or otherwise incorrect parameters)
- CIM_ERR_NOT_FOUND (the CIM Class does exist, but the requested CIM
- Instance does not exist in the specified namespace)
- CIM_ERR_FAILED (some other unspecified error occurred)
-
- """
-
logger = env.get_logger()
logger.log_debug('Entering %s.get_instance()' \
% self.__class__.__name__)
-
+ dn = model['Dependent']
+ lp = LinuxProcess.get_proc(dn['handle'])
+ if not lp:
+ raise pywbem.CIMError(pywbem.CIM_ERR_NOT_FOUND)
+ an = model['Antecedent']
+ fname = an['name']
+ if fname != lp.get_module_path():
+ raise pywbem.CIMError(pywbem.CIM_ERR_NOT_FOUND)
return model
def enum_instances(self, env, model, cim_class, keys_only):
- """Enumerate instances.
-
- The WBEM operations EnumerateInstances and EnumerateInstanceNames
- are both mapped to this method.
- This method is a python generator
-
- Keyword arguments:
- env -- Provider Environment (pycimmb.ProviderEnvironment)
- model -- A template of the pywbem.CIMInstances to be generated.
- The properties of the model are already filtered according to
- the PropertyList from the request. Only properties present in
- the model need to be given values. If you prefer, you can
- always set all of the values, and the instance will be filtered
- for you.
- cim_class -- The pywbem.CIMClass
- keys_only -- A boolean. True if only the key properties should be
- set on the generated instances.
-
- Possible Errors:
- CIM_ERR_FAILED (some other unspecified error occurred)
-
- """
-
logger = env.get_logger()
logger.log_debug('Entering %s.enum_instances()' \
% self.__class__.__name__)
-
- while False: # TODO more instances?
- # TODO fetch system resource
- # Key properties
- #model['Dependent'] = # TODO (type = REF (pywbem.CIMInstanceName(classname='OMC_UnixProcess', ...))
- #model['Antecedent'] = # TODO (type = REF (pywbem.CIMInstanceName(classname='OMC_DataFile', ...))
- if keys_only:
+ for lp in LinuxProcess.procs():
+ model['Dependent'] = lp.get_instance_name(cim_class.namespace)
+ fname = lp.get_module_path()
+ if fname:
+ model['Antecedent'] = OMC_LogicalFile.get_file_path(fname)
yield model
- else:
- try:
- yield self.get_instance(env, model, cim_class)
- except pywbem.CIMError, (num, msg):
- if num not in (pywbem.CIM_ERR_NOT_FOUND,
- pywbem.CIM_ERR_ACCESS_DENIED):
- raise
def set_instance(self, env, instance, previous_instance, cim_class):
- """Return a newly created or modified instance.
+ raise pywbem.CIMError(pywbem.CIM_ERR_NOT_SUPPORTED)
- Keyword arguments:
- env -- Provider Environment (pycimmb.ProviderEnvironment)
- instance -- The new pywbem.CIMInstance. If modifying an existing
- instance, the properties on this instance have been filtered by
- the PropertyList from the request.
- previous_instance -- The previous pywbem.CIMInstance if modifying
- an existing instance. None if creating a new instance.
- cim_class -- The pywbem.CIMClass
-
- Return the new instance. The keys must be set on the new instance.
-
- Possible Errors:
- CIM_ERR_ACCESS_DENIED
- CIM_ERR_NOT_SUPPORTED
- CIM_ERR_INVALID_PARAMETER (including missing, duplicate, unrecognized
- or otherwise incorrect parameters)
- CIM_ERR_ALREADY_EXISTS (the CIM Instance already exists -- only
- valid if previous_instance is None, indicating that the operation
- was CreateInstance)
- CIM_ERR_NOT_FOUND (the CIM Instance does not exist -- only valid
- if previous_instance is not None, indicating that the operation
- was ModifyInstance)
- CIM_ERR_FAILED (some other unspecified error occurred)
-
- """
-
- logger = env.get_logger()
- logger.log_debug('Entering %s.set_instance()' \
- % self.__class__.__name__)
- # TODO create or modify the instance
- raise pywbem.CIMError(pywbem.CIM_ERR_NOT_SUPPORTED) # Remove to implement
- return instance
-
def delete_instance(self, env, instance_name):
- """Delete an instance.
-
- Keyword arguments:
- env -- Provider Environment (pycimmb.ProviderEnvironment)
- instance_name -- A pywbem.CIMInstanceName specifying the instance
- to delete.
-
- Possible Errors:
- CIM_ERR_ACCESS_DENIED
- CIM_ERR_NOT_SUPPORTED
- CIM_ERR_INVALID_NAMESPACE
- CIM_ERR_INVALID_PARAMETER (including missing, duplicate, unrecognized
- or otherwise incorrect parameters)
- CIM_ERR_INVALID_CLASS (the CIM Class does not exist in the specified
- namespace)
- CIM_ERR_NOT_FOUND (the CIM Class does exist, but the requested CIM
- Instance does not exist in the specified namespace)
- CIM_ERR_FAILED (some other unspecified error occurred)
-
- """
-
- logger = env.get_logger()
- logger.log_debug('Entering %s.delete_instance()' \
- % self.__class__.__name__)
-
- # TODO delete the resource
- raise pywbem.CIMError(pywbem.CIM_ERR_NOT_SUPPORTED) # Remove to implement
+ raise pywbem.CIMError(pywbem.CIM_ERR_NOT_SUPPORTED)
def references(self, env, object_name, model, assoc_class,
result_class_name, role, result_role, keys_only):
- """Instrument Associations.
-
- All four association-related operations (Associators, AssociatorNames,
- References, ReferenceNames) are mapped to this method.
- This method is a python generator
-
- Keyword arguments:
- env -- Provider Environment (pycimmb.ProviderEnvironment)
- object_name -- A pywbem.CIMInstanceName that defines the source
- CIM Object whose associated Objects are to be returned.
- model -- A template pywbem.CIMInstance to serve as a model
- of the objects to be returned. Only properties present on this
- model need to be set.
- assoc_class -- The pywbem.CIMClass.
- result_class_name -- If not None, this string acts as a filter on
- the returned set of Objects by mandating that each returned
- Object MUST be either an Instance of this Class (or one of its
- subclasses) or be this Class (or one of its subclasses).
- role -- If not None, this string acts as a filter on the returned
- set of Objects by mandating that each returned Object MUST be
- associated to the source Object via an Association in which the
- source Object plays the specified role (i.e. the name of the
- Property in the Association Class that refers to the source
- Object MUST match the value of this parameter).
- result_role -- If not None this string acts as a filter on the
- returned set of Objects by mandating that each returned Object
- MUST be associated to the source Object via an Association in
- which the returned Object plays the specified role (i.e. the
- name of the Property in the Association Class that refers to
- the returned Object MUST match the value of this parameter).
- keys_only -- A boolean. True if only the key properties should be
- set on the generated instances.
-
- Possible Errors:
- CIM_ERR_ACCESS_DENIED
- CIM_ERR_NOT_SUPPORTED
- CIM_ERR_INVALID_NAMESPACE
- CIM_ERR_INVALID_PARAMETER (including missing, duplicate, unrecognized
- or otherwise incorrect parameters)
- CIM_ERR_FAILED (some other unspecified error occurred)
-
- """
- sys.path.insert(0,os.path.dirname(__file__))
- import OMC_LogicalFile
-
logger = env.get_logger()
logger.log_debug('Entering %s.references()' \
% self.__class__.__name__)
-
- if not role or role.lower() == 'dependent':
- if object_name.classname.lower() == 'omc_unixprocess':
- model['Dependent'] = object_name
- pid = object_name['handle']
- fname = '/proc/'+pid+'/exe'
- if os.path.exists(fname):
- fname = os.readlink(fname)
- fpath = OMC_LogicalFile.get_file_path(fname)
- model['Antecedent'] = fpath
- yield model
- if not role or role.lower() == 'antecedent':
- if is_subclass(env.get_cimom_handle(), object_name.namespace,
- sub=object_name.classname, super='omc_datafile'):
- model['Antecedent'] = object_name
- fname = object_name['name']
- for pid in os.listdir('/proc'):
- if not pid.isdigit():
- continue
- try:
- if fname == os.readlink('/proc/'+pid+'/exe'):
- procpath = get_proc_path(pid)
- model['Dependent'] = procpath
- yield model
- except OSError:
- continue
+ if object_name.classname.lower() == 'omc_unixprocess':
+ if not 'handle' in object_name:
+ return
+ lp = LinuxProcess.get_proc(object_name['handle'])
+ if not lp:
+ return
+ if role and role.lower() != 'dependent':
+ return
+ if result_role and result_role.lower() != 'antecedent':
+ return
+ if result_class_name:
+ if is_subclass(env.get_cimom_handle(), object_name.namespace,
+ sub=result_class_name, super='omc_datafile'):
+ pass
+ elif not is_subclass(env.get_cimom_handle(),
+ object_name.namespace, sub='omc_datafile',
+ super=result_classname):
+ return
+ model['Dependent'] = object_name
+ fname = '/proc/%d/exe' % lp.pid
+ if os.path.exists(fname):
+ fname = os.readlink(fname)
+ fpath = OMC_LogicalFile.get_file_path(fname)
+ fpath.namespace = object_name.namespace
+ model['Antecedent'] = fpath
+ yield model
+ return
+ if is_subclass(env.get_cimom_handle(), object_name.namespace,
+ sub=object_name.classname, super='omc_datafile'):
+ if role and role.lower() != 'antecedent':
+ return
+ if result_role and result_role.lower() != 'dependent':
+ return
+ if result_class_name:
+ if not is_subclass(env.get_cimom_handle(), object_name.namespace,
+ sub='omc_unixprocess', super=result_class_name):
+ return
+ model['Antecedent'] = object_name
+ fname = object_name['name']
+ if not os.path.exists(fname):
+ return
+ for lp in LinuxProcess.procs():
+ if lp.get_module_path() == fname:
+ model['Dependent'] = lp.get_instance_name(
+ object_name.namespace)
+ yield model
def get_providers(env):
return {'OMC_UnixProcess': OMC_UnixProcessProvider(),
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ba...@us...> - 2007-06-12 23:41:56
|
Revision: 472
http://svn.sourceforge.net/omc/?rev=472&view=rev
Author: bartw
Date: 2007-06-12 16:41:55 -0700 (Tue, 12 Jun 2007)
Log Message:
-----------
some fixes, and some build stuff.
Modified Paths:
--------------
pybase/trunk/OMC_InitdService.py
pybase/trunk/OMC_LogicalFile.py
Added Paths:
-----------
pybase/trunk/MANIFEST
pybase/trunk/OMC_Base.mof
pybase/trunk/omc-pybase-providers.spec
pybase/trunk/setup.py
Added: pybase/trunk/MANIFEST
===================================================================
--- pybase/trunk/MANIFEST (rev 0)
+++ pybase/trunk/MANIFEST 2007-06-12 23:41:55 UTC (rev 472)
@@ -0,0 +1,17 @@
+OMC_Base.mof
+OMC_InitdService.py
+OMC_InitdService.mof
+OMC_InitdService.reg
+OMC_LogicalFile.py
+OMC_LogicalFile.mof
+OMC_LogicalFile.reg
+OMC_OperatingSystem.py
+OMC_OperatingSystem.mof
+OMC_OperatingSystem.reg
+OMC_UnitaryComputerSystem.py
+OMC_UnitaryComputerSystem.mof
+OMC_UnitaryComputerSystem.reg
+OMC_UnixProcess.py
+OMC_UnixProcess.mof
+OMC_UnixProcess.reg
+setup.py
Added: pybase/trunk/OMC_Base.mof
===================================================================
--- pybase/trunk/OMC_Base.mof (rev 0)
+++ pybase/trunk/OMC_Base.mof 2007-06-12 23:41:55 UTC (rev 472)
@@ -0,0 +1,5 @@
+#pragma include ("OMC_UnitaryComputerSystem.mof")
+#pragma include ("OMC_OperatingSystem.mof")
+#pragma include ("OMC_LogicalFile.mof")
+#pragma include ("OMC_UnixProcess.mof")
+#pragma include ("OMC_InitdService.mof")
Modified: pybase/trunk/OMC_InitdService.py
===================================================================
--- pybase/trunk/OMC_InitdService.py 2007-06-11 20:07:41 UTC (rev 471)
+++ pybase/trunk/OMC_InitdService.py 2007-06-12 23:41:55 UTC (rev 472)
@@ -136,14 +136,15 @@
logger.log_debug('Entering %s.enum_instances()' \
% self.__class__.__name__)
+ model['SystemName'] = getfqdn()
+ model['SystemCreationClassName'] = 'OMC_UnitaryComputerSystem'
+ model['CreationClassName'] = 'OMC_InitdService'
for file in os.listdir('/etc/init.d'):
fullpath = '/etc/init.d/'+file
if file[0] == '.' or not os.path.isfile(fullpath):
continue
# Key properties
model['Name'] = file
- model['SystemName'] = getfqdn()
- model['SystemCreationClassName'] = 'OMC_UnitaryComputerSystem'
if keys_only:
yield model
else:
Modified: pybase/trunk/OMC_LogicalFile.py
===================================================================
--- pybase/trunk/OMC_LogicalFile.py 2007-06-11 20:07:41 UTC (rev 471)
+++ pybase/trunk/OMC_LogicalFile.py 2007-06-12 23:41:55 UTC (rev 472)
@@ -81,11 +81,12 @@
_scanmounts()
-def get_file_path(fname):
+def get_file_path(fname, ns=None):
keys = {}
get_file_keys(fname, keys)
return pywbem.CIMInstanceName(classname=keys['CreationClassName'],
- keybindings=keys)
+ keybindings=keys,
+ namespace=ns)
def get_file_keys(fname, map, stat=None, linux_file=False):
"""Set the keys on an instance or instance name
Added: pybase/trunk/omc-pybase-providers.spec
===================================================================
--- pybase/trunk/omc-pybase-providers.spec (rev 0)
+++ pybase/trunk/omc-pybase-providers.spec 2007-06-12 23:41:55 UTC (rev 472)
@@ -0,0 +1,69 @@
+#
+# spec file for package python-pywbem (Version 0.5)
+#
+# Copyright (c) 2007 SUSE LINUX Products GmbH, Nuernberg, Germany.
+# This file and all modifications and additions to the pristine
+# package are under the same license as the package itself.
+#
+# Please submit bugfixes or comments via http://bugs.opensuse.org/
+#
+
+# norootforbuild
+
+Name: omc-pybase-providers
+BuildRequires: python-devel openwbem
+Version: 0.1.0
+Release: 2
+Group: System/Management
+Summary: Base System Providers
+License: BSD
+URL: http://omc-project.org/
+BuildArch: noarch
+Source0: %{name}-%{version}.tar.gz
+PreReq: /usr/bin/loadmof.sh
+Requires: python-pywbem openwbem openwbem-python-providerifc
+BuildRoot: %{_tmppath}/%{name}-%{version}-build
+
+%description
+Base System CIM Providers
+
+
+Authors:
+--------
+ Jon Carey
+ Bart Whiteley
+
+%prep
+%setup
+
+%build
+python setup.py build
+
+%install
+# http://lists.opensuse.org/opensuse-packaging/2007-02/msg00005.html
+%{__rm} -rf $RPM_BUILD_ROOT
+%{__mkdir} $RPM_BUILD_ROOT
+python setup.py install --prefix=%{_prefix} --root $RPM_BUILD_ROOT \
+ --install-lib=/usr/lib/pycim -O1
+%{__mkdir} -p $RPM_BUILD_ROOT/usr/share/mof/%{name}
+install *.{mof,reg} $RPM_BUILD_ROOT/usr/share/mof/%{name}/
+
+# END OF INSTALL
+
+%clean
+%{__rm} -rf $RPM_BUILD_ROOT
+
+%files
+%defattr(-,root,root,-)
+/usr/lib/pycim/*
+/usr/share/mof/%{name}/*.mof
+/usr/share/mof/%{name}/*.reg
+
+%post
+loadmof.sh -n root/cimv2 /usr/share/mof/%{name}/OMC_Base.mof
+loadmof.sh -n Interop /usr/share/mof/%{name}/*.reg
+
+%changelog -n omc-pybase-providers
+* Tue May 15 2007 - bwh...@su...
+- First build
+
Added: pybase/trunk/setup.py
===================================================================
--- pybase/trunk/setup.py (rev 0)
+++ pybase/trunk/setup.py 2007-06-12 23:41:55 UTC (rev 472)
@@ -0,0 +1,22 @@
+#!/usr/bin/env python
+
+# Note, you'll typically want to override where these get installed.
+# For example:
+# python setup.py install --install-lib=/usr/lib/pycim -O1
+
+from distutils.core import setup
+
+setup(name='omc-pybase-providers',
+ author='Jon Carey, Bart Whiteley',
+ author_email='jc...@no..., bwh...@su...',
+ version='0.1.0',
+ description='Base Providers',
+ url='http://pywbem.sf.net/',
+ py_modules=['OMC_InitdService',
+ 'OMC_LogicalFile',
+ 'OMC_OperatingSystem',
+ 'OMC_UnitaryComputerSystem',
+ 'OMC_UnixProcess'],
+ #options={'install':{'--install-lib':'/usr/lib/pycim'}},
+ )
+
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ba...@us...> - 2007-06-11 20:07:39
|
Revision: 471
http://svn.sourceforge.net/omc/?rev=471&view=rev
Author: bartw
Date: 2007-06-11 13:07:41 -0700 (Mon, 11 Jun 2007)
Log Message:
-----------
added python providers
Added Paths:
-----------
pybase/
pybase/trunk/
pybase/trunk/OMC_InitdService.mof
pybase/trunk/OMC_InitdService.py
pybase/trunk/OMC_InitdService.reg
pybase/trunk/OMC_LogicalFile.mof
pybase/trunk/OMC_LogicalFile.py
pybase/trunk/OMC_LogicalFile.reg
pybase/trunk/OMC_OperatingSystem.mof
pybase/trunk/OMC_OperatingSystem.py
pybase/trunk/OMC_OperatingSystem.reg
pybase/trunk/OMC_UnitaryComputerSystem.mof
pybase/trunk/OMC_UnitaryComputerSystem.py
pybase/trunk/OMC_UnitaryComputerSystem.reg
pybase/trunk/OMC_UnixProcess.mof
pybase/trunk/OMC_UnixProcess.py
pybase/trunk/OMC_UnixProcess.reg
Added: pybase/trunk/OMC_InitdService.mof
===================================================================
--- pybase/trunk/OMC_InitdService.mof (rev 0)
+++ pybase/trunk/OMC_InitdService.mof 2007-06-11 20:07:41 UTC (rev 471)
@@ -0,0 +1,199 @@
+#pragma locale ("en_US")
+
+[ Description (
+"OMC_InitdService represents the function of a system init script "
+"found in the /etc/init.d directory. The Name field in this class will "
+"be the name of the script. The provider of this class knows nothing "
+"about the details of the service itself. The methods of this class "
+"all correspond to actions that can be taken on init.d scripts conforming "
+"to the LSB spec on system initialization. See "
+"http://refspecs.freestandards.org/LSB_2.0.1/LSB-Core/LSB-Core/sysinit.html "
+"for more information.") ]
+class OMC_InitdService : CIM_Service
+{
+ [Key, Propagated ( "OMC_UnitaryComputerSystem.CreationClassName" ),
+ Description ("The CreationClassName of the scoping System.")]
+ string SystemCreationClassName;
+
+ [Key, Propagated ( "OMC_UnitaryComputerSystem.Name" ),
+ Description ("The Name of the scoping System.")]
+ string SystemName;
+
+ [Key, Override ( "Name" ),
+ Description("This is the name of the script found in the init.d dir")]
+ string Name;
+
+ [ Description ("This method starts the service. "
+ "Return values are what is returned by the service script, and should follow the LSB spec. "
+ "See ValueMap."),
+ Override("StartService"),
+ ValueMap {"0", "1", "2", "3", "4", "5", "6", "7"},
+ Values {"Success", "Generic Error", "Invalid Arguments", "Unimplemented Feature", "Insufficient Privilege", "Program Not Installed", "Program Not Configured", "Program Not Running"}]
+ uint32 StartService ();
+
+ [ Description ("This method stops the service. "
+ "Return values are what is returned by the service script, and should follow the LSB spec. "
+ "See ValueMap."),
+ Override("StopService"),
+ ValueMap {"0", "1", "2", "3", "4", "5", "6", "7"},
+ Values {"Success", "Generic Error", "Invalid Arguments", "Unimplemented Feature", "Insufficient Privilege", "Program Not Installed", "Program Not Configured", "Program Not Running"}]
+ uint32 StopService ();
+
+
+ [ Description ("This method causes the configuration of the service to be reloaded without actually "
+ "stopping and restarting the service. This is an optional method in init scripts per LSB spec. "
+ "Return values are what is returned by the service script, and should follow the LSB spec. "
+ "See ValueMap."),
+ Override("ReloadService"),
+ ValueMap {"0", "1", "2", "3", "4", "5", "6", "7"},
+ Values {"Success", "Generic Error", "Invalid Arguments", "Unimplemented Feature", "Insufficient Privilege", "Program Not Installed", "Program Not Configured", "Program Not Running"}]
+ uint32 ReloadService ();
+
+ [ Description ("This method stops and restarts the service if the service is already running, "
+ "otherwise starts the service. "
+ "Return values are what is returned by the service script, and should follow the LSB spec. "
+ "See ValueMap."),
+ ValueMap {"0", "1", "2", "3", "4", "5", "6", "7"},
+ Values {"Success", "Generic Error", "Invalid Arguments", "Unimplemented Feature", "Insufficient Privilege", "Program Not Installed", "Program Not Configured", "Program Not Running"}]
+ uint32 RestartService ();
+
+ [ Description ("This method causes the configuration to be reloaded if the service supports this, "
+ "otherwise restart the service if it is running"
+ "Return values are what is returned by the service script, and should follow the LSB spec. "
+ "See ValueMap."),
+ ValueMap {"0", "1", "2", "3", "4", "5", "6", "7"},
+ Values {"Success", "Generic Error", "Invalid Arguments", "Unimplemented Feature", "Insufficient Privilege", "Program Not Installed", "Program Not Configured", "Program Not Running"}]
+ uint32 ForceReloadService ();
+
+ [ Description ("This method restarts the service if the service is already running. "
+ "This is an optional method in init scripts per LSB spec. "
+ "Return values are what is returned by the service script, and should follow the LSB spec. "
+ "See ValueMap."),
+ ValueMap {"0", "1", "2", "3", "4", "5", "6", "7"},
+ Values {"Success", "Generic Error", "Invalid Arguments", "Unimplemented Feature", "Insufficient Privilege", "Program Not Installed", "Program Not Configured", "Program Not Running"}]
+ uint32 TryRestartService ();
+
+ [ Description ("This method returns the status of the service. The integer returned is what the script "
+ "returns as its exit value. See LSB spec on init scripts. "
+ "Also see ValueMap."),
+ ValueMap {"0", "1", "2", "3", "4"},
+ Values {"Service Running", "Service Dead - pid file exists", "Service Dead - lock file exists", "Service Not Running", "Unknown"}]
+ uint32 ServiceStatus ();
+
+ [ Description ("This method configures the service's script to be installed or enabled in the system's "
+ "boot (init) script process. The service must already exist on the system and the "
+ "service's script must already exist on the system (usually in the init.d dir). "
+ "This method adds the service to the runlevels the script is assigned to. See LSB "
+ "spec on installing init scripts. "),
+ ValueMap {"0", "1"},
+ Values {"Success", "Failure"}]
+ uint32 EnableService ();
+
+ [ Description ("This method configures the service's script to be removed or disabled in the system's "
+ "boot (init) script process. The service's script is not removed from the system (init.d dir), "
+ "nor is the service removed from the system. This method removes the service from all runlevels "
+ "it is currently assigned to. See LSB spec on installing/removing init scripts. "),
+ ValueMap {"0", "1"},
+ Values {"Success", "Failure"}]
+ uint32 DisableService ();
+
+};
+
+
+[ Description("OMC_Runlevel represents a runlevel on a system, which is a collection of "
+ "init scripts, in this case, a collection of OMC_InitdService objects")]
+class OMC_Runlevel : CIM_CollectionOfMSEs
+{
+ [ Key, Propagated("OMC_UnitaryComputerSystem.CreationClassName") ]
+ string SystemCreationClassName;
+
+ [ Key, Propagated("OMC_UnitaryComputerSystem.Name") ]
+ string SystemName;
+
+ [ Description("The runlevel of this instance. This is typically a one-character identifier such as "
+ "0, 1, 2, 3, 4, 5, 6, S, or B"),
+ Key, Override("Name") ]
+ string Name;
+
+ [ Description ("This method sets the runlevel represented by this object as the default bootup runlevel for the "
+ "system. It returns 0 on success, 1 on failure, or 2 if attempting to set the default to 0, 6, "
+ "B, or something invalid. These runlevels are either invalid default runlevels, or they would "
+ "be unwise to set as default. "),
+ ValueMap {"0", "1", "2"},
+ Values {"Success", "Failure", "Unsupported"}]
+ uint32 SetAsDefault ();
+
+ [ Description ("This method switches the system to the runlevel represented by this object. "
+ "It returns 0 on success, 1 on failure, or 2 if attempting to change to "
+ "B or any other invalid runlevel. NOTE: Be aware that switching to certain "
+ "runlevels will cause the process running this method to be killed and the "
+ "function may never return. "),
+ ValueMap {"0", "1", "2"},
+ Values {"Success", "Failure", "Unsupported"}]
+ uint32 SwitchTo ();
+
+ [ Description ("This method returns the current runlevel of the system. "),
+ Static(true)]
+ string GetCurrentRunlevel ();
+
+ [ Description ("This method returns the default runlevel of the system. This is "
+ "the runlevel the system boots into as specified in the /etc/inittab file."),
+ Static(true)]
+ string GetDefaultRunlevel ();
+
+};
+
+
+
+[ Association,
+ Description(
+ "OMC_HostedInitdService associates the init.d service to the computer system.") ]
+class OMC_HostedInitdService : CIM_HostedService
+{
+ [ Override("Antecedent"), Min(1), Max(1),
+ Description("The hosting system") ]
+ OMC_UnitaryComputerSystem REF Antecedent;
+
+ [ Override("Dependent"), Weak, Min(0),
+ Description("The hosted init.d service") ]
+ OMC_InitdService REF Dependent;
+};
+
+
+[ Association,
+ Description(
+ "OMC_RunlevelInComputerSystem associates a OMC_Runlevel to its computer system.") ]
+class OMC_RunlevelInComputerSystem : CIM_HostedDependency
+{
+ [ Override("Antecedent"), Min(1), Max(1),
+ Description("The hosting system") ]
+ OMC_UnitaryComputerSystem REF Antecedent;
+
+ [ Override("Dependent"), Weak, Min(0),
+ Description("The hosted runlevel") ]
+ OMC_Runlevel REF Dependent;
+};
+
+
+[ Association,
+ Description(
+ "OMC_InitdServiceRunlevel associates a OMC_Runlevel to its services.") ]
+class OMC_InitdServiceRunlevel : CIM_CollectedMSEs
+{
+ [ Override("Collection"),
+ Description("The runlevel on a system") ]
+ OMC_Runlevel REF Collection;
+
+ [ Override("Member"),
+ Description("An init.d service belonging to the runlevel") ]
+ OMC_InitdService REF Member;
+};
+
+
+
+
+
+
+
+
+
Added: pybase/trunk/OMC_InitdService.py
===================================================================
--- pybase/trunk/OMC_InitdService.py (rev 0)
+++ pybase/trunk/OMC_InitdService.py 2007-06-11 20:07:41 UTC (rev 471)
@@ -0,0 +1,866 @@
+#*******************************************************************************
+# Copyright (C) 2007 Novell, Inc. All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions are met:
+#
+# - Redistributions of source code must retain the above copyright notice,
+# this list of conditions and the following disclaimer.
+#
+# - Redistributions in binary form must reproduce the above copyright notice,
+# this list of conditions and the following disclaimer in the documentation
+# and/or other materials provided with the distribution.
+#
+# - Neither the name of Novell, Inc. nor the names of its
+# contributors may be used to endorse or promote products derived from this
+# software without specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS''
+# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+# ARE DISCLAIMED. IN NO EVENT SHALL Novell, Inc. OR THE CONTRIBUTORS
+# BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+# POSSIBILITY OF SUCH DAMAGE.
+#
+#*****************************************************************************/
+
+"""Python Provider for OMC_InitdService
+
+Instruments the CIM class OMC_InitdService
+
+"""
+
+import pywbem
+from pycim import CIMProvider
+import os
+from subprocess import call
+from socket import getfqdn
+
+class OMC_InitdServiceProvider(CIMProvider):
+ """Instrument the CIM class OMC_InitdService
+
+ OMC_InitdService represents the function of a system init script found
+ in the /etc/init.d directory. The Name field in this class will be the
+ name of the script. The provider of this class knows nothing about
+ the details of the service itself. The methods of this class all
+ correspond to actions that can be taken on init.d scripts conforming
+ to the LSB spec on system initialization. See
+ http://refspecs.freestandards.org/LSB_2.0.1/LSB-Core/LSB-Core/sysinit.html
+ for more information.
+
+ """
+
+ def __init__ (self):
+ pass
+
+ def get_instance(self, env, model, cim_class):
+ """Return an instance.
+
+ Keyword arguments:
+ env -- Provider Environment (pycimmb.ProviderEnvironment)
+ model -- A template of the pywbem.CIMInstance to be returned. The
+ key properties are set on this instance to correspond to the
+ instanceName that was requested. The properties of the model
+ are already filtered according to the PropertyList from the
+ request. Only properties present in the model need to be
+ given values. If you prefer, you can set all of the
+ values, and the instance will be filtered for you.
+ cim_class -- The pywbem.CIMClass
+
+ Possible Errors:
+ CIM_ERR_ACCESS_DENIED
+ CIM_ERR_INVALID_PARAMETER (including missing, duplicate, unrecognized
+ or otherwise incorrect parameters)
+ CIM_ERR_NOT_FOUND (the CIM Class does exist, but the requested CIM
+ Instance does not exist in the specified namespace)
+ CIM_ERR_FAILED (some other unspecified error occurred)
+
+ """
+
+ logger = env.get_logger()
+ logger.log_debug('Entering %s.get_instance()' \
+ % self.__class__.__name__)
+
+ #model['Caption'] = # TODO (type = unicode)
+ #model['Description'] = # TODO (type = unicode)
+ #model['ElementName'] = # TODO (type = unicode)
+ #model['EnabledDefault'] = # TODO (type = pywbem.Uint16 self.Values.EnabledDefault) (default=2L)
+ #model['EnabledState'] = # TODO (type = pywbem.Uint16 self.Values.EnabledState) (default=5L)
+ #model['HealthState'] = # TODO (type = pywbem.Uint16 self.Values.HealthState)
+ #model['InstallDate'] = # TODO (type = pywbem.CIMDateTime)
+ osts = []
+ cmd = '/etc/init.d/%s status' % model['name']
+ st = call(cmd, shell=True)
+ if st == self.Values.ServiceStatus.Service_Running:
+ osts.append(self.Values.OperationalStatus.OK)
+ if osts:
+ model['OperationalStatus'] = osts
+ #model['OperationalStatus'] = # TODO (type = [pywbem.Uint16,] self.Values.OperationalStatus)
+ #model['OtherEnabledState'] = # TODO (type = unicode)
+ #model['RequestedState'] = # TODO (type = pywbem.Uint16 self.Values.RequestedState) (default=12L)
+ #model['Status'] = # TODO (type = [pywbem.Uint16,]
+ #model['StatusDescriptions'] = # TODO (type = [unicode,])
+ #model['TimeOfLastStateChange'] = # TODO (type = pywbem.CIMDateTime)
+ return model
+
+ def enum_instances(self, env, model, cim_class, keys_only):
+ """Enumerate instances.
+
+ The WBEM operations EnumerateInstances and EnumerateInstanceNames
+ are both mapped to this method.
+ This method is a python generator
+
+ Keyword arguments:
+ env -- Provider Environment (pycimmb.ProviderEnvironment)
+ model -- A template of the pywbem.CIMInstances to be generated.
+ The properties of the model are already filtered according to
+ the PropertyList from the request. Only properties present in
+ the model need to be given values. If you prefer, you can
+ always set all of the values, and the instance will be filtered
+ for you.
+ cim_class -- The pywbem.CIMClass
+ keys_only -- A boolean. True if only the key properties should be
+ set on the generated instances.
+
+ Possible Errors:
+ CIM_ERR_FAILED (some other unspecified error occurred)
+
+ """
+
+ logger = env.get_logger()
+ logger.log_debug('Entering %s.enum_instances()' \
+ % self.__class__.__name__)
+
+ for file in os.listdir('/etc/init.d'):
+ fullpath = '/etc/init.d/'+file
+ if file[0] == '.' or not os.path.isfile(fullpath):
+ continue
+ # Key properties
+ model['Name'] = file
+ model['SystemName'] = getfqdn()
+ model['SystemCreationClassName'] = 'OMC_UnitaryComputerSystem'
+ if keys_only:
+ yield model
+ else:
+ try:
+ yield self.get_instance(env, model, cim_class)
+ except pywbem.CIMError, (num, msg):
+ if num not in (pywbem.CIM_ERR_NOT_FOUND,
+ pywbem.CIM_ERR_ACCESS_DENIED):
+ raise
+
+ def set_instance(self, env, instance, previous_instance, cim_class):
+ """Return a newly created or modified instance.
+
+ Keyword arguments:
+ env -- Provider Environment (pycimmb.ProviderEnvironment)
+ instance -- The new pywbem.CIMInstance. If modifying an existing
+ instance, the properties on this instance have been filtered by
+ the PropertyList from the request.
+ previous_instance -- The previous pywbem.CIMInstance if modifying
+ an existing instance. None if creating a new instance.
+ cim_class -- The pywbem.CIMClass
+
+ Return the new instance. The keys must be set on the new instance.
+
+ Possible Errors:
+ CIM_ERR_ACCESS_DENIED
+ CIM_ERR_NOT_SUPPORTED
+ CIM_ERR_INVALID_PARAMETER (including missing, duplicate, unrecognized
+ or otherwise incorrect parameters)
+ CIM_ERR_ALREADY_EXISTS (the CIM Instance already exists -- only
+ valid if previous_instance is None, indicating that the operation
+ was CreateInstance)
+ CIM_ERR_NOT_FOUND (the CIM Instance does not exist -- only valid
+ if previous_instance is not None, indicating that the operation
+ was ModifyInstance)
+ CIM_ERR_FAILED (some other unspecified error occurred)
+
+ """
+
+ logger = env.get_logger()
+ logger.log_debug('Entering %s.set_instance()' \
+ % self.__class__.__name__)
+ # TODO create or modify the instance
+ raise pywbem.CIMError(pywbem.CIM_ERR_NOT_SUPPORTED) # Remove to implement
+ return instance
+
+ def delete_instance(self, env, instance_name):
+ """Delete an instance.
+
+ Keyword arguments:
+ env -- Provider Environment (pycimmb.ProviderEnvironment)
+ instance_name -- A pywbem.CIMInstanceName specifying the instance
+ to delete.
+
+ Possible Errors:
+ CIM_ERR_ACCESS_DENIED
+ CIM_ERR_NOT_SUPPORTED
+ CIM_ERR_INVALID_NAMESPACE
+ CIM_ERR_INVALID_PARAMETER (including missing, duplicate, unrecognized
+ or otherwise incorrect parameters)
+ CIM_ERR_INVALID_CLASS (the CIM Class does not exist in the specified
+ namespace)
+ CIM_ERR_NOT_FOUND (the CIM Class does exist, but the requested CIM
+ Instance does not exist in the specified namespace)
+ CIM_ERR_FAILED (some other unspecified error occurred)
+
+ """
+
+ logger = env.get_logger()
+ logger.log_debug('Entering %s.delete_instance()' \
+ % self.__class__.__name__)
+
+ # TODO delete the resource
+ raise pywbem.CIMError(pywbem.CIM_ERR_NOT_SUPPORTED) # Remove to implement
+
+ def cim_method_requeststatechange(self, env, object_name, method,
+ param_requestedstate,
+ param_timeoutperiod):
+ """Implements OMC_InitdService.RequestStateChange()
+
+ Requests that the state of the element be changed to the value
+ specified in the RequestedState parameter. When the requested
+ state change takes place, the EnabledState and RequestedState of
+ the element will be the same. Invoking the RequestStateChange
+ method multiple times could result in earlier requests being
+ overwritten or lost. If 0 is returned, then the task completed
+ successfully and the use of ConcreteJob was not required. If 4096
+ (0x1000) is returned, then the task will take some time to
+ complete, ConcreteJob will be created, and its reference returned
+ in the output parameter Job. Any other return code indicates an
+ error condition.
+
+ Keyword arguments:
+ env -- Provider Environment (pycimmb.ProviderEnvironment)
+ object_name -- A pywbem.CIMInstanceName or pywbem.CIMCLassName
+ specifying the object on which the method RequestStateChange()
+ should be invoked.
+ method -- A pywbem.CIMMethod representing the method meta-data
+ param_requestedstate -- The input parameter RequestedState (type pywbem.Uint16 self.Values.RequestStateChange.RequestedState)
+ The state requested for the element. This information will be
+ placed into the RequestedState property of the instance if the
+ return code of the RequestStateChange method is 0 ('Completed
+ with No Error'), 3 ('Timeout'), or 4096 (0x1000) ('Job
+ Started'). Refer to the description of the EnabledState and
+ RequestedState properties for the detailed explanations of the
+ RequestedState values.
+
+ param_timeoutperiod -- The input parameter TimeoutPeriod (type pywbem.CIMDateTime)
+ A timeout period that specifies the maximum amount of time that
+ the client expects the transition to the new state to take.
+ The interval format must be used to specify the TimeoutPeriod.
+ A value of 0 or a null parameter indicates that the client has
+ no time requirements for the transition. If this property
+ does not contain 0 or null and the implementation does not
+ support this parameter, a return code of 'Use Of Timeout
+ Parameter Not Supported' must be returned.
+
+
+ Returns a two-tuple containing the return value (type pywbem.Uint32 self.Values.RequestStateChange)
+ and a dictionary with the out-parameters
+
+ Output parameters:
+ Job -- (type REF (pywbem.CIMInstanceName(classname='CIM_ConcreteJob', ...))
+ Reference to the job (can be null if the task is completed).
+
+
+ Possible Errors:
+ CIM_ERR_ACCESS_DENIED
+ CIM_ERR_INVALID_PARAMETER (including missing, duplicate,
+ unrecognized or otherwise incorrect parameters)
+ CIM_ERR_NOT_FOUND (the target CIM Class or instance does not
+ exist in the specified namespace)
+ CIM_ERR_METHOD_NOT_AVAILABLE (the CIM Server is unable to honor
+ the invocation request)
+ CIM_ERR_FAILED (some other unspecified error occurred)
+
+ """
+
+ logger = env.get_logger()
+ logger.log_debug('Entering %s.cim_method_requeststatechange()' \
+ % self.__class__.__name__)
+
+ # TODO do something
+ raise pywbem.CIMError(pywbem.CIM_ERR_METHOD_NOT_AVAILABLE) # Remove to implemented
+ out_params = {}
+ #out_params['job'] = # TODO (type REF (pywbem.CIMInstanceName(classname='CIM_ConcreteJob', ...))
+ rval = None # TODO (type pywbem.Uint32 self.Values.RequestStateChange)
+ return (rval, out_params)
+
+ def cim_method_reloadservice(self, env, object_name, method):
+ """Implements OMC_InitdService.ReloadService()
+
+ This method causes the configuration of the service to be reloaded
+ without actually stopping and restarting the service. This is an
+ optional method in init scripts per LSB spec. Return values are
+ what is returned by the service script, and should follow the LSB
+ spec. See ValueMap.
+
+ Keyword arguments:
+ env -- Provider Environment (pycimmb.ProviderEnvironment)
+ object_name -- A pywbem.CIMInstanceName or pywbem.CIMCLassName
+ specifying the object on which the method ReloadService()
+ should be invoked.
+ method -- A pywbem.CIMMethod representing the method meta-data
+
+ Returns a two-tuple containing the return value (type pywbem.Uint32 self.Values.ReloadService)
+ and a dictionary with the out-parameters
+
+ Output parameters: none
+
+ Possible Errors:
+ CIM_ERR_ACCESS_DENIED
+ CIM_ERR_INVALID_PARAMETER (including missing, duplicate,
+ unrecognized or otherwise incorrect parameters)
+ CIM_ERR_NOT_FOUND (the target CIM Class or instance does not
+ exist in the specified namespace)
+ CIM_ERR_METHOD_NOT_AVAILABLE (the CIM Server is unable to honor
+ the invocation request)
+ CIM_ERR_FAILED (some other unspecified error occurred)
+
+ """
+
+ logger = env.get_logger()
+ logger.log_debug('Entering %s.cim_method_reloadservice()' \
+ % self.__class__.__name__)
+
+ out_params = {}
+ cmd = '/etc/init.d/%s reload' % object_name['name']
+ rval = pywbem.Uint32(call(cmd, shell=True))
+ return (rval, out_params)
+
+ def cim_method_stopservice(self, env, object_name, method):
+ """Implements OMC_InitdService.StopService()
+
+ This method stops the service. Return values are what is returned
+ by the service script, and should follow the LSB spec. See
+ ValueMap.
+
+ Keyword arguments:
+ env -- Provider Environment (pycimmb.ProviderEnvironment)
+ object_name -- A pywbem.CIMInstanceName or pywbem.CIMCLassName
+ specifying the object on which the method StopService()
+ should be invoked.
+ method -- A pywbem.CIMMethod representing the method meta-data
+
+ Returns a two-tuple containing the return value (type pywbem.Uint32 self.Values.StopService)
+ and a dictionary with the out-parameters
+
+ Output parameters: none
+
+ Possible Errors:
+ CIM_ERR_ACCESS_DENIED
+ CIM_ERR_INVALID_PARAMETER (including missing, duplicate,
+ unrecognized or otherwise incorrect parameters)
+ CIM_ERR_NOT_FOUND (the target CIM Class or instance does not
+ exist in the specified namespace)
+ CIM_ERR_METHOD_NOT_AVAILABLE (the CIM Server is unable to honor
+ the invocation request)
+ CIM_ERR_FAILED (some other unspecified error occurred)
+
+ """
+
+ logger = env.get_logger()
+ logger.log_debug('Entering %s.cim_method_stopservice()' \
+ % self.__class__.__name__)
+
+ out_params = {}
+ cmd = '/etc/init.d/%s stop' % object_name['name']
+ rval = pywbem.Uint32(call(cmd, shell=True))
+ return (rval, out_params)
+
+ def cim_method_enableservice(self, env, object_name, method):
+ """Implements OMC_InitdService.EnableService()
+
+ This method configures the service's script to be installed or
+ enabled in the system's boot (init) script process. The service
+ must already exist on the system and the service's script must
+ already exist on the system (usually in the init.d dir). This
+ method adds the service to the runlevels the script is assigned
+ to. See LSB spec on installing init scripts.
+
+ Keyword arguments:
+ env -- Provider Environment (pycimmb.ProviderEnvironment)
+ object_name -- A pywbem.CIMInstanceName or pywbem.CIMCLassName
+ specifying the object on which the method EnableService()
+ should be invoked.
+ method -- A pywbem.CIMMethod representing the method meta-data
+
+ Returns a two-tuple containing the return value (type pywbem.Uint32 self.Values.EnableService)
+ and a dictionary with the out-parameters
+
+ Output parameters: none
+
+ Possible Errors:
+ CIM_ERR_ACCESS_DENIED
+ CIM_ERR_INVALID_PARAMETER (including missing, duplicate,
+ unrecognized or otherwise incorrect parameters)
+ CIM_ERR_NOT_FOUND (the target CIM Class or instance does not
+ exist in the specified namespace)
+ CIM_ERR_METHOD_NOT_AVAILABLE (the CIM Server is unable to honor
+ the invocation request)
+ CIM_ERR_FAILED (some other unspecified error occurred)
+
+ """
+
+ logger = env.get_logger()
+ logger.log_debug('Entering %s.cim_method_enableservice()' \
+ % self.__class__.__name__)
+
+ # TODO do something
+ raise pywbem.CIMError(pywbem.CIM_ERR_METHOD_NOT_AVAILABLE) # Remove to implemented
+ out_params = {}
+ rval = None # TODO (type pywbem.Uint32 self.Values.EnableService)
+ return (rval, out_params)
+
+ def cim_method_tryrestartservice(self, env, object_name, method):
+ """Implements OMC_InitdService.TryRestartService()
+
+ This method restarts the service if the service is already running.
+ This is an optional method in init scripts per LSB spec. Return
+ values are what is returned by the service script, and should
+ follow the LSB spec. See ValueMap.
+
+ Keyword arguments:
+ env -- Provider Environment (pycimmb.ProviderEnvironment)
+ object_name -- A pywbem.CIMInstanceName or pywbem.CIMCLassName
+ specifying the object on which the method TryRestartService()
+ should be invoked.
+ method -- A pywbem.CIMMethod representing the method meta-data
+
+ Returns a two-tuple containing the return value (type pywbem.Uint32 self.Values.TryRestartService)
+ and a dictionary with the out-parameters
+
+ Output parameters: none
+
+ Possible Errors:
+ CIM_ERR_ACCESS_DENIED
+ CIM_ERR_INVALID_PARAMETER (including missing, duplicate,
+ unrecognized or otherwise incorrect parameters)
+ CIM_ERR_NOT_FOUND (the target CIM Class or instance does not
+ exist in the specified namespace)
+ CIM_ERR_METHOD_NOT_AVAILABLE (the CIM Server is unable to honor
+ the invocation request)
+ CIM_ERR_FAILED (some other unspecified error occurred)
+
+ """
+
+ logger = env.get_logger()
+ logger.log_debug('Entering %s.cim_method_tryrestartservice()' \
+ % self.__class__.__name__)
+
+ # TODO do something
+ raise pywbem.CIMError(pywbem.CIM_ERR_METHOD_NOT_AVAILABLE) # Remove to implemented
+ out_params = {}
+ rval = None # TODO (type pywbem.Uint32 self.Values.TryRestartService)
+ return (rval, out_params)
+
+ def cim_method_restartservice(self, env, object_name, method):
+ """Implements OMC_InitdService.RestartService()
+
+ This method stops and restarts the service if the service is
+ already running, otherwise starts the service. Return values are
+ what is returned by the service script, and should follow the LSB
+ spec. See ValueMap.
+
+ Keyword arguments:
+ env -- Provider Environment (pycimmb.ProviderEnvironment)
+ object_name -- A pywbem.CIMInstanceName or pywbem.CIMCLassName
+ specifying the object on which the method RestartService()
+ should be invoked.
+ method -- A pywbem.CIMMethod representing the method meta-data
+
+ Returns a two-tuple containing the return value (type pywbem.Uint32 self.Values.RestartService)
+ and a dictionary with the out-parameters
+
+ Output parameters: none
+
+ Possible Errors:
+ CIM_ERR_ACCESS_DENIED
+ CIM_ERR_INVALID_PARAMETER (including missing, duplicate,
+ unrecognized or otherwise incorrect parameters)
+ CIM_ERR_NOT_FOUND (the target CIM Class or instance does not
+ exist in the specified namespace)
+ CIM_ERR_METHOD_NOT_AVAILABLE (the CIM Server is unable to honor
+ the invocation request)
+ CIM_ERR_FAILED (some other unspecified error occurred)
+
+ """
+
+ logger = env.get_logger()
+ logger.log_debug('Entering %s.cim_method_restartservice()' \
+ % self.__class__.__name__)
+
+ out_params = {}
+ cmd = '/etc/init.d/%s restart' % object_name['name']
+ rval = pywbem.Uint32(call(cmd, shell=True))
+ return (rval, out_params)
+
+ def cim_method_forcereloadservice(self, env, object_name, method):
+ """Implements OMC_InitdService.ForceReloadService()
+
+ This method causes the configuration to be reloaded if the service
+ supports this, otherwise restart the service if it is
+ runningReturn values are what is returned by the service script,
+ and should follow the LSB spec. See ValueMap.
+
+ Keyword arguments:
+ env -- Provider Environment (pycimmb.ProviderEnvironment)
+ object_name -- A pywbem.CIMInstanceName or pywbem.CIMCLassName
+ specifying the object on which the method ForceReloadService()
+ should be invoked.
+ method -- A pywbem.CIMMethod representing the method meta-data
+
+ Returns a two-tuple containing the return value (type pywbem.Uint32 self.Values.ForceReloadService)
+ and a dictionary with the out-parameters
+
+ Output parameters: none
+
+ Possible Errors:
+ CIM_ERR_ACCESS_DENIED
+ CIM_ERR_INVALID_PARAMETER (including missing, duplicate,
+ unrecognized or otherwise incorrect parameters)
+ CIM_ERR_NOT_FOUND (the target CIM Class or instance does not
+ exist in the specified namespace)
+ CIM_ERR_METHOD_NOT_AVAILABLE (the CIM Server is unable to honor
+ the invocation request)
+ CIM_ERR_FAILED (some other unspecified error occurred)
+
+ """
+
+ logger = env.get_logger()
+ logger.log_debug('Entering %s.cim_method_forcereloadservice()' \
+ % self.__class__.__name__)
+
+ # TODO do something
+ raise pywbem.CIMError(pywbem.CIM_ERR_METHOD_NOT_AVAILABLE) # Remove to implemented
+ out_params = {}
+ rval = None # TODO (type pywbem.Uint32 self.Values.ForceReloadService)
+ return (rval, out_params)
+
+ def cim_method_startservice(self, env, object_name, method):
+ """Implements OMC_InitdService.StartService()
+
+ This method starts the service. Return values are what is returned
+ by the service script, and should follow the LSB spec. See
+ ValueMap.
+
+ Keyword arguments:
+ env -- Provider Environment (pycimmb.ProviderEnvironment)
+ object_name -- A pywbem.CIMInstanceName or pywbem.CIMCLassName
+ specifying the object on which the method StartService()
+ should be invoked.
+ method -- A pywbem.CIMMethod representing the method meta-data
+
+ Returns a two-tuple containing the return value (type pywbem.Uint32 self.Values.StartService)
+ and a dictionary with the out-parameters
+
+ Output parameters: none
+
+ Possible Errors:
+ CIM_ERR_ACCESS_DENIED
+ CIM_ERR_INVALID_PARAMETER (including missing, duplicate,
+ unrecognized or otherwise incorrect parameters)
+ CIM_ERR_NOT_FOUND (the target CIM Class or instance does not
+ exist in the specified namespace)
+ CIM_ERR_METHOD_NOT_AVAILABLE (the CIM Server is unable to honor
+ the invocation request)
+ CIM_ERR_FAILED (some other unspecified error occurred)
+
+ """
+
+ logger = env.get_logger()
+ logger.log_debug('Entering %s.cim_method_startservice()' \
+ % self.__class__.__name__)
+
+ out_params = {}
+ cmd = '/etc/init.d/%s start' % object_name['name']
+ rval = pywbem.Uint32(call(cmd, shell=True))
+ return (rval, out_params)
+
+ def cim_method_servicestatus(self, env, object_name, method):
+ """Implements OMC_InitdService.ServiceStatus()
+
+ This method returns the status of the service. The integer
+ returned is what the script returns as its exit value. See LSB
+ spec on init scripts. Also see ValueMap.
+
+ Keyword arguments:
+ env -- Provider Environment (pycimmb.ProviderEnvironment)
+ object_name -- A pywbem.CIMInstanceName or pywbem.CIMCLassName
+ specifying the object on which the method ServiceStatus()
+ should be invoked.
+ method -- A pywbem.CIMMethod representing the method meta-data
+
+ Returns a two-tuple containing the return value (type pywbem.Uint32 self.Values.ServiceStatus)
+ and a dictionary with the out-parameters
+
+ Output parameters: none
+
+ Possible Errors:
+ CIM_ERR_ACCESS_DENIED
+ CIM_ERR_INVALID_PARAMETER (including missing, duplicate,
+ unrecognized or otherwise incorrect parameters)
+ CIM_ERR_NOT_FOUND (the target CIM Class or instance does not
+ exist in the specified namespace)
+ CIM_ERR_METHOD_NOT_AVAILABLE (the CIM Server is unable to honor
+ the invocation request)
+ CIM_ERR_FAILED (some other unspecified error occurred)
+
+ """
+
+ logger = env.get_logger()
+ logger.log_debug('Entering %s.cim_method_servicestatus()' \
+ % self.__class__.__name__)
+
+ cmd = '/etc/init.d/%s status > /dev/null 2>&1' % object_name['name']
+ rval = pywbem.Uint32(call(cmd, shell=True))
+ return (rval, {})
+
+ def cim_method_disableservice(self, env, object_name, method):
+ """Implements OMC_InitdService.DisableService()
+
+ This method configures the service's script to be removed or
+ disabled in the system's boot (init) script process. The
+ service's script is not removed from the system (init.d dir), nor
+ is the service removed from the system. This method removes the
+ service from all runlevels it is currently assigned to. See LSB
+ spec on installing/removing init scripts.
+
+ Keyword arguments:
+ env -- Provider Environment (pycimmb.ProviderEnvironment)
+ object_name -- A pywbem.CIMInstanceName or pywbem.CIMCLassName
+ specifying the object on which the method DisableService()
+ should be invoked.
+ method -- A pywbem.CIMMethod representing the method meta-data
+
+ Returns a two-tuple containing the return value (type pywbem.Uint32 self.Values.DisableService)
+ and a dictionary with the out-parameters
+
+ Output parameters: none
+
+ Possible Errors:
+ CIM_ERR_ACCESS_DENIED
+ CIM_ERR_INVALID_PARAMETER (including missing, duplicate,
+ unrecognized or otherwise incorrect parameters)
+ CIM_ERR_NOT_FOUND (the target CIM Class or instance does not
+ exist in the specified namespace)
+ CIM_ERR_METHOD_NOT_AVAILABLE (the CIM Server is unable to honor
+ the invocation request)
+ CIM_ERR_FAILED (some other unspecified error occurred)
+
+ """
+
+ logger = env.get_logger()
+ logger.log_debug('Entering %s.cim_method_disableservice()' \
+ % self.__class__.__name__)
+
+ # TODO do something
+ raise pywbem.CIMError(pywbem.CIM_ERR_METHOD_NOT_AVAILABLE) # Remove to implemented
+ out_params = {}
+ rval = None # TODO (type pywbem.Uint32 self.Values.DisableService)
+ return (rval, out_params)
+
+ class Values(object):
+ class Status(object):
+ OK = 'OK'
+ Error = 'Error'
+ Degraded = 'Degraded'
+ Unknown = 'Unknown'
+ Pred_Fail = 'Pred Fail'
+ Starting = 'Starting'
+ Stopping = 'Stopping'
+ Service = 'Service'
+ Stressed = 'Stressed'
+ NonRecover = 'NonRecover'
+ No_Contact = 'No Contact'
+ Lost_Comm = 'Lost Comm'
+ Stopped = 'Stopped'
+
+ class RequestedState(object):
+ Enabled = pywbem.Uint16(2)
+ Disabled = pywbem.Uint16(3)
+ Shut_Down = pywbem.Uint16(4)
+ No_Change = pywbem.Uint16(5)
+ Offline = pywbem.Uint16(6)
+ Test = pywbem.Uint16(7)
+ Deferred = pywbem.Uint16(8)
+ Quiesce = pywbem.Uint16(9)
+ Reboot = pywbem.Uint16(10)
+ Reset = pywbem.Uint16(11)
+ Not_Applicable = pywbem.Uint16(12)
+ # DMTF_Reserved = ..
+ # Vendor_Reserved = 32768..65535
+
+ class HealthState(object):
+ Unknown = pywbem.Uint16(0)
+ OK = pywbem.Uint16(5)
+ Degraded_Warning = pywbem.Uint16(10)
+ Minor_failure = pywbem.Uint16(15)
+ Major_failure = pywbem.Uint16(20)
+ Critical_failure = pywbem.Uint16(25)
+ Non_recoverable_error = pywbem.Uint16(30)
+ # DMTF_Reserved = ..
+
+ class ReloadService(object):
+ Success = pywbem.Uint32(0)
+ Generic_Error = pywbem.Uint32(1)
+ Invalid_Arguments = pywbem.Uint32(2)
+ Unimplemented_Feature = pywbem.Uint32(3)
+ Insufficient_Privilege = pywbem.Uint32(4)
+ Program_Not_Installed = pywbem.Uint32(5)
+ Program_Not_Configured = pywbem.Uint32(6)
+ Program_Not_Running = pywbem.Uint32(7)
+
+ class EnabledDefault(object):
+ Enabled = pywbem.Uint16(2)
+ Disabled = pywbem.Uint16(3)
+ Not_Applicable = pywbem.Uint16(5)
+ Enabled_but_Offline = pywbem.Uint16(6)
+ No_Default = pywbem.Uint16(7)
+ Quiesce = pywbem.Uint16(9)
+ # DMTF_Reserved = ..
+ # Vendor_Reserved = 32768..65535
+
+ class EnabledState(object):
+ Unknown = pywbem.Uint16(0)
+ Other = pywbem.Uint16(1)
+ Enabled = pywbem.Uint16(2)
+ Disabled = pywbem.Uint16(3)
+ Shutting_Down = pywbem.Uint16(4)
+ Not_Applicable = pywbem.Uint16(5)
+ Enabled_but_Offline = pywbem.Uint16(6)
+ In_Test = pywbem.Uint16(7)
+ Deferred = pywbem.Uint16(8)
+ Quiesce = pywbem.Uint16(9)
+ Starting = pywbem.Uint16(10)
+ # DMTF_Reserved = 11..32767
+ # Vendor_Reserved = 32768..65535
+
+ class EnableService(object):
+ Success = pywbem.Uint32(0)
+ Failure = pywbem.Uint32(1)
+
+ class StopService(object):
+ Success = pywbem.Uint32(0)
+ Generic_Error = pywbem.Uint32(1)
+ Invalid_Arguments = pywbem.Uint32(2)
+ Unimplemented_Feature = pywbem.Uint32(3)
+ Insufficient_Privilege = pywbem.Uint32(4)
+ Program_Not_Installed = pywbem.Uint32(5)
+ Program_Not_Configured = pywbem.Uint32(6)
+ Program_Not_Running = pywbem.Uint32(7)
+
+ class StartService(object):
+ Success = pywbem.Uint32(0)
+ Generic_Error = pywbem.Uint32(1)
+ Invalid_Arguments = pywbem.Uint32(2)
+ Unimplemented_Feature = pywbem.Uint32(3)
+ Insufficient_Privilege = pywbem.Uint32(4)
+ Program_Not_Installed = pywbem.Uint32(5)
+ Program_Not_Configured = pywbem.Uint32(6)
+ Program_Not_Running = pywbem.Uint32(7)
+
+ class TryRestartService(object):
+ Success = pywbem.Uint32(0)
+ Generic_Error = pywbem.Uint32(1)
+ Invalid_Arguments = pywbem.Uint32(2)
+ Unimplemented_Feature = pywbem.Uint32(3)
+ Insufficient_Privilege = pywbem.Uint32(4)
+ Program_Not_Installed = pywbem.Uint32(5)
+ Program_Not_Configured = pywbem.Uint32(6)
+ Program_Not_Running = pywbem.Uint32(7)
+
+ class OperationalStatus(object):
+ Unknown = pywbem.Uint16(0)
+ Other = pywbem.Uint16(1)
+ OK = pywbem.Uint16(2)
+ Degraded = pywbem.Uint16(3)
+ Stressed = pywbem.Uint16(4)
+ Predictive_Failure = pywbem.Uint16(5)
+ Error = pywbem.Uint16(6)
+ Non_Recoverable_Error = pywbem.Uint16(7)
+ Starting = pywbem.Uint16(8)
+ Stopping = pywbem.Uint16(9)
+ Stopped = pywbem.Uint16(10)
+ In_Service = pywbem.Uint16(11)
+ No_Contact = pywbem.Uint16(12)
+ Lost_Communication = pywbem.Uint16(13)
+ Aborted = pywbem.Uint16(14)
+ Dormant = pywbem.Uint16(15)
+ Supporting_Entity_in_Error = pywbem.Uint16(16)
+ Completed = pywbem.Uint16(17)
+ Power_Mode = pywbem.Uint16(18)
+ # DMTF_Reserved = ..
+ # Vendor_Reserved = 0x8000..
+
+ class RestartService(object):
+ Success = pywbem.Uint32(0)
+ Generic_Error = pywbem.Uint32(1)
+ Invalid_Arguments = pywbem.Uint32(2)
+ Unimplemented_Feature = pywbem.Uint32(3)
+ Insufficient_Privilege = pywbem.Uint32(4)
+ Program_Not_Installed = pywbem.Uint32(5)
+ Program_Not_Configured = pywbem.Uint32(6)
+ Program_Not_Running = pywbem.Uint32(7)
+
+ class RequestStateChange(object):
+ Completed_with_No_Error = pywbem.Uint32(0)
+ Not_Supported = pywbem.Uint32(1)
+ Unknown_or_Unspecified_Error = pywbem.Uint32(2)
+ Cannot_complete_within_Timeout_Period = pywbem.Uint32(3)
+ Failed = pywbem.Uint32(4)
+ Invalid_Parameter = pywbem.Uint32(5)
+ In_Use = pywbem.Uint32(6)
+ # DMTF_Reserved = ..
+ Method_Parameters_Checked___Job_Started = pywbem.Uint32(4096)
+ Invalid_State_Transition = pywbem.Uint32(4097)
+ Use_of_Timeout_Parameter_Not_Supported = pywbem.Uint32(4098)
+ Busy = pywbem.Uint32(4099)
+ # Method_Reserved = 4100..32767
+ # Vendor_Specific = 32768..65535
+ class RequestedState(object):
+ Enabled = pywbem.Uint16(2)
+ Disabled = pywbem.Uint16(3)
+ Shut_Down = pywbem.Uint16(4)
+ Offline = pywbem.Uint16(6)
+ Test = pywbem.Uint16(7)
+ Defer = pywbem.Uint16(8)
+ Quiesce = pywbem.Uint16(9)
+ Reboot = pywbem.Uint16(10)
+ Reset = pywbem.Uint16(11)
+ # DMTF_Reserved = ..
+ # Vendor_Reserved = 32768..65535
+
+ class ForceReloadService(object):
+ Success = pywbem.Uint32(0)
+ Generic_Error = pywbem.Uint32(1)
+ Invalid_Arguments = pywbem.Uint32(2)
+ Unimplemented_Feature = pywbem.Uint32(3)
+ Insufficient_Privilege = pywbem.Uint32(4)
+ Program_Not_Installed = pywbem.Uint32(5)
+ Program_Not_Configured = pywbem.Uint32(6)
+ Program_Not_Running = pywbem.Uint32(7)
+
+ class ServiceStatus(object):
+ Service_Running = pywbem.Uint32(0)
+ Service_Dead___pid_file_exists = pywbem.Uint32(1)
+ Service_Dead___lock_file_exists = pywbem.Uint32(2)
+ Service_Not_Running = pywbem.Uint32(3)
+ Unknown = pywbem.Uint32(4)
+
+ class DisableService(object):
+ Success = pywbem.Uint32(0)
+ Failure = pywbem.Uint32(1)
+
+## end of class OMC_InitdServiceProvider
+
+def get_providers(env):
+ omc_initdservice_prov = OMC_InitdServiceProvider()
+ return {'OMC_InitdService': omc_initdservice_prov}
Added: pybase/trunk/OMC_InitdService.reg
===================================================================
--- pybase/trunk/OMC_InitdService.reg (rev 0)
+++ pybase/trunk/OMC_InitdService.reg 2007-06-11 20:07:41 UTC (rev 471)
@@ -0,0 +1,10 @@
+// Provider registration for OMC_InitdService
+instance of OpenWBEM_PyProviderRegistration
+{
+ InstanceID = "OMC:OMC_InitdService:01";
+ NamespaceNames = {"root/cimv2"};
+ ClassName = "OMC_InitdService";
+ ProviderTypes = {1,6}; // Instance, Method
+ ModulePath = "/usr/lib/pycim/OMC_InitdService.py";
+};
+
Added: pybase/trunk/OMC_LogicalFile.mof
===================================================================
--- pybase/trunk/OMC_LogicalFile.mof (rev 0)
+++ pybase/trunk/OMC_LogicalFile.mof 2007-06-11 20:07:41 UTC (rev 471)
@@ -0,0 +1,191 @@
+/*******************************************************************************
+ * Copyright (C) 2004 Novell, Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * - Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution.
+ *
+ * - Neither the name of Novell, Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from this
+ * software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS''
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL Novell, Inc. OR THE CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ ******************************************************************************/
+#pragma locale ("en_US")
+
+//////////////////////////////////////////////////////////////////////////////
+[ Abstract ]
+class OMC_DataFile : CIM_DataFile
+{
+ sint32 append([IN(true), OUT(false), REQUIRED(true)] string newtext);
+ sint32 write([IN(true), OUT(false), REQUIRED(true)] string newtext);
+ sint32 read([IN(false), OUT(true), REQUIRED(true)] string filetext);
+};
+
+//////////////////////////////////////////////////////////////////////////////
+[ Abstract ]
+class OMC_UnixDeviceFile : CIM_UnixDeviceFile
+{
+};
+
+//////////////////////////////////////////////////////////////////////////////
+[ Abstract ]
+class OMC_SymbolicLink : CIM_SymbolicLink
+{
+};
+
+//////////////////////////////////////////////////////////////////////////////
+[ Abstract ]
+class OMC_UnixDirectory : CIM_UnixDirectory
+{
+};
+
+//////////////////////////////////////////////////////////////////////////////
+[ Abstract ]
+class OMC_UnixSocketFile : CIM_LogicalFile
+{
+};
+
+//////////////////////////////////////////////////////////////////////////////
+[ Abstract ]
+class OMC_FIFOPipeFile : CIM_FIFOPipeFile
+{
+};
+
+//////////////////////////////////////////////////////////////////////////////
+[ Abstract ]
+class OMC_UnixFile : CIM_UnixFile
+{
+ boolean UserReadable;
+ boolean UserWritable;
+ boolean UserExecutable;
+ boolean GroupReadable;
+ boolean GroupWritable;
+ boolean GroupExecutable;
+ boolean WorldReadable;
+ boolean WorldWritable;
+ boolean WorldExecutable;
+};
+
+//////////////////////////////////////////////////////////////////////////////
+[ Association, Aggregation, Composition, Abstract,
+ Description("Specifies the hierarchical arrangement of LogicalFiles in a "
+ "Directory.")]
+class OMC_DirectoryContainsFile : CIM_DirectoryContainsFile
+{
+ [Override ("GroupComponent"), Aggregate, Max(1),
+ Description ("The Directory") ]
+ OMC_UnixDirectory REF GroupComponent;
+
+ [Override ("PartComponent"),
+ Description ("The LogicalFile 'contained within' the Directory.") ]
+ CIM_LogicalFile REF PartComponent;
+};
+
+//////////////////////////////////////////////////////////////////////////////
+[ Association, Abstract, Description (
+ "CIM_FileIdentity indicates that a UnixFile describes Unix-"
+ "specific aspects of the various subclasses of LogicalFile. "
+ "The association exists since it forces UnixFile to be "
+ "weak to (scoped by) the LogicalFile. This is not true in "
+ "the association's superclass, LogicalIdentity.")]
+class OMC_FileIdentity : CIM_FileIdentity
+{
+ [Override ("SystemElement"), Min (1), Max (1),
+ Description ("The Logical File.") ]
+ CIM_LogicalFile ref SystemElement;
+
+ [Override ("SameElement"), Weak, Max (1),
+ Description ("SameElement represents the additional aspects of the "
+ "Unix/Linux Logical file.") ]
+ OMC_UnixFile ref SameElement;
+
+};
+
+//////////////////////////////////////////////////////////////////////////////
+class OMC_LinuxDataFile : OMC_DataFile
+{
+};
+
+//////////////////////////////////////////////////////////////////////////////
+class OMC_LinuxDeviceFile : OMC_UnixDeviceFile
+{
+};
+
+//////////////////////////////////////////////////////////////////////////////
+class OMC_LinuxSymbolicLink : OMC_SymbolicLink
+{
+};
+
+//////////////////////////////////////////////////////////////////////////////
+class OMC_LinuxDirectory : OMC_UnixDirectory
+{
+};
+
+//////////////////////////////////////////////////////////////////////////////
+class OMC_LinuxFIFOPipeFile : OMC_FIFOPipeFile
+{
+};
+
+//////////////////////////////////////////////////////////////////////////////
+class OMC_LinuxSocketFile : OMC_UnixSocketFile
+{
+};
+
+//////////////////////////////////////////////////////////////////////////////
+class OMC_LinuxFile : OMC_UnixFile
+{
+};
+
+//////////////////////////////////////////////////////////////////////////////
+[Association, Aggregation, Composition,
+ Description("Specifies the hierarchical arrangement of LogicalFiles in a "
+ "Directory.")
+]
+class OMC_LinuxDirectoryContainsFile : OMC_DirectoryContainsFile
+{
+ [Override ("GroupComponent"), Aggregate, Max(1),
+ Description ("The Directory") ]
+ OMC_LinuxDirectory REF GroupComponent;
+
+ [Override ("PartComponent"),
+ Description ("The LogicalFile 'contained within' the Directory.") ]
+ CIM_LogicalFile REF PartComponent;
+};
+
+//////////////////////////////////////////////////////////////////////////////
+[Association, Description (
+ "CIM_FileIdentity indicates that a UnixFile describes Unix-"
+ "specific aspects of the various subclasses of LogicalFile. "
+ "The association exists since it forces UnixFile to be "
+ "weak to (scoped by) the LogicalFile. This is not true in "
+ "the association's superclass, LogicalIdentity.")]
+class OMC_LinuxFileIdentity : OMC_FileIdentity
+{
+ [Override ("SystemElement"), Min (1), Max (1),
+ Description ("The Logical File.") ]
+ CIM_LogicalFile ref SystemElement;
+
+ [Override ("SameElement"), Weak, Max (1), Description (
+ "SameElement represents the additional aspects of the "
+ "Unix/Linux Logical file.") ]
+ OMC_LinuxFile ref SameElement;
+
+};
+
Added: pybase/trunk/OMC_LogicalFile.py
===================================================================
--- pybase/trunk/OMC_LogicalFile.py (rev 0)
+++ pybase/trunk/OMC_LogicalFile.py 2007-06-11 20:07:41 UTC (rev 471)
@@ -0,0 +1,891 @@
+#*******************************************************************************
+# Copyright (C) 2007 Novell, Inc. All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions are met:
+#
+# - Redistributions of source code must retain the above copyright notice,
+# this list of conditions and the following disclaimer.
+#
+# - Redistributions in binary form must reproduce the above copyright notice,
+# this list of conditions and the following disclaimer in the documentation
+# and/or other materials provided with the distribution.
+#
+# - Neither the name of Novell, Inc. nor the names of its
+# contributors may be used to endorse or promote products derived from this
+# software without specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS''
+# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+# ARE DISCLAIMED. IN NO EVENT SHALL Novell, Inc. OR THE CONTRIBUTORS
+# BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+# POSSIBILITY OF SUCH DAMAGE.
+#
+#*****************************************************************************/
+"""Python Provider for CIM_LogicalFile
+
+Instruments the CIM class CIM_LogicalFile
+
+"""
+
+import pywbem
+from pycim import CIMProvider
+from stat import *
+from statvfs import *
+from socket import getfqdn
+import os
+from threading import RLock
+import pwd
+import grp
+
+_mounts = {}
+_mountssum = ''
+_guard = RLock()
+
+def _scanmounts():
+ """Process /proc/mounts."""
+ global _mountssum
+ global _mounts
+ mfile = open('/proc/mounts')
+ # mtime for /proc/mounts doesn't seem to get updated, so we'll
+ # compare the whole file instead
+ _guard.acquire()
+ contents = mfile.read()
+ if contents != _mountssum:
+ _mountssum = contents
+ _mounts.clear()
+ mfile.seek(0)
+ for line in mfile:
+ line = line.strip().split()
+ if line[0] == 'rootfs' or len(line) < 2 or line[1][0] != '/':
+ continue
+ dev = line[0]
+ if dev.startswith('/dev'):
+ tcount = 0
+ # naive way to not get stuck in link loops.
+ while os.path.islink(dev) and tcount < 10:
+ tcount += 1
+ target = os.readlink(dev)
+ if target[0] != '/':
+ target = os.path.dirname(dev)+'/'+target
+ dev = os.path.abspath(target)
+ _mounts[os.stat(line[1])[ST_DEV]] = dev
+ _guard.release()
+ mfile.close()
+
+_scanmounts()
+
+def get_file_path(fname):
+ keys = {}
+ get_file_keys(fname, keys)
+ return pywbem.CIMInstanceName(classname=keys['CreationClassName'],
+ keybindings=keys)
+
+def get_file_keys(fname, map, stat=None, linux_file=False):
+ """Set the keys on an instance or instance name
+
+ args:
+ fname -- The file name
+ map -- the mapping object
+ stat -- A stat tuple
+ linux_file -- True if the keys are for OMC...
[truncated message content] |
|
From: <ba...@us...> - 2007-06-06 21:19:19
|
Revision: 470
http://svn.sourceforge.net/omc/?rev=470&view=rev
Author: bartw
Date: 2007-06-06 14:19:20 -0700 (Wed, 06 Jun 2007)
Log Message:
-----------
moved yawn to pywbem project
Modified Paths:
--------------
tools/trunk/Makefile.am
Added Paths:
-----------
tools/trunk/yawn/README_moved_to_pywbem.txt
Removed Paths:
-------------
tools/trunk/yawn/Makefile.am
tools/trunk/yawn/deploy.SuSE
tools/trunk/yawn/yawn.py
Modified: tools/trunk/Makefile.am
===================================================================
--- tools/trunk/Makefile.am 2007-06-04 02:08:18 UTC (rev 469)
+++ tools/trunk/Makefile.am 2007-06-06 21:19:20 UTC (rev 470)
@@ -5,7 +5,6 @@
SUBDIRS = \
. \
cimtester \
- provtest \
- yawn
+ provtest
Deleted: tools/trunk/yawn/Makefile.am
===================================================================
--- tools/trunk/yawn/Makefile.am 2007-06-04 02:08:18 UTC (rev 469)
+++ tools/trunk/yawn/Makefile.am 2007-06-06 21:19:20 UTC (rev 470)
@@ -1 +0,0 @@
-EXTRA_DIST = yawn.py deploy.SuSE
Added: tools/trunk/yawn/README_moved_to_pywbem.txt
===================================================================
--- tools/trunk/yawn/README_moved_to_pywbem.txt (rev 0)
+++ tools/trunk/yawn/README_moved_to_pywbem.txt 2007-06-06 21:19:20 UTC (rev 470)
@@ -0,0 +1,6 @@
+Note:
+
+YAWN has move to the PyWBEM project (http://pywbem.sourceforge.net)
+
+Current svn for YAWN: http://pywbem.svn.sourceforge.net/viewvc/pywbem/yawn/
+
Deleted: tools/trunk/yawn/deploy.SuSE
===================================================================
--- tools/trunk/yawn/deploy.SuSE 2007-06-04 02:08:18 UTC (rev 469)
+++ tools/trunk/yawn/deploy.SuSE 2007-06-06 21:19:20 UTC (rev 470)
@@ -1,28 +0,0 @@
-NOTE: yawn currently requires the latest pywbem from svn.
-1. cd /usr/lib/python/site-packages
-2. svn co https://svn.sourceforge.net/svnroot/pywbem/trunk pywbem
-
-To deploy on SuSE 10:
-
-1. Enable mod_python in apache. This can be done with YaST. Run
- 'yast2 http-server', and check "Enable Python Scripting". Alternatively,
- edit /etc/sysconfig/apache2, and add "python" to the list of
- APACHE_MODULES. If you don't use YaST, make sure the apache2-mod_python
- package is installed (YaST will do this for you).
-2. Install the python-xml RPM from the SUSE media.
-3. It is a good idea to enable SSL also in apache
- - cd /usr/share/doc/packages/apache2; ./certificate.sh
- - Add "SSL" to APACHE_SERVER_FLAGS in /etc/sysconfig/apache2
- - cd /etc/apache2/vhosts.d; mv vhost-ssl.template vhost-ssl.conf
- - Add "ssl" to APACHE_MODULES in /etc/sysconfig/apache2
-4. Create the file /etc/apache2/conf.d/cim.conf containing the following:
- <Directory /srv/www/htdocs/cim>
- SetHandler mod_python
- PythonHandler mod_python.publisher
- PythonDebug On
- </Directory>
-5. Install (copy) yawn.py to /srv/www/htdocs/cim/index.py
-6. Restart apache2
-
-Now point your web browser to http://<server>/cim
-
Deleted: tools/trunk/yawn/yawn.py
===================================================================
--- tools/trunk/yawn/yawn.py 2007-06-04 02:08:18 UTC (rev 469)
+++ tools/trunk/yawn/yawn.py 2007-06-06 21:19:20 UTC (rev 470)
@@ -1,2012 +0,0 @@
-#!/usr/bin/env python
-#**************************************************************************
-#|
-#| Copyright (c) 2006 Novell, Inc.
-#| All Rights Reserved.
-#|
-#| This program is free software; you can redistribute it and/or
-#| modify it under the terms of version 2 of the GNU General Public License as
-#| published by the Free Software Foundation.
-#|
-#| This program is distributed in the hope that it will be useful,
-#| but WITHOUT ANY WARRANTY; without even the implied warranty of
-#| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-#| GNU General Public License for more details.
-#|
-#| You should have received a copy of the GNU General Public License
-#| along with this program; if not, contact Novell, Inc.
-#|
-#| To contact Novell about this file by physical or electronic mail,
-#| you may find current contact information at www.novell.com
-#|
-#|*************************************************************************
-
-# NOTE: yawn currently requires the latest pywbem from svn.
-# cd /usr/lib/python/site-packages
-# svn co https://svn.sourceforge.net/svnroot/pywbem/trunk pywbem
-
-# @author Bart Whiteley <bwh...@su...>
-# @author Norm Paxton <np...@no...>
-
-from mod_python import Cookie, apache
-from datetime import timedelta
-import pywbem
-import cgi
-import types
-import cPickle
-import base64
-import urlparse
-import string
-import zlib
-import os
-
-
-# Mostly I just wanted to be able to say that I've used lambda functions
-#_val2str = lambda x: (type(x) == types.UnicodeType and x or str(x))
-##############################################################################
-# no need to cgi.urllib.unquote_plus(). mod_python does that for us.
-_decodeObject = lambda x: (cPickle.loads(zlib.decompress(base64.b64decode(x))))
-##############################################################################
-_encodeObject = lambda x: (base64.b64encode(zlib.compress(cPickle.dumps(x, cPickle.HIGHEST_PROTOCOL))))
-##############################################################################
-def _val2str(x):
- #if type(x) == types.UnicodeType:
- # return x
- if x is None:
- return '<font color="#999999"><i>Null</i></font>'
- elif isinstance(x,list):
- rval = '{'
- if x:
- for i in range(0, len(x)):
- item = x[i]
- if i > 0:
- rval+= ', '
- strItem = _val2str(item)
- if type(item) in types.StringTypes:
- strItem = '"' + strItem + '"'
- rval+= strItem
- rval+= '}'
- return cgi.escape(rval)
- elif type(x) == timedelta:
- #http://msdn2.microsoft.com/en-us/library/aa387237.aspx
- #http://msdn2.microsoft.com/en-us/library/aa390895.aspx
- mss = str(x.microseconds)
- while len(mss) < 6:
- mss = '0' + mss
- hours = x.seconds / (60*60)
- mins = x.seconds % (60*60) / 60
- secs = x.seconds % 60
- hours = str(hours)
- mins = str(mins)
- secs = str(secs)
- if len(hours) < 2:
- hours = '0' + hours
- if len(mins) < 2:
- mins = '0' + mins
- if len(secs) < 2:
- secs = '0' + secs
- days = str(x.days)
- while len(days) < 8:
- days = '0'+days
- return cgi.escape(days + hours + mins + secs + '.' + mss + ':000')
-
- else:
- return cgi.escape(str(x))
-
-##############################################################################
-_status_codes = [('', '')
- ,('FAILED' , 'A general error occurred')
- ,('ACCESS_DENIED' , 'Resource not available')
- ,('INVALID_NAMESPACE' , 'The target namespace does not exist')
- ,('INVALID_PARAMETER' , 'Parameter value(s) invalid')
- ,('INVALID_CLASS' , 'The specified Class does not exist')
- ,('NOT_FOUND' , 'Requested object could not be found')
- ,('NOT_SUPPORTED' , 'Operation not supported')
- ,('CLASS_HAS_CHILDREN' , 'Class has subclasses')
- ,('CLASS_HAS_INSTANCES' , 'Class has instances')
- ,('INVALID_SUPERCLASS' , 'Superclass does not exist')
- ,('ALREADY_EXISTS' , 'Object already exists')
- ,('NO_SUCH_PROPERTY' , 'Property does not exist')
- ,('TYPE_MISMATCH' , 'Value incompatible with type')
- ,('QUERY_LANGUAGE_NOT_SUPPORTED', 'Query language not supported')
- ,('INVALID_QUERY' , 'Query not valid')
- ,('METHOD_NOT_AVAILABLE' , 'Extrinsic method not executed')
- ,('METHOD_NOT_FOUND' , 'Extrinsic method does not exist')]
-
-def _code2string(code):
- if code > len(_status_codes) -1:
- return (str(code), "UNKNOWN ERROR")
- return _status_codes[code]
-
-##############################################################################
-def _sortkey(keylist, klass):
- """Sort a list of property names, but bubble the key classes first
- in the sorted results."""
-
- def keycmp(a, b):
- def is_key(key):
- klassProp = klass.properties.has_key(key) and klass.properties[key] or None
- return klassProp and klassProp.qualifiers.has_key('key')
- is_key_a = is_key(a)
- is_key_b = is_key(b)
- if is_key_a and is_key_b:
- return cmp(a, b)
- if is_key_a and not is_key_b:
- return -1
- if not is_key_a and is_key_b:
- return 1
- return cmp(a, b)
-
- keylist.sort(keycmp)
-
-##############################################################################
-def getAllHierarchy(req, url, ns, className):
- hierarchy = []
-
- conn = _getConn(req, url, ns)
- hierarchy.append(className)
- classNameToCheck = className
- while classNameToCheck != None:
- subklass = conn.GetClass(classNameToCheck, LocalOnly = False, IncludeQualifiers = True)
- if subklass.superclass != None:
- classNameToCheck = subklass.superclass
- hierarchy.append(classNameToCheck)
- else:
- classNameToCheck = None
- return hierarchy;
-
-##############################################################################
-def isSubClass(req, url, ns, subClassName, parentClassName):
- conn = _getConn(req, url, ns)
-
- #first the easy case: are they the same
- req.write('<br>is ' + subClassName + ' a subclass of ' + parentClassName)
- if subClassName == parentClassName:
- return True
- #now, get the class object for subClassName, see if its parent class is parentClassName
- classNameToCheck = subClassName
- while classNameToCheck != None:
-# req.write('<br>is ' + subClassName + ' a subclass of ' + parentClassName)
-# req.write('<br>classNameToCheck: ' + classNameToCheck)
- subklass = conn.GetClass(classNameToCheck, LocalOnly = False, IncludeQualifiers = True)
-# req.write('<br>subklass: ' + `subklass`)
-# req.write('<br>parentClassName: ' + parentClassName)
-
- if subklass.superclass != None:
-# req.write('<br>subklass.superclass: ' + subklass.superclass)
- classNameToCheck = subklass.superclass
- if subklass.superclass == parentClassName:
- req.write('<br><b>Yes! Returning True</b><br><br>')
- return True
-# req.write('<br>new classNameToCheck: ' + classNameToCheck)
-# req.write('<br><br>')
- else:
- classNameToCheck = None
- req.write('<br><b>Didn\'t find it... returning False</b><br><br>')
- return False;
-
-##############################################################################
-def DeleteInstance(req, url, ns, instPath):
- conn = _frontMatter(req, url, ns)
- instName = _decodeObject(instPath)
- try:
- conn.DeleteInstance(instName)
- # TODO make this use _ex()
- except pywbem.cim_http.AuthError, arg:
- raise apache.SERVER_RETURN, apache.HTTP_UNAUTHORIZED
- except pywbem.CIMError, arg:
- req.write( _printHead('Error Deleting instance of '+instName.classname))
- req.write( 'Deleting instance of '+instName.classname+
- ' returned the following error:<br> <i>(' + `arg[0]` +
- ') : ' + arg[1] + '</i>')
- req.write( '</body></html>')
- return;
- urlargs = {'ns':ns,'url':url,'className':instName.classname}
- req.write( _printHead('Deleted Instance of '+instName.classname,
- urlargs=urlargs))
- req.write('Deleted Instance of ' + _makeHref(req, 'GetClass',
- urlargs, instName.classname))
- _printInstanceNames(req, urlargs, [instName], omitGetLink=True)
- return '</body></html>'
-
-##############################################################################
-def ReferenceNames(req, url, ns, instPath):
- """ The goal here is to list InstPaths to all related objects, grouped
-in the
- following manner:
- - Assoc Class Name
- - Role of related object
- - Type of object (its classname)
- - instPath1
- - instPath2
- - ...
- - Another type (classname)
- - instPaths
- - Another role
- - type
- - paths
- - Another Assoc Class Name
- - Role
- - ...
- Known bugs: if an assoc class has a key property of type other than REF,
- we'll probably blow up. We also won't follow non-key REF properties (if
- there are such things)
- """
- conn = _frontMatter(req, url, ns)
- urlargs = {}
- urlargs['ns'] = ns
- urlargs['url'] = url
- instName = _decodeObject(instPath)
- oldns = instName.namespace
- # TODO remove this namespace hack when pywbem is fixed
- instName.namespace = None
- refs = _ex(req, conn.ReferenceNames,ObjectName=instName)
- instName.namespace = oldns is not None and oldns or ns
-
- class_urlargs = urlargs.copy()
- class_urlargs["className"] = instName.classname
- ht = 'Objects associated with instance of '
- ht+= _makeHref(req, 'GetClass', class_urlargs, instName.classname)
- ht = _printHead('ReferenceNames '+instName.classname, ht, req, urlargs)
- req.write(ht)
-
- _printInstanceNames(req, urlargs, [instName])
- req.write('<hr>',0)
- refdict = {}
- for ref in refs:
- refInstPath = ref
- assocClassName = refInstPath.classname
- if assocClassName not in refdict.keys():
- refdict[assocClassName] = {}
- for role in refInstPath.keys():
- roleInstPath = refInstPath[role]
- if roleInstPath == instName:
- continue
- if role not in refdict[assocClassName].keys():
- refdict[assocClassName][role] = {}
- roleClassName = roleInstPath.classname
- if roleClassName not in refdict[assocClassName][role].keys():
- refdict[assocClassName][role][roleClassName] = []
- refdict[assocClassName][role][roleClassName].append(roleInstPath)
- assocClassNames = refdict.keys()
- assocClassNames.sort()
- req.write('<h2>Associations Available</h2><ul>')
- for assocClassName in assocClassNames:
- req.write('<li><a href="#' + assocClassName + '">'+assocClassName+'</a>')
- req.write('</ul>')
- for assocClassName in assocClassNames:
- class_urlargs["className"] = assocClassName
- assocLink = _makeHref(req, 'GetClass', class_urlargs, assocClassName)
- req.write( '<a name="' + assocClassName + '"/>')
- req.write( '\n<table border="1">\n',0)
- req.write( '<tr>\n')
- req.write( ' <td>\n')
- req.write( ' <table>\n')
- req.write( ' <tr>\n')
- req.write( ' <td>\n')
- req.write( ' <font size=+3>Association: '+assocLink+'</font>\n')
- req.write( ' </td>\n')
- req.write( ' </tr>\n')
- assocSet = refdict[assocClassName]
- roles = assocSet.keys()
- roles.sort()
- for role in roles:
- req.write( ' <tr>\n')
- req.write( ' <td>\n')
- req.write( ' <table border="1">\n')
- req.write( ' <tr>\n')
- req.write( ' <td>\n')
- req.write( ' <font size=+2>Role: '+role+'</font>\n')
- req.write( ' </td>\n')
- req.write( ' </tr>\n')
- classSet = assocSet[role]
- classNames = classSet.keys()
- classNames.sort()
- for className in classNames:
- class_urlargs["className"] = className
- typeLink = _makeHref(req, 'GetClass', class_urlargs, className)
- req.write( ' <tr>\n')
- req.write( ' <td>\n' )
- req.write( ' <table>\n')
- req.write( ' <tr>\n')
- req.write( ' <td>\n')
- req.write( ' <font size=+1>Type: '+typeLink+'</font>\n')
- req.write( ' </td>\n')
- req.write( ' </tr>\n')
- req.write( ' <tr>\n')
- req.write( ' <td>\n')
- instPathSet = classSet[className]
- instPathSet.sort()
- _printInstanceNames(req, urlargs, instPathSet)
- req.write( ' </td>\n')
- req.write( ' </tr>\n')
- req.write( ' </table>\n')
- req.write( ' </td>\n')
- req.write( ' </tr>\n' )
- req.write( ' </table>\n')
- req.write( ' </td>\n')
- req.write( ' </tr>\n')
-
- req.write( ' </table>\n')
- req.write( ' </td>\n')
- req.write( '</tr>\n')
- req.write( '</table>\n')
- return '</body></html>'
-
-##############################################################################
-def FilteredReferenceNames(req, url, ns, instPath, assocClass, resultClass,
- role, resultRole, assocCall, properties):
- conn = _frontMatter(req, url, ns)
- urlargs = {}
- urlargs['ns'] = ns
- urlargs['url'] = url
- instName = _decodeObject(instPath)
- refs = None
- req.write( _printHead(assocCall+' '+instName.classname,urlargs=urlargs))
-
- class_urlargs = urlargs.copy()
- class_urlargs["className"] = instName.classname
- ht = '<h1>Filtered Objects associated with instance of '
- ht+= _makeHref(req, 'GetClass', class_urlargs, instName.classname) +'</h1>'
- if assocCall=='Associators':
- ht+='<b>Associators ( AssocClass=' + assocClass + ', ResultClass=' + resultClass + ', Role=' + role + ', ResultRole=' + resultRole + ', Properties=' + properties + ' )</b><br><br>'
- elif assocCall=='Associator Names':
- ht+='<b>AssociatorNames ( AssocClass=' + assocClass + ', ResultClass=' + resultClass + ', Role=' + role + ', ResultRole=' + resultRole + ', Properties=' + properties + ' )</b><br><br>'
- elif assocCall=='References':
- ht+='<b>References ( ResultClass=' + resultClass + ', Role=' + role + ', Properties=' + properties + ' )</b><br><br>'
- elif assocCall=='Reference Names':
- ht+='<b>ReferenceNames ( ResultClass=' + resultClass + ', Role=' + role + ', Properties=' + properties + ' )</b><br><br>'
- req.write(ht)
-
- refdict = {}
- params = {}
-
- if len(assocClass) > 0:
- params['AssocClass'] = assocClass
- if len(resultClass) > 0:
- params['ResultClass'] = resultClass
- if len(role) > 0:
- params['Role'] = role
- if len(resultRole) > 0:
- params['ResultRole'] = resultRole
- if assocCall=='Associators' or assocCall=='References':
- params['IncludeQualifiers'] = True
-
- try:
- if assocCall=='Associators':
- assocs = conn.Associators(instName, **params)#, properties)
- req.write('Showing ' + `len(assocs)` + ' resulting object(s). <br><br>')
- for assoc in assocs:
- assocInstPath = assoc.path
- assocInst = assoc
- assocClassName = assocInst.classname
- req.write('<hr><h2>Objects of Class: ' + assocClassName + '</h2>')
- _printInstanceNames(req, urlargs, [assocInstPath])
-
- klass = _ex(req, conn.GetClass,ClassName=assocInstPath.classname, namespace=assocInstPath.namespace, LocalOnly = False, IncludeQualifiers = True)
- req.write(_displayInstance(req, assocInst, assocInstPath, klass, urlargs))
- elif assocCall=='Associator Names':
- assocNames = conn.AssociatorNames(instName, **params)#, properties)
- req.write('Showing ' + `len(assocNames)` + ' resulting object(s). <br><br>')
- for assocName in assocNames:
- assocInstPath = assocName
- req.write('<hr><h2>Objects of Class: ' + assocInstPath.classname + '</h2>')
- _printInstanceNames(req, urlargs, [assocInstPath])
- elif assocCall=='References':
- refs = _ex(req,conn.References,ObjectName=instName,
- **params)#, properties)
- req.write('Showing ' + `len(refs)` + ' resulting object(s). <br><br>')
- for ref in refs:
- assocInstPath = ref.path
- assocInst = ref
- assocClassName = assocInst.classname
- _printInstanceNames(req, urlargs, [assocInstPath])
-
- klass = _ex(req,conn.GetClass,ClassName=assocInstPath.classname, LocalOnly = False, IncludeQualifiers = True)
- req.write(_displayInstance(req, assocInst, assocInstPath, klass, urlargs))
- elif assocCall=='Reference Names':
- refNames = conn.ReferenceNames(instName, **params)#, properties)
- req.write('Showing ' + `len(refNames)` + ' resulting object(s). <br><br>')
- for refName in refNames:
- assocInstPath = refName
- req.write('<hr><h2>Objects of Class: ' + assocInstPath.classname + '</h2>')
- _printInstanceNames(req, urlargs, [assocInstPath])
- except pywbem.cim_http.AuthError, arg:
- raise apache.SERVER_RETURN, apache.HTTP_UNAUTHORIZED
-
- return '</body></html>'
-
-##############################################################################
-def AssociatorNames(req, url, ns, instPath):
- conn = _frontMatter(req, url, ns)
- urlargs = {}
- urlargs['ns'] = ns
- urlargs['url'] = url
- instName = _decodeObject(instPath)
- assocs = _ex(req,conn.AssociatorNames,ObjectName=instName)
- ht = _printHead('AssociatorNames '+instName.classname, urlargs=urlargs)
- groupedAssocs = {}
- for assoc in assocs:
- if assoc.classname not in groupedAssocs.keys():
- groupedAssocs[assoc.classname] = [assoc]
- else:
- groupedAssocs[assoc.classname].append(assoc)
- setkeys = groupedAssocs.keys()
- setkeys.sort()
- for setkey in setkeys:
- ht+= '<h2>'+setkey+'</h2>'
- req.write(ht)
- assocList = groupedAssocs[setkey]
- _printInstanceNames(req, urlargs, assocList)
- return '</body></html>'
-
-##############################################################################
-def FilteredReferenceNamesDialog(req, url, ns, instPath):
- conn = _frontMatter(req, url, ns)
- instName = _decodeObject(instPath)
- class_urlargs = {}
- class_urlargs['ns'] = ns
- class_urlargs['url'] = url
- class_urlargs["className"] = instName.classname
- ht = _printHead('Filtered ReferenceNames Dialog... (Coming...)', urlargs=class_urlargs)
- ht+= '<h1>Filtered References on Class '+_makeHref(req, 'GetClass', class_urlargs, instName.classname)+'</h1>'
- req.write(ht)
- _printInstanceNames(req, class_urlargs, [instName])
- ht= '<br><br><br><form type=get action="'+_baseScript(req)+'/FilteredReferenceNames" METHOD=GET>'
- ht+= '<input type=hidden name="url" value="'+url+'">'
- ht+= '<input type=hidden name="ns" value="'+ns+'">'
- ht+= '<input type=hidden name="instPath" value="'+instPath+'">'
- ht+= '<table border=1>'
- ht+= '<tr><td>Association Class<br><i>Not applicable for Reference/ReferenceNames</i></td><td><input type=text name="assocClass"></td></tr>'
- ht+= '<tr><td>Result Class</td><td><input type=text name="resultClass"></td></tr>'
- ht+= '<tr><td>Role</td><td><input type=text name="role"</td></tr>'
- ht+= '<tr><td>Result Role<br><i>Not applicable for Reference/ReferenceNames</i></td><td><input type=text name="resultRole"></td></tr>'
- ht+= '<tr><td>Properties<br><i>Comma-separated</i></td><td><input type=text name="properties"></td></tr>'
- ht+= '<tr><td valign=top>Call Type</td><td><select name="assocCall"><option value="Associators">Associator<br>'
- ht+= '<option value="Associator Names">Associator Names<br>'
- ht+= '<option value="References">References<br>'
- ht+= '<option value="Reference Names">Reference Names</select></td></tr>'
- ht+= '<tr><td colspan=2 align=right><input type=submit value="Submit"></td></tr>'
- ht+= '</table>'
- ht+= '</form>'
- req.write(ht)
- return '</body></html>'
-
-
-##############################################################################
-def _displayMappedValue(val, quals):
- rval = ''
- if isinstance(val, list):
- rval+= '{'
- valList = val
- else:
- valList = [val]
- valmapQual = quals['valuemap'].value
- valuesQual = quals['values'].value
- for i in valList:
- if i is not valList[0]:
- rval += ', '
- propstr = _val2str(i)
- rval+= propstr
- if propstr in valmapQual:
- valIdx = valmapQual.index(propstr)
- if valIdx < len(valuesQual):
- rval+= ' ('+valuesQual[valIdx]+')'
-
- if isinstance(val, list):
- rval+= '}'
- return rval
-
-##############################################################################
-def _displayInstance(req, inst, instName, klass, urlargs):
- class_urlargs = urlargs.copy()
- class_urlargs["className"] = klass.classname
- ht= '<h2>Instance of '+_makeHref(req, 'GetClass', class_urlargs, klass.classname)+'</h2>'
- ht+= '<h4>Host: <i><font color="#00AA00">' + _val2str(instName.host) + '</font></i>'
- ht+= '<br>Namespace: <i><font color="#00AA00">' + _val2str(instName.namespace) + '</font></i></h4>'
- ht+= '<align ="right">'
- urlargs['instPath'] = _encodeObject(instName)
- ht+= '</align>'
- keys = inst.keys()
- _sortkey(keys, klass)
- ht+= '<table border="1" cellpadding="2">'
- ht+= '<tr>'
- ht+= '<td>'+_makeHref(req, 'DeleteInstance', urlargs, 'Delete')
- ht+= '<br>'+_makeHref(req, 'ModifyInstPrep', urlargs, 'Modify')
- ht+= '</td>'
- ht+= '<td align="right" colspan=2>View '
- ht+= _makeHref(req, 'ReferenceNames', urlargs,'Objects Associated with this Instance')
- ht+= '<br>'
- ht+= _makeHref(req, 'FilteredReferenceNamesDialog', urlargs,'(With Filters)')
- ht+= '</td></tr>'
- ht+= '<tr bgcolor="CCCCCC"><th>Type</th><th>Name</th><th>Value</th>'
- haveRequiredProps = False
- for key in keys:
- prop = inst.properties[key]
- klassProp = klass.properties.has_key(key) and klass.properties[key] or None
- propIsKey = klassProp and klassProp.qualifiers.has_key('key')
- propIsRequired = klassProp and klassProp.qualifiers.has_key('required')
- propTitle = ''
- if klassProp and klassProp.qualifiers.has_key('description'):
- propTitle = klassProp.qualifiers['description'].value
- ht+= '<tr'
- if propIsKey:
- ht+= ' bgcolor="#FFDDDD"'
- elif propIsRequired:
- ht+= ' bgcolor="#FFaaaa"'
- haveRequiredProps = True
- ht+= '>'
- if prop.reference_class is None:
- ht+= '<td>'+prop.type
- if prop.is_array:
- ht+= ' [ ]'
- else:
- ht+= '<td>'+prop.reference_class + ' <i>Ref</i>'
- ht+= '</td><td title="'+cgi.escape(propTitle)+'">'+_makeHref(req, 'GetClass', class_urlargs, key, '#'+key.lower())+'</td><td>'
-
-
- if klassProp and klassProp.qualifiers.has_key('values') and klassProp.qualifiers.has_key('valuemap'):
- ht+= _displayMappedValue(prop.value, klassProp.qualifiers)
- elif prop.reference_class is not None:
- ns = _val2str(inst[key].namespace)
- urlargs['ns'] = ns
- targetInstName = inst[key]
- targetObjectPath = _val2str(targetInstName)
- ht+= _makeGetInstLink(req, urlargs, targetInstName, targetObjectPath)
- else:
- propval = _val2str(prop.value)
- if key.lower().endswith("classname"):
- link_urlargs = class_urlargs.copy()
- link_urlargs["className"] = propval
- ht+= _makeHref(req, "GetClass", link_urlargs, propval)
- else:
- ht+= propval
- ht+= '</td></tr>'
- ht+= '<tr><td colspan=3><table border=0><tr><td nowrap bgcolor="#FFDDDD">'
- ht+= '<i>Key Property</i></td>'
- if haveRequiredProps == True:
- ht+= '<td></td><td nowrap bgcolor="#FFaaaa">'
- ht+= '<i>Required (non-key) Property</i></td>'
- ht+= '<td width="100%" align="right"></table></td></tr>'
- if klass.methods:
- ht+= '<tr><td colspan=3>'
- ht+= '<table>'
- ht+= '<tr><td>'
- ht+= '<font size=+1><center><b>Methods</b></center></font>'
- ht+= '</td></tr>'
- for method in klass.methods.values():
- ht+= '<tr>'
- ht+= ' <td>'
- methUrlArgs = urlargs.copy()
- methUrlArgs['objPath'] = methUrlArgs['instPath']
- del methUrlArgs['instPath']
- methUrlArgs['method'] = method.name
- ht+= _makeHref(req, 'PrepMethod', methUrlArgs, method.name) + '('
- for param in method.parameters.keys():
- if param != method.parameters.keys()[0]:
- ht+= ','
- ht+= param
- ht+=')'
- ht+= ' </td>'
- ht+= '</tr>'
- ht+= '</table>'
- ht+= '</td></tr>'
- purlargs = {'obj': _encodeObject(instName)}
- ht+= '<tr><td colspan=3>'
- ht+= 'Get the '+_makeHref(req, 'Pickle', purlargs, 'LocalInstancePath')
- ht+= ' for use as a Method Reference Parameter'
- ht+= '</td></tr>'
- ht+= '</table>'
- return ht
-
-
-##############################################################################
-def GetInstance(req, url, ns, instPath):
- conn = _frontMatter(req, url, ns)
- urlargs = {}
- urlargs['ns'] = ns
- urlargs['url'] = url
- instName = _decodeObject(instPath)
- inst = None
- klass = _ex(req,conn.GetClass,ClassName=instName.classname, LocalOnly = False, IncludeQualifiers = True)
- inst = _ex(req,conn.GetInstance,InstanceName=instName, LocalOnly = False)
- ht = _printHead('Instance of '+instName.classname, req=req, urlargs=urlargs)
- ht+= _displayInstance(req, inst, instName, klass, urlargs)
- return ht + '</body></html>'
-
-##############################################################################
-def _makeHref(req, func, dict, target, append=''):
- return '<a href="'+_baseScript(req)+'/'+func+'?'+cgi.urllib.urlencode(dict)+append+'">'+cgi.escape(target)+'</a>'
-
-
-##############################################################################
-def _makeHrefWithTags(req, func, dict, target, openTags, closeTags):
- return '<a href="'+_baseScript(req)+'/'+func+'?'+cgi.urllib.urlencode(dict)+'">'+openTags+cgi.escape(target)+closeTags+'</a>'
-
-
-##############################################################################
-def _printInstHeading(keys, includeNS=False, omitGetLink = False):
- ht = ' <tr bgcolor="CCCCCC">\n'
- if not omitGetLink:
- ht+= ' <th></th>\n'
- for key in keys:
- ht+= ' <th>'+key+'</th>\n'
- if includeNS:
- ht+= '<th><i><font color="#00AA00">Namespace</font></i></th>'
- ht+= ' </tr>\n'
- return ht
-
-##############################################################################
-def _makeGetInstLink(req, urlargs, instName, targetName):
- urlargs['instPath'] = _encodeObject(instName)
- return _makeHref(req, 'GetInstance', urlargs, targetName)
-
-##############################################################################
-def _printInstRow(req, urlargs, keys, inst, omitGetLink = False):
- lurlargs = urlargs.copy()
- if inst.namespace is not None:
- lurlargs['ns'] = inst.namespace
- ht = ' <tr>\n'
- if not omitGetLink:
- ht+= ' <td>\n'
- ht+= _makeGetInstLink(req, lurlargs, inst, 'get')+'\n'
- ht+= ' </td>\n'
- for key in keys:
- keyval = inst[key]
- ht+= ' <td>\n'
- if isinstance(keyval, pywbem.CIMInstanceName):
- ns = keyval.namespace
- if ns is not None:
- lurlargs['ns'] = ns
- ht+= _makeGetInstLink(req, lurlargs, keyval, _val2str(keyval))+'\n'
- if ns is not None:
- ht+= '<br><i>In namespace: ' + ns + '</i>'
- else:
- ht+= _val2str(keyval)+'\n'
- ht+= ' </td>\n'
- if inst.namespace is not None:
- ht+= ' <td><i><font color="#00AA00">'+inst.namespace+'</font></i></td>\n'
- ht+= ' </tr>\n'
- req.write(ht)
-
-##############################################################################
-def Pickle(req, obj):
- req.add_common_vars()
- ht = _printHead("Object", "Object Serialization", req)
- ht+= '<p><i>To pass the following object as a Parameter Reference to a method call, copy this string to your clipboard and paste it to the parameter field.</i><p>'
- ht+= '<hr>'+obj+'<hr>'
- lobj = _decodeObject(obj)
- ht+= '<p><pre>'+cgi.escape(lobj.tocimxml().toprettyxml())+'</pre>'
- ht+= str(lobj)
- return ht + '</body></head>'
-
-##############################################################################
-def _printInstanceNames(req, urlargs, instNames, omitGetLink=False):
- if len(instNames) > 0:
- ht = '\n<table border="1" cellpadding="2">\n'
- if instNames[0].namespace:
- keys = instNames[0].keys()
- keys.sort()
- ht+= _printInstHeading(keys, includeNS=True, omitGetLink=omitGetLink)
- else:
- keys = instNames[0].keys()
- keys.sort()
- ht+= _printInstHeading(keys, omitGetLink=omitGetLink)
- req.write(ht)
- instNames.sort()
- for instName in instNames:
- _printInstRow(req, urlargs, keys, instName, omitGetLink)
- req.write( '</table>\n')
-
-##############################################################################
-def EnumInstances(req, url, ns, className):
- conn = _frontMatter(req, url, ns)
- urlargs = {}
- urlargs['ns'] = ns
- urlargs['url'] = url
- insts = _ex(req,conn.EnumerateInstances,ClassName = className, LocalOnly = False)
- ht = _printHead('Instances of '+className, 'Instances of '+className, req, urlargs=urlargs)
- numInsts = len(insts)
- msgStart = 'Showing '+`numInsts`+' Instances<br />'
- if numInsts == 0:
- msgStart = 'No Instances<br />'
- elif numInsts == 1:
- msgStart = ''
- ht+= msgStart
- req.write(ht)
- for inst in insts:
- instName = inst.path
- klass = conn.GetClass(instName.classname, LocalOnly = "false")
- req.write(_displayInstance(req, inst, instName, klass, urlargs.copy()))
- return '</body></html>'
-
-##############################################################################
-def _createOrModifyInstance(req, conn, url, ns, className, instName, **params):
- urlargs = {}
- urlargs['ns'] = ns
- urlargs['url'] = url
- klass = _ex(req, conn.GetClass, ClassName = className, LocalOnly = False, IncludeQualifiers = True)
- if instName is not None:
- inst = _ex(req, conn.GetInstance,InstanceName=instName, LocalOnly = False)
- else:
- inst = pywbem.CIMInstance(className)
- inst.path = pywbem.CIMInstanceName(className, namespace=ns)
- # Remove 'PropName.' prefix from param names.
- params = dict ([(x[9:],y) for (x, y) in params.items()])
- for propName, propVal in params.items():
- metaProp = klass.properties[propName]
- if metaProp.reference_class is not None:
- dt = metaProp.reference_class
- else:
- dt = metaProp.type
- if propVal:
- if metaProp.reference_class is not None:
- inst.properties[propName] = _decodeObject(propVal)
- else:
- if metaProp.is_array:
- if type(propVal) is not list:
- propVal = propVal.strip()
- propVal = propVal.strip('{}[]')
- propVal = propVal.strip()
- if len(propVal) > 2 and dt == 'string' \
- and propVal[0] == '"' and propVal[-1] == '"' :
- propVal = '['+propVal+']'
- propVal = eval(propVal)
- else:
- propVal = propVal.split(",")
- propVal = [x.strip() for x in propVal]
- propVal = [pywbem.tocimobj(dt, x) for x in propVal]
- inst.properties[propName] = propVal
- else:
- inst.properties[propName] = pywbem.tocimobj(dt, propVal)
- if instName:
- if instName.namespace is None:
- instName.namespace = ns
- inst.path = instName
- _ex(req, conn.ModifyInstance,ModifiedInstance=inst)
- else:
- instName = _ex(req, conn.CreateInstance, NewInstance=inst)
- inst = _ex(req, conn.GetInstance,InstanceName=instName, LocalOnly = False)
-
- urlargs['instPath'] = _encodeObject(instName)
- refurl = _baseScript(req)+'/GetInstance?'+cgi.urllib.urlencode(urlargs)
- ht = '<HTML>'
- ht+= '<META HTTP-EQUIV="Refresh" CONTENT="1;URL='+refurl+'">'
- ht+= '<HEAD><TITLE>Saving Instance...</TITLE> </HEAD>'
- ht+= '<BODY>The Instance has been saved. Refreshing...<br>'
- ht+= '<p>If your browser doesn't refresh to the new instance, '
- ht+= 'click '+ _makeGetInstLink(req, urlargs, instName, 'here.')
- return ht
-
-##############################################################################
-def CreateInstance(req, url, ns, className, **params):
- conn = _frontMatter(req, url, ns)
- ht = _createOrModifyInstance(req, conn, url, ns, className, None, **params)
- return ht + '</body></html>'
-
-##############################################################################
-def ModifyInstance(req, url, ns, instPath, **params):
- conn = _frontMatter(req, url, ns)
- instName = _decodeObject(instPath)
- ht = _createOrModifyInstance(req, conn, url, ns, instName.classname, instName, **params)
- return ht + '</body></html>'
-
-##############################################################################
-def CreateInstancePrep(req, url, ns, className):
- conn = _frontMatter(req, url, ns)
- klass = _ex(req, conn.GetClass, ClassName = className, LocalOnly = False, IncludeQualifiers = True)
- ht = _printHead('Create Instances of '+className,'Create Instances of '+className, req, urlargs={'ns':ns, 'url':url})
- ht+= _displayInstanceMod(req, conn, url, ns, klass)
- return ht + '</body></html>'
-
-##############################################################################
-def ModifyInstPrep(req, url, ns, instPath):
- conn = _frontMatter(req, url, ns)
- instPathDec = _decodeObject(instPath)
- klass = _ex(req,conn.GetClass,ClassName=instPathDec.classname, LocalOnly = False, IncludeQualifiers = True)
- ht = _printHead('Modify Instances of '+instPathDec.classname,'Modify Instances of '+instPathDec.classname, req, urlargs={'ns':ns, 'url':url})
- ht+= _displayInstanceMod(req, conn, url, ns, klass, (instPath, instPathDec))
- return ht + '</body></html>'
-
-##############################################################################
-def _displayInstanceMod(req, conn, url, ns, klass, oldInstPathPair = None):
- urlargs = {}
- urlargs['ns'] = ns
- urlargs['url'] = url
- oldInstPath = None
- oldInstPathDec = None
- if oldInstPathPair is not None:
- oldInstPath = oldInstPathPair[0]
- oldInstPathDec = oldInstPathPair[1]
- className = klass.classname
- urlargs['className'] = className
- oldInst = None
- if oldInstPathDec is not None:
- oldInst = _ex(req,conn.GetInstance,InstanceName=oldInstPathDec, LocalOnly = False)
- haveRequiredProps = False
- propNames = klass.properties.keys()
- _sortkey(propNames, klass)
- ht = '<table border=0><tr><td>'
- method = oldInst is not None and 'ModifyInstance' or 'CreateInstance'
- ht+= '<form action="'+_baseScript(req)+'/'+method+'" METHOD=POST>'
- ht+= '<input type=hidden name="url" value="'+url+'">'
- ht+= '<input type=hidden name="ns" value="'+ns+'">'
- if oldInstPathPair is None:
- ht+= '<input type=hidden name="className" value="'+className+'">'
- else:
- ht+= '<input type=hidden name="instPath" value="'+oldInstPath+'">'
- ht+= '<table border="1" cellpadding="2">'
- ht+= '<tr bgcolor="CCCCCC"><th>Type</th><th>Name</th><th>Value</th>'
- ht+= '</tr>'
- for propName in propNames:
- prop = klass.properties[propName]
- propIsKey = prop.qualifiers.has_key('key')
- propIsRequired = prop.qualifiers.has_key('required')
- propTitle = ''
- if prop.qualifiers.has_key('description'):
- propTitle = prop.qualifiers['description'].value
- ht+= '<tr'
- if propIsKey:
- ht+= ' bgcolor="#FFDDDD"'
- elif propIsRequired:
- ht+= ' bgcolor="#FFaaaa"'
- haveRequiredProps = True
- ht+= '>'
- if prop.reference_class is None:
- ht+= '<td>'+prop.type
- if prop.is_array:
- ht+= ' [ ]'
- else:
- ht+= '<td>'+prop.reference_class + ' <i>Ref</i>'
- ht+= '</td><td title="'+cgi.escape(propTitle)+'">'+_makeHref(req, 'GetClass', urlargs, propName, '#'+propName.lower())+'</td>'
- ht+= '<td>'
- fPropName = 'PropName.'+prop.name
- oldVal = None
- if oldInst is not None:
- if oldInst.properties.has_key(propName):
- oldVal = oldInst.properties[propName].value
- if prop.qualifiers.has_key('valuemap'):
- if type(oldVal) == list:
- oldVal = [str(x) for x in oldVal]
- needComboBox = True
- valmapQual = prop.qualifiers['valuemap'].value
- valuesQual = None
- if prop.qualifiers.has_key('values'):
- valuesQual = prop.qualifiers['values'].value
-
- # Disable the combobox for now, because it isn't working, and
- # we may not actually need it. For example, perhaps any time
- # values from VendorReserved are used, the vendor's subclass
- # will override the method, and thus the qualifiers, and provide
- # specific valuemap extensions that would in turn show up in our
- # drop down.
- #ht+= '<select name="'+fPropName+'" class="comboBox">'
- ht+= '<select name="'+fPropName+'"'
- if prop.is_array:
- ht+= ' MULTIPLE SIZE=4'
- ht+= '>'
- if not prop.is_array:
- ht+= '<option value='""'>'
- for i in range(0, len(valmapQual)):
- curVal = valmapQual[i]
- # skip valuemap items that aren't valid values
- # such as the numeric ranges for DMTF Reserved and whatnot
- try:
- pywbem.tocimobj(prop.type, curVal)
- except:
- continue
- ht+= '<option value="'+curVal+'"'
- if oldVal is not None:
- if type(oldVal) == list:
- if curVal in oldVal:
- ht+= ' SELECTED'
- elif str(oldVal) == curVal:
- ht+= ' SELECTED'
- ht+= '>'+curVal
- if valuesQual and i < len(valuesQual):
- ht+= ' ('+valuesQual[i]+')'
- ht+= '</select>'
-
- else:
- if oldVal is not None and propIsKey:
- ht+= _val2str(oldVal)
- elif prop.type == 'boolean' and not prop.is_array:
- ht+= '<select name="'+fPropName+'">'
- ht+= '<option value='""'>'
- ht+= '<option value="True"'
- if oldVal is not None and oldVal:
- ht+= ' SELECTED'
- ht+= '>True'
- ht+= '<option value="False"'
- if oldVal is not None and not oldVal:
- ht+= ' SELECTED'
- ht+= '>False'
- ht+= '</select>'
- else:
- ht+= '<input type=text size=50 name="'+fPropName+'"'
- if oldVal is not None:
- strValue = _val2str(oldVal)
- if isinstance(oldVal,list):
- strValue = strValue.replace('"','"')
- ht+= ' value="'+strValue+'"'
- ht+= '>'
- ht+= '</td></tr>'
-
- ht+= '</table></td></tr>'
- ht+= '<tr><td colspan=3><table border=0><tr><td nowrap bgcolor="#FFDDDD">'
- ht+= '<i>Key Property</i></td>'
- if haveRequiredProps == True:
- ht+= '<td></td><td nowrap bgcolor="#FFaaaa">'
- ht+= '<i>Required (non-key) Property</i></td>'
- ht+= '<td width="100%" align="right">'
- ht+= '<input type=submit value="Save Instance"></td></table></td></tr>'
- ht+= '</form>'
- ht+= '</table>'
- return ht
-
-##############################################################################
-def EnumInstanceNames(req, url, ns, className):
- conn = _frontMatter(req, url, ns)
- urlargs = {}
- urlargs['ns'] = ns
- urlargs['url'] = url
- instNames = _ex(req,conn.EnumerateInstanceNames,ClassName = className)
- numInsts = len(instNames)
- ht = ''
- if numInsts == 0:
- ht = 'No Instances'
- elif numInsts == 1:
- ht = '1 Instance'
- else:
- ht = `numInsts`+' Instances'
-
- class_urlargs = urlargs.copy()
- class_urlargs["className"] = className
- ht+= ' of '
- ht+= _makeHref(req, 'GetClass', class_urlargs, className) + '</h1>'
- ht = _printHead('Instances of '+className, ht, req, urlargs=urlargs)
- req.write(ht)
- _printInstanceNames(req, urlargs, instNames)
- ht = '<p>'
- ht+= _makeHref(req, 'CreateInstancePrep', class_urlargs, 'Create New Instance')
- return ht + '</body></html>'
-
-##############################################################################
-def _frontMatter(req, url, ns):
- req.add_common_vars()
- req.content_type = 'Text/HTML'
- authHeader = 'Basic realm="CIMOM at '+url+'"'
- req.headers_out["WWW-Authenticate"] = authHeader
- req.err_headers_out["WWW-Authenticate"] = authHeader
- return _getConn(req, url, ns)
-
-##############################################################################
-def InvokeMethod(req, url, ns, objPath, method, **params):
- conn = _frontMatter(req, url, ns)
- urlargs = {}
- urlargs['ns'] = ns
- urlargs['url'] = url
- className = None
- lobjPath = _decodeObject(objPath)
- if isinstance(lobjPath, pywbem.CIMInstanceName) and lobjPath.namespace is None:
- lobjPath.namespace = ns
- className = lobjPath.classname
- urlargs['className'] = className
- # else lobjPath is a CIMInstanceName
- klass = _ex(req,conn.GetClass,ClassName = lobjPath.classname, LocalOnly = "false")
- ht = 'Invoked method '+_makeHref(req, 'GetClass', urlargs, className)
- ht+= '::'+_makeHref(req, 'GetClass', urlargs, method, '#'+method.lower())
- ht+= '()'
- ht = _printHead('Results of Method '+className+'::'+method, ht, req, urlargs=urlargs)
-
- cimmethod = klass.methods[method]
- inParms = {}
-
- def type_str (meta_parm):
- if meta_parm.reference_class is not None:
- urlargs['className'] = metaParm.reference_class
- dt = 'REF ' + _makeHref(req, 'GetClass', urlargs,
- metaParm.reference_class)
- else:
- dt = metaParm.type
- if metaParm.is_array:
- dt+= '[]'
- return dt
-
- if params:
- # Remove 'MethParm.' prefix from param names.
- params = dict ([(x[9:],y) for (x, y) in params.items()])
- ht+= '<h3>With Input Parameters</h3>'
- ht+= '<table valign=top border=1>'
- ht+= ' <tr bgcolor="#CCCCCC"><th>Data Type</th><th>Param Name</th><th>Value</th></tr>'
- for paramName, paramVal in params.items():
- metaParm = cimmethod.parameters[paramName]
- dt = type_str(metaParm)
- ht+= ' <tr><td>'+dt+'</td>'
- ht+= ' <td>'+paramName+'</td>'
- ht+= ' <td>'+_val2str(paramVal)+'</td></tr>'
- if paramVal:
- if metaParm.is_array:
- if type(paramVal) is not list:
- paramVal = paramVal.strip()
- paramVal = paramVal.strip('{}[]')
- paramVal = paramVal.strip()
- if len(paramVal) > 2 and dt == 'string' \
- and paramVal[0] == '"' and paramVal[-1] == '"' :
- paramVal = '['+paramVal+']'
- paramVal = eval(paramVal)
- else:
- paramVal = paramVal.split(",")
- paramVal = [x.strip() for x in paramVal]
- if metaParm.reference_class is not None:
- paramVal = [_decodeObject(x) for x in paramVal]
- else:
- paramVal = [pywbem.tocimobj(dt, x) for x in paramVal]
- inParms[paramName] = paramVal
- else:
- if metaParm.reference_class is not None:
- inParms[paramName] = _decodeObject(paramVal)
- else:
- inParms[paramName] = pywbem.tocimobj(dt, paramVal)
- ht+= '</table>'
-
- (rval, outParms) = _ex(req,conn.InvokeMethod,MethodName=method, ObjectName=lobjPath, **inParms)
-
- if outParms:
- ht+= '<h3>Output Values</h3>'
- ht+= '<table border=1><tr bgcolor="#CCCCCC">'
- ht+= '<th>Data Type</th><th>Param Name</th><th>Value</th></tr>'
- for parmName, parm in outParms.items():
- metaParm = cimmethod.parameters[parmName]
- isRef = metaParm.reference_class is not None
- dt = type_str(metaParm)
- ht+= '<tr><td>'+dt+'</td><td>'+metaParm.name+'</td><td>'
- if metaParm.qualifiers.has_key('values') and metaParm.qualifiers.has_key('valuemap'):
- display = str(parm)
- valmapQual = metaParm.qualifiers['valuemap'].value
- valuesQual = metaParm.qualifiers['values'].value
- if display in valmapQual:
- valIdx = valmapQual.index(display)
- if valIdx < len(valuesQual):
- display = display + ' ('+valuesQual[valIdx]+')'
- ht+= display
- else:
- if isRef and parm is not None:
- ht+= _makeGetInstLink(req, urlargs, parm, _val2str(parm))
- else:
- ht+= _val2str(parm)
- ht+= '</td></tr>'
- ht+= '</table>'
-
- ht+= '<font size=+1><b>Method returned:</b></font> ' + _val2str(rval)
- urlargs['className'] = className
- ht+= '<p>Return to class ' + _makeHref(req, 'GetClass', urlargs, className)
- if isinstance(lobjPath, pywbem.CIMInstanceName):
- del urlargs['className']
- ht+= ' or instance of '+className + ':'
- req.write(ht)
- _printInstanceNames(req, urlargs, [lobjPath])
- ht = ''
-
- return ht + '</body></html>'
-
-##############################################################################
-def PrepMethod(req, url, ns, objPath, method):
- conn = _frontMatter(req, url, ns)
- urlargs = {}
- urlargs['ns'] = ns
- urlargs['url'] = url
- lobjPath = _decodeObject(objPath)
- className = None
- className = lobjPath.classname
- klass = _ex(req,conn.GetClass,ClassName = className, LocalOnly = "false")
-
- cimmethod = klass.methods[method]
- inParms = []
- outParms = []
- for param in cimmethod.parameters.values():
- # TODO is IN assumed to be true if the IN qualifier is missing?
- if not param.qualifiers.has_key('in') or param.qualifiers['in'].value:
- inParms.append(param)
- if param.qualifiers.has_key('out') and param.qualifiers['out'].value:
- outParms.append(param)
-
-
- classUrlArgs = urlargs.copy()
- classUrlArgs['className'] = className
- ht = 'Invoke method '+_makeHref(req, 'GetClass', classUrlArgs, className)
- ht+= '::'+_makeHref(req, 'GetClass', classUrlArgs, method, '#'+method.lower())+'()'
- # note, ht passed in as param.
- ht = _printHead('Method '+className+'::'+method, ht, req, urlargs=urlargs)
- if isinstance(lobjPath, pywbem.CIMInstanceName):
- ht+= 'on instance'
- req.write(ht,0)
- _printInstanceNames(req, urlargs, [lobjPath])
- ht = ''
- ht+= '<form action="'+_baseScript(req)+'/InvokeMethod" METHOD=POST>'
- ht+= '<input type=hidden name="url" value="'+url+'">'
- ht+= '<input type=hidden name="ns" value="'+ns+'">'
- ht+= '<input type=hidden name="objPath" value="'+objPath+'">'
- ht+= '<input type=hidden name="method" value="'+method+'">'
- ht+= '<table border=0>'
- needComboBox = False
- if inParms:
- someRequired = False
- ht+= '<h3>Enter Input Parameters</h3>'
- ht+= '<tr><td><table valign=top border=1>'
- ht+= '<tr bgcolor="#CCCCCC"><th>Data Type</th><th>Param Name</th><th>Value</th></tr>'
- for param in inParms:
- ht+= '<tr valign=top'
- if param.qualifiers.has_key('required') and param.qualifiers['required'].value:
- ht+= ' bgcolor="#FFDDDD"'
- someRequired = True
-
- if param.reference_class is not None:
- ht+= '><td>'+param.reference_class
- ht+= ' REF'
- else:
- ht+= '><td>'+param.type
- if param.is_array:
- ht+= ' [ ]'
- ht+= '</td>'
- ht+= '<td'
- if param.qualifiers.has_key('description'):
- ht+= ' title="'+cgi.escape(param.qualifiers['description'].value)+'"'
- ht+= '>'
- ht+= param.name
- ht+= '</td><td>'
- # avoid name collisions, in case some param is called ns, url, etc.
- parmName = 'MethParm.'+param.name
- if param.qualifiers.has_key('valuemap'):
- needComboBox = True
- valmapQual = param.qualifiers['valuemap'].value
- valuesQual = None
- if param.qualifiers.has_key('values'):
- valuesQual = param.qualifiers['values'].value
-
- # Disable the combobox for now, because it isn't working, and
- # we may not actually need it. For example, perhaps any time
- # values from VendorReserved are used, the vendor's subclass
- # will override the method, and thus the qualifiers, and provide
- # specific valuemap extensions that would in turn show up in our
- # drop down.
- #ht+= '<select name="'+parmName+'" class="comboBox">'
- ht+= '<select name="'+parmName+'"'
- if param.is_array:
- ht+= ' MULTIPLE SIZE=4'
- ht+= '>'
- if not param.is_array:
- ht+= '<option value="">'
- for i in range(0, len(valmapQual)):
- curVal = valmapQual[i]
- # skip valuemap items that aren't valid values
- # such as the numeric ranges for DMTF Reserved and whatnot
- try:
- pywbem.tocimobj(param.type, curVal)
- except:
- continue
- ht+= '<option value="'+curVal+'">'+curVal
- if valuesQual and i < len(valuesQual):
- ht+= ' ('+valuesQual[i]+')'
- ht+= '</select>'
-
- elif param.type == 'boolean':
- ht+= '<select name="'+parmName+'">'
- ht+= '<option value='""'>'
- ht+= '<option value="True">True'
- ht+= '<option value="False">False'
- ht+= '</select>'
- else:
- ht+= '<input type=text size=50 name="'+parmName+'">'
- ht+= '</td></tr>'
- ht+= '</table></td></tr>'
- ht+= '<tr>'
- if someRequired:
- ht+= '<td><table border=0><tr><td nowrap bgcolor="#FFDDDD">'
- ht+= '<i>Required Parameter</i></td><td width="100%" align="right">'
- else:
- ht+= '<td align="right">'
- ht+= '<input type=submit value="Invoke Method"></td></tr>'
- if someRequired:
- ht+= '</table></td></tr>'
- ht+= '</table>'
- else:
- ht+= '<input type=submit value="Invoke Method">'
- ht+= '</form>'
- if outParms:
- ht+= '<h3>Output Parameters</h3>'
- ht+= '<table valign=top border=1><tr bgcolor="#CCCCCC">'
- ht+= '<th>Data Type</th><th>Param Name</th></tr>'
- for param in outParms:
- ht+= '<tr valign=top><td>'
- if param.reference_class is not None:
- ht+= param.reference_class
- ht+= ' REF'
- else:
- ht+= param.type
- if param.is_array:
- ht+= ' [ ]'
- ht+= '</td><td'
- if param.qualifiers.has_key('description'):
- ht+= ' title="'+cgi.escape(param.qualifiers['description'].value)+'"'
- ht+= '>'+param.name+'</td></tr>'
- ht+= '</table>'
- rtype = cimmethod.return_type is not None and cimmethod.return_type or 'void'
- ht+= '<h3>Method return type: '+rtype+'</h3>'
-
- if needComboBox:
- ht+= _comboBox_js
-
- req.write(ht)
- return '</body></html>'
-
-##############################################################################
-def PrepMofComp(req, url):
- conn = _frontMatter(req, url, 'root/cimv2')
- ht = _printHead("MOF", "MOF", req, {'url':url})
- ht+= '<form action="'+_baseScript(req)+'/MofComp" '
- ht+= 'enctype="multipart/form-data" METHOD=POST>'
- ht+= '<input type=hidden name="url" value="'+url+'"/>'
- ht+= '<input type=hidden name="ns" value="'+'root/cimv2'+'"/>'
- ht+= '<input id="file" name="file" size="70" type="file" />'
- ht+= '<p><textarea cols="80" id="text" name="text" rows="40">'
- ht+= '</textarea>'
- ht+= '<p><input name="commit" type="submit" value="Submit" />'
- ht+= '</form>'
- return ht + '</body></html>'
-
-##############################################################################
-def MofComp(req, url, ns, file, text):
- conn = _frontMatter(req, url, 'root/cimv2')
- ht = _printHead("MOF", "MOF", req, {'url':url})
- ht+= "file:<pre>"
- ht+= cgi.escape(file.value)
- ht+= '</pre>'
- ht+= 'text:<pre>'
- ht+= cgi.escape(text)
- ht+= '</pre>'
- return ht + '</body></html>'
-
-##############################################################################
-def _ex(req, method, **params):
- try:
- return method(**params)
- except pywbem.cim_http.AuthError, arg:
- raise apache.SERVER_RETURN, apache.HTTP_UNAUTHORIZED
- except pywbem.CIMError, arg:
- ht = _printHead('Error')
- details = _code2string(arg[0])
- ht+= '<p><i>'+details[0]+': ' + details[1]+'</i>'
- ht+= '<pre>'+cgi.escape(arg[1])+'</pre>'
- ht+= '<hr>'
- if req.conn.debug:
- if req.conn.last_request is not None:
- ht+= '<pre>'+cgi.escape(req.conn.last_request)+'</pre>'
- ht+= '<hr>'
- if req.conn.last_reply is not None:
- ht+= '<pre>'+cgi.escape(req.conn.last_reply)+'</pre>'
- ht+= '</body></html>'
- req.write(ht)
- # see http://tinyurl.com...
[truncated message content] |
|
From: <ba...@us...> - 2007-06-04 02:08:16
|
Revision: 469
http://svn.sourceforge.net/omc/?rev=469&view=rev
Author: bartw
Date: 2007-06-03 19:08:18 -0700 (Sun, 03 Jun 2007)
Log Message:
-----------
renamed cimprovider -> pycim
Modified Paths:
--------------
tools/trunk/yawn/yawn.py
Modified: tools/trunk/yawn/yawn.py
===================================================================
--- tools/trunk/yawn/yawn.py 2007-05-24 17:41:45 UTC (rev 468)
+++ tools/trunk/yawn/yawn.py 2007-06-04 02:08:18 UTC (rev 469)
@@ -1309,7 +1309,7 @@
ht+= ' of this class.'
try:
# see if code generator is available
- from cimprovider import codegen
+ from pycim import codegen
ht+= ' '+ _makeHref(req,
'Provider', instUrlArgs, 'Python Provider')
except ImportError:
@@ -1961,7 +1961,7 @@
conn = _frontMatter(req, url, ns)
klass = _ex(req, conn.GetClass, ClassName = className, LocalOnly = "false",
IncludeClassOrigin = "true")
- from cimprovider import codegen
+ from pycim import codegen
code, mof = codegen(klass)
title = 'Python Provider for %s' % className
ht = _printHead(title, req)
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ba...@us...> - 2007-05-24 17:41:43
|
Revision: 468
http://svn.sourceforge.net/omc/?rev=468&view=rev
Author: bartw
Date: 2007-05-24 10:41:45 -0700 (Thu, 24 May 2007)
Log Message:
-----------
fix display of null and array params in InvokeMethod
Modified Paths:
--------------
tools/trunk/yawn/yawn.py
Modified: tools/trunk/yawn/yawn.py
===================================================================
--- tools/trunk/yawn/yawn.py 2007-05-23 05:03:33 UTC (rev 467)
+++ tools/trunk/yawn/yawn.py 2007-05-24 17:41:45 UTC (rev 468)
@@ -1,4 +1,4 @@
-#!/usr/bin/python
+#!/usr/bin/env python
#**************************************************************************
#|
#| Copyright (c) 2006 Novell, Inc.
@@ -334,7 +334,8 @@
return '</body></html>'
##############################################################################
-def FilteredReferenceNames(req, url, ns, instPath, assocClass, resultClass, role, resultRole, assocCall, properties):
+def FilteredReferenceNames(req, url, ns, instPath, assocClass, resultClass,
+ role, resultRole, assocCall, properties):
conn = _frontMatter(req, url, ns)
urlargs = {}
urlargs['ns'] = ns
@@ -1000,6 +1001,18 @@
cimmethod = klass.methods[method]
inParms = {}
+
+ def type_str (meta_parm):
+ if meta_parm.reference_class is not None:
+ urlargs['className'] = metaParm.reference_class
+ dt = 'REF ' + _makeHref(req, 'GetClass', urlargs,
+ metaParm.reference_class)
+ else:
+ dt = metaParm.type
+ if metaParm.is_array:
+ dt+= '[]'
+ return dt
+
if params:
# Remove 'MethParm.' prefix from param names.
params = dict ([(x[9:],y) for (x, y) in params.items()])
@@ -1008,10 +1021,7 @@
ht+= ' <tr bgcolor="#CCCCCC"><th>Data Type</th><th>Param Name</th><th>Value</th></tr>'
for paramName, paramVal in params.items():
metaParm = cimmethod.parameters[paramName]
- if metaParm.reference_class is not None:
- dt = metaParm.reference_class
- else:
- dt = metaParm.type
+ dt = type_str(metaParm)
ht+= ' <tr><td>'+dt+'</td>'
ht+= ' <td>'+paramName+'</td>'
ht+= ' <td>'+_val2str(paramVal)+'</td></tr>'
@@ -1048,14 +1058,8 @@
ht+= '<th>Data Type</th><th>Param Name</th><th>Value</th></tr>'
for parmName, parm in outParms.items():
metaParm = cimmethod.parameters[parmName]
- isRef = False
- if metaParm.reference_class is not None:
- isRef = True
- urlargs['className'] = metaParm.reference_class
- dt = _makeHref(req, 'GetClass', urlargs,
- metaParm.reference_class)
- else:
- dt = metaParm.type
+ isRef = metaParm.reference_class is not None
+ dt = type_str(metaParm)
ht+= '<tr><td>'+dt+'</td><td>'+metaParm.name+'</td><td>'
if metaParm.qualifiers.has_key('values') and metaParm.qualifiers.has_key('valuemap'):
display = str(parm)
@@ -1067,7 +1071,7 @@
display = display + ' ('+valuesQual[valIdx]+')'
ht+= display
else:
- if isRef:
+ if isRef and parm is not None:
ht+= _makeGetInstLink(req, urlargs, parm, _val2str(parm))
else:
ht+= _val2str(parm)
@@ -1305,7 +1309,7 @@
ht+= ' of this class.'
try:
# see if code generator is available
- from cimprovider import provider_template
+ from cimprovider import codegen
ht+= ' '+ _makeHref(req,
'Provider', instUrlArgs, 'Python Provider')
except ImportError:
@@ -1957,8 +1961,8 @@
conn = _frontMatter(req, url, ns)
klass = _ex(req, conn.GetClass, ClassName = className, LocalOnly = "false",
IncludeClassOrigin = "true")
- from cimprovider import provider_template
- code, mof = provider_template(klass)
+ from cimprovider import codegen
+ code, mof = codegen(klass)
title = 'Python Provider for %s' % className
ht = _printHead(title, req)
ht+= '<font size=+1><b>%s</b></font>' % title
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ba...@us...> - 2007-05-23 05:03:32
|
Revision: 467
http://svn.sourceforge.net/omc/?rev=467&view=rev
Author: bartw
Date: 2007-05-22 22:03:33 -0700 (Tue, 22 May 2007)
Log Message:
-----------
moved python provider generator to cimprovider
Modified Paths:
--------------
tools/trunk/yawn/yawn.py
Modified: tools/trunk/yawn/yawn.py
===================================================================
--- tools/trunk/yawn/yawn.py 2007-05-22 15:26:08 UTC (rev 466)
+++ tools/trunk/yawn/yawn.py 2007-05-23 05:03:33 UTC (rev 467)
@@ -1302,8 +1302,15 @@
ht+= '<div align=center>View '+_makeHref(req, 'EnumInstanceNames', instUrlArgs, 'Instance Names')
ht+= ' or '+_makeHref(req, 'EnumInstances', instUrlArgs, 'Instances')
ht+= ' or '+_makeHref(req, 'AssociatedClasses', instUrlArgs, 'Associated Classes')
- ht+= ' of this class. '+_makeHref(req,
- 'Provider', instUrlArgs, 'Python Provider')+'</div>'
+ ht+= ' of this class.'
+ try:
+ # see if code generator is available
+ from cimprovider import provider_template
+ ht+= ' '+ _makeHref(req,
+ 'Provider', instUrlArgs, 'Python Provider')
+ except ImportError:
+ pass
+ ht+= '</div>'
ht+= '<table border="1" cellpadding="2">'
if klass.qualifiers.has_key('aggregation'):
titleBGColor = "green"
@@ -1945,305 +1952,13 @@
##############################################################################
##############################################################################
##############################################################################
-def _providerTemplate (cc):
- #################
- def format_desc (obj):
- txt = ''
- try:
- raw = obj.qualifiers['description'].value
- beg = 0
- end = 0
- while beg < len(raw):
- beg = end
- end += 65
- while beg < len(raw) and raw[beg] in string.whitespace:
- beg = beg+1
- while end < len(raw) and end > beg \
- and raw[end] not in string.whitespace:
- end = end-1
- line = raw[beg:end]
- line = line.replace('\n',' ')
- txt +='''
- %s''' % line
- except KeyError:
- pass
- return txt
- #################
- def type_str (obj):
- tx = obj.type
- if tx == 'reference':
- tx = 'REF %s (CIMInstanceName)' % obj.reference_class
- if obj.is_array:
- tx += '[]'
- return tx
- #################
- def is_required (obj):
- try:
- if obj.qualifiers['required'].value:
- return '(Required)'
- else:
- return ''
- except KeyError:
- return ''
- #################
-
- mappings = {'classname':cc.classname,
- 'classname_l':cc.classname.lower()}
- isAssoc = 'association' in cc.qualifiers
-
- code = '''"""Python Provider for %(classname)s
-
-Instruments the CIM class %(classname)s
-"""
-
-import pywbem
-from cimprovider import CIMProvider
-
-class %(classname)sProvider(CIMProvider):
- """Instrument the CIM class %(classname)s
-''' % mappings
- code+= format_desc(cc)
- code+= '''
- """
-
- #########################################################################
- def __init__ (self):
- pass
-
- #########################################################################
- def get_instance (self, env, model, cim_class):
- """Return an instance of %(classname)s
-
- Keyword arguments:
- env -- Provider Environment
- model -- A template of the CIMInstance to be returned. The key
- properties are set on this instance to correspond to the
- instanceName that was requested. The properties of the model
- are already filtered according to the PropertyList from the
- request.
- cim_class -- The CIMClass %(classname)s
-
- """
-''' % mappings
- keyProps = [p for p in cc.properties.values() \
- if 'key' in p.qualifiers]
- for prop in cc.properties.values():
- if 'key' in prop.qualifiers:
- continue
- code+= '''
- if '%(pname)s' in model.properties:
- model['%(pname)s'] = # TODO (type = %(ptype)s) %(required)s''' \
- % { 'pname': prop.name, 'ptype': type_str(prop),
- 'required':is_required(prop) }
-
- code+= '''
- return model
-
- #########################################################################
- def enum_instances(self, env, model, cim_class, keys_only):
- """ Enumerate instances of %(classname)s
- The WBEM operations EnumerateInstances and EnumerateInstanceNames
- are both mapped to this method.
- This method is a python generator
-
- Keyword arguments:
- env -- Provider Environment
- model -- A template of the CIMInstances to be generated. The
- properties of the model are already filtered according to the
- PropertyList from the request.
- cim_class -- The CIMClass %(classname)s
- keys_only -- A boolean. True if only the key properties should be
- set on the generated instances.
-
- """
-
- while False: # TODO more instances?
- # TODO fetch system resource
- # Key properties''' % mappings
- for kp in keyProps:
- code+='''
- model['%(pname)s'] = # TODO (type = %(ptype)s)''' \
- % { 'pname':kp.name, 'ptype':type_str(kp) }
- code+='''
- if keys_only:
- yield model
- else:
- try:
- yield self.get_instance(env, model, cim_class)
- except pywbem.CIMError, (num, msg):
- if num not in (pywbem.CIM_ERR_NOT_FOUND,
- pywbem.CIM_ERR_ACCESS_DENIED):
- raise
-'''
-
- code+='''
- #########################################################################
- def set_instance(self, env, instance, previous_instance, cim_class):
- """ Return a newly created or modified instance of %(classname)s
-
- Keyword arguments:
- env -- Provider Environment
- instance -- The new CIMInstance. If modifying an existing instance,
- the properties on this instance have been filtered by the
- PropertyList from the request.
- previous_instance -- The previous instance if modifying an existing
- instance. None if creating a new instance.
- cim_class -- The CIMClass %(classname)s
-
- Return the new instance. The keys must be set on the new instance.
-
- """
-
- # TODO create or modify the instance
- return instance
-
- #########################################################################
- def delete_instance(self, env, instance_name):
- """ Delete an instance of %(classname)s
-
- Keyword arguments:
- env -- Provider Environment
- instance_name -- A CIMInstanceName specifying the instance of
- %(classname)s to delete.
-
- """ ''' % mappings
-
- for method in cc.methods.values():
- inParms = [ p for p in method.parameters.values() if \
- 'in' in p.qualifiers and p.qualifiers['in'].value ]
- outParms = [ p for p in method.parameters.values() if \
- 'out' in p.qualifiers and p.qualifiers['out'].value ]
- code+= '''
- #########################################################################
- def cim_method_%s(self, env, object_name, method''' % method.name.lower()
- for p in inParms:
- code+= ''',
- param_%s''' % p.name.lower()
- code+= '''):
- """Implements %s.%s()
-''' % (cc.classname, method.name)
- code+= format_desc(method)
-
- code+= '''
- Keyword arguments:
- env -- Provider Environment
- object_name -- A CIMInstanceName or CIMCLassName specifying the
- object on which the method %(mname)s should be invoked
- method -- A CIMMethod representing the method meta-data'''
-
- for p in inParms:
- code+= '''
- param_%s -- The input parameter %s (type %s) %s''' \
- % (p.name.lower(), p.name, type_str(p), is_required(p))
- code+= format_desc(p)
-
- code+='''
-
- Returns a two-tuple containing the return value (type %s)
- and a dictionary with the out-parameters
-
- Output parameters:''' %(method.return_type)
-
- if not outParms:
- code+= ' none'
- else:
- for p in outParms:
- code+='''
- %s -- (type %s) %s''' % (p.name, type_str(p), is_required(p))
- code+= format_desc(p)
-
-
- code+='''
-
- """
-
- # TODO do something
- out_params = {}'''
-
- for p in outParms:
- code+='''
- out_params['%s'] = # TODO (type %s)''' % (p.name.lower(), type_str(p))
-
- code+='''
- rval = # TODO (type %s)
- return (rval, out_params)
- ''' % method.return_type
-
- if isAssoc:
- code+= '''
- #########################################################################
- def references(self, env, object_name, model, assoc_class,
- result_class_name, role, result_role):
- """Instrument %(classname)s Associations.
- All four association-related operations (Associators, AssociatorNames,
- References, ReferenceNames) are mapped to this method.
- This method is a python generator
-
- Keyword arguments:
- env -- Provider Environment
- object_name -- A CIMInstanceName that defines the source CIM Object
- whose associated Objects are to be returned.
- model -- A template CIMInstance of %(classname)s to serve as a model
- of the objects to be returned. Only properties present on this
- model need to be returned.
- assoc_class -- The CIMClass %(classname)s
- result_class_name -- If not None, acts as a filter on the returned set
- of Objects by mandating that each returned Object MUST be either
- an Instance of this Class (or one of its subclasses) or be this
- Class (or one of its subclasses).
- role -- If not None, acts as a filter on the returned set of Objects
- by mandating that each returned Object MUST be associated to the
- source Object via an Association in which the source Object plays
- the specified role (i.e. the name of the Property in the
- Association Class that refers to the source Object MUST match
- the value of this parameter).
- result_role -- If not None, acts as a filter on the returned set of
- Objects by mandating that each returned Object MUST be associated
- to the source Object via an Association in which the returned
- Object plays the specified role (i.e. the name of the Property in
- the Association Class that refers to the returned Object MUST
- match the value of this parameter).
- """
-
-''' % mappings
-
- code+= '''
-
-## end of class %(classname)sProvider
-
-_%(classname_l)s_prov = %(classname)sProvider() # initialize provider
-py_providers = {'%(classname)s': _%(classname_l)s_prov} # register provider
-''' % mappings
-
- ptypes = ['1', 'Instance']
- if isAssoc:
- ptypes[0]+= ',3'
- ptypes[1]+= ', Associator'
- if cc.methods:
- ptypes[0]+= ',6'
- ptypes[1]+= ', Method'
- mof ='''
-// Provider registration for %(classname)s
-instance of OpenWBEM_PyProviderRegistration
-{
- InstanceID = "<org:product:unique_id>"; // TODO
- NamespaceNames = {"root/cimv2"};
- ClassName = "%(classname)s";
- ProviderTypes = {%(ptypeNums)s}; // %(ptypeStrs)s
- ModulePath = "/some/path/%(classname)sProvider.py"; // TODO
-};
-''' % {'classname': cc.classname,
- 'ptypeNums': ptypes[0],
- 'ptypeStrs': ptypes[1]}
-
- return code, mof
-
def Provider(req, url, ns, className):
conn = _frontMatter(req, url, ns)
klass = _ex(req, conn.GetClass, ClassName = className, LocalOnly = "false",
IncludeClassOrigin = "true")
- code, mof = _providerTemplate(klass)
+ from cimprovider import provider_template
+ code, mof = provider_template(klass)
title = 'Python Provider for %s' % className
ht = _printHead(title, req)
ht+= '<font size=+1><b>%s</b></font>' % title
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ba...@us...> - 2007-05-22 15:26:08
|
Revision: 466
http://svn.sourceforge.net/omc/?rev=466&view=rev
Author: bartw
Date: 2007-05-22 08:26:08 -0700 (Tue, 22 May 2007)
Log Message:
-----------
changed codegen a bit
Modified Paths:
--------------
tools/trunk/yawn/yawn.py
Modified: tools/trunk/yawn/yawn.py
===================================================================
--- tools/trunk/yawn/yawn.py 2007-05-21 22:53:49 UTC (rev 465)
+++ tools/trunk/yawn/yawn.py 2007-05-22 15:26:08 UTC (rev 466)
@@ -1237,6 +1237,33 @@
return '</body></html>'
##############################################################################
+def PrepMofComp(req, url):
+ conn = _frontMatter(req, url, 'root/cimv2')
+ ht = _printHead("MOF", "MOF", req, {'url':url})
+ ht+= '<form action="'+_baseScript(req)+'/MofComp" '
+ ht+= 'enctype="multipart/form-data" METHOD=POST>'
+ ht+= '<input type=hidden name="url" value="'+url+'"/>'
+ ht+= '<input type=hidden name="ns" value="'+'root/cimv2'+'"/>'
+ ht+= '<input id="file" name="file" size="70" type="file" />'
+ ht+= '<p><textarea cols="80" id="text" name="text" rows="40">'
+ ht+= '</textarea>'
+ ht+= '<p><input name="commit" type="submit" value="Submit" />'
+ ht+= '</form>'
+ return ht + '</body></html>'
+
+##############################################################################
+def MofComp(req, url, ns, file, text):
+ conn = _frontMatter(req, url, 'root/cimv2')
+ ht = _printHead("MOF", "MOF", req, {'url':url})
+ ht+= "file:<pre>"
+ ht+= cgi.escape(file.value)
+ ht+= '</pre>'
+ ht+= 'text:<pre>'
+ ht+= cgi.escape(text)
+ ht+= '</pre>'
+ return ht + '</body></html>'
+
+##############################################################################
def _ex(req, method, **params):
try:
return method(**params)
@@ -1971,8 +1998,9 @@
"""
import pywbem
+from cimprovider import CIMProvider
-class %(classname)sProvider:
+class %(classname)sProvider(CIMProvider):
"""Instrument the CIM class %(classname)s
''' % mappings
code+= format_desc(cc)
@@ -2044,10 +2072,8 @@
try:
yield self.get_instance(env, model, cim_class)
except pywbem.CIMError, (num, msg):
- if num in (pywbem.CIM_ERR_NOT_FOUND,
- pywbem.CIM_ERR_ACCESS_DENIED):
- pass # EnumerateInstances shouldn't return these
- else:
+ if num not in (pywbem.CIM_ERR_NOT_FOUND,
+ pywbem.CIM_ERR_ACCESS_DENIED):
raise
'''
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <bni...@us...> - 2007-05-21 22:53:51
|
Revision: 465
http://svn.sourceforge.net/omc/?rev=465&view=rev
Author: bnicholes
Date: 2007-05-21 15:53:49 -0700 (Mon, 21 May 2007)
Log Message:
-----------
Fix the addressing file code so that the addressing file is not opened repeatedly. Submitted by: [Jeff McMenomey <jeff mcmenomey hp com>]
Modified Paths:
--------------
clp/trunk/src/omcclpprogram.cpp
clp/trunk/src/omcclpprogram.h
Modified: clp/trunk/src/omcclpprogram.cpp
===================================================================
--- clp/trunk/src/omcclpprogram.cpp 2007-05-21 21:53:25 UTC (rev 464)
+++ clp/trunk/src/omcclpprogram.cpp 2007-05-21 22:53:49 UTC (rev 465)
@@ -76,6 +76,7 @@
, m_session(CIMNULL)
, m_sessionUFiP()
, m_clpout(clpout)
+ , m_addrref(NULL)
{
}
@@ -132,37 +133,46 @@
*/
OMCCLPConfigurationRef OMCCLPProgram::getAddrFileReference()
{
- if (m_addr_filename.empty())
+ //Let's not open the addressing configuration file a bunch of times. Do it
+ //once and re-use it. Re-opening this file many times can cause BIG performance problems.
+ //It doesn't appear that this should cause problems because each
+ //connection thread gets it's own OMCCLPDaemon object when it is created.
+ if (!m_addrref)
{
- m_addr_filename = getConfigItem(OMCClpdConfigOpts::CIM_ADDRESS_MAP_FILE_opt,
- OMCCLPD_DEFAULT_CIM_ADDRESS_MAP_FILE);
- }
- OMCCLPConfigurationRef addrref(new OMCCLPConfiguration(m_addr_filename));
+ if (m_addr_filename.empty())
+ {
+ m_addr_filename = getConfigItem(OMCClpdConfigOpts::CIM_ADDRESS_MAP_FILE_opt,
+ OMCCLPD_DEFAULT_CIM_ADDRESS_MAP_FILE);
+ }
- if (!addrref->isOpen())
- {
- String msg = String("The addressing file at ") + m_addr_filename +
- " appears to be empty or missing";
- logInfoMessage(msg);
- }
+ OMCCLPConfigurationRef addrref(new OMCCLPConfiguration(m_addr_filename));
- /* Get a list of all of the UFcTs that have a filter. */
- String ufcts = addrref->GetIniSectionsByKey("ufct");
- StringArray ufctSections = ufcts.tokenize(";");
+ if (!addrref->isOpen())
+ {
+ String msg = String("The addressing file at ") + m_addr_filename +
+ " appears to be empty or missing";
+ logInfoMessage(msg);
+ }
- for (int j=0; j<ufctSections.size(); j++)
- {
- String UFcT = addrref->GetIniSetting(ufctSections[j], String("ufct"));
+ /* Get a list of all of the UFcTs that have a filter. */
+ String ufcts = addrref->GetIniSectionsByKey("ufct");
+ StringArray ufctSections = ufcts.tokenize(";");
- addrref->PutIniSetting(String("UFcTs"), UFcT, ufctSections[j]);
- }
+ for (int j=0; j<ufctSections.size(); j++)
+ {
+ String UFcT = addrref->GetIniSetting(ufctSections[j], String("ufct"));
+ addrref->PutIniSetting(String("UFcTs"), UFcT, ufctSections[j]);
+ }
+
#ifdef DEBUG1
- StlIni::INIFile ini = addrref->getDataIni();
- SaveIni(ini, "debugdata.ini");
+ StlIni::INIFile ini = addrref->getDataIni();
+ SaveIni(ini, "debugdata.ini");
#endif
+ m_addrref = addrref;
+ }
- return addrref;
+ return m_addrref;
}
/**
Modified: clp/trunk/src/omcclpprogram.h
===================================================================
--- clp/trunk/src/omcclpprogram.h 2007-05-21 21:53:25 UTC (rev 464)
+++ clp/trunk/src/omcclpprogram.h 2007-05-21 22:53:49 UTC (rev 465)
@@ -203,6 +203,8 @@
CIMObjectPath m_session; // Reference to the session data
String m_sessionUFiP; // User friendly path that corresponds to the session object
std::ostream& m_clpout; // output stream
+ OMCCLPConfigurationRef m_addrref;
+
#ifndef OMCCLPCLIENT
LoggerRef m_logger;
#endif
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <bni...@us...> - 2007-05-21 21:53:23
|
Revision: 464
http://svn.sourceforge.net/omc/?rev=464&view=rev
Author: bnicholes
Date: 2007-05-21 14:53:25 -0700 (Mon, 21 May 2007)
Log Message:
-----------
Add switches to enable or disable the various binaries that are produced during the make. Submitted by: [Jeff McMenomey <jeff mcmenomey hp com>]
Modified Paths:
--------------
clp/trunk/configure.ac
clp/trunk/src/Makefile.am
Modified: clp/trunk/configure.ac
===================================================================
--- clp/trunk/configure.ac 2007-05-21 21:47:29 UTC (rev 463)
+++ clp/trunk/configure.ac 2007-05-21 21:53:25 UTC (rev 464)
@@ -32,6 +32,24 @@
OPT_FLAGS=" -DNDEBUG -O2" # Additional optimization flags.
#######################################################################
+# Allow the user to specify which pieces of OMC to build:
+# omcclp, omcclpc, omcclpd
+AC_ARG_ENABLE([omcclpcomb],
+[ --disable-omcclpcomb Disable the combined client/daemon build (omcclp)],
+[omcclpcomb=false],[omcclpcomb=true])
+AM_CONDITIONAL([OMCCLPCOMB], [test x$omcclpcomb = xtrue])
+
+AC_ARG_ENABLE([omcclpc],
+[ --disable-omcclpc Disable the client build (omcclpc)],
+[ omcclpc=false],[omcclpc=true])
+AM_CONDITIONAL([OMCCLPC], [test x$omcclpc = xtrue])
+
+AC_ARG_ENABLE([omcclpd],
+[ --disable-omcclpd Disable the daemon build (omcclpd)],
+[ omcclpd=false],[omcclpd=true])
+AM_CONDITIONAL([OMCCLPD], [test x$omcclpd = xtrue])
+
+#######################################################################
# Set the debug flag if specified
AC_ARG_ENABLE(debug-mode,
[--enable-debug-mode Enable debugging mode],
Modified: clp/trunk/src/Makefile.am
===================================================================
--- clp/trunk/src/Makefile.am 2007-05-21 21:47:29 UTC (rev 463)
+++ clp/trunk/src/Makefile.am 2007-05-21 21:53:25 UTC (rev 464)
@@ -1,8 +1,19 @@
SUBDIRS = clpaddrgram clpcmdgram
-bin_PROGRAMS = omcclp omcclpc
+OMCBINS =
+
+if OMCCLPCOMB
+OMCBINS += omcclp
+endif
+if OMCCLPC
+OMCBINS += omcclpc
+endif
+
+bin_PROGRAMS = $(OMCBINS)
+if OMCCLPD
sbin_PROGRAMS = omcclpd
+endif
omcclp_SOURCES = \
omcclp.cpp omcclp.h \
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <bni...@us...> - 2007-05-21 21:47:27
|
Revision: 463
http://svn.sourceforge.net/omc/?rev=463&view=rev
Author: bnicholes
Date: 2007-05-21 14:47:29 -0700 (Mon, 21 May 2007)
Log Message:
-----------
CLP fix so that improper targets aren't displayed as a result of the 'show' command, and 'show -l all' doesn't hang in some circumstances. Submitted by [Jeff McMenomey <jeff mcmenomey hp.com>]
Modified Paths:
--------------
clp/trunk/src/omcclpcmdshow.cpp
Modified: clp/trunk/src/omcclpcmdshow.cpp
===================================================================
--- clp/trunk/src/omcclpcmdshow.cpp 2007-05-16 20:26:31 UTC (rev 462)
+++ clp/trunk/src/omcclpcmdshow.cpp 2007-05-21 21:47:29 UTC (rev 463)
@@ -120,6 +120,15 @@
String ufct = stripUFiS(copia[i]->getTargetPathRef()->getTargetUFiT());
String fullTargetUFiP = getUFiPFromCIMObjectPath (clpSession, cop, ufct);
+ // Need to test for the case in which getUFiPFromCIMObjectPath fails
+ // to return a path. If the path is null, there are no more targets for the
+ // entered CIMObjectPath and setTargetsForTargets should return. Failure to test
+ // for a null return results in invalid target paths being displayed by the show
+ // command and infinite looping if show -l all is invoked. This looping is caused
+ // by setTargetsForTargets recursively calling itself due to mistakenly seeing
+ // its target as a parent and then the cycle repeats.
+ if ( fullTargetUFiP.empty() ) return;
+
try
{
/* Enumerate all of the CIMObjectPath objects that are associated
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ba...@us...> - 2007-05-16 20:26:41
|
Revision: 462
http://svn.sourceforge.net/omc/?rev=462&view=rev
Author: bartw
Date: 2007-05-16 13:26:31 -0700 (Wed, 16 May 2007)
Log Message:
-----------
changed formatting of errors. makes stack traces from python providers look pretty
Modified Paths:
--------------
tools/trunk/yawn/yawn.py
Modified: tools/trunk/yawn/yawn.py
===================================================================
--- tools/trunk/yawn/yawn.py 2007-05-15 16:13:24 UTC (rev 461)
+++ tools/trunk/yawn/yawn.py 2007-05-16 20:26:31 UTC (rev 462)
@@ -1245,7 +1245,8 @@
except pywbem.CIMError, arg:
ht = _printHead('Error')
details = _code2string(arg[0])
- ht+= '<p><i>'+details[0]+': '+details[1]+': '+cgi.escape(arg[1])+'</i>'
+ ht+= '<p><i>'+details[0]+': ' + details[1]+'</i>'
+ ht+= '<pre>'+cgi.escape(arg[1])+'</pre>'
ht+= '<hr>'
if req.conn.debug:
if req.conn.last_request is not None:
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ba...@us...> - 2007-05-15 16:13:25
|
Revision: 461
http://svn.sourceforge.net/omc/?rev=461&view=rev
Author: bartw
Date: 2007-05-15 09:13:24 -0700 (Tue, 15 May 2007)
Log Message:
-----------
bug fixes in bool handling
Modified Paths:
--------------
tools/trunk/yawn/yawn.py
Modified: tools/trunk/yawn/yawn.py
===================================================================
--- tools/trunk/yawn/yawn.py 2007-05-14 17:37:08 UTC (rev 460)
+++ tools/trunk/yawn/yawn.py 2007-05-15 16:13:24 UTC (rev 461)
@@ -57,8 +57,9 @@
elif isinstance(x,list):
rval = '{'
if x:
- for item in x:
- if item is not x[0]:
+ for i in range(0, len(x)):
+ item = x[i]
+ if i > 0:
rval+= ', '
strItem = _val2str(item)
if type(item) in types.StringTypes:
@@ -908,8 +909,8 @@
else:
if oldVal is not None and propIsKey:
ht+= _val2str(oldVal)
- elif prop.type == 'boolean':
- ht+= '<select name="'+fPropName+'"'
+ elif prop.type == 'boolean' and not prop.is_array:
+ ht+= '<select name="'+fPropName+'">'
ht+= '<option value='""'>'
ht+= '<option value="True"'
if oldVal is not None and oldVal:
@@ -1186,7 +1187,7 @@
ht+= '</select>'
elif param.type == 'boolean':
- ht+= '<select name="'+parmName+'"'
+ ht+= '<select name="'+parmName+'">'
ht+= '<option value='""'>'
ht+= '<option value="True">True'
ht+= '<option value="False">False'
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ba...@us...> - 2007-05-14 17:37:06
|
Revision: 460
http://svn.sourceforge.net/omc/?rev=460&view=rev
Author: bartw
Date: 2007-05-14 10:37:08 -0700 (Mon, 14 May 2007)
Log Message:
-----------
added link to namespace list
Modified Paths:
--------------
tools/trunk/yawn/yawn.py
Modified: tools/trunk/yawn/yawn.py
===================================================================
--- tools/trunk/yawn/yawn.py 2007-05-14 16:41:32 UTC (rev 459)
+++ tools/trunk/yawn/yawn.py 2007-05-14 17:37:08 UTC (rev 460)
@@ -1551,7 +1551,7 @@
classNames = _ex(req, conn.EnumerateClassNames,
DeepInheritance = mode=='flat')
- ht = _printHead('Classes in '+ns,'Classes in '+url+'/'+ns, req)
+ ht = _printHead('Classes in '+ns,'Classes in '+url+'/'+ns, req, {'url':url})
urlargs = {'ns': ns, 'url': url}
ecn_urlargs = urlargs.copy()
ecn_urlargs['mode'] = mode
@@ -1774,6 +1774,11 @@
ht+= '<td valign=top nowrap align=right><font size=-1><i>'
ht+= _makeHref(req, 'EnumClassNames', lurlargs, lurlargs['ns'])
ht+= ' </i></td>'
+ if urlargs and 'url' in urlargs:
+ ht+= '<td valign=top nowrap align=right><font size=-1><i>'
+ ht+= _makeHref(req, 'EnumNamespaces', {'url':urlargs['url']},
+ 'Namespaces')
+ ht+= ' </i></td>'
ht+= '<td valign=top nowrap align=right><font size=-1><i>'
ht+= '<a href="'+_baseScript(req)+'/Logout">Logout >></a></i>'
ht+= '</td></tr></table>'
@@ -1798,15 +1803,8 @@
return __file__[drlen:-3]
##############################################################################
-def Login(req, scheme, host, port, ns):
- url = scheme + '://'+host
- if not ((scheme == 'https' and port == '5989') or (scheme == 'http' and port == '5988')):
- url += ':'+port
- if ns:
- EnumClassNames(req, url, ns)
- return ' '
-
- conn = _frontMatter(req, url, ns)
+def EnumNamespaces(req, url):
+ conn = _frontMatter(req, url, '')
nsinsts = []
try:
for nsclass in ['CIM_Namespace', '__Namespace']:
@@ -1860,6 +1858,17 @@
return ht + '</body></html>'
##############################################################################
+def Login(req, scheme, host, port, ns):
+ url = scheme + '://'+host
+ if not ((scheme == 'https' and port == '5989') or (scheme == 'http' and port == '5988')):
+ url += ':'+port
+ if ns:
+ return EnumClassNames(req, url, ns)
+ return EnumNamespaces(req, url)
+
+
+
+##############################################################################
def Logout(req):
req.add_common_vars()
req.content_type = "Text/HTML"
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ba...@us...> - 2007-05-14 16:41:32
|
Revision: 459
http://svn.sourceforge.net/omc/?rev=459&view=rev
Author: bartw
Date: 2007-05-14 09:41:32 -0700 (Mon, 14 May 2007)
Log Message:
-----------
need to escape the generated code
Modified Paths:
--------------
tools/trunk/yawn/yawn.py
Modified: tools/trunk/yawn/yawn.py
===================================================================
--- tools/trunk/yawn/yawn.py 2007-05-13 02:12:50 UTC (rev 458)
+++ tools/trunk/yawn/yawn.py 2007-05-14 16:41:32 UTC (rev 459)
@@ -2211,11 +2211,11 @@
ht = _printHead(title, req)
ht+= '<font size=+1><b>%s</b></font>' % title
ht+= '<table bgcolor="#f9f9f9" cellspacing=0 cellpadding=10 border=1>'
- ht+= '<tr><td><pre>'+code+'</pre>'
+ ht+= '<tr><td><pre>'+cgi.escape(code)+'</pre>'
ht+= '</td></tr></table>'
ht+= '<font size=+1><b>Provider Registration MOF</b></font>'
ht+= '<table bgcolor="#f9f9f9" cellspacing=0 cellpadding=10 border=1>'
- ht+= '<tr><td><pre>'+mof+'</pre>'
+ ht+= '<tr><td><pre>'+cgi.escape(mof)+'</pre>'
ht+= '</td></tr></table>'
return ht
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ba...@us...> - 2007-05-13 02:12:48
|
Revision: 458
http://svn.sourceforge.net/omc/?rev=458&view=rev
Author: bartw
Date: 2007-05-12 19:12:50 -0700 (Sat, 12 May 2007)
Log Message:
-----------
provider codegen fixes
Modified Paths:
--------------
tools/trunk/yawn/yawn.py
Modified: tools/trunk/yawn/yawn.py
===================================================================
--- tools/trunk/yawn/yawn.py 2007-05-12 00:26:15 UTC (rev 457)
+++ tools/trunk/yawn/yawn.py 2007-05-13 02:12:50 UTC (rev 458)
@@ -1274,7 +1274,7 @@
ht+= ' or '+_makeHref(req, 'EnumInstances', instUrlArgs, 'Instances')
ht+= ' or '+_makeHref(req, 'AssociatedClasses', instUrlArgs, 'Associated Classes')
ht+= ' of this class. '+_makeHref(req,
- 'ProviderTemplate', instUrlArgs, 'Provider Template')+'</div>'
+ 'Provider', instUrlArgs, 'Python Provider')+'</div>'
ht+= '<table border="1" cellpadding="2">'
if klass.qualifiers.has_key('aggregation'):
titleBGColor = "green"
@@ -1769,7 +1769,7 @@
if heading is not None:
ht+= '<h1>'+heading+'</h1>'
ht+= '</td>'
- if urlargs and 'ns' in urlargs.keys() and 'url' in urlargs.keys():
+ if urlargs and 'ns' in urlargs and 'url' in urlargs:
lurlargs = {'ns':urlargs['ns'], 'url':urlargs['url']}
ht+= '<td valign=top nowrap align=right><font size=-1><i>'
ht+= _makeHref(req, 'EnumClassNames', lurlargs, lurlargs['ns'])
@@ -1951,7 +1951,7 @@
#################
mappings = {'classname':cc.classname,
- }
+ 'classname_l':cc.classname.lower()}
isAssoc = 'association' in cc.qualifiers
code = '''"""Python Provider for %(classname)s
@@ -2175,8 +2175,8 @@
## end of class %(classname)sProvider
-_prov = %(classname)sProvider() # initialize provider
-py_providers = {'%(classname)s: _prov} # register provider
+_%(classname_l)s_prov = %(classname)sProvider() # initialize provider
+py_providers = {'%(classname)s': _%(classname_l)s_prov} # register provider
''' % mappings
ptypes = ['1', 'Instance']
@@ -2186,29 +2186,38 @@
if cc.methods:
ptypes[0]+= ',6'
ptypes[1]+= ', Method'
- code+='''
-"""// Provider registration MOF for %(classname)s
+ mof ='''
+// Provider registration for %(classname)s
instance of OpenWBEM_PyProviderRegistration
{
InstanceID = "<org:product:unique_id>"; // TODO
NamespaceNames = {"root/cimv2"};
ClassName = "%(classname)s";
ProviderTypes = {%(ptypeNums)s}; // %(ptypeStrs)s
- ModulePath = "/some/path/%(classname)sProvider.py";
+ ModulePath = "/some/path/%(classname)sProvider.py"; // TODO
};
-"""
''' % {'classname': cc.classname,
'ptypeNums': ptypes[0],
'ptypeStrs': ptypes[1]}
- return code
+ return code, mof
-def ProviderTemplate(req, url, ns, className):
+def Provider(req, url, ns, className):
conn = _frontMatter(req, url, ns)
- req.content_type = 'text/plain'
klass = _ex(req, conn.GetClass, ClassName = className, LocalOnly = "false",
IncludeClassOrigin = "true")
- return _providerTemplate(klass)
+ code, mof = _providerTemplate(klass)
+ title = 'Python Provider for %s' % className
+ ht = _printHead(title, req)
+ ht+= '<font size=+1><b>%s</b></font>' % title
+ ht+= '<table bgcolor="#f9f9f9" cellspacing=0 cellpadding=10 border=1>'
+ ht+= '<tr><td><pre>'+code+'</pre>'
+ ht+= '</td></tr></table>'
+ ht+= '<font size=+1><b>Provider Registration MOF</b></font>'
+ ht+= '<table bgcolor="#f9f9f9" cellspacing=0 cellpadding=10 border=1>'
+ ht+= '<tr><td><pre>'+mof+'</pre>'
+ ht+= '</td></tr></table>'
+ return ht
##############################################################################
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|