-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathStatsManager.cpp
644 lines (537 loc) · 19.7 KB
/
StatsManager.cpp
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
/*
*
* (C) 2013-14 - ntop.org
*
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
*/
#include "ntop_includes.h"
#ifdef WIN32
/*
The strndup function copies not more than n characters (characters that
follow a null character are not copied) from string to a dynamically
allocated buffer. The copied string shall always be null terminated.
*/
char *strndup(const char *string, size_t s)
{
char *p, *r;
if (string == NULL)
return NULL;
p = (char*)string;
while (s > 0) {
if (*p == 0)
break;
p++;
s--;
}
s = (p - string);
r = (char*) malloc(1 + s);
if (r) {
strncpy(r, string, s);
r[s] = 0;
}
return r;
}
#endif
StatsManager::StatsManager(int ifid, const char *filename) {
char filePath[MAX_PATH], fileFullPath[MAX_PATH], fileName[MAX_PATH];
this->ifid = ifid, db = NULL;
MINUTE_CACHE_NAME = "MINUTE_STATS";
HOUR_CACHE_NAME = "HOUR_STATS";
DAY_CACHE_NAME = "DAY_STATS";
snprintf(filePath, sizeof(filePath), "%s/%d/top_talkers/",
ntop->get_working_dir(), ifid);
strncpy(fileName, filename, sizeof(fileName));
snprintf(fileFullPath, sizeof(fileFullPath), "%s/%d/top_talkers/%s",
ntop->get_working_dir(), ifid, filename);
ntop->fixPath(filePath);
ntop->fixPath(fileFullPath);
if(!Utils::mkdir_tree(filePath)) {
ntop->getTrace()->traceEvent(TRACE_WARNING,
"Unable to create directory %s", filePath);
return;
}
if (sqlite3_open(fileFullPath, &db)) {
ntop->getTrace()->traceEvent(TRACE_WARNING, "Unable to open %s: %s",
fileFullPath, sqlite3_errmsg(db));
db = NULL;
}
}
StatsManager::~StatsManager() {
if (db) sqlite3_close(db);
}
/**
* @brief Executes a database query on an already opened SQLite3 DB
* @brief This function implements handling of a direct query on
* a SQLite3 database, hiding DB-specific syntax and error
* handling.
*
* @param db_query A string keeping the query to be executed.
* @param callback Callback to be executed by the DB in case the query
* execution is successful.
* @param payload A pointer to be passed to the callback in case it
* is actually executed.
*
* @return Zero in case of success, nonzero in case of failure.
*/
int StatsManager::exec_query(char *db_query,
int (*callback)(void *, int, char **, char **),
void *payload) {
char *zErrMsg = 0;
if (!db) return(-1);
if(sqlite3_exec(db, db_query, callback, payload, &zErrMsg)) {
printf("SQL error: %s\n", sqlite3_errmsg(db));
ntop->getTrace()->traceEvent(TRACE_INFO, "SQL Error: %s", zErrMsg);
sqlite3_free(zErrMsg);
return 1;
}
return 0;
}
/**
* @brief Opens a new cache to be used to store statistics.
* @brief This function implements opening a new cache to store stats
* in; it is as of now based on SQLite3, and equals a new cache
* to a new table.
*
* @param cache_name Name of the cache to be opened.
*
* @return Zero in case of success, nonzero in case of failure.
*/
int StatsManager::openCache(const char *cache_name)
{
char table_query[MAX_QUERY];
int rc;
if (!db)
return 1;
if (caches[cache_name])
return 0;
snprintf(table_query, sizeof(table_query),
"CREATE TABLE IF NOT EXISTS %s "
"(TSTAMP VARCHAR PRIMARY KEY NOT NULL,"
"STATS TEXT NOT NULL);", cache_name);
m.lock(__FILE__, __LINE__);
rc = exec_query(table_query, NULL, NULL);
if (!rc)
caches[cache_name] = true;
m.unlock(__FILE__, __LINE__);
return rc;
}
/**
* @brief Database interface to implement stats purging.
* @details This function implements the database-specific code
* to delete stats older than a certain number of days.
*
* @todo Compute years better.
*
* @param cache_name Name of the cache to purge statistics from.
* @param key Key to use as boundary.
* @return Zero in case of success, nonzero in case of error.
*/
int StatsManager::deleteStatsOlderThan(const char *cache_name,
const int key) {
char query[MAX_QUERY];
int rc;
if (!db)
return -1;
if (openCache(cache_name))
return -1;
snprintf(query, sizeof(query), "DELETE FROM %s WHERE "
"CAST(TSTAMP AS INTEGER) < %d",
cache_name, key);
m.lock(__FILE__, __LINE__);
rc = exec_query(query, NULL, NULL);
m.unlock(__FILE__, __LINE__);
return rc;
}
/**
* @brief Minute stats interface to database purging.
* @details This function hides cache-specific details (e.g. building the key
* for the minute stats cache.
*
* @param num_days Number of days to use to purge statistics.
* @return Zero in case of success, nonzero in case of error.
*/
int StatsManager::deleteMinuteStatsOlderThan(unsigned num_days) {
time_t rawtime;
time(&rawtime);
rawtime -= rawtime % 60;
rawtime -= num_days * 24 * 60 * 60;
return deleteStatsOlderThan(MINUTE_CACHE_NAME, rawtime);
}
/**
* @brief Hour stats interface to database purging.
* @details This function hides cache-specific details (e.g. building the key
* for the hour stats cache.
*
* @param num_days Number of days to use to purge statistics.
* @return Zero in case of success, nonzero in case of error.
*/
int StatsManager::deleteHourStatsOlderThan(unsigned num_days) {
time_t rawtime;
time(&rawtime);
rawtime -= rawtime % 60;
rawtime -= num_days * 24 * 60 * 60;
return deleteStatsOlderThan(HOUR_CACHE_NAME, rawtime);
}
/**
* @brief Day stats interface to database purging.
* @details This function hides cache-specific details (e.g. building the key
* for the day stats cache.
*
* @param num_days Number of days to use to purge statistics.
* @return Zero in case of success, nonzero in case of error.
*/
int StatsManager::deleteDayStatsOlderThan(unsigned num_days) {
time_t rawtime;
time(&rawtime);
rawtime -= rawtime % 60;
rawtime -= num_days * 24 * 60 * 60;
return deleteStatsOlderThan(DAY_CACHE_NAME, rawtime);
}
struct statsManagerRetrieval {
vector<string> rows;
int num_vals;
};
/**
* @brief Callback for completion of retrieval of an interval of stats
*
* @param data Pointer to exchange data used by SQLite and the callback.
* @param argc Number of retrieved columns.
* @param argv Content of retrieved columns.
* @param azColName Retrieved columns name.
*
* @return Zero in case of success, nonzero in case of error.
*/
static int get_samplings_db(void *data, int argc,
char **argv, char **azColName) {
struct statsManagerRetrieval *retr = (struct statsManagerRetrieval *)data;
if (argc > 1) return -1;
retr->rows.push_back(argv[0]);
retr->num_vals++;
return 0;
}
/**
* @brief Retrieve an interval of samplings from a database
* @details This function implements the database-specific code
* to retrieve an interval of samplings.
*
* @param vals Pointer to a string array that will keep the result.
* @param num_vals Pointer to an integer that will keep the number
* of retrieved sampling points.
* @param cache_name Pointer to the name of the cache to retrieve
* stats from.
* @param key_start Key to use as left boundary.
* @param key_end Key to use as right boundary.
*
* @return Zero in case of success, nonzero in case of error.
*/
int StatsManager::retrieveStatsInterval(char ***vals,
int *num_vals,
const char *cache_name,
const int key_start,
const int key_end) {
char query[MAX_QUERY];
struct statsManagerRetrieval retvals;
vector<string> rows;
int rc;
if (!db)
return -1;
if (openCache(cache_name))
return -1;
memset(&retvals, 0, sizeof(retvals));
snprintf(query, sizeof(query), "SELECT STATS FROM %s WHERE TSTAMP >= %d "
"AND TSTAMP <= %d",
cache_name, key_start, key_end);
m.lock(__FILE__, __LINE__);
rc = exec_query(query, get_samplings_db, (void *)&retvals);
m.unlock(__FILE__, __LINE__);
if (retvals.num_vals > 0)
*vals = (char**) malloc(retvals.num_vals * sizeof(char*));
for (unsigned i = 0 ; i < retvals.rows.size() ; i++)
(*vals)[i] = strndup(retvals.rows[i].c_str(), MAX_QUERY);
*num_vals = retvals.num_vals;
return rc;
}
/**
* @brief Retrieve an interval of samplings from the minute stats cache
* @details This function implements the database-specific code
* to retrieve an interval of samplings masking out cache-specific
* details concerning the minute stats cache.
*
* @param epoch_start Left boundary of the interval.
* @param epoch_end Right boundary of the interval.
* @param vals Pointer to a string array that will keep the result.
* @param num_vals Pointer to an integer that will keep the number
* of retrieved sampling points.
*
* @return Zero in case of success, nonzero in case of error.
*/
int StatsManager::retrieveMinuteStatsInterval(time_t epoch_start,
time_t epoch_end,
char ***vals,
int *num_vals) {
if (!vals || !num_vals)
return -1;
return retrieveStatsInterval(vals, num_vals, MINUTE_CACHE_NAME, epoch_start, epoch_end);
}
/**
* @brief Retrieve an interval of samplings from the hour stats cache
* @details This function implements the database-specific code
* to retrieve an interval of samplings masking out cache-specific
* details concerning the hour stats cache.
*
* @param epoch_start Left boundary of the interval.
* @param epoch_end Right boundary of the interval.
* @param vals Pointer to a string array that will keep the result.
* @param num_vals Pointer to an integer that will keep the number
* of retrieved sampling points.
*
* @return Zero in case of success, nonzero in case of error.
*/
int StatsManager::retrieveHourStatsInterval(time_t epoch_start,
time_t epoch_end,
char ***vals,
int *num_vals) {
if (!vals || !num_vals)
return -1;
return retrieveStatsInterval(vals, num_vals, HOUR_CACHE_NAME, epoch_start, epoch_end);
}
/**
* @brief Retrieve an interval of samplings from the day stats cache
* @details This function implements the database-specific code
* to retrieve an interval of samplings masking out cache-specific
* details concerning the day stats cache.
*
* @param epoch_start Left boundary of the interval.
* @param epoch_end Right boundary of the interval.
* @param vals Pointer to a string array that will keep the result.
* @param num_vals Pointer to an integer that will keep the number
* of retrieved sampling points.
*
* @return Zero in case of success, nonzero in case of error.
*/
int StatsManager::retrieveDayStatsInterval(time_t epoch_start,
time_t epoch_end,
char ***vals,
int *num_vals) {
if (!vals || !num_vals)
return -1;
return retrieveStatsInterval(vals, num_vals, DAY_CACHE_NAME, epoch_start, epoch_end);
}
/**
* @brief Database interface to add a new stats sampling
* @details This function implements the database-specific layer for
* the historical database (as of now using SQLite3).
*
* @param sampling String to be written at specified sampling point.
* @param cache_name Name of the table to write the entry to.
* @param key Key to use to insert the sampling.
*
* @return Zero in case of success, nonzero in case of error.
*/
int StatsManager::insertSampling(char *sampling, const char *cache_name,
const int key) {
char query[MAX_QUERY];
sqlite3_stmt *stmt;
int rc = 0;
if (!db)
return -1;
if (openCache(cache_name))
return -1;
snprintf(query, sizeof(query), "INSERT INTO %s (TSTAMP, STATS) VALUES(?,?)",
cache_name);
m.lock(__FILE__, __LINE__);
if (sqlite3_prepare(db, query, -1, &stmt, 0) ||
sqlite3_bind_int(stmt, 1, key) ||
sqlite3_bind_text(stmt, 2, sampling, strlen(sampling), SQLITE_TRANSIENT)) {
rc = 1;
goto out_unlock;
}
while((rc = sqlite3_step(stmt)) != SQLITE_DONE) {
if (rc == SQLITE_ERROR) {
ntop->getTrace()->traceEvent(TRACE_INFO, "SQL Error: step");
rc = 1;
goto out;
}
}
rc = 0;
out:
sqlite3_finalize(stmt);
out_unlock:
m.unlock(__FILE__, __LINE__);
return rc;
}
/**
* @brief Interface function for insertion of a new minute stats sampling
* @details This public method implements insertion of a new sampling,
* hiding cache-specific details related to minute stats.
*
* @param timeinfo The sampling point expressed in localtime format.
* @param sampling Pointer to a string keeping the sampling.
*
* @return Zero in case of success, nonzero in case of failure.
*/
int StatsManager::insertMinuteSampling(time_t epoch, char *sampling) {
if (!sampling)
return -1;
return insertSampling(sampling, MINUTE_CACHE_NAME, epoch);
}
/**
* @brief Interface function for insertion of a new hour stats sampling
* @details This public method implements insertion of a new sampling,
* hiding cache-specific details related to hour stats.
*
* @param timeinfo The sampling point expressed in localtime format.
* @param sampling Pointer to a string keeping the sampling.
*
* @return Zero in case of success, nonzero in case of failure.
*/
int StatsManager::insertHourSampling(time_t epoch, char *sampling) {
if (!sampling)
return -1;
return insertSampling(sampling, HOUR_CACHE_NAME, epoch);
}
/**
* @brief Interface function for insertion of a new day stats sampling
* @details This public method implements insertion of a new sampling,
* hiding cache-specific details related to day stats.
*
* @param timeinfo The sampling point expressed in localtime format.
* @param sampling Pointer to a string keeping the sampling.
*
* @return Zero in case of success, nonzero in case of failure.
*/
int StatsManager::insertDaySampling(time_t epoch, char *sampling) {
if (!sampling)
return -1;
return insertSampling(sampling, DAY_CACHE_NAME, epoch);
}
/* *************************************************************** */
/**
* @brief Callback for completion of minute stats retrieval.
*
* @param data Pointer to exchange data used by SQLite and the callback.
* @param argc Number of retrieved columns.
* @param argv Content of retrieved columns.
* @param azColName Retrieved columns name.
*
* @return Zero in case of success, nonzero in case of error.
*/
static int get_sampling_db_callback(void *data, int argc,
char **argv, char **azColName) {
string *buffer = (string *)data;
if (argc > 1)
ntop->getTrace()->traceEvent(TRACE_INFO, "%s: more than one row (%d) returned",
__FUNCTION__, argc);
buffer->assign(argv[0]);
return 0;
}
/**
* @brief Database interface to retrieve a stats sampling
* @details This function implements the database-specific layer for
* the historical database (as of now using SQLite3).
*
* @param sampling Pointer to a string to be filled with retrieved data.
* @param cache_name Name of the cache to retrieve stats from.
* @param key_low Base key used to retrieve the sampling.
* @param key_high End key used to retrieve the sampling.
*
* @return Zero in case of success, nonzero in case of error.
*/
int StatsManager::getSampling(string *sampling, const char *cache_name,
const int key_low, const int key_high) {
char query[MAX_QUERY];
int rc;
*sampling = "[ ]";
if (!db)
return -1;
if (openCache(cache_name))
return -1;
snprintf(query, sizeof(query), "SELECT STATS FROM %s WHERE "
"CAST(TSTAMP AS INTEGER) <= %d AND "
"CAST(TSTAMP AS INTEGER) >= %d",
cache_name, key_high, key_low);
m.lock(__FILE__, __LINE__);
rc = exec_query(query, get_sampling_db_callback, (void *)sampling);
m.unlock(__FILE__, __LINE__);
return rc;
}
/**
* @brief Database interface to retrieve a sampling timestamp
* @details This function implements the database-specific layer to
* retrieve a timestamp for the historical interface.
*
* @param sampling Pointer to a string to be filled with retrieved data.
* @param cache_name Name of the cache to retrieve stats from.
* @param key_low Base epoch used for retrieval
* @param key_high Final epoch used for retrieval
*
* @return Zero in case of success, nonzero in case of error.
*/
int StatsManager::getRealEpoch(string *real_epoch, const char *cache_name,
const int key_low, const int key_high) {
char query[MAX_QUERY];
int rc;
*real_epoch = "0";
if (!db)
return -1;
if (openCache(cache_name))
return -1;
snprintf(query, sizeof(query), "SELECT TSTAMP FROM %s WHERE "
"CAST(TSTAMP AS INTEGER) <= %d AND "
"CAST(TSTAMP AS INTEGER) >= %d",
cache_name, key_high, key_low);
m.lock(__FILE__, __LINE__);
rc = exec_query(query, get_sampling_db_callback, (void *)real_epoch);
m.unlock(__FILE__, __LINE__);
return rc;
}
/**
* @brief Interface function for retrieval of a minute stats sampling
* @details This public method implements retrieval of an existing
* sampling, hiding cache-specific details related to minute stats.
*
* @param epoch The sampling point expressed as number of seconds
* from epoch.
* @param sampling Pointer to a string to be filled with the sampling.
*
* @return Zero in case of success, nonzero in case of failure.
*/
int StatsManager::getMinuteSampling(time_t epoch, string *sampling) {
if (!sampling)
return -1;
int epoch_start = epoch - (epoch % 60);
int epoch_end = epoch_start + 59;
return getSampling(sampling, MINUTE_CACHE_NAME, epoch_start, epoch_end);
}
/**
* @brief Interface function for retrieval of a real epoch from minute stats
* @details This public method implements retrieval of an existing
* sampling, hiding cache-specific details related to minute stats.
*
* @param epoch The sampling point expressed as number of seconds
* from epoch.
* @param sampling Pointer to a string to be filled with the sampling.
*
* @return Zero in case of success, nonzero in case of failure.
*/
int StatsManager::getMinuteRealEpoch(time_t epoch, string *real_epoch) {
if (!real_epoch)
return -1;
int epoch_start = epoch - (epoch % 60);
int epoch_end = epoch_start + 59;
return getRealEpoch(real_epoch, MINUTE_CACHE_NAME, epoch_start, epoch_end);
}