Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[APM] NP Migration - Saved Objects Client #57438

Closed
Closed
Show file tree
Hide file tree
Changes from 1 commit
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
5 changes: 1 addition & 4 deletions x-pack/legacy/plugins/apm/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ import { APMPluginContract } from '../../../plugins/apm/server';
import { LegacyPluginInitializer } from '../../../../src/legacy/types';
import { DEFAULT_APP_CATEGORIES } from '../../../../src/core/utils';
import mappings from './mappings.json';
import { makeApmUsageCollector } from './server/lib/apm_telemetry';

export const apm: LegacyPluginInitializer = kibana => {
return new kibana.Plugin({
Expand Down Expand Up @@ -109,11 +108,9 @@ export const apm: LegacyPluginInitializer = kibana => {
}
}
});
const { usageCollection } = server.newPlatform.setup.plugins;
makeApmUsageCollector(usageCollection, server);

const apmPlugin = server.newPlatform.setup.plugins
.apm as APMPluginContract;

apmPlugin.registerLegacyAPI({ server });
}
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,25 +45,10 @@ describe('apm_telemetry', () => {
});

describe('storeApmServicesTelemetry', () => {
let server: any;
let apmTelemetry: SavedObjectAttributes;
let savedObjectsClientInstance: any;
let savedObjectsClient: any;

beforeEach(() => {
savedObjectsClientInstance = { create: jest.fn() };
const callWithInternalUser = jest.fn();
const internalRepository = jest.fn();
server = {
savedObjects: {
SavedObjectsClient: jest.fn(() => savedObjectsClientInstance),
getSavedObjectsRepository: jest.fn(() => internalRepository)
},
plugins: {
elasticsearch: {
getCluster: jest.fn(() => ({ callWithInternalUser }))
}
}
};
apmTelemetry = {
has_any_services: true,
services_per_agent: {
Expand All @@ -72,30 +57,27 @@ describe('apm_telemetry', () => {
'js-base': 1
}
};
savedObjectsClient = { create: jest.fn() };
});

it('should call savedObjectsClient create with the given ApmTelemetry object', () => {
storeApmServicesTelemetry(server, apmTelemetry);
expect(savedObjectsClientInstance.create.mock.calls[0][1]).toBe(
apmTelemetry
);
storeApmServicesTelemetry(savedObjectsClient, apmTelemetry);
expect(savedObjectsClient.create.mock.calls[0][1]).toBe(apmTelemetry);
});

it('should call savedObjectsClient create with the apm-telemetry document type and ID', () => {
storeApmServicesTelemetry(server, apmTelemetry);
expect(savedObjectsClientInstance.create.mock.calls[0][0]).toBe(
storeApmServicesTelemetry(savedObjectsClient, apmTelemetry);
expect(savedObjectsClient.create.mock.calls[0][0]).toBe(
APM_SERVICES_TELEMETRY_SAVED_OBJECT_TYPE
);
expect(savedObjectsClientInstance.create.mock.calls[0][2].id).toBe(
expect(savedObjectsClient.create.mock.calls[0][2].id).toBe(
APM_SERVICES_TELEMETRY_SAVED_OBJECT_ID
);
});

it('should call savedObjectsClient create with overwrite: true', () => {
storeApmServicesTelemetry(server, apmTelemetry);
expect(savedObjectsClientInstance.create.mock.calls[0][2].overwrite).toBe(
true
);
storeApmServicesTelemetry(savedObjectsClient, apmTelemetry);
expect(savedObjectsClient.create.mock.calls[0][2].overwrite).toBe(true);
});
});
});
34 changes: 14 additions & 20 deletions x-pack/legacy/plugins/apm/server/lib/apm_telemetry/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,12 @@
*/

import { countBy } from 'lodash';
import { SavedObjectAttributes } from 'src/core/server';
import { SavedObjectAttributes, SavedObjectsClient } from 'src/core/server';
import { isAgentName } from '../../../common/agent_name';
import { getInternalSavedObjectsClient } from '../helpers/saved_objects_client';
import {
APM_SERVICES_TELEMETRY_SAVED_OBJECT_TYPE,
APM_SERVICES_TELEMETRY_SAVED_OBJECT_ID
} from '../../../common/apm_saved_object_constants';
import { APMLegacyServer } from '../../routes/typings';
import { UsageCollectionSetup } from '../../../../../../../src/plugins/usage_collection/server';

export function createApmTelementry(
Expand All @@ -25,35 +23,31 @@ export function createApmTelementry(
};
}

type ISavedObjectsClient = Pick<SavedObjectsClient, 'create' | 'get'>;

export async function storeApmServicesTelemetry(
server: APMLegacyServer,
savedObjectsClient: ISavedObjectsClient,
apmTelemetry: SavedObjectAttributes
) {
try {
const savedObjectsClient = getInternalSavedObjectsClient(server);
await savedObjectsClient.create(
APM_SERVICES_TELEMETRY_SAVED_OBJECT_TYPE,
apmTelemetry,
{
id: APM_SERVICES_TELEMETRY_SAVED_OBJECT_ID,
overwrite: true
}
);
} catch (e) {
server.log(['error'], `Unable to save APM telemetry data: ${e.message}`);
}
return savedObjectsClient.create(
APM_SERVICES_TELEMETRY_SAVED_OBJECT_TYPE,
apmTelemetry,
{
id: APM_SERVICES_TELEMETRY_SAVED_OBJECT_ID,
overwrite: true
}
);
}

export function makeApmUsageCollector(
usageCollector: UsageCollectionSetup,
server: APMLegacyServer
savedObjectsRepository: ISavedObjectsClient
) {
const apmUsageCollector = usageCollector.makeUsageCollector({
type: 'apm',
fetch: async () => {
const internalSavedObjectsClient = getInternalSavedObjectsClient(server);
try {
const apmTelemetrySavedObject = await internalSavedObjectsClient.get(
const apmTelemetrySavedObject = await savedObjectsRepository.get(
APM_SERVICES_TELEMETRY_SAVED_OBJECT_TYPE,
APM_SERVICES_TELEMETRY_SAVED_OBJECT_ID
);
Expand Down

This file was deleted.

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -6,42 +6,30 @@

import { createStaticIndexPattern } from './create_static_index_pattern';
import { Setup } from '../helpers/setup_request';
import * as savedObjectsClient from '../helpers/saved_objects_client';
import * as HistoricalAgentData from '../services/get_services/has_historical_agent_data';
import { APMRequestHandlerContext } from '../../routes/typings';

function getMockContext(config: Record<string, unknown>) {
return ({
config,
__LEGACY: {
server: {
savedObjects: {
getSavedObjectsRepository: jest.fn()
core: {
savedObjects: {
client: {
create: jest.fn()
}
}
}
} as unknown) as APMRequestHandlerContext;
}

describe('createStaticIndexPattern', () => {
let createSavedObject: jest.Mock;
beforeEach(() => {
createSavedObject = jest.fn();
jest
.spyOn(savedObjectsClient, 'getInternalSavedObjectsClient')
.mockReturnValue({
create: createSavedObject
} as any);
});

it(`should not create index pattern if 'xpack.apm.autocreateApmIndexPattern=false'`, async () => {
const setup = {} as Setup;
const context = getMockContext({
'xpack.apm.autocreateApmIndexPattern': false
});
await createStaticIndexPattern(setup, context);

expect(createSavedObject).not.toHaveBeenCalled();
expect(context.core.savedObjects.client.create).not.toHaveBeenCalled();
});

it(`should not create index pattern if no APM data is found`, async () => {
Expand All @@ -56,7 +44,7 @@ describe('createStaticIndexPattern', () => {
.mockResolvedValue(false);

await createStaticIndexPattern(setup, context);
expect(createSavedObject).not.toHaveBeenCalled();
expect(context.core.savedObjects.client.create).not.toHaveBeenCalled();
});

it(`should create index pattern`, async () => {
Expand All @@ -71,6 +59,6 @@ describe('createStaticIndexPattern', () => {
.mockResolvedValue(true);
await createStaticIndexPattern(setup, context);

expect(createSavedObject).toHaveBeenCalled();
expect(context.core.savedObjects.client.create).toHaveBeenCalled();
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
import { getInternalSavedObjectsClient } from '../helpers/saved_objects_client';
// eslint-disable-next-line @kbn/eslint/no-restricted-paths
import apmIndexPattern from '../../../../../../plugins/apm/server/tutorial/index_pattern.json';
import { APM_STATIC_INDEX_PATTERN_ID } from '../../../common/index_pattern_constants';
Expand Down Expand Up @@ -33,10 +32,8 @@ export async function createStaticIndexPattern(

try {
const apmIndexPatternTitle = config['apm_oss.indexPattern'];
const internalSavedObjectsClient = getInternalSavedObjectsClient(
context.__LEGACY.server
);
await internalSavedObjectsClient.create(
const savedObjectsClient = context.core.savedObjects.client;
await savedObjectsClient.create(
'index-pattern',
{
...apmIndexPattern.attributes,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

import { merge } from 'lodash';
import { Server } from 'hapi';
import { SavedObjectsClientContract } from 'kibana/server';
import { SavedObjectsClient } from 'src/core/server';
import { PromiseReturnType } from '../../../../typings/common';
import {
APM_INDICES_SAVED_OBJECT_TYPE,
Expand All @@ -15,6 +15,8 @@ import {
import { APMConfig } from '../../../../../../../plugins/apm/server';
import { APMRequestHandlerContext } from '../../../routes/typings';

type ISavedObjectsClient = Pick<SavedObjectsClient, 'create' | 'get'>;

export interface ApmIndicesConfig {
'apm_oss.sourcemapIndices': string;
'apm_oss.errorIndices': string;
Expand All @@ -32,7 +34,7 @@ export type ScopedSavedObjectsClient = ReturnType<
>;

async function getApmIndicesSavedObject(
savedObjectsClient: SavedObjectsClientContract
savedObjectsClient: ISavedObjectsClient
) {
const apmIndices = await savedObjectsClient.get<Partial<ApmIndicesConfig>>(
APM_INDICES_SAVED_OBJECT_TYPE,
Expand All @@ -59,7 +61,7 @@ export async function getApmIndices({
savedObjectsClient
}: {
config: APMConfig;
savedObjectsClient: SavedObjectsClientContract;
savedObjectsClient: ISavedObjectsClient;
}) {
try {
const apmIndicesSavedObject = await getApmIndicesSavedObject(
Expand Down
2 changes: 1 addition & 1 deletion x-pack/legacy/plugins/apm/server/routes/services.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ export const servicesRoute = createRoute(() => ({
({ agentName }) => agentName as AgentName
);
const apmTelemetry = createApmTelementry(agentNames);
storeApmServicesTelemetry(context.__LEGACY.server, apmTelemetry);
storeApmServicesTelemetry(context.core.savedObjects.client, apmTelemetry);

return services;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,7 @@ export const hasAPMData = async (
nodeId: string,
nodeType: InventoryItemType
) => {
const apmIndices = await framework.plugins.apm.getApmIndices(
requestContext.core.savedObjects.client
);
const apmIndices = await framework.plugins.apm.getApmIndices();
Copy link
Member

Choose a reason for hiding this comment

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

Nice!!

const apmIndex = apmIndices['apm_oss.transactionIndices'] || 'apm-*';
const fields = findInventoryFields(nodeType, sourceConfiguration.fields);

Expand Down
2 changes: 1 addition & 1 deletion x-pack/plugins/apm/kibana.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,5 @@
"configPath": ["xpack", "apm"],
"ui": false,
"requiredPlugins": ["apm_oss", "data", "home"],
"optionalPlugins": ["cloud"]
"optionalPlugins": ["cloud", "usageCollection"]
}
Loading