From cbcecf676bdd3195c554c67da89fdf9419fbfe3a Mon Sep 17 00:00:00 2001 From: Joshua Matsuoka Date: Tue, 25 Oct 2022 12:27:13 -0400 Subject: [PATCH] feat(jmc-agent): add JMC Agent probes UI (#558) * Agent Plugin Changes * tmp * Fix refreshing of ProbeTemplate table, add notifications * Adding Agent Tests * Fix ErrorView and AuthRetry * Fix Agent Probe Templates page tests, fix probe templates table, add deletion warning * Fixing Agent Live Probes page to work with new API implementation * Backing out unnecessary package.json change * Running prettier to fix formatting * Removing extraneous change * Removing unnecessary change * Fixing deletion warning and notifications * Moving Agent items under Events page, adding hints to error message when probes fail to load * Moving Agent help into agent components, adding notification for probe template deletion * Remove duplicate notification * Add error hint for Probetemplate component * clean up, formatting * add parameter to suppress graphical notification on error * test for and only display JMC Agent card if support is detected * fixup! test for and only display JMC Agent card if support is detected * apply prettier * chore(events): clean up api calls and use separate state for 2 tables * chore(live-probes): clean up live probe views * feat(agent): add delete modal for active probe view * chore(agent): clean up probe template view * chore(agent): continue to clean up * tests(agent): fix tests * Suppress notifications on refreshing probes * Fix notification handling for removing probes * leave card visible but disable tab if Agent not detected * Refresh probes table when receiving a removal notification, adjust tests accordingly * correct hook dep * don't re-query after successful deletion request, allow notification to prompt client-side model update * skip query on notification, just clear client-side model * test correction * Actually commit tests this time * Fix test mocks, adjust test to check for both probes, fix dependency array * fix(agent): disable remove button if no probes * fix(agent): add more tests * chore(agent): apply prettier * disable probe insertion button if agent not detected * tests(agent): add tests for inserting probes * chore(agent): remove unused imports Co-authored-by: Andrew Azores Co-authored-by: Thuan Vo --- src/app/Agent/AgentLiveProbes.tsx | 309 +++++++++++++ src/app/Agent/AgentProbeTemplates.tsx | 428 ++++++++++++++++++ src/app/Events/EventTemplates.tsx | 11 +- src/app/Events/Events.tsx | 87 +++- src/app/Modal/DeleteWarningUtils.tsx | 20 + src/app/Shared/Services/Api.service.tsx | 175 ++++++- .../Services/NotificationChannel.service.tsx | 36 ++ src/test/Agent/AgentLiveProbes.test.tsx | 249 ++++++++++ src/test/Agent/AgentProbeTemplates.test.tsx | 333 ++++++++++++++ .../AgentLiveProbes.test.tsx.snap | 404 +++++++++++++++++ .../AgentProbeTemplates.test.tsx.snap | 314 +++++++++++++ 11 files changed, 2325 insertions(+), 41 deletions(-) create mode 100644 src/app/Agent/AgentLiveProbes.tsx create mode 100644 src/app/Agent/AgentProbeTemplates.tsx create mode 100644 src/test/Agent/AgentLiveProbes.test.tsx create mode 100644 src/test/Agent/AgentProbeTemplates.test.tsx create mode 100644 src/test/Agent/__snapshots__/AgentLiveProbes.test.tsx.snap create mode 100644 src/test/Agent/__snapshots__/AgentProbeTemplates.test.tsx.snap diff --git a/src/app/Agent/AgentLiveProbes.tsx b/src/app/Agent/AgentLiveProbes.tsx new file mode 100644 index 000000000..e2f4ee21c --- /dev/null +++ b/src/app/Agent/AgentLiveProbes.tsx @@ -0,0 +1,309 @@ +/* + * Copyright The Cryostat Authors + * + * The Universal Permissive License (UPL), Version 1.0 + * + * Subject to the condition set forth below, permission is hereby granted to any + * person obtaining a copy of this software, associated documentation and/or data + * (collectively the "Software"), free of charge and under any and all copyright + * rights in the Software, and any and all patent rights owned or freely + * licensable by each licensor hereunder covering either (i) the unmodified + * Software as contributed to or provided by such licensor, or (ii) the Larger + * Works (as defined below), to deal in both + * + * (a) the Software, and + * (b) any piece of software and/or hardware listed in the lrgrwrks.txt file if + * one is included with the Software (each a "Larger Work" to which the Software + * is contributed by such licensors), + * + * without restriction, including without limitation the rights to copy, create + * derivative works of, display, perform, and distribute the Software and make, + * use, sell, offer for sale, import, export, have made, and have sold the + * Software and the Larger Work(s), and to sublicense the foregoing rights on + * either these or other terms. + * + * This license is subject to the following condition: + * The above copyright notice and either this complete permission notice or at + * a minimum a reference to the UPL must be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +import * as React from 'react'; +import { ServiceContext } from '@app/Shared/Services/Services'; +import { NotificationCategory } from '@app/Shared/Services/NotificationChannel.service'; +import { useSubscriptions } from '@app/utils/useSubscriptions'; +import { + Button, + Card, + CardBody, + CardHeaderMain, + CardHeader, + Toolbar, + ToolbarContent, + ToolbarGroup, + ToolbarItem, + TextInput, + Text, + TextVariants, + Stack, + StackItem, +} from '@patternfly/react-core'; +import { + Table, + TableBody, + TableHeader, + TableVariant, + ISortBy, + SortByDirection, + sortable, +} from '@patternfly/react-table'; +import { first } from 'rxjs/operators'; +import { LoadingView } from '@app/LoadingView/LoadingView'; +import { authFailMessage, ErrorView, isAuthFail } from '@app/ErrorView/ErrorView'; +import { EventProbe } from '@app/Shared/Services/Api.service'; +import { DeleteWarningModal } from '@app/Modal/DeleteWarningModal'; +import { DeleteWarningType } from '@app/Modal/DeleteWarningUtils'; + +export interface AgentLiveProbesProps {} + +export const AgentLiveProbes: React.FunctionComponent = (props) => { + const context = React.useContext(ServiceContext); + const addSubscription = useSubscriptions(); + + const [probes, setProbes] = React.useState([] as EventProbe[]); + const [filteredProbes, setFilteredProbes] = React.useState([] as EventProbe[]); + const [filterText, setFilterText] = React.useState(''); + const [sortBy, setSortBy] = React.useState({} as ISortBy); + const [isLoading, setIsLoading] = React.useState(false); + const [errorMessage, setErrorMessage] = React.useState(''); + const [warningModalOpen, setWarningModalOpen] = React.useState(false); + + const tableColumns = [ + { title: 'ID', transforms: [sortable] }, + { title: 'Name', transforms: [sortable] }, + { title: 'Class', transforms: [sortable] }, + { title: 'Description' }, + { title: 'Method', transforms: [sortable] }, + ]; + + const handleProbes = React.useCallback( + (probes) => { + setProbes(probes); + setErrorMessage(''); + setIsLoading(false); + }, + [setProbes, setIsLoading, setErrorMessage] + ); + + const handleError = React.useCallback( + (error) => { + setErrorMessage(error.message); + setIsLoading(false); + }, + [setIsLoading, setErrorMessage] + ); + + const refreshProbes = React.useCallback(() => { + setIsLoading(true); + addSubscription( + context.api.getActiveProbes(true).subscribe({ + next: (value) => handleProbes(value), + error: (err) => handleError(err), + }) + ); + }, [addSubscription, context.api, setIsLoading, handleProbes, handleError]); + + const handleSort = React.useCallback( + (evt, index, direction) => { + setSortBy({ index, direction }); + }, + [setSortBy] + ); + + const authRetry = React.useCallback(() => { + context.target.setAuthRetry(); + }, [context.target, context.target.setAuthRetry]); + + const handleDeleteAllProbes = React.useCallback(() => { + addSubscription( + context.api + .removeProbes() + .pipe(first()) + .subscribe(() => { + // do nothing - notification updates state + }) + ); + }, [addSubscription, context.api]); + + const handleWarningModalAccept = React.useCallback(() => handleDeleteAllProbes(), [handleDeleteAllProbes]); + + const handleWarningModalClose = React.useCallback(() => { + setWarningModalOpen(false); + }, [setWarningModalOpen]); + + const handleDeleteButton = React.useCallback(() => { + if (context.settings.deletionDialogsEnabledFor(DeleteWarningType.DeleteActiveProbes)) { + setWarningModalOpen(true); + } else { + handleDeleteAllProbes(); + } + }, [context.settings, setWarningModalOpen, handleDeleteAllProbes]); + + React.useEffect(() => { + addSubscription( + context.target.target().subscribe(() => { + setFilterText(''); + refreshProbes(); + }) + ); + }, [context, context.target, addSubscription, setFilterText, refreshProbes]); + + React.useEffect(() => { + if (!context.settings.autoRefreshEnabled()) { + return; + } + const id = window.setInterval( + () => refreshProbes(), + context.settings.autoRefreshPeriod() * context.settings.autoRefreshUnits() + ); + return () => window.clearInterval(id); + }, [context.settings, refreshProbes]); + + React.useEffect(() => { + addSubscription( + context.target.authFailure().subscribe(() => { + setErrorMessage(authFailMessage); + }) + ); + }, [addSubscription, context.target, setErrorMessage]); + + React.useEffect(() => { + addSubscription( + context.notificationChannel.messages(NotificationCategory.ProbeTemplateApplied).subscribe((_) => refreshProbes()) + ); + }, [addSubscription, context, context.notificationChannel, refreshProbes]); + + React.useEffect(() => { + addSubscription( + context.notificationChannel.messages(NotificationCategory.ProbesRemoved).subscribe((_) => setProbes([])) + ); + }, [addSubscription, context, context.notificationChannel, setProbes]); + + React.useEffect(() => { + let filtered: EventProbe[]; + if (!filterText) { + filtered = probes; + } else { + const ft = filterText.trim().toLowerCase(); + filtered = probes.filter( + (t: EventProbe) => + t.name.toLowerCase().includes(ft) || + t.description.toLowerCase().includes(ft) || + t.clazz.toLowerCase().includes(ft) || + t.methodDescriptor.toLowerCase().includes(ft) || + t.methodName.toLowerCase().includes(ft) + ); + } + const { index, direction } = sortBy; + if (typeof index === 'number') { + const keys = ['id', 'name', 'description', 'clazz', 'methodName']; + const key = keys[index]; + const sorted = filtered.sort((a, b) => (a[key] < b[key] ? -1 : a[key] > b[key] ? 1 : 0)); + filtered = direction === SortByDirection.asc ? sorted : sorted.reverse(); + } + setFilteredProbes([...filtered]); + }, [filterText, probes, sortBy, setFilteredProbes]); + + const displayTemplates = React.useMemo( + () => filteredProbes.map((t: EventProbe) => [t.id, t.name, t.clazz, t.description, t.methodName]), + [filteredProbes] + ); + + if (errorMessage != '') { + return ( + + ); + } else if (isLoading) { + return ; + } else { + return ( + <> + + + + + + About the JMC Agent + + + + The JMC Agent allows users to dynamically inject custom JFR events into running JVMs. In order to make + use of the JMC Agent, the agent jar must be present in the same container as the target, and the target + must be started with the agent (-javaagent:/path/to/agent.jar). Once these pre-requisites are met, the + user can upload probe templates to Cryostat and insert them to the target, as well as view or remove + currently active probes. + + + + + + + + + + + + + + + + + + + + + + +
+
+
+ + ); + } +}; diff --git a/src/app/Agent/AgentProbeTemplates.tsx b/src/app/Agent/AgentProbeTemplates.tsx new file mode 100644 index 000000000..c4753879b --- /dev/null +++ b/src/app/Agent/AgentProbeTemplates.tsx @@ -0,0 +1,428 @@ +/* + * Copyright The Cryostat Authors + * + * The Universal Permissive License (UPL), Version 1.0 + * + * Subject to the condition set forth below, permission is hereby granted to any + * person obtaining a copy of this software, associated documentation and/or data + * (collectively the "Software"), free of charge and under any and all copyright + * rights in the Software, and any and all patent rights owned or freely + * licensable by each licensor hereunder covering either (i) the unmodified + * Software as contributed to or provided by such licensor, or (ii) the Larger + * Works (as defined below), to deal in both + * + * (a) the Software, and + * (b) any piece of software and/or hardware listed in the lrgrwrks.txt file if + * one is included with the Software (each a "Larger Work" to which the Software + * is contributed by such licensors), + * + * without restriction, including without limitation the rights to copy, create + * derivative works of, display, perform, and distribute the Software and make, + * use, sell, offer for sale, import, export, have made, and have sold the + * Software and the Larger Work(s), and to sublicense the foregoing rights on + * either these or other terms. + * + * This license is subject to the following condition: + * The above copyright notice and either this complete permission notice or at + * a minimum a reference to the UPL must be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +import * as React from 'react'; +import { ServiceContext } from '@app/Shared/Services/Services'; +import { NotificationCategory } from '@app/Shared/Services/NotificationChannel.service'; +import { useSubscriptions } from '@app/utils/useSubscriptions'; +import { + ActionGroup, + Button, + Card, + CardBody, + CardHeaderMain, + CardHeader, + FileUpload, + Form, + FormGroup, + Modal, + ModalVariant, + Toolbar, + ToolbarContent, + ToolbarGroup, + ToolbarItem, + TextInput, + Text, + TextVariants, + StackItem, + Stack, +} from '@patternfly/react-core'; +import { UploadIcon } from '@patternfly/react-icons'; +import { + Table, + TableBody, + TableHeader, + TableVariant, + IAction, + IRowData, + IExtraData, + ISortBy, + SortByDirection, + sortable, +} from '@patternfly/react-table'; +import { first } from 'rxjs/operators'; +import { LoadingView } from '@app/LoadingView/LoadingView'; +import { ErrorView } from '@app/ErrorView/ErrorView'; +import { ProbeTemplate } from '@app/Shared/Services/Api.service'; +import { DeleteWarningType } from '@app/Modal/DeleteWarningUtils'; +import { DeleteWarningModal } from '@app/Modal/DeleteWarningModal'; + +export interface AgentProbeTemplatesProps { + agentDetected: boolean; +} + +export const AgentProbeTemplates: React.FunctionComponent = (props) => { + const context = React.useContext(ServiceContext); + const addSubscription = useSubscriptions(); + + const [templates, setTemplates] = React.useState([] as ProbeTemplate[]); + const [filteredTemplates, setFilteredTemplates] = React.useState([] as ProbeTemplate[]); + const [filterText, setFilterText] = React.useState(''); + const [modalOpen, setModalOpen] = React.useState(false); + const [uploadFile, setUploadFile] = React.useState(undefined as File | undefined); + const [uploadFilename, setUploadFilename] = React.useState(''); + const [uploading, setUploading] = React.useState(false); + const [fileRejected, setFileRejected] = React.useState(false); + const [sortBy, setSortBy] = React.useState({} as ISortBy); + const [isLoading, setIsLoading] = React.useState(false); + const [errorMessage, setErrorMessage] = React.useState(''); + const [rowDeleteData, setRowDeleteData] = React.useState({} as IRowData); + const [warningModalOpen, setWarningModalOpen] = React.useState(false); + + const tableColumns = React.useMemo(() => [{ title: 'Name', transforms: [sortable] }, { title: 'XML' }], [sortable]); + + const handleTemplates = React.useCallback( + (templates) => { + setTemplates(templates); + setIsLoading(false); + setErrorMessage(''); + }, + [setTemplates, setIsLoading, setErrorMessage] + ); + const handleError = React.useCallback( + (error) => { + setIsLoading(false); + setErrorMessage(error.message); + }, + [setIsLoading, setErrorMessage] + ); + + const refreshTemplates = React.useCallback(() => { + setIsLoading(true); + addSubscription( + context.api.getProbeTemplates().subscribe({ + next: (value) => handleTemplates(value), + error: (err) => handleError(err), + }) + ); + }, [addSubscription, context.api, setIsLoading, handleTemplates, handleError]); + + const handleDelete = React.useCallback( + (rowData) => { + addSubscription( + context.api + .deleteCustomProbeTemplate(rowData[0]) + .pipe(first()) + .subscribe(() => { + /** Do nothing. Notifications hook will handle */ + }) + ); + }, + [addSubscription, context.api] + ); + + const handleUploadCancel = React.useCallback(() => { + setUploadFile(undefined); + setUploadFilename(''); + setModalOpen(false); + }, [setUploadFile, setUploadFilename, setModalOpen]); + + const handleDeleteButton = React.useCallback( + (rowData) => { + if (context.settings.deletionDialogsEnabledFor(DeleteWarningType.DeleteEventTemplates)) { + setRowDeleteData(rowData); + setWarningModalOpen(true); + } else { + handleDelete(rowData); + } + }, + [context.settings, setWarningModalOpen, setRowDeleteData, handleDelete] + ); + + const handleWarningModalAccept = React.useCallback(() => { + handleDelete(rowDeleteData); + }, [handleDelete, rowDeleteData]); + + const handleWarningModalClose = React.useCallback(() => { + setWarningModalOpen(false); + }, [setWarningModalOpen]); + + const handleFileRejected = React.useCallback(() => { + setFileRejected(true); + }, [setFileRejected]); + + const handleSort = React.useCallback( + (event, index, direction) => { + setSortBy({ index, direction }); + }, + [setSortBy] + ); + + const handleInsert = React.useCallback( + (rowData) => { + addSubscription( + context.api + .insertProbes(rowData[0]) + .pipe(first()) + .subscribe(() => {}) + ); + }, + [addSubscription, context.api] + ); + + const actionResolver = React.useCallback( + (rowData: IRowData, extraData: IExtraData) => { + if (typeof extraData.rowIndex == 'undefined') { + return []; + } + return [ + { + title: 'Insert Probes...', + onClick: (event, rowId, rowData) => handleInsert(rowData), + isDisabled: !props.agentDetected, + }, + { + isSeparator: true, + }, + { + title: 'Delete', + onClick: (event, rowId, rowData) => handleDeleteButton(rowData), + }, + ] as IAction[]; + }, + [handleInsert, handleDeleteButton, props.agentDetected] + ); + + const handleTemplateUpload = React.useCallback(() => { + setModalOpen(true); + }, [setModalOpen]); + + const handleUploadModalClose = React.useCallback(() => { + setModalOpen(false); + }, [setModalOpen]); + + const handleFileChange = React.useCallback( + (value, filename) => { + setFileRejected(false); + setUploadFile(value); + setUploadFilename(filename); + }, + [setFileRejected, setUploadFile, setUploadFilename] + ); + + const handleUploadSubmit = React.useCallback(() => { + if (!uploadFile) { + window.console.error('Attempted to submit probe template upload without a file selected'); + return; + } + setUploading(true); + addSubscription( + context.api + .addCustomProbeTemplate(uploadFile) + .pipe(first()) + .subscribe((success) => { + setUploading(false); + if (success) { + setUploadFile(undefined); + setUploadFilename(''); + setModalOpen(false); + } + }) + ); + }, [uploadFile, setUploading, addSubscription, context.api, setUploadFile, setUploadFilename, setModalOpen]); + + React.useEffect(() => { + refreshTemplates(); + }, [refreshTemplates]); + + React.useEffect(() => { + if (!context.settings.autoRefreshEnabled()) { + return; + } + const id = window.setInterval( + () => refreshTemplates(), + context.settings.autoRefreshPeriod() * context.settings.autoRefreshUnits() + ); + return () => window.clearInterval(id); + }, [context.settings, refreshTemplates]); + + React.useEffect(() => { + addSubscription( + context.notificationChannel + .messages(NotificationCategory.ProbeTemplateUploaded) + .subscribe((v) => refreshTemplates()) + ); + }, [addSubscription, context.notificationChannel, refreshTemplates]); + + React.useEffect(() => { + addSubscription( + context.notificationChannel + .messages(NotificationCategory.ProbeTemplateDeleted) + .subscribe((v) => refreshTemplates()) + ); + }, [addSubscription, context.notificationChannel, refreshTemplates]); + + React.useEffect(() => { + let filtered: ProbeTemplate[]; + if (!filterText) { + filtered = templates; + } else { + const ft = filterText.trim().toLowerCase(); + filtered = templates.filter( + (t: ProbeTemplate) => t.name.toLowerCase().includes(ft) || t.xml.toLowerCase().includes(ft) + ); + } + const { index, direction } = sortBy; + if (typeof index === 'number') { + const keys = ['name', 'xml']; + const key = keys[index]; + const sorted = filtered.sort((a, b) => (a[key] < b[key] ? -1 : a[key] > b[key] ? 1 : 0)); + filtered = direction === SortByDirection.asc ? sorted : sorted.reverse(); + } + setFilteredTemplates([...filtered]); + }, [filterText, templates, sortBy, setFilteredTemplates]); + + const displayTemplates = React.useMemo( + () => filteredTemplates.map((t: ProbeTemplate) => [t.name, t.xml]), + [filteredTemplates] + ); + + if (errorMessage != '') { + return ( + + ); + } else if (isLoading) { + return ; + } else { + return ( + <> + + + + + + About the JMC Agent + + + + The JMC Agent allows users to dynamically inject custom JFR events into running JVMs. In order to make + use of the JMC Agent, the agent jar must be present in the same container as the target, and the target + must be started with the agent (-javaagent:/path/to/agent.jar). Once these pre-requisites are met, the + user can upload probe templates to Cryostat and insert them to the target, as well as view or remove + currently active probes. + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + + + + + +
+
+
+
+ + ); + } +}; diff --git a/src/app/Events/EventTemplates.tsx b/src/app/Events/EventTemplates.tsx index 2dd60bd1e..5313b68e6 100644 --- a/src/app/Events/EventTemplates.tsx +++ b/src/app/Events/EventTemplates.tsx @@ -204,11 +204,12 @@ export const EventTemplates = () => { }, []); React.useEffect(() => { - const sub = context.target.authFailure().subscribe(() => { - setErrorMessage(authFailMessage); - }); - return () => sub.unsubscribe(); - }, [context.target]); + addSubscription( + context.target.authFailure().subscribe(() => { + setErrorMessage(authFailMessage); + }) + ); + }, [addSubscription, context.target, setErrorMessage]); const displayTemplates = React.useMemo( () => diff --git a/src/app/Events/Events.tsx b/src/app/Events/Events.tsx index 07146ba7c..2ba4b4742 100644 --- a/src/app/Events/Events.tsx +++ b/src/app/Events/Events.tsx @@ -36,33 +36,84 @@ * SOFTWARE. */ import * as React from 'react'; +import { ServiceContext } from '@app/Shared/Services/Services'; +import { useSubscriptions } from '@app/utils/useSubscriptions'; import { TargetView } from '@app/TargetView/TargetView'; -import { Card, CardBody, Tab, Tabs } from '@patternfly/react-core'; +import { Card, CardBody, Stack, StackItem, Tab, Tabs, Tooltip } from '@patternfly/react-core'; import { EventTemplates } from './EventTemplates'; +import { AgentProbeTemplates } from '@app/Agent/AgentProbeTemplates'; +import { AgentLiveProbes } from '@app/Agent/AgentLiveProbes'; import { EventTypes } from './EventTypes'; +import { concatMap, filter } from 'rxjs'; +import { NO_TARGET } from '@app/Shared/Services/Target.service'; -export const Events = () => { - const [activeTab, setActiveTab] = React.useState(0); +export interface EventsProps {} - const handleTabSelect = (evt, idx) => { - setActiveTab(idx); - }; +export const Events: React.FunctionComponent = (props) => { + const context = React.useContext(ServiceContext); + const addSubscription = useSubscriptions(); + const [eventActiveTab, setEventActiveTab] = React.useState(0); + const [probeActiveTab, setProbeActiveTab] = React.useState(0); + const [agentDetected, setAgentDetected] = React.useState(false); + + React.useEffect(() => { + addSubscription( + context.target + .target() + .pipe( + filter((target) => target !== NO_TARGET), + concatMap((_) => context.api.isProbeEnabled()) + ) + .subscribe(setAgentDetected) + ); + }, [addSubscription, context.target, context.api, setAgentDetected]); + + const handleEventTabSelect = React.useCallback((evt, idx) => setEventActiveTab(idx), [setEventActiveTab]); + + const handleProbeTabSelect = React.useCallback((evt, idx) => setProbeActiveTab(idx), [setProbeActiveTab]); return ( <> - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + ) + } + > + + + + + + + ); diff --git a/src/app/Modal/DeleteWarningUtils.tsx b/src/app/Modal/DeleteWarningUtils.tsx index f4908076b..11e0981e4 100644 --- a/src/app/Modal/DeleteWarningUtils.tsx +++ b/src/app/Modal/DeleteWarningUtils.tsx @@ -40,6 +40,8 @@ export enum DeleteWarningType { DeleteArchivedRecordings = 'DeleteArchivedRecordings', DeleteAutomatedRules = 'DeleteAutomatedRules', DeleteEventTemplates = 'DeleteEventTemplates', + DeleteProbeTemplates = 'DeleteProbeTemplates', + DeleteActiveProbes = 'DeleteActiveProbes', DeleteJMXCredentials = 'DeleteJMXCredentials', DeleteCustomTargets = 'DeleteCustomTargets', } @@ -84,6 +86,22 @@ export const DeleteEventTemplates: DeleteWarning = { ariaLabel: 'Event template delete warning', }; +export const DeleteProbeTemplates: DeleteWarning = { + id: DeleteWarningType.DeleteProbeTemplates, + title: 'Permanently delete Probe Template?', + label: 'Delete Probe Template', + description: `Custom probe template data will be lost.`, + ariaLabel: 'Probe template delete warning', +}; + +export const DeleteActiveProbes: DeleteWarning = { + id: DeleteWarningType.DeleteActiveProbes, + title: 'Permanently remove Active Probes from the target?', + label: 'Remove Active Probes', + description: `Active probes will be removed from the target.`, + ariaLabel: 'Active Probes remove warning', +}; + export const DeleteJMXCredentials: DeleteWarning = { id: DeleteWarningType.DeleteJMXCredentials, title: 'Permanently delete JMX Credentials?', @@ -105,6 +123,8 @@ export const DeleteWarningKinds: DeleteWarning[] = [ DeleteArchivedRecordings, DeleteAutomatedRules, DeleteEventTemplates, + DeleteProbeTemplates, + DeleteActiveProbes, DeleteJMXCredentials, DeleteCustomTargets, ]; diff --git a/src/app/Shared/Services/Api.service.tsx b/src/app/Shared/Services/Api.service.tsx index 599d4932f..86874b046 100644 --- a/src/app/Shared/Services/Api.service.tsx +++ b/src/app/Shared/Services/Api.service.tsx @@ -35,19 +35,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -import { - from, - Observable, - ObservableInput, - of, - ReplaySubject, - forkJoin, - throwError, - EMPTY, - shareReplay, - Subject, - BehaviorSubject, -} from 'rxjs'; +import { from, Observable, ObservableInput, of, ReplaySubject, forkJoin, throwError, EMPTY, shareReplay } from 'rxjs'; import { fromFetch } from 'rxjs/fetch'; import { catchError, concatMap, filter, first, map, mergeMap, tap } from 'rxjs/operators'; import { NO_TARGET, Target, TargetService } from './Target.service'; @@ -444,6 +432,13 @@ export class ApiService { ); } + isProbeEnabled(): Observable { + return this.getActiveProbes(true).pipe( + concatMap((_) => of(true)), + catchError((_) => of(false)) + ); + } + deleteCustomEventTemplate(templateName: string): Observable { return this.sendRequest('v1', `templates/${encodeURIComponent(templateName)}`, { method: 'DELETE', @@ -476,6 +471,81 @@ export class ApiService { ); } + removeProbes(): Observable { + return this.target.target().pipe( + concatMap((target) => + this.sendRequest('v2', `targets/${encodeURIComponent(target.connectUrl)}/probes`, { + method: 'DELETE', + }).pipe( + tap((resp) => { + if (resp.status == 400) { + this.notifications.warning('Failed to remove Probes', 'The probes failed to be removed from the target'); + } + }), + map((resp) => resp.status == 200), + first() + ) + ) + ); + } + + insertProbes(templateName: string): Observable { + return this.target.target().pipe( + concatMap((target) => + this.sendRequest( + 'v2', + `targets/${encodeURIComponent(target.connectUrl)}/probes/${encodeURIComponent(templateName)}`, + { + method: 'POST', + } + ).pipe( + tap((resp) => { + if (resp.status == 400) { + this.notifications.warning( + 'Failed to insert Probes', + 'The probes failed to be injected. Check that the agent is present in the same container as the target JVM and the target is running with -javaagent:/path/to/agent' + ); + } + }), + map((resp) => resp.status == 200), + first() + ) + ) + ); + } + + addCustomProbeTemplate(file: File): Observable { + const body = new window.FormData(); + body.append('probeTemplate', file); + return this.sendRequest('v2', `probes/` + file.name, { + method: 'POST', + body, + }).pipe( + map((response) => { + if (!response.ok) { + throw response.statusText; + } + return true; + }), + catchError((): ObservableInput => of(false)) + ); + } + + deleteCustomProbeTemplate(templateName: string): Observable { + return this.sendRequest('v2', `probes/${encodeURIComponent(templateName)}`, { + method: 'DELETE', + body: null, + }).pipe( + map((response) => { + if (!response.ok) { + throw response.statusText; + } + return true; + }), + catchError((): ObservableInput => of(false)) + ); + } + cryostatVersion(): Observable { return this.cryostatVersionSubject.asObservable(); } @@ -496,6 +566,33 @@ export class ApiService { ); } + getProbeTemplates(): Observable { + return this.sendRequest('v2', 'probes', { method: 'GET' }).pipe( + concatMap((resp) => resp.json()), + map((response: ProbeTemplateResponse) => response.data.result), + first() + ); + } + + getActiveProbes(suppressNotifications = false): Observable { + return this.target.target().pipe( + concatMap((target) => + this.sendRequest( + 'v2', + `targets/${encodeURIComponent(target.connectUrl)}/probes`, + { + method: 'GET', + }, + suppressNotifications + ).pipe( + concatMap((resp) => resp.json()), + map((response: EventProbesResponse) => response.data.result), + first() + ) + ) + ); + } + graphql(query: string): Observable { const headers = new Headers(); headers.set('Content-Type', 'application/graphql'); @@ -760,7 +857,12 @@ export class ApiService { ); } - private sendRequest(apiVersion: ApiVersion, path: string, config?: RequestInit): Observable { + private sendRequest( + apiVersion: ApiVersion, + path: string, + config?: RequestInit, + suppressNotifications = false + ): Observable { const req = () => this.login.getHeaders().pipe( concatMap((headers) => { @@ -785,7 +887,7 @@ export class ApiService { if (resp.ok) return resp; throw new HttpError(resp); }), - catchError((err) => this.handleError(err, req)) + catchError((err) => this.handleError(err, req, suppressNotifications)) ); return req(); } @@ -802,7 +904,7 @@ export class ApiService { anchor.remove(); } - private handleError(error: Error, retry: () => Observable): ObservableInput { + private handleError(error: Error, retry: () => Observable, suppressNotifications = false): ObservableInput { if (isHttpError(error)) { if (error.httpResponse.status === 427) { const jmxAuthScheme = error.httpResponse.headers.get('X-JMX-Authenticate'); @@ -814,12 +916,16 @@ export class ApiService { this.target.setSslFailure(); } else { error.httpResponse.text().then((detail) => { - this.notifications.danger(`Request failed (${error.httpResponse.status} ${error.message})`, detail); + if (!suppressNotifications) { + this.notifications.danger(`Request failed (${error.httpResponse.status} ${error.message})`, detail); + } }); } throw error; } - this.notifications.danger(`Request failed`, error.message); + if (!suppressNotifications) { + this.notifications.danger(`Request failed`, error.message); + } throw error; } @@ -852,6 +958,18 @@ interface CredentialResponse extends ApiV2Response { }; } +interface ProbeTemplateResponse extends ApiV2Response { + data: { + result: ProbeTemplate[]; + }; +} + +interface EventProbesResponse extends ApiV2Response { + data: { + result: EventProbe[]; + }; +} + interface CredentialsResponse extends ApiV2Response { data: { result: StoredCredential[]; @@ -927,6 +1045,27 @@ export interface StoredCredential { numMatchingTargets: number; } +export interface ProbeTemplate { + name: string; + xml: string; +} + +export interface EventProbe { + id: string; + name: string; + clazz: string; + description: string; + path: string; + recordStackTrace: boolean; + useRethrow: boolean; + methodName: string; + methodDescriptor: string; + location: string; + returnValue: string; + parameters: string; + fields: string; +} + export interface MatchedCredential { matchExpression: string; targets: Target[]; diff --git a/src/app/Shared/Services/NotificationChannel.service.tsx b/src/app/Shared/Services/NotificationChannel.service.tsx index 525dd3b67..874e4ecac 100644 --- a/src/app/Shared/Services/NotificationChannel.service.tsx +++ b/src/app/Shared/Services/NotificationChannel.service.tsx @@ -59,6 +59,10 @@ export enum NotificationCategory { ArchivedRecordingDeleted = 'ArchivedRecordingDeleted', TemplateUploaded = 'TemplateUploaded', TemplateDeleted = 'TemplateDeleted', + ProbeTemplateUploaded = 'ProbeTemplateUploaded', + ProbeTemplateDeleted = 'ProbeTemplateDeleted', + ProbeTemplateApplied = 'ProbeTemplateApplied', + ProbesRemoved = 'ProbesRemoved', RuleCreated = 'RuleCreated', RuleUpdated = 'RuleUpdated', RuleDeleted = 'RuleDeleted', @@ -195,6 +199,22 @@ export const messageKeys = new Map([ body: (evt) => `${evt.message.template.name} was created`, } as NotificationMessageMapper, ], + [ + NotificationCategory.ProbeTemplateUploaded, + { + variant: AlertVariant.success, + title: 'Probe Template Created', + body: (evt) => `${evt.message.probeTemplate} was created`, + } as NotificationMessageMapper, + ], + [ + NotificationCategory.ProbeTemplateApplied, + { + variant: AlertVariant.success, + title: 'Probe Template Applied', + body: (evt) => `${evt.message.probeTemplate} was inserted`, + } as NotificationMessageMapper, + ], [ NotificationCategory.TemplateDeleted, { @@ -203,6 +223,22 @@ export const messageKeys = new Map([ body: (evt) => `${evt.message.template.name} was deleted`, } as NotificationMessageMapper, ], + [ + NotificationCategory.ProbeTemplateDeleted, + { + variant: AlertVariant.success, + title: 'Probe Template Deleted', + body: (evt) => `${evt.message.probeTemplate} was deleted`, + } as NotificationMessageMapper, + ], + [ + NotificationCategory.ProbesRemoved, + { + variant: AlertVariant.success, + title: 'Probes Removed from Target', + body: (evt) => `Probes successfully removed from ${evt.message.target}`, + } as NotificationMessageMapper, + ], [ NotificationCategory.RuleCreated, { diff --git a/src/test/Agent/AgentLiveProbes.test.tsx b/src/test/Agent/AgentLiveProbes.test.tsx new file mode 100644 index 000000000..cfbfe5d84 --- /dev/null +++ b/src/test/Agent/AgentLiveProbes.test.tsx @@ -0,0 +1,249 @@ +/* + * Copyright The Cryostat Authors + * + * The Universal Permissive License (UPL), Version 1.0 + * + * Subject to the condition set forth below, permission is hereby granted to any + * person obtaining a copy of this software, associated documentation and/or data + * (collectively the "Software"), free of charge and under any and all copyright + * rights in the Software, and any and all patent rights owned or freely + * licensable by each licensor hereunder covering either (i) the unmodified + * Software as contributed to or provided by such licensor, or (ii) the Larger + * Works (as defined below), to deal in both + * + * (a) the Software, and + * (b) any piece of software and/or hardware listed in the lrgrwrks.txt file if + * one is included with the Software (each a "Larger Work" to which the Software + * is contributed by such licensors), + * + * without restriction, including without limitation the rights to copy, create + * derivative works of, display, perform, and distribute the Software and make, + * use, sell, offer for sale, import, export, have made, and have sold the + * Software and the Larger Work(s), and to sublicense the foregoing rights on + * either these or other terms. + * + * This license is subject to the following condition: + * The above copyright notice and either this complete permission notice or at + * a minimum a reference to the UPL must be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +import * as React from 'react'; +import renderer, { act } from 'react-test-renderer'; +import { cleanup, render, screen, waitFor, within } from '@testing-library/react'; +import '@testing-library/jest-dom'; +import { of } from 'rxjs'; +import { EventProbe } from '@app/Shared/Services/Api.service'; +import { + MessageMeta, + MessageType, + NotificationCategory, + NotificationMessage, +} from '@app/Shared/Services/NotificationChannel.service'; +import { ServiceContext, defaultServices } from '@app/Shared/Services/Services'; +import userEvent from '@testing-library/user-event'; +import { DeleteActiveProbes } from '@app/Modal/DeleteWarningUtils'; +import { AgentLiveProbes } from '@app/Agent/AgentLiveProbes'; + +const mockConnectUrl = 'service:jmx:rmi://someUrl'; +const mockTarget = { connectUrl: mockConnectUrl, alias: 'fooTarget' }; + +const mockMessageType = { type: 'application', subtype: 'json' } as MessageType; + +const mockProbe: EventProbe = { + id: 'some_id', + name: 'some_name', + clazz: 'some_clazz', + description: 'some_desc', + recordStackTrace: true, + useRethrow: true, + methodName: 'a_method', + methodDescriptor: 'method_desc', + location: 'some_loc', + returnValue: 'a_value', + parameters: 'some_params', + fields: 'some_fields', + path: 'some_path', +}; + +const mockAnotherProbe: EventProbe = { + ...mockProbe, + id: 'another_id', + name: 'another_name', +}; + +const mockApplyTemplateNotification = { + meta: { + category: NotificationCategory.ProbeTemplateApplied, + type: mockMessageType, + } as MessageMeta, + message: { + template: mockProbe, + }, +} as NotificationMessage; + +const mockRemoveProbesNotification = { + meta: { + category: NotificationCategory.ProbesRemoved, + type: mockMessageType, + } as MessageMeta, + message: { + target: mockTarget, + }, +} as NotificationMessage; + +jest.spyOn(defaultServices.target, 'target').mockReturnValue(of(mockTarget)); +jest.spyOn(defaultServices.target, 'authFailure').mockReturnValue(of()); + +jest + .spyOn(defaultServices.settings, 'deletionDialogsEnabledFor') + .mockReturnValueOnce(false) // should remove all probes when Remove All Probe is clicked + .mockReturnValue(true); // should show warning modal and remove all probes when confirmed + +jest + .spyOn(defaultServices.api, 'getActiveProbes') + .mockReturnValueOnce(of([mockProbe])) // renders correctly + + .mockReturnValueOnce(of([])) // should disable remove button if there is no probe + + .mockReturnValueOnce(of([mockProbe])) // should add a probe after receiving a notification + .mockReturnValueOnce(of([mockProbe, mockAnotherProbe])) + + .mockReturnValue(of([mockProbe])); // All other tests + +jest + .spyOn(defaultServices.notificationChannel, 'messages') + .mockReturnValueOnce(of()) // renders correctly + .mockReturnValueOnce(of()) + + .mockReturnValueOnce(of()) // should disable remove button if there is no probe + .mockReturnValueOnce(of()) + + .mockReturnValueOnce(of(mockApplyTemplateNotification)) // should add a probe after receiving a notification + .mockReturnValueOnce(of()) + + .mockReturnValueOnce(of()) + .mockReturnValueOnce(of(mockRemoveProbesNotification)) // should remove a probe after receiving a notification + + .mockReturnValue(of()); // All other tests + +describe('', () => { + afterEach(cleanup); + + it('renders correctly', async () => { + let tree; + await act(async () => { + tree = renderer.create( + + + + ); + }); + expect(tree.toJSON()).toMatchSnapshot(); + }); + + it('should disable remove button if there is no probe', async () => { + render( + + + + ); + + const removeButton = screen.getByText('Remove All Probes'); + expect(removeButton).toBeInTheDocument(); + expect(removeButton).toBeVisible(); + expect(removeButton).toBeDisabled(); + }); + + it('should add a probe after receiving a notification', () => { + render( + + + + ); + + const addTemplateName = screen.getByText('another_name'); + expect(addTemplateName).toBeInTheDocument(); + expect(addTemplateName).toBeVisible(); + }); + + it('should remove all probes after receiving a notification', () => { + render( + + + + ); + expect(screen.queryByText('some_name')).not.toBeInTheDocument(); + expect(screen.queryByText('another_name')).not.toBeInTheDocument(); + }); + + it('should display the column header fields', () => { + render( + + + + ); + + const headers = ['ID', 'Name', 'Class', 'Description', 'Method']; + headers.forEach((header) => { + const nameHeader = screen.getByText(header); + expect(nameHeader).toBeInTheDocument(); + expect(nameHeader).toBeVisible(); + }); + }); + + it('should remove all probes when Remove All Probe is clicked', async () => { + const deleteRequestSpy = jest.spyOn(defaultServices.api, 'removeProbes').mockReturnValue(of(true)); + render( + + + + ); + + const removeButton = screen.getByText('Remove All Probes'); + expect(removeButton).toBeInTheDocument(); + expect(removeButton).toBeVisible(); + + userEvent.click(removeButton); + + expect(deleteRequestSpy).toBeCalledTimes(1); + }); + + it('should show warning modal and remove all probes when confirmed', async () => { + const deleteRequestSpy = jest.spyOn(defaultServices.api, 'removeProbes').mockReturnValue(of(true)); + render( + + + + ); + + const removeButton = screen.getByText('Remove All Probes'); + expect(removeButton).toBeInTheDocument(); + expect(removeButton).toBeVisible(); + + userEvent.click(removeButton); + + const warningModal = await screen.findByRole('dialog'); + expect(warningModal).toBeInTheDocument(); + expect(warningModal).toBeVisible(); + + const modalTitle = within(warningModal).getByText(DeleteActiveProbes.title); + expect(modalTitle).toBeInTheDocument(); + expect(modalTitle).toBeVisible(); + + const confirmButton = within(warningModal).getByText('Delete'); + expect(confirmButton).toBeInTheDocument(); + expect(confirmButton).toBeVisible(); + + userEvent.click(confirmButton); + + expect(deleteRequestSpy).toBeCalledTimes(1); + }); +}); diff --git a/src/test/Agent/AgentProbeTemplates.test.tsx b/src/test/Agent/AgentProbeTemplates.test.tsx new file mode 100644 index 000000000..df68e772b --- /dev/null +++ b/src/test/Agent/AgentProbeTemplates.test.tsx @@ -0,0 +1,333 @@ +/* + * Copyright The Cryostat Authors + * + * The Universal Permissive License (UPL), Version 1.0 + * + * Subject to the condition set forth below, permission is hereby granted to any + * person obtaining a copy of this software, associated documentation and/or data + * (collectively the "Software"), free of charge and under any and all copyright + * rights in the Software, and any and all patent rights owned or freely + * licensable by each licensor hereunder covering either (i) the unmodified + * Software as contributed to or provided by such licensor, or (ii) the Larger + * Works (as defined below), to deal in both + * + * (a) the Software, and + * (b) any piece of software and/or hardware listed in the lrgrwrks.txt file if + * one is included with the Software (each a "Larger Work" to which the Software + * is contributed by such licensors), + * + * without restriction, including without limitation the rights to copy, create + * derivative works of, display, perform, and distribute the Software and make, + * use, sell, offer for sale, import, export, have made, and have sold the + * Software and the Larger Work(s), and to sublicense the foregoing rights on + * either these or other terms. + * + * This license is subject to the following condition: + * The above copyright notice and either this complete permission notice or at + * a minimum a reference to the UPL must be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +import * as React from 'react'; +import renderer, { act } from 'react-test-renderer'; +import { act as doAct, cleanup, render, screen, waitFor, within } from '@testing-library/react'; +import '@testing-library/jest-dom'; +import { of } from 'rxjs'; +import { ProbeTemplate } from '@app/Shared/Services/Api.service'; +import { + MessageMeta, + MessageType, + NotificationCategory, + NotificationMessage, +} from '@app/Shared/Services/NotificationChannel.service'; +import { ServiceContext, defaultServices } from '@app/Shared/Services/Services'; +import userEvent from '@testing-library/user-event'; +import { DeleteProbeTemplates } from '@app/Modal/DeleteWarningUtils'; +import { AgentProbeTemplates } from '@app/Agent/AgentProbeTemplates'; + +const mockMessageType = { type: 'application', subtype: 'json' } as MessageType; + +const mockProbeTemplate: ProbeTemplate = { + name: 'someProbeTemplate', + xml: '', +}; + +const mockAnotherProbeTemplate: ProbeTemplate = { + name: 'anotherProbeTemplate', + xml: '', +}; + +const mockFileUpload = new File([mockProbeTemplate.xml], 'probe_template.xml', { type: 'xml' }); + +const mockCreateTemplateNotification = { + meta: { + category: NotificationCategory.ProbeTemplateUploaded, + type: mockMessageType, + } as MessageMeta, + message: { + template: mockAnotherProbeTemplate, + }, +} as NotificationMessage; + +const mockDeleteTemplateNotification = { + meta: { + category: NotificationCategory.ProbeTemplateDeleted, + type: mockMessageType, + }, + message: { + template: mockProbeTemplate, + }, +} as NotificationMessage; + +jest + .spyOn(defaultServices.settings, 'deletionDialogsEnabledFor') + .mockReturnValueOnce(false) // should delete a probe template when Delete is clicked + .mockReturnValue(true); // should show warning modal and delete a probe template when confirmed + +const uploadRequestSpy = jest.spyOn(defaultServices.api, 'addCustomProbeTemplate').mockReturnValue(of(true)); + +jest + .spyOn(defaultServices.api, 'getProbeTemplates') + .mockReturnValueOnce(of([mockProbeTemplate])) // renders Correctly + + .mockReturnValueOnce(of([mockProbeTemplate])) // should add a probe template after receiving a notification + .mockReturnValueOnce(of([mockProbeTemplate, mockAnotherProbeTemplate])) + + .mockReturnValueOnce(of([mockProbeTemplate])) // should remove a probe template after receiving a notification + .mockReturnValueOnce(of([])) + + .mockReturnValue(of([mockProbeTemplate])); // All other tests + +jest + .spyOn(defaultServices.notificationChannel, 'messages') + .mockReturnValueOnce(of()) // renders correctly + .mockReturnValueOnce(of()) + + .mockReturnValueOnce(of(mockCreateTemplateNotification)) // adds a template after receiving a notification + .mockReturnValueOnce(of()) + + .mockReturnValueOnce(of()) + .mockReturnValueOnce(of(mockDeleteTemplateNotification)) // removes a template after receiving a notification + + .mockReturnValue(of()); // All other tests + +describe('', () => { + afterEach(cleanup); + + it('renders correctly', async () => { + let tree; + await act(async () => { + tree = renderer.create( + + + + ); + }); + expect(tree.toJSON()).toMatchSnapshot(); + }); + + it('should add a probe template after receiving a notification', () => { + render( + + + + ); + + const addTemplateName = screen.getByText('anotherProbeTemplate'); + expect(addTemplateName).toBeInTheDocument(); + expect(addTemplateName).toBeVisible(); + }); + + it('should remove a probe template after receiving a notification', () => { + render( + + + + ); + expect(screen.queryByText('someProbeTemplate')).not.toBeInTheDocument(); + }); + + it('should display the column header fields', () => { + render( + + + + ); + const nameHeader = screen.getByText('Name'); + expect(nameHeader).toBeInTheDocument(); + expect(nameHeader).toBeVisible(); + + const xmlHeader = screen.getByText('XML'); + expect(xmlHeader).toBeInTheDocument(); + expect(xmlHeader).toBeVisible(); + }); + + it('should show modal when uploading', async () => { + render( + + + + ); + + const uploadButton = screen.getByRole('button', { name: 'Upload' }); + expect(uploadButton).toBeInTheDocument(); + expect(uploadButton).toBeVisible(); + + userEvent.click(uploadButton); + + const uploadModal = await screen.findByRole('dialog'); + expect(uploadModal).toBeInTheDocument(); + expect(uploadModal).toBeVisible(); + + const modalTitle = within(uploadModal).getByText('Create Custom Probe Template'); + expect(modalTitle).toBeInTheDocument(); + expect(modalTitle).toBeVisible(); + }); + + it('should upload a probe template when form is filled and Submit is clicked', async () => { + render( + + + + ); + + const uploadButton = screen.getByRole('button', { name: 'Upload' }); + expect(uploadButton).toBeInTheDocument(); + expect(uploadButton).toBeVisible(); + + userEvent.click(uploadButton); + + const uploadModal = await screen.findByRole('dialog'); + expect(uploadModal).toBeInTheDocument(); + expect(uploadModal).toBeVisible(); + + const modalTitle = within(uploadModal).getByText('Create Custom Probe Template'); + expect(modalTitle).toBeInTheDocument(); + expect(modalTitle).toBeVisible(); + + const fileUploadDropZone = within(uploadModal).getByLabelText( + 'Drag a file here or browse to upload' + ) as HTMLInputElement; + expect(fileUploadDropZone).toBeInTheDocument(); + expect(fileUploadDropZone).toBeVisible(); + + const browseButton = within(uploadModal).getByRole('button', { name: 'Browse...' }); + expect(browseButton).toBeInTheDocument(); + expect(browseButton).toBeVisible(); + + const uploadInput = uploadModal.querySelector("input[accept='.xml'][type='file']") as HTMLInputElement; + expect(uploadInput).toBeInTheDocument(); + expect(uploadInput).not.toBeVisible(); + + userEvent.click(browseButton); + userEvent.upload(uploadInput, mockFileUpload); + + expect(uploadInput.files).not.toBe(null); + expect(uploadInput.files![0]).toStrictEqual(mockFileUpload); + + const submitButton = screen.getByRole('button', { name: 'Submit' }) as HTMLButtonElement; + await waitFor(() => expect(submitButton).not.toBeDisabled()); + await doAct(async () => { + userEvent.click(submitButton); + }); + + expect(uploadRequestSpy).toHaveBeenCalledTimes(1); + expect(uploadRequestSpy).toHaveBeenCalledWith(mockFileUpload); + }); + + it('should delete a probe template when Delete is clicked', async () => { + const deleteRequestSpy = jest.spyOn(defaultServices.api, 'deleteCustomProbeTemplate').mockReturnValue(of(true)); + render( + + + + ); + + userEvent.click(screen.getByLabelText('Actions')); + + const deleteButton = await screen.findByText('Delete'); + expect(deleteButton).toBeInTheDocument(); + expect(deleteButton).toBeVisible(); + + userEvent.click(deleteButton); + + expect(deleteRequestSpy).toHaveBeenCalledTimes(1); + expect(deleteRequestSpy).toBeCalledWith('someProbeTemplate'); + }); + + it('should show warning modal and delete a probe template when confirmed', async () => { + const deleteRequestSpy = jest.spyOn(defaultServices.api, 'deleteCustomProbeTemplate').mockReturnValue(of(true)); + render( + + + + ); + + userEvent.click(screen.getByLabelText('Actions')); + + const deleteButton = await screen.findByText('Delete'); + expect(deleteButton).toBeInTheDocument(); + expect(deleteButton).toBeVisible(); + + userEvent.click(deleteButton); + + const warningModal = await screen.findByRole('dialog'); + expect(warningModal).toBeInTheDocument(); + expect(warningModal).toBeVisible(); + + const modalTitle = within(warningModal).getByText(DeleteProbeTemplates.title); + expect(modalTitle).toBeInTheDocument(); + expect(modalTitle).toBeVisible(); + + const confirmButton = within(warningModal).getByText('Delete'); + expect(confirmButton).toBeInTheDocument(); + expect(confirmButton).toBeVisible(); + + userEvent.click(confirmButton); + + expect(deleteRequestSpy).toHaveBeenCalledTimes(1); + expect(deleteRequestSpy).toBeCalledWith('someProbeTemplate'); + }); + + it('should insert probes if agent is enabled', async () => { + const insertProbesSpy = jest.spyOn(defaultServices.api, 'insertProbes').mockReturnValue(of(true)); + render( + + + + ); + + userEvent.click(screen.getByLabelText('Actions')); + + const insertButton = await screen.findByText('Insert Probes...'); + expect(insertButton).toBeInTheDocument(); + expect(insertButton).toBeVisible(); + expect(insertButton.getAttribute('aria-disabled')).toBe('false'); + + userEvent.click(insertButton); + + expect(insertProbesSpy).toHaveBeenCalledTimes(1); + expect(insertProbesSpy).toHaveBeenCalledWith(mockProbeTemplate.name); + }); + + it('should disable inserting probes if agent is not enabled', async () => { + render( + + + + ); + userEvent.click(screen.getByLabelText('Actions')); + + const insertButton = await screen.findByText('Insert Probes...'); + expect(insertButton).toBeInTheDocument(); + expect(insertButton).toBeVisible(); + expect(insertButton.getAttribute('aria-disabled')).toBe('true'); + }); +}); diff --git a/src/test/Agent/__snapshots__/AgentLiveProbes.test.tsx.snap b/src/test/Agent/__snapshots__/AgentLiveProbes.test.tsx.snap new file mode 100644 index 000000000..6b2458466 --- /dev/null +++ b/src/test/Agent/__snapshots__/AgentLiveProbes.test.tsx.snap @@ -0,0 +1,404 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[` renders correctly 1`] = ` +
+
+
+
+
+

+ About the JMC Agent +

+
+
+
+ The JMC Agent allows users to dynamically inject custom JFR events into running JVMs. In order to make use of the JMC Agent, the agent jar must be present in the same container as the target, and the target must be started with the agent (-javaagent:/path/to/agent.jar). Once these pre-requisites are met, the user can upload probe templates to Cryostat and insert them to the target, as well as view or remove currently active probes. +
+
+
+
+
+
+
+
+
+ +
+
+
+
+ +
+
+
+
+
+
+
+ + + + + + + + + + + + + + + + + + + + +
+
+
+`; diff --git a/src/test/Agent/__snapshots__/AgentProbeTemplates.test.tsx.snap b/src/test/Agent/__snapshots__/AgentProbeTemplates.test.tsx.snap new file mode 100644 index 000000000..38e332b3b --- /dev/null +++ b/src/test/Agent/__snapshots__/AgentProbeTemplates.test.tsx.snap @@ -0,0 +1,314 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[` renders correctly 1`] = ` +
+
+
+
+
+

+ About the JMC Agent +

+
+
+
+ The JMC Agent allows users to dynamically inject custom JFR events into running JVMs. In order to make use of the JMC Agent, the agent jar must be present in the same container as the target, and the target must be started with the agent (-javaagent:/path/to/agent.jar). Once these pre-requisites are met, the user can upload probe templates to Cryostat and insert them to the target, as well as view or remove currently active probes. +
+
+
+
+
+
+
+
+
+ +
+
+
+
+ +
+
+
+
+
+
+
+ + + + + + + + + + + + + + + + +
+
+
+`;