Passed
Push — develop ( f46262...cc5787 )
by Nikolay
07:20 queued 11s
created

LogsManagementProcessor::getLogFromFile()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 27
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 21
c 0
b 0
f 0
dl 0
loc 27
rs 9.584
cc 3
nc 4
nop 3
1
<?php
2
/**
3
 * Copyright © MIKO LLC - All Rights Reserved
4
 * Unauthorized copying of this file, via any medium is strictly prohibited
5
 * Proprietary and confidential
6
 * Written by Alexey Portnov, 8 2020
7
 */
8
9
namespace MikoPBX\PBXCoreREST\Lib;
10
11
use MikoPBX\Core\System\Network;
12
use MikoPBX\Core\System\System;
13
use MikoPBX\Core\System\Util;
14
use Phalcon\Di;
15
use Phalcon\Di\Injectable;
16
17
class LogsManagementProcessor extends Injectable
18
{
19
    public const DEFAULT_FILENAME = 'asterisk/messages';
20
21
    /**
22
     * Стартует запись логов.
23
     *
24
     * @param int $timeout
25
     *
26
     * @return \MikoPBX\PBXCoreREST\Lib\PBXApiResult
27
     * @throws \Exception
28
     */
29
    public static function startLog($timeout = 300): PBXApiResult
30
    {
31
        $res = new PBXApiResult();
32
        $res->processor = __METHOD__;
33
        self::stopLog();
34
        $dir_all_log = System::getLogDir();
35
        $findPath    = Util::which('find');
36
        Util::mwExec("{$findPath} {$dir_all_log}" . '/ -name *_start_all_log* | xargs rm -rf');
37
        // Получим каталог с логами.
38
        $dirlog = $dir_all_log . '/dir_start_all_log';
39
        Util::mwMkdir($dirlog);
40
41
        $pingPath = Util::which('ping');
42
        Util::mwExecBg("{$pingPath} 8.8.8.8 -w 2", "{$dirlog}/ping_8888.log");
43
        Util::mwExecBg("{$pingPath} ya.ru -w 2", "{$dirlog}/ping_8888.log");
44
45
        $opensslPath = Util::which('openssl');
46
        Util::mwExecBgWithTimeout(
47
            "{$opensslPath} s_client -connect lm.miko.ru:443 > {$dirlog}/openssl_lm_miko_ru.log",
48
            1
49
        );
50
        Util::mwExecBgWithTimeout(
51
            "{$opensslPath} s_client -connect lic.miko.ru:443 > {$dirlog}/openssl_lic_miko_ru.log",
52
            1
53
        );
54
        $routePath = Util::which('route');
55
        Util::mwExecBg("{$routePath} -n ", " {$dirlog}/rout_n.log");
56
57
        $asteriskPath = Util::which('asterisk');
58
        Util::mwExecBg("{$asteriskPath} -rx 'pjsip show registrations' ", " {$dirlog}/pjsip_show_registrations.log");
59
        Util::mwExecBg("{$asteriskPath} -rx 'pjsip show endpoints' ", " {$dirlog}/pjsip_show_endpoints.log");
60
        Util::mwExecBg("{$asteriskPath} -rx 'pjsip show contacts' ", " {$dirlog}/pjsip_show_contacts.log");
61
62
        $php_log = '/var/log/php_error.log';
63
        if (file_exists($php_log)) {
64
            $cpPath = Util::which('cp');
65
            Util::mwExec("{$cpPath} {$php_log} {$dirlog}");
66
        }
67
68
        $network     = new Network();
69
        $arr_eth     = $network->getInterfacesNames();
70
        $tcpdumpPath = Util::which('tcpdump');
71
        foreach ($arr_eth as $eth) {
72
            Util::mwExecBgWithTimeout(
73
                "{$tcpdumpPath} -i {$eth} -n -s 0 -vvv -w {$dirlog}/{$eth}.pcap",
74
                $timeout,
75
                "{$dirlog}/{$eth}_out.log"
76
            );
77
        }
78
        $res->success=true;
79
        return $res;
80
    }
81
82
    /**
83
     * Завершает запись логов.
84
     *
85
     * @return \MikoPBX\PBXCoreREST\Lib\PBXApiResult
86
     * @throws \Exception
87
     */
88
    public static function stopLog(): PBXApiResult
89
    {
90
        $res = new PBXApiResult();
91
        $res->processor = __METHOD__;
92
        $dir_all_log = System::getLogDir();
93
94
        Util::killByName('timeout');
95
        Util::killByName('tcpdump');
96
97
        $rmPath   = Util::which('rm');
98
        $findPath = Util::which('find');
99
        $za7Path  = Util::which('7za');
100
        $cpPath   = Util::which('cp');
101
        $chownPath   = Util::which('chown');
102
103
        $dirlog = $dir_all_log . '/dir_start_all_log';
104
        Util::mwMkdir($dirlog);
105
106
        $log_dir = System::getLogDir();
107
        Util::mwExec("{$cpPath} -R {$log_dir} {$dirlog}");
108
109
        $di         = Di::getDefault();
110
        $dirsConfig = $di->getShared('config');
111
112
        // Файл будет удален в cron скриптом cleaner_download_links.sh т.к. имя содержит "/temp-"
113
        // через 5 минут, если не будет занят процессом.
114
        $result     = $dirsConfig->path('core.tempDir') . '/temp-all-log-'.time().'.zip';
115
116
        if (file_exists($result)) {
117
            Util::mwExec("{$rmPath} -rf {$result}");
118
        }
119
        // Пакуем логи.
120
        Util::mwExec("{$za7Path} a -tzip -mx0 -spf '{$result}' '{$dirlog}'");
121
        // Удаляем логи. Оставляем только архив.
122
        Util::mwExec("{$findPath} {$dir_all_log}" . '/ -name *_start_all_log | xargs rm -rf');
123
124
        if (file_exists($dirlog)) {
125
            Util::mwExec("{$findPath} {$dirlog}" . '/ -name license.key | xargs rm -rf');
126
        }
127
        // Удаляем каталог логов.
128
        Util::mwExecBg("{$rmPath} -rf {$dirlog}");
129
130
131
        $uid = Util::generateRandomString(36);
132
        $di = Di::getDefault();
133
        $downloadLink = $di->getShared('config')->path('www.downloadCacheDir');
134
        $result_dir = "{$downloadLink}/{$uid}";
135
        Util::mwMkdir($result_dir);
136
        $link_name = md5($result) . '.' . Util::getExtensionOfFile($result);
137
        $lnPath = Util::which('ln');
138
139
        Util::mwExec("{$lnPath} -s {$result} {$result_dir}/{$link_name}");
140
        Util::mwExec("{$chownPath} www:www {$result_dir}/{$link_name}");
141
142
        $res->success=true;
143
        $res->data['filename'] = "{$uid}/{$link_name}";
144
        return $res;
145
    }
146
147
    /**
148
     * Returns list of log files to show them on web interface
149
     *
150
     * @return \MikoPBX\PBXCoreREST\Lib\PBXApiResult
151
     */
152
    public static function getLogsList(): PBXApiResult
153
    {
154
        $res = new PBXApiResult();
155
        $res->processor = __METHOD__;
156
        $logDir     = System::getLogDir();
157
        $filesList = [];
158
        $entries = FilesManagementProcessor::scanDirRecursively($logDir);
159
        $entries = array_merge(...$entries);
160
        foreach($entries as $entry) {
161
            $relativePath = str_ireplace($logDir. '/', '', $entry);
162
            $fileSize = ceil(filesize($entry)/1024);
163
            $filesList[$relativePath] =
164
            [
165
                'path'=> $relativePath,
166
                'size'=> "{$fileSize} kb",
167
                'default'=>($relativePath===self::DEFAULT_FILENAME)
168
            ];
169
        }
170
171
        ksort($filesList);
172
        $res->success=true;
173
        $res->data['files'] = $filesList;
174
        return $res;
175
    }
176
177
    /**
178
     * Gets log file content partially
179
     *
180
     * @param string $filename
181
     * @param string $filter
182
     * @param int    $lines
183
     *
184
     * @return PBXApiResult
185
     */
186
    public static function getLogFromFile($filename = 'messages', $filter = '', $lines = 500): PBXApiResult
187
    {
188
        $res = new PBXApiResult();
189
        $res->processor = __METHOD__;
190
        if ( ! file_exists($filename)) {
191
            $filename = System::getLogDir() . '/' . $filename;
192
        }
193
        if ( ! file_exists($filename)) {
194
            $res->success    = false;
195
            $res->messages[] = 'No access to the file ' . $filename;
196
        } else {
197
            $res->success = true;
198
            $cat          = Util::which('cat');
199
            $grep         = Util::which('grep');
200
            $tail         = Util::which('tail');
201
202
            $di          = Di::getDefault();
203
            $dirsConfig  = $di->getShared('config');
204
            $filenameTmp = $dirsConfig->path('www.downloadCacheDir') . '/' . __FUNCTION__ . '_' . time() . '.log';
205
            $cmd         = "{$cat} {$filename} | {$grep} " . escapeshellarg($filter) . " | $tail -n " . escapeshellarg(
206
                    $lines
207
                ) . "> $filenameTmp";
208
            Util::mwExec("$cmd; chown www:www $filenameTmp");
209
            $res->data['filename'] = $filenameTmp;
210
        }
211
212
        return $res;
213
    }
214
215
}