请演示用 systemd 定时任务每晚批量生成 500 张优惠券 SVG。
解读
面试官把“Linux 自动化运维 + Inkscape 批量出图”两个高频场景揉在一起,考察三点:
- 对 Inkscape 命令行(--export-type=svg、--export-filename、--actions 等)是否熟悉;
- 能否用 systemd timer 替代传统 crontab,实现“可追踪、可日志、可失败重启”的企业级定时方案;
- 脚本是否具备工程化思维:参数化、并发控制、错误重试、资源清理、国产操作系统兼容性(统信 UOS、麒麟等默认 systemd 环境)。
知识点
- Inkscape 1.x 以上版本 CLI 语法差异(--actions 取代 --verb)
- SVG 模板化:保留图层、变量占位符、inkscape:label 机制
- systemd timer 单元与 service 单元配对写法,OnCalendar 语法,AccuracySec,Persistent 选项
- Linux 临时目录规范(/tmp、/run/user/$(id -u))、systemd 私有临时目录(PrivateTmp=true)
- 并发控制:GNU Parallel、xargs -P、 flock 文件锁,防止 500 进程打爆 CPU
- 字体嵌入与商用版权:思源黑体、阿里巴巴普惠体(免费可商用),避免 Windows 字体
- 国产系统日志查看:journalctl -u 服务名 -b,方便甲方运维审计
- 失败通知:systemd 的 OnFailure= 可以调用 mailx 或企业微信 webhook
答案
-
目录规划(一次性 root 操作) mkdir -p /opt/coupon/{tpl,out,log,scripts} chown -R designer:designer /opt/coupon # 非 root 用户运行,满足等保要求
-
准备 SVG 模板 /opt/coupon/tpl/coupon.tpl.svg 关键行示例: <text id="sn" x="100" y="200" font-family="AlibabaPuHuiTi-2-65-Medium" font-size="32" fill="#e60012">SN_PLACEHOLDER</text> <text id="qr" x="400" y="200">QR_PLACEHOLDER</text>
-
批量生成脚本 /opt/coupon/scripts/batch_svg.sh #!/usr/bin/env bash set -euo pipefail TPL=/opt/coupon/tpl/coupon.tpl.svg OUT=/opt/coupon/out LOG=/opt/coupon/log/OUT ]] || mkdir -p "$OUT"
清空当天旧文件,避免重复
rm -f "$OUT"/*.svg
并发 8,CPU 核心数自适应
seq -w 1 500 | parallel -j 8 --progress
'SN={1} &&
QR=SN | qrencode -t SVG -o -) &&
sed -e "s/SN_PLACEHOLDER/QR|g" '"OUT"/coupon_{1}.svg' 2>&1 >> '"(date '+%F %T') batch done, count=OUT"'/*.svg | wc -l)" >> "$LOG"chmod +x /opt/coupon/scripts/batch_svg.sh
-
systemd service 单元 /etc/systemd/system/coupon-svg.service [Unit] Description=Batch generate 500 coupon SVGs After=network.target
[Service] Type=oneshot User=designer Group=designer ExecStart=/opt/coupon/scripts/batch_svg.sh WorkingDirectory=/opt/coupon PrivateTmp=true NoNewPrivileges=true
失败自动通知运维
OnFailure=coupon-failure-notify.service
日志统一走 journal
StandardOutput=journal StandardError=journal
-
systemd timer 单元 /etc/systemd/system/coupon-svg.timer [Unit] Description=Run coupon-svg daily at 01:30 Beijing time
[Timer] OnCalendar=--* 01:30:00
如果机器关机错过,开机后立刻补跑
Persistent=true AccuracySec=30s
[Install] WantedBy=timers.target
-
启用并验证 systemctl daemon-reload systemctl enable --now coupon-svg.timer
手动验证一次
systemctl start coupon-svg.service journalctl -u coupon-svg -f # 实时观察 ls /opt/coupon/out | wc -l # 应为 500
拓展思考
-
如果优惠券需要正反两面,可改用 Inkscape 的“图层可见性”动作: --actions="layer-show:front;export-filename:front_{SN}.svg;export-do;layer-hide:front;layer-show:back;export-filename:back_{SN}.svg;export-do" 一条命令输出两张图,减少 500→1000 的 I/O。
-
当 500 张图需要压缩成 ZIP 供市场部次日下载,可在 service 单元追加: ExecStartPost=/usr/bin/zip -j /opt/coupon/out/coupon_$(date +%F).zip /opt/coupon/out/*.svg 并配合 nginx autoindex 实现内网 HTTPS 下载,全程无人值守。
-
若未来版式升级,模板文件需热更新而不中断 timer,可把模板放 Git 仓库,脚本开头先 git pull,实现 CI/CD 化;同时用 systemd 的 Conflicts= 机制防止拉取时并发执行。
-
国内等保 2.0 要求“最小权限”,脚本里禁止 sudo、禁止写 /tmp 全局目录;日志留存 6 个月以上,可配置 logrotate 按日切割,并加密上传至公司堡垒机备份。