Compare commits
7
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c35ef3d383 | ||
|
|
cea46b494d | ||
|
|
b679381946 | ||
|
|
3480d810d4 | ||
|
|
271eac382e | ||
|
|
52403c6f95 | ||
|
|
4f626da9db |
@@ -57,6 +57,7 @@ jobs:
|
||||
npm run build
|
||||
npx playwright install --with-deps chromium
|
||||
npm run test:e2e
|
||||
npm run test:dist
|
||||
|
||||
- name: Verify release contracts and scripts
|
||||
run: |
|
||||
|
||||
@@ -4,6 +4,8 @@ frontend/dist/
|
||||
frontend/node_modules/
|
||||
frontend/playwright-report/
|
||||
frontend/test-results/
|
||||
frontend/playwright-report-dist/
|
||||
frontend/test-results-dist/
|
||||
.idea/
|
||||
.vscode/
|
||||
*.iml
|
||||
|
||||
@@ -49,7 +49,7 @@ npm run build
|
||||
Gitea API 只用于确认 Release tag 和资产名称;下载地址由受信 API 域名、仓库路径和 tag 重新构造,不采用
|
||||
Gitea 响应中可能错误指向内网地址的 `browser_download_url`。
|
||||
本版只支持由运维人员预先准备的外部 MySQL 8.4.x;安装器不会安装 MySQL、创建数据库容器或修改现有
|
||||
PostgreSQL 18。PostgreSQL 兼容开发已冻结,不属于本次 Preview.12 发布范围。
|
||||
PostgreSQL 18。PostgreSQL 兼容开发已冻结,不属于本次 Preview 发布范围。
|
||||
|
||||
执行命令的机器需预装 `bash`、`sudo`、`curl`、`mktemp` 和 `sha256sum`,并能访问目标 Gitea;`jq` 和 Java
|
||||
由安装器补齐;Java 17 优先使用服务器已有运行时,没有合适版本时才从官方 Azul 下载。数据库服务和数据库客户端均不会被安装。默认首次安装向导直接使用 JDBC 连接浏览器中填写的
|
||||
@@ -59,14 +59,14 @@ PostgreSQL 18。PostgreSQL 兼容开发已冻结,不属于本次 Preview.12
|
||||
### 直接 curl 安装
|
||||
|
||||
```bash
|
||||
curl -fsSL https://git.awaioi.com/ERP-Team/kaidi/releases/download/v1.0.0-preview.15/install.sh | sudo bash
|
||||
curl -fsSL https://git.awaioi.com/ERP-Team/kaidi/releases/download/v1.0.0-preview.19/install.sh | sudo bash
|
||||
```
|
||||
|
||||
这条命令会提示填写 Java 应用端口,直接回车使用 `18080`;随后安装最新签名 Release,并默认进入 `/setup`
|
||||
安装向导。Java 默认只监听 `127.0.0.1:所选端口`,前端页面、API 和健康检查均由同一端口提供。无人值守安装可直接指定:
|
||||
|
||||
```bash
|
||||
curl -fsSL https://git.awaioi.com/ERP-Team/kaidi/releases/download/v1.0.0-preview.15/install.sh \
|
||||
curl -fsSL https://git.awaioi.com/ERP-Team/kaidi/releases/download/v1.0.0-preview.19/install.sh \
|
||||
| sudo env KAIDI_APP_PORT=19090 bash
|
||||
```
|
||||
|
||||
@@ -74,8 +74,8 @@ curl -fsSL https://git.awaioi.com/ERP-Team/kaidi/releases/download/v1.0.0-previe
|
||||
时才设置 `KAIDI_SERVER_ADDRESS=0.0.0.0`,通常应保持默认回环绑定并由本机反向代理访问。需要在执行前独立校验安装脚本时使用:
|
||||
|
||||
```bash
|
||||
curl -fsSL https://git.awaioi.com/ERP-Team/kaidi/releases/download/v1.0.0-preview.15/install.sh -o /tmp/kaidi-install.sh
|
||||
printf '%s %s\n' 8a75ee99a1c2f426c11ea18c8ef65f4f4ac3f8d52321c358f3ff645baa6ad99c /tmp/kaidi-install.sh | sha256sum -c -
|
||||
curl -fsSL https://git.awaioi.com/ERP-Team/kaidi/releases/download/v1.0.0-preview.19/install.sh -o /tmp/kaidi-install.sh
|
||||
printf '%s %s\n' bc9001197af843dc323907a98023064ccc4f184e000543d2086b8a6f8161dbc7 /tmp/kaidi-install.sh | sha256sum -c -
|
||||
sudo bash /tmp/kaidi-install.sh
|
||||
rm -f /tmp/kaidi-install.sh
|
||||
```
|
||||
@@ -86,7 +86,7 @@ rm -f /tmp/kaidi-install.sh
|
||||
包装器会在 `sudo` 前校验 `deploy/install.sh` 的固定 SHA-256,再按同一公钥信任链安装最新签名 Release。
|
||||
|
||||
```bash
|
||||
git clone --branch v1.0.0-preview.15 --depth 1 https://git.awaioi.com/ERP-Team/kaidi.git kaidi-preview
|
||||
git clone --branch v1.0.0-preview.19 --depth 1 https://git.awaioi.com/ERP-Team/kaidi.git kaidi-preview
|
||||
cd kaidi-preview
|
||||
./deploy/install-from-git.sh
|
||||
```
|
||||
@@ -100,7 +100,7 @@ cd kaidi-preview
|
||||
- 不安装或创建数据库;在 `/setup` 中连接运维人员预先准备的外部 MySQL 8.4.x。
|
||||
- 识别 `x86_64`、`aarch64`、`armv7` 或 32 位 `i386/i486/i586/i686`;已有 Java 17 直接复用,否则校验 SHA-256 后下载对应的官方 Azul Java 17 JRE。
|
||||
- 使用安装器内置的 SHA-256 指纹校验 Release 公钥,再用该公钥验证发布清单 RSA 签名。
|
||||
- 首次安装默认启用 `/setup` 向导,不在命令行保存数据库密码;向导只接受 MySQL 8.4.x,并在提交前验证 DDL/DML 权限。
|
||||
- 首次安装默认启用 `/setup` 向导,不在命令行保存数据库密码;向导只接受 MySQL 8.4.x,并在提交前验证完整迁移权限。
|
||||
- 安装签名 Release 到 `/opt/kaidi/releases/<version>`,以 `/opt/kaidi/current` 原子切换当前版本。
|
||||
- 安装 `kaidi-finance.service`、更新监听服务和健康检查;Java 同时托管 TDesign 前端静态资源及 Vue 路由回退。
|
||||
- 向导只初始化一个由操作者填写的 `SYSTEM_ADMIN` 管理员,不创建项目、财务、资料或演示账号。
|
||||
@@ -141,11 +141,13 @@ sudo cat /root/kaidi-first-login.txt
|
||||
32 位服务端镜像,因此 32 位主机需要预先连接一台 MySQL 8.4 数据库,之后仍然只执行一个安装命令:
|
||||
|
||||
```bash
|
||||
curl -fsSL https://git.awaioi.com/ERP-Team/kaidi/releases/download/v1.0.0-preview.15/install.sh | sudo bash
|
||||
curl -fsSL https://git.awaioi.com/ERP-Team/kaidi/releases/download/v1.0.0-preview.19/install.sh | sudo bash
|
||||
```
|
||||
|
||||
无论主机架构如何,安装器都不会安装 MySQL、数据库客户端或创建数据库容器。在打开向导前,需要预先创建 `kaidi_finance`,并授予安装账号该库的
|
||||
DDL、DML 权限。向导会连接数据库、核验 MySQL 8.4.x 版本并用临时表验证权限,全部通过后 Flyway 才会建表。
|
||||
完整迁移权限。向导会连接数据库、核验 MySQL 8.4.x 版本,并实际探测建表、改表、索引、外键、存储过程、
|
||||
临时表及读写权限;专用数据库不是 `utf8mb4/utf8mb4_0900_ai_ci` 时,向导会在迁移前自动统一默认字符集和
|
||||
排序规则,全部通过后 Flyway 才会建表。
|
||||
数据库管理员可在 MySQL 8.4 中按实际应用服务器地址执行以下基线 SQL:
|
||||
|
||||
```sql
|
||||
@@ -161,18 +163,19 @@ GRANT ALL PRIVILEGES ON kaidi_finance.* TO 'kaidi'@'KAIDI_SERVER_IP';
|
||||
管理员数据和运维人员新增的环境变量:
|
||||
|
||||
```bash
|
||||
curl -fsSL https://git.awaioi.com/ERP-Team/kaidi/releases/download/v1.0.0-preview.15/install.sh \
|
||||
curl -fsSL https://git.awaioi.com/ERP-Team/kaidi/releases/download/v1.0.0-preview.22/install.sh \
|
||||
| sudo env KAIDI_REINSTALL=true KAIDI_SETUP_WIZARD=false bash
|
||||
```
|
||||
|
||||
没有显式设置 `KAIDI_APP_PORT` 时,修复性重装会沿用 `/etc/kaidi/kaidi.env` 中的原端口。重装失败会恢复原应用链接、Java 运行时、环境文件和 systemd 单元;脚本会明确报告回滚不完整,
|
||||
不会把恢复失败吞掉。
|
||||
不会把恢复失败吞掉。新版本安装器在 `KAIDI_REINSTALL=true` 时默认使用生产修复模式,显式的
|
||||
`KAIDI_SETUP_WIZARD=false` 仅用于兼容旧版本安装器。
|
||||
|
||||
如果安装器已完成但向导尚未提交,可执行下面的命令重新生成一次性安装码;该恢复路径只接受仍处于向导模式且未锁定的安装,正式模式不会被覆盖。
|
||||
|
||||
```bash
|
||||
curl -fsSL https://git.awaioi.com/ERP-Team/kaidi/releases/download/v1.0.0-preview.15/install.sh \
|
||||
| sudo env KAIDI_REINSTALL=true bash
|
||||
curl -fsSL https://git.awaioi.com/ERP-Team/kaidi/releases/download/v1.0.0-preview.22/install.sh \
|
||||
| sudo env KAIDI_REINSTALL=true KAIDI_SETUP_WIZARD=true bash
|
||||
```
|
||||
|
||||
### 停用并移除程序
|
||||
@@ -207,8 +210,8 @@ act_runner 提供 `ubuntu-24.04` 标签,并在 tag 发布时执行后端、前
|
||||
Preview 属性由 SemVer 版本名表达。之后推送 tag 即会构建、测试、签名并发布:
|
||||
|
||||
```bash
|
||||
git tag v1.0.0-preview.15
|
||||
git push origin v1.0.0-preview.15
|
||||
git tag v1.0.0-preview.19
|
||||
git push origin v1.0.0-preview.19
|
||||
```
|
||||
|
||||
在线更新使用独立的 TDesign 页面:隔离的系统管理员进入“系统治理 → 系统更新”。权限与配置页只管理用户、角色、数据范围、表单模板和参数版本,不配置系统名称或域名。
|
||||
@@ -260,7 +263,7 @@ cat /var/lib/kaidi-update/status.json
|
||||
```bash
|
||||
KAIDI_RELEASE_SIGNING_KEY=/secure/release-signing-private.pem \
|
||||
KAIDI_TRUSTED_RELEASE_PUBLIC_KEY_SHA256=807c6aec1dc3f7ce494db16aa9d763c66f292033c38f328afd0390d2715a8cd9 \
|
||||
./scripts/package-release.sh 1.0.0-preview.15
|
||||
./scripts/package-release.sh 1.0.0-preview.19
|
||||
KAIDI_TRUSTED_RELEASE_PUBLIC_KEY_SHA256=807c6aec1dc3f7ce494db16aa9d763c66f292033c38f328afd0390d2715a8cd9 \
|
||||
./scripts/verify-release.sh dist/release
|
||||
```
|
||||
|
||||
@@ -17,6 +17,6 @@ public class SetupLockedController {
|
||||
@GetMapping("/status")
|
||||
@PreAuthorize("true")
|
||||
public ApiResponse<SetupViews.Status> status() {
|
||||
return ApiResponse.ok(new SetupViews.Status(false, true, List.of("MYSQL"), "系统已完成安装"));
|
||||
return ApiResponse.ok(new SetupViews.Status(false, true, true, List.of("MYSQL"), "系统已完成安装"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -25,6 +25,9 @@ import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import org.flywaydb.core.Flyway;
|
||||
import org.flywaydb.core.api.FlywayException;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
|
||||
@@ -37,8 +40,15 @@ import org.springframework.transaction.support.TransactionTemplate;
|
||||
@ConditionalOnProperty(name = "finance.setup.enabled", havingValue = "true")
|
||||
public class SetupService {
|
||||
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(SetupService.class);
|
||||
private static final String MYSQL_PREFIX = "jdbc:mysql://";
|
||||
private static final String MYSQL_CHARACTER_SET = "utf8mb4";
|
||||
private static final String MYSQL_COLLATION = "utf8mb4_0900_ai_ci";
|
||||
private static final String RECOVERABLE_V068_SCRIPT = "V068__source_table_column_validation_metadata.sql";
|
||||
private static final List<String> SUPPORTED_TYPES = List.of(DatabaseType.MYSQL.name());
|
||||
private static final Set<Integer> MYSQL_PERMISSION_ERROR_CODES = Set.of(1044, 1045, 1142, 1227, 1370);
|
||||
private static final long RESTART_TRIGGER_DELAY_MILLIS = 2_000L;
|
||||
private static final int LOGIN_REDIRECT_DELAY_SECONDS = 10;
|
||||
|
||||
private final SetupProperties properties;
|
||||
private final AtomicBoolean locked = new AtomicBoolean(false);
|
||||
@@ -56,7 +66,7 @@ public class SetupService {
|
||||
|
||||
public SetupViews.Status status() {
|
||||
boolean isLocked = locked.get() || Files.exists(Path.of(properties.markerFile()));
|
||||
return new SetupViews.Status(!isLocked, isLocked, SUPPORTED_TYPES,
|
||||
return new SetupViews.Status(!isLocked, isLocked, false, SUPPORTED_TYPES,
|
||||
isLocked ? "安装向导已锁定" : "请完成数据库和管理员初始化");
|
||||
}
|
||||
|
||||
@@ -74,8 +84,10 @@ public class SetupService {
|
||||
false, "PostgreSQL 连接可用,但当前 Preview 的业务迁移仅支持 MySQL 8.4");
|
||||
}
|
||||
ConnectionResult connection = testConnection(settings);
|
||||
prepareDatabaseForInstallation(settings);
|
||||
validateSchemaForInstallation(settings);
|
||||
return new SetupViews.Connection(true, settings.type().name(), connection.version(), true,
|
||||
"MySQL 8.4 连接和 DDL/DML 权限验证通过");
|
||||
"MySQL 8.4 连接、排序规则和完整迁移权限验证通过");
|
||||
}
|
||||
|
||||
public SetupViews.Completed complete(SetupContracts.CompleteRequest request) {
|
||||
@@ -106,7 +118,7 @@ public class SetupService {
|
||||
if (properties.restartAfterComplete()) {
|
||||
Thread restart = new Thread(() -> {
|
||||
try {
|
||||
Thread.sleep(750L);
|
||||
Thread.sleep(RESTART_TRIGGER_DELAY_MILLIS);
|
||||
} catch (InterruptedException exception) {
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
@@ -116,18 +128,14 @@ public class SetupService {
|
||||
restart.start();
|
||||
}
|
||||
return new SetupViews.Completed(true, request.adminUsername(),
|
||||
"安装完成,系统正在切换到正式模式", 10);
|
||||
"安装完成,系统正在切换到正式模式", LOGIN_REDIRECT_DELAY_SECONDS);
|
||||
}
|
||||
|
||||
private void migrateAndCreateAdministrator(DatabaseSettings settings, SetupContracts.CompleteRequest request) {
|
||||
try {
|
||||
ensureCompatibleSchema(settings);
|
||||
Flyway.configure()
|
||||
.dataSource(settings.jdbcUrl(), settings.username(), settings.password())
|
||||
.locations("classpath:db/migration")
|
||||
.cleanDisabled(true)
|
||||
.load()
|
||||
.migrate();
|
||||
prepareDatabaseForInstallation(settings);
|
||||
validateSchemaForInstallation(settings);
|
||||
flyway(settings).migrate();
|
||||
DriverManagerDataSource dataSource = new DriverManagerDataSource(settings.jdbcUrl(), settings.username(),
|
||||
settings.password());
|
||||
JdbcTemplate jdbc = new JdbcTemplate(dataSource);
|
||||
@@ -137,12 +145,112 @@ public class SetupService {
|
||||
if (exception instanceof SetupException setupException) {
|
||||
throw setupException;
|
||||
}
|
||||
LOGGER.error("Database migration or administrator initialization failed", exception);
|
||||
throw new SetupException(org.springframework.http.HttpStatus.UNPROCESSABLE_ENTITY,
|
||||
"DATABASE_INITIALIZATION_FAILED", "数据库迁移或管理员初始化失败,请检查账号的 DDL/DML 权限");
|
||||
"DATABASE_INITIALIZATION_FAILED", databaseInitializationFailureMessage(exception));
|
||||
}
|
||||
}
|
||||
|
||||
private void ensureCompatibleSchema(DatabaseSettings settings) {
|
||||
private void prepareDatabaseForInstallation(DatabaseSettings settings) {
|
||||
JdbcTemplate jdbc = new JdbcTemplate(new DriverManagerDataSource(settings.jdbcUrl(), settings.username(),
|
||||
settings.password()));
|
||||
try {
|
||||
DatabaseCollation current = databaseCollation(jdbc, settings.database());
|
||||
if (!MYSQL_CHARACTER_SET.equalsIgnoreCase(current.characterSet())
|
||||
|| !MYSQL_COLLATION.equalsIgnoreCase(current.collation())) {
|
||||
jdbc.execute("ALTER DATABASE " + quoteIdentifier(settings.database())
|
||||
+ " CHARACTER SET " + MYSQL_CHARACTER_SET + " COLLATE " + MYSQL_COLLATION);
|
||||
DatabaseCollation updated = databaseCollation(jdbc, settings.database());
|
||||
if (!MYSQL_CHARACTER_SET.equalsIgnoreCase(updated.characterSet())
|
||||
|| !MYSQL_COLLATION.equalsIgnoreCase(updated.collation())) {
|
||||
throw new SetupException(org.springframework.http.HttpStatus.UNPROCESSABLE_ENTITY,
|
||||
"DATABASE_COLLATION_UNSUPPORTED", "数据库字符集或排序规则未能统一为 "
|
||||
+ MYSQL_CHARACTER_SET + "/" + MYSQL_COLLATION);
|
||||
}
|
||||
LOGGER.info("Normalized database {} from {}/{} to {}/{}", settings.database(),
|
||||
current.characterSet(), current.collation(), updated.characterSet(), updated.collation());
|
||||
}
|
||||
recoverV068CollationFailure(jdbc, settings.database());
|
||||
} catch (SetupException exception) {
|
||||
throw exception;
|
||||
} catch (RuntimeException exception) {
|
||||
LOGGER.error("Database collation preparation failed", exception);
|
||||
SQLException sqlException = findSqlException(exception);
|
||||
String detail = sqlException == null
|
||||
? "数据库字符集和排序规则初始化失败:" + safeErrorMessage(exception)
|
||||
: "数据库字符集和排序规则初始化失败" + sqlErrorSummary(sqlException);
|
||||
throw new SetupException(org.springframework.http.HttpStatus.UNPROCESSABLE_ENTITY,
|
||||
"DATABASE_COLLATION_PREPARATION_FAILED", detail);
|
||||
}
|
||||
}
|
||||
|
||||
private DatabaseCollation databaseCollation(JdbcTemplate jdbc, String database) {
|
||||
return jdbc.queryForObject("""
|
||||
SELECT default_character_set_name, default_collation_name
|
||||
FROM information_schema.schemata
|
||||
WHERE schema_name = ?
|
||||
""", (result, row) -> new DatabaseCollation(
|
||||
result.getString("default_character_set_name"), result.getString("default_collation_name")),
|
||||
database);
|
||||
}
|
||||
|
||||
private void recoverV068CollationFailure(JdbcTemplate jdbc, String database) {
|
||||
Integer historyCount = jdbc.queryForObject("""
|
||||
SELECT COUNT(*)
|
||||
FROM information_schema.tables
|
||||
WHERE table_schema = ? AND table_name = 'flyway_schema_history'
|
||||
""", Integer.class, database);
|
||||
if (historyCount == null || historyCount == 0) {
|
||||
return;
|
||||
}
|
||||
List<FailedMigration> failures = jdbc.query("""
|
||||
SELECT installed_rank, version, script
|
||||
FROM flyway_schema_history
|
||||
WHERE success = FALSE
|
||||
ORDER BY installed_rank
|
||||
""", (result, row) -> new FailedMigration(result.getInt("installed_rank"),
|
||||
result.getString("version"), result.getString("script")));
|
||||
if (failures.size() != 1) {
|
||||
return;
|
||||
}
|
||||
FailedMigration failure = failures.get(0);
|
||||
if (!("68".equals(failure.version()) || "068".equals(failure.version()))
|
||||
|| !RECOVERABLE_V068_SCRIPT.equals(failure.script())) {
|
||||
return;
|
||||
}
|
||||
Integer predecessorCount = jdbc.queryForObject("""
|
||||
SELECT COUNT(*)
|
||||
FROM flyway_schema_history
|
||||
WHERE version IN ('67', '067') AND success = TRUE
|
||||
""", Integer.class);
|
||||
if (predecessorCount == null || predecessorCount != 1) {
|
||||
return;
|
||||
}
|
||||
Integer laterSuccessCount = jdbc.queryForObject("""
|
||||
SELECT COUNT(*)
|
||||
FROM flyway_schema_history
|
||||
WHERE installed_rank > ? AND success = TRUE
|
||||
""", Integer.class, failure.installedRank());
|
||||
if (laterSuccessCount != null && laterSuccessCount > 0) {
|
||||
return;
|
||||
}
|
||||
int deleted = jdbc.update("""
|
||||
DELETE FROM flyway_schema_history
|
||||
WHERE installed_rank = ? AND version = ? AND script = ? AND success = FALSE
|
||||
""", failure.installedRank(), failure.version(), failure.script());
|
||||
if (deleted != 1) {
|
||||
throw new SetupException(org.springframework.http.HttpStatus.CONFLICT,
|
||||
"DATABASE_MIGRATION_RECOVERY_CONFLICT", "V068 迁移恢复状态已变化,请重新测试数据库连接");
|
||||
}
|
||||
LOGGER.warn("Removed the recoverable failed {} history row after database collation normalization",
|
||||
RECOVERABLE_V068_SCRIPT);
|
||||
}
|
||||
|
||||
private String quoteIdentifier(String identifier) {
|
||||
return "`" + identifier.replace("`", "``") + "`";
|
||||
}
|
||||
|
||||
private boolean ensureCompatibleSchema(DatabaseSettings settings) {
|
||||
JdbcTemplate jdbc = new JdbcTemplate(new DriverManagerDataSource(settings.jdbcUrl(), settings.username(),
|
||||
settings.password()));
|
||||
Integer tableCount = jdbc.queryForObject("""
|
||||
@@ -160,7 +268,42 @@ public class SetupService {
|
||||
throw new SetupException(org.springframework.http.HttpStatus.UNPROCESSABLE_ENTITY,
|
||||
"DATABASE_NOT_EMPTY", "请选择空数据库,或提供已有 Kaidi Flyway 数据库");
|
||||
}
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private void validateSchemaForInstallation(DatabaseSettings settings) {
|
||||
try {
|
||||
if (!ensureCompatibleSchema(settings)) {
|
||||
return;
|
||||
}
|
||||
flyway(settings).validate();
|
||||
} catch (SetupException exception) {
|
||||
throw exception;
|
||||
} catch (FlywayException exception) {
|
||||
LOGGER.error("Database migration history validation failed", exception);
|
||||
throw new SetupException(org.springframework.http.HttpStatus.UNPROCESSABLE_ENTITY,
|
||||
"DATABASE_MIGRATION_STATE_INVALID",
|
||||
"数据库迁移历史校验失败,请使用空数据库,或先修复已有迁移状态:" + safeErrorMessage(exception));
|
||||
} catch (RuntimeException exception) {
|
||||
LOGGER.error("Database schema inspection failed", exception);
|
||||
SQLException sqlException = findSqlException(exception);
|
||||
String detail = sqlException == null
|
||||
? "数据库结构检查失败:" + safeErrorMessage(exception)
|
||||
: databaseConnectionFailureMessage(sqlException);
|
||||
throw new SetupException(org.springframework.http.HttpStatus.UNPROCESSABLE_ENTITY,
|
||||
"DATABASE_SCHEMA_INSPECTION_FAILED", detail);
|
||||
}
|
||||
}
|
||||
|
||||
private Flyway flyway(DatabaseSettings settings) {
|
||||
return Flyway.configure()
|
||||
.dataSource(settings.jdbcUrl(), settings.username(), settings.password())
|
||||
.locations("classpath:db/migration")
|
||||
.ignoreMigrationPatterns("*:pending")
|
||||
.cleanDisabled(true)
|
||||
.load();
|
||||
}
|
||||
|
||||
private void initializeInstallation(JdbcTemplate jdbc, SetupContracts.CompleteRequest request) {
|
||||
@@ -280,18 +423,148 @@ public class SetupService {
|
||||
throw new SetupException(org.springframework.http.HttpStatus.UNPROCESSABLE_ENTITY,
|
||||
"MYSQL_VERSION_UNSUPPORTED", "当前版本要求 MySQL 8.4.x,检测到 " + version);
|
||||
}
|
||||
String probe = "kaidi_setup_probe_" + UUID.randomUUID().toString().replace("-", "");
|
||||
try {
|
||||
statement.execute("CREATE TABLE " + probe + " (id INT NOT NULL PRIMARY KEY)");
|
||||
statement.execute("INSERT INTO " + probe + " (id) VALUES (1)");
|
||||
statement.execute("UPDATE " + probe + " SET id = 2 WHERE id = 1");
|
||||
} finally {
|
||||
statement.execute("DROP TABLE IF EXISTS " + probe);
|
||||
}
|
||||
verifyMigrationPrivileges(connection, statement, settings.type());
|
||||
return new ConnectionResult(true, version);
|
||||
} catch (SQLException exception) {
|
||||
LOGGER.warn("Database connection or migration privilege verification failed: SQL state={}, errorCode={}",
|
||||
exception.getSQLState(), exception.getErrorCode(), exception);
|
||||
throw new SetupException(org.springframework.http.HttpStatus.UNPROCESSABLE_ENTITY,
|
||||
"DATABASE_CONNECTION_FAILED", "数据库连接或 DDL/DML 权限验证失败");
|
||||
"DATABASE_CONNECTION_FAILED", databaseConnectionFailureMessage(exception));
|
||||
}
|
||||
}
|
||||
|
||||
private String databaseConnectionFailureMessage(SQLException exception) {
|
||||
if (isPermissionError(exception)) {
|
||||
return "数据库账号缺少完整迁移权限" + sqlErrorSummary(exception);
|
||||
}
|
||||
if (exception.getSQLState() != null && exception.getSQLState().startsWith("08")) {
|
||||
return "数据库连接超时或中断" + sqlErrorSummary(exception);
|
||||
}
|
||||
return "数据库连接或完整迁移权限验证失败" + sqlErrorSummary(exception);
|
||||
}
|
||||
|
||||
private String databaseInitializationFailureMessage(Throwable exception) {
|
||||
SQLException sqlException = findSqlException(exception);
|
||||
if (sqlException != null) {
|
||||
if (isPermissionError(sqlException)) {
|
||||
return "数据库账号缺少完成迁移所需权限" + sqlErrorSummary(sqlException);
|
||||
}
|
||||
if (sqlException.getSQLState() != null && sqlException.getSQLState().startsWith("08")) {
|
||||
return "数据库迁移期间连接超时或中断" + sqlErrorSummary(sqlException);
|
||||
}
|
||||
return "数据库迁移或管理员初始化失败" + sqlErrorSummary(sqlException);
|
||||
}
|
||||
return "数据库迁移或管理员初始化失败:" + safeErrorMessage(exception);
|
||||
}
|
||||
|
||||
private SQLException findSqlException(Throwable exception) {
|
||||
Throwable current = exception;
|
||||
while (current != null) {
|
||||
if (current instanceof SQLException sqlException) {
|
||||
return sqlException;
|
||||
}
|
||||
current = current.getCause();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private boolean isPermissionError(SQLException exception) {
|
||||
return MYSQL_PERMISSION_ERROR_CODES.contains(exception.getErrorCode());
|
||||
}
|
||||
|
||||
private String sqlErrorSummary(SQLException exception) {
|
||||
String state = exception.getSQLState() == null ? "UNKNOWN" : exception.getSQLState();
|
||||
return "(SQLState " + state + ",错误码 " + exception.getErrorCode() + "):"
|
||||
+ safeErrorMessage(exception);
|
||||
}
|
||||
|
||||
private String safeErrorMessage(Throwable exception) {
|
||||
Throwable current = exception;
|
||||
while (current.getCause() != null) {
|
||||
current = current.getCause();
|
||||
}
|
||||
String message = current.getMessage() == null ? current.getClass().getSimpleName() : current.getMessage();
|
||||
String sanitized = message.replaceAll("(?i)(password|pwd)=([^\\s&;]+)", "$1=***")
|
||||
.replaceAll("\\s+", " ").trim();
|
||||
return sanitized.length() <= 240 ? sanitized : sanitized.substring(0, 240) + "...";
|
||||
}
|
||||
|
||||
private void verifyMigrationPrivileges(Connection connection, Statement statement, DatabaseType databaseType)
|
||||
throws SQLException {
|
||||
String suffix = UUID.randomUUID().toString().replace("-", "");
|
||||
String parentTable = "kaidi_setup_probe_parent_" + suffix;
|
||||
String childTable = "kaidi_setup_probe_child_" + suffix;
|
||||
String foreignKey = "fk_setup_probe_" + suffix;
|
||||
String index = "idx_setup_probe_" + suffix;
|
||||
String routine = "kaidi_setup_probe_routine_" + suffix;
|
||||
String temporaryTable = "kaidi_setup_probe_temp_" + suffix;
|
||||
try {
|
||||
statement.execute("CREATE TABLE " + parentTable + " (id INT NOT NULL PRIMARY KEY)");
|
||||
if (databaseType == DatabaseType.MYSQL) {
|
||||
statement.execute("CREATE TABLE " + childTable
|
||||
+ " (id INT NOT NULL PRIMARY KEY, parent_id INT NOT NULL, CONSTRAINT " + foreignKey
|
||||
+ " FOREIGN KEY (parent_id) REFERENCES " + parentTable + " (id))");
|
||||
statement.execute("ALTER TABLE " + childTable + " ADD COLUMN note VARCHAR(32) NULL");
|
||||
statement.execute("CREATE INDEX " + index + " ON " + childTable + " (parent_id)");
|
||||
statement.execute("CREATE PROCEDURE " + routine + "() SELECT 1 AS probe_value");
|
||||
try (Statement call = connection.createStatement();
|
||||
ResultSet result = call.executeQuery("CALL " + routine + "()")) {
|
||||
if (!result.next() || result.getInt(1) != 1) {
|
||||
throw new SQLException("Migration privilege routine probe returned an invalid result");
|
||||
}
|
||||
}
|
||||
statement.execute("INSERT INTO " + parentTable + " (id) VALUES (1)");
|
||||
statement.execute("INSERT INTO " + childTable + " (id, parent_id, note) VALUES (1, 1, 'probe')");
|
||||
try (ResultSet result = statement.executeQuery("SELECT note FROM " + childTable + " WHERE id = 1")) {
|
||||
if (!result.next() || !"probe".equals(result.getString(1))) {
|
||||
throw new SQLException("Migration privilege SELECT probe returned an invalid result");
|
||||
}
|
||||
}
|
||||
statement.execute("CREATE TEMPORARY TABLE " + temporaryTable
|
||||
+ " (id INT NOT NULL PRIMARY KEY)");
|
||||
statement.execute("INSERT INTO " + temporaryTable + " (id) VALUES (1)");
|
||||
statement.execute("DROP TEMPORARY TABLE " + temporaryTable);
|
||||
statement.execute("UPDATE " + childTable + " SET note = 'verified' WHERE id = 1");
|
||||
statement.execute("DELETE FROM " + childTable + " WHERE id = 1");
|
||||
statement.execute("DELETE FROM " + parentTable + " WHERE id = 1");
|
||||
} else {
|
||||
statement.execute("INSERT INTO " + parentTable + " (id) VALUES (1)");
|
||||
statement.execute("UPDATE " + parentTable + " SET id = 2 WHERE id = 1");
|
||||
statement.execute("DELETE FROM " + parentTable + " WHERE id = 2");
|
||||
}
|
||||
} catch (SQLException exception) {
|
||||
cleanupProbeObjects(statement, databaseType, routine, temporaryTable, childTable, parentTable, exception);
|
||||
throw exception;
|
||||
}
|
||||
cleanupProbeObjects(statement, databaseType, routine, temporaryTable, childTable, parentTable, null);
|
||||
}
|
||||
|
||||
private void cleanupProbeObjects(Statement statement, DatabaseType databaseType, String routine,
|
||||
String temporaryTable, String childTable, String parentTable,
|
||||
SQLException original)
|
||||
throws SQLException {
|
||||
SQLException cleanupFailure = null;
|
||||
List<String> cleanupStatements = databaseType == DatabaseType.MYSQL
|
||||
? List.of("DROP PROCEDURE IF EXISTS " + routine, "DROP TEMPORARY TABLE IF EXISTS " + temporaryTable,
|
||||
"DROP TABLE IF EXISTS " + childTable, "DROP TABLE IF EXISTS " + parentTable)
|
||||
: List.of("DROP TABLE IF EXISTS " + childTable, "DROP TABLE IF EXISTS " + parentTable);
|
||||
for (String sql : cleanupStatements) {
|
||||
try {
|
||||
statement.execute(sql);
|
||||
} catch (SQLException exception) {
|
||||
if (cleanupFailure == null) {
|
||||
cleanupFailure = exception;
|
||||
} else {
|
||||
cleanupFailure.addSuppressed(exception);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (cleanupFailure != null) {
|
||||
if (original != null) {
|
||||
original.addSuppressed(cleanupFailure);
|
||||
} else {
|
||||
throw cleanupFailure;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -411,6 +684,12 @@ public class SetupService {
|
||||
private record ConnectionResult(boolean successful, String version) {
|
||||
}
|
||||
|
||||
private record DatabaseCollation(String characterSet, String collation) {
|
||||
}
|
||||
|
||||
private record FailedMigration(int installedRank, String version, String script) {
|
||||
}
|
||||
|
||||
private record InstallationState(String setupTokenSha256, long administratorUserId,
|
||||
String administratorUsername) {
|
||||
}
|
||||
|
||||
@@ -10,6 +10,7 @@ public final class SetupViews {
|
||||
public record Status(
|
||||
boolean required,
|
||||
boolean locked,
|
||||
boolean ready,
|
||||
List<String> supportedDatabaseTypes,
|
||||
String message
|
||||
) {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package com.kaidi.finance.setup;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.kaidi.setup.SetupApplication;
|
||||
@@ -13,6 +14,7 @@ import java.sql.Statement;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import org.flywaydb.core.Flyway;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
@@ -60,9 +62,12 @@ class SetupApplicationIntegrationTest {
|
||||
|
||||
@Test
|
||||
void firstRunTestsDatabaseCreatesAdministratorAndLocksWizard() throws Exception {
|
||||
seedRecoverableV068CollationFailure();
|
||||
|
||||
ResponseEntity<JsonNode> initial = rest.getForEntity(url("/api/v1/setup/status"), JsonNode.class);
|
||||
assertThat(initial.getStatusCode()).isEqualTo(HttpStatus.OK);
|
||||
assertThat(initial.getBody().path("data").path("required").asBoolean()).isTrue();
|
||||
assertThat(initial.getBody().path("data").path("ready").asBoolean()).isFalse();
|
||||
|
||||
Map<String, Object> database = databaseRequest("wrong-code");
|
||||
ResponseEntity<JsonNode> denied = rest.postForEntity(url("/api/v1/setup/test-connection"),
|
||||
@@ -76,6 +81,39 @@ class SetupApplicationIntegrationTest {
|
||||
assertThat(tested.getStatusCode()).isEqualTo(HttpStatus.OK);
|
||||
assertThat(tested.getBody().path("data").path("successful").asBoolean()).isTrue();
|
||||
assertThat(tested.getBody().path("data").path("schemaReady").asBoolean()).isTrue();
|
||||
assertThat(tested.getBody().path("data").path("message").asText())
|
||||
.contains("排序规则和完整迁移权限验证通过");
|
||||
|
||||
try (Connection connection = DriverManager.getConnection(MYSQL.getJdbcUrl(), MYSQL.getUsername(),
|
||||
MYSQL.getPassword()); Statement statement = connection.createStatement()) {
|
||||
try (ResultSet result = statement.executeQuery("""
|
||||
SELECT
|
||||
(SELECT COUNT(*) FROM information_schema.tables
|
||||
WHERE table_schema = DATABASE() AND table_name LIKE 'kaidi_setup_probe_%')
|
||||
+
|
||||
(SELECT COUNT(*) FROM information_schema.routines
|
||||
WHERE routine_schema = DATABASE() AND routine_name LIKE 'kaidi_setup_probe_%')
|
||||
""")) {
|
||||
result.next();
|
||||
assertThat(result.getInt(1)).isZero();
|
||||
}
|
||||
try (ResultSet result = statement.executeQuery("""
|
||||
SELECT default_collation_name
|
||||
FROM information_schema.schemata
|
||||
WHERE schema_name = DATABASE()
|
||||
""")) {
|
||||
result.next();
|
||||
assertThat(result.getString(1)).isEqualTo("utf8mb4_0900_ai_ci");
|
||||
}
|
||||
try (ResultSet result = statement.executeQuery("""
|
||||
SELECT COUNT(*)
|
||||
FROM flyway_schema_history
|
||||
WHERE success = FALSE
|
||||
""")) {
|
||||
result.next();
|
||||
assertThat(result.getInt(1)).isZero();
|
||||
}
|
||||
}
|
||||
|
||||
Map<String, Object> complete = new LinkedHashMap<>(database);
|
||||
complete.put("adminUsername", "setup-admin");
|
||||
@@ -121,6 +159,34 @@ class SetupApplicationIntegrationTest {
|
||||
ResponseEntity<JsonNode> locked = rest.getForEntity(url("/api/v1/setup/status"), JsonNode.class);
|
||||
assertThat(locked.getBody().path("data").path("required").asBoolean()).isFalse();
|
||||
assertThat(locked.getBody().path("data").path("locked").asBoolean()).isTrue();
|
||||
assertThat(locked.getBody().path("data").path("ready").asBoolean()).isFalse();
|
||||
}
|
||||
|
||||
private void seedRecoverableV068CollationFailure() throws Exception {
|
||||
try (Connection connection = DriverManager.getConnection(MYSQL.getJdbcUrl(), MYSQL.getUsername(),
|
||||
MYSQL.getPassword()); Statement statement = connection.createStatement()) {
|
||||
statement.execute("ALTER DATABASE `" + MYSQL.getDatabaseName()
|
||||
+ "` CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci");
|
||||
}
|
||||
assertThatThrownBy(() -> Flyway.configure()
|
||||
.dataSource(MYSQL.getJdbcUrl(), MYSQL.getUsername(), MYSQL.getPassword())
|
||||
.locations("classpath:db/migration")
|
||||
.target("68")
|
||||
.load()
|
||||
.migrate())
|
||||
.hasMessageContaining("V068__source_table_column_validation_metadata.sql");
|
||||
try (Connection connection = DriverManager.getConnection(MYSQL.getJdbcUrl(), MYSQL.getUsername(),
|
||||
MYSQL.getPassword()); Statement statement = connection.createStatement();
|
||||
ResultSet result = statement.executeQuery("""
|
||||
SELECT COUNT(*)
|
||||
FROM flyway_schema_history
|
||||
WHERE version = '68'
|
||||
AND script = 'V068__source_table_column_validation_metadata.sql'
|
||||
AND success = FALSE
|
||||
""")) {
|
||||
result.next();
|
||||
assertThat(result.getInt(1)).isEqualTo(1);
|
||||
}
|
||||
}
|
||||
|
||||
private Map<String, Object> databaseRequest(String setupCode) {
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
package com.kaidi.finance.setup;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
class SetupReadinessTest {
|
||||
|
||||
private static final String TOKEN_SHA256 =
|
||||
"9158568c96987884c8141d363daceffda86bb17083054b36105934090aa7e166";
|
||||
|
||||
@TempDir
|
||||
private Path stateRoot;
|
||||
|
||||
@Test
|
||||
void distinguishesLockedSetupModeFromReadyApplicationMode() {
|
||||
SetupProperties properties = new SetupProperties(true, TOKEN_SHA256,
|
||||
stateRoot.resolve("application.env").toString(), stateRoot.resolve("locked").toString(), false);
|
||||
|
||||
SetupViews.Status setupMode = new SetupService(properties).status();
|
||||
SetupViews.Status applicationMode = new SetupLockedController().status().data();
|
||||
|
||||
assertThat(setupMode.required()).isTrue();
|
||||
assertThat(setupMode.ready()).isFalse();
|
||||
assertThat(applicationMode.required()).isFalse();
|
||||
assertThat(applicationMode.locked()).isTrue();
|
||||
assertThat(applicationMode.ready()).isTrue();
|
||||
}
|
||||
}
|
||||
@@ -5,7 +5,7 @@ umask 077
|
||||
|
||||
ROOT=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)
|
||||
INSTALLER="$ROOT/deploy/install.sh"
|
||||
INSTALLER_SHA256=${KAIDI_INSTALLER_SHA256:-8a75ee99a1c2f426c11ea18c8ef65f4f4ac3f8d52321c358f3ff645baa6ad99c}
|
||||
INSTALLER_SHA256=${KAIDI_INSTALLER_SHA256:-bc9001197af843dc323907a98023064ccc4f184e000543d2086b8a6f8161dbc7}
|
||||
RELEASE_API_URL=${KAIDI_RELEASE_API_URL:-https://git.awaioi.com/api/v1/repos/ERP-Team/kaidi/releases/latest}
|
||||
PUBLIC_KEY_SHA256=${KAIDI_RELEASE_PUBLIC_KEY_SHA256:-807c6aec1dc3f7ce494db16aa9d763c66f292033c38f328afd0390d2715a8cd9}
|
||||
TOKEN_FILE=${KAIDI_RELEASE_TOKEN_FILE:-}
|
||||
|
||||
+186
-47
@@ -18,7 +18,13 @@ SERVER_ADDRESS=${KAIDI_SERVER_ADDRESS:-127.0.0.1}
|
||||
PROXY_TARGET=
|
||||
TRUSTED_PUBLIC_KEY_SHA256=${KAIDI_RELEASE_PUBLIC_KEY_SHA256:-807c6aec1dc3f7ce494db16aa9d763c66f292033c38f328afd0390d2715a8cd9}
|
||||
REINSTALL=${KAIDI_REINSTALL:-false}
|
||||
SETUP_WIZARD=${KAIDI_SETUP_WIZARD:-true}
|
||||
if [ "${KAIDI_SETUP_WIZARD+x}" = x ]; then
|
||||
SETUP_WIZARD=$KAIDI_SETUP_WIZARD
|
||||
elif [ "$REINSTALL" = true ]; then
|
||||
SETUP_WIZARD=false
|
||||
else
|
||||
SETUP_WIZARD=true
|
||||
fi
|
||||
WORK_DIR=
|
||||
RELEASE_AUTH_HEADER_FILE=
|
||||
INSTALL_TRANSACTION_ARMED=false
|
||||
@@ -28,6 +34,9 @@ BACKUP_DIR=
|
||||
JAVA_STAGED_DIR=
|
||||
JAVA_PREVIOUS_DIR=
|
||||
JAVA_ACTIVATED=false
|
||||
SERVICE_USER=kaidi
|
||||
SERVICE_GROUP=kaidi
|
||||
HOST_ARCH=
|
||||
|
||||
log() { printf '[kaidi-install] %s\n' "$*"; }
|
||||
die() { printf '[kaidi-install] ERROR: %s\n' "$*" >&2; exit 1; }
|
||||
@@ -36,14 +45,42 @@ sha256_file() {
|
||||
sha256sum "$1" | awk '{print $1}'
|
||||
}
|
||||
|
||||
normalized_host_arch() {
|
||||
local machine host_bits
|
||||
machine=$(uname -m)
|
||||
host_bits=$(getconf LONG_BIT 2>/dev/null || true)
|
||||
case "$machine" in
|
||||
x86_64|amd64)
|
||||
[ "$host_bits" = 32 ] && printf x86 || printf x86_64
|
||||
;;
|
||||
i386|i486|i586|i686) printf x86 ;;
|
||||
aarch64|arm64)
|
||||
[ "$host_bits" = 32 ] && printf arm || printf aarch64
|
||||
;;
|
||||
armv7l|armv6l) printf arm ;;
|
||||
*) die "Unsupported CPU architecture: $machine" ;;
|
||||
esac
|
||||
}
|
||||
|
||||
preflight_host() {
|
||||
local host_bits expected_bits
|
||||
[ "$(uname -s)" = Linux ] || die "The installer only supports Linux"
|
||||
[ "$APP_ROOT" = /opt/kaidi ] && [ "$STATE_ROOT" = /var/lib/kaidi ] \
|
||||
&& [ "$UPDATE_STATE_ROOT" = /var/lib/kaidi-update ] && [ "$CONFIG_ROOT" = /etc/kaidi ] \
|
||||
|| die "Custom installation roots are not supported by the packaged systemd configuration"
|
||||
command -v systemctl >/dev/null 2>&1 || die "systemd is required"
|
||||
command -v systemd-analyze >/dev/null 2>&1 || die "systemd-analyze is required"
|
||||
command -v getconf >/dev/null 2>&1 || die "getconf is required"
|
||||
[ -d /run/systemd/system ] || die "systemd is not running as PID 1"
|
||||
[ -d /etc/systemd/system ] || die "/etc/systemd/system is missing"
|
||||
HOST_ARCH=$(normalized_host_arch)
|
||||
host_bits=$(getconf LONG_BIT 2>/dev/null || true)
|
||||
case "$HOST_ARCH" in
|
||||
x86_64|aarch64) expected_bits=64 ;;
|
||||
x86|arm) expected_bits=32 ;;
|
||||
esac
|
||||
[ "$host_bits" = "$expected_bits" ] \
|
||||
|| die "CPU architecture and userspace word size do not match: $HOST_ARCH/$host_bits-bit"
|
||||
[[ "$TRUSTED_PUBLIC_KEY_SHA256" =~ ^[0-9A-Fa-f]{64}$ ]] \
|
||||
|| die "Set KAIDI_RELEASE_PUBLIC_KEY_SHA256 to the trusted release public-key SHA-256"
|
||||
case "$REINSTALL" in
|
||||
@@ -62,28 +99,31 @@ preflight_host() {
|
||||
[ ! -e "$STATE_ROOT/setup/locked" ] \
|
||||
|| die "The setup wizard is already locked; use a normal repair reinstall"
|
||||
fi
|
||||
log "Environment verified: $(uname -sr), architecture=$HOST_ARCH, userspace=${host_bits}-bit, systemd"
|
||||
}
|
||||
|
||||
[ "$(id -u)" -eq 0 ] || die "Run with sudo or as root"
|
||||
[ -z "$RELEASE_TOKEN" ] || [ -z "$RELEASE_TOKEN_FILE" ] \
|
||||
|| die "Set only one of KAIDI_RELEASE_TOKEN or KAIDI_RELEASE_TOKEN_FILE"
|
||||
if [ -n "$RELEASE_TOKEN_FILE" ]; then
|
||||
[ -f "$RELEASE_TOKEN_FILE" ] && [ ! -L "$RELEASE_TOKEN_FILE" ] \
|
||||
|| die "KAIDI_RELEASE_TOKEN_FILE must be a regular file"
|
||||
[ "$(wc -c < "$RELEASE_TOKEN_FILE" | tr -d '[:space:]')" -le 512 ] \
|
||||
|| die "KAIDI_RELEASE_TOKEN_FILE is too large"
|
||||
RELEASE_TOKEN=$(cat "$RELEASE_TOKEN_FILE")
|
||||
fi
|
||||
[ "$REINSTALL" = "true" ] || [ ! -e "$APP_ROOT/current" ] \
|
||||
|| die "Kaidi Finance is already installed; use the system update page"
|
||||
if [ -z "$RELEASE_API_URL" ]; then
|
||||
case "$RELEASE_BASE_URL" in
|
||||
*OWNER/REPO*) die "Set KAIDI_RELEASE_BASE_URL or KAIDI_RELEASE_API_URL to the Git release source" ;;
|
||||
esac
|
||||
fi
|
||||
[ -z "$RELEASE_TOKEN" ] || { [ "${#RELEASE_TOKEN}" -le 512 ] \
|
||||
&& ! printf '%s' "$RELEASE_TOKEN" | grep -q '[[:cntrl:]]'; } \
|
||||
|| die "KAIDI_RELEASE_TOKEN is invalid"
|
||||
validate_inputs() {
|
||||
[ "$(id -u)" -eq 0 ] || die "Run with sudo or as root"
|
||||
[ -z "$RELEASE_TOKEN" ] || [ -z "$RELEASE_TOKEN_FILE" ] \
|
||||
|| die "Set only one of KAIDI_RELEASE_TOKEN or KAIDI_RELEASE_TOKEN_FILE"
|
||||
if [ -n "$RELEASE_TOKEN_FILE" ]; then
|
||||
[ -f "$RELEASE_TOKEN_FILE" ] && [ ! -L "$RELEASE_TOKEN_FILE" ] \
|
||||
|| die "KAIDI_RELEASE_TOKEN_FILE must be a regular file"
|
||||
[ "$(wc -c < "$RELEASE_TOKEN_FILE" | tr -d '[:space:]')" -le 512 ] \
|
||||
|| die "KAIDI_RELEASE_TOKEN_FILE is too large"
|
||||
RELEASE_TOKEN=$(cat "$RELEASE_TOKEN_FILE")
|
||||
fi
|
||||
[ "$REINSTALL" = "true" ] || [ ! -e "$APP_ROOT/current" ] \
|
||||
|| die "Kaidi Finance is already installed; use the system update page"
|
||||
if [ -z "$RELEASE_API_URL" ]; then
|
||||
case "$RELEASE_BASE_URL" in
|
||||
*OWNER/REPO*) die "Set KAIDI_RELEASE_BASE_URL or KAIDI_RELEASE_API_URL to the Git release source" ;;
|
||||
esac
|
||||
fi
|
||||
[ -z "$RELEASE_TOKEN" ] || { [ "${#RELEASE_TOKEN}" -le 512 ] \
|
||||
&& ! printf '%s' "$RELEASE_TOKEN" | grep -q '[[:cntrl:]]'; } \
|
||||
|| die "KAIDI_RELEASE_TOKEN is invalid"
|
||||
}
|
||||
|
||||
download() {
|
||||
local url=$1 output=$2
|
||||
@@ -170,12 +210,26 @@ install_packages() {
|
||||
}
|
||||
|
||||
azul_arch() {
|
||||
case "$(uname -m)" in
|
||||
x86_64|amd64) printf x86 ;;
|
||||
i386|i486|i586|i686) printf i686 ;;
|
||||
aarch64|arm64) printf arm_64 ;;
|
||||
armv7l|armv6l) printf arm ;;
|
||||
*) die "Unsupported CPU architecture: $(uname -m)" ;;
|
||||
case "${HOST_ARCH:-$(normalized_host_arch)}" in
|
||||
x86_64) printf x86 ;;
|
||||
x86) printf i686 ;;
|
||||
aarch64) printf arm_64 ;;
|
||||
arm) printf arm ;;
|
||||
esac
|
||||
}
|
||||
|
||||
java_arch_matches_host() {
|
||||
local java_bin=$1 java_arch host_arch
|
||||
host_arch=${HOST_ARCH:-$(normalized_host_arch)}
|
||||
java_arch=$(
|
||||
"$java_bin" -XshowSettings:properties -version 2>&1 \
|
||||
| sed -n 's/^[[:space:]]*os\.arch = [[:space:]]*//p' \
|
||||
| head -n 1
|
||||
)
|
||||
case "$host_arch:$java_arch" in
|
||||
x86_64:amd64|x86_64:x86_64|x86:x86|x86:i386|x86:i486|x86:i586|x86:i686|\
|
||||
aarch64:aarch64|aarch64:arm64|arm:arm) return 0 ;;
|
||||
*) return 1 ;;
|
||||
esac
|
||||
}
|
||||
|
||||
@@ -194,6 +248,7 @@ system_java_home() {
|
||||
| head -n 1
|
||||
)
|
||||
[[ "$java_major" =~ ^[0-9]+$ ]] && [ "$java_major" -ge 17 ] || return 1
|
||||
java_arch_matches_host "$java_bin" || return 1
|
||||
resolved_java=$(readlink -f "$java_bin" 2>/dev/null || printf '%s' "$java_bin")
|
||||
case "$resolved_java" in
|
||||
*/bin/java) home=${resolved_java%/bin/java} ;;
|
||||
@@ -204,12 +259,14 @@ system_java_home() {
|
||||
}
|
||||
|
||||
prepare_java() {
|
||||
local api java_metadata package_metadata package_uuid java_url java_sha256 actual_sha256 system_home
|
||||
local api java_metadata package_metadata package_uuid java_url java_sha256 actual_sha256 system_home java_line
|
||||
if system_home=$(system_java_home); then
|
||||
JAVA_STAGED_DIR="$WORK_DIR/java.next"
|
||||
ln -s "$system_home" "$JAVA_STAGED_DIR"
|
||||
log "Using existing Java 17 runtime at $system_home"
|
||||
"$JAVA_STAGED_DIR/bin/java" -version
|
||||
mkdir -p "$JAVA_STAGED_DIR"
|
||||
log "Copying existing Java 17 runtime from $system_home into the managed application directory"
|
||||
COPYFILE_DISABLE=1 cp -R "$system_home/." "$JAVA_STAGED_DIR/"
|
||||
java_line=$("$JAVA_STAGED_DIR/bin/java" -version 2>&1 | head -n 1)
|
||||
log "Local Java verified: $java_line"
|
||||
return 0
|
||||
fi
|
||||
log "No local Java 17 runtime found; downloading the official Azul Java 17 runtime"
|
||||
@@ -231,18 +288,88 @@ prepare_java() {
|
||||
[ "$actual_sha256" = "$java_sha256" ] || die "Java 17 runtime SHA-256 verification failed"
|
||||
mkdir -p "$JAVA_STAGED_DIR"
|
||||
tar -xzf "$WORK_DIR/java.tar.gz" --strip-components=1 -C "$JAVA_STAGED_DIR"
|
||||
"$JAVA_STAGED_DIR/bin/java" -version
|
||||
java_arch_matches_host "$JAVA_STAGED_DIR/bin/java" \
|
||||
|| die "Downloaded Java runtime architecture does not match $HOST_ARCH"
|
||||
java_line=$("$JAVA_STAGED_DIR/bin/java" -version 2>&1 | head -n 1)
|
||||
log "Downloaded Java verified: $java_line"
|
||||
}
|
||||
|
||||
activate_java() {
|
||||
mkdir -p "$APP_ROOT/runtime"
|
||||
JAVA_PREVIOUS_DIR="$WORK_DIR/java.previous"
|
||||
if [ -e "$APP_ROOT/runtime/java" ]; then
|
||||
if [ -e "$APP_ROOT/runtime/java" ] || [ -L "$APP_ROOT/runtime/java" ]; then
|
||||
mv "$APP_ROOT/runtime/java" "$JAVA_PREVIOUS_DIR"
|
||||
fi
|
||||
mv "$JAVA_STAGED_DIR" "$APP_ROOT/runtime/java"
|
||||
chown -R root:"$SERVICE_GROUP" "$APP_ROOT/runtime/java"
|
||||
chmod -R u=rwX,g=rX,o= "$APP_ROOT/runtime/java"
|
||||
JAVA_ACTIVATED=true
|
||||
"$APP_ROOT/runtime/java/bin/java" -version
|
||||
}
|
||||
|
||||
ensure_service_identity() {
|
||||
local existing_home nologin_path
|
||||
command -v getent >/dev/null 2>&1 || die "getent is required"
|
||||
if ! getent group "$SERVICE_GROUP" >/dev/null 2>&1; then
|
||||
groupadd --system "$SERVICE_GROUP"
|
||||
fi
|
||||
if id "$SERVICE_USER" >/dev/null 2>&1; then
|
||||
existing_home=$(getent passwd "$SERVICE_USER" | awk -F: '{print $6}')
|
||||
[ "$existing_home" = "$STATE_ROOT" ] \
|
||||
|| die "Existing user $SERVICE_USER has unexpected home directory $existing_home"
|
||||
if ! id -nG "$SERVICE_USER" | tr ' ' '\n' | grep -Fxq "$SERVICE_GROUP"; then
|
||||
usermod --append --groups "$SERVICE_GROUP" "$SERVICE_USER"
|
||||
fi
|
||||
return 0
|
||||
fi
|
||||
nologin_path=$(command -v nologin 2>/dev/null || true)
|
||||
[ -n "$nologin_path" ] || nologin_path=/usr/sbin/nologin
|
||||
[ -x "$nologin_path" ] || die "A nologin shell is required"
|
||||
useradd --system --gid "$SERVICE_GROUP" --home-dir "$STATE_ROOT" --shell "$nologin_path" "$SERVICE_USER"
|
||||
}
|
||||
|
||||
prepare_managed_layout() {
|
||||
command -v runuser >/dev/null 2>&1 || die "runuser is required"
|
||||
install -d -o root -g "$SERVICE_GROUP" -m 0750 \
|
||||
"$APP_ROOT" "$APP_ROOT/releases" "$APP_ROOT/runtime" "$APP_ROOT/bin"
|
||||
install -d -o "$SERVICE_USER" -g "$SERVICE_GROUP" -m 0750 \
|
||||
"$STATE_ROOT" "$STATE_ROOT/files" "$STATE_ROOT/tmp" /var/log/kaidi
|
||||
install -d -o "$SERVICE_USER" -g "$SERVICE_GROUP" -m 0700 "$STATE_ROOT/setup"
|
||||
install -d -o root -g "$SERVICE_GROUP" -m 0750 "$UPDATE_STATE_ROOT"
|
||||
install -d -o "$SERVICE_USER" -g "$SERVICE_GROUP" -m 0750 "$UPDATE_STATE_ROOT/inbox"
|
||||
install -d -o root -g root -m 0700 "$CONFIG_ROOT"
|
||||
}
|
||||
|
||||
secure_release_tree() {
|
||||
local release_dir=$1
|
||||
chown -R root:"$SERVICE_GROUP" "$release_dir"
|
||||
find "$release_dir" -type d -exec chmod 0750 {} +
|
||||
find "$release_dir" -type f -exec chmod 0640 {} +
|
||||
chmod 0750 "$release_dir/ops/update.sh"
|
||||
}
|
||||
|
||||
restore_security_contexts() {
|
||||
command -v restorecon >/dev/null 2>&1 || return 0
|
||||
restorecon -RF "$APP_ROOT" "$STATE_ROOT" "$UPDATE_STATE_ROOT" /var/log/kaidi \
|
||||
/etc/systemd/system/kaidi-finance.service \
|
||||
/etc/systemd/system/kaidi-update.service \
|
||||
/etc/systemd/system/kaidi-update.path >/dev/null 2>&1 \
|
||||
|| log "SELinux context restoration reported a warning; service access checks will decide whether installation can continue"
|
||||
}
|
||||
|
||||
verify_service_access() {
|
||||
# shellcheck disable=SC2016 # Positional parameters are expanded by the child shell.
|
||||
runuser -u "$SERVICE_USER" -- sh -c \
|
||||
'cd "$1" && test -r app.jar && test -r public/index.html' sh "$APP_ROOT/current" \
|
||||
|| die "$SERVICE_USER cannot traverse or read the active release"
|
||||
runuser -u "$SERVICE_USER" -- test -x "$APP_ROOT/runtime/java/bin/java" \
|
||||
|| die "$SERVICE_USER cannot execute the managed Java runtime"
|
||||
runuser -u "$SERVICE_USER" -- "$APP_ROOT/runtime/java/bin/java" -version >/dev/null 2>&1 \
|
||||
|| die "The managed Java runtime cannot execute as $SERVICE_USER"
|
||||
runuser -u "$SERVICE_USER" -- test -w "$STATE_ROOT/files" \
|
||||
|| die "$SERVICE_USER cannot write the file-storage directory"
|
||||
runuser -u "$SERVICE_USER" -- test -w "$UPDATE_STATE_ROOT/inbox" \
|
||||
|| die "$SERVICE_USER cannot write the update inbox"
|
||||
log "Service-user filesystem and Java access checks passed"
|
||||
}
|
||||
|
||||
random_secret() { openssl rand -base64 36 | tr -d '\n/+=' | cut -c1-36; }
|
||||
@@ -599,6 +726,12 @@ backup_managed_state() {
|
||||
|
||||
restore_unit_state() {
|
||||
local unit=$1 was_enabled=$2 was_active=$3
|
||||
if ! systemctl cat "$unit" >/dev/null 2>&1; then
|
||||
systemctl reset-failed "$unit" >/dev/null 2>&1 || true
|
||||
[ "$was_enabled" = false ] && [ "$was_active" = false ]
|
||||
return
|
||||
fi
|
||||
systemctl reset-failed "$unit" >/dev/null 2>&1 || true
|
||||
if [ "$was_enabled" = true ]; then
|
||||
systemctl enable "$unit" >/dev/null 2>&1
|
||||
else
|
||||
@@ -631,7 +764,7 @@ rollback_install() {
|
||||
local index=0 path rollback_failed=false
|
||||
set +e
|
||||
log "Installation failed; restoring the previous managed state"
|
||||
systemctl stop kaidi-update.path kaidi-finance.service >/dev/null 2>&1 || rollback_failed=true
|
||||
systemctl stop kaidi-update.path kaidi-finance.service >/dev/null 2>&1 || true
|
||||
for path in "${MANAGED_PATHS[@]}"; do
|
||||
restore_managed_path "$path" "$index" || rollback_failed=true
|
||||
index=$((index + 1))
|
||||
@@ -639,7 +772,7 @@ rollback_install() {
|
||||
if [ -n "$RELEASE_DIR" ]; then
|
||||
rm -rf -- "$RELEASE_DIR" || rollback_failed=true
|
||||
fi
|
||||
if [ -d "$JAVA_PREVIOUS_DIR" ]; then
|
||||
if [ -d "$JAVA_PREVIOUS_DIR" ] || [ -L "$JAVA_PREVIOUS_DIR" ]; then
|
||||
rm -rf -- "$APP_ROOT/runtime/java" || rollback_failed=true
|
||||
mkdir -p "$APP_ROOT/runtime" || rollback_failed=true
|
||||
mv "$JAVA_PREVIOUS_DIR" "$APP_ROOT/runtime/java" || rollback_failed=true
|
||||
@@ -666,8 +799,10 @@ cleanup() {
|
||||
exit "$result"
|
||||
}
|
||||
|
||||
main() {
|
||||
trap cleanup EXIT
|
||||
|
||||
validate_inputs
|
||||
configure_app_port
|
||||
preflight_host
|
||||
install_packages
|
||||
@@ -714,25 +849,18 @@ find "$WORK_DIR/extracted" -type l -print -quit | grep -q . \
|
||||
[ "$(cat "$WORK_DIR/extracted/VERSION")" = "$VERSION" ] || die "Release version mismatch"
|
||||
[ -x "$WORK_DIR/extracted/ops/update.sh" ] || die "Release updater is missing"
|
||||
|
||||
prepare_java
|
||||
configure_database
|
||||
preflight_database
|
||||
|
||||
id kaidi >/dev/null 2>&1 || useradd --system --home "$STATE_ROOT" --shell /usr/sbin/nologin kaidi
|
||||
mkdir -p "$APP_ROOT/releases" "$APP_ROOT/bin" "$STATE_ROOT/files" "$STATE_ROOT/tmp" \
|
||||
"$STATE_ROOT/setup" "$UPDATE_STATE_ROOT/inbox" "$CONFIG_ROOT" /var/log/kaidi
|
||||
chown -R kaidi:kaidi "$STATE_ROOT" "$UPDATE_STATE_ROOT/inbox" /var/log/kaidi
|
||||
chown root:kaidi "$UPDATE_STATE_ROOT"
|
||||
chmod 0750 "$STATE_ROOT" "$STATE_ROOT/files" "$STATE_ROOT/tmp" "$UPDATE_STATE_ROOT" "$UPDATE_STATE_ROOT/inbox"
|
||||
chmod 0700 "$STATE_ROOT/setup"
|
||||
ensure_service_identity
|
||||
prepare_managed_layout
|
||||
prepare_java
|
||||
|
||||
RELEASE_DIR="$APP_ROOT/releases/$VERSION"
|
||||
[ ! -e "$RELEASE_DIR" ] || RELEASE_DIR="$APP_ROOT/releases/${VERSION}-reinstall-$(date -u +%Y%m%dT%H%M%SZ)"
|
||||
backup_managed_state
|
||||
activate_java
|
||||
mv "$WORK_DIR/extracted" "$RELEASE_DIR"
|
||||
chown -R root:root "$RELEASE_DIR"
|
||||
chmod -R go-w "$RELEASE_DIR"
|
||||
secure_release_tree "$RELEASE_DIR"
|
||||
ln -sfn "$RELEASE_DIR" "$APP_ROOT/current.next"
|
||||
mv -Tf "$APP_ROOT/current.next" "$APP_ROOT/current"
|
||||
install -m 0755 "$RELEASE_DIR/ops/update.sh" "$APP_ROOT/bin/update.sh"
|
||||
@@ -824,7 +952,15 @@ chmod 0600 "$CONFIG_ROOT/update.env"
|
||||
install -m 0644 "$RELEASE_DIR/ops/kaidi-finance.service" /etc/systemd/system/kaidi-finance.service
|
||||
install -m 0644 "$RELEASE_DIR/ops/kaidi-update.service" /etc/systemd/system/kaidi-update.service
|
||||
install -m 0644 "$RELEASE_DIR/ops/kaidi-update.path" /etc/systemd/system/kaidi-update.path
|
||||
restore_security_contexts
|
||||
verify_service_access
|
||||
systemd-analyze verify \
|
||||
/etc/systemd/system/kaidi-finance.service \
|
||||
/etc/systemd/system/kaidi-update.service \
|
||||
/etc/systemd/system/kaidi-update.path >/dev/null \
|
||||
|| die "Installed systemd units failed validation"
|
||||
systemctl daemon-reload
|
||||
systemctl reset-failed kaidi-finance.service >/dev/null 2>&1 || true
|
||||
systemctl enable kaidi-finance.service
|
||||
systemctl restart kaidi-finance.service
|
||||
wait_for_health
|
||||
@@ -875,3 +1011,6 @@ if [ "$REINSTALL" != true ] && [ "$SETUP_WIZARD" != true ]; then
|
||||
log "Temporary credentials: /root/kaidi-first-login.txt"
|
||||
log "Change the temporary password immediately after first sign-in"
|
||||
fi
|
||||
}
|
||||
|
||||
main "$@"
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
Description=Kaidi Finance System
|
||||
After=network-online.target
|
||||
Wants=network-online.target
|
||||
StartLimitIntervalSec=60
|
||||
StartLimitBurst=3
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
|
||||
+102
-25
@@ -18,6 +18,9 @@ RELEASE_API_URL=${UPDATE_RELEASE_API_URL:-}
|
||||
RELEASE_TOKEN=${UPDATE_RELEASE_TOKEN:-}
|
||||
CACHE_ROOT=${KAIDI_UPDATE_CACHE_ROOT:-$STATE_ROOT/cache}
|
||||
SERVICE_NAME=${KAIDI_SERVICE_NAME:-kaidi-finance.service}
|
||||
UPDATE_PATH_NAME=${KAIDI_UPDATE_PATH_NAME:-kaidi-update.path}
|
||||
SERVICE_USER=${KAIDI_SERVICE_USER:-kaidi}
|
||||
SERVICE_GROUP=${KAIDI_SERVICE_GROUP:-kaidi}
|
||||
HEALTH_URL=${KAIDI_HEALTH_URL:-http://127.0.0.1:18080/actuator/health}
|
||||
APP_INDEX_URL=${KAIDI_APP_INDEX_URL:-http://127.0.0.1:18080/}
|
||||
LOCK_FILE=$STATE_ROOT/update.lock
|
||||
@@ -38,9 +41,10 @@ case "$HEALTH_ATTEMPTS:$HEALTH_INTERVAL_SECONDS" in
|
||||
esac
|
||||
[ "$HEALTH_ATTEMPTS" -ge 1 ] || { printf '%s\n' "Update health-check attempts must be at least 1" >&2; exit 1; }
|
||||
|
||||
mkdir -p "$STATE_ROOT/inbox" "$PROCESSING_DIR" "$FAILED_REQUEST_ROOT" "$TRANSACTION_ROOT" \
|
||||
"$STATE_ROOT/work" "$APP_ROOT/releases" "$LOG_ROOT" "$BACKUP_ROOT" "$CACHE_ROOT"
|
||||
chmod 0700 "$PROCESSING_DIR" "$FAILED_REQUEST_ROOT" "$TRANSACTION_ROOT" "$BACKUP_ROOT" "$CACHE_ROOT"
|
||||
bootstrap_die() {
|
||||
printf '%s\n' "$1" >&2
|
||||
exit 1
|
||||
}
|
||||
|
||||
status() {
|
||||
state=$1
|
||||
@@ -77,6 +81,43 @@ fail() {
|
||||
exit 1
|
||||
}
|
||||
|
||||
prepare_update_layout() {
|
||||
id "$SERVICE_USER" >/dev/null 2>&1 || bootstrap_die "Service user $SERVICE_USER is missing"
|
||||
id -nG "$SERVICE_USER" | tr ' ' '\n' | grep -Fxq "$SERVICE_GROUP" \
|
||||
|| bootstrap_die "Service user $SERVICE_USER is not a member of group $SERVICE_GROUP"
|
||||
command -v runuser >/dev/null 2>&1 || bootstrap_die "runuser is required"
|
||||
install -d -o root -g "$SERVICE_GROUP" -m 0750 \
|
||||
"$APP_ROOT" "$APP_ROOT/releases" "$APP_ROOT/runtime" "$APP_ROOT/bin" "$STATE_ROOT" \
|
||||
|| bootstrap_die "Managed application or update directories could not be prepared"
|
||||
install -d -o "$SERVICE_USER" -g "$SERVICE_GROUP" -m 0750 "$STATE_ROOT/inbox" "$LOG_ROOT" \
|
||||
|| bootstrap_die "Writable update directories could not be prepared"
|
||||
install -d -o root -g root -m 0700 \
|
||||
"$PROCESSING_DIR" "$FAILED_REQUEST_ROOT" "$TRANSACTION_ROOT" "$STATE_ROOT/work" \
|
||||
"$BACKUP_ROOT" "$CACHE_ROOT" \
|
||||
|| bootstrap_die "Private update directories could not be prepared"
|
||||
}
|
||||
|
||||
secure_release_tree() {
|
||||
release_dir=$1
|
||||
chown -R root:"$SERVICE_GROUP" "$release_dir" || return 1
|
||||
find "$release_dir" -type d -exec chmod 0750 {} + || return 1
|
||||
find "$release_dir" -type f -exec chmod 0640 {} + || return 1
|
||||
chmod 0750 "$release_dir/ops/update.sh"
|
||||
}
|
||||
|
||||
verify_release_access() {
|
||||
release_dir=$1
|
||||
# shellcheck disable=SC2016 # Positional parameters are expanded by the child shell.
|
||||
runuser -u "$SERVICE_USER" -- sh -c \
|
||||
'cd "$1" && test -r app.jar && test -r public/index.html' sh "$release_dir" \
|
||||
|| return 1
|
||||
runuser -u "$SERVICE_USER" -- test -x "$APP_ROOT/runtime/java/bin/java" \
|
||||
|| return 1
|
||||
runuser -u "$SERVICE_USER" -- "$APP_ROOT/runtime/java/bin/java" -version >/dev/null 2>&1
|
||||
}
|
||||
|
||||
prepare_update_layout
|
||||
|
||||
# shellcheck disable=SC2329 # Invoked by the EXIT trap below.
|
||||
cleanup() {
|
||||
rc=$?
|
||||
@@ -232,6 +273,22 @@ atomic_install() {
|
||||
mv -f "$install_temporary" "$install_destination"
|
||||
}
|
||||
|
||||
install_operation() {
|
||||
operation_source=$1
|
||||
operation_destination=$2
|
||||
operation_mode=$3
|
||||
operation_is_systemd=$4
|
||||
if [ -f "$operation_destination" ] && [ ! -L "$operation_destination" ] \
|
||||
&& cmp -s "$operation_source" "$operation_destination"; then
|
||||
chmod "$operation_mode" "$operation_destination"
|
||||
return
|
||||
fi
|
||||
atomic_install "$operation_source" "$operation_destination" "$operation_mode" || return 1
|
||||
if [ "$operation_is_systemd" = true ]; then
|
||||
SYSTEMD_OPERATIONS_CHANGED=true
|
||||
fi
|
||||
}
|
||||
|
||||
backup_managed_file() {
|
||||
backup_source=$1
|
||||
backup_name=$2
|
||||
@@ -271,14 +328,16 @@ backup_operations() {
|
||||
}
|
||||
|
||||
apply_operations() {
|
||||
atomic_install "$RELEASE_DIR/ops/update.sh" "$UPDATER_PATH" 0755 \
|
||||
&& atomic_install "$RELEASE_DIR/ops/kaidi-finance.service" \
|
||||
"$SYSTEMD_ROOT/kaidi-finance.service" 0644 \
|
||||
&& atomic_install "$RELEASE_DIR/ops/kaidi-update.service" \
|
||||
"$SYSTEMD_ROOT/kaidi-update.service" 0644 \
|
||||
&& atomic_install "$RELEASE_DIR/ops/kaidi-update.path" \
|
||||
"$SYSTEMD_ROOT/kaidi-update.path" 0644 \
|
||||
&& systemctl daemon-reload
|
||||
SYSTEMD_OPERATIONS_CHANGED=false
|
||||
install_operation "$RELEASE_DIR/ops/update.sh" "$UPDATER_PATH" 0755 false \
|
||||
&& install_operation "$RELEASE_DIR/ops/kaidi-finance.service" \
|
||||
"$SYSTEMD_ROOT/kaidi-finance.service" 0644 true \
|
||||
&& install_operation "$RELEASE_DIR/ops/kaidi-update.service" \
|
||||
"$SYSTEMD_ROOT/kaidi-update.service" 0644 true \
|
||||
&& install_operation "$RELEASE_DIR/ops/kaidi-update.path" \
|
||||
"$SYSTEMD_ROOT/kaidi-update.path" 0644 true \
|
||||
|| return 1
|
||||
[ "$SYSTEMD_OPERATIONS_CHANGED" = false ] || systemctl daemon-reload
|
||||
}
|
||||
|
||||
restore_operations() {
|
||||
@@ -317,23 +376,28 @@ rollback_active_transaction() {
|
||||
previous_target=$(transaction_value previous-target)
|
||||
failed_release=$(transaction_value release-dir)
|
||||
OPS_BACKUP="$ACTIVE_TRANSACTION/operations-backup"
|
||||
rollback_ok=true
|
||||
link_restored=true
|
||||
operations_restored=true
|
||||
|
||||
systemctl stop "$SERVICE_NAME" || true
|
||||
if [ -n "$previous_target" ] && [ -d "$previous_target" ]; then
|
||||
if ! ln -sfn "$previous_target" "$APP_ROOT/current.next" \
|
||||
|| ! mv -Tf "$APP_ROOT/current.next" "$APP_ROOT/current"; then
|
||||
rollback_ok=false
|
||||
link_restored=false
|
||||
fi
|
||||
else
|
||||
rollback_ok=false
|
||||
link_restored=false
|
||||
fi
|
||||
restore_operations || rollback_ok=false
|
||||
systemctl start "$SERVICE_NAME" || rollback_ok=false
|
||||
if [ "$rollback_ok" = true ] && verify_app_surface; then
|
||||
restore_operations || operations_restored=false
|
||||
systemctl reset-failed "$SERVICE_NAME" >/dev/null 2>&1 || true
|
||||
systemctl start "$SERVICE_NAME" || true
|
||||
if [ "$link_restored" = true ] && verify_app_surface; then
|
||||
remove_failed_release "$failed_release"
|
||||
rm -rf "$ACTIVE_TRANSACTION"
|
||||
fail "$reason; previous release was restored and verified"
|
||||
if [ "$operations_restored" = true ]; then
|
||||
fail "$reason; previous release was restored and verified"
|
||||
fi
|
||||
fail "$reason; previous release is running, but operations restoration requires manual review"
|
||||
fi
|
||||
TERMINAL_STATUS_WRITTEN=true
|
||||
status FAILED "$reason; rollback is incomplete and will be retried" "${TARGET_VERSION:-}"
|
||||
@@ -520,8 +584,14 @@ if [ -e "$RELEASE_DIR" ]; then
|
||||
rm -rf "$RELEASE_DIR" || fail "Failed release staging directory could not be cleaned"
|
||||
fi
|
||||
mv "$WORK_DIR/extracted" "$RELEASE_DIR" || fail "Release directory could not be activated"
|
||||
chown -R root:root "$RELEASE_DIR" || fail "Release ownership could not be secured"
|
||||
chmod -R go-w "$RELEASE_DIR" || fail "Release permissions could not be secured"
|
||||
secure_release_tree "$RELEASE_DIR" || fail "Release ownership or permissions could not be secured"
|
||||
if command -v restorecon >/dev/null 2>&1; then
|
||||
restorecon -RF "$APP_ROOT" >/dev/null 2>&1 || true
|
||||
fi
|
||||
if ! verify_release_access "$RELEASE_DIR"; then
|
||||
rm -rf "$RELEASE_DIR"
|
||||
fail "Service user cannot access the release or managed Java runtime"
|
||||
fi
|
||||
|
||||
PREVIOUS_TARGET=$(readlink "$APP_ROOT/current" 2>/dev/null || true)
|
||||
mkdir "$ACTIVE_TRANSACTION"
|
||||
@@ -552,15 +622,22 @@ write_transaction_value phase APP_SWITCHED
|
||||
|
||||
status RUNNING "Starting and verifying release $TARGET_VERSION" "$TARGET_VERSION"
|
||||
write_transaction_value phase HEALTH_CHECKING
|
||||
if systemctl start "$SERVICE_NAME" \
|
||||
&& systemctl is-active --quiet kaidi-update.path \
|
||||
&& verify_app_surface; then
|
||||
systemctl reset-failed "$SERVICE_NAME" >/dev/null 2>&1 || true
|
||||
systemctl start "$SERVICE_NAME" || true
|
||||
if verify_app_surface; then
|
||||
success_message="Release $TARGET_VERSION is running"
|
||||
if ! systemctl start "$UPDATE_PATH_NAME" >/dev/null 2>&1; then
|
||||
success_message="$success_message; automatic update watcher could not be started"
|
||||
fi
|
||||
write_transaction_value phase COMMITTED
|
||||
status SUCCEEDED "Release $TARGET_VERSION is running" "$TARGET_VERSION"
|
||||
status SUCCEEDED "$success_message" "$TARGET_VERSION"
|
||||
TERMINAL_STATUS_WRITTEN=true
|
||||
complete_request
|
||||
rm -rf "$ACTIVE_TRANSACTION"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
rollback_active_transaction "Release health or application-surface verification failed"
|
||||
service_state=$(systemctl is-active "$SERVICE_NAME" 2>/dev/null || true)
|
||||
[ -n "$service_state" ] || service_state=unknown
|
||||
rollback_active_transaction \
|
||||
"Release health or application-surface verification failed (service state: $service_state)"
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
import { expect, test } from '@playwright/test';
|
||||
|
||||
test('release build boots the setup wizard without runtime errors', async ({ page }) => {
|
||||
const pageErrors: string[] = [];
|
||||
const consoleErrors: string[] = [];
|
||||
|
||||
page.on('pageerror', (error) => pageErrors.push(error.message));
|
||||
page.on('console', (message) => {
|
||||
if (message.type() === 'error') consoleErrors.push(message.text());
|
||||
});
|
||||
await page.route('**/api/v1/setup/status', async (route) => {
|
||||
await route.fulfill({
|
||||
json: {
|
||||
data: {
|
||||
required: true,
|
||||
locked: false,
|
||||
supportedDatabaseTypes: ['MYSQL'],
|
||||
message: '请完成安装',
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
const response = await page.goto('/setup');
|
||||
expect(response?.ok()).toBe(true);
|
||||
await expect(page.getByRole('heading', { name: '安装向导', exact: true })).toBeVisible();
|
||||
expect(pageErrors).toEqual([]);
|
||||
expect(consoleErrors).toEqual([]);
|
||||
});
|
||||
@@ -11,6 +11,7 @@ test('first-run wizard tests MySQL, creates the administrator and stays responsi
|
||||
data: {
|
||||
required: !completed,
|
||||
locked: completed,
|
||||
ready: completed,
|
||||
supportedDatabaseTypes: ['MYSQL'],
|
||||
message: completed ? '系统已完成安装' : '请完成安装',
|
||||
},
|
||||
@@ -30,7 +31,7 @@ test('first-run wizard tests MySQL, creates the administrator and stays responsi
|
||||
databaseType: 'MYSQL',
|
||||
serverVersion: '8.4.6',
|
||||
schemaReady: true,
|
||||
message: 'MySQL 8.4 连接和 DDL/DML 权限验证通过',
|
||||
message: 'MySQL 8.4 连接、排序规则和完整迁移权限验证通过',
|
||||
},
|
||||
},
|
||||
});
|
||||
@@ -58,7 +59,7 @@ test('first-run wizard tests MySQL, creates the administrator and stays responsi
|
||||
await page.getByLabel('数据库密码').fill('fixture-db-password');
|
||||
await page.getByLabel('安装码').fill('fixture-setup-code');
|
||||
await page.getByRole('button', { name: '测试连接' }).click();
|
||||
await expect(page.getByText('MySQL 8.4 连接和 DDL/DML 权限验证通过')).toBeVisible();
|
||||
await expect(page.getByText('MySQL 8.4 连接、排序规则和完整迁移权限验证通过')).toBeVisible();
|
||||
await page.getByRole('button', { name: '下一步' }).click();
|
||||
|
||||
await page.getByLabel('管理员密码').fill('SetupAdmin@2026Strong');
|
||||
@@ -74,3 +75,61 @@ test('first-run wizard tests MySQL, creates the administrator and stays responsi
|
||||
}));
|
||||
expect(layout.scrollWidth).toBeLessThanOrEqual(layout.clientWidth);
|
||||
});
|
||||
|
||||
test('confirms completion after the setup response is interrupted by a service restart', async ({ page }) => {
|
||||
let completionStarted = false;
|
||||
let recoveryChecks = 0;
|
||||
await page.route('**/api/v1/setup/**', async (route) => {
|
||||
const request = route.request();
|
||||
const pathname = new URL(request.url()).pathname;
|
||||
if (pathname === '/api/v1/setup/status') {
|
||||
if (completionStarted) recoveryChecks += 1;
|
||||
const ready = completionStarted && recoveryChecks >= 2;
|
||||
await route.fulfill({
|
||||
json: {
|
||||
data: {
|
||||
required: !completionStarted,
|
||||
locked: completionStarted,
|
||||
ready,
|
||||
supportedDatabaseTypes: ['MYSQL'],
|
||||
message: ready ? '系统已完成安装' : '请完成安装',
|
||||
},
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
const body = request.postDataJSON() as Record<string, unknown>;
|
||||
if (pathname.endsWith('/test-connection')) {
|
||||
await route.fulfill({
|
||||
json: {
|
||||
data: {
|
||||
successful: true,
|
||||
databaseType: 'MYSQL',
|
||||
serverVersion: '8.4.6',
|
||||
schemaReady: true,
|
||||
message: 'MySQL 8.4 连接、排序规则和完整迁移权限验证通过',
|
||||
},
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
expect(body.adminUsername).toBe('admin');
|
||||
completionStarted = true;
|
||||
await route.abort('connectionreset');
|
||||
});
|
||||
|
||||
await page.goto('/setup');
|
||||
await page.getByLabel('数据库密码').fill('fixture-db-password');
|
||||
await page.getByLabel('安装码').fill('fixture-setup-code');
|
||||
await page.getByRole('button', { name: '测试连接' }).click();
|
||||
await page.getByRole('button', { name: '下一步' }).click();
|
||||
await page.getByLabel('管理员密码').fill('SetupAdmin@2026Strong');
|
||||
await page.getByLabel('确认密码').fill('SetupAdmin@2026Strong');
|
||||
await page.getByRole('button', { name: '完成安装' }).click();
|
||||
await page.getByRole('button', { name: '确定', exact: true }).click();
|
||||
|
||||
await expect(page.getByText('连接暂时中断,正在确认安装结果。')).toBeVisible();
|
||||
await expect(page.getByText('安装完成', { exact: true })).toBeVisible();
|
||||
await expect(page.getByText('安装已完成,系统正在切换到正式模式')).toBeVisible();
|
||||
await expect(page.getByText('网络请求失败')).toHaveCount(0);
|
||||
});
|
||||
|
||||
@@ -178,6 +178,16 @@ test('system administrator checks and queues a signed online update', async ({ p
|
||||
expect(installBodies).toEqual([{ version: '1.0.0-preview.2', reason: '管理员确认立即重启' }]);
|
||||
});
|
||||
|
||||
test('brand logo returns the active identity to its workbench', async ({ page }) => {
|
||||
await installFixture(page, [], []);
|
||||
await page.goto('/governance/update');
|
||||
|
||||
await page.locator('.brand-logo').click();
|
||||
|
||||
await expect(page).toHaveURL(/\/governance\/settings$/);
|
||||
await expect(page.getByText('选择工作身份', { exact: true })).toHaveCount(0);
|
||||
});
|
||||
|
||||
test('disabled online updates expose status without an executable check action', async ({ page }) => {
|
||||
await installFixture(page, [], [], false);
|
||||
await page.goto('/governance/update');
|
||||
|
||||
@@ -18,6 +18,7 @@
|
||||
"site:preview": "npm run build && cp -r dist _site",
|
||||
"test": "vitest run",
|
||||
"test:e2e": "playwright test",
|
||||
"test:dist": "playwright test --config playwright.dist.config.ts",
|
||||
"test:a11y": "playwright test e2e/accessibility.e2e.ts",
|
||||
"audit:dependencies": "npm audit --audit-level=high --registry=https://registry.npmjs.org",
|
||||
"check:production": "node scripts/check-production-hygiene.mjs",
|
||||
|
||||
@@ -6,6 +6,7 @@ const baseURL = `http://127.0.0.1:${port}`;
|
||||
export default defineConfig({
|
||||
testDir: './e2e',
|
||||
testMatch: '**/*.e2e.ts',
|
||||
testIgnore: 'dist-smoke.e2e.ts',
|
||||
outputDir: 'test-results',
|
||||
timeout: 30_000,
|
||||
expect: { timeout: 8_000 },
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
import { defineConfig } from '@playwright/test';
|
||||
|
||||
const port = Number(process.env.PLAYWRIGHT_DIST_PORT || 3012);
|
||||
const baseURL = `http://127.0.0.1:${port}`;
|
||||
|
||||
export default defineConfig({
|
||||
testDir: './e2e',
|
||||
testMatch: 'dist-smoke.e2e.ts',
|
||||
outputDir: 'test-results-dist',
|
||||
timeout: 30_000,
|
||||
expect: { timeout: 8_000 },
|
||||
fullyParallel: false,
|
||||
workers: 1,
|
||||
forbidOnly: Boolean(process.env.CI),
|
||||
retries: process.env.CI ? 1 : 0,
|
||||
reporter: process.env.CI ? [['list'], ['html', { open: 'never', outputFolder: 'playwright-report-dist' }]] : 'list',
|
||||
use: {
|
||||
baseURL,
|
||||
locale: 'zh-CN',
|
||||
timezoneId: 'Asia/Shanghai',
|
||||
screenshot: 'only-on-failure',
|
||||
trace: 'retain-on-failure',
|
||||
},
|
||||
webServer: {
|
||||
command: `npm run preview -- --host 127.0.0.1 --port ${port}`,
|
||||
url: baseURL,
|
||||
reuseExistingServer: false,
|
||||
timeout: 120_000,
|
||||
},
|
||||
projects: [{ name: 'chromium-dist', use: { browserName: 'chromium', viewport: { width: 1366, height: 768 } } }],
|
||||
});
|
||||
@@ -1,8 +1,11 @@
|
||||
import { request } from '@/utils/request';
|
||||
|
||||
const SETUP_COMPLETION_TIMEOUT_MS = 120_000;
|
||||
|
||||
export interface SetupStatus {
|
||||
required: boolean;
|
||||
locked: boolean;
|
||||
ready: boolean;
|
||||
supportedDatabaseTypes: string[];
|
||||
message: string;
|
||||
}
|
||||
@@ -43,6 +46,7 @@ function normalizeStatus(value: SetupStatus): SetupStatus {
|
||||
return {
|
||||
required: Boolean(value?.required),
|
||||
locked: Boolean(value?.locked),
|
||||
ready: Boolean(value?.ready),
|
||||
supportedDatabaseTypes: Array.isArray(value?.supportedDatabaseTypes) ? value.supportedDatabaseTypes : [],
|
||||
message: value?.message || '',
|
||||
};
|
||||
@@ -57,5 +61,7 @@ export function testSetupConnection(data: SetupDatabaseRequest) {
|
||||
}
|
||||
|
||||
export function completeSetup(data: SetupCompleteRequest) {
|
||||
return request.post<SetupCompleted>({ url: '/setup/complete', data }).then((value) => value);
|
||||
return request
|
||||
.post<SetupCompleted>({ url: '/setup/complete', data, timeout: SETUP_COMPLETION_TIMEOUT_MS })
|
||||
.then((value) => value);
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
<div :class="layoutCls">
|
||||
<t-head-menu :class="menuCls" :theme="menuTheme" expand-type="popup" :value="active">
|
||||
<template #logo>
|
||||
<span v-if="showLogo" class="header-logo-container" @click="handleNav('/role-select')">
|
||||
<span v-if="showLogo" class="header-logo-container" @click="handleNav(user.workbenchRoute)">
|
||||
<span class="header-brand">财务系统</span>
|
||||
</span>
|
||||
<div v-else class="header-operate-left">
|
||||
|
||||
@@ -45,7 +45,7 @@ import { useRouter } from 'vue-router';
|
||||
import { prefix } from '@/config/global';
|
||||
import { t } from '@/locales';
|
||||
import { getActive } from '@/router';
|
||||
import { useSettingStore } from '@/store';
|
||||
import { useSettingStore, useUserStore } from '@/store';
|
||||
import type { MenuRoute, ModeType } from '@/types/interface';
|
||||
|
||||
import pgk from '../../../package.json';
|
||||
@@ -155,6 +155,7 @@ const menuCls = computed(() => {
|
||||
|
||||
const router = useRouter();
|
||||
const settingStore = useSettingStore();
|
||||
const userStore = useUserStore();
|
||||
|
||||
const autoCollapsed = () => {
|
||||
const isCompact = window.innerWidth <= MIN_POINT;
|
||||
@@ -175,7 +176,7 @@ onUnmounted(() => {
|
||||
});
|
||||
|
||||
const goHome = () => {
|
||||
router.push('/role-select');
|
||||
router.push(userStore.workbenchRoute);
|
||||
};
|
||||
</script>
|
||||
<style lang="less" scoped>
|
||||
|
||||
@@ -73,16 +73,7 @@ const choose = async (roleCode: string) => {
|
||||
try {
|
||||
await userStore.selectRole(roleCode);
|
||||
permissionStore.initRoutes();
|
||||
const target = userStore.roles.find((role) => role.code === roleCode)?.workbenchRoute;
|
||||
const fallback =
|
||||
roleCode === 'PROJECT_MANAGER'
|
||||
? '/workbench/project'
|
||||
: roleCode === 'ARCHIVE_MANAGER'
|
||||
? '/workbench/archive'
|
||||
: roleCode === 'SYSTEM_ADMIN'
|
||||
? '/governance/settings'
|
||||
: '/workbench/finance';
|
||||
await router.replace(target || fallback);
|
||||
await router.replace(userStore.workbenchRoute);
|
||||
} catch (error) {
|
||||
MessagePlugin.error((error as Error).message || '身份选择失败,请重试');
|
||||
} finally {
|
||||
|
||||
@@ -162,6 +162,10 @@
|
||||
</t-form-item>
|
||||
</div>
|
||||
|
||||
<t-alert v-if="completing" class="setup-progress" theme="info" :close-btn="false">
|
||||
{{ completionProgressMessage }}
|
||||
</t-alert>
|
||||
|
||||
<div class="setup-actions">
|
||||
<t-button variant="outline" :disabled="completing" @click="currentStep = 0">
|
||||
<template #icon><t-icon name="chevron-left" /></template>
|
||||
@@ -223,8 +227,13 @@ const errorMessage = ref('');
|
||||
const connectionResult = ref<SetupConnection | null>(null);
|
||||
const verifiedFingerprint = ref('');
|
||||
const completionMessage = ref('系统正在重启,请稍候。');
|
||||
const completionProgressMessage = ref('正在初始化数据库结构并创建管理员,请稍候。');
|
||||
const countdown = ref(10);
|
||||
let countdownTimer: number | undefined;
|
||||
let unmounted = false;
|
||||
|
||||
const SETUP_CONFIRMATION_TIMEOUT_MS = 60_000;
|
||||
const SETUP_CONFIRMATION_INTERVAL_MS = 2_000;
|
||||
|
||||
const databaseForm = reactive<SetupDatabaseRequest>({
|
||||
setupCode: '',
|
||||
@@ -317,21 +326,51 @@ async function finishSetup(context?: SubmitContext) {
|
||||
return;
|
||||
}
|
||||
completing.value = true;
|
||||
completionProgressMessage.value = '正在初始化数据库结构并创建管理员,请稍候。';
|
||||
errorMessage.value = '';
|
||||
try {
|
||||
const result = await completeSetup({ ...databaseForm, ...adminForm });
|
||||
if (!result.completed) throw new Error('安装服务未确认完成,请稍后重试');
|
||||
completionMessage.value = result.message;
|
||||
countdown.value = Math.max(1, result.restartAfterSeconds || 10);
|
||||
currentStep.value = 2;
|
||||
startCountdown();
|
||||
showCompleted(result.message, result.restartAfterSeconds);
|
||||
} catch (error) {
|
||||
errorMessage.value = (error as Error).message || '安装初始化失败';
|
||||
const requestError = error as Error & { status?: number };
|
||||
if (requestError.status === undefined || requestError.status >= 500) {
|
||||
completionProgressMessage.value = '连接暂时中断,正在确认安装结果。';
|
||||
if (await waitForSetupCompletion()) {
|
||||
showCompleted('安装已完成,系统正在切换到正式模式', 10);
|
||||
return;
|
||||
}
|
||||
errorMessage.value = '安装结果暂未确认,请稍后重新打开安装页面;若问题持续,请检查服务日志。';
|
||||
} else {
|
||||
errorMessage.value = requestError.message || '安装初始化失败';
|
||||
}
|
||||
} finally {
|
||||
completing.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function waitForSetupCompletion() {
|
||||
const deadline = Date.now() + SETUP_CONFIRMATION_TIMEOUT_MS;
|
||||
while (Date.now() < deadline) {
|
||||
if (unmounted) return false;
|
||||
try {
|
||||
const status = await getSetupStatus();
|
||||
if (status.ready) return true;
|
||||
} catch {
|
||||
// A short connection failure is expected while systemd restarts the service.
|
||||
}
|
||||
await new Promise((resolve) => window.setTimeout(resolve, SETUP_CONFIRMATION_INTERVAL_MS));
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function showCompleted(message: string, restartAfterSeconds: number) {
|
||||
completionMessage.value = message;
|
||||
countdown.value = Math.max(1, restartAfterSeconds || 10);
|
||||
currentStep.value = 2;
|
||||
startCountdown();
|
||||
}
|
||||
|
||||
function confirmSetup() {
|
||||
void finishSetup();
|
||||
}
|
||||
@@ -340,13 +379,18 @@ function startCountdown() {
|
||||
window.clearInterval(countdownTimer);
|
||||
countdownTimer = window.setInterval(() => {
|
||||
countdown.value -= 1;
|
||||
if (countdown.value <= 0) openLogin();
|
||||
if (countdown.value <= 0) void openLogin();
|
||||
}, 1000);
|
||||
}
|
||||
|
||||
function openLogin() {
|
||||
async function openLogin() {
|
||||
window.clearInterval(countdownTimer);
|
||||
window.location.assign('/login');
|
||||
completionMessage.value = '系统正在启动,请稍候。';
|
||||
if (await waitForSetupCompletion()) {
|
||||
window.location.assign('/login');
|
||||
return;
|
||||
}
|
||||
completionMessage.value = '系统启动时间较长,请稍后刷新页面。';
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
@@ -364,7 +408,10 @@ onMounted(async () => {
|
||||
}
|
||||
});
|
||||
|
||||
onBeforeUnmount(() => window.clearInterval(countdownTimer));
|
||||
onBeforeUnmount(() => {
|
||||
unmounted = true;
|
||||
window.clearInterval(countdownTimer);
|
||||
});
|
||||
</script>
|
||||
<style scoped>
|
||||
.setup-page {
|
||||
@@ -382,8 +429,7 @@ onBeforeUnmount(() => window.clearInterval(countdownTimer));
|
||||
}
|
||||
|
||||
.setup-panel {
|
||||
align-self: center;
|
||||
justify-self: center;
|
||||
place-self: center;
|
||||
width: min(760px, 100%);
|
||||
min-width: 0;
|
||||
padding: 32px;
|
||||
@@ -445,6 +491,10 @@ h1 {
|
||||
margin-top: 8px;
|
||||
}
|
||||
|
||||
.setup-progress {
|
||||
margin-top: 20px;
|
||||
}
|
||||
|
||||
.setup-complete {
|
||||
min-height: 280px;
|
||||
display: flex;
|
||||
|
||||
@@ -5,6 +5,7 @@ import * as authApi from '@/api/auth';
|
||||
import { usePermissionStore } from '@/store';
|
||||
|
||||
import { hasPermissionAccess } from './menu-access';
|
||||
import { resolveWorkbenchRoute } from './workbench-route';
|
||||
|
||||
const emptyUser: UserView = {
|
||||
publicId: '',
|
||||
@@ -28,6 +29,7 @@ export const useUserStore = defineStore('user', {
|
||||
getters: {
|
||||
displayName: (state) => state.user.displayName || state.user.username,
|
||||
roleName: (state) => state.roles.find((role) => role.code === state.currentRole)?.name || '',
|
||||
workbenchRoute: (state) => resolveWorkbenchRoute(state.currentRole, state.roles),
|
||||
hasRole: (state) => (roleCode: string) => state.roles.some((role) => role.code === roleCode),
|
||||
hasPermission: (state) => (permission: string) =>
|
||||
hasPermissionAccess(state.currentRole, state.permissions, permission),
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
import type { RoleView } from '@/api/auth';
|
||||
|
||||
const fallbackWorkbenchRoutes: Record<string, string> = {
|
||||
PROJECT_MANAGER: '/workbench/project',
|
||||
FINANCE_MANAGER: '/workbench/finance',
|
||||
ARCHIVE_MANAGER: '/workbench/archive',
|
||||
SYSTEM_ADMIN: '/governance/settings',
|
||||
};
|
||||
|
||||
export function resolveWorkbenchRoute(currentRole: string | null, roles: RoleView[]): string {
|
||||
const configured = roles.find((role) => role.code === currentRole)?.workbenchRoute?.trim();
|
||||
return configured || fallbackWorkbenchRoutes[currentRole || ''] || '/role-select';
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
const requestMocks = vi.hoisted(() => ({
|
||||
post: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('@/utils/request', () => ({
|
||||
request: {
|
||||
post: requestMocks.post,
|
||||
},
|
||||
}));
|
||||
|
||||
import { completeSetup } from '../src/api/setup';
|
||||
|
||||
describe('setup API', () => {
|
||||
beforeEach(() => {
|
||||
requestMocks.post.mockReset();
|
||||
requestMocks.post.mockResolvedValue({ completed: true });
|
||||
});
|
||||
|
||||
it('allows enough time for the first database migration', async () => {
|
||||
const request = {
|
||||
setupCode: 'fixture-code',
|
||||
databaseType: 'MYSQL' as const,
|
||||
host: '127.0.0.1',
|
||||
port: 3306,
|
||||
database: 'kaidi_finance',
|
||||
username: 'kaidi',
|
||||
password: 'fixture-password',
|
||||
adminUsername: 'admin',
|
||||
adminDisplayName: '系统管理员',
|
||||
adminPassword: 'SetupAdmin@2026Strong',
|
||||
adminPasswordConfirmation: 'SetupAdmin@2026Strong',
|
||||
};
|
||||
|
||||
await completeSetup(request);
|
||||
|
||||
expect(requestMocks.post).toHaveBeenCalledWith({
|
||||
url: '/setup/complete',
|
||||
data: request,
|
||||
timeout: 120_000,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,25 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import type { RoleView } from '../src/api/auth';
|
||||
import { resolveWorkbenchRoute } from '../src/store/modules/workbench-route';
|
||||
|
||||
const roles: RoleView[] = [
|
||||
{ code: 'SYSTEM_ADMIN', name: '系统管理员', workbenchRoute: '/governance/settings' },
|
||||
{ code: 'FINANCE_MANAGER', name: '财务管理人员', workbenchRoute: '/workbench/finance' },
|
||||
];
|
||||
|
||||
describe('active identity workbench route', () => {
|
||||
it('uses the route supplied for the active role', () => {
|
||||
expect(resolveWorkbenchRoute('SYSTEM_ADMIN', roles)).toBe('/governance/settings');
|
||||
expect(resolveWorkbenchRoute('FINANCE_MANAGER', roles)).toBe('/workbench/finance');
|
||||
});
|
||||
|
||||
it('falls back to the built-in role workbench when the server route is absent', () => {
|
||||
expect(resolveWorkbenchRoute('PROJECT_MANAGER', [])).toBe('/workbench/project');
|
||||
expect(resolveWorkbenchRoute('ARCHIVE_MANAGER', [])).toBe('/workbench/archive');
|
||||
});
|
||||
|
||||
it('keeps role selection for sessions without an active identity', () => {
|
||||
expect(resolveWorkbenchRoute(null, roles)).toBe('/role-select');
|
||||
});
|
||||
});
|
||||
@@ -55,7 +55,6 @@ export default ({ mode }: ConfigEnv): UserConfig => {
|
||||
name: 'tdesign-vendor',
|
||||
test: /node_modules[\\/]tdesign-(?:vue-next|icons-vue-next)[\\/]/,
|
||||
priority: 30,
|
||||
maxSize: 480 * 1024,
|
||||
},
|
||||
{
|
||||
name: 'vue-vendor',
|
||||
|
||||
@@ -10,6 +10,10 @@ fail() {
|
||||
exit 1
|
||||
}
|
||||
|
||||
mode_of() {
|
||||
stat -c '%a' "$1" 2>/dev/null || stat -f '%Lp' "$1"
|
||||
}
|
||||
|
||||
# Load only pure helper functions. The installer itself must never run in this fixture.
|
||||
{
|
||||
sed -n '/^decode_env_value()/,/^}/p' "$ROOT/deploy/install.sh"
|
||||
@@ -22,7 +26,9 @@ fail() {
|
||||
sed -n '/^configure_app_port()/,/^}/p' "$ROOT/deploy/install.sh"
|
||||
sed -n '/^is_semver()/,/^}/p' "$ROOT/deploy/install.sh"
|
||||
sed -n '/^write_env_file_preserving_unknown()/,/^}/p' "$ROOT/deploy/install.sh"
|
||||
sed -n '/^normalized_host_arch()/,/^}/p' "$ROOT/deploy/install.sh"
|
||||
sed -n '/^azul_arch()/,/^}/p' "$ROOT/deploy/install.sh"
|
||||
sed -n '/^java_arch_matches_host()/,/^}/p' "$ROOT/deploy/install.sh"
|
||||
sed -n '/^system_java_home()/,/^}/p' "$ROOT/deploy/install.sh"
|
||||
sed -n '/^sha256_file()/,/^}/p' "$ROOT/deploy/install.sh"
|
||||
sed -n '/^prepare_java()/,/^}/p' "$ROOT/deploy/install.sh"
|
||||
@@ -31,6 +37,8 @@ fail() {
|
||||
sed -n '/^download_release_asset()/,/^}/p' "$ROOT/deploy/install.sh"
|
||||
sed -n '/^install_packages()/,/^}/p' "$ROOT/deploy/install.sh"
|
||||
sed -n '/^preflight_database()/,/^}/p' "$ROOT/deploy/install.sh"
|
||||
sed -n '/^secure_release_tree()/,/^}/p' "$ROOT/deploy/install.sh"
|
||||
sed -n '/^restore_unit_state()/,/^}/p' "$ROOT/deploy/install.sh"
|
||||
} > "$WORK/helpers.sh"
|
||||
# shellcheck disable=SC1090,SC1091
|
||||
source "$WORK/helpers.sh"
|
||||
@@ -38,6 +46,35 @@ source "$WORK/helpers.sh"
|
||||
export SETUP_WIZARD=true
|
||||
preflight_database || fail 'setup wizard database preflight returned a failure status'
|
||||
|
||||
release_permissions="$WORK/release-permissions"
|
||||
mkdir -p "$release_permissions/public" "$release_permissions/ops"
|
||||
printf 'jar\n' > "$release_permissions/app.jar"
|
||||
printf 'html\n' > "$release_permissions/public/index.html"
|
||||
printf '#!/bin/sh\n' > "$release_permissions/ops/update.sh"
|
||||
chmod -R 0777 "$release_permissions"
|
||||
(
|
||||
# shellcheck disable=SC2329 # Invoked indirectly by the sourced installer helper.
|
||||
chown() { return 0; }
|
||||
export SERVICE_GROUP=fixture
|
||||
secure_release_tree "$release_permissions"
|
||||
)
|
||||
[ "$(mode_of "$release_permissions")" = 750 ] || fail 'release root mode is not 0750'
|
||||
[ "$(mode_of "$release_permissions/public")" = 750 ] || fail 'release directory mode is not 0750'
|
||||
[ "$(mode_of "$release_permissions/app.jar")" = 640 ] || fail 'release file mode is not 0640'
|
||||
[ "$(mode_of "$release_permissions/ops/update.sh")" = 750 ] || fail 'release updater mode is not 0750'
|
||||
|
||||
(
|
||||
# shellcheck disable=SC2329 # Invoked indirectly by the sourced installer helper.
|
||||
systemctl() {
|
||||
case "$1" in
|
||||
cat) return 1 ;;
|
||||
reset-failed) return 0 ;;
|
||||
*) return 97 ;;
|
||||
esac
|
||||
}
|
||||
restore_unit_state missing.service false false
|
||||
) || fail 'rollback treated an absent first-install unit as an incomplete restoration'
|
||||
|
||||
# shellcheck disable=SC2034 # Referenced by the extracted installer helper.
|
||||
REINSTALL=true
|
||||
# shellcheck disable=SC2034 # Referenced by the extracted installer helper.
|
||||
@@ -137,10 +174,23 @@ for arch in i386 i486 i586 i686; do
|
||||
ARCH_FIXTURE=$arch
|
||||
[ "$(azul_arch)" = i686 ] || fail "$arch did not map to the Azul i686 runtime"
|
||||
done
|
||||
(
|
||||
ARCH_FIXTURE=x86_64
|
||||
# shellcheck disable=SC2329 # Invoked indirectly by the sourced architecture helper.
|
||||
getconf() { printf '32\n'; }
|
||||
[ "$(normalized_host_arch)" = x86 ] \
|
||||
|| fail '32-bit userspace on an x86_64 kernel was not normalized to x86'
|
||||
export HOST_ARCH=x86
|
||||
[ "$(azul_arch)" = i686 ] \
|
||||
|| fail '32-bit userspace on an x86_64 kernel did not select the i686 Java runtime'
|
||||
)
|
||||
|
||||
mkdir -p "$WORK/fake-jre/bin"
|
||||
cat > "$WORK/fake-jre/bin/java" <<'JAVA'
|
||||
#!/usr/bin/env sh
|
||||
if [ "${1:-}" = '-XshowSettings:properties' ]; then
|
||||
printf ' os.arch = x86\n' >&2
|
||||
fi
|
||||
printf 'openjdk version "17-fixture"\n' >&2
|
||||
JAVA
|
||||
chmod 0755 "$WORK/fake-jre/bin/java"
|
||||
@@ -168,9 +218,10 @@ prepare_java >/dev/null 2>&1
|
||||
rm -rf "$JAVA_STAGED_DIR"
|
||||
export KAIDI_JAVA_HOME="$WORK/fake-jre"
|
||||
prepare_java >/dev/null 2>&1
|
||||
[ -L "$JAVA_STAGED_DIR" ] || fail 'existing Java 17 runtime was not reused'
|
||||
[ "$(readlink -f "$JAVA_STAGED_DIR")" = "$(readlink -f "$WORK/fake-jre")" ] \
|
||||
|| fail 'installer linked an unexpected local Java runtime'
|
||||
[ -d "$JAVA_STAGED_DIR" ] && [ ! -L "$JAVA_STAGED_DIR" ] \
|
||||
|| fail 'existing Java 17 runtime was not copied into managed storage'
|
||||
cmp -s "$WORK/fake-jre/bin/java" "$JAVA_STAGED_DIR/bin/java" \
|
||||
|| fail 'installer staged an unexpected local Java runtime'
|
||||
|
||||
export RELEASE_API_URL=https://gitea.fixture.invalid/api/v1/repos/ERP-Team/kaidi/releases/latest
|
||||
RELEASE_TOKEN=fixture-read-only-token
|
||||
@@ -237,14 +288,35 @@ grep -Fq 'download "$api" "$java_metadata"' "$ROOT/deploy/install.sh" \
|
||||
# shellcheck disable=SC2016 # Match literal installer source.
|
||||
grep -Fq 'java_sha256=$(jq -er' "$ROOT/deploy/install.sh" \
|
||||
|| fail 'installer no longer obtains the Java runtime SHA-256'
|
||||
grep -Fq 'Using existing Java 17 runtime' "$ROOT/deploy/install.sh" \
|
||||
grep -Fq 'Copying existing Java 17 runtime' "$ROOT/deploy/install.sh" \
|
||||
|| fail 'installer no longer reuses a local Java 17 runtime'
|
||||
# shellcheck disable=SC2016 # Match literal installer source.
|
||||
grep -Fq 'cp -R "$system_home/." "$JAVA_STAGED_DIR/"' "$ROOT/deploy/install.sh" \
|
||||
|| fail 'installer no longer copies a local Java runtime into managed storage'
|
||||
# shellcheck disable=SC2016 # Match literal installer source.
|
||||
! grep -Fq 'ln -s "$system_home"' "$ROOT/deploy/install.sh" \
|
||||
|| fail 'installer must not link the service to an externally managed Java directory'
|
||||
# shellcheck disable=SC2016 # Match the literal installer command.
|
||||
grep -Fq -- '--connect-timeout 1 --max-time 2 "$HEALTH_URL" 2>/dev/null' "$ROOT/deploy/install.sh" \
|
||||
|| fail 'installer no longer performs a quiet bounded health check'
|
||||
grep -Fq 'restart_count" -ge 3' "$ROOT/deploy/install.sh" \
|
||||
|| fail 'installer no longer stops early after repeated service restarts'
|
||||
# shellcheck disable=SC2016 # Match literal installer source.
|
||||
grep -Fq 'install -d -o root -g "$SERVICE_GROUP" -m 0750' "$ROOT/deploy/install.sh" \
|
||||
|| fail 'installer no longer creates traversable root-owned application directories'
|
||||
# shellcheck disable=SC2016 # Match literal installer source.
|
||||
grep -Fq 'find "$release_dir" -type d -exec chmod 0750 {} +' "$ROOT/deploy/install.sh" \
|
||||
|| fail 'installer no longer secures release directory traversal permissions'
|
||||
# shellcheck disable=SC2016 # Match literal installer source.
|
||||
grep -Fq 'runuser -u "$SERVICE_USER" -- sh -c' "$ROOT/deploy/install.sh" \
|
||||
|| fail 'installer no longer validates the release as the service user'
|
||||
grep -Fq 'systemctl reset-failed kaidi-finance.service' "$ROOT/deploy/install.sh" \
|
||||
|| fail 'installer no longer resets stale systemd failure state'
|
||||
[ "$(tail -n 1 "$ROOT/deploy/install.sh")" = 'main "$@"' ] \
|
||||
|| fail 'installer can execute before the complete curl stream is parsed'
|
||||
grep -Fqx 'StartLimitBurst=3' "$ROOT/deploy/systemd/kaidi-finance.service" \
|
||||
|| fail 'application service no longer has a bounded restart burst'
|
||||
# shellcheck disable=SC2016 # Match literal installer source.
|
||||
grep -Fq '[ "$actual_sha256" = "$java_sha256" ]' "$ROOT/deploy/install.sh" \
|
||||
|| fail 'installer no longer verifies the Java runtime SHA-256'
|
||||
grep -Fq 'https://git.awaioi.com/api/v1/repos/ERP-Team/kaidi/releases/latest' "$ROOT/deploy/install.sh" \
|
||||
@@ -253,8 +325,11 @@ grep -Fq 'https://git.awaioi.com/api/v1/repos/ERP-Team/kaidi/releases/latest' "$
|
||||
grep -Fq 'TRUSTED_PUBLIC_KEY_SHA256=${KAIDI_RELEASE_PUBLIC_KEY_SHA256:-807c6aec1dc3f7ce494db16aa9d763c66f292033c38f328afd0390d2715a8cd9}' "$ROOT/deploy/install.sh" \
|
||||
|| fail 'installer does not pin the default release public-key fingerprint'
|
||||
# shellcheck disable=SC2016 # Match literal installer source.
|
||||
grep -Fq 'SETUP_WIZARD=${KAIDI_SETUP_WIZARD:-true}' "$ROOT/deploy/install.sh" \
|
||||
|| fail 'installer does not enable the first-run setup wizard by default'
|
||||
grep -Fq 'if [ "${KAIDI_SETUP_WIZARD+x}" = x ]; then' "$ROOT/deploy/install.sh" \
|
||||
|| fail 'installer no longer distinguishes an explicit setup-wizard selection'
|
||||
# shellcheck disable=SC2016 # Match literal installer source.
|
||||
grep -Fq 'elif [ "$REINSTALL" = true ]; then' "$ROOT/deploy/install.sh" \
|
||||
|| fail 'repair reinstall no longer defaults to production mode'
|
||||
! grep -Fq 'docker run' "$ROOT/deploy/install.sh" \
|
||||
|| fail 'installer must not create a MySQL container'
|
||||
! grep -Fq 'install_docker' "$ROOT/deploy/install.sh" \
|
||||
@@ -301,8 +376,8 @@ grep -Fq 'EnvironmentFile=-/var/lib/kaidi/setup/application.env' \
|
||||
grep -Fq 'EnvironmentFile=-/var/lib/kaidi/setup/application.env' \
|
||||
"$ROOT/deploy/systemd/kaidi-update.service" \
|
||||
|| fail 'update service no longer loads setup database overrides'
|
||||
# shellcheck disable=SC2016 # Match the literal installer source.
|
||||
grep -Fq 'chown root:kaidi "$UPDATE_STATE_ROOT"' "$ROOT/deploy/install.sh" \
|
||||
# shellcheck disable=SC2016 # Match literal installer source.
|
||||
grep -Fq 'install -d -o root -g "$SERVICE_GROUP" -m 0750 "$UPDATE_STATE_ROOT"' "$ROOT/deploy/install.sh" \
|
||||
|| fail 'update state parent is not group-accessible to the application user'
|
||||
grep -Fq 'install.sh | sudo bash' "$ROOT/README.md" \
|
||||
|| fail 'README does not document the public one-line setup-wizard install path'
|
||||
|
||||
@@ -11,6 +11,10 @@ fail() {
|
||||
exit 1
|
||||
}
|
||||
|
||||
mode_of() {
|
||||
stat -c '%a' "$1" 2>/dev/null || stat -f '%Lp' "$1"
|
||||
}
|
||||
|
||||
sed -n '/^is_semver()/,/^}/p' "$ROOT/deploy/update.sh" > "$WORK/update-semver.sh"
|
||||
# shellcheck disable=SC1090,SC1091
|
||||
source "$WORK/update-semver.sh"
|
||||
@@ -21,6 +25,20 @@ for version in 01.2.3 1.02.3 1.2.03 1.2.3-01 1.2.3-alpha..1; do
|
||||
! is_semver "$version" || fail "updater accepted invalid SemVer $version"
|
||||
done
|
||||
|
||||
missing_service_user="kaidi-fixture-missing-$$"
|
||||
if KAIDI_APP_ROOT="$WORK/bootstrap/app" \
|
||||
KAIDI_UPDATE_STATE_ROOT="$WORK/bootstrap/state" \
|
||||
KAIDI_LOG_ROOT="$WORK/bootstrap/log" \
|
||||
KAIDI_SERVICE_USER="$missing_service_user" \
|
||||
KAIDI_SERVICE_GROUP="$missing_service_user" \
|
||||
sh "$ROOT/deploy/update.sh" > "$WORK/bootstrap.log" 2>&1; then
|
||||
fail 'updater accepted a missing service identity during bootstrap'
|
||||
fi
|
||||
grep -Fq "Service user $missing_service_user is missing" "$WORK/bootstrap.log" \
|
||||
|| fail 'updater bootstrap failure did not preserve its diagnostic'
|
||||
! grep -Eq 'No such file|nonexistent directory|cannot create' "$WORK/bootstrap.log" \
|
||||
|| fail 'updater bootstrap failure was masked by an unavailable status directory'
|
||||
|
||||
write_mock_commands() {
|
||||
local mock_bin=$1
|
||||
mkdir -p "$mock_bin"
|
||||
@@ -74,6 +92,7 @@ SH
|
||||
cat > "$mock_bin/systemctl" <<'SH'
|
||||
#!/bin/sh
|
||||
printf '%s\n' "$*" >> "$MOCK_SYSTEMCTL_LOG"
|
||||
[ "${MOCK_UPDATE_PATH_START:-success}:$*" != 'fail:start kaidi-update.path' ] || exit 1
|
||||
exit 0
|
||||
SH
|
||||
|
||||
@@ -99,6 +118,33 @@ SH
|
||||
cat > "$mock_bin/chown" <<'SH'
|
||||
#!/bin/sh
|
||||
exit 0
|
||||
SH
|
||||
|
||||
cat > "$mock_bin/runuser" <<'SH'
|
||||
#!/bin/sh
|
||||
[ "${1:-}" = -u ] || exit 2
|
||||
shift 2
|
||||
[ "${1:-}" = -- ] && shift
|
||||
exec "$@"
|
||||
SH
|
||||
|
||||
cat > "$mock_bin/install" <<'SH'
|
||||
#!/usr/bin/env bash
|
||||
if [[ " $* " != *" -d "* ]]; then
|
||||
exec /usr/bin/install "$@"
|
||||
fi
|
||||
mode=0755
|
||||
paths=()
|
||||
while [ "$#" -gt 0 ]; do
|
||||
case "$1" in
|
||||
-d) shift ;;
|
||||
-o|-g) shift 2 ;;
|
||||
-m) mode=$2; shift 2 ;;
|
||||
*) paths+=("$1"); shift ;;
|
||||
esac
|
||||
done
|
||||
mkdir -p "${paths[@]}"
|
||||
chmod "$mode" "${paths[@]}"
|
||||
SH
|
||||
|
||||
cat > "$mock_bin/mv" <<'SH'
|
||||
@@ -125,6 +171,7 @@ SH
|
||||
build_release() {
|
||||
local fixture=$1
|
||||
local version=$2
|
||||
local unit_prefix=${3:-new}
|
||||
local stage="$fixture/stage"
|
||||
mkdir -p "$fixture/release" "$stage/public" "$stage/ops"
|
||||
printf 'new application\n' > "$stage/app.jar"
|
||||
@@ -133,7 +180,7 @@ build_release() {
|
||||
printf '#!/bin/sh\nprintf "new updater\\n"\n' > "$stage/ops/update.sh"
|
||||
chmod 0755 "$stage/ops/update.sh"
|
||||
for name in kaidi-finance.service kaidi-update.service kaidi-update.path; do
|
||||
printf 'new %s\n' "$name" > "$stage/ops/$name"
|
||||
printf '%s %s\n' "$unit_prefix" "$name" > "$stage/ops/$name"
|
||||
done
|
||||
|
||||
local artifact="kaidi-finance-$version.tar.gz"
|
||||
@@ -170,13 +217,18 @@ prepare_installation() {
|
||||
local fixture=$1
|
||||
local version=$2
|
||||
mkdir -p "$fixture/app/releases/1.0.0-preview.1/public" "$fixture/app/bin" \
|
||||
"$fixture/state/inbox" "$fixture/systemd" "$fixture/log"
|
||||
"$fixture/app/runtime/java/bin" "$fixture/state/inbox" "$fixture/systemd" "$fixture/log"
|
||||
printf 'old application\n' > "$fixture/app/releases/1.0.0-preview.1/app.jar"
|
||||
printf '<!doctype html><title>old</title>\n' > "$fixture/app/releases/1.0.0-preview.1/public/index.html"
|
||||
printf '1.0.0-preview.1\n' > "$fixture/app/releases/1.0.0-preview.1/VERSION"
|
||||
ln -s "$fixture/app/releases/1.0.0-preview.1" "$fixture/app/current"
|
||||
printf 'old update.sh\n' > "$fixture/app/bin/update.sh"
|
||||
chmod 0755 "$fixture/app/bin/update.sh"
|
||||
cat > "$fixture/app/runtime/java/bin/java" <<'SH'
|
||||
#!/bin/sh
|
||||
exit 0
|
||||
SH
|
||||
chmod 0755 "$fixture/app/runtime/java/bin/java"
|
||||
for name in kaidi-finance.service kaidi-update.service kaidi-update.path; do
|
||||
printf 'old %s\n' "$name" > "$fixture/systemd/$name"
|
||||
done
|
||||
@@ -222,6 +274,9 @@ run_update() {
|
||||
MOCK_RELEASE_ORIGIN="${FIXTURE_RELEASE_ORIGIN:-https://release.fixture.invalid}" \
|
||||
MOCK_EXPECT_RELEASE_TOKEN="${FIXTURE_RELEASE_TOKEN-}" \
|
||||
MOCK_SYSTEMCTL_LOG="$fixture/systemctl.log" \
|
||||
MOCK_UPDATE_PATH_START="${MOCK_UPDATE_PATH_START:-success}" \
|
||||
KAIDI_SERVICE_USER="$(id -un)" \
|
||||
KAIDI_SERVICE_GROUP="$(id -gn)" \
|
||||
KAIDI_APP_ROOT="$fixture/app" \
|
||||
KAIDI_UPDATE_STATE_ROOT="$fixture/state" \
|
||||
KAIDI_LOG_ROOT="$fixture/log" \
|
||||
@@ -310,6 +365,45 @@ assert_success_case() {
|
||||
|| fail 'success case left a claimed request behind'
|
||||
grep -qx 'daemon-reload' "$fixture/systemctl.log" || fail 'systemd units were not reloaded'
|
||||
! grep -qi nginx "$fixture/systemctl.log" || fail 'updater unexpectedly managed Nginx'
|
||||
[ "$(mode_of "$fixture/app")" = 750 ] || fail 'application root is not traversable by the service group'
|
||||
[ "$(mode_of "$fixture/app/releases/$version")" = 750 ] || fail 'release root mode is not 0750'
|
||||
[ "$(mode_of "$fixture/app/current/app.jar")" = 640 ] || fail 'release file mode is not 0640'
|
||||
[ "$(mode_of "$fixture/app/current/ops/update.sh")" = 750 ] || fail 'release updater mode is not 0750'
|
||||
}
|
||||
|
||||
assert_identical_systemd_operations_case() {
|
||||
local fixture="$WORK/identical-systemd"
|
||||
local version='1.0.0-preview.2'
|
||||
mkdir -p "$fixture"
|
||||
write_mock_commands "$fixture/mock-bin"
|
||||
build_release "$fixture" "$version" old
|
||||
prepare_installation "$fixture" "$version"
|
||||
|
||||
download_and_prepare_install "$fixture" "$version"
|
||||
: > "$fixture/systemctl.log"
|
||||
run_update "$fixture" success
|
||||
[ "$(readlink "$fixture/app/current")" = "$fixture/app/releases/$version" ] \
|
||||
|| fail 'identical systemd case did not activate the new application'
|
||||
! grep -qx 'daemon-reload' "$fixture/systemctl.log" \
|
||||
|| fail 'identical systemd units triggered an unnecessary daemon reload'
|
||||
}
|
||||
|
||||
assert_update_path_failure_keeps_application_case() {
|
||||
local fixture="$WORK/path-watcher-failure"
|
||||
local version='1.0.0-preview.2'
|
||||
mkdir -p "$fixture"
|
||||
write_mock_commands "$fixture/mock-bin"
|
||||
build_release "$fixture" "$version"
|
||||
prepare_installation "$fixture" "$version"
|
||||
|
||||
download_and_prepare_install "$fixture" "$version"
|
||||
MOCK_UPDATE_PATH_START=fail run_update "$fixture" success
|
||||
[ "$(readlink "$fixture/app/current")" = "$fixture/app/releases/$version" ] \
|
||||
|| fail 'path watcher failure rolled back a healthy application'
|
||||
[ "$(jq -r '.state' "$fixture/state/status.json")" = SUCCEEDED ] \
|
||||
|| fail 'path watcher failure did not preserve successful application state'
|
||||
grep -Fq 'automatic update watcher could not be started' "$fixture/state/status.json" \
|
||||
|| fail 'path watcher failure did not preserve its diagnostic'
|
||||
}
|
||||
|
||||
assert_rollback_case() {
|
||||
@@ -424,6 +518,8 @@ assert_install_without_verified_cache_rejected() {
|
||||
}
|
||||
|
||||
assert_success_case
|
||||
assert_identical_systemd_operations_case
|
||||
assert_update_path_failure_keeps_application_case
|
||||
assert_rollback_case
|
||||
assert_download_failure_case
|
||||
assert_database_failure_case
|
||||
|
||||
Reference in New Issue
Block a user