-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathperformance_monitoring_demo.cpp
More file actions
340 lines (270 loc) Β· 14.3 KB
/
Copy pathperformance_monitoring_demo.cpp
File metadata and controls
340 lines (270 loc) Β· 14.3 KB
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
// BSD 3-Clause License
// Copyright (c) 2025, πβππ₯ π
// See the LICENSE file in the project root for full license information.
/**
* @file performance_monitoring_demo.cpp
* @brief Performance monitoring with real-time metrics, analysis, and alerting
* @example performance_monitoring_demo.cpp
*
* Demonstrates the performance monitoring framework:
* - Basic system metrics collection (CPU, memory, disk I/O, network I/O)
* - Query performance tracking with slow-query detection
* - Connection pool monitoring and utilization analysis
* - Real-time performance dashboards with periodic snapshots
* - Performance report generation with optimization recommendations
* - Multi-format metrics export (Prometheus, JSON, CSV)
* - Configurable alerting system with severity levels
*/
#include <iostream>
#include <string>
#include <chrono>
#include <thread>
#include <memory>
#include <random>
#include "database/database_manager.h"
#include "database/core/database_context.h"
#include "database/monitoring/performance_monitor.h"
using namespace database;
using namespace database::monitoring;
void demonstrate_basic_metrics(std::shared_ptr<database_context> context) {
std::cout << "=== Basic Performance Metrics Demonstration ===\n";
// Initialize performance monitor via dependency injection
auto monitor = context->get_performance_monitor();
// Configure monitoring settings
monitoring_config config;
config.enable_query_tracking = true;
config.enable_connection_tracking = true;
config.slow_query_threshold = std::chrono::milliseconds(100);
config.alert_threshold_cpu = 80.0;
config.alert_threshold_memory = 85.0;
monitor->configure(config);
std::cout << "Performance monitoring configured with:\n";
std::cout << " - Query tracking: enabled\n";
std::cout << " - Connection tracking: enabled\n";
std::cout << " - Slow query threshold: 100ms\n";
std::cout << " - CPU alert threshold: 80%\n";
std::cout << " - Memory alert threshold: 85%\n";
// Get current system metrics
const auto& system_metrics = monitor->get_system_metrics();
std::cout << "\nCurrent System Metrics:\n";
std::cout << " CPU Usage: " << system_metrics.cpu_usage_percent << "%\n";
std::cout << " Memory Usage: " << system_metrics.memory_usage_percent << "%\n";
std::cout << " Disk I/O: " << system_metrics.disk_io_bytes_per_sec << " bytes/sec\n";
std::cout << " Network I/O: " << system_metrics.network_io_bytes_per_sec << " bytes/sec\n";
}
void demonstrate_query_metrics(std::shared_ptr<database_context> context) {
std::cout << "\n=== Query Performance Tracking ===\n";
auto monitor = context->get_performance_monitor();
// Simulate various database queries with different performance characteristics
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<> query_time_dist(10, 200);
std::uniform_int_distribution<> success_rate(1, 100);
std::cout << "Simulating database queries...\n";
for (int i = 0; i < 20; ++i) {
std::string query_type = (i % 4 == 0) ? "SELECT" :
(i % 4 == 1) ? "INSERT" :
(i % 4 == 2) ? "UPDATE" : "DELETE";
auto start_time = std::chrono::high_resolution_clock::now();
// Simulate query execution time
auto execution_time = std::chrono::milliseconds(query_time_dist(gen));
std::this_thread::sleep_for(execution_time);
auto end_time = std::chrono::high_resolution_clock::now();
bool success = success_rate(gen) > 5; // 95% success rate
// Record query metrics
query_metrics metrics;
metrics.query_type = query_type;
metrics.execution_time = execution_time;
metrics.success = success;
metrics.rows_affected = success ? (i * 3 + 1) : 0;
metrics.timestamp = start_time;
monitor->record_query_execution(metrics);
std::cout << " Query " << (i+1) << " (" << query_type << "): "
<< execution_time.count() << "ms, "
<< (success ? "SUCCESS" : "FAILED") << "\n";
}
// Display aggregated query statistics
std::cout << "\nQuery Performance Summary:\n";
const auto& query_stats = monitor->get_query_statistics();
std::cout << " Total Queries: " << query_stats.total_queries << "\n";
std::cout << " Successful Queries: " << query_stats.successful_queries << "\n";
std::cout << " Failed Queries: " << query_stats.failed_queries << "\n";
std::cout << " Success Rate: " <<
(100.0 * query_stats.successful_queries / query_stats.total_queries) << "%\n";
std::cout << " Average Execution Time: " <<
query_stats.average_execution_time.count() << "ms\n";
std::cout << " Slow Queries Detected: " << query_stats.slow_queries_count << "\n";
}
void demonstrate_connection_pool_metrics(std::shared_ptr<database_context> context) {
std::cout << "\n=== Connection Pool Performance Monitoring ===\n";
auto monitor = context->get_performance_monitor();
// Simulate connection pool activity
std::cout << "Simulating connection pool operations...\n";
for (int i = 0; i < 15; ++i) {
// Simulate getting connection from pool
auto start_time = std::chrono::high_resolution_clock::now();
// Simulate connection acquisition time
std::this_thread::sleep_for(std::chrono::milliseconds(5 + (i % 3) * 10));
auto end_time = std::chrono::high_resolution_clock::now();
connection_metrics metrics;
metrics.total_connections.store(20);
metrics.active_connections.store(8 + (i % 5));
metrics.idle_connections.store(metrics.total_connections.load() - metrics.active_connections.load());
metrics.connections_created.store(25 + i);
metrics.connections_destroyed.store(5 + (i / 5));
metrics.connection_errors.store(i / 10);
metrics.average_wait_time = std::chrono::duration_cast<std::chrono::milliseconds>(end_time - start_time);
metrics.peak_connections.store(std::max(static_cast<size_t>(20), metrics.active_connections.load()));
monitor->record_connection_metrics(metrics);
std::cout << " Pool State " << (i+1) << ": "
<< metrics.active_connections.load() << "/"
<< metrics.total_connections.load() << " active, "
<< "wait time: " << metrics.average_wait_time.count() << "ms\n";
}
// Display connection pool statistics
std::cout << "\nConnection Pool Performance Summary:\n";
const auto& pool_stats = monitor->get_connection_pool_statistics();
std::cout << " Pool Utilization: " << pool_stats.utilization_percentage << "%\n";
std::cout << " Average Wait Time: " << pool_stats.average_wait_time.count() << "ms\n";
std::cout << " Peak Connections: " << pool_stats.peak_connections << "\n";
std::cout << " Connection Errors: " << pool_stats.connection_errors << "\n";
std::cout << " Pool Efficiency Score: " << pool_stats.efficiency_score << "/100\n";
}
void demonstrate_real_time_monitoring(std::shared_ptr<database_context> context) {
std::cout << "\n=== Real-Time Performance Monitoring ===\n";
auto monitor = context->get_performance_monitor();
std::cout << "Starting real-time monitoring (5 seconds)...\n";
auto start_time = std::chrono::steady_clock::now();
int update_count = 0;
while (std::chrono::steady_clock::now() - start_time < std::chrono::seconds(5)) {
std::this_thread::sleep_for(std::chrono::seconds(1));
update_count++;
// Get real-time metrics
const auto& system_metrics = monitor->get_system_metrics();
const auto& alerts = monitor->get_active_alerts();
std::cout << "\n[" << update_count << "s] Real-time Status:\n";
std::cout << " CPU: " << system_metrics.cpu_usage_percent << "%, "
<< "Memory: " << system_metrics.memory_usage_percent << "%, "
<< "Active Alerts: " << alerts.size() << "\n";
// Display any active alerts
for (const auto& alert : alerts) {
std::cout << " β οΈ ALERT: " << alert.message
<< " (Severity: " << static_cast<int>(alert.severity) << ")\n";
}
if (alerts.empty()) {
std::cout << " β
All systems normal\n";
}
}
}
void demonstrate_performance_analysis(std::shared_ptr<database_context> context) {
std::cout << "\n=== Performance Analysis and Reporting ===\n";
auto monitor = context->get_performance_monitor();
// Generate performance report
std::cout << "Generating comprehensive performance report...\n";
const auto& report = monitor->generate_performance_report();
std::cout << "\nπ Performance Report Summary:\n";
std::cout << " Report Period: " << report.report_period_minutes << " minutes\n";
std::cout << " Total Operations: " << report.total_operations << "\n";
std::cout << " Average Response Time: " << report.average_response_time.count() << "ms\n";
std::cout << " Peak Throughput: " << report.peak_throughput_ops_per_sec << " ops/sec\n";
std::cout << " Error Rate: " << report.error_rate_percentage << "%\n";
std::cout << "\nπ Top Performance Insights:\n";
for (const auto& insight : report.performance_insights) {
std::cout << " β’ " << insight << "\n";
}
std::cout << "\nπ§ Optimization Recommendations:\n";
for (const auto& recommendation : report.recommendations) {
std::cout << " β " << recommendation << "\n";
}
}
void demonstrate_metrics_export(std::shared_ptr<database_context> context) {
std::cout << "\n=== Metrics Export for External Monitoring ===\n";
auto monitor = context->get_performance_monitor();
std::cout << "Exporting metrics in various formats...\n";
// Export Prometheus metrics
std::cout << "\n--- Prometheus Metrics Format ---\n";
const auto prometheus_metrics = monitor->export_prometheus_metrics();
std::cout << prometheus_metrics.substr(0, 300) << "...\n";
// Export JSON metrics
std::cout << "\n--- JSON Metrics Format ---\n";
const auto json_metrics = monitor->export_json_metrics();
std::cout << json_metrics.substr(0, 200) << "...\n";
// Export CSV metrics for analysis
std::cout << "\n--- CSV Export for Analysis ---\n";
const auto csv_data = monitor->export_csv_metrics();
std::cout << "CSV data exported: " << csv_data.size() << " bytes\n";
std::cout << "First few lines:\n";
auto first_newline = csv_data.find('\n', csv_data.find('\n') + 1);
std::cout << csv_data.substr(0, first_newline) << "\n";
std::cout << "\nMetrics can be integrated with:\n";
std::cout << " β’ Prometheus + Grafana for visualization\n";
std::cout << " β’ ELK Stack for log analysis\n";
std::cout << " β’ Custom monitoring dashboards\n";
std::cout << " β’ Third-party APM solutions\n";
}
void demonstrate_alerting_system(std::shared_ptr<database_context> context) {
std::cout << "\n=== Alerting and Notification System ===\n";
auto monitor = context->get_performance_monitor();
// Configure alert rules
alert_rule cpu_rule;
cpu_rule.metric_name = "cpu_usage_percent";
cpu_rule.threshold_value = 75.0;
cpu_rule.comparison = alert_comparison::greater_than;
cpu_rule.severity = alert_severity::warning;
cpu_rule.message = "High CPU usage detected";
alert_rule memory_rule;
memory_rule.metric_name = "memory_usage_percent";
memory_rule.threshold_value = 90.0;
memory_rule.comparison = alert_comparison::greater_than;
memory_rule.severity = alert_severity::critical;
memory_rule.message = "Critical memory usage level";
monitor->add_alert_rule(cpu_rule);
monitor->add_alert_rule(memory_rule);
std::cout << "Configured alert rules:\n";
std::cout << " β’ CPU usage > 75% (Warning)\n";
std::cout << " β’ Memory usage > 90% (Critical)\n";
// Simulate threshold breaches
std::cout << "\nSimulating alert conditions...\n";
// The monitoring system would automatically trigger alerts
// based on real system metrics or simulated conditions
std::cout << "Alert system is active and monitoring thresholds.\n";
std::cout << "In production, alerts would be sent via:\n";
std::cout << " β’ Email notifications\n";
std::cout << " β’ Slack/Teams integration\n";
std::cout << " β’ SMS alerts for critical issues\n";
std::cout << " β’ Webhook notifications to external systems\n";
}
int main() {
std::cout << "=== Performance Monitoring Framework Demonstration ===\n";
std::cout << "This sample demonstrates comprehensive performance monitoring\n";
std::cout << "capabilities for database operations and system resources.\n";
try {
// Initialize database context with dependency injection
auto context = std::make_shared<database_context>();
demonstrate_basic_metrics(context);
demonstrate_query_metrics(context);
demonstrate_connection_pool_metrics(context);
demonstrate_real_time_monitoring(context);
demonstrate_performance_analysis(context);
demonstrate_metrics_export(context);
demonstrate_alerting_system(context);
std::cout << "\n=== Performance Monitoring Features Summary ===\n";
std::cout << "β Real-time system and database metrics collection\n";
std::cout << "β Query performance tracking and analysis\n";
std::cout << "β Connection pool monitoring and optimization\n";
std::cout << "β Slow query detection and alerting\n";
std::cout << "β Performance trend analysis and reporting\n";
std::cout << "β Multi-format metrics export (Prometheus, JSON, CSV)\n";
std::cout << "β Configurable alerting with multiple severity levels\n";
std::cout << "β Integration with external monitoring systems\n";
std::cout << "\nFor production deployment:\n";
std::cout << " auto context = std::make_shared<database_context>();\n";
std::cout << " auto monitor = context->get_performance_monitor();\n";
std::cout << " monitor->configure(your_config);\n";
std::cout << " // Metrics are automatically collected during database operations\n";
} catch (const std::exception& e) {
std::cout << "Error: " << e.what() << std::endl;
return 1;
}
return 0;
}