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] Mobile most launches #168925

Merged
merged 36 commits into from
Nov 6, 2023
Merged
Show file tree
Hide file tree
Changes from 21 commits
Commits
Show all changes
36 commits
Select commit Hold shift + click to select a range
ebc8f05
Creating get mobile launches by location
LikeTheSalad Sep 21, 2023
e8fb0fe
Adding most launches to location stats
LikeTheSalad Sep 21, 2023
cbcdff1
Connecting most launches data to dashboard
LikeTheSalad Oct 11, 2023
e67c0d0
Created helper function to get log events
LikeTheSalad Oct 11, 2023
2cb6a0d
Created helper function to get log events
LikeTheSalad Oct 11, 2023
f2acd01
Adding comment on reusing errors indices for events
LikeTheSalad Oct 11, 2023
c4da8f4
Adding iOS active state for launches query
LikeTheSalad Oct 13, 2023
84fe444
Adding mobile launch tests
LikeTheSalad Oct 13, 2023
700db7a
Updating settins tests to add event index
LikeTheSalad Oct 13, 2023
5c8b70b
Removing event unused config index
LikeTheSalad Oct 13, 2023
4e9b616
Merge branch 'main' into mobile-launches
kibanamachine Oct 16, 2023
75f759e
Adding ApmFields
LikeTheSalad Oct 17, 2023
ac0be49
Merge branch 'mobile-launches' of github.com:LikeTheSalad/kibana into…
LikeTheSalad Oct 17, 2023
8ed14d6
Revert "Removing event unused config index"
LikeTheSalad Oct 18, 2023
79e0a08
Merge branch 'main' into mobile-launches
kibanamachine Oct 18, 2023
9fc934b
Removing processorEvent.event
LikeTheSalad Oct 18, 2023
5ac126e
Adding event type response
LikeTheSalad Oct 18, 2023
d8b1777
Merge branch 'mobile-launches' of github.com:LikeTheSalad/kibana into…
LikeTheSalad Oct 18, 2023
61cbdbf
Adding log event type to log event search response
LikeTheSalad Oct 18, 2023
2f249de
Adding processor.event attr to mock events
LikeTheSalad Oct 18, 2023
eea243d
Merge branch 'main' into mobile-launches
kibanamachine Oct 19, 2023
5415f6f
Merge branch 'main' into mobile-launches
kibanamachine Oct 30, 2023
50a5463
Removing filter from APMEventClient.logEventSearch
LikeTheSalad Oct 30, 2023
894437f
Removing processor from event_raw
LikeTheSalad Oct 30, 2023
e17aca9
Creating and using constant LABEL_LIFECYCLE_STATE
LikeTheSalad Oct 30, 2023
faae624
Properly handling test index routing in tests
LikeTheSalad Oct 30, 2023
d1bbcfb
Adding event.action to apm fields
LikeTheSalad Oct 30, 2023
1697bbb
Updating es fields snapshot
LikeTheSalad Oct 30, 2023
4516b20
Update x-pack/plugins/apm/server/routes/mobile/get_mobile_launches_by…
LikeTheSalad Nov 2, 2023
8797da7
Merge branch 'main' into mobile-launches
kibanamachine Nov 3, 2023
7b0195f
Fixing lambda param usage
LikeTheSalad Nov 3, 2023
1f794c9
Fixing mobile data by location timeseries and adding tests for it
LikeTheSalad Nov 3, 2023
5cafe2f
Adding mobile location timeseries tests
LikeTheSalad Nov 3, 2023
fe3df19
Addressing type errors for tests
LikeTheSalad Nov 3, 2023
4716f62
Enhancing api tests
LikeTheSalad Nov 6, 2023
9749e39
Merge branch 'main' into mobile-launches
kibanamachine Nov 6, 2023
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
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ export type ApmUserAgentFields = Partial<{
export interface ApmException {
message: string;
}

export interface Observer {
type: string;
version: string;
Expand Down Expand Up @@ -94,6 +95,7 @@ export type ApmFields = Fields<{
'error.type': string;
'event.ingested': number;
'event.name': string;
'event.kind': string;
Copy link
Contributor

Choose a reason for hiding this comment

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

Is this a new field for mobile? What does it represent?

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 was looking for ways to narrow down generic logs to only the ones we send as "events" using OTel's event API and I noticed that the logs I was targeting have this event.kind field set to event, so that's why I used it. It seems to be an ECS field. However, I'm not sure if it's the best way to do what I needed, I recall @bryce-b mentioning that another alternative could be to use the event.action attr instead, which OTel sends as event.name, and we could filter it to this particular event name, which is lifecycle. Although things started to fail once I did the change so I reverted it back, but if that's a better option, I can spend some more time on it until it works.

Copy link
Contributor

Choose a reason for hiding this comment

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

thanks for the clarification. Can you reach out to the apm-server team to verify it?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

They mentioned that event.kind shouldn't be used for this use case, so I tried to replace it with event.action equals to lifecycle but doing so broke the tests in mobile_location_stats.spec.ts. I tried a couple of things to make them work with event.action without luck unfortunately. So in the end, I just removed all filters in this function, so that the only filters applied to the query would be the ones passed by the caller of this logEventSearch function. Which currently is only done in here where the labels.lifecycle_state term is passed as filter.

'event.outcome': string;
'event.outcome_numeric':
| number
Expand Down Expand Up @@ -121,6 +123,7 @@ export type ApmFields = Fields<{
'kubernetes.pod.uid': string;
'labels.name': string;
'labels.telemetry_auto_version': string;
'labels.lifecycle_state': string;
'metricset.name': string;
'network.carrier.icc': string;
'network.carrier.mcc': string;
Expand Down
36 changes: 36 additions & 0 deletions packages/kbn-apm-synthtrace-client/src/lib/apm/event.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
/*
* 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 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/

import { ApmFields } from './apm_fields';
import { Serializable } from '../serializable';

export class Event extends Serializable<ApmFields> {
constructor(fields: ApmFields) {
super({
...fields,
'event.kind': 'event',

// Real log events don't have the "processor.event" attribute. See: https://github.com/elastic/apm-server/pull/11494
// This is a hack needed for the tests in "mobile/mobile_location_stats.spec.ts" to pass since the "SynthtraceEsClient.index" function
// inside "packages/kbn-apm-synthtrace/src/lib/shared/base_client.ts" requires this "processor.event" attr to be available,
// otherwise it'd throw this error: "Could not determine operation: _index and _action not defined in document".
'processor.event': 'error',
LikeTheSalad marked this conversation as resolved.
Show resolved Hide resolved
});
}

lifecycle(state: string): this {
this.fields['labels.lifecycle_state'] = state;
return this;
}

override timestamp(timestamp: number) {
const ret = super.timestamp(timestamp);
this.fields['timestamp.us'] = timestamp * 1000;
return ret;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@
import { Entity } from '../entity';
import { Span } from './span';
import { Transaction } from './transaction';
import { ApmFields, SpanParams, GeoLocation, ApmApplicationMetricFields } from './apm_fields';
import { Event } from './event';
import { ApmApplicationMetricFields, ApmFields, GeoLocation, SpanParams } from './apm_fields';
import { generateLongId } from '../utils/generate_id';
import { Metricset } from './metricset';
import { ApmError } from './apm_error';
Expand Down Expand Up @@ -143,6 +144,10 @@ export class MobileDevice extends Entity<ApmFields> {
return this;
}

event(): Event {
return new Event({ ...this.fields });
}

transaction(
...options:
| [{ transactionName: string; frameworkName?: string; frameworkVersion?: string }]
Expand Down
29 changes: 28 additions & 1 deletion packages/kbn-apm-synthtrace-client/src/lib/apm/transaction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
*/

import { ApmError } from './apm_error';
import { Event } from './event';
import { BaseSpan } from './base_span';
import { generateShortId } from '../utils/generate_id';
import { ApmFields } from './apm_fields';
Expand All @@ -15,6 +16,7 @@ import { getBreakdownMetrics } from './processors/get_breakdown_metrics';
export class Transaction extends BaseSpan {
private _sampled: boolean = true;
private readonly _errors: ApmError[] = [];
private readonly _events: Event[] = [];

constructor(fields: ApmFields) {
super({
Expand All @@ -35,6 +37,27 @@ export class Transaction extends BaseSpan {
error.fields['transaction.sampled'] = this.fields['transaction.sampled'];
});

this._events.forEach((event) => {
event.fields['trace.id'] = this.fields['trace.id'];
event.fields['transaction.id'] = this.fields['transaction.id'];
event.fields['transaction.type'] = this.fields['transaction.type'];
event.fields['transaction.sampled'] = this.fields['transaction.sampled'];
});

return this;
}

events(...events: Event[]) {
events.forEach((event) => {
event.fields['trace.id'] = this.fields['trace.id'];
event.fields['transaction.id'] = this.fields['transaction.id'];
event.fields['transaction.name'] = this.fields['transaction.name'];
event.fields['transaction.type'] = this.fields['transaction.type'];
event.fields['transaction.sampled'] = this.fields['transaction.sampled'];
});

this._events.push(...events);

return this;
}

Expand Down Expand Up @@ -62,13 +85,17 @@ export class Transaction extends BaseSpan {
this._errors.forEach((error) => {
error.fields['transaction.sampled'] = sampled;
});
this._events.forEach((event) => {
event.fields['transaction.sampled'] = sampled;
});
return this;
}

serialize() {
const [transaction, ...spans] = super.serialize();

const errors = this._errors.flatMap((error) => error.serialize());
const logEvents = this._events.flatMap((event) => event.serialize());

const directChildren = this.getChildren().map((child) => child.fields);

Expand All @@ -80,6 +107,6 @@ export class Transaction extends BaseSpan {
events.push(...spans);
}

return events.concat(errors).concat(breakdownMetrics);
return events.concat(errors).concat(breakdownMetrics).concat(logEvents);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -163,17 +163,18 @@ export function MobileLocationStats({
trendShape: MetricTrendShape.Area,
},
{
color: euiTheme.eui.euiColorDisabled,
color: euiTheme.eui.euiColorLightestShade,
title: i18n.translate('xpack.apm.mobile.location.metrics.launches', {
defaultMessage: 'Most launches',
}),
subtitle: i18n.translate('xpack.apm.mobile.coming.soon', {
defaultMessage: 'Coming Soon',
extra: getComparisonValueFormatter({
currentPeriodValue: currentPeriod?.mostLaunches.value,
previousPeriodValue: previousPeriod?.mostLaunches.value,
}),
icon: getIcon('launch'),
value: NOT_AVAILABLE_LABEL,
value: currentPeriod?.mostLaunches.location ?? NOT_AVAILABLE_LABEL,
valueFormatter: (value) => `${value}`,
trend: [],
trend: currentPeriod?.mostLaunches.timeseries,
trendShape: MetricTrendShape.Area,
},
];
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ import type { APMIndices } from '@kbn/apm-data-access-plugin/server';
import { ProcessorEvent } from '@kbn/observability-plugin/common';
import { uniq } from 'lodash';
import { ApmDataSource } from '../../../../../common/data_source';
import {} from '../../../../../common/document_type';
import { PROCESSOR_EVENT } from '../../../../../common/es_fields/apm';
import {
getConfigForDocumentType,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,12 @@ import type {
FieldCapsResponse,
MsearchMultisearchBody,
MsearchMultisearchHeader,
TermsEnumResponse,
TermsEnumRequest,
TermsEnumResponse,
} from '@elastic/elasticsearch/lib/api/types';
import { ElasticsearchClient, KibanaRequest } from '@kbn/core/server';
import type { ESSearchRequest, InferSearchResponseOf } from '@kbn/es-types';
import { ESFilter } from '@kbn/es-types';
import { ProcessorEvent } from '@kbn/observability-plugin/common';
import { unwrapEsResponse } from '@kbn/observability-plugin/server';
import { compact, omit } from 'lodash';
Expand All @@ -26,6 +27,7 @@ import { APMError } from '../../../../../typings/es_schemas/ui/apm_error';
import { Metric } from '../../../../../typings/es_schemas/ui/metric';
import { Span } from '../../../../../typings/es_schemas/ui/span';
import { Transaction } from '../../../../../typings/es_schemas/ui/transaction';
import { Event } from '../../../../../typings/es_schemas/ui/event';
import { withApmSpan } from '../../../../utils/with_apm_span';
import {
callAsyncWithDebug,
Expand All @@ -46,6 +48,13 @@ export type APMEventESSearchRequest = Omit<ESSearchRequest, 'index'> & {
};
};

export type APMLogEventESSearchRequest = Omit<ESSearchRequest, 'index'> & {
body: {
size: number;
track_total_hits: boolean | number;
};
};

type APMEventWrapper<T> = Omit<T, 'index'> & {
apm: { events: ProcessorEvent[] };
};
Expand All @@ -63,6 +72,9 @@ type TypeOfProcessorEvent<T extends ProcessorEvent> = {
metric: Metric;
}[T];

type TypedLogEventSearchResponse<TParams extends APMLogEventESSearchRequest> =
InferSearchResponseOf<Event, TParams>;

type TypedSearchResponse<TParams extends APMEventESSearchRequest> =
InferSearchResponseOf<
TypeOfProcessorEvent<
Expand Down Expand Up @@ -196,6 +208,50 @@ export class APMEventClient {
});
}

async logEventSearch<TParams extends APMLogEventESSearchRequest>(
operationName: string,
params: TParams
): Promise<TypedLogEventSearchResponse<TParams>> {
// Reusing indices configured for errors since both events and errors are stored as logs.
const index = processorEventsToIndex([ProcessorEvent.error], this.indices);

const filters: ESFilter[] = [
{
terms: {
['event.kind']: ['event'],
LikeTheSalad marked this conversation as resolved.
Show resolved Hide resolved
},
},
];

const searchParams = {
...omit(params, 'body'),
index,
body: {
...params.body,
query: {
bool: {
filter: filters,
must: compact([params.body.query]),
},
},
},
...(this.includeFrozen ? { ignore_throttled: false } : {}),
ignore_unavailable: true,
preference: 'any',
expand_wildcards: ['open' as const, 'hidden' as const],
};

return this.callAsyncWithDebug({
cb: (opts) =>
this.esClient.search(searchParams, opts) as unknown as Promise<{
body: TypedLogEventSearchResponse<TParams>;
}>,
operationName,
params: searchParams,
requestType: 'search',
});
}

async msearch<TParams extends APMEventESSearchRequest>(
operationName: string,
...allParams: TParams[]
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
/*
* 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 {
kqlQuery,
rangeQuery,
termQuery,
} from '@kbn/observability-plugin/server';
import { SERVICE_NAME } from '../../../common/es_fields/apm';
import { APMEventClient } from '../../lib/helpers/create_es_client/create_apm_event_client';
import { getOffsetInMs } from '../../../common/utils/get_offset_in_ms';
import { getBucketSize } from '../../../common/utils/get_bucket_size';
import { environmentQuery } from '../../../common/utils/environment_query';

interface Props {
kuery: string;
apmEventClient: APMEventClient;
serviceName: string;
environment: string;
start: number;
end: number;
locationField?: string;
offset?: string;
}

export async function getLaunchesByLocation({
kuery,
apmEventClient,
serviceName,
environment,
start,
end,
locationField,
offset,
}: Props) {
const { startWithOffset, endWithOffset } = getOffsetInMs({
start,
end,
offset,
});

const { intervalString } = getBucketSize({
start: startWithOffset,
end: endWithOffset,
minBucketSize: 60,
});

const aggs = {
launches: {
filter: {
terms: { ['labels.lifecycle_state']: ['created', 'active'] },
Copy link
Contributor

Choose a reason for hiding this comment

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

nit: Can you please convert labels.lifecycle_state as constant. Similar https://github.com/LikeTheSalad/kibana/blob/3a48bc9289b7dc9b8ecdebbf224a55686a5078f1/x-pack/plugins/apm/common/es_fields/apm.ts#L192C1-L192C1

Also, the values created and active can be enum.

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've converted labels.lifecycle_state to constant 👍 However, regarding creating enums for created and active, I'm not sure what could be a proper file to place them? Also, I guess we'd have to create 2 separate enums, one for android events which would contain created and other for iOS's events with active?

},
aggs: {
byLocation: {
terms: {
field: locationField,
},
},
},
},
};

const response = await apmEventClient.logEventSearch(
LikeTheSalad marked this conversation as resolved.
Show resolved Hide resolved
'get_mobile_location_launches',
{
body: {
track_total_hits: false,
size: 0,
query: {
bool: {
filter: [
...termQuery(SERVICE_NAME, serviceName),
...rangeQuery(startWithOffset, endWithOffset),
...environmentQuery(environment),
...kqlQuery(kuery),
],
},
},
aggs: {
timeseries: {
date_histogram: {
field: '@timestamp',
fixed_interval: intervalString,
min_doc_count: 0,
},
aggs,
},
...aggs,
},
},
}
);

return {
location: response.aggregations?.launches?.byLocation?.buckets[0]
?.key as string,
value:
response.aggregations?.launches?.byLocation?.buckets[0]?.doc_count ?? 0,
timeseries:
response.aggregations?.timeseries?.buckets.map((bucket) => ({
x: bucket.key,
y:
response.aggregations?.launches?.byLocation?.buckets[0]?.doc_count ??
Copy link
Contributor

Choose a reason for hiding this comment

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

Suggested change
response.aggregations?.launches?.byLocation?.buckets[0]?.doc_count ??
bucket.launches?.byLocation?.buckets[0]?.doc_count ?? 0

Otherwise, you'll always return the total launches for the timeseries.
it seems we have introduced this bug here

response.aggregations?.requests?.requestsByLocation?.buckets[0]

can you please fix there as well 🙏

Copy link
Contributor

Choose a reason for hiding this comment

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

Could you also please add an API test to prevent this issue? It appears that our existing tests were insufficient in identifying this problem

Copy link
Contributor Author

@LikeTheSalad LikeTheSalad Nov 3, 2023

Choose a reason for hiding this comment

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

Hi @kpatticha - I've just made these changes, fixed the same issue for get_mobile_http_requests_by_location.ts and also I had to fix it in here as well:

response.aggregations?.crashes?.crashesByLocation?.buckets[0]

I've also updated the API test to verify the changes. It should be good now, cheers!

0,
})) ?? [],
};
}
Loading