Reports.js 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  1. import CircularProgress from "@material-ui/core/CircularProgress";
  2. import IconButton from "@material-ui/core/IconButton";
  3. import Paper from "@material-ui/core/Paper";
  4. import Typography from "@material-ui/core/Typography";
  5. import RefreshIcon from "@material-ui/icons/Refresh";
  6. import { makeStyles } from "@material-ui/styles";
  7. import {
  8. filter,
  9. find,
  10. forEach,
  11. get,
  12. isArray,
  13. sortBy,
  14. toArray,
  15. trim,
  16. } from "lodash";
  17. import React, { useEffect, useState } from "react";
  18. import ReactDOM from "react-dom";
  19. import { useLocation, useHistory } from "react-router";
  20. import AllocationReport from "./components/allocationReport";
  21. import Controls from "./components/Controls";
  22. import Header from "./components/Header";
  23. import Page from "./components/Page";
  24. import Footer from "./components/Footer";
  25. import Subtitle from "./components/Subtitle";
  26. import Warnings from "./components/Warnings";
  27. import AllocationService from "./services/allocation";
  28. import {
  29. checkCustomWindow,
  30. cumulativeToTotals,
  31. rangeToCumulative,
  32. toVerboseTimeRange,
  33. } from "./util";
  34. import { currencyCodes } from "./constants/currencyCodes";
  35. const windowOptions = [
  36. { name: "Today", value: "today" },
  37. { name: "Yesterday", value: "yesterday" },
  38. { name: "Last 24h", value: "24h" },
  39. { name: "Last 48h", value: "48h" },
  40. { name: "Week-to-date", value: "week" },
  41. { name: "Last week", value: "lastweek" },
  42. { name: "Last 7 days", value: "7d" },
  43. { name: "Last 14 days", value: "14d" },
  44. ];
  45. const aggregationOptions = [
  46. { name: "Cluster", value: "cluster" },
  47. { name: "Node", value: "node" },
  48. { name: "Namespace", value: "namespace" },
  49. { name: "Controller Kind", value: "controllerKind" },
  50. { name: "Controller", value: "controller" },
  51. { name: "DaemonSet", value: "daemonset" },
  52. { name: "Deployment", value: "deployment" },
  53. { name: "Job", value: "job" },
  54. { name: "Service", value: "service" },
  55. { name: "StatefulSet", value: "statefulset" },
  56. { name: "Pod", value: "pod" },
  57. { name: "Container", value: "container" },
  58. ];
  59. const accumulateOptions = [
  60. { name: "Entire window", value: true },
  61. { name: "Daily", value: false },
  62. ];
  63. const useStyles = makeStyles({
  64. reportHeader: {
  65. display: "flex",
  66. flexFlow: "row",
  67. padding: 24,
  68. },
  69. titles: {
  70. flexGrow: 1,
  71. },
  72. });
  73. // generateTitle generates a string title from a report object
  74. function generateTitle({ window, aggregateBy, accumulate }) {
  75. let windowName = get(find(windowOptions, { value: window }), "name", "");
  76. if (windowName === "") {
  77. if (checkCustomWindow(window)) {
  78. windowName = toVerboseTimeRange(window);
  79. } else {
  80. console.warn(`unknown window: ${window}`);
  81. }
  82. }
  83. let aggregationName = get(
  84. find(aggregationOptions, { value: aggregateBy }),
  85. "name",
  86. ""
  87. ).toLowerCase();
  88. if (aggregationName === "") {
  89. console.warn(`unknown aggregation: ${aggregateBy}`);
  90. }
  91. let str = `${windowName} by ${aggregationName}`;
  92. if (!accumulate) {
  93. str = `${str} daily`;
  94. }
  95. return str;
  96. }
  97. const ReportsPage = () => {
  98. const classes = useStyles();
  99. // Allocation data state
  100. const [allocationData, setAllocationData] = useState([]);
  101. const [cumulativeData, setCumulativeData] = useState({});
  102. const [totalData, setTotalData] = useState({});
  103. // When allocation data changes, create a cumulative version of it
  104. useEffect(() => {
  105. const cumulative = rangeToCumulative(allocationData, aggregateBy);
  106. setCumulativeData(toArray(cumulative));
  107. setTotalData(cumulativeToTotals(cumulative));
  108. }, [allocationData]);
  109. // Form state, which controls form elements, but not the report itself. On
  110. // certain actions, the form state may flow into the report state.
  111. const [window, setWindow] = useState(windowOptions[0].value);
  112. const [aggregateBy, setAggregateBy] = useState(aggregationOptions[0].value);
  113. const [accumulate, setAccumulate] = useState(accumulateOptions[0].value);
  114. const [currency, setCurrency] = useState("USD");
  115. // Report state, including current report and saved options
  116. const [title, setTitle] = useState("Last 7 days by namespace daily");
  117. // When parameters changes, fetch data. This should be the
  118. // only mechanism used to fetch data. Also generate a sensible title from the paramters.
  119. useEffect(() => {
  120. setFetch(true);
  121. setTitle(generateTitle({ window, aggregateBy, accumulate }));
  122. }, [window, aggregateBy, accumulate]);
  123. // page and settings state
  124. const [init, setInit] = useState(false);
  125. const [fetch, setFetch] = useState(false);
  126. const [loading, setLoading] = useState(true);
  127. const [errors, setErrors] = useState([]);
  128. // Initialize once, then fetch report each time setFetch(true) is called
  129. useEffect(() => {
  130. if (!init) {
  131. initialize();
  132. }
  133. if (init || fetch) {
  134. fetchData();
  135. }
  136. }, [init, fetch]);
  137. // parse any context information from the URL
  138. const routerLocation = useLocation();
  139. const searchParams = new URLSearchParams(routerLocation.search);
  140. const routerHistory = useHistory();
  141. useEffect(() => {
  142. setWindow(searchParams.get("window") || "7d");
  143. setAggregateBy(searchParams.get("agg") || "namespace");
  144. setAccumulate(searchParams.get("acc") === "true" || false);
  145. setCurrency(searchParams.get("currency") || "USD");
  146. }, [routerLocation]);
  147. async function initialize() {
  148. setInit(true);
  149. }
  150. async function fetchData() {
  151. setLoading(true);
  152. setErrors([]);
  153. try {
  154. const resp = await AllocationService.fetchAllocation(
  155. window,
  156. aggregateBy,
  157. { accumulate }
  158. );
  159. if (resp.data && resp.data.length > 0) {
  160. const allocationRange = resp.data;
  161. for (const i in allocationRange) {
  162. // update cluster aggregations to use clusterName/clusterId names
  163. allocationRange[i] = sortBy(allocationRange[i], (a) => a.totalCost);
  164. }
  165. setAllocationData(allocationRange);
  166. } else {
  167. if (resp.message && resp.message.indexOf("boundary error") >= 0) {
  168. let match = resp.message.match(/(ETL is \d+\.\d+% complete)/);
  169. let secondary = "Try again after ETL build is complete";
  170. if (match.length > 0) {
  171. secondary = `${match[1]}. ${secondary}`;
  172. }
  173. setErrors([
  174. {
  175. primary: "Data unavailable while ETL is building",
  176. secondary: secondary,
  177. },
  178. ]);
  179. }
  180. setAllocationData([]);
  181. }
  182. } catch (err) {
  183. if (err.message.indexOf("404") === 0) {
  184. setErrors([
  185. {
  186. primary: "Failed to load report data",
  187. secondary:
  188. "Please update OpenCost to the latest version, then open an Issue on GitHub if problems persist.",
  189. },
  190. ]);
  191. } else {
  192. let secondary =
  193. "Please open an Issue on GitHub if problems persist.";
  194. if (err.message.length > 0) {
  195. secondary = err.message;
  196. }
  197. setErrors([
  198. {
  199. primary: "Failed to load report data",
  200. secondary: secondary,
  201. },
  202. ]);
  203. }
  204. setAllocationData([]);
  205. }
  206. setLoading(false);
  207. setFetch(false);
  208. }
  209. return (
  210. <Page active="reports.html">
  211. <Header>
  212. <IconButton aria-label="refresh" onClick={() => setFetch(true)}>
  213. <RefreshIcon />
  214. </IconButton>
  215. </Header>
  216. {!loading && errors.length > 0 && (
  217. <div style={{ marginBottom: 20 }}>
  218. <Warnings warnings={errors} />
  219. </div>
  220. )}
  221. {init && (
  222. <Paper id="report">
  223. <div className={classes.reportHeader}>
  224. <div className={classes.titles}>
  225. <Typography variant="h5">{title}</Typography>
  226. <Subtitle report={{ window, aggregateBy, accumulate }} />
  227. </div>
  228. <Controls
  229. windowOptions={windowOptions}
  230. window={window}
  231. setWindow={(win) => {
  232. searchParams.set("window", win);
  233. routerHistory.push({
  234. search: `?${searchParams.toString()}`,
  235. });
  236. }}
  237. aggregationOptions={aggregationOptions}
  238. aggregateBy={aggregateBy}
  239. setAggregateBy={(agg) => {
  240. searchParams.set("agg", agg);
  241. routerHistory.push({
  242. search: `?${searchParams.toString()}`,
  243. });
  244. }}
  245. accumulateOptions={accumulateOptions}
  246. accumulate={accumulate}
  247. setAccumulate={(acc) => {
  248. searchParams.set("acc", acc);
  249. routerHistory.push({
  250. search: `?${searchParams.toString()}`,
  251. });
  252. }}
  253. title={title}
  254. cumulativeData={cumulativeData}
  255. currency={currency}
  256. currencyOptions={currencyCodes}
  257. setCurrency={(curr) => {
  258. searchParams.set("currency", curr);
  259. routerHistory.push({
  260. search: `?${searchParams.toString()}`,
  261. });
  262. }}
  263. />
  264. </div>
  265. {loading && (
  266. <div style={{ display: "flex", justifyContent: "center" }}>
  267. <div style={{ paddingTop: 100, paddingBottom: 100 }}>
  268. <CircularProgress />
  269. </div>
  270. </div>
  271. )}
  272. {!loading && (
  273. <AllocationReport
  274. allocationData={allocationData}
  275. cumulativeData={cumulativeData}
  276. totalData={totalData}
  277. currency={currency}
  278. />
  279. )}
  280. </Paper>
  281. )}
  282. <Footer/>
  283. </Page>
  284. );
  285. };
  286. export default React.memo(ReportsPage);