UNPKG

3.44 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3const tslib_1 = require("tslib");
4const sdk_1 = require("@cto.ai/sdk");
5const debug_1 = tslib_1.__importDefault(require("debug"));
6const get_docker_1 = tslib_1.__importDefault(require("../utils/get-docker"));
7const debug = debug_1.default('ops:ContainerService');
8class ContainerService {
9 constructor() {
10 this.log = console.log;
11 this.create = async (op, options) => {
12 const docker = await get_docker_1.default(console, 'ContainerService');
13 this.log(`⚙️ Running ${sdk_1.ux.colors.dim(op.name)}...`);
14 try {
15 this.container = await docker.createContainer(options);
16 return this.container;
17 }
18 catch (err) {
19 debug('%O', err);
20 throw new Error('Error creating Docker container');
21 }
22 };
23 this.start = async (stream) => {
24 if (!this.container)
25 throw new Error('No docker container to start up');
26 try {
27 await this.container.start();
28 this.resize();
29 process.stdout.on('resize', this.resize);
30 await this.container.wait();
31 this.handleExit(stream, false);
32 }
33 catch (err) {
34 debug('%O', err);
35 throw new Error(err);
36 }
37 };
38 this.handleStream = (stream) => {
39 const CTRL_P = '\u0010';
40 const CTRL_Q = '\u0011';
41 let previousKey = '';
42 stream.pipe(process.stdout);
43 const stdin = process.stdin;
44 stdin.resume();
45 stdin.setEncoding('utf8');
46 stdin.setRawMode && stdin.setRawMode(true);
47 stdin.pipe(stream);
48 stdin.on('data', (key) => {
49 // Detects it is detaching a running container
50 if (previousKey === CTRL_P && key === CTRL_Q) {
51 this.handleExit(stream, false);
52 }
53 previousKey = key;
54 });
55 };
56 this.handleExit = (stream, isRaw) => {
57 if (!this.container)
58 throw new Error('No docker container for removal');
59 const stdout = process.stdout;
60 const stdin = process.stdin;
61 try {
62 stdout.removeListener('resize', this.resize);
63 stdin.removeAllListeners();
64 stdin.setRawMode && stdin.setRawMode(isRaw);
65 stdin.resume();
66 stream.end();
67 this.container.remove(() => process.exit());
68 }
69 catch (err) {
70 debug('%O', err);
71 throw new Error(err);
72 }
73 };
74 this.resize = () => {
75 if (!this.container)
76 throw new Error('No docker container for resize');
77 try {
78 const dimensions = {
79 h: process.stdout.rows,
80 w: process.stderr.columns,
81 };
82 if (dimensions.h !== 0 && dimensions.w !== 0) {
83 this.container.resize(dimensions, () => { });
84 }
85 }
86 catch (err) {
87 debug('%O', err);
88 throw new Error(err);
89 }
90 };
91 }
92}
93exports.ContainerService = ContainerService;