> ## Documentation Index
> Fetch the complete documentation index at: https://doc.lwops.cn/llms.txt
> Use this file to discover all available pages before exploring further.

# 乐维数据库定时备份(postgresql)

> [!TIP]
>
> 本文用于每天凌晨 1 点自动备份乐维的部分监控配置，并保留约 7 天。时间以服务器时区为准。配置 itops 的 crontab 且 crond 正常运行后，定时任务才会生效。
>
> 仅在本次备份成功后，脚本才会删除专用目录中超过约 7 天的同类归档。备份失败时，旧归档会保留。

| 范围 | 内容 |
| - | - |
| 包含 | `lwops` 数据库 `public` 模式中符合筛选条件的对象结构和数据，例如监控主机、监控项、触发器、用户记录和部分监控配置。 |
| 排除 | `public` 下以 `lw`、`history`、`trends` 开头的表及其他模式。监控历史与趋势、部分平台配置、数据库角色、其他数据库、应用程序和自定义脚本需另行备份。 |

> [!NOTE]
>
> 此流程验证**部分**监控配置能否导入独立数据库。整个平台的灾难恢复需要完整备份和单独的恢复演练。

## 1. 准备环境

示例使用乐维平台安装的 PostgreSQL 14.18 客户端，路径为 `/itops/postgresql/bin`。执行前核对实际工具路径、数据库地址和版本。

管理员创建备份目录。

```bash theme={null}
install -d -m 0700 -o itops -g itops /var/db-backup/lerwee-config
```

以 `itops` 系统用户编辑 `~/.pgpass`，加入以下默认数据库账密示例。部署时若已修改密码，请填实际值。若已有通配记录，将具体记录放在通配记录前。

```text theme={null}
su itops
```

```text theme={null}
vi ~/.pgpass
```

加入以下配置内容：

```text theme={null}
*:*:*:itops:ITOPS_p@ssw0rd
```

保存配置：按Esc按钮并输入:wq

修改密码文件仅归属用户可读写

```bash theme={null}
chmod 600 ~/.pgpass
```

## 2. 保存并手工试跑脚本

将下方脚本保存为 `/itops/postgresql/config_pg_dump.sh`

```bash theme={null}
#!/usr/bin/env bash
set -euo pipefail
umask 077
export PGCONNECT_TIMEOUT=10

# 1. 指定 PostgreSQL 工具和归档目录，生成带时间戳的文件名。
pgbin=/itops/postgresql/bin
dir=/var/db-backup/lerwee-config
stamp=$(date +%Y%m%d-%H%M%S)
file="$dir/lwops-config-${stamp}-$$.dump"
# 2. 在归档目录创建临时文件，脚本退出时清理。
tmp=$(mktemp "$dir/.lwops-config.XXXXXX")
trap 'rm -f -- "$tmp"' EXIT

# 3. 连接本机 lwops，以 itops 身份导出选定对象。密码由 ~/.pgpass 提供。
"$pgbin/pg_dump" -w -h 127.0.0.1 -p 5432 -U itops -d lwops \
  -n public -T 'public.lw*' -T 'public.history*' \
  -T 'public.trends*' -Fc -f "$tmp"
# 4. 完整读取归档进行检查，通过后保存为正式文件。
"$pgbin/pg_restore" -f /dev/null "$tmp"
mv -- "$tmp" "$file"
printf 'Backup OK: %s\n' "$file"
# 5. 仅清理本目录中超过约 7 天的同类归档。
find "$dir" -maxdepth 1 -type f -name 'lwops-config-*.dump' \
  -mmin +10080 -print -delete
```

以 `itops` 手工运行一次。看到 `Backup OK` 后，使用输出的归档路径查看清单。

```bash theme={null}
bash /itops/postgresql/config_pg_dump.sh
```

```text theme={null}
/itops/postgresql/bin/pg_restore -l /实际路径/归档.dump
```

![Shujukbeifen120202](https://mintcdn.com/lerwee/GislkgiFvPCTkQk0/images/shujukbeifen120202.png?fit=max\&auto=format\&n=GislkgiFvPCTkQk0\&q=85\&s=b987744296a7c9b49bd49d10cb2e3b38)

## 3. 启用每天凌晨 1 点的备份

1. 以 itops 用户运行 crontab -e，打开定时任务编辑器。

```cron theme={null}
crontab -e
```

2. 在编辑器里另起一行，粘贴下面的配置，保存并退出。

```cron theme={null}
0 1 * * * /usr/bin/bash /itops/postgresql/config_pg_dump.sh >> /var/db-backup/lerwee-config/backup.log 2>&1
```

3. 以 itops 用户运行 crontab -l，确认能看到刚保存的任务。以 root 代查时，使用 crontab -u itops -l。运行 systemctl is-active crond，确认返回 active。

```cron theme={null}
crontab -l
```

![Shujukbeifen120203](https://mintcdn.com/lerwee/GislkgiFvPCTkQk0/images/shujukbeifen120203.png?fit=max\&auto=format\&n=GislkgiFvPCTkQk0\&q=85\&s=bc372fa168b570e023e8db1f600010bc)

4. 首次凌晨 1 点过后，查看 /var/db-backup/lerwee-config/backup.log，确认有当次 Backup OK，且对应的 .dump 文件存在。

## 附录：验证归档能否恢复（可选）

验证账号需要创建数据库和安装 `vector` 扩展的权限。目标环境应提供与源库兼容的扩展版本。若 `~/.pgpass` 只匹配 `lwops`，可在演练期间添加以下条目，并在演练结束后删除。

```text theme={null}
127.0.0.1:5432:*:itops:ITOPS_p@ssw0rd
```

将脚本保存为 `restore_verify.sh`。它会创建 `lwops_verify_` 开头的测试库，跳过归档中的 `public` 建模式条目，并在一个事务中导入，出错时回滚本次导入。

```bash theme={null}
#!/usr/bin/env bash
set -euo pipefail
umask 077
export PGHOST=127.0.0.1 PGPORT=5432 PGUSER=itops
export PGCONNECT_TIMEOUT=10
p=/itops/postgresql/bin
archive=${1:?Pass the absolute path to the .dump file}
test -r "$archive"
db=lwops_verify_$(date +%s)_$$
toc=$(mktemp)
trap 'rm -f -- "$toc"' EXIT

"$p/pg_restore" -l "$archive" | \
  sed -E '/^[0-9]+; [0-9]+ [0-9]+ SCHEMA - public /s/^/;/' > "$toc"
"$p/createdb" -w -T template0 "$db"
printf 'Verification database: %s\n' "$db"
"$p/psql" -Xw -d "$db" -v ON_ERROR_STOP=1 \
  -c 'CREATE EXTENSION IF NOT EXISTS vector'
"$p/pg_restore" -w --single-transaction --exit-on-error \
  --no-owner --no-privileges -L "$toc" -d "$db" "$archive"
"$p/psql" -Xw -d "$db" -v ON_ERROR_STOP=1 -c \
  "SELECT current_database(), (SELECT count(*) FROM hosts) AS hosts,
   (SELECT count(*) FROM items) AS items,
   (SELECT count(*) FROM triggers) AS triggers,
   (SELECT count(*) FROM users) AS users;"
```

```bash theme={null}
bash restore_verify.sh /实际路径/归档.dump
```

核对输出中的测试库名称及主机、监控项、触发器和用户记录数。确认结果后，清理本次脚本创建的测试库。


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.