2
0

Reports.js 9.4 KB

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