import * as React from 'react'; import { useTranslation } from 'react-i18next'; import { saveAs } from 'file-saver'; import { Base64 } from 'js-base64'; import { useIsOnFeatureFlag } from '~/feature-flags/hooks'; import { KUBEARCHIVE_PATH_PREFIX, KUBEARCHIVE_TAIL_LINES } from '~/kubearchive/const'; import { type NormalizedLogSection } from '~/shared/components/virtualized-log-viewer'; import { LineBuffer } from '~/shared/utils/line-buffer'; import { ResourceSource } from '~/types/k8s'; import { commonFetchText } from '../../../../k8s'; import { getK8sResourceURL, getWebsocketSubProtocolAndPathPrefix } from '../../../../k8s/k8s-utils'; import { MessageHandler, WebSocketOptions } from '../../../../k8s/web-socket/types'; import { WebSocketFactory } from '../../../../k8s/web-socket/WebSocketFactory'; import { PodModel } from '../../../../models/pod'; import { TaskRunKind } from '../../../../types'; import { PodKind, ContainerSpec, ContainerStatus } from '../../types'; import { containerToLogSourceStatus, isContainerStepCompleted, LOG_SOURCE_TERMINATED, } from '../utils'; import LogViewer, { type Props as LogViewerProps } from './LogViewer'; const WEB_SOCKET_RETRY_COUNT = 5; const retryWebSocket = ( watchURL: string, wsOpts: WebSocketOptions, onMessage: MessageHandler, onError: () => void, retryCount = 0, ) => { const ws = new WebSocketFactory(watchURL, wsOpts); const handleError = () => { // stop retrying after 5 attempts if (retryCount < WEB_SOCKET_RETRY_COUNT) { setTimeout(() => { retryWebSocket(watchURL, wsOpts, onMessage, onError, retryCount + 1); }, 3000); // retry after 3 seconds } else { onError(); } }; ws.onMessage(onMessage).onError(handleError); return ws; }; type LogsProps = { resource: PodKind; containers: ContainerSpec[]; onScroll?: LogViewerProps['onScroll']; downloadAllLabel?: string; onDownloadAll?: () => Promise; taskRun: TaskRunKind | null; isLoading: boolean; allowAutoScroll: boolean; source: ResourceSource; }; const Logs: React.FC = ({ resource, containers, onScroll, downloadAllLabel, onDownloadAll, taskRun, isLoading, allowAutoScroll, source, }) => { const { t } = useTranslation(); const isKubearchiveEnabled = useIsOnFeatureFlag('kubearchive-logs'); const { metadata = {} } = resource; const { name: resName, namespace: resNamespace } = metadata; const buffersRef = React.useRef(new Map()); const tailedContainersRef = React.useRef(new Set()); const [renderTick, forceRender] = React.useReducer((x: number) => x + 1, 0); const rafRef = React.useRef(0); const [error, setError] = React.useState(false); const pendingFetchesRef = React.useRef(0); const [isFetchingLogs, setIsFetchingLogs] = React.useState(false); // to track which containers already started fetching const connectionManagerRef = React.useRef(new Map void>()); const appendLog = React.useCallback((containerName: string, message: string) => { let buf = buffersRef.current.get(containerName); if (!buf) { buf = new LineBuffer(); buffersRef.current.set(containerName, buf); } buf.append(message); if (!rafRef.current) { rafRef.current = requestAnimationFrame(() => { rafRef.current = 0; forceRender(); }); } }, []); React.useEffect( () => () => { if (rafRef.current) cancelAnimationFrame(rafRef.current); }, [], ); // loops through the containers and initiates fetching for each one React.useEffect(() => { const activeConnections = connectionManagerRef.current; const markFetchStarted = () => { pendingFetchesRef.current += 1; if (pendingFetchesRef.current === 1) { setIsFetchingLogs(true); } }; const markFetchFinished = () => { pendingFetchesRef.current = Math.max(0, pendingFetchesRef.current - 1); if (pendingFetchesRef.current === 0) { setIsFetchingLogs(false); } }; containers.forEach((container) => { if (activeConnections.has(container.name)) { return; } const { name } = container; const allStatuses: ContainerStatus[] = resource?.status?.containerStatuses ?? []; const status = allStatuses.find((c) => c.name === name); const resourceStatus = containerToLogSourceStatus(status); const isArchiveSource = isKubearchiveEnabled && source === ResourceSource.Archive; const urlOpts = { ns: resNamespace, name: resName, path: 'log', queryParams: { container: name, follow: resourceStatus === LOG_SOURCE_TERMINATED ? 'false' : 'true', ...(isArchiveSource ? { tailLines: String(KUBEARCHIVE_TAIL_LINES) } : undefined), }, }; const watchURL = getK8sResourceURL(PodModel, undefined, urlOpts); if (resourceStatus === LOG_SOURCE_TERMINATED) { const controller = new AbortController(); const { signal } = controller; markFetchStarted(); commonFetchText(watchURL, { signal, ...(isArchiveSource ? { pathPrefix: KUBEARCHIVE_PATH_PREFIX } : undefined), }) .then((res) => { appendLog(name, res); if (isArchiveSource) { const buf = buffersRef.current.get(name); if (buf && buf.length() >= KUBEARCHIVE_TAIL_LINES) { tailedContainersRef.current.add(name); } } }) .catch((err) => { if (err.name !== 'AbortError') { // Gracefully handle empty logs (404) from KubeArchive/Tekton Results. // When logs don't exist, both KubeArchive and Tekton Results return 404. // For cluster-sourced 404s the API often returns a meaningful message // (e.g. "container step-X is waiting to start: ImagePullBackOff") // which should be surfaced to the user. if (err?.code === 404 && source === ResourceSource.Archive) { const message = err instanceof Error ? err.message : ''; // Show the error with ANSI styling if available; otherwise mark the // container as fetched with empty content so folding can evaluate it // after load (and so the section still appears in the viewer). appendLog(name, message ? `\x1b[1;31mLOG FETCH ERROR:\n${message}\x1b[0m\n` : ''); return; } appendLog( name, `\x1b[1;31mLOG FETCH ERROR${err instanceof Error ? `:\n${err.message}` : ''}\x1b[0m\n`, ); } }) .finally(markFetchFinished); activeConnections.set(name, () => controller.abort()); } else { const wsOpts = getWebsocketSubProtocolAndPathPrefix(watchURL); const ws = retryWebSocket( watchURL, wsOpts, (msg) => { setError(false); appendLog(name, Base64.decode(msg as string)); }, () => { setError(true); }, ); activeConnections.set(name, () => ws.destroy()); } }); return () => { const containerNames = new Set(containers.map((c) => c.name)); activeConnections.forEach((destroy, name) => { if (!containerNames.has(name)) { destroy(); activeConnections.delete(name); } }); }; }, [containers, resource, resName, resNamespace, appendLog, source, isKubearchiveEnabled]); const allLogsTerminated = React.useMemo(() => { if (containers.length === 0) return false; const allStatuses: ContainerStatus[] = resource?.status?.containerStatuses ?? []; const terminatedContainers: string[] = []; const runningContainers: string[] = []; containers.forEach((container) => { const status = allStatuses.find((c) => c.name === container.name); const resourceStatus = containerToLogSourceStatus(status); if (resourceStatus === LOG_SOURCE_TERMINATED) { terminatedContainers.push(container.name); } else { runningContainers.push(container.name); } }); const allTerminated = runningContainers.length === 0; return allTerminated; }, [containers, resource?.status?.containerStatuses]); const sections = React.useMemo(() => { void renderTick; const statusByName = new Map( (resource?.status?.containerStatuses ?? []).map((status) => [status.name, status]), ); return containers .filter((c) => buffersRef.current.has(c.name)) .map((c) => { const buf = buffersRef.current.get(c.name); const lines = buf?.getLines() ?? []; return { containerName: c.name.toUpperCase(), lines, isCompleted: isContainerStepCompleted(statusByName.get(c.name)), isTailed: tailedContainersRef.current.has(c.name), hasTerminatedWithError: lines.some((line) => line.startsWith('LOG FETCH ERROR')) || (statusByName.get(c.name)?.state?.terminated?.exitCode ?? 0) !== 0, }; }); }, [renderTick, resource?.status?.containerStatuses, containers]); const isArchiveSource = isKubearchiveEnabled && source === ResourceSource.Archive; const getFullLogUrl = React.useCallback( (sectionIndex: number) => { const section = sections[sectionIndex]; if (!section) return null; const containerName = containers.find( (c) => c.name.toUpperCase() === section.containerName, )?.name; if (!containerName) return null; const urlOpts = { ns: resNamespace, name: resName, path: 'log', queryParams: { container: containerName, follow: 'false' }, }; return { url: getK8sResourceURL(PodModel, undefined, urlOpts), containerName }; }, [sections, containers, resNamespace, resName], ); const handleDownloadFullLogs = React.useCallback( async (sectionIndex: number) => { const result = getFullLogUrl(sectionIndex); if (!result) return; const text = await commonFetchText(result.url, { pathPrefix: KUBEARCHIVE_PATH_PREFIX }); const blob = new Blob([text], { type: 'text/plain;charset=utf-8' }); saveAs(blob, `${result.containerName}.log`); }, [getFullLogUrl], ); const handleViewFullLogs = React.useCallback( (sectionIndex: number) => { const result = getFullLogUrl(sectionIndex); if (!result) return; window.open(`/api/k8s/${KUBEARCHIVE_PATH_PREFIX}${result.url}`, '_blank'); }, [getFullLogUrl], ); return ( ); }; export default Logs;