1
0
mirror of https://github.com/lensapp/lens.git synced 2025-05-20 05:10:56 +00:00

Moving pod logs into Dock

Signed-off-by: Alex Andreev <alex.andreev.email@gmail.com>
This commit is contained in:
Alex Andreev 2020-10-06 11:09:05 +03:00
parent 87061cee9e
commit 3095ed4f7c
11 changed files with 375 additions and 11 deletions

View File

@ -47,6 +47,7 @@ export interface IPodLogsQuery {
tailLines?: number;
timestamps?: boolean;
sinceTime?: string; // Date.toISOString()-format
follow?: boolean;
}
export enum PodStatus {

View File

@ -12,6 +12,7 @@ import { cssNames, prevDefault } from "../../utils";
import { terminalStore, createTerminalTab } from "../dock/terminal.store";
import { _i18n } from "../../i18n";
import { hideDetails } from "../../navigation";
import { createPodLogsTab } from "../dock/pod-logs.store";
interface Props extends KubeObjectMenuProps<Pod> {
}
@ -42,7 +43,10 @@ export class PodMenu extends React.Component<Props> {
}
showLogs(container: IPodContainer) {
PodLogsDialog.open(this.props.object, container);
createPodLogsTab({
pod: this.props.object,
container
});
}
renderShellMenu() {

View File

@ -11,6 +11,7 @@ export enum TabKind {
EDIT_RESOURCE = "edit-resource",
INSTALL_CHART = "install-chart",
UPGRADE_CHART = "upgrade-chart",
POD_LOGS = "pod-logs",
}
export interface IDockTab {

View File

@ -22,6 +22,8 @@ import { createResourceTab, isCreateResourceTab } from "./create-resource.store"
import { isEditResourceTab } from "./edit-resource.store";
import { isInstallChartTab } from "./install-chart.store";
import { isUpgradeChartTab } from "./upgrade-chart.store";
import { PodLogs } from "./pod-logs";
import { isPodLogsTab } from "./pod-logs.store";
interface Props {
className?: string;
@ -59,6 +61,9 @@ export class Dock extends React.Component<Props> {
if (isInstallChartTab(tab) || isUpgradeChartTab(tab)) {
return <DockTab value={tab} icon={<Icon svg="install" />} />
}
if (isPodLogsTab(tab)) {
return <DockTab value={tab} icon="subject" />
}
}
renderTabContent() {
@ -71,6 +76,7 @@ export class Dock extends React.Component<Props> {
{isInstallChartTab(tab) && <InstallChart tab={tab} />}
{isUpgradeChartTab(tab) && <UpgradeChart tab={tab} />}
{isTerminalTab(tab) && <TerminalWindow tab={tab} />}
{isPodLogsTab(tab) && <PodLogs tab={tab} />}
</div>
)
}

View File

@ -13,7 +13,7 @@ import { Notifications } from "../notifications";
interface Props extends OptionalProps {
tabId: TabId;
submit: () => Promise<ReactNode | string>;
submit?: () => Promise<ReactNode | string>;
}
interface OptionalProps {
@ -23,6 +23,7 @@ interface OptionalProps {
submitLabel?: ReactNode;
submittingMessage?: ReactNode;
disableSubmit?: boolean;
showSubmit?: boolean;
showSubmitClose?: boolean;
showInlineInfo?: boolean;
showNotifications?: boolean;
@ -33,6 +34,7 @@ export class InfoPanel extends Component<Props> {
static defaultProps: OptionalProps = {
submitLabel: <Trans>Submit</Trans>,
submittingMessage: <Trans>Submitting..</Trans>,
showSubmit: true,
showSubmitClose: true,
showInlineInfo: true,
showNotifications: true,
@ -87,7 +89,7 @@ export class InfoPanel extends Component<Props> {
}
render() {
const { className, controls, submitLabel, disableSubmit, error, submittingMessage, showSubmitClose } = this.props;
const { className, controls, submitLabel, disableSubmit, error, submittingMessage, showSubmit, showSubmitClose } = this.props;
const { submit, close, submitAndClose, waiting } = this;
const isDisabled = !!(disableSubmit || waiting || error);
return (
@ -99,14 +101,16 @@ export class InfoPanel extends Component<Props> {
{waiting ? <><Spinner /> {submittingMessage}</> : this.renderErrorIcon()}
</div>
<Button plain label={<Trans>Cancel</Trans>} onClick={close} />
<Button
active
outlined={showSubmitClose}
primary={!showSubmitClose}// one button always should be primary (blue)
label={submitLabel}
onClick={submit}
disabled={isDisabled}
/>
{showSubmit && (
<Button
active
outlined={showSubmitClose}
primary={!showSubmitClose}// one button always should be primary (blue)
label={submitLabel}
onClick={submit}
disabled={isDisabled}
/>
)}
{showSubmitClose && (
<Button
primary active

View File

@ -0,0 +1,42 @@
.PodLogs {
.logs {
@include custom-scrollbar;
// fix for `this.logsElement.scrollTop = this.logsElement.scrollHeight`
// `overflow: overlay` don't allow scroll to the last line
overflow: auto;
color: $textColorAccent;
background: $logsBackground;
line-height: var(--log-line-height);
border-radius: 2px;
padding: $padding * 2;
font-family: $font-monospace;
font-size: smaller;
white-space: pre;
> div {
// Provides font better readability on large screens
-webkit-font-smoothing: subpixel-antialiased;
}
}
.new-logs-sep {
position: relative;
display: block;
height: 0;
border-top: 1px solid $primary;
margin: $margin * 2;
&:after {
position: absolute;
left: 50%;
transform: translate(-50%, -50%);
content: 'new';
background: $primary;
color: white;
padding: $padding / 3 $padding /2;
border-radius: $radius;
}
}
}

View File

@ -0,0 +1,29 @@
import { Pod, IPodContainer } from "../../api/endpoints";
import { autobind } from "../../utils";
import { DockTabStore } from "./dock-tab.store";
import { dockStore, IDockTab, TabKind } from "./dock.store";
export interface IPodLogsData {
pod: Pod;
container?: IPodContainer;
}
@autobind()
export class PodLogsStore extends DockTabStore<IPodLogsData> {
}
export const podLogsStore = new PodLogsStore();
export function createPodLogsTab(data: IPodLogsData, tabParams: Partial<IDockTab> = {}) {
const tab = dockStore.createTab({
kind: TabKind.POD_LOGS,
title: "Logs",
...tabParams
});
podLogsStore.setData(tab.id, data);
return tab;
}
export function isPodLogsTab(tab: IDockTab) {
return tab && tab.kind === TabKind.POD_LOGS;
}

View File

@ -0,0 +1,272 @@
import "./pod-logs.scss";
import React from "react";
import AnsiUp from "ansi_up";
import DOMPurify from "dompurify";
import { t, Trans } from "@lingui/macro";
import { observable } from "mobx";
import { observer } from "mobx-react";
import { _i18n } from "../../i18n";
import { IPodContainer, podsApi } from "../../api/endpoints";
import { cssNames, downloadFile, interval } from "../../utils";
import { Icon } from "../icon";
import { Select, SelectOption } from "../select";
import { Spinner } from "../spinner";
import { IDockTab } from "./dock.store";
import { InfoPanel } from "./info-panel";
import { podLogsStore } from "./pod-logs.store";
interface Props {
className?: string
tab: IDockTab
}
@observer
export class PodLogs extends React.Component<Props> {
@observable logs = ""; // latest downloaded logs for pod
@observable newLogs = ""; // new logs since dialog is open
@observable ready = false;
@observable selectedContainer: IPodContainer;
@observable showTimestamps = false;
@observable tailLines = 1000;
private logsElement: HTMLDivElement;
private refresher = interval(5, () => this.load());
private containers: IPodContainer[] = []
private initContainers: IPodContainer[] = []
private lastLineIsShown = true; // used for proper auto-scroll content after refresh
private colorConverter = new AnsiUp();
private lineOptions = [
{ label: _i18n._(t`All logs`), value: Number.MAX_SAFE_INTEGER },
{ label: 1000, value: 1000 },
{ label: 10000, value: 10000 },
{ label: 100000, value: 100000 },
]
componentDidMount() {
this.onOpen();
}
componentDidUpdate() {
// scroll logs only when it's already in the end,
// otherwise it can interrupt reading by jumping after loading new logs update
if (this.logsElement && this.lastLineIsShown) {
this.logsElement.scrollTop = this.logsElement.scrollHeight;
}
}
get tabData() {
return podLogsStore.getData(this.props.tab.id);
}
onOpen = async () => {
const { pod, container } = this.tabData;
this.containers = pod.getContainers();
this.initContainers = pod.getInitContainers();
await this.load();
this.refresher.start();
}
load = async () => {
const data = this.tabData;
if (!data) return;
try {
// if logs already loaded, check the latest timestamp for getting updates only from this point
const logsTimestamps = this.getTimestamps(this.newLogs || this.logs);
let lastLogDate = new Date(0)
if (logsTimestamps) {
lastLogDate = new Date(logsTimestamps.slice(-1)[0]);
lastLogDate.setSeconds(lastLogDate.getSeconds() + 1); // avoid duplicates from last second
}
const namespace = data.pod.getNs();
const name = data.pod.getName();
const logs = await podsApi.getLogs({ namespace, name }, {
timestamps: true,
container: this.selectedContainer?.name,
tailLines: this.tailLines ? this.tailLines : undefined,
sinceTime: lastLogDate.toISOString(),
});
if (!this.logs) {
this.logs = logs;
}
else if (logs) {
this.newLogs = `${this.newLogs}\n${logs}`.trim();
}
} catch (error) {
this.logs = [
_i18n._(t`Failed to load logs: ${error.message}`),
_i18n._(t`Reason: ${error.reason} (${error.code})`),
].join("\n")
}
this.ready = true;
}
reload = async () => {
this.logs = "";
this.newLogs = "";
this.lastLineIsShown = true;
this.ready = false;
this.refresher.stop();
await this.load();
this.refresher.start();
}
getLogs() {
const { logs, newLogs, showTimestamps } = this;
return {
logs: showTimestamps ? logs : this.removeTimestamps(logs),
newLogs: showTimestamps ? newLogs : this.removeTimestamps(newLogs),
}
}
getTimestamps(logs: string) {
return logs.match(/^\d+\S+/gm);
}
removeTimestamps(logs: string) {
return logs.replace(/^\d+.*?\s/gm, "");
}
toggleTimestamps = () => {
this.showTimestamps = !this.showTimestamps;
}
onScroll = (evt: React.UIEvent<HTMLDivElement>) => {
const logsArea = evt.currentTarget;
const { scrollHeight, clientHeight, scrollTop } = logsArea;
this.lastLineIsShown = clientHeight + scrollTop === scrollHeight;
};
downloadLogs = () => {
const { logs, newLogs } = this.getLogs();
const podName = this.tabData.pod.getName();
const fileName = this.selectedContainer ? this.selectedContainer.name : podName;
const fileContents = logs + newLogs;
downloadFile(fileName + ".log", fileContents, "text/plain");
}
onContainerChange = (option: SelectOption) => {
this.selectedContainer = this.containers
.concat(this.initContainers)
.find(container => container.name === option.value);
this.reload();
}
onTailLineChange = (option: SelectOption) => {
this.tailLines = option.value;
this.reload();
}
get containerSelectOptions() {
return [
{
label: _i18n._(t`All Containers`),
},
{
label: _i18n._(t`Containers`),
options: this.containers.map(container => {
return { value: container.name }
}),
},
{
label: _i18n._(t`Init Containers`),
options: this.initContainers.map(container => {
return { value: container.name }
}),
}
];
}
formatOptionLabel = (option: SelectOption) => {
const { value, label } = option;
if (!value) return _i18n._(t`All Containers`);
return label || <><Icon small material="view_carousel"/> {value}</>;
}
renderControls() {
if (!this.ready) return null;
const timestamps = this.getTimestamps(this.logs + this.newLogs);
return (
<div className="controls flex gaps align-center">
<span><Trans>Container</Trans></span>
<Select
options={this.containerSelectOptions}
value={{ value: this.selectedContainer?.name }}
formatOptionLabel={this.formatOptionLabel}
onChange={this.onContainerChange}
autoConvertOptions={false}
/>
<span><Trans>Lines</Trans></span>
<Select
value={this.tailLines}
options={this.lineOptions}
onChange={this.onTailLineChange}
/>
<div className="time-range">
{timestamps && (
<>
<Trans>From</Trans>{" "}
<b>{new Date(timestamps[0]).toLocaleString()}</b>{" "}
<Trans>to</Trans>{" "}
<b>{new Date(timestamps[timestamps.length - 1]).toLocaleString()}</b>
</>
)}
</div>
<div className="flex gaps">
<Icon
material="av_timer"
onClick={this.toggleTimestamps}
className={cssNames("timestamps-icon", { active: this.showTimestamps })}
tooltip={(this.showTimestamps ? _i18n._(t`Hide`) : _i18n._(t`Show`)) + " " + _i18n._(t`timestamps`)}
/>
<Icon
material="get_app"
onClick={this.downloadLogs}
tooltip={_i18n._(t`Save`)}
/>
</div>
</div>
);
}
renderLogs() {
if (!this.ready) {
return <Spinner center/>;
}
const { logs, newLogs } = this.getLogs();
if (!logs && !newLogs) {
return (
<div className="flex align-center justify-center">
<Trans>There are no logs available for container.</Trans>
</div>
);
}
return (
<>
<div dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(this.colorConverter.ansi_to_html(logs))}} />
{newLogs && (
<>
<p className="new-logs-sep" title={_i18n._(t`New logs since opening the dialog`)}/>
<div dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(this.colorConverter.ansi_to_html(newLogs))}} />
</>
)}
</>
);
}
render() {
const { className } = this.props;
return (
<div className={cssNames("PodLogs flex column", className)}>
<InfoPanel
tabId={this.props.tab.id}
controls={this.renderControls()}
showSubmitClose={false}
showSubmit={false}
/>
<div className="logs" onScroll={this.onScroll} ref={e => this.logsElement = e}>
{this.renderLogs()}
</div>
</div>
);
}
}

View File

@ -60,6 +60,7 @@
"dockHeadBackground": "#2e3136",
"dockInfoBackground": "#1e2125",
"dockInfoBorderColor": "#303136",
"logsBackground": "#000000",
"terminalBackground": "#000000",
"terminalForeground": "#ffffff",
"terminalCursor": "#ffffff",

View File

@ -61,6 +61,7 @@
"dockHeadBackground": "#e8e8e8",
"dockInfoBackground": "#e8e8e8",
"dockInfoBorderColor": "#c9cfd3",
"logsBackground": "#ffffff",
"terminalBackground": "#ffffff",
"terminalForeground": "#2d2d2d",
"terminalCursor": "#2d2d2d",

View File

@ -91,6 +91,9 @@ $terminalBrightMagenta: var(--terminalBrightMagenta);
$terminalBrightCyan: var(--terminalBrightCyan);
$terminalBrightWhite: var(--terminalBrightWhite);
// Logs
$logsBackground: var(--logsBackground);
// Dialogs
$dialogTextColor: var(--dialogTextColor);
$dialogBackground: var(--dialogBackground);