stack.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409
  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. updateStatus() {
  150. let statusList = Stack.getStatusList();
  151. let status = statusList.get(this.name);
  152. if (status) {
  153. this._status = status;
  154. } else {
  155. this._status = UNKNOWN;
  156. }
  157. }
  158. static getStackList(server : DockgeServer, useCacheForManaged = false) : Map<string, Stack> {
  159. let stacksDir = server.stacksDir;
  160. let stackList : Map<string, Stack>;
  161. if (useCacheForManaged && this.managedStackList.size > 0) {
  162. stackList = this.managedStackList;
  163. } else {
  164. stackList = new Map<string, Stack>();
  165. // Scan the stacks directory, and get the stack list
  166. let filenameList = fs.readdirSync(stacksDir);
  167. for (let filename of filenameList) {
  168. try {
  169. // Check if it is a directory
  170. let stat = fs.statSync(path.join(stacksDir, filename));
  171. if (!stat.isDirectory()) {
  172. continue;
  173. }
  174. let stack = this.getStack(server, filename);
  175. stack._status = CREATED_FILE;
  176. stackList.set(filename, stack);
  177. } catch (e) {
  178. if (e instanceof Error) {
  179. log.warn("getStackList", `Failed to get stack ${filename}, error: ${e.message}`);
  180. }
  181. }
  182. }
  183. // Cache by copying
  184. this.managedStackList = new Map(stackList);
  185. }
  186. // Also get the list from `docker compose ls --all --format json`
  187. let res = childProcess.execSync("docker compose ls --all --format json");
  188. let composeList = JSON.parse(res.toString());
  189. for (let composeStack of composeList) {
  190. // Skip the dockge stack
  191. // TODO: Could be self managed?
  192. if (composeStack.Name === "dockge") {
  193. continue;
  194. }
  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. stack = new Stack(server, composeStack.Name);
  199. stackList.set(composeStack.Name, stack);
  200. }
  201. stack._status = this.statusConvert(composeStack.Status);
  202. stack._configFilePath = composeStack.ConfigFiles;
  203. }
  204. return stackList;
  205. }
  206. /**
  207. * Get the status list, it will be used to update the status of the stacks
  208. * Not all status will be returned, only the stack that is deployed or created to `docker compose` will be returned
  209. */
  210. static getStatusList() : Map<string, number> {
  211. let statusList = new Map<string, number>();
  212. let res = childProcess.execSync("docker compose ls --all --format json");
  213. let composeList = JSON.parse(res.toString());
  214. for (let composeStack of composeList) {
  215. statusList.set(composeStack.Name, this.statusConvert(composeStack.Status));
  216. }
  217. return statusList;
  218. }
  219. /**
  220. * Convert the status string from `docker compose ls` to the status number
  221. * Input Example: "exited(1), running(1)"
  222. * @param status
  223. */
  224. static statusConvert(status : string) : number {
  225. if (status.startsWith("created")) {
  226. return CREATED_STACK;
  227. } else if (status.includes("exited")) {
  228. // If one of the service is exited, we consider the stack is exited
  229. return EXITED;
  230. } else if (status.startsWith("running")) {
  231. // If there is no exited services, there should be only running services
  232. return RUNNING;
  233. } else {
  234. return UNKNOWN;
  235. }
  236. }
  237. static getStack(server: DockgeServer, stackName: string) : Stack {
  238. let dir = path.join(server.stacksDir, stackName);
  239. if (!fs.existsSync(dir) || !fs.statSync(dir).isDirectory()) {
  240. // Maybe it is a stack managed by docker compose directly
  241. let stackList = this.getStackList(server);
  242. let stack = stackList.get(stackName);
  243. if (stack) {
  244. return stack;
  245. } else {
  246. // Really not found
  247. throw new ValidationError("Stack not found");
  248. }
  249. }
  250. let stack = new Stack(server, stackName);
  251. stack._status = UNKNOWN;
  252. stack._configFilePath = path.resolve(dir);
  253. return stack;
  254. }
  255. async start(socket: DockgeSocket) {
  256. const terminalName = getComposeTerminalName(this.name);
  257. let exitCode = await Terminal.exec(this.server, socket, terminalName, "docker", [ "compose", "up", "-d", "--remove-orphans" ], this.path);
  258. if (exitCode !== 0) {
  259. throw new Error("Failed to start, please check the terminal output for more information.");
  260. }
  261. return exitCode;
  262. }
  263. async stop(socket: DockgeSocket) : Promise<number> {
  264. const terminalName = getComposeTerminalName(this.name);
  265. let exitCode = await Terminal.exec(this.server, socket, terminalName, "docker", [ "compose", "stop" ], this.path);
  266. if (exitCode !== 0) {
  267. throw new Error("Failed to stop, please check the terminal output for more information.");
  268. }
  269. return exitCode;
  270. }
  271. async restart(socket: DockgeSocket) : Promise<number> {
  272. const terminalName = getComposeTerminalName(this.name);
  273. let exitCode = await Terminal.exec(this.server, socket, terminalName, "docker", [ "compose", "restart" ], 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 down(socket: DockgeSocket) : Promise<number> {
  280. const terminalName = getComposeTerminalName(this.name);
  281. let exitCode = await Terminal.exec(this.server, socket, terminalName, "docker", [ "compose", "down" ], this.path);
  282. if (exitCode !== 0) {
  283. throw new Error("Failed to down, please check the terminal output for more information.");
  284. }
  285. return exitCode;
  286. }
  287. async update(socket: DockgeSocket) {
  288. const terminalName = getComposeTerminalName(this.name);
  289. let exitCode = await Terminal.exec(this.server, socket, terminalName, "docker", [ "compose", "pull" ], this.path);
  290. if (exitCode !== 0) {
  291. throw new Error("Failed to pull, please check the terminal output for more information.");
  292. }
  293. // If the stack is not running, we don't need to restart it
  294. this.updateStatus();
  295. log.debug("update", "Status: " + this.status);
  296. if (this.status !== RUNNING) {
  297. return exitCode;
  298. }
  299. exitCode = await Terminal.exec(this.server, socket, terminalName, "docker", [ "compose", "up", "-d", "--remove-orphans" ], this.path);
  300. if (exitCode !== 0) {
  301. throw new Error("Failed to restart, please check the terminal output for more information.");
  302. }
  303. return exitCode;
  304. }
  305. async joinCombinedTerminal(socket: DockgeSocket) {
  306. const terminalName = getCombinedTerminalName(this.name);
  307. const terminal = Terminal.getOrCreateTerminal(this.server, terminalName, "docker", [ "compose", "logs", "-f", "--tail", "100" ], this.path);
  308. terminal.rows = COMBINED_TERMINAL_ROWS;
  309. terminal.cols = COMBINED_TERMINAL_COLS;
  310. terminal.join(socket);
  311. terminal.start();
  312. }
  313. async joinContainerTerminal(socket: DockgeSocket, serviceName: string, shell : string = "sh", index: number = 0) {
  314. const terminalName = getContainerExecTerminalName(this.name, serviceName, index);
  315. let terminal = Terminal.getTerminal(terminalName);
  316. if (!terminal) {
  317. terminal = new InteractiveTerminal(this.server, terminalName, "docker", [ "compose", "exec", serviceName, shell ], this.path);
  318. terminal.rows = TERMINAL_ROWS;
  319. log.debug("joinContainerTerminal", "Terminal created");
  320. }
  321. terminal.join(socket);
  322. terminal.start();
  323. }
  324. async getServiceStatusList() {
  325. let statusList = new Map<string, number>();
  326. let res = childProcess.execSync("docker compose ps --format json", {
  327. cwd: this.path,
  328. });
  329. let lines = res.toString().split("\n");
  330. for (let line of lines) {
  331. try {
  332. let obj = JSON.parse(line);
  333. if (obj.Health === "") {
  334. statusList.set(obj.Service, obj.State);
  335. } else {
  336. statusList.set(obj.Service, obj.Health);
  337. }
  338. } catch (e) {
  339. }
  340. }
  341. return statusList;
  342. }
  343. }