Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion locales/en/public.json
Original file line number Diff line number Diff line change
Expand Up @@ -865,7 +865,9 @@
},
"DEFINITION_HELPER_TEXT": "Enter a Smart Trigger definition. A custom trigger definition must consist of both an expression that defines the overall trigger condition and the name of an event template that is used for the JFR Recording. The expression is a <a>Common Expression Language (CEL)</a> code snippet that defines one or more constraints and a target duration.",
"DEFINITION_HINT": "The set of constraints and target duration must be separated by a semicolon (;) character. Each constraint must include: the name of an MBean counter; a relational operator such as > (greater than), = (equal to), <(less than), and so on; and a specified value. The type of relational operator and value that you can specify depends on the associated MBean counter type. The constraint and duration must be enclosed in square brackets, followed by a tilde then the Recording Template name.",
"DEFINITION_HINT_BODY": "For an example definition: [ProcessCpuLoad>0.2;TargetDuration>duration(\"30s\")]~Profiling"
"DEFINITION_HINT_BODY": "For an example definition: [ProcessCpuLoad>0.2;TargetDuration>duration(\"30s\")]",
"TEMPLATE_SELECT": "Select an Event Template for starting a recording when the Trigger Condition is met.",
"AVAILABLE_MBEANS": "Select an MBean to check the value of."
},
"AuditLog": {
"TITLE": "Audit Log",
Expand Down
15 changes: 15 additions & 0 deletions src/app/Shared/Services/Api.service.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@ import {
AuditQueryParams,
AuditRevisionsResponse,
AuditRevisionDetail,
MbeanAttributeMap,
} from './api.types';
import {
isHttpError,
Expand Down Expand Up @@ -2082,6 +2083,20 @@ export class ApiService {
);
}

getTargetMbeans(
target: TargetStub,
suppressNotifications = false,
skipStatusCheck = false,
): Observable<MbeanAttributeMap[]> {
return this.doGet<MbeanAttributeMap[]>(
`targets/${target.id}/mbean-query`,
'beta',
undefined,
suppressNotifications,
skipStatusCheck,
);
}

getTargetEventTypes(
target: TargetStub,
suppressNotifications = false,
Expand Down
15 changes: 15 additions & 0 deletions src/app/Shared/Services/api.types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -445,6 +445,21 @@ export interface SmartTrigger {
timeConditionFirstMet: string;
}

export interface MBeanAttributeInfo {
name: string;
type: string;
description: string;
parentBean: string;
isReadable: boolean;
isWritable: boolean;
isIs: boolean;
}

export interface MbeanAttributeMap {
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: MBean, capital B

mBeanName: string;
attributes: MBeanAttributeInfo[];
}

// ======================================
// Template resources
// ======================================
Expand Down
169 changes: 164 additions & 5 deletions src/app/Triggers/SmartTriggers.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,23 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { EventTemplateIdentifier } from '@app/CreateRecording/types';
import { ColumnConfig, DiagnosticsTable } from '@app/Diagnostics/DiagnosticsTable';
import { DeleteWarningModal } from '@app/Modal/DeleteWarningModal';
import { DeleteOrDisableWarningType } from '@app/Modal/types';
import { CEL_SPEC_HREF } from '@app/Rules/utils';
import { SelectTemplateSelectorForm } from '@app/Shared/Components/SelectTemplateSelectorForm';
import { LoadingProps } from '@app/Shared/Components/types';

import { NotificationCategory, NullableTarget, SmartTrigger } from '@app/Shared/Services/api.types';
import {
EventTemplate,
MBeanAttributeInfo,
MbeanAttributeMap,
NotificationCategory,
NullableTarget,
SmartTrigger,
Target,
} from '@app/Shared/Services/api.types';
import { ServiceContext } from '@app/Shared/Services/Services';
import { useSubscriptions } from '@app/utils/hooks/useSubscriptions';
import { TableColumn, hashCode, portalRoot, sortResources } from '@app/utils/utils';
Expand Down Expand Up @@ -52,6 +62,8 @@ import {
FormHelperText,
HelperText,
HelperTextItem,
FormSelect,
FormSelectOption,
} from '@patternfly/react-core';
import { Modal, ModalVariant } from '@patternfly/react-core/deprecated';
import { EllipsisVIcon, SearchIcon } from '@patternfly/react-icons';
Expand All @@ -61,6 +73,7 @@ import _ from 'lodash';
import * as React from 'react';
import { Trans } from 'react-i18next';
import { first, forkJoin, Observable } from 'rxjs';
import { SmartTriggersFormData } from './types';

export const tableColumns: TableColumn[] = [
{
Expand Down Expand Up @@ -633,16 +646,70 @@ export interface CreateSmartTriggersModalProps {
onAccept: (s: string) => void;
}

export interface MbeanSelectorOption {
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

same here

value: string;
label: string;
disabled: boolean;
}

export const CreateSmartTriggersModal: React.FC<CreateSmartTriggersModalProps> = ({ onClose, ...props }) => {
const submitRef = React.useRef<HTMLDivElement>(null); // Use ref to refer to submit trigger div
const abortRef = React.useRef<HTMLDivElement>(null); // Use ref to refer to abort trigger div
const [templates, setTemplates] = React.useState<EventTemplate[]>([]);
const [mbeans, setMbeans] = React.useState<MbeanAttributeMap[]>([]);
const [mbeanSelectValue, setMbeanSelectValue] = React.useState<string>();
const addSubscription = useSubscriptions();
const context = React.useContext(ServiceContext);
const [formData, setFormData] = React.useState<SmartTriggersFormData>({
name: '',
nameValid: ValidatedOptions.default,
enabled: true,
expression: '', // Use this for displaying Match Expression input
expressionValid: ValidatedOptions.default,
});

// FIXME Triggers currently rely on MbeanMetrics. We can query all
// registered mbeans/attributes but we need to filter the supported ones.
const supportedTriggerAttributes: string[] = React.useMemo(
() => [
'ThreadCount',
'DaemonThreadCount',
'Arch',
'AvailableProcessors',
'Version',
'SystemCpuLoad',
'SystemLoadAverage',
'ProcessCpuLoad',
'TotalPhysicalMemorySize',
'FreePhyiscalMemorySize',
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

typo? Phyiscal -> Physical

'TotalSwapSpaceSize',
'HeapMemoryUsage',
'HeapMemoryUsagePercent',
'BootClassPath',
'ClassPath',
'InputArguments',
'LibraryPath',
'ManagementSpecVersion',
'SpecName',
'SpecVendor',
'StartTime',
'SystemProperties',
'Uptime',
'VmName',
'VmVendor',
'VmVersion',
'BootClassPathSupported',
],
[],
);

const [uploading, setUploading] = React.useState(false);

const expressionRegex = RegExp('\\[(.*(&&)*|(\\|\\|)*)\\]~([\\w\\-]+)(?:\\.jfc)?');
const expressionRegex = RegExp('\\[(.*(&&)*|(\\|\\|)*)\\]');

const [expressionInput, setExpressionInput] = React.useState('');
const [expressionValid, setExpressionValid] = React.useState(ValidatedOptions.default);
const [templateValid, setTemplateValid] = React.useState(ValidatedOptions.default);

const reset = React.useCallback(() => {
setUploading(false);
Expand All @@ -660,11 +727,11 @@ export const CreateSmartTriggersModal: React.FC<CreateSmartTriggersModalProps> =

const handleSubmit = React.useCallback(() => {
submitRef.current && submitRef.current.click();
props.onAccept(expressionInput);
props.onAccept(expressionInput + '~' + formData.template?.name);
setUploading(false);
onClose();
setExpressionInput('');
}, [props, onClose, expressionInput, submitRef]);
}, [props, onClose, expressionInput, submitRef, formData.template?.name]);

const submitButtonLoadingProps = React.useMemo(
() =>
Expand All @@ -676,6 +743,66 @@ export const CreateSmartTriggersModal: React.FC<CreateSmartTriggersModalProps> =
[uploading],
);

const refreshFormOptions = React.useCallback(
(target: Target) => {
if (!target) {
return;
}
addSubscription(
forkJoin({
templates: context.api.getTargetEventTemplates(target),
mbeans: context.api.getTargetMbeans(target),
}).subscribe({
next: ({ templates, mbeans }) => {
setTemplates(templates);
setMbeans(mbeans);
},
}),
);
},
[addSubscription, context.api, setTemplates],
);

React.useEffect(() => {
addSubscription(context.target.target().subscribe(refreshFormOptions));
}, [addSubscription, context.target, refreshFormOptions]);

const selectedSpecifier = React.useMemo(() => {
const { template } = formData;
if (template && template.name && template.type) {
return `${template.name},${template.type}`;
}
return '';
}, [formData]);

const MbeanOptions = React.useMemo(() => {
var attributes: MbeanSelectorOption[] = [];
mbeans.forEach((m: MbeanAttributeMap) => {
m.attributes.forEach((i: MBeanAttributeInfo) => {
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If supportedTriggerAttributes is just a hardcoded list of the MBeans we expect to see present in the remote JVM, then do we even need to send a query at this point... ? It seems like just returning the supported attributes list would do the same thing more simply, until we actually have some wider support on the backend (agent side) for processing other MBean metrics in the CEL expressions. Or am I missing something here?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You're correct that hardcoding it would achieve the same thing, I wanted to lay the groundwork here for generic mbean attributes down the line but for now we can get rid of the query if you'd prefer and just hardcode the list options.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If it's currently functionally equivalent then I think for now let's just go with the hardcoded list so that we can get that UI enhancement in, and work on the broader-scoped change that affects multiple components when we're further out from a dev freeze. Maybe the hardcoded version of this can go directly into #2155 and this PR can build on top of that do to the enhanced filtering based on actual live data pulled from the Agent.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sounds good, I'll add it to that PR

if (supportedTriggerAttributes.includes(i.name)) {
attributes.push({
value: i.name,
label: `${i.parentBean} - ${i.name} (${i.type})`,
disabled: false,
});
}
});
});
return attributes;
}, [mbeans, supportedTriggerAttributes]);

const handleTemplateChange = React.useCallback(
(template: EventTemplateIdentifier) => {
setFormData((old) => ({ ...old, template }));
setTemplateValid(ValidatedOptions.success);
},
[setFormData],
);

const onMbeanChange = (_event: React.FormEvent<HTMLSelectElement>, value: string) => {
setMbeanSelectValue(value);
};

return (
<Modal
isOpen={props.isOpen}
Expand All @@ -686,6 +813,26 @@ export const CreateSmartTriggersModal: React.FC<CreateSmartTriggersModalProps> =
description="Create a customized Smart Trigger. This is a specialized tool available in the Cryostat Agent that listens for a condition to be met for a specified Mbean, after which a recording will be started with the specified template. This is only available for targets using the Cryostat Agent."
>
<Form>
<FormHelperText>
<HelperText>
<HelperTextItem>{t('Triggers.AVAILABLE_MBEANS')}</HelperTextItem>
</HelperText>
</FormHelperText>
<FormSelect value={mbeanSelectValue} onChange={onMbeanChange} aria-label="MBean Input" ouiaId="BasicFormSelect">
<FormSelectOption
isDisabled={true}
key={-1}
value={''}
label={'Select an MBean Attribute'}
isPlaceholder={true}
/>
{MbeanOptions.map((option, index) => (
<FormSelectOption isDisabled={option.disabled} key={index} value={option.value} label={option.label} />
))}
</FormSelect>
<HelperText>
<HelperTextItem>{`Selected MBean attribute has the name: ${mbeanSelectValue}, Use this to build your expression.`}</HelperTextItem>
</HelperText>
<FormGroup label="Smart Trigger definition" isRequired fieldId="definition">
<TextArea
value={expressionInput}
Expand Down Expand Up @@ -722,13 +869,25 @@ export const CreateSmartTriggersModal: React.FC<CreateSmartTriggersModalProps> =
</HelperTextItem>
</HelperText>
</FormHelperText>
<FormHelperText>
<HelperText>
<HelperTextItem>{t('Triggers.TEMPLATE_SELECT')}</HelperTextItem>
</HelperText>
</FormHelperText>
<SelectTemplateSelectorForm
selected={selectedSpecifier}
templates={templates}
validated={templateValid}
disabled={uploading}
onSelect={handleTemplateChange}
/>
<ActionGroup>
<>
<Button
aria-label="submit-button"
variant="primary"
onClick={handleSubmit}
isDisabled={expressionValid != ValidatedOptions.success}
isDisabled={expressionValid != ValidatedOptions.success || templateValid != ValidatedOptions.success}
{...submitButtonLoadingProps}
>
{uploading ? 'Submitting' : 'Submit'}
Expand Down
33 changes: 33 additions & 0 deletions src/app/Triggers/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
/*
* Copyright The Cryostat Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { EventTemplate } from '@app/Shared/Services/api.types';
import { ValidatedOptions } from '@patternfly/react-core';

export type EventTemplateIdentifier = Pick<EventTemplate, 'name' | 'type'>;

interface _FormBaseData {
name: string;
enabled: boolean;
expression: string;
template?: EventTemplateIdentifier;
}

interface _FormValidationData {
nameValid: ValidatedOptions;
expressionValid: ValidatedOptions;
}

export type SmartTriggersFormData = _FormBaseData & _FormValidationData;
1 change: 1 addition & 0 deletions src/mirage/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1072,6 +1072,7 @@ export const startMirage = ({ environment = 'development' } = {}) => {
this.post('api/beta/diagnostics/targets/:targetId/gc', () => {
return new Response(204);
});
this.get('api/beta/targets/:targetId/mbean-query', () => []);
this.get('api/beta/targets/:targetId/smart_triggers', (schema) => schema.all(Resource.SMART_TRIGGER).models);
this.delete('api/beta/targets/:targetId/smart_triggers/:uuid', (schema, request) => {
const smartTriggerId = request.params.uuid;
Expand Down
Loading
Loading