AdminInterface.php 14.5 KB
Newer Older
Dominik Hebeler's avatar
Dominik Hebeler committed
1
2
3
4
<?php

namespace App\Http\Controllers;

5
use App\Jobs\ConvertCountFile;
Dominik Hebeler's avatar
Dominik Hebeler committed
6
use Carbon\Carbon;
Dominik Hebeler's avatar
Dominik Hebeler committed
7
use Illuminate\Http\Request;
8
use Illuminate\Support\Facades\Redis;
9
use Response;
Dominik Hebeler's avatar
Dominik Hebeler committed
10
11
12

class AdminInterface extends Controller
{
Dominik Hebeler's avatar
Dominik Hebeler committed
13
    public function index(Request $request)
14
15
16
17
18
19
20
    {
        // Let's get the stats for this server.
        // First we need to check, which Fetcher could be available by parsing the sumas.xml
        $names = $this->getSearchEngineNames();

        // Now we gonna check which stats we can find
        $stati = array();
Dominik Hebeler's avatar
Dominik Hebeler committed
21
        foreach ($names as $name) {
22
            $stats = Redis::hgetall($name . ".stats");
Dominik Hebeler's avatar
Dominik Hebeler committed
23
            if (sizeof($stats) > 0) {
24
25
                $fetcherStatus = Redis::get($name);
                $stati[$name]["status"] = $fetcherStatus;
Dominik Hebeler's avatar
Dominik Hebeler committed
26
27
                foreach ($stats as $pid => $value) {
                    if (strstr($value, ";")) {
28
29
                        $value = explode(";", $value);
                        $connection = json_decode(base64_decode($value[0]), true);
Dominik Hebeler's avatar
Dominik Hebeler committed
30
31
                        foreach ($connection as $key => $val) {
                            if (strstr($key, "_time")) {
32
                                $stati[$name]["fetcher"][$pid]["connection"][$key] = $val;
Dominik Hebeler's avatar
Dominik Hebeler committed
33
34
                            }

35
36
37
                        }
                        $stati[$name]["fetcher"][$pid]["poptime"] = $value[1];
                    }
Dominik Hebeler's avatar
Dominik Hebeler committed
38
                }
39
40
            }
        }
Dominik Hebeler's avatar
Dominik Hebeler committed
41

42
        // So now we can generate Median Times for every Fetcher
Dominik Hebeler's avatar
Dominik Hebeler committed
43
        $fetcherCount = 0;
Dominik Hebeler's avatar
Dominik Hebeler committed
44
        foreach ($stati as $engineName => $engineStats) {
45
46
            $connection = array();
            $poptime = 0;
Dominik Hebeler's avatar
Dominik Hebeler committed
47
            $fetcherCount += sizeof($engineStats["fetcher"]);
Dominik Hebeler's avatar
Dominik Hebeler committed
48
49
50
            foreach ($engineStats["fetcher"] as $pid => $stats) {
                foreach ($stats["connection"] as $key => $value) {
                    if (!isset($connection[$key])) {
51
                        $connection[$key] = $value;
Dominik Hebeler's avatar
Dominik Hebeler committed
52
                    } else {
53
54
55
56
                        $connection[$key] += $value;
                    }
                }
                $poptime += floatval($stats["poptime"]);
57
            }
Dominik Hebeler's avatar
Dominik Hebeler committed
58
            foreach ($connection as $key => $value) {
59
60
61
62
63
64
                $connection[$key] /= sizeof($engineStats["fetcher"]);
            }
            $poptime /= sizeof($engineStats["fetcher"]);

            $stati[$engineName]["median-connection"] = $connection;
            $stati[$engineName]["median-poptime"] = $poptime;
Dominik Hebeler's avatar
Dominik Hebeler committed
65
        }
66

Dominik Hebeler's avatar
Dominik Hebeler committed
67
        return view('admin.admin')
68
            ->with('title', 'Fetcher Status')
Dominik Hebeler's avatar
Dominik Hebeler committed
69
70
            ->with('stati', $stati)
            ->with('fetcherCount', $fetcherCount);
71
72
73
74
75
76
        $stati = json_encode($stati);
        $response = Response::make($stati, 200);
        $response->header("Content-Type", "application/json");
        return $response;
    }

Dominik Hebeler's avatar
Dominik Hebeler committed
77
78
    private function getSearchEngineNames()
    {
79
        $url = config_path() . "/sumas.xml";
Dominik Hebeler's avatar
Dominik Hebeler committed
80
        $xml = \simplexml_load_file($url);
81
82
83
        $sumas = $xml->xpath("suma");

        $names = array();
Dominik Hebeler's avatar
Dominik Hebeler committed
84
        foreach ($sumas as $suma) {
85
86
87
            $names[] = $suma["name"]->__toString();
        }
        return $names;
Dominik Hebeler's avatar
Dominik Hebeler committed
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
    private function convertLogs()
    {
        $oldLogsPath = \storage_path("logs/metager/old/");
        $dir = new \DirectoryIterator($oldLogsPath);
        foreach ($dir as $fileinfo) {
            if ($fileinfo->isDot()) {
                continue;
            }
            $filename = $oldLogsPath . "/" . $fileinfo->getFilename();
            $daysAgo = substr($fileinfo->getFilename(), strrpos($fileinfo->getFilename(), ".") + 1);
            $dateOfFile = Carbon::now()->subDays($daysAgo);
            $outputFile = \storage_path("logs/metager/" . $dateOfFile->format("Y/m/d") . ".log");
            if (!file_exists(dirname($outputFile))) {
                \mkdir(dirname($outputFile), 0777, true);
            }
            $fhw = fopen($outputFile, "w");
            $fhr = fopen($filename, "r");
            try {
                $first = true;
                while (($line = fgets($fhr)) != false) {
                    $date = trim(substr($line, 0, strpos($line, "]")), "[");
                    $date = trim(substr($date, strrpos($date, " ")));
                    $rest = trim(substr($line, strpos($line, "]") + 1));
                    $outputString = "";
                    if (!$first) {
                        $outputString .= PHP_EOL;
                    }
                    $outputString .= $date . " " . $rest;
                    $first = false;
                    fwrite($fhw, $outputString);
                }
            } finally {
                fclose($fhw);
                fclose($fhr);
            }
        }
    }

128
    public function count(Request $request)
129
    {
130
131
        #$this->convertLogs();
        #return;
132
        $days = intval($request->input('days', 28));
Dominik Hebeler's avatar
Dominik Hebeler committed
133
134
135
136
        $interface = $request->input('interface', 'all');
        if (!is_int($days) || $days <= 0) {
            $days = 28;
        }
Dominik Hebeler's avatar
Dominik Hebeler committed
137
        $logs = $this->getStats($days);
Dominik Hebeler's avatar
Dominik Hebeler committed
138

Dominik Hebeler's avatar
Dominik Hebeler committed
139
140
        $oldLogs = [];
        $rekordTag = 0;
141
        $rekordTagSameTime = 0;
Dominik Hebeler's avatar
Dominik Hebeler committed
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
        $minCount = 0;
        $rekordTagDate = "";
        $size = 0;
        $count = 0;

        $now = Carbon::now()->subMinutes(Carbon::now()->minute % 5)->format('H:i');
        if ($now === "00:00") {
            $now = "00:05";
        }

        foreach ($logs as $key => $stats) {
            if ($key === 0) {
                // Log for today
                $logToday = empty($stats->insgesamt->{$interface}) ? 0 : $stats->insgesamt->{$interface};
                continue;
            }
            $insgesamt = empty($stats->insgesamt->{$interface}) ? 0 : $stats->insgesamt->{$interface};
            $sameTime = empty($stats->time->{$now}->{$interface}) ? 0 : $stats->time->{$now}->{$interface};

            if ($insgesamt > $rekordTag) {
                $rekordTag = $insgesamt;
                $rekordTagSameTime = $sameTime;
                $rekordTagDate = Carbon::now()->subDays($key)->format('d.m.Y');
            }
            if ($minCount === 0 || $insgesamt < $minCount) {
                $minCount = $insgesamt;
            }
            $oldLogs[$key]['sameTime'] = number_format(floatval($sameTime), 0, ",", ".");
            $oldLogs[$key]['insgesamt'] = number_format(floatval($insgesamt), 0, ",", ".");
            # Nun noch den median:
            $count += $insgesamt;
            $size++;
            if ($size > 0) {
                $oldLogs[$key]['median'] = number_format(floatval(round($count / $size)), 0, ",", ".");
            }

        }

        if ($request->input('out', 'web') === "web") {
            return view('admin.count')
                ->with('title', 'Suchanfragen - MetaGer')
                ->with('today', number_format(floatval($logToday), 0, ",", "."))
                ->with('oldLogs', $oldLogs)
                ->with('minCount', $minCount)
                ->with('rekordCount', number_format(floatval($rekordTag), 0, ",", "."))
                ->with('rekordTagSameTime', number_format(floatval($rekordTagSameTime), 0, ",", "."))
                ->with('rekordDate', $rekordTagDate)
                ->with('days', $days);
        } else {
            $result = "";
            foreach ($oldLogs as $key => $value) {
                $resultTmp = '"' . date("D, d M y", mktime(date("H"), date("i"), date("s"), date("m"), date("d") - $key, date("Y"))) . '",';
                $resultTmp .= '"' . $value['sameTime'] . '",';
                $resultTmp .= '"' . $value['insgesamt'] . '",';
                $resultTmp .= '"' . $value['median'] . '"' . "\r\n";
                $result = $resultTmp . $result;
            }
            return response($result, 200)
                ->header('Content-Type', 'text/csv')
                ->header('Content-Disposition', 'attachment; filename="count.csv"');

        }

    }

    public function countGraphToday()
    {
        $stats = $this->getStats(0)[0];

        $hourly = [];
        $previous = 0;
        $max = 0;
        foreach ($stats->time as $time => $timeStats) {
            $hour = intval(substr($time, 0, strpos($time, ":")));
            if (empty($hourly[$hour])) {
                $hourly[$hour] = 0;
            }
            $hourly[$hour] += $timeStats->all - $previous;
            $previous = $timeStats->all;
            if ($hourly[$hour] > $max) {
                $max = $hourly[$hour];
            }
        }
        $result = [
            "insgesamt" => $stats->insgesamt->all,
            "max" => $max,
            "hourly" => $hourly,
        ];

        return response()
            ->view('admin.countGraphToday', ["data" => $result], 200)
            ->header('Content-Type', "image/svg+xml");

    }

Dominik Hebeler's avatar
Dominik Hebeler committed
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
    public function engineStats()
    {
        $result = [];
        $result["loadavg"] = sys_getloadavg();

        // Memory Data
        $data = explode("\n", trim(file_get_contents("/proc/meminfo")));
        $meminfo = [];
        foreach ($data as $line) {
            list($key, $val) = explode(":", $line);
            $meminfo[$key] = trim($val);
        }
        $conversions = [
            "KB",
            "MB",
            "GB",
            "TB",
        ];

        $memAvailable = $meminfo["MemAvailable"];
        $memAvailable = intval(explode(" ", $memAvailable)[0]);
        $counter = 0;
        while ($memAvailable > 1000) {
            $memAvailable /= 1000.0;
            $counter++;
        }
        $memAvailable = round($memAvailable);
        $memAvailable .= " " . $conversions[$counter];

        $result["memoryAvailable"] = $memAvailable;

        $resultCount = 0;
        $file = "/var/log/metager/mg3.log";
        if (file_exists($file)) {
            $fh = fopen($file, "r");
            try {
                while (fgets($fh) !== false) {
                    $resultCount++;
                }
            } finally {
                fclose($fh);
            }
        }

        $result["resultCount"] = number_format($resultCount, 0, ",", ".");
        return response()->json($result);
    }

Dominik Hebeler's avatar
Dominik Hebeler committed
285
286
    private function getStats($days)
    {
287
288
289
290
291
292
        $maxDate = Carbon::createFromFormat('d.m.Y', "28.06.2016");
        $selectedDate = Carbon::now()->subDays($days);
        if ($maxDate > $selectedDate) {
            $days = $maxDate->diffInDays(Carbon::now());
        }

293
        $logToday = \App\MetaGer::getMGLogFile();
Dominik Hebeler's avatar
Dominik Hebeler committed
294

295
        $archivePath = storage_path("logs/metager/");
296
297
298

        $today = [
            'logFile' => $logToday,
299
300
            'countPath' => storage_path('logs/metager/count/'),
            'countFile' => storage_path('logs/metager/count/' . getmypid()),
301
302
303
304
305
306
307
308
309
310
311
312
313
314
        ];
        if (\file_exists($today["countFile"])) {
            unlink($today["countFile"]);
        }

        $neededLogs = [
            0 => $today,
        ];
        $logsToRequest = [
            0 => $today,
        ];
        $requestedLogs = [];
        for ($i = 1; $i <= $days; $i++) {
            $date = Carbon::now()->subDays($i);
315
            $countPath = storage_path('logs/metager/count/' . $date->format("Y/m") . "/");
316
317
            $countFile = $countPath . $date->day . ".json";
            $neededLogs[$i] = [
318
                'logFile' => $archivePath . $date->format("Y/m/d") . ".log",
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
                'countPath' => $countPath,
                'countFile' => $countFile,
            ];
            if (!file_exists($neededLogs[$i]['countFile'])) {
                $logsToRequest[$i] = $neededLogs[$i];
            }
        }
        if (sizeof($logsToRequest) > 100) {
            set_time_limit(600);
        }
        // Create the Jobs for count file creation
        while (sizeof($logsToRequest) > 0 || sizeof($requestedLogs) > 0) {
            if (sizeof($requestedLogs) < 20 && sizeof($logsToRequest) > 0) {
                $newJob = array_shift($logsToRequest);
                $newJob["startedAt"] = time();
                $requestedLogs[] = $newJob;

                Redis::set(md5($newJob["countFile"]), "running");
                Redis::expire(md5($newJob["countFile"]), 15);
                ConvertCountFile::dispatch($newJob);
Dominik Hebeler's avatar
Dominik Hebeler committed
339
            } else {
340
                usleep(50000);
Dominik Hebeler's avatar
Dominik Hebeler committed
341
            }
342
343
344
345
346
347
348
349
350
351
352
353
            // Remove all finished Jobs
            $removedOne = false;
            do {
                $removedOne = false;
                foreach ($requestedLogs as $index => $requestedLog) {
                    if (!Redis::exists(md5($requestedLog["countFile"]))) {
                        unset($requestedLogs[$index]);
                        $removedOne = true;
                        break;
                    }
                }
            } while ($removedOne === true);
354
        }
355

Dominik Hebeler's avatar
Dominik Hebeler committed
356
        $result = [];
357
358
359
360

        foreach ($neededLogs as $key => $value) {
            $countFile = $value["countFile"];
            if (file_exists($countFile)) {
Dominik Hebeler's avatar
Dominik Hebeler committed
361
                $result[$key] = json_decode(file_get_contents($countFile));
362
            }
363
364
        }

Dominik Hebeler's avatar
Dominik Hebeler committed
365
366
        if (\file_exists($today["countFile"])) {
            unlink($today["countFile"]);
367
368
        }

Dominik Hebeler's avatar
Dominik Hebeler committed
369
        return $result;
370
    }
Dominik Hebeler's avatar
Dominik Hebeler committed
371

Dominik Hebeler's avatar
Dominik Hebeler committed
372
    public function check()
373
    {
Dominik Hebeler's avatar
Dominik Hebeler committed
374
        $q = "";
375
376
377
378
379
380
381
382
383
384
385
        $logpath = \App\MetaGer::getMGLogFile();

        if (file_exists($logpath)) {
            $fp = @fopen($logpath, "r");
            while (($line = fgets($fp)) !== false) {
                if (!empty($line)) {
                    $q = $line;
                }
            }
            fclose($fp);
            $q = substr($q, strpos($q, "eingabe=") + 8);
386
387
388
389
390
        }
        return view('admin.check')
            ->with('title', 'Wer sucht was? - MetaGer')
            ->with('q', $q);
    }
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

    public function engines()
    {
        # Wir laden den Inhalt der Log Datei und übergeben ihn an den view
        $file = "/var/log/metager/engine.log";
        if (file_exists($file) && is_readable($file)) {
            $engineStats = file_get_contents($file);
            # Daten vom JSON Format dekodieren
            $engineStats = json_decode($engineStats, true);

            # Eine Sortierung wäre nicht das verkehrteste
            uasort($engineStats["recent"], function ($a, $b) {
                if ($a["requests"] == $b["requests"]) {
                    return 0;
                }

                return ($a["requests"] < $b["requests"]) ? 1 : -1;
            });

            uasort($engineStats["overall"], function ($a, $b) {
                if ($a["requests"] == $b["requests"]) {
                    return 0;
                }

                return ($a["requests"] < $b["requests"]) ? 1 : -1;
            });
            return view('admin.engines')
                ->with('engineStats', $engineStats)
                ->with('title', "Suchmaschinenstatus - MetaGer");
        } else {
            return redirect(url('admin'));
        }
    }
Dominik Hebeler's avatar
Dominik Hebeler committed
424
}