marshaller.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731
  1. import './ActionButton.js' // To define action-button
  2. import { ExecutionDialog } from './ExecutionDialog.js'
  3. import { ActionStatusDisplay } from './ActionStatusDisplay.js'
  4. function createElement (tag, attributes) {
  5. const el = document.createElement(tag)
  6. if (attributes !== null) {
  7. if (attributes.classNames !== undefined) {
  8. el.classList.add(...attributes.classNames)
  9. }
  10. if (attributes.innerText !== undefined) {
  11. el.innerText = attributes.innerText
  12. }
  13. }
  14. return el
  15. }
  16. function createTag (val) {
  17. const domTag = createElement('span', {
  18. innerText: val,
  19. classNames: ['tag']
  20. })
  21. return domTag
  22. }
  23. function createAnnotation (key, val) {
  24. const domAnnotation = createElement('span', {
  25. classNames: ['annotation']
  26. })
  27. domAnnotation.appendChild(createElement('span', {
  28. innerText: key,
  29. classNames: ['annotation-key']
  30. }))
  31. domAnnotation.appendChild(createElement('span', {
  32. innerText: val,
  33. classNames: ['annotation-value']
  34. }))
  35. return domAnnotation
  36. }
  37. /**
  38. * This is a weird function that just sets some globals.
  39. */
  40. export function initMarshaller () {
  41. window.showSection = showSection
  42. window.showSectionView = showSectionView
  43. window.executionDialog = new ExecutionDialog()
  44. window.logEntries = new Map()
  45. window.registeredPaths = new Map()
  46. window.breadcrumbNavigation = []
  47. window.currentPath = ''
  48. window.addEventListener('EventExecutionStarted', onExecutionStarted)
  49. window.addEventListener('EventExecutionFinished', onExecutionFinished)
  50. window.addEventListener('EventOutputChunk', onOutputChunk)
  51. }
  52. function setUsername (username, provider) {
  53. document.getElementById('username').innerText = username
  54. document.getElementById('username').setAttribute('title', provider)
  55. if (window.settings.AuthLocalLogin || window.settings.AuthOAuth2Providers !== null) {
  56. if (username === 'guest') {
  57. document.getElementById('link-login').hidden = false
  58. document.getElementById('link-logout').hidden = true
  59. } else {
  60. document.getElementById('link-login').hidden = true
  61. if (provider === 'local' || provider === 'oauth2') {
  62. document.getElementById('link-logout').hidden = false
  63. }
  64. }
  65. }
  66. }
  67. export function marshalDashboardComponentsJsonToHtml (json) {
  68. if (json == null) { // eg: HTTP 403
  69. setUsername('guest', 'system')
  70. if (window.settings.AuthLoginUrl !== '') {
  71. window.location = window.settings.AuthLoginUrl
  72. } else {
  73. showSection('/login')
  74. }
  75. } else {
  76. setUsername(json.authenticatedUser, json.authenticatedUserProvider)
  77. marshalActionsJsonToHtml(json)
  78. marshalDashboardStructureToHtml(json)
  79. }
  80. document.body.setAttribute('initial-marshal-complete', 'true')
  81. }
  82. function marshalActionsJsonToHtml (json) {
  83. const currentIterationTimestamp = Date.now()
  84. window.actionButtons = {}
  85. for (const jsonButton of json.actions) {
  86. let htmlButton = window.actionButtons[jsonButton.id]
  87. if (typeof htmlButton === 'undefined') {
  88. htmlButton = document.createElement('action-button')
  89. htmlButton.constructFromJson(jsonButton)
  90. window.actionButtons[jsonButton.title] = htmlButton
  91. }
  92. htmlButton.updateFromJson(jsonButton)
  93. htmlButton.updateIterationTimestamp = currentIterationTimestamp
  94. }
  95. // Remove existing, but stale buttons (that were not updated in this round)
  96. for (const existingButton of document.querySelectorAll('action-button')) {
  97. if (existingButton.updateIterationTimestamp !== currentIterationTimestamp) {
  98. existingButton.remove()
  99. }
  100. }
  101. }
  102. function onOutputChunk (evt) {
  103. const chunk = evt.payload
  104. if (chunk.executionTrackingId === window.executionDialog.executionTrackingId) {
  105. window.terminal.write(chunk.output)
  106. window.executionDialog.showOutput()
  107. }
  108. }
  109. function onExecutionStarted (evt) {
  110. const logEntry = evt.payload.logEntry
  111. marshalLogsJsonToHtml({
  112. logs: [logEntry]
  113. })
  114. }
  115. function onExecutionFinished (evt) {
  116. const logEntry = evt.payload.logEntry
  117. window.logEntries.set(logEntry.executionTrackingId, logEntry)
  118. const actionButton = window.actionButtons[logEntry.actionTitle]
  119. if (actionButton === undefined) {
  120. return
  121. }
  122. let feedbackButton = actionButton;
  123. switch (actionButton.popupOnStart) {
  124. case 'execution-button':
  125. let executionButton = document.querySelector('execution-button#execution-' + logEntry.executionTrackingId)
  126. if (executionButton != null) {
  127. feedbackButton = executionButton
  128. }
  129. break
  130. case 'execution-dialog-output-html':
  131. case 'execution-dialog-stdout-only':
  132. case 'execution-dialog':
  133. // We don't need to fetch the logEntry for the dialog because we already
  134. // have it, so we open the dialog and it will get updated below.
  135. window.executionDialog.show()
  136. window.executionDialog.executionTrackingId = logEntry.uuid
  137. break
  138. }
  139. feedbackButton.onExecutionFinished(logEntry)
  140. marshalLogsJsonToHtml({
  141. logs: [logEntry]
  142. })
  143. // If the current execution dialog is open, update that too
  144. if (window.executionDialog.dlg.open && window.executionDialog.executionUuid === logEntry.uuid) {
  145. window.executionDialog.renderExecutionResult({
  146. logEntry: logEntry,
  147. type: actionButton.popupOnStart,
  148. })
  149. }
  150. }
  151. function convertPathToBreadcrumb (path) {
  152. const parts = path.split('/')
  153. const result = []
  154. for (let i = 0; i < parts.length; i++) {
  155. if (parts[i] === '') {
  156. continue
  157. }
  158. result.push(parts.slice(0, i + 1).join('/'))
  159. }
  160. return result
  161. }
  162. function showExecutionResult (pathName) {
  163. const executionTrackingId = pathName.split('/')[2]
  164. window.executionDialog.fetchExecutionResult(executionTrackingId)
  165. window.executionDialog.show()
  166. }
  167. function showSection (pathName) {
  168. if (pathName.startsWith('/logs/')) {
  169. showExecutionResult(pathName)
  170. pushNewNavigationPath(pathName)
  171. return
  172. }
  173. const path = window.registeredPaths.get(pathName)
  174. if (path === undefined) {
  175. console.warn('Section not found by path: ' + pathName)
  176. showSection('/')
  177. return
  178. }
  179. window.convertPathToBreadcrumb = convertPathToBreadcrumb
  180. window.currentPath = pathName
  181. window.breadcrumbNavigation = convertPathToBreadcrumb(pathName)
  182. for (const section of document.querySelectorAll('section')) {
  183. if (section.title === path.section) {
  184. section.style.display = 'block'
  185. } else {
  186. section.style.display = 'none'
  187. }
  188. }
  189. pushNewNavigationPath(pathName)
  190. setSectionNavigationVisible(false)
  191. showSectionView(path.view)
  192. }
  193. function pushNewNavigationPath (pathName) {
  194. window.history.pushState({
  195. path: pathName
  196. }, null, pathName)
  197. }
  198. function setSectionNavigationVisible (visible) {
  199. const nav = document.querySelector('nav')
  200. const btn = document.getElementById('sidebar-toggler-button')
  201. nav.removeAttribute('hidden')
  202. if (document.body.classList.contains('has-sidebar')) {
  203. if (visible) {
  204. btn.setAttribute('aria-pressed', false)
  205. btn.setAttribute('aria-label', 'Open sidebar navigation')
  206. btn.innerHTML = '&laquo;'
  207. nav.classList.add('shown')
  208. } else {
  209. btn.setAttribute('aria-pressed', true)
  210. btn.setAttribute('aria-label', 'Close sidebar navigation')
  211. btn.innerHTML = '&#9776;'
  212. nav.classList.remove('shown')
  213. }
  214. } else {
  215. btn.disabled = true
  216. }
  217. }
  218. export function setupSectionNavigation (style) {
  219. const nav = document.querySelector('nav')
  220. const btn = document.getElementById('sidebar-toggler-button')
  221. if (style === 'sidebar') {
  222. nav.classList.add('sidebar')
  223. document.body.classList.add('has-sidebar')
  224. btn.onclick = () => {
  225. if (nav.classList.contains('shown')) {
  226. setSectionNavigationVisible(false)
  227. } else {
  228. setSectionNavigationVisible(true)
  229. }
  230. }
  231. } else {
  232. nav.classList.add('topbar')
  233. document.body.classList.add('has-topbar')
  234. }
  235. registerSection('/', 'Actions', null, document.getElementById('showActions'))
  236. registerSection('/diagnostics', 'Diagnostics', null, document.getElementById('showDiagnostics'))
  237. registerSection('/logs', 'Logs', null, document.getElementById('showLogs'))
  238. registerSection('/login', 'Login', null, null)
  239. }
  240. function registerSection (path, section, view, linkElement) {
  241. window.registeredPaths.set(path, {
  242. section: section,
  243. view: view
  244. })
  245. if (linkElement != null) {
  246. addLinkToSection(path, linkElement)
  247. }
  248. }
  249. function addLinkToSection (pathName, element) {
  250. const path = window.registeredPaths.get(pathName)
  251. element.href = 'javascript:void(0)'
  252. element.title = path.section
  253. element.onclick = () => {
  254. showSection(pathName)
  255. }
  256. }
  257. export function refreshDiagnostics () {
  258. document.getElementById('diagnostics-sshfoundkey').innerHTML = window.settings.SshFoundKey
  259. document.getElementById('diagnostics-sshfoundconfig').innerHTML = window.settings.SshFoundConfig
  260. }
  261. function getSystemTitle (title) {
  262. return title.replaceAll(' ', '')
  263. }
  264. function marshalSingleDashboard (dashboard, nav) {
  265. const oldsection = document.querySelector('section[title="' + getSystemTitle(dashboard.title) + '"]')
  266. if (oldsection != null) {
  267. oldsection.remove()
  268. }
  269. const section = document.createElement('section')
  270. section.setAttribute('system-title', getSystemTitle(dashboard.title))
  271. section.title = section.getAttribute('system-title')
  272. const def = createFieldset('default', section)
  273. section.appendChild(def)
  274. document.getElementsByTagName('main')[0].appendChild(section)
  275. marshalContainerContents(dashboard, section, def, dashboard.title)
  276. const oldLi = nav.querySelector('li[title="' + dashboard.title + '"]')
  277. if (oldLi != null) {
  278. oldLi.remove()
  279. }
  280. const navigationA = document.createElement('a')
  281. navigationA.title = dashboard.title
  282. navigationA.innerText = dashboard.title
  283. registerSection('/' + getSystemTitle(section.title), section.title, null, navigationA)
  284. const navigationLi = document.createElement('li')
  285. navigationLi.appendChild(navigationA)
  286. navigationLi.title = dashboard.title
  287. document.getElementById('navigation-links').appendChild(navigationLi)
  288. }
  289. function marshalDashboardStructureToHtml (json) {
  290. const nav = document.getElementById('navigation-links')
  291. for (const dashboard of json.dashboards) {
  292. marshalSingleDashboard(dashboard, nav)
  293. }
  294. const rootGroup = document.querySelector('#root-group')
  295. for (const btn of Object.values(window.actionButtons)) {
  296. if (btn.parentElement === null) {
  297. rootGroup.appendChild(btn)
  298. }
  299. }
  300. const shouldHideActions = rootGroup.querySelectorAll('action-button').length === 0 && json.dashboards.length > 0
  301. if (shouldHideActions) {
  302. nav.querySelector('li[title="Actions"]').style.display = 'none'
  303. }
  304. if (window.currentPath !== '') {
  305. showSection(window.currentPath)
  306. } else if (window.location.pathname !== '/' && document.body.getAttribute('initial-marshal-complete') === null) {
  307. showSection(window.location.pathname)
  308. } else {
  309. if (shouldHideActions) {
  310. showSection('/' + getSystemTitle(json.dashboards[0].title))
  311. } else {
  312. showSection('/')
  313. }
  314. }
  315. }
  316. function marshalLink (item, fieldset) {
  317. let btn = window.actionButtons[item.title]
  318. if (typeof btn === 'undefined') {
  319. btn = document.createElement('button')
  320. btn.innerText = 'Action not found: ' + item.title
  321. btn.classList.add('error')
  322. }
  323. if (item.cssClass !== '') {
  324. btn.classList.add(item.cssClass)
  325. }
  326. fieldset.appendChild(btn)
  327. }
  328. function marshalMreOutput (dashboardComponent, fieldset) {
  329. const pre = document.createElement('pre')
  330. pre.classList.add('mre-output')
  331. pre.innerHTML = 'Waiting...'
  332. const executionStatus = {
  333. actionId: dashboardComponent.title
  334. }
  335. window.fetch(window.restBaseUrl + 'ExecutionStatus', {
  336. method: 'POST',
  337. headers: {
  338. 'Content-Type': 'application/json'
  339. },
  340. body: JSON.stringify(executionStatus)
  341. }).then((res) => {
  342. if (res.ok) {
  343. return res.json()
  344. } else {
  345. pre.innerHTML = 'error'
  346. throw new Error(res.statusText)
  347. }
  348. }).then((json) => {
  349. updateMre(pre, json.logEntry)
  350. })
  351. const updateMre = (pre, json) => {
  352. pre.innerHTML = json.output
  353. }
  354. window.addEventListener('ExecutionFinished', (e) => {
  355. // The dashboard component "title" field is used for lots of things
  356. // and in this context for MreOutput it's just to refer an an actionId.
  357. //
  358. // So this is not a typo.
  359. if (e.payload.actionId === dashboardComponent.title) {
  360. updateMre(pre, e.payload)
  361. }
  362. })
  363. fieldset.appendChild(pre)
  364. }
  365. function marshalContainerContents (json, section, fieldset, parentDashboard) {
  366. for (const item of json.contents) {
  367. switch (item.type) {
  368. case 'fieldset':
  369. marshalFieldset(item, section, parentDashboard)
  370. break
  371. case 'directory': {
  372. const directoryPath = marshalDirectory(item, section)
  373. marshalDirectoryButton(item, fieldset, directoryPath)
  374. }
  375. break
  376. case 'display':
  377. marshalDisplay(item, fieldset)
  378. break
  379. case 'stdout-most-recent-execution':
  380. marshalMreOutput(item, fieldset)
  381. break
  382. case 'link':
  383. marshalLink(item, fieldset)
  384. break
  385. default:
  386. }
  387. }
  388. }
  389. function createFieldset (title, parentDashboard) {
  390. const legend = document.createElement('legend')
  391. legend.innerText = title
  392. const fs = document.createElement('fieldset')
  393. fs.title = title
  394. fs.appendChild(legend)
  395. if (typeof parentDashboard === 'undefined') {
  396. fs.setAttribute('parent-dashboard', '')
  397. } else {
  398. fs.setAttribute('parent-dashboard', parentDashboard)
  399. }
  400. return fs
  401. }
  402. function marshalFieldset (item, section, parentDashboard) {
  403. const fs = createFieldset(item.title, parentDashboard)
  404. marshalContainerContents(item, section, fs, parentDashboard)
  405. section.appendChild(fs)
  406. }
  407. function showSectionView (selected) {
  408. if (selected === '') {
  409. selected = null
  410. }
  411. for (const fieldset of document.querySelectorAll('fieldset')) {
  412. if (selected === null) {
  413. if ((fieldset.id === 'root-group' || fieldset.getAttribute('parent-dashboard') !== '') && fieldset.children.length > 1) {
  414. fieldset.style.display = 'grid'
  415. } else {
  416. fieldset.style.display = 'none'
  417. }
  418. } else {
  419. if (fieldset.title === selected) {
  420. fieldset.style.display = 'grid'
  421. } else {
  422. fieldset.style.display = 'none'
  423. }
  424. }
  425. }
  426. const current = window.registeredPaths.get(window.currentPath)
  427. for (const navLink of document.querySelector('nav').querySelectorAll('a')) {
  428. if (navLink.title === current.section) {
  429. navLink.classList.add('selected')
  430. } else {
  431. navLink.classList.remove('selected')
  432. }
  433. }
  434. rebuildH1BreadcrumbNavigation(selected)
  435. pushNewNavigationPath(window.currentPath)
  436. }
  437. function rebuildH1BreadcrumbNavigation () {
  438. const title = document.querySelector('h1')
  439. title.innerHTML = ''
  440. const rootLink = document.createElement('a')
  441. rootLink.innerText = window.pageTitle
  442. rootLink.href = 'javascript:void(0)'
  443. rootLink.onclick = () => {
  444. showSection('/')
  445. }
  446. title.appendChild(rootLink)
  447. for (const pathName of window.breadcrumbNavigation) {
  448. const sep = document.createElement('span')
  449. sep.innerHTML = ' &raquo; '
  450. title.append(sep)
  451. const path = window.registeredPaths.get(pathName)
  452. title.appendChild(createNavigationBreadcrumbDisplay(path))
  453. }
  454. document.title = title.innerText
  455. }
  456. function createNavigationBreadcrumbDisplay (path) {
  457. const a = document.createElement('a')
  458. a.href = 'javascript:void(0)'
  459. if (path.view === null) {
  460. a.title = path.section
  461. a.innerText = path.section
  462. } else {
  463. a.innerText = path.view
  464. a.title = path.view
  465. }
  466. a.onclick = () => {
  467. showSectionView(path.view)
  468. }
  469. return a
  470. }
  471. function marshalDisplay (item, fieldset) {
  472. const display = document.createElement('div')
  473. display.innerHTML = item.title
  474. display.classList.add('display')
  475. if (item.cssClass !== '') {
  476. display.classList.add(item.cssClass)
  477. }
  478. fieldset.appendChild(display)
  479. }
  480. function marshalDirectoryButton (item, fieldset, path) {
  481. const directoryButton = document.createElement('button')
  482. directoryButton.innerHTML = '<span class = "icon">' + item.icon + '</span> ' + item.title
  483. directoryButton.onclick = () => {
  484. showSection(path)
  485. }
  486. fieldset.appendChild(directoryButton)
  487. }
  488. function marshalDirectory (item, section) {
  489. const fs = createFieldset(item.title)
  490. fs.style.display = 'none'
  491. const directoryBackButton = document.createElement('button')
  492. directoryBackButton.innerHTML = window.settings.DefaultIconForBack
  493. directoryBackButton.title = 'Go back one directory'
  494. directoryBackButton.onclick = () => {
  495. showSection('/' + section.title)
  496. }
  497. fs.appendChild(directoryBackButton)
  498. marshalContainerContents(item, section, fs)
  499. section.appendChild(fs)
  500. const path = '/' + section.title + '/' + getSystemTitle(item.title)
  501. registerSection(path, section.title, item.title, null)
  502. return path
  503. }
  504. export function marshalLogsJsonToHtml (json) {
  505. // This function is called internally with a "fake" server response, that does
  506. // not have pageSize set. So we need to check if it's set before trying to use it.
  507. if (json.pageSize !== undefined) {
  508. document.getElementById('logs-server-page-size').innerText = json.pageSize
  509. }
  510. if (json.logs != null && json.logs.length > 0) {
  511. document.getElementById('logsTable').hidden = false
  512. document.getElementById('logsTableEmpty').hidden = true
  513. } else {
  514. return
  515. }
  516. for (const logEntry of json.logs) {
  517. let row = document.getElementById('log-' + logEntry.executionTrackingId)
  518. if (row == null) {
  519. const tpl = document.getElementById('tplLogRow')
  520. row = tpl.content.querySelector('tr').cloneNode(true)
  521. row.id = 'log-' + logEntry.executionTrackingId
  522. row.querySelector('.content').onclick = () => {
  523. window.executionDialog.reset()
  524. window.executionDialog.show()
  525. window.executionDialog.renderExecutionResult({
  526. logEntry: window.logEntries.get(logEntry.executionTrackingId)
  527. })
  528. pushNewNavigationPath('/logs/' + logEntry.executionTrackingId)
  529. }
  530. row.exitCodeDisplay = new ActionStatusDisplay(row.querySelector('.exit-code'))
  531. logEntry.dom = row
  532. window.logEntries.set(logEntry.executionTrackingId, logEntry)
  533. document.querySelector('#logTableBody').prepend(row)
  534. }
  535. row.querySelector('.timestamp').innerText = logEntry.datetimeStarted
  536. row.querySelector('.content').innerText = logEntry.actionTitle
  537. row.querySelector('.icon').innerHTML = logEntry.actionIcon
  538. row.setAttribute('title', logEntry.actionTitle)
  539. row.exitCodeDisplay.update(logEntry)
  540. row.querySelector('.tags').innerHTML = ''
  541. for (const tag of logEntry.tags) {
  542. row.querySelector('.tags').append(createTag(tag))
  543. }
  544. row.querySelector('.tags').append(createAnnotation('user', logEntry.user))
  545. }
  546. }
  547. window.addEventListener('popstate', (e) => {
  548. e.preventDefault()
  549. if (e.state != null && typeof e.state.path !== 'undefined') {
  550. showSection(e.state.path)
  551. }
  552. })
  553. export function refreshServerConnectionLabel () {
  554. if (window.restAvailable) {
  555. document.querySelector('#serverConnectionRest').classList.remove('error')
  556. } else {
  557. document.querySelector('#serverConnectionRest').classList.add('error')
  558. }
  559. if (window.websocketAvailable) {
  560. document.querySelector('#serverConnectionWebSocket').classList.remove('error')
  561. document.querySelector('#serverConnectionWebSocket').innerText = 'WebSocket'
  562. } else {
  563. document.querySelector('#serverConnectionWebSocket').classList.add('error')
  564. document.querySelector('#serverConnectionWebSocket').innerText = 'WebSocket Error'
  565. }
  566. }