1
0
mirror of https://github.com/lensapp/lens.git synced 2024-09-20 22:07:31 +03:00

Merge branch 'master' into extensions-api

Signed-off-by: Jari Kolehmainen <jari.kolehmainen@gmail.com>
This commit is contained in:
Jari Kolehmainen 2020-10-27 09:24:27 +02:00
commit 4e8bdace79
13 changed files with 409 additions and 189 deletions

View File

@ -15,7 +15,6 @@ export class PodLogsMenu extends React.Component<Props> {
selectedContainer: container, selectedContainer: container,
showTimestamps: false, showTimestamps: false,
previous: false, previous: false,
tailLines: 1000
}); });
} }

View File

@ -166,8 +166,8 @@ describe("Lens integration tests", () => {
pages: [{ pages: [{
name: "Cluster", name: "Cluster",
href: "cluster", href: "cluster",
expectedSelector: "div.ClusterNoMetrics p", expectedSelector: "div.Cluster div.label",
expectedText: "Metrics are not available due" expectedText: "Master"
}] }]
}, },
{ {

View File

@ -37,12 +37,12 @@ export class HelmRepoManager extends Singleton {
async loadAvailableRepos(): Promise<HelmRepo[]> { async loadAvailableRepos(): Promise<HelmRepo[]> {
const res = await customRequestPromise({ const res = await customRequestPromise({
uri: "https://hub.helm.sh/assets/js/repos.json", uri: "https://github.com/lensapp/artifact-hub-repositories/releases/download/latest/repositories.json",
json: true, json: true,
resolveWithFullResponse: true, resolveWithFullResponse: true,
timeout: 10000, timeout: 10000,
}); });
return orderBy<HelmRepo>(res.body.data, repo => repo.name); return orderBy<HelmRepo>(res.body, repo => repo.name);
} }
async init() { async init() {

View File

@ -141,7 +141,7 @@ export class HelmRelease implements ItemObject {
chart: string chart: string
status: string status: string
updated: string updated: string
revision: number revision: string
getId() { getId() {
return this.namespace + this.name; return this.namespace + this.name;
@ -165,7 +165,7 @@ export class HelmRelease implements ItemObject {
} }
getRevision() { getRevision() {
return this.revision; return parseInt(this.revision, 10);
} }
getStatus() { getStatus() {

View File

@ -109,6 +109,14 @@ export class Ingress extends KubeObject {
} }
return ports.join(", ") return ports.join(", ")
} }
getLoadBalancers() {
const { status: { loadBalancer = { ingress: [] } } } = this;
return (loadBalancer.ingress ?? []).map(address => (
address.hostname || address.ip
))
}
} }
export const ingressApi = new IngressApi({ export const ingressApi = new IngressApi({

View File

@ -152,7 +152,16 @@ export interface IPodContainerStatus {
reason: string; reason: string;
}; };
}; };
lastState: {}; lastState: {
[index: string]: object;
terminated?: {
startedAt: string;
finishedAt: string;
exitCode: number;
reason: string;
containerID: string;
};
};
ready: boolean; ready: boolean;
restartCount: number; restartCount: number;
image: string; image: string;

View File

@ -39,12 +39,14 @@ export class Ingresses extends React.Component<Props> {
renderTableHeader={[ renderTableHeader={[
{ title: <Trans>Name</Trans>, className: "name", sortBy: sortBy.name }, { title: <Trans>Name</Trans>, className: "name", sortBy: sortBy.name },
{ title: <Trans>Namespace</Trans>, className: "namespace", sortBy: sortBy.namespace }, { title: <Trans>Namespace</Trans>, className: "namespace", sortBy: sortBy.namespace },
{ title: <Trans>LoadBalancers</Trans>, className: "loadbalancers" },
{ title: <Trans>Rules</Trans>, className: "rules" }, { title: <Trans>Rules</Trans>, className: "rules" },
{ title: <Trans>Age</Trans>, className: "age", sortBy: sortBy.age }, { title: <Trans>Age</Trans>, className: "age", sortBy: sortBy.age },
]} ]}
renderTableContents={(ingress: Ingress) => [ renderTableContents={(ingress: Ingress) => [
ingress.getName(), ingress.getName(),
ingress.getNs(), ingress.getNs(),
ingress.getLoadBalancers().map(lb => <p key={lb}>{lb}</p>),
ingress.getRoutes().map(route => <p key={route}>{route}</p>), ingress.getRoutes().map(route => <p key={route}>{route}</p>),
ingress.getAge(), ingress.getAge(),
]} ]}

View File

@ -1,7 +1,6 @@
import "./pod-container-env.scss"; import "./pod-container-env.scss";
import React, { useEffect, useState } from "react"; import React, { useEffect, useState } from "react";
import flatten from "lodash/flatten";
import { observer } from "mobx-react"; import { observer } from "mobx-react";
import { Trans } from "@lingui/macro"; import { Trans } from "@lingui/macro";
import { IPodContainer, Secret } from "../../api/endpoints"; import { IPodContainer, Secret } from "../../api/endpoints";
@ -11,6 +10,7 @@ import { secretsStore } from "../+config-secrets/secrets.store";
import { configMapsStore } from "../+config-maps/config-maps.store"; import { configMapsStore } from "../+config-maps/config-maps.store";
import { Icon } from "../icon"; import { Icon } from "../icon";
import { base64, cssNames } from "../../utils"; import { base64, cssNames } from "../../utils";
import _ from "lodash";
interface Props { interface Props {
container: IPodContainer; container: IPodContainer;
@ -40,7 +40,9 @@ export const ContainerEnvironment = observer((props: Props) => {
) )
const renderEnv = () => { const renderEnv = () => {
return env.map(variable => { const orderedEnv = _.sortBy(env, 'name');
return orderedEnv.map(variable => {
const { name, value, valueFrom } = variable const { name, value, valueFrom } = variable
let secretValue = null let secretValue = null
@ -89,7 +91,7 @@ export const ContainerEnvironment = observer((props: Props) => {
</div> </div>
)) ))
}) })
return flatten(envVars) return _.flatten(envVars)
} }
return ( return (

View File

@ -2,7 +2,7 @@ import "./pod-details-container.scss"
import React from "react"; import React from "react";
import { t, Trans } from "@lingui/macro"; import { t, Trans } from "@lingui/macro";
import { IPodContainer, Pod } from "../../api/endpoints"; import { IPodContainer, IPodContainerStatus, Pod } from "../../api/endpoints";
import { DrawerItem } from "../drawer"; import { DrawerItem } from "../drawer";
import { cssNames } from "../../utils"; import { cssNames } from "../../utils";
import { StatusBrick } from "../status-brick"; import { StatusBrick } from "../status-brick";
@ -21,12 +21,37 @@ interface Props {
} }
export class PodDetailsContainer extends React.Component<Props> { export class PodDetailsContainer extends React.Component<Props> {
renderStatus(state: string, status: IPodContainerStatus) {
const ready = status ? status.ready : ""
return (
<span className={cssNames("status", state)}>
{state}{ready ? `, ${_i18n._(t`ready`)}` : ""}
{state === 'terminated' ? ` - ${status.state.terminated.reason} (${_i18n._(t`exit code`)}: ${status.state.terminated.exitCode})` : ''}
</span>
);
}
renderLastState(lastState: string, status: IPodContainerStatus) {
if (lastState === 'terminated') {
return (
<span>
{lastState}<br/>
{_i18n._(t`Reason`)}: {status.lastState.terminated.reason} - {_i18n._(t`exit code`)}: {status.lastState.terminated.exitCode}<br/>
{_i18n._(t`Started at`)}: {status.lastState.terminated.startedAt}<br/>
{_i18n._(t`Finished at`)}: {status.lastState.terminated.finishedAt}<br/>
</span>
)
}
}
render() { render() {
const { pod, container, metrics } = this.props const { pod, container, metrics } = this.props
if (!pod || !container) return null if (!pod || !container) return null
const { name, image, imagePullPolicy, ports, volumeMounts, command, args } = container const { name, image, imagePullPolicy, ports, volumeMounts, command, args } = container
const status = pod.getContainerStatuses().find(status => status.name === container.name) const status = pod.getContainerStatuses().find(status => status.name === container.name)
const state = status ? Object.keys(status.state)[0] : "" const state = status ? Object.keys(status.state)[0] : ""
const lastState = status ? Object.keys(status.lastState)[0] : ""
const ready = status ? status.ready : "" const ready = status ? status.ready : ""
const liveness = pod.getLivenessProbe(container) const liveness = pod.getLivenessProbe(container)
const readiness = pod.getReadinessProbe(container) const readiness = pod.getReadinessProbe(container)
@ -48,10 +73,12 @@ export class PodDetailsContainer extends React.Component<Props> {
} }
{status && {status &&
<DrawerItem name={<Trans>Status</Trans>}> <DrawerItem name={<Trans>Status</Trans>}>
<span className={cssNames("status", state)}> {this.renderStatus(state, status)}
{state}{ready ? `, ${_i18n._(t`ready`)}` : ""} </DrawerItem>
{state === 'terminated' ? ` - ${status.state.terminated.reason} (${_i18n._(t`exit code`)}: ${status.state.terminated.exitCode})` : ''} }
</span> {lastState &&
<DrawerItem name={<Trans>Last Status</Trans>}>
{this.renderLastState(lastState, status)}
</DrawerItem> </DrawerItem>
} }
<DrawerItem name={<Trans>Image</Trans>}> <DrawerItem name={<Trans>Image</Trans>}>

View File

@ -0,0 +1,116 @@
import React from "react";
import { observer } from "mobx-react";
import { IPodLogsData, podLogsStore } from "./pod-logs.store";
import { t, Trans } from "@lingui/macro";
import { Select, SelectOption } from "../select";
import { Badge } from "../badge";
import { Icon } from "../icon";
import { _i18n } from "../../i18n";
import { cssNames, downloadFile } from "../../utils";
import { Pod } from "../../api/endpoints";
interface Props {
ready: boolean
tabId: string
tabData: IPodLogsData
logs: string[][]
save: (data: Partial<IPodLogsData>) => void
reload: () => void
}
export const PodLogControls = observer((props: Props) => {
if (!props.ready) return null;
const { tabData, tabId, save, reload, logs } = props;
const { selectedContainer, showTimestamps, previous } = tabData;
const since = podLogsStore.getTimestamps(podLogsStore.logs.get(tabId)[0]);
const pod = new Pod(tabData.pod);
const toggleTimestamps = () => {
save({ showTimestamps: !showTimestamps });
}
const togglePrevious = () => {
save({ previous: !previous });
reload();
}
const downloadLogs = () => {
const fileName = selectedContainer ? selectedContainer.name : pod.getName();
const [oldLogs, newLogs] = logs;
downloadFile(fileName + ".log", [...oldLogs, ...newLogs].join("\n"), "text/plain");
}
const onContainerChange = (option: SelectOption) => {
const { containers, initContainers } = tabData;
save({
selectedContainer: containers
.concat(initContainers)
.find(container => container.name === option.value)
})
reload();
}
const containerSelectOptions = () => {
const { containers, initContainers } = tabData;
return [
{
label: _i18n._(t`Containers`),
options: containers.map(container => {
return { value: container.name }
}),
},
{
label: _i18n._(t`Init Containers`),
options: initContainers.map(container => {
return { value: container.name }
}),
}
];
}
const formatOptionLabel = (option: SelectOption) => {
const { value, label } = option;
return label || <><Icon small material="view_carousel"/> {value}</>;
}
return (
<div className="PodLogControls flex gaps align-center">
<span><Trans>Pod</Trans>:</span> <Badge label={pod.getName()}/>
<span><Trans>Namespace</Trans>:</span> <Badge label={pod.getNs()}/>
<span><Trans>Container</Trans></span>
<Select
options={containerSelectOptions()}
value={{ value: selectedContainer.name }}
formatOptionLabel={formatOptionLabel}
onChange={onContainerChange}
autoConvertOptions={false}
/>
<div className="time-range">
{since && (
<>
<Trans>Since</Trans>{" "}
<b>{new Date(since[0]).toLocaleString()}</b>
</>
)}
</div>
<div className="flex gaps">
<Icon
material="av_timer"
onClick={toggleTimestamps}
className={cssNames("timestamps-icon", { active: showTimestamps })}
tooltip={(showTimestamps ? _i18n._(t`Hide`) : _i18n._(t`Show`)) + " " + _i18n._(t`timestamps`)}
/>
<Icon
material="history"
onClick={togglePrevious}
className={cssNames("undo-icon", { active: previous })}
tooltip={(previous ? _i18n._(t`Show current logs`) : _i18n._(t`Show previous terminated container logs`))}
/>
<Icon
material="get_app"
onClick={downloadLogs}
tooltip={_i18n._(t`Save`)}
/>
</div>
</div>
);
});

View File

@ -27,7 +27,7 @@
display: block; display: block;
height: 0; height: 0;
border-top: 1px solid $primary; border-top: 1px solid $primary;
margin: $margin * 2; margin: $margin * 2 0;
&:after { &:after {
position: absolute; position: absolute;
@ -40,4 +40,21 @@
border-radius: $radius; border-radius: $radius;
} }
} }
.jump-to-bottom {
position: absolute;
right: 30px;
padding: $unit / 2 $unit * 1.5;
border-radius: $unit * 2;
opacity: 0;
transition: opacity 0.2s;
&.active {
opacity: 1;
}
.Icon {
--size: $unit * 2;
}
}
} }

View File

@ -1,10 +1,11 @@
import { autorun, observable } from "mobx"; import { autorun, computed, observable, reaction } from "mobx";
import { Pod, IPodContainer, podsApi } from "../../api/endpoints"; import { Pod, IPodContainer, podsApi, IPodLogsQuery } from "../../api/endpoints";
import { autobind, interval } from "../../utils"; import { autobind, interval } from "../../utils";
import { DockTabStore } from "./dock-tab.store"; import { DockTabStore } from "./dock-tab.store";
import { dockStore, IDockTab, TabKind } from "./dock.store"; import { dockStore, IDockTab, TabKind } from "./dock.store";
import { t } from "@lingui/macro"; import { t } from "@lingui/macro";
import { _i18n } from "../../i18n"; import { _i18n } from "../../i18n";
import { isDevelopment } from "../../../common/vars";
export interface IPodLogsData { export interface IPodLogsData {
pod: Pod; pod: Pod;
@ -12,22 +13,25 @@ export interface IPodLogsData {
containers: IPodContainer[] containers: IPodContainer[]
initContainers: IPodContainer[] initContainers: IPodContainer[]
showTimestamps: boolean showTimestamps: boolean
tailLines: number
previous: boolean previous: boolean
} }
type TabId = string; type TabId = string;
type PodLogLine = string;
interface PodLogs { // Number for log lines to load
oldLogs?: string export const logRange = isDevelopment ? 100 : 1000;
newLogs?: string
}
@autobind() @autobind()
export class PodLogsStore extends DockTabStore<IPodLogsData> { export class PodLogsStore extends DockTabStore<IPodLogsData> {
private refresher = interval(10, () => this.load(dockStore.selectedTabId)); private refresher = interval(10, () => {
const id = dockStore.selectedTabId
if (!this.logs.get(id)) return
this.loadMore(id)
});
@observable logs = observable.map<TabId, PodLogs>(); @observable logs = observable.map<TabId, PodLogLine[]>();
@observable newLogSince = observable.map<TabId, string>(); // Timestamp after which all logs are considered to be new
constructor() { constructor() {
super({ super({
@ -41,49 +45,110 @@ export class PodLogsStore extends DockTabStore<IPodLogsData> {
this.refresher.stop(); this.refresher.stop();
} }
}, { delay: 500 }); }, { delay: 500 });
reaction(() => this.logs.get(dockStore.selectedTabId), () => {
this.setNewLogSince(dockStore.selectedTabId);
})
} }
/**
* Function prepares tailLines param for passing to API request
* Each time it increasing it's number, caused to fetch more logs.
* Also, it handles loading errors, rewriting whole logs with error
* messages
* @param tabId
*/
load = async (tabId: TabId) => { load = async (tabId: TabId) => {
if (!this.logs.has(tabId)) {
this.logs.set(tabId, { oldLogs: "", newLogs: "" })
}
const data = this.getData(tabId);
const { oldLogs, newLogs } = this.logs.get(tabId);
const { selectedContainer, tailLines, previous } = data;
const pod = new Pod(data.pod);
try { try {
// if logs already loaded, check the latest timestamp for getting updates only from this point const logs = await this.loadLogs(tabId, {
const logsTimestamps = this.getTimestamps(newLogs || oldLogs); tailLines: this.lines + logRange
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 = pod.getNs();
const name = pod.getName();
const loadedLogs = await podsApi.getLogs({ namespace, name }, {
sinceTime: lastLogDate.toISOString(),
timestamps: true, // Always setting timestampt to separate old logs from new ones
container: selectedContainer.name,
tailLines,
previous
}); });
if (!oldLogs) { this.refresher.start();
this.logs.set(tabId, { oldLogs: loadedLogs, newLogs }); this.logs.set(tabId, logs);
} else {
this.logs.set(tabId, { oldLogs, newLogs: loadedLogs });
}
} catch ({error}) { } catch ({error}) {
this.logs.set(tabId, { const message = [
oldLogs: [ _i18n._(t`Failed to load logs: ${error.message}`),
_i18n._(t`Failed to load logs: ${error.message}`), _i18n._(t`Reason: ${error.reason} (${error.code})`)
_i18n._(t`Reason: ${error.reason} (${error.code})`) ];
].join("\n"), this.refresher.stop();
newLogs this.logs.set(tabId, message);
});
} }
} }
/**
* Function is used to refreser/stream-like requests.
* It changes 'sinceTime' param each time allowing to fetch logs
* starting from last line recieved.
* @param tabId
*/
loadMore = async (tabId: TabId) => {
const oldLogs = this.logs.get(tabId);
const logs = await this.loadLogs(tabId, {
sinceTime: this.getLastSinceTime(tabId)
});
// Add newly received logs to bottom
this.logs.set(tabId, [...oldLogs, ...logs]);
}
/**
* Main logs loading function adds necessary data to payload and makes
* an API request
* @param tabId
* @param params request parameters described in IPodLogsQuery interface
* @returns {Promise} A fetch request promise
*/
loadLogs = async (tabId: TabId, params: Partial<IPodLogsQuery>) => {
const data = this.getData(tabId);
const { selectedContainer, previous } = data;
const pod = new Pod(data.pod);
const namespace = pod.getNs();
const name = pod.getName();
return podsApi.getLogs({ namespace, name }, {
...params,
timestamps: true, // Always setting timestampt to separate old logs from new ones
container: selectedContainer.name,
previous
}).then(result => {
const logs = [...result.split("\n")]; // Transform them into array
logs.pop(); // Remove last empty element
return logs;
});
}
/**
* Sets newLogSince separator timestamp to split old logs from new ones
* @param tabId
*/
setNewLogSince(tabId: TabId) {
if (!this.logs.has(tabId) || this.newLogSince.has(tabId)) return;
const timestamp = this.getLastSinceTime(tabId);
this.newLogSince.set(tabId, timestamp.split(".")[0]); // Removing milliseconds from string
}
/**
* Converts logs into a string array
* @returns {number} Length of log lines
*/
@computed
get lines() {
const id = dockStore.selectedTabId;
const logs = this.logs.get(id);
return logs ? logs.length : 0;
}
/**
* It gets timestamps from all logs then returns last one + 1 second
* (this allows to avoid getting the last stamp in the selection)
* @param tabId
*/
getLastSinceTime(tabId: TabId) {
const logs = this.logs.get(tabId);
const timestamps = this.getTimestamps(logs[logs.length - 1]);
const stamp = new Date(timestamps ? timestamps[0] : null);
stamp.setSeconds(stamp.getSeconds() + 1); // avoid duplicates from last second
return stamp.toISOString();
}
getTimestamps(logs: string) { getTimestamps(logs: string) {
return logs.match(/^\d+\S+/gm); return logs.match(/^\d+\S+/gm);
} }
@ -116,7 +181,7 @@ export function createPodLogsTab(data: IPodLogsData, tabParams: Partial<IDockTab
tab = dockStore.createTab({ tab = dockStore.createTab({
id: podId, id: podId,
kind: TabKind.POD_LOGS, kind: TabKind.POD_LOGS,
title: `Logs: ${data.pod.getName()}`, title: data.pod.getName(),
...tabParams ...tabParams
}, false); }, false);
podLogsStore.setData(tab.id, data); podLogsStore.setData(tab.id, data);

View File

@ -6,13 +6,14 @@ import { t, Trans } from "@lingui/macro";
import { computed, observable, reaction } from "mobx"; import { computed, observable, reaction } from "mobx";
import { disposeOnUnmount, observer } from "mobx-react"; import { disposeOnUnmount, observer } from "mobx-react";
import { _i18n } from "../../i18n"; import { _i18n } from "../../i18n";
import { autobind, cssNames, downloadFile } from "../../utils"; import { autobind, cssNames } from "../../utils";
import { Icon } from "../icon"; import { Icon } from "../icon";
import { Select, SelectOption } from "../select";
import { Spinner } from "../spinner"; import { Spinner } from "../spinner";
import { IDockTab } from "./dock.store"; import { IDockTab } from "./dock.store";
import { InfoPanel } from "./info-panel"; import { InfoPanel } from "./info-panel";
import { IPodLogsData, podLogsStore } from "./pod-logs.store"; import { IPodLogsData, logRange, podLogsStore } from "./pod-logs.store";
import { Button } from "../button";
import { PodLogControls } from "./pod-log-controls";
interface Props { interface Props {
className?: string className?: string
@ -22,27 +23,31 @@ interface Props {
@observer @observer
export class PodLogs extends React.Component<Props> { export class PodLogs extends React.Component<Props> {
@observable ready = false; @observable ready = false;
@observable preloading = false; // Indicator for setting Spinner (loader) at the top of the logs
@observable showJumpToBottom = false;
private logsElement: HTMLDivElement; private logsElement: HTMLDivElement;
private lastLineIsShown = true; // used for proper auto-scroll content after refresh private lastLineIsShown = true; // used for proper auto-scroll content after refresh
private colorConverter = new AnsiUp(); 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() { componentDidMount() {
disposeOnUnmount(this, disposeOnUnmount(this, [
reaction(() => this.props.tab.id, async () => { reaction(() => this.props.tab.id, async () => {
if (podLogsStore.logs.has(this.tabId)) { if (podLogsStore.logs.has(this.tabId)) {
this.ready = true; this.ready = true;
return; return;
} }
await this.load(); await this.load();
}, { fireImmediately: true }) }, { fireImmediately: true }),
);
// Check if need to show JumpToBottom if new log amount is less than previous one
reaction(() => podLogsStore.logs.get(this.tabId), () => {
const { tabId } = this;
if (podLogsStore.logs.has(tabId) && podLogsStore.logs.get(tabId).length < logRange) {
this.showJumpToBottom = false;
}
})
]);
} }
componentDidUpdate() { componentDidUpdate() {
@ -78,136 +83,90 @@ export class PodLogs extends React.Component<Props> {
await this.load(); await this.load();
} }
@computed /**
get logs() { * Function loads more logs (usually after user scrolls to top) and sets proper
if (!podLogsStore.logs.has(this.tabId)) return; * scrolling position
const { oldLogs, newLogs } = podLogsStore.logs.get(this.tabId); * @param scrollHeight previous scrollHeight position before adding new lines
const { getData, removeTimestamps } = podLogsStore; */
const { showTimestamps } = getData(this.tabId); loadMore = async (scrollHeight: number) => {
return { if (podLogsStore.lines < logRange) return;
oldLogs: showTimestamps ? oldLogs : removeTimestamps(oldLogs), this.preloading = true;
newLogs: showTimestamps ? newLogs : removeTimestamps(newLogs) await podLogsStore.load(this.tabId).then(() => this.preloading = false);
if (this.logsElement.scrollHeight > scrollHeight) {
// Set scroll position back to place where preloading started
this.logsElement.scrollTop = this.logsElement.scrollHeight - scrollHeight - 48;
} }
} }
toggleTimestamps = () => { /**
this.save({ showTimestamps: !this.tabData.showTimestamps }); * Computed prop which returns logs with or without timestamps added to each line and
} * does separation between new and old logs
* @returns {Array} An array with 2 items - [oldLogs, newLogs]
togglePrevious = () => { */
this.save({ previous: !this.tabData.previous }); @computed
this.reload(); get logs() {
if (!podLogsStore.logs.has(this.tabId)) return [];
const logs = podLogsStore.logs.get(this.tabId);
const { getData, removeTimestamps, newLogSince } = podLogsStore;
const { showTimestamps } = getData(this.tabId);
let oldLogs: string[] = logs;
let newLogs: string[] = [];
if (newLogSince.has(this.tabId)) {
// Finding separator timestamp in logs
const index = logs.findIndex(item => item.includes(newLogSince.get(this.tabId)));
if (index !== -1) {
// Splitting logs to old and new ones
oldLogs = logs.slice(0, index);
newLogs = logs.slice(index);
}
}
if (!showTimestamps) {
return [oldLogs, newLogs].map(logs => logs.map(item => removeTimestamps(item)))
}
return [oldLogs, newLogs];
} }
onScroll = (evt: React.UIEvent<HTMLDivElement>) => { onScroll = (evt: React.UIEvent<HTMLDivElement>) => {
const logsArea = evt.currentTarget; const logsArea = evt.currentTarget;
const toBottomOffset = 100 * 16; // 100 lines * 16px (height of each line)
const { scrollHeight, clientHeight, scrollTop } = logsArea; const { scrollHeight, clientHeight, scrollTop } = logsArea;
if (scrollTop === 0) {
this.loadMore(scrollHeight);
}
if (scrollHeight - scrollTop > toBottomOffset) {
this.showJumpToBottom = true;
} else {
this.showJumpToBottom = false;
}
this.lastLineIsShown = clientHeight + scrollTop === scrollHeight; this.lastLineIsShown = clientHeight + scrollTop === scrollHeight;
}; };
downloadLogs = () => { renderJumpToBottom() {
const { oldLogs, newLogs } = this.logs; if (!this.logsElement) return null;
const { pod, selectedContainer } = this.tabData;
const fileName = selectedContainer ? selectedContainer.name : pod.getName();
const fileContents = oldLogs + newLogs;
downloadFile(fileName + ".log", fileContents, "text/plain");
}
onContainerChange = (option: SelectOption) => {
const { containers, initContainers } = this.tabData;
this.save({
selectedContainer: containers
.concat(initContainers)
.find(container => container.name === option.value)
})
this.reload();
}
onTailLineChange = (option: SelectOption) => {
this.save({ tailLines: option.value })
this.reload();
}
get containerSelectOptions() {
const { containers, initContainers } = this.tabData;
return [
{
label: _i18n._(t`Containers`),
options: containers.map(container => {
return { value: container.name }
}),
},
{
label: _i18n._(t`Init Containers`),
options: initContainers.map(container => {
return { value: container.name }
}),
}
];
}
formatOptionLabel = (option: SelectOption) => {
const { value, label } = option;
return label || <><Icon small material="view_carousel"/> {value}</>;
}
renderControls() {
if (!this.ready) return null;
const { selectedContainer, showTimestamps, tailLines, previous } = this.tabData;
const timestamps = podLogsStore.getTimestamps(podLogsStore.logs.get(this.tabId).oldLogs);
return ( return (
<div className="controls flex gaps align-center"> <Button
<span><Trans>Container</Trans></span> primary
<Select className={cssNames("jump-to-bottom flex gaps", {active: this.showJumpToBottom})}
options={this.containerSelectOptions} onClick={evt => {
value={{ value: selectedContainer.name }} evt.currentTarget.blur();
formatOptionLabel={this.formatOptionLabel} this.logsElement.scrollTo({
onChange={this.onContainerChange} top: this.logsElement.scrollHeight,
autoConvertOptions={false} behavior: "auto"
/> });
<span><Trans>Lines</Trans></span> }}
<Select >
value={tailLines} <Trans>Jump to bottom</Trans>
options={this.lineOptions} <Icon material="expand_more" />
onChange={this.onTailLineChange} </Button>
/>
<div className="time-range">
{timestamps && (
<>
<Trans>Since</Trans>{" "}
<b>{new Date(timestamps[0]).toLocaleString()}</b>
</>
)}
</div>
<div className="flex gaps">
<Icon
material="av_timer"
onClick={this.toggleTimestamps}
className={cssNames("timestamps-icon", { active: showTimestamps })}
tooltip={(showTimestamps ? _i18n._(t`Hide`) : _i18n._(t`Show`)) + " " + _i18n._(t`timestamps`)}
/>
<Icon
material="undo"
onClick={this.togglePrevious}
className={cssNames("undo-icon", { active: previous })}
tooltip={(previous ? _i18n._(t`Show current logs`) : _i18n._(t`Show previous terminated container logs`))}
/>
<Icon
material="get_app"
onClick={this.downloadLogs}
tooltip={_i18n._(t`Save`)}
/>
</div>
</div>
); );
} }
renderLogs() { renderLogs() {
const [oldLogs, newLogs] = this.logs;
if (!this.ready) { if (!this.ready) {
return <Spinner center/>; return <Spinner center/>;
} }
const { oldLogs, newLogs } = this.logs; if (!oldLogs.length && !newLogs.length) {
if (!oldLogs && !newLogs) {
return ( return (
<div className="flex align-center justify-center"> <div className="flex align-center justify-center">
<Trans>There are no logs available for container.</Trans> <Trans>There are no logs available for container.</Trans>
@ -216,11 +175,16 @@ export class PodLogs extends React.Component<Props> {
} }
return ( return (
<> <>
<div dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(this.colorConverter.ansi_to_html(oldLogs))}} /> {this.preloading && (
{newLogs && ( <div className="flex justify-center">
<Spinner />
</div>
)}
<div dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(this.colorConverter.ansi_to_html(oldLogs.join("\n"))) }} />
{newLogs.length > 0 && (
<> <>
<p className="new-logs-sep" title={_i18n._(t`New logs since opening the dialog`)}/> <p className="new-logs-sep" title={_i18n._(t`New logs since opening logs tab`)}/>
<div dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(this.colorConverter.ansi_to_html(newLogs))}} /> <div dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(this.colorConverter.ansi_to_html(newLogs.join("\n"))) }} />
</> </>
)} )}
</> </>
@ -229,15 +193,26 @@ export class PodLogs extends React.Component<Props> {
render() { render() {
const { className } = this.props; const { className } = this.props;
const controls = (
<PodLogControls
ready={this.ready}
tabId={this.tabId}
tabData={this.tabData}
logs={this.logs}
save={this.save}
reload={this.reload}
/>
)
return ( return (
<div className={cssNames("PodLogs flex column", className)}> <div className={cssNames("PodLogs flex column", className)}>
<InfoPanel <InfoPanel
tabId={this.props.tab.id} tabId={this.props.tab.id}
controls={this.renderControls()} controls={controls}
showSubmitClose={false} showSubmitClose={false}
showButtons={false} showButtons={false}
/> />
<div className="logs" onScroll={this.onScroll} ref={e => this.logsElement = e}> <div className="logs" onScroll={this.onScroll} ref={e => this.logsElement = e}>
{this.renderJumpToBottom()}
{this.renderLogs()} {this.renderLogs()}
</div> </div>
</div> </div>