-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.ts
More file actions
452 lines (398 loc) · 12.7 KB
/
main.ts
File metadata and controls
452 lines (398 loc) · 12.7 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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
import { VERSION } from "./version.ts";
import { Hono } from "hono";
import { logger as honoLogger } from "hono/logger";
import { cors } from "hono/cors";
import { Command } from "@cliffy/command";
import * as path from "@std/path";
import "@std/dotenv/load"; // Automatically load .env file
import { middlewareRateLimit } from "./lib/middleware/ratelimit/index.ts";
import { middlewareAuth } from "./lib/middleware/auth/index.ts";
import { DockerService } from "./lib/docker/index.ts";
// Custom logger that handles silent mode and file logging
class Logger {
private logFile: string | null = null;
private silent: boolean = false;
constructor(options?: { logFile?: string; silent?: boolean }) {
this.logFile = options?.logFile || null;
this.silent = options?.silent || false;
}
// Log to both console and file if specified
async log(message: string, level: "info" | "error" = "info") {
const timestamp = new Date().toISOString();
const formattedMessage = `${timestamp} [${level.toUpperCase()}] ${message}`;
// Write to file if specified
if (this.logFile) {
try {
await Deno.writeTextFile(
this.logFile,
formattedMessage + "\n",
{ append: true, create: true },
);
} catch (error) {
// Only log file errors to console if not in silent mode
if (!this.silent) {
const message = error instanceof Error
? error.message
: String(error);
console.error(`Failed to write to log file: ${message}`);
}
}
}
// Output to console if not in silent mode
if (!this.silent) {
if (level === "error") {
console.error(formattedMessage);
} else {
console.log(formattedMessage);
}
}
}
info(message: string) {
return this.log(message, "info");
}
error(message: string) {
return this.log(message, "error");
}
}
// Create a logger instance based on command options
function createLogger(options: { silent?: boolean; logFile?: string }) {
const logFilePath = options.logFile;
// If log file path is provided, ensure the directory exists
if (logFilePath) {
try {
const dirPath = path.dirname(logFilePath);
Deno.mkdirSync(dirPath, { recursive: true });
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
console.error(`Failed to create log directory: ${message}`);
}
}
return new Logger({
logFile: logFilePath,
silent: options.silent || false,
});
}
// Function to start the server
async function startServer(options: {
silent?: boolean;
logFile?: string;
}) {
const logger = createLogger(options);
// Load environment variables
if (!Deno.env.get("DOCKER_CONTROL_TOKEN")) {
await logger.error(
"Error: DOCKER_CONTROL_TOKEN is not set in the environment variables.",
);
Deno.exit(1);
}
// Check if the socket exists.
const socketPath = Deno.env.get("DOCKER_CONTROL_SOCKET") ||
"/var/run/docker.sock";
try {
await Deno.stat(socketPath);
} catch (err) {
if (err instanceof Deno.errors.NotFound) {
await logger.error(`Socket not found at ${socketPath}`);
Deno.exit(1);
} else {
await logger.error(`Unexpected Error: ${err}`);
Deno.exit(1);
}
}
const dockerService = new DockerService();
const app = new Hono();
// Enable logging middleware if not in silent mode
if (!options.silent) {
app.use(honoLogger());
}
// Enable CORS middleware
app.use(
"/*",
cors({
origin: "*",
allowMethods: ["GET"],
allowHeaders: ["Authorization", "Content-Type"],
}),
);
// Apply custom middlewares
app.use("/*", middlewareRateLimit, middlewareAuth);
// Endpoint to list running Docker containers
app.get("/containers", async (c) => {
try {
const data = await dockerService.getAllContainers();
return c.json(data);
} catch (err) {
await logger.error(`Unexpected Error: ${err}`);
return c.text("Internal Server Error", 500);
}
});
app.get("/names", async (c) => {
try {
const names = await dockerService.getContainerNames();
return c.json(names);
} catch (err) {
await logger.error(`Unexpected Error: ${err}`);
return c.text("Internal Server Error", 500);
}
});
app.get("/status", async (c) => {
try {
const statusInfo = await dockerService.getContainerStatus();
return c.json(statusInfo);
} catch (err) {
await logger.error(`Unexpected Error: ${err}`);
return c.text("Internal Server Error", 500);
}
});
app.post("/control/:association/:value/start", async (c) => {
const association = c.req.param("association");
const value = c.req.param("value");
try {
let container;
switch (association) {
case "id":
container = await dockerService.findContainerById(value);
break;
case "name":
container = await dockerService.findContainerByName(value);
break;
default:
return c.json(
{ error: "Invalid association parameter. Use 'id' or 'name'." },
400,
);
}
if (!container) {
return c.json(
{ error: `Container with ${association} '${value}' not found` },
404,
);
}
// Use the container ID for the operation
const result = await dockerService.startContainer(container.Id);
return c.json(result);
} catch (err) {
await logger.error(
`Error starting container with ${association} '${value}': ${err}`,
);
if (err instanceof Error && err.message.includes("not found")) {
return c.json({ error: err.message }, 404);
}
return c.json({ error: "Internal Server Error" }, 500);
}
});
app.post("/control/:association/:value/stop", async (c) => {
const association = c.req.param("association");
const value = c.req.param("value");
try {
let container;
switch (association) {
case "id":
container = await dockerService.findContainerById(value);
break;
case "name":
container = await dockerService.findContainerByName(value);
break;
default:
return c.json(
{ error: "Invalid association parameter. Use 'id' or 'name'." },
400,
);
}
if (!container) {
return c.json(
{ error: `Container with ${association} '${value}' not found` },
404,
);
}
// Use the container ID for the operation
const result = await dockerService.stopContainer(container.Id);
return c.json(result);
} catch (err) {
await logger.error(
`Error stopping container with ${association} '${value}': ${err}`,
);
if (err instanceof Error && err.message.includes("not found")) {
return c.json({ error: err.message }, 404);
}
return c.json({ error: "Internal Server Error" }, 500);
}
});
app.post("/control/:association/:value/restart", async (c) => {
const association = c.req.param("association");
const value = c.req.param("value");
try {
let container;
switch (association) {
case "id":
container = await dockerService.findContainerById(value);
break;
case "name":
container = await dockerService.findContainerByName(value);
break;
default:
return c.json(
{ error: "Invalid association parameter. Use 'id' or 'name'." },
400,
);
}
if (!container) {
return c.json(
{ error: `Container with ${association} '${value}' not found` },
404,
);
}
// Use the container ID for the operation
const result = await dockerService.restartContainer(container.Id);
return c.json(result);
} catch (err) {
await logger.error(
`Error restarting container with ${association} '${value}': ${err}`,
);
if (err instanceof Error && err.message.includes("not found")) {
return c.json({ error: err.message }, 404);
}
return c.json({ error: "Internal Server Error" }, 500);
}
});
app.get("/control/:association/:value/logs", async (c) => {
const association = c.req.param("association");
const value = c.req.param("value");
// Get the optional tail parameter (number of lines)
const tailParam = c.req.query("tail");
const tail = tailParam ? parseInt(tailParam, 10) : undefined;
// Get the optional since parameter (time duration like "1h", "2d")
const since = c.req.query("since");
// Get the optional from/to parameters (Unix timestamps)
const fromParam = c.req.query("from");
const toParam = c.req.query("to");
// Parse from/to as numbers if provided
const from = fromParam ? parseInt(fromParam, 10) : undefined;
const to = toParam ? parseInt(toParam, 10) : undefined;
// Validate that if 'to' is provided, 'from' must also be provided
if (toParam && !fromParam) {
return c.json(
{ error: "Parameter 'to' requires 'from' to be provided" },
400,
);
}
try {
let container;
switch (association) {
case "id":
container = await dockerService.findContainerById(value);
break;
case "name":
container = await dockerService.findContainerByName(value);
break;
default:
return c.json(
{ error: "Invalid association parameter. Use 'id' or 'name'." },
400,
);
}
if (!container) {
return c.json(
{ error: `Container with ${association} '${value}' not found` },
404,
);
}
// Use the container ID for the operation
const result = await dockerService.getContainerLogs(
container.Id,
tail,
since,
from,
to,
);
return c.text(result);
} catch (err) {
await logger.error(
`Error getting logs for container with ${association} '${value}': ${err}`,
);
if (err instanceof Error && err.message.includes("not found")) {
return c.json({ error: err.message }, 404);
}
return c.text("Internal Server Error", 500);
}
});
app.get("/control/:association/:value/status", async (c) => {
const association = c.req.param("association");
const value = c.req.param("value");
try {
let container;
switch (association) {
case "id":
container = await dockerService.findContainerById(value);
break;
case "name":
container = await dockerService.findContainerByName(value);
break;
default:
return c.json(
{ error: "Invalid association parameter. Use 'id' or 'name'." },
400,
);
}
if (!container) {
return c.json(
{ error: `Container with ${association} '${value}' not found` },
404,
);
}
// Use the container ID for the operation
const result = await dockerService.getContainerStatusById(container.Id);
return c.json(result);
} catch (err) {
await logger.error(
`Error getting status for container with ${association} '${value}': ${err}`,
);
if (err instanceof Error && err.message.includes("not found")) {
return c.json({ error: err.message }, 404);
}
return c.json({ error: "Internal Server Error" }, 500);
}
});
// Fallback Route
app.notFound((c) => c.text(`API path '${c.req.path}' not found`, 404));
// Start the server
const DOCKER_CONTROL_PORT = Deno.env.get("DOCKER_CONTROL_PORT") || 54320;
Deno.serve(
{
port: Number(DOCKER_CONTROL_PORT),
onListen: () => {
logger.info(
`Docker Control is running at http://127.0.0.1:${DOCKER_CONTROL_PORT}`,
);
},
},
app.fetch,
);
}
// Export server function to be called by CLI
function start(options: {
silent?: boolean;
logFile?: string;
}) {
startServer(options);
}
// Parse command line arguments
function setupCLI() {
return new Command()
.name("docker-control")
.version(VERSION)
.description("Hivecom Docker container orchestration and metrics API")
.option("-s, --silent", "Run in silent mode (no console output)")
.option("-l, --log-file <path:string>", "Log output to the specified file")
.action(start)
.command("serve", "Start the Docker control API server")
.option("-s, --silent", "Run in silent mode (no console output)")
.option("-l, --log-file <path:string>", "Log output to the specified file")
.action(start);
}
// Create CLI parser
const cli = setupCLI();
// Run the CLI
if (import.meta.main) {
cli.parse(Deno.args);
}