-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbootstrap.service.ts
More file actions
189 lines (167 loc) · 5.53 KB
/
bootstrap.service.ts
File metadata and controls
189 lines (167 loc) · 5.53 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
import { Listr } from 'listr2';
import pWaitFor from 'p-wait-for';
import { createComposeCommandArgs, type ComposeLayerSelection } from '../lib/compose.js';
import type { BootstrapCommandOptions } from '../types/cli.types.js';
import type { ProjectContext } from '../types/project.types.js';
import { ensureGiteaAdmin } from './gitea-admin.service.js';
import { printCommandHeader } from '../ui/banner.js';
import { formatTaskTitle, printInfo, printSuccess } from '../ui/logger.js';
import { runCommand } from '../utils/process.js';
import { parseAiLlmBootstrapEnv, parseBootstrapEnv } from './project.service.js';
const VERBOSE_TASK_RENDERER = 'verbose' as const;
/**
* Runs the standalone bootstrap workflow.
*/
export async function runBootstrapCommand(
context: ProjectContext,
options: BootstrapCommandOptions
): Promise<void> {
printCommandHeader({
title: 'Bootstrap Atlas Lab',
summary: 'Reconcile core runtime state plus optional AI LLM bootstrap',
projectRoot: context.projectRoot,
workingDirectory: context.workingDirectory
});
await new Listr(createBootstrapTasks(context, options), {
concurrent: false,
exitOnError: true,
renderer: VERBOSE_TASK_RENDERER
}).run();
printSuccess('Bootstrap completed.', 'bootstrap');
}
/**
* Creates reusable bootstrap tasks so `up` can nest them in its own workflow.
*/
export function createBootstrapTasks(
context: ProjectContext,
options: BootstrapCommandOptions
) {
const env = parseBootstrapEnv(context.env);
const aiLlmEnv = options.withAiLlm ? parseAiLlmBootstrapEnv(context.env) : undefined;
const tasks = [];
if (!options.skipGitea) {
tasks.push({
title: formatTaskTitle('bootstrap', 'Align Gitea root account'),
task: async () => {
await waitForService(context, 'gitea');
const result = await ensureGiteaAdmin(context, env);
printInfo(`Gitea root account ${result}.`, 'bootstrap');
}
});
}
if (options.withAiLlm && !options.skipOllama && aiLlmEnv) {
tasks.push({
title: formatTaskTitle('bootstrap', 'Align Ollama runtime models'),
task: async () => {
const result = await ensureOllamaModels(context);
printInfo(`Ollama runtime models ${result}.`, 'bootstrap');
}
});
}
return tasks;
}
/**
* Waits for Ollama and ensures the configured runtime models are present locally.
*/
async function ensureOllamaModels(
context: ProjectContext
): Promise<'present' | 'pulled'> {
await waitForService(context, 'ollama', 180, { includeAiLlm: true });
const syncResult = await runCommand(
'docker',
createComposeCommandArgs(context, [
'exec',
'-T',
'ollama',
'sh',
'/opt/atlas-lab/model-sync/sync-ollama-models.sh'
], { includeAiLlm: true }),
{
cwd: context.projectRoot,
captureOutput: true,
scope: 'bootstrap'
}
);
const lines = syncResult.stdout
.split(/\r?\n/u)
.map((line) => line.trim())
.filter((line) => line.length > 0);
for (const line of lines) {
if (!line.startsWith('ATLAS_OLLAMA_MODEL_SYNC_RESULT=')) {
printInfo(line, 'bootstrap');
}
}
const resultLine = lines.find((line) => line.startsWith('ATLAS_OLLAMA_MODEL_SYNC_RESULT='));
return resultLine?.endsWith('pulled') ? 'pulled' : 'present';
}
/**
* Polls Docker until the service reaches either `healthy` or `running`.
*/
export async function waitForService(
context: ProjectContext,
serviceName: string,
timeoutSeconds = 180,
selection: ComposeLayerSelection = {}
): Promise<void> {
let lastReportedState = '';
await pWaitFor(
async () => {
const containerId = await runCommand(
'docker',
createComposeCommandArgs(context, ['ps', '-q', serviceName], selection),
{
cwd: context.projectRoot,
captureOutput: true,
scope: 'bootstrap'
}
);
if (!containerId.stdout.trim()) {
reportServiceWaitState(serviceName, 'container not created yet', lastReportedState);
lastReportedState = 'container not created yet';
return false;
}
const state = await runCommand(
'docker',
[
'inspect',
'--format',
'{{if .State.Health}}{{.State.Health.Status}}{{else}}{{.State.Status}}{{end}}',
containerId.stdout.trim()
],
{
cwd: context.projectRoot,
captureOutput: true,
scope: 'bootstrap'
}
);
const normalizedState = normalizeServiceRuntimeState(state.stdout);
reportServiceWaitState(serviceName, normalizedState, lastReportedState);
lastReportedState = normalizedState;
return ['healthy', 'running'].includes(normalizedState);
},
{
interval: 2_000,
timeout: {
milliseconds: timeoutSeconds * 1000,
message: new Error(`Timed out waiting for service '${serviceName}' to become healthy`)
}
}
);
printSuccess(`Service '${serviceName}' is ready (${lastReportedState || 'healthy'}).`, 'bootstrap');
}
/**
* Emits a progress line only when the observed service state changes.
*/
function reportServiceWaitState(serviceName: string, nextState: string, previousState: string): void {
if (nextState === previousState) {
return;
}
printInfo(`Waiting for service '${serviceName}': ${nextState}.`, 'bootstrap');
}
/**
* Normalizes the runtime state returned by `docker inspect`.
*/
function normalizeServiceRuntimeState(rawState: string): string {
const normalizedState = rawState.trim();
return normalizedState.length > 0 ? normalizedState : 'unknown';
}