@kne/fastify-app-manager 0.1.29 → 0.1.31
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/index.js +18 -0
- package/libs/controllers/link.js +103 -0
- package/libs/controllers/migration.js +6 -6
- package/libs/models/app.js +15 -9
- package/libs/services/app.js +71 -13
- package/libs/services/bootstrap.js +54 -6
- package/libs/services/dbops.js +19 -0
- package/libs/services/link.js +405 -0
- package/libs/services/migration.js +22 -0
- package/libs/services/openApi.js +14 -1
- package/libs/utils/appKind.js +33 -0
- package/libs/utils/permissionSnapshot.js +140 -0
- package/libs/utils/proxyAudit.js +59 -0
- package/oidc.js +121 -12
- package/package.json +1 -1
package/index.js
CHANGED
|
@@ -55,6 +55,24 @@ module.exports = fp(
|
|
|
55
55
|
getOpenApiToken: null,
|
|
56
56
|
/** async ({ app, userId, tenantId }) => accessToken,以登录用户身份签发子应用令牌;不传则 /app/open-api/token 不可用 */
|
|
57
57
|
issueUserAccessToken: null,
|
|
58
|
+
/**
|
|
59
|
+
* 外部关联(linked)应用:
|
|
60
|
+
* - origin:本平台对外 ORIGIN,须与 installKey.platformOrigin 一致
|
|
61
|
+
* - signPlatformAssertion / ensureLinkedRegistration / getOpsServiceToken:通常来自 createAppOidc 返回值
|
|
62
|
+
* - linkSyncIntervalMs:定时同步权限/健康,0 表示仅启动时同步一次
|
|
63
|
+
*/
|
|
64
|
+
origin: null,
|
|
65
|
+
signPlatformAssertion: null,
|
|
66
|
+
ensureLinkedRegistration: null,
|
|
67
|
+
getOpsServiceToken: null,
|
|
68
|
+
/** async ({ app, tree, sourceKey }) => void,权限快照合并后通知宿主(如 tenant.setPermissionSource) */
|
|
69
|
+
onPermissionsSynced: null,
|
|
70
|
+
/** async ({ app, sourceKey }) => void,删除 linked 应用时移除权限源 */
|
|
71
|
+
onPermissionsRemoved: null,
|
|
72
|
+
/** async () => string[],导入时校验 appName 不与本平台权限顶层码冲突 */
|
|
73
|
+
getPermissionRootCodes: null,
|
|
74
|
+
linkSyncIntervalMs: 5 * 60 * 1000,
|
|
75
|
+
linkProxyTimeoutMs: 15000,
|
|
58
76
|
/** async ({ fileId, name, version, request }) => Buffer,版本上传传 fileId 时读取宿主文件 */
|
|
59
77
|
resolveVersionFile: null,
|
|
60
78
|
secretEnvKeyPattern: /(SECRET|PASSWORD|TOKEN|KEY|PRIVATE)/i,
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
const fp = require('fastify-plugin');
|
|
2
|
+
const { str, obj, success, any } = require('../schema/response');
|
|
3
|
+
|
|
4
|
+
const TAG_APP = '应用中心管理后台-应用';
|
|
5
|
+
|
|
6
|
+
module.exports = fp(async (fastify, options) => {
|
|
7
|
+
const { services } = fastify[options.name];
|
|
8
|
+
const auth = () => options.createAuthenticate();
|
|
9
|
+
|
|
10
|
+
fastify.post(
|
|
11
|
+
`${options.prefix}/app/link/import`,
|
|
12
|
+
{
|
|
13
|
+
onRequest: auth(),
|
|
14
|
+
schema: {
|
|
15
|
+
tags: [TAG_APP],
|
|
16
|
+
summary: '凭 installKey 添加外部关联应用',
|
|
17
|
+
description: '解析远程登记生成的 installKey,用本平台 IdP 断言兑换并激活;创建 kind=linked 应用,不分配本机端口/PM2。需宿主配置 origin 与 createAppOidc 的 ensureLinkedRegistration / signPlatformAssertion / getServiceToken。',
|
|
18
|
+
body: {
|
|
19
|
+
type: 'object',
|
|
20
|
+
required: ['installKey'],
|
|
21
|
+
properties: {
|
|
22
|
+
installKey: { type: 'string', description: '远程一次性安装密钥(base64url JSON)' },
|
|
23
|
+
name: { type: 'string', description: '可选覆盖应用 slug;默认取 key 内 appName' },
|
|
24
|
+
label: { type: 'string', description: '可选覆盖显示名' }
|
|
25
|
+
}
|
|
26
|
+
},
|
|
27
|
+
response: success('导入后的应用', obj({ name: str('应用 name'), kind: str('managed|linked'), status: str('状态') }))
|
|
28
|
+
}
|
|
29
|
+
},
|
|
30
|
+
async request => services.link.importByInstallKey(request.body || {})
|
|
31
|
+
);
|
|
32
|
+
|
|
33
|
+
fastify.post(
|
|
34
|
+
`${options.prefix}/app/link/sync`,
|
|
35
|
+
{
|
|
36
|
+
onRequest: auth(),
|
|
37
|
+
schema: {
|
|
38
|
+
tags: [TAG_APP],
|
|
39
|
+
summary: '同步全部外部关联应用',
|
|
40
|
+
description: '拉取远程权限树快照、幂等 ensure OIDC,并探测 /ready 写回 status',
|
|
41
|
+
response: success('同步结果', any())
|
|
42
|
+
}
|
|
43
|
+
},
|
|
44
|
+
async () => services.link.syncAllLinked()
|
|
45
|
+
);
|
|
46
|
+
|
|
47
|
+
fastify.post(
|
|
48
|
+
`${options.prefix}/app/:name/link/sync`,
|
|
49
|
+
{
|
|
50
|
+
onRequest: auth(),
|
|
51
|
+
schema: {
|
|
52
|
+
tags: [TAG_APP],
|
|
53
|
+
summary: '同步单个外部关联应用',
|
|
54
|
+
params: {
|
|
55
|
+
type: 'object',
|
|
56
|
+
required: ['name'],
|
|
57
|
+
properties: { name: { type: 'string', description: '应用 name' } }
|
|
58
|
+
},
|
|
59
|
+
response: success('同步结果', any())
|
|
60
|
+
}
|
|
61
|
+
},
|
|
62
|
+
async request => {
|
|
63
|
+
const app = await services.app.detail({ name: request.params.name });
|
|
64
|
+
const row = await fastify[options.name].models.app.findOne({ where: { name: app.name } });
|
|
65
|
+
return services.link.syncOne(row);
|
|
66
|
+
}
|
|
67
|
+
);
|
|
68
|
+
|
|
69
|
+
fastify.get(
|
|
70
|
+
`${options.prefix}/app/:name/link/audit`,
|
|
71
|
+
{
|
|
72
|
+
onRequest: auth(),
|
|
73
|
+
schema: {
|
|
74
|
+
tags: [TAG_APP],
|
|
75
|
+
summary: '外部关联应用代理审计',
|
|
76
|
+
description: '主平台侧记录:谁通过平台代理打了远程 /app-ops',
|
|
77
|
+
params: {
|
|
78
|
+
type: 'object',
|
|
79
|
+
required: ['name'],
|
|
80
|
+
properties: { name: { type: 'string', description: '应用 name' } }
|
|
81
|
+
},
|
|
82
|
+
querystring: {
|
|
83
|
+
type: 'object',
|
|
84
|
+
properties: {
|
|
85
|
+
action: { type: 'string', description: '按动作筛选' },
|
|
86
|
+
limit: { type: 'number', description: '条数,默认 50' },
|
|
87
|
+
offset: { type: 'number', description: '偏移' }
|
|
88
|
+
}
|
|
89
|
+
},
|
|
90
|
+
response: success('审计列表', any())
|
|
91
|
+
}
|
|
92
|
+
},
|
|
93
|
+
async request => {
|
|
94
|
+
await services.app.detail({ name: request.params.name });
|
|
95
|
+
return services.link.listProxyAudit({
|
|
96
|
+
appName: request.params.name,
|
|
97
|
+
action: request.query?.action,
|
|
98
|
+
limit: request.query?.limit,
|
|
99
|
+
offset: request.query?.offset
|
|
100
|
+
});
|
|
101
|
+
}
|
|
102
|
+
);
|
|
103
|
+
});
|
|
@@ -10,7 +10,7 @@ module.exports = fp(async (fastify, options) => {
|
|
|
10
10
|
|
|
11
11
|
const versionProps = {
|
|
12
12
|
name: { type: 'string', description: '应用 name' },
|
|
13
|
-
versionId: { type: 'string', description: '版本 ID' }
|
|
13
|
+
versionId: { type: 'string', description: '版本 ID;linked 外部应用可不传,代理远程 server/sql' }
|
|
14
14
|
};
|
|
15
15
|
|
|
16
16
|
fastify.get(
|
|
@@ -20,10 +20,10 @@ module.exports = fp(async (fastify, options) => {
|
|
|
20
20
|
schema: {
|
|
21
21
|
tags: [TAG],
|
|
22
22
|
summary: '版本迁移脚本列表(含执行状态)',
|
|
23
|
-
description: '脚本内容以数据库为准;执行状态读自应用数据库的迁移记录表,读取失败时 executed 为 null 并返回 dbError',
|
|
23
|
+
description: '脚本内容以数据库为准;执行状态读自应用数据库的迁移记录表,读取失败时 executed 为 null 并返回 dbError;linked 应用不传 versionId,代理远程 /app-ops/migrations',
|
|
24
24
|
query: {
|
|
25
25
|
type: 'object',
|
|
26
|
-
required: ['name'
|
|
26
|
+
required: ['name'],
|
|
27
27
|
properties: versionProps
|
|
28
28
|
},
|
|
29
29
|
response: success(
|
|
@@ -61,7 +61,7 @@ module.exports = fp(async (fastify, options) => {
|
|
|
61
61
|
summary: '读取迁移脚本内容',
|
|
62
62
|
query: {
|
|
63
63
|
type: 'object',
|
|
64
|
-
required: ['name', '
|
|
64
|
+
required: ['name', 'file'],
|
|
65
65
|
properties: Object.assign({}, versionProps, { file: { type: 'string', description: SQL_FILE } })
|
|
66
66
|
},
|
|
67
67
|
response: success('脚本内容', obj('脚本内容', { name: str('文件名'), content: str('SQL 内容') }))
|
|
@@ -120,10 +120,10 @@ module.exports = fp(async (fastify, options) => {
|
|
|
120
120
|
description: 'execute 在应用数据库执行脚本并记录,mark 只记录为已执行,unmark 删除执行记录(不回滚已执行的 SQL)',
|
|
121
121
|
body: {
|
|
122
122
|
type: 'object',
|
|
123
|
-
required: ['name', '
|
|
123
|
+
required: ['name', 'file', 'action'],
|
|
124
124
|
properties: Object.assign({}, versionProps, {
|
|
125
125
|
file: { type: 'string', description: SQL_FILE },
|
|
126
|
-
action: { type: 'string', enum: ['execute', 'mark', 'unmark'], description: '操作:execute 执行,mark 标记已执行,unmark
|
|
126
|
+
action: { type: 'string', enum: ['execute', 'mark', 'unmark'], description: '操作:execute 执行,mark 标记已执行,unmark 撤销执行记录;linked 应用不传 versionId' }
|
|
127
127
|
})
|
|
128
128
|
},
|
|
129
129
|
response: success('操作结果', migrationResult)
|
package/libs/models/app.js
CHANGED
|
@@ -13,11 +13,17 @@ module.exports = ({ DataTypes }) => {
|
|
|
13
13
|
allowNull: false,
|
|
14
14
|
comment: '用户可见应用名'
|
|
15
15
|
},
|
|
16
|
+
kind: {
|
|
17
|
+
type: DataTypes.STRING,
|
|
18
|
+
allowNull: false,
|
|
19
|
+
defaultValue: 'managed',
|
|
20
|
+
comment: 'managed=本机托管 | linked=外部关联'
|
|
21
|
+
},
|
|
16
22
|
domain: {
|
|
17
23
|
type: DataTypes.STRING,
|
|
18
24
|
allowNull: true,
|
|
19
25
|
unique: true,
|
|
20
|
-
comment: '绑定域名 Host'
|
|
26
|
+
comment: '绑定域名 Host;linked 必须为空'
|
|
21
27
|
},
|
|
22
28
|
icon: {
|
|
23
29
|
type: DataTypes.STRING,
|
|
@@ -45,12 +51,12 @@ module.exports = ({ DataTypes }) => {
|
|
|
45
51
|
type: DataTypes.JSON,
|
|
46
52
|
allowNull: false,
|
|
47
53
|
defaultValue: {},
|
|
48
|
-
comment: '
|
|
54
|
+
comment: '扩展字段(linked 含 baseUrl / linkStatus / permissionsSnapshot)'
|
|
49
55
|
},
|
|
50
56
|
port: {
|
|
51
57
|
type: DataTypes.INTEGER,
|
|
52
|
-
allowNull:
|
|
53
|
-
comment: '
|
|
58
|
+
allowNull: true,
|
|
59
|
+
comment: '分配端口;linked 可空'
|
|
54
60
|
},
|
|
55
61
|
status: {
|
|
56
62
|
type: DataTypes.STRING,
|
|
@@ -65,14 +71,14 @@ module.exports = ({ DataTypes }) => {
|
|
|
65
71
|
},
|
|
66
72
|
rootPath: {
|
|
67
73
|
type: DataTypes.STRING,
|
|
68
|
-
allowNull:
|
|
69
|
-
comment: '
|
|
74
|
+
allowNull: true,
|
|
75
|
+
comment: '应用根目录;linked 可空'
|
|
70
76
|
},
|
|
71
77
|
pm2Name: {
|
|
72
78
|
type: DataTypes.STRING,
|
|
73
|
-
allowNull:
|
|
79
|
+
allowNull: true,
|
|
74
80
|
unique: true,
|
|
75
|
-
comment: 'PM2
|
|
81
|
+
comment: 'PM2 进程名;linked 可空'
|
|
76
82
|
},
|
|
77
83
|
message: {
|
|
78
84
|
type: DataTypes.TEXT,
|
|
@@ -82,7 +88,7 @@ module.exports = ({ DataTypes }) => {
|
|
|
82
88
|
},
|
|
83
89
|
options: {
|
|
84
90
|
comment: '托管应用',
|
|
85
|
-
indexes: [{ fields: ['status'] }, { fields: ['domain'] }]
|
|
91
|
+
indexes: [{ fields: ['status'] }, { fields: ['domain'] }, { fields: ['kind'] }]
|
|
86
92
|
}
|
|
87
93
|
};
|
|
88
94
|
};
|
package/libs/services/app.js
CHANGED
|
@@ -30,6 +30,7 @@ const { readSqlDir, writeSqlDir } = require('../utils/versionSql');
|
|
|
30
30
|
const { createDeployProgress } = require('../utils/deployProgress');
|
|
31
31
|
const pwaDocument = require('@kne/pwa-document');
|
|
32
32
|
const pm2Util = require('../utils/pm2');
|
|
33
|
+
const { KIND_MANAGED, KIND_LINKED, isLinked, linkedBaseUrl, assertNotLinked } = require('../utils/appKind');
|
|
33
34
|
|
|
34
35
|
const NAME_RE = /^[a-z0-9]([a-z0-9-]{0,62}[a-z0-9])?$/;
|
|
35
36
|
|
|
@@ -81,8 +82,14 @@ module.exports = fp(async (fastify, options) => {
|
|
|
81
82
|
}, []);
|
|
82
83
|
};
|
|
83
84
|
const resolveEntries = appLike => {
|
|
84
|
-
const
|
|
85
|
-
|
|
85
|
+
const linked = isLinked(appLike);
|
|
86
|
+
const remote = linked ? linkedBaseUrl(appLike) : null;
|
|
87
|
+
const base = remote || mountPrefix(appLike.name);
|
|
88
|
+
return normalizeEntries(appLike.options?.entries).map(entry => {
|
|
89
|
+
const pathPart = entry.path.startsWith('/') ? entry.path : `/${entry.path}`;
|
|
90
|
+
const url = remote ? `${remote}${pathPart}` : `${base}${pathPart}`;
|
|
91
|
+
return Object.assign({}, entry, { path: remote ? url : entry.path, url });
|
|
92
|
+
});
|
|
86
93
|
};
|
|
87
94
|
|
|
88
95
|
const toPublicApp = app => {
|
|
@@ -95,7 +102,11 @@ module.exports = fp(async (fastify, options) => {
|
|
|
95
102
|
json.env = maskEnvForResponse(json.env || {}, envOpts);
|
|
96
103
|
json.passthroughEnvKeys = options.passthroughEnvKeys || [];
|
|
97
104
|
json.secretEnvKeys = collectSecretKeys(json.env || {}, envOpts);
|
|
98
|
-
|
|
105
|
+
const linked = isLinked(json);
|
|
106
|
+
const remote = linked ? linkedBaseUrl(json) : null;
|
|
107
|
+
json.pathUrl = remote ? `${remote}/` : `${mountPrefix(json.name)}/`;
|
|
108
|
+
json.openUrl = json.pathUrl;
|
|
109
|
+
json.kind = linked ? KIND_LINKED : KIND_MANAGED;
|
|
99
110
|
json.category = json.options?.category || null;
|
|
100
111
|
json.isPublic = isAppPublic(json);
|
|
101
112
|
json.entries = resolveEntries(json);
|
|
@@ -159,6 +170,7 @@ module.exports = fp(async (fastify, options) => {
|
|
|
159
170
|
const app = await models.app.create({
|
|
160
171
|
name,
|
|
161
172
|
label,
|
|
173
|
+
kind: KIND_MANAGED,
|
|
162
174
|
domain: domain || null,
|
|
163
175
|
icon: icon || null,
|
|
164
176
|
description: description || null,
|
|
@@ -218,6 +230,9 @@ module.exports = fp(async (fastify, options) => {
|
|
|
218
230
|
|
|
219
231
|
const saveEnv = async ({ name, env, secretEnvKeys: nextSecretKeys } = {}) => {
|
|
220
232
|
const app = await getByName(name);
|
|
233
|
+
if (isLinked(app)) {
|
|
234
|
+
httpError(400, '外部应用环境变量只读,请在远程部署侧修改后重启');
|
|
235
|
+
}
|
|
221
236
|
// 密钥类型不可撤销,只随变量删除而移除
|
|
222
237
|
const secretEnvKeys = normalizeSecretKeys([...resolveSecretEnvKeys(app), ...(nextSecretKeys || [])]);
|
|
223
238
|
// PORT 由端口池分配,启动时总会覆盖,不接受外部写入
|
|
@@ -259,15 +274,29 @@ module.exports = fp(async (fastify, options) => {
|
|
|
259
274
|
.filter(app => !publicOnly || isAppPublic(app))
|
|
260
275
|
.map(app => {
|
|
261
276
|
const active = deployProgress.active(app.name);
|
|
277
|
+
const linked = isLinked(app);
|
|
278
|
+
const base = linked ? linkedBaseUrl(app) : null;
|
|
279
|
+
const pathUrl = linked && base ? `${base}/` : `${mountPrefix(app.name)}/`;
|
|
280
|
+
const entries = resolveEntries(app)
|
|
281
|
+
.filter(entry => entry.showInCenter)
|
|
282
|
+
.map(entry =>
|
|
283
|
+
linked && base
|
|
284
|
+
? Object.assign({}, entry, {
|
|
285
|
+
path: entry.path.startsWith('http') ? entry.path : `${base}${entry.path.startsWith('/') ? '' : '/'}${entry.path}`
|
|
286
|
+
})
|
|
287
|
+
: entry
|
|
288
|
+
);
|
|
262
289
|
return {
|
|
263
290
|
name: app.name,
|
|
264
291
|
label: app.label,
|
|
292
|
+
kind: linked ? KIND_LINKED : KIND_MANAGED,
|
|
265
293
|
icon: app.icon,
|
|
266
294
|
description: app.description,
|
|
267
295
|
category: app.options?.category || null,
|
|
268
296
|
isPublic: isAppPublic(app),
|
|
269
|
-
pathUrl
|
|
270
|
-
|
|
297
|
+
pathUrl,
|
|
298
|
+
openUrl: pathUrl,
|
|
299
|
+
entries,
|
|
271
300
|
deployment: active ? { source: active.source } : null
|
|
272
301
|
};
|
|
273
302
|
});
|
|
@@ -369,6 +398,7 @@ module.exports = fp(async (fastify, options) => {
|
|
|
369
398
|
if (!app) {
|
|
370
399
|
httpError(404, `app ${name} not found; create it first`);
|
|
371
400
|
}
|
|
401
|
+
assertNotLinked(app, '版本上传');
|
|
372
402
|
// The (app_name, version) unique index also covers soft-deleted rows, so they must be purged before reuse.
|
|
373
403
|
const dup = await models.appVersion.findOne({ where: { appName: name, version }, paranoid: false });
|
|
374
404
|
if (dup && !dup.isSoftDeleted()) {
|
|
@@ -789,7 +819,7 @@ module.exports = fp(async (fastify, options) => {
|
|
|
789
819
|
const excluded = new Set(excludeIds.map(String));
|
|
790
820
|
const results = [];
|
|
791
821
|
for (const app of apps) {
|
|
792
|
-
if (excluded.has(String(app.id))) {
|
|
822
|
+
if (excluded.has(String(app.id)) || isLinked(app)) {
|
|
793
823
|
continue;
|
|
794
824
|
}
|
|
795
825
|
const shouldRecover = recoverIfMissing && (app.status === 'running' || app.status === 'deploying');
|
|
@@ -905,6 +935,9 @@ module.exports = fp(async (fastify, options) => {
|
|
|
905
935
|
*/
|
|
906
936
|
const getEnvDeclaration = async ({ name, versionId } = {}) => {
|
|
907
937
|
const app = await getByName(name);
|
|
938
|
+
if (isLinked(app)) {
|
|
939
|
+
return fastify[options.name].services.link.proxy.env(app);
|
|
940
|
+
}
|
|
908
941
|
const ver = await resolveDeclarationVersion(app, versionId);
|
|
909
942
|
const schema = ver ? await getVersionEnvSchema(ver) : null;
|
|
910
943
|
const injected = listInjectedEnvKeys(app);
|
|
@@ -1012,6 +1045,9 @@ module.exports = fp(async (fastify, options) => {
|
|
|
1012
1045
|
const apps = await models.app.findAll({ where: { currentVersionId: { [Op.ne]: null } } });
|
|
1013
1046
|
const missing = [];
|
|
1014
1047
|
for (const app of apps) {
|
|
1048
|
+
if (isLinked(app)) {
|
|
1049
|
+
continue;
|
|
1050
|
+
}
|
|
1015
1051
|
const ver = await models.appVersion.findByPk(app.currentVersionId);
|
|
1016
1052
|
if (ver && !(await fs.pathExists(path.join(ver.artifactPath, 'server')))) {
|
|
1017
1053
|
missing.push({ app, ver });
|
|
@@ -1119,6 +1155,7 @@ module.exports = fp(async (fastify, options) => {
|
|
|
1119
1155
|
|
|
1120
1156
|
const deploy = async ({ name, versionId, version, runMigration = true, migrations, progressId }) => {
|
|
1121
1157
|
const app = await getByName(name);
|
|
1158
|
+
assertNotLinked(app, '部署');
|
|
1122
1159
|
let ver = null;
|
|
1123
1160
|
if (versionId) {
|
|
1124
1161
|
ver = await models.appVersion.findByPk(versionId);
|
|
@@ -1250,6 +1287,7 @@ module.exports = fp(async (fastify, options) => {
|
|
|
1250
1287
|
|
|
1251
1288
|
const stop = async ({ name }) => {
|
|
1252
1289
|
const app = await getByName(name);
|
|
1290
|
+
assertNotLinked(app, '停止');
|
|
1253
1291
|
try {
|
|
1254
1292
|
await pm2Util.stopApp(app.pm2Name);
|
|
1255
1293
|
} catch (e) {
|
|
@@ -1276,6 +1314,7 @@ module.exports = fp(async (fastify, options) => {
|
|
|
1276
1314
|
|
|
1277
1315
|
const start = async ({ name }) => {
|
|
1278
1316
|
const app = await getByName(name);
|
|
1317
|
+
assertNotLinked(app, '启动');
|
|
1279
1318
|
const env = await prepareStartEnv(app);
|
|
1280
1319
|
await app.update({ status: 'deploying', message: null });
|
|
1281
1320
|
try {
|
|
@@ -1291,6 +1330,7 @@ module.exports = fp(async (fastify, options) => {
|
|
|
1291
1330
|
|
|
1292
1331
|
const restart = async ({ name }) => {
|
|
1293
1332
|
const app = await getByName(name);
|
|
1333
|
+
assertNotLinked(app, '重启');
|
|
1294
1334
|
const env = await prepareStartEnv(app);
|
|
1295
1335
|
await app.update({ status: 'deploying', message: null });
|
|
1296
1336
|
try {
|
|
@@ -1312,21 +1352,24 @@ module.exports = fp(async (fastify, options) => {
|
|
|
1312
1352
|
|
|
1313
1353
|
const remove = async ({ name, exportBeforeRemove = true, cleanupData = true, allowRemoveIfCleanupIncomplete = false, force = false, removeSqliteFile = false } = {}) => {
|
|
1314
1354
|
const app = await getByName(name);
|
|
1315
|
-
|
|
1316
|
-
|
|
1317
|
-
|
|
1318
|
-
|
|
1355
|
+
const linked = isLinked(app);
|
|
1356
|
+
if (!linked && app.pm2Name) {
|
|
1357
|
+
try {
|
|
1358
|
+
await pm2Util.deleteProcess(app.pm2Name);
|
|
1359
|
+
} catch (e) {
|
|
1360
|
+
// ignore
|
|
1361
|
+
}
|
|
1319
1362
|
}
|
|
1320
1363
|
|
|
1321
1364
|
const dbops = fastify[options.name].services.dbops;
|
|
1322
1365
|
let exportResult = null;
|
|
1323
1366
|
let cleanupResult = null;
|
|
1324
1367
|
|
|
1325
|
-
if (exportBeforeRemove && !force) {
|
|
1368
|
+
if (!linked && exportBeforeRemove && !force) {
|
|
1326
1369
|
exportResult = await dbops.exportData({ name });
|
|
1327
1370
|
}
|
|
1328
1371
|
|
|
1329
|
-
if (cleanupData) {
|
|
1372
|
+
if (!linked && cleanupData) {
|
|
1330
1373
|
cleanupResult = await dbops.cleanup({ name, removeSqliteFile });
|
|
1331
1374
|
if (cleanupResult.manualRequired && !allowRemoveIfCleanupIncomplete) {
|
|
1332
1375
|
return {
|
|
@@ -1341,7 +1384,9 @@ module.exports = fp(async (fastify, options) => {
|
|
|
1341
1384
|
const snapshot = app.toJSON();
|
|
1342
1385
|
await models.appVersion.destroy({ where: { appName: name } });
|
|
1343
1386
|
await models.appOpenApiRecord.destroy({ where: { appName: name }, force: true });
|
|
1344
|
-
|
|
1387
|
+
if (!linked && app.rootPath) {
|
|
1388
|
+
await fs.remove(app.rootPath).catch(() => {});
|
|
1389
|
+
}
|
|
1345
1390
|
deployProgress.clear(app.name);
|
|
1346
1391
|
await app.destroy();
|
|
1347
1392
|
if (typeof options.onAppRemoved === 'function') {
|
|
@@ -1351,6 +1396,13 @@ module.exports = fp(async (fastify, options) => {
|
|
|
1351
1396
|
fastify.log.warn({ err: e, appName: name }, 'onAppRemoved hook failed');
|
|
1352
1397
|
}
|
|
1353
1398
|
}
|
|
1399
|
+
if (linked && typeof options.onPermissionsRemoved === 'function') {
|
|
1400
|
+
try {
|
|
1401
|
+
await options.onPermissionsRemoved({ app: snapshot, sourceKey: `app:${name}` });
|
|
1402
|
+
} catch (e) {
|
|
1403
|
+
fastify.log.warn({ err: e, appName: name }, 'onPermissionsRemoved hook failed');
|
|
1404
|
+
}
|
|
1405
|
+
}
|
|
1354
1406
|
return {
|
|
1355
1407
|
removed: true,
|
|
1356
1408
|
export: exportResult,
|
|
@@ -1376,12 +1428,18 @@ module.exports = fp(async (fastify, options) => {
|
|
|
1376
1428
|
|
|
1377
1429
|
const logs = async ({ name, stream = 'out', file, perPage = 100, currentPage = 1, beforeLine } = {}) => {
|
|
1378
1430
|
const app = await getByName(name);
|
|
1431
|
+
if (isLinked(app)) {
|
|
1432
|
+
return fastify[options.name].services.link.proxy.logs(app, { stream, file, perPage, currentPage, beforeLine });
|
|
1433
|
+
}
|
|
1379
1434
|
const filePath = file ? await resolveExistingLogFile(app, file) : currentLogFile(app, stream);
|
|
1380
1435
|
return readLogTail(filePath, { perPage, currentPage, beforeLine, timezone: options.logTimezone });
|
|
1381
1436
|
};
|
|
1382
1437
|
|
|
1383
1438
|
const logFiles = async ({ name }) => {
|
|
1384
1439
|
const app = await getByName(name);
|
|
1440
|
+
if (isLinked(app)) {
|
|
1441
|
+
return fastify[options.name].services.link.proxy.logFiles(app);
|
|
1442
|
+
}
|
|
1385
1443
|
const pageData = (await listLogFiles(logsDirOf(app))).map(item => Object.assign({}, item, { mtime: toIsoInTz(item.mtime, options.logTimezone) }));
|
|
1386
1444
|
return { pageData, totalCount: pageData.length };
|
|
1387
1445
|
};
|
|
@@ -42,7 +42,8 @@ module.exports = fp(async (fastify, options) => {
|
|
|
42
42
|
const { models } = fastify[options.name];
|
|
43
43
|
const targets = [
|
|
44
44
|
[models.appVersion, ['fileId', 'migrationFiles', 'envSchema']],
|
|
45
|
-
[models.appOpenApiRecord, ['searchText']]
|
|
45
|
+
[models.appOpenApiRecord, ['searchText']],
|
|
46
|
+
[models.app, ['kind']]
|
|
46
47
|
];
|
|
47
48
|
for (const [model, names] of targets) {
|
|
48
49
|
const queryInterface = model.sequelize.getQueryInterface();
|
|
@@ -51,10 +52,30 @@ module.exports = fp(async (fastify, options) => {
|
|
|
51
52
|
for (const name of names) {
|
|
52
53
|
const attr = model.rawAttributes[name];
|
|
53
54
|
if (!columns[attr.field]) {
|
|
54
|
-
await queryInterface.addColumn(table, attr.field, {
|
|
55
|
+
await queryInterface.addColumn(table, attr.field, {
|
|
56
|
+
type: attr.type,
|
|
57
|
+
allowNull: attr.allowNull !== false,
|
|
58
|
+
defaultValue: attr.defaultValue,
|
|
59
|
+
comment: attr.comment
|
|
60
|
+
});
|
|
55
61
|
}
|
|
56
62
|
}
|
|
57
63
|
}
|
|
64
|
+
// linked 应用不占本机端口/目录/PM2:将既有非空列改为可空(幂等)
|
|
65
|
+
const queryInterface = models.app.sequelize.getQueryInterface();
|
|
66
|
+
const table = models.app.getTableName();
|
|
67
|
+
const columns = await queryInterface.describeTable(table);
|
|
68
|
+
for (const name of ['port', 'rootPath', 'pm2Name']) {
|
|
69
|
+
const attr = models.app.rawAttributes[name];
|
|
70
|
+
const col = columns[attr.field];
|
|
71
|
+
if (col && col.allowNull === false) {
|
|
72
|
+
await queryInterface.changeColumn(table, attr.field, {
|
|
73
|
+
type: attr.type,
|
|
74
|
+
allowNull: true,
|
|
75
|
+
comment: attr.comment
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
}
|
|
58
79
|
};
|
|
59
80
|
|
|
60
81
|
const onReady = async () => {
|
|
@@ -123,7 +144,24 @@ module.exports = fp(async (fastify, options) => {
|
|
|
123
144
|
if (options.loadSampleIntervalMs > 0) {
|
|
124
145
|
sampleLoad().catch(err => fastify.log.debug({ err }, 'load sampling failed'));
|
|
125
146
|
}
|
|
147
|
+
const link = fastify[options.name].services.link;
|
|
148
|
+
if (link?.syncAllLinked) {
|
|
149
|
+
link.syncAllLinked().catch(err => fastify.log.warn({ err }, 'linked apps sync failed'));
|
|
150
|
+
}
|
|
126
151
|
});
|
|
152
|
+
|
|
153
|
+
const linkSyncMs = options.linkSyncIntervalMs || 0;
|
|
154
|
+
if (linkSyncMs > 0) {
|
|
155
|
+
const linkTimer = setInterval(() => {
|
|
156
|
+
const link = fastify[options.name].services.link;
|
|
157
|
+
if (link?.syncAllLinked) {
|
|
158
|
+
link.syncAllLinked().catch(err => fastify.log.warn({ err }, 'linked apps sync failed'));
|
|
159
|
+
}
|
|
160
|
+
}, linkSyncMs);
|
|
161
|
+
linkTimer.unref?.();
|
|
162
|
+
// 挂到实例上,onClose 时可清理;无专门字段时依赖进程退出
|
|
163
|
+
fastify[options.name]._linkSyncTimer = linkTimer;
|
|
164
|
+
}
|
|
127
165
|
};
|
|
128
166
|
|
|
129
167
|
const fsEnsureAppsRoot = async () => {
|
|
@@ -188,9 +226,13 @@ module.exports = fp(async (fastify, options) => {
|
|
|
188
226
|
*/
|
|
189
227
|
const migratePm2Names = async () => {
|
|
190
228
|
const { models } = fastify[options.name];
|
|
229
|
+
const { isLinked } = require('../utils/appKind');
|
|
191
230
|
const apps = await models.app.findAll();
|
|
192
231
|
const migrated = [];
|
|
193
232
|
for (const app of apps) {
|
|
233
|
+
if (isLinked(app) || !app.pm2Name || !app.rootPath) {
|
|
234
|
+
continue;
|
|
235
|
+
}
|
|
194
236
|
const pm2Name = createPm2Name(options.hostName, app.name);
|
|
195
237
|
if (app.pm2Name === pm2Name) {
|
|
196
238
|
continue;
|
|
@@ -236,9 +278,13 @@ module.exports = fp(async (fastify, options) => {
|
|
|
236
278
|
|
|
237
279
|
const runRotation = async ({ now = new Date() } = {}) => {
|
|
238
280
|
const { models } = fastify[options.name];
|
|
239
|
-
const
|
|
281
|
+
const { isLinked } = require('../utils/appKind');
|
|
282
|
+
const apps = await models.app.findAll({ attributes: ['name', 'rootPath', 'kind', 'options'] });
|
|
240
283
|
const targets = [];
|
|
241
284
|
for (const app of apps) {
|
|
285
|
+
if (isLinked(app) || !app.rootPath) {
|
|
286
|
+
continue;
|
|
287
|
+
}
|
|
242
288
|
const logsDir = path.join(app.rootPath, 'logs');
|
|
243
289
|
if (await fs.pathExists(logsDir)) {
|
|
244
290
|
targets.push({ name: app.name, logsDir });
|
|
@@ -314,16 +360,18 @@ module.exports = fp(async (fastify, options) => {
|
|
|
314
360
|
}
|
|
315
361
|
const { models } = fastify[options.name];
|
|
316
362
|
const summary = summarizeProcesses(await pm2Util.list(), { now: now.getTime() });
|
|
317
|
-
const
|
|
363
|
+
const { isLinked } = require('../utils/appKind');
|
|
364
|
+
const apps = await models.app.findAll({ attributes: ['name', 'pm2Name', 'kind', 'options'] });
|
|
365
|
+
const managed = apps.filter(app => !isLinked(app) && app.pm2Name);
|
|
318
366
|
const base = { ts: now.getTime(), sampledAt: toIsoInTz(now, options.logTimezone) };
|
|
319
|
-
const samples =
|
|
367
|
+
const samples = managed.map(app => {
|
|
320
368
|
const sample = Object.assign({ name: app.name }, base, summary.get(app.pm2Name) || OFFLINE_LOAD, {
|
|
321
369
|
requests: requestMetrics.snapshot(app.name, { now: base.ts })
|
|
322
370
|
});
|
|
323
371
|
loadStore.push(app.name, sample);
|
|
324
372
|
return sample;
|
|
325
373
|
});
|
|
326
|
-
const names =
|
|
374
|
+
const names = managed.map(app => app.name);
|
|
327
375
|
loadStore.retain(names);
|
|
328
376
|
requestMetrics.retain(names);
|
|
329
377
|
return samples;
|
package/libs/services/dbops.js
CHANGED
|
@@ -24,6 +24,8 @@ module.exports = fp(async (fastify, options) => {
|
|
|
24
24
|
throw err;
|
|
25
25
|
};
|
|
26
26
|
|
|
27
|
+
const { isLinked } = require('../utils/appKind');
|
|
28
|
+
|
|
27
29
|
const getByName = async name => {
|
|
28
30
|
const app = await models.app.findOne({ where: { name } });
|
|
29
31
|
if (!app) {
|
|
@@ -32,6 +34,8 @@ module.exports = fp(async (fastify, options) => {
|
|
|
32
34
|
return app;
|
|
33
35
|
};
|
|
34
36
|
|
|
37
|
+
const linkedProxy = () => fastify[options.name].services.link.proxy;
|
|
38
|
+
|
|
35
39
|
const resolveEnvForApp = app =>
|
|
36
40
|
resolveAppDbEnv({
|
|
37
41
|
passthroughEnvKeys: options.passthroughEnvKeys,
|
|
@@ -116,6 +120,9 @@ module.exports = fp(async (fastify, options) => {
|
|
|
116
120
|
|
|
117
121
|
const listTables = async ({ name, scope } = {}) => {
|
|
118
122
|
const app = await getByName(name);
|
|
123
|
+
if (isLinked(app)) {
|
|
124
|
+
return linkedProxy().dbTables(app);
|
|
125
|
+
}
|
|
119
126
|
return withSequelize(app, async (sequelize, env) => {
|
|
120
127
|
const all = await listAllTables(sequelize);
|
|
121
128
|
const dbScope = resolveDbScope(app.env || {}, app.options || {});
|
|
@@ -288,6 +295,9 @@ module.exports = fp(async (fastify, options) => {
|
|
|
288
295
|
|
|
289
296
|
const listRows = async ({ name, table, currentPage = 1, perPage = 20, filter, includeDeleted, sort, keyword } = {}) => {
|
|
290
297
|
const app = await getByName(name);
|
|
298
|
+
if (isLinked(app)) {
|
|
299
|
+
return linkedProxy().dbRows(app, { table, currentPage, perPage, filter, includeDeleted, sort, keyword });
|
|
300
|
+
}
|
|
291
301
|
const showDeleted = includeDeleted === true || includeDeleted === 'true' || includeDeleted === 1;
|
|
292
302
|
return withSequelize(app, async sequelize => {
|
|
293
303
|
const all = await listAllTables(sequelize);
|
|
@@ -368,6 +378,9 @@ module.exports = fp(async (fastify, options) => {
|
|
|
368
378
|
|
|
369
379
|
const saveRow = async ({ name, table, data = {}, autoGenerate } = {}) => {
|
|
370
380
|
const app = await getByName(name);
|
|
381
|
+
if (isLinked(app)) {
|
|
382
|
+
return linkedProxy().dbSaveRow(app, { table, data, autoGenerate });
|
|
383
|
+
}
|
|
371
384
|
return withSequelize(app, async sequelize => {
|
|
372
385
|
const all = await listAllTables(sequelize);
|
|
373
386
|
assertTableOwned(app, all, table);
|
|
@@ -457,6 +470,9 @@ module.exports = fp(async (fastify, options) => {
|
|
|
457
470
|
|
|
458
471
|
const removeRow = async ({ name, table, id, pk, hard = false } = {}) => {
|
|
459
472
|
const app = await getByName(name);
|
|
473
|
+
if (isLinked(app)) {
|
|
474
|
+
return linkedProxy().dbRemoveRow(app, { table, id, pk, hard });
|
|
475
|
+
}
|
|
460
476
|
return withSequelize(app, async sequelize => {
|
|
461
477
|
const all = await listAllTables(sequelize);
|
|
462
478
|
assertTableOwned(app, all, table);
|
|
@@ -508,6 +524,9 @@ module.exports = fp(async (fastify, options) => {
|
|
|
508
524
|
|
|
509
525
|
const runQuery = async ({ name, sql, replacements = {}, maxRows } = {}) => {
|
|
510
526
|
const app = await getByName(name);
|
|
527
|
+
if (isLinked(app)) {
|
|
528
|
+
return linkedProxy().dbQuery(app, { sql, replacements, maxRows });
|
|
529
|
+
}
|
|
511
530
|
const limit = Math.min(Math.max(1, Number(maxRows) || options.dbQueryMaxRows || 500), options.dbQueryMaxRows || 500);
|
|
512
531
|
const checked = assertReadOnlyQuerySql(sql);
|
|
513
532
|
return withSequelize(app, async sequelize => {
|