stack.ts 13 KB

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