useLastSeenPodStatus.ts 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. import { useContext, useEffect, useState } from "react";
  2. import api from "shared/api";
  3. import { Context } from "shared/Context";
  4. const useLastSeenPodStatus = ({
  5. podName,
  6. namespace,
  7. resource_type,
  8. }: {
  9. podName: string;
  10. namespace: string;
  11. resource_type: string;
  12. }) => {
  13. const [status, setCurrentStatus] = useState(null);
  14. const [isLoading, setIsLoading] = useState(true);
  15. const [hasError, setHasError] = useState(false);
  16. const { currentProject, currentCluster } = useContext(Context);
  17. const getPodStatus = (status: any) => {
  18. if (
  19. status?.phase === "Pending" &&
  20. status?.containerStatuses !== undefined
  21. ) {
  22. return status.containerStatuses[0].state?.waiting?.reason || "Pending";
  23. } else if (status?.phase === "Pending") {
  24. return "Pending";
  25. }
  26. if (status?.phase === "Failed") {
  27. return "failed";
  28. }
  29. if (status?.phase === "Running") {
  30. let collatedStatus = "running";
  31. status?.containerStatuses?.forEach((s: any) => {
  32. if (s.state?.waiting) {
  33. collatedStatus =
  34. s.state?.waiting?.reason === "CrashLoopBackOff"
  35. ? "failed"
  36. : "waiting";
  37. } else if (s.state?.terminated) {
  38. collatedStatus = "failed";
  39. }
  40. });
  41. return collatedStatus;
  42. }
  43. };
  44. const updatePods = async () => {
  45. try {
  46. const res = await api.getPodByName(
  47. "<token>",
  48. {},
  49. {
  50. project_id: currentProject.id,
  51. cluster_id: currentCluster.id,
  52. namespace: "default",
  53. name: podName,
  54. }
  55. );
  56. //console.log(getPodStatus(res.data.status));
  57. setCurrentStatus(getPodStatus(res.data.status));
  58. } catch (error) {
  59. if (error?.response?.status === 404) {
  60. setCurrentStatus("Deleted");
  61. } else {
  62. setHasError(true);
  63. }
  64. } finally {
  65. setIsLoading(false);
  66. }
  67. };
  68. useEffect(() => {
  69. if (resource_type?.toLowerCase() === "pod") {
  70. updatePods();
  71. }
  72. }, [podName, namespace, resource_type]);
  73. return {
  74. status,
  75. isLoading,
  76. hasError,
  77. };
  78. };
  79. export default useLastSeenPodStatus;