All files / modules/85-cv/pages/health-source/connectors/PrometheusHealthSource PrometheusHealthSource.tsx

88.41% Statements 61/69
69.52% Branches 73/105
66.67% Functions 8/12
88.06% Lines 59/67

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              24x 24x 24x 24x 24x   24x 24x 24x 24x 24x 24x 24x 24x 24x         24x         24x 24x   24x 24x 24x 24x             24x 19x   18x         18x   18x   18x 18x 18x 18x     18x     18x                   18x 6x                         18x           18x       18x   18x         44x                         18x                   36x         36x 6x             36x                                                                                                                                                                                                                                   3x         3x 3x 3x 3x 3x 3x 3x                             4x                         4x 2x 2x   2x 2x 2x                              
/*
 * 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, useContext, useMemo } from 'react'
import { Container, Formik, FormikForm, Text, Layout, SelectOption, Utils, Accordion } from '@wings-software/uicore'
import { useParams } from 'react-router-dom'
import { noop } from 'lodash-es'
import { SetupSourceTabsContext } from '@cv/components/CVSetupSourcesView/SetupSourceTabs/SetupSourceTabs'
import type { ProjectPathProps } from '@common/interfaces/RouteInterfaces'
import { GroupName } from '@cv/pages/health-source/common/GroupName/GroupName'
import { SetupSourceCardHeader } from '@cv/components/CVSetupSourcesView/SetupSourceCardHeader/SetupSourceCardHeader'
import DrawerFooter from '@cv/pages/health-source/common/DrawerFooter/DrawerFooter'
import { StackdriverDefinition, useGetLabelNames, useGetMetricNames, useGetMetricPacks } from 'services/cv'
import { useStrings } from 'framework/strings'
import { NameId } from '@common/components/NameIdDescriptionTags/NameIdDescriptionTags'
import useGroupedSideNaveHook from '@cv/hooks/GroupedSideNaveHook/useGroupedSideNaveHook'
import { PrometheusQueryBuilder } from './components/PrometheusQueryBuilder/PrometheusQueryBuilder'
import {
  validateMappings,
  transformPrometheusSetupSourceToHealthSource,
  transformPrometheusHealthSourceToSetupSource
} from './PrometheusHealthSource.utils'
import {
  PrometheusMonitoringSourceFieldNames,
  MapPrometheusQueryToService,
  PrometheusSetupSource
} from './PrometheusHealthSource.constants'
import { initializeGroupNames } from '../../common/GroupName/GroupName.utils'
import CustomMetric from '../../common/CustomMetric/CustomMetric'
import type { UpdatedHealthSource } from '../../HealthSourceDrawer/HealthSourceDrawerContent.types'
import { updateMultiSelectOption } from './components/PrometheusQueryBuilder/components/PrometheusFilterSelector/utils'
import { PrometheusQueryViewer } from './components/PrometheusQueryViewer/PrometheusQueryViewer'
import SelectHealthSourceServices from '../../common/SelectHealthSourceServices/SelectHealthSourceServices'
import css from './PrometheusHealthSource.module.scss'
 
export interface PrometheusHealthSourceProps {
  data: any
  onSubmit: (formdata: PrometheusSetupSource, UpdatedHealthSource: UpdatedHealthSource) => Promise<void>
}
 
export function PrometheusHealthSource(props: PrometheusHealthSourceProps): JSX.Element {
  const { data: sourceData, onSubmit } = props
 
  const { projectIdentifier, orgIdentifier, accountId } = useParams<ProjectPathProps & { identifier: string }>()
 
  const {
    onPrevious,
    sourceData: { existingMetricDetails }
  } = useContext(SetupSourceTabsContext)
 
  const metricDefinitions = existingMetricDetails?.spec?.metricDefinitions
 
  const { getString } = useStrings()
  const connectorIdentifier = sourceData?.connectorRef || ''
  const [labelNameTracingId, metricNameTracingId] = useMemo(() => [Utils.randomId(), Utils.randomId()], [])
  const metricPackResponse = useGetMetricPacks({
    queryParams: { projectIdentifier, orgIdentifier, accountId, dataSourceType: 'PROMETHEUS' }
  })
  const labelNamesResponse = useGetLabelNames({
    queryParams: { projectIdentifier, orgIdentifier, accountId, connectorIdentifier, tracingId: labelNameTracingId }
  })
  const metricNamesResponse = useGetMetricNames({
    queryParams: {
      projectIdentifier,
      orgIdentifier,
      accountId,
      tracingId: metricNameTracingId,
      connectorIdentifier
    }
  })
 
  const transformedSourceData = useMemo(
    () => transformPrometheusHealthSourceToSetupSource(sourceData, getString),
    [sourceData]
  )
 
  const {
    createdMetrics,
    mappedMetrics,
    selectedMetric,
    groupedCreatedMetrics,
    groupedCreatedMetricsList,
    setMappedMetrics,
    setCreatedMetrics,
    setGroupedCreatedMetrics
  } = useGroupedSideNaveHook({
    defaultCustomMetricName: getString('cv.monitoringSources.prometheus.prometheusMetric'),
    initCustomMetricData: {},
    mappedServicesAndEnvs: transformedSourceData.mappedServicesAndEnvs
  })
 
  const [prometheusGroupNames, setPrometheusGroupName] = useState<SelectOption[]>(
    initializeGroupNames(mappedMetrics, getString)
  )
 
  const initialFormValues = mappedMetrics.get(selectedMetric || '') as MapPrometheusQueryToService
 
  return (
    <Formik<MapPrometheusQueryToService>
      formName="mapPrometheus"
      initialValues={initialFormValues}
      isInitialValid={(args: any) =>
        Object.keys(
          validateMappings(
            getString,
            groupedCreatedMetricsList,
            groupedCreatedMetricsList.indexOf(selectedMetric),
            args.initialValues,
            mappedMetrics
          )
        ).length === 0
      }
      onSubmit={noop}
      enableReinitialize={true}
      validate={values => {
        return validateMappings(
          getString,
          groupedCreatedMetricsList,
          groupedCreatedMetricsList.indexOf(selectedMetric),
          values,
          mappedMetrics
        )
      }}
    >
      {formikProps => {
        const currentSelectedMetricDetail = metricDefinitions?.find(
          (metricDefinition: StackdriverDefinition) =>
            metricDefinition.metricName === mappedMetrics.get(selectedMetric || '')?.metricName
        )
 
        if (!formikProps.touched?.identifier) {
          formikProps.setTouched({
            ...formikProps.touched,
            [PrometheusMonitoringSourceFieldNames.METRIC_IDENTIFIER]: true,
            [PrometheusMonitoringSourceFieldNames.METRIC_NAME]: true
          })
        }
 
        return (
          <FormikForm>
            <CustomMetric
              isPrimaryMetric
              isValidInput={formikProps.isValid}
              setMappedMetrics={setMappedMetrics}
              selectedMetric={selectedMetric}
              formikValues={formikProps.values as any}
              mappedMetrics={mappedMetrics}
              createdMetrics={createdMetrics}
              setCreatedMetrics={setCreatedMetrics}
              defaultMetricName={getString('cv.monitoringSources.prometheus.prometheusMetric')}
              tooptipMessage={getString('cv.monitoringSources.gcoLogs.addQueryTooltip')}
              addFieldLabel={getString('cv.monitoringSources.addMetric')}
              initCustomForm={
                {
                  query: '',
                  groupName: { label: '', value: '' },
                  isManualQuery: false
                } as any
              }
              groupedCreatedMetrics={groupedCreatedMetrics}
              setGroupedCreatedMetrics={setGroupedCreatedMetrics}
            >
              <Container className={css.main}>
                <SetupSourceCardHeader
                  mainHeading={getString('cv.monitoringSources.prometheus.querySpecificationsAndMappings')}
                  subHeading={getString('cv.monitoringSources.prometheus.customizeQuery')}
                />
                {formikProps.values?.isManualQuery && (
                  <Container className={css.manualQueryWarning}>
                    <Text icon="warning-sign" iconProps={{ size: 14 }}>
                      {getString('cv.monitoringSources.prometheus.isManualQuery')}
                    </Text>
                    <Text
                      intent="primary"
                      onClick={() =>
                        formikProps.setFieldValue(PrometheusMonitoringSourceFieldNames.IS_MANUAL_QUERY, false)
                      }
                    >
                      {getString('cv.monitoringSources.prometheus.undoManualQuery')}
                    </Text>
                  </Container>
                )}
                <Layout.Horizontal className={css.content} spacing="xlarge">
                  <Accordion activeId="metricToService" className={css.accordian}>
                    <Accordion.Panel
                      id="metricToService"
                      summary={getString('cv.monitoringSources.mapMetricsToServices')}
                      details={
                        <>
                          <NameId
                            nameLabel={getString('cv.monitoringSources.metricNameLabel')}
                            identifierProps={{
                              inputName: PrometheusMonitoringSourceFieldNames.METRIC_NAME,
                              idName: PrometheusMonitoringSourceFieldNames.METRIC_IDENTIFIER,
                              isIdentifierEditable: Boolean(!currentSelectedMetricDetail?.identifier)
                            }}
                          />
                          <GroupName
                            groupNames={prometheusGroupNames}
                            onChange={formikProps.setFieldValue}
                            item={formikProps.values?.groupName}
                            setGroupNames={setPrometheusGroupName}
                          />
                        </>
                      }
                    />
                    {!formikProps.values?.isManualQuery && (
                      <Accordion.Panel
                        id="queryBuilder"
                        summary={getString('cv.monitoringSources.buildYourQuery')}
                        details={
                          <PrometheusQueryBuilder
                            connectorIdentifier={connectorIdentifier}
                            labelNamesResponse={labelNamesResponse}
                            metricNamesResponse={metricNamesResponse}
                            aggregatorValue={formikProps.values?.aggregator}
                            onUpdateFilter={(fieldName, updatedItem) => {
                              formikProps.setFieldValue(
                                fieldName,
                                updateMultiSelectOption(updatedItem, (formikProps.values as any)[fieldName])
                              )
                            }}
                            onRemoveFilter={(fieldName, index) => {
                              const arr = (formikProps.values as any)[fieldName]
                              if (arr) {
                                arr.splice(index, 1)
                                formikProps.setFieldValue(fieldName, Array.from(arr))
                              }
                            }}
                          />
                        }
                      />
                    )}
                    <Accordion.Panel
                      id="assign"
                      summary={getString('cv.monitoringSources.assign')}
                      details={
                        <SelectHealthSourceServices
                          values={{
                            sli: !!formikProps?.values?.sli,
                            riskCategory: formikProps?.values?.riskCategory,
                            healthScore: !!formikProps?.values?.healthScore,
                            continuousVerification: !!formikProps?.values?.continuousVerification
                          }}
                          metricPackResponse={metricPackResponse}
                          labelNamesResponse={labelNamesResponse}
                        />
                      }
                    />
                  </Accordion>
                  <PrometheusQueryViewer
                    onChange={(fieldName, value) => {
                      Eif (
                        fieldName === PrometheusMonitoringSourceFieldNames.IS_MANUAL_QUERY &&
                        value === true &&
                        formikProps.values
                      ) {
                        formikProps.values.prometheusMetric = undefined
                        formikProps.values.serviceFilter = undefined
                        formikProps.values.envFilter = undefined
                        formikProps.values.additionalFilter = undefined
                        formikProps.values.prometheusMetric = undefined
                        formikProps.values.aggregator = undefined
                        formikProps.setValues({ ...formikProps.values, isManualQuery: true })
                      } else {
                        formikProps.setFieldValue(fieldName, value)
                      }
                    }}
                    values={formikProps.values}
                    connectorIdentifier={connectorIdentifier}
                  />
                </Layout.Horizontal>
              </Container>
            </CustomMetric>
            <DrawerFooter
              isSubmit
              onPrevious={onPrevious}
              onNext={async () => {
                formikProps.setTouched({
                  ...formikProps.touched,
                  [PrometheusMonitoringSourceFieldNames.PROMETHEUS_METRIC]: true,
                  [PrometheusMonitoringSourceFieldNames.GROUP_NAME]: true,
                  [PrometheusMonitoringSourceFieldNames.SERVICE_FILTER]: true,
                  [PrometheusMonitoringSourceFieldNames.ENVIRONMENT_FILTER]: true,
                  [PrometheusMonitoringSourceFieldNames.SLI]: true,
                  [PrometheusMonitoringSourceFieldNames.RISK_CATEGORY]: true,
                  [PrometheusMonitoringSourceFieldNames.LOWER_BASELINE_DEVIATION]: true,
                  [PrometheusMonitoringSourceFieldNames.METRIC_IDENTIFIER]: true,
                  [PrometheusMonitoringSourceFieldNames.METRIC_NAME]: true
                })
 
                if (Object.keys(formikProps.errors || {})?.length > 0) {
                  formikProps.validateForm()
                  return
                }
                const updatedMetric = formikProps.values
                Eif (updatedMetric) mappedMetrics.set(selectedMetric, updatedMetric)
                await onSubmit(
                  sourceData,
                  transformPrometheusSetupSourceToHealthSource({
                    ...transformedSourceData,
                    mappedServicesAndEnvs: mappedMetrics as Map<string, MapPrometheusQueryToService>
                  })
                )
              }}
            />
          </FormikForm>
        )
      }}
    </Formik>
  )
}