]> git.decadent.org.uk Git - nfs-utils.git/blob - tools/nfs-iostat/nfs-iostat.py
794d4a82b3cbb6d9fa61660e3abf6adb4cd7cc0e
[nfs-utils.git] / tools / nfs-iostat / nfs-iostat.py
1 #!/usr/bin/env python
2 # -*- python-mode -*-
3 """Emulate iostat for NFS mount points using /proc/self/mountstats
4 """
5
6 __copyright__ = """
7 Copyright (C) 2005, Chuck Lever <cel@netapp.com>
8
9 This program is free software; you can redistribute it and/or modify
10 it under the terms of the GNU General Public License version 2 as
11 published by the Free Software Foundation.
12
13 This program is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 GNU General Public License for more details.
17
18 You should have received a copy of the GNU General Public License
19 along with this program; if not, write to the Free Software
20 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
21 """
22
23 import sys, os, time
24
25 Iostats_version = '0.2'
26
27 def difference(x, y):
28     """Used for a map() function
29     """
30     return x - y
31
32 NfsEventCounters = [
33     'inoderevalidates',
34     'dentryrevalidates',
35     'datainvalidates',
36     'attrinvalidates',
37     'vfsopen',
38     'vfslookup',
39     'vfspermission',
40     'vfsupdatepage',
41     'vfsreadpage',
42     'vfsreadpages',
43     'vfswritepage',
44     'vfswritepages',
45     'vfsreaddir',
46     'vfssetattr',
47     'vfsflush',
48     'vfsfsync',
49     'vfslock',
50     'vfsrelease',
51     'congestionwait',
52     'setattrtrunc',
53     'extendwrite',
54     'sillyrenames',
55     'shortreads',
56     'shortwrites',
57     'delay'
58 ]
59
60 NfsByteCounters = [
61     'normalreadbytes',
62     'normalwritebytes',
63     'directreadbytes',
64     'directwritebytes',
65     'serverreadbytes',
66     'serverwritebytes',
67     'readpages',
68     'writepages'
69 ]
70
71 class DeviceData:
72     """DeviceData objects provide methods for parsing and displaying
73     data for a single mount grabbed from /proc/self/mountstats
74     """
75     def __init__(self):
76         self.__nfs_data = dict()
77         self.__rpc_data = dict()
78         self.__rpc_data['ops'] = []
79
80     def __parse_nfs_line(self, words):
81         if words[0] == 'device':
82             self.__nfs_data['export'] = words[1]
83             self.__nfs_data['mountpoint'] = words[4]
84             self.__nfs_data['fstype'] = words[7]
85             if words[7] == 'nfs':
86                 self.__nfs_data['statvers'] = words[8]
87         elif words[0] == 'age:':
88             self.__nfs_data['age'] = long(words[1])
89         elif words[0] == 'opts:':
90             self.__nfs_data['mountoptions'] = ''.join(words[1:]).split(',')
91         elif words[0] == 'caps:':
92             self.__nfs_data['servercapabilities'] = ''.join(words[1:]).split(',')
93         elif words[0] == 'nfsv4:':
94             self.__nfs_data['nfsv4flags'] = ''.join(words[1:]).split(',')
95         elif words[0] == 'sec:':
96             keys = ''.join(words[1:]).split(',')
97             self.__nfs_data['flavor'] = int(keys[0].split('=')[1])
98             self.__nfs_data['pseudoflavor'] = 0
99             if self.__nfs_data['flavor'] == 6:
100                 self.__nfs_data['pseudoflavor'] = int(keys[1].split('=')[1])
101         elif words[0] == 'events:':
102             i = 1
103             for key in NfsEventCounters:
104                 self.__nfs_data[key] = int(words[i])
105                 i += 1
106         elif words[0] == 'bytes:':
107             i = 1
108             for key in NfsByteCounters:
109                 self.__nfs_data[key] = long(words[i])
110                 i += 1
111
112     def __parse_rpc_line(self, words):
113         if words[0] == 'RPC':
114             self.__rpc_data['statsvers'] = float(words[3])
115             self.__rpc_data['programversion'] = words[5]
116         elif words[0] == 'xprt:':
117             self.__rpc_data['protocol'] = words[1]
118             if words[1] == 'udp':
119                 self.__rpc_data['port'] = int(words[2])
120                 self.__rpc_data['bind_count'] = int(words[3])
121                 self.__rpc_data['rpcsends'] = int(words[4])
122                 self.__rpc_data['rpcreceives'] = int(words[5])
123                 self.__rpc_data['badxids'] = int(words[6])
124                 self.__rpc_data['inflightsends'] = long(words[7])
125                 self.__rpc_data['backlogutil'] = long(words[8])
126             elif words[1] == 'tcp':
127                 self.__rpc_data['port'] = words[2]
128                 self.__rpc_data['bind_count'] = int(words[3])
129                 self.__rpc_data['connect_count'] = int(words[4])
130                 self.__rpc_data['connect_time'] = int(words[5])
131                 self.__rpc_data['idle_time'] = int(words[6])
132                 self.__rpc_data['rpcsends'] = int(words[7])
133                 self.__rpc_data['rpcreceives'] = int(words[8])
134                 self.__rpc_data['badxids'] = int(words[9])
135                 self.__rpc_data['inflightsends'] = long(words[10])
136                 self.__rpc_data['backlogutil'] = long(words[11])
137         elif words[0] == 'per-op':
138             self.__rpc_data['per-op'] = words
139         else:
140             op = words[0][:-1]
141             self.__rpc_data['ops'] += [op]
142             self.__rpc_data[op] = [long(word) for word in words[1:]]
143
144     def parse_stats(self, lines):
145         """Turn a list of lines from a mount stat file into a 
146         dictionary full of stats, keyed by name
147         """
148         found = False
149         for line in lines:
150             words = line.split()
151             if len(words) == 0:
152                 continue
153             if (not found and words[0] != 'RPC'):
154                 self.__parse_nfs_line(words)
155                 continue
156
157             found = True
158             self.__parse_rpc_line(words)
159
160     def is_nfs_mountpoint(self):
161         """Return True if this is an NFS or NFSv4 mountpoint,
162         otherwise return False
163         """
164         if self.__nfs_data['fstype'] == 'nfs':
165             return True
166         elif self.__nfs_data['fstype'] == 'nfs4':
167             return True
168         return False
169
170     def compare_iostats(self, old_stats):
171         """Return the difference between two sets of stats
172         """
173         result = DeviceData()
174
175         # copy self into result
176         for key, value in self.__nfs_data.iteritems():
177             result.__nfs_data[key] = value
178         for key, value in self.__rpc_data.iteritems():
179             result.__rpc_data[key] = value
180
181         # compute the difference of each item in the list
182         # note the copy loop above does not copy the lists, just
183         # the reference to them.  so we build new lists here
184         # for the result object.
185         for op in result.__rpc_data['ops']:
186             result.__rpc_data[op] = map(difference, self.__rpc_data[op], old_stats.__rpc_data[op])
187
188         # update the remaining keys we care about
189         result.__rpc_data['rpcsends'] -= old_stats.__rpc_data['rpcsends']
190         result.__rpc_data['backlogutil'] -= old_stats.__rpc_data['backlogutil']
191
192         for key in NfsEventCounters:
193             result.__nfs_data[key] -= old_stats.__nfs_data[key]
194         for key in NfsByteCounters:
195             result.__nfs_data[key] -= old_stats.__nfs_data[key]
196
197         return result
198
199     def __print_data_cache_stats(self):
200         """Print the data cache hit rate
201         """
202         nfs_stats = self.__nfs_data
203         app_bytes_read = float(nfs_stats['normalreadbytes'])
204         if app_bytes_read != 0:
205             client_bytes_read = float(nfs_stats['serverreadbytes'] - nfs_stats['directreadbytes'])
206             ratio = ((app_bytes_read - client_bytes_read) * 100) / app_bytes_read
207
208             print
209             print 'app bytes: %f  client bytes %f' % (app_bytes_read, client_bytes_read)
210             print 'Data cache hit ratio: %4.2f%%' % ratio
211
212     def __print_attr_cache_stats(self, sample_time):
213         """Print attribute cache efficiency stats
214         """
215         nfs_stats = self.__nfs_data
216         getattr_stats = self.__rpc_data['GETATTR']
217
218         if nfs_stats['inoderevalidates'] != 0:
219             getattr_ops = float(getattr_stats[1])
220             opens = float(nfs_stats['vfsopen'])
221             revalidates = float(nfs_stats['inoderevalidates']) - opens
222             if revalidates != 0:
223                 ratio = ((revalidates - getattr_ops) * 100) / revalidates
224             else:
225                 ratio = 0.0
226
227             data_invalidates = float(nfs_stats['datainvalidates'])
228             attr_invalidates = float(nfs_stats['attrinvalidates'])
229
230             print
231             print '%d inode revalidations, hitting in cache %4.2f%% of the time' % \
232                 (revalidates, ratio)
233             print '%d open operations (mandatory GETATTR requests)' % opens
234             if getattr_ops != 0:
235                 print '%4.2f%% of GETATTRs resulted in data cache invalidations' % \
236                    ((data_invalidates * 100) / getattr_ops)
237
238     def __print_dir_cache_stats(self, sample_time):
239         """Print directory stats
240         """
241         nfs_stats = self.__nfs_data
242         lookup_ops = self.__rpc_data['LOOKUP'][0]
243         readdir_ops = self.__rpc_data['READDIR'][0]
244         if self.__rpc_data.has_key('READDIRPLUS'):
245             readdir_ops += self.__rpc_data['READDIRPLUS'][0]
246
247         dentry_revals = nfs_stats['dentryrevalidates']
248         opens = nfs_stats['vfsopen']
249         lookups = nfs_stats['vfslookup']
250         getdents = nfs_stats['vfsreaddir']
251
252         print
253         print '%d open operations (pathname lookups)' % opens
254         print '%d dentry revalidates and %d vfs lookup requests' % \
255             (dentry_revals, lookups),
256         print 'resulted in %d LOOKUPs on the wire' % lookup_ops
257         print '%d vfs getdents calls resulted in %d READDIRs on the wire' % \
258             (getdents, readdir_ops)
259
260     def __print_page_stats(self, sample_time):
261         """Print page cache stats
262         """
263         nfs_stats = self.__nfs_data
264
265         vfsreadpage = nfs_stats['vfsreadpage']
266         vfsreadpages = nfs_stats['vfsreadpages']
267         pages_read = nfs_stats['readpages']
268         vfswritepage = nfs_stats['vfswritepage']
269         vfswritepages = nfs_stats['vfswritepages']
270         pages_written = nfs_stats['writepages']
271
272         print
273         print '%d nfs_readpage() calls read %d pages' % \
274             (vfsreadpage, vfsreadpage)
275         print '%d nfs_readpages() calls read %d pages' % \
276             (vfsreadpages, pages_read - vfsreadpage),
277         if vfsreadpages != 0:
278             print '(%.1f pages per call)' % \
279                 (float(pages_read - vfsreadpage) / vfsreadpages)
280         else:
281             print
282
283         print
284         print '%d nfs_updatepage() calls' % nfs_stats['vfsupdatepage']
285         print '%d nfs_writepage() calls wrote %d pages' % \
286             (vfswritepage, vfswritepage)
287         print '%d nfs_writepages() calls wrote %d pages' % \
288             (vfswritepages, pages_written - vfswritepage),
289         if (vfswritepages) != 0:
290             print '(%.1f pages per call)' % \
291                 (float(pages_written - vfswritepage) / vfswritepages)
292         else:
293             print
294
295         congestionwaits = nfs_stats['congestionwait']
296         if congestionwaits != 0:
297             print
298             print '%d congestion waits' % congestionwaits
299
300     def __print_rpc_op_stats(self, op, sample_time):
301         """Print generic stats for one RPC op
302         """
303         if not self.__rpc_data.has_key(op):
304             return
305
306         rpc_stats = self.__rpc_data[op]
307         ops = float(rpc_stats[0])
308         retrans = float(rpc_stats[1] - rpc_stats[0])
309         kilobytes = float(rpc_stats[3] + rpc_stats[4]) / 1024
310         rtt = float(rpc_stats[6])
311         exe = float(rpc_stats[7])
312
313         # prevent floating point exceptions
314         if ops != 0:
315             kb_per_op = kilobytes / ops
316             retrans_percent = (retrans * 100) / ops
317             rtt_per_op = rtt / ops
318             exe_per_op = exe / ops
319         else:
320             kb_per_op = 0.0
321             retrans_percent = 0.0
322             rtt_per_op = 0.0
323             exe_per_op = 0.0
324
325         op += ':'
326         print '%s' % op.lower().ljust(15),
327         print '  ops/s\t\t   Kb/s\t\t  Kb/op\t\tretrans\t\tavg RTT (ms)\tavg exe (ms)'
328
329         print '\t\t%7.3f' % (ops / sample_time),
330         print '\t%7.3f' % (kilobytes / sample_time),
331         print '\t%7.3f' % kb_per_op,
332         print ' %7d (%3.1f%%)' % (retrans, retrans_percent),
333         print '\t%7.3f' % rtt_per_op,
334         print '\t%7.3f' % exe_per_op
335
336     def display_iostats(self, sample_time, which):
337         """Display NFS and RPC stats in an iostat-like way
338         """
339         sends = float(self.__rpc_data['rpcsends'])
340         if sample_time == 0:
341             sample_time = float(self.__nfs_data['age'])
342         if sends != 0:
343             backlog = (float(self.__rpc_data['backlogutil']) / sends) / sample_time
344         else:
345             backlog = 0.0
346
347         print
348         print '%s mounted on %s:' % \
349             (self.__nfs_data['export'], self.__nfs_data['mountpoint'])
350         print
351
352         print '   op/s\t\trpc bklog'
353         print '%7.2f' % (sends / sample_time), 
354         print '\t%7.2f' % backlog
355
356         if which == 0:
357             self.__print_rpc_op_stats('READ', sample_time)
358             self.__print_rpc_op_stats('WRITE', sample_time)
359         elif which == 1:
360             self.__print_rpc_op_stats('GETATTR', sample_time)
361             self.__print_rpc_op_stats('ACCESS', sample_time)
362             self.__print_attr_cache_stats(sample_time)
363         elif which == 2:
364             self.__print_rpc_op_stats('LOOKUP', sample_time)
365             self.__print_rpc_op_stats('READDIR', sample_time)
366             if self.__rpc_data.has_key('READDIRPLUS'):
367                 self.__print_rpc_op_stats('READDIRPLUS', sample_time)
368             self.__print_dir_cache_stats(sample_time)
369         elif which == 3:
370             self.__print_rpc_op_stats('READ', sample_time)
371             self.__print_rpc_op_stats('WRITE', sample_time)
372             self.__print_page_stats(sample_time)
373
374 #
375 # Functions
376 #
377
378 def print_iostat_help(name):
379     print 'usage: %s [ <interval> [ <count> ] ] [ <options> ] [ <mount point> ] ' % name
380     print
381     print ' Version %s' % Iostats_version
382     print
383     print ' Sample iostat-like program to display NFS client per-mount statistics.'
384     print
385     print ' The <interval> parameter specifies the amount of time in seconds between'
386     print ' each report.  The first report contains statistics for the time since each'
387     print ' file system was mounted.  Each subsequent report contains statistics'
388     print ' collected during the interval since the previous report.'
389     print
390     print ' If the <count> parameter is specified, the value of <count> determines the'
391     print ' number of reports generated at <interval> seconds apart.  If the interval'
392     print ' parameter is specified without the <count> parameter, the command generates'
393     print ' reports continuously.'
394     print
395     print ' Options include "--attr", which displays statistics related to the attribute'
396     print ' cache, "--dir", which displays statistics related to directory operations,'
397     print ' and "--page", which displays statistics related to the page cache.'
398     print ' By default, if no option is specified, statistics related to file I/O are'
399     print ' displayed.'
400     print
401     print ' If one or more <mount point> names are specified, statistics for only these'
402     print ' mount points will be displayed.  Otherwise, all NFS mount points on the'
403     print ' client are listed.'
404
405 def parse_stats_file(filename):
406     """pop the contents of a mountstats file into a dictionary,
407     keyed by mount point.  each value object is a list of the
408     lines in the mountstats file corresponding to the mount
409     point named in the key.
410     """
411     ms_dict = dict()
412     key = ''
413
414     f = file(filename)
415     for line in f.readlines():
416         words = line.split()
417         if len(words) == 0:
418             continue
419         if words[0] == 'device':
420             key = words[4]
421             new = [ line.strip() ]
422         else:
423             new += [ line.strip() ]
424         ms_dict[key] = new
425     f.close
426
427     return ms_dict
428
429 def print_iostat_summary(old, new, devices, time, ac):
430     for device in devices:
431         stats = DeviceData()
432         stats.parse_stats(new[device])
433         if not old:
434             stats.display_iostats(time, ac)
435         else:
436             old_stats = DeviceData()
437             old_stats.parse_stats(old[device])
438             diff_stats = stats.compare_iostats(old_stats)
439             diff_stats.display_iostats(time, ac)
440
441 def iostat_command(name):
442     """iostat-like command for NFS mount points
443     """
444     mountstats = parse_stats_file('/proc/self/mountstats')
445     devices = []
446     which = 0
447     interval_seen = False
448     count_seen = False
449
450     for arg in sys.argv:
451         if arg in ['-h', '--help', 'help', 'usage']:
452             print_iostat_help(name)
453             return
454
455         if arg in ['-v', '--version', 'version']:
456             print '%s version %s' % (name, Iostats_version)
457             return
458
459         if arg in ['-a', '--attr']:
460             which = 1
461             continue
462
463         if arg in ['-d', '--dir']:
464             which = 2
465             continue
466
467         if arg in ['-p', '--page']:
468             which = 3
469             continue
470
471         if arg == sys.argv[0]:
472             continue
473
474         if arg in mountstats:
475             devices += [arg]
476         elif not interval_seen:
477             interval = int(arg)
478             if interval > 0:
479                 interval_seen = True
480             else:
481                 print 'Illegal <interval> value'
482                 return
483         elif not count_seen:
484             count = int(arg)
485             if count > 0:
486                 count_seen = True
487             else:
488                 print 'Illegal <count> value'
489                 return
490
491     # make certain devices contains only NFS mount points
492     if len(devices) > 0:
493         check = []
494         for device in devices:
495             stats = DeviceData()
496             stats.parse_stats(mountstats[device])
497             if stats.is_nfs_mountpoint():
498                 check += [device]
499         devices = check
500     else:
501         for device, descr in mountstats.iteritems():
502             stats = DeviceData()
503             stats.parse_stats(descr)
504             if stats.is_nfs_mountpoint():
505                 devices += [device]
506     if len(devices) == 0:
507         print 'No NFS mount points were found'
508         return
509
510     old_mountstats = None
511     sample_time = 0.0
512
513     if not interval_seen:
514         print_iostat_summary(old_mountstats, mountstats, devices, sample_time, which)
515         return
516
517     if count_seen:
518         while count != 0:
519             print_iostat_summary(old_mountstats, mountstats, devices, sample_time, which)
520             old_mountstats = mountstats
521             time.sleep(interval)
522             sample_time = interval
523             mountstats = parse_stats_file('/proc/self/mountstats')
524             count -= 1
525     else: 
526         while True:
527             print_iostat_summary(old_mountstats, mountstats, devices, sample_time, which)
528             old_mountstats = mountstats
529             time.sleep(interval)
530             sample_time = interval
531             mountstats = parse_stats_file('/proc/self/mountstats')
532
533 #
534 # Main
535 #
536 prog = os.path.basename(sys.argv[0])
537
538 try:
539     iostat_command(prog)
540 except KeyboardInterrupt:
541     print 'Caught ^C... exiting'
542     sys.exit(1)
543
544 sys.exit(0)