Skip to content

Commit

Permalink
[ILM] Read only view (elastic#186955)
Browse files Browse the repository at this point in the history
## Summary
Fixes elastic#184805

This PR adds a flyout to view an ILM policy. With this change, the ILM
plugin can be also accessed by users with "read" permission for ILM.
To test this PR, create a new role with `read_ilm` Elasticsearch
privileges and all Kibana privileges.

### Screenshots 

<img width="545" alt="Screenshot 2024-09-06 at 17 40 46"
src="https://github.com/user-attachments/assets/74d3beb2-857c-4803-b308-80a2c1509696">

<img width="540" alt="Screenshot 2024-09-06 at 17 40 59"
src="https://github.com/user-attachments/assets/82046408-cbef-4de3-aa7d-7b69193ad6b7">




https://github.com/user-attachments/assets/01fb445a-120a-489e-8f8d-26375ce391b1



### Checklist

Delete any items that are not applicable to this PR.

- [ ] Any text added follows [EUI's writing
guidelines](https://elastic.github.io/eui/#/guidelines/writing), uses
sentence case text and includes [i18n
support](https://github.com/elastic/kibana/blob/main/packages/kbn-i18n/README.md)
- [ ]
[Documentation](https://www.elastic.co/guide/en/kibana/master/development-documentation.html)
was added for features that require explanation or tutorials
- [ ] [Unit or functional
tests](https://www.elastic.co/guide/en/kibana/master/development-tests.html)
were updated or added to match the most common scenarios
- [ ] [Flaky Test
Runner](https://ci-stats.kibana.dev/trigger_flaky_test_runner/1) was
used on any tests changed
- [ ] Any UI touched in this PR is usable by keyboard only (learn more
about [keyboard accessibility](https://webaim.org/techniques/keyboard/))
- [ ] Any UI touched in this PR does not create any new axe failures
(run axe in browser:
[FF](https://addons.mozilla.org/en-US/firefox/addon/axe-devtools/),
[Chrome](https://chrome.google.com/webstore/detail/axe-web-accessibility-tes/lhdoppojpmngadmnindnejefpokejbdd?hl=en-US))
- [ ] If a plugin configuration key changed, check if it needs to be
allowlisted in the cloud and added to the [docker
list](https://github.com/elastic/kibana/blob/main/src/dev/build/tasks/os_packages/docker_generator/resources/base/bin/kibana-docker)
- [ ] This renders correctly on smaller devices using a responsive
layout. (You can test this [in your
browser](https://www.browserstack.com/guide/responsive-testing-on-local-server))
- [ ] This was checked for [cross-browser
compatibility](https://www.elastic.co/support/matrix#matrix_browsers)


### Risk Matrix

Delete this section if it is not applicable to this PR.

Before closing this PR, invite QA, stakeholders, and other developers to
identify risks that should be tested prior to the change/feature
release.

When forming the risk matrix, consider some of the following examples
and how they may potentially impact the change:

| Risk | Probability | Severity | Mitigation/Notes |

|---------------------------|-------------|----------|-------------------------|
| Multiple Spaces&mdash;unexpected behavior in non-default Kibana Space.
| Low | High | Integration tests will verify that all features are still
supported in non-default Kibana Space and when user switches between
spaces. |
| Multiple nodes&mdash;Elasticsearch polling might have race conditions
when multiple Kibana nodes are polling for the same tasks. | High | Low
| Tasks are idempotent, so executing them multiple times will not result
in logical error, but will degrade performance. To test for this case we
add plenty of unit tests around this logic and document manual testing
procedure. |
| Code should gracefully handle cases when feature X or plugin Y are
disabled. | Medium | High | Unit tests will verify that any feature flag
or plugin combination still results in our service operational. |
| [See more potential risk
examples](https://github.com/elastic/kibana/blob/main/RISK_MATRIX.mdx) |


### For maintainers

- [ ] This was checked for breaking API changes and was [labeled
appropriately](https://www.elastic.co/guide/en/kibana/master/contributing.html#kibana-release-notes-process)

---------

Co-authored-by: kibanamachine <[email protected]>
  • Loading branch information
yuliacech and kibanamachine authored Sep 20, 2024
1 parent 9a9c0f1 commit 1e572cf
Show file tree
Hide file tree
Showing 76 changed files with 2,766 additions and 369 deletions.

Large diffs are not rendered by default.

97 changes: 97 additions & 0 deletions x-pack/plugins/index_lifecycle_management/__jest__/mocks.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/

import type { PolicyFromES } from '../common/types';

export const policyAllPhases: PolicyFromES = {
name: 'test',
modifiedDate: '2024-08-12T12:17:06.271Z',
version: 1,
policy: {
name: 'test',
phases: {
hot: {
actions: {
rollover: {
max_age: '30d',
max_primary_shard_size: '50gb',
max_primary_shard_docs: 25,
max_docs: 235,
max_size: '2gb',
},
set_priority: {
priority: 100,
},
forcemerge: {
max_num_segments: 3,
index_codec: 'best_compression',
},
shrink: {
number_of_shards: 1,
},
readonly: {},
},
min_age: '0ms',
},
warm: {
min_age: '3d',
actions: {
set_priority: {
priority: 50,
},
shrink: {
max_primary_shard_size: '4gb',
},
forcemerge: {
max_num_segments: 44,
index_codec: 'best_compression',
},
allocate: {
number_of_replicas: 3,
},
downsample: {
fixed_interval: '1d',
},
},
},
cold: {
min_age: '55d',
actions: {
searchable_snapshot: {
snapshot_repository: 'found-snapshots',
},
set_priority: {
priority: 0,
},
allocate: {
number_of_replicas: 3,
},
downsample: {
fixed_interval: '4d',
},
},
},
frozen: {
min_age: '555d',
actions: {
searchable_snapshot: {
snapshot_repository: 'found-snapshots',
},
},
},
delete: {
min_age: '7365d',
actions: {
wait_for_snapshot: {
policy: 'cloud-snapshot-policy',
},
delete: {},
},
},
},
},
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/

import React, { ReactElement } from 'react';
import { mountWithIntl } from '@kbn/test-jest-helpers';
import { findTestSubject, takeMountedSnapshot } from '@elastic/eui/lib/test';

import { docLinksServiceMock } from '@kbn/core/public/mocks';

import type { PolicyFromES } from '../common/types';
import { KibanaContextProvider } from '../public/shared_imports';
import { PolicyListContextProvider } from '../public/application/sections/policy_list/policy_list_context';
import { ViewPolicyFlyout } from '../public/application/sections/policy_list/policy_flyout';
import * as readOnlyHook from '../public/application/lib/use_is_read_only';
import { policyAllPhases } from './mocks';

let component: ReactElement;
const TestComponent = ({ policy }: { policy: PolicyFromES }) => {
return (
<KibanaContextProvider
services={{ getUrlForApp: () => '', docLinks: docLinksServiceMock.createStartContract() }}
>
<PolicyListContextProvider>
<ViewPolicyFlyout policy={policy} />
</PolicyListContextProvider>
</KibanaContextProvider>
);
};

describe('View policy flyout', () => {
beforeAll(() => {
jest.spyOn(readOnlyHook, 'useIsReadOnly').mockReturnValue(false);
component = <TestComponent policy={policyAllPhases} />;
});
it('shows all phases', () => {
const rendered = mountWithIntl(component);
expect(takeMountedSnapshot(rendered)).toMatchSnapshot();
});

it('renders manage button', () => {
const rendered = mountWithIntl(component);
const button = findTestSubject(rendered, 'managePolicyButton');
expect(button.exists()).toBeTruthy();
});

it(`doesn't render manage button in read only view`, () => {
jest.spyOn(readOnlyHook, 'useIsReadOnly').mockReturnValue(true);
component = <TestComponent policy={policyAllPhases} />;
const rendered = mountWithIntl(component);
const button = findTestSubject(rendered, 'managePolicyButton');
expect(button.exists()).toBeFalsy();
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import { init as initHttp } from '../public/application/services/http';
import { init as initUiMetric } from '../public/application/services/ui_metric';
import { KibanaContextProvider } from '../public/shared_imports';
import { PolicyListContextProvider } from '../public/application/sections/policy_list/policy_list_context';
import * as readOnlyHook from '../public/application/lib/use_is_read_only';

initHttp(httpServiceMock.createSetupContract());
initUiMetric(usageCollectionPluginMock.createSetupContract());
Expand Down Expand Up @@ -72,9 +73,16 @@ jest.mock('react-router-dom', () => ({
...jest.requireActual('react-router-dom'),
useHistory: () => ({
createHref: jest.fn(),
location: {
search: '',
},
}),
}));

const mockReactRouterNavigate = jest.fn();
jest.mock('@kbn/kibana-react-plugin/public', () => ({
...jest.requireActual('@kbn/kibana-react-plugin/public'),
reactRouterNavigate: () => mockReactRouterNavigate(),
}));
let component: ReactElement;

const snapshot = (rendered: string[]) => {
Expand Down Expand Up @@ -129,6 +137,7 @@ const TestComponent = ({ testPolicies }: { testPolicies: PolicyFromES[] }) => {
};
describe('policy table', () => {
beforeEach(() => {
jest.spyOn(readOnlyHook, 'useIsReadOnly').mockReturnValue(false);
component = <TestComponent testPolicies={policies} />;
window.localStorage.removeItem('ILM_SHOW_MANAGED_POLICIES_BY_DEFAULT');
});
Expand Down Expand Up @@ -296,7 +305,9 @@ describe('policy table', () => {
test('add index template modal shows when add policy to index template button is pressed', () => {
const rendered = mountWithIntl(component);
const policyRow = findTestSubject(rendered, `policyTableRow-${testPolicy.name}`);
const addPolicyToTemplateButton = findTestSubject(policyRow, 'addPolicyToTemplate');
const actionsButton = findTestSubject(policyRow, 'euiCollapsedItemActionsButton');
actionsButton.simulate('click');
const addPolicyToTemplateButton = findTestSubject(rendered, 'addPolicyToTemplate');
addPolicyToTemplateButton.simulate('click');
rendered.update();
expect(findTestSubject(rendered, 'addPolicyToTemplateModal').exists()).toBeTruthy();
Expand All @@ -312,6 +323,10 @@ describe('policy table', () => {
expect(policyIndices).toBe(`${testPolicy.indices.length}`);
const policyModifiedDate = findTestSubject(firstRow, 'policy-modifiedDate').text();
expect(policyModifiedDate).toBe(`${testDateFormatted}`);

const cells = firstRow.find('td');
// columns are name, linked index templates, linked indices, modified date, actions
expect(cells.length).toBe(5);
});
test('opens a flyout with index templates', () => {
const rendered = mountWithIntl(component);
Expand All @@ -323,4 +338,25 @@ describe('policy table', () => {
const indexTemplatesLinks = findTestSubject(rendered, 'indexTemplateLink');
expect(indexTemplatesLinks.length).toBe(testPolicy.indexTemplates.length);
});
test('opens a flyout to view policy by calling reactRouterNavigate', async () => {
const rendered = mountWithIntl(component);
const policyNameLink = findTestSubject(rendered, 'policyTablePolicyNameLink').at(0);
policyNameLink.simulate('click');
rendered.update();
expect(mockReactRouterNavigate).toHaveBeenCalled();
});

describe('read only view', () => {
beforeEach(() => {
jest.spyOn(readOnlyHook, 'useIsReadOnly').mockReturnValue(true);
component = <TestComponent testPolicies={policies} />;
});
it(`doesn't show actions column in the table`, () => {
const rendered = mountWithIntl(component);
const policyRow = findTestSubject(rendered, `policyTableRow-testy0`);
const cells = policyRow.find('td');
// columns are name, linked index templates, linked indices, modified date
expect(cells.length).toBe(4);
});
});
});
70 changes: 5 additions & 65 deletions x-pack/plugins/index_lifecycle_management/common/types/policies.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,21 +60,13 @@ export interface SerializedActionWithAllocation {
migrate?: MigrateAction;
}

export type SearchableSnapshotStorage = 'full_copy' | 'shared_cache';

export interface SearchableSnapshotAction {
snapshot_repository: string;
/**
* We do not configure this value in the UI as it is an advanced setting that will
* not suit the vast majority of cases.
*/
force_merge_index?: boolean;
/**
* This configuration lets the user create full or partial searchable snapshots.
* Full searchable snapshots store primary data locally and store replica data in the snapshot.
* Partial searchable snapshots store no data locally.
*/
storage?: SearchableSnapshotStorage;
}

export interface RolloverAction {
Expand All @@ -96,9 +88,7 @@ export interface SerializedHotPhase extends SerializedPhase {
shrink?: ShrinkAction;
downsample?: DownsampleAction;

set_priority?: {
priority: number | null;
};
set_priority?: SetPriorityAction;
/**
* Only available on enterprise license
*/
Expand All @@ -113,9 +103,7 @@ export interface SerializedWarmPhase extends SerializedPhase {
forcemerge?: ForcemergeAction;
readonly?: {};
downsample?: DownsampleAction;
set_priority?: {
priority: number | null;
};
set_priority?: SetPriorityAction;
migrate?: MigrateAction;
};
}
Expand All @@ -126,9 +114,7 @@ export interface SerializedColdPhase extends SerializedPhase {
readonly?: {};
downsample?: DownsampleAction;
allocate?: AllocateAction;
set_priority?: {
priority: number | null;
};
set_priority?: SetPriorityAction;
migrate?: MigrateAction;
/**
* Only available on enterprise license
Expand All @@ -139,11 +125,6 @@ export interface SerializedColdPhase extends SerializedPhase {

export interface SerializedFrozenPhase extends SerializedPhase {
actions: {
allocate?: AllocateAction;
set_priority?: {
priority: number | null;
};
migrate?: MigrateAction;
/**
* Only available on enterprise license
*/
Expand Down Expand Up @@ -187,11 +168,8 @@ export interface DownsampleAction {
fixed_interval: string;
}

export interface LegacyPolicy {
name: string;
phases: {
delete: DeletePhase;
};
export interface SetPriorityAction {
priority: number | null;
}

export interface CommonPhaseSettings {
Expand All @@ -203,44 +181,6 @@ export interface PhaseWithMinAge {
selectedMinimumAgeUnits: string;
}

export interface PhaseWithIndexPriority {
phaseIndexPriority: string;
}

export interface PhaseWithForcemergeAction {
forceMergeEnabled: boolean;
selectedForceMergeSegments: string;
bestCompressionEnabled: boolean;
}

export interface DeletePhase extends CommonPhaseSettings, PhaseWithMinAge {
waitForSnapshotPolicy: string;
}

export interface IndexLifecyclePolicy {
index: string;
managed: boolean;
action?: string;
action_time_millis?: number;
age?: string;
failed_step?: string;
failed_step_retry_count?: number;
is_auto_retryable_error?: boolean;
lifecycle_date_millis?: number;
phase?: string;
phase_execution?: {
policy: string;
modified_date_in_millis: number;
version: number;
phase_definition: SerializedPhase;
};
phase_time_millis?: number;
policy?: string;
step?: string;
step_info?: {
reason?: string;
type?: string;
message?: string;
};
step_time_millis?: number;
}
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,9 @@ const getTestBedConfig = (initialEntries: string[]): TestBedConfig => ({

export interface AppTestBed extends TestBed {
actions: {
clickPolicyNameLink: () => void;
clickCreatePolicyButton: () => void;
clickPolicyNameLink: () => Promise<void>;
clickCreatePolicyButton: () => Promise<void>;
clickEditPolicyButton: () => Promise<void>;
};
}

Expand Down Expand Up @@ -53,9 +54,17 @@ export const setup = async (
component.update();
};

const clickEditPolicyButton = async () => {
const { component, find } = testBed;
await act(async () => {
find('editPolicy').simulate('click', { button: 0 });
});
component.update();
};

return {
...testBed,
actions: { clickPolicyNameLink, clickCreatePolicyButton },
actions: { clickPolicyNameLink, clickCreatePolicyButton, clickEditPolicyButton },
};
};

Expand Down
Loading

0 comments on commit 1e572cf

Please sign in to comment.