Selaa lähdekoodia

Merge branch 'belanger/agent-v3-integration' of https://github.com/porter-dev/porter into belanger/agent-v3-integration

Alexander Belanger 3 vuotta sitten
vanhempi
sitoutus
d53efb2c44

+ 7 - 1
dashboard/src/components/porter-form/PorterFormWrapper.tsx

@@ -3,6 +3,7 @@ import React, { useEffect, useState } from "react";
 import PorterForm from "./PorterForm";
 import PorterForm from "./PorterForm";
 import { InjectedProps, PorterFormData } from "./types";
 import { InjectedProps, PorterFormData } from "./types";
 import { PorterFormContextProvider } from "./PorterFormContextProvider";
 import { PorterFormContextProvider } from "./PorterFormContextProvider";
+import _ from "lodash";
 
 
 type PropsType = {
 type PropsType = {
   formData: any;
   formData: any;
@@ -25,6 +26,7 @@ type PropsType = {
   includeMetadata?: boolean;
   includeMetadata?: boolean;
   injectedProps?: InjectedProps;
   injectedProps?: InjectedProps;
   overrideCurrentTab?: string;
   overrideCurrentTab?: string;
+  onTabChange?: (newTab: string) => void;
 };
 };
 
 
 const PorterFormWrapper: React.FC<PropsType> = ({
 const PorterFormWrapper: React.FC<PropsType> = ({
@@ -48,6 +50,7 @@ const PorterFormWrapper: React.FC<PropsType> = ({
   includeMetadata,
   includeMetadata,
   injectedProps,
   injectedProps,
   overrideCurrentTab,
   overrideCurrentTab,
+  onTabChange = _.noop,
 }) => {
 }) => {
   const hashCode = (s: string) => {
   const hashCode = (s: string) => {
     return s?.split("").reduce(function (a, b) {
     return s?.split("").reduce(function (a, b) {
@@ -105,7 +108,10 @@ const PorterFormWrapper: React.FC<PropsType> = ({
           color={color}
           color={color}
           saveValuesStatus={saveValuesStatus}
           saveValuesStatus={saveValuesStatus}
           currentTab={currentTab}
           currentTab={currentTab}
-          setCurrentTab={setCurrentTab}
+          setCurrentTab={(newTab) => {
+            setCurrentTab(newTab);
+            onTabChange(newTab);
+          }}
           isLaunch={isLaunch}
           isLaunch={isLaunch}
           hideSpacer={hideBottomSpacer}
           hideSpacer={hideBottomSpacer}
           redirectTabAfterSave={redirectTabAfterSave}
           redirectTabAfterSave={redirectTabAfterSave}

+ 85 - 18
dashboard/src/main/home/cluster-dashboard/expanded-chart/ExpandedChart.tsx

@@ -38,9 +38,9 @@ type Props = {
 };
 };
 
 
 const getReadableDate = (s: string) => {
 const getReadableDate = (s: string) => {
-  let ts = new Date(s);
-  let date = ts.toLocaleDateString();
-  let time = ts.toLocaleTimeString([], {
+  const ts = new Date(s);
+  const date = ts.toLocaleDateString();
+  const time = ts.toLocaleTimeString([], {
     hour: "numeric",
     hour: "numeric",
     minute: "2-digit",
     minute: "2-digit",
   });
   });
@@ -72,12 +72,12 @@ const ExpandedChart: React.FC<Props> = (props) => {
   const [imageIsPlaceholder, setImageIsPlaceholer] = useState<boolean>(false);
   const [imageIsPlaceholder, setImageIsPlaceholer] = useState<boolean>(false);
   const [newestImage, setNewestImage] = useState<string>(null);
   const [newestImage, setNewestImage] = useState<string>(null);
   const [isLoadingChartData, setIsLoadingChartData] = useState<boolean>(true);
   const [isLoadingChartData, setIsLoadingChartData] = useState<boolean>(true);
-  const [showRepoTooltip, setShowRepoTooltip] = useState(false);
   const [isAuthorized] = useAuth();
   const [isAuthorized] = useAuth();
   const [fullScreenLogs, setFullScreenLogs] = useState<boolean>(false);
   const [fullScreenLogs, setFullScreenLogs] = useState<boolean>(false);
   const [isFullscreen, setIsFullscreen] = useState<boolean>(false);
   const [isFullscreen, setIsFullscreen] = useState<boolean>(false);
-  const [logData, setLogData] = useState<InitLogData>();
+  const [logData, setLogData] = useState<InitLogData>({});
   const [overrideCurrentTab, setOverrideCurrentTab] = useState("");
   const [overrideCurrentTab, setOverrideCurrentTab] = useState("");
+  const [isAgentInstalled, setIsAgentInstalled] = useState<boolean>(false);
 
 
   const {
   const {
     isStack,
     isStack,
@@ -180,7 +180,7 @@ const ExpandedChart: React.FC<Props> = (props) => {
     const wsConfig = {
     const wsConfig = {
       onmessage(evt: MessageEvent) {
       onmessage(evt: MessageEvent) {
         const event = JSON.parse(evt.data);
         const event = JSON.parse(evt.data);
-        let object = event.Object;
+        const object = event.Object;
         object.metadata.kind = event.Kind;
         object.metadata.kind = event.Kind;
 
 
         if (event.event_type != "UPDATE") {
         if (event.event_type != "UPDATE") {
@@ -248,11 +248,11 @@ const ExpandedChart: React.FC<Props> = (props) => {
       values = currentChart.config;
       values = currentChart.config;
     }
     }
 
 
-    for (let key in rawValues) {
+    for (const key in rawValues) {
       _.set(values, key, rawValues[key]);
       _.set(values, key, rawValues[key]);
     }
     }
 
 
-    let valuesYaml = yaml.dump({
+    const valuesYaml = yaml.dump({
       ...values,
       ...values,
     });
     });
 
 
@@ -315,7 +315,6 @@ const ExpandedChart: React.FC<Props> = (props) => {
 
 
     setSaveValueStatus("loading");
     setSaveValueStatus("loading");
 
 
-    // console.log("valuesYaml", valuesYaml);
     try {
     try {
       await api.upgradeChartValues(
       await api.upgradeChartValues(
         "<token>",
         "<token>",
@@ -366,9 +365,9 @@ const ExpandedChart: React.FC<Props> = (props) => {
   const handleUpgradeVersion = useCallback(
   const handleUpgradeVersion = useCallback(
     async (version: string, cb: () => void) => {
     async (version: string, cb: () => void) => {
       // convert current values to yaml
       // convert current values to yaml
-      let values = currentChart.config;
+      const values = currentChart.config;
 
 
-      let valuesYaml = yaml.dump({
+      const valuesYaml = yaml.dump({
         ...values,
         ...values,
       });
       });
 
 
@@ -400,7 +399,7 @@ const ExpandedChart: React.FC<Props> = (props) => {
 
 
         cb && cb();
         cb && cb();
       } catch (err) {
       } catch (err) {
-        let parsedErr = err?.response?.data?.error;
+        const parsedErr = err?.response?.data?.error;
 
 
         if (parsedErr) {
         if (parsedErr) {
           err = parsedErr;
           err = parsedErr;
@@ -420,17 +419,22 @@ const ExpandedChart: React.FC<Props> = (props) => {
   );
   );
 
 
   const renderTabContents = (currentTab: string) => {
   const renderTabContents = (currentTab: string) => {
-    let { setSidebar } = props;
-    let chart = currentChart;
-    // console.log("CONTROLLERS", controllers);
+    const { setSidebar } = props;
+    const chart = currentChart; // // Reset the logData when navigating to a different tab
+
     switch (currentTab) {
     switch (currentTab) {
       case "logs":
       case "logs":
+        if (!isAgentInstalled) {
+          return null;
+        }
+
         return (
         return (
           <LogsSection
           <LogsSection
             currentChart={chart}
             currentChart={chart}
             isFullscreen={isFullscreen}
             isFullscreen={isFullscreen}
             setIsFullscreen={setIsFullscreen}
             setIsFullscreen={setIsFullscreen}
             initData={logData}
             initData={logData}
+            setInitData={setLogData}
           />
           />
         );
         );
       case "metrics":
       case "metrics":
@@ -550,7 +554,10 @@ const ExpandedChart: React.FC<Props> = (props) => {
         currentChart.chart.metadata.name === "job")
         currentChart.chart.metadata.name === "job")
     ) {
     ) {
       leftTabOptions.push({ label: "Events", value: "events" });
       leftTabOptions.push({ label: "Events", value: "events" });
-      leftTabOptions.push({ label: "Logs", value: "logs" });
+
+      if (isAgentInstalled) {
+        leftTabOptions.push({ label: "Logs", value: "logs" });
+      }
     }
     }
     leftTabOptions.push({ label: "Status", value: "status" });
     leftTabOptions.push({ label: "Status", value: "status" });
 
 
@@ -581,7 +588,7 @@ const ExpandedChart: React.FC<Props> = (props) => {
 
 
     // Filter tabs if previewing an old revision or updating the chart version
     // Filter tabs if previewing an old revision or updating the chart version
     if (isPreview) {
     if (isPreview) {
-      let liveTabs = ["status", "events", "settings", "deploy", "metrics"];
+      const liveTabs = ["status", "events", "settings", "deploy", "metrics"];
       rightTabOptions = rightTabOptions.filter(
       rightTabOptions = rightTabOptions.filter(
         (tab: any) => !liveTabs.includes(tab.value)
         (tab: any) => !liveTabs.includes(tab.value)
       );
       );
@@ -700,6 +707,58 @@ const ExpandedChart: React.FC<Props> = (props) => {
     }
     }
   };
   };
 
 
+  // Check if porter agent is installed. If not installed hide the `Logs` component
+  useEffect(() => {
+    api
+      .detectPorterAgent(
+        "<token>",
+        {},
+        {
+          project_id: currentProject.id,
+          cluster_id: currentCluster.id,
+        }
+      )
+      .then(() => setIsAgentInstalled(true))
+      .catch((err) => {
+        setIsAgentInstalled(false);
+
+        if (err.status !== 404) {
+          setCurrentError(
+            "We could not detect the Porter agent installation status, please try again."
+          );
+        }
+      });
+  }, []);
+
+  useEffect(() => {
+    if (logData.revision) {
+      api
+        .getRevisions(
+          "<token>",
+          {},
+          {
+            id: currentProject.id,
+            namespace: props.currentChart.namespace,
+            cluster_id: currentCluster.id,
+            name: props.currentChart.name,
+          }
+        )
+        .then((res) => {
+          const chart = res.data?.find(
+            (revision: ChartType) =>
+              revision.version.toString() === logData.revision
+          );
+
+          setCurrentChart(chart ?? props.currentChart);
+        })
+        .catch(console.log);
+
+        return;
+    }
+
+    setCurrentChart(props.currentChart);
+  }, [logData, props.currentChart]);
+
   useEffect(() => {
   useEffect(() => {
     window.analytics?.track("Opened Chart", {
     window.analytics?.track("Opened Chart", {
       chart: currentChart.name,
       chart: currentChart.name,
@@ -726,7 +785,7 @@ const ExpandedChart: React.FC<Props> = (props) => {
   useEffect(() => {
   useEffect(() => {
     updateTabs();
     updateTabs();
     localStorage.setItem("devOpsMode", devOpsMode.toString());
     localStorage.setItem("devOpsMode", devOpsMode.toString());
-  }, [devOpsMode, currentChart?.form, isPreview]);
+  }, [devOpsMode, currentChart?.form, isPreview, isAgentInstalled]);
 
 
   useEffect((): any => {
   useEffect((): any => {
     let isSubscribed = true;
     let isSubscribed = true;
@@ -911,6 +970,14 @@ const ExpandedChart: React.FC<Props> = (props) => {
                               },
                               },
                             }}
                             }}
                             overrideCurrentTab={overrideCurrentTab}
                             overrideCurrentTab={overrideCurrentTab}
+                            onTabChange={
+                              (newTab) => {
+                                if (newTab !== "logs") {
+                                  setOverrideCurrentTab("");
+                                  setLogData({});
+                                }
+                              }
+                            }
                           />
                           />
                         </BodyWrapper>
                         </BodyWrapper>
                       )}
                       )}

+ 4 - 6
dashboard/src/main/home/cluster-dashboard/expanded-chart/RevisionSection.tsx

@@ -184,12 +184,10 @@ class RevisionSection extends Component<PropsType, StateType> {
   };
   };
 
 
   handleClickRevision = (revision: ChartType) => {
   handleClickRevision = (revision: ChartType) => {
-    let isCurrent = revision.version === this.state.maxVersion;
-    if (isCurrent) {
-      this.props.setRevision(revision, true);
-    } else {
-      this.props.setRevision(revision);
-    }
+    this.props.setRevision(
+      revision,
+      revision.version === this.state.maxVersion
+    );
   };
   };
 
 
   renderRevisionList = () => {
   renderRevisionList = () => {

+ 7 - 2
dashboard/src/main/home/cluster-dashboard/expanded-chart/events/EventList.tsx

@@ -237,10 +237,10 @@ const EventList: React.FC<Props> = ({ filters, setLogData }) => {
             </TableWrapper>
             </TableWrapper>
           ) : (
           ) : (
             <Placeholder>
             <Placeholder>
-              <div>
+              <NoResultsFoundWrapper>
                 <Title>No results found</Title>
                 <Title>No results found</Title>
                 There were no results found for this filter.
                 There were no results found for this filter.
-              </div>
+              </NoResultsFoundWrapper>
             </Placeholder>
             </Placeholder>
           )}
           )}
         </>
         </>
@@ -406,3 +406,8 @@ const StyledMonitorList = styled.div`
   border-radius: 5px;
   border-radius: 5px;
   border: 1px solid #aaaabb33;
   border: 1px solid #aaaabb33;
 `;
 `;
+
+const NoResultsFoundWrapper = styled(Flex)`
+  flex-direction: column;
+  justify-contents: center;
+`;

+ 3 - 1
dashboard/src/main/home/cluster-dashboard/expanded-chart/logs-section/LogsSection.tsx

@@ -32,6 +32,7 @@ type Props = {
   isFullscreen: boolean;
   isFullscreen: boolean;
   setIsFullscreen: (x: boolean) => void;
   setIsFullscreen: (x: boolean) => void;
   initData?: InitLogData;
   initData?: InitLogData;
+  setInitData: (initData: InitLogData) => void;
 };
 };
 
 
 const escapeRegExp = (str: string) => {
 const escapeRegExp = (str: string) => {
@@ -97,6 +98,7 @@ const LogsSection: React.FC<Props> = ({
   isFullscreen,
   isFullscreen,
   setIsFullscreen,
   setIsFullscreen,
   initData = {},
   initData = {},
+  setInitData,
 }) => {
 }) => {
   const scrollToBottomRef = useRef<HTMLDivElement | undefined>(undefined);
   const scrollToBottomRef = useRef<HTMLDivElement | undefined>(undefined);
   const { currentProject, currentCluster } = useContext(Context);
   const { currentProject, currentCluster } = useContext(Context);
@@ -108,7 +110,7 @@ const LogsSection: React.FC<Props> = ({
   const [searchText, setSearchText] = useState("");
   const [searchText, setSearchText] = useState("");
   const [enteredSearchText, setEnteredSearchText] = useState("");
   const [enteredSearchText, setEnteredSearchText] = useState("");
   const [selectedDate, setSelectedDate] = useState<Date | undefined>(
   const [selectedDate, setSelectedDate] = useState<Date | undefined>(
-    initData ? dayjs(initData.timestamp).toDate() : undefined
+    initData.timestamp ? dayjs(initData.timestamp).toDate() : undefined
   );
   );
 
 
   const { loading, logs, refresh, moveCursor, paginationInfo } = useLogs(
   const { loading, logs, refresh, moveCursor, paginationInfo } = useLogs(