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

Fleet Usage telemetry extension #145353

Merged
merged 16 commits into from
Nov 23, 2022
Merged
Show file tree
Hide file tree
Changes from 8 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
96 changes: 96 additions & 0 deletions x-pack/plugins/fleet/server/collectors/agent_collectors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,9 @@
import type { SavedObjectsClient, ElasticsearchClient } from '@kbn/core/server';

import type { FleetConfigType } from '../../common/types';
import { AGENTS_INDEX } from '../../common';
import * as AgentService from '../services/agents';
import { appContextService } from '../services';

export interface AgentUsage {
total_enrolled: number;
Expand Down Expand Up @@ -47,3 +49,97 @@ export const getAgentUsage = async (
updating,
};
};

export interface AgentData {
agent_versions: string[];
agent_checkin_status: {
error: number;
degraded: number;
};
agent_checkin_status_last_1h: {
error: number;
degraded: number;
};
}

const DEFAULT_AGENT_DATA = {
agent_versions: [],
agent_checkin_status: { error: 0, degraded: 0 },
agent_checkin_status_last_1h: { error: 0, degraded: 0 },
};

export const getAgentData = async (esClient?: ElasticsearchClient): Promise<AgentData> => {
Copy link
Member

Choose a reason for hiding this comment

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

it will be a great improvements to write an integration tests for these collectors(I think it's doable with a jest integration test).
Maybe this can be done in a follow up issue if it's too much work.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I'll look into adding integration tests.

I think I might create a separate pr for the agent logs collector too, since that depends on ES change.

Copy link
Contributor Author

@juliaElastic juliaElastic Nov 22, 2022

Choose a reason for hiding this comment

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

Added integration test.
I wonder how could we improve the integration test framework, it seems rather slow to start up an ES instance for every test. And it is slow to test changes locally too.
Raised a separate issue for improvements: #145988

if (!esClient) {
return DEFAULT_AGENT_DATA;
}
try {
const transformLastCheckinStatusBuckets = (resp: any) =>
((resp?.aggregations?.last_checkin_status as any).buckets ?? []).reduce(
(acc: any, bucket: any) => {
if (acc[bucket.key] !== undefined) acc[bucket.key] = bucket.doc_count;
return acc;
},
{ error: 0, degraded: 0 }
);
const response = await esClient.search({
index: AGENTS_INDEX,
size: 0,
aggs: {
versions: {
terms: { field: 'agent.version' },
},
last_checkin_status: {
terms: { field: 'last_checkin_status' },
},
},
});
const versions = ((response?.aggregations?.versions as any).buckets ?? []).map(
(bucket: any) => bucket.key
);
const statuses = transformLastCheckinStatusBuckets(response);

const responseLast1h = await esClient.search({
index: AGENTS_INDEX,
size: 0,
query: {
bool: {
filter: [
{
bool: {
must: [
{
range: {
last_checkin: {
gte: 'now-1h/h',
lt: 'now/h',
},
},
},
],
},
},
],
},
},
aggs: {
last_checkin_status: {
terms: { field: 'last_checkin_status' },
},
},
});
const statusesLast1h = transformLastCheckinStatusBuckets(responseLast1h);

return {
agent_versions: versions,
agent_checkin_status: statuses,
agent_checkin_status_last_1h: statusesLast1h,
};
} catch (error) {
if (error.statusCode === 404) {
appContextService.getLogger().debug('Index .fleet-agents does not exist yet.');
} else {
throw error;
}
return DEFAULT_AGENT_DATA;
}
};
42 changes: 42 additions & 0 deletions x-pack/plugins/fleet/server/collectors/agent_policies.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
/*
* 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 { SavedObjectsClient, ElasticsearchClient } from '@kbn/core/server';

import { AGENT_POLICY_INDEX } from '../../common';
import { ES_SEARCH_LIMIT } from '../../common/constants';

export const getAgentPoliciesUsage = async (
soClient?: SavedObjectsClient,
esClient?: ElasticsearchClient
): Promise<any> => {
if (!soClient || !esClient) {
return {};
}

const res = await esClient.search({
index: AGENT_POLICY_INDEX,
size: ES_SEARCH_LIMIT,
track_total_hits: true,
rest_total_hits_as_int: true,
});

const agentPolicies = res.hits.hits;

const outputTypes = new Set<string>();
agentPolicies.forEach((item) => {
const source = (item._source as any) ?? {};
Object.keys(source.data.outputs).forEach((output) => {
outputTypes.add(source.data.outputs[output].type);
});
});

return {
count: res.hits.total,
output_types: Array.from(outputTypes),
};
};
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@

import type { SavedObjectsClient, ElasticsearchClient } from '@kbn/core/server';

import { PACKAGE_POLICY_SAVED_OBJECT_TYPE, SO_SEARCH_LIMIT } from '../constants';

import { packagePolicyService } from '../services';
import { getAgentStatusForAgentPolicy } from '../services/agents';
import { listFleetServerHosts } from '../services/fleet_server_host';
Expand Down Expand Up @@ -84,3 +86,32 @@ export const getFleetServerUsage = async (
num_host_urls: numHostsUrls,
};
};

export const getFleetServerConfig = async (
soClient?: SavedObjectsClient,
esClient?: ElasticsearchClient
): Promise<any> => {
if (!soClient || !esClient) {
return {};
}
const fleetServerHosts = await listFleetServerHosts(soClient);
const hosts = fleetServerHosts.items.map((item) => ({
...item,
proxy_id: (item as any).proxy_id ?? '',
}));

const res = await packagePolicyService.list(soClient, {
page: 1,
perPage: SO_SEARCH_LIMIT,
kuery: `${PACKAGE_POLICY_SAVED_OBJECT_TYPE}.package.name:fleet_server`,
});
const policies = res.items.map((item) => ({
id: item.id,
name: item.name,
enabled: item.enabled,
policy_id: item.policy_id,
input_config: (item.inputs[0] ?? {}).compiled_input,
}));

return { hosts, policies };
};
22 changes: 19 additions & 3 deletions x-pack/plugins/fleet/server/collectors/register.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,14 @@ import type { CoreSetup } from '@kbn/core/server';
import type { FleetConfigType } from '..';

import { getIsAgentsEnabled } from './config_collectors';
import { getAgentUsage } from './agent_collectors';
import { getAgentUsage, getAgentData } from './agent_collectors';
import type { AgentUsage } from './agent_collectors';
import { getInternalClients } from './helpers';
import { getPackageUsage } from './package_collectors';
import type { PackageUsage } from './package_collectors';
import { getFleetServerUsage } from './fleet_server_collector';
import { getFleetServerUsage, getFleetServerConfig } from './fleet_server_collector';
import type { FleetServerUsage } from './fleet_server_collector';
import { getAgentPoliciesUsage } from './agent_policies';

export interface Usage {
agents_enabled: boolean;
Expand All @@ -26,7 +27,22 @@ export interface Usage {
fleet_server: FleetServerUsage;
}

export const fetchUsage = async (core: CoreSetup, config: FleetConfigType) => {
export const fetchFleetUsage = async (core: CoreSetup, config: FleetConfigType) => {
const [soClient, esClient] = await getInternalClients(core);
const usage = {
agents_enabled: getIsAgentsEnabled(config),
agents: await getAgentUsage(config, soClient, esClient),
fleet_server: await getFleetServerUsage(soClient, esClient),
packages: await getPackageUsage(soClient),
...(await getAgentData(esClient)),
fleet_server_config: await getFleetServerConfig(soClient, esClient),
agent_policies: await getAgentPoliciesUsage(soClient, esClient),
};
return usage;
};

// used by kibana daily collector
const fetchUsage = async (core: CoreSetup, config: FleetConfigType) => {
const [soClient, esClient] = await getInternalClients(core);
const usage = {
agents_enabled: getIsAgentsEnabled(config),
Expand Down
16 changes: 7 additions & 9 deletions x-pack/plugins/fleet/server/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,11 @@ import {
AgentServiceImpl,
PackageServiceImpl,
} from './services';
import { registerFleetUsageCollector, fetchUsage, fetchAgentsUsage } from './collectors/register';
import {
registerFleetUsageCollector,
fetchAgentsUsage,
fetchFleetUsage,
} from './collectors/register';
import { getAuthzFromRequest, makeRouterWithFleetAuthz } from './routes/security';
import { FleetArtifactsClient } from './services/artifacts';
import type { FleetRouter } from './types/request_context';
Expand Down Expand Up @@ -370,14 +374,8 @@ export class FleetPlugin

// Register usage collection
registerFleetUsageCollector(core, config, deps.usageCollection);
const fetch = async () => fetchUsage(core, config);
this.fleetUsageSender = new FleetUsageSender(
deps.taskManager,
core,
fetch,
this.kibanaVersion,
this.isProductionMode
);
const fetch = async () => fetchFleetUsage(core, config);
this.fleetUsageSender = new FleetUsageSender(deps.taskManager, core, fetch);
registerFleetUsageLogger(deps.taskManager, async () => fetchAgentsUsage(core, config));

const router: FleetRouter = core.http.createRouter<FleetRequestHandlerContext>();
Expand Down
Loading