This repository has been archived by the owner on Nov 26, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 330
/
dstat
executable file
·2834 lines (2520 loc) · 94.9 KB
/
dstat
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
### This program is free software; you can redistribute it and/or
### modify it under the terms of the GNU General Public License
### as published by the Free Software Foundation; either version 2
### of the License, or (at your option) any later version.
###
### This program is distributed in the hope that it will be useful,
### but WITHOUT ANY WARRANTY; without even the implied warranty of
### MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
### GNU General Public License for more details.
###
### You should have received a copy of the GNU General Public License
### along with this program; if not, write to the Free Software
### Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
### Copyright 2004-2019 Dag Wieers <[email protected]>
from __future__ import absolute_import, division, generators, print_function
__metaclass__ = type
import collections
import fnmatch
import getopt
import getpass
import glob
import linecache
import os
import re
import resource
import sched
import six
import sys
import time
VERSION = '0.8.0'
theme = { 'default': '' }
if sys.version_info < (2, 2):
sys.exit('error: Python 2.2 or later required')
pluginpath = [
os.path.expanduser('~/.dstat/'), # home + /.dstat/
os.path.abspath(os.path.dirname(sys.argv[0])) + '/plugins/', # binary path + /plugins/
'/usr/share/dstat/',
'/usr/local/share/dstat/',
]
class Options:
def __init__(self, args):
self.args = args
self.bits = False
self.blackonwhite = False
self.count = -1
self.cpulist = None
self.debug = 0
self.delay = 1
self.disklist = None
self.full = False
self.float = False
self.integer = False
self.intlist = None
self.netlist = None
self.swaplist = None
self.color = None
self.update = True
self.header = True
self.output = False
self.pidfile = False
self.profile = ''
### List of available plugins
allplugins = listplugins()
### List of plugins to show
self.plugins = []
### Implicit if no terminal is used
if not sys.stdout.isatty():
self.color = False
self.header = False
self.update = False
### Temporary hardcoded for my own project
self.diskset = {
'local': ('sda', 'hd[a-d]'),
'lores': ('sd[b-k]', 'sd[v-z]', 'sda[a-e]'),
'hires': ('sd[l-u]', 'sda[f-o]'),
}
try:
opts, args = getopt.getopt(args, 'acdfghilmno:prstTvyC:D:I:M:N:S:V',
['all', 'all-plugins', 'bits', 'bw', 'black-on-white', 'color',
'debug', 'filesystem', 'float', 'full', 'help', 'integer',
'list', 'mods', 'modules', 'nocolor', 'noheaders', 'noupdate',
'output=', 'pidfile=', 'profile', 'version', 'vmstat'] + allplugins)
except getopt.error as exc:
print('dstat: %s, try dstat -h for a list of all the options' % exc)
sys.exit(1)
for opt, arg in opts:
if opt in ['-c']:
self.plugins.append('cpu')
elif opt in ['-C']:
self.cpulist = arg.split(',')
elif opt in ['-d']:
self.plugins.append('disk')
elif opt in ['-D']:
self.disklist = arg.split(',')
elif opt in ['--filesystem']:
self.plugins.append('fs')
elif opt in ['-g']:
self.plugins.append('page')
elif opt in ['-i']:
self.plugins.append('int')
elif opt in ['-I']:
self.intlist = arg.split(',')
elif opt in ['-l']:
self.plugins.append('load')
elif opt in ['-m']:
self.plugins.append('mem')
elif opt in ['-M', '--mods', '--modules']:
print('WARNING: Option %s is deprecated, please use --%s instead' % (opt, ' --'.join(arg.split(','))), file=sys.stderr)
self.plugins += arg.split(',')
elif opt in ['-n']:
self.plugins.append('net')
elif opt in ['-N']:
self.netlist = arg.split(',')
elif opt in ['-p']:
self.plugins.append('proc')
elif opt in ['-r']:
self.plugins.append('io')
elif opt in ['-s']:
self.plugins.append('swap')
elif opt in ['-S']:
self.swaplist = arg.split(',')
elif opt in ['-t']:
self.plugins.append('time')
elif opt in ['-T']:
self.plugins.append('epoch')
elif opt in ['-y']:
self.plugins.append('sys')
elif opt in ['-a', '--all']:
self.plugins += [ 'cpu', 'disk', 'net', 'page', 'sys' ]
elif opt in ['-v', '--vmstat']:
self.plugins += [ 'proc', 'mem', 'page', 'disk', 'sys', 'cpu' ]
elif opt in ['-f', '--full']:
self.full = True
elif opt in ['--all-plugins']:
### Make list unique in a fancy fast way
plugins = list({}.fromkeys(allplugins).keys())
plugins.sort()
self.plugins += plugins
elif opt in ['--bits']:
self.bits = True
elif opt in ['--bw', '--black-on-white', '--blackonwhite']:
self.blackonwhite = True
elif opt in ['--color']:
self.color = True
self.update = True
elif opt in ['--debug']:
self.debug = self.debug + 1
elif opt in ['--float']:
self.float = True
elif opt in ['--integer']:
self.integer = True
elif opt in ['--list']:
showplugins()
sys.exit(0)
elif opt in ['--nocolor']:
self.color = False
elif opt in ['--noheaders']:
self.header = False
elif opt in ['--noupdate']:
self.update = False
elif opt in ['-o', '--output']:
self.output = arg
elif opt in ['--pidfile']:
self.pidfile = arg
elif opt in ['--profile']:
self.profile = 'dstat_profile.log'
elif opt in ['-h', '--help']:
self.usage()
self.help()
sys.exit(0)
elif opt in ['-V', '--version']:
self.version()
sys.exit(0)
elif opt.startswith('--'):
self.plugins.append(opt[2:])
else:
print('dstat: option %s unknown to getopt, try dstat -h for a list of all the options' % opt)
sys.exit(1)
if self.float and self.integer:
print('dstat: option --float and --integer are mutual exclusive, you can only force one')
sys.exit(1)
if not self.plugins:
print('You did not select any stats, using -cdngy by default.')
self.plugins = [ 'cpu', 'disk', 'net', 'page', 'sys' ]
try:
if len(args) > 0: self.delay = int(args[0])
if len(args) > 1: self.count = int(args[1])
except:
print('dstat: incorrect argument, try dstat -h for the correct syntax')
sys.exit(1)
if self.delay <= 0:
print('dstat: delay must be an integer, greater than zero')
sys.exit(1)
if self.debug:
print('Plugins: %s' % self.plugins)
def version(self):
print('Dstat %s' % VERSION)
print('Written by Dag Wieers <[email protected]>')
print('Homepage at http://dag.wieers.com/home-made/dstat/')
print()
print('Platform %s/%s' % (os.name, sys.platform))
print('Kernel %s' % os.uname()[2])
print('Python %s' % sys.version)
print()
color = ""
if not gettermcolor():
color = "no "
print('Terminal type: %s (%scolor support)' % (os.getenv('TERM'), color))
rows, cols = gettermsize()
print('Terminal size: %d lines, %d columns' % (rows, cols))
print()
print('Processors: %d' % getcpunr())
print('Pagesize: %d' % resource.getpagesize())
print('Clock ticks per secs: %d' % os.sysconf('SC_CLK_TCK'))
print()
global op
op = self
showplugins()
def usage(self):
print('Usage: dstat [-afv] [options..] [delay [count]]')
def help(self):
print('''Versatile tool for generating system resource statistics)
Dstat options:
-c, --cpu enable cpu stats
-C 0,3,total include cpu0, cpu3 and total
-d, --disk enable disk stats
-D total,hda include hda and total
-g, --page enable page stats
-i, --int enable interrupt stats
-I 5,eth2 include int5 and interrupt used by eth2
-l, --load enable load stats
-m, --mem enable memory stats
-n, --net enable network stats
-N eth1,total include eth1 and total
-p, --proc enable process stats
-r, --io enable io stats (I/O requests completed)
-s, --swap enable swap stats
-S swap1,total include swap1 and total
-t, --time enable time/date output
-T, --epoch enable time counter (seconds since epoch)
-y, --sys enable system stats
--aio enable aio stats
--fs, --filesystem enable fs stats
--ipc enable ipc stats
--lock enable lock stats
--raw enable raw stats
--socket enable socket stats
--tcp enable tcp stats
--udp enable udp stats
--unix enable unix stats
--vm enable vm stats
--vm-adv enable advanced vm stats
--zones enable zoneinfo stats
--list list all available plugins
--<plugin-name> enable external plugin by name (see --list)
-a, --all equals -cdngy (default)
-f, --full automatically expand -C, -D, -I, -N and -S lists
-v, --vmstat equals -pmgdsc -D total
--bits force bits for values expressed in bytes
--float force float values on screen
--integer force integer values on screen
--bw, --black-on-white change colors for white background terminal
--color force colors
--nocolor disable colors
--noheaders disable repetitive headers
--noupdate disable intermediate updates
--output file write CSV output to file
--profile show profiling statistics when exiting dstat
delay is the delay in seconds between each update (default: 1)
count is the number of updates to display before exiting (default: unlimited)
''')
### START STATS DEFINITIONS ###
class dstat:
vars = None
name = None
nick = None
type = 'f'
types = ()
width = 5
scale = 1024
scales = ()
cols = 0
struct = None
# val = {}
# set1 = {}
# set2 = {}
def prepare(self):
if callable(self.discover):
self.discover = self.discover()
if callable(self.vars):
self.vars = self.vars()
if not self.vars:
raise Exception('No counter objects to monitor')
if callable(self.name):
self.name = self.name()
if callable(self.nick):
self.nick = self.nick()
if not self.nick:
self.nick = self.vars
self.val = {}; self.set1 = {}; self.set2 = {}
if self.struct: ### Plugin API version 2
for name in self.vars + [ 'total', ]:
self.val[name] = self.struct
self.set1[name] = self.struct
self.set2[name] = {}
elif self.cols <= 0: ### Plugin API version 1
for name in self.vars:
self.val[name] = self.set1[name] = self.set2[name] = 0
else: ### Plugin API version 1
for name in self.vars + [ 'total', ]:
self.val[name] = list(range(self.cols))
self.set1[name] = list(range(self.cols))
self.set2[name] = list(range(self.cols))
for i in list(range(self.cols)):
self.val[name][i] = self.set1[name][i] = self.set2[name][i] = 0
# print(self.val)
def open(self, *filenames):
"Open stat file descriptor"
self.file = []
self.fd = []
for filename in filenames:
try:
fd = dopen(filename)
if fd:
self.file.append(filename)
self.fd.append(fd)
except:
pass
if not self.fd:
raise Exception('Cannot open file %s' % filename)
def readlines(self):
"Return lines from any file descriptor"
for fd in self.fd:
fd.seek(0)
for line in fd.readlines():
yield line
### Implemented linecache (for top-plugins) but slows down normal plugins
# for fd in self.fd:
# i = 1
# while True:
# line = linecache.getline(fd.name, i);
# if not line: break
# yield line
# i += 1
def splitline(self, sep=None):
for fd in self.fd:
fd.seek(0)
return fd.read().split(sep)
def splitlines(self, sep=None, replace=None):
"Return split lines from any file descriptor"
for fd in self.fd:
fd.seek(0)
for line in fd.readlines():
if replace and sep:
yield line.replace(replace, sep).split(sep)
elif replace:
yield line.replace(replace, ' ').split()
else:
yield line.split(sep)
# ### Implemented linecache (for top-plugins) but slows down normal plugins
# for fd in self.fd:
# if replace and sep:
# yield line.replace(replace, sep).split(sep)
# elif replace:
# yield line.replace(replace, ' ').split()
# else:
# yield line.split(sep)
# i += 1
def statwidth(self):
"Return complete stat width"
if self.cols:
return len(self.vars) * self.colwidth() + len(self.vars) - 1
else:
return len(self.nick) * self.colwidth() + len(self.nick) - 1
def colwidth(self):
"Return column width"
if isinstance(self.name, six.string_types):
return self.width
else:
return len(self.nick) * self.width + len(self.nick) - 1
def title(self):
ret = theme['title']
if isinstance(self.name, six.string_types):
width = self.statwidth()
return ret + self.name[0:width].center(width).replace(' ', '-') + theme['default']
for i, name in enumerate(self.name):
width = self.colwidth()
ret = ret + name[0:width].center(width).replace(' ', '-')
if i + 1 != len(self.vars):
if op.color:
ret = ret + theme['frame'] + char['dash'] + theme['title']
else:
ret = ret + char['space']
return ret
def subtitle(self):
ret = ''
if isinstance(self.name, six.string_types):
for i, nick in enumerate(self.nick):
ret = ret + theme['subtitle'] + nick[0:self.width].center(self.width) + theme['default']
if i + 1 != len(self.nick): ret = ret + char['space']
return ret
else:
for i, name in enumerate(self.name):
for j, nick in enumerate(self.nick):
ret = ret + theme['subtitle'] + nick[0:self.width].center(self.width) + theme['default']
if j + 1 != len(self.nick): ret = ret + char['space']
if i + 1 != len(self.name): ret = ret + theme['frame'] + char['colon']
return ret
def csvtitle(self):
if isinstance(self.name, six.string_types):
return '"' + self.name + '"' + char['sep'] * (len(self.nick) - 1)
else:
ret = ''
for i, name in enumerate(self.name):
ret = ret + '"' + name + '"' + char['sep'] * (len(self.nick) - 1)
if i + 1 != len(self.name): ret = ret + char['sep']
return ret
def csvsubtitle(self):
ret = ''
if isinstance(self.name, six.string_types):
for i, nick in enumerate(self.nick):
ret = ret + '"' + nick + '"'
if i + 1 != len(self.nick): ret = ret + char['sep']
elif len(self.name) == 1:
for i, name in enumerate(self.name):
for j, nick in enumerate(self.nick):
ret = ret + '"' + nick + '"'
if j + 1 != len(self.nick): ret = ret + char['sep']
if i + 1 != len(self.name): ret = ret + char['sep']
else:
for i, name in enumerate(self.name):
for j, nick in enumerate(self.nick):
ret = ret + '"' + name + ':' + nick + '"'
if j + 1 != len(self.nick): ret = ret + char['sep']
if i + 1 != len(self.name): ret = ret + char['sep']
return ret
def check(self):
"Check if stat is applicable"
# if hasattr(self, 'fd') and not self.fd:
# raise Exception, 'File %s does not exist' % self.fd
if not self.vars:
raise Exception('No objects found, no stats available')
if not self.discover:
raise Exception('No objects discovered, no stats available')
if self.colwidth():
return True
raise Exception('Unknown problem, please report')
def discover(self, *objlist):
return True
def show(self):
"Display stat results"
line = ''
if hasattr(self, 'output'):
return cprint(self.output, self.type, self.width, self.scale)
for i, name in enumerate(self.vars):
if i < len(self.types):
ctype = self.types[i]
else:
ctype = self.type
if i < len(self.scales):
scale = self.scales[i]
else:
scale = self.scale
if isinstance(self.val[name], collections.Sequence) and not isinstance(self.val[name], six.string_types):
line = line + cprintlist(self.val[name], ctype, self.width, scale)
sep = theme['frame'] + char['colon']
if i + 1 != len(self.vars):
line = line + sep
else:
### Make sure we don't show more values than we have nicknames
if i >= len(self.nick): break
line = line + cprint(self.val[name], ctype, self.width, scale)
sep = char['space']
if i + 1 != len(self.nick):
line = line + sep
return line
def showend(self, totlist, vislist):
if vislist and self is not vislist[-1]:
return theme['frame'] + char['pipe']
elif totlist != vislist:
return theme['frame'] + char['gt']
return ''
def showcsv(self):
def printcsv(var):
if var != round(var):
return '%.3f' % var
return '%d' % int(round(var))
line = ''
for i, name in enumerate(self.vars):
if isinstance(self.val[name], types.ListType) or isinstance(self.val[name], types.TupleType):
for j, val in enumerate(self.val[name]):
line = line + printcsv(val)
if j + 1 != len(self.val[name]):
line = line + char['sep']
elif isinstance(self.val[name], types.StringType):
line = line + self.val[name]
else:
line = line + printcsv(self.val[name])
if i + 1 != len(self.vars):
line = line + char['sep']
return line
def showcsvend(self, totlist, vislist):
if vislist and self is not vislist[-1]:
return char['sep']
elif totlist and self is not totlist[-1]:
return char['sep']
return ''
class dstat_aio(dstat):
def __init__(self):
self.name = 'async'
self.nick = ('#aio',)
self.vars = ('aio',)
self.type = 'd'
self.width = 5;
self.open('/proc/sys/fs/aio-nr')
def extract(self):
for l in self.splitlines():
if len(l) < 1: continue
self.val['aio'] = int(l[0])
class dstat_cpu(dstat):
def __init__(self):
self.nick = ( 'usr', 'sys', 'idl', 'wai', 'stl' )
self.type = 'p'
self.width = 3
self.scale = 34
self.open('/proc/stat')
self.cols = 5
def discover(self, *objlist):
ret = []
for l in self.splitlines():
if len(l) < 9 or l[0][0:3] != 'cpu': continue
ret.append(l[0][3:])
ret.sort()
for item in objlist: ret.append(item)
return ret
def vars(self):
ret = []
if op.cpulist and 'all' in op.cpulist:
varlist = []
cpu = 0
while cpu < cpunr:
varlist.append(str(cpu))
cpu = cpu + 1
# if len(varlist) > 2: varlist = varlist[0:2]
elif op.cpulist:
varlist = op.cpulist
else:
varlist = ('total',)
for name in varlist:
if name in self.discover + ['total']:
ret.append(name)
return ret
def name(self):
ret = []
for name in self.vars:
if name == 'total':
ret.append('total cpu usage')
else:
ret.append('cpu' + name + ' usage')
return ret
def extract(self):
for l in self.splitlines():
if len(l) < 9: continue
for name in self.vars:
if l[0] == 'cpu' + name or ( l[0] == 'cpu' and name == 'total' ):
self.set2[name] = ( int(l[1]) + int(l[2]) + int(l[6]) + int(l[7]), int(l[3]), int(l[4]), int(l[5]), int(l[8]) )
for name in self.vars:
for i in list(range(self.cols)):
if sum(self.set2[name]) > sum(self.set1[name]):
self.val[name][i] = 100.0 * (self.set2[name][i] - self.set1[name][i]) / (sum(self.set2[name]) - sum(self.set1[name]))
else:
self.val[name][i] = 0
# print("Error: tick problem detected, this should never happen !", file=sys.stderr)
if step == op.delay:
self.set1.update(self.set2)
class dstat_cpu_use(dstat_cpu):
def __init__(self):
self.name = 'per cpu usage'
self.type = 'p'
self.width = 3
self.scale = 34
self.open('/proc/stat')
self.cols = 7
if not op.cpulist:
self.vars = [ str(x) for x in list(range(cpunr)) ]
def extract(self):
for l in self.splitlines():
if len(l) < 9: continue
for name in self.vars:
if l[0] == 'cpu' + name or ( l[0] == 'cpu' and name == 'total' ):
self.set2[name] = ( int(l[1]) + int(l[2]), int(l[3]), int(l[4]), int(l[5]), int(l[6]), int(l[7]), int(l[8]) )
for name in self.vars:
if sum(self.set2[name]) > sum(self.set1[name]):
self.val[name] = 100.0 - 100.0 * (self.set2[name][2] - self.set1[name][2]) / (sum(self.set2[name]) - sum(self.set1[name]))
else:
self.val[name] = 0
# print("Error: tick problem detected, this should never happen !", file=sys.stderr)
if step == op.delay:
self.set1.update(self.set2)
class dstat_cpu_adv(dstat_cpu):
def __init__(self):
self.nick = ( 'usr', 'sys', 'idl', 'wai', 'hiq', 'siq', 'stl' )
self.type = 'p'
self.width = 3
self.scale = 34
self.open('/proc/stat')
self.cols = 7
def extract(self):
for l in self.splitlines():
if len(l) < 9: continue
for name in self.vars:
if l[0] == 'cpu' + name or ( l[0] == 'cpu' and name == 'total' ):
self.set2[name] = ( int(l[1]) + int(l[2]), int(l[3]), int(l[4]), int(l[5]), int(l[6]), int(l[7]), int(l[8]) )
for name in self.vars:
for i in list(range(self.cols)):
if sum(self.set2[name]) > sum(self.set1[name]):
self.val[name][i] = 100.0 * (self.set2[name][i] - self.set1[name][i]) / (sum(self.set2[name]) - sum(self.set1[name]))
else:
self.val[name][i] = 0
# print("Error: tick problem detected, this should never happen !", file=sys.stderr)
if step == op.delay:
self.set1.update(self.set2)
class dstat_cpu24(dstat):
def __init__(self):
self.nick = ( 'usr', 'sys', 'idl')
self.type = 'p'
self.width = 3
self.scale = 34
self.open('/proc/stat')
self.cols = 3
def discover(self, *objlist):
ret = []
for l in self.splitlines():
if len(l) != 5 or l[0][0:3] != 'cpu': continue
ret.append(l[0][3:])
ret.sort()
for item in objlist: ret.append(item)
return ret
def vars(self):
ret = []
if op.cpulist and 'all' in op.cpulist:
varlist = []
cpu = 0
while cpu < cpunr:
varlist.append(str(cpu))
cpu = cpu + 1
# if len(varlist) > 2: varlist = varlist[0:2]
elif op.cpulist:
varlist = op.cpulist
else:
varlist = ('total',)
for name in varlist:
if name in self.discover + ['total']:
ret.append(name)
return ret
def name(self):
ret = []
for name in self.vars:
if name == 'total':
ret.append('cpu usage')
else:
ret.append('cpu' + name)
return ret
def extract(self):
for l in self.splitlines():
for name in self.vars:
if l[0] == 'cpu' + name or ( l[0] == 'cpu' and name == 'total' ):
self.set2[name] = ( int(l[1]) + int(l[2]), int(l[3]), int(l[4]) )
for name in self.vars:
for i in list(range(self.cols)):
self.val[name][i] = 100.0 * (self.set2[name][i] - self.set1[name][i]) / (sum(self.set2[name]) - sum(self.set1[name]))
if step == op.delay:
self.set1.update(self.set2)
class dstat_disk(dstat):
def __init__(self):
self.nick = ('read', 'writ')
self.type = 'b'
self.diskfilter = re.compile('^([hsv]d[a-z]+\d+|cciss/c\d+d\d+p\d+|dm-\d+|md\d+|mmcblk\d+p\d0|VxVM\d+)$')
self.open('/proc/diskstats')
self.cols = 2
def discover(self, *objlist):
ret = []
for l in self.splitlines():
if len(l) < 13: continue
if l[3:] == ['0',] * 11: continue
name = l[2]
ret.append(name)
for item in objlist: ret.append(item)
if not ret:
raise Exception("No suitable block devices found to monitor")
return ret
def basename(self, disk):
"Strip /dev/ and convert symbolic link"
if disk[:5] == '/dev/':
# file or symlink
if os.path.exists(disk):
# e.g. /dev/disk/by-uuid/15e40cc5-85de-40ea-b8fb-cb3a2eaf872
if os.path.islink(disk):
target = os.readlink(disk)
# convert relative pathname to absolute
if target[0] != '/':
target = os.path.join(os.path.dirname(disk), target)
target = os.path.normpath(target)
print('dstat: symlink %s -> %s' % (disk, target))
disk = target
# trim leading /dev/
return disk[5:]
else:
print('dstat: %s does not exist' % disk)
else:
return disk
def vars(self):
ret = []
if op.disklist:
varlist = list(map(self.basename, op.disklist))
elif not op.full:
varlist = ('total',)
else:
varlist = []
for name in self.discover:
if self.diskfilter.match(name): continue
if name not in blockdevices(): continue
varlist.append(name)
# if len(varlist) > 2: varlist = varlist[0:2]
varlist.sort()
for name in varlist:
if name in self.discover + ['total'] or name in op.diskset:
ret.append(name)
return ret
def name(self):
return ['dsk/'+sysfs_dev(name) for name in self.vars]
def extract(self):
for name in self.vars: self.set2[name] = (0, 0)
for l in self.splitlines():
if len(l) < 13: continue
if l[5] == '0' and l[9] == '0': continue
name = l[2]
if l[3:] == ['0',] * 11: continue
if not self.diskfilter.match(name):
self.set2['total'] = ( self.set2['total'][0] + int(l[5]), self.set2['total'][1] + int(l[9]) )
if name in self.vars and name != 'total':
self.set2[name] = ( self.set2[name][0] + int(l[5]), self.set2[name][1] + int(l[9]) )
for diskset in self.vars:
if diskset in op.diskset:
for disk in op.diskset[diskset]:
if fnmatch.fnmatch(name, disk):
self.set2[diskset] = ( self.set2[diskset][0] + int(l[5]), self.set2[diskset][1] + int(l[9]) )
for name in self.set2:
self.val[name] = list(map(lambda x, y: (y - x) * 512.0 / elapsed, self.set1[name], self.set2[name]))
if step == op.delay:
self.set1.update(self.set2)
class dstat_disk24(dstat):
def __init__(self):
self.nick = ('read', 'writ')
self.type = 'b'
self.diskfilter = re.compile('^([hsv]d[a-z]+\d+|cciss/c\d+d\d+p\d+|dm-\d+|md\d+|mmcblk\d+p\d0|VxVM\d+)$')
self.open('/proc/partitions')
if self.fd and not self.discover:
raise Exception('Kernel has no per-partition I/O accounting [CONFIG_BLK_STATS], use at least 2.4.20')
self.cols = 2
def discover(self, *objlist):
ret = []
for l in self.splitlines():
if len(l) < 15 or l[0] == 'major' or int(l[1]) % 16 != 0: continue
name = l[3]
ret.append(name)
for item in objlist: ret.append(item)
if not ret:
raise Exception("No suitable block devices found to monitor")
return ret
def basename(self, disk):
"Strip /dev/ and convert symbolic link"
if disk[:5] == '/dev/':
# file or symlink
if os.path.exists(disk):
# e.g. /dev/disk/by-uuid/15e40cc5-85de-40ea-b8fb-cb3a2eaf872
if os.path.islink(disk):
target = os.readlink(disk)
# convert relative pathname to absolute
if target[0] != '/':
target = os.path.join(os.path.dirname(disk), target)
target = os.path.normpath(target)
print('dstat: symlink %s -> %s' % (disk, target))
disk = target
# trim leading /dev/
return disk[5:]
else:
print('dstat: %s does not exist' % disk)
else:
return disk
def vars(self):
ret = []
if op.disklist:
varlist = list(map(self.basename, op.disklist))
elif not op.full:
varlist = ('total',)
else:
varlist = []
for name in self.discover:
if self.diskfilter.match(name): continue
varlist.append(name)
# if len(varlist) > 2: varlist = varlist[0:2]
varlist.sort()
for name in varlist:
if name in self.discover + ['total'] or name in op.diskset:
ret.append(name)
return ret
def name(self):
return ['dsk/'+sysfs_dev(name) for name in self.vars]
def extract(self):
for name in self.vars: self.set2[name] = (0, 0)
for l in self.splitlines():
if len(l) < 15 or l[0] == 'major' or int(l[1]) % 16 != 0: continue
name = l[3]
if not self.diskfilter.match(name):
self.set2['total'] = ( self.set2['total'][0] + int(l[6]), self.set2['total'][1] + int(l[10]) )
if name in self.vars:
self.set2[name] = ( self.set2[name][0] + int(l[6]), self.set2[name][1] + int(l[10]) )
for diskset in self.vars:
if diskset in op.diskset:
for disk in op.diskset[diskset]:
if fnmatch.fnmatch(name, disk):
self.set2[diskset] = ( self.set2[diskset][0] + int(l[6]), self.set2[diskset][1] + int(l[10]) )
for name in self.set2:
self.val[name] = list(map(lambda x, y: (y - x) * 512.0 / elapsed, self.set1[name], self.set2[name]))
if step == op.delay:
self.set1.update(self.set2)
### FIXME: Needs rework, does anyone care ?
class dstat_disk24_old(dstat):
def __init__(self):
self.nick = ('read', 'writ')
self.type = 'b'
self.diskfilter = re.compile('^([hsv]d[a-z]+\d+|cciss/c\d+d\d+p\d+|dm-\d+|md\d+|mmcblk\d+p\d0|VxVM\d+)$')
self.regexp = re.compile('^\((\d+),(\d+)\):\(\d+,\d+,(\d+),\d+,(\d+)\)$')
self.open('/proc/stat')
self.cols = 2
def discover(self, *objlist):
ret = []
for l in self.splitlines(':'):
if len(l) < 3: continue
name = l[0]
if name != 'disk_io': continue
for pair in line.split()[1:]:
m = self.regexp.match(pair)
if not m: continue
l = m.groups()
if len(l) < 4: continue
name = dev(int(l[0]), int(l[1]))
ret.append(name)
break
for item in objlist: ret.append(item)
if not ret:
raise Exception("No suitable block devices found to monitor")
return ret
def vars(self):
ret = []
if op.disklist:
varlist = op.disklist
elif not op.full:
varlist = ('total',)
else:
varlist = []
for name in self.discover:
if self.diskfilter.match(name): continue
varlist.append(name)
# if len(varlist) > 2: varlist = varlist[0:2]
varlist.sort()
for name in varlist:
if name in self.discover + ['total'] or name in op.diskset:
ret.append(name)
return ret
def name(self):
return ['dsk/'+name for name in self.vars]
def extract(self):
for name in self.vars: self.set2[name] = (0, 0)
for line in self.splitlines(':'):
if len(l) < 3: continue
name = l[0]
if name != 'disk_io': continue
for pair in line.split()[1:]:
m = self.regexp.match(pair)
if not m: continue
l = m.groups()
if len(l) < 4: continue
name = dev(int(l[0]), int(l[1]))
if not self.diskfilter.match(name):
self.set2['total'] = ( self.set2['total'][0] + int(l[2]), self.set2['total'][1] + int(l[3]) )
if name in self.vars and name != 'total':
self.set2[name] = ( self.set2[name][0] + int(l[2]), self.set2[name][1] + int(l[3]) )
for diskset in self.vars:
if diskset in op.diskset:
for disk in op.diskset[diskset]:
if fnmatch.fnmatch(name, disk):
self.set2[diskset] = ( self.set2[diskset][0] + int(l[2]), self.set2[diskset][1] + int(l[3]) )
break
for name in self.set2:
self.val[name] = list(map(lambda x, y: (y - x) * 512.0 / elapsed, self.set1[name], self.set2[name]))
if step == op.delay: