[Search] [Onboarding] Add metering stats API information to indices GET (#191631)

## Summary

Adds index size and doc count to indices management indices API. This
API is available only on ES3, relying on the _metering/stats API to
provide this information. The use of the API is scoped only for
serverless projects, via a config.

AppEx will roll out the UI changes for the other ES3 project solutions.

### 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
- [x] [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—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—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: Elastic Machine <elasticmachine@users.noreply.github.com>
This commit is contained in:
Joe McElroy 2024-09-02 11:39:54 +01:00 committed by GitHub
parent a48701029c
commit c5fe61851c
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
14 changed files with 292 additions and 152 deletions

View file

@ -100,6 +100,8 @@ xpack.index_management.enableIndexActions: false
xpack.index_management.enableLegacyTemplates: false
# Disable index stats information from Index Management UI
xpack.index_management.enableIndexStats: false
# Enable size and doc count information via metering API from Index Management UI
xpack.index_management.enableSizeAndDocCount: true
# Disable data stream stats information from Index Management UI
xpack.index_management.enableDataStreamStats: false
# Only limited index settings can be edited

View file

@ -63,6 +63,7 @@ export interface AppDependencies {
enableIndexActions: boolean;
enableLegacyTemplates: boolean;
enableIndexStats: boolean;
enableSizeAndDocCount: boolean;
enableDataStreamStats: boolean;
editableIndexSettings: 'all' | 'limited';
enableMappingsSourceFieldSection: boolean;

View file

@ -41,6 +41,7 @@ export class IndexMgmtUIPlugin
enableIndexActions: boolean;
enableLegacyTemplates: boolean;
enableIndexStats: boolean;
enableSizeAndDocCount: boolean;
enableDataStreamStats: boolean;
editableIndexSettings: 'all' | 'limited';
isIndexManagementUiEnabled: boolean;
@ -59,6 +60,7 @@ export class IndexMgmtUIPlugin
enableIndexActions,
enableLegacyTemplates,
enableIndexStats,
enableSizeAndDocCount,
enableDataStreamStats,
editableIndexSettings,
enableMappingsSourceFieldSection,
@ -70,6 +72,7 @@ export class IndexMgmtUIPlugin
enableIndexActions: enableIndexActions ?? true,
enableLegacyTemplates: enableLegacyTemplates ?? true,
enableIndexStats: enableIndexStats ?? true,
enableSizeAndDocCount: enableSizeAndDocCount ?? true,
enableDataStreamStats: enableDataStreamStats ?? true,
editableIndexSettings: editableIndexSettings ?? 'all',
enableMappingsSourceFieldSection: enableMappingsSourceFieldSection ?? true,

View file

@ -52,6 +52,7 @@ export interface ClientConfigType {
enableIndexActions?: boolean;
enableLegacyTemplates?: boolean;
enableIndexStats?: boolean;
enableSizeAndDocCount?: boolean;
enableDataStreamStats?: boolean;
editableIndexSettings?: 'all' | 'limited';
enableMappingsSourceFieldSection?: boolean;

View file

@ -38,6 +38,11 @@ const schemaLatest = schema.object(
// deprecate as unused after semantic text is enabled everywhere
enableSemanticText: schema.boolean({ defaultValue: true }),
}),
enableSizeAndDocCount: offeringBasedSchema({
// Size and document count information is enabled in serverless; refer to the serverless.yml file as the source of truth
// We take this approach in order to have a central place (serverless.yml) for serverless config across Kibana
serverless: schema.boolean({ defaultValue: true }),
}),
enableIndexStats: offeringBasedSchema({
// Index stats information is disabled in serverless; refer to the serverless.yml file as the source of truth
// We take this approach in order to have a central place (serverless.yml) for serverless config across Kibana

View file

@ -19,143 +19,188 @@ describe('[Index management API Routes] fetch indices lib function', () => {
const getIndices = router.getMockESApiFn('indices.get');
const getIndicesStats = router.getMockESApiFn('indices.stats');
const getMeteringStats = router.getMockESApiFnAsSecondaryAuthUser('transport.request');
const mockRequest: RequestMock = {
method: 'get',
path: addBasePath('/indices'),
};
beforeAll(() => {
registerIndicesRoutes({
...routeDependencies,
router,
});
});
test('regular index', async () => {
getIndices.mockResolvedValue({
regular_index: createTestIndexState(),
});
getIndicesStats.mockResolvedValue({
indices: {
regular_index: createTestIndexStats({ uuid: 'regular_index' }),
},
describe('stateful', () => {
beforeAll(() => {
registerIndicesRoutes({
...routeDependencies,
config: {
...routeDependencies.config,
isSizeAndDocCountEnabled: false,
isIndexStatsEnabled: true,
},
router,
});
});
await expect(router.runRequest(mockRequest)).resolves.toEqual({
body: [createTestIndexResponse({ name: 'regular_index', uuid: 'regular_index' })],
});
});
test('index with aliases', async () => {
getIndices.mockResolvedValue({
index_with_aliases: createTestIndexState({
aliases: { test_alias: {}, another_alias: {} },
}),
});
getIndicesStats.mockResolvedValue({
indices: {
index_with_aliases: createTestIndexStats({ uuid: 'index_with_aliases' }),
},
});
test('regular index', async () => {
getIndices.mockResolvedValue({
regular_index: createTestIndexState(),
});
getIndicesStats.mockResolvedValue({
indices: {
regular_index: createTestIndexStats({ uuid: 'regular_index' }),
},
});
await expect(router.runRequest(mockRequest)).resolves.toEqual({
body: [
createTestIndexResponse({
aliases: ['test_alias', 'another_alias'],
name: 'index_with_aliases',
uuid: 'index_with_aliases',
await expect(router.runRequest(mockRequest)).resolves.toEqual({
body: [createTestIndexResponse({ name: 'regular_index', uuid: 'regular_index' })],
});
});
test('index with aliases', async () => {
getIndices.mockResolvedValue({
index_with_aliases: createTestIndexState({
aliases: { test_alias: {}, another_alias: {} },
}),
],
});
});
test('frozen index', async () => {
getIndices.mockResolvedValue({
frozen_index: createTestIndexState({
settings: { index: { number_of_shards: 1, number_of_replicas: 1, frozen: 'true' } },
}),
});
getIndicesStats.mockResolvedValue({
indices: {
frozen_index: createTestIndexStats({ uuid: 'frozen_index' }),
},
});
});
getIndicesStats.mockResolvedValue({
indices: {
index_with_aliases: createTestIndexStats({ uuid: 'index_with_aliases' }),
},
});
await expect(router.runRequest(mockRequest)).resolves.toEqual({
body: [
createTestIndexResponse({
name: 'frozen_index',
uuid: 'frozen_index',
isFrozen: true,
await expect(router.runRequest(mockRequest)).resolves.toEqual({
body: [
createTestIndexResponse({
aliases: ['test_alias', 'another_alias'],
name: 'index_with_aliases',
uuid: 'index_with_aliases',
}),
],
});
});
test('frozen index', async () => {
getIndices.mockResolvedValue({
frozen_index: createTestIndexState({
settings: { index: { number_of_shards: 1, number_of_replicas: 1, frozen: 'true' } },
}),
],
});
});
test('hidden index', async () => {
getIndices.mockResolvedValue({
hidden_index: createTestIndexState({
settings: { index: { number_of_shards: 1, number_of_replicas: 1, hidden: 'true' } },
}),
});
getIndicesStats.mockResolvedValue({
indices: {
hidden_index: createTestIndexStats({ uuid: 'hidden_index' }),
},
});
});
getIndicesStats.mockResolvedValue({
indices: {
frozen_index: createTestIndexStats({ uuid: 'frozen_index' }),
},
});
await expect(router.runRequest(mockRequest)).resolves.toEqual({
body: [
createTestIndexResponse({
name: 'hidden_index',
uuid: 'hidden_index',
hidden: true,
await expect(router.runRequest(mockRequest)).resolves.toEqual({
body: [
createTestIndexResponse({
name: 'frozen_index',
uuid: 'frozen_index',
isFrozen: true,
}),
],
});
});
test('hidden index', async () => {
getIndices.mockResolvedValue({
hidden_index: createTestIndexState({
settings: { index: { number_of_shards: 1, number_of_replicas: 1, hidden: 'true' } },
}),
],
});
});
test('data stream index', async () => {
getIndices.mockResolvedValue({
data_stream_index: createTestIndexState({
data_stream: 'test_data_stream',
}),
});
getIndicesStats.mockResolvedValue({
indices: {
data_stream_index: createTestIndexStats({ uuid: 'data_stream_index' }),
},
});
});
getIndicesStats.mockResolvedValue({
indices: {
hidden_index: createTestIndexStats({ uuid: 'hidden_index' }),
},
});
await expect(router.runRequest(mockRequest)).resolves.toEqual({
body: [
createTestIndexResponse({
name: 'data_stream_index',
uuid: 'data_stream_index',
await expect(router.runRequest(mockRequest)).resolves.toEqual({
body: [
createTestIndexResponse({
name: 'hidden_index',
uuid: 'hidden_index',
hidden: true,
}),
],
});
});
test('data stream index', async () => {
getIndices.mockResolvedValue({
data_stream_index: createTestIndexState({
data_stream: 'test_data_stream',
}),
],
});
getIndicesStats.mockResolvedValue({
indices: {
data_stream_index: createTestIndexStats({ uuid: 'data_stream_index' }),
},
});
await expect(router.runRequest(mockRequest)).resolves.toEqual({
body: [
createTestIndexResponse({
name: 'data_stream_index',
uuid: 'data_stream_index',
data_stream: 'test_data_stream',
}),
],
});
});
test('index missing in stats call', async () => {
getIndices.mockResolvedValue({
index_missing_stats: createTestIndexState(),
});
// simulates when an index has been deleted after get indices call
// deleted index won't be present in the indices stats call response
getIndicesStats.mockResolvedValue({
indices: {
some_other_index: createTestIndexStats({ uuid: 'some_other_index' }),
},
});
await expect(router.runRequest(mockRequest)).resolves.toEqual({
body: [
createTestIndexResponse({
name: 'index_missing_stats',
uuid: undefined,
health: undefined,
status: undefined,
documents: 0,
size: '0b',
primary_size: '0b',
}),
],
});
});
});
test('index missing in stats call', async () => {
getIndices.mockResolvedValue({
index_missing_stats: createTestIndexState(),
describe('stateless', () => {
beforeAll(() => {
registerIndicesRoutes({
...routeDependencies,
config: {
...routeDependencies.config,
isSizeAndDocCountEnabled: true,
isIndexStatsEnabled: false,
},
router,
});
});
// simulates when an index has been deleted after get indices call
// deleted index won't be present in the indices stats call response
getIndicesStats.mockResolvedValue({
indices: {
some_other_index: createTestIndexStats({ uuid: 'some_other_index' }),
},
});
await expect(router.runRequest(mockRequest)).resolves.toEqual({
body: [
createTestIndexResponse({
name: 'index_missing_stats',
uuid: undefined,
health: undefined,
status: undefined,
documents: 0,
size: '0b',
primary_size: '0b',
}),
],
test('regular index', async () => {
getIndices.mockResolvedValue({
regular_index: createTestIndexState(),
});
getMeteringStats.mockResolvedValue({
indices: [{ name: 'regular_index', num_docs: 100, size_in_bytes: 1000 }],
});
await expect(router.runRequest(mockRequest)).resolves.toEqual({
body: [
{
name: 'regular_index',
isFrozen: false,
aliases: 'none',
hidden: false,
data_stream: undefined,
documents: 100,
size: '1000b',
},
],
});
});
});
});

View file

@ -11,6 +11,14 @@ import { IndexDataEnricher } from '../services';
import { Index } from '..';
import { RouteDependencies } from '../types';
interface MeteringStatsResponse {
indices: Array<{
name: string;
num_docs: number;
size_in_bytes: number;
}>;
}
async function fetchIndicesCall(
client: IScopedClusterClient,
config: RouteDependencies['config'],
@ -42,12 +50,18 @@ async function fetchIndicesCall(
const indicesNames = Object.keys(indices);
// Return response without index stats, if isIndexStatsEnabled === false
if (config.isIndexStatsEnabled === false) {
if (config.isIndexStatsEnabled) {
const { indices: indicesStats } = await client.asCurrentUser.indices.stats({
index: indexNamesString,
expand_wildcards: ['hidden', 'all'],
forbid_closed_indices: false,
metric: ['docs', 'store'],
});
return indicesNames.map((indexName: string) => {
const indexData = indices[indexName];
const aliases = Object.keys(indexData.aliases!);
return {
const baseResponse = {
name: indexName,
primary: indexData.settings?.index?.number_of_shards,
replica: indexData.settings?.index?.number_of_replicas,
@ -56,20 +70,69 @@ async function fetchIndicesCall(
hidden: indexData.settings?.index?.hidden === 'true',
data_stream: indexData.data_stream,
};
if (indicesStats) {
const indexStats = indicesStats[indexName];
return {
...baseResponse,
health: indexStats?.health,
status: indexStats?.status,
uuid: indexStats?.uuid,
documents: indexStats?.primaries?.docs?.count ?? 0,
documents_deleted: indexStats?.primaries?.docs?.deleted ?? 0,
size: new ByteSizeValue(indexStats?.total?.store?.size_in_bytes ?? 0).toString(),
primary_size: new ByteSizeValue(
indexStats?.primaries?.store?.size_in_bytes ?? 0
).toString(),
};
}
return baseResponse;
});
}
const { indices: indicesStats } = await client.asCurrentUser.indices.stats({
index: indexNamesString,
expand_wildcards: ['hidden', 'all'],
forbid_closed_indices: false,
metric: ['docs', 'store'],
});
// uses the _metering/stats API to get the number of documents and size of the index
// this API is only available in ES3
if (config.isSizeAndDocCountEnabled) {
const { indices: indicesStats } =
await client.asSecondaryAuthUser.transport.request<MeteringStatsResponse>({
method: 'GET',
path: `/_metering/stats/` + indexNamesString,
});
return indicesNames.map((indexName: string) => {
const indexData = indices[indexName];
const aliases = Object.keys(indexData.aliases!);
const baseResponse = {
name: indexName,
isFrozen: false,
aliases: aliases.length ? aliases : 'none',
hidden: indexData.settings?.index?.hidden === 'true',
data_stream: indexData.data_stream,
};
if (indicesStats) {
const indexStats = indicesStats.find((index) => index.name === indexName);
return {
...baseResponse,
documents: indexStats?.num_docs ?? 0,
size: new ByteSizeValue(indexStats?.size_in_bytes ?? 0).toString(),
};
}
return baseResponse;
});
}
// if neither index stats (Stateful only API)
// nor size and doc count are enabled (ES3 only API)
// return the base response
return indicesNames.map((indexName: string) => {
const indexData = indices[indexName];
const aliases = Object.keys(indexData.aliases!);
const baseResponse = {
return {
name: indexName,
primary: indexData.settings?.index?.number_of_shards,
replica: indexData.settings?.index?.number_of_replicas,
@ -78,25 +141,6 @@ async function fetchIndicesCall(
hidden: indexData.settings?.index?.hidden === 'true',
data_stream: indexData.data_stream,
};
if (indicesStats) {
const indexStats = indicesStats[indexName];
return {
...baseResponse,
health: indexStats?.health,
status: indexStats?.status,
uuid: indexStats?.uuid,
documents: indexStats?.primaries?.docs?.count ?? 0,
documents_deleted: indexStats?.primaries?.docs?.deleted ?? 0,
size: new ByteSizeValue(indexStats?.total?.store?.size_in_bytes ?? 0).toString(),
primary_size: new ByteSizeValue(
indexStats?.primaries?.store?.size_in_bytes ?? 0
).toString(),
};
}
return baseResponse;
});
}

View file

@ -55,7 +55,8 @@ export class IndexMgmtServerPlugin implements Plugin<IndexManagementPluginSetup,
config: {
isSecurityEnabled: () => security !== undefined && security.license.isEnabled(),
isLegacyTemplatesEnabled: this.config.enableLegacyTemplates,
isIndexStatsEnabled: this.config.enableIndexStats,
isIndexStatsEnabled: this.config.enableIndexStats ?? true,
isSizeAndDocCountEnabled: this.config.enableSizeAndDocCount ?? false,
isDataStreamStatsEnabled: this.config.enableDataStreamStats,
enableMappingsSourceFieldSection: this.config.enableMappingsSourceFieldSection,
enableTogglingDataRetention: this.config.enableTogglingDataRetention,

View file

@ -48,6 +48,7 @@ describe('GET privileges', () => {
isSecurityEnabled: () => true,
isLegacyTemplatesEnabled: true,
isIndexStatsEnabled: true,
isSizeAndDocCountEnabled: false,
isDataStreamStatsEnabled: true,
enableMappingsSourceFieldSection: true,
enableTogglingDataRetention: true,
@ -119,6 +120,7 @@ describe('GET privileges', () => {
isSecurityEnabled: () => false,
isLegacyTemplatesEnabled: true,
isIndexStatsEnabled: true,
isSizeAndDocCountEnabled: false,
isDataStreamStatsEnabled: true,
enableMappingsSourceFieldSection: true,
enableTogglingDataRetention: true,

View file

@ -48,6 +48,7 @@ describe('GET privileges', () => {
isSecurityEnabled: () => true,
isLegacyTemplatesEnabled: true,
isIndexStatsEnabled: true,
isSizeAndDocCountEnabled: false,
isDataStreamStatsEnabled: true,
enableMappingsSourceFieldSection: true,
enableTogglingDataRetention: true,
@ -119,6 +120,7 @@ describe('GET privileges', () => {
isSecurityEnabled: () => false,
isLegacyTemplatesEnabled: true,
isIndexStatsEnabled: true,
isSizeAndDocCountEnabled: false,
isDataStreamStatsEnabled: true,
enableMappingsSourceFieldSection: true,
enableTogglingDataRetention: true,

View file

@ -14,6 +14,7 @@ export const routeDependencies: Omit<RouteDependencies, 'router'> = {
isSecurityEnabled: jest.fn().mockReturnValue(true),
isLegacyTemplatesEnabled: true,
isIndexStatsEnabled: true,
isSizeAndDocCountEnabled: false,
isDataStreamStatsEnabled: true,
enableMappingsSourceFieldSection: true,
enableTogglingDataRetention: true,

View file

@ -96,6 +96,10 @@ export class RouterMock implements IRouter {
return get(this.contextMock.core.elasticsearch.client.asCurrentUser, path);
}
getMockESApiFnAsSecondaryAuthUser(path: string): jest.Mock {
return get(this.contextMock.core.elasticsearch.client.asSecondaryAuthUser, path);
}
runRequest({ method, path, ...mockRequest }: RequestMock) {
const handler = this.cacheHandlers[method][path];

View file

@ -25,6 +25,7 @@ export interface RouteDependencies {
isSecurityEnabled: () => boolean;
isLegacyTemplatesEnabled: boolean;
isIndexStatsEnabled: boolean;
isSizeAndDocCountEnabled: boolean;
isDataStreamStatsEnabled: boolean;
enableMappingsSourceFieldSection: boolean;
enableTogglingDataRetention: boolean;

View file

@ -63,7 +63,14 @@ export default function ({ getService }: FtrProviderContext) {
const sortedReceivedKeys = Object.keys(indexCreated).sort();
expect(sortedReceivedKeys).to.eql(['aliases', 'hidden', 'isFrozen', 'name']);
expect(sortedReceivedKeys).to.eql([
'aliases',
'documents',
'hidden',
'isFrozen',
'name',
'size',
]);
});
});
@ -77,7 +84,14 @@ export default function ({ getService }: FtrProviderContext) {
expect(index).to.be.ok();
expect(Object.keys(index).sort()).to.eql(['aliases', 'hidden', 'isFrozen', 'name']);
expect(Object.keys(index).sort()).to.eql([
'aliases',
'documents',
'hidden',
'isFrozen',
'name',
'size',
]);
});
it('throws 404 for a non-existent index', async () => {
@ -121,7 +135,14 @@ export default function ({ getService }: FtrProviderContext) {
expect(index).to.be.ok();
expect(Object.keys(index).sort()).to.eql(['aliases', 'hidden', 'isFrozen', 'name']);
expect(Object.keys(index).sort()).to.eql([
'aliases',
'documents',
'hidden',
'isFrozen',
'name',
'size',
]);
});
it('fails to re-create the same index', async () => {
@ -147,7 +168,14 @@ export default function ({ getService }: FtrProviderContext) {
(index: { name: string }) => index.name === 'reload-test-index'
);
const sortedReceivedKeys = Object.keys(indexCreated).sort();
expect(sortedReceivedKeys).to.eql(['aliases', 'hidden', 'isFrozen', 'name']);
expect(sortedReceivedKeys).to.eql([
'aliases',
'documents',
'hidden',
'isFrozen',
'name',
'size',
]);
expect(body.length > 1).to.be(true); // to contrast it with the next test
});