forked from loadavg/loadavg
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclass.Logger.php
executable file
·438 lines (312 loc) · 10.3 KB
/
class.Logger.php
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
<?php
/**
* LoadAvg - Server Monitoring & Analytics
* http://www.loadavg.com
*
* Main controller class for LoadAvg 2.0
*
* @link https://github.com/loadavg/loadavg
* @author Karsten Becker
* @copyright 2014 Sputnik7
*
* This file is licensed under the Affero General Public License version 3 or
* later.
*/
class Logger
{
public static $_settings; // storing standard settings and/or loaded modules settings
public static $_classes; // storing loaded modules classes
public static $_modules; // storing and managing modules
public static $_plugins; // storing and managing plugins
public static $current_date; // current date
public static $settings_ini;
/**
* setSettings
*
* Stores the standard settings
*
* @param string $module name of the module
* @param array $args array of module settings
*/
public function setSettings($module, $args)
{
@self::$_settings->$module = $args;
}
public function __construct()
{
date_default_timezone_set("UTC");
self::$settings_ini = "settings.ini.php";
$this->setSettings('general',
parse_ini_file(APP_PATH . '/config/' . self::$settings_ini, true)
);
//get the date and timezone - logger uses server time or override
date_default_timezone_set(self::$_settings->general['settings']['timezone']);
//do we use this ? loggger is always current ?
self::$current_date = (isset($_GET['logdate']) && !empty($_GET['logdate'])) ? $_GET['logdate'] : date("Y-m-d");
//generate list of all modules
LoadUtility::generateExtensionList( 'modules', self::$_modules );
//load all charting modules that are enabled
LoadUtility::loadExtensions( 'modules', self::$_settings, self::$_classes, self::$_modules, true);
//generate list of all modules
LoadUtility::generateExtensionList( 'plugins', self::$_modules );
//load all charting modules that are enabled
LoadUtility::loadExtensions( 'plugins', self::$_settings, self::$_classes, self::$_modules, true);
/*
//generate list of all modules
//$this->generateModuleList('modules');
//generate list of all modules
LoadUtility::generateExtensionList( 'plugins', self::$_plugins );
//load all charting modules that are enabled
LoadUtility::loadExtensions( 'plugins', self::$_settings, self::$_classes, self::$_plugins, true);
//load all charting modules that are enabled
//$this->loadModules('modules');
*/
}
/**
* getDates
*
* Gets date range from logfiles to populate the select box from topbar
* Also used to check for old log files in logger
*
* @return array $return array with list of dates
*/
//grabs dates of ALL log files to be safe but would be faster if it did just one module
public static function getDates()
{
$dates = array();
foreach ( glob( HOME_PATH . "/logs/*.log") as $file ) {
//find files with number format only
preg_match("/([0-9-]+)/", basename($file), $output_array);
if ( isset( $output_array[0] ) && !empty( $output_array[0] ) )
$dates[] = $output_array[0];
}
//get rid of all duplicate dates
$dates = array_unique($dates);
//need to properly sort the array before returning it
asort ($dates);
return $dates;
}
/**
* getLoggerInterval
*
* Gets the timing for the logger from system settings and returns it in seconds
*
*/
public function getLoggerInterval( )
{
$interval = Logger::$_settings->general['settings']['logger_interval'];
if ( $interval ) {
$interval = $interval * 60;
return $interval;
} else {
//default is 5 minutes if no interval use that
return 300;
}
}
//called via array_map below to delete files and directories
public function cleanFiles($filename) {
//echo "removing : " . $filename . "\n";
if (! is_dir($filename)) {
unlink($filename);
}
else
$this->deleteDir($filename);
}
/**
* rotateLogFiles
*
* rotates the log files out by deleting old files older than @daystokeep
*
*/
public function rotateLogFiles ($logdir)
{
//echo "ROTATE \n";
$fromDate = strtotime("-". Logger::$_settings->general['settings']['daystokeep'] ." days 00:00:00");
//echo "fromDate " . $fromDate . "\n";
$dates = $this->getDates();
foreach ( $dates as $date ) {
$date = strtotime($date);
if ($date < $fromDate) {
$mask = $logdir . "*_" . date("Y-m-d", $date) . "*.log";
echo "MASK " . $date . " " . $mask . "\n";
//var_dump ( glob( $mask ) );
//array_map( 'unlink', glob( $mask ) );
//array_map( 'cleanFiles', glob( $mask ) );
array_map( array('Logger','cleanFiles') , glob( $mask ));
}
}
}
//used by cleanFiles above for deleting directories
public static function deleteDir($dirPath) {
if (! is_dir($dirPath)) {
throw new InvalidArgumentException("$dirPath must be a directory");
}
if (substr($dirPath, strlen($dirPath) - 1, 1) != '/') {
$dirPath .= '/';
}
$files = glob($dirPath . '*', GLOB_MARK);
foreach ($files as $file) {
if (is_dir($file)) {
self::deleteDir($file);
} else {
unlink($file);
}
}
rmdir($dirPath);
}
/*
* used to test if log files are being created by logger
* needs better testing currently a bit of a hack
* as we just test if the log directory is empty or not
*/
function testLogs( $mode = true)
{
$loadedModules = self::$_settings->general['modules'];
$logdir = HOME_PATH . '/' . self::$_settings->general['settings']['logs_dir'];
$test_worked = false;
$test_nested = false;
if ( LoadUtility::is_dir_empty($logdir))
return false;
// Check for each module we have loadedModules
foreach ( $loadedModules as $module => $value ) {
if ( $value == "false" ) continue;
$moduleSettings = Logger::$_settings->$module;
// Check if loadedModules module needs loggable capabilities
if ( $moduleSettings['module']['logable'] == "true" ) {
foreach ( $moduleSettings['logging']['args'] as $args) {
$args = json_decode($args);
$class = Logger::$_classes[$module];
$caller = $args->function;
//skip network interfaces as they have nested logs and work differently
//later need to skip all nested logs as we check those below
if ( $args->logfile == "network_%s_%s.log" )
{
$test_nested = true;
}
else
{
$filename = ( $logdir . sprintf($args->logfile, date('Y-m-d')) );
if (file_exists($filename)) {
$test_worked = true;
}
if ($mode == true)
echo "Log: $filename Status: $test_worked \n";
}
}
}
}
if ($test_nested == true) {
//now do nested charts
foreach (Logger::$_settings->general['network_interface'] as $interface => $value) {
if ( !( isset(Logger::$_settings->general['network_interface'][$interface])
&& Logger::$_settings->general['network_interface'][$interface] == "true" ) )
continue;
$filename = ( $logdir . sprintf($args->logfile, date('Y-m-d') , $interface ) );
if (file_exists($filename)) {
$test_worked = true;
}
if ($mode == true)
echo "Log: $filename Status: $test_worked \n";
}
}
return $test_worked;
}
/**
* sendApiData
*
* If API is activated sends data to server
*
* @param array $data array of data to send to the server
* @return string $result message returned from the server
*/
public function sendApiData( $data ) {
// for debugging
//var_dump($data); //exit;
//echo 'DEBUG: ' . json_encode($data);
$url = self::$_settings->general['api']['url'];
$user_url = $url . '/users/';
$server_url = $url . '/servers/';
//validate API access here
if ( self::$_settings->general['api']['server_token'] && self::$_settings->general['api']['key'] ) {
$ch = curl_init($server_url . self::$_settings->general['api']['server_token'] . '/' . self::$_settings->general['api']['key'] . '/v');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$account_valid = curl_exec($ch);
} else
$account_valid = 'false';
//get server id from server token
if ( self::$_settings->general['api']['server_token'] ) {
$ch = curl_init($server_url . self::$_settings->general['api']['server_token'] . '/t');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$server_exists = curl_exec($ch);
} else
$server_exists = 'false';
//echo $server_url.json_decode($server_exists)->id.'/data';
//validation needs to happen on the sever this is still insecure!
//need to pass api token and server token over in data push
if( $server_exists != 'false' && $account_valid != 'false' )
{
//file_put_contents("file.txt", json_encode($data)); test data
$curl = curl_init();
// Set some options - we are passing in a useragent too here
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => $server_url.json_decode($server_exists)->id.'/data',
CURLOPT_USERAGENT => 'LoadAvg Client',
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => array(
'data' => json_encode($data),
)
));
// Send the request & save response to $resp
$resp = curl_exec($curl);
// Close request to clear up some resources
curl_close($curl);
//used for debugging to file
//file_put_contents("file.txt",$resp);
return true;
}
return null;
}
/**
* getProcStats
*
* parses /proc/stat and returns line $theLine
* move this out into utility functions later on
*
*/
public function getProcStats (array &$data, $theLine = 0)
{
//we grab data from proc/stat in one pass as it changes as you read it
$stats = file('/proc/stat');
//if array is emoty we didnt work
if($stats === array())
return false;
//echo 'STATS:' . $stats[1];
//grab cpu data
$data = explode(" ", preg_replace("!cpu +!", "", $stats[$theLine]));
return true;
}
/**
* testLoggerCore
*
* see if things are set up corectly and we are logging
*
*/
public function testLoggerCore ($api = false)
{
$logger_status = $this->testLogs();
if ( $logger_status )
echo "The logger appears to be running \n";
else
echo "The logger does not seem to be running \n";
// Sending data to API server
if ( $api ) {
echo "API Active, Testing API \n";
$apistatus = $this->testApiConnection(true);
if ( $apistatus )
echo "The API appears to be running \n";
else
echo "The API does not seem to be running \n";
}
}
}