cloudCostReports.js 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  1. import * as React from "react";
  2. import Page from "./components/Page";
  3. import Header from "./components/Header";
  4. import IconButton from "@material-ui/core/IconButton";
  5. import RefreshIcon from "@material-ui/icons/Refresh";
  6. import { makeStyles } from "@material-ui/styles";
  7. import { Paper, Typography } from "@material-ui/core";
  8. import CircularProgress from "@material-ui/core/CircularProgress";
  9. import { get, find } from "lodash";
  10. import { useLocation, useHistory } from "react-router";
  11. import { checkCustomWindow, toVerboseTimeRange } from "./util";
  12. import CloudCostEditControls from "./cloudCost/controls/cloudCostEditControls";
  13. import Subtitle from "./components/Subtitle";
  14. import Warnings from "./components/Warnings";
  15. import CloudCostTopService from "./services/cloudCostTop";
  16. import {
  17. windowOptions,
  18. costMetricOptions,
  19. aggregationOptions,
  20. aggMap,
  21. } from "./cloudCost/tokens";
  22. import { currencyCodes } from "./constants/currencyCodes";
  23. import CloudCost from "./cloudCost/cloudCost";
  24. import { CloudCostDetails } from "./cloudCost/cloudCostDetails";
  25. const CloudCostReports = () => {
  26. const useStyles = makeStyles({
  27. reportHeader: {
  28. display: "flex",
  29. flexFlow: "row",
  30. padding: 24,
  31. },
  32. titles: {
  33. flexGrow: 1,
  34. },
  35. });
  36. const classes = useStyles();
  37. // Form state, which controls form elements, but not the report itself. On
  38. // certain actions, the form state may flow into the report state.
  39. const [title, setTitle] = React.useState(
  40. "Cumulative cost for last 7 days by account"
  41. );
  42. const [window, setWindow] = React.useState(windowOptions[0].value);
  43. const [aggregateBy, setAggregateBy] = React.useState(
  44. aggregationOptions[0].value
  45. );
  46. const [costMetric, setCostMetric] = React.useState(
  47. costMetricOptions[0].value
  48. );
  49. const [filters, setFilters] = React.useState([]);
  50. const [currency, setCurrency] = React.useState("USD");
  51. const [selectedProviderId, setSelectedProviderId] = React.useState("");
  52. const [selectedItemName, setselectedItemName] = React.useState("");
  53. const sampleData = aggregateBy.includes("item");
  54. // page and settings state
  55. const [init, setInit] = React.useState(false);
  56. const [fetch, setFetch] = React.useState(false);
  57. const [loading, setLoading] = React.useState(true);
  58. const [errors, setErrors] = React.useState([]);
  59. // data
  60. const [cloudCostData, setCloudCostData] = React.useState([]);
  61. function generateTitle({ window, aggregateBy, costMetric }) {
  62. let windowName = get(find(windowOptions, { value: window }), "name", "");
  63. if (windowName === "") {
  64. if (checkCustomWindow(window)) {
  65. windowName = toVerboseTimeRange(window);
  66. } else {
  67. console.warn(`unknown window: ${window}`);
  68. }
  69. }
  70. let aggregationName = get(
  71. find(aggregationOptions, { value: aggregateBy }),
  72. "name",
  73. ""
  74. ).toLowerCase();
  75. if (aggregationName === "") {
  76. console.warn(`unknown aggregation: ${aggregateBy}`);
  77. }
  78. let str = `Cumulative cost for ${windowName} by ${aggregationName}`;
  79. if (!costMetric) {
  80. str = `${str} amoritizedNetCost`;
  81. }
  82. return str;
  83. }
  84. // parse any context information from the URL
  85. const routerLocation = useLocation();
  86. const searchParams = new URLSearchParams(routerLocation.search);
  87. const routerHistory = useHistory();
  88. async function initialize() {
  89. setInit(true);
  90. }
  91. async function fetchData() {
  92. setLoading(true);
  93. setErrors([]);
  94. try {
  95. const resp = await CloudCostTopService.fetchCloudCostData(
  96. window,
  97. aggregateBy,
  98. costMetric,
  99. filters
  100. );
  101. if (resp) {
  102. setCloudCostData(resp);
  103. } else {
  104. if (resp.message && resp.message.indexOf("boundary error") >= 0) {
  105. let match = resp.message.match(/(ETL is \d+\.\d+% complete)/);
  106. let secondary = "Try again after ETL build is complete";
  107. if (match.length > 0) {
  108. secondary = `${match[1]}. ${secondary}`;
  109. }
  110. setErrors([
  111. {
  112. primary: "Data unavailable while ETL is building",
  113. secondary: secondary,
  114. },
  115. ]);
  116. }
  117. setCloudCostData([]);
  118. }
  119. } catch (err) {
  120. if (err.message.indexOf("404") === 0) {
  121. setErrors([
  122. {
  123. primary: "Failed to load report data",
  124. secondary:
  125. "Please update Kubecost to the latest version, then contact support if problems persist.",
  126. },
  127. ]);
  128. } else {
  129. let secondary =
  130. "Please contact Kubecost support with a bug report if problems persist.";
  131. if (err.message.length > 0) {
  132. secondary = err.message;
  133. }
  134. setErrors([
  135. {
  136. primary: "Failed to load report data",
  137. secondary: secondary,
  138. },
  139. ]);
  140. }
  141. setCloudCostData([]);
  142. }
  143. setLoading(false);
  144. }
  145. function drilldown(row) {
  146. if (aggregateBy.includes("item")) {
  147. try {
  148. setSelectedProviderId(row.providerID);
  149. setselectedItemName(row.labelName ?? row.name);
  150. } catch (e) {
  151. logger.error(e);
  152. }
  153. return;
  154. }
  155. const nameParts = row.name.split("/");
  156. const nextAgg = aggregateBy.includes("service") ? "item" : "service";
  157. const aggToString = [aggregateBy];
  158. const newFilters = aggToString.map((property, i) => {
  159. const value = nameParts[i];
  160. return {
  161. property,
  162. value,
  163. name: aggMap[property] || property,
  164. };
  165. });
  166. setFilters(newFilters);
  167. setAggregateBy(nextAgg);
  168. }
  169. React.useEffect(() => {
  170. setWindow(searchParams.get("window") || "7d");
  171. setAggregateBy(searchParams.get("agg") || "provider");
  172. setCostMetric(searchParams.get("costMetric") || "AmortizedNetCost");
  173. setCurrency(searchParams.get("currency") || "USD");
  174. }, [routerLocation]);
  175. // Initialize once, then fetch report each time setFetch(true) is called
  176. React.useEffect(() => {
  177. if (!init) {
  178. initialize();
  179. }
  180. if (init || fetch) {
  181. fetchData();
  182. }
  183. }, [init, fetch]);
  184. React.useEffect(() => {
  185. setFetch(!fetch);
  186. setTitle(generateTitle({ window, aggregateBy, costMetric }));
  187. }, [window, aggregateBy, costMetric, filters]);
  188. return (
  189. <Page active="cloud.html">
  190. <Header>
  191. <IconButton aria-label="refresh" onClick={() => setFetch(true)}>
  192. <RefreshIcon />
  193. </IconButton>
  194. </Header>
  195. {!loading && errors.length > 0 && (
  196. <div style={{ marginBottom: 20 }}>
  197. <Warnings warnings={errors} />
  198. </div>
  199. )}
  200. {init && (
  201. <Paper id="cloud-cost">
  202. <div className={classes.reportHeader}>
  203. <div className={classes.titles}>
  204. <Typography variant="h5">{title}</Typography>
  205. <Subtitle report={{ window, aggregateBy }} />
  206. </div>
  207. <CloudCostEditControls
  208. windowOptions={windowOptions}
  209. window={window}
  210. setWindow={(win) => {
  211. searchParams.set("window", win);
  212. routerHistory.push({
  213. search: `?${searchParams.toString()}`,
  214. });
  215. }}
  216. aggregationOptions={aggregationOptions}
  217. aggregateBy={aggregateBy}
  218. setAggregateBy={(agg) => {
  219. searchParams.set("agg", agg);
  220. routerHistory.push({
  221. search: `?${searchParams.toString()}`,
  222. });
  223. }}
  224. costMetricOptions={costMetricOptions}
  225. costMetric={costMetric}
  226. setCostMetric={(c) => {
  227. searchParams.set("costMetric", c);
  228. routerHistory.push({
  229. search: `?${searchParams.toString()}`,
  230. });
  231. }}
  232. title={title}
  233. // cumulativeData={cumulativeData}
  234. currency={currency}
  235. currencyOptions={currencyCodes}
  236. setCurrency={(curr) => {
  237. searchParams.set("currency", curr);
  238. routerHistory.push({
  239. search: `?${searchParams.toString()}`,
  240. });
  241. }}
  242. />
  243. </div>
  244. {loading && (
  245. <div style={{ display: "flex", justifyContent: "center" }}>
  246. <div style={{ paddingTop: 100, paddingBottom: 100 }}>
  247. <CircularProgress />
  248. </div>
  249. </div>
  250. )}
  251. {!loading && (
  252. <CloudCost
  253. cumulativeData={cloudCostData.tableRows}
  254. currency={currency}
  255. graphData={cloudCostData.graphData}
  256. totalData={cloudCostData.tableTotal}
  257. drilldown={drilldown}
  258. sampleData={sampleData}
  259. />
  260. )}
  261. {selectedProviderId && selectedItemName && (
  262. <CloudCostDetails
  263. onClose={() => {
  264. setSelectedProviderId("");
  265. setselectedItemName("");
  266. }}
  267. selectedProviderId={selectedProviderId}
  268. selectedItem={selectedItemName}
  269. agg={aggregateBy}
  270. filters={filters}
  271. costMetric={costMetric}
  272. window={window}
  273. currency={currency}
  274. />
  275. )}
  276. </Paper>
  277. )}
  278. </Page>
  279. );
  280. };
  281. export default React.memo(CloudCostReports);