From 74138ac3e627b684c32a7c2d2200e715892011df Mon Sep 17 00:00:00 2001 From: Igor Kulikov Date: Tue, 24 Nov 2026 16:06:13 +0200 Subject: [PATCH] feat: the system administrator Home System card: single node CPU, RAM and disk tiles with the last hour's chart, a cluster's services table sortable with show more and scrolling, the worst load as a callout, the installed version with the hidden update brought back; the Home charts' tooltips in the design's dark readout for System and Activity --- .../devices-activity-home.component.ts | 60 +-- .../components/home-list-footer.component.ts | 25 +- .../pages/home-page/components/home-menu.scss | 4 + .../product-release-home.component.ts | 20 +- .../system-status-home.component.html | 102 ++++ .../system-status-home.component.scss | 263 ++++++++++ .../system-status-home.component.ts | 451 +++++++++++++++++- .../home/pages/home-page/home-cards.models.ts | 2 +- .../home/pages/home-page/home-chart.models.ts | 40 ++ .../pages/home-page/sys-admin-home.service.ts | 22 +- .../assets/locale/locale.constant-en_US.json | 17 + 11 files changed, 939 insertions(+), 67 deletions(-) create mode 100644 ui-ngx/src/app/modules/home/pages/home-page/components/system-status-home.component.html create mode 100644 ui-ngx/src/app/modules/home/pages/home-page/components/system-status-home.component.scss create mode 100644 ui-ngx/src/app/modules/home/pages/home-page/home-chart.models.ts diff --git a/ui-ngx/src/app/modules/home/pages/home-page/components/devices-activity-home.component.ts b/ui-ngx/src/app/modules/home/pages/home-page/components/devices-activity-home.component.ts index 6c24cd225f..e71097f755 100644 --- a/ui-ngx/src/app/modules/home/pages/home-page/components/devices-activity-home.component.ts +++ b/ui-ngx/src/app/modules/home/pages/home-page/components/devices-activity-home.component.ts @@ -8,13 +8,11 @@ import { DestroyRef, ElementRef, inject, - Injector, NgZone, Renderer2, signal, viewChild } from '@angular/core'; -import { DomSanitizer } from '@angular/platform-browser'; import { TranslateService } from '@ngx-translate/core'; import { Store } from '@ngrx/store'; import { AppState } from '@core/core.state'; @@ -28,14 +26,11 @@ import { EntityDataCmd, IntervalType, TelemetrySubscriber } from '@shared/models import { AliasFilterType } from '@shared/models/alias.models'; import { EntityKeyType } from '@shared/models/query/query.models'; import { AggregationType } from '@shared/models/time/time.models'; -import { DateFormatProcessor } from '@shared/models/widget-settings.models'; import { HomeCardId } from '@shared/models/user-settings.models'; -import { formatValue } from '@core/utils'; import { ECharts, echartsModule, EChartsOption } from '@home/components/widget/lib/chart/echarts-widget.models'; -import { TimeSeriesChartTooltip } from '@home/components/widget/lib/chart/time-series-chart-tooltip.models'; -import { TimeSeriesChartDataItem } from '@home/components/widget/lib/chart/time-series-chart.models'; import { HOME_CARDS } from '@home/pages/home-page/home-cards.models'; import { HomeToggleOption } from '@home/pages/home-page/components/home-toggle.component'; +import { homeChartHoverSymbol, homeChartTooltipHtml, homeChartTooltipOptions } from '@home/pages/home-page/home-chart.models'; type ActivitySeries = 'devices' | 'messages'; @@ -81,8 +76,6 @@ const SERIES: ActivitySeriesConfig[] = [ {id: 'messages', key: 'transportMsgCountHourly', label: 'home.activity.messages', daily: true} ]; -const font = (size: number, weight: string) => ({family: 'Roboto', size, sizeUnit: 'px', style: 'normal', weight, lineHeight: '16px'}); - @Component({ selector: 'tb-devices-activity-home', templateUrl: './devices-activity-home.component.html', @@ -103,9 +96,7 @@ export class DevicesActivityHomeComponent implements AfterViewInit { private telemetryWsService = inject(TelemetryWebsocketService); private zone = inject(NgZone); private renderer = inject(Renderer2); - private sanitizer = inject(DomSanitizer); private translate = inject(TranslateService); - private injector = inject(Injector); private host = inject>(ElementRef); readonly tab = signal(this.series[0].id); @@ -124,24 +115,6 @@ export class DevicesActivityHomeComponent implements AfterViewInit { private subscribers: TelemetrySubscriber[] = []; private resizeObserver: ResizeObserver; - private readonly tooltip = new TimeSeriesChartTooltip(this.renderer, this.sanitizer, { - showTooltip: true, - tooltipTrigger: undefined, - tooltipLabelFont: font(12, '400'), - tooltipLabelColor: 'rgba(0, 0, 0, 0.76)', - tooltipValueFont: font(12, '500'), - tooltipValueColor: 'rgba(0, 0, 0, 0.76)', - tooltipShowDate: true, - tooltipDateInterval: false, - tooltipDateFormat: {format: null, lastUpdateAgo: false, custom: false, auto: true, autoDateFormatSettings: {}}, - tooltipDateFont: {...font(11, '400')}, - tooltipDateColor: 'rgba(0, 0, 0, 0.76)', - tooltipBackgroundColor: 'rgba(255, 255, 255, 0.76)', - tooltipBackgroundBlur: 4 - }, DateFormatProcessor.fromSettings(this.injector, - {format: null, lastUpdateAgo: false, custom: false, auto: true, autoDateFormatSettings: {}}), - (value, _latestData, units, decimals) => formatValue(value, decimals, units, false), this.translate); - private endTs = Date.now(); private startTs = startOfFirstDay(this.endTs); @@ -267,6 +240,16 @@ export class DevicesActivityHomeComponent implements AfterViewInit { return `${String(date.getDate()).padStart(2, '0')} ${date.toLocaleString(this.translate.currentLang?.replace('_', '-') || 'en-US', {month: 'short'})}`; } + private tooltipHeader(series: ActivitySeriesConfig, offset: number): string { + const span = this.endTs - this.startTs; + const date = new Date(this.startTs + offset); + const day = `${String(date.getDate()).padStart(2, '0')} ${date.toLocaleString(this.translate.currentLang?.replace('_', '-') || 'en-US', {month: 'short'})}`; + if (series.daily) { + return offset >= span - 1000 ? this.translate.instant('home.activity.today') : day; + } + return `${day}, ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`; + } + setTab(tab: ActivitySeries): void { this.tab.set(tab); setTimeout(() => Object.values(this.charts).forEach(chart => chart.resize())); @@ -300,25 +283,17 @@ export class DevicesActivityHomeComponent implements AfterViewInit { private option(series: ActivitySeriesConfig, points: [number, number][], color: string): EChartsOption { const label = this.translate.instant(series.label); - const daily = series.daily; - const dataItems = [{id: series.id, units: '', decimals: 0, latestData: {}} as unknown as TimeSeriesChartDataItem]; const span = this.endTs - this.startTs; const yScale = scale(points); - const toAbsolute = (params: CallbackDataParams[]) => params.map(param => - ({...param, value: [Number(param.value[0]) + this.startTs, param.value[1]]}) as CallbackDataParams); return { backgroundColor: 'transparent', tooltip: [{ - trigger: 'axis', - confine: true, - appendTo: 'body', - axisPointer: {type: 'line'}, - formatter: (params: CallbackDataParams[]) => - this.tooltip.formatted(toAbsolute(params.filter(param => param.seriesId === series.id)), -1, dataItems, daily ? DAY : null), - padding: [8, 12], - backgroundColor: 'rgba(255, 255, 255, 0.76)', - borderWidth: 0, - extraCssText: 'line-height: 1; backdrop-filter: blur(4px);' + ...homeChartTooltipOptions, + formatter: (params: CallbackDataParams[]) => { + const param = params.find(item => item.seriesId === series.id); + return param ? homeChartTooltipHtml(this.tooltipHeader(series, Number(param.value[0])), + [{color, name: label, value: shortNumber(Number(param.value[1]))}]) : ''; + } }], grid: [{left: 36, right: 28, top: 6, bottom: 26, containLabel: false}], xAxis: [{ @@ -360,6 +335,7 @@ export class DevicesActivityHomeComponent implements AfterViewInit { color, smooth: false, showSymbol: false, + ...homeChartHoverSymbol(color), lineStyle: {width: 2, color, cap: 'round', join: 'round'}, areaStyle: { color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [ diff --git a/ui-ngx/src/app/modules/home/pages/home-page/components/home-list-footer.component.ts b/ui-ngx/src/app/modules/home/pages/home-page/components/home-list-footer.component.ts index 717c8c2ea8..4ae2813187 100644 --- a/ui-ngx/src/app/modules/home/pages/home-page/components/home-list-footer.component.ts +++ b/ui-ngx/src/app/modules/home/pages/home-page/components/home-list-footer.component.ts @@ -2,7 +2,7 @@ // SPDX-License-Identifier: BUSL-1.1 import { ChangeDetectionStrategy, Component, computed, input, output } from '@angular/core'; import { Params } from '@angular/router'; -import { HOME_LIST_LIMIT, homeListFew, homeListShown } from '@home/pages/home-page/home-list.models'; +import { HOME_LIST_LIMIT, HOME_LIST_PREVIEW, HOME_LIST_SLACK } from '@home/pages/home-page/home-list.models'; @Component({ selector: 'tb-home-list-footer', @@ -39,16 +39,33 @@ export class HomeListFooterComponent { params = input(null); + preview = input(HOME_LIST_PREVIEW); + + slack = input(HOME_LIST_SLACK); + + limit = input(HOME_LIST_LIMIT); + + scroll = input(false); + expandedChange = output(); - readonly few = computed(() => homeListFew(this.total())); + readonly few = computed(() => this.total() <= this.preview() + this.slack()); - readonly shown = computed(() => homeListShown(this.total(), this.expanded())); + readonly shown = computed(() => { + const total = this.total(); + if (this.few()) { + return total; + } + if (this.expanded()) { + return this.scroll() ? total : Math.min(total, this.limit()); + } + return this.preview(); + }); readonly toggleLabel = computed(() => { if (this.expanded()) { return 'home.list.show-less'; } - return this.total() <= HOME_LIST_LIMIT ? 'home.list.show-all' : 'home.list.show-more'; + return this.total() <= this.limit() ? 'home.list.show-all' : 'home.list.show-more'; }); } diff --git a/ui-ngx/src/app/modules/home/pages/home-page/components/home-menu.scss b/ui-ngx/src/app/modules/home/pages/home-page/components/home-menu.scss index 53d2c903dd..e19adf59c1 100644 --- a/ui-ngx/src/app/modules/home/pages/home-page/components/home-menu.scss +++ b/ui-ngx/src/app/modules/home/pages/home-page/components/home-menu.scss @@ -9,3 +9,7 @@ margin-bottom: 4px; } } + +.tb-system-tooltip .mdc-tooltip__surface { + white-space: pre-line; +} diff --git a/ui-ngx/src/app/modules/home/pages/home-page/components/product-release-home.component.ts b/ui-ngx/src/app/modules/home/pages/home-page/components/product-release-home.component.ts index c9cef6714d..60ccbe60d3 100644 --- a/ui-ngx/src/app/modules/home/pages/home-page/components/product-release-home.component.ts +++ b/ui-ngx/src/app/modules/home/pages/home-page/components/product-release-home.component.ts @@ -2,14 +2,12 @@ // SPDX-License-Identifier: BUSL-1.1 import { ChangeDetectionStrategy, Component, computed, inject, signal } from '@angular/core'; import { TranslateService } from '@ngx-translate/core'; -import { AdminService } from '@core/http/admin.service'; import { ToastNotificationService } from '@core/services/toast-notification.service'; import { UpdateMessage } from '@shared/models/settings.models'; +import { SysAdminHomeService } from '@home/pages/home-page/sys-admin-home.service'; const UNDO_MS = 6000; -let hiddenVersion: string | null = null; - @Component({ selector: 'tb-product-release-home', templateUrl: './product-release-home.component.html', @@ -21,23 +19,22 @@ export class ProductReleaseHomeComponent { private translate = inject(TranslateService); private toast = inject(ToastNotificationService); + private sysAdminHome = inject(SysAdminHomeService); readonly update = signal(null); - private readonly hidden = signal(hiddenVersion); - readonly shown = computed(() => { const update = this.update(); - return !!update?.updateAvailable && this.hidden() !== update.latestVersion; + return !!update?.updateAvailable && this.sysAdminHome.hiddenRelease() !== update.latestVersion; }); constructor() { - inject(AdminService).checkUpdates({ignoreErrors: true, ignoreLoading: true}).subscribe(update => this.update.set(update)); + this.sysAdminHome.update$.subscribe(update => this.update.set(update)); } hide(): void { const version = this.update().latestVersion; - this.setHidden(version); + this.sysAdminHome.setHiddenRelease(version); this.toast.dispatchNotification({ message: this.translate.instant('home.release.hidden', {version}), type: 'info', @@ -46,12 +43,7 @@ export class ProductReleaseHomeComponent { verticalPosition: 'bottom', panelClass: 'tb-home-toast', actionLabel: this.translate.instant('home.customize.undo'), - onAction: () => this.setHidden(null) + onAction: () => this.sysAdminHome.setHiddenRelease(null) }); } - - private setHidden(version: string | null): void { - hiddenVersion = version; - this.hidden.set(version); - } } diff --git a/ui-ngx/src/app/modules/home/pages/home-page/components/system-status-home.component.html b/ui-ngx/src/app/modules/home/pages/home-page/components/system-status-home.component.html new file mode 100644 index 0000000000..228bb5a5cc --- /dev/null +++ b/ui-ngx/src/app/modules/home/pages/home-page/components/system-status-home.component.html @@ -0,0 +1,102 @@ + + + @if (loaded()) { + {{ cluster() ? ('home.system.services' | translate: {count: services().length}) : ('home.system.last-hour' | translate) }} + } + + @if (update(); as info) { + + @if (info.currentVersionReleaseNotesUrl) { + {{ 'home.system.version' | translate: {version: info.currentVersion} }} + } @else { + {{ 'home.system.version' | translate: {version: info.currentVersion} }} + } + @if (releaseHidden()) { + + } + + } + + @if (loaded()) { + @if (cluster()) { +
+ + + + + + @for (metric of metrics; track metric.id) { + + } + + + + @for (service of shownServices(); track service.serviceId) { + + + + @for (metric of metrics; track metric.id) { + @let figLevel = serviceLevel(service, metric.id); + + } + + } + +
+ + + + + +
{{ service.serviceId }}{{ service.serviceType }} + + @if (figLevel) { + {{ figLevel === 'crit' ? 'error' : 'warning' }} + } + {{ serviceValue(service, metric.id) }}% + +
+
+ + } @else { +
+ @for (gauge of gauges(); track gauge.id) { +
+
+ {{ gauge.label | translate }} + @if (gauge.level) { + {{ gauge.level === 'crit' ? 'error' : 'warning' }} + } +
+
{{ gauge.value | number: '1.0-0' }}%{{ gauge.total }}
+
+ } +
+ + } + @if (callout(); as note) { +
+ {{ note.level === 'crit' ? 'error_outline' : 'warning_amber' }} + {{ note.title }}. {{ note.text }} +
+ } + } +
diff --git a/ui-ngx/src/app/modules/home/pages/home-page/components/system-status-home.component.scss b/ui-ngx/src/app/modules/home/pages/home-page/components/system-status-home.component.scss new file mode 100644 index 0000000000..9f1dfb1fd2 --- /dev/null +++ b/ui-ngx/src/app/modules/home/pages/home-page/components/system-status-home.component.scss @@ -0,0 +1,263 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +@use './home-table'; + +:host { + display: block; + min-width: 0; +} + +.tb-system-period { + margin-left: 4px; + font: 400 14px/20px var(--tb-font, Roboto, sans-serif); + white-space: nowrap; + color: var(--tb-ink-54, rgba(0, 0, 0, 0.54)); +} + +.tb-system-version { + display: inline-flex; + align-items: baseline; + gap: 8px; + white-space: nowrap; +} + +.tb-system-version-link { + font: 400 14px/20px var(--tb-font, Roboto, sans-serif); + white-space: nowrap; + text-decoration: none; + color: var(--tb-ink-54, rgba(0, 0, 0, 0.54)); + + &, &:hover, &:focus, &:active { + border-bottom: none; + } + + &:is(a):hover { + text-decoration: underline; + color: var(--tb-ink, rgba(0, 0, 0, 0.87)); + } +} + +.tb-system-version-new { + padding: 0; + border: 0; + background: none; + font: 500 14px/20px var(--tb-font, Roboto, sans-serif); + color: var(--tb-primary-500); + cursor: pointer; + + &::before { + content: "ยท"; + margin-right: 8px; + font-weight: 400; + color: var(--tb-ink-38, rgba(0, 0, 0, 0.38)); + } + + &:hover { + text-decoration: underline; + } + + &:focus-visible { + outline: 2px solid var(--tb-primary-500); + outline-offset: 2px; + border-radius: 2px; + } +} + +.tb-system-gauges { + display: grid; + grid-template-columns: repeat(3, minmax(0, 1fr)); + gap: 8px; +} + +.tb-system-gauge { + display: flex; + flex-direction: column; + gap: 6px; + box-sizing: border-box; + min-width: 0; + padding: 8px 12px 10px; + border: 1px solid rgba(0, 0, 0, 0.10); + border-radius: 10px; + background: #fff; + + &.warn .tb-system-gauge-count { + color: #955400; + } + + &.crit .tb-system-gauge-count { + color: var(--tb-sev-critical, #D12730); + } + + &.crit .tb-system-gauge-mark { + color: var(--tb-sev-critical, #D12730); + } +} + +.tb-system-gauge-head { + display: flex; + align-items: center; + justify-content: space-between; +} + +.tb-system-gauge-title { + display: inline-flex; + align-items: center; + gap: 6px; + font: 400 14px/20px var(--tb-font, Roboto, sans-serif); + letter-spacing: 0.1px; + color: var(--tb-ink-76, rgba(0, 0, 0, 0.76)); +} + +.tb-system-key { + flex: none; + width: 8px; + height: 8px; + border-radius: 50%; +} + +.tb-system-gauge-mark.mat-icon { + width: 18px; + height: 18px; + font-size: 18px; + color: #b26500; +} + +.tb-system-gauge-count { + display: flex; + flex-wrap: wrap; + align-items: baseline; + gap: 0 6px; + font: 500 20px/28px var(--tb-font, Roboto, sans-serif); + white-space: nowrap; + font-variant-numeric: tabular-nums; + color: var(--tb-ink, rgba(0, 0, 0, 0.87)); +} + +.tb-system-gauge-total { + font: 400 13px/18px var(--tb-font, Roboto, sans-serif); + white-space: nowrap; + color: var(--tb-text-secondary, rgba(0, 0, 0, 0.6)); +} + +.tb-system-chart { + height: 130px; +} + +.tb-system-services-wrap.scrolling { + max-height: calc(32px + var(--tb-system-rows) * 36px); + overflow-y: auto; + scrollbar-width: thin; + + thead th { + position: sticky; + top: 0; + z-index: 1; + background: var(--tb-surface, #fff); + } +} + +.tb-system-services { + table-layout: auto; + + tbody tr { + cursor: default; + } + + .col-service { + width: 99%; + max-width: 0; + overflow: hidden; + text-overflow: ellipsis; + } + + td.col-type { + font-size: 13px; + color: var(--tb-text-secondary, rgba(0, 0, 0, 0.6)); + } + + .col-num { + width: 64px; + text-align: right; + } + + th.col-num .th-label { + flex-direction: row-reverse; + } +} + +.tb-system-mono { + font-family: 'Roboto Mono', monospace; + font-size: 13px; +} + +.tb-system-fig { + display: inline-flex; + align-items: center; + gap: 2px; + font-variant-numeric: tabular-nums; + + .mat-icon { + width: 16px; + height: 16px; + font-size: 16px; + color: inherit; + } + + &.warn { + color: #955400; + } + + &.crit { + font-weight: 500; + color: var(--tb-sev-critical, #D12730); + } +} + +.tb-system-callout { + display: flex; + align-items: flex-start; + gap: 10px; + padding: 10px 12px; + border-radius: 8px; + font: 400 13px/18px var(--tb-font, Roboto, sans-serif); + color: var(--tb-ink-76, rgba(0, 0, 0, 0.76)); + + > .mat-icon { + flex: none; + width: 20px; + height: 20px; + font-size: 20px; + } + + > span { + flex: 1; + min-width: 0; + } + + &.crit { + background: rgba(209, 39, 48, 0.04); + + > .mat-icon { + color: var(--tb-sev-critical, #D12730); + } + } + + &.warn { + background: rgb(255 167 38 / 0.16); + + > .mat-icon { + color: #b26500; + } + } +} + +@container tb-home (max-width: 599px) { + .tb-system-services .col-type { + display: none; + } + + .tb-system-gauge { + padding-right: 8px; + padding-left: 8px; + } +} diff --git a/ui-ngx/src/app/modules/home/pages/home-page/components/system-status-home.component.ts b/ui-ngx/src/app/modules/home/pages/home-page/components/system-status-home.component.ts index dea5e21c67..49ab7166a0 100644 --- a/ui-ngx/src/app/modules/home/pages/home-page/components/system-status-home.component.ts +++ b/ui-ngx/src/app/modules/home/pages/home-page/components/system-status-home.component.ts @@ -1,16 +1,461 @@ // SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. // SPDX-License-Identifier: BUSL-1.1 -import { ChangeDetectionStrategy, Component } from '@angular/core'; +import { + afterRenderEffect, + ChangeDetectionStrategy, + Component, + computed, + DestroyRef, + ElementRef, + inject, + NgZone, + Renderer2, + signal, + viewChild +} from '@angular/core'; +import { TranslateService } from '@ngx-translate/core'; +import * as echarts from 'echarts/core'; +import { CallbackDataParams } from 'echarts/types/dist/shared'; +import { TelemetryWebsocketService } from '@core/ws/telemetry-websocket.service'; +import { EntityDataCmd, IntervalType, TelemetrySubscriber } from '@shared/models/telemetry/telemetry.models'; +import { AliasFilterType } from '@shared/models/alias.models'; +import { EntityKeyType } from '@shared/models/query/query.models'; +import { AggregationType } from '@shared/models/time/time.models'; +import { UpdateMessage } from '@shared/models/settings.models'; import { HomeCardId } from '@shared/models/user-settings.models'; +import { ECharts, echartsModule, EChartsOption } from '@home/components/widget/lib/chart/echarts-widget.models'; import { HOME_CARDS } from '@home/pages/home-page/home-cards.models'; +import { SysAdminHomeService } from '@home/pages/home-page/sys-admin-home.service'; +import { homeChartHoverSymbol, homeChartTooltipHtml, homeChartTooltipOptions } from '@home/pages/home-page/home-chart.models'; + +type SystemMetric = 'cpu' | 'ram' | 'disk'; +type SystemLevel = 'crit' | 'warn' | ''; +type ServiceSortKey = 'serviceId' | 'serviceType' | SystemMetric; + +interface MetricConfig { + id: SystemMetric; + key: string; + label: string; + color: string; +} + +interface ClusterService { + serviceId: string; + serviceType: string; + cpuUsage: number; + cpuCount: number; + memoryUsage: number; + totalMemory: number; + discUsage: number; + totalDiscSpace: number; +} + +interface SystemWorst { + metric: SystemMetric; + value: number; + level: SystemLevel; + services: string[]; +} + +const METRICS: MetricConfig[] = [ + {id: 'cpu', key: 'cpuUsage', label: 'widgets.system-info.cpu', color: '#305680'}, + {id: 'ram', key: 'memoryUsage', label: 'widgets.system-info.ram', color: '#9c27b0'}, + {id: 'disk', key: 'discUsage', label: 'widgets.system-info.disk', color: '#26a69a'} +]; + +const SERVICE_KEYS: Record = {cpu: 'cpuUsage', ram: 'memoryUsage', disk: 'discUsage'}; +const LATEST_KEYS = ['clusterMode', 'clusterSystemData', 'cpuUsage', 'cpuCount', 'memoryUsage', 'totalMemory', 'discUsage', 'totalDiscSpace']; +const HOUR = 3600000; +const MINUTE = 60000; +const LABEL_STEP = 15 * MINUTE; +const LOADING_HEIGHT = 304; +const SERVICES_PREVIEW = 8; +const SERVICES_SLACK = 2; +const SERVICES_LIMIT = 20; +const AXIS_LABEL = {color: 'rgba(0, 0, 0, 0.56)', fontFamily: 'Roboto', fontSize: 12, fontWeight: 400, lineHeight: 16}; + +const GB = 1024 * 1024 * 1024; + +const gigabytes = (bytes: number): number => Math.round(bytes / GB); + +const level = (value: number): SystemLevel => value > 85 ? 'crit' : value > 75 ? 'warn' : ''; @Component({ selector: 'tb-system-status-home', - template: ``, + templateUrl: './system-status-home.component.html', + styleUrls: ['./system-status-home.component.scss'], standalone: false, changeDetection: ChangeDetectionStrategy.OnPush }) export class SystemStatusHomeComponent { - readonly card = HOME_CARDS[HomeCardId.SYSTEM_STATUS]; + readonly metrics = METRICS; + + private telemetryWsService = inject(TelemetryWebsocketService); + private zone = inject(NgZone); + private renderer = inject(Renderer2); + private translate = inject(TranslateService); + private host = inject>(ElementRef); + private sysAdminHome = inject(SysAdminHomeService); + + private readonly latest = signal | null>(null); + private readonly history = signal>({cpu: [], ram: [], disk: []}); + private readonly window = signal({start: Date.now() - HOUR, end: Date.now()}); + + readonly servicesPreview = SERVICES_PREVIEW; + readonly servicesSlack = SERVICES_SLACK; + readonly servicesLimit = SERVICES_LIMIT; + + readonly expanded = signal(false); + + readonly update = signal(null); + readonly sort = signal<[ServiceSortKey, 'asc' | 'desc']>(['serviceId', 'asc']); + + readonly cluster = computed(() => this.latest()?.clusterMode === 'true'); + + readonly loaded = computed(() => this.latest() !== null); + + readonly cardDefinition = computed(() => { + const card = HOME_CARDS[HomeCardId.SYSTEM_STATUS]; + return this.loaded() ? card : {...card, height: LOADING_HEIGHT}; + }); + + readonly services = computed(() => { + const data = this.latest()?.clusterSystemData; + if (!this.cluster() || !data) { + return []; + } + try { + return JSON.parse(data); + } catch { + return []; + } + }); + + readonly sortedServices = computed(() => { + const [key, direction] = this.sort(); + const value = (service: ClusterService) => key === 'serviceId' || key === 'serviceType' ? service[key] : service[SERVICE_KEYS[key]]; + return [...this.services()].sort((a, b) => { + const first = value(a); + const second = value(b); + return (first > second ? 1 : first < second ? -1 : 0) * (direction === 'asc' ? 1 : -1); + }); + }); + + readonly shownServices = computed(() => { + const services = this.sortedServices(); + if (this.expanded() || services.length <= SERVICES_PREVIEW + SERVICES_SLACK) { + return services; + } + return services.slice(0, SERVICES_PREVIEW); + }); + + readonly scrolling = computed(() => this.expanded() && this.services().length > SERVICES_LIMIT); + + readonly gauges = computed(() => { + const latest = this.latest() ?? {}; + const totals: Record = { + cpu: this.translate.instant('home.system.cores', {count: this.number(latest.cpuCount)}), + ram: this.translate.instant('home.system.gb', {value: gigabytes(this.number(latest.totalMemory))}), + disk: this.translate.instant('home.system.gb', {value: gigabytes(this.number(latest.totalDiscSpace))}) + }; + const totalValues: Record = { + cpu: 100, ram: this.number(latest.totalMemory), disk: this.number(latest.totalDiscSpace) + }; + return METRICS.map(metric => { + const value = this.number(latest[metric.key]); + return { + ...metric, + value, + level: level(value), + total: totals[metric.id], + tooltip: this.valueTooltip(metric.id, value, totalValues[metric.id]) + }; + }); + }); + + readonly worst = computed(() => { + if (!this.loaded()) { + return null; + } + let loads: {metric: SystemMetric; value: number; service?: string}[]; + if (this.cluster()) { + loads = this.services().flatMap(service => METRICS.map(metric => + ({metric: metric.id, value: Number(service[SERVICE_KEYS[metric.id]]) || 0, service: service.serviceId}))); + } else { + loads = this.gauges().map(gauge => ({metric: gauge.id, value: gauge.value})); + } + if (!loads.length) { + return null; + } + const top = loads.reduce((max, load) => load.value > max.value ? load : max); + return { + metric: top.metric, + value: top.value, + level: level(top.value), + services: loads.filter(load => load.service && load.metric === top.metric && load.value === top.value).map(load => load.service) + }; + }); + + readonly callout = computed(() => { + const worst = this.worst(); + if (!worst?.level) { + return null; + } + const name = this.metricName(worst.metric); + const value = Math.round(worst.value); + const title = worst.services.length + ? this.translate.instant('home.system.at-on', {name, value, services: worst.services.join(this.translate.instant('home.system.and'))}) + : this.translate.instant('home.system.at', {name, value}); + return {level: worst.level, title, text: this.levelText(worst.metric, worst.level).replace(/^[^.]+\.\s*/, '')}; + }); + + readonly releaseHidden = computed(() => { + const update = this.update(); + return !!update?.updateAvailable && this.sysAdminHome.hiddenRelease() === update.latestVersion; + }); + + private readonly chartElement = viewChild>('chart'); + + private chart: ECharts | null = null; + + constructor() { + this.sysAdminHome.update$.subscribe(update => this.update.set(update)); + const subscriber = this.subscribe(); + const tick = setInterval(() => this.window.set({start: Date.now() - HOUR, end: Date.now()}), MINUTE); + const resizeObserver = new ResizeObserver(() => this.chart?.resize()); + resizeObserver.observe(this.host.nativeElement); + afterRenderEffect(() => this.render()); + inject(DestroyRef).onDestroy(() => { + subscriber.unsubscribe(); + clearInterval(tick); + resizeObserver.disconnect(); + this.chart?.dispose(); + }); + } + + sortBy(key: ServiceSortKey): void { + const [current, direction] = this.sort(); + if (current === key) { + this.sort.set([key, direction === 'asc' ? 'desc' : 'asc']); + } else { + this.sort.set([key, key === 'serviceId' || key === 'serviceType' ? 'asc' : 'desc']); + } + } + + sortIcon(key: ServiceSortKey): string { + const [current, direction] = this.sort(); + return current === key && direction === 'desc' ? 'arrow_downward' : 'arrow_upward'; + } + + ariaSort(key: ServiceSortKey): string { + const [current, direction] = this.sort(); + return current === key ? (direction === 'asc' ? 'ascending' : 'descending') : 'none'; + } + + serviceValue(service: ClusterService, metric: SystemMetric): number { + return Math.round(Number(service[SERVICE_KEYS[metric]]) || 0); + } + + serviceLevel(service: ClusterService, metric: SystemMetric): SystemLevel { + return level(Number(service[SERVICE_KEYS[metric]]) || 0); + } + + serviceTooltip(service: ClusterService, metric: SystemMetric): string { + const total = metric === 'cpu' ? 100 : metric === 'ram' ? service.totalMemory : service.totalDiscSpace; + return this.valueTooltip(metric, Number(service[SERVICE_KEYS[metric]]) || 0, total); + } + + showRelease(): void { + this.sysAdminHome.setHiddenRelease(null); + setTimeout(() => document.querySelector('[data-home-card="productRelease"]')?.scrollIntoView({behavior: 'smooth', block: 'nearest'})); + } + + private subscribe(): TelemetrySubscriber { + const now = Date.now(); + const cmd = new EntityDataCmd(); + cmd.query = { + entityFilter: {type: AliasFilterType.apiUsageState}, + pageLink: {page: 0, pageSize: 1}, + entityFields: [], + latestValues: LATEST_KEYS.map(key => ({type: EntityKeyType.TIME_SERIES, key})) + }; + cmd.historyCmd = { + keys: METRICS.map(metric => metric.key), + startTs: now - HOUR, + endTs: now, + intervalType: IntervalType.MILLISECONDS, + interval: 1000, + timeZoneId: Intl.DateTimeFormat().resolvedOptions().timeZone, + limit: 1000, + agg: AggregationType.NONE + }; + cmd.latestCmd = {keys: LATEST_KEYS.map(key => ({type: EntityKeyType.TIME_SERIES, key}))}; + const subscriber = new TelemetrySubscriber(this.telemetryWsService, this.zone); + subscriber.subscriptionCommands.push(cmd); + subscriber.entityData$.subscribe(update => { + const entity = (update.data?.data ?? update.update ?? [])[0]; + if (!entity) { + if (update.data) { + this.latest.set({}); + } + return; + } + const latest = {...(this.latest() ?? {})}; + LATEST_KEYS.forEach(key => { + const value = entity.latest?.[EntityKeyType.TIME_SERIES]?.[key]; + if (value?.ts) { + latest[key] = value.value; + } + }); + const history = {...this.history()}; + METRICS.forEach(metric => { + const points = new Map(history[metric.id]); + (entity.timeseries?.[metric.key] ?? []).forEach(value => points.set(value.ts, Number(value.value))); + const value = entity.latest?.[EntityKeyType.TIME_SERIES]?.[metric.key]; + if (value?.ts) { + points.set(value.ts, Number(value.value)); + } + history[metric.id] = [...points.entries()].filter(([, number]) => !isNaN(number)).sort((a, b) => a[0] - b[0]); + }); + this.history.set(history); + this.latest.set(latest); + this.window.set({start: Date.now() - HOUR, end: Date.now()}); + }); + subscriber.subscribe(); + return subscriber; + } + + private render(): void { + const element = this.chartElement()?.nativeElement; + const history = this.history(); + const window = this.window(); + if (!element) { + this.chart?.dispose(); + this.chart = null; + return; + } + echartsModule.init(); + if (this.chart && this.chart.getDom() !== element) { + this.chart.dispose(); + this.chart = null; + } + if (!this.chart) { + this.renderer.setStyle(element, 'letterSpacing', 'normal'); + this.chart = echarts.init(element, null, {renderer: 'svg'}); + } + this.chart.setOption(this.option(history, window), true); + } + + private option(history: Record, window: {start: number; end: number}): EChartsOption { + const span = window.end - window.start; + const series = METRICS.map(metric => ({ + metric, + points: history[metric.id].filter(([ts]) => ts >= window.start).map(([ts, value]) => [ts - window.start, value] as [number, number]) + })); + return { + backgroundColor: 'transparent', + tooltip: [{ + ...homeChartTooltipOptions, + formatter: (params: CallbackDataParams[]) => this.tooltip(params.filter(param => METRICS.some(metric => metric.id === param.seriesId)), + window.start) + }], + grid: [{left: 40, right: 12, top: 6, bottom: 26, containLabel: false}], + xAxis: [{ + type: 'value', + min: 0, + max: span, + interval: LABEL_STEP, + axisLine: {show: false}, + axisTick: {show: false}, + splitLine: {show: false}, + axisLabel: { + ...AXIS_LABEL, + margin: 12, + showMinLabel: true, + showMaxLabel: true, + alignMinLabel: 'left', + alignMaxLabel: 'right', + formatter: (value: number) => this.xLabel(window.start, span, value) + } + }], + yAxis: [{ + type: 'value', + min: 0, + max: 100, + interval: 50, + axisLine: {show: false}, + axisTick: {show: false}, + splitLine: {show: true, lineStyle: {color: 'rgba(0, 0, 0, 0.06)', width: 1}}, + axisLabel: {...AXIS_LABEL, margin: 8, formatter: (value: number) => `${value}%`} + }], + series: series.flatMap(({metric, points}) => [{ + id: metric.id, + type: 'line' as const, + name: this.translate.instant(metric.label), + color: metric.color, + smooth: false, + showSymbol: false, + ...homeChartHoverSymbol(metric.color), + lineStyle: {width: 2, color: metric.color, cap: 'round' as const, join: 'round' as const}, + data: points + }, { + id: `${metric.id}-now`, + type: 'line' as const, + silent: true, + tooltip: {show: false}, + showSymbol: true, + symbol: 'circle', + symbolSize: 8, + z: 3, + itemStyle: {color: metric.color, borderColor: '#fff', borderWidth: 2}, + lineStyle: {width: 0}, + data: points.length ? [points[points.length - 1]] : [] + }]), + animation: false + }; + } + + private tooltip(params: CallbackDataParams[], start: number): string { + if (!params.length) { + return ''; + } + const date = new Date(Number(params[0].value[0]) + start); + const time = `${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`; + return homeChartTooltipHtml(time, params.map(param => { + const metric = METRICS.find(item => item.id === param.seriesId); + return {color: metric.color, name: this.metricName(metric.id), value: `${Math.round(Number(param.value[1]))}%`}; + })); + } + + private xLabel(start: number, span: number, offset: number): string { + if (offset >= span - 1000) { + return this.translate.instant('home.system.now'); + } + if (offset > span - LABEL_STEP + MINUTE) { + return ''; + } + const date = new Date(start + offset); + return `${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`; + } + + private valueTooltip(metric: SystemMetric, value: number, total: number): string { + const rounded = Math.round(value); + const used = metric === 'cpu' ? `${rounded} / 100 %` : `${gigabytes(total * value / 100)} / ${gigabytes(total)} GB`; + const valueLevel = level(value); + return valueLevel ? `${used}\n\n${this.levelText(metric, valueLevel)}` : used; + } + + private levelText(metric: SystemMetric, valueLevel: SystemLevel): string { + return this.translate.instant(`widgets.system-info.${metric}-${valueLevel === 'crit' ? 'critical' : 'warning'}-text`); + } + + private metricName(metric: SystemMetric): string { + return this.translate.instant(`widgets.system-info.${metric}`); + } + + private number(value: string | undefined): number { + const number = Number(value); + return isFinite(number) ? number : 0; + } } diff --git a/ui-ngx/src/app/modules/home/pages/home-page/home-cards.models.ts b/ui-ngx/src/app/modules/home/pages/home-page/home-cards.models.ts index 917a916973..b071924468 100644 --- a/ui-ngx/src/app/modules/home/pages/home-page/home-cards.models.ts +++ b/ui-ngx/src/app/modules/home/pages/home-page/home-cards.models.ts @@ -24,7 +24,7 @@ export const HOME_CARDS: Record = { [HomeCardId.MOBILE_APP]: {id: HomeCardId.MOBILE_APP, icon: 'phone_iphone', name: 'home.cards.mobile-app'}, [HomeCardId.PRODUCT_RELEASE]: {id: HomeCardId.PRODUCT_RELEASE, icon: 'new_releases', name: 'home.cards.product-release', height: 100}, [HomeCardId.GET_STARTED_SYS_ADMIN]: {id: HomeCardId.GET_STARTED_SYS_ADMIN, icon: 'rocket_launch', name: 'home.cards.get-started'}, - [HomeCardId.SYSTEM_STATUS]: {id: HomeCardId.SYSTEM_STATUS, icon: 'dns', name: 'home.cards.system-status', height: 304}, + [HomeCardId.SYSTEM_STATUS]: {id: HomeCardId.SYSTEM_STATUS, icon: 'dns', name: 'home.cards.system-status'}, [HomeCardId.LICENSE]: {id: HomeCardId.LICENSE, icon: 'verified', name: 'home.cards.license', link: '/license', height: 398}, [HomeCardId.INSTALL_ITEMS]: {id: HomeCardId.INSTALL_ITEMS, icon: 'domain', name: 'home.cards.install-items'} }; diff --git a/ui-ngx/src/app/modules/home/pages/home-page/home-chart.models.ts b/ui-ngx/src/app/modules/home/pages/home-page/home-chart.models.ts new file mode 100644 index 0000000000..6449ea8a75 --- /dev/null +++ b/ui-ngx/src/app/modules/home/pages/home-page/home-chart.models.ts @@ -0,0 +1,40 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 + +export interface HomeChartTooltipRow { + color: string; + name: string; + value: string; +} + +const escapeHtml = (text: string): string => + text.replace(/&/g, '&').replace(//g, '>').replace(/"/g, '"'); + +export const homeChartTooltipHtml = (header: string, rows: HomeChartTooltipRow[]): string => { + const items = rows.map(row => '' + + `' + + `${escapeHtml(row.name)}${escapeHtml(row.value)}`).join(''); + return '
${escapeHtml(header)}${items}
`; +}; + +export const homeChartTooltipOptions = { + trigger: 'axis' as const, + confine: true, + axisPointer: {type: 'line' as const, lineStyle: {color: 'rgba(0, 0, 0, 0.38)', type: 'dashed' as const, width: 1}}, + position: (point: number[], _params: unknown, _dom: unknown, _rect: unknown, size: {contentSize: number[]; viewSize: number[]}) => + [point[0] > size.viewSize[0] * 0.6 ? point[0] - 10 - size.contentSize[0] : point[0] + 10, 0], + padding: [6, 8], + backgroundColor: 'rgba(0, 0, 0, 0.87)', + borderWidth: 0, + extraCssText: 'border-radius: 6px; box-shadow: 0 2px 8px rgba(0, 0, 0, 0.16); min-width: 96px; box-sizing: border-box;' +}; + +export const homeChartHoverSymbol = (color: string) => ({ + symbol: 'circle', + symbolSize: 8, + itemStyle: {color, borderColor: '#fff', borderWidth: 2}, + emphasis: {scale: false} +}); diff --git a/ui-ngx/src/app/modules/home/pages/home-page/sys-admin-home.service.ts b/ui-ngx/src/app/modules/home/pages/home-page/sys-admin-home.service.ts index ac793a1bab..26a328d66b 100644 --- a/ui-ngx/src/app/modules/home/pages/home-page/sys-admin-home.service.ts +++ b/ui-ngx/src/app/modules/home/pages/home-page/sys-admin-home.service.ts @@ -1,16 +1,32 @@ // SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. // SPDX-License-Identifier: BUSL-1.1 -import { inject, Injectable } from '@angular/core'; +import { inject, Injectable, signal } from '@angular/core'; import { Observable, of } from 'rxjs'; import { catchError, shareReplay } from 'rxjs/operators'; import { AdminService } from '@core/http/admin.service'; -import { FeaturesInfo } from '@shared/models/settings.models'; +import { FeaturesInfo, UpdateMessage } from '@shared/models/settings.models'; + +let hiddenRelease: string | null = null; @Injectable() export class SysAdminHomeService { - readonly featuresInfo$: Observable = inject(AdminService).getFeaturesInfo({ignoreErrors: true, ignoreLoading: true}).pipe( + private adminService = inject(AdminService); + + readonly featuresInfo$: Observable = this.adminService.getFeaturesInfo({ignoreErrors: true, ignoreLoading: true}).pipe( + catchError(() => of(null)), + shareReplay(1) + ); + + readonly update$: Observable = this.adminService.checkUpdates({ignoreErrors: true, ignoreLoading: true}).pipe( catchError(() => of(null)), shareReplay(1) ); + + readonly hiddenRelease = signal(hiddenRelease); + + setHiddenRelease(version: string | null): void { + hiddenRelease = version; + this.hiddenRelease.set(version); + } } diff --git a/ui-ngx/src/assets/locale/locale.constant-en_US.json b/ui-ngx/src/assets/locale/locale.constant-en_US.json index bb562e8e10..604a4e778d 100644 --- a/ui-ngx/src/assets/locale/locale.constant-en_US.json +++ b/ui-ngx/src/assets/locale/locale.constant-en_US.json @@ -8851,6 +8851,23 @@ "configured": "configured", "not-configured": "not configured" }, + "system": { + "last-hour": "Last hour", + "services": "{ count, plural, =1 {1 service} other {# services} }", + "version": "ThingsBoard {{version}}", + "release-notes": "Release notes of {{version}}", + "available": "{{version}} available", + "show-update": "Show the update again", + "cores": "{ count, plural, =1 {1 core} other {# cores} }", + "gb": "{{value}} GB", + "at": "{{name}} at {{value}}%", + "at-on": "{{name}} at {{value}}% on {{services}}", + "and": " and ", + "now": "now", + "chart": "CPU, RAM and disk over the last hour", + "service-id": "Service id", + "service-type": "Service type" + }, "list": { "show-more": "Show more", "show-all": "Show all",