stack.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484
  1. import { DockgeServer } from "./dockge-server";
  2. import fs, { promises as fsAsync } from "fs";
  3. import { log } from "./log";
  4. import yaml from "yaml";
  5. import { DockgeSocket, fileExists, ValidationError } from "./util-server";
  6. import path from "path";
  7. import {
  8. COMBINED_TERMINAL_COLS,
  9. COMBINED_TERMINAL_ROWS,
  10. CREATED_FILE,
  11. CREATED_STACK,
  12. EXITED, getCombinedTerminalName,
  13. getComposeTerminalName, getContainerExecTerminalName,
  14. PROGRESS_TERMINAL_ROWS,
  15. RUNNING, TERMINAL_ROWS,
  16. UNKNOWN
  17. } from "./util-common";
  18. import { InteractiveTerminal, Terminal } from "./terminal";
  19. import childProcessAsync from "promisify-child-process";
  20. export class Stack {
  21. name: string;
  22. protected _status: number = UNKNOWN;
  23. protected _composeYAML?: string;
  24. protected _composeENV?: string;
  25. protected _configFilePath?: string;
  26. protected _composeFileName: string = "compose.yaml";
  27. protected server: DockgeServer;
  28. protected combinedTerminal? : Terminal;
  29. protected static managedStackList: Map<string, Stack> = new Map();
  30. constructor(server : DockgeServer, name : string, composeYAML? : string, composeENV? : string, skipFSOperations = false) {
  31. this.name = name;
  32. this.server = server;
  33. this._composeYAML = composeYAML;
  34. this._composeENV = composeENV;
  35. if (!skipFSOperations) {
  36. // Check if compose file name is different from compose.yaml
  37. const supportedFileNames = [ "compose.yaml", "compose.yml", "docker-compose.yml", "docker-compose.yaml" ];
  38. for (const filename of supportedFileNames) {
  39. if (fs.existsSync(path.join(this.path, filename))) {
  40. this._composeFileName = filename;
  41. break;
  42. }
  43. }
  44. }
  45. }
  46. toJSON() : object {
  47. let obj = this.toSimpleJSON();
  48. return {
  49. ...obj,
  50. composeYAML: this.composeYAML,
  51. composeENV: this.composeENV,
  52. };
  53. }
  54. toSimpleJSON() : object {
  55. return {
  56. name: this.name,
  57. status: this._status,
  58. tags: [],
  59. isManagedByDockge: this.isManagedByDockge,
  60. composeFileName: this._composeFileName,
  61. };
  62. }
  63. /**
  64. * Get the status of the stack from `docker compose ps --format json`
  65. */
  66. async ps() : Promise<object> {
  67. let res = await childProcessAsync.spawn("docker", [ "compose", "ps", "--format", "json" ], {
  68. cwd: this.path,
  69. encoding: "utf-8",
  70. });
  71. if (!res.stdout) {
  72. return {};
  73. }
  74. return JSON.parse(res.stdout.toString());
  75. }
  76. get isManagedByDockge() : boolean {
  77. return fs.existsSync(this.path) && fs.statSync(this.path).isDirectory();
  78. }
  79. get status() : number {
  80. return this._status;
  81. }
  82. validate() {
  83. // Check name, allows [a-z][0-9] _ - only
  84. if (!this.name.match(/^[a-z0-9_-]+$/)) {
  85. throw new ValidationError("Stack name can only contain [a-z][0-9] _ - only");
  86. }
  87. // Check YAML format
  88. yaml.parse(this.composeYAML);
  89. let lines = this.composeENV.split("\n");
  90. // Check if the .env is able to pass docker-compose
  91. // Prevent "setenv: The parameter is incorrect"
  92. // It only happens when there is one line and it doesn't contain "="
  93. if (lines.length === 1 && !lines[0].includes("=") && lines[0].length > 0) {
  94. throw new ValidationError("Invalid .env format");
  95. }
  96. }
  97. get composeYAML() : string {
  98. if (this._composeYAML === undefined) {
  99. try {
  100. this._composeYAML = fs.readFileSync(path.join(this.path, this._composeFileName), "utf-8");
  101. } catch (e) {
  102. this._composeYAML = "";
  103. }
  104. }
  105. return this._composeYAML;
  106. }
  107. get composeENV() : string {
  108. if (this._composeENV === undefined) {
  109. try {
  110. this._composeENV = fs.readFileSync(path.join(this.path, ".env"), "utf-8");
  111. } catch (e) {
  112. this._composeENV = "";
  113. }
  114. }
  115. return this._composeENV;
  116. }
  117. get path() : string {
  118. return path.join(this.server.stacksDir, this.name);
  119. }
  120. get fullPath() : string {
  121. let dir = this.path;
  122. // Compose up via node-pty
  123. let fullPathDir;
  124. // if dir is relative, make it absolute
  125. if (!path.isAbsolute(dir)) {
  126. fullPathDir = path.join(process.cwd(), dir);
  127. } else {
  128. fullPathDir = dir;
  129. }
  130. return fullPathDir;
  131. }
  132. /**
  133. * Save the stack to the disk
  134. * @param isAdd
  135. */
  136. async save(isAdd : boolean) {
  137. this.validate();
  138. let dir = this.path;
  139. // Check if the name is used if isAdd
  140. if (isAdd) {
  141. if (await fileExists(dir)) {
  142. throw new ValidationError("Stack name already exists");
  143. }
  144. // Create the stack folder
  145. await fsAsync.mkdir(dir);
  146. } else {
  147. if (!await fileExists(dir)) {
  148. throw new ValidationError("Stack not found");
  149. }
  150. }
  151. // Write or overwrite the compose.yaml
  152. await fsAsync.writeFile(path.join(dir, this._composeFileName), this.composeYAML);
  153. const envPath = path.join(dir, ".env");
  154. // Write or overwrite the .env
  155. // If .env is not existing and the composeENV is empty, we don't need to write it
  156. if (await fileExists(envPath) || this.composeENV.trim() !== "") {
  157. await fsAsync.writeFile(envPath, this.composeENV);
  158. }
  159. }
  160. async deploy(socket? : DockgeSocket) : Promise<number> {
  161. const terminalName = getComposeTerminalName(this.name);
  162. let exitCode = await Terminal.exec(this.server, socket, terminalName, "docker", [ "compose", "up", "-d", "--remove-orphans" ], this.path);
  163. if (exitCode !== 0) {
  164. throw new Error("Failed to deploy, please check the terminal output for more information.");
  165. }
  166. return exitCode;
  167. }
  168. async delete(socket?: DockgeSocket) : Promise<number> {
  169. const terminalName = getComposeTerminalName(this.name);
  170. let exitCode = await Terminal.exec(this.server, socket, terminalName, "docker", [ "compose", "down", "--remove-orphans" ], this.path);
  171. if (exitCode !== 0) {
  172. throw new Error("Failed to delete, please check the terminal output for more information.");
  173. }
  174. // Remove the stack folder
  175. await fsAsync.rm(this.path, {
  176. recursive: true,
  177. force: true
  178. });
  179. return exitCode;
  180. }
  181. async updateStatus() {
  182. let statusList = await Stack.getStatusList();
  183. let status = statusList.get(this.name);
  184. if (status) {
  185. this._status = status;
  186. } else {
  187. this._status = UNKNOWN;
  188. }
  189. }
  190. static async getStackList(server : DockgeServer, useCacheForManaged = false) : Promise<Map<string, Stack>> {
  191. let stacksDir = server.stacksDir;
  192. let stackList : Map<string, Stack>;
  193. // Use cached stack list?
  194. if (useCacheForManaged && this.managedStackList.size > 0) {
  195. stackList = this.managedStackList;
  196. } else {
  197. stackList = new Map<string, Stack>();
  198. // Scan the stacks directory, and get the stack list
  199. let filenameList = await fsAsync.readdir(stacksDir);
  200. for (let filename of filenameList) {
  201. try {
  202. // Check if it is a directory
  203. let stat = await fsAsync.stat(path.join(stacksDir, filename));
  204. if (!stat.isDirectory()) {
  205. continue;
  206. }
  207. let stack = await this.getStack(server, filename);
  208. stack._status = CREATED_FILE;
  209. stackList.set(filename, stack);
  210. } catch (e) {
  211. if (e instanceof Error) {
  212. log.warn("getStackList", `Failed to get stack ${filename}, error: ${e.message}`);
  213. }
  214. }
  215. }
  216. // Cache by copying
  217. this.managedStackList = new Map(stackList);
  218. }
  219. // Get status from docker compose ls
  220. let res = await childProcessAsync.spawn("docker", [ "compose", "ls", "--all", "--format", "json" ], {
  221. encoding: "utf-8",
  222. });
  223. if (!res.stdout) {
  224. return stackList;
  225. }
  226. let composeList = JSON.parse(res.stdout.toString());
  227. for (let composeStack of composeList) {
  228. let stack = stackList.get(composeStack.Name);
  229. // This stack probably is not managed by Dockge, but we still want to show it
  230. if (!stack) {
  231. // Skip the dockge stack if it is not managed by Dockge
  232. if (composeStack.Name === "dockge") {
  233. continue;
  234. }
  235. stack = new Stack(server, composeStack.Name);
  236. stackList.set(composeStack.Name, stack);
  237. }
  238. stack._status = this.statusConvert(composeStack.Status);
  239. stack._configFilePath = composeStack.ConfigFiles;
  240. }
  241. return stackList;
  242. }
  243. /**
  244. * Get the status list, it will be used to update the status of the stacks
  245. * Not all status will be returned, only the stack that is deployed or created to `docker compose` will be returned
  246. */
  247. static async getStatusList() : Promise<Map<string, number>> {
  248. let statusList = new Map<string, number>();
  249. let res = await childProcessAsync.spawn("docker", [ "compose", "ls", "--all", "--format", "json" ], {
  250. encoding: "utf-8",
  251. });
  252. let composeList = JSON.parse(res.toString());
  253. for (let composeStack of composeList) {
  254. statusList.set(composeStack.Name, this.statusConvert(composeStack.Status));
  255. }
  256. return statusList;
  257. }
  258. /**
  259. * Convert the status string from `docker compose ls` to the status number
  260. * Input Example: "exited(1), running(1)"
  261. * @param status
  262. */
  263. static statusConvert(status : string) : number {
  264. if (status.startsWith("created")) {
  265. return CREATED_STACK;
  266. } else if (status.includes("exited")) {
  267. // If one of the service is exited, we consider the stack is exited
  268. return EXITED;
  269. } else if (status.startsWith("running")) {
  270. // If there is no exited services, there should be only running services
  271. return RUNNING;
  272. } else {
  273. return UNKNOWN;
  274. }
  275. }
  276. static async getStack(server: DockgeServer, stackName: string, skipFSOperations = false) : Promise<Stack> {
  277. let dir = path.join(server.stacksDir, stackName);
  278. if (!skipFSOperations) {
  279. if (!await fileExists(dir) || !(await fsAsync.stat(dir)).isDirectory()) {
  280. // Maybe it is a stack managed by docker compose directly
  281. let stackList = await this.getStackList(server, true);
  282. let stack = stackList.get(stackName);
  283. if (stack) {
  284. return stack;
  285. } else {
  286. // Really not found
  287. throw new ValidationError("Stack not found");
  288. }
  289. }
  290. } else {
  291. //log.debug("getStack", "Skip FS operations");
  292. }
  293. let stack : Stack;
  294. if (!skipFSOperations) {
  295. stack = new Stack(server, stackName);
  296. } else {
  297. stack = new Stack(server, stackName, undefined, undefined, true);
  298. }
  299. stack._status = UNKNOWN;
  300. stack._configFilePath = path.resolve(dir);
  301. return stack;
  302. }
  303. async start(socket: DockgeSocket) {
  304. const terminalName = getComposeTerminalName(this.name);
  305. let exitCode = await Terminal.exec(this.server, socket, terminalName, "docker", [ "compose", "up", "-d", "--remove-orphans" ], this.path);
  306. if (exitCode !== 0) {
  307. throw new Error("Failed to start, please check the terminal output for more information.");
  308. }
  309. return exitCode;
  310. }
  311. async stop(socket: DockgeSocket) : Promise<number> {
  312. const terminalName = getComposeTerminalName(this.name);
  313. let exitCode = await Terminal.exec(this.server, socket, terminalName, "docker", [ "compose", "stop" ], this.path);
  314. if (exitCode !== 0) {
  315. throw new Error("Failed to stop, please check the terminal output for more information.");
  316. }
  317. return exitCode;
  318. }
  319. async restart(socket: DockgeSocket) : Promise<number> {
  320. const terminalName = getComposeTerminalName(this.name);
  321. let exitCode = await Terminal.exec(this.server, socket, terminalName, "docker", [ "compose", "restart" ], this.path);
  322. if (exitCode !== 0) {
  323. throw new Error("Failed to restart, please check the terminal output for more information.");
  324. }
  325. return exitCode;
  326. }
  327. async down(socket: DockgeSocket) : Promise<number> {
  328. const terminalName = getComposeTerminalName(this.name);
  329. let exitCode = await Terminal.exec(this.server, socket, terminalName, "docker", [ "compose", "down" ], this.path);
  330. if (exitCode !== 0) {
  331. throw new Error("Failed to down, please check the terminal output for more information.");
  332. }
  333. return exitCode;
  334. }
  335. async update(socket: DockgeSocket) {
  336. const terminalName = getComposeTerminalName(this.name);
  337. let exitCode = await Terminal.exec(this.server, socket, terminalName, "docker", [ "compose", "pull" ], this.path);
  338. if (exitCode !== 0) {
  339. throw new Error("Failed to pull, please check the terminal output for more information.");
  340. }
  341. // If the stack is not running, we don't need to restart it
  342. await this.updateStatus();
  343. log.debug("update", "Status: " + this.status);
  344. if (this.status !== RUNNING) {
  345. return exitCode;
  346. }
  347. exitCode = await Terminal.exec(this.server, socket, terminalName, "docker", [ "compose", "up", "-d", "--remove-orphans" ], this.path);
  348. if (exitCode !== 0) {
  349. throw new Error("Failed to restart, please check the terminal output for more information.");
  350. }
  351. return exitCode;
  352. }
  353. async joinCombinedTerminal(socket: DockgeSocket) {
  354. const terminalName = getCombinedTerminalName(this.name);
  355. const terminal = Terminal.getOrCreateTerminal(this.server, terminalName, "docker", [ "compose", "logs", "-f", "--tail", "100" ], this.path);
  356. terminal.enableKeepAlive = true;
  357. terminal.rows = COMBINED_TERMINAL_ROWS;
  358. terminal.cols = COMBINED_TERMINAL_COLS;
  359. terminal.join(socket);
  360. terminal.start();
  361. }
  362. async leaveCombinedTerminal(socket: DockgeSocket) {
  363. const terminalName = getCombinedTerminalName(this.name);
  364. const terminal = Terminal.getTerminal(terminalName);
  365. if (terminal) {
  366. terminal.leave(socket);
  367. }
  368. }
  369. async joinContainerTerminal(socket: DockgeSocket, serviceName: string, shell : string = "sh", index: number = 0) {
  370. const terminalName = getContainerExecTerminalName(this.name, serviceName, index);
  371. let terminal = Terminal.getTerminal(terminalName);
  372. if (!terminal) {
  373. terminal = new InteractiveTerminal(this.server, terminalName, "docker", [ "compose", "exec", serviceName, shell ], this.path);
  374. terminal.rows = TERMINAL_ROWS;
  375. log.debug("joinContainerTerminal", "Terminal created");
  376. }
  377. terminal.join(socket);
  378. terminal.start();
  379. }
  380. async getServiceStatusList() {
  381. let statusList = new Map<string, number>();
  382. try {
  383. let res = await childProcessAsync.spawn("docker", [ "compose", "ps", "--format", "json" ], {
  384. cwd: this.path,
  385. encoding: "utf-8",
  386. });
  387. if (!res.stdout) {
  388. return statusList;
  389. }
  390. let lines = res.stdout?.toString().split("\n");
  391. for (let line of lines) {
  392. try {
  393. let obj = JSON.parse(line);
  394. if (obj.Health === "") {
  395. statusList.set(obj.Service, obj.State);
  396. } else {
  397. statusList.set(obj.Service, obj.Health);
  398. }
  399. } catch (e) {
  400. }
  401. }
  402. return statusList;
  403. } catch (e) {
  404. log.error("getServiceStatusList", e);
  405. return statusList;
  406. }
  407. }
  408. }