1 #!/usr/bin/env @PYTHON_SHEBANG@
3 # Print out statistics for all cached dmu buffers. This information
4 # is available through the dbufs kstat and may be post-processed as
5 # needed by the script.
9 # The contents of this file are subject to the terms of the
10 # Common Development and Distribution License, Version 1.0 only
11 # (the "License"). You may not use this file except in compliance
14 # You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
15 # or http://www.opensolaris.org/os/licensing.
16 # See the License for the specific language governing permissions
17 # and limitations under the License.
19 # When distributing Covered Code, include this CDDL HEADER in each
20 # file and include the License file at usr/src/OPENSOLARIS.LICENSE.
21 # If applicable, add the following below this CDDL HEADER, with the
22 # fields enclosed by brackets "[]" replaced with your own identifying
23 # information: Portions Copyright [yyyy] [name of copyright owner]
27 # Copyright (C) 2013 Lawrence Livermore National Security, LLC.
28 # Produced at Lawrence Livermore National Laboratory (cf, DISCLAIMER).
30 # This script must remain compatible with and Python 3.6+.
38 bhdr = ["pool", "objset", "object", "level", "blkid", "offset", "dbsize"]
39 bxhdr = ["pool", "objset", "object", "level", "blkid", "offset", "dbsize",
40 "meta", "state", "dbholds", "dbc", "list", "atype", "flags",
41 "count", "asize", "access", "mru", "gmru", "mfu", "gmfu", "l2",
42 "l2_dattr", "l2_asize", "l2_comp", "aholds", "dtype", "btype",
43 "data_bs", "meta_bs", "bsize", "lvls", "dholds", "blocks", "dsize"]
44 bincompat = ["cached", "direct", "indirect", "bonus", "spill"]
46 dhdr = ["pool", "objset", "object", "dtype", "cached"]
47 dxhdr = ["pool", "objset", "object", "dtype", "btype", "data_bs", "meta_bs",
48 "bsize", "lvls", "dholds", "blocks", "dsize", "cached", "direct",
49 "indirect", "bonus", "spill"]
50 dincompat = ["level", "blkid", "offset", "dbsize", "meta", "state", "dbholds",
51 "dbc", "list", "atype", "flags", "count", "asize", "access",
52 "mru", "gmru", "mfu", "gmfu", "l2", "l2_dattr", "l2_asize",
55 thdr = ["pool", "objset", "dtype", "cached"]
56 txhdr = ["pool", "objset", "dtype", "cached", "direct", "indirect",
58 tincompat = ["object", "level", "blkid", "offset", "dbsize", "meta", "state",
59 "dbc", "dbholds", "list", "atype", "flags", "count", "asize",
60 "access", "mru", "gmru", "mfu", "gmfu", "l2", "l2_dattr",
61 "l2_asize", "l2_comp", "aholds", "btype", "data_bs", "meta_bs",
62 "bsize", "lvls", "dholds", "blocks", "dsize"]
65 # hdr: [size, scale, description]
66 "pool": [15, -1, "pool name"],
67 "objset": [6, -1, "dataset identification number"],
68 "object": [10, -1, "object number"],
69 "level": [5, -1, "indirection level of buffer"],
70 "blkid": [8, -1, "block number of buffer"],
71 "offset": [12, 1024, "offset in object of buffer"],
72 "dbsize": [7, 1024, "size of buffer"],
73 "meta": [4, -1, "is this buffer metadata?"],
74 "state": [5, -1, "state of buffer (read, cached, etc)"],
75 "dbholds": [7, 1000, "number of holds on buffer"],
76 "dbc": [3, -1, "in dbuf cache"],
77 "list": [4, -1, "which ARC list contains this buffer"],
78 "atype": [7, -1, "ARC header type (data or metadata)"],
79 "flags": [9, -1, "ARC read flags"],
80 "count": [5, -1, "ARC data count"],
81 "asize": [7, 1024, "size of this ARC buffer"],
82 "access": [10, -1, "time this ARC buffer was last accessed"],
83 "mru": [5, 1000, "hits while on the ARC's MRU list"],
84 "gmru": [5, 1000, "hits while on the ARC's MRU ghost list"],
85 "mfu": [5, 1000, "hits while on the ARC's MFU list"],
86 "gmfu": [5, 1000, "hits while on the ARC's MFU ghost list"],
87 "l2": [5, 1000, "hits while on the L2ARC"],
88 "l2_dattr": [8, -1, "L2ARC disk address/offset"],
89 "l2_asize": [8, 1024, "L2ARC alloc'd size (depending on compression)"],
90 "l2_comp": [21, -1, "L2ARC compression algorithm for buffer"],
91 "aholds": [6, 1000, "number of holds on this ARC buffer"],
92 "dtype": [27, -1, "dnode type"],
93 "btype": [27, -1, "bonus buffer type"],
94 "data_bs": [7, 1024, "data block size"],
95 "meta_bs": [7, 1024, "metadata block size"],
96 "bsize": [6, 1024, "bonus buffer size"],
97 "lvls": [6, -1, "number of indirection levels"],
98 "dholds": [6, 1000, "number of holds on dnode"],
99 "blocks": [8, 1000, "number of allocated blocks"],
100 "dsize": [12, 1024, "size of dnode"],
101 "cached": [6, 1024, "bytes cached for all blocks"],
102 "direct": [6, 1024, "bytes cached for direct blocks"],
103 "indirect": [8, 1024, "bytes cached for indirect blocks"],
104 "bonus": [5, 1024, "bytes cached for bonus buffer"],
105 "spill": [5, 1024, "bytes cached for spill block"],
110 sep = " " # Default separator is 2 spaces
111 cmd = ("Usage: dbufstat [-bdhnrtvx] [-i file] [-f fields] [-o file] "
112 "[-s string] [-F filter]\n")
116 if sys.platform.startswith("freebsd"):
118 # Requires py-sysctl on FreeBSD
122 dbufs = sysctl.filter("kstat.zfs.misc.dbufs")[0].value
123 sys.stdin = io.StringIO(dbufs)
126 elif sys.platform.startswith("linux"):
128 return "/proc/spl/kstat/zfs/dbufs"
131 def print_incompat_helper(incompat):
133 for key in sorted(incompat):
135 sys.stderr.write("\t")
137 sys.stderr.write(",\n\t")
140 sys.stderr.write(", ")
142 sys.stderr.write("%s" % key)
145 sys.stderr.write("\n\n")
148 def detailed_usage():
149 sys.stderr.write("%s\n" % cmd)
151 sys.stderr.write("Field definitions incompatible with '-b' option:\n")
152 print_incompat_helper(bincompat)
154 sys.stderr.write("Field definitions incompatible with '-d' option:\n")
155 print_incompat_helper(dincompat)
157 sys.stderr.write("Field definitions incompatible with '-t' option:\n")
158 print_incompat_helper(tincompat)
160 sys.stderr.write("Field definitions are as follows:\n")
161 for key in sorted(cols.keys()):
162 sys.stderr.write("%11s : %s\n" % (key, cols[key][2]))
163 sys.stderr.write("\n")
169 sys.stderr.write("%s\n" % cmd)
170 sys.stderr.write("\t -b : Print table of information for each dbuf\n")
171 sys.stderr.write("\t -d : Print table of information for each dnode\n")
172 sys.stderr.write("\t -h : Print this help message\n")
173 sys.stderr.write("\t -n : Exclude header from output\n")
174 sys.stderr.write("\t -r : Print raw values\n")
175 sys.stderr.write("\t -t : Print table of information for each dnode type"
177 sys.stderr.write("\t -v : List all possible field headers and definitions"
179 sys.stderr.write("\t -x : Print extended stats\n")
180 sys.stderr.write("\t -i : Redirect input from the specified file\n")
181 sys.stderr.write("\t -f : Specify specific fields to print (see -v)\n")
182 sys.stderr.write("\t -o : Redirect output to the specified file\n")
183 sys.stderr.write("\t -s : Override default field separator with custom "
184 "character or string\n")
185 sys.stderr.write("\t -F : Filter output by value or regex\n")
186 sys.stderr.write("\nExamples:\n")
187 sys.stderr.write("\tdbufstat -d -o /tmp/d.log\n")
188 sys.stderr.write("\tdbufstat -t -s \",\" -o /tmp/t.log\n")
189 sys.stderr.write("\tdbufstat -v\n")
190 sys.stderr.write("\tdbufstat -d -f pool,object,objset,dsize,cached\n")
191 sys.stderr.write("\tdbufstat -bx -F dbc=1,objset=54,pool=testpool\n")
192 sys.stderr.write("\n")
197 def prettynum(sz, scale, num=0):
200 suffix = [' ', 'K', 'M', 'G', 'T', 'P', 'E', 'Z']
204 if raw or scale == -1:
205 return "%*s" % (sz, num)
207 # Rounding error, return 0
211 while num > scale and index < 5:
217 return "%*d" % (sz, num)
219 if (save / scale) < 10:
220 return "%*.1f%s" % (sz - 1, num, suffix[index])
222 return "%*d%s" % (sz - 1, num, suffix[index])
231 sys.stdout.write("%s%s" % (
232 prettynum(cols[col][0], cols[col][1], v[col]), sep))
233 sys.stdout.write("\n")
235 if e.errno == errno.EPIPE:
245 sys.stdout.write("%*s%s" % (cols[col][0], col, sep))
246 sys.stdout.write("\n")
248 if e.errno == errno.EPIPE:
252 def get_typestring(t):
256 "DMU_OT_OBJECT_DIRECTORY",
257 "DMU_OT_OBJECT_ARRAY",
258 "DMU_OT_PACKED_NVLIST",
259 "DMU_OT_PACKED_NVLIST_SIZE",
263 "DMU_OT_SPACE_MAP_HEADER",
272 "DMU_OT_DSL_DIR_CHILD_MAP",
273 "DMU_OT_DSL_DS_SNAP_MAP",
275 "DMU_OT_DSL_DATASET",
279 "DMU_OT_PLAIN_FILE_CONTENTS",
280 "DMU_OT_DIRECTORY_CONTENTS",
281 "DMU_OT_MASTER_NODE",
282 "DMU_OT_UNLINKED_SET",
286 # other; for testing only!
287 "DMU_OT_PLAIN_OTHER",
288 "DMU_OT_UINT64_OTHER",
292 "DMU_OT_SPA_HISTORY",
293 "DMU_OT_SPA_HISTORY_OFFSETS",
300 "DMU_OT_NEXT_CLONES",
302 "DMU_OT_USERGROUP_USED",
303 "DMU_OT_USERGROUP_QUOTA",
308 "DMU_OT_SA_MASTER_NODE",
309 "DMU_OT_SA_ATTR_REGISTRATION",
310 "DMU_OT_SA_ATTR_LAYOUTS",
314 "DMU_OT_DEADLIST_HDR",
316 "DMU_OT_BPOBJ_SUBOBJ"]
318 0x80: "DMU_OTN_UINT8_DATA",
319 0xc0: "DMU_OTN_UINT8_METADATA",
320 0x81: "DMU_OTN_UINT16_DATA",
321 0xc1: "DMU_OTN_UINT16_METADATA",
322 0x82: "DMU_OTN_UINT32_DATA",
323 0xc2: "DMU_OTN_UINT32_METADATA",
324 0x83: "DMU_OTN_UINT64_DATA",
325 0xc3: "DMU_OTN_UINT64_METADATA",
326 0x84: "DMU_OTN_ZAP_DATA",
327 0xc4: "DMU_OTN_ZAP_METADATA",
328 0xa0: "DMU_OTN_UINT8_ENC_DATA",
329 0xe0: "DMU_OTN_UINT8_ENC_METADATA",
330 0xa1: "DMU_OTN_UINT16_ENC_DATA",
331 0xe1: "DMU_OTN_UINT16_ENC_METADATA",
332 0xa2: "DMU_OTN_UINT32_ENC_DATA",
333 0xe2: "DMU_OTN_UINT32_ENC_METADATA",
334 0xa3: "DMU_OTN_UINT64_ENC_DATA",
335 0xe3: "DMU_OTN_UINT64_ENC_METADATA",
336 0xa4: "DMU_OTN_ZAP_ENC_DATA",
337 0xe4: "DMU_OTN_ZAP_ENC_METADATA"}
339 # If "-rr" option is used, don't convert to string representation
344 if t < len(ot_strings):
347 return otn_strings[t]
348 except (IndexError, KeyError):
352 def get_compstring(c):
353 comp_strings = ["ZIO_COMPRESS_INHERIT", "ZIO_COMPRESS_ON",
354 "ZIO_COMPRESS_OFF", "ZIO_COMPRESS_LZJB",
355 "ZIO_COMPRESS_EMPTY", "ZIO_COMPRESS_GZIP_1",
356 "ZIO_COMPRESS_GZIP_2", "ZIO_COMPRESS_GZIP_3",
357 "ZIO_COMPRESS_GZIP_4", "ZIO_COMPRESS_GZIP_5",
358 "ZIO_COMPRESS_GZIP_6", "ZIO_COMPRESS_GZIP_7",
359 "ZIO_COMPRESS_GZIP_8", "ZIO_COMPRESS_GZIP_9",
360 "ZIO_COMPRESS_ZLE", "ZIO_COMPRESS_LZ4",
361 "ZIO_COMPRESS_ZSTD", "ZIO_COMPRESS_FUNCTION"]
363 # If "-rr" option is used, don't convert to string representation
368 return comp_strings[c]
373 def parse_line(line, labels):
379 # These are "special" fields computed in the update_dict
380 # function, prevent KeyError exception on labels[col] for these.
381 if col not in ['bonus', 'cached', 'direct', 'indirect', 'spill']:
382 val = line[labels[col]]
384 if col in ['pool', 'flags']:
386 elif col in ['dtype', 'btype']:
387 new[col] = get_typestring(int(val))
388 elif col in ['l2_comp']:
389 new[col] = get_compstring(int(val))
396 def update_dict(d, k, line, labels):
397 pool = line[labels['pool']]
398 objset = line[labels['objset']]
399 key = line[labels[k]]
401 dbsize = int(line[labels['dbsize']])
402 blkid = int(line[labels['blkid']])
403 level = int(line[labels['level']])
408 if objset not in d[pool]:
409 d[pool][objset] = dict()
411 if key not in d[pool][objset]:
412 d[pool][objset][key] = parse_line(line, labels)
413 d[pool][objset][key]['bonus'] = 0
414 d[pool][objset][key]['cached'] = 0
415 d[pool][objset][key]['direct'] = 0
416 d[pool][objset][key]['indirect'] = 0
417 d[pool][objset][key]['spill'] = 0
419 d[pool][objset][key]['cached'] += dbsize
422 d[pool][objset][key]['bonus'] += dbsize
424 d[pool][objset][key]['spill'] += dbsize
427 d[pool][objset][key]['direct'] += dbsize
429 d[pool][objset][key]['indirect'] += dbsize
434 def skip_line(vals, filters):
436 Determines if a line should be skipped during printing
437 based on a set of filters
439 if len(filters) == 0:
444 val = prettynum(cols[key][0], cols[key][1], vals[key]).strip()
445 # we want a full match here
446 if re.match("(?:" + filters[key] + r")\Z", val) is None:
452 def print_dict(d, filters, noheader):
455 for pool in list(d.keys()):
456 for objset in list(d[pool].keys()):
457 for v in list(d[pool][objset].values()):
458 if not skip_line(v, filters):
462 def dnodes_build_dict(filehandle):
466 # First 3 lines are header information, skip the first two
470 # The third line contains the labels and index locations
471 for i, v in enumerate(next(filehandle).split()):
474 # The rest of the file is buffer information
475 for line in filehandle:
476 update_dict(dnodes, 'object', line.split(), labels)
481 def types_build_dict(filehandle):
485 # First 3 lines are header information, skip the first two
489 # The third line contains the labels and index locations
490 for i, v in enumerate(next(filehandle).split()):
493 # The rest of the file is buffer information
494 for line in filehandle:
495 update_dict(types, 'dtype', line.split(), labels)
500 def buffers_print_all(filehandle, filters, noheader):
503 # First 3 lines are header information, skip the first two
507 # The third line contains the labels and index locations
508 for i, v in enumerate(next(filehandle).split()):
514 # The rest of the file is buffer information
515 for line in filehandle:
516 vals = parse_line(line.split(), labels)
517 if not skip_line(vals, filters):
539 opts, args = getopt.getopt(
541 "bdf:hi:o:rs:tvxF:n",
560 for opt, arg in opts:
561 if opt in ('-b', '--buffers'):
563 if opt in ('-d', '--dnodes'):
565 if opt in ('-f', '--columns'):
567 if opt in ('-h', '--help'):
569 if opt in ('-i', '--infile'):
571 if opt in ('-o', '--outfile'):
573 if opt in ('-r', '--raw'):
575 if opt in ('-s', '--separator'):
577 if opt in ('-t', '--types'):
579 if opt in ('-v', '--verbose'):
581 if opt in ('-x', '--extended'):
583 if opt in ('-n', '--noheader'):
585 if opt in ('-F', '--filter'):
586 fils = [x.strip() for x in arg.split(",")]
589 f = [x.strip() for x in fil.split("=")]
592 sys.stderr.write("Invalid filter '%s'.\n" % fil)
596 sys.stderr.write("Invalid field '%s' in filter.\n" % f[0])
600 sys.stderr.write("Field '%s' specified multiple times in "
605 re.compile("(?:" + f[1] + r")\Z")
607 sys.stderr.write("Invalid regex for field '%s' in "
613 if hflag or (xflag and desired_cols):
619 # Ensure at most only one of b, d, or t flags are set
620 if (bflag and dflag) or (bflag and tflag) or (dflag and tflag):
624 hdr = bxhdr if xflag else bhdr
626 hdr = txhdr if xflag else thdr
627 else: # Even if dflag is False, it's the default if none set
629 hdr = dxhdr if xflag else dhdr
632 hdr = desired_cols.split(",")
639 elif ((bflag and bincompat and ele in bincompat) or
640 (dflag and dincompat and ele in dincompat) or
641 (tflag and tincompat and ele in tincompat)):
645 sys.stderr.write("Invalid column definition! -- %s\n" % invalid)
648 if len(incompat) > 0:
649 sys.stderr.write("Incompatible field specified! -- %s\n" %
655 tmp = open(ofile, "w")
659 sys.stderr.write("Cannot open %s for writing\n" % ofile)
663 ifile = default_ifile()
667 tmp = open(ifile, "r")
670 sys.stderr.write("Cannot open %s for reading\n" % ifile)
674 buffers_print_all(sys.stdin, filters, nflag)
677 print_dict(dnodes_build_dict(sys.stdin), filters, nflag)
680 print_dict(types_build_dict(sys.stdin), filters, nflag)
683 if __name__ == '__main__':