]> git.proxmox.com Git - mirror_zfs-debian.git/blob - cmd/arcstat/arcstat.py
New upstream version 0.7.9
[mirror_zfs-debian.git] / cmd / arcstat / arcstat.py
1 #!/usr/bin/python
2 #
3 # Print out ZFS ARC Statistics exported via kstat(1)
4 # For a definition of fields, or usage, use arctstat.pl -v
5 #
6 # This script is a fork of the original arcstat.pl (0.1) by
7 # Neelakanth Nadgir, originally published on his Sun blog on
8 # 09/18/2007
9 # http://blogs.sun.com/realneel/entry/zfs_arc_statistics
10 #
11 # This version aims to improve upon the original by adding features
12 # and fixing bugs as needed. This version is maintained by
13 # Mike Harsch and is hosted in a public open source repository:
14 # http://github.com/mharsch/arcstat
15 #
16 # Comments, Questions, or Suggestions are always welcome.
17 # Contact the maintainer at ( mike at harschsystems dot com )
18 #
19 # CDDL HEADER START
20 #
21 # The contents of this file are subject to the terms of the
22 # Common Development and Distribution License, Version 1.0 only
23 # (the "License"). You may not use this file except in compliance
24 # with the License.
25 #
26 # You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
27 # or http://www.opensolaris.org/os/licensing.
28 # See the License for the specific language governing permissions
29 # and limitations under the License.
30 #
31 # When distributing Covered Code, include this CDDL HEADER in each
32 # file and include the License file at usr/src/OPENSOLARIS.LICENSE.
33 # If applicable, add the following below this CDDL HEADER, with the
34 # fields enclosed by brackets "[]" replaced with your own identifying
35 # information: Portions Copyright [yyyy] [name of copyright owner]
36 #
37 # CDDL HEADER END
38 #
39 #
40 # Fields have a fixed width. Every interval, we fill the "v"
41 # hash with its corresponding value (v[field]=value) using calculate().
42 # @hdr is the array of fields that needs to be printed, so we
43 # just iterate over this array and print the values using our pretty printer.
44 #
45
46
47 import sys
48 import time
49 import getopt
50 import re
51 import copy
52
53 from decimal import Decimal
54 from signal import signal, SIGINT, SIGWINCH, SIG_DFL
55
56 cols = {
57 # HDR: [Size, Scale, Description]
58 "time": [8, -1, "Time"],
59 "hits": [4, 1000, "ARC reads per second"],
60 "miss": [4, 1000, "ARC misses per second"],
61 "read": [4, 1000, "Total ARC accesses per second"],
62 "hit%": [4, 100, "ARC Hit percentage"],
63 "miss%": [5, 100, "ARC miss percentage"],
64 "dhit": [4, 1000, "Demand hits per second"],
65 "dmis": [4, 1000, "Demand misses per second"],
66 "dh%": [3, 100, "Demand hit percentage"],
67 "dm%": [3, 100, "Demand miss percentage"],
68 "phit": [4, 1000, "Prefetch hits per second"],
69 "pmis": [4, 1000, "Prefetch misses per second"],
70 "ph%": [3, 100, "Prefetch hits percentage"],
71 "pm%": [3, 100, "Prefetch miss percentage"],
72 "mhit": [4, 1000, "Metadata hits per second"],
73 "mmis": [4, 1000, "Metadata misses per second"],
74 "mread": [4, 1000, "Metadata accesses per second"],
75 "mh%": [3, 100, "Metadata hit percentage"],
76 "mm%": [3, 100, "Metadata miss percentage"],
77 "arcsz": [5, 1024, "ARC Size"],
78 "c": [4, 1024, "ARC Target Size"],
79 "mfu": [4, 1000, "MFU List hits per second"],
80 "mru": [4, 1000, "MRU List hits per second"],
81 "mfug": [4, 1000, "MFU Ghost List hits per second"],
82 "mrug": [4, 1000, "MRU Ghost List hits per second"],
83 "eskip": [5, 1000, "evict_skip per second"],
84 "mtxmis": [6, 1000, "mutex_miss per second"],
85 "dread": [5, 1000, "Demand accesses per second"],
86 "pread": [5, 1000, "Prefetch accesses per second"],
87 "l2hits": [6, 1000, "L2ARC hits per second"],
88 "l2miss": [6, 1000, "L2ARC misses per second"],
89 "l2read": [6, 1000, "Total L2ARC accesses per second"],
90 "l2hit%": [6, 100, "L2ARC access hit percentage"],
91 "l2miss%": [7, 100, "L2ARC access miss percentage"],
92 "l2asize": [7, 1024, "Actual (compressed) size of the L2ARC"],
93 "l2size": [6, 1024, "Size of the L2ARC"],
94 "l2bytes": [7, 1024, "bytes read per second from the L2ARC"],
95 }
96
97 v = {}
98 hdr = ["time", "read", "miss", "miss%", "dmis", "dm%", "pmis", "pm%", "mmis",
99 "mm%", "arcsz", "c"]
100 xhdr = ["time", "mfu", "mru", "mfug", "mrug", "eskip", "mtxmis", "dread",
101 "pread", "read"]
102 sint = 1 # Default interval is 1 second
103 count = 1 # Default count is 1
104 hdr_intr = 20 # Print header every 20 lines of output
105 opfile = None
106 sep = " " # Default separator is 2 spaces
107 version = "0.4"
108 l2exist = False
109 cmd = ("Usage: arcstat.py [-hvx] [-f fields] [-o file] [-s string] [interval "
110 "[count]]\n")
111 cur = {}
112 d = {}
113 out = None
114 kstat = None
115 float_pobj = re.compile("^[0-9]+(\.[0-9]+)?$")
116
117
118 def detailed_usage():
119 sys.stderr.write("%s\n" % cmd)
120 sys.stderr.write("Field definitions are as follows:\n")
121 for key in cols:
122 sys.stderr.write("%11s : %s\n" % (key, cols[key][2]))
123 sys.stderr.write("\n")
124
125 sys.exit(0)
126
127
128 def usage():
129 sys.stderr.write("%s\n" % cmd)
130 sys.stderr.write("\t -h : Print this help message\n")
131 sys.stderr.write("\t -v : List all possible field headers and definitions"
132 "\n")
133 sys.stderr.write("\t -x : Print extended stats\n")
134 sys.stderr.write("\t -f : Specify specific fields to print (see -v)\n")
135 sys.stderr.write("\t -o : Redirect output to the specified file\n")
136 sys.stderr.write("\t -s : Override default field separator with custom "
137 "character or string\n")
138 sys.stderr.write("\nExamples:\n")
139 sys.stderr.write("\tarcstat.py -o /tmp/a.log 2 10\n")
140 sys.stderr.write("\tarcstat.py -s \",\" -o /tmp/a.log 2 10\n")
141 sys.stderr.write("\tarcstat.py -v\n")
142 sys.stderr.write("\tarcstat.py -f time,hit%,dh%,ph%,mh% 1\n")
143 sys.stderr.write("\n")
144
145 sys.exit(1)
146
147
148 def kstat_update():
149 global kstat
150
151 k = [line.strip() for line in open('/proc/spl/kstat/zfs/arcstats')]
152
153 if not k:
154 sys.exit(1)
155
156 del k[0:2]
157 kstat = {}
158
159 for s in k:
160 if not s:
161 continue
162
163 name, unused, value = s.split()
164 kstat[name] = Decimal(value)
165
166
167 def snap_stats():
168 global cur
169 global kstat
170
171 prev = copy.deepcopy(cur)
172 kstat_update()
173
174 cur = kstat
175 for key in cur:
176 if re.match(key, "class"):
177 continue
178 if key in prev:
179 d[key] = cur[key] - prev[key]
180 else:
181 d[key] = cur[key]
182
183
184 def prettynum(sz, scale, num=0):
185 suffix = [' ', 'K', 'M', 'G', 'T', 'P', 'E', 'Z']
186 index = 0
187 save = 0
188
189 # Special case for date field
190 if scale == -1:
191 return "%s" % num
192
193 # Rounding error, return 0
194 elif 0 < num < 1:
195 num = 0
196
197 while num > scale and index < 5:
198 save = num
199 num = num / scale
200 index += 1
201
202 if index == 0:
203 return "%*d" % (sz, num)
204
205 if (save / scale) < 10:
206 return "%*.1f%s" % (sz - 1, num, suffix[index])
207 else:
208 return "%*d%s" % (sz - 1, num, suffix[index])
209
210
211 def print_values():
212 global hdr
213 global sep
214 global v
215
216 for col in hdr:
217 sys.stdout.write("%s%s" % (
218 prettynum(cols[col][0], cols[col][1], v[col]),
219 sep
220 ))
221 sys.stdout.write("\n")
222 sys.stdout.flush()
223
224
225 def print_header():
226 global hdr
227 global sep
228
229 for col in hdr:
230 sys.stdout.write("%*s%s" % (cols[col][0], col, sep))
231 sys.stdout.write("\n")
232
233
234 def get_terminal_lines():
235 try:
236 import fcntl
237 import termios
238 import struct
239 data = fcntl.ioctl(sys.stdout.fileno(), termios.TIOCGWINSZ, '1234')
240 sz = struct.unpack('hh', data)
241 return sz[0]
242 except Exception:
243 pass
244
245
246 def update_hdr_intr():
247 global hdr_intr
248
249 lines = get_terminal_lines()
250 if lines and lines > 3:
251 hdr_intr = lines - 3
252
253
254 def resize_handler(signum, frame):
255 update_hdr_intr()
256
257
258 def init():
259 global sint
260 global count
261 global hdr
262 global xhdr
263 global opfile
264 global sep
265 global out
266 global l2exist
267
268 desired_cols = None
269 xflag = False
270 hflag = False
271 vflag = False
272 i = 1
273
274 try:
275 opts, args = getopt.getopt(
276 sys.argv[1:],
277 "xo:hvs:f:",
278 [
279 "extended",
280 "outfile",
281 "help",
282 "verbose",
283 "separator",
284 "columns"
285 ]
286 )
287 except getopt.error as msg:
288 sys.stderr.write(msg)
289 usage()
290 opts = None
291
292 for opt, arg in opts:
293 if opt in ('-x', '--extended'):
294 xflag = True
295 if opt in ('-o', '--outfile'):
296 opfile = arg
297 i += 1
298 if opt in ('-h', '--help'):
299 hflag = True
300 if opt in ('-v', '--verbose'):
301 vflag = True
302 if opt in ('-s', '--separator'):
303 sep = arg
304 i += 1
305 if opt in ('-f', '--columns'):
306 desired_cols = arg
307 i += 1
308 i += 1
309
310 argv = sys.argv[i:]
311 sint = Decimal(argv[0]) if argv else sint
312 count = int(argv[1]) if len(argv) > 1 else count
313
314 if len(argv) > 1:
315 sint = Decimal(argv[0])
316 count = int(argv[1])
317
318 elif len(argv) > 0:
319 sint = Decimal(argv[0])
320 count = 0
321
322 if hflag or (xflag and desired_cols):
323 usage()
324
325 if vflag:
326 detailed_usage()
327
328 if xflag:
329 hdr = xhdr
330
331 update_hdr_intr()
332
333 # check if L2ARC exists
334 snap_stats()
335 l2_size = cur.get("l2_size")
336 if l2_size:
337 l2exist = True
338
339 if desired_cols:
340 hdr = desired_cols.split(",")
341
342 invalid = []
343 incompat = []
344 for ele in hdr:
345 if ele not in cols:
346 invalid.append(ele)
347 elif not l2exist and ele.startswith("l2"):
348 sys.stdout.write("No L2ARC Here\n%s\n" % ele)
349 incompat.append(ele)
350
351 if len(invalid) > 0:
352 sys.stderr.write("Invalid column definition! -- %s\n" % invalid)
353 usage()
354
355 if len(incompat) > 0:
356 sys.stderr.write("Incompatible field specified! -- %s\n" %
357 incompat)
358 usage()
359
360 if opfile:
361 try:
362 out = open(opfile, "w")
363 sys.stdout = out
364
365 except IOError:
366 sys.stderr.write("Cannot open %s for writing\n" % opfile)
367 sys.exit(1)
368
369
370 def calculate():
371 global d
372 global v
373 global l2exist
374
375 v = dict()
376 v["time"] = time.strftime("%H:%M:%S", time.localtime())
377 v["hits"] = d["hits"] / sint
378 v["miss"] = d["misses"] / sint
379 v["read"] = v["hits"] + v["miss"]
380 v["hit%"] = 100 * v["hits"] / v["read"] if v["read"] > 0 else 0
381 v["miss%"] = 100 - v["hit%"] if v["read"] > 0 else 0
382
383 v["dhit"] = (d["demand_data_hits"] + d["demand_metadata_hits"]) / sint
384 v["dmis"] = (d["demand_data_misses"] + d["demand_metadata_misses"]) / sint
385
386 v["dread"] = v["dhit"] + v["dmis"]
387 v["dh%"] = 100 * v["dhit"] / v["dread"] if v["dread"] > 0 else 0
388 v["dm%"] = 100 - v["dh%"] if v["dread"] > 0 else 0
389
390 v["phit"] = (d["prefetch_data_hits"] + d["prefetch_metadata_hits"]) / sint
391 v["pmis"] = (d["prefetch_data_misses"] +
392 d["prefetch_metadata_misses"]) / sint
393
394 v["pread"] = v["phit"] + v["pmis"]
395 v["ph%"] = 100 * v["phit"] / v["pread"] if v["pread"] > 0 else 0
396 v["pm%"] = 100 - v["ph%"] if v["pread"] > 0 else 0
397
398 v["mhit"] = (d["prefetch_metadata_hits"] +
399 d["demand_metadata_hits"]) / sint
400 v["mmis"] = (d["prefetch_metadata_misses"] +
401 d["demand_metadata_misses"]) / sint
402
403 v["mread"] = v["mhit"] + v["mmis"]
404 v["mh%"] = 100 * v["mhit"] / v["mread"] if v["mread"] > 0 else 0
405 v["mm%"] = 100 - v["mh%"] if v["mread"] > 0 else 0
406
407 v["arcsz"] = cur["size"]
408 v["c"] = cur["c"]
409 v["mfu"] = d["mfu_hits"] / sint
410 v["mru"] = d["mru_hits"] / sint
411 v["mrug"] = d["mru_ghost_hits"] / sint
412 v["mfug"] = d["mfu_ghost_hits"] / sint
413 v["eskip"] = d["evict_skip"] / sint
414 v["mtxmis"] = d["mutex_miss"] / sint
415
416 if l2exist:
417 v["l2hits"] = d["l2_hits"] / sint
418 v["l2miss"] = d["l2_misses"] / sint
419 v["l2read"] = v["l2hits"] + v["l2miss"]
420 v["l2hit%"] = 100 * v["l2hits"] / v["l2read"] if v["l2read"] > 0 else 0
421
422 v["l2miss%"] = 100 - v["l2hit%"] if v["l2read"] > 0 else 0
423 v["l2asize"] = cur["l2_asize"]
424 v["l2size"] = cur["l2_size"]
425 v["l2bytes"] = d["l2_read_bytes"] / sint
426
427
428 def main():
429 global sint
430 global count
431 global hdr_intr
432
433 i = 0
434 count_flag = 0
435
436 init()
437 if count > 0:
438 count_flag = 1
439
440 signal(SIGINT, SIG_DFL)
441 signal(SIGWINCH, resize_handler)
442 while True:
443 if i == 0:
444 print_header()
445
446 snap_stats()
447 calculate()
448 print_values()
449
450 if count_flag == 1:
451 if count <= 1:
452 break
453 count -= 1
454
455 i = 0 if i >= hdr_intr else i + 1
456 time.sleep(sint)
457
458 if out:
459 out.close()
460
461
462 if __name__ == '__main__':
463 main()