فهرست منبع

rfac: move useLogs to separate file

Soham Parekh 3 سال پیش
والد
کامیت
fa753a1010

+ 9 - 18
dashboard/package-lock.json

@@ -15504,8 +15504,7 @@
     "@icons/material": {
       "version": "0.2.4",
       "resolved": "https://registry.npmjs.org/@icons/material/-/material-0.2.4.tgz",
-      "integrity": "sha512-QPcGmICAPbGLGb6F/yNf/KzKqvFx8z5qx3D1yFqVAjoFmXK35EgyW+cJ57Te3CNsmzblwtzakLGFqHPqrfb4Tw==",
-      "requires": {}
+      "integrity": "sha512-QPcGmICAPbGLGb6F/yNf/KzKqvFx8z5qx3D1yFqVAjoFmXK35EgyW+cJ57Te3CNsmzblwtzakLGFqHPqrfb4Tw=="
     },
     "@ironplans/api": {
       "version": "0.4.1",
@@ -15634,8 +15633,7 @@
     "@material-ui/types": {
       "version": "5.1.0",
       "resolved": "https://registry.npmjs.org/@material-ui/types/-/types-5.1.0.tgz",
-      "integrity": "sha512-7cqRjrY50b8QzRSYyhSpx4WRw2YuO0KKIGQEVk5J8uoz2BanawykgZGoWEqKm7pVIbzFDN0SpPcVV4IhOFkl8A==",
-      "requires": {}
+      "integrity": "sha512-7cqRjrY50b8QzRSYyhSpx4WRw2YuO0KKIGQEVk5J8uoz2BanawykgZGoWEqKm7pVIbzFDN0SpPcVV4IhOFkl8A=="
     },
     "@material-ui/utils": {
       "version": "4.11.3",
@@ -15934,8 +15932,7 @@
       "version": "7.2.1",
       "resolved": "https://registry.npmjs.org/@testing-library/user-event/-/user-event-7.2.1.tgz",
       "integrity": "sha512-oZ0Ib5I4Z2pUEcoo95cT1cr6slco9WY7yiPpG+RGNkj8YcYgJnM7pXmYmorNOReh8MIGcKSqXyeGjxnr8YiZbA==",
-      "dev": true,
-      "requires": {}
+      "dev": true
     },
     "@types/body-parser": {
       "version": "1.19.2",
@@ -17009,15 +17006,13 @@
       "version": "1.0.1",
       "resolved": "https://registry.npmjs.org/ajv-errors/-/ajv-errors-1.0.1.tgz",
       "integrity": "sha512-DCRfO/4nQ+89p/RK43i8Ezd41EqdGIU4ld7nGF8OQ14oc/we5rEntLCUa7+jrn3nn83BosfwZA0wb4pon2o8iQ==",
-      "dev": true,
-      "requires": {}
+      "dev": true
     },
     "ajv-keywords": {
       "version": "3.5.2",
       "resolved": "https://registry.npmjs.org/ajv-keywords/-/ajv-keywords-3.5.2.tgz",
       "integrity": "sha512-5p6WTN0DdTGVQk6VjcEju19IgaHudalcfabD7yhDGeA6bcQnmL+CpveLJq/3hvfwd1aof6L386Ougkx6RfyMIQ==",
-      "dev": true,
-      "requires": {}
+      "dev": true
     },
     "anser": {
       "version": "2.1.0",
@@ -17976,8 +17971,7 @@
     "cohere-sentry": {
       "version": "1.0.1",
       "resolved": "https://registry.npmjs.org/cohere-sentry/-/cohere-sentry-1.0.1.tgz",
-      "integrity": "sha512-OHdKcc8LED8X/JQKlMD0Zapb4rcOkPu0m11+okHouMDep1/MvyOG4JXcK4Mo3sabJT65yozc9Uo+nJfSWzaFcg==",
-      "requires": {}
+      "integrity": "sha512-OHdKcc8LED8X/JQKlMD0Zapb4rcOkPu0m11+okHouMDep1/MvyOG4JXcK4Mo3sabJT65yozc9Uo+nJfSWzaFcg=="
     },
     "collection-visit": {
       "version": "1.0.0",
@@ -20918,8 +20912,7 @@
     "markdown-to-jsx": {
       "version": "7.1.3",
       "resolved": "https://registry.npmjs.org/markdown-to-jsx/-/markdown-to-jsx-7.1.3.tgz",
-      "integrity": "sha512-jtQ6VyT7rMT5tPV0g2EJakEnXLiPksnvlYtwQsVVZ611JsWGN8bQ1tVSDX4s6JllfEH6wmsYxNjTUAMrPmNA8w==",
-      "requires": {}
+      "integrity": "sha512-jtQ6VyT7rMT5tPV0g2EJakEnXLiPksnvlYtwQsVVZ611JsWGN8bQ1tVSDX4s6JllfEH6wmsYxNjTUAMrPmNA8w=="
     },
     "material-colors": {
       "version": "1.2.6",
@@ -22324,8 +22317,7 @@
     "react-table": {
       "version": "7.7.0",
       "resolved": "https://registry.npmjs.org/react-table/-/react-table-7.7.0.tgz",
-      "integrity": "sha512-jBlj70iBwOTvvImsU9t01LjFjy4sXEtclBovl3mTiqjz23Reu0DKnRza4zlLtOPACx6j2/7MrQIthIK1Wi+LIA==",
-      "requires": {}
+      "integrity": "sha512-jBlj70iBwOTvvImsU9t01LjFjy4sXEtclBovl3mTiqjz23Reu0DKnRza4zlLtOPACx6j2/7MrQIthIK1Wi+LIA=="
     },
     "react-transition-group": {
       "version": "4.4.2",
@@ -25478,8 +25470,7 @@
       "version": "7.5.5",
       "resolved": "https://registry.npmjs.org/ws/-/ws-7.5.5.tgz",
       "integrity": "sha512-BAkMFcAzl8as1G/hArkxOxq3G7pjUqQ3gzYbLL0/5zNkph70e+lCoxBGnm6AW1+/aiNeV4fnKqZ8m4GZewmH2w==",
-      "dev": true,
-      "requires": {}
+      "dev": true
     },
     "xtend": {
       "version": "4.0.2",

+ 4 - 244
dashboard/src/main/home/cluster-dashboard/expanded-chart/status/Logs.tsx

@@ -1,40 +1,10 @@
-import React, {
-  Component,
-  useContext,
-  useEffect,
-  useMemo,
-  useRef,
-  useState,
-} from "react";
+import React, { useEffect, useRef, useState } from "react";
 import styled from "styled-components";
-import { Context } from "shared/Context";
-import * as Anser from "anser";
-import api from "shared/api";
-import { NewWebsocketOptions, useWebsockets } from "shared/hooks/useWebsockets";
+import Anser from "anser";
 import CommandLineIcon from "assets/command-line-icon";
 import ConnectToLogsInstructionModal from "./ConnectToLogsInstructionModal";
-
-const MAX_LOGS = 250;
-
-type SelectedPodType = {
-  spec: {
-    [key: string]: any;
-    containers: {
-      [key: string]: any;
-      name: string;
-    }[];
-  };
-  metadata: {
-    name: string;
-    namespace: string;
-    labels: {
-      [key: string]: string;
-    };
-  };
-  status: {
-    phase: string;
-  };
-};
+import { SelectedPodType } from "./types";
+import { useLogs } from "./useLogs";
 
 const LogsFC: React.FC<{
   selectedPod: SelectedPodType;
@@ -253,216 +223,6 @@ const LogsFC: React.FC<{
 
 export default LogsFC;
 
-const useLogs = (
-  currentPod: SelectedPodType,
-  scroll?: (smooth: boolean) => void
-) => {
-  const currentPodName = useRef<string>();
-
-  const { currentCluster, currentProject } = useContext(Context);
-  const [containers, setContainers] = useState<string[]>([]);
-  const [currentContainer, setCurrentContainer] = useState<string>("");
-  const [logs, setLogs] = useState<{
-    [key: string]: Anser.AnserJsonEntry[][];
-  }>({});
-
-  const [prevLogs, setPrevLogs] = useState<{
-    [key: string]: Anser.AnserJsonEntry[][];
-  }>({});
-
-  const {
-    newWebsocket,
-    openWebsocket,
-    closeAllWebsockets,
-    getWebsocket,
-    closeWebsocket,
-  } = useWebsockets();
-
-  const getSystemLogs = async () => {
-    const events = await api
-      .getPodEvents(
-        "<token>",
-        {},
-        {
-          name: currentPod?.metadata?.name,
-          namespace: currentPod?.metadata?.namespace,
-          cluster_id: currentCluster?.id,
-          id: currentProject?.id,
-        }
-      )
-      .then((res) => res.data);
-
-    let processedLogs = [] as Anser.AnserJsonEntry[][];
-
-    events.items.forEach((evt: any) => {
-      let ansiEvtType = evt.type == "Warning" ? "\u001b[31m" : "\u001b[32m";
-      let ansiLog = Anser.ansiToJson(
-        `${ansiEvtType}${evt.type}\u001b[0m \t \u001b[43m\u001b[34m\t${evt.reason} \u001b[0m \t ${evt.message}`
-      );
-      processedLogs.push(ansiLog);
-    });
-
-    // SET LOGS FOR SYSTEM
-    setLogs((prevState) => ({
-      ...prevState,
-      system: processedLogs,
-    }));
-  };
-
-  const getContainerPreviousLogs = async (containerName: string) => {
-    try {
-      const logs = await api
-        .getPreviousLogsForContainer<{ previous_logs: string[] }>(
-          "<token>",
-          {
-            container_name: containerName,
-          },
-          {
-            pod_name: currentPod?.metadata?.name,
-            namespace: currentPod?.metadata?.namespace,
-            cluster_id: currentCluster?.id,
-            project_id: currentProject?.id,
-          }
-        )
-        .then((res) => res.data);
-      // Process logs
-      const processedLogs: Anser.AnserJsonEntry[][] = logs.previous_logs.map(
-        (currentLog) => {
-          let ansiLog = Anser.ansiToJson(currentLog);
-          return ansiLog;
-        }
-      );
-
-      setPrevLogs((pl) => ({
-        ...pl,
-        [containerName]: processedLogs,
-      }));
-    } catch (error) {}
-  };
-
-  const setupWebsocket = (containerName: string, websocketKey: string) => {
-    if (!currentPod?.metadata?.name) return;
-
-    const endpoint = `/api/projects/${currentProject.id}/clusters/${currentCluster.id}/namespaces/${currentPod?.metadata?.namespace}/pod/${currentPod?.metadata?.name}/logs?container_name=${containerName}`;
-
-    const config: NewWebsocketOptions = {
-      onopen: () => {
-        console.log("Opened websocket:", websocketKey);
-      },
-      onmessage: (evt: MessageEvent) => {
-        let ansiLog = Anser.ansiToJson(evt.data);
-        setLogs((logs) => {
-          const tmpLogs = { ...logs };
-          let containerLogs = tmpLogs[containerName] || [];
-
-          containerLogs.push(ansiLog);
-          // this is technically not as efficient as things could be
-          // if there are performance issues, a deque can be used in place of a list
-          // for storing logs
-          if (containerLogs.length > MAX_LOGS) {
-            containerLogs.shift();
-          }
-          if (typeof scroll === "function") {
-            scroll(true);
-          }
-          return {
-            ...logs,
-            [containerName]: containerLogs,
-          };
-        });
-      },
-      onclose: () => {
-        console.log("Closed websocket:", websocketKey);
-      },
-    };
-
-    newWebsocket(websocketKey, endpoint, config);
-    openWebsocket(websocketKey);
-  };
-
-  const refresh = () => {
-    const websocketKey = `${currentPodName.current}-${currentContainer}-websocket`;
-    closeWebsocket(websocketKey);
-
-    setPrevLogs((prev) => ({ ...prev, [currentContainer]: [] }));
-    setLogs((prev) => ({ ...prev, [currentContainer]: [] }));
-
-    if (!Array.isArray(containers)) {
-      return;
-    }
-
-    if (currentContainer === "system") {
-      getSystemLogs();
-    } else {
-      getContainerPreviousLogs(currentContainer);
-      setupWebsocket(currentContainer, websocketKey);
-    }
-  };
-
-  useEffect(() => {
-    // console.log("Selected pod updated");
-    if (currentPod?.metadata?.name === currentPodName.current) {
-      return () => {};
-    }
-    currentPodName.current = currentPod?.metadata?.name;
-    const currentContainers =
-      currentPod?.spec?.containers?.map((container) => container?.name) || [];
-
-    setContainers(currentContainers);
-    setCurrentContainer(currentContainers[0]);
-  }, [currentPod]);
-
-  // Retrieve all previous logs for containers
-  useEffect(() => {
-    if (!Array.isArray(containers)) {
-      return;
-    }
-
-    closeAllWebsockets();
-
-    setPrevLogs({});
-    setLogs({});
-
-    getSystemLogs();
-    containers.forEach((containerName) => {
-      const websocketKey = `${currentPodName.current}-${containerName}-websocket`;
-
-      getContainerPreviousLogs(containerName);
-
-      if (!getWebsocket(websocketKey)) {
-        setupWebsocket(containerName, websocketKey);
-      }
-    });
-
-    return () => {
-      closeAllWebsockets();
-    };
-  }, [containers]);
-
-  useEffect(() => {
-    return () => {
-      closeAllWebsockets();
-    };
-  }, []);
-
-  const currentLogs = useMemo(() => {
-    return logs[currentContainer] || [];
-  }, [currentContainer, logs]);
-
-  const currentPreviousLogs = useMemo(() => {
-    return prevLogs[currentContainer] || [];
-  }, [currentContainer, prevLogs]);
-
-  return {
-    containers,
-    currentContainer,
-    setCurrentContainer,
-    logs: currentLogs,
-    previousLogs: currentPreviousLogs,
-    refresh,
-  };
-};
-
 const Highlight = styled.div`
   display: flex;
   align-items: center;

+ 19 - 0
dashboard/src/main/home/cluster-dashboard/expanded-chart/status/types.ts

@@ -0,0 +1,19 @@
+export type SelectedPodType = {
+  spec: {
+    [key: string]: any;
+    containers: {
+      [key: string]: any;
+      name: string;
+    }[];
+  };
+  metadata: {
+    name: string;
+    namespace: string;
+    labels: {
+      [key: string]: string;
+    };
+  };
+  status: {
+    phase: string;
+  };
+};

+ 218 - 0
dashboard/src/main/home/cluster-dashboard/expanded-chart/status/useLogs.ts

@@ -0,0 +1,218 @@
+import Anser from "anser";
+import { useContext, useEffect, useMemo, useRef, useState } from "react";
+import api from "shared/api";
+import { Context } from "shared/Context";
+import { useWebsockets, NewWebsocketOptions } from "shared/hooks/useWebsockets";
+import { SelectedPodType } from "./types";
+
+const MAX_LOGS = 250;
+
+export const useLogs = (
+  currentPod: SelectedPodType,
+  scroll?: (smooth: boolean) => void
+) => {
+  const currentPodName = useRef<string>();
+
+  const { currentCluster, currentProject } = useContext(Context);
+  const [containers, setContainers] = useState<string[]>([]);
+  const [currentContainer, setCurrentContainer] = useState<string>("");
+  const [logs, setLogs] = useState<{
+    [key: string]: Anser.AnserJsonEntry[][];
+  }>({});
+
+  const [prevLogs, setPrevLogs] = useState<{
+    [key: string]: Anser.AnserJsonEntry[][];
+  }>({});
+
+  const {
+    newWebsocket,
+    openWebsocket,
+    closeAllWebsockets,
+    getWebsocket,
+    closeWebsocket,
+  } = useWebsockets();
+
+  const getSystemLogs = async () => {
+    const events = await api
+      .getPodEvents(
+        "<token>",
+        {},
+        {
+          name: currentPod?.metadata?.name,
+          namespace: currentPod?.metadata?.namespace,
+          cluster_id: currentCluster?.id,
+          id: currentProject?.id,
+        }
+      )
+      .then((res) => res.data);
+
+    let processedLogs = [] as Anser.AnserJsonEntry[][];
+
+    events.items.forEach((evt: any) => {
+      let ansiEvtType = evt.type == "Warning" ? "\u001b[31m" : "\u001b[32m";
+      let ansiLog = Anser.ansiToJson(
+        `${ansiEvtType}${evt.type}\u001b[0m \t \u001b[43m\u001b[34m\t${evt.reason} \u001b[0m \t ${evt.message}`
+      );
+      processedLogs.push(ansiLog);
+    });
+
+    // SET LOGS FOR SYSTEM
+    setLogs((prevState) => ({
+      ...prevState,
+      system: processedLogs,
+    }));
+  };
+
+  const getContainerPreviousLogs = async (containerName: string) => {
+    try {
+      const logs = await api
+        .getPreviousLogsForContainer<{ previous_logs: string[] }>(
+          "<token>",
+          {
+            container_name: containerName,
+          },
+          {
+            pod_name: currentPod?.metadata?.name,
+            namespace: currentPod?.metadata?.namespace,
+            cluster_id: currentCluster?.id,
+            project_id: currentProject?.id,
+          }
+        )
+        .then((res) => res.data);
+      // Process logs
+      const processedLogs: Anser.AnserJsonEntry[][] = logs.previous_logs.map(
+        (currentLog) => {
+          let ansiLog = Anser.ansiToJson(currentLog);
+          return ansiLog;
+        }
+      );
+
+      setPrevLogs((pl) => ({
+        ...pl,
+        [containerName]: processedLogs,
+      }));
+    } catch (error) {}
+  };
+
+  const setupWebsocket = (containerName: string, websocketKey: string) => {
+    if (!currentPod?.metadata?.name) return;
+
+    const endpoint = `/api/projects/${currentProject.id}/clusters/${currentCluster.id}/namespaces/${currentPod?.metadata?.namespace}/pod/${currentPod?.metadata?.name}/logs?container_name=${containerName}`;
+
+    const config: NewWebsocketOptions = {
+      onopen: () => {
+        console.log("Opened websocket:", websocketKey);
+      },
+      onmessage: (evt: MessageEvent) => {
+        let ansiLog = Anser.ansiToJson(evt.data);
+        setLogs((logs) => {
+          const tmpLogs = { ...logs };
+          let containerLogs = tmpLogs[containerName] || [];
+
+          containerLogs.push(ansiLog);
+          // this is technically not as efficient as things could be
+          // if there are performance issues, a deque can be used in place of a list
+          // for storing logs
+          if (containerLogs.length > MAX_LOGS) {
+            containerLogs.shift();
+          }
+          if (typeof scroll === "function") {
+            scroll(true);
+          }
+          return {
+            ...logs,
+            [containerName]: containerLogs,
+          };
+        });
+      },
+      onclose: () => {
+        console.log("Closed websocket:", websocketKey);
+      },
+    };
+
+    newWebsocket(websocketKey, endpoint, config);
+    openWebsocket(websocketKey);
+  };
+
+  const refresh = () => {
+    const websocketKey = `${currentPodName.current}-${currentContainer}-websocket`;
+    closeWebsocket(websocketKey);
+
+    setPrevLogs((prev) => ({ ...prev, [currentContainer]: [] }));
+    setLogs((prev) => ({ ...prev, [currentContainer]: [] }));
+
+    if (!Array.isArray(containers)) {
+      return;
+    }
+
+    if (currentContainer === "system") {
+      getSystemLogs();
+    } else {
+      getContainerPreviousLogs(currentContainer);
+      setupWebsocket(currentContainer, websocketKey);
+    }
+  };
+
+  useEffect(() => {
+    // console.log("Selected pod updated");
+    if (currentPod?.metadata?.name === currentPodName.current) {
+      return () => {};
+    }
+    currentPodName.current = currentPod?.metadata?.name;
+    const currentContainers =
+      currentPod?.spec?.containers?.map((container) => container?.name) || [];
+
+    setContainers(currentContainers);
+    setCurrentContainer(currentContainers[0]);
+  }, [currentPod]);
+
+  // Retrieve all previous logs for containers
+  useEffect(() => {
+    if (!Array.isArray(containers)) {
+      return;
+    }
+
+    closeAllWebsockets();
+
+    setPrevLogs({});
+    setLogs({});
+
+    getSystemLogs();
+    containers.forEach((containerName) => {
+      const websocketKey = `${currentPodName.current}-${containerName}-websocket`;
+
+      getContainerPreviousLogs(containerName);
+
+      if (!getWebsocket(websocketKey)) {
+        setupWebsocket(containerName, websocketKey);
+      }
+    });
+
+    return () => {
+      closeAllWebsockets();
+    };
+  }, [containers]);
+
+  useEffect(() => {
+    return () => {
+      closeAllWebsockets();
+    };
+  }, []);
+
+  const currentLogs = useMemo(() => {
+    return logs[currentContainer] || [];
+  }, [currentContainer, logs]);
+
+  const currentPreviousLogs = useMemo(() => {
+    return prevLogs[currentContainer] || [];
+  }, [currentContainer, prevLogs]);
+
+  return {
+    containers,
+    currentContainer,
+    setCurrentContainer,
+    logs: currentLogs,
+    previousLogs: currentPreviousLogs,
+    refresh,
+  };
+};