F OpenNebula/one#7397: Tab to display virtual machine logs (#3967)

Signed-off-by: dcarracedo <dcarracedo@opennebula.io>
Co-authored-by: Tino Vázquez <cvazquez@opennebula.io>
This commit is contained in:
DavidandTino Vázquez authored and GitHub committed 2025-12-15 16:50:06 +01:00
1 parent d15b90931b
commit 7d4bb5be4a
15 files changed
+713 -3

No files matched your search

@@ -151,3 +151,6 @@ info-tabs:
template:
enabled: true
logs:
enabled: true
+31
View File
@@ -96,6 +96,7 @@
"react-router-dom": "5.3.0",
"react-transition-group": "4.4.1",
"react-virtual": "2.7.1",
"react-virtualized": "9.22.6",
"recharts": "2.7.3",
"redux": "4.1.1",
"redux-persist": "6.0.0",
@@ -13240,6 +13241,23 @@
"react": "^16.6.3 || ^17.0.0"
}
},
"node_modules/react-virtualized": {
"version": "9.22.6",
"resolved": "https://registry.npmjs.org/react-virtualized/-/react-virtualized-9.22.6.tgz",
"integrity": "sha512-U5j7KuUQt3AaMatlMJ0UJddqSiX+Km0YJxSqbAzIiGw5EmNz0khMyqP2hzgu4+QUtm+QPIrxzUX4raJxmVJnHg==",
"dependencies": {
"@babel/runtime": "^7.7.2",
"clsx": "^1.0.4",
"dom-helpers": "^5.1.3",
"loose-envify": "^1.4.0",
"prop-types": "^15.7.2",
"react-lifecycles-compat": "^3.0.4"
},
"peerDependencies": {
"react": "^16.3.0 || ^17.0.0 || ^18.0.0 || ^19.0.0",
"react-dom": "^16.3.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"
}
},
"node_modules/readable-stream": {
"version": "1.1.14",
"resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-1.1.14.tgz",
@@ -25595,6 +25613,19 @@
"@reach/observe-rect": "^1.1.0"
}
},
"react-virtualized": {
"version": "9.22.6",
"resolved": "https://registry.npmjs.org/react-virtualized/-/react-virtualized-9.22.6.tgz",
"integrity": "sha512-U5j7KuUQt3AaMatlMJ0UJddqSiX+Km0YJxSqbAzIiGw5EmNz0khMyqP2hzgu4+QUtm+QPIrxzUX4raJxmVJnHg==",
"requires": {
"@babel/runtime": "^7.7.2",
"clsx": "^1.0.4",
"dom-helpers": "^5.1.3",
"loose-envify": "^1.4.0",
"prop-types": "^15.7.2",
"react-lifecycles-compat": "^3.0.4"
}
},
"readable-stream": {
"version": "1.1.14",
"resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-1.1.14.tgz",
+3 -1
View File
@@ -23,7 +23,8 @@
"lint": "npm run lint-client && npm run lint-server",
"lint-client": "eslint ./src/client/",
"lint-server": "eslint ./src/server/",
"lint-fix": "eslint ./src/ --fix"
"lint-fix": "eslint ./src/ --fix",
"dev-server": "cross-env NODE_ENV=development babel-node ./src/server/index.js"
},
"author": "opennebula.io",
"license": "Apache-2.0",
@@ -139,6 +140,7 @@
"react-router-dom": "5.3.0",
"react-transition-group": "4.4.1",
"react-virtual": "2.7.1",
"react-virtualized": "9.22.6",
"recharts": "2.7.3",
"redux": "4.1.1",
"redux-persist": "6.0.0",
@@ -0,0 +1,351 @@
/* ------------------------------------------------------------------------- *
* Copyright 2002-2025, OpenNebula Project, OpenNebula Systems *
* *
* Licensed under the Apache License, Version 2.0 (the "License"); you may *
* not use this file except in compliance with the License. You may obtain *
* a copy of the License at *
* *
* http://www.apache.org/licenses/LICENSE-2.0 *
* *
* Unless required by applicable law or agreed to in writing, software *
* distributed under the License is distributed on an "AS IS" BASIS, *
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *
* See the License for the specific language governing permissions and *
* limitations under the License. *
* ------------------------------------------------------------------------- */
import { useState, useRef, useEffect, useMemo, useCallback } from 'react'
import PropTypes from 'prop-types'
import {
Box,
FormControl,
InputBase,
useTheme,
MenuList,
MenuItem,
Stack,
} from '@mui/material'
import {
List as VirtualizedList,
AutoSizer,
CellMeasurer,
CellMeasurerCache,
} from 'react-virtualized'
import {
Search as SearchIcon,
Filter,
SortDown,
SortUp,
RefreshDouble,
} from 'iconoir-react'
import { T, STYLE_BUTTONS } from '@ConstantsModule'
import { Tr, Translate, SubmitButton } from '@modules/components'
import { styles } from '@modules/components/LogsViewer/styles'
import HeaderPopover from '@modules/components/Header/Popover'
import clsx from 'clsx'
/**
* Cache for Cell Measure (to calculate height of log lines)
*/
const cache = new CellMeasurerCache({
fixedWidth: true,
defaultHeight: 24,
minHeight: 24,
keyMapper: (rowIndex) => rowIndex,
})
/**
* Lov viewer component.
*
* @param {object} props - Log viewer properties
* @param {object} props.logs - Logs data
* @param {object} props.getLogs - Function to refresh logs
* @param {boolean} props.isFetching - If the request to get logs to the API is in progress
* @param {object} props.options - Component options
* @returns {object} - The Log Viewer component
*/
const LogsViewer = ({ logs, getLogs, isFetching, options = {} }) => {
// Get options
const { followLogs = false } = options
// Get styles
const theme = useTheme()
const classes = useMemo(() => styles(theme), [theme])
// Sort
const [sortAsc, setSortAsc] = useState(true)
const toggleSort = () => {
setSortAsc((prev) => !prev)
}
// Levels of debug and filters
const levels = ['debug', 'info', 'warn', 'error']
const [level, setLevel] = useState()
const [filterValue, setFilterValue] = useState('')
const [filteredLogs, setFilteredLogs] = useState(logs?.lines || [])
// Follow logs
useEffect(() => {
if (followLogs && listRef.current && filteredLogs.length > 0) {
// Scroll to the last row
listRef.current.scrollToRow(filteredLogs.length - 1)
}
}, [filteredLogs, followLogs])
// Virtualized list ref
const listRef = useRef(null)
// Recompute row heights if logs change
useEffect(() => {
if (listRef.current) {
cache.clearAll()
listRef.current.recomputeRowHeights()
}
}, [logs])
// Combined filtering function
const applyFilters = useCallback(() => {
let filtered = logs.lines
// Filter by level
if (level) {
filtered = filtered.filter(
(log) => log.level.toLowerCase() === level.toLowerCase()
)
}
// Filter by text
const cleanText = filterValue.trim().toLowerCase()
if (cleanText) {
filtered = filtered.filter((log) =>
log.text.toLowerCase().includes(cleanText)
)
}
// Sort
filtered = sortAsc ? filtered : [...filtered].reverse()
setFilteredLogs(filtered)
}, [logs.lines, level, filterValue, sortAsc])
// Handlers
const handleFilterText = (event) => {
setFilterValue(event.target.value)
}
const handleFilterLevel = (selectedLevel) => {
// Toggle: if the clicked level is already active, clear it
setLevel((prev) => (prev === selectedLevel ? undefined : selectedLevel))
}
// Trigger filtering whenever search text or level changes
useEffect(() => {
applyFilters()
}, [applyFilters])
// Highlight search matches
const highlightMatch = (text, query) => {
if (!query) return text
const escaped = query.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
const regex = new RegExp(`(${escaped})`, 'gi')
const parts = text.split(regex)
return parts.map((part, i) =>
regex.test(part) ? (
<mark key={i} style={{ background: '#ffee58', padding: '0 2px' }}>
{part}
</mark>
) : (
part
)
)
}
const Row = ({ index, key, style, parent }) => {
const log = filteredLogs[index]
const regexDate = /^(.+?\[\w\])\s*(.*)/
const matchDate = log.text.match(regexDate)
const header = matchDate ? matchDate[1] : null
const message = matchDate ? matchDate[2] : log.text
return (
<CellMeasurer
key={key}
cache={cache}
parent={parent}
columnIndex={0}
rowIndex={index}
>
{({ registerChild, measure }) => (
<div
ref={registerChild}
onLoad={measure}
style={{
...style,
padding: '4px 8px',
whiteSpace: 'pre-wrap',
wordBreak: 'break-word',
}}
>
<Box
className={clsx(
classes.containerText,
log.level && classes[`${log.level}Log`]
)}
>
{header ? (
<>
<span className={classes.dateText}>
{highlightMatch(header, filterValue)}
</span>
<span className={classes.logText}>
{highlightMatch(message, filterValue)}
</span>
</>
) : (
<span className={classes.logText}>
{highlightMatch(log.text, filterValue)}
</span>
)}
</Box>
</div>
)}
</CellMeasurer>
)
}
Row.propTypes = {
index: PropTypes.number.isRequired,
key: PropTypes.string,
style: PropTypes.object.isRequired,
parent: PropTypes.object.isRequired,
}
return (
<Box>
<Stack
direction="row"
sx={{
gap: 2,
mb: 2,
mt: 2,
justifyContent: 'space-between',
alignItems: 'center',
}}
>
{/* Search input */}
<div className={classes.search}>
<div className={classes.searchIcon}>
<SearchIcon />
</div>
<FormControl className={classes.inputRoot}>
<InputBase
value={filterValue}
type="search"
onChange={handleFilterText}
placeholder={`${Tr(T.Search)}...`}
classes={{ root: classes.inputRoot, input: classes.inputInput }}
inputProps={{ 'aria-label': 'search', 'data-cy': 'log-search' }}
/>
</FormControl>
</div>
<Stack
direction="row"
sx={{
gap: 2,
mb: 2,
mt: 2,
justifyContent: 'flex-end',
alignItems: 'center',
}}
>
{/* Level filter popover */}
<HeaderPopover
id="filter-by-level"
icon={<Filter />}
buttonLabel={
level ? level.toUpperCase() : <Translate word={T['logs.level']} />
}
buttonProps={{
'data-cy': 'filter-by-level',
disableElevation: true,
importance: STYLE_BUTTONS.IMPORTANCE.SECONDARY,
size: STYLE_BUTTONS.SIZE.MEDIUM,
type: STYLE_BUTTONS.TYPE.FILLED,
active: level !== undefined,
}}
popperProps={{ placement: 'bottom-end' }}
>
{() => (
<MenuList>
{levels.map((lvl) => (
<MenuItem key={lvl} onClick={() => handleFilterLevel(lvl)}>
<span
style={{ fontWeight: level === lvl ? 'bold' : 'normal' }}
>
{lvl}
</span>
</MenuItem>
))}
</MenuList>
)}
</HeaderPopover>
{sortAsc ? (
<SubmitButton
data-cy="sort-desc"
icon={<SortDown />}
tooltip={Tr(T.Sort)}
onClick={toggleSort}
/>
) : (
<SubmitButton
data-cy="sort-asc"
icon={<SortUp />}
tooltip={Tr(T.Sort)}
onClick={toggleSort}
/>
)}
<SubmitButton
data-cy="detail-refresh"
icon={<RefreshDouble />}
tooltip={Tr(T.Refresh)}
isSubmitting={isFetching}
onClick={() => getLogs()}
/>
</Stack>
</Stack>
{/* Virtualized log list */}
<Box
style={{ height: 600 }}
className={classes.logsContainer}
data-cy="logs-viewer"
>
<AutoSizer>
{({ height, width }) => (
<VirtualizedList
ref={listRef}
width={width}
height={height}
deferredMeasurementCache={cache}
rowHeight={cache.rowHeight}
rowCount={filteredLogs?.length || 0}
rowRenderer={Row}
overscanRowCount={10}
/>
)}
</AutoSizer>
</Box>
</Box>
)
}
LogsViewer.propTypes = {
logs: PropTypes.object,
getLogs: PropTypes.object,
isFetching: PropTypes.bool,
options: PropTypes.object,
}
export default LogsViewer
@@ -0,0 +1,105 @@
/* ------------------------------------------------------------------------- *
* Copyright 2002-2025, OpenNebula Project, OpenNebula Systems *
* *
* Licensed under the Apache License, Version 2.0 (the "License"); you may *
* not use this file except in compliance with the License. You may obtain *
* a copy of the License at *
* *
* http://www.apache.org/licenses/LICENSE-2.0 *
* *
* Unless required by applicable law or agreed to in writing, software *
* distributed under the License is distributed on an "AS IS" BASIS, *
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *
* See the License for the specific language governing permissions and *
* limitations under the License. *
* ------------------------------------------------------------------------- */
/* eslint-disable jsdoc/require-jsdoc */
import { css } from '@emotion/css'
export const styles = ({ palette }) => ({
search: css({
gridArea: 'search',
position: 'relative',
borderRadius: '6.25rem',
display: 'flex',
alignItems: 'center',
...palette.searchBar.normal,
borderWidth: '0.0625rem',
borderStyle: 'solid',
'&:hover': {
...palette.searchBar.hover,
borderWidth: '0.0625rem',
borderStyle: 'solid',
},
'&:focus-within': {
...palette.searchBar.focus,
borderWidth: '0.125rem',
borderStyle: 'solid',
},
padding: '1rem 1rem 1rem 1.5rem',
width: '60%',
marginRight: '1rem',
}),
searchIcon: css({
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
color: palette.searchBar.icon.color,
}),
inputRoot: css({
flex: 1,
margin: 0,
}),
inputInput: css({
padding: 0,
lineHeight: '1.25rem',
fontWeight: 500,
'&::-webkit-search-cancel-button': {
cursor: 'pointer',
},
'&::-ms-clear': {
cursor: 'pointer',
},
'&::after': {
cursor: 'pointer',
},
}),
logsContainer: css({
background: palette.logsViewer.backgroundColor,
}),
dateText: css({
color: palette.logsViewer.colorDate,
fontFamily: 'Courier New',
fontSize: '14px',
fontStyle: 'normal',
fontWeight: 700,
lineHeight: '16px',
}),
logText: css({
color: palette.logsViewer.colorLog,
fontFamily: 'Courier New',
fontSize: '14px',
fontStyle: 'normal',
fontWeight: 700,
lineHeight: '16px',
}),
containerText: css({
paddingLeft: '12px',
}),
infoLog: css({
borderLeft: `3px solid ${palette.logsViewer.info.color}`,
}),
debugLog: css({
borderLeft: `3px solid ${palette.logsViewer.debug.color}`,
}),
warnLog: css({
borderLeft: `3px solid ${palette.logsViewer.warn.color}`,
}),
errorLog: css({
borderLeft: `3px solid ${palette.logsViewer.error.color}`,
}),
highlightText: css({
background: palette.logsViewer.highlight,
padding: '0 1px',
}),
})
@@ -0,0 +1,58 @@
/* ------------------------------------------------------------------------- *
* Copyright 2002-2025, OpenNebula Project, OpenNebula Systems *
* *
* Licensed under the Apache License, Version 2.0 (the "License"); you may *
* not use this file except in compliance with the License. You may obtain *
* a copy of the License at *
* *
* http://www.apache.org/licenses/LICENSE-2.0 *
* *
* Unless required by applicable law or agreed to in writing, software *
* distributed under the License is distributed on an "AS IS" BASIS, *
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *
* See the License for the specific language governing permissions and *
* limitations under the License. *
* ------------------------------------------------------------------------- */
import { ReactElement } from 'react'
import PropTypes from 'prop-types'
import { Stack } from '@mui/material'
import { VmAPI } from '@FeaturesModule'
import LogsViewer from '@modules/components/LogsViewer'
import { OpenNebulaLogo } from '@modules/components/Icons'
/**
* Renders logs tab.
*
* @param {object} props - Props
* @param {string} props.id - Virtual machine id
* @returns {ReactElement} Logs tab
*/
const LogsTab = ({ id }) => {
// Get vm logs
const {
data: logsData,
refetch,
isFetching,
} = VmAPI.useGetVmLogsQuery({ id })
return logsData ? (
<LogsViewer logs={logsData} getLogs={refetch} isFetching={isFetching} />
) : (
<Stack
direction="row"
sx={{ justifyContent: 'center', alignItems: 'center' }}
>
<OpenNebulaLogo width={150} height={150} spinner />
</Stack>
)
}
LogsTab.propTypes = {
tabProps: PropTypes.object,
id: PropTypes.string,
}
LogsTab.displayName = 'LogsTab'
export default LogsTab
@@ -38,6 +38,7 @@ import SchedActions from '@modules/components/Tabs/Vm/SchedActions'
import Snapshot from '@modules/components/Tabs/Vm/Snapshot'
import Storage from '@modules/components/Tabs/Vm/Storage'
import Template from '@modules/components/Tabs/Vm/Template'
import Logs from '@modules/components/Tabs/Vm/Logs'
const useStyles = ({ palette }) => ({
vmError: css({
@@ -60,6 +61,7 @@ const getTabComponent = (tabName) =>
storage: Storage,
configuration: Configuration,
template: Template,
logs: Logs,
}[tabName])
const VmTabs = memo(({ id, singleActions }) => {
@@ -2561,4 +2561,7 @@ module.exports = {
/* Drivers */
Synchronize: 'Synchronize',
Source: 'Source',
/* Log viewer */
'logs.level': 'Level',
}
@@ -370,6 +370,22 @@ const vmApi = oneApi.injectEndpoints({
return { params, command }
},
}),
getVmLogs: builder.query({
// /**
// * Retrieves log for a vm.
// *
// * @returns {number} VM ID
// * @throws Fails when response isn't code 200
// */
query: (params) => {
const name = ExtraActions.VM_LOGS
const command = { name, ...ExtraCommands[name] }
return { params, command }
},
keepUnusedDataFor: 0,
providesTags: [],
}),
allocateVm: builder.mutation({
/**
* Allocates a new virtual machine in OpenNebula.
@@ -1368,6 +1384,7 @@ const vmQueries = (({
useLazyCalculateShowbackQuery,
useGetVmsPaginatedQuery,
useLazyGetVmsPaginatedQuery,
useGetVmLogsQuery,
// Mutations
useAllocateVmMutation,
@@ -1433,6 +1450,7 @@ const vmQueries = (({
useLazyCalculateShowbackQuery,
useGetVmsPaginatedQuery,
useLazyGetVmsPaginatedQuery,
useGetVmLogsQuery,
// Mutations
useAllocateVmMutation,
@@ -484,6 +484,27 @@ export const darkPalette = {
color: sunstoneColors.white,
},
},
// Log viewer
logsViewer: {
backgroundColor: '#40435C',
colorDate: '#C4CDD5',
colorLog: '#F5F7F9',
highlight: '#ffee58',
debug: {
color: '#80B2FF',
},
info: {
color: '#1B4079',
},
warn: {
color: '#FF6E1F',
},
error: {
color: '#FF5779',
},
},
sunstoneColors: sunstoneColors,
error: {
@@ -493,6 +493,27 @@ export const lightPalette = {
color: sunstoneColors.black,
},
},
// Log viewer
logsViewer: {
backgroundColor: '#F5F7F9',
colorDate: '#637381',
colorLog: '#40435C',
highlight: '#ffee58',
debug: {
color: '#637381',
},
info: {
color: '#1B4079',
},
warn: {
color: '#FF6E1F',
},
error: {
color: '#FF5779',
},
},
sunstoneColors: sunstoneColors,
error: {
@@ -16,6 +16,9 @@
const btoa = require('btoa')
const { createHash, createCipheriv } = require('crypto')
const { defaults, httpCodes } = require('server/utils/constants')
const { global } = require('window-or-global')
const fs = require('fs-extra')
const {
httpResponse,
executeCommand,
@@ -29,7 +32,8 @@ const { createTokenServerAdmin } = require('server/routes/api/auth/utils')
const { USER_INFO } = userActions
const { VM_INFO } = vmActions
const { ok, unauthorized, internalServerError, badRequest } = httpCodes
const { ok, unauthorized, internalServerError, badRequest, notFound } =
httpCodes
const {
defaultEmptyFunction,
defaultCommandVM,
@@ -342,9 +346,80 @@ const encryptConnection = (data) => {
return { iv: iv.toString('base64'), value }
}
/**
* Get vm logs.
*
* @param {object} res - http response
* @param {Function} next - express stepper
* @param {object} params - params of http request
*/
const vmLogs = async (res = {}, next = defaultEmptyFunction, params = {}) => {
// Prepare response
let rtn
// Get vm id
const { id } = params
if (id !== undefined && id !== '' && Number.isInteger(Number(id))) {
try {
// Path to the vm
const logPath = `${global.paths.LOG_LOCATION}/${id}.log`
// Check if the file exists
await fs.access(logPath)
// Read the file
const content = await fs.readFile(logPath, 'utf-8')
// Split content into lines
const linesArray = content
.split('\n')
.filter((line) => line.trim() !== '')
// Map each line to the desired format
const lines = linesArray?.map((line) => {
// Defautl level
let level = 'debug'
// Check log level
if (/\[E\]/.test(line)) level = 'error'
else if (/\[W\]/.test(line)) level = 'warning'
else if (/\[D\]/.test(line)) level = 'debug'
else if (/\[I\]/.test(line)) level = 'info'
return { level, text: line }
})
// Build final JSON
const result = {
meta: {
mode: 'all',
total_lines: lines.length,
},
lines,
}
rtn = httpResponse(ok, result)
} catch (err) {
if (err.code === 'ENOENT') {
rtn = httpResponse(notFound, `Log file not found`)
} else {
rtn = httpResponse(internalServerError)
}
}
} else {
// There is no id in the request
rtn = httpResponse(badRequest, '', '')
}
res.locals.httpCode = rtn
next()
}
const functionRoutes = {
saveAsTemplate,
generateGuacamoleSession,
vmLogs,
}
module.exports = functionRoutes
@@ -18,9 +18,10 @@ const { Actions, Commands } = require('server/routes/api/vm/routes')
const {
saveAsTemplate,
generateGuacamoleSession,
vmLogs,
} = require('server/routes/api/vm/functions')
const { VM_SAVEASTEMPLATE, GUACAMOLE } = Actions
const { VM_SAVEASTEMPLATE, GUACAMOLE, VM_LOGS } = Actions
module.exports = [
{
@@ -31,4 +32,8 @@ module.exports = [
...Commands[GUACAMOLE],
action: generateGuacamoleSession,
},
{
...Commands[VM_LOGS],
action: vmLogs,
},
]
@@ -25,10 +25,12 @@ const { resource, postBody, query } = fromData
const VM_SAVEASTEMPLATE = 'vm.saveastemplate'
const GUACAMOLE = 'vm.guacamole'
const VM_LOGS = 'vm.logs'
const Actions = {
VM_SAVEASTEMPLATE,
GUACAMOLE,
VM_LOGS,
}
module.exports = {
@@ -69,5 +71,15 @@ module.exports = {
},
},
},
[VM_LOGS]: {
path: `${basepath}/:id/logs`,
httpMethod: GET,
auth: true,
params: {
id: {
from: resource,
},
},
},
},
}
+3
View File
@@ -607,6 +607,9 @@ const genPathResources = () => {
if (!global.paths.ETC_CPI) {
global.paths.ETC_CPI = `${ETC_LOCATION}/${defaultAppName}`
}
if (!global.paths.LOG_LOCATION) {
global.paths.LOG_LOCATION = LOG_LOCATION
}
}
}