stack.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  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. if (fs.existsSync(path.join(this.path, "compose.yml"))){
  35. this._composeFileName = "compose.yml";
  36. } else if (fs.existsSync(path.join(this.path, "docker-compose.yml"))){
  37. this._composeFileName = "docker-compose.yml";
  38. } else if (fs.existsSync(path.join(this.path, "docker-compose.yaml"))){
  39. this._composeFileName = "docker-compose.yaml";
  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", "all" ], 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. log.warn("getStackList", `Failed to get stack ${filename}, error: ${e.message}`);
  170. }
  171. }
  172. // Cache by copying
  173. this.managedStackList = new Map(stackList);
  174. }
  175. // Also get the list from `docker compose ls --all --format json`
  176. let res = childProcess.execSync("docker compose ls --all --format json");
  177. let composeList = JSON.parse(res.toString());
  178. for (let composeStack of composeList) {
  179. // Skip the dockge stack
  180. // TODO: Could be self managed?
  181. if (composeStack.Name === "dockge") {
  182. continue;
  183. }
  184. let stack = stackList.get(composeStack.Name);
  185. // This stack probably is not managed by Dockge, but we still want to show it
  186. if (!stack) {
  187. stack = new Stack(server, composeStack.Name);
  188. stackList.set(composeStack.Name, stack);
  189. }
  190. stack._status = this.statusConvert(composeStack.Status);
  191. stack._configFilePath = composeStack.ConfigFiles;
  192. }
  193. return stackList;
  194. }
  195. /**
  196. * Get the status list, it will be used to update the status of the stacks
  197. * Not all status will be returned, only the stack that is deployed or created to `docker compose` will be returned
  198. */
  199. static getStatusList() : Map<string, number> {
  200. let statusList = new Map<string, number>();
  201. let res = childProcess.execSync("docker compose ls --all --format json");
  202. let composeList = JSON.parse(res.toString());
  203. for (let composeStack of composeList) {
  204. statusList.set(composeStack.Name, this.statusConvert(composeStack.Status));
  205. }
  206. return statusList;
  207. }
  208. /**
  209. * Convert the status string from `docker compose ls` to the status number
  210. * @param status
  211. */
  212. static statusConvert(status : string) : number {
  213. if (status.startsWith("created")) {
  214. return CREATED_STACK;
  215. } else if (status.startsWith("running")) {
  216. return RUNNING;
  217. } else if (status.startsWith("exited")) {
  218. return EXITED;
  219. } else {
  220. return UNKNOWN;
  221. }
  222. }
  223. static getStack(server: DockgeServer, stackName: string) : Stack {
  224. let dir = path.join(server.stacksDir, stackName);
  225. if (!fs.existsSync(dir) || !fs.statSync(dir).isDirectory()) {
  226. // Maybe it is a stack managed by docker compose directly
  227. let stackList = this.getStackList(server);
  228. let stack = stackList.get(stackName);
  229. if (stack) {
  230. return stack;
  231. } else {
  232. // Really not found
  233. throw new ValidationError("Stack not found");
  234. }
  235. }
  236. let stack = new Stack(server, stackName);
  237. stack._status = UNKNOWN;
  238. stack._configFilePath = path.resolve(dir);
  239. return stack;
  240. }
  241. async start(socket: DockgeSocket) {
  242. const terminalName = getComposeTerminalName(this.name);
  243. let exitCode = await Terminal.exec(this.server, socket, terminalName, "docker", [ "compose", "up", "-d", "--remove-orphans" ], this.path);
  244. if (exitCode !== 0) {
  245. throw new Error("Failed to start, please check the terminal output for more information.");
  246. }
  247. return exitCode;
  248. }
  249. async stop(socket: DockgeSocket) : Promise<number> {
  250. const terminalName = getComposeTerminalName(this.name);
  251. let exitCode = await Terminal.exec(this.server, socket, terminalName, "docker", [ "compose", "stop" ], this.path);
  252. if (exitCode !== 0) {
  253. throw new Error("Failed to stop, please check the terminal output for more information.");
  254. }
  255. return exitCode;
  256. }
  257. async restart(socket: DockgeSocket) : Promise<number> {
  258. const terminalName = getComposeTerminalName(this.name);
  259. let exitCode = await Terminal.exec(this.server, socket, terminalName, "docker", [ "compose", "restart" ], this.path);
  260. if (exitCode !== 0) {
  261. throw new Error("Failed to restart, please check the terminal output for more information.");
  262. }
  263. return exitCode;
  264. }
  265. async update(socket: DockgeSocket) {
  266. const terminalName = getComposeTerminalName(this.name);
  267. let exitCode = await Terminal.exec(this.server, socket, terminalName, "docker", [ "compose", "pull" ], this.path);
  268. if (exitCode !== 0) {
  269. throw new Error("Failed to pull, please check the terminal output for more information.");
  270. }
  271. exitCode = await Terminal.exec(this.server, socket, terminalName, "docker", [ "compose", "up", "-d", "--remove-orphans" ], this.path);
  272. if (exitCode !== 0) {
  273. throw new Error("Failed to restart, please check the terminal output for more information.");
  274. }
  275. return exitCode;
  276. }
  277. async joinCombinedTerminal(socket: DockgeSocket) {
  278. const terminalName = getCombinedTerminalName(this.name);
  279. const terminal = Terminal.getOrCreateTerminal(this.server, terminalName, "docker", [ "compose", "logs", "-f", "--tail", "100" ], this.path);
  280. terminal.rows = COMBINED_TERMINAL_ROWS;
  281. terminal.cols = COMBINED_TERMINAL_COLS;
  282. terminal.join(socket);
  283. terminal.start();
  284. }
  285. async joinContainerTerminal(socket: DockgeSocket, serviceName: string, shell : string = "sh", index: number = 0) {
  286. const terminalName = getContainerExecTerminalName(this.name, serviceName, index);
  287. let terminal = Terminal.getTerminal(terminalName);
  288. if (!terminal) {
  289. terminal = new InteractiveTerminal(this.server, terminalName, "docker", [ "compose", "exec", serviceName, shell ], this.path);
  290. terminal.rows = TERMINAL_ROWS;
  291. log.debug("joinContainerTerminal", "Terminal created");
  292. }
  293. terminal.join(socket);
  294. terminal.start();
  295. }
  296. async getServiceStatusList() {
  297. let statusList = new Map<string, number>();
  298. let res = childProcess.execSync("docker compose ps --format json", {
  299. cwd: this.path,
  300. });
  301. let lines = res.toString().split("\n");
  302. for (let line of lines) {
  303. try {
  304. let obj = JSON.parse(line);
  305. statusList.set(obj.Service, obj.State);
  306. } catch (e) {
  307. }
  308. }
  309. return statusList;
  310. }
  311. }