Przeglądaj źródła

finishing touches

Feroze Mohideen 2 lat temu
rodzic
commit
fdc160cca3

+ 23 - 15
dashboard/src/components/Selector.tsx

@@ -1,6 +1,7 @@
 import React, { Component } from "react";
 import styled from "styled-components";
 import { Context } from "shared/Context";
+import Loading from "./Loading";
 
 export type SelectorPropsType<T> = {
   activeValue: T;
@@ -18,6 +19,7 @@ export type SelectorPropsType<T> = {
   placeholder?: string;
   scrollBuffer?: boolean;
   disableTooltip?: boolean;
+  isLoading?: boolean;
 };
 
 type StateType = {};
@@ -157,7 +159,7 @@ export default class Selector<T> extends Component<SelectorPropsType<T>, StateTy
   };
 
   render() {
-    let { activeValue } = this.props;
+    let { activeValue, isLoading } = this.props;
 
     return (
       <StyledSelector width={this.props.width}>
@@ -178,17 +180,23 @@ export default class Selector<T> extends Component<SelectorPropsType<T>, StateTy
           onMouseEnter={() => this.setState({ showTooltip: true })}
           onMouseLeave={() => this.setState({ showTooltip: false })}
         >
-          <Flex>
-            {this.renderIcon()}
-            <TextWrap>
-              {activeValue
-                ? activeValue === ""
-                  ? "All"
-                  : this.getLabel(activeValue)
-                : this.props.placeholder}
-            </TextWrap>
-          </Flex>
-          <i className="material-icons">arrow_drop_down</i>
+          {isLoading ?
+            <Loading />
+            :
+            <>
+              <Flex>
+                {this.renderIcon()}
+                <TextWrap>
+                  {activeValue
+                    ? activeValue === ""
+                      ? "All"
+                      : this.getLabel(activeValue)
+                    : this.props.placeholder}
+                </TextWrap>
+              </Flex>
+              <i className="material-icons">arrow_drop_down</i>
+            </>
+          }
         </MainSelector>
         {!this.props.disableTooltip && this.state.showTooltip && (
           <Tooltip>
@@ -328,7 +336,7 @@ const StyledSelector = styled.div<{ width: string }>`
   width: ${(props) => props.width};
 `;
 
-const MainSelector = styled.div<{ 
+const MainSelector = styled.div<{
   disabled?: boolean;
   expanded: boolean;
   width: string;
@@ -349,8 +357,8 @@ const MainSelector = styled.div<{
   background: ${props => props.expanded ? "#ffffff33" : props.theme.fg};
   :hover {
     background: ${props => props.expanded ? "#ffffff33" : (
-      props.disabled ? "#ffffff11" : "#ffffff22"
-    )};
+    props.disabled ? "#ffffff11" : "#ffffff22"
+  )};
   }
 
   > i {

+ 2 - 0
dashboard/src/components/form-components/SelectRow.tsx

@@ -16,6 +16,7 @@ type PropsType<T> = {
   doc?: string;
   disabled?: boolean;
   selectorProps?: Partial<SelectorPropsType<T>>;
+  isLoading?: boolean;
 };
 
 export default function SelectRow<T>(props: PropsType<T>) {
@@ -40,6 +41,7 @@ export default function SelectRow<T>(props: PropsType<T>) {
           width={props.width || "270px"}
           dropdownWidth={props.width}
           dropdownMaxHeight={props.dropdownMaxHeight}
+          isLoading={props.isLoading}
           {...(props.selectorProps || {})}
         />
       </SelectWrapper>

+ 92 - 342
dashboard/src/main/home/app-dashboard/expanded-app/metrics/MetricsChart.tsx

@@ -1,352 +1,116 @@
-import React, { useContext, useEffect, useState } from "react";
+import React, { useState } from "react";
 import ParentSize from "@visx/responsive/lib/components/ParentSize";
-import axios from "axios";
 import styled from "styled-components";
 
-import api from "shared/api";
-import { ChartTypeWithExtendedConfig } from "shared/types";
-import { Context } from "shared/Context";
-
 import AggregatedDataLegend from "../../../cluster-dashboard/expanded-chart/metrics/AggregatedDataLegend";
 import StatusCodeDataLegend from "./StatusCodeDataLegend";
 import AreaChart from "./AreaChart";
 import StackedAreaChart from "./StackedAreaChart";
 import CheckboxRow from "components/form-components/CheckboxRow";
 import Loading from "components/Loading";
-import { AvailableMetrics, GenericMetricResponse, NormalizedMetricsData, NormalizedNginxStatusMetricsData } from "../../../cluster-dashboard/expanded-chart/metrics/types";
-import { MetricNormalizer } from "./utils";
-
-export const resolutions: { [range: string]: string } = {
-    "1H": "1s",
-    "6H": "15s",
-    "1D": "15s",
-    "1M": "5h",
-};
-
-export const secondsBeforeNow: { [range: string]: number } = {
-    "1H": 60 * 60,
-    "6H": 60 * 60 * 6,
-    "1D": 60 * 60 * 24,
-    "1M": 60 * 60 * 24 * 30,
-};
+import { AggregatedMetric, Metric, NginxStatusMetric, isNginxMetric } from "./types";
 
 type PropsType = {
-    currentChart: ChartTypeWithExtendedConfig;
-    pods: any[];
-    selectedController: any;
-    selectedIngress: any;
-    selectedMetric: string;
-    selectedMetricLabel: string;
-    selectedPod: string;
-    selectedRange: string;
+  metric: Metric;
+  selectedRange: string;
+  isLoading: boolean;
 };
 
 const MetricsChart: React.FunctionComponent<PropsType> = ({
-    currentChart,
-    pods,
-    selectedController,
-    selectedIngress,
-    selectedMetric,
-    selectedMetricLabel,
-    selectedPod,
-    selectedRange,
+  metric,
+  selectedRange,
+  isLoading,
 }) => {
-    const [isAggregated, setIsAggregated] = useState<boolean>(false);
-    const [aggregatedData, setAggregatedData] = useState<
-        Record<string, NormalizedMetricsData[]>
-    >({});
-    const [data, setData] = useState<NormalizedMetricsData[]>([]);
-    const [areaData, setAreaData] = useState<NormalizedNginxStatusMetricsData[]>([]);
-    const [hpaData, setHpaData] = useState<NormalizedMetricsData[]>([]);
-    const [hpaEnabled, setHpaEnabled] = useState(false);
-    const [showHpaToggle, setShowHpaToggle] = useState(false);
-    const [isLoading, setIsLoading] = useState(0);
-
-    const { currentCluster, currentProject, setCurrentError } = useContext(
-        Context
-    );
-
-    const getMetrics = async () => {
-        if (selectedMetric == "nginx:status") {
-            getNginxMetrics();
-        } else {
-            getAppMetrics();
-        }
-    };
-
-    const getAppMetrics = async () => {
-        if (pods?.length == 0) {
-            return;
-        }
-
-        if (selectedMetric == "nginx:status") {
-            return;
-        }
-
-        try {
-            let shouldsum = selectedPod === "All";
-            let namespace = currentChart.namespace;
-
-            // calculate start and end range
-            const d = new Date();
-            const end = Math.round(d.getTime() / 1000);
-            const start = end - secondsBeforeNow[selectedRange];
-
-            let podNames = [] as string[];
-
-            if (selectedMetric == "nginx:errors") {
-                podNames = [selectedIngress?.name];
-                namespace = selectedIngress?.namespace || "default";
-                shouldsum = false;
-            }
-
-            let kind = selectedController?.kind
-            if (selectedMetric == "nginx:status") {
-                kind = "Ingress";
-            }
-
-            const serviceName: string = selectedController?.metadata.labels["app.kubernetes.io/name"]
-            const isHpaEnabled: boolean = currentChart?.config?.[serviceName]?.autoscaling?.enabled
-
-            setIsLoading((prev) => prev + 1);
-            setAggregatedData({});
-            setIsAggregated(shouldsum);
-            setShowHpaToggle(isHpaEnabled);
-            setHpaEnabled(isHpaEnabled);
-
-            const aggregatedMetricsRequest = api.getMetrics(
-                "<token>",
-                {
-                    metric: selectedMetric,
-                    shouldsum: false,
-                    kind: kind,
-                    name: selectedController?.metadata.name,
-                    namespace: namespace,
-                    startrange: start,
-                    endrange: end,
-                    resolution: resolutions[selectedRange],
-                    pods: [],
-                },
-                {
-                    id: currentProject.id,
-                    cluster_id: currentCluster.id,
-                }
-            );
-
-            let requests = [
-                aggregatedMetricsRequest,
-            ];
-
-            if (shouldsum && isHpaEnabled && ["cpu", "memory"].includes(selectedMetric)) {
-                let hpaMetricType = "cpu_hpa_threshold";
-                if (selectedMetric === "memory") {
-                    hpaMetricType = "memory_hpa_threshold";
-                }
-                const hpaMetricsRequest = api.getMetrics(
-                    "<token>",
-                    {
-                        metric: hpaMetricType,
-                        shouldsum: shouldsum,
-                        kind: kind,
-                        name: selectedController?.metadata.name,
-                        namespace: namespace,
-                        startrange: start,
-                        endrange: end,
-                        resolution: resolutions[selectedRange],
-                        pods: [],
-                    },
-                    {
-                        id: currentProject.id,
-                        cluster_id: currentCluster.id,
-                    }
-                );
-                requests.push(hpaMetricsRequest);
-            }
-
-            axios
-                .all(requests)
-                .then((responses) => {
-                    const allPodsRes = responses[0];
-                    const allPodsData: GenericMetricResponse[] = allPodsRes.data ?? [];
-                    const allPodsMetrics = allPodsData.flatMap((d) => d.results);
-                    const allPodsMetricsNormalized = new MetricNormalizer(
-                        [{ results: allPodsMetrics }],
-                        selectedMetric as AvailableMetrics,
-                    );
-                    const [data, allPodsAggregatedData] = allPodsMetricsNormalized.getAggregatedData()
-                    setData(data)
-                    setAggregatedData(allPodsAggregatedData);
-
-                    if (isHpaEnabled && ["cpu", "memory"].includes(selectedMetric)) {
-                        let hpaMetricType = "cpu_hpa_threshold"
-                        if (selectedMetric === "memory") {
-                            hpaMetricType = "memory_hpa_threshold"
-                        }
-                        const hpaRes = responses[1];
-                        if (!Array.isArray(hpaRes.data) || !hpaRes.data[0]?.results) {
-                            return;
-                        }
-                        const autoscalingMetrics = new MetricNormalizer(hpaRes.data, hpaMetricType as AvailableMetrics);
-                        setHpaData(autoscalingMetrics.getParsedData());
-                    }
-                })
-                .catch(error => {
-                    setCurrentError(JSON.stringify(error));
-                })
-        } catch (error) {
-            setCurrentError(JSON.stringify(error));
-        } finally {
-            setIsLoading((prev) => prev - 1);
-        }
-    };
-
-    const getNginxMetrics = async () => {
-        const name = selectedController?.metadata.name
-        if (name.length === undefined) {
-            return
-        }
-
-        if (selectedMetric != "nginx:status") {
-            return;
-        }
-
-        let requests = [];
-        const namespace = currentChart.namespace;
-        const kind = "Ingress";
-
-        // calculate start and end range
-        const d = new Date();
-        const end = Math.round(d.getTime() / 1000);
-        const start = end - secondsBeforeNow[selectedRange];
-
-        try {
-            setIsLoading((prev) => prev + 1);
-            const response = await api.getMetrics(
-                "<token>",
-                {
-                    metric: selectedMetric,
-                    shouldsum: false,
-                    kind: kind,
-                    name: selectedController?.metadata.name,
-                    namespace: namespace,
-                    startrange: start,
-                    endrange: end,
-                    resolution: resolutions[selectedRange],
-                    pods: [],
-                },
-                {
-                    id: currentProject.id,
-                    cluster_id: currentCluster.id,
-                }
-            );
-            const metrics = new MetricNormalizer(
-                response.data,
-                selectedMetric as AvailableMetrics
-            );
-
-            setAreaData(metrics.getNginxStatusData());
-        } catch (error) {
-            setCurrentError(JSON.stringify(error));
-        } finally {
-            setIsLoading((prev) => prev - 1);
-        }
+  const [showAutoscalingLine, setShowAutoscalingLine] = useState(false);
+  // TODO: fix the type-filtering here
+  const renderMetric = (metric: Metric) => {
+    if (isNginxMetric(metric)) {
+      return renderNginxMetric(metric);
     }
-
-    useEffect(() => {
-        if (selectedRange && selectedController) {
-            getNginxMetrics();
+    return renderAggregatedMetric(metric as AggregatedMetric);
+  }
+  const renderAggregatedMetric = (metric: AggregatedMetric) => {
+    if (metric.data.length === 0) {
+      return (
+        <Message>
+          No data available yet.
+        </Message>
+      )
+    }
+    return (
+      <>
+        {metric.hpaData.length > 0 &&
+          <CheckboxRow
+            toggle={() => setShowAutoscalingLine((prev: any) => !prev)}
+            checked={showAutoscalingLine}
+            label="Show Autoscaling Threshold"
+          />
         }
-    }, [
-        selectedRange,
-        selectedController,
-    ]);
+        <ParentSize>
+          {({ width, height }) => (
+            <AreaChart
+              dataKey={metric.label}
+              aggregatedData={metric.aggregatedData}
+              isAggregated={true}
+              data={metric.data}
+              hpaData={metric.hpaData}
+              hpaEnabled={showAutoscalingLine}
+              width={width}
+              height={height - 10}
+              resolution={selectedRange}
+              margin={{ top: 40, right: -40, bottom: 0, left: 50 }}
+            />
+          )}
+        </ParentSize>
+        <RowWrapper>
+          <AggregatedDataLegend data={metric.data} hideAvg={true} />
+        </RowWrapper>
+      </>
+    )
+  }
 
-    useEffect(() => {
-        if (selectedRange && selectedPod && selectedController) {
-            getAppMetrics();
-        }
-    }, [
-        selectedRange,
-        selectedPod,
-        selectedController,
-        selectedIngress,
-        pods,
-    ]);
+  const renderNginxMetric = (metric: NginxStatusMetric) => {
+    if (metric.areaData.length === 0) {
+      return (
+        <Message>
+          No data available yet.
+        </Message>
+      );
+    }
 
     return (
-        <StyledMetricsChart>
-            <MetricsHeader>
-                <Flex>
-                    <MetricSelector>
-                        <MetricsLabel>{selectedMetricLabel}</MetricsLabel>
-                    </MetricSelector>
-                </Flex>
-            </MetricsHeader>
-            {isLoading > 0 && <Loading />}
-            {(data.length === 0 && Object.keys(areaData).length === 0) && isLoading === 0 && (
-                <Message>
-                    No data available yet.
-                    <Highlight color={"#8590ff"} onClick={getMetrics}>
-                        <i className="material-icons">autorenew</i>
-                        Refresh
-                    </Highlight>
-                </Message>
-            )}
-            {data.length > 0 && isLoading === 0 && (
-                <>
-                    {showHpaToggle &&
-                        ["cpu", "memory"].includes(selectedMetric) && (
-                            <CheckboxRow
-                                toggle={() => setHpaEnabled((prev: any) => !prev)}
-                                checked={hpaEnabled}
-                                label="Show Autoscaling Threshold"
-                            />
-                        )}
-                    <ParentSize>
-                        {({ width, height }) => (
-                            <AreaChart
-                                dataKey={selectedMetricLabel}
-                                aggregatedData={aggregatedData}
-                                isAggregated={isAggregated}
-                                data={data}
-                                hpaData={hpaData}
-                                hpaEnabled={
-                                    hpaEnabled && ["cpu", "memory"].includes(selectedMetric)
-                                }
-                                width={width}
-                                height={height - 10}
-                                resolution={selectedRange}
-                                margin={{ top: 40, right: -40, bottom: 0, left: 50 }}
-                            />
-                        )}
-                    </ParentSize>
-                    <RowWrapper>
-                        <AggregatedDataLegend data={data} hideAvg={isAggregated} />
-                    </RowWrapper>
-                </>
-            )}
+      <>
+        <ParentSize>
+          {({ width, height }) => (
+            <StackedAreaChart
+              dataKey={metric.label}
+              data={metric.areaData}
+              width={width}
+              height={height - 10}
+              resolution={selectedRange}
+              margin={{ top: 40, right: -40, bottom: 0, left: 50 }}
+            />
+          )}
+        </ParentSize>
+        <RowWrapper>
+          <StatusCodeDataLegend />
+        </RowWrapper>
+      </>
+    )
+  }
 
-            {Object.keys(areaData).length > 0 && isLoading === 0 && (
-                <>
-                    <ParentSize>
-                        {({ width, height }) => (
-                            <StackedAreaChart
-                                dataKey={selectedMetricLabel}
-                                data={areaData}
-                                width={width}
-                                height={height - 10}
-                                resolution={selectedRange}
-                                margin={{ top: 40, right: -40, bottom: 0, left: 50 }}
-                            />
-                        )}
-                    </ParentSize>
-                    <RowWrapper>
-                        <StatusCodeDataLegend />
-                    </RowWrapper>
-                </>
-            )}
-        </StyledMetricsChart>
-    );
+  return (
+    <StyledMetricsChart>
+      <MetricsHeader>
+        <Flex>
+          <MetricSelector>
+            <MetricsLabel>{metric.label}</MetricsLabel>
+          </MetricSelector>
+        </Flex>
+      </MetricsHeader>
+      {isLoading ? <Loading /> : renderMetric(metric)}
+    </StyledMetricsChart>
+  );
 };
 
 export default MetricsChart;
@@ -356,20 +120,6 @@ const Flex = styled.div`
   align-items: center;
 `;
 
-const Highlight = styled.div`
-  display: flex;
-  align-items: center;
-  justify-content: center;
-  margin-left: 8px;
-  color: ${(props: { color: string }) => props.color};
-  cursor: pointer;
-
-  > i {
-    font-size: 20px;
-    margin-right: 3px;
-  }
-`;
-
 const Message = styled.div`
   display: flex;
   height: 100%;

+ 0 - 233
dashboard/src/main/home/app-dashboard/expanded-app/metrics/MetricsChart2.tsx

@@ -1,233 +0,0 @@
-import React, { useContext, useEffect, useState } from "react";
-import ParentSize from "@visx/responsive/lib/components/ParentSize";
-import axios from "axios";
-import styled from "styled-components";
-
-import api from "shared/api";
-import { ChartTypeWithExtendedConfig } from "shared/types";
-import { Context } from "shared/Context";
-
-import AggregatedDataLegend from "../../../cluster-dashboard/expanded-chart/metrics/AggregatedDataLegend";
-import StatusCodeDataLegend from "./StatusCodeDataLegend";
-import AreaChart from "./AreaChart";
-import StackedAreaChart from "./StackedAreaChart";
-import CheckboxRow from "components/form-components/CheckboxRow";
-import Loading from "components/Loading";
-import { AvailableMetrics, GenericMetricResponse, NormalizedMetricsData, NormalizedNginxStatusMetricsData } from "../../../cluster-dashboard/expanded-chart/metrics/types";
-import { MetricNormalizer } from "./utils";
-import { AggregatedMetric, Metric, NginxStatusMetric, isNginxMetric } from "./types";
-
-export const resolutions: { [range: string]: string } = {
-  "1H": "1s",
-  "6H": "15s",
-  "1D": "15s",
-  "1M": "5h",
-};
-
-export const secondsBeforeNow: { [range: string]: number } = {
-  "1H": 60 * 60,
-  "6H": 60 * 60 * 6,
-  "1D": 60 * 60 * 24,
-  "1M": 60 * 60 * 24 * 30,
-};
-
-type PropsType = {
-  metric: Metric;
-  selectedRange: string;
-};
-
-const MetricsChart2: React.FunctionComponent<PropsType> = ({
-  metric,
-  selectedRange,
-}) => {
-  const [showAutoscalingLine, setShowAutoscalingLine] = useState(false);
-  // TODO: fix the type-filtering here
-  const renderMetric = (metric: Metric) => {
-    if (isNginxMetric(metric)) {
-      return renderNginxMetric(metric);
-    }
-    return renderAggregatedMetric(metric as AggregatedMetric);
-  }
-  const renderAggregatedMetric = (metric: AggregatedMetric) => {
-    if (metric.data.length === 0) {
-      return (
-        <Message>
-          No data available yet.
-        </Message>
-      )
-    }
-    return (
-      <>
-        {metric.hpaData.length > 0 &&
-          <CheckboxRow
-            toggle={() => setShowAutoscalingLine((prev: any) => !prev)}
-            checked={showAutoscalingLine}
-            label="Show Autoscaling Threshold"
-          />
-        }
-        <ParentSize>
-          {({ width, height }) => (
-            <AreaChart
-              dataKey={metric.label}
-              aggregatedData={metric.aggregatedData}
-              isAggregated={true}
-              data={metric.data}
-              hpaData={metric.hpaData}
-              hpaEnabled={showAutoscalingLine}
-              width={width}
-              height={height - 10}
-              resolution={selectedRange}
-              margin={{ top: 40, right: -40, bottom: 0, left: 50 }}
-            />
-          )}
-        </ParentSize>
-        <RowWrapper>
-          <AggregatedDataLegend data={metric.data} hideAvg={true} />
-        </RowWrapper>
-      </>
-    )
-  }
-
-  const renderNginxMetric = (metric: NginxStatusMetric) => {
-    if (metric.areaData.length === 0) {
-      return (
-        <Message>
-          No data available yet.
-        </Message>
-      );
-    }
-
-    return (
-      <>
-        <ParentSize>
-          {({ width, height }) => (
-            <StackedAreaChart
-              dataKey={metric.label}
-              data={metric.areaData}
-              width={width}
-              height={height - 10}
-              resolution={selectedRange}
-              margin={{ top: 40, right: -40, bottom: 0, left: 50 }}
-            />
-          )}
-        </ParentSize>
-        <RowWrapper>
-          <StatusCodeDataLegend />
-        </RowWrapper>
-      </>
-    )
-  }
-
-  return (
-    <StyledMetricsChart>
-      <MetricsHeader>
-        <Flex>
-          <MetricSelector>
-            <MetricsLabel>{metric.label}</MetricsLabel>
-          </MetricSelector>
-        </Flex>
-      </MetricsHeader>
-      {renderMetric(metric)}
-    </StyledMetricsChart>
-  );
-};
-
-export default MetricsChart2;
-
-const Flex = styled.div`
-  display: flex;
-  align-items: center;
-`;
-
-const Highlight = styled.div`
-  display: flex;
-  align-items: center;
-  justify-content: center;
-  margin-left: 8px;
-  color: ${(props: { color: string }) => props.color};
-  cursor: pointer;
-
-  > i {
-    font-size: 20px;
-    margin-right: 3px;
-  }
-`;
-
-const Message = styled.div`
-  display: flex;
-  height: 100%;
-  width: calc(100% - 150px);
-  align-items: center;
-  justify-content: center;
-  margin-left: 75px;
-  text-align: center;
-  color: #ffffff44;
-  font-size: 13px;
-`;
-
-const MetricsHeader = styled.div`
-  width: 100%;
-  display: flex;
-  align-items: center;
-  overflow: visible;
-  justify-content: space-between;
-`;
-
-const MetricsLabel = styled.div`
-  white-space: nowrap;
-  text-overflow: ellipsis;
-  overflow: hidden;
-  max-width: 200px;
-`;
-
-const MetricSelector = styled.div`
-  font-size: 13px;
-  font-weight: 500;
-  position: relative;
-  color: #ffffff;
-  display: flex;
-  align-items: center;
-  cursor: pointer;
-  border-radius: 5px;
-  :hover {
-    > i {
-      background: #ffffff22;
-    }
-  }
-
-  > i {
-    border-radius: 20px;
-    font-size: 20px;
-    margin-left: 10px;
-  }
-`;
-
-const RowWrapper = styled.div`
-  width: 100%;
-  display: flex;
-  justify-content: flex-end;
-`;
-
-
-const StyledMetricsChart = styled.div`
-  width: 100%;
-  min-height: 240px;
-  height: calc(100vh - 700px);
-  display: flex;
-  flex-direction: column;
-  position: relative;
-  font-size: 13px;
-  animation: floatIn 0.3s;
-  animation-timing-function: ease-out;
-  animation-fill-mode: forwards;
-  @keyframes floatIn {
-    from {
-      opacity: 0;
-      transform: translateY(10px);
-    }
-    to {
-      opacity: 1;
-      transform: translateY(0px);
-    }
-  }
-`;

+ 103 - 197
dashboard/src/main/home/app-dashboard/expanded-app/metrics/MetricsSection.tsx

@@ -1,4 +1,4 @@
-import React, { useContext, useEffect, useMemo, useState } from "react";
+import React, { useContext, useEffect, useState } from "react";
 import styled from "styled-components";
 
 import api from "shared/api";
@@ -7,12 +7,13 @@ import { ChartType } from "shared/types";
 
 import TabSelector from "components/TabSelector";
 import SelectRow from "components/form-components/SelectRow";
-import MetricsChart from "./MetricsChart";
-import { getServiceNameFromControllerName, MetricNormalizer } from "./utils";
+import { getServiceNameFromControllerName, MetricNormalizer, resolutions, secondsBeforeNow } from "./utils";
 import { Metric, MetricType, NginxStatusMetric } from "./types";
 import { match } from "ts-pattern";
 import { AvailableMetrics, NormalizedMetricsData } from "main/home/cluster-dashboard/expanded-chart/metrics/types";
-import MetricsChart2 from "./MetricsChart2";
+import MetricsChart from "./MetricsChart";
+import { useQuery } from "@tanstack/react-query";
+import Loading from "components/Loading";
 
 type PropsType = {
   currentChart: ChartType;
@@ -20,73 +21,32 @@ type PropsType = {
   serviceName?: string;
 };
 
-export const resolutions: { [range: string]: string } = {
-  "1H": "1s",
-  "6H": "15s",
-  "1D": "15s",
-  "1M": "5h",
-};
-
-export const secondsBeforeNow: { [range: string]: number } = {
-  "1H": 60 * 60,
-  "6H": 60 * 60 * 6,
-  "1D": 60 * 60 * 24,
-  "1M": 60 * 60 * 24 * 30,
-};
-
 const MetricsSection: React.FunctionComponent<PropsType> = ({
   currentChart,
   appName,
   serviceName,
 }) => {
-  const [controllerOptions, setControllerOptions] = useState([]);
-  const [selectedController, setSelectedController] = useState<any>();
-  const [ingressOptions, setIngressOptions] = useState([]);
-  const [selectedIngress, setSelectedIngress] = useState(null);
+  const [selectedController, setSelectedController] = useState<any>(null);
   const [selectedRange, setSelectedRange] = useState("1H");
-  const [isLoading, setIsLoading] = useState(0);
-  const [metrics, setMetrics] = useState<Metric[]>([]);
 
-  const { currentCluster, currentProject, setCurrentError } = useContext(
+  const { currentCluster, currentProject } = useContext(
     Context
   );
 
-  const [, forceUpdate] = React.useReducer(x => x + 1, 0);
-
-  useEffect(() => {
-    if (currentChart?.chart?.metadata?.name === "ingress-nginx") {
-      setIsLoading((prev) => prev + 1);
-
-      api
-        .getNGINXIngresses(
-          "<token>",
-          {},
-          {
-            id: currentProject.id,
-            cluster_id: currentCluster.id,
-          }
-        )
-        .then((res) => {
-          const ingressOptions = res.data.map((ingress: any) => ({
-            value: ingress,
-            label: ingress.name,
-          }));
-          setIngressOptions(ingressOptions);
-          setSelectedIngress(ingressOptions[0]?.value);
-          // iterate through the controllers to get the list of pods
-        })
-        .catch((err) => {
-          setCurrentError(JSON.stringify(err));
-        })
-        .finally(() => {
-          setIsLoading((prev) => prev - 1);
-        });
-    }
-
-    setIsLoading((prev) => prev + 1);
-
-    api
-      .getChartControllers(
+  const { data: controllerOptions, isLoading: isControllerListLoading } = useQuery(
+    [
+      "getChartControllers",
+      currentProject?.id,
+      currentChart.name,
+      currentChart.namespace,
+      currentCluster?.id,
+      currentChart.version,
+    ],
+    async () => {
+      if (currentProject?.id == null || currentCluster?.id == null) {
+        return;
+      }
+      const res = await api.getChartControllers(
         "<token>",
         {},
         {
@@ -96,60 +56,53 @@ const MetricsSection: React.FunctionComponent<PropsType> = ({
           cluster_id: currentCluster.id,
           revision: currentChart.version,
         }
-      )
-      .then((res) => {
-        const controllerOptions = res.data.map((controller: any) => {
-          return { value: controller, label: getServiceNameFromControllerName(controller?.metadata?.name, appName) };
-        });
+      );
 
-        setControllerOptions(controllerOptions);
-        const controllerOption = controllerOptions.find(
-          (option: any) => option.label === serviceName
-        );
-        if (controllerOption) {
-          setSelectedController(controllerOption.value);
-        } else {
-          setSelectedController(controllerOptions[0]?.value);
-        }
-      })
-      .catch((err) => {
-        setCurrentError(JSON.stringify(err));
-        setControllerOptions([]);
-      })
-      .finally(() => {
-        setIsLoading((prev) => prev - 1);
+      const controllerOptions = res.data.map((controller: any) => {
+        return { value: controller, label: getServiceNameFromControllerName(controller?.metadata?.name, appName) };
       });
-  }, [currentChart, currentCluster, currentProject]);
-
-  useEffect(() => {
-    refreshMetrics();
-  }, [selectedController]);
 
-  const refreshMetrics = async () => {
-    if (currentProject?.id == null || currentCluster?.id == null) {
-      return;
+      return controllerOptions;
     }
-    const newMetrics = [] as Metric[];
-    const metricTypes: MetricType[] = ["cpu", "memory", "network", "nginx:status"];
+  );
+
+  const { data: metricsData, isLoading: isMetricsDataLoading, refetch } = useQuery(
+    [
+      "getMetrics",
+      currentProject?.id,
+      currentCluster?.id,
+      selectedController?.metadata?.name,
+      selectedRange,
+    ],
+    async () => {
+      if (currentProject?.id == null || currentCluster?.id == null) {
+        return;
+      }
+      const metrics = [] as Metric[];
+      const metricTypes: MetricType[] = ["cpu", "memory", "network"];
 
-    const serviceName: string = selectedController?.metadata.labels["app.kubernetes.io/name"]
-    const isHpaEnabled: boolean = currentChart?.config?.[serviceName]?.autoscaling?.enabled
+      const serviceName: string = selectedController?.metadata.labels["app.kubernetes.io/name"]
+      const isHpaEnabled: boolean = currentChart?.config?.[serviceName]?.autoscaling?.enabled
 
-    if (isHpaEnabled) {
-      metricTypes.push("hpa_replicas");
-    }
+      if (isHpaEnabled) {
+        metricTypes.push("hpa_replicas");
+      }
 
-    if (currentChart?.chart?.metadata?.name == "ingress-nginx") {
-      metricTypes.push("nginx:errors");
-    }
+      if (currentChart?.chart?.metadata?.name == "ingress-nginx") {
+        metricTypes.push("nginx:errors");
+      }
+
+      if (currentChart?.config?.[serviceName]?.ingress?.enabled) {
+        metricTypes.push("nginx:status")
+      }
 
-    const d = new Date();
-    const end = Math.round(d.getTime() / 1000);
-    const start = end - secondsBeforeNow[selectedRange];
+      const d = new Date();
+      const end = Math.round(d.getTime() / 1000);
+      const start = end - secondsBeforeNow[selectedRange];
+
+      for (const metricType of metricTypes) {
+        const kind = metricType === "nginx:status" ? "Ingress" : selectedController?.kind
 
-    for (const metricType of metricTypes) {
-      const kind = metricType === "nginx:status" ? "Ingress" : selectedController?.kind
-      try {
         const aggregatedMetricsResponse = await api.getMetrics(
           "<token>",
           {
@@ -175,15 +128,15 @@ const MetricsSection: React.FunctionComponent<PropsType> = ({
         if (metricType === "nginx:status") {
           const nginxMetric: NginxStatusMetric = {
             type: metricType,
-            label: "Nginx Status Codes",
+            label: "Throughput",
             areaData: metricsNormalizer.getNginxStatusData(),
           }
-          newMetrics.push(nginxMetric)
+          metrics.push(nginxMetric)
         } else {
           const [data, allPodsAggregatedData] = metricsNormalizer.getAggregatedData();
           const hpaData: NormalizedMetricsData[] = [];
 
-          if (isHpaEnabled && ["cpu", "memory"].includes(metricType)) {
+          if (isHpaEnabled) {
             let hpaMetricType = "cpu_hpa_threshold"
             if (metricType === "memory") {
               hpaMetricType = "memory_hpa_threshold"
@@ -243,38 +196,51 @@ const MetricsSection: React.FunctionComponent<PropsType> = ({
             }))
             .with("nginx:errors", () => ({
               type: metricType,
-              label: "Nginx Errors",
+              label: "5XX Error Percentage",
               data: data,
               aggregatedData: allPodsAggregatedData,
               hpaData,
             }))
             .exhaustive();
-          newMetrics.push(metric);
+          metrics.push(metric);
         }
-      } catch (err) {
-        console.log(err);
-      }
-    };
+      };
+      return metrics;
+    },
+    {
+      enabled: selectedController != null,
+    }
+  );
 
-    setMetrics(newMetrics);
-  }
+  useEffect(() => {
+    if (controllerOptions == null) {
+      return;
+    }
+    const controllerOption = controllerOptions.find(
+      (option: any) => option.label === serviceName
+    );
+    if (controllerOption) {
+      setSelectedController(controllerOption.value);
+    } else {
+      setSelectedController(controllerOptions[0]?.value);
+    }
+  }, [controllerOptions]);
 
-  const renderHpaChart = () => {
-    const serviceName: string = selectedController?.metadata.labels["app.kubernetes.io/name"]
-    const isHpaEnabled: boolean = currentChart?.config?.[serviceName]?.autoscaling?.enabled
-    return isHpaEnabled ? (
-      <MetricsChart
-        currentChart={currentChart}
-        selectedController={selectedController}
-        selectedIngress={selectedIngress}
-        selectedMetric="hpa_replicas"
-        selectedMetricLabel="Number of replicas"
-        selectedPod="All"
-        selectedRange={selectedRange}
-        pods={[]}
-      />
-    ) : null
-  };
+  const renderMetrics = () => {
+    if (metricsData == null) {
+      return <Loading />;
+    }
+    return metricsData.map((metric: Metric, i: number) => {
+      return (
+        <MetricsChart
+          key={i}
+          metric={metric}
+          selectedRange={selectedRange}
+          isLoading={isMetricsDataLoading}
+        />
+      );
+    })
+  }
 
   return (
     <StyledMetricsSection>
@@ -286,9 +252,10 @@ const MetricsSection: React.FunctionComponent<PropsType> = ({
             value={selectedController}
             setActiveValue={(x: any) => setSelectedController(x)}
             options={controllerOptions}
-            width="100%"
+            width="200px"
+            isLoading={isControllerListLoading}
           />
-          <Highlight color={"#7d7d81"} onClick={() => forceUpdate()}>
+          <Highlight color={"#7d7d81"} onClick={() => refetch()}>
             <i className="material-icons">autorenew</i>
           </Highlight>
         </Flex>
@@ -308,68 +275,7 @@ const MetricsSection: React.FunctionComponent<PropsType> = ({
           />
         </RangeWrapper>
       </MetricsHeader>
-      <MetricsChart
-        currentChart={currentChart}
-        selectedController={selectedController}
-        selectedIngress={selectedIngress}
-        selectedMetric="cpu"
-        selectedMetricLabel="CPU Utilization (vCPUs)"
-        selectedPod="All"
-        selectedRange={selectedRange}
-        pods={[]}
-      />
-      <MetricsChart
-        currentChart={currentChart}
-        selectedController={selectedController}
-        selectedIngress={selectedIngress}
-        selectedMetric="memory"
-        selectedMetricLabel="RAM Utilization (Mi)"
-        selectedPod="All"
-        selectedRange={selectedRange}
-        pods={[]}
-      />
-      <MetricsChart
-        currentChart={currentChart}
-        selectedController={selectedController}
-        selectedIngress={selectedIngress}
-        selectedMetric="network"
-        selectedMetricLabel="Network Received Bytes (Ki)"
-        selectedPod="All"
-        selectedRange={selectedRange}
-        pods={[]}
-      />
-      <MetricsChart
-        currentChart={currentChart}
-        selectedController={selectedController}
-        selectedIngress={selectedIngress}
-        selectedMetric="nginx:status"
-        selectedMetricLabel="Nginx Status Codes"
-        selectedPod="All"
-        selectedRange={selectedRange}
-        pods={[]}
-      />
-      {renderHpaChart()}
-      {currentChart?.chart?.metadata?.name == "ingress-nginx" && (
-        <MetricsChart
-          currentChart={currentChart}
-          selectedController={selectedController}
-          selectedIngress={selectedIngress}
-          selectedMetric="nginx:errors"
-          selectedMetricLabel="5XX Error Percentage"
-          selectedPod="All"
-          selectedRange={selectedRange}
-          pods={[]}
-        />
-      )}
-      {metrics.map((metric: Metric, i: number) => {
-        return (
-          <MetricsChart2
-            key={i}
-            metric={metric}
-            selectedRange={selectedRange}
-          />
-        );
-      })}
+      {renderMetrics()}
     </StyledMetricsSection>
   );
 };

+ 14 - 0
dashboard/src/main/home/app-dashboard/expanded-app/metrics/utils.ts

@@ -261,4 +261,18 @@ export class MetricNormalizer {
     }
 }
 
+export const resolutions: { [range: string]: string } = {
+    "1H": "1s",
+    "6H": "15s",
+    "1D": "15s",
+    "1M": "5h",
+};
+
+export const secondsBeforeNow: { [range: string]: number } = {
+    "1H": 60 * 60,
+    "6H": 60 * 60 * 6,
+    "1D": 60 * 60 * 24,
+    "1M": 60 * 60 * 24 * 30,
+};
+