Skip to content

Commit

Permalink
Merge branch 'main' into agent_flyout/refactor_flyout
Browse files Browse the repository at this point in the history
  • Loading branch information
kibanamachine authored Apr 6, 2022
2 parents d3a854d + d2be8b5 commit ec2b052
Show file tree
Hide file tree
Showing 54 changed files with 388 additions and 236 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,10 @@ export const IndexPatternTable = ({
dataViews,
overlays,
uiSettings,
onDelete: () => loadDataViews(),
onDelete: () => {
setSelectedItems([]);
loadDataViews();
},
});
if (selectedItems.length === 0) {
return;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
import React from 'react';

import { createFleetTestRendererMock } from '../../../../../../mock';
import type { Agent } from '../../../../types';
import type { Agent, AgentPolicy } from '../../../../types';
import { useGetPackageInfoByKey } from '../../../../../../hooks/use_request/epm';

import { AgentDashboardLink } from './agent_dashboard_link';
Expand All @@ -26,7 +26,7 @@ jest.mock('../../../../../../hooks/use_fleet_status', () => ({
jest.mock('../../../../../../hooks/use_request/epm');

describe('AgentDashboardLink', () => {
it('should enable the button if elastic_agent package is installed', async () => {
it('should enable the button if elastic_agent package is installed and policy has monitoring enabled', async () => {
mockedUseGetPackageInfoByKey.mockReturnValue({
isLoading: false,
data: {
Expand All @@ -44,14 +44,19 @@ describe('AgentDashboardLink', () => {
id: 'agent-id-123',
} as unknown as Agent
}
agentPolicy={
{
monitoring_enabled: ['logs', 'metrics'],
} as unknown as AgentPolicy
}
/>
);

expect(result.queryByRole('link')).not.toBeNull();
expect(result.getByRole('link').hasAttribute('href')).toBeTruthy();
});

it('should not enable the button if elastic_agent package is installed', async () => {
it('should not enable the button if elastic_agent package is not installed and policy has monitoring enabled', async () => {
mockedUseGetPackageInfoByKey.mockReturnValue({
isLoading: false,
data: {
Expand All @@ -69,6 +74,42 @@ describe('AgentDashboardLink', () => {
id: 'agent-id-123',
} as unknown as Agent
}
agentPolicy={
{
monitoring_enabled: ['logs', 'metrics'],
} as unknown as AgentPolicy
}
/>
);

expect(result.queryByRole('link')).toBeNull();
expect(result.queryByRole('button')).not.toBeNull();
expect(result.getByRole('button').hasAttribute('disabled')).toBeTruthy();
});

it('should not enable the button if elastic_agent package is installed and policy do not have monitoring enabled', async () => {
mockedUseGetPackageInfoByKey.mockReturnValue({
isLoading: false,
data: {
item: {
status: 'installed',
},
},
} as ReturnType<typeof useGetPackageInfoByKey>);
const testRenderer = createFleetTestRendererMock();

const result = testRenderer.render(
<AgentDashboardLink
agent={
{
id: 'agent-id-123',
} as unknown as Agent
}
agentPolicy={
{
monitoring_enabled: [],
} as unknown as AgentPolicy
}
/>
);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import { FormattedMessage } from '@kbn/i18n-react';
import { EuiButton, EuiToolTip } from '@elastic/eui';

import { useGetPackageInfoByKey, useKibanaLink } from '../../../../hooks';
import type { Agent } from '../../../../types';
import type { Agent, AgentPolicy } from '../../../../types';
import {
FLEET_ELASTIC_AGENT_PACKAGE,
FLEET_ELASTIC_AGENT_DETAILS_DASHBOARD_ID,
Expand All @@ -34,10 +34,14 @@ function useAgentDashboardLink(agent: Agent) {

export const AgentDashboardLink: React.FunctionComponent<{
agent: Agent;
}> = ({ agent }) => {
agentPolicy?: AgentPolicy;
}> = ({ agent, agentPolicy }) => {
const { isInstalled, link, isLoading } = useAgentDashboardLink(agent);

const buttonArgs = !isInstalled || isLoading ? { disabled: true } : { href: link };
const isLogAndMetricsEnabled = agentPolicy?.monitoring_enabled?.length ?? 0 > 0;

const buttonArgs =
!isInstalled || isLoading || !isLogAndMetricsEnabled ? { disabled: true } : { href: link };

const button = (
<EuiButton fill {...buttonArgs} isLoading={isLoading}>
Expand All @@ -48,12 +52,27 @@ export const AgentDashboardLink: React.FunctionComponent<{
</EuiButton>
);

if (!isLogAndMetricsEnabled) {
return (
<EuiToolTip
content={
<FormattedMessage
id="xpack.fleet.agentDetails.viewDashboardButton.disabledNoLogsAndMetricsTooltip"
defaultMessage="Logs and metrics for agent are not enabled in the agent policy."
/>
}
>
{button}
</EuiToolTip>
);
}

if (!isInstalled) {
return (
<EuiToolTip
content={
<FormattedMessage
id="xpack.fleet.agentDetails.viewDashboardButtonDisabledTooltip"
id="xpack.fleet.agentDetails.viewDashboardButton.disabledNoIntegrationTooltip"
defaultMessage="Agent dashboard not found, you need to install the elastic_agent integration."
/>
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ export const AgentDetailsPage: React.FunctionComponent = () => {
</EuiFlexItem>
)}
<EuiFlexItem grow={false}>
<AgentDashboardLink agent={agentData?.item} />
<AgentDashboardLink agent={agentData?.item} agentPolicy={agentPolicyData?.item} />
</EuiFlexItem>
</EuiFlexGroup>
</>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -408,8 +408,7 @@ describe('editor_frame', () => {
setDatasourceState(updatedState);
});

// validation requires to calls this getConfiguration API
expect(mockVisualization.getConfiguration).toHaveBeenCalledTimes(6);
expect(mockVisualization.getConfiguration).toHaveBeenCalledTimes(2);
expect(mockVisualization.getConfiguration).toHaveBeenLastCalledWith(
expect.objectContaining({
state: updatedState,
Expand Down Expand Up @@ -487,8 +486,7 @@ describe('editor_frame', () => {
setDatasourceState({});
});

// validation requires to calls this getConfiguration API
expect(mockVisualization.getConfiguration).toHaveBeenCalledTimes(6);
expect(mockVisualization.getConfiguration).toHaveBeenCalledTimes(2);
expect(mockVisualization.getConfiguration).toHaveBeenLastCalledWith(
expect.objectContaining({
frame: expect.objectContaining({
Expand Down Expand Up @@ -847,8 +845,7 @@ describe('editor_frame', () => {
instance.find('[data-test-subj="lnsSuggestion"]').at(2).simulate('click');
});

// validation requires to calls this getConfiguration API
expect(mockVisualization.getConfiguration).toHaveBeenCalledTimes(6);
expect(mockVisualization.getConfiguration).toHaveBeenCalledTimes(2);
expect(mockVisualization.getConfiguration).toHaveBeenLastCalledWith(
expect.objectContaining({
state: suggestionVisState,
Expand Down Expand Up @@ -928,7 +925,7 @@ describe('editor_frame', () => {
},
{
score: 0.6,
state: {},
state: suggestionVisState,
title: 'Suggestion2',
previewIcon: 'empty',
},
Expand All @@ -939,7 +936,7 @@ describe('editor_frame', () => {
getSuggestions: () => [
{
score: 0.8,
state: suggestionVisState,
state: {},
title: 'Suggestion3',
previewIcon: 'empty',
},
Expand Down Expand Up @@ -980,6 +977,8 @@ describe('editor_frame', () => {
})
).instance;

instance.update();

act(() => {
instance.find('[data-test-subj="mockVisA"]').find(DragDrop).prop('onDrop')!(
{
Expand All @@ -992,7 +991,7 @@ describe('editor_frame', () => {
);
});

expect(mockVisualization2.getConfiguration).toHaveBeenCalledWith(
expect(mockVisualization.getConfiguration).toHaveBeenCalledWith(
expect.objectContaining({
state: suggestionVisState,
})
Expand Down Expand Up @@ -1035,20 +1034,8 @@ describe('editor_frame', () => {
visualizationMap: {
testVis: {
...mockVisualization,
getSuggestions: () => [
{
score: 0.2,
state: {},
title: 'Suggestion1',
previewIcon: 'empty',
},
{
score: 0.6,
state: {},
title: 'Suggestion2',
previewIcon: 'empty',
},
],
// do not return suggestions for the currently active vis, otherwise it will be chosen
getSuggestions: () => [],
},
testVis2: {
...mockVisualization2,
Expand Down Expand Up @@ -1079,6 +1066,7 @@ describe('editor_frame', () => {
} as EditorFrameProps;

instance = (await mountWithProvider(<EditorFrame {...props} />)).instance;
instance.update();

act(() => {
instance.find(DragDrop).filter('[dataTestSubj="lnsWorkspace"]').prop('onDrop')!(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ import {
FramePublicAPI,
InitializationOptions,
Visualization,
VisualizationDimensionGroupConfig,
VisualizationMap,
VisualizeEditorContext,
} from '../../types';
Expand Down Expand Up @@ -197,24 +196,8 @@ export const validateDatasourceAndVisualization = (
currentVisualizationState: unknown | undefined,
frameAPI: Pick<FramePublicAPI, 'datasourceLayers'>
): ErrorMessage[] | undefined => {
const layersGroups = currentVisualizationState
? currentVisualization
?.getLayerIds(currentVisualizationState)
.reduce<Record<string, VisualizationDimensionGroupConfig[]>>((memo, layerId) => {
const groups = currentVisualization?.getConfiguration({
frame: frameAPI,
layerId,
state: currentVisualizationState,
}).groups;
if (groups) {
memo[layerId] = groups;
}
return memo;
}, {})
: undefined;

const datasourceValidationErrors = currentDatasourceState
? currentDataSource?.getErrorMessages(currentDatasourceState, layersGroups)
? currentDataSource?.getErrorMessages(currentDatasourceState)
: undefined;

const visualizationValidationErrors = currentVisualizationState
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,11 @@ import {
} from '../../../../../../src/plugins/expressions/public';
import { prependDatasourceExpression } from './expression_helpers';
import { trackUiEvent, trackSuggestionEvent } from '../../lens_ui_telemetry';
import { getMissingIndexPattern, validateDatasourceAndVisualization } from './state_helpers';
import {
getMissingIndexPattern,
validateDatasourceAndVisualization,
getDatasourceLayers,
} from './state_helpers';
import {
rollbackSuggestion,
selectExecutionContextSearch,
Expand Down Expand Up @@ -226,16 +230,28 @@ export function SuggestionPanel({
visualizationId,
visualizationState: suggestionVisualizationState,
datasourceState: suggestionDatasourceState,
datasourceId: suggetionDatasourceId,
datasourceId: suggestionDatasourceId,
}) => {
return (
!hide &&
validateDatasourceAndVisualization(
suggetionDatasourceId ? datasourceMap[suggetionDatasourceId] : null,
suggestionDatasourceId ? datasourceMap[suggestionDatasourceId] : null,
suggestionDatasourceState,
visualizationMap[visualizationId],
suggestionVisualizationState,
frame
{
datasourceLayers: getDatasourceLayers(
suggestionDatasourceId
? {
[suggestionDatasourceId]: {
isLoading: true,
state: suggestionDatasourceState,
},
}
: {},
datasourceMap
),
}
) == null
);
}
Expand Down Expand Up @@ -284,6 +300,7 @@ export function SuggestionPanel({
activeDatasourceId,
datasourceMap,
visualizationMap,
frame.activeData,
]);

const context: ExecutionContextSearch = useLensSelector(selectExecutionContextSearch);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -186,7 +186,7 @@ export function loadInitial(
setState({
isSaveable: true,
sharingSavedObjectProps,
filters,
filters: data.query.filterManager.getFilters(),
query: doc.state.query,
searchSessionId:
dashboardFeatureFlag.allowByValueEmbeddables &&
Expand Down
13 changes: 11 additions & 2 deletions x-pack/plugins/lens/public/state_management/load_initial.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import { Location, History } from 'history';
import { act } from 'react-dom/test-utils';
import { LensEmbeddableInput } from '../embeddable';
import { loadInitial } from './lens_slice';
import { Filter } from '@kbn/es-query';

const history = {
location: {
Expand Down Expand Up @@ -214,9 +215,16 @@ describe('Initializing the store', () => {
});

it('loads a document and uses query and filters if initial input is provided', async () => {
const { store, deps } = await makeLensStore({ preloadedState });
const { store, deps } = makeLensStore({ preloadedState });

const mockFilters = 'some filters from the filter manager' as unknown as Filter[];

jest
.spyOn(deps.lensServices.data.query.filterManager, 'getFilters')
.mockReturnValue(mockFilters);

await act(async () => {
await store.dispatch(loadInitial(defaultProps));
store.dispatch(loadInitial(defaultProps));
});

expect(deps.lensServices.attributeService.unwrapAttributes).toHaveBeenCalledWith({
Expand All @@ -233,6 +241,7 @@ describe('Initializing the store', () => {
query: 'kuery',
isLoading: false,
activeDatasourceId: 'testDatasource',
filters: mockFilters,
}),
});
});
Expand Down
Loading

0 comments on commit ec2b052

Please sign in to comment.