import { saveAs } from 'file-saver'; import { FeatureFlagsStore } from '~/feature-flags/store'; import { fetchResourceWithK8sAndKubeArchive } from '~/kubearchive/resource-utils'; import { PipelineRunModel } from '~/models/pipelineruns'; import { ResourceSource } from '~/types/k8s'; import { commonFetchText } from '../../../../k8s'; import { getK8sResourceURL } from '../../../../k8s/k8s-utils'; import { PodModel } from '../../../../models/pod'; import { TaskRunKind } from '../../../../types'; import { getTaskRunLog } from '../../../../utils/tekton-results'; import { LineBuffer } from '../../../utils/line-buffer'; import { ContainerSpec, ContainerStatus, PodKind } from '../../types'; import { containerToLogSourceStatus, LOG_SOURCE_TERMINATED, LOG_SOURCE_WAITING } from '../utils'; const getSortedContainerStatus = ( containers: ContainerSpec[], containerStatuses: ContainerStatus[], ): ContainerStatus[] => { const containerNames = containers.map((c) => c.name); const sortedContainerStatus = []; containerStatuses.forEach((cs) => { const containerIndex = containerNames.indexOf(cs.name); sortedContainerStatus[containerIndex] = cs; }); return sortedContainerStatus; }; export const getRenderContainers = ( pod: PodKind, ): { containers: ContainerSpec[]; stillFetching: boolean } => { const containers: ContainerSpec[] = pod?.spec?.containers ?? []; const containerStatuses: ContainerStatus[] = pod?.status?.containerStatuses ?? []; const sortedContainerStatuses = getSortedContainerStatus(containers, containerStatuses); const firstRunningCont = sortedContainerStatuses.findIndex( (container) => containerToLogSourceStatus(container) !== LOG_SOURCE_TERMINATED, ); return { containers: containers.slice( 0, firstRunningCont === -1 ? containers.length : firstRunningCont + 1, ), stillFetching: firstRunningCont !== -1, }; }; type OrderedSteps = { stepsList: ContainerStatus[]; source?: ResourceSource; }; const getOrderedStepsFromPod = (ns: string, name?: string): Promise => { if (!name) { return Promise.resolve({ stepsList: [], source: undefined, }); } return fetchResourceWithK8sAndKubeArchive({ model: PodModel, queryOptions: { ns, name }, }) .then((res) => { const isKubearchiveEnabled = FeatureFlagsStore.isOn('kubearchive-logs'); // Legacy option to support getting logs from Tekton if (res.source === ResourceSource.Archive && !isKubearchiveEnabled) { return { stepsList: [], source: ResourceSource.Archive, }; } return { stepsList: getSortedContainerStatus( res.resource.spec.containers ?? [], res.resource.status?.containerStatuses ?? [], ), source: res.source, }; }) .catch((err) => { // eslint-disable-next-line no-console console.warn('Error Downloading logs', err); return { stepsList: [], source: undefined }; }); }; type StepsWatchUrl = { [key: string]: { name: string; source?: ResourceSource; steps: { [step: string]: WatchURLStatus }; }; }; type WatchURLStatus = { status: string; url: string; }; export const getDownloadAllLogsCallback = ( sortedTaskRunNames: string[], taskRuns: TaskRunKind[], namespace: string, pipelineRunName: string, ): (() => Promise) => { const getWatchUrls = async (): Promise => { const orderedSteps: OrderedSteps[] = await Promise.all( sortedTaskRunNames.map((currTask) => { const { status } = taskRuns.find((t) => t.metadata.name === currTask) ?? {}; return getOrderedStepsFromPod(namespace, status?.podName); }), ); return sortedTaskRunNames.reduce((acc, currTask, i) => { const taskRun = taskRuns.find((t) => t.metadata.name === currTask); const pipelineTaskName = taskRun?.spec.taskRef?.name ?? taskRun?.metadata.name; const status = taskRun.status; const podName = status?.podName; const steps = orderedSteps[i].stepsList; const allStepUrls = steps.reduce((stepUrls, currentStep) => { const { name } = currentStep; const currentStatus = containerToLogSourceStatus(currentStep); if (currentStatus === LOG_SOURCE_WAITING) return stepUrls; const urlOpts = { ns: namespace, name: podName, path: 'log', queryParams: { container: name, follow: 'true', }, }; return { ...stepUrls, [name]: { status: currentStatus, url: getK8sResourceURL(PodModel, undefined, urlOpts), } as WatchURLStatus, }; }, {}); acc[currTask] = { name: pipelineTaskName, source: orderedSteps[i].source, steps: { ...allStepUrls }, }; return acc; }, {}); }; const fetchLogs = async (tasksPromise: Promise) => { const tasks = await tasksPromise; const isKubearchiveEnabled = FeatureFlagsStore.isOn('kubearchive-logs'); let allLogs = ''; for (const currTask of sortedTaskRunNames) { const task = tasks[currTask]; const steps = Object.keys(task.steps); allLogs += `${task.name}\n\n`; if (steps.length > 0) { for (const step of steps) { const { url, status } = task.steps[step]; const getContentPromise = commonFetchText( url, isKubearchiveEnabled && task.source === ResourceSource.Archive ? { pathPrefix: 'plugins/kubearchive' } : undefined, ) .then((logs) => { return `${step.toUpperCase()}\n\n${logs}\n\n`; }) .catch((err) => { // eslint-disable-next-line no-console console.warn(`Error downloading logs for '${step}' of task '${task.name}'`, err); return ''; }); allLogs += status === LOG_SOURCE_TERMINATED ? // If we are done, we want this log content await getContentPromise : // If we are not done, let's not wait indefinitely await Promise.race([ getContentPromise, new Promise((resolve) => { setTimeout(() => resolve(''), 1000); }), ]); } } else { const taskRun = taskRuns.find((t) => t.metadata.name === currTask); const pipelineRunUID = taskRun?.metadata?.ownerReferences?.find( (res) => res.kind === PipelineRunModel.kind, )?.uid; allLogs += await getTaskRunLog(namespace, taskRun?.metadata?.uid, pipelineRunUID).then( (log) => `${tasks[currTask].name.toUpperCase()}\n\n${log}\n\n`, ); } } const buffer = new LineBuffer(); buffer.ingest(allLogs); const blob = buffer.getBlob({ type: 'text/plain;charset=utf-8', }); saveAs(blob, `${pipelineRunName}.log`); return null; }; return (): Promise => { return fetchLogs(getWatchUrls()); }; };