Gitlab多个项目自动聚合到一个项目

最近公司在搞知识库,整个线路是把md文件上传到Gitlab多个仓库,然后再由Weknora自动去同步,但是Weknora的知识库给AI检索还好,给人去阅读的话不是很方便,所以需要一个md渲染平台还需要做权限控制,调研了下,发现wikijs比较合适,但是wikijs只能同步一个Gitlab仓库,我们需要同步多个仓库,所以就考虑在Gitlab新建一个聚合仓库,把需要同步的仓库都自动聚合到这个聚合仓库里,wikijs再同步这个聚合仓库。

wikijs部署步骤就不赘述了,通过官方文档去部署即可,这里说下怎么把多个Gitlab仓库同步到一个聚合仓库里。

方案总览

最终形态是:

plaintext

1
2
3
4
5
6
7
8
9
10
11
12
13
product-base  push main
│
├─ CI job → 调用 GitLab 触发 API ──┐
│
product-iter push main │
│ ▼
└─ CI job → 调用 GitLab 触发 API ──► docs-wiki 流水线
│
├─ clone 两个源仓库
├─ rsync 到 product-base/ 和 product-iter/
├─ commit + push
▼
Wiki.js 定时拉取 docs-wiki

准备工作

安装gitlab-runner

先在Gitlab群组里装一个共享的runner:

在一台能访问Gitlab的服务器上安装gitlab-runner:

1
2
3
4
5
6
7
8
9
10
11
12
# Download the binary for your system
sudo curl -L --output /usr/local/bin/gitlab-runner https://gitlab-runner-downloads.s3.amazonaws.com/latest/binaries/gitlab-runner-linux-amd64

# Give it permissions to execute
sudo chmod +x /usr/local/bin/gitlab-runner

# Create a GitLab CI user
sudo useradd --comment 'GitLab Runner' --create-home gitlab-runner --shell /bin/bash

# Install and run as service
sudo gitlab-runner install --user=gitlab-runner --working-directory=/home/gitlab-runner
sudo gitlab-runner start

把runner注册到Gitlab:

1
gitlab-runner register   --non-interactive   --url "http://gitlab.example.com/"   --registration-token "********V7"   --executor "docker"   --docker-image "swr.cn-north-4.myhuaweicloud.com/ddn-k8s/docker.io/library/alpine:3.20.2"   --description "docs-sync-group-runner"   --tag-list ""   --run-untagged=true   --locked=false

注册完之后到gitlab上查看是否在线:

gitlab-runner的配置文件在/etc/gitlab-runner/config.toml,要修改配置的话,可以修改此文件,然后重启gitlab-runner:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
[root@qifu-host02 ~]# cat /etc/gitlab-runner/config.toml 
concurrent = 1
check_interval = 0
shutdown_timeout = 0

[session_server]
session_timeout = 1800

[[runners]]
name = "docs-sync-group-runner"
url = "http://172.17.229.30:9980/"
clone_url = "http://172.17.229.30:9980/"
id = 1
token = "_****Xc"
token_obtained_at = 2026-12-03T03:00:28Z
token_expires_at = 0001-01-01T00:00:00Z
executor = "docker"
run_untagged = true
locked = false
[runners.cache]
MaxUploadedArchiveSize = 0
[runners.cache.s3]
AssumeRoleMaxConcurrency = 0
[runners.cache.gcs]
[runners.cache.azure]
[runners.docker]
tls_verify = false
image = "docs-sync-tools:1.0"
pull_policy = "if-not-present"
extra_hosts = ["git.example.com:172.17.229.30"]
privileged = false
disable_entrypoint_overwrite = false
oom_kill_disable = false
disable_cache = false
volumes = ["/cache"]
volume_keep = false
shm_size = 0
network_mtu = 0
1
gitlab-runner restart  ##重启

构建gitlab-runner的镜像

Dockerfile:

1
2
3
4
FROM swr.cn-north-4.myhuaweicloud.com/ddn-k8s/docker.io/library/alpine:3.20.2
RUN apk add --no-cache git rsync curl ca-certificates \
&& git config --global user.name "Docs Sync Bot" \
&& git config --global user.email "bot@keyfil.com"

构建打包:

1
docker build -t docs-sync-tools:1.0 .

确认三个仓库的基本信息

先收集好这些信息,后面用到:

示例值项目说明
mygroup/product-base源仓库 1完整路径,含 group
mygroup/product-iter源仓库 2完整路径,含 group
mygroup/docs-wiki聚合仓库新建的
https://gitlab.example.comGitLab 地址自托管填自己的,SaaS 填 https://gitlab.com
master分支名两边保持一致
数字,如 12345聚合仓库项目 ID在 docs-wiki 项目首页能看到

需要在三个仓库上都有 Maintainer 或以上权限,否则建不了 trigger token 和 CI 变量。

创建聚合仓库

  1. GitLab 首页点 New project → Create blank project。
  2. Project name 填 docs-wiki。
  3. Project URL 选一个合适的 group,比如 mygroup/docs-wiki。
  4. Visibility Level 选 Private。
  5. 点 Create project。
  6. 进入项目后,在右上角或项目首页找到 Project ID,记下来,比如 12345。
  7. 在项目里手动建一个master分支:
    • 进入 Repository → Branches。
    • 如果默认分支已经是 master,跳过。
    • 如果是 main,点 Settings → Repository → Default branch,改成 master。

创建专用机器人账号并生成 PAT

这一步是为了让聚合仓库的 CI 能“读两个源仓库、写聚合仓库”。

  1. 创建一个专用账号,比如 docs-sync-bot(或者用你自己的账号也行,但专用账号更安全)。
  2. 用这个账号登录 GitLab。
  3. 右上角头像 → Preferences / User Settings → Access Tokens。
  4. 点 Add new token。
  5. Token name 填 docs-sync。
  6. Expiration date 设一个远期日期,比如一年后。
  7. Scopes 勾选:
    • read_repository
    • write_repository
  8. 点 Create personal access token。
  9. 立刻复制 token,页面刷新后就看不到了。这个值记作 MIRROR_TOKEN。

给机器人账号授权

  1. 进入product-base→Settings → Members → Invite members:
    • 搜索 docs-sync-bot
    • Role 选 Reporter(只读够了)
    • 点 Invite
  2. 进入 product-iter,同样操作,Role 选 Reporter。
  3. 进入docs-wiki→Settings → Members → Invite members:
    • 搜索 docs-sync-bot
    • Role 选 Maintainer
    • 点 Invite

为什么聚合仓库要给 Maintainer:如果 main 是受保护分支,Developer 可能 push 不进去。Maintainer 最省事。

本地验证 PAT 权限

在电脑上执行下面命令,把占位符替换掉:

1
git clone https://oauth2:你的MIRROR_TOKEN@gitlab.example.com/mygroup/product-base.git /tmp/test-base

能 clone 成功说明读权限没问题。

再测写权限:

1
2
3
4
5
6
git clone https://oauth2:你的MIRROR_TOKEN@gitlab.example.com/mygroup/docs-wiki.git /tmp/test-wiki
cd /tmp/test-wiki
echo test > test-write.txt
git add test-write.txt
git commit -m "test token write"
git push origin HEAD:main

推送成功后,去 GitLab 网页把 test-write.txt 删掉,再提交一次,或者直接在仓库里删除这个文件。验证完记得清理测试仓库。


配置聚合仓库

在聚合仓库添加 CI 变量

进入 docs-wiki → Settings → CI/CD → Variables → Add variable,逐个添加:

KeyValue勾选
MIRROR_TOKEN第 3 步的 PATMasked ✅;
SYNC_REPOSproduct-base=kbase/product-base product-iter=kbase/product-iter空格分隔多个仓库,后续需要加仓库的话,修改这个变量即可
SYNC_BRANCHmaster默认分支

说明:

  • MIRROR_TOKEN 一定要勾 Masked,否则日志可能泄露。
  • master分支没保护的话,Protected不勾。

在聚合仓库生成 Pipeline trigger token

  1. 进入 docs-wiki → Settings → CI/CD。
  2. 展开 Pipeline trigger tokens。
  3. 点 Add new token。
  4. Description 填 wiki-sync-trigger。
  5. 点 Create pipeline trigger token。
  6. 立刻复制 token,记作 WIKI_TRIGGER_TOKEN。

这个 token 代表创建者的权限,所以创建者必须对 docs-wiki 有 Maintainer 权限。

确认聚合仓库有可用的 Runner

  1. 进入 docs-wiki → Settings → CI/CD → Runners。
  2. 确认 Available shared runners 是启用的,或者你有自己的 runner。
  3. 记一下 runner 用的是 Docker 还是 Shell,后面镜像配置要对应。

如果没有 runner,CI 不会跑,后面全白搭。

创建聚合仓库的 .gitlab-ci.yml

在 docs-wiki 仓库根目录新建文件 .gitlab-ci.yml,内容如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
stages:
- sync

sync-docs:
stage: sync
image: docs-sync-tools:1.0
resource_group: docs-aggregate
interruptible: false
rules:
- if: '$CI_PIPELINE_SOURCE == "schedule"'
- if: '$CI_PIPELINE_SOURCE == "web"'
- if: '$CI_PIPELINE_SOURCE == "trigger"'
script:
- 'echo "SYNC_SOURCE=[${SYNC_SOURCE:-all}]"'
- |
for item in $SYNC_REPOS; do
name=${item%%=*}
target=${item#*=}
case "$target" in
*:*) path=${target%%:*}; branch=${target##*:} ;;
*) path="$target"; branch="$SYNC_BRANCH" ;;
esac
if [ "${SYNC_SOURCE:-all}" = "all" ] || [ "$SYNC_SOURCE" = "$name" ]; then
echo "Cloning $name <- $path (branch: $branch)"
git clone --depth 1 -b "$branch" "http://oauth2:${MIRROR_TOKEN}@172.17.229.30:9980/${path}.git" "_src_$name"
fi
done
- |
for item in $SYNC_REPOS; do
name=${item%%=*}
if [ -d "_src_$name" ]; then
mkdir -p "$name"
rsync -a --delete --exclude=.git --exclude=.gitlab-ci.yml "_src_$name/" "$name/"
rm -rf "_src_$name"
fi
done
- rm -rf _src_*
- git add -A
- 'if git diff --cached --quiet; then echo "No content changes. Skip commit."; exit 0; fi'
- 'git commit -m "chore: sync docs from ${SYNC_SOURCE:-all} [skip ci]"'
- git push "http://oauth2:${MIRROR_TOKEN}@172.17.229.30:9980/${CI_PROJECT_PATH}.git" "HEAD:${CI_DEFAULT_BRANCH}"

逐行解释几个关键点:

  • resource_group: docs-aggregate:保证同时来两个触发时排队执行,不会一起 push 冲突。
  • rules 只接受 schedule / web / trigger,故意不接受 push,避免自己提交的 commit 又触发自己形成死循环。
  • rsync --delete:源仓库删文件,聚合仓库也删。
  • --exclude='.gitlab-ci.yml':防止把源仓库的 CI 配置复制进 Wiki 内容里。
  • [skip ci]:双保险,即使将来加了 push 规则也不会自触发。
  • CI_PROJECT_PATH、CI_DEFAULT_BRANCH 都是 GitLab 内置变量,不用填。

提交这个文件到 master。

手动跑一次聚合仓库流水线验证

  1. 进入 docs-wiki → Build → Pipelines。
  2. 点右上角 Run pipeline。
  3. 分支选 master。
  4. 点 Run pipeline。
  5. 等 job sync-docs 变绿。
  6. 进入Repository → Files,确认出现了:
    • product-base/
    • product-iter/
  7. 点进目录,确认里面的 md 文件都在。

如果这里失败,先看 job 日志,常见原因见最后的排查表。


配置两个源仓库的自动触发

在 product-base 添加触发变量

  1. 进入 product-base → Settings → CI/CD → Variables → Add variable。
  2. 添加:
KeyValue勾选
WIKI_TRIGGER_TOKEN第 7 步复制的 trigger tokenMasked ✅
WIKI_PROJECT_ID12345(聚合仓库数字 ID)无

确认 product-base 的 Runner 可用

  1. 进入 product-base → Settings → CI/CD → Runners。
  2. 确认有可用 runner。触发 job 只需要 curl,任何 Docker runner 都能跑。

在 product-base 添加触发 job

打开 product-base 仓库根目录的 .gitlab-ci.yml。

情况 A:原来没有 .gitlab-ci.yml

新建文件,内容:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
stages:
- build
- test
- deploy

trigger-wiki-sync:
stage: deploy
image: docs-sync-tools:1.0
rules:
- if: '$CI_COMMIT_BRANCH == "master"'
script:
- |
curl --fail --request POST \
--form "token=$WIKI_TRIGGER_TOKEN" \
--form "ref=master" \
--form "variables[SYNC_SOURCE]=product-base" \
"http://172.17.229.30:9980/api/v4/projects/${WIKI_PROJECT_ID}/trigger/pipeline"

情况 B:原来已经有 .gitlab-ci.yml

不要覆盖,直接在文件末尾追加:

1
2
3
4
5
6
7
8
9
10
11
12
trigger-wiki-sync:
stage: deploy
image: docs-sync-tools:1.0
rules:
- if: '$CI_COMMIT_BRANCH == "master"'
script:
- |
curl --fail --request POST \
--form "token=$WIKI_TRIGGER_TOKEN" \
--form "ref=master" \
--form "variables[SYNC_SOURCE]=product-base" \
"http://172.17.229.30:9980/api/v4/projects/${WIKI_PROJECT_ID}/trigger/pipeline"

如果你原来的文件里自定义了 stages,比如:

1
2
3
stages:
- build
- test

那必须在 stages 里加上 deploy,否则 job 会报 stage not found:

1
2
3
4
stages:
- build
- test
- deploy

提交到 master。

在 product-iter 重复此步骤

完全一样的配置:

  • 变量 WIKI_TRIGGER_TOKEN = 同一个 trigger token
  • 变量 WIKI_PROJECT_ID = 同一个 12345
  • .gitlab-ci.yml 里追加同样的 job:(只改这一项:–form “variables[SYNC_SOURCE]=product-iter”)

其他不需要改任何东西,因为聚合仓库的脚本本来就同步两个目录。

验证源仓库触发是否生效

  1. 在 product-base 里随便改一个 md 文件,commit message 写 test wiki sync,push 到 master。
  2. 进入 product-base → Build → Pipelines,确认 trigger-wiki-sync job 是绿色。
  3. 进入 docs-wiki → Build → Pipelines,应该看到一条 source 为 trigger 的新流水线。
  4. 等 sync-docs job 变绿。
  5. 进入 docs-wiki → Repository → Commits,看到一条 chore: sync docs from source repos [skip ci]。
  6. 打开 product-base/ 目录,确认你刚改的文件内容已经更新。
  7. 对 product-iter 重复一次。

加定时兜底

在聚合仓库建定时流水线

  1. 进入 docs-wiki → Build → Pipeline schedules。
  2. 点 New schedule。
  3. Description 填 wiki docs fallback sync。
  4. Interval pattern 填:

plaintext

1
0 * * * *

表示每小时整点跑一次。如果你想更频繁,填 */30 * * * *。

  1. Target branch 选 master。
  2. 变量留空。
  3. 点 Create pipeline schedule。

这条定时任务的作用是:万一某次 push 触发失败、token 过期、有人绕过 CI 直接改文件,最终也能被纠正回来。

定时清理

pipeline和job的记录不会自动清理,时间一长,数据太多,我们可以通过调用API去删除,这里写个脚本定时清理这些数据以及docker构建残留和docker运行时间长导致的大log日志(没有在/etc/docker/daemon.json里做日志管理的情况)

gitlab-cleanup.sh:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
#!/usr/bin/env bash
# GitLab CI 清理脚本:删除旧流水线(连带 job 日志)、清除旧 job 日志、清理 Runner 上的 Docker 垃圾
#
# 部署:
# 1. mkdir -p /etc/gitlab-cleanup /opt/scripts
# 2. echo -n '你的PAT(api scope)' > /etc/gitlab-cleanup/gitlab.token
# chmod 600 /etc/gitlab-cleanup/gitlab.token
# 3. yum install -y jq || apt-get install -y jq
# 4. 把本脚本放到 /opt/scripts/gitlab-cleanup.sh,chmod +x
# 5. 先预览:DRY_RUN=1 /opt/scripts/gitlab-cleanup.sh all
# 6. crontab -e 加入(GitLab 和 Runner 都在本机时):
# 0 4 * * * /opt/scripts/gitlab-cleanup.sh docker >> /var/log/gitlab-cleanup.log 2>&1
# 0 5 * * 0 /opt/scripts/gitlab-cleanup.sh pipelines >> /var/log/gitlab-cleanup.log 2>&1
# 如果 GitLab 在另一台机器,把 pipelines 那行放到 GitLab 机器上执行,docker 留在 Runner 机器。
#
# 注意:PAT 需要 api scope,账号对三个项目 Owner 权限。
#
# 用法:
# gitlab-cleanup.sh pipelines # 删除旧流水线(同时删除其 job 和日志)
# gitlab-cleanup.sh logs # 只清除旧 job 的日志(erase),保留流水线记录
# gitlab-cleanup.sh docker # 清理 Docker 垃圾 + 截断超大 json.log
# gitlab-cleanup.sh all # pipelines + docker(默认)
# DRY_RUN=1 gitlab-cleanup.sh all # 只打印将要做什么,不实际删除

set -uo pipefail

# ===================== 配置区 =====================
# GitLab 访问地址(API 用),用 IP 避免 DNS 问题
GITLAB_BASE="${GITLAB_BASE:-http://172.17.229.30:9980}"

# PAT 存放文件,内容只有 token 一行,权限 600
TOKEN_FILE="${TOKEN_FILE:-/etc/gitlab-cleanup/gitlab.token}"

# 三个项目,填 URL 编码后的路径(/ 写成 %2F)或纯数字项目 ID
# docs-wiki 的项目 ID 是 181;下面三个路径请按你们实际情况核对
PROJECTS=(
"kbase%2Fproduct-base"
"kbase%2Fproduct-iter"
"kbase%2Fdocs-wiki"
)

# 保留策略
KEEP_DAYS="${KEEP_DAYS:-30}" # 删除多少天前的流水线/日志
KEEP_RECENT="${KEEP_RECENT:-10}" # 每个项目至少保留最近 N 条,避免误删刚跑完的
LOG_TRUNCATE_MB="${LOG_TRUNCATE_MB:-500}" # 超过该大小的容器 json.log 截断为 0
DOCKER_PRUNE_HOURS="${DOCKER_PRUNE_HOURS:-168}" # Docker 容器/构建缓存保留小时数(168=7天)
DOCKER_ROOT="${DOCKER_ROOT:-/var/lib/docker}" # Docker data-root

DRY_RUN="${DRY_RUN:-0}"
LOCK_FILE="/var/lock/gitlab-cleanup.lock"
# =================================================

log() { printf '[%s] %s\n' "$(date '+%F %T')" "$*"; }
die() { log "ERROR: $*"; exit 1; }

check_deps() {
local need=(curl jq flock)
case "${1:-all}" in
docker|all) need+=(docker find truncate date) ;;
esac
local c
for c in "${need[@]}"; do
command -v "$c" >/dev/null 2>&1 || die "缺少命令 [$c],请先安装(jq: yum install -y jq)"
done
}

load_token() {
if [ -n "${GITLAB_TOKEN:-}" ]; then
PAT="$GITLAB_TOKEN"
elif [ -r "$TOKEN_FILE" ]; then
PAT=$(tr -d '\r\n' < "$TOKEN_FILE")
else
die "读不到 PAT:请把 token 写入 $TOKEN_FILE 并设置权限 600"
fi
[ -n "$PAT" ] || die "PAT 为空,拒绝执行"
}

api_get() {
local path="$1"
curl -sS --max-time 30 -H "PRIVATE-TOKEN: $PAT" "${GITLAB_BASE}/api/v4${path}"
}

# 分页收集 "id<TAB>created_at",endpoint 需自带 ?scope=finished
collect_items() {
local endpoint="$1" out="$2"
local sep="?"
case "$endpoint" in *\?*) sep="&" ;; esac
: > "$out"
local page=1 resp typ count
while [ "$page" -le 100 ]; do
resp=$(api_get "${endpoint}${sep}per_page=100&page=${page}")
typ=$(printf '%s' "$resp" | jq -r 'type' 2>/dev/null || echo error)
if [ "$typ" != "array" ]; then
log "API 返回异常(${endpoint} page=${page}): $(printf '%s' "$resp" | head -c 200)"
break
fi
count=$(printf '%s' "$resp" | jq 'length')
[ "$count" -eq 0 ] && break
printf '%s' "$resp" | jq -r '.[] | "\(.id)\t\(.created_at)"' >> "$out"
page=$((page + 1))
done
}

cleanup_pipelines() {
load_token
local tmp cutoff proj total id created ts code deleted=0 kept=0
tmp=$(mktemp)
cutoff=$(date -u -d "${KEEP_DAYS} days ago" +%s)

for proj in "${PROJECTS[@]}"; do
log "项目 ${proj}: 拉取已完成的流水线列表"
collect_items "/projects/${proj}/pipelines?scope=finished" "$tmp"
total=$(wc -l < "$tmp" | tr -d ' ')
log "项目 ${proj}: 共 ${total} 条已完成流水线,保留最近 ${KEEP_RECENT} 条,删除 ${KEEP_DAYS} 天前的"

sort -rn "$tmp" | tail -n +$((KEEP_RECENT + 1)) | while IFS=$'\t' read -r id created; do
[ -n "$id" ] || continue
ts=$(date -u -d "$created" +%s 2>/dev/null || echo 0)
[ "$ts" -ge "$cutoff" ] && continue

if [ "$DRY_RUN" = "1" ]; then
log "[DRY] 项目 ${proj}: 将删除 pipeline ${id} (${created})"
continue
fi
code=$(curl -sS -o /dev/null -w '%{http_code}' --max-time 30 -X DELETE \
-H "PRIVATE-TOKEN: $PAT" \
"${GITLAB_BASE}/api/v4/projects/${proj}/pipelines/${id}")
case "$code" in
200|204) log "项目 ${proj}: 已删除 pipeline ${id}"; deleted=$((deleted + 1)) ;;
429) log "项目 ${proj}: 触发限流,跳过 pipeline ${id},下次任务重试" ;;
*) log "项目 ${proj}: 删除 pipeline ${id} 失败,HTTP ${code}" ;;
esac
sleep 0.2
done
done
rm -f "$tmp"
log "流水线清理结束。DRY_RUN=${DRY_RUN}"
}

cleanup_job_logs() {
load_token
local tmp cutoff proj total id created ts code
tmp=$(mktemp)
cutoff=$(date -u -d "${KEEP_DAYS} days ago" +%s)

for proj in "${PROJECTS[@]}"; do
log "项目 ${proj}: 拉取 job 列表"
collect_items "/projects/${proj}/jobs" "$tmp"
total=$(wc -l < "$tmp" | tr -d ' ')
log "项目 ${proj}: 共 ${total} 条 job,清除 ${KEEP_DAYS} 天前的日志"

sort -rn "$tmp" | tail -n +$((KEEP_RECENT + 1)) | while IFS=$'\t' read -r id created; do
[ -n "$id" ] || continue
ts=$(date -u -d "$created" +%s 2>/dev/null || echo 0)
[ "$ts" -ge "$cutoff" ] && continue

if [ "$DRY_RUN" = "1" ]; then
log "[DRY] 项目 ${proj}: 将 erase job ${id} (${created})"
continue
fi
code=$(curl -sS -o /dev/null -w '%{http_code}' --max-time 30 -X POST \
-H "PRIVATE-TOKEN: $PAT" \
"${GITLAB_BASE}/api/v4/projects/${proj}/jobs/${id}/erase")
case "$code" in
200|201|204) log "项目 ${proj}: 已 erase job ${id}" ;;
429) log "项目 ${proj}: 触发限流,跳过 job ${id}" ;;
*) log "项目 ${proj}: erase job ${id} 返回 HTTP ${code}(已被删除的流水线会这样,正常)" ;;
esac
sleep 0.3
done
done
rm -f "$tmp"
log "job 日志清理结束。DRY_RUN=${DRY_RUN}"
}

cleanup_docker() {
command -v docker >/dev/null 2>&1 || die "本机没有 docker 命令"
log "开始清理 Docker:日志截断阈值 ${LOG_TRUNCATE_MB}MB,容器/缓存保留 ${DOCKER_PRUNE_HOURS} 小时"

# 1) 截断超大容器日志。注意:绝不 rm,rm 不会释放仍被占用的空间
find "${DOCKER_ROOT}/containers" -type f -name '*-json.log' -size "+${LOG_TRUNCATE_MB}M" -print0 2>/dev/null |
while IFS= read -r -d '' f; do
if [ "$DRY_RUN" = "1" ]; then
log "[DRY] 将截断容器日志 ${f}"
else
local_size=$(du -h "$f" 2>/dev/null | cut -f1)
if truncate -s 0 "$f" 2>/dev/null; then
log "已截断容器日志 ${f}(原 ${local_size})"
else
log "截断失败:${f},请检查权限"
fi
fi
done

# 2) 清理停止的容器和旧构建缓存。有 tag 的镜像不会被删(docs-sync-tools:1.0 安全)
if [ "$DRY_RUN" = "1" ]; then
log "[DRY] 将执行 docker container/builder/image prune"
else
docker container prune -f --filter "until=${DOCKER_PRUNE_HOURS}h" 2>&1 | tail -n 3
docker builder prune -f --filter "until=${DOCKER_PRUNE_HOURS}h" 2>&1 | tail -n 3
docker image prune -f 2>&1 | tail -n 3
docker system df
fi
log "Docker 清理结束。DRY_RUN=${DRY_RUN}"
}

usage() {
cat <<'EOF'
用法: gitlab-cleanup.sh [pipelines|logs|docker|all]
pipelines 删除旧流水线(连带 job 和日志)
logs 只 erase 旧 job 的日志,保留流水线记录
docker 清理 Runner 的 Docker 垃圾 + 截断超大 json.log
all pipelines + docker(默认)
环境变量: DRY_RUN=1 只预览;KEEP_DAYS=30;KEEP_RECENT=10;GITLAB_TOKEN=xxx
EOF
}

ACTION="${1:-all}"
check_deps "$ACTION"

mkdir -p "$(dirname "$LOCK_FILE")"
exec 9>"$LOCK_FILE"
if ! flock -n 9; then
log "已有清理任务在运行,本次退出"
exit 0
fi

log "========== 开始清理,模式: ${ACTION},DRY_RUN=${DRY_RUN} =========="
case "$ACTION" in
pipelines) cleanup_pipelines ;;
logs) cleanup_job_logs ;;
docker) cleanup_docker ;;
all) cleanup_pipelines; cleanup_docker ;;
*) usage; exit 1 ;;
esac
log "========== 清理完成 =========="
Thank you for your accept. mua!
-------------本文结束感谢您的阅读-------------