win32pdhquery.py 20 KB

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