-
Notifications
You must be signed in to change notification settings - Fork 47
/
pg_view.py
3624 lines (3219 loc) · 140 KB
/
pg_view.py
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
# -*- coding: utf-8 -*-
import os
import re
import sys
import glob
import logging
from optparse import OptionParser
from operator import itemgetter
from datetime import datetime, timedelta
from numbers import Number
from multiprocessing import Process, JoinableQueue, cpu_count # for then number of cpus
import platform
import resource
import socket
import subprocess
import time
import traceback
import json
from collections import namedtuple
__appname__ = 'pg_view'
__version__ = '1.2.0'
__author__ = 'Oleksii Kliukin <[email protected]>'
__license__ = 'Apache 2.0'
if sys.hexversion >= 0x03000000:
import configparser as ConfigParser
from queue import Empty
long = int
maxsize = sys.maxsize
else:
import ConfigParser
from Queue import Empty
maxsize = sys.maxint
try:
import psycopg2
import psycopg2.extras
psycopg2_available = True
except ImportError:
psycopg2_available = False
try:
import curses
curses_available = True
except ImportError:
print('Unable to import ncurses, curses output will be unavailable')
curses_available = False
# enum emulation
def enum(**enums):
return type('Enum', (), enums)
class ColumnType(namedtuple('ColumnType', 'value header header_position')):
__slots__ = ()
@property
def length(self):
return len(self.value) + (0 if not self.header_position else len(self.header) + 1)
COLSTATUS = enum(cs_ok=0, cs_warning=1, cs_critical=2)
COLALIGN = enum(ca_none=0, ca_left=1, ca_center=2, ca_right=3)
COLTYPES = enum(ct_string=0, ct_number=1)
COLHEADER = enum(ch_default=0, ch_prepend=1, ch_append=2)
OUTPUT_METHOD = enum(console='console', json='json', curses='curses')
STAT_FIELD = enum(st_pid=0, st_process_name=1, st_state=2, st_ppid=3, st_start_time=21)
BLOCK_SIZE = 1024
MEM_PAGE_SIZE = resource.getpagesize()
# some global variables for keyboard output
freeze = False
filter_aux = True
autohide_fields = False
display_units = False
notrim = False
realtime = False
# validation functions for OUTPUT_METHOD
def get_valid_output_methods():
result = []
for key in OUTPUT_METHOD.__dict__.keys():
if re.match(r'^[a-z][a-z_]+$', key):
value = OUTPUT_METHOD.__dict__[key]
result.append(value)
return result
def output_method_is_valid(method):
'''
>>> output_method_is_valid('foo')
False
>>> output_method_is_valid('curses')
True
'''
return method in get_valid_output_methods()
def parse_args():
'''parse command-line options'''
parser = OptionParser(add_help_option=False)
parser.add_option('-H', '--help', help='show_help', action='help')
parser.add_option('-v', '--verbose', help='verbose mode', action='store_true', dest='verbose')
parser.add_option('-i', '--instance', help='name of the instance to monitor', action='store', dest='instance')
parser.add_option('-t', '--tick', help='tick length (in seconds)',
action='store', dest='tick', type='int', default=1)
parser.add_option('-o', '--output-method', help='send output to the following source', action='store',
default=OUTPUT_METHOD.curses, dest='output_method')
parser.add_option('-V', '--use-version',
help='version of the instance to monitor (in case it can\'t be autodetected)',
action='store', dest='version', type='float')
parser.add_option('-l', '--log-file', help='direct log output to the file', action='store',
dest='log_file')
parser.add_option('-R', '--reset-output', help='clear screen after each tick', action='store_true', default=False,
dest='clear_screen')
parser.add_option('-c', '--configuration-file', help='configuration file for PostgreSQL connections',
action='store', default='', dest='config_file')
parser.add_option('-P', '--pid', help='always track a given pid (may be used multiple times)',
action='append', type=int, default=[])
parser.add_option('-U', '--username', help='database user name',
action='store', dest='username')
parser.add_option('-d', '--dbname', help='database name to connect to',
action='store', dest='dbname')
parser.add_option('-h', '--host', help='database connection host '
'(or a directory path for the unix socket connection)',
action='store', dest='host')
parser.add_option('-p', '--port', help='database port number', action='store', dest='port')
options, args = parser.parse_args()
return options, args
# setup system constants
TICK_LENGTH = 1
output_method = OUTPUT_METHOD.curses
options = None
logger = None
class StatCollector(object):
""" Generic class to store abstract function and data required to collect system statistics,
produce diffs and emit output rows.
"""
BYTE_MAP = [('TB', 1073741824), ('GB', 1048576), ('MB', 1024)]
USER_HZ = os.sysconf(os.sysconf_names['SC_CLK_TCK'])
RD = 1
NCURSES_DEFAULTS = {
'pos': -1,
'noautohide': False,
'w': 0,
'align': COLALIGN.ca_none,
'column_header': COLHEADER.ch_default,
}
NCURSES_CUSTOM_OUTPUT_FIELDS = ['header', 'prefix', 'prepend_column_headers']
def __init__(self, ticks_per_refresh=1, produce_diffs=True):
self.rows_prev = []
self.rows_cur = []
self.time_diff = 0
self.rows_diff = []
self.ticks = 0
self.ticks_per_refresh = ticks_per_refresh
self.diff_time = 0
self._previous_moment = None
self._current_moment = None
self.produce_diffs = produce_diffs
self.show_units = False
self.ignore_autohide = True
self.notrim = False
# transformation data
self.transform_dict_data = {} # data to transform a dictionary input to the stat row
self.transform_list_data = {} # ditto for the list input
# diff calculation data
self.diff_generator_data = {} # data to produce a diff row out of 2 input ones.
self.output_transform_data = {} # data to transform diff output
self.output_function = {OUTPUT_METHOD.console: self.console_output, OUTPUT_METHOD.json: self.json_output,
OUTPUT_METHOD.curses: self.ncurses_output}
self.cook_function = {OUTPUT_METHOD.curses: self.curses_cook_value}
self.ncurses_custom_fields = dict.fromkeys(StatCollector.NCURSES_CUSTOM_OUTPUT_FIELDS, None)
def postinit(self):
for l in [self.transform_list_data, self.transform_dict_data, self.diff_generator_data,
self.output_transform_data]:
self.validate_list_out(l)
self.output_column_positions = self._calculate_output_column_positions()
def set_ignore_autohide(self, new_status):
self.ignore_autohide = new_status
def set_notrim(self, val):
self.notrim = val
def _calculate_output_column_positions(self):
result = {}
for idx, col in enumerate(self.output_transform_data):
result[col['out']] = idx
return result
def enumerate_output_methods(self):
return self.output_function.keys()
@staticmethod
def exec_command_with_output(cmdline):
""" Execute comand (including shell ones), return a tuple with error code (1 element) and output (rest) """
proc = subprocess.Popen(cmdline, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
ret = proc.wait()
if ret != 0:
logger.error('The command {cmd} returned a non-zero exit code'.format(cmd=cmdline))
return ret, proc.stdout.read().strip()
@staticmethod
def validate_list_out(l):
""" If the list element doesn't supply an out column - remove it """
for col in l:
if 'out' not in col:
el = l.pop(l.index(col))
logger.error('Removed {0} column because it did not specify out value'.format(el))
@staticmethod
def ticks_to_seconds(tick_value_str):
return (float(tick_value_str) / StatCollector.USER_HZ if tick_value_str is not None else None)
@staticmethod
def bytes_to_mbytes(bytes_val):
return (float(bytes_val) / 1048576 if bytes_val is not None else None)
@staticmethod
def sectors_to_mbytes(sectors):
return (float(sectors) / 2048 if sectors is not None else None)
@staticmethod
def kb_to_mbytes(kb):
return (float(kb) / 1024 if kb is not None else None)
@staticmethod
def time_diff_to_percent(timediff_val):
return (float(timediff_val) * 100 if timediff_val is not None else None)
@staticmethod
def format_date_from_epoch(epoch_val):
lt = time.localtime(epoch_val)
today = time.localtime()
time_format_str = '%H:%M:%S'
if lt.tm_year != today.tm_year or lt.tm_mon != today.tm_mon or lt.tm_mday != today.tm_mday:
# only show minutes and seconds
time_format_str = '%m-%d %H:%M:%S'
# show full date
return time.strftime(time_format_str, time.localtime(epoch_val))
@staticmethod
def kb_pretty_print_long(b):
""" Show kb values in a human readable form. """
r = []
for l, n in StatCollector.BYTE_MAP:
d = b / n
if d:
r.append(str(d) + l)
b = b % n
return ' '.join(r)
@staticmethod
def kb_pretty_print(b):
""" Show memory size as a float value in the biggest measurement units """
r = []
v = 0
for l, n in StatCollector.BYTE_MAP:
if b > n:
v = round(float(b) / n, 1)
r.append(str(v) + l)
break
if len(r) == 0:
return '{0}KB'.format(str(b))
else:
return ' '.join(r)
@staticmethod
def time_interval_pretty_print(start_time, is_delta):
'''Returns a human readable string that shows a time between now and the timestamp passed as an argument.
The passed argument can be a timestamp (returned by time.time() call) a datetime object or a timedelta object.
In case it is a timedelta object, then it is formatted only
'''
if isinstance(start_time, Number):
if is_delta:
delta = timedelta(seconds=int(time.time() - start_time))
else:
delta = timedelta(seconds=start_time)
elif isinstance(start_time, datetime):
if is_delta:
delta = datetime.now() - start_time
else:
delta = start_time
elif isinstance(start_time, timedelta):
delta = start_time
else:
raise ValueError('passed value should be either a number of seconds ' +
'from year 1970 or datetime instance of timedelta instance')
delta = abs(delta)
secs = delta.seconds
mins = int(secs / 60)
secs %= 60
hrs = int(mins / 60)
mins %= 60
hrs %= 24
result = ''
if delta.days:
result += str(delta.days) + 'd'
if hrs:
if hrs < 10:
result += '0'
result += str(hrs)
result += ':'
if mins < 10:
result += '0'
result += str(mins)
result += ':'
if secs < 10:
result += '0'
result += str(secs)
if not result:
result = str(int(delta.microseconds / 1000)) + 'ms'
return result
@staticmethod
def time_pretty_print(start_time):
return StatCollector.time_interval_pretty_print(start_time, False)
@staticmethod
def delta_pretty_print(start_time):
return StatCollector.time_interval_pretty_print(start_time, True)
@staticmethod
def sectors_pretty_print(b):
return StatCollector.kb_pretty_print(b * 2)
@staticmethod
def int_lower_than_non_zero(row, col, val, bound):
return val > 0 and val < bound
@staticmethod
def time_field_to_seconds(val):
result = 0
num = 0
accum_digits = []
semicolons_no = val.count(':')
for c in val:
if c.isdigit():
accum_digits.append(c)
else:
if len(accum_digits) > 0:
num = int(''.join(accum_digits))
if c == 'd':
num *= 86400
elif c == ':':
num *= 60 ** semicolons_no
semicolons_no -= 1
result += num
num = 0
accum_digits = []
return result
def time_field_status(self, row, col):
val = row[self.output_column_positions[col['out']]]
num = StatCollector.time_field_to_seconds(val)
if num <= col['critical']:
return {-1: COLSTATUS.cs_critical}
elif num <= col['warning']:
return {-1: COLSTATUS.cs_warning}
return {-1: COLSTATUS.cs_ok}
@staticmethod
def warn_non_optional_column(colname):
logger.error('Column {0} is not optional, but input row has no value for it'.format(colname))
def set_units_display(self, status):
self.show_units = status
def needs_diffs(self):
""" whether the collector needs diffs. It might not if it's not interested in them,
or if it doesn't have data to produce them yet.
"""
return self.produce_diffs and self.rows_prev is not None and self.rows_cur is not None and len(self.rows_prev) \
> 0 and len(self.rows_cur) > 0
def tick(self):
self.ticks += 1
def needs_refresh(self):
return self.ticks % self.ticks_per_refresh == 0
def refresh(self):
self._do_refresh(None)
def ident(self):
return str(self.__class__).lower().split('.')[-1].split('statcollector')[0]
def ncurses_set_prefix(self, new_prefix):
self.ncurses_custom_fields['prefix'] = new_prefix
def cook_row(self, row, header, method):
cooked_vals = []
if not self.cook_function.get(method):
return row
if len(row) != len(header):
logger.error('Unable to cook row with non-matching number of header and value columns: ' +
'row {0} header {1}'.format(row, header))
cook_fn = self.cook_function[method]
for no, val in enumerate(row):
# if might be tempting to just get the column from output_transform_data using
# the header, but it's wrong: see _produce_output_name for details. This, of
# course, assumes the number of columns in the output_transform_data is the
# same as in row: thus, we need to avoid filtering rows in the collector.
newval = cook_fn(val, header[no], self.output_transform_data[no])
cooked_vals.append(newval)
return cooked_vals
def curses_cook_value(self, attname, raw_val, output_data):
""" return cooked version of the row, with values transformed. A transformation is
the same for all columns and depends on the values only.
"""
val = raw_val
header = str(attname)
# change the None output to ''
if raw_val is None:
return ColumnType(value='', header='', header_position=None)
if str(raw_val) == 'True':
val = 'T'
elif str(raw_val) == 'False':
val = 'F'
if output_data.get('maxw', 0) > 0 and not self.notrim and len(str(val)) > output_data['maxw']:
# if the value is larger than the maximum allowed width - trim it by removing chars from the middle
val = self._trim_text_middle(val, output_data['maxw'])
if self.ncurses_custom_fields.get('prepend_column_headers') or output_data.get('column_header',
COLHEADER.ch_default) == COLHEADER.ch_prepend:
header_position = COLHEADER.ch_prepend
elif output_data.get('column_header', COLHEADER.ch_default) == COLHEADER.ch_append:
header_position = COLHEADER.ch_append
else:
header = ''
header_position = None
return ColumnType(value=str(val), header=header, header_position=header_position)
@staticmethod
def _trim_text_middle(val, maxw):
""" Trim data by removing middle characters, so hello world' for 8 will become hel..rld.
This kind of trimming seems to be better than tail trimming for user and database names.
"""
half = int((maxw - 2) / 2)
return val[:half] + '..' + val[-half:]
def _do_refresh(self, new_rows):
""" Make a place for new rows and calculate the time diff """
self.rows_prev = self.rows_cur
self.rows_cur = new_rows
self._previous_moment = self._current_moment
self._current_moment = time.time()
if self._previous_moment is None:
self.diff_time = 0
else:
self.diff_time = self._current_moment - self._previous_moment
def _produce_diff_row(self, prev, cur):
""" produce output columns out of 2 input ones (previous and current). If the value
doesn't exist in either of the diffed rows - we set the result to None
"""
# exit early if we don't need any diffs
if not self.produce_diffs:
return {}
result = {}
for col in self.diff_generator_data:
# Only process attributes for which out it set.
attname = col['out']
incol = (col['in'] if 'in' in col and col['in'] else attname)
# if diff is False = copy the attribute as is.
if 'diff' in col and col['diff'] is False:
result[attname] = (cur[incol] if incol in cur else None)
elif 'fn' in col:
# if diff is True and fn is supplied - apply it to the current and previous row.
result[attname] = (col['fn'](incol, cur, prev) if cur.get(incol, None) is not None and prev.get(incol,
None) is not None else None)
else:
# default case - calculate the diff between the current attribute's values of
# old and new rows and divide it by the time interval passed between measurements.
result[attname] = ((cur[incol] - prev[incol]) / self.diff_time if cur.get(incol, None) is not None and
prev.get(incol, None) is not None and self.diff_time >= 0 else None)
return result
def _produce_output_row(self, row):
""" produce the output row for the screen, json or the database
from the diff rows. It consists of renaming columns and rounding
the result when necessary
"""
result = {}
# produce the output row column by column
for col in self.output_transform_data:
attname = self._produce_output_name(col)
val = self._produce_output_value(row, col)
result[attname] = val
return result
def _produce_output_value(self, row, col, method=OUTPUT_METHOD.console):
# get the input value
if 'in' in col:
val = row.get(col['in'], None)
else:
val = row.get(col['out'], None)
# if function is specified - apply it to the input value
if 'fn' in col and val is not None:
val = col['fn'](val)
# if rounding is necessary - round the input value up to specified
# decimal points
if 'round' in col and val is not None:
val = round(val, col['round'])
return val
def _produce_output_name(self, col):
# get the output column name
attname = col['out']
# add units to the column name if neccessary
if 'units' in col and self.show_units:
attname += ' ' + col['units']
return attname
def _calculate_output_status(self, row, col, val, method):
""" Examine the current status indicators and produce the status
value for the specific column of the given row
"""
st = {-1: COLSTATUS.cs_ok}
# if value is missing - don't bother calculating anything
if val is None:
return st
if 'status_fn' in col:
st = col['status_fn'](row, col)
if len(st) == 0:
st = {-1: COLSTATUS.cs_ok}
else:
words = str(val).split()
for i, word in enumerate(words):
for st_name, st_status in zip(('critical', 'warning'), (COLSTATUS.cs_critical, COLSTATUS.cs_warning)):
if st_name in col:
typ = type(col[st_name])
if typ == int:
typ = float
if typ(word) >= col[st_name]:
st[i] = st_status
break
if i not in st:
st[i] = COLSTATUS.cs_ok
return st
def _get_columns_to_hide(self, result_rows, status_rows):
""" scan the (cooked) rows, do not show columns that are empty """
to_skip = []
for col in self.output_transform_data:
if col.get('pos') == -1:
continue
attname = self._produce_output_name(col)
empty = True
for r in result_rows:
if r[attname].value != '':
empty = False
break
if empty:
to_skip.append(attname)
elif col.get('hide_if_ok', False):
status_ok = True
for row in status_rows:
if attname in row and row[attname]:
for cl in row[attname]:
if row[attname][cl] != COLSTATUS.cs_ok:
status_ok = False
break
if not status_ok:
break
if status_ok:
to_skip.append(attname)
return to_skip
def _transform_input(self, x, custom_transformation_data=None):
if isinstance(x, list) or isinstance(x, tuple):
return self._transform_list(x, custom_transformation_data)
elif isinstance(x, dict):
return self._transform_dict(x, custom_transformation_data)
elif isinstance(x, str):
return self._transform_string(x)
else:
raise Exception('transformation of data type {0} is not supported'.format(type(x)))
# The following 2 functions are almost the same. The only difference is the
# behavior in case 'in' is not specified: the _dict version assumes the in
# column is the same as the out one, the list emits the warning and skips
# the column.
def _transform_list(self, l, custom_transformation_data=None):
result = {}
# choose between the 'embedded' and external transformations
if custom_transformation_data is not None:
transformation_data = custom_transformation_data
else:
transformation_data = self.transform_list_data
if transformation_data is not None:
total = len(l)
for col in transformation_data:
# set the output column name
attname = col['out']
if 'infn' in col:
if len(l) > 0:
result[attname] = col['infn'](attname, l, 'optional' in col and col['optional'])
else:
result[attname] = None
else:
incol = col['in']
# get the column from which the value is extracted
if incol > total - 1:
result[attname] = None
# complain on optional columns, but only if the list to transform has any data
# we want to catch cases when the data collectors (i.e. df, du) doesn't deliver
# the result in the format we ask them to, but, on the other hand, if there is
# nothing at all from them - then the problem is elsewhere and there is no need
# to bleat here for each missing column.
if not col.get('optional', False) and len(l) > 0:
self.warn_non_optional_column(incol)
else:
result[attname] = l[incol]
# if transformation function is supplied - apply it to the input data.
if 'fn' in col and result[attname] is not None:
result[attname] = col['fn'](result[attname])
return result
raise Exception('No data for the list transformation supplied')
# Most of the functionality is the same as in the dict transforming function above.
def _transform_dict(self, l, custom_transformation_data=None):
result = {}
if custom_transformation_data is not None:
transformation_data = custom_transformation_data
else:
transformation_data = self.transform_dict_data
if transformation_data:
for col in transformation_data:
attname = col['out']
# if input column name is not supplied - assume it's the same as an output one.
incol = self._get_input_column_name(col)
# if infn is supplied - it calculates the column value possbily using other values
# in the row - we don't use incoming column in this case.
if 'infn' in col:
if len(l) > 0:
result[attname] = col['infn'](attname, l, 'optional' in col and col['optional'])
else:
result[attname] = None
elif incol not in l:
# if the column is marked as optional and it's not present in the output data
# set None instead
result[attname] = None
# see the comment at _transform_list on why we do complain here.
if not col.get('optional', False) and len(l) > 0:
self.warn_non_optional_column(incol)
else:
result[attname] = l[incol]
if 'fn' in col and result[attname] is not None:
result[attname] = col['fn'](result[attname])
return result
raise Exception('No data for the dict transformation supplied')
def _transform_string(self, d):
raise Exception('transformation of input type string is not implemented')
def _output_template_for_console(self):
return ' '.join(self._output_row_for_console(None, 't'))
def _output_row_for_console(self, row, typ='v'):
return self._output_row_generic(row, typ, method=OUTPUT_METHOD.console)
def _output_row_for_curses(self, row, typ='v'):
return self._output_row_generic(row, typ, method=OUTPUT_METHOD.curses)
def _output_row_generic(self, row, typ='v', method=OUTPUT_METHOD.console):
""" produce a single output row of the type specified by the
last argument:
t - template row
h - header row (only names)
v - values rows
"""
vals = []
# produce the output row column by column
for i, col in enumerate(self.output_transform_data):
# get the final attribute name and value
if typ == 't':
if 'w' not in col:
val = '{{{0}}}'.format(i)
else:
val = '{{{0}:<{1}}}'.format(i, col['w'])
elif typ == 'h':
val = self._produce_output_name(col)
else:
val = self._produce_output_value(row, col, method)
# prepare the list for the output
vals.append(val)
if 'typ' != 'v':
return vals
else:
return vals
def console_output(self, rows, before_string=None, after_string=None):
""" Main entry point for preparing textual console output """
result = []
# start by filling-out width of the values
self._calculate_dynamic_width(rows)
# now produce output template, headers and actual values
templ = self._output_template_for_console()
header = self._output_row_for_console(None, 'h')
if before_string:
result.append(before_string)
result.append(templ.format(*header))
for r in rows:
row = self._output_row_for_console(r, 'v')
result.append(templ.format(*row))
if after_string:
result.append(after_string)
return '\n'.join(result)
def _calculate_dynamic_width(self, rows, method=OUTPUT_METHOD.console):
""" Examine values in all rows and get the width dynamically """
for col in self.output_transform_data:
minw = col.get('minw', 0)
attname = self._produce_output_name(col)
# XXX: if append_column_header, min width should include the size of the attribut name
if method == OUTPUT_METHOD.curses and self.ncurses_custom_fields.get('prepend_column_headers'):
minw += len(attname) + 1
col['w'] = len(attname)
# use cooked values
for row in rows:
if method == OUTPUT_METHOD.curses and self.ncurses_filter_row(row):
continue
val = self._produce_output_value(row, col, method)
if self.cook_function.get(method):
val = self.cook_function[method](attname, val, col)
if method == OUTPUT_METHOD.curses:
curw = val.length
else:
curw = len(str(val))
if curw > col['w']:
col['w'] = curw
if minw > 0:
col['w'] = max(minw, col['w'])
def _calculate_statuses_for_row(self, row, method):
statuses = []
for num, col in enumerate(self.output_transform_data):
statuses.append(self._calculate_output_status(row, col, row[num], method))
return statuses
def _calculate_column_types(self, rows):
result = {}
if len(rows) > 0:
colnames = rows[0].keys()
for colname in colnames:
for r in rows:
val = r[colname]
if val is None or val == '':
continue
else:
if isinstance(val, Number):
result[colname] = COLTYPES.ct_number
else:
result[colname] = COLTYPES.ct_string
break
else:
# if all values are None - we don't care, so use a generic string
result[colname] = COLTYPES.ct_string
return result
def _get_highlights(self):
return [col.get('highlight', False) for col in self.output_transform_data]
@staticmethod
def _get_input_column_name(col):
if 'in' in col:
return col['in']
else:
return col['out']
def json_output(self, rows, before_string=None, after_string=None):
output = {}
data = []
output['type'] = StatCollector.ident(self)
if self.__dict__.get('dbname') and self.__dict__.get('dbver'):
output['name'] = '{0}/{1}'.format(self.dbname, self.dbver)
for r in rows:
data.append(self._produce_output_row(r))
output['data'] = data
return json.dumps(output, indent=4)
def ncurses_filter_row(self, row):
return False
def ncurses_output(self, rows, before_string=None, after_string=None):
""" for ncurses - we just return data structures. The output code
is quite complex and deserves a separate class.
"""
self._calculate_dynamic_width(rows, method=OUTPUT_METHOD.curses)
raw_result = {}
for k in StatCollector.NCURSES_DEFAULTS.keys():
raw_result[k] = []
for col in self.output_transform_data:
for opt in StatCollector.NCURSES_DEFAULTS.keys():
raw_result[opt].append((col[opt] if opt in col else StatCollector.NCURSES_DEFAULTS[opt]))
result_header = self._output_row_for_curses(None, 'h')
result_rows = []
status_rows = []
values_rows = []
for r in rows:
values_row = self._output_row_for_curses(r, 'v')
if self.ncurses_filter_row(dict(zip(result_header, values_row))):
continue
cooked_row = self.cook_row(result_header, values_row, method=OUTPUT_METHOD.curses)
status_row = self._calculate_statuses_for_row(values_row, method=OUTPUT_METHOD.curses)
result_rows.append(dict(zip(result_header, cooked_row)))
status_rows.append(dict(zip(result_header, status_row)))
values_rows.append(dict(zip(result_header, values_row)))
types_row = self._calculate_column_types(values_rows)
result = {}
result['rows'] = result_rows
result['statuses'] = status_rows
result['hide'] = self._get_columns_to_hide(result_rows, status_rows)
result['highlights'] = dict(zip(result_header, self._get_highlights()))
result['types'] = types_row
for x in StatCollector.NCURSES_CUSTOM_OUTPUT_FIELDS:
result[x] = self.ncurses_custom_fields.get(x, None)
for k in StatCollector.NCURSES_DEFAULTS.keys():
if k == 'noautohide' and self.ignore_autohide:
result[k] = dict.fromkeys(result_header, True)
else:
result[k] = dict(zip(result_header, raw_result[k]))
return {self.ident(): result}
def output(self, method, before_string=None, after_string=None):
if method not in self.output_function:
raise Exception('Output method {0} is not supported'.format(method))
if self.produce_diffs:
rows = self.rows_diff
else:
rows = self.rows_cur
return self.output_function[method](rows, before_string, after_string)
def diff(self):
# reset all previous values
self.rows_diff = []
# empty values for current or prev rows are already covered by the need
for prev, cur in zip(self.rows_prev, self.rows_cur):
candidate = self._produce_diff_row(prev, cur)
if candidate is not None and len(candidate) > 0:
# produce the actual diff row
self.rows_diff.append(candidate)
class PgstatCollector(StatCollector):
""" Collect PostgreSQL-related statistics """
STATM_FILENAME = '/proc/{0}/statm'
def __init__(self, pgcon, pid, dbname, dbver, always_track_pids):
super(PgstatCollector, self).__init__()
self.postmaster_pid = pid
self.pgcon = pgcon
self.pids = []
self.rows_diff = []
self.rows_diff_output = []
# figure out our backend pid
self.connection_pid = pgcon.get_backend_pid()
self.max_connections = self._get_max_connections()
self.recovery_status = self._get_recovery_status()
self.always_track_pids = always_track_pids
self.dbname = dbname
self.dbver = dbver
self.server_version = pgcon.get_parameter_status('server_version')
self.filter_aux_processes = True
self.total_connections = 0
self.active_connections = 0
self.transform_list_data = [
{'out': 'pid', 'in': 0, 'fn': int},
{'out': 'state', 'in': 2},
{'out': 'utime', 'in': 13, 'fn': StatCollector.ticks_to_seconds},
{'out': 'stime', 'in': 14, 'fn': StatCollector.ticks_to_seconds},
{'out': 'priority', 'in': 17, 'fn': int},
{'out': 'starttime', 'in': 21, 'fn': long},
{'out': 'vsize', 'in': 22, 'fn': int},
{'out': 'rss', 'in': 23, 'fn': int},
{
'out': 'delayacct_blkio_ticks',
'in': 41,
'fn': long,
'optional': True,
},
{
'out': 'guest_time',
'in': 42,
'fn': StatCollector.ticks_to_seconds,
'optional': True,
},
]
self.transform_dict_data = [{'out': 'read_bytes', 'fn': int, 'optional': True}, {'out': 'write_bytes',
'fn': int, 'optional': True}]
self.diff_generator_data = [
{'out': 'pid', 'diff': False},
{'out': 'type', 'diff': False},
{'out': 'state', 'diff': False},
{'out': 'priority', 'diff': False},
{'out': 'utime'},
{'out': 'stime'},
{'out': 'guest_time'},
{'out': 'delayacct_blkio_ticks'},
{'out': 'read_bytes'},
{'out': 'write_bytes'},
{'out': 'uss', 'diff': False},
{'out': 'age', 'diff': False},
{'out': 'datname', 'diff': False},
{'out': 'usename', 'diff': False},
{'out': 'waiting', 'diff': False},
{'out': 'locked_by', 'diff': False},
{'out': 'query', 'diff': False},
]
self.output_transform_data = [ # query with age 5 and more will have the age column highlighted
{
'out': 'pid',
'pos': 0,
'minw': 5,
'noautohide': True,
},
{
'out': 'lock',
'in': 'locked_by',
'pos': 1,
'minw': 5,
'noautohide': True,
},
{'out': 'type', 'pos': 1},
{
'out': 's',
'in': 'state',
'pos': 2,
'status_fn': self.check_ps_state,
'warning': 'D',
},
{
'out': 'utime',
'units': '%',
'fn': StatCollector.time_diff_to_percent,
'round': StatCollector.RD,