dashboard.js 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570
  1. import { Readable } from 'stream';
  2. import { readFileSync } from 'fs';
  3. import { currentLoad, mem, networkStats, fsSize, dockerContainerStats } from 'systeminformation';
  4. import { Op } from 'sequelize';
  5. import Docker from 'dockerode';
  6. import { Permission, User, ServerSettings } from '../database/models.js';
  7. import { docker, docker2, docker3, docker4, host_list, host2_list, host3_list, host4_list } from '../server.js';
  8. let [ hidden, alert, newCards, stats ] = [ '', '', '', {} ];
  9. let logString = '';
  10. // async function hostInfo(host) {
  11. // let info = await ServerSettings.findOne({ where: {key: host}});
  12. // try {
  13. // if (info.value != 'off' && info.value != '') {
  14. // let values = info.value.split(',');
  15. // return { tag: values[0], ip: values[1], port: values[2] };
  16. // }
  17. // } catch {
  18. // // console.log(`${host}: No Value Set`);
  19. // }
  20. // }
  21. export const Dashboard = async (req, res) => {
  22. console.log(`Viewing Host: ${req.params.host}`);
  23. let { link1, link2, link3, link4, link5, link6, link7, link8, link9 } = ['', '', '', '', '', '', '', '', ''];
  24. // let host2 = await hostInfo('host2');
  25. // let host3 = await hostInfo('host3');
  26. // let host4 = await hostInfo('host4');
  27. if (docker2 || docker3 || docker4) {
  28. link1 = `<a href="/1/dashboard" class="btn text-green" name="host">
  29. Host 1
  30. </a>`;
  31. link5 = `<a href="/0/dashboard" class="btn text-green" name="hosts">
  32. All
  33. </a>`;
  34. }
  35. if (docker2) { link2 = `<a href="/2/dashboard" class="btn text-green" name="host2">
  36. Host2
  37. </a>`;
  38. }
  39. if (docker3) { link3 = `<a href="/3/dashboard" class="btn text-green" name="host3">
  40. Host3
  41. </a>`;
  42. }
  43. if (docker4) { link4 = `<a href="/4/dashboard" class="btn text-green" name="host4">
  44. Host4
  45. </a>`;
  46. }
  47. res.render("dashboard", {
  48. username: req.session.username,
  49. avatar: req.session.username.charAt(0).toUpperCase(),
  50. role: req.session.role,
  51. alert: req.session.alert,
  52. link1: link1,
  53. link2: link2,
  54. link3: link3,
  55. link4: link4,
  56. link5: link5,
  57. link6: '',
  58. link7: '',
  59. link8: '',
  60. link9: '',
  61. });
  62. }
  63. export const ContainerAction = async (req, res) => {
  64. // Assign values
  65. let container_name = req.header('hx-trigger-name');
  66. let container_id = req.header('hx-trigger');
  67. let action = req.params.action;
  68. if (container_id == 'reset') {
  69. console.log('Resetting view');
  70. await Permission.update({ hide: false }, { where: { userID: req.session.userID } });
  71. res.send('ok');
  72. return;
  73. }
  74. // Inspect the container
  75. let container = docker.getContainer(container_id);
  76. let containerInfo = await container.inspect();
  77. let state = containerInfo.State.Status;
  78. console.log(`Container: ${container_name} ID: ${container_id} State: ${state} Action: ${action}`);
  79. function status (state) {
  80. return(`<span class="text-yellow align-items-center lh-1"><svg xmlns="http://www.w3.org/2000/svg" class="icon-tabler icon-tabler-point-filled" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round"> <path stroke="none" d="M0 0h24v24H0z" fill="none"></path> <path d="M12 7a5 5 0 1 1 -4.995 5.217l-.005 -.217l.005 -.217a5 5 0 0 1 4.995 -4.783z" stroke-width="0" fill="currentColor"></path></svg>
  81. ${state}
  82. </span>`);
  83. }
  84. if ((action == 'start') && (state == 'exited')) {
  85. await container.start();
  86. res.send(status('starting'));
  87. } else if ((action == 'start') && (state == 'paused')) {
  88. await container.unpause();
  89. res.send(status('starting'));
  90. } else if ((action == 'stop') && (state != 'exited')) {
  91. await container.stop();
  92. res.send(status('stopping'));
  93. } else if ((action == 'pause') && (state == 'paused')) {
  94. await container.unpause();
  95. res.send(status('starting'));
  96. } else if ((action == 'pause') && (state == 'running')) {
  97. await container.pause();
  98. res.send(status('pausing'));
  99. } else if (action == 'restart') {
  100. await container.restart();
  101. res.send(status('restarting'));
  102. } else if (action == 'hide') {
  103. let exists = await Permission.findOne({ where: { containerID: container_id, userID: req.session.userID }});
  104. if (!exists) { const newPermission = await Permission.create({ containerName: container_name, containerID: container_id, username: req.session.username, userID: req.session.userID, hide: true }); }
  105. else { exists.update({ hide: true }); }
  106. // Array of hidden containers
  107. hidden = await Permission.findAll({ where: { userID: req.session.userID, hide: true}}, { attributes: ['containerID'] });
  108. // Map the container IDs
  109. hidden = hidden.map((container) => container.containerID);
  110. console.log(hidden);
  111. res.send("ok");
  112. }
  113. }
  114. export const DashboardAction = async (req, res) => {
  115. let name = req.header('hx-trigger-name');
  116. let value = req.header('hx-trigger');
  117. let action = req.params.action;
  118. let modal = '';
  119. // console.log(`Action: ${action} Name: ${name} Value: ${value}`);
  120. if (req.body.search) {
  121. console.log(req.body.search);
  122. res.send('search');
  123. return;
  124. }
  125. switch (action) {
  126. // case 'checkhost':
  127. // let link = '';
  128. // let host_info = await hostInfo(name);
  129. // try {
  130. // var docker2 = new Docker({ protocol: 'http', host: host_info.ip, port: host_info.port });
  131. // let containers = await docker2.listContainers({ all: true });
  132. // link = `<button class="btn text-green" name="host2">
  133. // ${host_info.tag}
  134. // </button>`;
  135. // } catch {
  136. // console.log(`Error connecting to ${name}`);
  137. // link = `<button class="btn text-red" name="host2">
  138. // ${host_info.tag}
  139. // </button>`;
  140. // }
  141. // res.send(link);
  142. // return;
  143. case 'permissions': // (Action = Selecting 'Permissions' from the dropdown) Creates the permissions modal
  144. // To capitalize the title
  145. let title = name.charAt(0).toUpperCase() + name.slice(1);
  146. // Empty the permissions list
  147. let permissions_list = '';
  148. // Get the container ID
  149. let container = docker.getContainer(name);
  150. let containerInfo = await container.inspect();
  151. let container_id = containerInfo.Id;
  152. // Get the body of the permissions modal
  153. let permissions_modal = readFileSync('./views/modals/permissions.html', 'utf8');
  154. // Replace the title and container name in the modal
  155. permissions_modal = permissions_modal.replace(/PermissionsTitle/g, title);
  156. permissions_modal = permissions_modal.replace(/PermissionsContainer/g, name);
  157. permissions_modal = permissions_modal.replace(/ContainerID/g, container_id);
  158. // Get a list of all users
  159. let users = await User.findAll({ attributes: ['username', 'userID']});
  160. // Loop through each user to check what permissions they have
  161. for (let i = 0; i < users.length; i++) {
  162. // Get the user_permissions form
  163. let user_permissions = readFileSync('./views/partials/user_permissions.html', 'utf8');
  164. // Check if the user has any permissions for the container
  165. let exists = await Permission.findOne({ where: { containerID: container_id, userID: users[i].userID }});
  166. // Create an entry if one doesn't exist
  167. if (!exists) { const newPermission = await Permission.create({ containerName: name, containerID: container_id, username: users[i].username, userID: users[i].userID }); }
  168. // Get the permissions for the user
  169. let permissions = await Permission.findOne({ where: { containerID: container_id, userID: users[i].userID }});
  170. // Fill in the form values
  171. if (permissions.uninstall == true) { user_permissions = user_permissions.replace(/data-UninstallCheck/g, 'checked'); }
  172. if (permissions.edit == true) { user_permissions = user_permissions.replace(/data-EditCheck/g, 'checked'); }
  173. if (permissions.upgrade == true) { user_permissions = user_permissions.replace(/data-UpgradeCheck/g, 'checked'); }
  174. if (permissions.start == true) { user_permissions = user_permissions.replace(/data-StartCheck/g, 'checked'); }
  175. if (permissions.stop == true) { user_permissions = user_permissions.replace(/data-StopCheck/g, 'checked'); }
  176. if (permissions.pause == true) { user_permissions = user_permissions.replace(/data-PauseCheck/g, 'checked'); }
  177. if (permissions.restart == true) { user_permissions = user_permissions.replace(/data-RestartCheck/g, 'checked'); }
  178. if (permissions.logs == true) { user_permissions = user_permissions.replace(/data-LogsCheck/g, 'checked'); }
  179. if (permissions.view == true) { user_permissions = user_permissions.replace(/data-ViewCheck/g, 'checked'); }
  180. user_permissions = user_permissions.replace(/EntryNumber/g, i);
  181. user_permissions = user_permissions.replace(/EntryNumber/g, i);
  182. user_permissions = user_permissions.replace(/EntryNumber/g, i);
  183. user_permissions = user_permissions.replace(/PermissionsUsername/g, users[i].username);
  184. user_permissions = user_permissions.replace(/PermissionsUsername/g, users[i].username);
  185. user_permissions = user_permissions.replace(/PermissionsUsername/g, users[i].username);
  186. user_permissions = user_permissions.replace(/PermissionsContainer/g, name);
  187. user_permissions = user_permissions.replace(/PermissionsContainer/g, name);
  188. user_permissions = user_permissions.replace(/PermissionsContainer/g, name);
  189. user_permissions = user_permissions.replace(/PermissionsUserID/g, users[i].userID);
  190. user_permissions = user_permissions.replace(/PermissionsID/g, container_id);
  191. // Add the user entry to the permissions list
  192. permissions_list += user_permissions;
  193. }
  194. // Insert the user list into the permissions modal
  195. permissions_modal = permissions_modal.replace(/PermissionsList/g, permissions_list);
  196. // Send the permissions modal
  197. res.send(permissions_modal);
  198. return;
  199. case 'uninstall':
  200. modal = readFileSync('./views/modals/uninstall.html', 'utf8');
  201. modal = modal.replace(/AppName/g, name);
  202. res.send(modal);
  203. return;
  204. case 'details':
  205. modal = readFileSync('./views/modals/details.html', 'utf8');
  206. let details = await containerInfo(name);
  207. modal = modal.replace(/AppName/g, details.name);
  208. modal = modal.replace(/AppImage/g, details.image);
  209. for (let i = 0; i <= 6; i++) {
  210. modal = modal.replaceAll(`Port${i}Check`, details.ports[i]?.check || '');
  211. modal = modal.replaceAll(`Port${i}External`, details.ports[i]?.external || '');
  212. modal = modal.replaceAll(`Port${i}Internal`, details.ports[i]?.internal || '');
  213. modal = modal.replaceAll(`Port${i}Protocol`, details.ports[i]?.protocol || '');
  214. }
  215. for (let i = 0; i <= 6; i++) {
  216. modal = modal.replaceAll(`Vol${i}Source`, details.volumes[i]?.Source || '');
  217. modal = modal.replaceAll(`Vol${i}Destination`, details.volumes[i]?.Destination || '');
  218. modal = modal.replaceAll(`Vol${i}RW`, details.volumes[i]?.RW || '');
  219. }
  220. for (let i = 0; i <= 19; i++) {
  221. modal = modal.replaceAll(`Label${i}Key`, Object.keys(details.labels)[i] || '');
  222. modal = modal.replaceAll(`Label${i}Value`, Object.values(details.labels)[i] || '');
  223. }
  224. // console.log(details.env);
  225. for (let i = 0; i <= 19; i++) {
  226. modal = modal.replaceAll(`Env${i}Key`, details.env[i]?.split('=')[0] || '');
  227. modal = modal.replaceAll(`Env${i}Value`, details.env[i]?.split('=')[1] || '');
  228. }
  229. res.send(modal);
  230. return;
  231. case 'updates':
  232. res.send(newCards);
  233. newCards = '';
  234. return;
  235. case 'card':
  236. // Check which cards the user has permissions for
  237. await userCards(req.session);
  238. // Remove the container if it isn't in the user's list
  239. if (!req.session.container_list.find(c => c.container === name)) {
  240. res.send('');
  241. return;
  242. } else {
  243. // Get the container information and send the updated card
  244. let details = await containerInfo(value);
  245. let card = await createCard(details);
  246. res.send(card);
  247. return;
  248. }
  249. case 'logs':
  250. logString = '';
  251. let options = { follow: false, stdout: true, stderr: false, timestamps: true };
  252. console.log(`Getting logs for ${name}`);
  253. docker.getContainer(name).logs(options, function (err, stream) {
  254. if (err) { console.log(`some error getting logs`); return; }
  255. const readableStream = Readable.from(stream);
  256. readableStream.on('data', function (chunk) {
  257. logString += chunk.toString('utf8');
  258. });
  259. readableStream.on('end', function () {
  260. res.send(`<pre>${logString}</pre>`);
  261. });
  262. });
  263. return;
  264. case 'alert':
  265. req.session.alert = '';
  266. res.send('');
  267. return;
  268. }
  269. }
  270. async function containerInfo (containerID) {
  271. // get the container info
  272. let container = docker.getContainer(containerID);
  273. let info = await container.inspect();
  274. let image = info.Config.Image;
  275. let container_id = info.Id;
  276. // grab the service name from the end of the image name
  277. let service = image.split('/').pop();
  278. // remove the tag from the service name if it exists
  279. try { service = service.split(':')[0]; } catch {}
  280. let ports_list = [];
  281. let external = 0;
  282. let internal = 0;
  283. try {
  284. for (const [key, value] of Object.entries(info.HostConfig.PortBindings)) {
  285. let ports = {
  286. check: 'checked',
  287. external: value[0].HostPort,
  288. internal: key.split('/')[0],
  289. protocol: key.split('/')[1]
  290. }
  291. ports_list.push(ports);
  292. }
  293. } catch {}
  294. try {
  295. external = ports_list[0].external;
  296. internal = ports_list[0].internal;
  297. } catch {}
  298. let details = {
  299. name: info.Name.slice(1),
  300. image: image,
  301. service: service,
  302. containerID: container_id,
  303. state: info.State.Status,
  304. external_port: external,
  305. internal_port: internal,
  306. ports: ports_list,
  307. volumes: info.Mounts,
  308. env: info.Config.Env,
  309. labels: info.Config.Labels,
  310. link: 'localhost',
  311. }
  312. return details;
  313. }
  314. async function createCard (details) {
  315. let shortname = details.name.slice(0, 10) + '...';
  316. let trigger = 'data-hx-trigger="load, every 3s"';
  317. let state = details.state;
  318. let card = readFileSync('./views/partials/containerFull.html', 'utf8');
  319. let app_icon = (details.labels['com.docker.compose.service']);
  320. let links = await ServerSettings.findOne({ where: {key: 'links'}});
  321. if (!links) { links = { value: 'localhost' }; }
  322. let state_color = '';
  323. switch (state) {
  324. case 'running':
  325. state_color = 'green';
  326. break;
  327. case 'exited':
  328. state = 'stopped';
  329. state_color = 'red';
  330. trigger = 'data-hx-trigger="load"';
  331. break;
  332. case 'paused':
  333. state_color = 'orange';
  334. trigger = 'data-hx-trigger="load"';
  335. break;
  336. case 'installing':
  337. state_color = 'blue';
  338. trigger = 'data-hx-trigger="load"';
  339. break;
  340. }
  341. // if (name.startsWith('dweebui')) { disable = 'disabled=""'; }
  342. card = card.replace(/AppName/g, details.name);
  343. card = card.replace(/AppID/g, details.containerID);
  344. card = card.replace(/AppShortName/g, shortname);
  345. card = card.replace(/AppIcon/g, app_icon);
  346. card = card.replace(/AppState/g, state);
  347. card = card.replace(/StateColor/g, state_color);
  348. card = card.replace(/AppLink/g, links.value);
  349. card = card.replace(/ExternalPort/g, details.external_port);
  350. card = card.replace(/InternalPort/g, details.internal_port);
  351. card = card.replace(/ChartName/g, details.name.replace(/-/g, ''));
  352. card = card.replace(/AppNameState/g, `${details.name}State`);
  353. card = card.replace(/data-trigger=""/, trigger);
  354. return card;
  355. }
  356. // Creates a list of containers that the user should be able to see.
  357. async function userCards (session) {
  358. // Create an empty container list.
  359. session.container_list = [];
  360. // Check what containers the user has hidden.
  361. let hidden = await Permission.findAll({ where: { userID: session.userID, hide: true }, attributes: ['containerID'], raw: true });
  362. // Check which containers the user has permissions for.
  363. let visable = await Permission.findAll({ where: { userID: session.userID, [Op.or]: [{ uninstall: true }, { edit: true }, { upgrade: true }, { start: true }, { stop: true }, { pause: true }, { restart: true }, { logs: true }, { view: true }] }, attributes: ['containerID'], raw: true});
  364. // Get a list of all the containers.
  365. let containers = await docker.listContainers({ all: true });
  366. // Loop through the list of containers.
  367. for (let i = 0; i < containers.length; i++) {
  368. // Get the container ID.
  369. let containerID = containers[i].Id;
  370. // Skip the container if it's ID is in the hidden list.
  371. if (hidden.includes(containerID)) { console.log('skipped hidden container'); continue; }
  372. // If the user is admin and they don't have it hidden, add it to the list.
  373. if (session.role == 'admin') { session.container_list.push({ container: containerID, state: containers[i].State }); }
  374. // Add the container if it's ID is in the visable list.
  375. else if (visable.includes(containerID)){ session.container_list.push({ container: containerID, state: containers[i].State }); }
  376. }
  377. // Create the lists if they don't exist.
  378. if (!session.sent_list) { session.sent_list = []; }
  379. if (!session.update_list) { session.update_list = []; }
  380. if (!session.new_cards) { session.new_cards = []; }
  381. }
  382. async function updateDashboard (session) {
  383. // Get the list of containers and the list of containers that have been sent.
  384. let container_list = session.container_list;
  385. let sent_list = session.sent_list;
  386. session.new_cards = [];
  387. session.update_list = [];
  388. // Loop through the containers list
  389. container_list.forEach(info => {
  390. // Get the containerID and state
  391. let { container, state } = info;
  392. // Check if the container is in the sent list
  393. let sent = sent_list.find(c => c.container === container);
  394. // If it's not in the sent list, add it to the new cards list.
  395. if (!sent) { session.new_cards.push(container);}
  396. // If it is in the sent list, check if the state has changed.
  397. else if (sent.state !== state) { session.update_list.push(container); }
  398. });
  399. // Loop through the sent list to see if any containers have been removed
  400. sent_list.forEach(info => {
  401. let { container } = info;
  402. let exists = container_list.find(c => c.container === container);
  403. if (!exists) { session.update_list.push(container); }
  404. });
  405. }
  406. // HTMX server-side events
  407. export const SSE = async (req, res) => {
  408. // Set the headers
  409. res.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', 'Connection': 'keep-alive' });
  410. // Check for container changes every 500ms
  411. let eventCheck = setInterval(async () => {
  412. await userCards(req.session);
  413. // check if the cards displayed are the same as what's in the session
  414. if ((JSON.stringify(req.session.container_list) === JSON.stringify(req.session.sent_list))) { return; }
  415. await updateDashboard(req.session);
  416. for (let i = 0; i < req.session.new_cards.length; i++) {
  417. let details = await containerInfo(req.session.new_cards[i]);
  418. let card = await createCard(details);
  419. newCards += card;
  420. req.session.alert = '';
  421. }
  422. for (let i = 0; i < req.session.update_list.length; i++) {
  423. res.write(`event: ${req.session.update_list[i]}\n`);
  424. res.write(`data: 'update cards'\n\n`);
  425. }
  426. res.write(`event: update\n`);
  427. res.write(`data: 'update cards'\n\n`);
  428. req.session.sent_list = req.session.container_list.slice();
  429. }, 500);
  430. req.on('close', () => {
  431. clearInterval(eventCheck);
  432. });
  433. };
  434. // Server metrics (CPU, RAM, TX, RX, DISK)
  435. export const Stats = async (req, res) => {
  436. let name = req.header('hx-trigger-name');
  437. let color = req.header('hx-trigger');
  438. let value = 0;
  439. switch (name) {
  440. case 'CPU':
  441. await currentLoad().then(data => { value = Math.round(data.currentLoad); });
  442. break;
  443. case 'RAM':
  444. await mem().then(data => { value = Math.round((data.active / data.total) * 100); });
  445. break;
  446. case 'NET':
  447. let [down, up, percent] = [0, 0, 0];
  448. await networkStats().then(data => { down = Math.round(data[0].rx_bytes / (1024 * 1024)); up = Math.round(data[0].tx_bytes / (1024 * 1024)); percent = Math.round((down / 1000) * 100); });
  449. let net = `<div class="font-weight-medium"><label class="cpu-text mb-1">Down:${down}MB Up:${up}MB</label></div>
  450. <div class="cpu-bar meter animate ${color}"><span style="width:20%"><span></span></span></div>`;
  451. res.send(net);
  452. return;
  453. case 'DISK':
  454. await fsSize().then(data => { value = data[0].use; });
  455. break;
  456. }
  457. let info = `<div class="font-weight-medium"> <label class="cpu-text mb-1">${name} ${value}%</label></div>
  458. <div class="cpu-bar meter animate ${color}"><span style="width:${value}%"><span></span></span></div>`;
  459. res.send(info);
  460. }
  461. // Imported by utils/install.js
  462. export async function addAlert (session, type, message) {
  463. session.alert = `<div class="alert alert-${type} alert-dismissible py-2 mb-0" role="alert" id="alert">
  464. <div class="d-flex">
  465. <div class="spinner-border text-info nav-link">
  466. <span class="visually-hidden">Loading...</span>
  467. </div>
  468. <div>
  469.   ${message}
  470. </div>
  471. </div>
  472. <button class="btn-close" data-hx-post="/dashboard/alert" data-hx-trigger="click" data-hx-target="#alert" data-hx-swap="outerHTML" style="padding-top: 0.5rem;"></button>
  473. </div>`;
  474. }
  475. export const UpdatePermissions = async (req, res) => {
  476. let { userID, container, containerID, reset_permissions } = req.body;
  477. let id = req.header('hx-trigger');
  478. console.log(`User: ${userID} Container: ${container} ContainerID: ${containerID} Reset: ${reset_permissions}`);
  479. if (reset_permissions) {
  480. await Permission.update({ uninstall: false, edit: false, upgrade: false, start: false, stop: false, pause: false, restart: false, logs: false, view: false }, { where: { containerID: containerID} });
  481. return;
  482. }
  483. await Permission.update({ uninstall: false, edit: false, upgrade: false, start: false, stop: false, pause: false, restart: false, logs: false, view: false}, { where: { containerID: containerID, userID: userID } });
  484. Object.keys(req.body).forEach(async function(key) {
  485. if (key != 'user' && key != 'container') {
  486. let permissions = req.body[key];
  487. if (permissions.includes('uninstall')) { await Permission.update({ uninstall: true }, { where: { containerID: containerID, userID: userID}}); }
  488. if (permissions.includes('edit')) { await Permission.update({ edit: true }, { where: { containerID: containerID, userID: userID}}); }
  489. if (permissions.includes('upgrade')) { await Permission.update({ upgrade: true }, { where: { containerID: containerID, userID: userID}}); }
  490. if (permissions.includes('start')) { await Permission.update({ start: true }, { where: { containerID: containerID, userID: userID}}); }
  491. if (permissions.includes('stop')) { await Permission.update({ stop: true }, { where: { containerID: containerID, userID: userID}}); }
  492. if (permissions.includes('pause')) { await Permission.update({ pause: true }, { where: { containerID: containerID, userID: userID}}); }
  493. if (permissions.includes('restart')) { await Permission.update({ restart: true }, { where: { containerID: containerID, userID: userID}}); }
  494. if (permissions.includes('logs')) { await Permission.update({ logs: true }, { where: { containerID: containerID, userID: userID}}); }
  495. if (permissions.includes('view')) { await Permission.update({ view: true }, { where: { containerID: containerID, userID: userID}}); }
  496. }
  497. });
  498. if (id == 'submit') {
  499. res.send('<button class="btn" type="button" id="confirmed" hx-post="/updatePermissions" hx-swap="outerHTML" hx-trigger="load delay:2s">Update ✔️</button>');
  500. return;
  501. } else if (id == 'confirmed') {
  502. res.send('<button class="btn" type="button" id="submit" hx-post="/updatePermissions" hx-vals="#updatePermissions" hx-swap="outerHTML">Update </button>');
  503. return;
  504. }
  505. }
  506. // Container charts
  507. export const Chart = async (req, res) => {
  508. let name = req.header('hx-trigger-name');
  509. if (!stats[name]) { stats[name] = { cpuArray: Array(15).fill(0), ramArray: Array(15).fill(0) }; }
  510. const info = await dockerContainerStats(name);
  511. stats[name].cpuArray.push(Math.round(info[0].cpuPercent));
  512. stats[name].ramArray.push(Math.round(info[0].memPercent));
  513. stats[name].cpuArray = stats[name].cpuArray.slice(-15);
  514. stats[name].ramArray = stats[name].ramArray.slice(-15);
  515. let chart = `
  516. <script>
  517. ${name}chart.updateSeries([{data: [${stats[name].cpuArray}]}, {data: [${stats[name].ramArray}]}])
  518. </script>`
  519. res.send(chart);
  520. }