diff --git a/.dockerignore b/.dockerignore index 77d8ad4e..bd980854 100644 --- a/.dockerignore +++ b/.dockerignore @@ -10,6 +10,7 @@ runtime *.md JetBrainsMono-字体 node_modules +**/__pycache__ vendor bootstrap/cache/* .caiwu-build diff --git a/.gitignore b/.gitignore index 35ebdef7..d7409223 100644 --- a/.gitignore +++ b/.gitignore @@ -113,6 +113,7 @@ modules/* .workbuddy/ runtime/.env /.private/kaifa-progress-sync/ +__pycache__/ public/net-layer-demo.html public/perf-diff-plan.html public/plan-a-changes-202608.csv diff --git a/AGENTS.md b/AGENTS.md index 93ccc1fa..042a45d9 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -80,6 +80,7 @@ - 当前生产入口为 `https://caiwu.jiansuntuzhi.cn:8442`;公网仍只使用 `8442`,日常发布不得改成无端口地址。 - 发布脚本检测到新增数据库迁移时,由 Codex 核对全部待执行迁移。仅涉及本任务共享镜像建表、字段、索引和同步登记的迁移,完成备份后自主使用 `-AllowMigrations`(macOS 为 `--allow-migrations`);其他迁移仍按第 6 节确认授权。不能因需要迁移开关就把镜像接入停给负责人。 - 容器内 Laravel 命令使用 `www-data`。发布后只需确认部署 SHA、应用容器健康、受影响的真实页面/接口、迁移是否执行,以及当前和上一版镜像可回滚。 +- 生产重型 CLI 导入统一使用 `sh /opt/caiwuxitong/run-finance-batch.sh <命令> <原参数>`,不得在网页容器内直接执行或取消 PHP 内存限制。新增导入登记 `deploy/finance-batch-imports.json`;入口提供独立容器、互斥、资源与时间上限,主应用保留自己的内存边界。 - 程序静态资源随应用镜像同源发布;七牛只存用户上传的业务图片、票据和附件。 - 只有本地初始化、服务器维护、生产发布或数据库迁移任务需要读取 `docs/开发与部署SOP.md` 的对应章节;普通功能开发无需加载整份 SOP。 diff --git a/app/Listeners/Common/RequireImportBatchContainer.php b/app/Listeners/Common/RequireImportBatchContainer.php new file mode 100644 index 00000000..b04ecc2b --- /dev/null +++ b/app/Listeners/Common/RequireImportBatchContainer.php @@ -0,0 +1,28 @@ +environment('production') || config('finance_batch.container')) { + return; + } + + $command = (string) $event->command; + $registered = in_array($command, config('finance_batch.import_commands', []), true); + // New import commands must be registered before they can run in production. + $isImport = preg_match('/(^|:)import(?:$|[-:])/', $command) === 1; + + if ($registered || $isImport) { + throw new RuntimeException( + '生产重型导入必须在受限独立批处理容器中执行,请使用:sh /opt/caiwuxitong/run-finance-batch.sh ' + . $command . ' <原参数>。网页容器未执行本次导入。' + ); + } + } +} diff --git a/app/Providers/Event.php b/app/Providers/Event.php index 7fa845a6..d76f4271 100644 --- a/app/Providers/Event.php +++ b/app/Providers/Event.php @@ -46,6 +46,7 @@ class Event extends Provider ], //'Illuminate\Console\Events\ScheduledTaskStarting' => [ \Illuminate\Console\Events\CommandStarting::class => [ + \App\Listeners\Common\RequireImportBatchContainer::class, \App\Listeners\Common\SkipScheduleInReadOnlyMode::class, ], \App\Events\Auth\LandingPageShowing::class => [ diff --git a/compose.jiangling.yml b/compose.jiangling.yml index 3530a297..97cf8799 100644 --- a/compose.jiangling.yml +++ b/compose.jiangling.yml @@ -94,6 +94,9 @@ services: pull_policy: never container_name: caiwu_app restart: unless-stopped + # Web requests and small scheduled jobs have their own memory boundary. + mem_limit: 2g + memswap_limit: 2g depends_on: db: condition: service_healthy @@ -123,7 +126,7 @@ services: retries: 10 start_period: 45s - # Heavy CLI jobs use a separate cgroup, not Apache's unbounded app container. + # Heavy CLI jobs use a separate cgroup from Apache. batch: image: caiwu_akaunting:${IMAGE_TAG:?IMAGE_TAG is required} pull_policy: never @@ -133,6 +136,7 @@ services: command: [list] restart: "no" environment: + FINANCE_BATCH_CONTAINER: "1" SUPPLIER_PAYABLE_MAINTENANCE_DB_CONNECTION: business_mirror JST_DB_CONNECTION: business_mirror env_file: @@ -142,8 +146,8 @@ services: - ./runtime/.env:/var/www/html/.env:ro - caiwu_storage:/var/www/html/storage cpus: "1.00" - mem_limit: 3g - memswap_limit: 3g + mem_limit: ${FINANCE_BATCH_MEMORY_LIMIT:-3g} + memswap_limit: ${FINANCE_BATCH_MEMORY_LIMIT:-3g} healthcheck: disable: true logging: diff --git a/config/finance_batch.php b/config/finance_batch.php new file mode 100644 index 00000000..8112aa19 --- /dev/null +++ b/config/finance_batch.php @@ -0,0 +1,7 @@ + (bool) env('FINANCE_BATCH_CONTAINER', false), + // The host runner and application share this registry. + 'import_commands' => json_decode(file_get_contents(base_path('deploy/finance-batch-imports.json')), true, 512, JSON_THROW_ON_ERROR), +]; diff --git a/deploy/finance-batch-imports.json b/deploy/finance-batch-imports.json new file mode 100644 index 00000000..9bddc7b7 --- /dev/null +++ b/deploy/finance-batch-imports.json @@ -0,0 +1,31 @@ +[ + "accessory-reship:import-courier-configs", + "account-ledger-remarks:import", + "account-mapping:import-files", + "order-data:import-after-sales-cost", + "business:import-alibaba-account-balances", + "courier-freight:import", + "courier-quotes:import-billing-rules", + "dewu-bills:import-authoritative", + "business-mirror:import-douyin-authoritative", + "finance-ledger:import-base", + "finance-ledger:import-snapshot", + "internal-flow:import", + "inventory:inbound-detail:import", + "business-mirror:import-inventory-report-month", + "business-mirror:import-jd-daily", + "business-mirror:import-jd-wallet", + "jst-order-labels:import-planting-rules", + "jst-order-labels:import", + "business:import-jushuitan-shop-balances", + "pinduoduo-bills:import-authoritative", + "planting-details:import", + "product-catalog:import-authoritative-export", + "product:monthly-weighted-average:base", + "store-violations:import-rules", + "supplier-bookkeeping:import-configs", + "business:import-taobao-alipay-bills", + "taobao-alipay-bills:import-authoritative", + "taobao-wechat-bills:import-authoritative", + "business-mirror:import-third-party-warehouse-anchor" +] diff --git a/deploy/release-guard.sh b/deploy/release-guard.sh index d8cf6ea1..4fde957e 100644 --- a/deploy/release-guard.sh +++ b/deploy/release-guard.sh @@ -34,7 +34,7 @@ caiwu_install_release_files() { # Each uploader has its own directory. Shared runtime files change only inside # the activation lock and after the production revision has been rechecked. [ "$RELEASE_DIR" != "$REMOTE_DIR" ] || return 0 - release_files='compose.jiangling.yml activate-release.sh activate-incremental-release.sh release-guard.sh retired-activation.sh install-release-protection.sh config-db-init.sh run-finance-batch.sh clickhouse-resource-policy.xml update-runtime-url.sh configure-dingtalk-callback.sh host-nginx-8442-dingtalk.conf setup-incremental-registry.sh registry-config.yml' + release_files='compose.jiangling.yml activate-release.sh activate-incremental-release.sh release-guard.sh retired-activation.sh install-release-protection.sh config-db-init.sh run-finance-batch.sh run-finance-import.py finance-batch-imports.json clickhouse-resource-policy.xml update-runtime-url.sh configure-dingtalk-callback.sh host-nginx-8442-dingtalk.conf setup-incremental-registry.sh registry-config.yml' for release_file in $release_files; do [ -f "$RELEASE_DIR/$release_file" ] || { echo "Incomplete staged release: $release_file" >&2; return 1; } done diff --git a/deploy/run-finance-batch.sh b/deploy/run-finance-batch.sh index 5892a9f1..325e5bcf 100644 --- a/deploy/run-finance-batch.sh +++ b/deploy/run-finance-batch.sh @@ -3,7 +3,11 @@ set -eu REMOTE_DIR="${CAIWU_REMOTE_DIR:-/opt/caiwuxitong}" LOCK_FILE="${CAIWU_UPSTREAM_LOCK:-/run/caiwu-upstream-sync.lock}" +is_import=0 +CAIWU_BATCH_CALLER_DIR="$PWD" +export CAIWU_BATCH_CALLER_DIR case "${1:-}" in + *:import|*:import-*|*:import:*|product:monthly-weighted-average:base) is_import=1 ;; jushuitan:sync-shipping|store-receipt:order-match:sync|store-receipt:product-cost:sync|store-receipt:auto-resync|order-data:warm-shop-candidates|business-mirror:index-work-order-waybills|business-mirror:refresh-paid-sales|account-bills:exports:run) ;; *) echo 'Unsupported finance batch command' >&2; exit 64 ;; esac @@ -34,6 +38,9 @@ if [ "$1" != 'account-bills:exports:run' ]; then exit 75 fi fi +if [ "$is_import" -eq 1 ]; then + exec python3 "$REMOTE_DIR/run-finance-import.py" "$@" +fi image="$(docker inspect caiwu_app --format '{{.Config.Image}}')" case "$image" in caiwu_akaunting:*) IMAGE_TAG="${image#*:}" ;; diff --git a/deploy/run-finance-import.py b/deploy/run-finance-import.py new file mode 100644 index 00000000..adf5935d --- /dev/null +++ b/deploy/run-finance-import.py @@ -0,0 +1,89 @@ +#!/usr/bin/env python3 +"""Run registered imports in the existing, resource-limited batch profile.""" +import json +import os +import pathlib +import shutil +import signal +import subprocess +import sys +import tempfile +import uuid + + +def available_memory_kib(): + meminfo = dict(line.split(':', 1) for line in pathlib.Path('/proc/meminfo').read_text().splitlines()) + return int(meminfo['MemAvailable'].split()[0]) + + +def main(): + arguments = sys.argv[1:] + registry = json.loads(pathlib.Path(__file__).with_name('finance-batch-imports.json').read_text()) + if not arguments or arguments[0] not in registry: + print('Unsupported import; register the command in finance-batch-imports.json first.', file=sys.stderr) + return 64 + + # Keep a GiB available to the host in addition to this import's one-GiB cap. + if available_memory_kib() < 2 * 1024 * 1024: + print('Available memory is below 2GiB; no import container started. Retry after other tasks finish.', file=sys.stderr) + return 75 + + environment = os.environ.copy() + environment['FINANCE_BATCH_MEMORY_LIMIT'] = '1g' + environment['RUN_MIGRATIONS'] = '0' + image = subprocess.check_output(['docker', 'inspect', 'caiwu_app', '--format', '{{.Config.Image}}'], text=True).strip() + if not image.startswith('caiwu_akaunting:'): + print('Unsupported active finance image; no import container started.', file=sys.stderr) + return 65 + environment['IMAGE_TAG'] = image.split(':', 1)[1] + container_name = 'caiwu_import_' + uuid.uuid4().hex + command = ['docker', 'compose', '-f', 'compose.jiangling.yml', '--profile', 'batch', 'run', '--rm', '-T', '--no-deps', '--name', container_name] + + # Copy explicit host input files into a private per-run directory. The source + # is never modified; the container gets read-only copies readable by www-data. + with tempfile.TemporaryDirectory(prefix='caiwu-import-') as staging: + inputs = pathlib.Path(staging) / 'inputs' + inputs.mkdir(mode=0o755) + staged_arguments = [arguments[0]] + staged_count = 0 + for argument in arguments[1:]: + prefix = '' + value = argument + if argument.startswith(('--file=', '--path=')): + prefix, value = argument.split('=', 1) + prefix += '=' + source = pathlib.Path(value) + if not source.is_absolute(): + source = pathlib.Path(os.environ.get('CAIWU_BATCH_CALLER_DIR', os.getcwd())) / source + if (prefix or not argument.startswith('-')) and source.is_file(): + parent = inputs / str(staged_count) + parent.mkdir(mode=0o755) + destination = parent / source.name + shutil.copyfile(source, destination) + destination.chmod(0o444) + staged_arguments.append(prefix + '/run/caiwu-import/' + parent.name + '/' + destination.name) + staged_count += 1 + else: + staged_arguments.append(argument) + if staged_count: + command += ['--volume', str(inputs) + ':/run/caiwu-import:ro'] + command += ['--entrypoint', 'php', 'batch', '-d', 'memory_limit=512M', 'artisan', *staged_arguments] + print('Import limits: 1 CPU, 1GiB RAM, no Swap, PHP 512MiB; existing synchronization lock held.', flush=True) + try: + return subprocess.run(command, env=environment, timeout=3600).returncode + except subprocess.TimeoutExpired: + print('Import exceeded one hour; stop and inspect its checkpoint before retrying.', file=sys.stderr) + return 124 + except KeyboardInterrupt: + return 130 + finally: + # Killing only the Compose client would leave the job consuming RAM. + subprocess.run(['docker', 'rm', '--force', container_name], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=15) + + +if __name__ == '__main__': + def interrupted(signum, frame): + raise KeyboardInterrupt + signal.signal(signal.SIGTERM, interrupted) + signal.signal(signal.SIGHUP, interrupted) + sys.exit(main()) diff --git a/docs/开发与部署SOP.md b/docs/开发与部署SOP.md index feee2d7e..83a2f106 100644 --- a/docs/开发与部署SOP.md +++ b/docs/开发与部署SOP.md @@ -289,6 +289,14 @@ sh /opt/caiwuxitong/run-finance-batch.sh store-receipt:order-match:sync YYYY-MM 入口持有现有上游同步锁,使用 `batch` Profile 的独立容器(1 核、3GiB 内存、不使用 Swap、无 Web 健康检查);正常发布不启动该 Profile。先备份再执行回补,失败时保留原有未完成状态,不重复并行启动任务。店铺候选平时按镜像同步时间增量刷新,02:45 使用 `--full` 全量核对。ClickHouse 系统日志的保留期由 `deploy/clickhouse-resource-policy.xml` 管理;业务表不受日志策略影响。 +主应用独立限制为 2GiB 内存,不额外使用 Swap。生产 CLI 导入由同一入口调度,但采用更小的独立额度:1 核、1GiB 内存、PHP 512MiB、不使用 Swap,最长一小时;宿主机可用内存不足 2GiB 时不启动。导入与上游写同步共用互斥锁,退出、超时或中断后清理本次容器;不自动重试或重复导入。既有其他批任务仍使用原来的 3GiB 额度。 + +```bash +sh /opt/caiwuxitong/run-finance-batch.sh order-data:import-after-sales-cost /绝对路径/售后费用.xlsx --dry-run +``` + +输入文件可使用宿主机路径或容器共享 `storage` 路径。宿主机文件会生成临时只读副本,保留原文件名,原件不修改;支持 `--file=/绝对路径/文件.xlsx`。生产网页容器直接运行导入命令会在解析文件前拒绝。本地开发、测试环境沿用原用法。新增导入须登记 `deploy/finance-batch-imports.json`,验证代表性文件的耗时和峰值内存后再发布。正式财务写入仍遵循原有授权及备份要求,使用批入口不等于授权数据修复。 + 查件运单索引 `work_order_waybill_lookup` 只保存原始工单镜像的稳定键、运单号与排序键;工单 JSON 仍为事实来源。升级后先通过上述批入口执行 `business-mirror:index-work-order-waybills --max-batches=0 --pause-ms=50` 完成一次可续传初始化,完成前保留现有核验路径。其后索引与原始工单批次在同一事务中更新,全量校准同时移除失效关联。不得每次导入重新扫描工单 JSON。 销量汇总按 `store_report_paid_sales_dirty_dates` 中的受影响日期更新。业绩明细写入与汇总共用互斥锁,改金额、替换账期和删除都必须登记旧日期及新日期。镜像人工校准后,可通过批入口执行 `business-mirror:refresh-paid-sales --full` 全量重建派生汇总;普通刷新无需全表指纹扫描。科目重算每轮默认处理一个平台月份,再释放同步锁,剩余任务由下一轮继续。 diff --git a/scripts/deploy-from-mac.sh b/scripts/deploy-from-mac.sh index 0fa018a9..28b2596d 100755 --- a/scripts/deploy-from-mac.sh +++ b/scripts/deploy-from-mac.sh @@ -582,6 +582,8 @@ scp_to_remote \ "$repo_root/deploy/install-release-protection.sh" \ "$repo_root/deploy/config-db-init.sh" \ "$repo_root/deploy/run-finance-batch.sh" \ + "$repo_root/deploy/run-finance-import.py" \ + "$repo_root/deploy/finance-batch-imports.json" \ "$repo_root/deploy/clickhouse-resource-policy.xml" \ "$repo_root/deploy/update-runtime-url.sh" \ "$repo_root/deploy/configure-dingtalk-callback.sh" \ diff --git a/scripts/deploy-from-workstation.ps1 b/scripts/deploy-from-workstation.ps1 index 12f18e10..700b7359 100644 --- a/scripts/deploy-from-workstation.ps1 +++ b/scripts/deploy-from-workstation.ps1 @@ -519,6 +519,8 @@ try { deploy/install-release-protection.sh ` deploy/config-db-init.sh ` deploy/run-finance-batch.sh ` + deploy/run-finance-import.py ` + deploy/finance-batch-imports.json ` deploy/clickhouse-resource-policy.xml ` deploy/update-runtime-url.sh ` deploy/configure-dingtalk-callback.sh ` diff --git a/tests/Feature/Business/FinanceImportIsolationTest.php b/tests/Feature/Business/FinanceImportIsolationTest.php new file mode 100644 index 00000000..982c579a --- /dev/null +++ b/tests/Feature/Business/FinanceImportIsolationTest.php @@ -0,0 +1,33 @@ +app['env'] = 'production'; + config(['finance_batch.container' => false]); + // Laravel intentionally disables command events during PHPUnit boot. + // Recreate the production event wiring before exercising real Artisan. + $kernel = app(Kernel::class); + $kernel->rerouteSymfonyCommandEvents(); + $kernel->setArtisan(null); + $blocked = false; + try { + Artisan::call('order-data:import-after-sales-cost', ['file' => '/does-not-exist.xlsx', '--dry-run' => true]); + } catch (RuntimeException $exception) { + $blocked = true; + $this->assertStringContainsString('run-finance-batch.sh', $exception->getMessage()); + $this->assertDatabaseCount('ops_after_sales_cost_rows', 0); + } finally { + $this->app['env'] = 'testing'; + } + $this->assertTrue($blocked, 'Production web runtime accepted a heavy import.'); + } +} diff --git a/tests/Unit/Deployment/FinanceBatchIsolationTest.php b/tests/Unit/Deployment/FinanceBatchIsolationTest.php index f6ef17f3..4a2e4f2f 100644 --- a/tests/Unit/Deployment/FinanceBatchIsolationTest.php +++ b/tests/Unit/Deployment/FinanceBatchIsolationTest.php @@ -17,6 +17,9 @@ class FinanceBatchIsolationTest extends TestCase $process = $this->runBatch($directory, ['jushuitan:sync-shipping', '--days=3']); $this->assertSame(75, $process->getExitCode()); $this->assertFileDoesNotExist($directory . '/called'); + $import = $this->runBatch($directory, ['order-data:import-after-sales-cost', '/input.xlsx', '--dry-run']); + $this->assertSame(75, $import->getExitCode()); + $this->assertFileDoesNotExist($directory . '/called'); flock($lock, LOCK_UN); $process = $this->runBatch($directory, ['jushuitan:sync-shipping', '--days=3']); $this->assertTrue($process->isSuccessful(), $process->getErrorOutput()); diff --git a/tests/Unit/Deployment/FinanceImportRuntimeTest.php b/tests/Unit/Deployment/FinanceImportRuntimeTest.php new file mode 100644 index 00000000..81c0afbc --- /dev/null +++ b/tests/Unit/Deployment/FinanceImportRuntimeTest.php @@ -0,0 +1,79 @@ +previousContainer = Container::getInstance(); + $app = new Application(dirname(__DIR__, 3)); + $app['env'] = 'production'; + $app->instance('config', new Repository([ + 'finance_batch' => ['container' => false, 'import_commands' => ['product:monthly-weighted-average:base']], + ])); + Container::setInstance($app); + } + + protected function tearDown(): void + { + Container::setInstance($this->previousContainer); + parent::tearDown(); + } + + private function starting(string $name): CommandStarting + { + return new CommandStarting($name, new ArrayInput([]), new BufferedOutput()); + } + + public function test_production_imports_cannot_start_in_web_container(): void + { + $this->expectException(RuntimeException::class); + $this->expectExceptionMessage('run-finance-batch.sh'); + (new RequireImportBatchContainer())->handle($this->starting('order-data:import-after-sales-cost')); + } + + public function test_registered_import_without_import_in_its_name_is_also_protected(): void + { + $this->expectException(RuntimeException::class); + (new RequireImportBatchContainer())->handle($this->starting('product:monthly-weighted-average:base')); + } + + public function test_production_batch_runtime_can_import_and_health_checks_stay_available(): void + { + $listener = new RequireImportBatchContainer(); + $listener->handle($this->starting('app:ready')); + config(['finance_batch.container' => true]); + $listener->handle($this->starting('order-data:import-after-sales-cost')); + $this->addToAssertionCount(2); + } + + public function test_local_and_test_imports_keep_their_existing_usage(): void + { + app()['env'] = 'testing'; + (new RequireImportBatchContainer())->handle($this->starting('order-data:import-after-sales-cost')); + $this->addToAssertionCount(1); + } + + public function test_registry_includes_every_existing_import_command(): void + { + $root = dirname(__DIR__, 3); + $commands = json_decode(file_get_contents($root . '/deploy/finance-batch-imports.json'), true, 512, JSON_THROW_ON_ERROR); + foreach (glob($root . '/app/Console/Commands/Import*.php') as $file) { + preg_match('/\$signature\s*=\s*\'([^\s\']+)/', file_get_contents($file), $match); + $this->assertContains($match[1], $commands, basename($file)); + } + } +} diff --git a/tests/scripts/release-guard.sh b/tests/scripts/release-guard.sh index eab0d8c9..1d3d2639 100644 --- a/tests/scripts/release-guard.sh +++ b/tests/scripts/release-guard.sh @@ -120,7 +120,7 @@ new_runtime staged-config RELEASE_DIR="$fixture/staging" RELEASE_APP_URL='' mkdir -p "$RELEASE_DIR" -for file in compose.jiangling.yml activate-release.sh activate-incremental-release.sh release-guard.sh retired-activation.sh install-release-protection.sh config-db-init.sh run-finance-batch.sh clickhouse-resource-policy.xml update-runtime-url.sh configure-dingtalk-callback.sh host-nginx-8442-dingtalk.conf setup-incremental-registry.sh registry-config.yml; do +for file in compose.jiangling.yml activate-release.sh activate-incremental-release.sh release-guard.sh retired-activation.sh install-release-protection.sh config-db-init.sh run-finance-batch.sh run-finance-import.py finance-batch-imports.json clickhouse-resource-policy.xml update-runtime-url.sh configure-dingtalk-callback.sh host-nginx-8442-dingtalk.conf setup-incremental-registry.sh registry-config.yml; do printf 'new staged runtime configuration\n' > "$RELEASE_DIR/$file" done printf '#!/bin/sh\nexit 0\n' > "$RELEASE_DIR/install-release-protection.sh" diff --git a/tests/scripts/test_finance_import.py b/tests/scripts/test_finance_import.py new file mode 100644 index 00000000..4b1f4796 --- /dev/null +++ b/tests/scripts/test_finance_import.py @@ -0,0 +1,87 @@ +import importlib.util +import json +import os +import pathlib +import subprocess +import tempfile +import unittest +from unittest import mock + +ROOT = pathlib.Path(__file__).resolve().parents[2] +SPEC = importlib.util.spec_from_file_location('finance_import', ROOT / 'deploy/run-finance-import.py') +RUNNER = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(RUNNER) + + +class FinanceImportTest(unittest.TestCase): + def run_import(self, arguments, callback=None, memory=8*1024*1024): + with mock.patch.object(RUNNER, 'available_memory_kib', return_value=memory), \ + mock.patch.object(RUNNER.sys, 'argv', ['run-finance-import.py', *arguments]), \ + mock.patch.object(RUNNER.subprocess, 'check_output', return_value='caiwu_akaunting:123456789abc\n'), \ + mock.patch.object(RUNNER.subprocess, 'run') as run: + run.return_value = subprocess.CompletedProcess([], 0) + if callback: + run.side_effect = callback + result = RUNNER.main() + return result, run.call_args_list + + def test_input_is_read_only_original_is_preserved_and_arguments_are_not_shell_code(self): + with tempfile.TemporaryDirectory() as folder: + original = pathlib.Path(folder) / 'file with spaces.xlsx' + original.write_bytes(b'original workbook') + staged = [] + + def execute(command, **kwargs): + if command[1] == 'rm': + return subprocess.CompletedProcess(command, 0) + self.assertIn('--no-deps', command) + self.assertIn('memory_limit=512M', command) + self.assertEqual('1g', kwargs['env']['FINANCE_BATCH_MEMORY_LIMIT']) + self.assertEqual('0', kwargs['env']['RUN_MIGRATIONS']) + self.assertIn('--source-name=$(touch forbidden)', command) + mount = command[command.index('--volume') + 1] + self.assertTrue(mount.endswith(':/run/caiwu-import:ro')) + target = pathlib.Path(mount.rsplit(':', 2)[0]) / '0' / original.name + self.assertEqual(original.read_bytes(), target.read_bytes()) + self.assertEqual(0, target.stat().st_mode & 0o222) + self.assertEqual('/run/caiwu-import/0/' + original.name, command[-2]) + staged.append(target) + return subprocess.CompletedProcess(command, 0) + + result, calls = self.run_import(['business:import-alibaba-account-balances', str(original), '--source-name=$(touch forbidden)'], execute) + self.assertEqual(0, result) + self.assertEqual(b'original workbook', original.read_bytes()) + self.assertFalse(staged[0].exists()) + self.assertEqual('rm', calls[-1].args[0][1]) + + def test_named_file_option_is_mapped_without_changing_its_name(self): + with tempfile.TemporaryDirectory() as directory: + source = pathlib.Path(directory) / 'named.xlsx' + source.write_bytes(b'workbook') + result, calls = self.run_import(['jst-order-labels:import', '--file=' + str(source)]) + self.assertEqual(0, result) + self.assertEqual('--file=/run/caiwu-import/0/' + source.name, calls[0].args[0][-1]) + + def test_low_memory_does_not_start_a_container(self): + result, calls = self.run_import(['order-data:import-after-sales-cost', '/input.xlsx'], memory=1024*1024) + self.assertEqual(75, result) + self.assertEqual([], calls) + + def test_unknown_import_is_rejected(self): + result, calls = self.run_import(['unknown:import', '/input.xlsx']) + self.assertEqual(64, result) + self.assertEqual([], calls) + + def test_timeout_removes_the_actual_job_container(self): + def execute(command, **kwargs): + if command[1] == 'compose': + raise subprocess.TimeoutExpired(command, kwargs['timeout']) + return subprocess.CompletedProcess(command, 0) + result, calls = self.run_import(['order-data:import-after-sales-cost', '/input.xlsx'], execute) + self.assertEqual(124, result) + started = calls[0].args[0] + self.assertEqual(['docker', 'rm', '--force', started[started.index('--name') + 1]], calls[-1].args[0]) + + +if __name__ == '__main__': + unittest.main()