-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdocker_dashboard_server.py
538 lines (477 loc) · 13.3 KB
/
docker_dashboard_server.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
import os
from flask import Flask, render_template_string, request
import json
from datetime import datetime
import pandas as pd
import subprocess
app = Flask(__name__)
HTML_TEMPLATE = """
<!DOCTYPE html>
<html>
<!-- [Previous head and style sections remain the same] -->
<head>
<title>Docker Stats Dashboard</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.0/chart.min.js"></script>
<style>
body {
font-family: Arial, sans-serif;
margin: 20px;
background-color: #f5f5f5;
}
.container {
max-width: 1200px;
margin: 0 auto;
}
.card {
background: white;
border-radius: 8px;
padding: 20px;
margin-bottom: 20px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
.charts-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 20px;
margin-bottom: 30px;
}
.chart-container {
height: 250px;
margin-bottom: 20px;
}
.stats-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
gap: 20px;
margin-bottom: 30px;
}
.metric {
padding: 15px;
border-radius: 8px;
background: #f8f9fa;
}
.metric h3 {
margin: 0 0 10px 0;
color: #333;
}
.metric p {
margin: 5px 0;
}
.refresh-button {
background: #007bff;
color: white;
border: none;
padding: 10px 20px;
border-radius: 4px;
cursor: pointer;
margin-bottom: 20px;
}
.refresh-button:hover {
background: #0056b3;
}
.last-update {
color: #666;
margin-bottom: 20px;
}
.controls {
display: flex;
align-items: center;
gap: 15px;
margin-bottom: 20px;
}
.line-count {
display: flex;
align-items: center;
gap: 10px;
}
.line-count input {
width: 100px;
padding: 8px;
border: 1px solid #ccc;
border-radius: 4px;
}
.line-count label {
color: #666;
}
</style>
</head>
<body>
<div class="container">
<h1>Docker Dashboard</h1>
<div class="controls">
<form action="/" method="get" class="line-count">
<label for="lines">Number of lines:</label>
<input type="number" id="lines" name="lines" value="{{ line_count }}" min="1">
<button type="submit" class="refresh-button">Refresh Data</button>
</form>
</div>
<p class="last-update">Last updated: {{ last_update }}</p>
<!-- [Rest of the template remains the same] -->
{% for container in containers %}
<div class="card">
<h2>{{ container.name }}</h2>
<div class="stats-grid">
<div class="metric">
<h3>CPU Usage</h3>
<p>Current: {{ container.current_cpu }}%</p>
<p>Average: {{ container.avg_cpu }}%</p>
</div>
<div class="metric">
<h3>Memory Usage</h3>
<p>Current: {{ container.current_memory.usage }} / {{ container.current_memory.limit }}</p>
<p>Usage (MB): {{ container.current_memory_mb }} MB</p>
<p>Limit (MB): {{ container.memory_limit_mb }} MB</p>
<p>Percentage: {{ container.current_memory.percent }}</p>
</div>
<div class="metric">
<h3>Network I/O</h3>
<p>Input: {{ container.current_network.input }}</p>
<p>Output: {{ container.current_network.output }}</p>
</div>
</div>
<div class="charts-grid">
<div class="chart-container">
<canvas id="cpuChart{{ loop.index }}"></canvas>
</div>
<div class="chart-container">
<canvas id="memChart{{ loop.index }}"></canvas>
</div>
<div class="chart-container">
<canvas id="netChart{{ loop.index }}"></canvas>
</div>
<div class="chart-container">
<canvas id="blockChart{{ loop.index }}"></canvas>
</div>
</div>
</div>
{% endfor %}
</div>
<script>
const chartOptions = {
responsive: true,
maintainAspectRatio: false,
plugins: {
legend: {
position: 'top',
align: 'start'
}
},
scales: {
y: {
beginAtZero: true,
position: 'left'
},
x: {
ticks: {
maxRotation: 45,
minRotation: 45
}
}
}
};
{% for container in containers %}
// CPU chart
new Chart(document.getElementById('cpuChart{{ loop.index }}').getContext('2d'), {
type: 'line',
data: {
labels: {{ container.timestamps | tojson }},
datasets: [{
label: 'CPU Usage (%)',
data: {{ container.cpu_history | tojson }},
borderColor: '#007bff',
tension: 0.1
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
plugins: {
legend: {
position: 'top',
align: 'start'
}
},
scales: {
y: {
type: 'linear',
display: true,
position: 'left',
beginAtZero: true,
title: {
display: true,
text: 'CPU %',
padding: { top: 10, bottom: 10 }
}
},
x: {
ticks: {
maxRotation: 45,
minRotation: 45
}
}
}
}});
// memory chart
new Chart(document.getElementById('memChart{{ loop.index }}').getContext('2d'), {
type: 'line',
data: {
labels: {{ container.timestamps | tojson }},
datasets: [{
label: 'Memory Usage (%)',
data: {{ container.memory_history | tojson }},
borderColor: '#28a745',
tension: 0.1,
yAxisID: 'percentage'
}, {
label: 'Memory Usage (MB)',
data: {{ container.memory_mb_history | tojson }},
borderColor: '#20c997',
tension: 0.1,
yAxisID: 'megabytes'
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
plugins: {
legend: {
position: 'top',
align: 'start'
}
},
scales: {
percentage: {
type: 'linear',
display: true,
position: 'left',
grid: {
drawOnChartArea: true
},
title: {
display: true,
text: 'Memory %',
padding: { top: 10, bottom: 10 }
}
},
megabytes: {
type: 'linear',
display: true,
position: 'right',
grid: {
drawOnChartArea: false
},
title: {
display: true,
text: 'Memory MB',
padding: { top: 10, bottom: 10 }
}
},
x: {
ticks: {
maxRotation: 45,
minRotation: 45
}
}
}
}});
// network I/O chart
new Chart(document.getElementById('netChart{{ loop.index }}').getContext('2d'), {
type: 'line',
data: {
labels: {{ container.timestamps | tojson }},
datasets: [{
label: 'Network Input',
data: {{ container.net_in_history | tojson }},
borderColor: '#dc3545',
tension: 0.1
}, {
label: 'Network Output',
data: {{ container.net_out_history | tojson }},
borderColor: '#fd7e14',
tension: 0.1
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
plugins: {
legend: {
position: 'top',
align: 'start'
}
},
scales: {
y: {
type: 'linear',
display: true,
position: 'left',
beginAtZero: true,
title: {
display: true,
text: 'Network I/O (MB)',
padding: { top: 10, bottom: 10 }
}
},
x: {
ticks: {
maxRotation: 45,
minRotation: 45
}
}
}
}});
// block I/O chart
new Chart(document.getElementById('blockChart{{ loop.index }}').getContext('2d'), {
type: 'line',
data: {
labels: {{ container.timestamps | tojson }},
datasets: [{
label: 'Block Input',
data: {{ container.block_in_history | tojson }},
borderColor: '#6610f2',
tension: 0.1
}, {
label: 'Block Output',
data: {{ container.block_out_history | tojson }},
borderColor: '#20c997',
tension: 0.1
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
plugins: {
legend: {
position: 'top',
align: 'start'
}
},
scales: {
y: {
type: 'linear',
display: true,
position: 'left',
beginAtZero: true,
title: {
display: true,
text: 'Block I/O (MB)',
padding: { top: 10, bottom: 10 }
}
},
x: {
ticks: {
maxRotation: 45,
minRotation: 45
}
}
}
}});
{% endfor %}
</script>
</body>
</html>
"""
def convert_to_mb(size_str):
size_str = size_str.upper()
number = float("".join(filter(lambda x: x.isdigit() or x == ".", size_str)))
if "KIB" in size_str or "KB" in size_str:
return number / 1024
elif "MIB" in size_str or "MB" in size_str:
return number
elif "GIB" in size_str or "GB" in size_str:
return number * 1024
return number
def parse_stats_file(file_path):
data = []
with open(file_path, "r") as f:
for line in f:
data.append(json.loads(line))
return data
def process_container_data(data):
df = pd.DataFrame(data)
containers = []
for name, group in df.groupby("name"):
group = group.sort_values("timestamp")
cpu_values = [float(str(cpu).rstrip("%")) for cpu in group["cpu_percent"]]
# memory
memory_values = [
float(str(mem["percent"]).rstrip("%")) for mem in group["memory"]
]
memory_mb_values = [convert_to_mb(mem["usage"]) for mem in group["memory"]]
# network I/O
net_in_values = [convert_to_mb(net["input"]) for net in group["network"]]
net_out_values = [convert_to_mb(net["output"]) for net in group["network"]]
# block I/O
block_in_values = [convert_to_mb(block["input"]) for block in group["block_io"]]
block_out_values = [
convert_to_mb(block["output"]) for block in group["block_io"]
]
timestamps = [
datetime.strptime(ts, "%Y-%m-%dT%H:%M:%SZ").strftime("%H:%M")
for ts in group["timestamp"]
]
latest = group.iloc[-1]
current_memory_mb = convert_to_mb(latest["memory"]["usage"])
memory_limit_mb = convert_to_mb(latest["memory"]["limit"])
containers.append(
{
"name": name,
"current_cpu": latest["cpu_percent"],
"avg_cpu": f"{sum(cpu_values) / len(cpu_values):.2f}",
"current_memory": latest["memory"],
"current_memory_mb": f"{current_memory_mb:.2f}",
"memory_limit_mb": f"{memory_limit_mb:.2f}",
"current_network": latest["network"],
"timestamps": timestamps,
"cpu_history": cpu_values,
"memory_history": memory_values,
"memory_mb_history": memory_mb_values,
"net_in_history": net_in_values,
"net_out_history": net_out_values,
"block_in_history": block_in_values,
"block_out_history": block_out_values,
}
)
containers.sort(key=lambda x: x["name"], reverse=True)
return containers
last_update = None
def fetch_remote_logs(remote_alias, remote_path, line_count=None):
"""Fetch logs from remote server using SSH and tail"""
try:
if line_count:
command = f"ssh {remote_alias} 'sudo tail -n {line_count} {remote_path}'"
else:
command = f"ssh {remote_alias} 'sudo cat {remote_path}'"
result = subprocess.run(command, shell=True, capture_output=True, text=True)
if result.returncode != 0:
print(f"Error fetching logs: {result.stderr}")
return []
data = []
for line in result.stdout.splitlines():
if line.strip():
try:
data.append(json.loads(line))
except json.JSONDecodeError as e:
print(f"Error parsing JSON line: {e}")
continue
return data
except Exception as e:
print(f"Error executing SSH command: {e}")
return []
@app.route("/")
def dashboard():
remote_alias = "swecc-server"
remote_path = "/var/log/docker-stats.log"
line_count = request.args.get("lines", type=int)
data = fetch_remote_logs(remote_alias, remote_path, line_count)
if not data:
return "Error: Could not fetch log data from remote server.", 500
containers = process_container_data(data)
return render_template_string(
HTML_TEMPLATE,
containers=containers,
last_update=datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
line_count=line_count or "",
)
if __name__ == "__main__":
app.run(debug=True, host="0.0.0.0", port=3000)