home *** CD-ROM | disk | FTP | other *** search
/ Chip 2004 July / CMCD0704.ISO / Software / Shareware / Comunicatii / jyte / jyte.exe / win32pdhquery.py < prev    next >
Text File  |  2002-01-08  |  21KB  |  509 lines

  1. '''
  2. Performance Data Helper (PDH) Query Classes
  3.  
  4. Wrapper classes for end-users and high-level access to the PDH query
  5. mechanisms.  PDH is a win32-specific mechanism for accessing the
  6. performance data made available by the system.  The Python for Windows
  7. PDH module does not implement the "Registry" interface, implementing
  8. the more straightforward Query-based mechanism.
  9.  
  10. The basic idea of a PDH Query is an object which can query the system
  11. about the status of any number of "counters."  The counters are paths
  12. to a particular piece of performance data.  For instance, the path 
  13. '\\Memory\\Available Bytes' describes just about exactly what it says
  14. it does, the amount of free memory on the default computer expressed 
  15. in Bytes.  These paths can be considerably more complex than this, 
  16. but part of the point of this wrapper module is to hide that
  17. complexity from the end-user/programmer.
  18.  
  19. EXAMPLE: A more complex Path
  20.     '\\\\RAISTLIN\\PhysicalDisk(_Total)\\Avg. Disk Bytes/Read'
  21.     Raistlin --> Computer Name
  22.     PhysicalDisk --> Object Name
  23.     _Total --> The particular Instance (in this case, all instances, i.e. all drives)
  24.     Avg. Disk Bytes/Read --> The piece of data being monitored.
  25.  
  26. EXAMPLE: Collecting Data with a Query
  27.     As an example, the following code implements a logger which allows the
  28.     user to choose what counters they would like to log, and logs those
  29.     counters for 30 seconds, at two-second intervals.
  30.     
  31.     query = Query()
  32.     query.addcounterbybrowsing()
  33.     query.collectdatafor(30,2)
  34.     
  35.     The data is now stored in a list of lists as:
  36.     query.curresults
  37.     
  38.     The counters(paths) which were used to collect the data are:
  39.     query.curpaths
  40.     
  41.     You can use the win32pdh.ParseCounterPath(path) utility function
  42.     to turn the paths into more easily read values for your task, or
  43.     write the data to a file, or do whatever you want with it.
  44.  
  45. OTHER NOTABLE METHODS:
  46.     query.collectdatawhile(period) # start a logging thread for collecting data
  47.     query.collectdatawhile_stop() # signal the logging thread to stop logging
  48.     query.collectdata() # run the query only once
  49.     query.addperfcounter(object, counter, machine=None) # add a standard performance counter
  50.     query.addinstcounter(object, counter,machine=None,objtype = 'Process',volatile=1,format = win32pdh.PDH_FMT_LONG) # add a possibly volatile counter
  51.  
  52. ### Known bugs and limitations ###
  53. Due to a problem with threading under the PythonWin interpreter, there
  54. will be no data logged if the PythonWin window is not the foreground
  55. application.  Workaround: scripts using threading should be run in the
  56. python.exe interpreter.
  57.  
  58. The volatile-counter handlers are possibly buggy, they haven't been
  59. tested to any extent.  The wrapper Query makes it safe to pass invalid
  60. paths (a -1 will be returned, or the Query will be totally ignored,
  61. depending on the missing element), so you should be able to work around
  62. the error by including all possible paths and filtering out the -1's.
  63.  
  64. There is no way I know of to stop a thread which is currently sleeping,
  65. so you have to wait until the thread in collectdatawhile is activated
  66. again.  This might become a problem in situations where the collection
  67. period is multiple minutes (or hours, or whatever).
  68.  
  69. Should make the win32pdh.ParseCounter function available to the Query
  70. classes as a method or something similar, so that it can be accessed
  71. by programmes that have just picked up an instance from somewhere.
  72.  
  73. Should explicitly mention where QueryErrors can be raised, and create a
  74. full test set to see if there are any uncaught win32api.error's still
  75. hanging around.
  76.  
  77. When using the python.exe interpreter, the addcounterbybrowsing-
  78. generated browser window is often hidden behind other windows.  No known
  79. workaround other than Alt-tabing to reach the browser window.
  80.  
  81. ### Other References ###
  82. The win32pdhutil module (which should be in the %pythonroot%/win32/lib 
  83. directory) provides quick-and-dirty utilities for one-off access to
  84. variables from the PDH.  Almost everything in that module can be done
  85. with a Query object, but it provides task-oriented functions for a
  86. number of common one-off tasks.
  87.  
  88. If you can access the MS Developers Network Library, you can find
  89. information about the PDH API as MS describes it.  In general the
  90. Python version of the API is just a wrapper around the Query-based
  91. version of this API (as far as I can see), so you can learn what
  92. you need to from there.  From what I understand, the MSDN Online 
  93. resources are available for the price of signing up for them.  I can't
  94. guarantee how long that's supposed to last. (Or anything for that
  95. matter).
  96. http://premium.microsoft.com/isapi/devonly/prodinfo/msdnprod/msdnlib.idc?theURL=/msdn/library/sdkdoc/perfdata_4982.htm
  97.  
  98. The eventual plan is for my (Mike Fletcher's) Starship account to include
  99. a section on NT Administration, and the Query is the first project
  100. in this plan.  There should be an article describing the creation of
  101. a simple logger there, but the example above is 90% of the work of
  102. that project, so don't sweat it if you don't find anything there.
  103. (currently the account hasn't been set up).
  104. http://starship.skyport.net/crew/mcfletch/
  105.  
  106. If you need to contact me immediately, (why I can't imagine), you can
  107. email me at mcfletch@golden.net, or just post your question to the
  108. Python newsgroup with a catchy subject line.
  109. news:comp.lang.python
  110.  
  111. ### Other Stuff ###
  112. The Query classes are by Mike Fletcher, with the working code
  113. being corruptions of Mark Hammonds win32pdhutil module.
  114.  
  115. Use at your own risk, no warranties, no guarantees, no assurances,
  116. if you use it, you accept the risk of using it, etceteras.
  117.  
  118. '''
  119. # Feb 12, 98 - MH added "rawaddcounter" so caller can get exception details.
  120.  
  121. import win32pdh, win32api,time, thread,copy
  122.  
  123. class BaseQuery:
  124.     '''
  125.     Provides wrapped access to the Performance Data Helper query
  126.     objects, generally you should use the child class Query
  127.     unless you have need of doing weird things :)
  128.  
  129.     This class supports two major working paradigms.  In the first,
  130.     you open the query, and run it as many times as you need, closing
  131.     the query when you're done with it.  This is suitable for static
  132.     queries (ones where processes being monitored don't disappear).
  133.  
  134.     In the second, you allow the query to be opened each time and
  135.     closed afterward.  This causes the base query object to be
  136.     destroyed after each call.  Suitable for dynamic queries (ones
  137.     which watch processes which might be closed while watching.)
  138.     '''
  139.     def __init__(self,paths=None):
  140.         '''
  141.         The PDH Query object is initialised with a single, optional
  142.         list argument, that must be properly formatted PDH Counter
  143.         paths.  Generally this list will only be provided by the class
  144.         when it is being unpickled (removed from storage).  Normal
  145.         use is to call the class with no arguments and use the various
  146.         addcounter functions (particularly, for end user's, the use of
  147.         addcounterbybrowsing is the most common approach)  You might
  148.         want to provide the list directly if you want to hard-code the
  149.         elements with which your query deals (and thereby avoid the
  150.         overhead of unpickling the class).
  151.         '''
  152.         self.counters = []
  153.         if paths:
  154.             self.paths = paths
  155.         else:
  156.             self.paths = []
  157.         self._base = None
  158.         self.active = 0
  159.         self.curpaths = []
  160.     def addcounterbybrowsing(self, flags = win32pdh.PERF_DETAIL_WIZARD, windowtitle="Python Browser"):
  161.         '''
  162.         Adds possibly multiple paths to the paths attribute of the query,
  163.         does this by calling the standard counter browsing dialogue.  Within
  164.         this dialogue, find the counter you want to log, and click: Add,
  165.         repeat for every path you want to log, then click on close.  The
  166.         paths are appended to the non-volatile paths list for this class,
  167.         subclasses may create a function which parses the paths and decides
  168.         (via heuristics) whether to add the path to the volatile or non-volatile
  169.         path list.
  170.         e.g.:
  171.             query.addcounter()
  172.         '''
  173.         win32pdh.BrowseCounters(None,0, self.paths.append, flags, windowtitle)
  174.     def rawaddcounter(self,object, counter, instance = None, inum=-1, machine=None):
  175.         '''
  176.         Adds a single counter path, without catching any exceptions.
  177.         
  178.         See addcounter for details.
  179.         '''
  180.         path = win32pdh.MakeCounterPath( (machine,object,instance, None, inum,counter) )
  181.         self.paths.append(path)
  182.     
  183.     def addcounter(self,object, counter, instance = None, inum=-1, machine=None):
  184.         '''
  185.         Adds a single counter path to the paths attribute.  Normally
  186.         this will be called by a child class' speciality functions,
  187.         rather than being called directly by the user. (Though it isn't
  188.         hard to call manually, since almost everything is given a default)
  189.         This method is only functional when the query is closed (or hasn't
  190.         yet been opened).  This is to prevent conflict in multi-threaded
  191.         query applications).
  192.         e.g.:
  193.             query.addcounter('Memory','Available Bytes')
  194.         '''
  195.         if not self.active:
  196.             try:
  197.                 self.rawaddcounter(object, counter, instance, inum, machine)
  198.                 return 0
  199.             except win32api.error:
  200.                 return -1
  201.         else:
  202.             return -1
  203.         
  204.     def open(self):
  205.         '''
  206.         Build the base query object for this wrapper,
  207.         then add all of the counters required for the query.
  208.         Raise a QueryError if we can't complete the functions.
  209.         If we are already open, then do nothing.
  210.         '''
  211.         if not self.active: # to prevent having multiple open queries
  212.             # curpaths are made accessible here because of the possibility of volatile paths
  213.             # which may be dynamically altered by subclasses.
  214.             self.curpaths = copy.copy(self.paths)
  215.             try:
  216.                 base = win32pdh.OpenQuery()
  217.                 for path in self.paths:
  218.                     try:
  219.                         self.counters.append(win32pdh.AddCounter(base, path))
  220.                     except win32api.error: # we passed a bad path
  221.                         self.counters.append(0)
  222.                         pass
  223.                 self._base = base
  224.                 self.active = 1
  225.                 return 0 # open succeeded
  226.             except: # if we encounter any errors, kill the Query
  227.                 try:
  228.                     self.killbase(base)
  229.                 except NameError: # failed in creating query
  230.                     pass
  231.                 self.active = 0
  232.                 self.curpaths = []
  233.                 raise QueryError(self)
  234.         return 1 # already open
  235.         
  236.     def killbase(self,base=None):
  237.         '''
  238.         ### This is not a public method
  239.         Mission critical function to kill the win32pdh objects held
  240.         by this object.  User's should generally use the close method
  241.         instead of this method, in case a sub-class has overridden
  242.         close to provide some special functionality.
  243.         '''
  244.         # Kill Pythonic references to the objects in this object's namespace
  245.         self._base = None
  246.         counters = self.counters
  247.         self.counters = []
  248.         # we don't kill the curpaths for convenience, this allows the
  249.         # user to close a query and still access the last paths
  250.         self.active = 0
  251.         # Now call the delete functions on all of the objects
  252.         try:
  253.             map(win32pdh.RemoveCounter,counters)
  254.         except:
  255.             pass
  256.         try:
  257.             win32pdh.CloseQuery(base)
  258.         except:
  259.             pass
  260.         del(counters)
  261.         del(base)
  262.     def close(self):
  263.         '''
  264.         Makes certain that the underlying query object has been closed,
  265.         and that all counters have been removed from it.  This is
  266.         important for reference counting.
  267.         You should only need to call close if you have previously called
  268.         open.  The collectdata methods all can handle opening and
  269.         closing the query.  Calling close multiple times is acceptable.
  270.         '''
  271.         try:
  272.             self.killbase(self._base)
  273.         except AttributeError:
  274.             self.killbase()
  275.     __del__ = close
  276.     def collectdata(self,format = win32pdh.PDH_FMT_LONG):
  277.         '''
  278.         Returns the formatted current values for the Query
  279.         '''
  280.         if self._base: # we are currently open, don't change this
  281.             return self.collectdataslave(format)
  282.         else: # need to open and then close the _base, should be used by one-offs and elements tracking application instances
  283.             self.open() # will raise QueryError if couldn't open the query
  284.             temp = self.collectdataslave(format)
  285.             self.close() # will always close
  286.             return temp
  287.     def collectdataslave(self,format = win32pdh.PDH_FMT_LONG):
  288.         '''
  289.         ### Not a public method
  290.         Called only when the Query is known to be open, runs over
  291.         the whole set of counters, appending results to the temp,
  292.         returns the values as a list.
  293.         '''
  294.         try:
  295.             win32pdh.CollectQueryData(self._base)
  296.             temp = []
  297.             for counter in self.counters:
  298.                 ok = 0
  299.                 try:
  300.                     if counter:
  301.                         temp.append(win32pdh.GetFormattedCounterValue(counter, format)[1])
  302.                         ok = 1
  303.                 except win32api.error:
  304.                     pass
  305.                 if not ok:
  306.                     temp.append(-1) # a better way to signal failure???
  307.             return temp
  308.         except win32api.error: # will happen if, for instance, no counters are part of the query and we attempt to collect data for it.
  309.             return [-1] * len(self.counters)
  310.     # pickle functions
  311.     def __getinitargs__(self):
  312.         '''
  313.         ### Not a public method
  314.         '''
  315.         return (self.paths,)
  316.         
  317. class Query(BaseQuery):
  318.     '''
  319.     Performance Data Helper(PDH) Query object:
  320.     
  321.     Provides a wrapper around the native PDH query object which
  322.     allows for query reuse, query storage, and general maintenance
  323.     functions (adding counter paths in various ways being the most
  324.     obvious ones).
  325.     '''
  326.     def __init__(self,*args,**namedargs):
  327.         '''
  328.         The PDH Query object is initialised with a single, optional
  329.         list argument, that must be properly formatted PDH Counter
  330.         paths.  Generally this list will only be provided by the class
  331.         when it is being unpickled (removed from storage).  Normal
  332.         use is to call the class with no arguments and use the various
  333.         addcounter functions (particularly, for end user's, the use of
  334.         addcounterbybrowsing is the most common approach)  You might
  335.         want to provide the list directly if you want to hard-code the
  336.         elements with which your query deals (and thereby avoid the
  337.         overhead of unpickling the class).
  338.         '''
  339.         self.volatilecounters = []
  340.         apply(BaseQuery.__init__, (self,)+args, namedargs)
  341.     def addperfcounter(self, object, counter, machine=None):
  342.         '''
  343.         A "Performance Counter" is a stable, known, common counter,
  344.         such as Memory, or Processor.  The use of addperfcounter by 
  345.         end-users is deprecated, since the use of 
  346.         addcounterbybrowsing is considerably more flexible and general.
  347.         It is provided here to allow the easy development of scripts
  348.         which need to access variables so common we know them by name
  349.         (such as Memory|Available Bytes), and to provide symmetry with
  350.         the add inst counter method.
  351.         usage:
  352.             query.addperfcounter('Memory', 'Available Bytes')
  353.         It is just as easy to access addcounter directly, the following
  354.         has an identicle effect.
  355.             query.addcounter('Memory', 'Available Bytes')
  356.         '''
  357.         BaseQuery.addcounter(self, object=object, counter=counter, machine=machine)
  358.     def addinstcounter(self, object, counter,machine=None,objtype = 'Process',volatile=1,format = win32pdh.PDH_FMT_LONG):
  359.         '''
  360.         The purpose of using an instcounter is to track particular
  361.         instances of a counter object (e.g. a single processor, a single
  362.         running copy of a process).  For instance, to track all python.exe
  363.         instances, you would need merely to ask:
  364.             query.addinstcounter('python','Virtual Bytes')
  365.         You can find the names of the objects and their available counters 
  366.         by doing an addcounterbybrowsing() call on a query object (or by
  367.         looking in performance monitor's add dialog.)
  368.         
  369.         Beyond merely rearranging the call arguments to make more sense,
  370.         if the volatile flag is true, the instcounters also recalculate
  371.         the paths of the available instances on every call to open the
  372.         query.
  373.         '''
  374.         if volatile:
  375.             self.volatilecounters.append((object,counter,machine,objtype,format))
  376.         else:
  377.             self.paths[len(self.paths):] = self.getinstpaths(object,counter,machine,objtype,format)
  378.                 
  379.     def getinstpaths(self,object,counter,machine=None,objtype='Process',format = win32pdh.PDH_FMT_LONG):
  380.         '''
  381.         ### Not an end-user function
  382.         Calculate the paths for an instance object. Should alter
  383.         to allow processing for lists of object-counter pairs.
  384.         '''
  385.         items, instances = win32pdh.EnumObjectItems(None,None,objtype, -1)
  386.         # find out how many instances of this element we have...
  387.         instances.sort()
  388.         try:
  389.             cur = instances.index(object)
  390.         except ValueError:
  391.             return [] # no instances of this object
  392.         temp = [object]
  393.         try:
  394.             while instances[cur+1] == object:
  395.                 temp.append(object)
  396.                 cur = cur+1
  397.         except IndexError: # if we went over the end
  398.             pass
  399.         paths = []
  400.         for ind in range(len(temp)):
  401.             # can this raise an error?
  402.             paths.append(win32pdh.MakeCounterPath( (machine,'Process',object,None,ind,counter) ) )
  403.         return paths # should also return the number of elements for naming purposes
  404.  
  405.     def open(self,*args,**namedargs):
  406.         '''
  407.         Explicitly open a query:
  408.         When you are needing to make multiple calls to the same query,
  409.         it is most efficient to open the query, run all of the calls,
  410.         then close the query, instead of having the collectdata method
  411.         automatically open and close the query each time it runs.
  412.         There are currently no arguments to open.
  413.         '''
  414.         # do all the normal opening stuff, self._base is now the query object
  415.         apply(BaseQuery.open,(self,)+args, namedargs)
  416.         # should rewrite getinstpaths to take a single tuple
  417.         paths = []
  418.         for tup in self.volatilecounters:
  419.             paths[len(paths):] = apply(self.getinstpaths, tup)
  420.         for path in paths:
  421.             try:
  422.                 self.counters.append(win32pdh.AddCounter(self._base, path))
  423.                 self.curpaths.append(path) # if we fail on the line above, this path won't be in the table or the counters
  424.             except win32api.error:
  425.                 pass # again, what to do with a malformed path???
  426.     def collectdatafor(self, totalperiod, period=1):
  427.         '''
  428.         Non-threaded collection of performance data:
  429.         This method allows you to specify the total period for which you would
  430.         like to run the Query, and the time interval between individual
  431.         runs.  The collected data is stored in query.curresults at the
  432.         _end_ of the run.  The pathnames for the query are stored in
  433.         query.curpaths.
  434.         e.g.:
  435.             query.collectdatafor(30,2)
  436.         Will collect data for 30seconds at 2 second intervals
  437.         '''
  438.         tempresults = []
  439.         try:
  440.             self.open()
  441.             for ind in xrange(totalperiod/period):
  442.                 tempresults.append(self.collectdata())
  443.                 time.sleep(period)
  444.             self.curresults = tempresults
  445.         finally:
  446.             self.close()
  447.     def collectdatawhile(self, period=1):
  448.         '''
  449.         Threaded collection of performance data:
  450.         This method sets up a simple semaphor system for signalling 
  451.         when you would like to start and stop a threaded data collection
  452.         method.  The collection runs every period seconds until the
  453.         semaphor attribute is set to a non-true value (which normally
  454.         should be done by calling query.collectdatawhile_stop() .)
  455.         e.g.:
  456.             query.collectdatawhile(2)
  457.             # starts the query running, returns control to the caller immediately
  458.             # is collecting data every two seconds.
  459.             # do whatever you want to do while the thread runs, then call:
  460.             query.collectdatawhile_stop()
  461.             # when you want to deal with the data.  It is generally a good idea
  462.             # to sleep for period seconds yourself, since the query will not copy
  463.             # the required data until the next iteration:
  464.             time.sleep(2)
  465.             # now you can access the data from the attributes of the query
  466.             query.curresults
  467.             query.curpaths
  468.         '''
  469.         self.collectdatawhile_active = 1
  470.         thread.start_new_thread(self.collectdatawhile_slave,(period,))
  471.     def collectdatawhile_stop(self):
  472.         '''
  473.         Signals the collectdatawhile slave thread to stop collecting data
  474.         on the next logging iteration.
  475.         '''
  476.         self.collectdatawhile_active = 0
  477.     def collectdatawhile_slave(self, period):
  478.         '''
  479.         ### Not a public function
  480.         Does the threaded work of collecting the data and storing it
  481.         in an attribute of the class.
  482.         '''
  483.         tempresults = []
  484.         try:
  485.             self.open() # also sets active, so can't be changed.
  486.             while self.collectdatawhile_active:
  487.                 tempresults.append(self.collectdata())
  488.                 time.sleep(period)
  489.             self.curresults = tempresults
  490.         finally:
  491.             self.close()
  492.         
  493.     # pickle functions
  494.     def __getinitargs__(self):
  495.         return (self.paths,)
  496.     def __getstate__(self):
  497.         return self.volatilecounters
  498.     def __setstate__(self, volatilecounters):
  499.         self.volatilecounters = volatilecounters
  500.  
  501.  
  502. class QueryError:
  503.     def __init__(self, query):
  504.         self.query = query
  505.     def __repr__(self):
  506.         return '<Query Error in %s>'%repr(self.query)
  507.     __str__ = __repr__
  508.     
  509.