Reports.js 9.4 KB

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