All files / modules/75-ce/components/COGatewayAccess LBAdvancedConfiguration.tsx

95.77% Statements 68/71
84.21% Branches 32/38
87.5% Functions 14/16
95.59% Lines 65/68

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              5x 5x 5x 5x 5x 5x 5x 5x 5x           5x     5x 5x 5x             5x                 5x 53x 51x 51x 51x 51x 51x   51x 51x 51x 51x   51x               51x 14x 13x   1x       51x 26x     51x 26x       26x 26x     51x 12x 12x 12x 12x 12x                     12x   12x     51x 13x 13x     12x 12x     1x   13x       51x 4x 4x     51x 2x 2x 2x     51x 2x 2x     51x         1x                                                                                   2x                                 5x  
/*
 * 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, { useEffect, useState } from 'react'
import { useParams } from 'react-router-dom'
import { isEmpty as _isEmpty, defaultTo as _defaultTo } from 'lodash-es'
import { Container, Icon, Layout, Switch, Tabs, Text } from '@wings-software/uicore'
import { Tab } from '@blueprintjs/core'
import { useStrings } from 'framework/strings'
import { Utils } from '@ce/common/Utils'
import { useToaster } from '@common/exports'
import {
  HealthCheck,
  PortConfig,
  useSecurityGroupsOfInstances,
  NetworkSecurityGroupForInstanceArray
} from 'services/lw'
import { portProtocolMap } from '@ce/constants'
import type { AccountPathProps } from '@common/interfaces/RouteInterfaces'
import type { ASRuleCreationActiveStep, GatewayDetails } from '../COCreateGateway/models'
import CORoutingTable from '../COGatewayConfig/CORoutingTable'
import COHealthCheckTable from '../COGatewayConfig/COHealthCheckTable'
import {
  getAllInboundRules,
  getDefinedInboundRules,
  getPortConfig,
  getSecurityGroupsBodyText,
  getDefaultPortConfigs
} from './helper'
import css from './COGatewayAccess.module.scss'
 
interface LBAdvancedConfigurationProps {
  gatewayDetails: GatewayDetails
  setGatewayDetails: (details: GatewayDetails) => void
  activeStepDetails?: ASRuleCreationActiveStep | null
  setServerNames: (values: string[]) => void
}
 
const LBAdvancedConfiguration: React.FC<LBAdvancedConfigurationProps> = props => {
  const { getString } = useStrings()
  const { accountId } = useParams<AccountPathProps>()
  const { showError } = useToaster()
  const isK8sRule = Utils.isK8sRule(props.gatewayDetails)
  const isAzureProvider = Utils.isProviderAzure(props.gatewayDetails.provider)
  const isGcpProvider = Utils.isProviderGcp(props.gatewayDetails.provider)
 
  const [activeConfigTabId, setActiveConfigTabId] = useState<string | undefined>(props.activeStepDetails?.tabId)
  const [routingRecords, setRoutingRecords] = useState<PortConfig[]>(props.gatewayDetails.routing.ports)
  const [healthCheckPattern, setHealthCheckPattern] = useState<HealthCheck | null>(props.gatewayDetails.healthCheck)
  const [showRoutingTable, setShowRoutingTable] = useState<boolean>(false)
 
  const { mutate: getSecurityGroups, loading: loadingSecurityGroups } = useSecurityGroupsOfInstances({
    account_id: accountId,
    queryParams: {
      cloud_account_id: props.gatewayDetails.cloudAccount.id,
      accountIdentifier: accountId
    }
  })
 
  useEffect(() => {
    if (_isEmpty(routingRecords) && !_isEmpty(props.gatewayDetails.selectedInstances)) {
      fetchInstanceSecurityGroups()
    } else {
      setShowRoutingTable(true)
    }
  }, [])
 
  const getServerNames = () => {
    return routingRecords ? routingRecords?.map(record => record.server_name).filter(v => !_isEmpty(v)) : []
  }
 
  useEffect(() => {
    const updatedGatewayDetails = {
      ...props.gatewayDetails,
      routing: { ...props.gatewayDetails.routing, ports: routingRecords }
    }
    props.setGatewayDetails(updatedGatewayDetails)
    props.setServerNames(getServerNames() as string[])
  }, [routingRecords])
 
  const handleSaveRoutingRecords = (data: NetworkSecurityGroupForInstanceArray) => {
    const securityGroups = Object.entries(data).map(([, groups]) => groups)
    const inboundRules = getAllInboundRules(securityGroups)
    const definedRules = getDefinedInboundRules(inboundRules)
    let newRecords = []
    Iif (!_isEmpty(definedRules)) {
      newRecords = definedRules
        .filter(rule => Object.keys(portProtocolMap).includes(rule.from as string))
        .map(rule =>
          getPortConfig({
            from: Number(rule.from),
            to: _defaultTo(Number(rule.to), 0),
            protocol: portProtocolMap[Number(rule.from)]
          })
        )
    } else {
      newRecords = getDefaultPortConfigs()
    }
    setRoutingRecords(newRecords)
  }
 
  const fetchInstanceSecurityGroups = async (): Promise<void> => {
    try {
      const result = await getSecurityGroups({
        text: getSecurityGroupsBodyText(props.gatewayDetails, { isAzureProvider, isGcpProvider })
      })
      Eif (result && result.response) {
        handleSaveRoutingRecords(result.response)
      }
    } catch (e) {
      showError(e.data?.message || e.message, undefined, 'ce.creaetap.result.error')
    } finally {
      setShowRoutingTable(true)
    }
  }
 
  const updateGatewayHealthCheck = (_healthCheckDetails: HealthCheck | null) => {
    const updatedGatewayDetails = { ...props.gatewayDetails, healthCheck: _healthCheckDetails }
    props.setGatewayDetails(updatedGatewayDetails)
  }
 
  const handleHealthCheckToggle = (toggleStatus: boolean) => {
    const hcData = toggleStatus ? Utils.getDefaultRuleHealthCheck() : null
    setHealthCheckPattern(hcData)
    updateGatewayHealthCheck(hcData)
  }
 
  const handleUpdatePattern = (_data: HealthCheck) => {
    setHealthCheckPattern(_data)
    updateGatewayHealthCheck(_data)
  }
 
  return (
    <Container className={css.dnsLinkContainer}>
      <Tabs
        id="tabsId1"
        selectedTabId={activeConfigTabId}
        onChange={tabId => tabId !== activeConfigTabId && setActiveConfigTabId(tabId as string)}
      >
        <Tab
          id="routing"
          title={getString('ce.co.gatewayReview.routing')}
          panel={
            <Container style={{ backgroundColor: '#FBFBFB' }}>
              {!isK8sRule && (
                <>
                  <Text className={css.titleHelpTextDescription}>
                    {getString('ce.co.gatewayConfig.routingDescription')}
                  </Text>
                  <Layout.Vertical spacing="large">
                    {!showRoutingTable || loadingSecurityGroups ? (
                      <Icon
                        name="spinner"
                        size={24}
                        color="blue500"
                        style={{ alignSelf: 'center', marginTop: '10px' }}
                      />
                    ) : (
                      <CORoutingTable routingRecords={routingRecords} setRoutingRecords={setRoutingRecords} />
                    )}
                  </Layout.Vertical>
                </>
              )}
            </Container>
          }
        />
        <Tab
          id="healthcheck"
          title={getString('ce.co.gatewayConfig.healthCheck')}
          panel={
            <Container style={{ backgroundColor: '#FBFBFB' }}>
              <Text className={css.titleHelpTextDescription}>
                {getString('ce.co.gatewayConfig.healthCheckDescription')}
              </Text>
              <Layout.Vertical spacing="large" padding="large">
                <Switch
                  label={getString('ce.co.gatewayConfig.healthCheck')}
                  className={css.switchFont}
                  onChange={e => {
                    handleHealthCheckToggle(e.currentTarget.checked)
                  }}
                  checked={!_isEmpty(healthCheckPattern)}
                  data-testid={'toggleHealthCheck'}
                />
                {healthCheckPattern && (
                  <COHealthCheckTable pattern={healthCheckPattern} updatePattern={handleUpdatePattern} />
                )}
              </Layout.Vertical>
            </Container>
          }
        />
      </Tabs>
    </Container>
  )
}
 
export default LBAdvancedConfiguration