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.
- package/LICENSE +176 -0
- package/README.md +31 -3
- package/client-v2.js +1 -0
- package/client.js +1 -0
- package/dist/client/127.09e6675863ac8138.js +10 -0
- package/dist/client/57.67f04a547ead06b8.js +10 -0
- package/dist/client/660.546c702d1ddf7eff.js +10 -0
- package/dist/client/981.e38099c59bf992f0.js +10 -0
- package/dist/client/index.js +10 -0
- package/dist/client-v2/127.9f65dc2e3d0df10a.js +10 -0
- package/dist/client-v2/57.a60e16e4b4e4fa28.js +10 -0
- package/dist/client-v2/660.29ae3c3b4040039d.js +10 -0
- package/dist/client-v2/981.8627062881ad83d1.js +10 -0
- package/dist/client-v2/index.js +10 -0
- package/dist/externalVersion.js +20 -0
- package/dist/index.js +48 -0
- package/dist/locale/en-US.json +193 -0
- package/dist/locale/vi-VN.json +193 -0
- package/dist/locale/zh-CN.json +193 -0
- package/dist/node_modules/joi/dist/joi-browser.min.js +1 -0
- package/dist/node_modules/joi/lib/annotate.js +175 -0
- package/dist/node_modules/joi/lib/base.js +1069 -0
- package/dist/node_modules/joi/lib/cache.js +143 -0
- package/dist/node_modules/joi/lib/common.js +216 -0
- package/dist/node_modules/joi/lib/compile.js +283 -0
- package/dist/node_modules/joi/lib/errors.js +271 -0
- package/dist/node_modules/joi/lib/extend.js +312 -0
- package/dist/node_modules/joi/lib/index.d.ts +2365 -0
- package/dist/node_modules/joi/lib/index.js +1 -0
- package/dist/node_modules/joi/lib/manifest.js +476 -0
- package/dist/node_modules/joi/lib/messages.js +207 -0
- package/dist/node_modules/joi/lib/modify.js +267 -0
- package/dist/node_modules/joi/lib/ref.js +414 -0
- package/dist/node_modules/joi/lib/schemas.js +302 -0
- package/dist/node_modules/joi/lib/state.js +166 -0
- package/dist/node_modules/joi/lib/template.js +463 -0
- package/dist/node_modules/joi/lib/trace.js +346 -0
- package/dist/node_modules/joi/lib/types/alternatives.js +364 -0
- package/dist/node_modules/joi/lib/types/any.js +174 -0
- package/dist/node_modules/joi/lib/types/array.js +809 -0
- package/dist/node_modules/joi/lib/types/binary.js +100 -0
- package/dist/node_modules/joi/lib/types/boolean.js +150 -0
- package/dist/node_modules/joi/lib/types/date.js +233 -0
- package/dist/node_modules/joi/lib/types/function.js +93 -0
- package/dist/node_modules/joi/lib/types/keys.js +1084 -0
- package/dist/node_modules/joi/lib/types/link.js +184 -0
- package/dist/node_modules/joi/lib/types/number.js +363 -0
- package/dist/node_modules/joi/lib/types/object.js +22 -0
- package/dist/node_modules/joi/lib/types/string.js +850 -0
- package/dist/node_modules/joi/lib/types/symbol.js +102 -0
- package/dist/node_modules/joi/lib/validator.js +750 -0
- package/dist/node_modules/joi/lib/values.js +263 -0
- package/dist/node_modules/joi/node_modules/@hapi/topo/lib/index.d.ts +60 -0
- package/dist/node_modules/joi/node_modules/@hapi/topo/lib/index.js +225 -0
- package/dist/node_modules/joi/node_modules/@hapi/topo/package.json +30 -0
- package/dist/node_modules/joi/package.json +1 -0
- package/dist/server/actions/portainer.js +317 -0
- package/dist/server/collections/portainer-instances.js +54 -0
- package/dist/server/index.js +54 -0
- package/dist/server/instructions/PortainerStackControlInstruction.js +156 -0
- package/dist/server/instructions/PortainerStackRedeployInstruction.js +254 -0
- package/dist/server/instructions/helpers.js +211 -0
- package/dist/server/plugin.js +177 -0
- package/dist/server/services/PortainerClient.js +669 -0
- package/dist/shared/collection.js +57 -0
- package/dist/shared/constants.js +66 -0
- package/dist/shared/env.js +238 -0
- package/dist/shared/types.js +24 -0
- package/package.json +50 -4
- package/server.js +1 -0
- package/src/client/index.tsx +50 -0
- package/src/client/instructions.tsx +76 -0
- package/src/client-v2/__tests__/workflow-registration.test.tsx +242 -0
- package/src/client-v2/components/ControlFieldset.tsx +46 -0
- package/src/client-v2/components/PortainerEnvEditor.tsx +223 -0
- package/src/client-v2/components/PortainerSettingsPage.tsx +707 -0
- package/src/client-v2/components/PortainerTargetFields.tsx +309 -0
- package/src/client-v2/components/RedeployFieldset.tsx +124 -0
- package/src/client-v2/components/StackDetailDrawer.tsx +790 -0
- package/src/client-v2/index.tsx +50 -0
- package/src/client-v2/instructions.tsx +162 -0
- package/src/client-v2/locale.ts +24 -0
- package/src/index.ts +11 -0
- package/src/locale/en-US.json +193 -0
- package/src/locale/vi-VN.json +193 -0
- package/src/locale/zh-CN.json +193 -0
- package/src/server/__tests__/portainer-workflow.test.ts +559 -0
- package/src/server/actions/portainer.ts +361 -0
- package/src/server/collections/portainer-instances.ts +34 -0
- package/src/server/index.ts +13 -0
- package/src/server/instructions/PortainerStackControlInstruction.ts +139 -0
- package/src/server/instructions/PortainerStackRedeployInstruction.ts +255 -0
- package/src/server/instructions/helpers.ts +237 -0
- package/src/server/plugin.ts +174 -0
- package/src/server/services/PortainerClient.ts +846 -0
- package/src/shared/collection.ts +32 -0
- package/src/shared/constants.ts +25 -0
- package/src/shared/env.ts +243 -0
- package/src/shared/types.ts +164 -0
|
@@ -0,0 +1,846 @@
|
|
|
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 http from 'node:http';
|
|
11
|
+
import https from 'node:https';
|
|
12
|
+
import { URL } from 'node:url';
|
|
13
|
+
import { DEFAULT_TIMEOUT_MS, MAX_TIMEOUT_MS, MIN_TIMEOUT_MS } from '../../shared/constants';
|
|
14
|
+
import type {
|
|
15
|
+
ID,
|
|
16
|
+
PortainerContainerStats,
|
|
17
|
+
PortainerContainerSummary,
|
|
18
|
+
PortainerDeploymentRecord,
|
|
19
|
+
PortainerEndpointSummary,
|
|
20
|
+
PortainerEnvPair,
|
|
21
|
+
PortainerStackDetail,
|
|
22
|
+
PortainerStackSummary,
|
|
23
|
+
} from '../../shared/types';
|
|
24
|
+
|
|
25
|
+
export interface PortainerClientOptions {
|
|
26
|
+
baseUrl: string;
|
|
27
|
+
apiKey?: string;
|
|
28
|
+
allowInsecureTls?: boolean;
|
|
29
|
+
timeoutMs?: number;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export class PortainerApiError extends Error {
|
|
33
|
+
status?: number;
|
|
34
|
+
code?: string;
|
|
35
|
+
details?: unknown;
|
|
36
|
+
|
|
37
|
+
constructor(message: string, options?: { status?: number; code?: string; details?: unknown }) {
|
|
38
|
+
super(message);
|
|
39
|
+
this.name = 'PortainerApiError';
|
|
40
|
+
this.status = options?.status;
|
|
41
|
+
this.code = options?.code;
|
|
42
|
+
this.details = options?.details;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export interface RawPortainerGitAuth {
|
|
47
|
+
Username?: string;
|
|
48
|
+
Password?: string;
|
|
49
|
+
GitCredentialID?: number;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export interface RawPortainerGitConfig {
|
|
53
|
+
URL?: string;
|
|
54
|
+
ReferenceName?: string;
|
|
55
|
+
ConfigFilePath?: string;
|
|
56
|
+
ConfigHash?: string;
|
|
57
|
+
Authentication?: RawPortainerGitAuth | null;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export interface RawPortainerDeploymentStatus {
|
|
61
|
+
Status?: number;
|
|
62
|
+
Time?: number;
|
|
63
|
+
Message?: string;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export interface RawPortainerStack {
|
|
67
|
+
Id: number;
|
|
68
|
+
Name: string;
|
|
69
|
+
EndpointId: number;
|
|
70
|
+
Type?: number;
|
|
71
|
+
Status?: number;
|
|
72
|
+
EntryPoint?: string;
|
|
73
|
+
ProjectPath?: string;
|
|
74
|
+
CreationDate?: number;
|
|
75
|
+
CreatedBy?: string;
|
|
76
|
+
UpdateDate?: number;
|
|
77
|
+
UpdatedBy?: string;
|
|
78
|
+
Env?: Array<{ name?: string; value?: string }> | null;
|
|
79
|
+
GitConfig?: RawPortainerGitConfig | null;
|
|
80
|
+
DeploymentStatus?: RawPortainerDeploymentStatus[] | null;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
interface RawDockerPort {
|
|
84
|
+
IP?: string;
|
|
85
|
+
PrivatePort?: number;
|
|
86
|
+
PublicPort?: number;
|
|
87
|
+
Type?: string;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
interface RawDockerContainer {
|
|
91
|
+
Id?: string;
|
|
92
|
+
Names?: string[];
|
|
93
|
+
Image?: string;
|
|
94
|
+
State?: string;
|
|
95
|
+
Status?: string;
|
|
96
|
+
Created?: number;
|
|
97
|
+
Labels?: Record<string, string>;
|
|
98
|
+
Ports?: RawDockerPort[];
|
|
99
|
+
NetworkSettings?: {
|
|
100
|
+
Networks?: Record<string, { IPAddress?: string }>;
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
export interface RawDockerStats {
|
|
105
|
+
cpu_stats?: {
|
|
106
|
+
cpu_usage?: {
|
|
107
|
+
total_usage?: number;
|
|
108
|
+
percpu_usage?: number[];
|
|
109
|
+
};
|
|
110
|
+
system_cpu_usage?: number;
|
|
111
|
+
online_cpus?: number;
|
|
112
|
+
};
|
|
113
|
+
precpu_stats?: {
|
|
114
|
+
cpu_usage?: {
|
|
115
|
+
total_usage?: number;
|
|
116
|
+
};
|
|
117
|
+
system_cpu_usage?: number;
|
|
118
|
+
};
|
|
119
|
+
memory_stats?: {
|
|
120
|
+
usage?: number;
|
|
121
|
+
limit?: number;
|
|
122
|
+
stats?: {
|
|
123
|
+
inactive_file?: number;
|
|
124
|
+
total_inactive_file?: number;
|
|
125
|
+
};
|
|
126
|
+
};
|
|
127
|
+
networks?: Record<string, { rx_bytes?: number; tx_bytes?: number }>;
|
|
128
|
+
blkio_stats?: {
|
|
129
|
+
io_service_bytes_recursive?: Array<{ op?: string; value?: number }>;
|
|
130
|
+
};
|
|
131
|
+
pids_stats?: {
|
|
132
|
+
current?: number;
|
|
133
|
+
};
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
export function assertValidPortainerUrl(rawUrl: string): URL {
|
|
137
|
+
const trimmed = String(rawUrl ?? '').trim();
|
|
138
|
+
if (!trimmed) {
|
|
139
|
+
throw new PortainerApiError('Portainer base URL is required', { code: 'INVALID_URL' });
|
|
140
|
+
}
|
|
141
|
+
let parsed: URL;
|
|
142
|
+
try {
|
|
143
|
+
parsed = new URL(trimmed);
|
|
144
|
+
} catch {
|
|
145
|
+
throw new PortainerApiError('Portainer base URL is invalid', { code: 'INVALID_URL' });
|
|
146
|
+
}
|
|
147
|
+
if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
|
|
148
|
+
throw new PortainerApiError('Portainer base URL must use http or https', { code: 'INVALID_URL' });
|
|
149
|
+
}
|
|
150
|
+
if (parsed.username || parsed.password) {
|
|
151
|
+
throw new PortainerApiError('Portainer base URL must not embed credentials', { code: 'INVALID_URL' });
|
|
152
|
+
}
|
|
153
|
+
return parsed;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
export function assertPositiveInt(value: ID | null | undefined, label: string): number {
|
|
157
|
+
const num = typeof value === 'number' ? value : Number(String(value ?? '').trim());
|
|
158
|
+
if (!Number.isSafeInteger(num) || num <= 0) {
|
|
159
|
+
throw new PortainerApiError(`${label} must be a positive integer`, { code: 'INVALID_PARAM' });
|
|
160
|
+
}
|
|
161
|
+
return num;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
export function assertValidWebhookId(rawWebhookId: string | null | undefined): string {
|
|
165
|
+
const trimmed = String(rawWebhookId ?? '').trim();
|
|
166
|
+
if (!trimmed || !/^[A-Za-z0-9_-]{8,128}$/.test(trimmed)) {
|
|
167
|
+
throw new PortainerApiError('Webhook token must be 8-128 alphanumeric, dash, or underscore characters', {
|
|
168
|
+
code: 'INVALID_WEBHOOK',
|
|
169
|
+
});
|
|
170
|
+
}
|
|
171
|
+
return trimmed;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
export function assertValidContainerId(rawContainerId: string | null | undefined): string {
|
|
175
|
+
const trimmed = String(rawContainerId ?? '').trim();
|
|
176
|
+
if (!trimmed || !/^[a-fA-F0-9]{12,64}$/.test(trimmed)) {
|
|
177
|
+
throw new PortainerApiError('Container ID must be a 12-64 character hexadecimal identifier', {
|
|
178
|
+
code: 'INVALID_PARAM',
|
|
179
|
+
});
|
|
180
|
+
}
|
|
181
|
+
return trimmed;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
export function computeDockerContainerStats(raw: RawDockerStats | null | undefined): PortainerContainerStats {
|
|
185
|
+
const cpuTotal = Number(raw?.cpu_stats?.cpu_usage?.total_usage ?? 0);
|
|
186
|
+
const preCpuTotal = Number(raw?.precpu_stats?.cpu_usage?.total_usage ?? 0);
|
|
187
|
+
const sysCpu = Number(raw?.cpu_stats?.system_cpu_usage ?? 0);
|
|
188
|
+
const preSysCpu = Number(raw?.precpu_stats?.system_cpu_usage ?? 0);
|
|
189
|
+
const cpuDelta = cpuTotal - preCpuTotal;
|
|
190
|
+
const sysDelta = sysCpu - preSysCpu;
|
|
191
|
+
const perCpu = raw?.cpu_stats?.cpu_usage?.percpu_usage;
|
|
192
|
+
const onlineCpus = Number(raw?.cpu_stats?.online_cpus ?? 0) || (Array.isArray(perCpu) ? perCpu.length : 0) || 1;
|
|
193
|
+
const cpuPercent =
|
|
194
|
+
cpuDelta > 0 && sysDelta > 0
|
|
195
|
+
? Math.round(((cpuDelta / sysDelta) * onlineCpus * 100 + Number.EPSILON) * 100) / 100
|
|
196
|
+
: 0;
|
|
197
|
+
|
|
198
|
+
const rawMemUsage = Number(raw?.memory_stats?.usage ?? 0);
|
|
199
|
+
const inactiveFile = Number(
|
|
200
|
+
raw?.memory_stats?.stats?.inactive_file ?? raw?.memory_stats?.stats?.total_inactive_file ?? 0,
|
|
201
|
+
);
|
|
202
|
+
const memUsageBytes = Math.max(0, rawMemUsage - inactiveFile);
|
|
203
|
+
const memLimitBytes = Math.max(0, Number(raw?.memory_stats?.limit ?? 0));
|
|
204
|
+
const memPercent =
|
|
205
|
+
memLimitBytes > 0 ? Math.round(((memUsageBytes / memLimitBytes) * 100 + Number.EPSILON) * 100) / 100 : 0;
|
|
206
|
+
|
|
207
|
+
let netRxBytes = 0;
|
|
208
|
+
let netTxBytes = 0;
|
|
209
|
+
if (raw?.networks && typeof raw.networks === 'object') {
|
|
210
|
+
for (const iface of Object.values(raw.networks)) {
|
|
211
|
+
netRxBytes += Math.max(0, Number(iface?.rx_bytes ?? 0));
|
|
212
|
+
netTxBytes += Math.max(0, Number(iface?.tx_bytes ?? 0));
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
let blockReadBytes = 0;
|
|
217
|
+
let blockWriteBytes = 0;
|
|
218
|
+
const ioEntries = raw?.blkio_stats?.io_service_bytes_recursive;
|
|
219
|
+
if (Array.isArray(ioEntries)) {
|
|
220
|
+
for (const entry of ioEntries) {
|
|
221
|
+
const op = String(entry?.op ?? '').toLowerCase();
|
|
222
|
+
const val = Math.max(0, Number(entry?.value ?? 0));
|
|
223
|
+
if (op === 'read') {
|
|
224
|
+
blockReadBytes += val;
|
|
225
|
+
} else if (op === 'write') {
|
|
226
|
+
blockWriteBytes += val;
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
const pids = Math.max(0, Number(raw?.pids_stats?.current ?? 0));
|
|
232
|
+
|
|
233
|
+
return {
|
|
234
|
+
cpuPercent,
|
|
235
|
+
memUsageBytes,
|
|
236
|
+
memLimitBytes,
|
|
237
|
+
memPercent,
|
|
238
|
+
netRxBytes,
|
|
239
|
+
netTxBytes,
|
|
240
|
+
blockReadBytes,
|
|
241
|
+
blockWriteBytes,
|
|
242
|
+
pids,
|
|
243
|
+
};
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
/**
|
|
247
|
+
* Strip Docker Engine's 8-byte multiplexed stdout/stderr frame headers when present (`Tty: false`),
|
|
248
|
+
* falling back cleanly to plain UTF-8 text (`Tty: true`).
|
|
249
|
+
*/
|
|
250
|
+
export function demuxDockerLogBuffer(buf: Buffer): string {
|
|
251
|
+
if (!buf || buf.length === 0) {
|
|
252
|
+
return '';
|
|
253
|
+
}
|
|
254
|
+
const looksMultiplexed =
|
|
255
|
+
buf.length >= 8 && (buf[0] === 0 || buf[0] === 1 || buf[0] === 2) && buf[1] === 0 && buf[2] === 0 && buf[3] === 0;
|
|
256
|
+
|
|
257
|
+
if (!looksMultiplexed) {
|
|
258
|
+
return buf.toString('utf8');
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
const parts: Buffer[] = [];
|
|
262
|
+
let offset = 0;
|
|
263
|
+
while (offset + 8 <= buf.length) {
|
|
264
|
+
const streamType = buf[offset];
|
|
265
|
+
if (
|
|
266
|
+
(streamType !== 0 && streamType !== 1 && streamType !== 2) ||
|
|
267
|
+
buf[offset + 1] !== 0 ||
|
|
268
|
+
buf[offset + 2] !== 0 ||
|
|
269
|
+
buf[offset + 3] !== 0
|
|
270
|
+
) {
|
|
271
|
+
parts.push(buf.subarray(offset));
|
|
272
|
+
break;
|
|
273
|
+
}
|
|
274
|
+
const frameLen = buf.readUInt32BE(offset + 4);
|
|
275
|
+
const payloadStart = offset + 8;
|
|
276
|
+
const payloadEnd = Math.min(buf.length, payloadStart + frameLen);
|
|
277
|
+
parts.push(buf.subarray(payloadStart, payloadEnd));
|
|
278
|
+
offset = payloadEnd;
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
return Buffer.concat(parts).toString('utf8');
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
export function clampTimeoutMs(timeoutMs?: number | null, fallback = DEFAULT_TIMEOUT_MS): number {
|
|
285
|
+
const num = Number(timeoutMs);
|
|
286
|
+
if (!Number.isFinite(num) || num <= 0) {
|
|
287
|
+
return fallback;
|
|
288
|
+
}
|
|
289
|
+
return Math.min(MAX_TIMEOUT_MS, Math.max(MIN_TIMEOUT_MS, Math.trunc(num)));
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
function normalizeEnvArray(raw?: Array<{ name?: string; value?: string }> | null): PortainerEnvPair[] {
|
|
293
|
+
if (!Array.isArray(raw)) {
|
|
294
|
+
return [];
|
|
295
|
+
}
|
|
296
|
+
const pairs: PortainerEnvPair[] = [];
|
|
297
|
+
for (const item of raw) {
|
|
298
|
+
const name = String(item?.name ?? '').trim();
|
|
299
|
+
if (!name) {
|
|
300
|
+
continue;
|
|
301
|
+
}
|
|
302
|
+
pairs.push({ name, value: String(item?.value ?? '') });
|
|
303
|
+
}
|
|
304
|
+
return pairs;
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
export function toStackSummary(stack: RawPortainerStack): PortainerStackSummary {
|
|
308
|
+
const env = normalizeEnvArray(stack.Env);
|
|
309
|
+
const git = stack.GitConfig;
|
|
310
|
+
return {
|
|
311
|
+
id: Number(stack.Id),
|
|
312
|
+
name: String(stack.Name ?? ''),
|
|
313
|
+
endpointId: Number(stack.EndpointId),
|
|
314
|
+
type: Number(stack.Type ?? 2),
|
|
315
|
+
status: Number(stack.Status ?? 1),
|
|
316
|
+
isGitStack: Boolean(git && git.URL),
|
|
317
|
+
gitRepoUrl: git?.URL ? String(git.URL) : undefined,
|
|
318
|
+
gitReference: git?.ReferenceName ? String(git.ReferenceName) : undefined,
|
|
319
|
+
envCount: env.length,
|
|
320
|
+
};
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
export function toStackDetail(stack: RawPortainerStack): PortainerStackDetail {
|
|
324
|
+
const summary = toStackSummary(stack);
|
|
325
|
+
const git = stack.GitConfig;
|
|
326
|
+
const auth = git?.Authentication;
|
|
327
|
+
const credId = Number(auth?.GitCredentialID ?? 0);
|
|
328
|
+
const deployments: PortainerDeploymentRecord[] | undefined = Array.isArray(stack.DeploymentStatus)
|
|
329
|
+
? stack.DeploymentStatus.map((item) => ({
|
|
330
|
+
status: Number(item?.Status ?? 0),
|
|
331
|
+
time: typeof item?.Time === 'number' && item.Time > 0 ? item.Time : undefined,
|
|
332
|
+
message: item?.Message ? String(item.Message) : undefined,
|
|
333
|
+
}))
|
|
334
|
+
: undefined;
|
|
335
|
+
|
|
336
|
+
return {
|
|
337
|
+
...summary,
|
|
338
|
+
env: normalizeEnvArray(stack.Env),
|
|
339
|
+
hasSavedGitCredential: credId > 0,
|
|
340
|
+
gitCredentialId: credId > 0 ? credId : 0,
|
|
341
|
+
gitUsername: auth?.Username ? String(auth.Username) : undefined,
|
|
342
|
+
entryPoint: stack.EntryPoint ? String(stack.EntryPoint) : undefined,
|
|
343
|
+
projectPath: stack.ProjectPath ? String(stack.ProjectPath) : undefined,
|
|
344
|
+
createdAt: typeof stack.CreationDate === 'number' && stack.CreationDate > 0 ? stack.CreationDate : undefined,
|
|
345
|
+
createdBy: stack.CreatedBy ? String(stack.CreatedBy) : undefined,
|
|
346
|
+
updatedAt: typeof stack.UpdateDate === 'number' && stack.UpdateDate > 0 ? stack.UpdateDate : undefined,
|
|
347
|
+
updatedBy: stack.UpdatedBy ? String(stack.UpdatedBy) : undefined,
|
|
348
|
+
gitConfigFilePath: git?.ConfigFilePath ? String(git.ConfigFilePath) : undefined,
|
|
349
|
+
gitCommitHash: git?.ConfigHash ? String(git.ConfigHash) : undefined,
|
|
350
|
+
deployments,
|
|
351
|
+
};
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
export class PortainerClient {
|
|
355
|
+
private readonly baseUrl: URL;
|
|
356
|
+
private readonly apiKey: string;
|
|
357
|
+
private readonly allowInsecureTls: boolean;
|
|
358
|
+
private readonly timeoutMs: number;
|
|
359
|
+
|
|
360
|
+
constructor(options: PortainerClientOptions) {
|
|
361
|
+
this.baseUrl = assertValidPortainerUrl(options.baseUrl);
|
|
362
|
+
this.apiKey = String(options.apiKey ?? '').trim();
|
|
363
|
+
this.allowInsecureTls = Boolean(options.allowInsecureTls);
|
|
364
|
+
this.timeoutMs = clampTimeoutMs(options.timeoutMs);
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
private buildUrl(pathname: string, query?: Record<string, string | number | undefined>): URL {
|
|
368
|
+
const basePath = this.baseUrl.pathname.replace(/\/+$/, '');
|
|
369
|
+
const suffix = pathname.startsWith('/') ? pathname : `/${pathname}`;
|
|
370
|
+
const target = new URL(this.baseUrl.toString());
|
|
371
|
+
target.pathname = `${basePath}${suffix}`;
|
|
372
|
+
target.search = '';
|
|
373
|
+
if (query) {
|
|
374
|
+
for (const [key, value] of Object.entries(query)) {
|
|
375
|
+
if (typeof value !== 'undefined' && value !== '') {
|
|
376
|
+
target.searchParams.set(key, String(value));
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
return target;
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
async request<TResponse>(options: {
|
|
384
|
+
method: 'GET' | 'POST' | 'PUT' | 'DELETE';
|
|
385
|
+
path: string;
|
|
386
|
+
query?: Record<string, string | number | undefined>;
|
|
387
|
+
body?: unknown;
|
|
388
|
+
timeoutMs?: number;
|
|
389
|
+
skipAuth?: boolean;
|
|
390
|
+
rawBuffer?: boolean;
|
|
391
|
+
signal?: AbortSignal;
|
|
392
|
+
}): Promise<TResponse> {
|
|
393
|
+
if (!options.skipAuth && !this.apiKey) {
|
|
394
|
+
throw new PortainerApiError('Portainer API key is required', { code: 'MISSING_API_KEY' });
|
|
395
|
+
}
|
|
396
|
+
const targetUrl = this.buildUrl(options.path, options.query);
|
|
397
|
+
const payload = typeof options.body !== 'undefined' ? Buffer.from(JSON.stringify(options.body), 'utf8') : null;
|
|
398
|
+
const timeout = clampTimeoutMs(options.timeoutMs, this.timeoutMs);
|
|
399
|
+
|
|
400
|
+
const headers: Record<string, string> = {
|
|
401
|
+
Accept: 'application/json',
|
|
402
|
+
};
|
|
403
|
+
if (!options.skipAuth) {
|
|
404
|
+
headers['X-API-Key'] = this.apiKey;
|
|
405
|
+
}
|
|
406
|
+
if (payload) {
|
|
407
|
+
headers['Content-Type'] = 'application/json';
|
|
408
|
+
headers['Content-Length'] = String(payload.byteLength);
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
const transport = targetUrl.protocol === 'https:' ? https : http;
|
|
412
|
+
|
|
413
|
+
return new Promise<TResponse>((resolve, reject) => {
|
|
414
|
+
if (options.signal?.aborted) {
|
|
415
|
+
reject(new PortainerApiError('Portainer request aborted', { code: 'ECONNABORTED' }));
|
|
416
|
+
return;
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
let settled = false;
|
|
420
|
+
const finish = (fn: () => void) => {
|
|
421
|
+
if (settled) return;
|
|
422
|
+
settled = true;
|
|
423
|
+
if (options.signal) {
|
|
424
|
+
options.signal.removeEventListener('abort', onAbort);
|
|
425
|
+
}
|
|
426
|
+
fn();
|
|
427
|
+
};
|
|
428
|
+
|
|
429
|
+
const req = transport.request(
|
|
430
|
+
targetUrl,
|
|
431
|
+
{
|
|
432
|
+
method: options.method,
|
|
433
|
+
headers,
|
|
434
|
+
timeout,
|
|
435
|
+
...(targetUrl.protocol === 'https:' ? { rejectUnauthorized: !this.allowInsecureTls } : {}),
|
|
436
|
+
},
|
|
437
|
+
(res) => {
|
|
438
|
+
const chunks: Buffer[] = [];
|
|
439
|
+
res.on('data', (chunk: Buffer) => chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)));
|
|
440
|
+
res.on('end', () => {
|
|
441
|
+
const fullBuffer = Buffer.concat(chunks);
|
|
442
|
+
const status = res.statusCode ?? 500;
|
|
443
|
+
if (status >= 200 && status < 300 && options.rawBuffer) {
|
|
444
|
+
finish(() => resolve(fullBuffer as unknown as TResponse));
|
|
445
|
+
return;
|
|
446
|
+
}
|
|
447
|
+
const rawText = fullBuffer.toString('utf8');
|
|
448
|
+
let parsedBody: unknown = rawText;
|
|
449
|
+
if (rawText.trim()) {
|
|
450
|
+
try {
|
|
451
|
+
parsedBody = JSON.parse(rawText);
|
|
452
|
+
} catch {
|
|
453
|
+
parsedBody = rawText;
|
|
454
|
+
}
|
|
455
|
+
} else {
|
|
456
|
+
parsedBody = null;
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
if (status >= 200 && status < 300) {
|
|
460
|
+
finish(() => resolve(parsedBody as TResponse));
|
|
461
|
+
return;
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
const bodyObj =
|
|
465
|
+
typeof parsedBody === 'object' && parsedBody !== null ? (parsedBody as Record<string, unknown>) : null;
|
|
466
|
+
const remoteMessage =
|
|
467
|
+
(typeof bodyObj?.message === 'string' && bodyObj.message) ||
|
|
468
|
+
(typeof bodyObj?.details === 'string' && bodyObj.details) ||
|
|
469
|
+
(typeof parsedBody === 'string' && parsedBody.slice(0, 300)) ||
|
|
470
|
+
`Portainer responded with HTTP ${status}`;
|
|
471
|
+
|
|
472
|
+
finish(() =>
|
|
473
|
+
reject(
|
|
474
|
+
new PortainerApiError(remoteMessage, {
|
|
475
|
+
status,
|
|
476
|
+
code: `HTTP_${status}`,
|
|
477
|
+
details: bodyObj ?? undefined,
|
|
478
|
+
}),
|
|
479
|
+
),
|
|
480
|
+
);
|
|
481
|
+
});
|
|
482
|
+
},
|
|
483
|
+
);
|
|
484
|
+
|
|
485
|
+
function onAbort() {
|
|
486
|
+
req.destroy();
|
|
487
|
+
finish(() => reject(new PortainerApiError('Portainer request aborted', { code: 'ECONNABORTED' })));
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
if (options.signal) {
|
|
491
|
+
options.signal.addEventListener('abort', onAbort, { once: true });
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
req.on('timeout', () => {
|
|
495
|
+
req.destroy();
|
|
496
|
+
finish(() =>
|
|
497
|
+
reject(new PortainerApiError(`Portainer request timed out after ${timeout}ms`, { code: 'ECONNABORTED' })),
|
|
498
|
+
);
|
|
499
|
+
});
|
|
500
|
+
|
|
501
|
+
req.on('error', (err: NodeJS.ErrnoException) => {
|
|
502
|
+
const safeMsg = (err.message || 'Network error calling Portainer').replace(this.apiKey || '__none__', '***');
|
|
503
|
+
finish(() => reject(new PortainerApiError(safeMsg, { code: err.code || 'NETWORK_ERROR' })));
|
|
504
|
+
});
|
|
505
|
+
|
|
506
|
+
if (payload) {
|
|
507
|
+
req.write(payload);
|
|
508
|
+
}
|
|
509
|
+
req.end();
|
|
510
|
+
});
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
async getStatus(signal?: AbortSignal): Promise<{ Version?: string; InstanceID?: string }> {
|
|
514
|
+
return this.request<{ Version?: string; InstanceID?: string }>({
|
|
515
|
+
method: 'GET',
|
|
516
|
+
path: '/api/status',
|
|
517
|
+
signal,
|
|
518
|
+
});
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
async listEndpoints(signal?: AbortSignal): Promise<PortainerEndpointSummary[]> {
|
|
522
|
+
const raw = await this.request<Array<Record<string, unknown>>>({
|
|
523
|
+
method: 'GET',
|
|
524
|
+
path: '/api/endpoints',
|
|
525
|
+
signal,
|
|
526
|
+
});
|
|
527
|
+
if (!Array.isArray(raw)) {
|
|
528
|
+
return [];
|
|
529
|
+
}
|
|
530
|
+
return raw.map((item) => ({
|
|
531
|
+
id: Number(item.Id),
|
|
532
|
+
name: String(item.Name ?? `Endpoint #${item.Id}`),
|
|
533
|
+
type: Number(item.Type ?? 1),
|
|
534
|
+
status: Number(item.Status ?? 1),
|
|
535
|
+
url: typeof item.URL === 'string' ? item.URL : undefined,
|
|
536
|
+
}));
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
async listStacks(endpointId?: number | null, signal?: AbortSignal): Promise<PortainerStackSummary[]> {
|
|
540
|
+
const query = endpointId && endpointId > 0 ? { filters: JSON.stringify({ EndpointID: endpointId }) } : undefined;
|
|
541
|
+
const raw = await this.request<RawPortainerStack[]>({
|
|
542
|
+
method: 'GET',
|
|
543
|
+
path: '/api/stacks',
|
|
544
|
+
query,
|
|
545
|
+
signal,
|
|
546
|
+
});
|
|
547
|
+
if (!Array.isArray(raw)) {
|
|
548
|
+
return [];
|
|
549
|
+
}
|
|
550
|
+
const mapped = raw.map(toStackSummary);
|
|
551
|
+
return endpointId && endpointId > 0 ? mapped.filter((item) => item.endpointId === endpointId) : mapped;
|
|
552
|
+
}
|
|
553
|
+
|
|
554
|
+
async getRawStack(stackId: number, signal?: AbortSignal): Promise<RawPortainerStack> {
|
|
555
|
+
const validId = assertPositiveInt(stackId, 'Stack ID');
|
|
556
|
+
return this.request<RawPortainerStack>({
|
|
557
|
+
method: 'GET',
|
|
558
|
+
path: `/api/stacks/${encodeURIComponent(String(validId))}`,
|
|
559
|
+
signal,
|
|
560
|
+
});
|
|
561
|
+
}
|
|
562
|
+
|
|
563
|
+
async getStackDetail(stackId: number, signal?: AbortSignal): Promise<PortainerStackDetail> {
|
|
564
|
+
const raw = await this.getRawStack(stackId, signal);
|
|
565
|
+
return toStackDetail(raw);
|
|
566
|
+
}
|
|
567
|
+
|
|
568
|
+
async getStackFile(stackId: number, signal?: AbortSignal): Promise<string> {
|
|
569
|
+
const validId = assertPositiveInt(stackId, 'Stack ID');
|
|
570
|
+
const res = await this.request<{ StackFileContent?: string }>({
|
|
571
|
+
method: 'GET',
|
|
572
|
+
path: `/api/stacks/${encodeURIComponent(String(validId))}/file`,
|
|
573
|
+
signal,
|
|
574
|
+
});
|
|
575
|
+
return String(res?.StackFileContent ?? '');
|
|
576
|
+
}
|
|
577
|
+
|
|
578
|
+
async redeployGitStack(
|
|
579
|
+
stackId: number,
|
|
580
|
+
endpointId: number,
|
|
581
|
+
payload: {
|
|
582
|
+
env: PortainerEnvPair[];
|
|
583
|
+
prune: boolean;
|
|
584
|
+
repullImage: boolean;
|
|
585
|
+
repositoryReferenceName: string;
|
|
586
|
+
repositoryAuthentication: boolean;
|
|
587
|
+
repositoryGitCredentialID?: number;
|
|
588
|
+
repositoryUsername?: string;
|
|
589
|
+
repositoryPassword?: string;
|
|
590
|
+
},
|
|
591
|
+
options?: { timeoutMs?: number; signal?: AbortSignal },
|
|
592
|
+
): Promise<RawPortainerStack> {
|
|
593
|
+
const validStackId = assertPositiveInt(stackId, 'Stack ID');
|
|
594
|
+
const validEndpointId = assertPositiveInt(endpointId, 'Environment (Endpoint) ID');
|
|
595
|
+
return this.request<RawPortainerStack>({
|
|
596
|
+
method: 'PUT',
|
|
597
|
+
path: `/api/stacks/${encodeURIComponent(String(validStackId))}/git/redeploy`,
|
|
598
|
+
query: { endpointId: validEndpointId },
|
|
599
|
+
body: {
|
|
600
|
+
env: payload.env,
|
|
601
|
+
prune: payload.prune,
|
|
602
|
+
pullImage: payload.repullImage,
|
|
603
|
+
repullImageAndRedeploy: payload.repullImage,
|
|
604
|
+
repositoryReferenceName: payload.repositoryReferenceName,
|
|
605
|
+
repositoryAuthentication: payload.repositoryAuthentication,
|
|
606
|
+
...(payload.repositoryGitCredentialID && payload.repositoryGitCredentialID > 0
|
|
607
|
+
? { repositoryGitCredentialID: payload.repositoryGitCredentialID }
|
|
608
|
+
: {}),
|
|
609
|
+
...(payload.repositoryUsername ? { repositoryUsername: payload.repositoryUsername } : {}),
|
|
610
|
+
...(payload.repositoryPassword ? { repositoryPassword: payload.repositoryPassword } : {}),
|
|
611
|
+
},
|
|
612
|
+
timeoutMs: options?.timeoutMs,
|
|
613
|
+
signal: options?.signal,
|
|
614
|
+
});
|
|
615
|
+
}
|
|
616
|
+
|
|
617
|
+
async updateComposeStack(
|
|
618
|
+
stackId: number,
|
|
619
|
+
endpointId: number,
|
|
620
|
+
payload: {
|
|
621
|
+
stackFileContent: string;
|
|
622
|
+
env: PortainerEnvPair[];
|
|
623
|
+
prune: boolean;
|
|
624
|
+
repullImage: boolean;
|
|
625
|
+
},
|
|
626
|
+
options?: { timeoutMs?: number; signal?: AbortSignal },
|
|
627
|
+
): Promise<RawPortainerStack> {
|
|
628
|
+
const validStackId = assertPositiveInt(stackId, 'Stack ID');
|
|
629
|
+
const validEndpointId = assertPositiveInt(endpointId, 'Environment (Endpoint) ID');
|
|
630
|
+
return this.request<RawPortainerStack>({
|
|
631
|
+
method: 'PUT',
|
|
632
|
+
path: `/api/stacks/${encodeURIComponent(String(validStackId))}`,
|
|
633
|
+
query: { endpointId: validEndpointId },
|
|
634
|
+
body: {
|
|
635
|
+
stackFileContent: payload.stackFileContent,
|
|
636
|
+
env: payload.env,
|
|
637
|
+
prune: payload.prune,
|
|
638
|
+
pullImage: payload.repullImage,
|
|
639
|
+
},
|
|
640
|
+
timeoutMs: options?.timeoutMs,
|
|
641
|
+
signal: options?.signal,
|
|
642
|
+
});
|
|
643
|
+
}
|
|
644
|
+
|
|
645
|
+
async triggerWebhook(
|
|
646
|
+
webhookId: string,
|
|
647
|
+
tag?: string | null,
|
|
648
|
+
options?: { timeoutMs?: number; signal?: AbortSignal },
|
|
649
|
+
): Promise<unknown> {
|
|
650
|
+
const validWebhook = assertValidWebhookId(webhookId);
|
|
651
|
+
const trimmedTag = String(tag ?? '').trim();
|
|
652
|
+
return this.request<unknown>({
|
|
653
|
+
method: 'POST',
|
|
654
|
+
path: `/api/stacks/webhooks/${encodeURIComponent(validWebhook)}`,
|
|
655
|
+
query: trimmedTag ? { tag: trimmedTag } : undefined,
|
|
656
|
+
skipAuth: true,
|
|
657
|
+
timeoutMs: options?.timeoutMs,
|
|
658
|
+
signal: options?.signal,
|
|
659
|
+
});
|
|
660
|
+
}
|
|
661
|
+
|
|
662
|
+
async startStack(stackId: number, endpointId: number, signal?: AbortSignal): Promise<RawPortainerStack> {
|
|
663
|
+
const validStackId = assertPositiveInt(stackId, 'Stack ID');
|
|
664
|
+
const validEndpointId = assertPositiveInt(endpointId, 'Environment (Endpoint) ID');
|
|
665
|
+
return this.request<RawPortainerStack>({
|
|
666
|
+
method: 'POST',
|
|
667
|
+
path: `/api/stacks/${encodeURIComponent(String(validStackId))}/start`,
|
|
668
|
+
query: { endpointId: validEndpointId },
|
|
669
|
+
signal,
|
|
670
|
+
});
|
|
671
|
+
}
|
|
672
|
+
|
|
673
|
+
async stopStack(stackId: number, endpointId: number, signal?: AbortSignal): Promise<RawPortainerStack> {
|
|
674
|
+
const validStackId = assertPositiveInt(stackId, 'Stack ID');
|
|
675
|
+
const validEndpointId = assertPositiveInt(endpointId, 'Environment (Endpoint) ID');
|
|
676
|
+
return this.request<RawPortainerStack>({
|
|
677
|
+
method: 'POST',
|
|
678
|
+
path: `/api/stacks/${encodeURIComponent(String(validStackId))}/stop`,
|
|
679
|
+
query: { endpointId: validEndpointId },
|
|
680
|
+
signal,
|
|
681
|
+
});
|
|
682
|
+
}
|
|
683
|
+
|
|
684
|
+
/**
|
|
685
|
+
* Wait until an asynchronous Portainer deployment (`Status === 3`, Deploying) settles into Active (`1`),
|
|
686
|
+
* Inactive (`2`), or Error (`4`), throwing `PortainerApiError` when deployment fails.
|
|
687
|
+
*/
|
|
688
|
+
async waitForStackSettlement(
|
|
689
|
+
stackId: number,
|
|
690
|
+
initialStack: RawPortainerStack,
|
|
691
|
+
options?: { timeoutMs?: number; pollIntervalMs?: number; signal?: AbortSignal },
|
|
692
|
+
): Promise<RawPortainerStack> {
|
|
693
|
+
let current = initialStack;
|
|
694
|
+
const timeout = clampTimeoutMs(options?.timeoutMs, this.timeoutMs);
|
|
695
|
+
const pollInterval = Math.max(50, options?.pollIntervalMs ?? 1500);
|
|
696
|
+
const deadline = Date.now() + timeout;
|
|
697
|
+
|
|
698
|
+
while (Number(current?.Status) === 3) {
|
|
699
|
+
if (options?.signal?.aborted) {
|
|
700
|
+
throw new PortainerApiError('Portainer stack deployment aborted', { code: 'ECONNABORTED' });
|
|
701
|
+
}
|
|
702
|
+
if (Date.now() >= deadline) {
|
|
703
|
+
throw new PortainerApiError(`Timed out waiting for Portainer Stack #${stackId} deployment after ${timeout}ms`, {
|
|
704
|
+
code: 'ECONNABORTED',
|
|
705
|
+
});
|
|
706
|
+
}
|
|
707
|
+
await new Promise<void>((resolve, reject) => {
|
|
708
|
+
const timer = setTimeout(() => {
|
|
709
|
+
options?.signal?.removeEventListener('abort', onAbort);
|
|
710
|
+
resolve();
|
|
711
|
+
}, pollInterval);
|
|
712
|
+
function onAbort() {
|
|
713
|
+
clearTimeout(timer);
|
|
714
|
+
reject(new PortainerApiError('Portainer stack deployment aborted', { code: 'ECONNABORTED' }));
|
|
715
|
+
}
|
|
716
|
+
options?.signal?.addEventListener('abort', onAbort, { once: true });
|
|
717
|
+
});
|
|
718
|
+
current = await this.getRawStack(stackId, options?.signal);
|
|
719
|
+
}
|
|
720
|
+
|
|
721
|
+
if (Number(current?.Status) === 4) {
|
|
722
|
+
const entries = Array.isArray(current.DeploymentStatus) ? current.DeploymentStatus : [];
|
|
723
|
+
const lastError = [...entries].reverse().find((item) => item?.Status === 4 && item?.Message);
|
|
724
|
+
const message = lastError?.Message
|
|
725
|
+
? `Portainer deployment failed: ${lastError.Message}`
|
|
726
|
+
: `Portainer Stack #${stackId} entered error status`;
|
|
727
|
+
throw new PortainerApiError(message, { code: 'DEPLOYMENT_FAILED', status: 502 });
|
|
728
|
+
}
|
|
729
|
+
|
|
730
|
+
return current;
|
|
731
|
+
}
|
|
732
|
+
|
|
733
|
+
async listStackContainers(
|
|
734
|
+
endpointId: number,
|
|
735
|
+
stackName: string,
|
|
736
|
+
signal?: AbortSignal,
|
|
737
|
+
): Promise<PortainerContainerSummary[]> {
|
|
738
|
+
const validEndpointId = assertPositiveInt(endpointId, 'Environment (Endpoint) ID');
|
|
739
|
+
const trimmedName = String(stackName ?? '').trim();
|
|
740
|
+
if (!trimmedName) {
|
|
741
|
+
return [];
|
|
742
|
+
}
|
|
743
|
+
const filters = JSON.stringify({
|
|
744
|
+
label: [`com.docker.compose.project=${trimmedName}`],
|
|
745
|
+
});
|
|
746
|
+
const raw = await this.request<RawDockerContainer[]>({
|
|
747
|
+
method: 'GET',
|
|
748
|
+
path: `/api/endpoints/${encodeURIComponent(String(validEndpointId))}/docker/containers/json`,
|
|
749
|
+
query: { all: 1, filters },
|
|
750
|
+
signal,
|
|
751
|
+
});
|
|
752
|
+
if (!Array.isArray(raw)) {
|
|
753
|
+
return [];
|
|
754
|
+
}
|
|
755
|
+
return raw.map((container) => {
|
|
756
|
+
const state = String(container.State ?? 'unknown').toLowerCase();
|
|
757
|
+
const status = String(container.Status ?? '');
|
|
758
|
+
const unhealthy = /\(unhealthy\)/i.test(status) || state === 'restarting' || state === 'dead';
|
|
759
|
+
const firstName = Array.isArray(container.Names) && container.Names[0] ? container.Names[0] : '';
|
|
760
|
+
const service = container.Labels?.['com.docker.compose.service'];
|
|
761
|
+
|
|
762
|
+
const portsSet = new Set<string>();
|
|
763
|
+
if (Array.isArray(container.Ports)) {
|
|
764
|
+
for (const p of container.Ports) {
|
|
765
|
+
const proto = p.Type || 'tcp';
|
|
766
|
+
if (p.PublicPort && p.PrivatePort) {
|
|
767
|
+
const hostPrefix = p.IP ? `${p.IP}:` : '';
|
|
768
|
+
portsSet.add(`${hostPrefix}${p.PublicPort}->${p.PrivatePort}/${proto}`);
|
|
769
|
+
} else if (p.PrivatePort) {
|
|
770
|
+
portsSet.add(`${p.PrivatePort}/${proto}`);
|
|
771
|
+
}
|
|
772
|
+
}
|
|
773
|
+
}
|
|
774
|
+
|
|
775
|
+
const ipAddresses: string[] = [];
|
|
776
|
+
if (container.NetworkSettings?.Networks && typeof container.NetworkSettings.Networks === 'object') {
|
|
777
|
+
for (const net of Object.values(container.NetworkSettings.Networks)) {
|
|
778
|
+
if (net?.IPAddress && !ipAddresses.includes(net.IPAddress)) {
|
|
779
|
+
ipAddresses.push(net.IPAddress);
|
|
780
|
+
}
|
|
781
|
+
}
|
|
782
|
+
}
|
|
783
|
+
|
|
784
|
+
return {
|
|
785
|
+
id: String(container.Id ?? '').slice(0, 12),
|
|
786
|
+
name: firstName.replace(/^\/+/, ''),
|
|
787
|
+
service: service ? String(service) : undefined,
|
|
788
|
+
image: String(container.Image ?? ''),
|
|
789
|
+
state,
|
|
790
|
+
status,
|
|
791
|
+
healthy: state === 'running' && !unhealthy,
|
|
792
|
+
created: typeof container.Created === 'number' && container.Created > 0 ? container.Created : undefined,
|
|
793
|
+
ports: Array.from(portsSet),
|
|
794
|
+
ipAddresses,
|
|
795
|
+
};
|
|
796
|
+
});
|
|
797
|
+
}
|
|
798
|
+
|
|
799
|
+
async getContainerLiveStats(
|
|
800
|
+
endpointId: number,
|
|
801
|
+
containerId: string,
|
|
802
|
+
signal?: AbortSignal,
|
|
803
|
+
): Promise<PortainerContainerStats> {
|
|
804
|
+
const validEndpointId = assertPositiveInt(endpointId, 'Environment (Endpoint) ID');
|
|
805
|
+
const validContainerId = assertValidContainerId(containerId);
|
|
806
|
+
const raw = await this.request<RawDockerStats>({
|
|
807
|
+
method: 'GET',
|
|
808
|
+
path: `/api/endpoints/${encodeURIComponent(String(validEndpointId))}/docker/containers/${encodeURIComponent(
|
|
809
|
+
validContainerId,
|
|
810
|
+
)}/stats`,
|
|
811
|
+
query: { stream: 'false' },
|
|
812
|
+
timeoutMs: 10_000,
|
|
813
|
+
signal,
|
|
814
|
+
});
|
|
815
|
+
return computeDockerContainerStats(raw);
|
|
816
|
+
}
|
|
817
|
+
|
|
818
|
+
async getContainerLogs(endpointId: number, containerId: string, tail = 100, signal?: AbortSignal): Promise<string> {
|
|
819
|
+
const validEndpointId = assertPositiveInt(endpointId, 'Environment (Endpoint) ID');
|
|
820
|
+
const validContainerId = assertValidContainerId(containerId);
|
|
821
|
+
const clampedTail = Math.min(1000, Math.max(10, Math.trunc(Number(tail) || 100)));
|
|
822
|
+
const buf = await this.request<Buffer>({
|
|
823
|
+
method: 'GET',
|
|
824
|
+
path: `/api/endpoints/${encodeURIComponent(String(validEndpointId))}/docker/containers/${encodeURIComponent(
|
|
825
|
+
validContainerId,
|
|
826
|
+
)}/logs`,
|
|
827
|
+
query: {
|
|
828
|
+
stdout: 1,
|
|
829
|
+
stderr: 1,
|
|
830
|
+
tail: clampedTail,
|
|
831
|
+
timestamps: 1,
|
|
832
|
+
},
|
|
833
|
+
rawBuffer: true,
|
|
834
|
+
timeoutMs: 15_000,
|
|
835
|
+
signal,
|
|
836
|
+
});
|
|
837
|
+
return demuxDockerLogBuffer(buf);
|
|
838
|
+
}
|
|
839
|
+
}
|
|
840
|
+
|
|
841
|
+
export function summarizeContainersHealth(containers: PortainerContainerSummary[]) {
|
|
842
|
+
const totalCount = containers.length;
|
|
843
|
+
const runningCount = containers.filter((c) => c.state === 'running').length;
|
|
844
|
+
const healthy = totalCount > 0 && containers.every((c) => c.healthy);
|
|
845
|
+
return { totalCount, runningCount, healthy };
|
|
846
|
+
}
|