stack.ts 15 KB

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