每天自动备份、每小时巡检、定期归档日志,失败要能告警到人,且「谁跑了什么」可追溯。四个包各管一段:
wise-crontab调度、wise-backup备份、wise-health-check巡检、wise-operation-log审计。
场景
运维现状是"七八条系统 crontab,散在不同机器上,跑失败只有一封没人看的邮件"。要收拢成三件事:任务集中登记(不再改 crontab)、失败有人管(告警到群)、事后能复盘(谁跑、跑了多久、退出码多少)。
开始之前
composer require wiseadmin/wise-crontab wiseadmin/wise-backup wiseadmin/wise-health-check wiseadmin/wise-operation-log
php think vendor:publish
php think migrate:run系统 crontab 只需要一条——所有具体任务交给包判断到点没有:
* * * * * cd /path/to/project && php think wise:crontab:run >> /dev/null 2>&1步骤一:任务集中登记
// config/wise-crontab.php
return [
// 收紧成「只允许这几个入口」,不要保留宽松的 /^php\s+/
'allowed_command_patterns' => [
'/^php\s+think\s+wise:(backup:(run|clean)|health:check|operationlog:(archive|clean)|crontab:clean)(\s+--?[a-z][a-z0-9-]*(=\S+)?)*$/',
],
'lock_driver' => 'redis', // 多机部署不要用 file
'log_retention_days' => 30,
'alert' => [
'enabled' => true,
'on_failure' => true,
'on_timeout' => true,
'channels' => ['email', 'dingtalk'],
'throttle' => 300,
'recipients' => ['ops@example.com'],
],
'tasks' => [
[
'name' => '数据库每日备份',
'command' => 'php think wise:backup:run',
'schedule' => '每天凌晨2点', // 等价 0 2 * * *
'allow_concurrent' => false,
'max_retries' => 1,
'timeout' => 3600,
'enabled' => true,
],
[
'name' => '备份保留清理',
'command' => 'php think wise:backup:clean',
'cron_expression' => '10 3 * * *',
'timeout' => 600,
'enabled' => true,
],
[
'name' => '环境健康巡检',
'command' => 'php think wise:health:check --alert',
'schedule' => '每小时',
'timeout' => 180,
'enabled' => true,
],
[
'name' => '操作日志归档',
'command' => 'php think wise:operationlog:archive',
'schedule' => '每天凌晨4点',
'timeout' => 1800,
'enabled' => true,
],
[
'name' => '操作日志清理',
'command' => 'php think wise:operationlog:clean 90 --max=200000 --audit',
'cron_expression' => '30 4 1 * *',
'timeout' => 1800,
'enabled' => true,
],
],
];两个写法细节:schedule(语义化)优先于 cron_expression;任务源是配置文件 + crontab_task 表合并,同名时数据库优先——所以"改配置没生效"先看后台有没有同名任务。
步骤二:备份与保留策略怎么配合
// config/wise-backup.php
'retention' => ['daily' => 7, 'weekly' => 4, 'monthly' => 6],
'destinations' => ['local'],wise:backup:clean 的真实策略:
- 最近
daily天:全留; daily ~ daily + weekly*7天:每周只留最新 1 份;- 超过 35 天:进月桶,每月留最新 1 份,早于 cutoff 全删。
所以每天备份一次 + 每天清理一次就够了,保留层级自动派生。顺序不能反:清理必须排在备份之后,否则某天备份失败时旧包已被删,就没有可用备份了。
异地备份单独一条(多目标也可以直接写进 destinations):
['name' => '数据库每周异地上传', 'command' => 'php think wise:backup:run --destination=s3', 'cron_expression' => '0 3 * * 0', 'enabled' => true]步骤三:告警有两条链路
链路 A(health-check 自带):--alert 只在有异常时推送,渠道来自 .env:
ENV_CHECK_ALERT_ENABLED=true
ENV_CHECK_ALERT_WEBHOOK_URL=https://oapi.dingtalk.com/robot/send?access_token=xxx
ENV_CHECK_ALERT_WEBHOOK_SECRET=xxx链路 B(crontab 把非零退出码变告警):wise:health:check 有任何 warning/error 时退 1 → crontab 记 failure → 触发 CrontabAlertEvent。
AlertManager 只广播事件,真正发信要宿主监听:
// app/event.php
return ['listen' => [
\wise\crontab\event\CrontabAlertEvent::class => [\app\listener\CrontabAlertNotifier::class],
]];namespace app\listener;
use wise\crontab\event\CrontabAlertEvent;
use wise\notification\contract\Message;
use wise\notification\facade\Notification;
class CrontabAlertNotifier
{
public function handle(CrontabAlertEvent $event): void
{
$m = $event->message; // title / content / channels / recipients / task_name / timestamp
Notification::channel(['dingtalk', 'email'])
->priority('urgent')
->send(
\app\model\User::find(1),
new Message(
title: $m['title'] ?? '定时任务异常',
content: $m['content'] ?? '',
data: ['task' => $m['task_name'] ?? '', 'time' => $m['timestamp'] ?? ''],
)
);
}
}复用 wise-notification 比自己裸写 curl 强的地方:重试、熔断、脱敏、发送记录都是现成的。alert.throttle = 300 表示同一任务 300 秒内只告警一次,"每小时巡检"不会刷屏。
步骤四:归档与清理(注意退出码)
// config/wise-operation-log.php
'ttl' => ['days' => 90, 'max_records' => 200000, 'auto_cleanup' => false],
'archive' => [
'enable' => true, // 必须显式开启,否则命令只提示未启用并返回
'trigger' => ['command' => true],
'days' => 90,
'target' => ['type' => 'table', 'table_name' => 'operation_log_archive', 'chunk_size' => 5000],
'after_archive' => ['delete_source' => true],
],
'audit' => ['retention_days' => 1095],php think wise:operationlog:archive --dry-run
php think wise:operationlog:archive
php think wise:operationlog:clean 90 --max=200000 --audit --audit-days=1095一个必须知道的事实:wise:operationlog:archive 与 clean 的 execute() 声明为 : void,ThinkPHP 视为退出码 0——crontab 无法据此判定失败。对策是三条并用:
- 归档前跑
--dry-run人工核对; - 用
wise:operationlog:report --stats判断数据量是否真的下降; - 真要"失败就告警",在宿主包一层返回 int 的自定义 Command 再调度它。
步骤五:执行顺序与维护窗口
同一轮 tick 内按任务列表顺序串行执行。要表达"先后"用依赖表:
php think wise:crontab:dependency add --task=备份保留清理 --depends=数据库每日备份 --condition=success
php think wise:crontab:dependency add --task=操作日志清理 --depends=操作日志归档 --condition=success
php think wise:crontab:window add --start=22:00 --end=02:00 --days=1-5 --reason="夜间发版"依赖条件 success / completed / any;未满足的任务计入 blocked_by_dependency,不会静默跳过。维护窗口用于发版期间避开备份与清理——比临时注释掉任务可靠,因为窗口结束后自动恢复。
步骤六:谁记了什么
| 记录 | 表 | 覆盖范围 |
|---|---|---|
| 任务执行 | crontab_task_log(status / output / exit_code / duration / retry_count) | 所有被调度的 CLI 任务 |
| 操作日志 | operation_log(Attribute 声明、脱敏) | HTTP 请求 |
| 审计日志 | audit_log(POST/PUT/DELETE/PATCH) | HTTP 写操作 |
CLI 巡检没有"操作人":谁跑了巡检看 crontab_task_log,业务改了什么看 operation_log / audit_log。OperationLog 门面没有对外的 record() 方法,所以"让巡检手动写一条操作日志"是做不到的——不要往这个方向设计。
步骤七:命令白名单的三层防护
- 命中
allowed_command_patterns任一正则才执行,否则按失败落库、不启动进程; - 正则之前还有引号感知的 shell 元字符扫描:引号外的
; & | $ > <与换行一律拒绝,双引号内的$(...)/ 反引号也拒绝,单引号内放行; - 白名单挡不住
php -r '<任意代码>'——php开头就命中默认正则。所以生产必须把模式收紧成入口级锚定正则(如步骤一),并限制任务只能由后台授权用户或运维写入。
第 3 条是这一节的重点:白名单是"防手滑",不是"防恶意"。真正的边界是"谁能写任务"。
五条验收信号
php think wise:crontab:list
php think wise:crontab:run
php think wise:crontab:stats --hours=24crontab_task_log有各任务记录,含exit_code与耗时;- 故意让
wise:health:check报异常,CrontabAlertEvent被触发(监听器里有日志即算通); - 写一条不在白名单的命令,被拒绝且没有启动进程;
wise:backup:clean --dry-run列的待删项里,不含保留期内的备份;wise:operationlog:archive之后report --stats的行数明显下降。