Skip to content

Commit

Permalink
Release v3.0.1
Browse files Browse the repository at this point in the history
  • Loading branch information
getcompass-opensource committed Jul 23, 2024
1 parent d077802 commit 85c7196
Show file tree
Hide file tree
Showing 48 changed files with 4,837 additions and 129 deletions.
2 changes: 1 addition & 1 deletion php_file_node/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ RUN apt-get update && apt-get install -y wget git perl libperl-dev libgd3 libgd-
RUN apt-get update && apt-get install -y libmemcached-dev gettext default-mysql-client zlib1g-dev netcat cron libzip-dev
RUN apt-get update && apt-get install -y git

RUN apt install /tmp/prebuild/libhwy0_0.17.0-11_amd64.deb && apt install /tmp/prebuild/libhwy-dev_0.17.0-11_amd64.deb && apt install /tmp/prebuild/php/zip_1.22.2-1_amd64.deb
RUN apt install /tmp/prebuild/libhwy0_0.17.0-11_amd64.deb && apt install /tmp/prebuild/libhwy-dev_0.17.0-11_amd64.deb
RUN apt install /tmp/prebuild/libjxl_0.8_amd64.deb && apt install /tmp/prebuild/libjxl-dev_0.8_amd64.deb && apt install /tmp/prebuild/libjxl-gdk-pixbuf_0.8_amd64.deb
RUN cd /tmp && tar -zxf pcre-8.45.tar.gz && cd pcre-8.45 && ./configure && make && make install \
&& cd /tmp && tar -zxf zlib-1.2.11.tar.gz && cd zlib-1.2.11 && ./configure && make && make install \
Expand Down
30 changes: 0 additions & 30 deletions php_file_node/dev/configs/crontab.txt
Original file line number Diff line number Diff line change
Expand Up @@ -4,49 +4,19 @@
# Cron_File_Relocate [0-9]
* * * * * bash -l -c "/usr/bin/php8.1 -dxdebug.start_with_request=0 /app/api/cron/file/relocate.php start bot0 >> /var/log/cron.log 2>&1"
* * * * * bash -l -c "/usr/bin/php8.1 -dxdebug.start_with_request=0 /app/api/cron/file/relocate.php start bot10 >> /var/log/cron.log 2>&1"
* * * * * bash -l -c "/usr/bin/php8.1 -dxdebug.start_with_request=0 /app/api/cron/file/relocate.php start bot11 >> /var/log/cron.log 2>&1"
* * * * * bash -l -c "/usr/bin/php8.1 -dxdebug.start_with_request=0 /app/api/cron/file/relocate.php start bot12 >> /var/log/cron.log 2>&1"
* * * * * bash -l -c "/usr/bin/php8.1 -dxdebug.start_with_request=0 /app/api/cron/file/relocate.php start bot13 >> /var/log/cron.log 2>&1"
* * * * * bash -l -c "/usr/bin/php8.1 -dxdebug.start_with_request=0 /app/api/cron/file/relocate.php start bot14 >> /var/log/cron.log 2>&1"

# Cron_PostUpload_Image [0-9]
* * * * * bash -l -c "/usr/bin/php8.1 -dxdebug.start_with_request=0 /app/api/cron/postupload/image.php start bot0 >> /var/log/cron.log 2>&1"
* * * * * bash -l -c "/usr/bin/php8.1 -dxdebug.start_with_request=0 /app/api/cron/postupload/image.php start bot10 >> /var/log/cron.log 2>&1"
* * * * * bash -l -c "/usr/bin/php8.1 -dxdebug.start_with_request=0 /app/api/cron/postupload/image.php start bot11 >> /var/log/cron.log 2>&1"
* * * * * bash -l -c "/usr/bin/php8.1 -dxdebug.start_with_request=0 /app/api/cron/postupload/image.php start bot12 >> /var/log/cron.log 2>&1"
* * * * * bash -l -c "/usr/bin/php8.1 -dxdebug.start_with_request=0 /app/api/cron/postupload/image.php start bot13 >> /var/log/cron.log 2>&1"
* * * * * bash -l -c "/usr/bin/php8.1 -dxdebug.start_with_request=0 /app/api/cron/postupload/image.php start bot14 >> /var/log/cron.log 2>&1"
* * * * * bash -l -c "/usr/bin/php8.1 -dxdebug.start_with_request=0 /app/api/cron/postupload/image.php start bot15 >> /var/log/cron.log 2>&1"
* * * * * bash -l -c "/usr/bin/php8.1 -dxdebug.start_with_request=0 /app/api/cron/postupload/image.php start bot16 >> /var/log/cron.log 2>&1"
* * * * * bash -l -c "/usr/bin/php8.1 -dxdebug.start_with_request=0 /app/api/cron/postupload/image.php start bot17 >> /var/log/cron.log 2>&1"
* * * * * bash -l -c "/usr/bin/php8.1 -dxdebug.start_with_request=0 /app/api/cron/postupload/image.php start bot18 >> /var/log/cron.log 2>&1"
* * * * * bash -l -c "/usr/bin/php8.1 -dxdebug.start_with_request=0 /app/api/cron/postupload/image.php start bot19 >> /var/log/cron.log 2>&1"

# Cron_PostUpload_Video [0-9]
* * * * * bash -l -c "/usr/bin/php8.1 -dxdebug.start_with_request=0 /app/api/cron/postupload/video.php start bot0 >> /var/log/cron.log 2>&1"
* * * * * bash -l -c "/usr/bin/php8.1 -dxdebug.start_with_request=0 /app/api/cron/postupload/video.php start bot10 >> /var/log/cron.log 2>&1"
* * * * * bash -l -c "/usr/bin/php8.1 -dxdebug.start_with_request=0 /app/api/cron/postupload/video.php start bot11 >> /var/log/cron.log 2>&1"
* * * * * bash -l -c "/usr/bin/php8.1 -dxdebug.start_with_request=0 /app/api/cron/postupload/video.php start bot12 >> /var/log/cron.log 2>&1"
* * * * * bash -l -c "/usr/bin/php8.1 -dxdebug.start_with_request=0 /app/api/cron/postupload/video.php start bot13 >> /var/log/cron.log 2>&1"
* * * * * bash -l -c "/usr/bin/php8.1 -dxdebug.start_with_request=0 /app/api/cron/postupload/video.php start bot14 >> /var/log/cron.log 2>&1"
* * * * * bash -l -c "/usr/bin/php8.1 -dxdebug.start_with_request=0 /app/api/cron/postupload/video.php start bot15 >> /var/log/cron.log 2>&1"
* * * * * bash -l -c "/usr/bin/php8.1 -dxdebug.start_with_request=0 /app/api/cron/postupload/video.php start bot16 >> /var/log/cron.log 2>&1"
* * * * * bash -l -c "/usr/bin/php8.1 -dxdebug.start_with_request=0 /app/api/cron/postupload/video.php start bot17 >> /var/log/cron.log 2>&1"

# Cron_PostUpload_Audio [0-9]
* * * * * bash -l -c "/usr/bin/php8.1 -dxdebug.start_with_request=0 /app/api/cron/postupload/audio.php start bot0 >> /var/log/cron.log 2>&1"
* * * * * bash -l -c "/usr/bin/php8.1 -dxdebug.start_with_request=0 /app/api/cron/postupload/audio.php start bot10 >> /var/log/cron.log 2>&1"
* * * * * bash -l -c "/usr/bin/php8.1 -dxdebug.start_with_request=0 /app/api/cron/postupload/audio.php start bot11 >> /var/log/cron.log 2>&1"
* * * * * bash -l -c "/usr/bin/php8.1 -dxdebug.start_with_request=0 /app/api/cron/postupload/audio.php start bot12 >> /var/log/cron.log 2>&1"
* * * * * bash -l -c "/usr/bin/php8.1 -dxdebug.start_with_request=0 /app/api/cron/postupload/audio.php start bot13 >> /var/log/cron.log 2>&1"
* * * * * bash -l -c "/usr/bin/php8.1 -dxdebug.start_with_request=0 /app/api/cron/postupload/audio.php start bot14 >> /var/log/cron.log 2>&1"
* * * * * bash -l -c "/usr/bin/php8.1 -dxdebug.start_with_request=0 /app/api/cron/postupload/audio.php start bot15 >> /var/log/cron.log 2>&1"

# Cron_PostUpload_Document [0-9]
* * * * * bash -l -c "/usr/bin/php8.1 -dxdebug.start_with_request=0 /app/api/cron/postupload/document.php start bot0 >> /var/log/cron.log 2>&1"
* * * * * bash -l -c "/usr/bin/php8.1 -dxdebug.start_with_request=0 /app/api/cron/postupload/document.php start bot10 >> /var/log/cron.log 2>&1"
* * * * * bash -l -c "/usr/bin/php8.1 -dxdebug.start_with_request=0 /app/api/cron/postupload/document.php start bot11 >> /var/log/cron.log 2>&1"
* * * * * bash -l -c "/usr/bin/php8.1 -dxdebug.start_with_request=0 /app/api/cron/postupload/document.php start bot12 >> /var/log/cron.log 2>&1"
* * * * * bash -l -c "/usr/bin/php8.1 -dxdebug.start_with_request=0 /app/api/cron/postupload/document.php start bot13 >> /var/log/cron.log 2>&1"
* * * * * bash -l -c "/usr/bin/php8.1 -dxdebug.start_with_request=0 /app/api/cron/postupload/document.php start bot14 >> /var/log/cron.log 2>&1"
* * * * * bash -l -c "/usr/bin/php8.1 -dxdebug.start_with_request=0 /app/api/cron/postupload/document.php start bot15 >> /var/log/cron.log 2>&1"
19 changes: 19 additions & 0 deletions php_file_node/private/custom.local.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,25 @@
define("NOTICE_BOT_TOKEN" , "${NOTICE_BOT_TOKEN}");
define("NOTICE_CHANNEL_EXCEPTION" , "${NOTICE_CHANNEL_EXCEPTION}");

// -------------------------------------------------------
// ШИФРОВАНИЕ
// -------------------------------------------------------

// для всего остального - один
define("ENCRYPT_KEY_DEFAULT" , "${ENCRYPT_KEY_DEFAULT}"); // ключ
define("ENCRYPT_IV_DEFAULT" , "${ENCRYPT_IV_DEFAULT}"); // вектор шифрования

// -------------------------------------------------------
// SALT ДЛЯ УПАКОВЩИКОВ ПРОЕКТА
// -------------------------------------------------------

// соль для формирования file_map
define("SALT_PACK_FILE" , [
1 => "${SALT_PACK_FILE_1}",
2 => "${SALT_PACK_FILE_2}",
3 => "${SALT_PACK_FILE_3}",
]);

// -------------------------------------------------------
// КЛЮЧИ SOCKET для приложений
// -------------------------------------------------------
Expand Down
9 changes: 8 additions & 1 deletion php_file_node/src/Compass/FileNode/_module_request.php
Original file line number Diff line number Diff line change
Expand Up @@ -37,9 +37,16 @@

\BaseFrame\Conf\ConfHandler::init(
getConfig("SHARDING_GO"), getConfig("SHARDING_SPHINX"), getConfig("SHARDING_RABBIT"),
getConfig("SHARDING_MYSQL"), getConfig("SHARDING_MCACHE"),getConfig("GLOBAL_OFFICE_IP")
getConfig("SHARDING_MYSQL"), getConfig("SHARDING_MCACHE"), getConfig("GLOBAL_OFFICE_IP")
);

\BaseFrame\Crypt\CryptProvider::init([
\BaseFrame\Crypt\CryptProvider::DEFAULT => new \BaseFrame\Crypt\CryptData(ENCRYPT_KEY_DEFAULT, ENCRYPT_IV_DEFAULT),
]);
\BaseFrame\Crypt\PackCryptProvider::init([
\BaseFrame\Crypt\PackCryptProvider::FILE => new \BaseFrame\Crypt\PackCryptData(SALT_PACK_FILE, \BaseFrame\Crypt\CryptProvider::default()),
]);

// возвращаем обработчики
return include_once FILENODE_MODULE_ROOT . "_module/route.php";

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
<?php

namespace Compass\FileNode;

/**
* Класс описывает действие скачивания файла по ссылке и его сохранения на ноде через миграцию
*/
class Domain_File_Action_DownloadByMigration {

protected const _REDIRECT_MAX_COUNT = 10; // максимальное количество редиректов
protected const _MAX_FILE_DOWNLOAD_CONTENT_LENGTH = 1024 * 1024 * 1024; // максимальный размер содержимого для файлов

/**
* Выполняем действие
*
* @throws cs_InvalidFileTypeForSource
* @throws \cs_CurlError
* @throws cs_DownloadFailed
*/
public static function do(int $user_id, string $file_url, int $company_id, string $company_url, int $file_source, string $original_file_name):array {

if (mb_strlen($original_file_name) < 1) {
throw new Domain_File_Exception_IncorrectFileName();
}

// пробуем скачать файл
$file_content = self::_downloadFile($file_url);

// сохраняем содержимое скачиваемого файла во временный файл
$tmp_file_path = Type_File_Utils::generateTmpPath();
Type_File_Utils::saveContentToFile($tmp_file_path, $file_content);

if ($file_source === FILE_SOURCE_MESSAGE_VOICE) {

ffmpeg_exec("-i", $tmp_file_path, "-map", "a", $new_tmp_file_path = Type_File_Utils::generateTmpPath("aac"));
$original_file_name = pathinfo($original_file_name, PATHINFO_FILENAME) . ".aac";
unlink($tmp_file_path);
$tmp_file_path = $new_tmp_file_path;
}

Type_System_Admin::log("migration-file-upload", "user_id: {$user_id} company_urk: {$company_url} file_url: {$file_url} file_source: {$file_source} original_file_name: {$original_file_name} tmp_file_path: {$tmp_file_path}");

// сохраняем файл
return Helper_File::uploadFile($user_id, $company_id, $company_url, $file_source, $original_file_name, $tmp_file_path);
}

/**
* Скачивание файла
*
* @throws \cs_CurlError
* @throws cs_DownloadFailed
*/
protected static function _downloadFile(string $file_url, bool $is_source_trusted = false, int $timeout = 120, string|bool $node_id = false, int $max_file_size = self::_MAX_FILE_DOWNLOAD_CONTENT_LENGTH):string {

// если файл находится на этой же ноде
if (NODE_ID == $node_id) {

$path = parse_url($file_url)["path"];
$path = strstr($path, FOLDER_FILE_NAME);

return file_get_contents(PATH_WWW . $path);
}

$curl = new \Curl();
self::_setTimeout($curl, $timeout);

// получаем файл
$curl->setOpt(CURLOPT_NOBODY, true);
$curl->setOpt(CURLOPT_FOLLOWLOCATION, true);
$curl->setOpt(CURLOPT_MAXREDIRS, self::_REDIRECT_MAX_COUNT);

$curl->get($file_url);

if ($curl->getResponseCode() != 200) {
throw new cs_DownloadFailed();
}

// если нам отдали хедер content-length, то на берегу проверяем, что мы можем скачать файл такой длины
$headers = $curl->getHeaders();
$headers = array_change_key_case($headers, CASE_LOWER);
if (!$is_source_trusted && isset($headers["content-length"])) {

// если нам отдали массив из длины контента
if (is_array($headers["content-length"])) {
$headers["content-length"] = array_pop($headers["content-length"]);
}

// если размер контента больше 1000mb - выходим
if ($headers["content-length"] > $max_file_size) {
throw new cs_DownloadFailed();
}
}

// скачиваем файл
$file_url = $curl->getEffectiveUrl();
$curl->setOpt(CURLOPT_NOBODY, false);
$curl->setOpt(CURLOPT_FOLLOWLOCATION, true);
// мониторим, сколько скачали, если больше 1000 мб, то завершаем
// нельзя верить только хедеру content-length. Злоумышленник или кривые руки разраба может им манипулировать. Для этого и добавлена функция прогресса
$curl->setOpt(CURLOPT_MAXFILESIZE, $max_file_size);
$curl->setOpt(CURLOPT_PROGRESSFUNCTION, function(int $download_size, int $downloaded, int $max_file_size) {

return ($downloaded > $max_file_size) ? 1 : 0;
});

try {
$content = $curl->get($file_url);
} catch (\cs_CurlError) {

// ошибка курла возникнет, если вышли за пределы загружаемого или поймали таймаут
throw new cs_DownloadFailed();
}

if ($curl->getResponseCode() != 200) {
throw new cs_DownloadFailed();
}
return $content;
}

/**
* Устанавливаем timeout для curl
*/
protected static function _setTimeout(\Curl $curl, int $timeout):void {

$curl->setTimeout($timeout);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
use BaseFrame\Monitor\Core;
use BaseFrame\Monitor\MetricAggregator;
use BaseFrame\Monitor\Helper\Metric;
use BaseFrame\Server\ServerProvider;

/**
* Сценарии мониторинга для prometheus
Expand All @@ -32,9 +31,7 @@ public static function collect():string {
self::_collectPostUploadQueue($metric_aggregator, "post_upload_document", FILE_TYPE_DOCUMENT, $need_work);

// отправляем
if (!ServerProvider::isCi()) {
Core::flush();
}
Core::flush();
return $prometheus_sender->metricToString();
}

Expand Down
48 changes: 47 additions & 1 deletion php_file_node/src/Compass/FileNode/api/includes/helper/file.php
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ public static function uploadFile(int $user_id, int $company_id, string $company
// делаем первичную обработку в зависимости от типа файла
try {
$extra = Type_File_Process::doProcessOnUpload($part_path, $company_id, $company_url, $file_type, $user_id, $parent_file_key, $file_extension);
} catch (cs_FileProcessFailed | cs_VideoProcessFailed) {
} catch (cs_FileProcessFailed|cs_VideoProcessFailed) {

// если не смогли обработать и это превью то выбрасываем exception
if ($file_source == FILE_SOURCE_MESSAGE_PREVIEW_IMAGE) {
Expand All @@ -139,4 +139,50 @@ public static function uploadFile(int $user_id, int $company_id, string $company
return $file_row;
}

// метод для сохранения файла на ноде
public static function uploadFileByMigration(int $user_id, int $company_id, string $company_url, int $file_source, string $original_file_name, string $tmp_file_path, int $need_work, string $parent_file_key = "", bool $is_cdn = false):array {

$mime_type = Type_File_Utils::getMimeType($tmp_file_path);
$file_extension = Type_File_Utils::getExtension($original_file_name);
$size_kb = Type_File_Utils::getFileSizeKb($tmp_file_path);
$file_hash = Type_File_Utils::getFileHash($tmp_file_path);
$file_type = Type_File_Main::getFileType($tmp_file_path, $mime_type, $size_kb, $file_source, $file_extension);
$file_source = Type_File_Main::tryGetFileSource($file_type, $file_source);
$part_path = Type_File_Main::moveFileToRandomDirByMigration($tmp_file_path, $file_extension, $company_id);
$file_path = Type_File_Utils::getFilePathFromPartPath($part_path);

// если тип определилили не как картинку, а файл должен им быть - возвращаем ошибку
if ($file_type !== FILE_TYPE_IMAGE && $file_source === FILE_SOURCE_MESSAGE_PREVIEW_IMAGE) {
throw new cs_InvalidFileTypeForSource();
}

// делаем первичную обработку в зависимости от типа файла
try {
$extra = Type_File_Process::doProcessOnUpload($part_path, $company_id, $company_url, $file_type, $user_id, $parent_file_key, $file_extension);
} catch (cs_FileProcessFailed|cs_VideoProcessFailed) {

// если не смогли обработать и это превью то выбрасываем exception
if ($file_source == FILE_SOURCE_MESSAGE_PREVIEW_IMAGE) {
throw new cs_InvalidFileTypeForSource();
}

// иначе отдаем как дефолт и обрабтываем его так
$file_type = FILE_TYPE_DEFAULT;
$extra = Type_File_Default_Process::doProcessOnUpload($part_path, $company_id, $company_url);
}

// получаем размер изображения после обработки
$size_kb = Type_File_Utils::getFileSizeKb($file_path);

// сохраняем файл на файловой ноде
$file_row = Type_File_Main::create(
$user_id, $file_type, $file_source, $size_kb, $mime_type, $original_file_name,
$file_extension, $extra, $part_path, $file_hash, $is_cdn
);

// оправляем на пост обработку
Type_File_Process::sendToPostUpload($file_row, $part_path, $need_work);

return $file_row;
}
}
44 changes: 44 additions & 0 deletions php_file_node/src/Compass/FileNode/api/includes/type/file/main.php
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,50 @@ public static function moveFileToRandomDir(string $src_file_path, string $file_e
return $part_path;
}

// создаем папку под файл
public static function moveFileToRandomDirByMigration(string $src_file_path, string $file_extension, int $company_id):string {

$part_path = Type_File_Utils::generatePathPart($file_extension, $company_id);

// создаем папку с нужным названием
$file_path = Type_File_Utils::getFilePathFromPartPath($part_path);
Type_File_Utils::makeDir($file_path);

// делаем проверку, что такой файл уже существует
self::_throwIfFileExist($file_path);

// перемещает файл который был загружен не с помощью post
copy($src_file_path, $file_path);

// задаем права
chmod($file_path, 0644);

return $part_path;
}

// создаем папку под файл
public static function generatePathPart(string $save_file_path, string $src_file_path, string $file_extension):string {

$part_path = Type_File_Utils::generatePathPartByMigration($save_file_path, $file_extension);

// создаем папку с нужным названием
$file_path = Type_File_Utils::getFilePathFromPartPath($part_path);
Type_File_Utils::makeDir($file_path);

// делаем проверку, что такой файл уже существует
self::_throwIfFileExist($file_path);

// перемещает файл который был загружен не с помощью post
if (copy($src_file_path, $file_path)) {
unlink($src_file_path);
}

// задаем права
chmod($file_path, 0644);

return $part_path;
}

// проверяет что такой файл есть
protected static function _throwIfFileExist(string $file_path):void {

Expand Down
Loading

0 comments on commit 85c7196

Please sign in to comment.