apps.js 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  1. const asyncWrapper = require('../middleware/asyncWrapper');
  2. const ErrorResponse = require('../utils/ErrorResponse');
  3. const App = require('../models/App');
  4. const Config = require('../models/Config');
  5. const { Sequelize } = require('sequelize');
  6. const axios = require('axios');
  7. const Logger = require('../utils/Logger');
  8. const logger = new Logger();
  9. const k8s = require('@kubernetes/client-node');
  10. // @desc Create new app
  11. // @route POST /api/apps
  12. // @access Public
  13. exports.createApp = asyncWrapper(async (req, res, next) => {
  14. // Get config from database
  15. const pinApps = await Config.findOne({
  16. where: { key: 'pinAppsByDefault' },
  17. });
  18. let app;
  19. let _body = { ...req.body };
  20. if (req.file) {
  21. _body.icon = req.file.filename;
  22. }
  23. if (pinApps) {
  24. if (parseInt(pinApps.value)) {
  25. app = await App.create({
  26. ..._body,
  27. isPinned: true,
  28. });
  29. } else {
  30. app = await App.create(req.body);
  31. }
  32. }
  33. res.status(201).json({
  34. success: true,
  35. data: app,
  36. });
  37. });
  38. // @desc Get all apps
  39. // @route GET /api/apps
  40. // @access Public
  41. exports.getApps = asyncWrapper(async (req, res, next) => {
  42. // Get config from database
  43. const useOrdering = await Config.findOne({
  44. where: { key: 'useOrdering' },
  45. });
  46. const useDockerApi = await Config.findOne({
  47. where: { key: 'dockerApps' },
  48. });
  49. const useKubernetesApi = await Config.findOne({
  50. where: { key: 'kubernetesApps' },
  51. });
  52. const unpinStoppedApps = await Config.findOne({
  53. where: { key: 'unpinStoppedApps' },
  54. });
  55. const orderType = useOrdering ? useOrdering.value : 'createdAt';
  56. let apps;
  57. if (useDockerApi && useDockerApi.value == 1) {
  58. let containers = null;
  59. const host = await Config.findOne({
  60. where: { key: 'dockerHost' },
  61. });
  62. try {
  63. if (host.value.includes('localhost')) {
  64. let { data } = await axios.get(
  65. `http://${host.value}/containers/json?{"status":["running"]}`,
  66. {
  67. socketPath: '/var/run/docker.sock',
  68. }
  69. );
  70. containers = data;
  71. } else {
  72. let { data } = await axios.get(
  73. `http://${host.value}/containers/json?{"status":["running"]}`
  74. );
  75. containers = data;
  76. }
  77. } catch {
  78. logger.log(`Can't connect to the docker api on ${host.value}`, 'ERROR');
  79. }
  80. if (containers) {
  81. apps = await App.findAll({
  82. order: [[orderType, 'ASC']],
  83. });
  84. containers = containers.filter((e) => Object.keys(e.Labels).length !== 0);
  85. const dockerApps = [];
  86. for (const container of containers) {
  87. let labels = container.Labels;
  88. if (!('flame.url' in labels)) {
  89. for (const label of Object.keys(labels)) {
  90. if (/^traefik.*.frontend.rule/.test(label)) {
  91. // Traefik 1.x
  92. let value = labels[label];
  93. if (value.indexOf('Host') !== -1) {
  94. value = value.split('Host:')[1];
  95. labels['flame.url'] = 'https://' + value.split(',').join(';https://');
  96. }
  97. } else if (/^traefik.*?\.rule/.test(label)) {
  98. // Traefik 2.x
  99. const value = labels[label];
  100. if (value.indexOf('Host') !== -1) {
  101. const regex = /\`([a-zA-Z0-9\.\-]+)\`/g;
  102. const domains = []
  103. while ((match = regex.exec(value)) != null) {
  104. domains.push('http://' + match[1]);
  105. }
  106. if (domains.length > 0) {
  107. labels['flame.url'] = domains.join(';');
  108. }
  109. }
  110. }
  111. }
  112. }
  113. if (
  114. 'flame.name' in labels &&
  115. 'flame.url' in labels &&
  116. /^app/.test(labels['flame.type'])
  117. ) {
  118. for (let i = 0; i < labels['flame.name'].split(';').length; i++) {
  119. const names = labels['flame.name'].split(';');
  120. const urls = labels['flame.url'].split(';');
  121. let icons = '';
  122. if ('flame.icon' in labels) {
  123. icons = labels['flame.icon'].split(';');
  124. }
  125. dockerApps.push({
  126. name: names[i] || names[0],
  127. url: urls[i] || urls[0],
  128. icon: icons[i] || 'docker',
  129. });
  130. }
  131. }
  132. }
  133. if (unpinStoppedApps && unpinStoppedApps.value == 1) {
  134. for (const app of apps) {
  135. await app.update({ isPinned: false });
  136. }
  137. }
  138. for (const item of dockerApps) {
  139. if (apps.some((app) => app.name === item.name)) {
  140. const app = apps.filter((e) => e.name === item.name)[0];
  141. if (
  142. item.icon === 'custom' ||
  143. (item.icon === 'docker' && app.icon != 'docker')
  144. ) {
  145. await app.update({
  146. name: item.name,
  147. url: item.url,
  148. isPinned: true,
  149. });
  150. } else {
  151. await app.update({
  152. name: item.name,
  153. url: item.url,
  154. icon: item.icon,
  155. isPinned: true,
  156. });
  157. }
  158. } else {
  159. await App.create({
  160. name: item.name,
  161. url: item.url,
  162. icon: item.icon === 'custom' ? 'docker' : item.icon,
  163. isPinned: true,
  164. });
  165. }
  166. }
  167. }
  168. }
  169. if (useKubernetesApi && useKubernetesApi.value == 1) {
  170. let ingresses = null;
  171. try {
  172. const kc = new k8s.KubeConfig();
  173. kc.loadFromCluster();
  174. const k8sNetworkingV1Api = kc.makeApiClient(k8s.NetworkingV1Api);
  175. await k8sNetworkingV1Api.listIngressForAllNamespaces().then((res) => {
  176. ingresses = res.body.items;
  177. });
  178. } catch {
  179. logger.log("Can't connect to the kubernetes api", 'ERROR');
  180. }
  181. if (ingresses) {
  182. apps = await App.findAll({
  183. order: [[orderType, 'ASC']],
  184. });
  185. ingresses = ingresses.filter(
  186. (e) => Object.keys(e.metadata.annotations).length !== 0
  187. );
  188. const kubernetesApps = [];
  189. for (const ingress of ingresses) {
  190. const annotations = ingress.metadata.annotations;
  191. if (
  192. 'flame.pawelmalak/name' in annotations &&
  193. 'flame.pawelmalak/url' in annotations &&
  194. /^app/.test(annotations['flame.pawelmalak/type'])
  195. ) {
  196. kubernetesApps.push({
  197. name: annotations['flame.pawelmalak/name'],
  198. url: annotations['flame.pawelmalak/url'],
  199. icon: annotations['flame.pawelmalak/icon'] || 'kubernetes',
  200. });
  201. }
  202. }
  203. if (unpinStoppedApps && unpinStoppedApps.value == 1) {
  204. for (const app of apps) {
  205. await app.update({ isPinned: false });
  206. }
  207. }
  208. for (const item of kubernetesApps) {
  209. if (apps.some((app) => app.name === item.name)) {
  210. const app = apps.filter((e) => e.name === item.name)[0];
  211. await app.update({ ...item, isPinned: true });
  212. } else {
  213. await App.create({
  214. ...item,
  215. isPinned: true,
  216. });
  217. }
  218. }
  219. }
  220. }
  221. if (orderType == 'name') {
  222. apps = await App.findAll({
  223. order: [[Sequelize.fn('lower', Sequelize.col('name')), 'ASC']],
  224. });
  225. } else {
  226. apps = await App.findAll({
  227. order: [[orderType, 'ASC']],
  228. });
  229. }
  230. if (process.env.NODE_ENV === 'production') {
  231. // Set header to fetch containers info every time
  232. res.status(200).setHeader('Cache-Control', 'no-store').json({
  233. success: true,
  234. data: apps,
  235. });
  236. return;
  237. }
  238. res.status(200).json({
  239. success: true,
  240. data: apps,
  241. });
  242. });
  243. // @desc Get single app
  244. // @route GET /api/apps/:id
  245. // @access Public
  246. exports.getApp = asyncWrapper(async (req, res, next) => {
  247. const app = await App.findOne({
  248. where: { id: req.params.id },
  249. });
  250. if (!app) {
  251. return next(
  252. new ErrorResponse(`App with id of ${req.params.id} was not found`, 404)
  253. );
  254. }
  255. res.status(200).json({
  256. success: true,
  257. data: app,
  258. });
  259. });
  260. // @desc Update app
  261. // @route PUT /api/apps/:id
  262. // @access Public
  263. exports.updateApp = asyncWrapper(async (req, res, next) => {
  264. let app = await App.findOne({
  265. where: { id: req.params.id },
  266. });
  267. if (!app) {
  268. return next(
  269. new ErrorResponse(`App with id of ${req.params.id} was not found`, 404)
  270. );
  271. }
  272. let _body = { ...req.body };
  273. if (req.file) {
  274. _body.icon = req.file.filename;
  275. }
  276. app = await app.update(_body);
  277. res.status(200).json({
  278. success: true,
  279. data: app,
  280. });
  281. });
  282. // @desc Delete app
  283. // @route DELETE /api/apps/:id
  284. // @access Public
  285. exports.deleteApp = asyncWrapper(async (req, res, next) => {
  286. await App.destroy({
  287. where: { id: req.params.id },
  288. });
  289. res.status(200).json({
  290. success: true,
  291. data: {},
  292. });
  293. });
  294. // @desc Reorder apps
  295. // @route PUT /api/apps/0/reorder
  296. // @access Public
  297. exports.reorderApps = asyncWrapper(async (req, res, next) => {
  298. req.body.apps.forEach(async ({ id, orderId }) => {
  299. await App.update(
  300. { orderId },
  301. {
  302. where: { id },
  303. }
  304. );
  305. });
  306. res.status(200).json({
  307. success: true,
  308. data: {},
  309. });
  310. });