Debian Codegraph @

install/freeipa-webui/src/pages/Hosts/Hosts.tsx

raw
1 import React, { useEffect, useState } from "react";
2 // PatternFly
3 import {
4 Button,
5 Content,
6 DropdownItem,
7 Flex,
8 FlexItem,
9 PageSection,
10 PaginationVariant,
11 ToolbarItemVariant,
12 } from "@patternfly/react-core";
13 import {
14 InnerScrollContainer,
15 OuterScrollContainer,
16 } from "@patternfly/react-table";
17 // Layouts
18 import TitleLayout from "src/components/layouts/TitleLayout";
19 import ToolbarLayout, {
20 ToolbarItem,
21 } from "src/components/layouts/ToolbarLayout";
22 import SearchInputLayout from "src/components/layouts/SearchInputLayout";
23 import SecondaryButton from "src/components/layouts/SecondaryButton";
24 import HelpTextWithIconLayout from "src/components/layouts/HelpTextWithIconLayout";
25 import KebabLayout from "src/components/layouts/KebabLayout";
26 import ModalWithFormLayout from "src/components/layouts/ModalWithFormLayout";
27 // Components
28 import BulkSelectorPrep from "src/components/BulkSelectorPrep";
29 import PaginationLayout from "src/components/layouts/PaginationLayout";
30 import ContextualHelpPanel from "src/components/ContextualHelpPanel/ContextualHelpPanel";
31 // Tables
32 import HostsTable from "./HostsTable";
33 // Modal
34 import AddHost from "src/components/modals/HostModals/AddHost";
35 import DeleteHosts from "src/components/modals/HostModals/DeleteHosts";
36 // Redux
37 import { useAppDispatch, useAppSelector } from "src/store/hooks";
38 // Data types
39 import { Host } from "src/utils/datatypes/globalDataTypes";
40 // Utils
41 import { API_VERSION_BACKUP, isHostSelectable } from "src/utils/utils";
42 // Hooks
43 import { addAlert } from "src/store/Global/alerts-slice";
44 import useUpdateRoute from "src/hooks/useUpdateRoute";
45 import useListPageSearchParams from "src/hooks/useListPageSearchParams";
46 // Errors
47 import { FetchBaseQueryError } from "@reduxjs/toolkit/query";
48 import { SerializedError } from "@reduxjs/toolkit";
49 import useApiError from "src/hooks/useApiError";
50 import GlobalErrors from "src/components/errors/GlobalErrors";
51 import ModalErrors from "src/components/errors/ModalErrors";
52 // RPC client
53 import { GenericPayload, useSearchEntriesMutation } from "../../services/rpc";
54 import {
55 useGettingHostQuery,
56 useAutoMemberRebuildHostsMutation,
57 } from "../../services/rpcHosts";
58
59 const Hosts = () => {
60 const dispatch = useAppDispatch();
61
62 // URL parameters: page number, page size, search value
63 const { page, setPage, perPage, setPerPage, searchValue, setSearchValue } =
64 useListPageSearchParams();
65
66 // Update current route data to Redux and highlight the current page in the Nav bar
67 const { browserTitle } = useUpdateRoute({ pathname: "hosts" });
68
69 // Set the page title to be shown in the browser tab
70 React.useEffect(() => {
71 document.title = browserTitle;
72 }, [browserTitle]);
73
74 // Define 'executeCommand' to execute simple commands (via Mutation)
75 const [executeAutoMemberRebuild] = useAutoMemberRebuildHostsMutation();
76
77 // Retrieve API version from environment data
78 const apiVersion = useAppSelector(
79 (state) => state.global.environment.api_version
80 ) as string;
81
82 // Initialize hosts list (Redux)
83 const [hostsList, setHostsList] = useState<Host[]>([]);
84
85 // Handle API calls errors
86 const globalErrors = useApiError([]);
87 const modalErrors = useApiError([]);
88
89 // Table comps
90 const [selectedPerPage, setSelectedPerPage] = useState<number>(0);
91 const [totalCount, setHostsTotalCount] = useState<number>(0);
92 const [searchDisabled, setSearchIsDisabled] = useState<boolean>(false);
93
94 const updateSelectedPerPage = (selected: number) => {
95 setSelectedPerPage(selected);
96 };
97 const updatePage = (newPage: number) => {
98 setPage(newPage);
99 };
100 const updatePerPage = (newSetPerPage: number) => {
101 setPerPage(newSetPerPage);
102 };
103
104 // 'Delete' button state
105 const [isDeleteButtonDisabled, setIsDeleteButtonDisabled] =
106 useState<boolean>(true);
107
108 const updateIsDeleteButtonDisabled = (value: boolean) => {
109 setIsDeleteButtonDisabled(value);
110 };
111
112 // If some entries have been deleted, restore the selectedHosts list
113 const [isDeletion, setIsDeletion] = useState(false);
114
115 const updateIsDeletion = (value: boolean) => {
116 setIsDeletion(value);
117 };
118
119 const updateShownHostsList = (newShownHostsList: Host[]) => {
120 setHostsList(newShownHostsList);
121 };
122
123 // Button disabled due to error
124 const [isDisabledDueError, setIsDisabledDueError] = useState<boolean>(false);
125
126 // Page indexes
127 const firstHostIdx = (page - 1) * perPage;
128 const lastHostIdx = page * perPage;
129
130 // Derived states - what we get from API
131 const hostDataResponse = useGettingHostQuery({
132 searchValue: searchValue,
133 sizeLimit: 0,
134 apiVersion: apiVersion || API_VERSION_BACKUP,
135 startIdx: firstHostIdx,
136 stopIdx: lastHostIdx,
137 } as GenericPayload);
138
139 const {
140 data: batchResponse,
141 isLoading: isBatchLoading,
142 error: batchError,
143 } = hostDataResponse;
144
145 // Handle data when the API call is finished
146 useEffect(() => {
147 if (hostDataResponse.isFetching) {
148 setShowTableRows(false);
149 // Reset selected users on refresh
150 setHostsTotalCount(0);
151 globalErrors.clear();
152 setIsDisabledDueError(false);
153 return;
154 }
155
156 // API response: Success
157 if (
158 hostDataResponse.isSuccess &&
159 hostDataResponse.data &&
160 batchResponse !== undefined
161 ) {
162 const hostsListResult = batchResponse.result.results;
163 const totalCount = batchResponse.result.totalCount;
164 const hostsListSize = batchResponse.result.count;
165 const hostsList: Host[] = [];
166
167 for (let i = 0; i < hostsListSize; i++) {
168 hostsList.push(hostsListResult[i].result);
169 }
170
171 setHostsList(hostsList);
172 setHostsTotalCount(totalCount);
173 // Show table elements
174 setShowTableRows(true);
175 }
176
177 // API response: Error
178 if (
179 !hostDataResponse.isLoading &&
180 hostDataResponse.isError &&
181 hostDataResponse.error !== undefined
182 ) {
183 // This normally happens when the user is not authorized to view the data
184 // So instead of adding an error, refresh page
185 window.location.reload();
186 }
187 }, [hostDataResponse]);
188
189 // Always refetch data when the component is loaded.
190 // This ensures the data is always up-to-date.
191 useEffect(() => {
192 hostDataResponse.refetch();
193 }, []);
194
195 // Refresh button handling
196 const refreshHostsData = () => {
197 // Hide table
198 setShowTableRows(false);
199
200 // Reset selected hosts on refresh
201 setHostsTotalCount(0);
202 clearSelectedHosts();
203
204 hostDataResponse.refetch();
205 };
206
207 const updateSearchValue = (value: string) => {
208 setSearchValue(value);
209 };
210
211 const [selectedHosts, setSelectedHostsList] = useState<Host[]>([]);
212 const clearSelectedHosts = () => {
213 const emptyList: Host[] = [];
214 setSelectedHostsList(emptyList);
215 };
216
217 const [retrieveHost] = useSearchEntriesMutation({});
218
219 // Issue a search using a specific search value
220 const submitSearchValue = () => {
221 setShowTableRows(false);
222 setHostsTotalCount(0);
223 setSearchIsDisabled(true);
224 retrieveHost({
225 searchValue: searchValue,
226 sizeLimit: 0,
227 apiVersion: apiVersion || API_VERSION_BACKUP,
228 startIdx: firstHostIdx,
229 stopIdx: lastHostIdx,
230 entryType: "host",
231 } as GenericPayload).then((result) => {
232 // Manage new response here
233 if ("data" in result) {
234 const searchError = result.data?.error as
235 | FetchBaseQueryError
236 | SerializedError;
237
238 if (searchError) {
239 // Error
240 let error: string | undefined = "";
241 if ("error" in searchError) {
242 error = searchError.error;
243 } else if ("message" in searchError) {
244 error = searchError.message;
245 }
246 dispatch(
247 addAlert({
248 name: "submit-search-value-error",
249 title: error || "Error when searching for hosts",
250 variant: "danger",
251 })
252 );
253 } else {
254 // Success
255 const hostsListResult = result.data?.result.results || [];
256 const hostsListSize = result.data?.result.count || 0;
257 const totalCount = result.data?.result.totalCount || 0;
258 const hostsList: Host[] = [];
259
260 for (let i = 0; i < hostsListSize; i++) {
261 hostsList.push(hostsListResult[i].result);
262 }
263
264 setHostsList(hostsList);
265 setHostsTotalCount(totalCount);
266 // Show table elements
267 setShowTableRows(true);
268 }
269 setSearchIsDisabled(false);
270 }
271 });
272 };
273
274 // Show table rows
275 const [showTableRows, setShowTableRows] = useState(!isBatchLoading);
276
277 const updateSelectedHosts = (hosts: Host[], isSelected: boolean) => {
278 let newSelectedHosts: Host[] = [];
279 if (isSelected) {
280 newSelectedHosts = JSON.parse(JSON.stringify(selectedHosts));
281 for (let i = 0; i < hosts.length; i++) {
282 if (
283 selectedHosts.find(
284 (selectedUser) => selectedUser.fqdn[0] === hosts[i].fqdn[0]
285 )
286 ) {
287 // Already in the list
288 continue;
289 }
290 // Add user to list
291 newSelectedHosts.push(hosts[i]);
292 }
293 } else {
294 // Remove host
295 for (let i = 0; i < selectedHosts.length; i++) {
296 let found = false;
297 for (let ii = 0; ii < hosts.length; ii++) {
298 if (selectedHosts[i].fqdn[0] === hosts[ii].fqdn[0]) {
299 found = true;
300 break;
301 }
302 }
303 if (!found) {
304 // Keep this valid selected entry
305 newSelectedHosts.push(selectedHosts[i]);
306 }
307 }
308 }
309 setSelectedHostsList(newSelectedHosts);
310 setIsDeleteButtonDisabled(newSelectedHosts.length === 0);
311 };
312
313 // - Helper method to set the selected users from the table
314 const setHostSelected = (host: Host, isSelecting = true) => {
315 if (isHostSelectable(host)) {
316 updateSelectedHosts([host], isSelecting);
317 }
318 };
319
320 // Show table rows only when data is fully retrieved
321 useEffect(() => {
322 if (showTableRows !== !isBatchLoading) {
323 setShowTableRows(!isBatchLoading);
324 }
325 }, [isBatchLoading]);
326
327 // Dropdown kebab
328 const [kebabIsOpen, setKebabIsOpen] = useState(false);
329
330 // [API call] 'Rebuild auto membership'
331 // TODO: Move this into a separate component
332 const onRebuildAutoMembership = () => {
333 // Task can potentially run for a very long time, give feed back that we
334 // at least started the task
335 dispatch(
336 addAlert({
337 name: "rebuild-automember-start",
338 title:
339 "Starting automember rebuild membership task (this may take a long " +
340 "time to complete) ...",
341 variant: "info",
342 })
343 );
344 executeAutoMemberRebuild(selectedHosts).then((result) => {
345 if ("data" in result) {
346 const automemberError = result.data?.error as
347 | FetchBaseQueryError
348 | SerializedError;
349
350 if (automemberError) {
351 // alert: error
352 let error: string | undefined = "";
353 if ("error" in automemberError) {
354 error = automemberError.error;
355 } else if ("message" in automemberError) {
356 error = automemberError.message;
357 }
358
359 dispatch(
360 addAlert({
361 name: "rebuild-automember-error",
362 title: error || "Error when rebuilding membership",
363 variant: "danger",
364 })
365 );
366 } else {
367 // alert: success
368 dispatch(
369 addAlert({
370 name: "rebuild-automember-success",
371 title: "Automember rebuild membership task completed",
372 variant: "success",
373 })
374 );
375 }
376 // Hide modal
377 setIsMembershipModalOpen(!isMembershipModalOpen);
378 }
379 });
380 };
381
382 // 'Rebuild auto membership' modal
383 const [isMembershipModalOpen, setIsMembershipModalOpen] = useState(false);
384
385 const membershipModalActions: JSX.Element[] = [
386 <Button
387 data-cy="modal-button-ok"
388 key="rebuild-auto-membership"
389 variant="primary"
390 onClick={onRebuildAutoMembership}
391 form="rebuild-auto-membership-modal"
392 >
393 OK
394 </Button>,
395 <Button
396 data-cy="modal-button-cancel"
397 key="cancel-rebuild-auto-membership"
398 variant="link"
399 onClick={() => setIsMembershipModalOpen(!isMembershipModalOpen)}
400 >
401 Cancel
402 </Button>,
403 ];
404
405 // 'Rebuild auto membership' modal fields: Confirmation question
406 const confirmationQuestion = [
407 {
408 id: "question-text",
409 pfComponent: (
410 <Content component="p">
411 <b>Warning</b> In case of a high number of users, hosts or groups, the
412 rebuild task may require high CPU usage. This can severely impact
413 server performance. Typically this only needs to be done once after
414 importing raw data into the server. Are you sure you want to rebuild
415 the auto memberships?
416 </Content>
417 ),
418 },
419 ];
420
421 const dropdownItems = [
422 <DropdownItem
423 data-cy="hosts-kebab-rebuild-auto-membership"
424 key="rebuild auto membership"
425 component="button"
426 onClick={() => setIsMembershipModalOpen(!isMembershipModalOpen)}
427 >
428 Rebuild auto membership
429 </DropdownItem>,
430 ];
431
432 const onKebabToggle = () => {
433 setKebabIsOpen(!kebabIsOpen);
434 };
435
436 const onFocus = () => {
437 const element = document.getElementById("main-dropdown-kebab");
438 element?.focus();
439 };
440
441 const onDropdownSelect = (
442 // eslint-disable-next-line @typescript-eslint/no-unused-vars
443 _event: React.MouseEvent<Element, MouseEvent> | undefined
444 ) => {
445 setKebabIsOpen(!kebabIsOpen);
446 onFocus();
447 };
448
449 // Modals functionality
450 const [showAddModal, setShowAddModal] = useState(false);
451 const [showDeleteModal, setShowDeleteModal] = useState(false);
452
453 const onAddClickHandler = () => {
454 setShowAddModal(true);
455 };
456 const onCloseAddModal = () => {
457 setShowAddModal(false);
458 };
459 const onAddModalToggle = () => {
460 setShowAddModal(!showAddModal);
461 };
462
463 const onDeleteHandler = () => {
464 setShowDeleteModal(true);
465 };
466 const onDeleteModalToggle = () => {
467 setShowDeleteModal(!showDeleteModal);
468 };
469
470 // Table-related shared functionality
471 // - Selectable checkboxes on table
472 const selectableHostsTable = hostsList.filter(isHostSelectable); // elements per Table
473
474 // Data wrappers
475 // - 'PaginationLayout'
476 const paginationData = {
477 page,
478 perPage,
479 updatePage,
480 updatePerPage,
481 updateSelectedPerPage,
482 updateShownElementsList: updateShownHostsList,
483 totalCount,
484 };
485
486 // - 'BulkSelectorPrep'
487 const hostsBulkSelectorData = {
488 selected: selectedHosts,
489 updateSelected: updateSelectedHosts,
490 selectableTable: selectableHostsTable,
491 nameAttr: "fqdn",
492 };
493
494 const buttonsData = {
495 updateIsDeleteButtonDisabled,
496 };
497
498 const selectedPerPageData = {
499 selectedPerPage,
500 updateSelectedPerPage,
501 };
502
503 // - 'DeleteHosts'
504 const deleteHostsButtonsData = {
505 updateIsDeleteButtonDisabled,
506 updateIsDeletion,
507 };
508
509 const selectedHostsData = {
510 selectedHosts,
511 clearSelectedHosts,
512 };
513
514 // - 'HostsTable'
515 const hostsTableData = {
516 isHostSelectable,
517 selectedHosts,
518 selectableHostsTable,
519 setHostSelected,
520 clearSelectedHosts,
521 };
522
523 const hostsTableButtonsData = {
524 updateIsDeleteButtonDisabled,
525 isDeletion,
526 updateIsDeletion,
527 };
528
529 // - 'SearchInputLayout'
530 const searchValueData = {
531 searchValue,
532 updateSearchValue,
533 submitSearchValue,
534 };
535
536 // Contextual links panel
537 const [isContextualPanelExpanded, setIsContextualPanelExpanded] =
538 React.useState(false);
539
540 const onOpenContextualPanel = () => {
541 setIsContextualPanelExpanded(!isContextualPanelExpanded);
542 };
543
544 const onCloseContextualPanel = () => {
545 setIsContextualPanelExpanded(false);
546 };
547
548 // List of toolbar items
549 const toolbarItems: ToolbarItem[] = [
550 {
551 key: 0,
552 element: (
553 <BulkSelectorPrep
554 list={hostsList}
555 shownElementsList={hostsList}
556 elementData={hostsBulkSelectorData}
557 buttonsData={buttonsData}
558 selectedPerPageData={selectedPerPageData}
559 />
560 ),
561 },
562 {
563 key: 1,
564 element: (
565 <SearchInputLayout
566 dataCy="search"
567 name="search"
568 ariaLabel="Search hosts"
569 placeholder="Search"
570 searchValueData={searchValueData}
571 isDisabled={searchDisabled}
572 />
573 ),
574 toolbarItemVariant: ToolbarItemVariant.label,
575 toolbarItemGap: { default: "gapMd" },
576 },
577 {
578 key: 2,
579 toolbarItemVariant: ToolbarItemVariant.separator,
580 },
581 {
582 key: 3,
583 element: (
584 <SecondaryButton
585 onClickHandler={refreshHostsData}
586 isDisabled={!showTableRows}
587 dataCy="hosts-button-refresh"
588 >
589 Refresh
590 </SecondaryButton>
591 ),
592 },
593 {
594 key: 4,
595 element: (
596 <SecondaryButton
597 isDisabled={isDeleteButtonDisabled || !showTableRows}
598 onClickHandler={onDeleteHandler}
599 dataCy="hosts-button-delete"
600 >
601 Delete
602 </SecondaryButton>
603 ),
604 },
605 {
606 key: 5,
607 element: (
608 <SecondaryButton
609 onClickHandler={onAddClickHandler}
610 isDisabled={!showTableRows || isDisabledDueError}
611 dataCy="hosts-button-add"
612 >
613 Add
614 </SecondaryButton>
615 ),
616 },
617 {
618 key: 6,
619 element: (
620 <KebabLayout
621 onDropdownSelect={onDropdownSelect}
622 onKebabToggle={onKebabToggle}
623 idKebab="main-dropdown-kebab"
624 isKebabOpen={kebabIsOpen}
625 dropdownItems={!showTableRows ? [] : dropdownItems}
626 dataCy="hosts-kebab"
627 isDisabled={!showTableRows}
628 />
629 ),
630 },
631 {
632 key: 7,
633 toolbarItemVariant: ToolbarItemVariant.separator,
634 },
635 {
636 key: 8,
637 element: (
638 <HelpTextWithIconLayout
639 textContent="Help"
640 onClick={onOpenContextualPanel}
641 />
642 ),
643 },
644 {
645 key: 9,
646 element: (
647 <PaginationLayout
648 list={hostsList}
649 paginationData={paginationData}
650 widgetId="pagination-options-menu-top"
651 isCompact={true}
652 />
653 ),
654 toolbarItemAlignment: { default: "alignEnd" },
655 },
656 ];
657
658 return (
659 <ContextualHelpPanel
660 fromPage="hosts"
661 isExpanded={isContextualPanelExpanded}
662 onClose={onCloseContextualPanel}
663 >
664 <div>
665 <PageSection hasBodyWrapper={false}>
666 <TitleLayout id="Hosts title" headingLevel="h1" text="Hosts" />
667 </PageSection>
668 <PageSection hasBodyWrapper={false} isFilled={false}>
669 <Flex direction={{ default: "column" }}>
670 <FlexItem>
671 <ToolbarLayout toolbarItems={toolbarItems} />
672 </FlexItem>
673 <FlexItem style={{ flex: "0 0 auto" }}>
674 <OuterScrollContainer>
675 <InnerScrollContainer
676 style={{ height: "60vh", overflow: "auto" }}
677 >
678 {batchError !== undefined && batchError ? (
679 <GlobalErrors errors={globalErrors.getAll()} />
680 ) : (
681 <HostsTable
682 elementsList={hostsList}
683 shownElementsList={hostsList}
684 showTableRows={showTableRows}
685 hostsData={hostsTableData}
686 buttonsData={hostsTableButtonsData}
687 paginationData={selectedPerPageData}
688 searchValue={searchValue}
689 />
690 )}
691 </InnerScrollContainer>
692 </OuterScrollContainer>
693 </FlexItem>
694 <FlexItem
695 style={{ flex: "0 0 auto", position: "sticky", bottom: 0 }}
696 >
697 <PaginationLayout
698 list={hostsList}
699 paginationData={paginationData}
700 variant={PaginationVariant.bottom}
701 widgetId="pagination-options-menu-bottom"
702 />
703 </FlexItem>
704 </Flex>
705 </PageSection>
706 <ModalErrors errors={modalErrors.getAll()} dataCy="hosts-modal-error" />
707 {isMembershipModalOpen && (
708 <ModalWithFormLayout
709 variantType="medium"
710 modalPosition="top"
711 offPosition="76px"
712 title="Confirmation"
713 formId="rebuild-auto-membership-modal"
714 fields={confirmationQuestion}
715 show={isMembershipModalOpen}
716 onClose={() => setIsMembershipModalOpen(!isMembershipModalOpen)}
717 actions={membershipModalActions}
718 dataCy="hosts-rebuild-auto-membership-modal"
719 />
720 )}
721 <AddHost
722 show={showAddModal}
723 handleModalToggle={onAddModalToggle}
724 onOpenAddModal={onAddClickHandler}
725 onCloseAddModal={onCloseAddModal}
726 onRefresh={refreshHostsData}
727 />
728 <DeleteHosts
729 show={showDeleteModal}
730 handleModalToggle={onDeleteModalToggle}
731 selectedHostsData={selectedHostsData}
732 buttonsData={deleteHostsButtonsData}
733 onRefresh={refreshHostsData}
734 />
735 </div>
736 </ContextualHelpPanel>
737 );
738 };
739
740 export default Hosts;