@ostro-cloud/cli 0.0.0-stage → 1.0.0-alpha.10
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/README.md +105 -2
- package/RELEASE_NOTES_v1.0.0-alpha.10.md +219 -0
- package/bin/ostro.js +233 -0
- package/lib/client.js +258 -0
- package/lib/commands/configure.js +35 -0
- package/lib/commands/deploy.js +61 -0
- package/lib/commands/formation.js +684 -0
- package/lib/commands/k8s.js +44 -0
- package/lib/commands/login.js +154 -0
- package/lib/commands/s3.js +88 -0
- package/lib/commands/serverless.js +104 -0
- package/lib/commands/status.js +41 -0
- package/lib/commands/tunnel.js +129 -0
- package/package.json +38 -5
|
@@ -0,0 +1,684 @@
|
|
|
1
|
+
const { getStoredConfig, resolveServiceUrl, request, buildHmacHeaders, resolveAuthTokenViaIam } = require('../client');
|
|
2
|
+
const fs = require('fs');
|
|
3
|
+
const path = require('path');
|
|
4
|
+
const os = require('os');
|
|
5
|
+
const http = require('http');
|
|
6
|
+
const https = require('https');
|
|
7
|
+
const { execSync } = require('child_process');
|
|
8
|
+
|
|
9
|
+
function parseParameters(paramInput) {
|
|
10
|
+
if (!paramInput) return {};
|
|
11
|
+
if (typeof paramInput === 'object' && !Array.isArray(paramInput)) return paramInput;
|
|
12
|
+
const params = {};
|
|
13
|
+
const entries = Array.isArray(paramInput) ? paramInput : String(paramInput).split(',');
|
|
14
|
+
for (const entry of entries) {
|
|
15
|
+
const eqIdx = entry.indexOf('=');
|
|
16
|
+
if (eqIdx > 0) {
|
|
17
|
+
const k = entry.slice(0, eqIdx).trim();
|
|
18
|
+
const v = entry.slice(eqIdx + 1).trim();
|
|
19
|
+
if (k) params[k] = v;
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
return params;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* POSTs a gzipped tar of sourceDir to the formation build API.
|
|
27
|
+
* Returns the built image ref (e.g. "prod/my-stack:v-123456").
|
|
28
|
+
*/
|
|
29
|
+
async function buildImageViaApi(formationUrl, stackName, sourceDir) {
|
|
30
|
+
console.log(`\x1b[36m📦 Uploading source for remote build [${stackName}]...\x1b[0m`);
|
|
31
|
+
|
|
32
|
+
const tarPath = path.join(os.tmpdir(), `ostro-build-${stackName}-${Date.now()}.tar.gz`);
|
|
33
|
+
execSync(
|
|
34
|
+
`tar -czf "${tarPath}" -C "${sourceDir}" .`,
|
|
35
|
+
{ stdio: 'pipe' }
|
|
36
|
+
);
|
|
37
|
+
|
|
38
|
+
const tarBuffer = fs.readFileSync(tarPath);
|
|
39
|
+
fs.unlinkSync(tarPath);
|
|
40
|
+
|
|
41
|
+
const config = getStoredConfig();
|
|
42
|
+
let authToken = config.sessionToken || config.token;
|
|
43
|
+
const hasAccessKeys = Boolean(config.accessKeyId && config.secretAccessKey);
|
|
44
|
+
if (!authToken) {
|
|
45
|
+
if (!hasAccessKeys) {
|
|
46
|
+
throw new Error('Authentication required. Run "ostro-cloud login" or set OSTRO_ACCESS_KEY_ID / OSTRO_SECRET_ACCESS_KEY / OSTRO_SESSION_TOKEN.');
|
|
47
|
+
}
|
|
48
|
+
authToken = await resolveAuthTokenViaIam(config);
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
// Use Node's http/https directly — global fetch (undici) rejects Node Buffers as binary body
|
|
52
|
+
const statusCode = await new Promise((resolve, reject) => {
|
|
53
|
+
const url = new URL(`${formationUrl}/api/builds`);
|
|
54
|
+
const transport = url.protocol === 'https:' ? https : http;
|
|
55
|
+
const req = transport.request({
|
|
56
|
+
hostname: url.hostname,
|
|
57
|
+
port: url.port || (url.protocol === 'https:' ? 443 : 80),
|
|
58
|
+
path: url.pathname + url.search,
|
|
59
|
+
method: 'POST',
|
|
60
|
+
headers: {
|
|
61
|
+
'Authorization': `Bearer ${authToken}`,
|
|
62
|
+
'X-Ostro-Session-Token': authToken,
|
|
63
|
+
'Content-Type': 'application/octet-stream',
|
|
64
|
+
'Accept': 'application/json',
|
|
65
|
+
'X-Stack-Name': stackName,
|
|
66
|
+
'Content-Length': String(tarBuffer.length),
|
|
67
|
+
},
|
|
68
|
+
}, (res) => {
|
|
69
|
+
const chunks = [];
|
|
70
|
+
res.on('data', (chunk) => chunks.push(chunk));
|
|
71
|
+
res.on('end', () => {
|
|
72
|
+
const body = Buffer.concat(chunks).toString('utf-8');
|
|
73
|
+
let data;
|
|
74
|
+
try {
|
|
75
|
+
data = (body.trimStart().startsWith('{') || body.trimStart().startsWith('[')) ? JSON.parse(body) : body;
|
|
76
|
+
} catch {
|
|
77
|
+
data = body;
|
|
78
|
+
}
|
|
79
|
+
if (res.statusCode < 200 || res.statusCode >= 300) {
|
|
80
|
+
const msg = (typeof data === 'object' ? (data?.message || data?.error || JSON.stringify(data)) : data) || `Build API HTTP ${res.statusCode}`;
|
|
81
|
+
return reject(new Error(msg));
|
|
82
|
+
}
|
|
83
|
+
const imageRef = (typeof data === 'object' ? (data?.image || data?.imageRef || data?.image_ref) : null);
|
|
84
|
+
if (!imageRef) return reject(new Error(`Build API did not return an image ref. Response: ${typeof data === 'object' ? JSON.stringify(data) : data}`));
|
|
85
|
+
console.log(`\x1b[32m✔ Image built: \x1b[33m${imageRef}\x1b[0m`);
|
|
86
|
+
resolve(imageRef);
|
|
87
|
+
});
|
|
88
|
+
});
|
|
89
|
+
req.on('error', reject);
|
|
90
|
+
req.write(tarBuffer);
|
|
91
|
+
req.end();
|
|
92
|
+
});
|
|
93
|
+
|
|
94
|
+
return statusCode;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function loadEnvParams(templateDir, effectiveParams) {
|
|
98
|
+
const dotEnvPath = path.join(templateDir, '.env');
|
|
99
|
+
if (!fs.existsSync(dotEnvPath)) return effectiveParams;
|
|
100
|
+
const envVars = {};
|
|
101
|
+
for (const line of fs.readFileSync(dotEnvPath, 'utf-8').split(/\r?\n/)) {
|
|
102
|
+
const m = line.match(/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)\s*$/);
|
|
103
|
+
if (m) envVars[m[1]] = m[2].replace(/^["']|["']$/g, '');
|
|
104
|
+
}
|
|
105
|
+
const envParamMap = {
|
|
106
|
+
AgentToken: envVars.AGENT_TOKEN,
|
|
107
|
+
AuthSecret: envVars.AUTH_SECRET,
|
|
108
|
+
AdminUsername: envVars.ADMIN_USERNAME,
|
|
109
|
+
AdminPasswordHash: envVars.ADMIN_PASSWORD_HASH,
|
|
110
|
+
};
|
|
111
|
+
const merged = { ...effectiveParams };
|
|
112
|
+
for (const [k, v] of Object.entries(envParamMap)) {
|
|
113
|
+
if (v && merged[k] === undefined) merged[k] = v;
|
|
114
|
+
}
|
|
115
|
+
return merged;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
async function validateTemplate(options = {}) {
|
|
119
|
+
const config = getStoredConfig();
|
|
120
|
+
const templatePath = options.template || (fs.existsSync('template.yaml') ? 'template.yaml' : (fs.existsSync('template.yml') ? 'template.yml' : null));
|
|
121
|
+
if (!templatePath) {
|
|
122
|
+
console.error('\x1b[31m✖ Template file path is required. Pass --template <file> or place template.yaml in current directory.\x1b[0m');
|
|
123
|
+
return;
|
|
124
|
+
}
|
|
125
|
+
if (!fs.existsSync(templatePath)) {
|
|
126
|
+
console.error(`\x1b[31m✖ Template file not found:\x1b[0m ${templatePath}`);
|
|
127
|
+
return;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
const region = options.region || config.region || null;
|
|
131
|
+
const regionLabel = region ? ` (${region})` : '';
|
|
132
|
+
console.log(`\x1b[36m🔍 Validating Ostro Formation Template: \x1b[33m${templatePath}\x1b[36m${regionLabel}...\x1b[0m`);
|
|
133
|
+
|
|
134
|
+
const yamlContent = fs.readFileSync(templatePath, 'utf-8');
|
|
135
|
+
const formationUrl = resolveServiceUrl('formation', options.formationUrl);
|
|
136
|
+
const templateDir = path.dirname(path.resolve(templatePath));
|
|
137
|
+
const stackName = options.stackName || path.basename(process.cwd());
|
|
138
|
+
|
|
139
|
+
let effectiveParams = parseParameters(options.parameters);
|
|
140
|
+
if (typeof effectiveParams === 'string') {
|
|
141
|
+
try { effectiveParams = JSON.parse(effectiveParams); } catch { effectiveParams = {}; }
|
|
142
|
+
}
|
|
143
|
+
effectiveParams = loadEnvParams(templateDir, effectiveParams);
|
|
144
|
+
|
|
145
|
+
const codeUriMatch = yamlContent.match(/^\s*(?:CodeUri|BuildContext)\s*:\s*['"]?([^\s'"#]+)['"]?/m);
|
|
146
|
+
const codeUriDir = codeUriMatch ? path.resolve(templateDir, codeUriMatch[1]) : null;
|
|
147
|
+
const buildContextDir = (codeUriDir && fs.existsSync(codeUriDir))
|
|
148
|
+
? codeUriDir
|
|
149
|
+
: (fs.existsSync(path.join(templateDir, 'Dockerfile'))
|
|
150
|
+
? templateDir
|
|
151
|
+
: (fs.existsSync(path.join(process.cwd(), 'Dockerfile')) ? process.cwd() : null));
|
|
152
|
+
|
|
153
|
+
if (options.image) {
|
|
154
|
+
effectiveParams = { ...effectiveParams, Image: options.image };
|
|
155
|
+
} else if (buildContextDir && options.build !== false && !options.skipBuild) {
|
|
156
|
+
try {
|
|
157
|
+
const imageRef = await buildImageViaApi(formationUrl, stackName, buildContextDir);
|
|
158
|
+
effectiveParams = { ...effectiveParams, Image: imageRef };
|
|
159
|
+
} catch (err) {
|
|
160
|
+
console.error(`\x1b[31m✖ Remote build failed:\x1b[0m`, err.message);
|
|
161
|
+
return;
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
const parameters = parseParameters(options.parameters);
|
|
166
|
+
|
|
167
|
+
try {
|
|
168
|
+
const queryParams = new URLSearchParams();
|
|
169
|
+
if (region) queryParams.set('region', region);
|
|
170
|
+
const queryStr = queryParams.toString() ? `?${queryParams.toString()}` : '';
|
|
171
|
+
|
|
172
|
+
const result = await request(`${formationUrl}/api/templates/validate${queryStr}`, {
|
|
173
|
+
method: 'POST',
|
|
174
|
+
body: JSON.stringify({ template: yamlContent, parameters })
|
|
175
|
+
});
|
|
176
|
+
|
|
177
|
+
if (result.valid) {
|
|
178
|
+
console.log(`\x1b[32m✔ Template syntax, parameters, and all resource schemas are VALID!\x1b[0m`);
|
|
179
|
+
if (result.description) console.log(` Description: \x1b[90m${result.description}\x1b[0m`);
|
|
180
|
+
if (result.parameters?.length > 0) console.log(` Parameters (${result.parameters.length}): \x1b[33m${result.parameters.join(', ')}\x1b[0m`);
|
|
181
|
+
if (result.resources?.length > 0) {
|
|
182
|
+
console.log(`\n \x1b[1mValidated Resources (${result.resources.length}):\x1b[0m`);
|
|
183
|
+
result.resources.forEach((r, idx) => {
|
|
184
|
+
console.log(` ${String(idx + 1).padStart(2)}. \x1b[36m${(r.logicalId || '').padEnd(25)}\x1b[0m \x1b[33m${r.type}\x1b[0m`);
|
|
185
|
+
});
|
|
186
|
+
}
|
|
187
|
+
console.log('');
|
|
188
|
+
} else {
|
|
189
|
+
console.error(`\x1b[31m✖ Template validation failed:\x1b[0m`, result.message || 'Unknown error');
|
|
190
|
+
}
|
|
191
|
+
} catch (err) {
|
|
192
|
+
console.error(`\x1b[31m✖ Template validation FAILED:\x1b[0m`, err.message);
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
async function createStack(options = {}) {
|
|
197
|
+
const config = getStoredConfig();
|
|
198
|
+
if (!options.stackName) {
|
|
199
|
+
console.error('\x1b[31m✖ Stack name is required. Pass --stack-name <name>.\x1b[0m');
|
|
200
|
+
return;
|
|
201
|
+
}
|
|
202
|
+
const templatePath = options.template || (fs.existsSync('template.yaml') ? 'template.yaml' : (fs.existsSync('template.yml') ? 'template.yml' : null));
|
|
203
|
+
if (!templatePath) {
|
|
204
|
+
console.error('\x1b[31m✖ Template file path is required. Pass --template <file> or place template.yaml in current directory.\x1b[0m');
|
|
205
|
+
return;
|
|
206
|
+
}
|
|
207
|
+
if (!fs.existsSync(templatePath)) {
|
|
208
|
+
console.error(`\x1b[31m✖ Template file not found:\x1b[0m ${templatePath}`);
|
|
209
|
+
return;
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
const stackName = options.stackName;
|
|
213
|
+
const region = options.region || config.region || null;
|
|
214
|
+
const regionLabel = region ? ` (${region})` : '';
|
|
215
|
+
console.log(`\x1b[36m🚀 Creating Ostro Formation Stack [${stackName}]${regionLabel}...\x1b[0m`);
|
|
216
|
+
|
|
217
|
+
const yamlContent = fs.readFileSync(templatePath, 'utf-8');
|
|
218
|
+
const formationUrl = resolveServiceUrl('formation', options.formationUrl);
|
|
219
|
+
const templateDir = path.dirname(path.resolve(templatePath));
|
|
220
|
+
|
|
221
|
+
let effectiveParams = parseParameters(options.parameters);
|
|
222
|
+
if (typeof effectiveParams === 'string') {
|
|
223
|
+
try { effectiveParams = JSON.parse(effectiveParams); } catch { effectiveParams = {}; }
|
|
224
|
+
}
|
|
225
|
+
effectiveParams = loadEnvParams(templateDir, effectiveParams);
|
|
226
|
+
|
|
227
|
+
const codeUriMatch = yamlContent.match(/^\s*(?:CodeUri|BuildContext)\s*:\s*['"]?([^\s'"#]+)['"]?/m);
|
|
228
|
+
const codeUriDir = codeUriMatch ? path.resolve(templateDir, codeUriMatch[1]) : null;
|
|
229
|
+
const buildContextDir = (codeUriDir && fs.existsSync(codeUriDir))
|
|
230
|
+
? codeUriDir
|
|
231
|
+
: (fs.existsSync(path.join(templateDir, 'Dockerfile'))
|
|
232
|
+
? templateDir
|
|
233
|
+
: (fs.existsSync(path.join(process.cwd(), 'Dockerfile')) ? process.cwd() : null));
|
|
234
|
+
|
|
235
|
+
if (options.image) {
|
|
236
|
+
effectiveParams = { ...effectiveParams, Image: options.image };
|
|
237
|
+
} else if (buildContextDir && options.build !== false && !options.skipBuild) {
|
|
238
|
+
try {
|
|
239
|
+
const imageRef = await buildImageViaApi(formationUrl, stackName, buildContextDir);
|
|
240
|
+
effectiveParams = { ...effectiveParams, Image: imageRef };
|
|
241
|
+
} catch (err) {
|
|
242
|
+
console.error(`\x1b[31m✖ Remote build failed:\x1b[0m`, err.message);
|
|
243
|
+
return;
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
const parameters = parseParameters(options.parameters);
|
|
248
|
+
|
|
249
|
+
try {
|
|
250
|
+
const queryParams = new URLSearchParams();
|
|
251
|
+
if (region) queryParams.set('region', region);
|
|
252
|
+
const queryStr = queryParams.toString() ? `?${queryParams.toString()}` : '';
|
|
253
|
+
|
|
254
|
+
const result = await request(`${formationUrl}/api/stacks${queryStr}`, {
|
|
255
|
+
method: 'POST',
|
|
256
|
+
body: JSON.stringify({
|
|
257
|
+
name: stackName,
|
|
258
|
+
template: yamlContent,
|
|
259
|
+
parameters,
|
|
260
|
+
disableRollback: !!options.disableRollback,
|
|
261
|
+
terminationProtection: !!options.terminationProtection,
|
|
262
|
+
roleArn: options.roleArn || undefined,
|
|
263
|
+
allowUpdate: false
|
|
264
|
+
})
|
|
265
|
+
});
|
|
266
|
+
|
|
267
|
+
if (result.success === false) throw new Error(result.error || result.message || 'Stack creation failed');
|
|
268
|
+
|
|
269
|
+
console.log(`\x1b[32m✔ Stack [${stackName}] creation initiated successfully!\x1b[0m`);
|
|
270
|
+
console.log(` Stack ID: \x1b[33m${result.id || `arn:ostro:cloudformation:stack/${stackName}`}\x1b[0m`);
|
|
271
|
+
console.log(` Status: \x1b[32m${result.status || 'CREATE_IN_PROGRESS'}\x1b[0m\n`);
|
|
272
|
+
} catch (err) {
|
|
273
|
+
console.error(`\x1b[31m✖ Stack creation failed:\x1b[0m`, err.message);
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
async function deployStack(options = {}) {
|
|
278
|
+
const config = getStoredConfig();
|
|
279
|
+
if (!options.stackName) throw new Error('Stack name is required. Pass --stack-name <name>.');
|
|
280
|
+
if (!options.template) throw new Error('Template file path is required. Pass --template <file>.');
|
|
281
|
+
|
|
282
|
+
const stackName = options.stackName;
|
|
283
|
+
const templatePath = options.template;
|
|
284
|
+
const region = options.region || config.region || null;
|
|
285
|
+
const regionLabel = region ? ` (${region})` : '';
|
|
286
|
+
console.log(`\x1b[36m⚡ Deploying Ostro Formation Stack [${stackName}]${regionLabel}...\x1b[0m`);
|
|
287
|
+
|
|
288
|
+
if (!fs.existsSync(templatePath)) {
|
|
289
|
+
console.error(`\x1b[31m✖ Template file not found:\x1b[0m ${templatePath}`);
|
|
290
|
+
return;
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
const yamlContent = fs.readFileSync(templatePath, 'utf-8');
|
|
294
|
+
const formationUrl = resolveServiceUrl('formation', options.formationUrl);
|
|
295
|
+
const templateDir = path.dirname(path.resolve(templatePath));
|
|
296
|
+
|
|
297
|
+
let effectiveParams = parseParameters(options.parameters);
|
|
298
|
+
if (typeof effectiveParams === 'string') {
|
|
299
|
+
try { effectiveParams = JSON.parse(effectiveParams); } catch { effectiveParams = {}; }
|
|
300
|
+
}
|
|
301
|
+
effectiveParams = loadEnvParams(templateDir, effectiveParams);
|
|
302
|
+
|
|
303
|
+
const codeUriMatch = yamlContent.match(/^\s*(?:CodeUri|BuildContext)\s*:\s*['"]?([^\s'"#]+)['"]?/m);
|
|
304
|
+
const codeUriDir = codeUriMatch ? path.resolve(templateDir, codeUriMatch[1]) : null;
|
|
305
|
+
const buildContextDir = (codeUriDir && fs.existsSync(codeUriDir))
|
|
306
|
+
? codeUriDir
|
|
307
|
+
: (fs.existsSync(path.join(templateDir, 'Dockerfile'))
|
|
308
|
+
? templateDir
|
|
309
|
+
: (fs.existsSync(path.join(process.cwd(), 'Dockerfile')) ? process.cwd() : null));
|
|
310
|
+
|
|
311
|
+
if (options.image) {
|
|
312
|
+
effectiveParams = { ...effectiveParams, Image: options.image };
|
|
313
|
+
} else if (buildContextDir && options.build !== false && !options.skipBuild) {
|
|
314
|
+
try {
|
|
315
|
+
const imageRef = await buildImageViaApi(formationUrl, stackName, buildContextDir);
|
|
316
|
+
effectiveParams = { ...effectiveParams, Image: imageRef };
|
|
317
|
+
} catch (err) {
|
|
318
|
+
console.error(`\x1b[31m✖ Remote build failed:\x1b[0m`, err.message);
|
|
319
|
+
return;
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
try {
|
|
324
|
+
const queryParams = new URLSearchParams();
|
|
325
|
+
if (region) queryParams.set('region', region);
|
|
326
|
+
const queryStr = queryParams.toString() ? `?${queryParams.toString()}` : '';
|
|
327
|
+
|
|
328
|
+
let result;
|
|
329
|
+
try {
|
|
330
|
+
result = await request(`${formationUrl}/api/stacks${queryStr}`, {
|
|
331
|
+
method: 'POST',
|
|
332
|
+
body: JSON.stringify({
|
|
333
|
+
name: stackName,
|
|
334
|
+
template: yamlContent,
|
|
335
|
+
parameters: effectiveParams,
|
|
336
|
+
...(region ? { region } : {}),
|
|
337
|
+
allowUpdate: true
|
|
338
|
+
})
|
|
339
|
+
});
|
|
340
|
+
} catch (innerErr) {
|
|
341
|
+
const isSizeError = /too large|413|size limit|exceed/i.test(innerErr.message || '');
|
|
342
|
+
if (isSizeError) {
|
|
343
|
+
throw new Error(`Template too large for direct deploy.\n Run: ostro formation package -t ${templatePath} --s3-bucket <bucket>\n Then: ostro formation deploy -t <packaged.yaml> -s ${stackName}`);
|
|
344
|
+
}
|
|
345
|
+
throw innerErr;
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
if (!result.success && result.message) throw new Error(result.message);
|
|
349
|
+
|
|
350
|
+
const stackId = result.id || stackName;
|
|
351
|
+
const isUpdate = String(result.status || '').startsWith('UPDATE');
|
|
352
|
+
console.log(` Waiting for stack ${isUpdate ? 'update' : 'create'} to complete...`);
|
|
353
|
+
|
|
354
|
+
const final = await waitForStack(formationUrl, stackId, stackName);
|
|
355
|
+
const finalStatus = final.status || result.status || 'UNKNOWN';
|
|
356
|
+
|
|
357
|
+
if (/FAILED|ROLLBACK/.test(finalStatus)) {
|
|
358
|
+
throw new Error(`Stack [${stackName}] finished in state ${finalStatus}.\n Run: ostro formation describe ${stackName}`);
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
const verb = finalStatus.startsWith('UPDATE') ? 'updated' : 'created';
|
|
362
|
+
console.log(`\x1b[32m✔ Successfully ${verb} stack - ${stackName}\x1b[0m`);
|
|
363
|
+
console.log(` ARN: \x1b[33m${final.id || stackId}\x1b[0m`);
|
|
364
|
+
console.log(` Status: \x1b[32m${finalStatus}\x1b[0m`);
|
|
365
|
+
const resources = final.resources || result.resources;
|
|
366
|
+
if (resources?.length > 0) {
|
|
367
|
+
console.log(`\n \x1b[1mResources (${resources.length}):\x1b[0m`);
|
|
368
|
+
resources.forEach(r => {
|
|
369
|
+
console.log(` ✔ \x1b[36m${r.logical_id.padEnd(25)}\x1b[0m \x1b[33m${r.type.padEnd(30)}\x1b[0m → \x1b[32m${r.physical_id}\x1b[0m`);
|
|
370
|
+
});
|
|
371
|
+
}
|
|
372
|
+
console.log('');
|
|
373
|
+
} catch (err) {
|
|
374
|
+
console.error(`\x1b[31m✖ Stack deployment failed:\x1b[0m`, err.message);
|
|
375
|
+
process.exitCode = 1;
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
// Polls the Formation API until the stack reaches a terminal state (AWS CLI `deploy` semantics).
|
|
380
|
+
async function waitForStack(formationUrl, stackId, stackName, { timeoutMs = 600000, intervalMs = 3000 } = {}) {
|
|
381
|
+
const deadline = Date.now() + timeoutMs;
|
|
382
|
+
let last = null;
|
|
383
|
+
while (Date.now() < deadline) {
|
|
384
|
+
await new Promise(r => setTimeout(r, intervalMs));
|
|
385
|
+
try {
|
|
386
|
+
const res = await request(`${formationUrl}/api/stacks`);
|
|
387
|
+
const list = res.data || res;
|
|
388
|
+
const stack = (list || []).find(s => s.id === stackId || s.name === stackName);
|
|
389
|
+
if (stack) {
|
|
390
|
+
last = stack;
|
|
391
|
+
if (!String(stack.status || '').endsWith('_IN_PROGRESS')) return stack;
|
|
392
|
+
}
|
|
393
|
+
} catch {
|
|
394
|
+
// transient poll failure — keep waiting until the deadline
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
throw new Error(`Timed out waiting for stack [${stackName}] to reach a terminal state (last status: ${last?.status || 'unknown'}).`);
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
async function listStacks(options = {}) {
|
|
401
|
+
const config = getStoredConfig();
|
|
402
|
+
const region = options.region || config.region || null;
|
|
403
|
+
const headerStr = region ? ` [REGION: ${region}]` : '';
|
|
404
|
+
console.log(`\x1b[36m⚡ Ostro Formation Stacks${headerStr}\x1b[0m\n`);
|
|
405
|
+
|
|
406
|
+
try {
|
|
407
|
+
const formationUrl = resolveServiceUrl('formation', options.formationUrl);
|
|
408
|
+
const queryParams = new URLSearchParams();
|
|
409
|
+
if (region) queryParams.set('region', region);
|
|
410
|
+
const queryStr = queryParams.toString() ? `?${queryParams.toString()}` : '';
|
|
411
|
+
|
|
412
|
+
const res = await request(`${formationUrl}/api/stacks${queryStr}`);
|
|
413
|
+
const list = res.data || res;
|
|
414
|
+
if (!Array.isArray(list) || list.length === 0) {
|
|
415
|
+
console.log(` \x1b[33m(No stacks found)\x1b[0m`);
|
|
416
|
+
return;
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
console.log(` ${'STACK NAME'.padEnd(35)} ${'STATUS'.padEnd(20)} ${'CREATED'}`);
|
|
420
|
+
console.log(` ${'-'.repeat(75)}`);
|
|
421
|
+
list.forEach(s => {
|
|
422
|
+
console.log(` \x1b[32m${s.name.padEnd(35)}\x1b[0m \x1b[33m${(s.status || 'CREATE_COMPLETE').padEnd(20)}\x1b[0m ${s.created_at || s.createdAt || 'N/A'}`);
|
|
423
|
+
});
|
|
424
|
+
console.log(`\n Total: ${list.length} stack(s) active`);
|
|
425
|
+
} catch (err) {
|
|
426
|
+
console.error(`\x1b[31m✖ Error fetching stacks:\x1b[0m`, err.message);
|
|
427
|
+
}
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
async function describeStack(stackName, options = {}) {
|
|
431
|
+
try {
|
|
432
|
+
const formationUrl = resolveServiceUrl('formation', options.formationUrl);
|
|
433
|
+
const res = await request(`${formationUrl}/api/stacks`);
|
|
434
|
+
const list = res.data || res;
|
|
435
|
+
const stack = (list || []).find(s => s.name === stackName || s.id === stackName);
|
|
436
|
+
if (!stack) {
|
|
437
|
+
console.error(`\x1b[31m✖ Stack not found:\x1b[0m ${stackName}`);
|
|
438
|
+
return;
|
|
439
|
+
}
|
|
440
|
+
console.log(`\x1b[36m📑 Ostro Formation Stack: ${stack.name}\x1b[0m`);
|
|
441
|
+
console.log(` ARN: \x1b[33m${stack.id}\x1b[0m`);
|
|
442
|
+
console.log(` Status: \x1b[32m${stack.status}\x1b[0m`);
|
|
443
|
+
console.log(` Drift: ${stack.drift_status || 'IN_SYNC'}`);
|
|
444
|
+
console.log(` Created: ${stack.created_at}\n`);
|
|
445
|
+
} catch (err) {
|
|
446
|
+
console.error(`\x1b[31m✖ Error describing stack:\x1b[0m`, err.message);
|
|
447
|
+
}
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
async function deleteStack(stackName, options = {}) {
|
|
451
|
+
console.log(`\x1b[31m🗑 Deleting Ostro Formation Stack [${stackName}]...\x1b[0m`);
|
|
452
|
+
try {
|
|
453
|
+
const formationUrl = resolveServiceUrl('formation', options.formationUrl);
|
|
454
|
+
const res = await request(`${formationUrl}/api/stacks`);
|
|
455
|
+
const list = res.data || res;
|
|
456
|
+
const stack = (list || []).find(s => s.name === stackName || s.id === stackName);
|
|
457
|
+
if (!stack) {
|
|
458
|
+
console.error(`\x1b[31m✖ Stack not found:\x1b[0m ${stackName}`);
|
|
459
|
+
return;
|
|
460
|
+
}
|
|
461
|
+
await request(`${formationUrl}/api/stacks/${encodeURIComponent(stack.id)}`, { method: 'DELETE' });
|
|
462
|
+
console.log(`\x1b[32m✔ Stack [${stackName}] deleted successfully.\x1b[0m\n`);
|
|
463
|
+
} catch (err) {
|
|
464
|
+
console.error(`\x1b[31m✖ Stack deletion failed:\x1b[0m`, err.message);
|
|
465
|
+
}
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
// ---------------------------------------------------------------------------
|
|
469
|
+
// S3 packaging (like `aws cloudformation package`)
|
|
470
|
+
// Scans template for local Code/Content/Source paths, zips+uploads to S3,
|
|
471
|
+
// and rewrites them as s3:// URIs in an output template.
|
|
472
|
+
//
|
|
473
|
+
// Auto-select strategy (error-based, mirroring AWS CLI behaviour):
|
|
474
|
+
// - deployStack tries direct inline POST first
|
|
475
|
+
// - If API returns 413 or a "too large" error, it auto-calls packageAndDeploy
|
|
476
|
+
// which uploads the template body to S3 and redeploys using the S3 URI
|
|
477
|
+
// ---------------------------------------------------------------------------
|
|
478
|
+
|
|
479
|
+
async function _uploadToS3(s3Url, authToken, s3Bucket, s3Key, fileBuffer) {
|
|
480
|
+
const uploadUrl = `${s3Url}/api/s3/${encodeURIComponent(s3Bucket)}/${encodeURIComponent(s3Key)}`;
|
|
481
|
+
const res = await fetch(uploadUrl, {
|
|
482
|
+
method: 'PUT',
|
|
483
|
+
headers: {
|
|
484
|
+
'Authorization': `Bearer ${authToken}`,
|
|
485
|
+
'X-Ostro-Session-Token': authToken,
|
|
486
|
+
'Content-Type': 'application/octet-stream',
|
|
487
|
+
},
|
|
488
|
+
body: fileBuffer,
|
|
489
|
+
});
|
|
490
|
+
if (!res.ok) {
|
|
491
|
+
const txt = await res.text().catch(() => `HTTP ${res.status}`);
|
|
492
|
+
throw new Error(`S3 upload failed (${res.status}): ${txt}`);
|
|
493
|
+
}
|
|
494
|
+
return `s3://${s3Bucket}/${s3Key}`;
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
async function packageStack(options = {}) {
|
|
498
|
+
const config = getStoredConfig();
|
|
499
|
+
const templatePath = options.template || (fs.existsSync('template.yaml') ? 'template.yaml' : (fs.existsSync('template.yml') ? 'template.yml' : null));
|
|
500
|
+
if (!templatePath) {
|
|
501
|
+
console.error('\x1b[31m✖ Template file required. Pass --template <file> or place template.yaml in current directory.\x1b[0m');
|
|
502
|
+
process.exitCode = 1;
|
|
503
|
+
return;
|
|
504
|
+
}
|
|
505
|
+
if (!fs.existsSync(templatePath)) {
|
|
506
|
+
console.error(`\x1b[31m✖ Template file not found:\x1b[0m ${templatePath}`);
|
|
507
|
+
process.exitCode = 1;
|
|
508
|
+
return;
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
const s3Bucket = options.s3Bucket;
|
|
512
|
+
const s3Prefix = (options.s3Prefix || 'ostro-formation').replace(/\/+$/, '');
|
|
513
|
+
const outputTemplate = options.outputTemplate || templatePath.replace(/\.(yaml|yml|json)$/, '-packaged.$1');
|
|
514
|
+
|
|
515
|
+
if (!s3Bucket) {
|
|
516
|
+
console.error('\x1b[31m✖ S3 bucket required. Pass --s3-bucket <bucket>.\x1b[0m');
|
|
517
|
+
process.exitCode = 1;
|
|
518
|
+
return;
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
const authToken = config.sessionToken || config.token;
|
|
522
|
+
if (!authToken) throw new Error('Authentication required. Run "ostro-cloud login".');
|
|
523
|
+
|
|
524
|
+
const s3Url = resolveServiceUrl('storage', options.s3Url);
|
|
525
|
+
const templateDir = path.dirname(path.resolve(templatePath));
|
|
526
|
+
let yamlContent = fs.readFileSync(templatePath, 'utf-8');
|
|
527
|
+
|
|
528
|
+
console.log(`\x1b[36m📦 Packaging Ostro Formation template: \x1b[33m${templatePath}\x1b[0m`);
|
|
529
|
+
console.log(` S3 bucket: \x1b[33ms3://${s3Bucket}/${s3Prefix}/\x1b[0m\n`);
|
|
530
|
+
|
|
531
|
+
// Fail fast if the target bucket does not exist (AWS CLI package semantics).
|
|
532
|
+
try {
|
|
533
|
+
const res = await request(`${s3Url}/api/s3/buckets`);
|
|
534
|
+
const buckets = res.data || res;
|
|
535
|
+
if (!Array.isArray(buckets)) {
|
|
536
|
+
throw new Error('Unexpected response from the storage service while listing buckets.');
|
|
537
|
+
}
|
|
538
|
+
const found = buckets.some(b => (b.name || b.Name || b.bucket_name) === s3Bucket);
|
|
539
|
+
if (!found) {
|
|
540
|
+
const names = buckets.map(b => b.name || b.Name || b.bucket_name).filter(Boolean);
|
|
541
|
+
console.error(`\x1b[31m✖ S3 bucket not found: \x1b[33m${s3Bucket}\x1b[0m`);
|
|
542
|
+
console.error(` Available buckets: ${names.length ? names.join(', ') : '(none)'}`);
|
|
543
|
+
console.error(` Create the bucket in the Ostro Bucket console, then re-run this command.`);
|
|
544
|
+
process.exitCode = 1;
|
|
545
|
+
return;
|
|
546
|
+
}
|
|
547
|
+
} catch (err) {
|
|
548
|
+
console.error(`\x1b[31m✖ Could not verify S3 bucket [${s3Bucket}]:\x1b[0m`, err.message);
|
|
549
|
+
process.exitCode = 1;
|
|
550
|
+
return;
|
|
551
|
+
}
|
|
552
|
+
|
|
553
|
+
// Find local path references in the template (Code:, Content:, Source: patterns)
|
|
554
|
+
const localPathRe = /^(\s+(?:Code|Content|Source|Handler|Filename):\s+)(\.\/[^\s]+|[^s][^\s]*\/[^\s]*)$/gm;
|
|
555
|
+
const replacements = [];
|
|
556
|
+
let match;
|
|
557
|
+
while ((match = localPathRe.exec(yamlContent)) !== null) {
|
|
558
|
+
const localPath = match[2].trim();
|
|
559
|
+
const absPath = path.resolve(templateDir, localPath);
|
|
560
|
+
if (fs.existsSync(absPath)) {
|
|
561
|
+
replacements.push({ full: match[0], prefix: match[1], localPath, absPath });
|
|
562
|
+
}
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
if (replacements.length === 0) {
|
|
566
|
+
console.log('\x1b[33m No local artifact paths found. Template requires no packaging.\x1b[0m');
|
|
567
|
+
fs.copyFileSync(templatePath, outputTemplate);
|
|
568
|
+
console.log(`\x1b[32m✔ Output template written to: \x1b[33m${outputTemplate}\x1b[0m`);
|
|
569
|
+
return;
|
|
570
|
+
}
|
|
571
|
+
|
|
572
|
+
const timestamp = Date.now();
|
|
573
|
+
for (const rep of replacements) {
|
|
574
|
+
const isDir = fs.statSync(rep.absPath).isDirectory();
|
|
575
|
+
let fileBuffer;
|
|
576
|
+
const s3Key = `${s3Prefix}/${timestamp}/${path.basename(rep.localPath)}.zip`;
|
|
577
|
+
|
|
578
|
+
if (isDir) {
|
|
579
|
+
const zipPath = path.join(os.tmpdir(), `ostro-pkg-${timestamp}-${path.basename(rep.localPath)}.zip`);
|
|
580
|
+
execSync(`cd "${rep.absPath}" && zip -r "${zipPath}" . --exclude "*.ts" --exclude "node_modules/*" --exclude ".git/*"`, { stdio: 'pipe' });
|
|
581
|
+
fileBuffer = fs.readFileSync(zipPath);
|
|
582
|
+
fs.unlinkSync(zipPath);
|
|
583
|
+
} else {
|
|
584
|
+
fileBuffer = fs.readFileSync(rep.absPath);
|
|
585
|
+
}
|
|
586
|
+
|
|
587
|
+
const sizeKB = (fileBuffer.length / 1024).toFixed(1);
|
|
588
|
+
process.stdout.write(` Uploading \x1b[36m${rep.localPath}\x1b[0m (${sizeKB} KB)... `);
|
|
589
|
+
const s3Uri = await _uploadToS3(s3Url, authToken, s3Bucket, s3Key, fileBuffer);
|
|
590
|
+
console.log(`\x1b[32m✔\x1b[0m \x1b[33m${s3Uri}\x1b[0m`);
|
|
591
|
+
|
|
592
|
+
yamlContent = yamlContent.replace(rep.full, `${rep.prefix}${s3Uri}`);
|
|
593
|
+
}
|
|
594
|
+
|
|
595
|
+
fs.writeFileSync(outputTemplate, yamlContent, 'utf-8');
|
|
596
|
+
console.log(`\n\x1b[32m✔ Packaged template written to: \x1b[33m${outputTemplate}\x1b[0m`);
|
|
597
|
+
console.log(` Use this template for deployment:\n \x1b[90mostro formation deploy -t ${outputTemplate} -s <stack-name>\x1b[0m\n`);
|
|
598
|
+
}
|
|
599
|
+
|
|
600
|
+
// ---------------------------------------------------------------------------
|
|
601
|
+
// Local build + SSH deploy (OPS-08 / OPS-09)
|
|
602
|
+
// Build order: UI (vite) → ostro-build → rsync .dist/ to server root
|
|
603
|
+
// ---------------------------------------------------------------------------
|
|
604
|
+
|
|
605
|
+
async function buildAndDeployService(serviceDir, options = {}) {
|
|
606
|
+
const targetHost = options.host || process.env.OSTRO_DEPLOY_HOST;
|
|
607
|
+
if (!targetHost) {
|
|
608
|
+
throw new Error('SSH target host is required. Pass --host <user@host> or set OSTRO_DEPLOY_HOST.');
|
|
609
|
+
}
|
|
610
|
+
const remoteBase = options.remotePath || process.env.OSTRO_REMOTE_PATH || '/opt/ostro-cloud';
|
|
611
|
+
const svcName = path.basename(path.resolve(serviceDir));
|
|
612
|
+
const remoteDest = `${targetHost}:${remoteBase}/${svcName}/`;
|
|
613
|
+
|
|
614
|
+
console.log(`\x1b[36m🔨 Building \x1b[33m${svcName}\x1b[36m then deploying to \x1b[33m${remoteDest}\x1b[0m\n`);
|
|
615
|
+
|
|
616
|
+
const absDir = path.resolve(serviceDir);
|
|
617
|
+
if (!fs.existsSync(absDir)) {
|
|
618
|
+
console.error(`\x1b[31m✖ Service directory not found:\x1b[0m ${absDir}`);
|
|
619
|
+
return;
|
|
620
|
+
}
|
|
621
|
+
|
|
622
|
+
const pkgJson = path.join(absDir, 'package.json');
|
|
623
|
+
if (!fs.existsSync(pkgJson)) {
|
|
624
|
+
console.error(`\x1b[31m✖ No package.json in:\x1b[0m ${absDir}`);
|
|
625
|
+
return;
|
|
626
|
+
}
|
|
627
|
+
|
|
628
|
+
let pkg;
|
|
629
|
+
try { pkg = JSON.parse(fs.readFileSync(pkgJson, 'utf-8')); } catch { pkg = { scripts: {} }; }
|
|
630
|
+
const scripts = pkg.scripts || {};
|
|
631
|
+
|
|
632
|
+
// Step 1: UI build first (vite) if present — ostro-build auto-clones public/static
|
|
633
|
+
const hasVite = scripts.production || scripts.prod || scripts.development;
|
|
634
|
+
if (hasVite && !options.skipUi) {
|
|
635
|
+
console.log(' \x1b[36m[1/2]\x1b[0m Building UI (vite)...');
|
|
636
|
+
try {
|
|
637
|
+
execSync('npm run prod', { cwd: absDir, stdio: 'inherit' });
|
|
638
|
+
console.log(' \x1b[32m✔ UI build done\x1b[0m');
|
|
639
|
+
} catch (err) {
|
|
640
|
+
console.error('\x1b[31m✖ UI build failed\x1b[0m');
|
|
641
|
+
if (!options.continueOnUiError) return;
|
|
642
|
+
}
|
|
643
|
+
}
|
|
644
|
+
|
|
645
|
+
// Step 2: Backend build (ostro-build compiles TS → .dist/)
|
|
646
|
+
const stepLabel = hasVite ? '[2/2]' : '[1/1]';
|
|
647
|
+
console.log(` \x1b[36m${stepLabel}\x1b[0m Building backend (ostro-build)...`);
|
|
648
|
+
try {
|
|
649
|
+
execSync('npm run build', { cwd: absDir, stdio: 'inherit' });
|
|
650
|
+
console.log(' \x1b[32m✔ Backend build done\x1b[0m');
|
|
651
|
+
} catch (err) {
|
|
652
|
+
console.error('\x1b[31m✖ Backend build failed\x1b[0m');
|
|
653
|
+
return;
|
|
654
|
+
}
|
|
655
|
+
|
|
656
|
+
const distDir = path.join(absDir, '.dist');
|
|
657
|
+
if (!fs.existsSync(distDir)) {
|
|
658
|
+
console.error('\x1b[31m✖ .dist/ not found after build\x1b[0m');
|
|
659
|
+
return;
|
|
660
|
+
}
|
|
661
|
+
|
|
662
|
+
// Step 3: rsync .dist/* directly to remote service root (OPS-08)
|
|
663
|
+
console.log(`\n \x1b[36m[deploy]\x1b[0m Syncing .dist/ → \x1b[33m${remoteDest}\x1b[0m`);
|
|
664
|
+
try {
|
|
665
|
+
execSync(
|
|
666
|
+
`rsync -avz --delete "${distDir}/" "${remoteDest}"`,
|
|
667
|
+
{ stdio: 'inherit' }
|
|
668
|
+
);
|
|
669
|
+
console.log(`\n\x1b[32m✔ Deployed \x1b[33m${svcName}\x1b[32m to \x1b[33m${remoteDest}\x1b[0m\n`);
|
|
670
|
+
} catch (err) {
|
|
671
|
+
console.error(`\x1b[31m✖ rsync failed:\x1b[0m ${err.message}`);
|
|
672
|
+
}
|
|
673
|
+
}
|
|
674
|
+
|
|
675
|
+
module.exports = {
|
|
676
|
+
validateTemplate,
|
|
677
|
+
createStack,
|
|
678
|
+
deployStack,
|
|
679
|
+
listStacks,
|
|
680
|
+
describeStack,
|
|
681
|
+
deleteStack,
|
|
682
|
+
packageStack,
|
|
683
|
+
buildAndDeployService,
|
|
684
|
+
};
|