marshaller.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714
  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. switch (actionButton.popupOnStart) {
  123. case 'execution-button':
  124. if (document.querySelector('execution-button#execution-' + logEntry.executionTrackingId) !== null) { // If the button was created in our instance
  125. document.querySelector('execution-button#execution-' + logEntry.executionTrackingId).onExecutionFinished(logEntry)
  126. }
  127. break
  128. case 'execution-dialog-stdout-only':
  129. case 'execution-dialog':
  130. actionButton.onExecutionFinished(logEntry)
  131. // We don't need to fetch the logEntry for the dialog because we already
  132. // have it, so we open the dialog and it will get updated below.
  133. window.executionDialog.show()
  134. window.executionDialog.executionTrackingId = logEntry.uuid
  135. break
  136. default:
  137. actionButton.onExecutionFinished(logEntry)
  138. break
  139. }
  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. })
  148. }
  149. }
  150. function convertPathToBreadcrumb (path) {
  151. const parts = path.split('/')
  152. const result = []
  153. for (let i = 0; i < parts.length; i++) {
  154. if (parts[i] === '') {
  155. continue
  156. }
  157. result.push(parts.slice(0, i + 1).join('/'))
  158. }
  159. return result
  160. }
  161. function showExecutionResult (pathName) {
  162. const executionTrackingId = pathName.split('/')[2]
  163. window.executionDialog.fetchExecutionResult(executionTrackingId)
  164. window.executionDialog.show()
  165. }
  166. function showSection (pathName) {
  167. if (pathName.startsWith('/logs/')) {
  168. showExecutionResult(pathName)
  169. pushNewNavigationPath(pathName)
  170. return
  171. }
  172. const path = window.registeredPaths.get(pathName)
  173. if (path === undefined) {
  174. console.warn('Section not found by path: ' + pathName)
  175. showSection('/')
  176. return
  177. }
  178. window.convertPathToBreadcrumb = convertPathToBreadcrumb
  179. window.currentPath = pathName
  180. window.breadcrumbNavigation = convertPathToBreadcrumb(pathName)
  181. for (const section of document.querySelectorAll('section')) {
  182. if (section.title === path.section) {
  183. section.style.display = 'block'
  184. } else {
  185. section.style.display = 'none'
  186. }
  187. }
  188. pushNewNavigationPath(pathName)
  189. setSectionNavigationVisible(false)
  190. showSectionView(path.view)
  191. }
  192. function pushNewNavigationPath (pathName) {
  193. window.history.pushState({
  194. path: pathName
  195. }, null, pathName)
  196. }
  197. function setSectionNavigationVisible (visible) {
  198. const nav = document.querySelector('nav')
  199. const btn = document.getElementById('sidebar-toggler-button')
  200. nav.removeAttribute('hidden')
  201. if (document.body.classList.contains('has-sidebar')) {
  202. if (visible) {
  203. btn.setAttribute('aria-pressed', false)
  204. btn.setAttribute('aria-label', 'Open sidebar navigation')
  205. btn.innerHTML = '&laquo;'
  206. nav.classList.add('shown')
  207. } else {
  208. btn.setAttribute('aria-pressed', true)
  209. btn.setAttribute('aria-label', 'Close sidebar navigation')
  210. btn.innerHTML = '&#9776;'
  211. nav.classList.remove('shown')
  212. }
  213. } else {
  214. btn.disabled = true
  215. }
  216. }
  217. export function setupSectionNavigation (style) {
  218. const nav = document.querySelector('nav')
  219. const btn = document.getElementById('sidebar-toggler-button')
  220. if (style === 'sidebar') {
  221. nav.classList.add('sidebar')
  222. document.body.classList.add('has-sidebar')
  223. btn.onclick = () => {
  224. if (nav.classList.contains('shown')) {
  225. setSectionNavigationVisible(false)
  226. } else {
  227. setSectionNavigationVisible(true)
  228. }
  229. }
  230. } else {
  231. nav.classList.add('topbar')
  232. document.body.classList.add('has-topbar')
  233. }
  234. registerSection('/', 'Actions', null, document.getElementById('showActions'))
  235. registerSection('/diagnostics', 'Diagnostics', null, document.getElementById('showDiagnostics'))
  236. registerSection('/logs', 'Logs', null, document.getElementById('showLogs'))
  237. registerSection('/login', 'Login', null, null)
  238. }
  239. function registerSection (path, section, view, linkElement) {
  240. window.registeredPaths.set(path, {
  241. section: section,
  242. view: view
  243. })
  244. if (linkElement != null) {
  245. addLinkToSection(path, linkElement)
  246. }
  247. }
  248. function addLinkToSection (pathName, element) {
  249. const path = window.registeredPaths.get(pathName)
  250. element.href = 'javascript:void(0)'
  251. element.title = path.section
  252. element.onclick = () => {
  253. showSection(pathName)
  254. }
  255. }
  256. export function refreshDiagnostics () {
  257. document.getElementById('diagnostics-sshfoundkey').innerHTML = window.settings.SshFoundKey
  258. document.getElementById('diagnostics-sshfoundconfig').innerHTML = window.settings.SshFoundConfig
  259. }
  260. function getSystemTitle (title) {
  261. return title.replaceAll(' ', '')
  262. }
  263. function marshalSingleDashboard (dashboard, nav) {
  264. const oldsection = document.querySelector('section[title="' + getSystemTitle(dashboard.title) + '"]')
  265. if (oldsection != null) {
  266. oldsection.remove()
  267. }
  268. const section = document.createElement('section')
  269. section.setAttribute('system-title', getSystemTitle(dashboard.title))
  270. section.title = section.getAttribute('system-title')
  271. const def = createFieldset('default', section)
  272. section.appendChild(def)
  273. document.getElementsByTagName('main')[0].appendChild(section)
  274. marshalContainerContents(dashboard, section, def, dashboard.title)
  275. const oldLi = nav.querySelector('li[title="' + dashboard.title + '"]')
  276. if (oldLi != null) {
  277. oldLi.remove()
  278. }
  279. const navigationA = document.createElement('a')
  280. navigationA.title = dashboard.title
  281. navigationA.innerText = dashboard.title
  282. registerSection('/' + getSystemTitle(section.title), section.title, null, navigationA)
  283. const navigationLi = document.createElement('li')
  284. navigationLi.appendChild(navigationA)
  285. navigationLi.title = dashboard.title
  286. document.getElementById('navigation-links').appendChild(navigationLi)
  287. }
  288. function marshalDashboardStructureToHtml (json) {
  289. const nav = document.getElementById('navigation-links')
  290. for (const dashboard of json.dashboards) {
  291. marshalSingleDashboard(dashboard, nav)
  292. }
  293. const rootGroup = document.querySelector('#root-group')
  294. for (const btn of Object.values(window.actionButtons)) {
  295. if (btn.parentElement === null) {
  296. rootGroup.appendChild(btn)
  297. }
  298. }
  299. const shouldHideActions = rootGroup.querySelectorAll('action-button').length === 0 && json.dashboards.length > 0
  300. if (shouldHideActions) {
  301. nav.querySelector('li[title="Actions"]').style.display = 'none'
  302. }
  303. if (window.currentPath !== '') {
  304. showSection(window.currentPath)
  305. } else if (window.location.pathname !== '/' && document.body.getAttribute('initial-marshal-complete') === null) {
  306. showSection(window.location.pathname)
  307. } else {
  308. if (shouldHideActions) {
  309. showSection('/' + getSystemTitle(json.dashboards[0].title))
  310. } else {
  311. showSection('/')
  312. }
  313. }
  314. }
  315. function marshalLink (item, fieldset) {
  316. let btn = window.actionButtons[item.title]
  317. if (typeof btn === 'undefined') {
  318. btn = document.createElement('button')
  319. btn.innerText = 'Action not found: ' + item.title
  320. btn.classList.add('error')
  321. }
  322. if (item.cssClass !== '') {
  323. btn.classList.add(item.cssClass)
  324. }
  325. fieldset.appendChild(btn)
  326. }
  327. function marshalMreOutput (dashboardComponent, fieldset) {
  328. const pre = document.createElement('pre')
  329. pre.classList.add('mre-output')
  330. pre.innerHTML = 'Waiting...'
  331. const executionStatus = {
  332. actionId: dashboardComponent.title
  333. }
  334. window.fetch(window.restBaseUrl + 'ExecutionStatus', {
  335. method: 'POST',
  336. headers: {
  337. 'Content-Type': 'application/json'
  338. },
  339. body: JSON.stringify(executionStatus)
  340. }).then((res) => {
  341. if (res.ok) {
  342. return res.json()
  343. } else {
  344. pre.innerHTML = 'error'
  345. throw new Error(res.statusText)
  346. }
  347. }).then((json) => {
  348. updateMre(pre, json.logEntry)
  349. })
  350. const updateMre = (pre, json) => {
  351. pre.innerHTML = json.output
  352. }
  353. window.addEventListener('ExecutionFinished', (e) => {
  354. // The dashboard component "title" field is used for lots of things
  355. // and in this context for MreOutput it's just to refer an an actionId.
  356. //
  357. // So this is not a typo.
  358. if (e.payload.actionId === dashboardComponent.title) {
  359. updateMre(pre, e.payload)
  360. }
  361. })
  362. fieldset.appendChild(pre)
  363. }
  364. function marshalContainerContents (json, section, fieldset, parentDashboard) {
  365. for (const item of json.contents) {
  366. switch (item.type) {
  367. case 'fieldset':
  368. marshalFieldset(item, section, parentDashboard)
  369. break
  370. case 'directory': {
  371. const directoryPath = marshalDirectory(item, section)
  372. marshalDirectoryButton(item, fieldset, directoryPath)
  373. }
  374. break
  375. case 'display':
  376. marshalDisplay(item, fieldset)
  377. break
  378. case 'stdout-most-recent-execution':
  379. marshalMreOutput(item, fieldset)
  380. break
  381. case 'link':
  382. marshalLink(item, fieldset)
  383. break
  384. default:
  385. }
  386. }
  387. }
  388. function createFieldset (title, parentDashboard) {
  389. const legend = document.createElement('legend')
  390. legend.innerText = title
  391. const fs = document.createElement('fieldset')
  392. fs.title = title
  393. fs.appendChild(legend)
  394. if (typeof parentDashboard === 'undefined') {
  395. fs.setAttribute('parent-dashboard', '')
  396. } else {
  397. fs.setAttribute('parent-dashboard', parentDashboard)
  398. }
  399. return fs
  400. }
  401. function marshalFieldset (item, section, parentDashboard) {
  402. const fs = createFieldset(item.title, parentDashboard)
  403. marshalContainerContents(item, section, fs, parentDashboard)
  404. section.appendChild(fs)
  405. }
  406. function showSectionView (selected) {
  407. if (selected === '') {
  408. selected = null
  409. }
  410. for (const fieldset of document.querySelectorAll('fieldset')) {
  411. if (selected === null) {
  412. if ((fieldset.id === 'root-group' || fieldset.getAttribute('parent-dashboard') !== '') && fieldset.children.length > 1) {
  413. fieldset.style.display = 'grid'
  414. } else {
  415. fieldset.style.display = 'none'
  416. }
  417. } else {
  418. if (fieldset.title === selected) {
  419. fieldset.style.display = 'grid'
  420. } else {
  421. fieldset.style.display = 'none'
  422. }
  423. }
  424. }
  425. const current = window.registeredPaths.get(window.currentPath)
  426. for (const navLink of document.querySelector('nav').querySelectorAll('a')) {
  427. if (navLink.title === current.section) {
  428. navLink.classList.add('selected')
  429. } else {
  430. navLink.classList.remove('selected')
  431. }
  432. }
  433. rebuildH1BreadcrumbNavigation(selected)
  434. pushNewNavigationPath(window.currentPath)
  435. }
  436. function rebuildH1BreadcrumbNavigation () {
  437. const title = document.querySelector('h1')
  438. title.innerHTML = ''
  439. const rootLink = document.createElement('a')
  440. rootLink.innerText = window.pageTitle
  441. rootLink.href = 'javascript:void(0)'
  442. rootLink.onclick = () => {
  443. showSection('/')
  444. }
  445. title.appendChild(rootLink)
  446. for (const pathName of window.breadcrumbNavigation) {
  447. const sep = document.createElement('span')
  448. sep.innerHTML = ' &raquo; '
  449. title.append(sep)
  450. const path = window.registeredPaths.get(pathName)
  451. title.appendChild(createNavigationBreadcrumbDisplay(path))
  452. }
  453. document.title = title.innerText
  454. }
  455. function createNavigationBreadcrumbDisplay (path) {
  456. const a = document.createElement('a')
  457. a.href = 'javascript:void(0)'
  458. if (path.view === null) {
  459. a.title = path.section
  460. a.innerText = path.section
  461. } else {
  462. a.innerText = path.view
  463. a.title = path.view
  464. }
  465. a.onclick = () => {
  466. showSectionView(path.view)
  467. }
  468. return a
  469. }
  470. function marshalDisplay (item, fieldset) {
  471. const display = document.createElement('div')
  472. display.innerHTML = item.title
  473. display.classList.add('display')
  474. if (item.cssClass !== '') {
  475. display.classList.add(item.cssClass)
  476. }
  477. fieldset.appendChild(display)
  478. }
  479. function marshalDirectoryButton (item, fieldset, path) {
  480. const directoryButton = document.createElement('button')
  481. directoryButton.innerHTML = '<span class = "icon">' + item.icon + '</span> ' + item.title
  482. directoryButton.onclick = () => {
  483. showSection(path)
  484. }
  485. fieldset.appendChild(directoryButton)
  486. }
  487. function marshalDirectory (item, section) {
  488. const fs = createFieldset(item.title)
  489. fs.style.display = 'none'
  490. const directoryBackButton = document.createElement('button')
  491. directoryBackButton.innerHTML = window.settings.DefaultIconForBack
  492. directoryBackButton.title = 'Go back one directory'
  493. directoryBackButton.onclick = () => {
  494. showSection('/' + section.title)
  495. }
  496. fs.appendChild(directoryBackButton)
  497. marshalContainerContents(item, section, fs)
  498. section.appendChild(fs)
  499. const path = '/' + section.title + '/' + getSystemTitle(item.title)
  500. registerSection(path, section.title, item.title, null)
  501. return path
  502. }
  503. export function marshalLogsJsonToHtml (json) {
  504. for (const logEntry of json.logs) {
  505. let row = document.getElementById('log-' + logEntry.executionTrackingId)
  506. if (row == null) {
  507. const tpl = document.getElementById('tplLogRow')
  508. row = tpl.content.querySelector('tr').cloneNode(true)
  509. row.id = 'log-' + logEntry.executionTrackingId
  510. row.querySelector('.content').onclick = () => {
  511. window.executionDialog.reset()
  512. window.executionDialog.show()
  513. window.executionDialog.renderExecutionResult({
  514. logEntry: window.logEntries.get(logEntry.executionTrackingId)
  515. })
  516. pushNewNavigationPath('/logs/' + logEntry.executionTrackingId)
  517. }
  518. row.exitCodeDisplay = new ActionStatusDisplay(row.querySelector('.exit-code'))
  519. logEntry.dom = row
  520. window.logEntries.set(logEntry.executionTrackingId, logEntry)
  521. document.querySelector('#logTableBody').prepend(row)
  522. }
  523. row.querySelector('.timestamp').innerText = logEntry.datetimeStarted
  524. row.querySelector('.content').innerText = logEntry.actionTitle
  525. row.querySelector('.icon').innerHTML = logEntry.actionIcon
  526. row.setAttribute('title', logEntry.actionTitle)
  527. row.exitCodeDisplay.update(logEntry)
  528. row.querySelector('.tags').innerHTML = ''
  529. for (const tag of logEntry.tags) {
  530. row.querySelector('.tags').append(createTag(tag))
  531. }
  532. row.querySelector('.tags').append(createAnnotation('user', logEntry.user))
  533. }
  534. }
  535. window.addEventListener('popstate', (e) => {
  536. e.preventDefault()
  537. if (e.state != null && typeof e.state.path !== 'undefined') {
  538. showSection(e.state.path)
  539. }
  540. })
  541. export function refreshServerConnectionLabel () {
  542. if (window.restAvailable) {
  543. document.querySelector('#serverConnectionRest').classList.remove('error')
  544. } else {
  545. document.querySelector('#serverConnectionRest').classList.add('error')
  546. }
  547. if (window.websocketAvailable) {
  548. document.querySelector('#serverConnectionWebSocket').classList.remove('error')
  549. document.querySelector('#serverConnectionWebSocket').innerText = 'WebSocket'
  550. } else {
  551. document.querySelector('#serverConnectionWebSocket').classList.add('error')
  552. document.querySelector('#serverConnectionWebSocket').innerText = 'WebSocket Error'
  553. }
  554. }