feat: show systemd service logs in service details (#2440)

Co-authored-by: hank <hank@henrygd.me>
This commit is contained in:
spatiumstas
2026-09-28 13:57:36 -04:00
committed by GitHub
co-authored by hank
parent ad215788ed
commit 7626e5e3c8
19 changed files with 618 additions and 78 deletions
+6
View File
@@ -28,6 +28,8 @@ const (
SyncNetworkMonitors
// Request the list of pending package updates from agent
GetPackageUpdates
// Request recent logs for a systemd service from the agent.
GetSystemdLogs
// Add new actions here...
)
@@ -85,3 +87,7 @@ type ContainerInfoRequest struct {
type SystemdInfoRequest struct {
ServiceName string `cbor:"0,keyasint"`
}
type SystemdLogsRequest struct {
ServiceName string `cbor:"0,keyasint"`
}
+1
View File
@@ -194,6 +194,7 @@ type Info struct {
RootDiskName string `json:"rdn,omitempty" cbor:"24,keyasint,omitempty"` // custom name for root disk (set via FILESYSTEM=device__name)
PackageUpdates []uint16 `json:"pu,omitempty" cbor:"25,keyasint,omitempty"` // [totalUpdates, securityUpdates] (security omitted if unknown)
WiFi map[string]WiFi `json:"wf,omitempty" cbor:"26,keyasint,omitempty"` // connected Wi-Fi interfaces
SystemdLogs bool `json:"jl,omitempty" cbor:"27,keyasint,omitempty"` // agent can read the system journal
}
// Data that does not change during process lifetime and is not needed in All Systems table
+41
View File
@@ -15,6 +15,7 @@ import (
"github.com/blang/semver"
"github.com/henrygd/beszel"
"github.com/henrygd/beszel/internal/alerts"
systementity "github.com/henrygd/beszel/internal/entities/system"
"github.com/henrygd/beszel/internal/ghupdate"
"github.com/henrygd/beszel/internal/hub/config"
"github.com/henrygd/beszel/internal/hub/systems"
@@ -202,6 +203,8 @@ func (h *Hub) registerApiRoutes(se *core.ServeEvent) error {
apiAuth.POST("/zfs/refresh", h.refreshZfsData).BindFunc(excludeReadOnlyRole)
// get systemd service details
apiAuth.GET("/systemd/info", h.getSystemdInfo)
// get recent logs for a systemd service
apiAuth.GET("/systemd/logs", h.getSystemdLogs)
// get pending package updates
apiAuth.GET("/package-updates", h.getPackageUpdates)
// /containers routes
@@ -447,6 +450,44 @@ func (h *Hub) getSystemdInfo(e *core.RequestEvent) error {
return e.JSON(http.StatusOK, map[string]any{"details": details})
}
// getSystemdLogs handles GET /api/beszel/systemd/logs requests.
func (h *Hub) getSystemdLogs(e *core.RequestEvent) error {
query := e.Request.URL.Query()
systemID := query.Get("system")
serviceName := query.Get("service")
if systemID == "" || serviceName == "" {
return e.BadRequestError("Invalid system or service parameter", nil)
}
system, err := h.sm.GetSystem(systemID)
if err != nil || !system.HasUser(e.App, e.Auth) {
return e.NotFoundError("", nil)
}
// Only fetch logs for services that are currently monitored on this system.
_, err = e.App.FindFirstRecordByFilter("systemd_services", "system = {:system} && name = {:name}", dbx.Params{
"system": systemID,
"name": serviceName,
})
if err != nil {
return e.NotFoundError("", err)
}
// Old agents and agents without journal access do not advertise this capability.
systemRecord, err := e.App.FindRecordById("systems", systemID)
if err != nil {
return e.NotFoundError("", err)
}
var info systementity.Info
if err := systemRecord.UnmarshalJSONField("info", &info); err != nil || !info.SystemdLogs {
return e.JSON(http.StatusOK, map[string]string{"logs": ""})
}
logs, err := system.FetchSystemdLogsFromAgent(serviceName)
if err != nil {
return e.InternalServerError("", err)
}
return e.JSON(http.StatusOK, map[string]string{"logs": logs})
}
// getPackageUpdates handles GET /api/beszel/package-updates requests
func (h *Hub) getPackageUpdates(e *core.RequestEvent) error {
systemID := e.Request.URL.Query().Get("system")
+19
View File
@@ -684,6 +684,25 @@ func TestApiRoutesAuthentication(t *testing.T) {
})
},
},
{
Name: "GET /systemd/logs - old agent without capability returns empty logs",
Method: http.MethodGet,
URL: fmt.Sprintf("/api/beszel/systemd/logs?system=%s&service=nginx.service", system.Id),
Headers: map[string]string{
"Authorization": userToken,
},
ExpectedStatus: 200,
ExpectedContent: []string{`"logs":""`},
TestAppFactory: testAppFactory,
BeforeTestFunc: func(t testing.TB, app *pbTests.TestApp, e *core.ServeEvent) {
beszelTests.CreateRecord(app, "systemd_services", map[string]any{
"system": system.Id,
"name": "nginx.service",
"state": 0,
"sub": 1,
})
},
},
// Auth Optional Routes - Should work without authentication
{
+9
View File
@@ -777,6 +777,15 @@ func (sys *System) FetchSystemdInfoFromAgent(serviceName string) (systemd.Servic
return result, err
}
// FetchSystemdLogsFromAgent fetches recent journal entries for a systemd service from the agent.
func (sys *System) FetchSystemdLogsFromAgent(serviceName string) (string, error) {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
var result string
err := sys.request(ctx, common.GetSystemdLogs, common.SystemdLogsRequest{ServiceName: serviceName}, &result)
return result, err
}
// FetchSmartDataFromAgent fetches SMART data from the agent.
func (sys *System) FetchSmartDataFromAgent() (smart.SmartDataResponse, error) {
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
+10
View File
@@ -115,6 +115,16 @@ func unmarshalLegacyResponse(resp common.AgentResponse, action common.WebSocketA
}
*d = resp.ServiceInfo
return nil
case common.GetSystemdLogs:
d, ok := dest.(*string)
if !ok {
return fmt.Errorf("unexpected dest type for GetSystemdLogs: %T", dest)
}
if resp.String == nil {
return errors.New("no systemd logs in response")
}
*d = *resp.String
return nil
}
return fmt.Errorf("unsupported action: %d", action)
}
+9
View File
@@ -31,3 +31,12 @@ func TestUnmarshalSmartDataResponse(t *testing.T) {
})
}
}
func TestUnmarshalSystemdLogsResponse(t *testing.T) {
logs := "2026-09-27T12:00:00+00:00 host nginx[1]: started"
response := common.AgentResponse{String: &logs}
var result string
require.NoError(t, UnmarshalResponse(response, common.GetSystemdLogs, &result))
assert.Equal(t, logs, result)
}
@@ -32,6 +32,7 @@ import { Separator } from "../ui/separator"
import { $router, Link } from "../router"
import { listenKeys } from "nanostores"
import { getPagePath } from "@nanostores/router"
import { LogsDisplay, LogsFullscreenDialog } from "@/components/logs-display"
const syntaxTheme = "github-dark-dimmed"
@@ -372,7 +373,7 @@ function ContainerSheet({
open={logsFullscreenOpen}
onOpenChange={setLogsFullscreenOpen}
logsDisplay={logsDisplay}
containerName={container.name}
name={container.name}
onRefresh={refreshLogs}
isRefreshing={isRefreshingLogs}
/>
@@ -424,15 +425,7 @@ function ContainerSheet({
<MaximizeIcon className="size-4" />
</Button>
</div>
<div
ref={logsContainerRef}
className={cn(
"max-h-[calc(50dvh-10rem)] w-full overflow-auto p-3 rounded-md bg-gh-dark text-white text-sm",
!logsDisplay && ["animate-pulse", "h-full"]
)}
>
<div dangerouslySetInnerHTML={{ __html: logsDisplay }} />
</div>
<LogsDisplay logsDisplay={logsDisplay} containerRef={logsContainerRef} />
<div className="flex items-center w-full">
<h3>{t`Detail`}</h3>
<Button
@@ -508,58 +501,6 @@ const ContainerTableRow = memo(function ContainerTableRow({
)
})
function LogsFullscreenDialog({
open,
onOpenChange,
logsDisplay,
containerName,
onRefresh,
isRefreshing,
}: {
open: boolean
onOpenChange: (open: boolean) => void
logsDisplay: string
containerName: string
onRefresh: () => void | Promise<void>
isRefreshing: boolean
}) {
const outerContainerRef = useRef<HTMLDivElement>(null)
useEffect(() => {
if (open && logsDisplay) {
// Scroll the outer container to bottom
const scrollToBottom = () => {
if (outerContainerRef.current) {
outerContainerRef.current.scrollTop = outerContainerRef.current.scrollHeight
}
}
setTimeout(scrollToBottom, 50)
}
}, [open, logsDisplay])
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="w-[calc(100vw-20px)] h-[calc(100dvh-20px)] max-w-none p-0 bg-gh-dark border-0 text-white">
<DialogTitle className="sr-only">{containerName} logs</DialogTitle>
<div ref={outerContainerRef} className="h-full overflow-auto">
<div className="h-full w-full px-3 leading-relaxed rounded-md bg-gh-dark text-sm">
<div className="py-3" dangerouslySetInnerHTML={{ __html: logsDisplay }} />
</div>
</div>
<button
onClick={onRefresh}
className="absolute top-3 right-11 opacity-60 hover:opacity-100 p-1"
disabled={isRefreshing}
title={t`Refresh`}
aria-label={t`Refresh`}
>
<RefreshCwIcon className={`size-4 transition-transform duration-300 ${isRefreshing ? "animate-spin" : ""}`} />
</button>
</DialogContent>
</Dialog>
)
}
function InfoFullscreenDialog({
open,
onOpenChange,
@@ -0,0 +1,76 @@
/** biome-ignore-all lint/security/noDangerouslySetInnerHtml: log HTML is generated locally by Shiki */
import { t } from "@lingui/core/macro"
import { RefreshCwIcon } from "lucide-react"
import { type RefObject, useEffect, useRef } from "react"
import { Dialog, DialogContent, DialogTitle, dialogIconButtonClassName } from "@/components/ui/dialog"
import { cn } from "@/lib/utils"
type LogsDisplayProps = {
logsDisplay: string
containerRef: RefObject<HTMLDivElement | null>
}
// Shared by Docker and systemd service sheets so logs behave identically.
export function LogsDisplay({ logsDisplay, containerRef }: LogsDisplayProps) {
return (
<div
ref={containerRef}
className={cn(
"max-h-[calc(50dvh-10rem)] w-full overflow-auto p-3 rounded-md bg-gh-dark text-white text-sm",
!logsDisplay && ["animate-pulse", "h-full"]
)}
>
<div dangerouslySetInnerHTML={{ __html: logsDisplay }} />
</div>
)
}
export function LogsFullscreenDialog({
open,
onOpenChange,
logsDisplay,
name,
onRefresh,
isRefreshing,
}: {
open: boolean
onOpenChange: (open: boolean) => void
logsDisplay: string
name: string
onRefresh: () => void | Promise<void>
isRefreshing: boolean
}) {
const outerContainerRef = useRef<HTMLDivElement>(null)
useEffect(() => {
if (open && logsDisplay) {
setTimeout(() => {
if (outerContainerRef.current) {
outerContainerRef.current.scrollTop = outerContainerRef.current.scrollHeight
}
}, 50)
}
}, [open, logsDisplay])
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="w-[calc(100vw-20px)] h-[calc(100dvh-20px)] max-w-none p-0 bg-gh-dark border-0 text-white">
<DialogTitle className="sr-only">{name} logs</DialogTitle>
<div ref={outerContainerRef} className="absolute inset-x-0 bottom-0 top-12 overflow-auto">
<div className="min-h-full w-full px-3 leading-relaxed rounded-md bg-gh-dark text-sm">
<div className="py-3" dangerouslySetInnerHTML={{ __html: logsDisplay }} />
</div>
</div>
<button
onClick={onRefresh}
className={cn("absolute end-11 top-3 opacity-60 hover:opacity-100", dialogIconButtonClassName)}
disabled={isRefreshing}
title={t`Refresh`}
aria-label={t`Refresh`}
>
<RefreshCwIcon className={cn("size-4 transition-transform duration-300", isRefreshing && "animate-spin")} />
</button>
</DialogContent>
</Dialog>
)
}
@@ -13,14 +13,16 @@ import {
type VisibilityState,
} from "@tanstack/react-table"
import { useVirtualizer, type VirtualItem } from "@tanstack/react-virtual"
import { LoaderCircleIcon } from "lucide-react"
import { LoaderCircleIcon, MaximizeIcon, RefreshCwIcon } from "lucide-react"
import { listenKeys } from "nanostores"
import { memo, type ReactNode, useEffect, useMemo, useRef, useState } from "react"
import { getStatusColor, systemdTableCols } from "@/components/systemd-table/systemd-table-columns"
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert"
import { Card, CardHeader, CardTitle } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Sheet, SheetContent, SheetHeader, SheetTitle } from "@/components/ui/sheet"
import { LogsDisplay, LogsFullscreenDialog } from "@/components/logs-display"
import { Sheet, SheetContent, SheetDescription, SheetHeader, SheetTitle } from "@/components/ui/sheet"
import { TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"
import { pb } from "@/lib/api"
import { ServiceStatus, ServiceStatusLabels, type ServiceSubState, ServiceSubStateLabels } from "@/lib/enums"
@@ -29,6 +31,19 @@ import { cn, decimalString, formatBytes, useBrowserStorage } from "@/lib/utils"
import type { SystemdRecord, SystemdServiceDetails } from "@/types"
import { Separator } from "../ui/separator"
const syntaxTheme = "github-dark-dimmed"
async function getSystemdLogsHtml(systemId: string, serviceName: string): Promise<string> {
const [{ highlighter }, { logs }] = await Promise.all([
import("@/lib/shiki"),
pb.send<{ logs: string }>("/api/beszel/systemd/logs", {
requestKey: null,
query: { system: systemId, service: serviceName },
}),
])
return logs ? highlighter.codeToHtml(logs, { lang: "log", theme: syntaxTheme }) : ""
}
export default function SystemdTable({ systemId }: { systemId?: string }) {
const loadTime = Date.now()
const [data, setData] = useState<SystemdRecord[]>([])
@@ -199,8 +214,10 @@ const AllSystemdTable = memo(function AllSystemdTable({
const scrollRef = useRef<HTMLDivElement>(null)
const activeService = useRef<SystemdRecord | null>(null)
const [sheetOpen, setSheetOpen] = useState(false)
const [sheetSession, setSheetSession] = useState(0)
const openSheet = (service: SystemdRecord) => {
activeService.current = service
setSheetSession((session) => session + 1)
setSheetOpen(true)
}
@@ -245,6 +262,7 @@ const AllSystemdTable = memo(function AllSystemdTable({
</table>
</div>
<SystemdSheet
key={sheetSession}
sheetOpen={sheetOpen}
setSheetOpen={setSheetOpen}
activeService={activeService}
@@ -266,9 +284,23 @@ function SystemdSheet({
systemId?: string
}) {
const service = activeService.current
const targetSystemId = systemId ?? service?.system
const canReadLogs = !!targetSystemId && !!$allSystemsById.get()[targetSystemId]?.info?.jl
const [details, setDetails] = useState<SystemdServiceDetails | null>(null)
const [isLoading, setIsLoading] = useState(false)
const [error, setError] = useState<string | null>(null)
const [logs, setLogs] = useState("")
const [logsStatus, setLogsStatus] = useState<"loading" | "ready" | "empty" | "error">("loading")
const [isLoadingLogs, setIsLoadingLogs] = useState(false)
const [logsFullscreenOpen, setLogsFullscreenOpen] = useState(false)
const logsContainerRef = useRef<HTMLDivElement>(null)
const logsRequestId = useRef(0)
const scrollLogsToBottom = () => {
if (logsContainerRef.current) {
logsContainerRef.current.scrollTo({ top: logsContainerRef.current.scrollHeight })
}
}
useEffect(() => {
if (!sheetOpen || !service) {
@@ -283,7 +315,7 @@ function SystemdSheet({
pb.send<{ details: SystemdServiceDetails }>("/api/beszel/systemd/info", {
query: {
system: systemId,
system: targetSystemId,
service: service.name,
},
})
@@ -310,7 +342,46 @@ function SystemdSheet({
return () => {
cancelled = true
}
}, [sheetOpen, service, systemId])
}, [sheetOpen, service, targetSystemId])
const loadLogs = async () => {
if (!service || !targetSystemId || !canReadLogs) return
const requestId = ++logsRequestId.current
setLogsStatus(logs ? "ready" : "loading")
setIsLoadingLogs(true)
try {
const logs = await getSystemdLogsHtml(targetSystemId, service.name)
if (requestId !== logsRequestId.current) return
setLogs(logs)
setLogsStatus(logs ? "ready" : "empty")
} catch (err) {
if (requestId !== logsRequestId.current) return
console.error(err)
setLogsStatus("error")
} finally {
if (requestId === logsRequestId.current) setIsLoadingLogs(false)
}
}
useEffect(() => {
if (sheetOpen && canReadLogs) {
loadLogs()
}
return () => {
logsRequestId.current++
}
}, [sheetOpen, service, targetSystemId, canReadLogs])
useEffect(() => {
if (!sheetOpen) setLogsFullscreenOpen(false)
}, [sheetOpen])
useEffect(() => {
if (logs) {
setTimeout(scrollLogsToBottom, 20)
}
}, [logs])
if (!service) return null
@@ -433,19 +504,75 @@ function SystemdSheet({
return (
<Sheet open={sheetOpen} onOpenChange={setSheetOpen}>
<SheetContent className="w-full sm:max-w-220 p-6 overflow-y-auto">
<LogsFullscreenDialog
open={logsFullscreenOpen && !!logs}
onOpenChange={setLogsFullscreenOpen}
logsDisplay={logs}
name={service.name}
onRefresh={loadLogs}
isRefreshing={isLoadingLogs}
/>
<SheetContent className="w-full min-w-0 sm:max-w-220 p-6 overflow-y-auto">
<SheetHeader className="p-0">
<SheetTitle>
<Trans>Service Details</Trans>
</SheetTitle>
<SheetDescription className="sr-only">{service.name}</SheetDescription>
</SheetHeader>
<div className="grid gap-6">
{isLoading && (
<div className="flex items-center gap-2 text-sm text-muted-foreground">
<LoaderCircleIcon className="size-4 animate-spin" />
<Trans>Loading...</Trans>
<div className="grid min-w-0 grid-cols-[minmax(0,1fr)] gap-6">
{canReadLogs && (
<div className="min-w-0">
<div className="flex items-center mb-3">
<h3 className="text-sm font-medium">
<Trans>Logs</Trans>
</h3>
<Button
variant="ghost"
size="sm"
onClick={loadLogs}
className="h-8 w-8 p-0 ms-auto"
disabled={isLoadingLogs}
aria-label={t`Refresh`}
>
<RefreshCwIcon
className={cn("size-4 transition-transform duration-300", isLoadingLogs && "animate-spin")}
/>
</Button>
<Button
variant="ghost"
size="sm"
onClick={() => setLogsFullscreenOpen(true)}
className="h-8 w-8 p-0"
aria-label={t`Logs`}
disabled={!logs}
>
<MaximizeIcon className="size-4" />
</Button>
</div>
{logs ? (
<LogsDisplay logsDisplay={logs} containerRef={logsContainerRef} />
) : logsStatus === "loading" ? (
<>
<div className="h-28" aria-busy="true">
<LogsDisplay logsDisplay="" containerRef={logsContainerRef} />
</div>
<output className="sr-only">
<Trans>Loading...</Trans>
</output>
</>
) : (
<output className="flex min-h-28 items-center justify-center rounded-md bg-muted/40 p-3 text-sm text-muted-foreground">
{logsStatus === "error" ? <Trans>Failed to load logs.</Trans> : <Trans>No logs found.</Trans>}
</output>
)}
{logs && logsStatus === "error" && (
<output className="mt-2 block text-sm text-destructive">
<Trans>Failed to load logs.</Trans>
</output>
)}
</div>
)}
{error && (
<Alert className="border-destructive/50 text-destructive dark:border-destructive/60 dark:text-destructive">
<AlertTitle>
@@ -454,6 +581,12 @@ function SystemdSheet({
<AlertDescription>{error}</AlertDescription>
</Alert>
)}
{isLoading && (
<div className="flex items-center gap-2 text-sm text-muted-foreground">
<LoaderCircleIcon className="size-4 animate-spin" />
<Trans>Loading...</Trans>
</div>
)}
<div>
<div className="border rounded-md">
+9 -1
View File
@@ -12,6 +12,8 @@ const DialogPortal = DialogPrimitive.Portal
const DialogClose = DialogPrimitive.Close
const dialogIconButtonClassName = "inline-flex size-6 items-center justify-center"
const DialogOverlay = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Overlay>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Overlay>
@@ -42,7 +44,12 @@ const DialogContent = React.forwardRef<
{...props}
>
{children}
<DialogPrimitive.Close className="absolute end-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-hidden focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground">
<DialogPrimitive.Close
className={cn(
"absolute end-3 top-3 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-hidden focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground",
dialogIconButtonClassName
)}
>
<X className="h-4 w-4" />
<span className="sr-only">Close</span>
</DialogPrimitive.Close>
@@ -82,6 +89,7 @@ const DialogDescription = React.forwardRef<
DialogDescription.displayName = DialogPrimitive.Description.displayName
export {
dialogIconButtonClassName,
Dialog,
DialogPortal,
DialogOverlay,
+7 -1
View File
@@ -2,6 +2,7 @@ import * as SheetPrimitive from "@radix-ui/react-dialog"
import { XIcon } from "lucide-react"
import type * as React from "react"
import { dialogIconButtonClassName } from "@/components/ui/dialog"
import { cn } from "@/lib/utils"
function Sheet({ ...props }: React.ComponentProps<typeof SheetPrimitive.Root>) {
@@ -61,7 +62,12 @@ function SheetContent({
{...props}
>
{children}
<SheetPrimitive.Close className="ring-offset-background focus:ring-ring data-[state=open]:bg-secondary absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none">
<SheetPrimitive.Close
className={cn(
"ring-offset-background focus:ring-ring data-[state=open]:bg-secondary absolute top-3 end-3 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none",
dialogIconButtonClassName
)}
>
<XIcon className="size-4" />
<span className="sr-only">Close</span>
</SheetPrimitive.Close>
+2
View File
@@ -71,6 +71,8 @@ export interface SystemInfo {
bb?: number
/** agent version */
v: string
/** agent can read the system journal */
jl?: boolean
/** system is using podman */
p?: boolean
/** highest gpu utilization */