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

82.2% Statements 97/118
69% Branches 227/329
65% Functions 13/20
81.58% Lines 93/114

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                25x         25x                 25x                     25x                                                           25x                                 25x                     25x         86x 10x         65x 11x 1x         11x 1x           65x     25x             62x                                       62x       62x 8x 8x 8x 8x     62x 410x   54x 54x   54x 54x   302x       62x 62x 75x 62x   13x     62x 75x 75x     62x 75x 62x   13x     62x 13x         62x           62x                   62x   62x     25x         62x 62x 9x       62x     25x                         25x 6x 6x 4x     2x 2x 2x     2x       18x 6x     12x 12x 12x 12x       12x     25x       6x 5x     6x 1x                                       5x                 5x 6x 6x                                                     5x     25x 2x                     2x                                     2x   2x       2x       2x 2x 2x 1x   2x 1x     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 type { SelectOption, MultiSelectOption } from '@wings-software/uicore'
import { clone, isNumber } from 'lodash-es'
import type { FormikProps } from 'formik'
import type { PrometheusFilter, PrometheusHealthSourceSpec, TimeSeriesMetricDefinition } from 'services/cv'
import type { StringsMap } from 'stringTypes'
import type { UseStringsReturn } from 'framework/strings'
import {
  CreatedMetricsWithSelectedIndex,
  PrometheusMonitoringSourceFieldNames,
  SelectedAndMappedMetrics,
  PrometheusSetupSource,
  RiskProfileCatgory,
  MapPrometheusQueryToService,
  PrometheusProductNames
} from './PrometheusHealthSource.constants'
import { HealthSourceTypes } from '../../types'
import type { UpdatedHealthSource } from '../../HealthSourceDrawer/HealthSourceDrawerContent.types'
import type { CustomMappedMetric } from '../../common/CustomMetric/CustomMetric.types'
 
type UpdateSelectedMetricsMap = {
  updatedMetric: string
  oldMetric: string
  mappedMetrics: Map<string, MapPrometheusQueryToService>
  formikProps: FormikProps<MapPrometheusQueryToService | undefined>
}
 
export function updateSelectedMetricsMap({
  updatedMetric,
  oldMetric,
  mappedMetrics,
  formikProps
}: UpdateSelectedMetricsMap): SelectedAndMappedMetrics {
  const updatedMap = new Map(mappedMetrics)
 
  // in the case where user updates metric name, update the key for current value
  if (oldMetric !== formikProps.values?.metricName) {
    updatedMap.delete(oldMetric)
  }
 
  // if newly created metric create form object
  if (!updatedMap.has(updatedMetric)) {
    updatedMap.set(updatedMetric, {
      identifier: updatedMetric.split(' ').join('_'),
      metricName: updatedMetric,
      query: '',
      isManualQuery: false
    })
  }
 
  // update map with current form data
  if (formikProps.values?.metricName) {
    updatedMap.set(formikProps.values.metricName, formikProps.values as MapPrometheusQueryToService)
  }
  return { selectedMetric: updatedMetric, mappedMetrics: updatedMap }
}
 
export function initializeSelectedMetricsMap(
  defaultSelectedMetricName: string,
  mappedServicesAndEnvs?: Map<string, MapPrometheusQueryToService>
): SelectedAndMappedMetrics {
  return {
    selectedMetric: (Array.from(mappedServicesAndEnvs?.keys() || [])?.[0] as string) || defaultSelectedMetricName,
    mappedMetrics:
      mappedServicesAndEnvs ||
      new Map([
        [
          defaultSelectedMetricName,
          { metricName: defaultSelectedMetricName, isManualQuery: false, query: '', identifier: '' }
        ]
      ])
  }
}
 
export function initializeCreatedMetrics(
  defaultSelectedMetricName: string,
  selectedMetric: string,
  mappedMetrics: SelectedAndMappedMetrics['mappedMetrics']
): CreatedMetricsWithSelectedIndex {
  return {
    createdMetrics: Array.from(mappedMetrics.keys()) || [defaultSelectedMetricName],
    selectedMetricIndex: Array.from(mappedMetrics.keys()).findIndex(metric => metric === selectedMetric)
  }
}
 
export function validateAssginComponent(
  values: MapPrometheusQueryToService,
  requiredFieldErrors: { [x: string]: string },
  getString: UseStringsReturn['getString']
): { [x: string]: string } {
  if (![values.sli, values.continuousVerification, values.healthScore].some(i => i)) {
    requiredFieldErrors[PrometheusMonitoringSourceFieldNames.SLI] = getString(
      'cv.monitoringSources.gco.mapMetricsToServicesPage.validation.baseline'
    )
  }
 
  if (values.continuousVerification || values.healthScore) {
    if (!values.riskCategory) {
      requiredFieldErrors[PrometheusMonitoringSourceFieldNames.RISK_CATEGORY] = getString(
        'cv.monitoringSources.gco.mapMetricsToServicesPage.validation.riskCategory'
      )
    }
 
    if (values.lowerBaselineDeviation !== true && values.higherBaselineDeviation !== true) {
      requiredFieldErrors[PrometheusMonitoringSourceFieldNames.LOWER_BASELINE_DEVIATION] = getString(
        'cv.monitoringSources.prometheus.validation.deviation'
      )
    }
  }
 
  return requiredFieldErrors
}
 
export function validateMappings(
  getString: UseStringsReturn['getString'],
  createdMetrics: string[],
  selectedMetricIndex: number,
  values?: MapPrometheusQueryToService,
  mappedMetrics?: Map<string, CustomMappedMetric>
): { [fieldName: string]: string } {
  let requiredFieldErrors = {
    [PrometheusMonitoringSourceFieldNames.ENVIRONMENT_FILTER]: getString(
      'cv.monitoringSources.prometheus.validation.filterOnEnvironment'
    ),
    [PrometheusMonitoringSourceFieldNames.METRIC_NAME]: getString('cv.monitoringSources.metricNameValidation'),
    [PrometheusMonitoringSourceFieldNames.METRIC_IDENTIFIER]: getString('validation.identifierRequired'),
    [PrometheusMonitoringSourceFieldNames.PROMETHEUS_METRIC]: getString(
      'cv.monitoringSources.prometheus.validation.promethusMetric'
    ),
    [PrometheusMonitoringSourceFieldNames.GROUP_NAME]: getString(
      'cv.monitoringSources.prometheus.validation.groupName'
    ),
    [PrometheusMonitoringSourceFieldNames.SERVICE_FILTER]: getString(
      'cv.monitoringSources.prometheus.validation.filterOnService'
    ),
    [PrometheusMonitoringSourceFieldNames.QUERY]: getString(
      'cv.monitoringSources.gco.manualInputQueryModal.validation.query'
    )
  }
 
  Iif (!values) {
    return requiredFieldErrors
  }
 
  if (values.isManualQuery) {
    delete requiredFieldErrors[PrometheusMonitoringSourceFieldNames.SERVICE_FILTER]
    delete requiredFieldErrors[PrometheusMonitoringSourceFieldNames.ENVIRONMENT_FILTER]
    delete requiredFieldErrors[PrometheusMonitoringSourceFieldNames.SERVICE_INSTANCE]
    delete requiredFieldErrors[PrometheusMonitoringSourceFieldNames.PROMETHEUS_METRIC]
  }
 
  for (const fieldName of Object.keys(requiredFieldErrors)) {
    switch (fieldName) {
      case PrometheusMonitoringSourceFieldNames.ENVIRONMENT_FILTER:
        if (values.envFilter?.length) delete requiredFieldErrors[fieldName]
        break
      case PrometheusMonitoringSourceFieldNames.SERVICE_FILTER:
        if (values.serviceFilter?.length) delete requiredFieldErrors[fieldName]
        break
      default:
        if ((values as any)[fieldName]) delete requiredFieldErrors[fieldName]
    }
  }
 
  requiredFieldErrors = validateGroupName(requiredFieldErrors, getString, values.groupName)
  const duplicateNames = createdMetrics?.filter((metricName, index) => {
    if (index === selectedMetricIndex) {
      return false
    }
    return metricName === values.metricName
  })
 
  const identifiers = createdMetrics.map(metricName => {
    const metricData = mappedMetrics?.get(metricName) as MapPrometheusQueryToService
    return metricData?.identifier
  })
 
  const duplicateIdentifier = identifiers?.filter((identifier, index) => {
    if (index === selectedMetricIndex) {
      return false
    }
    return identifier === values.identifier
  })
 
  if (values.identifier && duplicateIdentifier.length) {
    requiredFieldErrors[PrometheusMonitoringSourceFieldNames.METRIC_IDENTIFIER] = getString(
      'cv.monitoringSources.prometheus.validation.metricIdentifierUnique'
    )
  }
 
  Iif (values.metricName && duplicateNames.length) {
    requiredFieldErrors[PrometheusMonitoringSourceFieldNames.METRIC_NAME] = getString(
      'cv.monitoringSources.prometheus.validation.metricNameUnique'
    )
  }
 
  Iif (
    !requiredFieldErrors[PrometheusMonitoringSourceFieldNames.QUERY] &&
    isNumber(values.recordCount) &&
    values.recordCount > 1
  ) {
    requiredFieldErrors[PrometheusMonitoringSourceFieldNames.QUERY] = getString(
      'cv.monitoringSources.prometheus.validation.recordCount'
    )
  }
 
  requiredFieldErrors = validateAssginComponent(values, { ...requiredFieldErrors }, getString)
 
  return requiredFieldErrors
}
 
const validateGroupName = (
  requiredFieldErrors: { [x: string]: string },
  getString: UseStringsReturn['getString'],
  groupName?: SelectOption
): { [x: string]: string } => {
  const _requiredFieldErrors = clone(requiredFieldErrors)
  if (!groupName || (!groupName?.label && !groupName?.value)) {
    _requiredFieldErrors[PrometheusMonitoringSourceFieldNames.GROUP_NAME] = getString(
      'cv.monitoringSources.prometheus.validation.groupName'
    )
  }
  return _requiredFieldErrors
}
 
export function initializePrometheusGroupNames(
  mappedMetrics: Map<string, MapPrometheusQueryToService>,
  getString: UseStringsReturn['getString']
): SelectOption[] {
  const groupNames = Array.from(mappedMetrics?.entries())
    .map(metric => {
      const { groupName } = metric?.[1] || {}
      return groupName || null
    })
    .filter(groupItem => groupItem !== null) as SelectOption[]
  return [{ label: getString('cv.addNew'), value: '' }, ...groupNames]
}
 
export function transformLabelToPrometheusFilter(options?: MultiSelectOption[]): PrometheusFilter[] {
  const filters: PrometheusFilter[] = []
  if (!options?.length) {
    return filters
  }
 
  options.forEach(option => {
    const labelValue = option.label.split(':')
    filters.push({ labelName: labelValue[0], labelValue: labelValue[1] || labelValue[0] })
  })
 
  return filters
}
 
function generateMultiSelectOptionListFromPrometheusFilter(filters?: PrometheusFilter[]): MultiSelectOption[] {
  if (!filters?.length) {
    return []
  }
 
  const options: MultiSelectOption[] = []
  for (const filter of filters) {
    Eif (filter?.labelName && filter.labelValue) {
      options.push({ label: `${filter.labelName}:${filter.labelValue}`, value: filter.labelName })
    }
  }
 
  return options
}
 
export function transformPrometheusHealthSourceToSetupSource(
  sourceData: any,
  getString: (key: keyof StringsMap, vars?: Record<string, any> | undefined) => string
): PrometheusSetupSource {
  const healthSource: UpdatedHealthSource = sourceData?.healthSourceList?.find(
    (source: UpdatedHealthSource) => source.name === sourceData.healthSourceName
  )
 
  if (!healthSource) {
    return {
      isEdit: false,
      healthSourceIdentifier: sourceData.healthSourceIdentifier,
      mappedServicesAndEnvs: new Map([
        [
          getString('cv.monitoringSources.prometheus.prometheusMetric'),
          {
            metricName: getString('cv.monitoringSources.prometheus.prometheusMetric'),
            isManualQuery: false,
            query: '',
            identifier: 'prometheus_metric'
          }
        ]
      ]),
      healthSourceName: sourceData.healthSourceName,
      connectorRef: sourceData.connectorRef,
      product: { label: PrometheusProductNames.APM, value: PrometheusProductNames.APM }
    }
  }
 
  const setupSource: PrometheusSetupSource = {
    isEdit: sourceData.isEdit,
    mappedServicesAndEnvs: new Map(),
    healthSourceIdentifier: sourceData.healthSourceIdentifier,
    healthSourceName: sourceData.healthSourceName,
    product: sourceData.product,
    connectorRef: sourceData.connectorRef
  }
 
  for (const metricDefinition of (healthSource?.spec as PrometheusHealthSourceSpec)?.metricDefinitions || []) {
    Eif (metricDefinition?.metricName) {
      setupSource.mappedServicesAndEnvs.set(metricDefinition.metricName, {
        identifier: metricDefinition.identifier,
        metricName: metricDefinition.metricName,
        prometheusMetric: metricDefinition.prometheusMetric,
        query: metricDefinition.query || '',
        isManualQuery: metricDefinition.isManualQuery || false,
        serviceFilter: generateMultiSelectOptionListFromPrometheusFilter(metricDefinition.serviceFilter),
        envFilter: generateMultiSelectOptionListFromPrometheusFilter(metricDefinition.envFilter),
        additionalFilter: generateMultiSelectOptionListFromPrometheusFilter(metricDefinition.additionalFilters),
        aggregator: metricDefinition.aggregation,
        riskCategory:
          metricDefinition?.analysis?.riskProfile?.category && metricDefinition?.analysis?.riskProfile?.metricType
            ? `${metricDefinition?.analysis?.riskProfile?.category}/${metricDefinition?.analysis?.riskProfile?.metricType}`
            : '',
        serviceInstance: metricDefinition?.analysis?.deploymentVerification?.serviceInstanceFieldName,
        lowerBaselineDeviation:
          metricDefinition?.analysis?.riskProfile?.thresholdTypes?.includes('ACT_WHEN_LOWER') || false,
        higherBaselineDeviation:
          metricDefinition?.analysis?.riskProfile?.thresholdTypes?.includes('ACT_WHEN_HIGHER') || false,
        groupName: { label: metricDefinition.groupName || '', value: metricDefinition.groupName || '' },
        continuousVerification: metricDefinition?.analysis?.deploymentVerification?.enabled,
        healthScore: metricDefinition?.analysis?.liveMonitoring?.enabled,
        sli: metricDefinition.sli?.enabled
      })
    }
  }
 
  return setupSource
}
 
export function transformPrometheusSetupSourceToHealthSource(setupSource: PrometheusSetupSource): UpdatedHealthSource {
  const dsConfig: UpdatedHealthSource = {
    type: HealthSourceTypes.Prometheus as UpdatedHealthSource['type'],
    identifier: setupSource.healthSourceIdentifier,
    name: setupSource.healthSourceName,
    spec: {
      connectorRef: setupSource?.connectorRef,
      feature: PrometheusProductNames.APM,
      metricDefinitions: []
    }
  }
 
  for (const entry of setupSource.mappedServicesAndEnvs.entries()) {
    const {
      envFilter,
      metricName,
      identifier,
      groupName,
      prometheusMetric,
      serviceFilter,
      serviceInstance,
      isManualQuery,
      query,
      aggregator,
      additionalFilter,
      riskCategory,
      lowerBaselineDeviation,
      higherBaselineDeviation,
      sli,
      continuousVerification,
      healthScore
    }: MapPrometheusQueryToService = entry[1]
 
    Iif (!groupName || !metricName) {
      continue
    }
 
    Iif (!isManualQuery && (!prometheusMetric || !envFilter || !serviceFilter)) {
      continue
    }
 
    const [category, metricType] = riskCategory?.split('/') || []
    const thresholdTypes: TimeSeriesMetricDefinition['thresholdType'][] = []
    if (lowerBaselineDeviation) {
      thresholdTypes.push('ACT_WHEN_LOWER')
    }
    if (higherBaselineDeviation) {
      thresholdTypes.push('ACT_WHEN_HIGHER')
    }
 
    ;(dsConfig.spec as any).metricDefinitions.push({
      prometheusMetric,
      metricName,
      identifier,
      serviceFilter: transformLabelToPrometheusFilter(serviceFilter),
      isManualQuery,
      query,
      envFilter: transformLabelToPrometheusFilter(envFilter),
      additionalFilters: transformLabelToPrometheusFilter(additionalFilter),
      aggregation: aggregator,
      groupName: groupName.value as string,
      sli: { enabled: Boolean(sli) },
      analysis: {
        riskProfile: {
          category: category as RiskProfileCatgory,
          metricType: metricType,
          thresholdTypes
        },
        liveMonitoring: { enabled: Boolean(healthScore) },
        deploymentVerification: { enabled: Boolean(continuousVerification), serviceInstanceFieldName: serviceInstance }
      }
    })
  }
 
  return dsConfig
}