plugin-workflow-portainer 0.0.0-stage → 0.2.0

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.
Files changed (99) hide show
  1. package/LICENSE +176 -0
  2. package/README.md +31 -3
  3. package/client-v2.js +1 -0
  4. package/client.js +1 -0
  5. package/dist/client/127.09e6675863ac8138.js +10 -0
  6. package/dist/client/57.67f04a547ead06b8.js +10 -0
  7. package/dist/client/660.546c702d1ddf7eff.js +10 -0
  8. package/dist/client/981.e38099c59bf992f0.js +10 -0
  9. package/dist/client/index.js +10 -0
  10. package/dist/client-v2/127.9f65dc2e3d0df10a.js +10 -0
  11. package/dist/client-v2/57.a60e16e4b4e4fa28.js +10 -0
  12. package/dist/client-v2/660.29ae3c3b4040039d.js +10 -0
  13. package/dist/client-v2/981.8627062881ad83d1.js +10 -0
  14. package/dist/client-v2/index.js +10 -0
  15. package/dist/externalVersion.js +20 -0
  16. package/dist/index.js +48 -0
  17. package/dist/locale/en-US.json +193 -0
  18. package/dist/locale/vi-VN.json +193 -0
  19. package/dist/locale/zh-CN.json +193 -0
  20. package/dist/node_modules/joi/dist/joi-browser.min.js +1 -0
  21. package/dist/node_modules/joi/lib/annotate.js +175 -0
  22. package/dist/node_modules/joi/lib/base.js +1069 -0
  23. package/dist/node_modules/joi/lib/cache.js +143 -0
  24. package/dist/node_modules/joi/lib/common.js +216 -0
  25. package/dist/node_modules/joi/lib/compile.js +283 -0
  26. package/dist/node_modules/joi/lib/errors.js +271 -0
  27. package/dist/node_modules/joi/lib/extend.js +312 -0
  28. package/dist/node_modules/joi/lib/index.d.ts +2365 -0
  29. package/dist/node_modules/joi/lib/index.js +1 -0
  30. package/dist/node_modules/joi/lib/manifest.js +476 -0
  31. package/dist/node_modules/joi/lib/messages.js +207 -0
  32. package/dist/node_modules/joi/lib/modify.js +267 -0
  33. package/dist/node_modules/joi/lib/ref.js +414 -0
  34. package/dist/node_modules/joi/lib/schemas.js +302 -0
  35. package/dist/node_modules/joi/lib/state.js +166 -0
  36. package/dist/node_modules/joi/lib/template.js +463 -0
  37. package/dist/node_modules/joi/lib/trace.js +346 -0
  38. package/dist/node_modules/joi/lib/types/alternatives.js +364 -0
  39. package/dist/node_modules/joi/lib/types/any.js +174 -0
  40. package/dist/node_modules/joi/lib/types/array.js +809 -0
  41. package/dist/node_modules/joi/lib/types/binary.js +100 -0
  42. package/dist/node_modules/joi/lib/types/boolean.js +150 -0
  43. package/dist/node_modules/joi/lib/types/date.js +233 -0
  44. package/dist/node_modules/joi/lib/types/function.js +93 -0
  45. package/dist/node_modules/joi/lib/types/keys.js +1084 -0
  46. package/dist/node_modules/joi/lib/types/link.js +184 -0
  47. package/dist/node_modules/joi/lib/types/number.js +363 -0
  48. package/dist/node_modules/joi/lib/types/object.js +22 -0
  49. package/dist/node_modules/joi/lib/types/string.js +850 -0
  50. package/dist/node_modules/joi/lib/types/symbol.js +102 -0
  51. package/dist/node_modules/joi/lib/validator.js +750 -0
  52. package/dist/node_modules/joi/lib/values.js +263 -0
  53. package/dist/node_modules/joi/node_modules/@hapi/topo/lib/index.d.ts +60 -0
  54. package/dist/node_modules/joi/node_modules/@hapi/topo/lib/index.js +225 -0
  55. package/dist/node_modules/joi/node_modules/@hapi/topo/package.json +30 -0
  56. package/dist/node_modules/joi/package.json +1 -0
  57. package/dist/server/actions/portainer.js +317 -0
  58. package/dist/server/collections/portainer-instances.js +54 -0
  59. package/dist/server/index.js +54 -0
  60. package/dist/server/instructions/PortainerStackControlInstruction.js +156 -0
  61. package/dist/server/instructions/PortainerStackRedeployInstruction.js +254 -0
  62. package/dist/server/instructions/helpers.js +211 -0
  63. package/dist/server/plugin.js +177 -0
  64. package/dist/server/services/PortainerClient.js +669 -0
  65. package/dist/shared/collection.js +57 -0
  66. package/dist/shared/constants.js +66 -0
  67. package/dist/shared/env.js +238 -0
  68. package/dist/shared/types.js +24 -0
  69. package/package.json +50 -4
  70. package/server.js +1 -0
  71. package/src/client/index.tsx +50 -0
  72. package/src/client/instructions.tsx +76 -0
  73. package/src/client-v2/__tests__/workflow-registration.test.tsx +242 -0
  74. package/src/client-v2/components/ControlFieldset.tsx +46 -0
  75. package/src/client-v2/components/PortainerEnvEditor.tsx +223 -0
  76. package/src/client-v2/components/PortainerSettingsPage.tsx +707 -0
  77. package/src/client-v2/components/PortainerTargetFields.tsx +309 -0
  78. package/src/client-v2/components/RedeployFieldset.tsx +124 -0
  79. package/src/client-v2/components/StackDetailDrawer.tsx +790 -0
  80. package/src/client-v2/index.tsx +50 -0
  81. package/src/client-v2/instructions.tsx +162 -0
  82. package/src/client-v2/locale.ts +24 -0
  83. package/src/index.ts +11 -0
  84. package/src/locale/en-US.json +193 -0
  85. package/src/locale/vi-VN.json +193 -0
  86. package/src/locale/zh-CN.json +193 -0
  87. package/src/server/__tests__/portainer-workflow.test.ts +559 -0
  88. package/src/server/actions/portainer.ts +361 -0
  89. package/src/server/collections/portainer-instances.ts +34 -0
  90. package/src/server/index.ts +13 -0
  91. package/src/server/instructions/PortainerStackControlInstruction.ts +139 -0
  92. package/src/server/instructions/PortainerStackRedeployInstruction.ts +255 -0
  93. package/src/server/instructions/helpers.ts +237 -0
  94. package/src/server/plugin.ts +174 -0
  95. package/src/server/services/PortainerClient.ts +846 -0
  96. package/src/shared/collection.ts +32 -0
  97. package/src/shared/constants.ts +25 -0
  98. package/src/shared/env.ts +243 -0
  99. package/src/shared/types.ts +164 -0
@@ -0,0 +1,255 @@
1
+ /**
2
+ * This file is part of the NocoBase (R) project.
3
+ * Copyright (c) 2020-2024 NocoBase Co., Ltd.
4
+ * Authors: NocoBase Team.
5
+ *
6
+ * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
7
+ * For more information, please refer to: https://www.nocobase.com/agreement.
8
+ */
9
+
10
+ import Joi from 'joi';
11
+ import { Instruction, JOB_STATUS, type FlowNodeModel, type JobModel, type Processor } from '@nocobase/plugin-workflow';
12
+ import { buildEffectiveStackEnv, normalizeGitReference } from '../../shared/env';
13
+ import type { PortainerContainerSummary, PortainerStackRedeployConfig } from '../../shared/types';
14
+ import {
15
+ assertPositiveInt,
16
+ clampTimeoutMs,
17
+ PortainerApiError,
18
+ summarizeContainersHealth,
19
+ toStackDetail,
20
+ type RawPortainerStack,
21
+ } from '../services/PortainerClient';
22
+ import {
23
+ formatFailureResult,
24
+ resolvePortainerInstance,
25
+ runPortainerWorkflowTask,
26
+ type ResolvedPortainerInstance,
27
+ } from './helpers';
28
+
29
+ const numOrVar = Joi.alternatives().try(Joi.number(), Joi.string().allow(''), Joi.allow(null));
30
+
31
+ function resolveGitAuthPayload(stack: RawPortainerStack, instance: ResolvedPortainerInstance) {
32
+ const stackAuth = stack.GitConfig?.Authentication;
33
+ const stackCredId = Number(stackAuth?.GitCredentialID ?? 0);
34
+ const effectiveCredId = stackCredId > 0 ? stackCredId : instance.gitCredentialId;
35
+
36
+ if (effectiveCredId && effectiveCredId > 0) {
37
+ return {
38
+ repositoryAuthentication: true,
39
+ repositoryGitCredentialID: effectiveCredId,
40
+ ...(stackAuth?.Username ? { repositoryUsername: String(stackAuth.Username) } : {}),
41
+ };
42
+ }
43
+
44
+ if (instance.gitAccessToken) {
45
+ return {
46
+ repositoryAuthentication: true,
47
+ repositoryUsername: String(stackAuth?.Username || instance.gitUsername || 'oauth2'),
48
+ repositoryPassword: instance.gitAccessToken,
49
+ };
50
+ }
51
+
52
+ if (stackAuth?.Username) {
53
+ return {
54
+ repositoryAuthentication: true,
55
+ repositoryUsername: String(stackAuth.Username),
56
+ };
57
+ }
58
+
59
+ return {
60
+ repositoryAuthentication: false,
61
+ };
62
+ }
63
+
64
+ export async function executePortainerRedeploy(
65
+ app: Parameters<typeof resolvePortainerInstance>[0],
66
+ config: PortainerStackRedeployConfig,
67
+ signal?: AbortSignal,
68
+ ) {
69
+ const startedAt = new Date();
70
+ const instance = await resolvePortainerInstance(app, config.instanceId ?? null);
71
+ const timeoutMs = clampTimeoutMs(config.timeoutMs, instance.defaultTimeoutMs);
72
+ const mode = config.mode === 'webhook' ? 'webhook' : 'stack';
73
+
74
+ if (mode === 'webhook') {
75
+ await instance.client.triggerWebhook(config.webhookId ?? '', config.webhookTag, { timeoutMs, signal });
76
+ const finishedAt = new Date();
77
+ return {
78
+ ok: true,
79
+ instanceId: instance.id,
80
+ instanceName: instance.name,
81
+ endpointId: null,
82
+ stackId: null,
83
+ stackName: null,
84
+ stackType: 'webhook' as const,
85
+ stackStatus: 1,
86
+ gitReference: null,
87
+ webhookTag: config.webhookTag ? String(config.webhookTag).trim() : null,
88
+ appliedEnv: {},
89
+ appliedEnvCount: 0,
90
+ runningCount: 0,
91
+ totalCount: 0,
92
+ healthy: true,
93
+ containers: [] as PortainerContainerSummary[],
94
+ startedAt: startedAt.toISOString(),
95
+ finishedAt: finishedAt.toISOString(),
96
+ durationMs: Math.max(0, finishedAt.getTime() - startedAt.getTime()),
97
+ };
98
+ }
99
+
100
+ const stackId = assertPositiveInt(config.stackId ?? undefined, 'Stack ID');
101
+ const rawStack = await instance.client.getRawStack(stackId, signal);
102
+ const stackDetail = toStackDetail(rawStack);
103
+
104
+ const hasExplicitEndpoint =
105
+ config.endpointId !== null && typeof config.endpointId !== 'undefined' && String(config.endpointId).trim() !== '';
106
+ const endpointId = hasExplicitEndpoint
107
+ ? assertPositiveInt(config.endpointId ?? undefined, 'Environment (Endpoint) ID')
108
+ : assertPositiveInt(rawStack.EndpointId, 'Stack Endpoint ID');
109
+
110
+ const { env, maskedEnv } = buildEffectiveStackEnv({
111
+ existingEnv: stackDetail.env,
112
+ strategy: config.envStrategy ?? 'merge',
113
+ dynamicEnv: config.dynamicEnv,
114
+ envText: config.envText,
115
+ envPairs: config.envPairs,
116
+ });
117
+
118
+ const prune = Boolean(config.prune);
119
+ const repullImage = Boolean(config.repullImage);
120
+ let updatedStack: RawPortainerStack;
121
+ let gitReferenceUsed: string | null = null;
122
+
123
+ if (stackDetail.isGitStack) {
124
+ gitReferenceUsed = normalizeGitReference(config.gitReference, stackDetail.gitReference);
125
+ const gitAuth = resolveGitAuthPayload(rawStack, instance);
126
+ updatedStack = await instance.client.redeployGitStack(
127
+ stackId,
128
+ endpointId,
129
+ {
130
+ env,
131
+ prune,
132
+ repullImage,
133
+ repositoryReferenceName: gitReferenceUsed,
134
+ ...gitAuth,
135
+ },
136
+ { timeoutMs, signal },
137
+ );
138
+ } else {
139
+ const stackFileContent = await instance.client.getStackFile(stackId, signal);
140
+ if (!stackFileContent.trim()) {
141
+ throw new PortainerApiError('Portainer stack file content is empty; cannot update non-Git stack', {
142
+ code: 'EMPTY_STACK_FILE',
143
+ });
144
+ }
145
+ updatedStack = await instance.client.updateComposeStack(
146
+ stackId,
147
+ endpointId,
148
+ {
149
+ stackFileContent,
150
+ env,
151
+ prune,
152
+ repullImage,
153
+ },
154
+ { timeoutMs, signal },
155
+ );
156
+ }
157
+
158
+ updatedStack = await instance.client.waitForStackSettlement(stackId, updatedStack, { timeoutMs, signal });
159
+
160
+ const stackName = String(updatedStack?.Name ?? rawStack.Name ?? '');
161
+ let containers: PortainerContainerSummary[] = [];
162
+ try {
163
+ containers = await instance.client.listStackContainers(endpointId, stackName, signal);
164
+ } catch {
165
+ containers = [];
166
+ }
167
+ const health = summarizeContainersHealth(containers);
168
+ const finishedAt = new Date();
169
+
170
+ return {
171
+ ok: true,
172
+ instanceId: instance.id,
173
+ instanceName: instance.name,
174
+ endpointId,
175
+ stackId,
176
+ stackName,
177
+ stackType: stackDetail.isGitStack ? ('git' as const) : ('compose' as const),
178
+ stackStatus: Number(updatedStack?.Status ?? rawStack.Status ?? 1),
179
+ gitReference: gitReferenceUsed,
180
+ appliedEnv: maskedEnv,
181
+ appliedEnvCount: env.length,
182
+ runningCount: health.runningCount,
183
+ totalCount: health.totalCount,
184
+ healthy: containers.length > 0 ? health.healthy : true,
185
+ containers,
186
+ startedAt: startedAt.toISOString(),
187
+ finishedAt: finishedAt.toISOString(),
188
+ durationMs: Math.max(0, finishedAt.getTime() - startedAt.getTime()),
189
+ };
190
+ }
191
+
192
+ export class PortainerStackRedeployInstruction extends Instruction {
193
+ configSchema = Joi.object({
194
+ instanceId: numOrVar,
195
+ mode: Joi.string().valid('stack', 'webhook').default('stack'),
196
+ endpointId: numOrVar,
197
+ stackId: numOrVar,
198
+ webhookId: Joi.string().allow('', null),
199
+ webhookTag: Joi.string().allow('', null),
200
+ gitReference: Joi.string().allow('', null),
201
+ repullImage: Joi.boolean().default(false),
202
+ prune: Joi.boolean().default(false),
203
+ envStrategy: Joi.string().valid('merge', 'replace').default('merge'),
204
+ dynamicEnv: Joi.any(),
205
+ envText: Joi.string().allow('', null),
206
+ envPairs: Joi.array().items(
207
+ Joi.object({
208
+ name: Joi.string().allow('', null),
209
+ value: Joi.any(),
210
+ secret: Joi.boolean(),
211
+ }).unknown(true),
212
+ ),
213
+ timeoutMs: numOrVar,
214
+ ignoreFail: Joi.boolean().default(false),
215
+ }).unknown(true);
216
+
217
+ async run(node: FlowNodeModel, prevJob: JobModel, processor: Processor, options?: { signal?: AbortSignal }) {
218
+ const config = processor.getParsedValue(node.config ?? {}, node.id) as PortainerStackRedeployConfig;
219
+ return runPortainerWorkflowTask({
220
+ workflow: this.workflow,
221
+ node,
222
+ prevJob,
223
+ processor,
224
+ ignoreFail: config.ignoreFail,
225
+ signal: options?.signal,
226
+ execute: (signal) => executePortainerRedeploy(this.workflow.app, config, signal),
227
+ });
228
+ }
229
+
230
+ async resume(node: FlowNodeModel, job: JobModel) {
231
+ const config = (node.config ?? {}) as PortainerStackRedeployConfig;
232
+ if (config.ignoreFail) {
233
+ job.set('status', JOB_STATUS.RESOLVED);
234
+ }
235
+ return job;
236
+ }
237
+
238
+ async test(config: PortainerStackRedeployConfig) {
239
+ const startedAt = new Date();
240
+ try {
241
+ const result = await executePortainerRedeploy(this.workflow.app, config);
242
+ return {
243
+ status: JOB_STATUS.RESOLVED,
244
+ result,
245
+ };
246
+ } catch (error) {
247
+ return {
248
+ status: config.ignoreFail ? JOB_STATUS.RESOLVED : JOB_STATUS.FAILED,
249
+ result: formatFailureResult(error, startedAt),
250
+ };
251
+ }
252
+ }
253
+ }
254
+
255
+ export default PortainerStackRedeployInstruction;
@@ -0,0 +1,237 @@
1
+ /**
2
+ * This file is part of the NocoBase (R) project.
3
+ * Copyright (c) 2020-2024 NocoBase Co., Ltd.
4
+ * Authors: NocoBase Team.
5
+ *
6
+ * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
7
+ * For more information, please refer to: https://www.nocobase.com/agreement.
8
+ */
9
+
10
+ import type { Model } from '@nocobase/database';
11
+ import type WorkflowPlugin from '@nocobase/plugin-workflow';
12
+ import {
13
+ EXECUTION_STATUS,
14
+ JOB_STATUS,
15
+ type FlowNodeModel,
16
+ type IJob,
17
+ type JobModel,
18
+ type Processor,
19
+ } from '@nocobase/plugin-workflow';
20
+ import type Application from '@nocobase/server';
21
+ import { DEFAULT_TIMEOUT_MS, PORTAINER_INSTANCES_COLLECTION } from '../../shared/constants';
22
+ import type { ID } from '../../shared/types';
23
+ import { clampTimeoutMs, PortainerApiError, PortainerClient } from '../services/PortainerClient';
24
+
25
+ export interface ResolvedPortainerInstance {
26
+ id: number;
27
+ name: string;
28
+ baseUrl: string;
29
+ apiKey: string;
30
+ gitUsername?: string;
31
+ gitAccessToken?: string;
32
+ gitCredentialId?: number;
33
+ allowInsecureTls: boolean;
34
+ defaultTimeoutMs: number;
35
+ client: PortainerClient;
36
+ }
37
+
38
+ export async function decryptIfNeeded(app: Application, value: unknown): Promise<string> {
39
+ const raw = String(value ?? '').trim();
40
+ if (!raw) {
41
+ return '';
42
+ }
43
+ const decryptor = (app as unknown as { aesEncryptor?: { decrypt(v: string): Promise<string> | string } })
44
+ .aesEncryptor;
45
+ if (!decryptor) {
46
+ return raw;
47
+ }
48
+ try {
49
+ return await decryptor.decrypt(raw);
50
+ } catch {
51
+ return raw;
52
+ }
53
+ }
54
+
55
+ export async function resolvePortainerInstance(
56
+ app: Application,
57
+ instanceId?: ID | null,
58
+ ): Promise<ResolvedPortainerInstance> {
59
+ const repo = app.db.getRepository(PORTAINER_INSTANCES_COLLECTION);
60
+ if (!repo) {
61
+ throw new PortainerApiError('Portainer instances collection is not initialized', { code: 'NO_COLLECTION' });
62
+ }
63
+
64
+ let record: Model | null = null;
65
+ const trimmedId = instanceId !== null && typeof instanceId !== 'undefined' ? String(instanceId).trim() : '';
66
+
67
+ if (trimmedId) {
68
+ const numericId = Number(trimmedId);
69
+ if (!Number.isSafeInteger(numericId) || numericId <= 0) {
70
+ throw new PortainerApiError(`Invalid Portainer instance ID "${trimmedId}"`, { code: 'INVALID_INSTANCE' });
71
+ }
72
+ record = await repo.findOne({ filter: { id: numericId, enabled: true } });
73
+ if (!record) {
74
+ throw new PortainerApiError(`Portainer instance #${numericId} was not found or is disabled`, {
75
+ code: 'INSTANCE_NOT_FOUND',
76
+ });
77
+ }
78
+ } else {
79
+ record = await repo.findOne({ filter: { isDefault: true, enabled: true } });
80
+ if (!record) {
81
+ record = await repo.findOne({ filter: { enabled: true }, sort: ['id'] });
82
+ }
83
+ if (!record) {
84
+ throw new PortainerApiError('No enabled Portainer instance is configured', { code: 'NO_INSTANCE' });
85
+ }
86
+ }
87
+
88
+ const baseUrl = String(record.get('baseUrl') ?? '').trim();
89
+ const apiKey = await decryptIfNeeded(app, record.get('apiKey'));
90
+ const gitAccessToken = await decryptIfNeeded(app, record.get('gitAccessToken'));
91
+ const gitUsername = String(record.get('gitUsername') ?? '').trim() || undefined;
92
+ const rawCredId = Number(record.get('gitCredentialId') ?? 0);
93
+ const gitCredentialId = Number.isSafeInteger(rawCredId) && rawCredId > 0 ? rawCredId : undefined;
94
+ const allowInsecureTls = Boolean(record.get('allowInsecureTls'));
95
+ const defaultTimeoutMs = clampTimeoutMs(Number(record.get('defaultTimeoutMs') ?? DEFAULT_TIMEOUT_MS));
96
+
97
+ const client = new PortainerClient({
98
+ baseUrl,
99
+ apiKey,
100
+ allowInsecureTls,
101
+ timeoutMs: defaultTimeoutMs,
102
+ });
103
+
104
+ return {
105
+ id: Number(record.get('id')),
106
+ name: String(record.get('name') ?? ''),
107
+ baseUrl,
108
+ apiKey,
109
+ gitUsername,
110
+ gitAccessToken: gitAccessToken || undefined,
111
+ gitCredentialId,
112
+ allowInsecureTls,
113
+ defaultTimeoutMs,
114
+ client,
115
+ };
116
+ }
117
+
118
+ export function formatFailureResult(error: unknown, startedAt: Date) {
119
+ const finishedAt = new Date();
120
+ const durationMs = Math.max(0, finishedAt.getTime() - startedAt.getTime());
121
+ if (error instanceof PortainerApiError) {
122
+ return {
123
+ ok: false,
124
+ errorMessage: error.message,
125
+ errorCode: error.code ?? 'PORTAINER_ERROR',
126
+ httpStatus: error.status ?? null,
127
+ startedAt: startedAt.toISOString(),
128
+ finishedAt: finishedAt.toISOString(),
129
+ durationMs,
130
+ };
131
+ }
132
+ const message = error instanceof Error ? error.message : String(error);
133
+ return {
134
+ ok: false,
135
+ errorMessage: message,
136
+ errorCode: 'EXECUTION_ERROR',
137
+ httpStatus: null,
138
+ startedAt: startedAt.toISOString(),
139
+ finishedAt: finishedAt.toISOString(),
140
+ durationMs,
141
+ };
142
+ }
143
+
144
+ function resolveFailureJobStatus(ignoreFail: boolean | undefined, error: unknown): number {
145
+ if (ignoreFail) {
146
+ return JOB_STATUS.RESOLVED;
147
+ }
148
+ if (error instanceof PortainerApiError && error.code === 'ECONNABORTED') {
149
+ return JOB_STATUS.ABORTED;
150
+ }
151
+ return JOB_STATUS.FAILED;
152
+ }
153
+
154
+ /**
155
+ * Shared sync/async workflow execution bridge modeled after NocoBase's native RequestInstruction.
156
+ */
157
+ export async function runPortainerWorkflowTask<TResult extends Record<string, unknown>>(params: {
158
+ workflow: WorkflowPlugin;
159
+ node: FlowNodeModel;
160
+ prevJob: JobModel;
161
+ processor: Processor;
162
+ ignoreFail?: boolean;
163
+ signal?: AbortSignal;
164
+ execute: (signal?: AbortSignal) => Promise<TResult>;
165
+ }) {
166
+ const { workflow, node, prevJob, processor, ignoreFail, execute } = params;
167
+ const startedAt = new Date();
168
+ const sync = processor.isInstructionSync(node);
169
+
170
+ if (sync) {
171
+ try {
172
+ const result = await execute(params.signal);
173
+ return {
174
+ status: JOB_STATUS.RESOLVED,
175
+ result,
176
+ };
177
+ } catch (error) {
178
+ return {
179
+ status: resolveFailureJobStatus(ignoreFail, error),
180
+ result: formatFailureResult(error, startedAt),
181
+ };
182
+ }
183
+ }
184
+
185
+ const savedJob = processor.saveJob({
186
+ status: JOB_STATUS.PENDING,
187
+ nodeId: node.id,
188
+ nodeKey: node.key,
189
+ upstreamId: prevJob?.id ?? null,
190
+ });
191
+ const jobId = savedJob.id;
192
+
193
+ await processor.exit();
194
+ const abortHandle = processor.createBackgroundAbortHandle();
195
+ const jobDone: IJob = { status: JOB_STATUS.PENDING };
196
+
197
+ const settle = async () => {
198
+ try {
199
+ const result = await execute(abortHandle.signal);
200
+ jobDone.status = JOB_STATUS.RESOLVED;
201
+ jobDone.result = result;
202
+ } catch (error) {
203
+ processor.logger.error(
204
+ `[plugin-workflow-portainer] node (#${node.id}) execution failed: ${
205
+ error instanceof Error ? error.message : String(error)
206
+ }`,
207
+ );
208
+ jobDone.status = abortHandle.signal.aborted ? JOB_STATUS.ABORTED : resolveFailureJobStatus(ignoreFail, error);
209
+ jobDone.result = formatFailureResult(error, startedAt);
210
+ } finally {
211
+ abortHandle.dispose();
212
+ const job = (await workflow.app.db.getRepository('jobs').findOne({
213
+ filterByTk: jobId,
214
+ })) as JobModel | null;
215
+ if (job) {
216
+ const execution = await job.getExecution();
217
+ const aborted = await workflow.abortExecutionIfExpired(execution);
218
+ if (!aborted) {
219
+ await execution.reload();
220
+ await job.reload();
221
+ }
222
+ if (!aborted && execution.status === EXECUTION_STATUS.STARTED && job.status === JOB_STATUS.PENDING) {
223
+ job.set(jobDone);
224
+ await workflow.resume(job);
225
+ }
226
+ }
227
+ }
228
+ };
229
+
230
+ settle().catch((caught) => {
231
+ processor.logger.error(
232
+ `[plugin-workflow-portainer] async job settle failed (#${node.id}): ${
233
+ caught instanceof Error ? caught.message : String(caught)
234
+ }`,
235
+ );
236
+ });
237
+ }
@@ -0,0 +1,174 @@
1
+ /**
2
+ * This file is part of the NocoBase (R) project.
3
+ * Copyright (c) 2020-2024 NocoBase Co., Ltd.
4
+ * Authors: NocoBase Team.
5
+ *
6
+ * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
7
+ * For more information, please refer to: https://www.nocobase.com/agreement.
8
+ */
9
+
10
+ import { resolve } from 'node:path';
11
+ import type { Context } from '@nocobase/actions';
12
+ import type { Model } from '@nocobase/database';
13
+ import type WorkflowPlugin from '@nocobase/plugin-workflow';
14
+ import { Plugin } from '@nocobase/server';
15
+ import {
16
+ INSTRUCTION_TYPES,
17
+ PORTAINER_ACL_SNIPPET,
18
+ PORTAINER_INSTANCES_COLLECTION,
19
+ PORTAINER_RESOURCE,
20
+ SECRET_MASK,
21
+ } from '../shared/constants';
22
+ import { createPortainerResourceActions } from './actions/portainer';
23
+ import { PortainerStackControlInstruction } from './instructions/PortainerStackControlInstruction';
24
+ import { PortainerStackRedeployInstruction } from './instructions/PortainerStackRedeployInstruction';
25
+ import { assertValidPortainerUrl, clampTimeoutMs } from './services/PortainerClient';
26
+
27
+ const ENCRYPTED_FIELDS = ['apiKey', 'gitAccessToken'] as const;
28
+ const METADATA_READ_ACTIONS = [
29
+ 'listInstances',
30
+ 'listEndpoints',
31
+ 'listStacks',
32
+ 'getStackDetail',
33
+ 'getStackOverview',
34
+ 'getContainerLogs',
35
+ ] as const;
36
+
37
+ function maskSecretFields(payload: unknown): unknown {
38
+ if (!payload || typeof payload !== 'object') {
39
+ return payload;
40
+ }
41
+ if (Array.isArray(payload)) {
42
+ return payload.map(maskSecretFields);
43
+ }
44
+ const obj = payload as Record<string, unknown>;
45
+ if (typeof obj.toJSON === 'function') {
46
+ return maskSecretFields((obj as { toJSON: () => unknown }).toJSON());
47
+ }
48
+ const clone: Record<string, unknown> = { ...obj };
49
+ for (const field of ENCRYPTED_FIELDS) {
50
+ if (typeof clone[field] === 'string' && clone[field]) {
51
+ clone[field] = SECRET_MASK;
52
+ }
53
+ }
54
+ if (Array.isArray(clone.data)) {
55
+ clone.data = clone.data.map(maskSecretFields);
56
+ }
57
+ if (clone.data && typeof clone.data === 'object' && !Array.isArray(clone.data)) {
58
+ clone.data = maskSecretFields(clone.data);
59
+ }
60
+ if (Array.isArray(clone.rows)) {
61
+ clone.rows = clone.rows.map(maskSecretFields);
62
+ }
63
+ return clone;
64
+ }
65
+
66
+ export class PluginWorkflowPortainerServer extends Plugin {
67
+ private canReadWorkflowMetadata(ctx: Context, action: (typeof METADATA_READ_ACTIONS)[number]): boolean {
68
+ const userId = ctx.state?.currentUser?.id;
69
+ const roles = ctx.state?.currentRoles;
70
+ if (!userId || !Array.isArray(roles)) {
71
+ return false;
72
+ }
73
+ return roles.some((role) => {
74
+ if (typeof role !== 'string') {
75
+ return false;
76
+ }
77
+ if (role === 'root') {
78
+ return true;
79
+ }
80
+ if (this.app.acl.can({ role, resource: PORTAINER_RESOURCE, action })) {
81
+ return true;
82
+ }
83
+ if (this.app.acl.can({ role, resource: 'workflows', action: 'update' })) {
84
+ return true;
85
+ }
86
+ if (this.app.acl.can({ role, resource: 'flow_nodes', action: 'update' })) {
87
+ return true;
88
+ }
89
+ return false;
90
+ });
91
+ }
92
+
93
+ async beforeLoad() {
94
+ await this.db.import({
95
+ directory: resolve(__dirname, 'collections'),
96
+ });
97
+
98
+ this.db.on(`${PORTAINER_INSTANCES_COLLECTION}.beforeSave`, async (model: Model) => {
99
+ if (model.changed('baseUrl') && model.get('baseUrl')) {
100
+ assertValidPortainerUrl(String(model.get('baseUrl')));
101
+ }
102
+ if (model.changed('defaultTimeoutMs') && model.get('defaultTimeoutMs') !== null) {
103
+ model.set('defaultTimeoutMs', clampTimeoutMs(Number(model.get('defaultTimeoutMs'))));
104
+ }
105
+ const encryptor = (this.app as unknown as { aesEncryptor?: { encrypt(v: string): Promise<string> | string } })
106
+ .aesEncryptor;
107
+
108
+ for (const field of ENCRYPTED_FIELDS) {
109
+ if (!model.changed(field)) {
110
+ continue;
111
+ }
112
+ const rawVal = model.get(field);
113
+ if (rawVal === SECRET_MASK) {
114
+ model.set(field, model.previous(field));
115
+ continue;
116
+ }
117
+ if (typeof rawVal === 'string' && rawVal.trim() && encryptor) {
118
+ const encrypted = await encryptor.encrypt(rawVal.trim());
119
+ model.set(field, encrypted);
120
+ }
121
+ }
122
+ });
123
+
124
+ this.db.on(`${PORTAINER_INSTANCES_COLLECTION}.afterSave`, async (model: Model) => {
125
+ if (model.get('isDefault')) {
126
+ const currentId = Number(model.get('id'));
127
+ const repo = this.db.getRepository(PORTAINER_INSTANCES_COLLECTION);
128
+ const others = await repo.find({
129
+ filter: {
130
+ isDefault: true,
131
+ id: { $ne: currentId },
132
+ },
133
+ });
134
+ for (const item of others) {
135
+ await item.update({ isDefault: false });
136
+ }
137
+ }
138
+ });
139
+ }
140
+
141
+ async load() {
142
+ const workflow = (this.app.pm.get('workflow') || this.app.pm.get('@nocobase/plugin-workflow')) as
143
+ | WorkflowPlugin
144
+ | undefined;
145
+
146
+ if (workflow?.registerInstruction) {
147
+ workflow.registerInstruction(INSTRUCTION_TYPES.redeploy, new PortainerStackRedeployInstruction(workflow));
148
+ workflow.registerInstruction(INSTRUCTION_TYPES.control, new PortainerStackControlInstruction(workflow));
149
+ }
150
+
151
+ this.app.resourceManager.define({
152
+ name: PORTAINER_RESOURCE,
153
+ actions: createPortainerResourceActions(this.app),
154
+ });
155
+
156
+ this.app.resourceManager.use(async (ctx, next) => {
157
+ await next();
158
+ if (ctx.action?.resourceName === PORTAINER_INSTANCES_COLLECTION && ctx.body) {
159
+ ctx.body = maskSecretFields(ctx.body);
160
+ }
161
+ });
162
+
163
+ this.app.acl.registerSnippet({
164
+ name: PORTAINER_ACL_SNIPPET,
165
+ actions: [`${PORTAINER_INSTANCES_COLLECTION}:*`, `${PORTAINER_RESOURCE}:*`],
166
+ });
167
+
168
+ for (const action of METADATA_READ_ACTIONS) {
169
+ this.app.acl.allow(PORTAINER_RESOURCE, action, (ctx: Context) => this.canReadWorkflowMetadata(ctx, action));
170
+ }
171
+ }
172
+ }
173
+
174
+ export default PluginWorkflowPortainerServer;