Total Complexity | 213 |
Total Lines | 1424 |
Duplicated Lines | 0 % |
Changes | 15 | ||
Bugs | 0 | Features | 0 |
Complex classes like Storage often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
While breaking up the class, it is a good idea to analyze how other classes use Storage, and based on these observations, apply Extract Interface, too.
1 | <?php |
||
44 | class Storage extends Di\Injectable |
||
45 | { |
||
46 | /** |
||
47 | * Возвращает директорию для хранения файлов записей разговоров. |
||
48 | * |
||
49 | * @return string |
||
50 | */ |
||
51 | public static function getMonitorDir(): string |
||
59 | } |
||
60 | |||
61 | /** |
||
62 | * Возвращает директорию для хранения media файлов. |
||
63 | * |
||
64 | * @return string |
||
65 | */ |
||
66 | public static function getMediaDir(): string |
||
74 | } |
||
75 | |||
76 | |||
77 | /** |
||
78 | * Прверяем является ли диск хранилищем. |
||
79 | * |
||
80 | * @param $device |
||
81 | * |
||
82 | * @return bool |
||
83 | */ |
||
84 | public static function isStorageDisk($device): bool |
||
85 | { |
||
86 | $result = false; |
||
87 | if (!file_exists($device)) { |
||
88 | return $result; |
||
89 | } |
||
90 | |||
91 | $tmp_dir = '/tmp/mnt_' . time(); |
||
92 | Util::mwMkdir($tmp_dir); |
||
93 | $out = []; |
||
94 | |||
95 | $storage = new self(); |
||
96 | $uid_part = 'UUID=' . $storage->getUuid($device) . ''; |
||
97 | $format = $storage->getFsType($device); |
||
98 | if ($format === '') { |
||
99 | return false; |
||
100 | } |
||
101 | $mountPath = Util::which('mount'); |
||
102 | $umountPath = Util::which('umount'); |
||
103 | $rmPath = Util::which('rm'); |
||
104 | |||
105 | Processes::mwExec("{$mountPath} -t {$format} {$uid_part} {$tmp_dir}", $out); |
||
106 | if (is_dir("{$tmp_dir}/mikopbx") && trim(implode('', $out)) === '') { |
||
107 | // $out - пустая строка, ошибок нет |
||
108 | // присутствует каталог mikopbx. |
||
109 | $result = true; |
||
110 | } |
||
111 | if (self::isStorageDiskMounted($device)) { |
||
112 | Processes::mwExec("{$umountPath} {$device}"); |
||
113 | } |
||
114 | |||
115 | if (!self::isStorageDiskMounted($device)) { |
||
116 | Processes::mwExec("{$rmPath} -rf '{$tmp_dir}'"); |
||
117 | } |
||
118 | |||
119 | return $result; |
||
120 | } |
||
121 | |||
122 | /** |
||
123 | * Получение идентификатора устройства. |
||
124 | * |
||
125 | * @param $device |
||
126 | * |
||
127 | * @return string |
||
128 | */ |
||
129 | public function getUuid($device): string |
||
130 | { |
||
131 | if (empty($device)) { |
||
132 | return ''; |
||
133 | } |
||
134 | $lsBlkPath = Util::which('lsblk'); |
||
135 | $busyboxPath = Util::which('busybox'); |
||
136 | |||
137 | $cmd = "{$lsBlkPath} -r -o NAME,UUID | {$busyboxPath} grep " . basename($device) . " | {$busyboxPath} cut -d ' ' -f 2"; |
||
138 | $res = Processes::mwExec($cmd, $output); |
||
139 | if ($res === 0 && count($output) > 0) { |
||
140 | $result = $output[0]; |
||
141 | } else { |
||
142 | $result = ''; |
||
143 | } |
||
144 | |||
145 | return $result; |
||
146 | } |
||
147 | |||
148 | /** |
||
149 | * Возвращает тип файловой системы блочного устройства. |
||
150 | * |
||
151 | * @param $device |
||
152 | * |
||
153 | * @return string |
||
154 | */ |
||
155 | public function getFsType($device): string |
||
175 | } |
||
176 | |||
177 | /** |
||
178 | * Moves predefined sound files to storage disk |
||
179 | * Changes SoundFiles records |
||
180 | */ |
||
181 | public static function moveReadOnlySoundsToStorage(): void |
||
208 | } |
||
209 | |||
210 | /** |
||
211 | * Copies MOH sound files to storage and creates record on SoundFiles table |
||
212 | */ |
||
213 | public static function copyMohFilesToStorage(): void |
||
214 | { |
||
215 | if(!self::isStorageDiskMounted()) { |
||
216 | return; |
||
217 | } |
||
218 | $di = Di::getDefault(); |
||
219 | if ($di === null) { |
||
220 | return; |
||
221 | } |
||
222 | $config = $di->getConfig(); |
||
223 | $oldMohDir = $config->path('asterisk.astvarlibdir') . '/sounds/moh'; |
||
224 | $currentMohDir = $config->path('asterisk.mohdir'); |
||
225 | if ( ! file_exists($oldMohDir)||Util::mwMkdir($currentMohDir)) { |
||
226 | return; |
||
227 | } |
||
228 | $files = scandir($oldMohDir); |
||
229 | foreach ($files as $file) { |
||
230 | if (in_array($file, ['.', '..'])) { |
||
231 | continue; |
||
232 | } |
||
233 | if (copy($oldMohDir.'/'.$file, $currentMohDir.'/'.$file)) { |
||
234 | $sound_file = new SoundFiles(); |
||
235 | $sound_file->path = $currentMohDir . '/' . $file; |
||
236 | $sound_file->category = SoundFiles::CATEGORY_MOH; |
||
237 | $sound_file->name = $file; |
||
238 | $sound_file->save(); |
||
239 | } |
||
240 | } |
||
241 | } |
||
242 | |||
243 | /** |
||
244 | * Проверка, смонтирован ли диск - хранилище. |
||
245 | * |
||
246 | * @param string $filter |
||
247 | * @param string $mount_dir |
||
248 | * |
||
249 | * @return bool |
||
250 | */ |
||
251 | public static function isStorageDiskMounted($filter = '', &$mount_dir = ''): bool |
||
282 | } |
||
283 | |||
284 | /** |
||
285 | * Монитирование каталога с удаленного сервера SFTP. |
||
286 | * |
||
287 | * @param $host |
||
288 | * @param int $port |
||
289 | * @param string $user |
||
290 | * @param string $pass |
||
291 | * @param string $remout_dir |
||
292 | * @param string $local_dir |
||
293 | * |
||
294 | * @return bool |
||
295 | */ |
||
296 | public static function mountSftpDisk($host, $port, $user, $pass, $remout_dir, $local_dir): bool |
||
313 | } |
||
314 | |||
315 | /** |
||
316 | * Монитирование каталога с удаленного сервера FTP. |
||
317 | * |
||
318 | * @param $host |
||
319 | * @param $port |
||
320 | * @param $user |
||
321 | * @param $pass |
||
322 | * @param string $remout_dir |
||
323 | * @param $local_dir |
||
324 | * |
||
325 | * @return bool |
||
326 | */ |
||
327 | public static function mountFtp($host, $port, $user, $pass, $remout_dir, $local_dir): bool |
||
361 | } |
||
362 | |||
363 | /** |
||
364 | * Монитирование каталога с удаленного сервера FTP. |
||
365 | * |
||
366 | * @param $host |
||
367 | * @param $user |
||
368 | * @param $pass |
||
369 | * @param $dstDir |
||
370 | * @param $local_dir |
||
371 | * |
||
372 | * @return bool |
||
373 | */ |
||
374 | public static function mountWebDav($host, $user, $pass, $dstDir, $local_dir): bool |
||
375 | { |
||
376 | $host = trim($host); |
||
377 | $dstDir = trim($dstDir); |
||
378 | if(substr($host, -1) === '/'){ |
||
379 | $host = substr($host, 0, -1); |
||
380 | } |
||
381 | if($dstDir[0] === '/'){ |
||
382 | $dstDir = substr($dstDir, 1); |
||
383 | } |
||
384 | Util::mwMkdir($local_dir); |
||
385 | $out = []; |
||
386 | $conf = 'dav_user www'.PHP_EOL. |
||
387 | 'dav_group www'.PHP_EOL; |
||
388 | |||
389 | file_put_contents('/etc/davfs2/secrets', "{$host}{$dstDir} $user $pass"); |
||
390 | file_put_contents('/etc/davfs2/davfs2.conf', $conf); |
||
391 | $timeoutPath = Util::which('timeout'); |
||
392 | $mount = Util::which('mount.davfs'); |
||
393 | $command = "$timeoutPath 3 yes | $mount {$host}{$dstDir} {$local_dir}"; |
||
394 | Processes::mwExec($command, $out); |
||
395 | $response = trim(implode('', $out)); |
||
396 | if ('Terminated' === $response) { |
||
397 | // Удаленный сервер не ответил / или не корректно указан пароль. |
||
398 | unset($response); |
||
399 | } |
||
400 | return self::isStorageDiskMounted("$local_dir "); |
||
401 | } |
||
402 | |||
403 | /** |
||
404 | * Запускает процесс форматирования диска. |
||
405 | * |
||
406 | * @param $dev |
||
407 | * |
||
408 | * @return array|bool |
||
409 | */ |
||
410 | public static function mkfs_disk($dev) |
||
411 | { |
||
412 | if (!file_exists($dev)) { |
||
413 | $dev = "/dev/{$dev}"; |
||
414 | } |
||
415 | if (!file_exists($dev)) { |
||
416 | return false; |
||
417 | } |
||
418 | $dir = ''; |
||
419 | self::isStorageDiskMounted($dev, $dir); |
||
420 | |||
421 | if (empty($dir) || self::umountDisk($dir)) { |
||
422 | // Диск размонтирован. |
||
423 | $st = new Storage(); |
||
424 | // Будет запущен процесс: |
||
425 | $st->formatDiskLocal($dev, true); |
||
426 | sleep(1); |
||
427 | |||
428 | return (self::statusMkfs($dev) === 'inprogress'); |
||
429 | } |
||
430 | |||
431 | // Ошибка размонтирования диска. |
||
432 | return false; |
||
433 | } |
||
434 | |||
435 | /** |
||
436 | * Размонтирует диск. Удаляет каталог в случае успеха. |
||
437 | * |
||
438 | * @param $dir |
||
439 | * |
||
440 | * @return bool |
||
441 | */ |
||
442 | public static function umountDisk($dir): bool |
||
443 | { |
||
444 | $umountPath = Util::which('umount'); |
||
445 | $rmPath = Util::which('rm'); |
||
446 | if (self::isStorageDiskMounted($dir)) { |
||
447 | Processes::mwExec("/sbin/shell_functions.sh 'killprocesses' '$dir' -TERM 0"); |
||
448 | Processes::mwExec("{$umountPath} {$dir}"); |
||
449 | } |
||
450 | $result = ! self::isStorageDiskMounted($dir); |
||
451 | if ($result && file_exists($dir)) { |
||
452 | // Если диск не смонтирован, то удаляем каталог. |
||
453 | Processes::mwExec("{$rmPath} -rf '{$dir}'"); |
||
454 | } |
||
455 | |||
456 | return $result; |
||
457 | } |
||
458 | |||
459 | /** |
||
460 | * Разметка диска. |
||
461 | * |
||
462 | * @param string $device |
||
463 | * @param bool $bg |
||
464 | * |
||
465 | * @return mixed |
||
466 | */ |
||
467 | public function formatDiskLocal($device, $bg = false) |
||
468 | { |
||
469 | $partedPath = Util::which('parted'); |
||
470 | $retVal = Processes::mwExec( |
||
471 | "{$partedPath} --script --align optimal '{$device}' 'mklabel msdos mkpart primary ext4 0% 100%'" |
||
472 | ); |
||
473 | Util::sysLogMsg(__CLASS__, "{$partedPath} returned {$retVal}"); |
||
474 | if (false === $bg) { |
||
475 | sleep(1); |
||
476 | } |
||
477 | |||
478 | return $this->formatDiskLocalPart2($device, $bg); |
||
479 | } |
||
480 | |||
481 | /** |
||
482 | * Форматирование диска. |
||
483 | * |
||
484 | * @param string $device |
||
485 | * @param bool $bg |
||
486 | * |
||
487 | * @return mixed |
||
488 | */ |
||
489 | private function formatDiskLocalPart2($device, $bg = false): bool |
||
490 | { |
||
491 | if (is_numeric(substr($device, -1))) { |
||
492 | $device_id = ""; |
||
493 | } else { |
||
494 | $device_id = "1"; |
||
495 | } |
||
496 | $format = 'ext4'; |
||
497 | $mkfsPath = Util::which("mkfs.{$format}"); |
||
498 | $cmd = "{$mkfsPath} {$device}{$device_id}"; |
||
499 | if ($bg === false) { |
||
500 | $retVal = (Processes::mwExec("{$cmd} 2>&1") === 0); |
||
501 | Util::sysLogMsg(__CLASS__, "{$mkfsPath} returned {$retVal}"); |
||
502 | } else { |
||
503 | usleep(200000); |
||
504 | Processes::mwExecBg($cmd); |
||
505 | $retVal = true; |
||
506 | } |
||
507 | |||
508 | return $retVal; |
||
509 | } |
||
510 | |||
511 | /** |
||
512 | * Возвращает текущий статус форматирования диска. |
||
513 | * |
||
514 | * @param $dev |
||
515 | * |
||
516 | * @return string |
||
517 | */ |
||
518 | public static function statusMkfs($dev): string |
||
519 | { |
||
520 | if (!file_exists($dev)) { |
||
521 | $dev = "/dev/{$dev}"; |
||
522 | } |
||
523 | $out = []; |
||
524 | $psPath = Util::which('ps'); |
||
525 | $grepPath = Util::which('grep'); |
||
526 | Processes::mwExec("{$psPath} -A -f | {$grepPath} {$dev} | {$grepPath} mkfs | {$grepPath} -v grep", $out); |
||
527 | $mount_dir = trim(implode('', $out)); |
||
528 | |||
529 | return empty($mount_dir) ? 'ended' : 'inprogress'; |
||
530 | } |
||
531 | |||
532 | /** |
||
533 | * Clear cache folders from PHP sessions files |
||
534 | */ |
||
535 | public static function clearSessionsFiles(): void |
||
536 | { |
||
537 | $di = Di::getDefault(); |
||
538 | if ($di === null) { |
||
539 | return; |
||
540 | } |
||
541 | $config = $di->getShared('config'); |
||
542 | $phpSessionDir = $config->path('www.phpSessionDir'); |
||
543 | if (!empty($phpSessionDir)) { |
||
544 | $rmPath = Util::which('rm'); |
||
545 | Processes::mwExec("{$rmPath} -rf {$phpSessionDir}/*"); |
||
546 | } |
||
547 | } |
||
548 | |||
549 | /** |
||
550 | * Возвращает все подключенные HDD. |
||
551 | * |
||
552 | * @param bool $mounted_only |
||
553 | * |
||
554 | * @return array |
||
555 | */ |
||
556 | public function getAllHdd($mounted_only = false): array |
||
557 | { |
||
558 | $res_disks = []; |
||
559 | |||
560 | if (Util::isSystemctl()) { |
||
561 | $out = []; |
||
562 | $grepPath = Util::which('grep'); |
||
563 | $dfPath = Util::which('df'); |
||
564 | $awkPath = Util::which('awk'); |
||
565 | Processes::mwExec( |
||
566 | "{$dfPath} -k /storage/usbdisk1 | {$awkPath} '{ print $1 \"|\" $3 \"|\" $4} ' | {$grepPath} -v 'Available'", |
||
567 | $out |
||
568 | ); |
||
569 | $disk_data = explode('|', implode(" ", $out)); |
||
570 | if (count($disk_data) === 3) { |
||
571 | $m_size = round(($disk_data[1] + $disk_data[2]) / 1024, 1); |
||
572 | $res_disks[] = [ |
||
573 | 'id' => $disk_data[0], |
||
574 | 'size' => "" . $m_size, |
||
575 | 'size_text' => "" . $m_size . " Mb", |
||
576 | 'vendor' => 'Debian', |
||
577 | 'mounted' => '/storage/usbdisk1', |
||
578 | 'free_space' => round($disk_data[2] / 1024, 1), |
||
579 | 'partitions' => [], |
||
580 | 'sys_disk' => true, |
||
581 | ]; |
||
582 | } |
||
583 | |||
584 | return $res_disks; |
||
585 | } |
||
586 | |||
587 | $cd_disks = $this->cdromGetDevices(); |
||
588 | $disks = $this->diskGetDevices(); |
||
589 | |||
590 | $cf_disk = ''; |
||
591 | $varEtcDir = $this->config->path('core.varEtcDir'); |
||
592 | |||
593 | if (file_exists($varEtcDir . '/cfdevice')) { |
||
594 | $cf_disk = trim(file_get_contents($varEtcDir . '/cfdevice')); |
||
595 | } |
||
596 | |||
597 | foreach ($disks as $disk => $diskInfo) { |
||
598 | $type = $diskInfo['fstype']??''; |
||
599 | if($type === 'linux_raid_member'){ |
||
600 | continue; |
||
601 | } |
||
602 | if (in_array($disk, $cd_disks, true)) { |
||
603 | // Это CD-ROM. |
||
604 | continue; |
||
605 | } |
||
606 | unset($temp_vendor, $temp_size, $original_size); |
||
607 | $mounted = self::diskIsMounted($disk); |
||
608 | if ($mounted_only === true && $mounted === false) { |
||
609 | continue; |
||
610 | } |
||
611 | $sys_disk = ($cf_disk === $disk); |
||
612 | |||
613 | $mb_size = 0; |
||
614 | if (is_file("/sys/block/" . $disk . "/size")) { |
||
615 | $original_size = trim(file_get_contents("/sys/block/" . $disk . "/size")); |
||
616 | $original_size = ($original_size * 512 / 1024 / 1024); |
||
617 | $mb_size = $original_size; |
||
618 | } |
||
619 | if ($mb_size > 100) { |
||
620 | $temp_size = sprintf("%.0f MB", $mb_size); |
||
621 | $temp_vendor = $this->getVendorDisk($diskInfo); |
||
622 | $free_space = $this->getFreeSpace($disk); |
||
623 | |||
624 | $arr_disk_info = $this->determineFormatFs($diskInfo); |
||
625 | |||
626 | if (count($arr_disk_info) > 0) { |
||
627 | $used = 0; |
||
628 | foreach ($arr_disk_info as $disk_info) { |
||
629 | $used += $disk_info['used_space']; |
||
630 | } |
||
631 | if ($used > 0) { |
||
632 | $free_space = $mb_size - $used; |
||
633 | } |
||
634 | } |
||
635 | |||
636 | $res_disks[] = [ |
||
637 | 'id' => $disk, |
||
638 | 'size' => $mb_size, |
||
639 | 'size_text' => $temp_size, |
||
640 | 'vendor' => $temp_vendor, |
||
641 | 'mounted' => $mounted, |
||
642 | 'free_space' => $free_space, |
||
643 | 'partitions' => $arr_disk_info, |
||
644 | 'sys_disk' => $sys_disk, |
||
645 | ]; |
||
646 | } |
||
647 | } |
||
648 | return $res_disks; |
||
649 | } |
||
650 | |||
651 | /** |
||
652 | * Получение массива подключенныйх cdrom. |
||
653 | * |
||
654 | * @return array |
||
655 | */ |
||
656 | private function cdromGetDevices(): array |
||
657 | { |
||
658 | $disks = []; |
||
659 | $blockDevices = $this->getLsBlkDiskInfo(); |
||
660 | foreach ($blockDevices as $diskData) { |
||
661 | $type = $diskData['type'] ?? ''; |
||
662 | $name = $diskData['name'] ?? ''; |
||
663 | if ($type !== 'rom' || $name === '') { |
||
664 | continue; |
||
665 | } |
||
666 | $disks[] = $name; |
||
667 | } |
||
668 | return $disks; |
||
669 | } |
||
670 | |||
671 | /** |
||
672 | * Получение массива подключенныйх HDD. |
||
673 | * @param false $diskOnly |
||
674 | * @return array |
||
675 | */ |
||
676 | public function diskGetDevices($diskOnly = false): array |
||
677 | { |
||
678 | $disks = []; |
||
679 | $blockDevices = $this->getLsBlkDiskInfo(); |
||
680 | |||
681 | foreach ($blockDevices as $diskData) { |
||
682 | $type = $diskData['type'] ?? ''; |
||
683 | $name = $diskData['name'] ?? ''; |
||
684 | if ($type !== 'disk' || $name === '') { |
||
685 | continue; |
||
686 | } |
||
687 | $disks[$name] = $diskData; |
||
688 | if ($diskOnly === true) { |
||
689 | continue; |
||
690 | } |
||
691 | $children = $diskData['children'] ?? []; |
||
692 | |||
693 | foreach ($children as $child) { |
||
694 | $childName = $child['name'] ?? ''; |
||
695 | if ($childName === '') { |
||
696 | continue; |
||
697 | } |
||
698 | $disks[$childName] = $child; |
||
699 | } |
||
700 | } |
||
701 | return $disks; |
||
702 | } |
||
703 | |||
704 | /** |
||
705 | * Возвращает информацию о дисках. |
||
706 | * @return array |
||
707 | */ |
||
708 | private function getLsBlkDiskInfo(): array |
||
709 | { |
||
710 | $lsBlkPath = Util::which('lsblk'); |
||
711 | Processes::mwExec( |
||
712 | "{$lsBlkPath} -J -b -o VENDOR,MODEL,SERIAL,LABEL,TYPE,FSTYPE,MOUNTPOINT,SUBSYSTEMS,NAME,UUID", |
||
713 | $out |
||
714 | ); |
||
715 | try { |
||
716 | $data = json_decode(implode(PHP_EOL, $out), true, 512, JSON_THROW_ON_ERROR); |
||
717 | $data = $data['blockdevices'] ?? []; |
||
718 | } catch (JsonException $e) { |
||
719 | $data = []; |
||
720 | } |
||
721 | return $data; |
||
722 | } |
||
723 | |||
724 | /** |
||
725 | * Проверка, смонтирован ли диск. |
||
726 | * |
||
727 | * @param $disk |
||
728 | * @param $filter |
||
729 | * |
||
730 | * @return string|bool |
||
731 | */ |
||
732 | public static function diskIsMounted($disk, $filter = '/dev/') |
||
733 | { |
||
734 | $out = []; |
||
735 | $grepPath = Util::which('grep'); |
||
736 | $mountPath = Util::which('mount'); |
||
737 | Processes::mwExec("{$mountPath} | {$grepPath} '{$filter}{$disk}'", $out); |
||
738 | if (count($out) > 0) { |
||
739 | $res_out = end($out); |
||
740 | } else { |
||
741 | $res_out = implode('', $out); |
||
742 | } |
||
743 | $data = explode(' ', trim($res_out)); |
||
744 | |||
745 | return (count($data) > 2) ? $data[2] : false; |
||
746 | } |
||
747 | |||
748 | /** |
||
749 | * Получение сведений по диску. |
||
750 | * |
||
751 | * @param $diskInfo |
||
752 | * |
||
753 | * @return string |
||
754 | */ |
||
755 | private function getVendorDisk($diskInfo): string |
||
756 | { |
||
757 | $temp_vendor = []; |
||
758 | $keys = ['vendor', 'model', 'type']; |
||
759 | foreach ($keys as $key) { |
||
760 | $data = $diskInfo[$key] ?? ''; |
||
761 | if ($data !== '') { |
||
762 | $temp_vendor[] = trim(str_replace(',', '', $data)); |
||
763 | } |
||
764 | } |
||
765 | if (count($temp_vendor) === 0) { |
||
766 | $temp_vendor[] = $diskInfo['name'] ?? 'ERROR: NoName'; |
||
767 | } |
||
768 | return implode(', ', $temp_vendor); |
||
769 | } |
||
770 | |||
771 | /** |
||
772 | * Получаем свободное место на диске в Mb. |
||
773 | * |
||
774 | * @param $hdd |
||
775 | * |
||
776 | * @return mixed |
||
777 | */ |
||
778 | public function getFreeSpace($hdd) |
||
779 | { |
||
780 | $out = []; |
||
781 | $hdd = escapeshellarg($hdd); |
||
782 | $grepPath = Util::which('grep'); |
||
783 | $awkPath = Util::which('awk'); |
||
784 | $dfPath = Util::which('df'); |
||
785 | Processes::mwExec("{$dfPath} -m | {$grepPath} {$hdd} | {$awkPath} '{print $4}'", $out); |
||
786 | $result = 0; |
||
787 | foreach ($out as $res) { |
||
788 | if (!is_numeric($res)) { |
||
789 | continue; |
||
790 | } |
||
791 | $result += (1 * $res); |
||
792 | } |
||
793 | |||
794 | return $result; |
||
795 | } |
||
796 | |||
797 | private function getDiskParted($diskName): array |
||
798 | { |
||
799 | $result = []; |
||
800 | $lsBlkPath = Util::which('lsblk'); |
||
801 | Processes::mwExec("{$lsBlkPath} -J -b -o NAME,TYPE {$diskName}", $out); |
||
802 | try { |
||
803 | $data = json_decode(implode(PHP_EOL, $out), true, 512, JSON_THROW_ON_ERROR); |
||
804 | $data = $data['blockdevices'][0] ?? []; |
||
805 | } catch (\JsonException $e) { |
||
806 | $data = []; |
||
807 | } |
||
808 | |||
809 | $type = $data['children'][0]['type'] ?? ''; |
||
810 | if (strpos($type, 'raid') === false) { |
||
811 | $children = $data['children']??[]; |
||
812 | foreach ($children as $child) { |
||
813 | $result[] = $child['name']; |
||
814 | } |
||
815 | } |
||
816 | |||
817 | return $result; |
||
818 | } |
||
819 | |||
820 | /** |
||
821 | * Определить формат файловой системы и размер дисков. |
||
822 | * |
||
823 | * @param $deviceInfo |
||
824 | * |
||
825 | * @return array|bool |
||
826 | */ |
||
827 | public function determineFormatFs($deviceInfo) |
||
828 | { |
||
829 | $allow_formats = ['ext2', 'ext4', 'fat', 'ntfs', 'msdos']; |
||
830 | $device = basename($deviceInfo['name'] ?? ''); |
||
831 | |||
832 | $devices = $this->getDiskParted('/dev/'.$deviceInfo['name'] ?? ''); |
||
833 | $result_data = []; |
||
834 | foreach ($devices as $dev) { |
||
835 | if (empty($dev) || (count($devices) > 1 && $device === $dev) || is_dir("/sys/block/{$dev}")) { |
||
836 | continue; |
||
837 | } |
||
838 | $mb_size = 0; |
||
839 | $path_size_info = ''; |
||
840 | $tmp_path = "/sys/block/{$device}/{$dev}/size"; |
||
841 | if (file_exists($tmp_path)) { |
||
842 | $path_size_info = $tmp_path; |
||
843 | } |
||
844 | if (empty($path_size_info)) { |
||
845 | $tmp_path = "/sys/block/" . substr($dev, 0, 3) . "/{$dev}/size"; |
||
846 | if (file_exists($tmp_path)) { |
||
847 | $path_size_info = $tmp_path; |
||
848 | } |
||
849 | } |
||
850 | |||
851 | if (!empty($path_size_info)) { |
||
852 | $original_size = trim(file_get_contents($path_size_info)); |
||
853 | $original_size = ($original_size * 512 / 1024 / 1024); |
||
854 | $mb_size = $original_size; |
||
855 | } |
||
856 | |||
857 | $tmp_dir = "/tmp/{$dev}_" . time(); |
||
858 | $out = []; |
||
859 | |||
860 | $fs = null; |
||
861 | $need_unmount = false; |
||
862 | $mount_dir = ''; |
||
863 | if (self::isStorageDiskMounted("/dev/{$dev} ", $mount_dir)) { |
||
864 | $grepPath = Util::which('grep'); |
||
865 | $awkPath = Util::which('awk'); |
||
866 | $mountPath = Util::which('mount'); |
||
867 | Processes::mwExec("{$mountPath} | {$grepPath} '/dev/{$dev}' | {$awkPath} '{print $5}'", $out); |
||
868 | $fs = trim(implode("", $out)); |
||
869 | $fs = ($fs === 'fuseblk') ? 'ntfs' : $fs; |
||
870 | $free_space = $this->getFreeSpace("/dev/{$dev} "); |
||
871 | $used_space = $mb_size - $free_space; |
||
872 | } else { |
||
873 | $format = $this->getFsType($device); |
||
874 | if (in_array($format, $allow_formats)) { |
||
875 | $fs = $format; |
||
876 | } |
||
877 | self::mountDisk($dev, $format, $tmp_dir); |
||
878 | |||
879 | $need_unmount = true; |
||
880 | $used_space = Util::getSizeOfFile($tmp_dir); |
||
881 | } |
||
882 | $result_data[] = [ |
||
883 | "dev" => $dev, |
||
884 | 'size' => round($mb_size, 2), |
||
885 | "used_space" => round($used_space, 2), |
||
886 | "free_space" => round($mb_size - $used_space, 2), |
||
887 | "uuid" => $this->getUuid("/dev/{$dev} "), |
||
888 | "fs" => $fs, |
||
889 | ]; |
||
890 | if ($need_unmount) { |
||
891 | self::umountDisk($tmp_dir); |
||
892 | } |
||
893 | } |
||
894 | |||
895 | return $result_data; |
||
896 | } |
||
897 | |||
898 | /** |
||
899 | * Монтирует диск в указанный каталог. |
||
900 | * |
||
901 | * @param $dev |
||
902 | * @param $format |
||
903 | * @param $dir |
||
904 | * |
||
905 | * @return bool |
||
906 | */ |
||
907 | public static function mountDisk($dev, $format, $dir): bool |
||
908 | { |
||
909 | if (self::isStorageDiskMounted("/dev/{$dev} ")) { |
||
910 | return true; |
||
911 | } |
||
912 | Util::mwMkdir($dir); |
||
913 | |||
914 | if (!file_exists($dir)) { |
||
915 | Util::sysLogMsg('Storage', "Unable mount $dev $format to $dir. Unable create dir."); |
||
916 | |||
917 | return false; |
||
918 | } |
||
919 | $dev = str_replace('/dev/', '', $dev); |
||
920 | if ('ntfs' === $format) { |
||
921 | $mountNtfs3gPath = Util::which('mount.ntfs-3g'); |
||
922 | Processes::mwExec("{$mountNtfs3gPath} /dev/{$dev} {$dir}", $out); |
||
923 | } else { |
||
924 | $storage = new self(); |
||
925 | $uid_part = 'UUID=' . $storage->getUuid("/dev/{$dev}") . ''; |
||
926 | $mountPath = Util::which('mount'); |
||
927 | Processes::mwExec("{$mountPath} -t {$format} {$uid_part} {$dir}", $out); |
||
928 | } |
||
929 | |||
930 | return self::isStorageDiskMounted("/dev/{$dev} "); |
||
931 | } |
||
932 | |||
933 | /** |
||
934 | * Монтирование разделов диска с базой данных настроек. |
||
935 | */ |
||
936 | public function configure(): void |
||
937 | { |
||
938 | if(Util::isSystemctl()){ |
||
939 | $this->updateConfigWithNewMountPoint("/storage/usbdisk1"); |
||
940 | $this->createWorkDirs(); |
||
941 | PHPConf::setupLog(); |
||
942 | return; |
||
943 | } |
||
944 | |||
945 | $cf_disk = ''; |
||
946 | $varEtcDir = $this->config->path('core.varEtcDir'); |
||
947 | $storage_dev_file = "{$varEtcDir}/storage_device"; |
||
948 | if (file_exists($storage_dev_file)) { |
||
949 | unlink($storage_dev_file); |
||
950 | } |
||
951 | |||
952 | if (file_exists($varEtcDir . '/cfdevice')) { |
||
953 | $cf_disk = trim(file_get_contents($varEtcDir . '/cfdevice')); |
||
954 | } |
||
955 | $disks = $this->getDiskSettings(); |
||
956 | $conf = ''; |
||
957 | foreach ($disks as $disk) { |
||
958 | clearstatcache(); |
||
959 | if ($disk['device'] !== "/dev/{$cf_disk}") { |
||
960 | // Если это обычный диск, то раздел 1. |
||
961 | $part = "1"; |
||
962 | } else { |
||
963 | // Если это системный диск, то пытаемся подключить раздел 4. |
||
964 | $part = "4"; |
||
965 | } |
||
966 | $devName = self::getDevPartName($disk['device'], $part); |
||
967 | $dev = '/dev/' . $devName; |
||
968 | if (!$this->hddExists($dev)) { |
||
969 | // Диск не существует. |
||
970 | continue; |
||
971 | } |
||
972 | if ($disk['media'] === '1' || !file_exists($storage_dev_file)) { |
||
973 | file_put_contents($storage_dev_file, "/storage/usbdisk{$disk['id']}"); |
||
974 | $this->updateConfigWithNewMountPoint("/storage/usbdisk{$disk['id']}"); |
||
975 | } |
||
976 | $formatFs = $this->getFsType($dev); |
||
977 | if($formatFs !== $disk['filesystemtype'] && !($formatFs === 'ext4' && $disk['filesystemtype'] === 'ext2')){ |
||
978 | Util::sysLogMsg('Storage', "The file system type has changed {$disk['filesystemtype']} -> {$formatFs}. The disk will not be connected."); |
||
979 | continue; |
||
980 | } |
||
981 | $str_uid = 'UUID=' . $this->getUuid($dev) . ''; |
||
982 | $conf .= "{$str_uid} /storage/usbdisk{$disk['id']} {$formatFs} async,rw 0 0\n"; |
||
983 | $mount_point = "/storage/usbdisk{$disk['id']}"; |
||
984 | Util::mwMkdir($mount_point); |
||
985 | } |
||
986 | $this->saveFstab($conf); |
||
987 | $this->createWorkDirs(); |
||
988 | PHPConf::setupLog(); |
||
989 | } |
||
990 | |||
991 | /** |
||
992 | * Получаем настройки диска из базы данных. |
||
993 | * |
||
994 | * @param string $id |
||
995 | * |
||
996 | * @return array |
||
997 | */ |
||
998 | public function getDiskSettings($id = ''): array |
||
999 | { |
||
1000 | $data = []; |
||
1001 | if ('' === $id) { |
||
1002 | // Возвращаем данные до модификации. |
||
1003 | $data = StorageModel::find()->toArray(); |
||
1004 | } else { |
||
1005 | $pbxSettings = StorageModel::findFirst("id='$id'"); |
||
1006 | if ($pbxSettings !== null) { |
||
1007 | $data = $pbxSettings->toArray(); |
||
1008 | } |
||
1009 | } |
||
1010 | |||
1011 | return $data; |
||
1012 | } |
||
1013 | |||
1014 | /** |
||
1015 | * Проверяет, существует ли диск в массиве. |
||
1016 | * |
||
1017 | * @param $disk |
||
1018 | * |
||
1019 | * @return bool |
||
1020 | */ |
||
1021 | private function hddExists($disk): bool |
||
1022 | { |
||
1023 | $result = false; |
||
1024 | $uid = $this->getUuid($disk); |
||
1025 | if ($uid !== false && file_exists($disk)) { |
||
1026 | $result = true; |
||
1027 | } |
||
1028 | return $result; |
||
1029 | } |
||
1030 | |||
1031 | /** |
||
1032 | * After mount storage we will change /mountpoint/ to new $mount_point value |
||
1033 | * |
||
1034 | * @param string $mount_point |
||
1035 | * |
||
1036 | */ |
||
1037 | private function updateConfigWithNewMountPoint(string $mount_point): void |
||
1038 | { |
||
1039 | $staticSettingsFile = '/etc/inc/mikopbx-settings.json'; |
||
1040 | $staticSettingsFileOrig = appPath('config/mikopbx-settings.json'); |
||
1041 | |||
1042 | $jsonString = file_get_contents($staticSettingsFileOrig); |
||
1043 | try { |
||
1044 | $data = json_decode($jsonString, true, 512, JSON_THROW_ON_ERROR); |
||
1045 | } catch (JsonException $exception) { |
||
1046 | throw new Error("{$staticSettingsFileOrig} has broken format"); |
||
1047 | } |
||
1048 | foreach ($data as $rootKey => $rootEntry) { |
||
1049 | foreach ($rootEntry as $nestedKey => $entry) { |
||
1050 | if (stripos($entry, '/mountpoint') !== false) { |
||
1051 | $data[$rootKey][$nestedKey] = str_ireplace('/mountpoint', $mount_point, $entry); |
||
1052 | } |
||
1053 | } |
||
1054 | } |
||
1055 | |||
1056 | $newJsonString = json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES); |
||
1057 | file_put_contents($staticSettingsFile, $newJsonString); |
||
1058 | $this->updateEnvironmentAfterChangeMountPoint(); |
||
1059 | } |
||
1060 | |||
1061 | |||
1062 | /** |
||
1063 | * Recreates DI services and reloads config from JSON file |
||
1064 | * |
||
1065 | */ |
||
1066 | private function updateEnvironmentAfterChangeMountPoint(): void |
||
1067 | { |
||
1068 | // Update config variable |
||
1069 | ConfigProvider::recreateConfigProvider(); |
||
1070 | $this->config = $this->di->get('config'); |
||
1071 | |||
1072 | // Reload classes from system and storage disks |
||
1073 | ClassLoader::init(); |
||
1074 | |||
1075 | // Reload all providers |
||
1076 | RegisterDIServices::init(); |
||
1077 | } |
||
1078 | |||
1079 | /** |
||
1080 | * Generates fstab file |
||
1081 | * Mounts volumes |
||
1082 | * |
||
1083 | * @param string $conf |
||
1084 | */ |
||
1085 | public function saveFstab($conf = ''): void |
||
1086 | { |
||
1087 | if(Util::isSystemctl()){ |
||
1088 | // Не настраиваем. |
||
1089 | return; |
||
1090 | } |
||
1091 | |||
1092 | $varEtcDir = $this->config->path('core.varEtcDir'); |
||
1093 | // Точка монтирования доп. дисков. |
||
1094 | Util::mwMkdir('/storage'); |
||
1095 | $chmodPath = Util::which('chmod'); |
||
1096 | Processes::mwExec("{$chmodPath} 755 /storage"); |
||
1097 | if (!file_exists($varEtcDir . '/cfdevice')) { |
||
1098 | return; |
||
1099 | } |
||
1100 | $fstab = ''; |
||
1101 | $file_data = file_get_contents($varEtcDir . '/cfdevice'); |
||
1102 | $cf_disk = trim($file_data); |
||
1103 | if ('' === $cf_disk) { |
||
1104 | return; |
||
1105 | } |
||
1106 | $part2 = self::getDevPartName($cf_disk, '2'); |
||
1107 | $part3 = self::getDevPartName($cf_disk, '3'); |
||
1108 | |||
1109 | $uid_part2 = 'UUID=' . $this->getUuid("/dev/{$part2}"); |
||
1110 | $format_p2 = $this->getFsType($part2); |
||
1111 | $uid_part3 = 'UUID=' . $this->getUuid("/dev/{$part3}"); |
||
1112 | $format_p3 = $this->getFsType($part3); |
||
1113 | |||
1114 | $fstab .= "{$uid_part2} /offload {$format_p2} ro 0 0\n"; |
||
1115 | $fstab .= "{$uid_part3} /cf {$format_p3} rw 1 1\n"; |
||
1116 | $fstab .= $conf; |
||
1117 | |||
1118 | file_put_contents("/etc/fstab", $fstab); |
||
1119 | // Дублируем для работы vmtoolsd. |
||
1120 | file_put_contents("/etc/mtab", $fstab); |
||
1121 | $mountPath = Util::which('mount'); |
||
1122 | Processes::mwExec("{$mountPath} -a 2> /dev/null"); |
||
1123 | Util::addRegularWWWRights('/cf'); |
||
1124 | } |
||
1125 | |||
1126 | /** |
||
1127 | * Возвращает имя раздела диска по имени и номеру. |
||
1128 | * @param string $dev |
||
1129 | * @param string $part |
||
1130 | * @return string |
||
1131 | */ |
||
1132 | public static function getDevPartName(string $dev, string $part): string |
||
1133 | { |
||
1134 | $lsBlkPath = Util::which('lsblk'); |
||
1135 | $cutPath = Util::which('cut'); |
||
1136 | $grepPath = Util::which('grep'); |
||
1137 | $sortPath = Util::which('sort'); |
||
1138 | |||
1139 | $command = "{$lsBlkPath} -r | {$grepPath} ' part' | {$sortPath} -u | {$cutPath} -d ' ' -f 1 | {$grepPath} \"" . basename( |
||
1140 | $dev |
||
1141 | ) . "\" | {$grepPath} \"{$part}\$\""; |
||
1142 | Processes::mwExec($command, $out); |
||
1143 | $devName = trim(implode('', $out)); |
||
1144 | return trim($devName); |
||
1145 | } |
||
1146 | |||
1147 | /** |
||
1148 | * Creates system folders according to config file |
||
1149 | * |
||
1150 | * @return void |
||
1151 | */ |
||
1152 | private function createWorkDirs(): void |
||
1153 | { |
||
1154 | $path = ''; |
||
1155 | $mountPath = Util::which('mount'); |
||
1156 | Processes::mwExec("{$mountPath} -o remount,rw /offload 2> /dev/null"); |
||
1157 | |||
1158 | $isLiveCd = file_exists('/offload/livecd'); |
||
1159 | // Create dirs |
||
1160 | $arrConfig = $this->config->toArray(); |
||
1161 | foreach ($arrConfig as $rootEntry) { |
||
1162 | foreach ($rootEntry as $key => $entry) { |
||
1163 | if (stripos($key, 'path') === false && stripos($key, 'dir') === false) { |
||
1164 | continue; |
||
1165 | } |
||
1166 | if (file_exists($entry)) { |
||
1167 | continue; |
||
1168 | } |
||
1169 | if ($isLiveCd && strpos($entry, '/offload/') === 0) { |
||
1170 | continue; |
||
1171 | } |
||
1172 | $path .= " $entry"; |
||
1173 | } |
||
1174 | } |
||
1175 | |||
1176 | if (!empty($path)) { |
||
1177 | Util::mwMkdir($path); |
||
1178 | } |
||
1179 | |||
1180 | $downloadCacheDir = appPath('sites/pbxcore/files/cache'); |
||
1181 | if (!$isLiveCd) { |
||
1182 | Util::mwMkdir($downloadCacheDir); |
||
1183 | Util::createUpdateSymlink($this->config->path('www.downloadCacheDir'), $downloadCacheDir); |
||
1184 | } |
||
1185 | |||
1186 | $this->createAssetsSymlinks(); |
||
1187 | |||
1188 | Util::createUpdateSymlink($this->config->path('www.phpSessionDir'), '/var/lib/php/session'); |
||
1189 | Util::createUpdateSymlink($this->config->path('www.uploadDir'), '/ultmp'); |
||
1190 | |||
1191 | $filePath = appPath('src/Core/Asterisk/Configs/lua/extensions.lua'); |
||
1192 | Util::createUpdateSymlink($filePath, '/etc/asterisk/extensions.lua'); |
||
1193 | |||
1194 | // Create symlinks to AGI-BIN |
||
1195 | $agiBinDir = $this->config->path('asterisk.astagidir'); |
||
1196 | if ($isLiveCd && strpos($agiBinDir, '/offload/') !== 0) { |
||
1197 | Util::mwMkdir($agiBinDir); |
||
1198 | } |
||
1199 | |||
1200 | $roAgiBinFolder = appPath('src/Core/Asterisk/agi-bin'); |
||
1201 | $files = glob("{$roAgiBinFolder}/*.{php}", GLOB_BRACE); |
||
1202 | foreach ($files as $file) { |
||
1203 | $fileInfo = pathinfo($file); |
||
1204 | $newFilename = "{$agiBinDir}/{$fileInfo['filename']}.{$fileInfo['extension']}"; |
||
1205 | Util::createUpdateSymlink($file, $newFilename); |
||
1206 | } |
||
1207 | $this->clearCacheFiles(); |
||
1208 | $this->applyFolderRights(); |
||
1209 | Processes::mwExec("{$mountPath} -o remount,ro /offload 2> /dev/null"); |
||
1210 | } |
||
1211 | |||
1212 | /** |
||
1213 | * Creates JS, CSS, IMG cache folders and links |
||
1214 | * |
||
1215 | */ |
||
1216 | public function createAssetsSymlinks(): void |
||
1217 | { |
||
1218 | $jsCacheDir = appPath('sites/admin-cabinet/assets/js/cache'); |
||
1219 | Util::createUpdateSymlink($this->config->path('adminApplication.assetsCacheDir') . '/js', $jsCacheDir); |
||
1220 | |||
1221 | $cssCacheDir = appPath('sites/admin-cabinet/assets/css/cache'); |
||
1222 | Util::createUpdateSymlink($this->config->path('adminApplication.assetsCacheDir') . '/css', $cssCacheDir); |
||
1223 | |||
1224 | $imgCacheDir = appPath('sites/admin-cabinet/assets/img/cache'); |
||
1225 | Util::createUpdateSymlink($this->config->path('adminApplication.assetsCacheDir') . '/img', $imgCacheDir); |
||
1226 | } |
||
1227 | |||
1228 | /** |
||
1229 | * Clears cache folders from old and orphaned files |
||
1230 | */ |
||
1231 | public function clearCacheFiles(): void |
||
1232 | { |
||
1233 | $cacheDirs = []; |
||
1234 | $cacheDirs[] = $this->config->path('www.uploadDir'); |
||
1235 | $cacheDirs[] = $this->config->path('www.downloadCacheDir'); |
||
1236 | $cacheDirs[] = $this->config->path('adminApplication.assetsCacheDir') . '/js'; |
||
1237 | $cacheDirs[] = $this->config->path('adminApplication.assetsCacheDir') . '/css'; |
||
1238 | $cacheDirs[] = $this->config->path('adminApplication.assetsCacheDir') . '/img'; |
||
1239 | $cacheDirs[] = $this->config->path('adminApplication.voltCacheDir'); |
||
1240 | $rmPath = Util::which('rm'); |
||
1241 | foreach ($cacheDirs as $cacheDir) { |
||
1242 | if (!empty($cacheDir)) { |
||
1243 | Processes::mwExec("{$rmPath} -rf {$cacheDir}/*"); |
||
1244 | } |
||
1245 | } |
||
1246 | |||
1247 | // Delete boot cache folders |
||
1248 | if (is_dir('/mountpoint') && self::isStorageDiskMounted()) { |
||
1249 | Processes::mwExec("{$rmPath} -rf /mountpoint"); |
||
1250 | } |
||
1251 | } |
||
1252 | |||
1253 | /** |
||
1254 | * Create system folders and links after upgrade and connect config DB |
||
1255 | */ |
||
1256 | public function createWorkDirsAfterDBUpgrade(): void |
||
1263 | } |
||
1264 | |||
1265 | /** |
||
1266 | * Restore modules cache folders and symlinks |
||
1267 | */ |
||
1268 | public function createModulesCacheSymlinks(): void |
||
1269 | { |
||
1274 | } |
||
1275 | } |
||
1276 | |||
1277 | /** |
||
1278 | * Fixes permissions for Folder and Files |
||
1279 | */ |
||
1280 | private function applyFolderRights(): void |
||
1281 | { |
||
1282 | // Add Rights to the WWW dirs plus some core dirs |
||
1283 | $www_dirs = []; |
||
1284 | $exec_dirs = []; |
||
1285 | |||
1286 | $arrConfig = $this->config->toArray(); |
||
1287 | foreach ($arrConfig as $key => $entry) { |
||
1288 | if (in_array($key, ['www', 'adminApplication'])) { |
||
1289 | foreach ($entry as $subKey => $subEntry) { |
||
1290 | if (stripos($subKey, 'path') === false && stripos($subKey, 'dir') === false) { |
||
1291 | continue; |
||
1292 | } |
||
1293 | $www_dirs[] = $subEntry; |
||
1294 | } |
||
1295 | } |
||
1296 | } |
||
1297 | |||
1298 | $www_dirs[] = $this->config->path('core.tempDir'); |
||
1299 | $www_dirs[] = $this->config->path('core.logsDir'); |
||
1300 | |||
1301 | // Create empty log files with www rights |
||
1302 | $logFiles = [ |
||
1303 | $this->config->path('database.debugLogFile'), |
||
1304 | $this->config->path('cdrDatabase.debugLogFile'), |
||
1305 | $this->config->path('eventsLogDatabase.debugLogFile') |
||
1306 | ]; |
||
1307 | |||
1308 | foreach ($logFiles as $logFile) { |
||
1309 | $filename = (string)$logFile; |
||
1310 | if (!file_exists($filename)) { |
||
1311 | file_put_contents($filename, ''); |
||
1312 | } |
||
1313 | $www_dirs[] = $filename; |
||
1314 | } |
||
1315 | |||
1316 | $www_dirs[] = '/etc/version'; |
||
1317 | $www_dirs[] = appPath('/'); |
||
1318 | |||
1319 | // Add read rights |
||
1320 | Util::addRegularWWWRights(implode(' ', $www_dirs)); |
||
1321 | |||
1322 | // Add executable rights |
||
1323 | $exec_dirs[] = appPath('src/Core/Asterisk/agi-bin'); |
||
1324 | $exec_dirs[] = appPath('src/Core/Rc'); |
||
1325 | Util::addExecutableRights(implode(' ', $exec_dirs)); |
||
1326 | |||
1327 | $mountPath = Util::which('mount'); |
||
1328 | Processes::mwExec("{$mountPath} -o remount,ro /offload 2> /dev/null"); |
||
1329 | } |
||
1330 | |||
1331 | /** |
||
1332 | * Creates swap file on storage |
||
1333 | */ |
||
1334 | public function mountSwap(): void |
||
1335 | { |
||
1336 | if(Util::isSystemctl()){ |
||
1337 | // Не настраиваем. |
||
1338 | return; |
||
1339 | } |
||
1340 | $tempDir = $this->config->path('core.tempDir'); |
||
1341 | $swapFile = "{$tempDir}/swapfile"; |
||
1342 | |||
1343 | $swapOffCmd = Util::which('swapoff'); |
||
1344 | Processes::mwExec("{$swapOffCmd} {$swapFile}"); |
||
1345 | |||
1346 | $this->makeSwapFile($swapFile); |
||
1347 | if (!file_exists($swapFile)) { |
||
1348 | return; |
||
1349 | } |
||
1350 | $swapOnCmd = Util::which('swapon'); |
||
1351 | $result = Processes::mwExec("{$swapOnCmd} {$swapFile}"); |
||
1352 | Util::sysLogMsg('Swap', 'connect swap result: ' . $result, LOG_INFO); |
||
1353 | } |
||
1354 | |||
1355 | /** |
||
1356 | * Создает swap файл на storage. |
||
1357 | * @param $swapFile |
||
1358 | */ |
||
1359 | private function makeSwapFile($swapFile): void |
||
1360 | { |
||
1361 | $swapLabel = Util::which('swaplabel'); |
||
1362 | if (Processes::mwExec("{$swapLabel} {$swapFile}") === 0) { |
||
1363 | // Файл уже существует. |
||
1364 | return; |
||
1365 | } |
||
1366 | if (file_exists($swapFile)) { |
||
1367 | unlink($swapFile); |
||
1368 | } |
||
1369 | |||
1370 | $size = $this->getStorageFreeSpaceMb(); |
||
1371 | if ($size > 2000) { |
||
1372 | $swapSize = 1024; |
||
1373 | } elseif ($size > 1000) { |
||
1374 | $swapSize = 512; |
||
1375 | } else { |
||
1376 | // Не достаточно свободного места. |
||
1377 | return; |
||
1378 | } |
||
1379 | $bs = 1024; |
||
1380 | $countBlock = $swapSize * $bs; |
||
1381 | $ddCmd = Util::which('dd'); |
||
1382 | |||
1383 | Util::sysLogMsg('Swap', 'make swap ' . $swapFile, LOG_INFO); |
||
1384 | Processes::mwExec("{$ddCmd} if=/dev/zero of={$swapFile} bs={$bs} count={$countBlock}"); |
||
1385 | |||
1386 | $mkSwapCmd = Util::which('mkswap'); |
||
1387 | Processes::mwExec("{$mkSwapCmd} {$swapFile}"); |
||
1388 | } |
||
1389 | |||
1390 | /** |
||
1391 | * Returns free space on mounted storage disk |
||
1392 | * |
||
1393 | * @return int size in megabytes |
||
1394 | */ |
||
1395 | public function getStorageFreeSpaceMb(): int |
||
1396 | { |
||
1397 | $size = 0; |
||
1398 | $mntDir = ''; |
||
1399 | $mounted = self::isStorageDiskMounted('', $mntDir); |
||
1400 | if (!$mounted) { |
||
1401 | return 0; |
||
1402 | } |
||
1403 | $hd = $this->getAllHdd(true); |
||
1404 | foreach ($hd as $disk) { |
||
1405 | if ($disk['mounted'] === $mntDir) { |
||
1406 | $size = $disk['free_space']; |
||
1407 | break; |
||
1408 | } |
||
1409 | } |
||
1410 | return $size; |
||
1411 | } |
||
1412 | |||
1413 | /** |
||
1414 | * Сохраняем новые данные диска. |
||
1415 | * |
||
1416 | * @param $data |
||
1417 | * @param string $id |
||
1418 | */ |
||
1419 | public function saveDiskSettings($data, $id = '1'): void |
||
1442 | } |
||
1443 | } |
||
1444 | |||
1445 | /** |
||
1446 | * Получение имени диска, смонтированного на conf.recover. |
||
1447 | * @return string |
||
1448 | */ |
||
1449 | public function getRecoverDiskName(): string |
||
1450 | { |
||
1451 | $disks = $this->diskGetDevices(true); |
||
1452 | foreach ($disks as $disk => $diskInfo) { |
||
1453 | // RAID содержит вложенный массив "children" |
||
1454 | if (isset($diskInfo['children'][0]['children'])) { |
||
1455 | $diskInfo = $diskInfo['children'][0]; |
||
1456 | // Корректируем имя диска. Это RAID или иной виртуальный device. |
||
1457 | $disk = $diskInfo['name']; |
||
1458 | } |
||
1459 | foreach ($diskInfo['children'] as $child) { |
||
1460 | $mountpoint = $child['mountpoint'] ?? ''; |
||
1461 | $diskPath = "/dev/{$disk}"; |
||
1462 | if ($mountpoint === '/conf.recover' && file_exists($diskPath)) { |
||
1468 | } |
||
1469 | } |