All files / modules/35-connectors/common/VerifyOutOfClusterDelegate VerifyOutOfClusterDelegate.tsx

77.91% Statements 67/86
51.37% Branches 150/292
60% Functions 9/15
77.91% Lines 67/86

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 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464              258x 258x 258x 258x 258x 258x 258x                     258x 258x 258x           258x 258x 258x 258x 258x                                             258x     258x   258x 29x                                                                 29x 27x   4x       2x   2x                       4x               15x       29x   29x                             258x 32x 29x 29x         29x 29x 29x   29x 29x 29x           29x 29x   29x   29x 13x 13x     29x                                                                             29x                                         29x           29x                                                                                                                                                                                     29x 29x                                                                 29x 13x 13x 13x 13x   3x 3x               3x             10x 10x                 29x 13x     29x 13x       29x                                                           3x                                           258x  
/*
 * 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, { useState, useEffect } from 'react'
import { useParams } from 'react-router-dom'
import cx from 'classnames'
import { StepsProgress, Layout, Button, Text, StepProps, Container, ButtonVariation } from '@wings-software/uicore'
import { Color, FontVariation, Intent } from '@harness/design-system'
import { useGetDelegateFromId } from 'services/portal'
import {
  useGetTestConnectionResult,
  ResponseConnectorValidationResult,
  ConnectorConfigDTO,
  Error,
  ConnectorInfoDTO,
  EntityGitDetails,
  ResponseMessage
} from 'services/cd-ng'
 
import type { StepDetails } from '@connectors/interfaces/ConnectorInterface'
import { Connectors, CONNECTOR_CREDENTIALS_STEP_IDENTIFIER } from '@connectors/constants'
import { useStrings } from 'framework/strings'
import {
  GetTestConnectionValidationTextByType,
  removeErrorCode,
  DelegateTypes
} from '@connectors/pages/connectors/utils/ConnectorUtils'
import type { ProjectPathProps } from '@common/interfaces/RouteInterfaces'
import { ErrorHandler } from '@common/components/ErrorHandler/ErrorHandler'
import { useTelemetry } from '@common/hooks/useTelemetry'
import { connectorsTrackEventMap } from '@connectors/utils/connectorEvents'
import Suggestions from '../ErrorSuggestions/ErrorSuggestionsCe'
import css from './VerifyOutOfClusterDelegate.module.scss'
 
interface RenderUrlInfo {
  type: string
  url?: string
}
 
interface VerifyOutOfClusterDelegateProps {
  type: string
  isStep: boolean
  onClose?: () => void
  setIsEditMode?: (val: boolean) => void // Remove after removing all usages
  url?: string
  isLastStep?: boolean
  name?: string
  connectorInfo: ConnectorInfoDTO | void
  gitDetails?: EntityGitDetails
  stepIndex?: number // will make this mandatory once all usages sends the value
}
export interface VerifyOutOfClusterStepProps extends ConnectorConfigDTO {
  isEditMode?: boolean
}
 
export const STEP = {
  TEST_CONNECTION: 'TEST_CONNECTION'
}
export const StepIndex = new Map([[STEP.TEST_CONNECTION, 1]])
 
const RenderUrlInfo: React.FC<StepProps<VerifyOutOfClusterStepProps> & RenderUrlInfo> = props => {
  const { getString } = useStrings()
 
  /* istanbul ignore next */
  const getLabel = (): string => {
    switch (props.type) {
      case Connectors.KUBERNETES_CLUSTER:
        return getString('connectors.testConnectionStep.url.k8s')
      case Connectors.DOCKER:
        return getString('connectors.testConnectionStep.url.docker')
      case Connectors.NEXUS:
        return getString('connectors.testConnectionStep.url.nexus')
      case Connectors.ARTIFACTORY:
        return getString('connectors.testConnectionStep.url.artifactory')
 
      case Connectors.APP_DYNAMICS:
        return getString('connectors.testConnectionStep.url.appD')
 
      case Connectors.SPLUNK:
        return getString('connectors.testConnectionStep.url.splunk')
 
      case Connectors.VAULT:
        return getString('connectors.testConnectionStep.url.vault')
      case 'Gcr':
        return getString('connectors.testConnectionStep.url.gcr')
      case Connectors.BITBUCKET:
      case Connectors.GITLAB:
      case Connectors.GITHUB:
      case Connectors.GIT:
        return getString('connectors.testConnectionStep.url.bitbucket')
      default:
        return ''
    }
  }
  const getValue = () => {
    switch (props.type) {
      case Connectors.KUBERNETES_CLUSTER:
        return props.prevStepData?.masterUrl
      case Connectors.HttpHelmRepo:
        return props.prevStepData?.helmRepoUrl
      case Connectors.DOCKER:
        return props.prevStepData?.dockerRegistryUrl
      case Connectors.NEXUS:
        return props.prevStepData?.nexusServerUrl
 
      case Connectors.ARTIFACTORY:
        return props.prevStepData?.artifactoryServerUrl
 
      case Connectors.APP_DYNAMICS:
        return props.prevStepData?.spec?.controllerUrl
 
      case Connectors.SPLUNK:
        return props.prevStepData?.splunkUrl
 
      case Connectors.VAULT:
        return props.prevStepData?.spec?.vaultUrl
      case Connectors.BITBUCKET:
      case Connectors.GITLAB:
      case Connectors.GITHUB:
      case Connectors.GIT:
        return props.prevStepData?.url
 
      default:
        return ''
    }
  }
 
  const value = props.url || getValue()
 
  return value ? (
    <Layout.Horizontal padding={{ top: 'xsmall' }} spacing="xsmall">
      <Text color={Color.GREY_400} font={{ size: 'small' }} className={css.subHeading}>
        {getLabel()}
      </Text>
      <Text color={Color.GREY_600} font={{ size: 'small' }} className={css.subHeading} lineClamp={1} width={'600px'}>
        {value}
      </Text>
    </Layout.Horizontal>
  ) : (
    <></>
  )
}
 
const VerifyOutOfClusterDelegate: React.FC<StepProps<VerifyOutOfClusterStepProps> & VerifyOutOfClusterDelegateProps> =
  props => {
    const { prevStepData, nextStep, isLastStep = false, connectorInfo } = props
    const branch = props.isStep ? prevStepData?.branch : props.gitDetails?.branch
    const repoIdentifier = props.isStep ? prevStepData?.repo : props.gitDetails?.repoIdentifier
    const {
      accountId,
      projectIdentifier: projectIdentifierFromUrl,
      orgIdentifier: orgIdentifierFromUrl
    } = useParams<ProjectPathProps>()
    const projectIdentifier = connectorInfo ? connectorInfo.projectIdentifier : projectIdentifierFromUrl
    const orgIdentifier = connectorInfo ? connectorInfo.orgIdentifier : orgIdentifierFromUrl
 
    const [viewDetails, setViewDetails] = useState<boolean>(false)
    const [testConnectionResponse, setTestConnectionResponse] = useState<ResponseConnectorValidationResult>()
    const [stepDetails, setStepDetails] = useState<StepDetails>({
      step: 1,
      intent: Intent.WARNING,
      status: 'PROCESS'
    })
 
    const ceConnectors: string[] = [Connectors.CE_KUBERNETES, Connectors.CEAWS, Connectors.CE_AZURE, Connectors.CE_GCP]
    const isCeConnector = ceConnectors.includes(props.type)
 
    const { trackEvent } = useTelemetry()
 
    useEffect(() => {
      const eventName = connectorsTrackEventMap[props.type]
      eventName && trackEvent(eventName, {})
    }, [])
 
    const { getString } = useStrings()
 
    /* istanbul ignore next */
    const getPermissionsLink = (): string => {
      switch (props.type) {
        case Connectors.KUBERNETES_CLUSTER:
          return 'https://ngdocs.harness.io/article/sjjik49xww-kubernetes-cluster-connector-settings-reference'
        case Connectors.DOCKER:
          return 'https://ngdocs.harness.io/article/u9bsd77g5a-docker-registry-connector-settings-reference'
        case Connectors.AWS:
          return 'https://ngdocs.harness.io/article/m5vkql35ca-aws-connector-settings-reference'
        case Connectors.NEXUS:
          return 'https://ngdocs.harness.io/article/faor0dc98d-nexus-connector-settings-reference'
        case Connectors.ARTIFACTORY:
          return 'https://ngdocs.harness.io/article/euueiiai4m-artifactory-connector-settings-reference'
        case Connectors.GCP:
        case 'Gcr':
          return 'https://ngdocs.harness.io/article/yykfduond6-gcs-connector-settings-reference'
        case Connectors.GIT:
          return 'https://ngdocs.harness.io/category/xyexvcc206-ref-source-repo-provider'
        case Connectors.GITHUB:
          return 'https://ngdocs.harness.io/article/v9sigwjlgo-git-hub-connector-settings-reference'
        case Connectors.GITLAB:
          return 'https://ngdocs.harness.io/article/5abnoghjgo-git-lab-connector-settings-reference'
        case Connectors.BITBUCKET:
          return 'https://ngdocs.harness.io/article/iz5tucdwyu-bitbucket-connector-settings-reference'
        case Connectors.Jira:
          return 'https://ngdocs.harness.io/article/e6s32ec7i7'
        case Connectors.SERVICE_NOW:
          return 'https://ngdocs.harness.io/article/illz8off8q'
        case Connectors.HttpHelmRepo:
          return 'https://ngdocs.harness.io/article/a0jotsvsi7'
        case Connectors.DATADOG:
          return 'https://ngdocs.harness.io/article/g21fb5kfkg-connect-to-monitoring-and-logging-systems#step_add_datadog'
        default:
          return ''
      }
    }
 
    const { mutate: reloadTestConnection, loading } = useGetTestConnectionResult({
      identifier: connectorInfo && connectorInfo.identifier ? connectorInfo.identifier : prevStepData?.identifier || '',
      queryParams: {
        accountIdentifier: accountId,
        orgIdentifier: orgIdentifier,
        projectIdentifier: projectIdentifier,
        branch,
        repoIdentifier
      },
      requestOptions: {
        headers: {
          'content-type': 'application/json'
        }
      }
    })
 
    const {
      data: delegate,
      error: delegateError,
      refetch: refetchDelegateFromId,
      loading: loadingDelegate
    } = useGetDelegateFromId({
      delegateId: testConnectionResponse?.data?.delegateId || '',
      queryParams: { accountId },
      lazy: true
    })
 
    const renderError = () => {
      const { responseMessages = null } = testConnectionResponse?.data as Error
      const genericHandler = (
        <Layout.Vertical>
          <Layout.Horizontal className={css.errorResult}>
            <Text
              color={Color.GREY_900}
              lineClamp={1}
              font={{ size: 'small', weight: 'semi-bold' }}
              margin={{ top: 'small', bottom: 'small' }}
            >
              {testConnectionResponse?.data?.errorSummary}
            </Text>
            {testConnectionResponse?.data?.errors && (
              <Button
                text="View Details"
                intent="primary"
                font={{ size: 'small' }}
                minimal
                onClick={() => setViewDetails(!viewDetails)}
                rightIcon={viewDetails ? 'chevron-up' : 'chevron-down'}
                iconProps={{ size: 12 }}
              />
            )}
          </Layout.Horizontal>
          {viewDetails ? (
            <div className={css.errorMsg}>
              <pre>{JSON.stringify({ errors: removeErrorCode(testConnectionResponse?.data?.errors) }, null, ' ')}</pre>
            </div>
          ) : null}
        </Layout.Vertical>
      )
 
      return (
        <Layout.Vertical className={css.stepError}>
          {responseMessages ? (
            <ErrorHandler
              responseMessages={responseMessages}
              className={css.errorHandler}
              errorHintsRenderer={
                isCeConnector
                  ? hints => (
                      <Suggestions
                        items={hints as ResponseMessage[]}
                        header={getString('common.errorHandler.tryTheseSuggestions')}
                        icon={'lightbulb'}
                        connectorType={props.type}
                      />
                    )
                  : undefined
              }
            />
          ) : (
            genericHandler
          )}
          {/* TODO: when install delegate behaviour is known {testConnectionResponse?.data?.delegateId ? ( */}
          {!isCeConnector ? (
            <Layout.Horizontal spacing="small">
              {props.isStep ? (
                <Button
                  text={getString('editCredentials')}
                  variation={ButtonVariation.SECONDARY}
                  onClick={() => {
                    const isTransitionToCredentialsStepSuccessful = props.gotoStep?.({
                      stepIdentifier: CONNECTOR_CREDENTIALS_STEP_IDENTIFIER,
                      prevStepData
                    })
                    if (!isTransitionToCredentialsStepSuccessful) {
                      props.previousStep?.({ ...prevStepData })
                    }
                    props.setIsEditMode?.(true) // Remove after all usages
                  }}
                  withoutBoxShadow
                />
              ) : null}
              <Text
                onClick={() => window.open(getPermissionsLink(), '_blank')}
                className={cx(css.veiwPermission, { [css.marginAuto]: props.isStep })}
                intent="primary"
              >
                {getString('connectors.testConnectionStep.viewPermissions')}
              </Text>
            </Layout.Horizontal>
          ) : null}
          {/* ) : (
          <Button text={getString('connectors.testConnectionStep.installNewDelegate')} disabled width="160px" />
        )} */}
        </Layout.Vertical>
      )
    }
 
    const getStepOne = (): JSX.Element => {
      return (
        <Layout.Vertical width={'100%'}>
          <Text color={Color.GREY_600}>
            {prevStepData?.spec?.auth?.type === 'Anonymous'
              ? getString('connectors.testConnectionStep.validationText.testingURLReachability')
              : GetTestConnectionValidationTextByType(props.type)}
          </Text>
          {!loading && testConnectionResponse?.data?.delegateId ? (
            <Text padding={{ top: 'xsmall' }} color={Color.GREY_900} font={{ size: 'small' }}>
              {getString('connectors.testConnectionStep.executingOn')}
              {loadingDelegate
                ? getString('loading')
                : delegateError
                ? getString('connectors.testConnectionStep.noDelegate')
                : delegate?.resource?.hostName}
            </Text>
          ) : null}
 
          {stepDetails.step === StepIndex.get(STEP.TEST_CONNECTION) ? (
            stepDetails.status === 'ERROR' ? (
              testConnectionResponse?.data?.errorSummary ||
              testConnectionResponse?.data?.errors ||
              (testConnectionResponse?.data as Error)?.responseMessages ? (
                renderError()
              ) : (
                <Text padding={{ top: 'small' }}>{getString('connectors.testConnectionStep.placeholderError')}</Text>
              )
            ) : null
          ) : null}
        </Layout.Vertical>
      )
    }
 
    const executeEstablishConnection = async (): Promise<void> => {
      Eif (stepDetails.step === StepIndex.get(STEP.TEST_CONNECTION)) {
        Eif (stepDetails.status === 'PROCESS') {
          try {
            const result = await reloadTestConnection()
 
            setTestConnectionResponse(result)
            Iif (result?.data?.status === 'SUCCESS') {
              setStepDetails({
                step: 2,
                intent: Intent.SUCCESS,
                status: 'DONE'
              })
              props.completedStep?.(props.stepIndex as number)
            } else {
              setStepDetails({
                step: 1,
                intent: Intent.DANGER,
                status: 'ERROR'
              })
            }
          } catch (err) {
            setTestConnectionResponse(err)
            setStepDetails({
              step: 1,
              intent: Intent.DANGER,
              status: 'ERROR'
            })
          }
        }
      }
    }
    useEffect(() => {
      executeEstablishConnection()
    }, [])
 
    useEffect(() => {
      Iif (testConnectionResponse?.data?.delegateId) {
        refetchDelegateFromId()
      }
    }, [testConnectionResponse?.data?.delegateId])
    return (
      <Layout.Vertical>
        <Layout.Vertical>
          <Text font={{ variation: FontVariation.H3 }} color={Color.GREY_800}>
            {getString('connectors.stepThreeName')}
          </Text>
          {prevStepData?.delegateType === DelegateTypes.DELEGATE_IN_CLUSTER ? null : (
            <RenderUrlInfo type={props.type} prevStepData={prevStepData} url={props.url} />
          )}
          <Container className={cx(css.content, { [css.contentMinHeight]: props.isStep })} padding={{ top: 'xxlarge' }}>
            <StepsProgress
              steps={[getStepOne()]}
              intent={stepDetails.intent}
              current={stepDetails.step}
              currentStatus={stepDetails.status}
            />
 
            {stepDetails.status === 'DONE' ? (
              <Text color={Color.GREEN_600} font={{ weight: 'bold' }} padding={{ top: 'large' }}>
                {getString('connectors.testConnectionStep.verificationSuccessful')}
              </Text>
            ) : null}
          </Container>
        </Layout.Vertical>
        {props.isStep ? (
          isLastStep ? (
            <Layout.Horizontal spacing="large" className={css.btnWrapper}>
              <Button
                intent="primary"
                onClick={() => {
                  props.onClose?.()
                }}
                text={getString('finish')}
                variation={ButtonVariation.SECONDARY}
              />
            </Layout.Horizontal>
          ) : (
            <Layout.Horizontal spacing="large" className={css.btnWrapper}>
              <Button
                variation={ButtonVariation.PRIMARY}
                onClick={() => {
                  nextStep?.({ ...prevStepData })
                }}
                text={getString('continue')}
              />
            </Layout.Horizontal>
          )
        ) : null}
      </Layout.Vertical>
    )
  }
 
export default VerifyOutOfClusterDelegate