All files / modules/70-pipeline/pages/execution/ExecutionLandingPage ExecutionLandingPage.tsx

92.31% Statements 96/104
86.86% Branches 238/274
71.43% Functions 15/21
94.12% Lines 96/102

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314              2x 2x 2x 2x 2x 2x 2x 2x   2x 2x           2x 2x 2x 2x     2x 2x 2x 2x 2x 2x 2x 2x 2x   2x   2x 2x   2x                               13x 1x 1x 1x       12x 7x 7x 7x     5x         5x           5x 1x 1x     5x 1x 1x       2x 23x   23x 23x     23x 23x     23x 23x 23x     23x 23x 23x 23x 23x 23x 23x           23x                                   23x             23x 9x         23x 9x 9x       23x             23x 23x 60x     23x 9x             23x 9x   9x 9x 9x   9x       23x   23x 21x 4x 1x 1x       4x 4x           23x 13x                   23x 9x 8x         23x 12x 9x   12x     23x                                                                                                                                                                
/*
 * Copyright 2021 Harness Inc. All rights reserved.
 * Use of this source code is governed by the PolyForm Shield 1.0.0 license
 * that can be found in the licenses directory at the root of this repository, also available at
 * https://polyformproject.org/wp-content/uploads/2020/06/PolyForm-Shield-1.0.0.txt.
 */
 
import React, { Dispatch, SetStateAction, useEffect } from 'react'
import { Intent } from '@blueprintjs/core'
import { useParams, useLocation } from 'react-router-dom'
import { get, isEmpty, pickBy } from 'lodash-es'
import { Text, Icon, PageError, PageSpinner, Layout } from '@wings-software/uicore'
import { FontVariation, Color } from '@harness/design-system'
import { DeprecatedImageInfo, useGetExecutionConfig } from 'services/ci'
import { GovernanceMetadata, useGetExecutionDetail, ResponsePipelineExecutionDetail } from 'services/pipeline-ng'
import type { ExecutionNode } from 'services/pipeline-ng'
import { ExecutionStatus, isExecutionComplete } from '@pipeline/utils/statusHelpers'
import {
  getPipelineStagesMap,
  getActiveStageForPipeline,
  getActiveStep,
  addServiceDependenciesFromLiteTaskEngine
} from '@pipeline/utils/executionUtils'
import useRBACError from '@rbac/utils/useRBACError/useRBACError'
import { useQueryParams, useDeepCompareEffect } from '@common/hooks'
import { joinAsASentence } from '@common/utils/StringUtils'
import { String, useStrings } from 'framework/strings'
import type { ExecutionPageQueryParams } from '@pipeline/utils/types'
import type { ExecutionPathProps, PipelineType } from '@common/interfaces/RouteInterfaces'
import { PipelineExecutionWarning } from '@pipeline/components/PipelineExecutionWarning/PipelineExecutionWarning'
import { logsCache } from '@pipeline/components/LogsContent/LogsState/utils'
import { EvaluationModal } from '@governance/EvaluationModal'
import ExecutionContext, { GraphCanvasState } from '@pipeline/context/ExecutionContext'
import { ModuleName } from 'framework/types/ModuleName'
import useTabVisible from '@common/hooks/useTabVisible'
import { ExecutionHeader } from './ExecutionHeader/ExecutionHeader'
import ExecutionMetadata from './ExecutionMetadata/ExecutionMetadata'
import ExecutionTabs from './ExecutionTabs/ExecutionTabs'
 
import css from './ExecutionLandingPage.module.scss'
 
export const POLL_INTERVAL = 2 /* sec */ * 1000 /* ms */
const PageTabs = { PIPELINE: 'pipeline' }
 
const setStageIds = ({
  queryParams,
  setAutoSelectedStageId,
  setAutoSelectedStepId,
  setSelectedStepId,
  setSelectedStageId,
  data
}: {
  queryParams: ExecutionPageQueryParams
  setAutoSelectedStageId: Dispatch<SetStateAction<string>>
  setAutoSelectedStepId: Dispatch<SetStateAction<string>>
  setSelectedStepId: Dispatch<SetStateAction<string>>
  setSelectedStageId: Dispatch<SetStateAction<string>>
  data?: ResponsePipelineExecutionDetail | null
}): void => {
  // if user has selected a stage/step do not auto-update
  if (queryParams.stage || queryParams.step) {
    setAutoSelectedStageId('')
    setAutoSelectedStepId('')
    return
  }
 
  // if no data is found, reset the stage and step
  if (!data || !data?.data) {
    setAutoSelectedStageId('')
    setAutoSelectedStepId('')
    return
  }
 
  const runningStage = getActiveStageForPipeline(
    data.data.pipelineExecutionSummary,
    data.data?.pipelineExecutionSummary?.status as ExecutionStatus
  )
 
  const runningStep = getActiveStep(
    data.data.executionGraph || {},
    undefined,
    data.data.pipelineExecutionSummary?.layoutNodeMap
  )
 
  if (runningStage) {
    setAutoSelectedStageId(runningStage)
    setSelectedStageId(runningStage)
  }
 
  if (runningStep) {
    setAutoSelectedStepId(runningStep)
    setSelectedStepId(runningStep)
  }
}
 
export default function ExecutionLandingPage(props: React.PropsWithChildren<unknown>): React.ReactElement {
  const { getString } = useStrings()
  const { orgIdentifier, projectIdentifier, executionIdentifier, accountId, module } =
    useParams<PipelineType<ExecutionPathProps>>()
  const [allNodeMap, setAllNodeMap] = React.useState<Record<string, ExecutionNode>>({})
 
  /* cache token required for retrieving logs */
  const [logsToken, setLogsToken] = React.useState('')
  const { getRBACErrorMessage } = useRBACError()
 
  /* These are used when auto updating selected stage/step when a pipeline is running */
  const [autoSelectedStageId, setAutoSelectedStageId] = React.useState<string>('')
  const [autoSelectedStepId, setAutoSelectedStepId] = React.useState<string>('')
  const [isPipelineInvalid, setIsPipelineInvalid] = React.useState(false)
 
  /* These are updated only when new data is fetched successfully */
  const [selectedStageId, setSelectedStageId] = React.useState<string>('')
  const [selectedStepId, setSelectedStepId] = React.useState<string>('')
  const queryParams = useQueryParams<ExecutionPageQueryParams>()
  const location = useLocation<{ shouldShowGovernanceEvaluations: boolean; governanceMetadata: GovernanceMetadata }>()
  const locationPathNameArr = location?.pathname?.split('/') || []
  const selectedPageTab = locationPathNameArr[locationPathNameArr.length - 1]
  const [stepsGraphCanvasState, setStepsGraphCanvasState] = React.useState<GraphCanvasState>({
    offsetX: 5,
    offsetY: 0,
    zoom: 100
  })
 
  const { data, refetch, loading, error } = useGetExecutionDetail({
    planExecutionId: executionIdentifier,
    queryParams: {
      orgIdentifier,
      projectIdentifier,
      accountIdentifier: accountId,
      stageNodeId: isEmpty(queryParams.stage || autoSelectedStageId)
        ? undefined
        : queryParams.stage || autoSelectedStageId
    },
    debounce: 500
  })
 
  const {
    data: executionConfig,
    refetch: fetchExecutionConfig,
    loading: isFetchingExecutionConfig,
    error: errorWhileFetchingExecutionConfig
  } = useGetExecutionConfig({
    queryParams: {
      accountIdentifier: accountId
    },
    lazy: true
  })
 
  useEffect(() => {
    Iif (data?.data?.pipelineExecutionSummary?.modules?.includes(ModuleName.CI.toLowerCase())) {
      fetchExecutionConfig()
    }
  }, [data?.data?.pipelineExecutionSummary?.modules?.length])
 
  const deprecatedImages = React.useMemo(() => {
    Eif (!isFetchingExecutionConfig && !errorWhileFetchingExecutionConfig) {
      return executionConfig?.data as DeprecatedImageInfo[]
    }
  }, [executionConfig?.data])
 
  const getDeprecatedImageSummary = (images: DeprecatedImageInfo[]): string => {
    const tagWithVersions = images
      .filter((image: DeprecatedImageInfo) => !!image.tag && !!image.version)
      .map((image: DeprecatedImageInfo) => `${image.tag}(${image.version})`)
    return joinAsASentence(tagWithVersions)
  }
 
  const graphNodeMap = data?.data?.executionGraph?.nodeMap || {}
  const isDataLoadedForSelectedStage = Object.keys(graphNodeMap).some(
    key => graphNodeMap?.[key]?.setupId === selectedStageId
  )
 
  const pipelineStagesMap = React.useMemo(() => {
    return getPipelineStagesMap(
      data?.data?.pipelineExecutionSummary?.layoutNodeMap,
      data?.data?.pipelineExecutionSummary?.startingNodeId
    )
  }, [data?.data?.pipelineExecutionSummary?.layoutNodeMap, data?.data?.pipelineExecutionSummary?.startingNodeId])
 
  // combine steps and dependencies(ci stage)
  useDeepCompareEffect(() => {
    const nodeMap = { ...data?.data?.executionGraph?.nodeMap }
    // NOTE: add dependencies from "liteEngineTask" (ci stage)
    addServiceDependenciesFromLiteTaskEngine(nodeMap, data?.data?.executionGraph?.nodeAdjacencyListMap)
    setAllNodeMap(oldNodeMap => {
      const interruptHistories = pickBy(oldNodeMap, val => get(val, '__isInterruptNode'))
 
      return { ...interruptHistories, ...nodeMap }
    })
  }, [data?.data?.executionGraph?.nodeMap, data?.data?.executionGraph?.nodeAdjacencyListMap])
 
  const visibility = useTabVisible()
  // setup polling
  React.useEffect(() => {
    if (!loading && data && !isExecutionComplete(data.data?.pipelineExecutionSummary?.status)) {
      const timerId = window.setTimeout(() => {
        Eif (visibility) {
          refetch()
        }
      }, POLL_INTERVAL)
 
      return () => {
        window.clearTimeout(timerId)
      }
    }
  }, [data, refetch, loading, visibility])
 
  // show the current running stage and steps automatically
  React.useEffect(() => {
    setStageIds({
      queryParams,
      setAutoSelectedStageId,
      setAutoSelectedStepId,
      setSelectedStepId,
      setSelectedStageId,
      data
    })
  }, [queryParams, data])
 
  React.useEffect(() => {
    return () => {
      logsCache.clear()
    }
  }, [])
 
  // update stage/step selection
  React.useEffect(() => {
    if (loading) {
      setSelectedStageId((queryParams.stage as string) || autoSelectedStageId)
    }
    setSelectedStepId((queryParams.step as string) || autoSelectedStepId)
  }, [loading, queryParams, autoSelectedStageId, autoSelectedStepId])
 
  return (
    <ExecutionContext.Provider
      value={{
        pipelineExecutionDetail: data?.data || null,
        allNodeMap,
        pipelineStagesMap,
        isPipelineInvalid,
        selectedStageId,
        selectedStepId,
        loading,
        isDataLoadedForSelectedStage,
        queryParams,
        logsToken,
        setLogsToken,
        refetch,
        stepsGraphCanvasState,
        setStepsGraphCanvasState,
        setSelectedStageId,
        setSelectedStepId,
        setIsPipelineInvalid,
        addNewNodeToMap(id, node) {
          setAllNodeMap(nodeMap => ({ ...nodeMap, [id]: node }))
        }
      }}
    >
      {loading && !data ? <PageSpinner /> : null}
      {error ? (
        <PageError message={getRBACErrorMessage(error) as string} />
      ) : (
        <main className={css.main}>
          <div className={css.lhs}>
            <header className={css.header}>
              <ExecutionHeader />
              <ExecutionMetadata />
            </header>
            <ExecutionTabs />
            {module === 'ci' && (
              <>
                {deprecatedImages?.length ? (
                  <PipelineExecutionWarning
                    warning={
                      <>
                        <Layout.Horizontal spacing="small" flex={{ alignItems: 'center' }}>
                          <Icon name="warning-sign" intent={Intent.DANGER} />
                          <Text color={Color.ORANGE_900} font={{ variation: FontVariation.SMALL_BOLD }}>
                            {getString('pipeline.imageVersionDeprecated')}
                          </Text>
                        </Layout.Horizontal>
                        <Text font={{ weight: 'semi-bold', size: 'small' }} color={Color.PRIMARY_10} lineClamp={2}>
                          <String
                            stringID="pipeline.unsupportedImagesWarning"
                            vars={{
                              summary: `${getDeprecatedImageSummary(deprecatedImages)}.`
                            }}
                            useRichText
                          />
                        </Text>
                        {/* <Link to={'/'}>{getString('learnMore')}</Link> */}
                      </>
                    }
                  />
                ) : null}
              </>
            )}
            <div
              className={css.childContainer}
              data-view={(selectedPageTab === PageTabs.PIPELINE && queryParams.view) || 'graph'}
              id="pipeline-execution-container"
            >
              {props.children}
            </div>
            {!!location?.state?.shouldShowGovernanceEvaluations && (
              <EvaluationModal accountId={accountId} metadata={location?.state?.governanceMetadata} />
            )}
          </div>
        </main>
      )}
    </ExecutionContext.Provider>
  )
}