-
Notifications
You must be signed in to change notification settings - Fork 0
/
system_stats.patch
3855 lines (3797 loc) · 141 KB
/
system_stats.patch
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
From 929d8f1ed0bcce78db795fe7cab9484c4e610a13 Mon Sep 17 00:00:00 2001
From: Sahil Harpal <[email protected]>
Date: Wed, 16 Aug 2023 15:19:15 +0530
Subject: [PATCH 1/4] System stats changes except process and disk information
---
web/pgadmin/dashboard/__init__.py | 131 ++++++
web/pgadmin/dashboard/static/js/Dashboard.jsx | 234 +++++++---
.../dashboard/static/js/SystemStats/CPU.jsx | 377 ++++++++++++++++
.../static/js/SystemStats/Memory.jsx | 372 +++++++++++++++
.../static/js/SystemStats/Storage.jsx | 329 ++++++++++++++
.../static/js/SystemStats/Summary.jsx | 422 ++++++++++++++++++
.../sql/default/system_statistics.sql | 100 +++++
.../js/components/PgChart/DonutChart.jsx | 70 +++
.../js/components/PgChart/StreamingChart.jsx | 146 ++++--
9 files changed, 2090 insertions(+), 91 deletions(-)
create mode 100644 web/pgadmin/dashboard/static/js/SystemStats/CPU.jsx
create mode 100644 web/pgadmin/dashboard/static/js/SystemStats/Memory.jsx
create mode 100644 web/pgadmin/dashboard/static/js/SystemStats/Storage.jsx
create mode 100644 web/pgadmin/dashboard/static/js/SystemStats/Summary.jsx
create mode 100644 web/pgadmin/dashboard/templates/dashboard/sql/default/system_statistics.sql
create mode 100644 web/pgadmin/static/js/components/PgChart/DonutChart.jsx
diff --git a/web/pgadmin/dashboard/__init__.py b/web/pgadmin/dashboard/__init__.py
index 1dac54e74..c18f5d3de 100644
--- a/web/pgadmin/dashboard/__init__.py
+++ b/web/pgadmin/dashboard/__init__.py
@@ -112,6 +112,72 @@ class DashboardModule(PgAdminModule):
help_str=help_string
)
+ self.hpc_stats_refresh = self.dashboard_preference.register(
+ 'dashboards', 'hpc_stats_refresh',
+ gettext("Handle & Process count statistics refresh rate"),
+ 'integer', 5, min_val=1, max_val=999999,
+ category_label=PREF_LABEL_REFRESH_RATES,
+ help_str=help_string
+ )
+
+ self.cu_stats_refresh = self.dashboard_preference.register(
+ 'dashboards', 'cu_stats_refresh',
+ gettext(
+ "Percentage of CPU time used by different process \
+ modes statistics refresh rate"
+ ), 'integer', 5, min_val=1, max_val=999999,
+ category_label=PREF_LABEL_REFRESH_RATES,
+ help_str=help_string
+ )
+
+ self.la_stats_refresh = self.dashboard_preference.register(
+ 'dashboards', 'la_stats_refresh',
+ gettext("Average load statistics refresh rate"), 'integer',
+ 5, min_val=1, max_val=999999,
+ category_label=PREF_LABEL_REFRESH_RATES,
+ help_str=help_string
+ )
+
+ self.pcu_stats_refresh = self.dashboard_preference.register(
+ 'dashboards', 'pcu_stats_refresh',
+ gettext("CPU usage per process statistics refresh rate"),
+ 'integer', 5, min_val=1, max_val=999999,
+ category_label=PREF_LABEL_REFRESH_RATES,
+ help_str=help_string
+ )
+
+ self.m_stats_refresh = self.dashboard_preference.register(
+ 'dashboards', 'm_stats_refresh',
+ gettext("Memory usage statistics refresh rate"), 'integer',
+ 5, min_val=1, max_val=999999,
+ category_label=PREF_LABEL_REFRESH_RATES,
+ help_str=help_string
+ )
+
+ self.sm_stats_refresh = self.dashboard_preference.register(
+ 'dashboards', 'sm_stats_refresh',
+ gettext("Swap memory usage statistics refresh rate"), 'integer',
+ 5, min_val=1, max_val=999999,
+ category_label=PREF_LABEL_REFRESH_RATES,
+ help_str=help_string
+ )
+
+ self.pmu_stats_refresh = self.dashboard_preference.register(
+ 'dashboards', 'pmu_stats_refresh',
+ gettext("Memory usage per process statistics refresh rate"),
+ 'integer', 5, min_val=1, max_val=999999,
+ category_label=PREF_LABEL_REFRESH_RATES,
+ help_str=help_string
+ )
+
+ self.io_stats_refresh = self.dashboard_preference.register(
+ 'dashboards', 'io_stats_refresh',
+ gettext("I/O analysis statistics refresh rate"), 'integer',
+ 5, min_val=1, max_val=999999,
+ category_label=PREF_LABEL_REFRESH_RATES,
+ help_str=help_string
+ )
+
self.display_graphs = self.dashboard_preference.register(
'display', 'show_graphs',
gettext("Show graphs?"), 'boolean', True,
@@ -197,6 +263,12 @@ class DashboardModule(PgAdminModule):
'dashboard.get_prepared_by_database_id',
'dashboard.config',
'dashboard.get_config_by_server_id',
+ 'dashboard.check_system_statistics',
+ 'dashboard.check_system_statistics_sid',
+ 'dashboard.check_system_statistics_did',
+ 'dashboard.system_statistics',
+ 'dashboard.system_statistics_sid',
+ 'dashboard.system_statistics_did',
]
@@ -536,3 +608,62 @@ def terminate_session(sid=None, did=None, pid=None):
response=gettext("Success") if res else gettext("Failed"),
status=200
)
+
+
+# To check whether system stats extesion is present or not
[email protected]('check_extension/system_statistics',
+ endpoint='check_system_statistics', methods=['GET'])
[email protected]('check_extension/system_statistics/<int:sid>',
+ endpoint='check_system_statistics_sid', methods=['GET'])
[email protected]('check_extension/system_statistics/<int:sid>/<int:did>',
+ endpoint='check_system_statistics_did', methods=['GET'])
+@login_required
+@check_precondition
+def check_system_statistics(sid=None, did=None):
+ sql = "SELECT * FROM pg_extension WHERE extname = 'system_stats';"
+ status, res = g.conn.execute_scalar(sql)
+ if not status:
+ return internal_server_error(errormsg=res)
+ data = {}
+ if res is not None:
+ data['ss_present'] = True
+ else:
+ data['ss_present'] = False
+ return ajax_response(
+ response=data,
+ status=200
+ )
+
+
+# System Statistics Backend
[email protected]('/system_statistics',
+ endpoint='system_statistics', methods=['GET'])
[email protected]('/system_statistics/<int:sid>',
+ endpoint='system_statistics_sid', methods=['GET'])
[email protected]('/system_statistics/<int:sid>/<int:did>',
+ endpoint='system_statistics_did', methods=['GET'])
+@login_required
+@check_precondition
+def system_statistics(sid=None, did=None):
+ resp_data = {}
+
+ if request.args['chart_names'] != '':
+ chart_names = request.args['chart_names'].split(',')
+
+ if not sid:
+ return internal_server_error(errormsg='Server ID not specified.')
+
+ sql = render_template(
+ "/".join([g.template_path, 'system_statistics.sql']), did=did,
+ chart_names=chart_names,
+ )
+ status, res = g.conn.execute_dict(sql)
+
+ for chart_row in res['rows']:
+ resp_data[chart_row['chart_name']] = json.loads(
+ chart_row['chart_data'])
+
+ return ajax_response(
+ response=resp_data,
+ status=200
+ )
diff --git a/web/pgadmin/dashboard/static/js/Dashboard.jsx b/web/pgadmin/dashboard/static/js/Dashboard.jsx
index 7194fcc10..e6afeff07 100644
--- a/web/pgadmin/dashboard/static/js/Dashboard.jsx
+++ b/web/pgadmin/dashboard/static/js/Dashboard.jsx
@@ -29,6 +29,10 @@ import _ from 'lodash';
import CachedOutlinedIcon from '@material-ui/icons/CachedOutlined';
import EmptyPanelMessage from '../../../static/js/components/EmptyPanelMessage';
import TabPanel from '../../../static/js/components/TabPanel';
+import Summary from 'SystemStats/Summary';
+import CPU from 'SystemStats/CPU';
+import Memory from 'SystemStats/Memory';
+import Storage from 'SystemStats/Storage';
function parseData(data) {
let res = [];
@@ -148,12 +152,21 @@ export default function Dashboard({
}) {
const classes = useStyles();
let tabs = [gettext('Sessions'), gettext('Locks'), gettext('Prepared Transactions')];
+ let mainTabs = [gettext('General'), gettext('System Statistics')];
+ let systemStatsTabs = [gettext('Summary'), gettext('CPU'), gettext('Memory'), gettext('Storage')];
const [dashData, setdashData] = useState([]);
const [msg, setMsg] = useState('');
+ const [ssMsg, setSsMsg] = useState('');
const [tabVal, setTabVal] = useState(0);
+ const [mainTabVal, setmainTabVal] = useState(0);
const [refresh, setRefresh] = useState(false);
const [activeOnly, setActiveOnly] = useState(false);
const [schemaDict, setSchemaDict] = React.useState({});
+ const [systemStatsTabVal, setSystemStatsTabVal] = useState(0);
+
+ const systemStatsTabChanged = (e, tabVal) => {
+ setSystemStatsTabVal(tabVal);
+ };
if (!did) {
tabs.push(gettext('Configuration'));
@@ -163,6 +176,10 @@ export default function Dashboard({
setTabVal(tabVal);
};
+ const mainTabChanged = (e, tabVal) => {
+ setmainTabVal(tabVal);
+ };
+
const serverConfigColumns = [
{
accessor: 'name',
@@ -745,6 +762,7 @@ export default function Dashboard({
useEffect(() => {
let url,
+ ss_extension_check_url = url_for('dashboard.check_system_statistics'),
message = gettext(
'Please connect to the selected server to view the dashboard.'
);
@@ -770,6 +788,10 @@ export default function Dashboard({
if (did) url += sid + '/' + did;
else url += sid;
+ if (did && !props.dbConnected) return;
+ if (did) ss_extension_check_url += '/' + sid + '/' + did;
+ else ss_extension_check_url += '/' + sid;
+
const api = getApiInstance();
if (node) {
api({
@@ -787,6 +809,20 @@ export default function Dashboard({
// show failed message.
setMsg(gettext('Failed to retrieve data from the server.'));
});
+
+ api({
+ url: ss_extension_check_url,
+ type: 'GET',
+ })
+ .then((res) => {
+ const data = res.data;
+ if(data['ss_present'] == false){
+ setSsMsg(gettext('System stats extension is not installed. You can install the extension in a database using the "CREATE EXTENSION system_stats;" SQL command. Reload the pgAdmin once you installed.'));
+ }
+ })
+ .catch(() => {
+ setSsMsg(gettext('Failed to verify the presence of system stats extension.'));
+ });
} else {
setMsg(message);
}
@@ -867,68 +903,148 @@ export default function Dashboard({
{sid && props.serverConnected ? (
<Box className={classes.dashboardPanel}>
<Box className={classes.emptyPanel}>
- {!_.isUndefined(preferences) && preferences.show_graphs && (
- <Graphs
- key={sid + did}
- preferences={preferences}
- sid={sid}
- did={did}
- pageVisible={props.panelVisible}
- ></Graphs>
- )}
- {!_.isUndefined(preferences) && preferences.show_activity && (
- <Box className={classes.panelContent}>
- <Box
- className={classes.cardHeader}
- title={props.dbConnected ? gettext('Database activity') : gettext('Server activity')}
- >
- {props.dbConnected ? gettext('Database activity') : gettext('Server activity')}{' '}
+ <Box className={classes.panelContent}>
+ <Box height="100%" display="flex" flexDirection="column">
+ <Box>
+ <Tabs
+ value={mainTabVal}
+ onChange={mainTabChanged}
+ >
+ {mainTabs.map((tabValue) => {
+ return <Tab key={tabValue} label={tabValue} />;
+ })}
+ <RefreshButton/>
+ </Tabs>
</Box>
- <Box height="100%" display="flex" flexDirection="column">
- <Box>
- <Tabs
- value={tabVal}
- onChange={tabChanged}
- >
- {tabs.map((tabValue) => {
- return <Tab key={tabValue} label={tabValue} />;
- })}
- <RefreshButton/>
- </Tabs>
+ {/* General Statistics */}
+ <TabPanel value={mainTabVal} index={0} classNameRoot={classes.tabPanel}>
+ {!_.isUndefined(preferences) && preferences.show_graphs && (
+ <Graphs
+ key={sid + did}
+ preferences={preferences}
+ sid={sid}
+ did={did}
+ pageVisible={props.panelVisible}
+ ></Graphs>
+ )}
+ {!_.isUndefined(preferences) && preferences.show_activity && (
+ <Box className={classes.panelContent}>
+ <Box
+ className={classes.cardHeader}
+ title={props.dbConnected ? gettext('Database activity') : gettext('Server activity')}
+ >
+ {props.dbConnected ? gettext('Database activity') : gettext('Server activity')}{' '}
+ </Box>
+ <Box height="100%" display="flex" flexDirection="column">
+ <Box>
+ <Tabs
+ value={tabVal}
+ onChange={tabChanged}
+ >
+ {tabs.map((tabValue) => {
+ return <Tab key={tabValue} label={tabValue} />;
+ })}
+ <RefreshButton/>
+ </Tabs>
+ </Box>
+ <TabPanel value={tabVal} index={0} classNameRoot={classes.tabPanel}>
+ <PgTable
+ caveTable={false}
+ CustomHeader={CustomActiveOnlyHeader}
+ columns={activityColumns}
+ data={filteredDashData}
+ schema={schemaDict}
+ ></PgTable>
+ </TabPanel>
+ <TabPanel value={tabVal} index={1} classNameRoot={classes.tabPanel}>
+ <PgTable
+ caveTable={false}
+ columns={databaseLocksColumns}
+ data={dashData}
+ ></PgTable>
+ </TabPanel>
+ <TabPanel value={tabVal} index={2} classNameRoot={classes.tabPanel}>
+ <PgTable
+ caveTable={false}
+ columns={databasePreparedColumns}
+ data={dashData}
+ ></PgTable>
+ </TabPanel>
+ <TabPanel value={tabVal} index={3} classNameRoot={classes.tabPanel}>
+ <PgTable
+ caveTable={false}
+ columns={serverConfigColumns}
+ data={dashData}
+ ></PgTable>
+ </TabPanel>
+ </Box>
+ </Box>
+ )}
+ </TabPanel>
+ {/* System Statistics */}
+ <TabPanel value={mainTabVal} index={1} classNameRoot={classes.tabPanel}>
+ <Box height="100%" display="flex" flexDirection="column">
+ {ssMsg === '' ?
+ <>
+ <Box>
+ <Tabs
+ value={systemStatsTabVal}
+ onChange={systemStatsTabChanged}
+ >
+ {systemStatsTabs.map((tabValue) => {
+ return <Tab key={tabValue} label={tabValue} />;
+ })}
+ </Tabs>
+ </Box>
+ <TabPanel value={systemStatsTabVal} index={0} classNameRoot={classes.tabPanel}>
+ <Summary
+ key={sid + did}
+ preferences={preferences}
+ sid={sid}
+ did={did}
+ pageVisible={props.panelVisible}
+ serverConnected={props.serverConnected}
+ />
+ </TabPanel>
+ <TabPanel value={systemStatsTabVal} index={1} classNameRoot={classes.tabPanel}>
+ <CPU
+ key={sid + did}
+ preferences={preferences}
+ sid={sid}
+ did={did}
+ pageVisible={props.panelVisible}
+ serverConnected={props.serverConnected}
+ />
+ </TabPanel>
+ <TabPanel value={systemStatsTabVal} index={2} classNameRoot={classes.tabPanel}>
+ <Memory
+ key={sid + did}
+ preferences={preferences}
+ sid={sid}
+ did={did}
+ pageVisible={props.panelVisible}
+ serverConnected={props.serverConnected}
+ />
+ </TabPanel>
+ <TabPanel value={systemStatsTabVal} index={3} classNameRoot={classes.tabPanel}>
+ <Storage
+ key={sid + did}
+ preferences={preferences}
+ sid={sid}
+ did={did}
+ pageVisible={props.panelVisible}
+ serverConnected={props.serverConnected}
+ />
+ </TabPanel>
+ </> :
+ <div className={classes.emptyPanel}>
+ <EmptyPanelMessage text={ssMsg}/>
+ </div>
+ }
</Box>
- <TabPanel value={tabVal} index={0} classNameRoot={classes.tabPanel}>
- <PgTable
- caveTable={false}
- CustomHeader={CustomActiveOnlyHeader}
- columns={activityColumns}
- data={filteredDashData}
- schema={schemaDict}
- ></PgTable>
- </TabPanel>
- <TabPanel value={tabVal} index={1} classNameRoot={classes.tabPanel}>
- <PgTable
- caveTable={false}
- columns={databaseLocksColumns}
- data={dashData}
- ></PgTable>
- </TabPanel>
- <TabPanel value={tabVal} index={2} classNameRoot={classes.tabPanel}>
- <PgTable
- caveTable={false}
- columns={databasePreparedColumns}
- data={dashData}
- ></PgTable>
- </TabPanel>
- <TabPanel value={tabVal} index={3} classNameRoot={classes.tabPanel}>
- <PgTable
- caveTable={false}
- columns={serverConfigColumns}
- data={dashData}
- ></PgTable>
- </TabPanel>
- </Box>
+ </TabPanel>
</Box>
- )}
+ </Box>
</Box>
</Box>
) : showDefaultContents() }
diff --git a/web/pgadmin/dashboard/static/js/SystemStats/CPU.jsx b/web/pgadmin/dashboard/static/js/SystemStats/CPU.jsx
new file mode 100644
index 000000000..276034d9e
--- /dev/null
+++ b/web/pgadmin/dashboard/static/js/SystemStats/CPU.jsx
@@ -0,0 +1,377 @@
+/////////////////////////////////////////////////////////////
+//
+// pgAdmin 4 - PostgreSQL Tools
+//
+// Copyright (C) 2013 - 2023, The pgAdmin Development Team
+// This software is released under the PostgreSQL Licence
+//
+//////////////////////////////////////////////////////////////
+// eslint-disable-next-line react/display-name
+import React, { useState, useEffect, useRef, useReducer, useMemo } from 'react';
+import PgTable from 'sources/components/PgTable';
+import gettext from 'sources/gettext';
+import PropTypes from 'prop-types';
+import { makeStyles } from '@material-ui/core/styles';
+import url_for from 'sources/url_for';
+import {getGCD, getEpoch} from 'sources/utils';
+import {ChartContainer} from '../Dashboard';
+import { Grid } from '@material-ui/core';
+import { DATA_POINT_SIZE } from 'sources/chartjs';
+import StreamingChart from '../../../../static/js/components/PgChart/StreamingChart';
+import {useInterval, usePrevious} from 'sources/custom_hooks';
+import axios from 'axios';
+
+export const X_AXIS_LENGTH = 75;
+
+const useStyles = makeStyles((theme) => ({
+ autoResizer: {
+ height: '100% !important',
+ width: '100% !important',
+ background: theme.palette.grey[400],
+ padding: '7.5px',
+ overflowX: 'auto !important',
+ overflowY: 'hidden !important',
+ minHeight: '100%',
+ minWidth: '100%',
+ },
+ container: {
+ height: 'auto',
+ background: theme.palette.grey[200],
+ padding: '10px',
+ marginBottom: '30px',
+ },
+ fixedContainer: {
+ height: '577px',
+ background: theme.palette.grey[200],
+ padding: '10px',
+ marginBottom: '30px',
+ },
+ containerHeader: {
+ fontSize: '16px',
+ fontWeight: 'bold',
+ marginBottom: '5px',
+ }
+}));
+
+export function formatBytes(bytes) {
+ const units = ['B', 'KB', 'MB', 'GB', 'TB'];
+ let unitIndex = 0;
+
+ while (bytes >= 1024 && unitIndex < units.length - 1) {
+ bytes /= 1024;
+ unitIndex++;
+ }
+
+ return `${bytes.toFixed(2)} ${units[unitIndex]}`;
+}
+
+export function transformData(labels, refreshRate) {
+ const colors = ['#FF6384','#36A2EB','#FFCE56','#4BC0C0','#9966FF','#FF9F40','#8D6E63','#2196F3','#FFEB3B','#9C27B0','#00BCD4','#CDDC39'];
+ let datasets = Object.keys(labels).map((label, i)=>{
+ return {
+ label: label,
+ data: labels[label] || [],
+ borderColor: colors[i],
+ pointHitRadius: DATA_POINT_SIZE,
+ };
+ }) || [];
+
+ return {
+ datasets: datasets,
+ refreshRate: refreshRate,
+ };
+}
+
+/* URL for fetching graphs data */
+export function getStatsUrl(sid=-1, did=-1, chart_names=[]) {
+ let base_url = url_for('dashboard.system_statistics');
+ base_url += '/' + sid;
+ base_url += (did > 0) ? ('/' + did) : '';
+ base_url += '?chart_names=' + chart_names.join(',');
+
+ return base_url;
+}
+
+/* This will process incoming charts data add it the previous charts
+ * data to get the new state.
+ */
+export function statsReducer(state, action) {
+
+ if(action.reset) {
+ return action.reset;
+ }
+
+ if(!action.incoming) {
+ return state;
+ }
+
+ if(!action.counterData) {
+ action.counterData = action.incoming;
+ }
+
+ let newState = {};
+ Object.keys(action.incoming).forEach(label => {
+ if(state[label]) {
+ newState[label] = [
+ action.counter ? action.incoming[label] - action.counterData[label] : action.incoming[label],
+ ...state[label].slice(0, X_AXIS_LENGTH-1),
+ ];
+ } else {
+ newState[label] = [
+ action.counter ? action.incoming[label] - action.counterData[label] : action.incoming[label],
+ ];
+ }
+ });
+ return newState;
+}
+
+const chartsDefault = {
+ 'cu_stats': {'User Normal': [], 'User Niced': [], 'Kernel': [], 'Idle': []},
+ 'la_stats': {'1 min': [], '5 mins': [], '10 mins': [], '15 mins': []},
+ 'pcu_stats': {},
+};
+
+export default function CPU({preferences, sid, did, pageVisible, enablePoll=true}) {
+ const refreshOn = useRef(null);
+ const prevPrefernces = usePrevious(preferences);
+
+ const [cpuUsageInfo, cpuUsageInfoReduce] = useReducer(statsReducer, chartsDefault['cu_stats']);
+ const [loadAvgInfo, loadAvgInfoReduce] = useReducer(statsReducer, chartsDefault['la_stats']);
+ const [processCpuUsageStats, setProcessCpuUsageStats] = useState([]);
+
+ const [, setCounterData] = useState({});
+
+ const [pollDelay, setPollDelay] = useState(5000);
+
+ const [errorMsg, setErrorMsg] = useState(null);
+ const [chartDrawnOnce, setChartDrawnOnce] = useState(false);
+
+ const tableHeader = [
+ {
+ Header: 'PID',
+ accessor: 'pid',
+ sortable: true,
+ resizable: true,
+ disableGlobalFilter: false,
+ },
+ {
+ Header: 'Name',
+ accessor: 'name',
+ sortable: true,
+ resizable: true,
+ disableGlobalFilter: false,
+ },
+ {
+ Header: 'CPU Usage',
+ accessor: 'cpu_usage',
+ sortable: true,
+ resizable: true,
+ disableGlobalFilter: false,
+ },
+ ];
+
+ useEffect(()=>{
+ let calcPollDelay = false;
+ if(prevPrefernces) {
+ if(prevPrefernces['cu_stats_refresh'] != preferences['cu_stats_refresh']) {
+ cpuUsageInfoReduce({reset: chartsDefault['cu_stats']});
+ calcPollDelay = true;
+ }
+ if(prevPrefernces['la_stats_refresh'] != preferences['la_stats_refresh']) {
+ loadAvgInfoReduce({reset: chartsDefault['la_stats']});
+ calcPollDelay = true;
+ }
+ if(prevPrefernces['pcu_stats_refresh'] != preferences['pcu_stats_refresh']) {
+ setProcessCpuUsageStats({reset: chartsDefault['pcu_stats']});
+ calcPollDelay = true;
+ }
+ } else {
+ calcPollDelay = true;
+ }
+ if(calcPollDelay) {
+ const keys = Object.keys(chartsDefault);
+ const length = keys.length;
+ if(length == 1){
+ setPollDelay(
+ preferences[keys[0]+'_refresh']*1000
+ );
+ } else {
+ setPollDelay(
+ getGCD(Object.keys(chartsDefault).map((name)=>preferences[name+'_refresh']))*1000
+ );
+ }
+ }
+ }, [preferences]);
+
+ useEffect(()=>{
+ /* Charts rendered are not visible when, the dashboard is hidden but later visible */
+ if(pageVisible && !chartDrawnOnce) {
+ setChartDrawnOnce(true);
+ }
+ }, [pageVisible]);
+
+ useInterval(()=>{
+ const currEpoch = getEpoch();
+ if(refreshOn.current === null) {
+ let tmpRef = {};
+ Object.keys(chartsDefault).forEach((name)=>{
+ tmpRef[name] = currEpoch;
+ });
+ refreshOn.current = tmpRef;
+ }
+
+ let getFor = [];
+ Object.keys(chartsDefault).forEach((name)=>{
+ if(currEpoch >= refreshOn.current[name]) {
+ getFor.push(name);
+ refreshOn.current[name] = currEpoch + preferences[name+'_refresh'];
+ }
+ });
+
+ let path = getStatsUrl(sid, did, getFor);
+ if (!pageVisible){
+ return;
+ }
+ axios.get(path)
+ .then((resp)=>{
+ let data = resp.data;
+ setErrorMsg(null);
+ if(data.hasOwnProperty('cu_stats')){
+ let new_cu_stats = {
+ 'User Normal': data['cu_stats']['usermode_normal_process_percent']?data['cu_stats']['usermode_normal_process_percent']:0,
+ 'User Niced': data['cu_stats']['usermode_niced_process_percent']?data['cu_stats']['usermode_niced_process_percent']:0,
+ 'Kernel': data['cu_stats']['kernelmode_process_percent']?data['cu_stats']['kernelmode_process_percent']:0,
+ 'Idle': data['cu_stats']['idle_mode_percent']?data['cu_stats']['idle_mode_percent']:0,
+ };
+ cpuUsageInfoReduce({incoming: new_cu_stats});
+ }
+
+ if(data.hasOwnProperty('la_stats')){
+ let new_la_stats = {
+ '1 min': data['la_stats']['load_avg_one_minute']?data['la_stats']['load_avg_one_minute']:0,
+ '5 mins': data['la_stats']['load_avg_five_minutes']?data['la_stats']['load_avg_five_minutes']:0,
+ '10 mins': data['la_stats']['load_avg_ten_minutes']?data['la_stats']['load_avg_ten_minutes']:0,
+ '15 mins': data['la_stats']['load_avg_fifteen_minutes']?data['la_stats']['load_avg_fifteen_minutes']:0,
+ };
+ loadAvgInfoReduce({incoming: new_la_stats});
+ }
+
+ if(data.hasOwnProperty('pcu_stats')){
+ let pcu_info_list = [];
+ const pcu_info_obj = data['pcu_stats'];
+ for (const key in pcu_info_obj) {
+ pcu_info_list.push({ icon: '', pid: pcu_info_obj[key]['pid'], name: pcu_info_obj[key]['name'], cpu_usage: formatBytes(pcu_info_obj[key]['cpu_usage']) });
+ }
+
+ setProcessCpuUsageStats(pcu_info_list);
+ }
+
+ setCounterData((prevCounterData)=>{
+ return {
+ ...prevCounterData,
+ ...data,
+ };
+ });
+ })
+ .catch((error)=>{
+ if(!errorMsg) {
+ cpuUsageInfoReduce({reset:chartsDefault['cu_stats']});
+ loadAvgInfoReduce({reset:chartsDefault['la_stats']});
+ setCounterData({});
+ if(error.response) {
+ if (error.response.status === 428) {
+ setErrorMsg(gettext('Please connect to the selected server to view the graph.'));
+ } else {
+ setErrorMsg(gettext('An error occurred whilst rendering the graph.'));
+ }
+ } else if(error.request) {
+ setErrorMsg(gettext('Not connected to the server or the connection to the server has been closed.'));
+ return;
+ } else {
+ console.error(error);
+ }
+ }
+ });
+ }, enablePoll ? pollDelay : -1);
+
+ return (
+ <>
+ <div data-testid='graph-poll-delay' style={{display: 'none'}}>{pollDelay}</div>
+ {chartDrawnOnce &&
+ <CPUWrapper
+ cpuUsageInfo={transformData(cpuUsageInfo, preferences['cu_stats_refresh'])}
+ loadAvgInfo={transformData(loadAvgInfo, preferences['la_stats_refresh'])}
+ processCpuUsageStats={processCpuUsageStats}
+ tableHeader={tableHeader}
+ errorMsg={errorMsg}
+ showTooltip={preferences['graph_mouse_track']}
+ showDataPoints={preferences['graph_data_points']}
+ lineBorderWidth={preferences['graph_line_border_width']}
+ isDatabase={did > 0}
+ isTest={false}
+ />
+ }
+ </>
+ );
+}
+
+CPU.propTypes = {
+ preferences: PropTypes.object.isRequired,
+ sid: PropTypes.oneOfType([PropTypes.string.isRequired, PropTypes.number.isRequired]),
+ did: PropTypes.oneOfType([PropTypes.string.isRequired, PropTypes.number.isRequired]),
+ pageVisible: PropTypes.bool,
+ enablePoll: PropTypes.bool,
+};
+
+export function CPUWrapper(props) {
+ const classes = useStyles();
+ const options = useMemo(()=>({
+ showDataPoints: props.showDataPoints,
+ showTooltip: props.showTooltip,
+ lineBorderWidth: props.lineBorderWidth,
+ }), [props.showTooltip, props.showDataPoints, props.lineBorderWidth]);
+ return (
+ <>
+ <Grid container spacing={1} className={classes.container}>
+ <Grid item md={6} sm={12}>
+ <div className={classes.containerHeader}>{gettext('CPU Usage ()')}</div>
+ <ChartContainer id='cu-graph' title={gettext('')} datasets={props.cpuUsageInfo.datasets} errorMsg={props.errorMsg} isTest={props.isTest}>
+ <StreamingChart data={props.cpuUsageInfo} dataPointSize={DATA_POINT_SIZE} xRange={X_AXIS_LENGTH} options={options} />
+ </ChartContainer>
+ </Grid>
+ <Grid item md={6} sm={12}>
+ <div className={classes.containerHeader}>{gettext('Load Average')}</div>
+ <ChartContainer id='la-graph' title={gettext('')} datasets={props.loadAvgInfo.datasets} errorMsg={props.errorMsg} isTest={props.isTest}>
+ <StreamingChart data={props.loadAvgInfo} dataPointSize={DATA_POINT_SIZE} xRange={X_AXIS_LENGTH} options={options} />
+ </ChartContainer>
+ </Grid>
+ </Grid>
+ <Grid container spacing={1} className={classes.fixedContainer}>
+ <PgTable
+ className={classes.autoResizer}
+ columns={props.tableHeader}
+ data={props.processCpuUsageStats}
+ msg={props.errorMsg}
+ type={'panel'}
+ ></PgTable>
+ </Grid>
+ </>
+ );
+}
+
+const propTypeStats = PropTypes.shape({
+ datasets: PropTypes.array,
+ refreshRate: PropTypes.number.isRequired,
+});
+CPUWrapper.propTypes = {
+ cpuUsageInfo: propTypeStats.isRequired,
+ loadAvgInfo: propTypeStats.isRequired,
+ processCpuUsageStats: PropTypes.array.isRequired,
+ tableHeader: PropTypes.array.isRequired,
+ errorMsg: PropTypes.string,
+ showTooltip: PropTypes.bool.isRequired,
+ showDataPoints: PropTypes.bool.isRequired,
+ lineBorderWidth: PropTypes.number.isRequired,
+ isDatabase: PropTypes.bool.isRequired,
+ isTest: PropTypes.bool,
+};
\ No newline at end of file
diff --git a/web/pgadmin/dashboard/static/js/SystemStats/Memory.jsx b/web/pgadmin/dashboard/static/js/SystemStats/Memory.jsx
new file mode 100644
index 000000000..74e8f424b
--- /dev/null
+++ b/web/pgadmin/dashboard/static/js/SystemStats/Memory.jsx
@@ -0,0 +1,372 @@
+import React, { useState, useEffect, useRef, useReducer, useMemo } from 'react';
+import PgTable from 'sources/components/PgTable';
+import gettext from 'sources/gettext';
+import PropTypes from 'prop-types';
+import { makeStyles } from '@material-ui/core/styles';
+import url_for from 'sources/url_for';
+import {getGCD, getEpoch} from 'sources/utils';
+import {ChartContainer} from '../Dashboard';
+import { Grid } from '@material-ui/core';
+import { DATA_POINT_SIZE } from 'sources/chartjs';
+import StreamingChart from '../../../../static/js/components/PgChart/StreamingChart';
+import {useInterval, usePrevious} from 'sources/custom_hooks';
+import axios from 'axios';
+
+export const X_AXIS_LENGTH = 75;
+
+const useStyles = makeStyles((theme) => ({
+ autoResizer: {
+ height: '100% !important',
+ width: '100% !important',
+ background: theme.palette.grey[400],
+ padding: '7.5px',
+ overflowX: 'auto !important',
+ overflowY: 'hidden !important',
+ minHeight: '100%',
+ minWidth: '100%',
+ },
+ container: {
+ height: 'auto',
+ background: theme.palette.grey[200],
+ padding: '10px',
+ marginBottom: '30px',
+ },
+ fixedContainer: {
+ height: '577px',
+ background: theme.palette.grey[200],
+ padding: '10px',
+ marginBottom: '30px',
+ },
+ containerHeader: {
+ fontSize: '16px',
+ fontWeight: 'bold',
+ marginBottom: '5px',
+ }
+}));
+
+export function formatBytes(bytes) {
+ const units = ['B', 'KB', 'MB', 'GB', 'TB'];
+ let unitIndex = 0;
+
+ while (bytes >= 1024 && unitIndex < units.length - 1) {
+ bytes /= 1024;
+ unitIndex++;
+ }
+
+ return `${bytes.toFixed(2)} ${units[unitIndex]}`;
+}
+
+export function transformData(labels, refreshRate) {
+ const colors = ['#FF6384','#36A2EB','#FFCE56','#4BC0C0','#9966FF','#FF9F40','#8D6E63','#2196F3','#FFEB3B','#9C27B0','#00BCD4','#CDDC39'];
+ let datasets = Object.keys(labels).map((label, i)=>{
+ return {
+ label: label,
+ data: labels[label] || [],
+ borderColor: colors[i],
+ pointHitRadius: DATA_POINT_SIZE,
+ };
+ }) || [];
+
+ return {
+ datasets: datasets,
+ refreshRate: refreshRate,
+ };
+}
+
+/* URL for fetching graphs data */
+export function getStatsUrl(sid=-1, did=-1, chart_names=[]) {
+ let base_url = url_for('dashboard.system_statistics');
+ base_url += '/' + sid;
+ base_url += (did > 0) ? ('/' + did) : '';
+ base_url += '?chart_names=' + chart_names.join(',');
+
+ return base_url;
+}
+
+/* This will process incoming charts data add it the previous charts
+ * data to get the new state.
+ */
+export function statsReducer(state, action) {
+
+ if(action.reset) {
+ return action.reset;
+ }
+
+ if(!action.incoming) {
+ return state;
+ }
+
+ if(!action.counterData) {
+ action.counterData = action.incoming;
+ }
+
+ let newState = {};
+ Object.keys(action.incoming).forEach(label => {
+ if(state[label]) {
+ newState[label] = [
+ action.counter ? action.incoming[label] - action.counterData[label] : action.incoming[label],
+ ...state[label].slice(0, X_AXIS_LENGTH-1),
+ ];
+ } else {
+ newState[label] = [
+ action.counter ? action.incoming[label] - action.counterData[label] : action.incoming[label],
+ ];
+ }
+ });
+ return newState;
+}
+
+const chartsDefault = {
+ 'm_stats': {'Total': [], 'Used': [], 'Free': []},
+ 'sm_stats': {'Total': [], 'Used': [], 'Free': []},
+ 'pmu_stats': {},
+};
+
+export default function Memory({preferences, sid, did, pageVisible, enablePoll=true}) {
+ const refreshOn = useRef(null);
+ const prevPrefernces = usePrevious(preferences);
+
+ const [memoryUsageInfo, memoryUsageInfoReduce] = useReducer(statsReducer, chartsDefault['m_stats']);
+ const [swapMemoryUsageInfo, swapMemoryUsageInfoReduce] = useReducer(statsReducer, chartsDefault['sm_stats']);
+ const [processMemoryUsageStats, setProcessMemoryUsageStats] = useState([]);
+
+ const [, setCounterData] = useState({});
+
+ const [pollDelay, setPollDelay] = useState(5000);
+ const [errorMsg, setErrorMsg] = useState(null);
+ const [chartDrawnOnce, setChartDrawnOnce] = useState(false);
+