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] Fix links to Logs view to point to Discover in Serverless #171525

Merged
merged 5 commits into from
Nov 21, 2023
Merged
Show file tree
Hide file tree
Changes from 4 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
Original file line number Diff line number Diff line change
Expand Up @@ -4,21 +4,14 @@
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/

import url from 'url';
import { stringify } from 'querystring';

import React, { memo, useMemo, useState, useCallback, useEffect } from 'react';
import styled from 'styled-components';
import { encode } from '@kbn/rison';
import {
EuiFlexGroup,
EuiFlexItem,
EuiSuperDatePicker,
EuiFilterGroup,
EuiPanel,
EuiButton,
EuiButtonEmpty,
EuiCallOut,
EuiLink,
} from '@elastic/eui';
Expand All @@ -42,6 +35,7 @@ import { LogLevelFilter } from './filter_log_level';
import { LogQueryBar } from './query_bar';
import { buildQuery } from './build_query';
import { SelectLogLevel } from './select_log_level';
import { ViewLogsButton } from './view_logs_button';

const WrapperFlexGroup = styled(EuiFlexGroup)`
height: 100%;
Expand Down Expand Up @@ -118,7 +112,7 @@ const AgentPolicyLogsNotEnabledCallout: React.FunctionComponent<{ agentPolicy: A

export const AgentLogsUI: React.FunctionComponent<AgentLogsProps> = memo(
({ agent, agentPolicy, state }) => {
const { data, application, http, cloud } = useStartServices();
const { data, application, cloud } = useStartServices();
const { update: updateState } = AgentLogsUrlStateHelper.useTransitions();
const isLogsUIAvailable = !cloud?.isServerlessEnabled;

Expand Down Expand Up @@ -218,37 +212,6 @@ export const AgentLogsUI: React.FunctionComponent<AgentLogsProps> = memo(
[agent.id, state.datasets, state.logLevels, state.query]
);

// Generate URL to pass page state to Logs UI
const viewInLogsUrl = useMemo(
() =>
http.basePath.prepend(
url.format({
pathname: '/app/logs/stream',
search: stringify({
logPosition: encode({
start: state.start,
end: state.end,
streamLive: false,
}),
logFilter: encode({
expression: logStreamQuery,
kind: 'kuery',
}),
}),
})
),
[http.basePath, state.start, state.end, logStreamQuery]
);

const viewInDiscoverUrl = useMemo(() => {
const index = 'logs-*';
const datasetQuery = 'data_stream.dataset:elastic_agent';
const agentIdQuery = `elastic_agent.id:${agent.id}`;
return http.basePath.prepend(
`/app/discover#/?_a=(index:'${index}',query:(language:kuery,query:'${datasetQuery}%20AND%20${agentIdQuery}'))`
);
}, [http.basePath, agent.id]);

const agentVersion = agent.local_metadata?.elastic?.agent?.version;
const isLogFeatureAvailable = useMemo(() => {
if (!agentVersion) {
Expand Down Expand Up @@ -357,30 +320,12 @@ export const AgentLogsUI: React.FunctionComponent<AgentLogsProps> = memo(
application,
}}
>
{isLogsUIAvailable ? (
<EuiButtonEmpty
href={viewInLogsUrl}
iconType="popout"
flush="both"
data-test-subj="viewInLogsBtn"
>
<FormattedMessage
id="xpack.fleet.agentLogs.openInLogsUiLinkText"
defaultMessage="Open in Logs"
/>
</EuiButtonEmpty>
) : (
<EuiButton
href={viewInDiscoverUrl}
iconType="popout"
data-test-subj="viewInDiscoverBtn"
>
<FormattedMessage
id="xpack.fleet.agentLogs.openInDiscoverUiLinkText"
defaultMessage="Open in Discover"
/>
</EuiButton>
)}
<ViewLogsButton
viewInLogs={isLogsUIAvailable}
logStreamQuery={logStreamQuery}
startTime={state.start}
endTime={state.end}
/>
</RedirectAppLinks>
</EuiFlexItem>
</EuiFlexGroup>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
/*
* 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 url from 'url';
import { stringify } from 'querystring';

import React, { useMemo } from 'react';
import { encode } from '@kbn/rison';
import { EuiButton } from '@elastic/eui';
import { FormattedMessage } from '@kbn/i18n-react';

import { useStartServices } from '../../../../../hooks';

interface ViewLogsProps {
viewInLogs: boolean;
logStreamQuery: string;
startTime: string;
endTime: string;
}

/*
Button that takes to the Logs view Ui when that is available, otherwise fallback to the Discover UI
The urls are built using same logStreamQuery (provided by a prop), startTime and endTime, ensuring that they'll both will target same log lines
*/
export const ViewLogsButton: React.FunctionComponent<ViewLogsProps> = ({
viewInLogs,
logStreamQuery,
startTime,
endTime,
}) => {
const { http } = useStartServices();

// Generate URL to pass page state to Logs UI
const viewInLogsUrl = useMemo(
() =>
http.basePath.prepend(
url.format({
pathname: '/app/logs/stream',
search: stringify({
logPosition: encode({
start: startTime,
end: endTime,
streamLive: false,
}),
logFilter: encode({
expression: logStreamQuery,
kind: 'kuery',
}),
}),
})
),
[http.basePath, startTime, endTime, logStreamQuery]
);

const viewInDiscoverUrl = useMemo(() => {
const index = 'logs-*';
const query = encode({
query: logStreamQuery,
language: 'kuery',
});
return http.basePath.prepend(
`/app/discover#/?_g=(filters:!(),refreshInterval:(pause:!t,value:60000),time:(from:'${startTime}',to:'${endTime}'))&_a=(columns:!(event.dataset,message),index:'${index}',query:${query})`
);
}, [logStreamQuery, http.basePath, startTime, endTime]);

return (
criamico marked this conversation as resolved.
Show resolved Hide resolved
<>
{viewInLogs ? (
<EuiButton href={viewInLogsUrl} iconType="popout" data-test-subj="viewInLogsBtn">
<FormattedMessage
id="xpack.fleet.agentLogs.openInLogsUiLinkText"
defaultMessage="Open in Logs"
/>
</EuiButton>
) : (
<EuiButton href={viewInDiscoverUrl} iconType="popout" data-test-subj="viewInDiscoverBtn">
<FormattedMessage
id="xpack.fleet.agentLogs.openInDiscoverUiLinkText"
defaultMessage="Open in Discover"
/>
</EuiButton>
)}
</>
);
};
Original file line number Diff line number Diff line change
Expand Up @@ -5,21 +5,18 @@
* 2.0.
*/

import { stringify } from 'querystring';

import styled from 'styled-components';
import React from 'react';
import { encode } from '@kbn/rison';
import type { EuiBasicTableProps } from '@elastic/eui';
import { EuiButton, EuiAccordion, EuiToolTip, EuiText, EuiBasicTable } from '@elastic/eui';
import { FormattedMessage } from '@kbn/i18n-react';
import { EuiAccordion, EuiToolTip, EuiText, EuiBasicTable } from '@elastic/eui';
import { RedirectAppLinks } from '@kbn/shared-ux-link-redirect-app';

import { i18n } from '@kbn/i18n';

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

import { buildQuery } from '../../agent_details_page/components/agent_logs/build_query';
import { ViewLogsButton } from '../../agent_details_page/components/agent_logs/view_logs_button';

import type { ActionStatus } from '../../../../types';
import { useStartServices } from '../../../../hooks';
Expand All @@ -32,27 +29,36 @@ const TruncatedEuiText = styled(EuiText)`

export const ViewErrors: React.FunctionComponent<{ action: ActionStatus }> = ({ action }) => {
const coreStart = useStartServices();
const isLogsUIAvailable = !coreStart.cloud?.isServerlessEnabled;

const addOrSubtractMinutes = (timestamp: string, interval: number, subtract?: boolean) => {
criamico marked this conversation as resolved.
Show resolved Hide resolved
const date = new Date(timestamp);
if (!subtract) {
date.setMinutes(date.getMinutes() + interval);
} else {
date.setMinutes(date.getMinutes() - interval);
}
return date.toISOString();
};

const getLogsButton = (agentId: string, timestamp: string, viewInLogs: boolean) => {
const startTime = addOrSubtractMinutes(timestamp, 5, true);
const endTime = addOrSubtractMinutes(timestamp, 5);

const logStreamQuery = (agentId: string) =>
buildQuery({
const logStreamQuery = buildQuery({
agentId,
datasets: ['elastic_agent'],
logLevels: ['error'],
userQuery: '',
});

const getErrorLogsUrl = (agentId: string, timestamp: string) => {
const queryParams = stringify({
logPosition: encode({
position: { time: Date.parse(timestamp) },
streamLive: false,
}),
logFilter: encode({
expression: logStreamQuery(agentId),
kind: 'kuery',
}),
});
return coreStart.http.basePath.prepend(`/app/logs/stream?${queryParams}`);
return (
<ViewLogsButton
viewInLogs={viewInLogs}
logStreamQuery={logStreamQuery}
startTime={startTime}
endTime={endTime}
/>
);
};

const columns: EuiBasicTableProps<ActionErrorResult>['columns'] = [
Expand Down Expand Up @@ -89,16 +95,7 @@ export const ViewErrors: React.FunctionComponent<{ action: ActionStatus }> = ({
const errorItem = (action.latestErrors ?? []).find((item) => item.agentId === agentId);
return (
<RedirectAppLinks coreStart={coreStart}>
<EuiButton
href={getErrorLogsUrl(agentId, errorItem!.timestamp)}
color="danger"
data-test-subj="viewLogsBtn"
>
<FormattedMessage
id="xpack.fleet.agentActivityFlyout.reviewErrorLogs"
defaultMessage="Review error logs"
/>
</EuiButton>
{getLogsButton(agentId, errorItem!.timestamp, !!isLogsUIAvailable)}
</RedirectAppLinks>
);
},
Expand Down
8 changes: 6 additions & 2 deletions x-pack/plugins/fleet/public/custom_logs_assets_extension.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,12 @@ import { useStartServices } from './hooks';
import type { PackageAssetsComponent } from './types';

export const CustomLogsAssetsExtension: PackageAssetsComponent = () => {
const { http } = useStartServices();
const logStreamUrl = http.basePath.prepend('/app/logs/stream');
const { http, cloud } = useStartServices();
const isLogsUIAvailable = !cloud?.isServerlessEnabled;
// if logs ui is not available, link to discover
const logStreamUrl = isLogsUIAvailable
? http.basePath.prepend('/app/logs/stream')
: http.basePath.prepend('/app/discover');

const views: CustomAssetsAccordionProps['views'] = [
{
Expand Down
1 change: 0 additions & 1 deletion x-pack/plugins/translations/translations/fr-FR.json
Original file line number Diff line number Diff line change
Expand Up @@ -17101,7 +17101,6 @@
"xpack.fleet.agentActivityFlyout.inProgressTitle": "En cours",
"xpack.fleet.agentActivityFlyout.noActivityDescription": "Le fil d'activités s'affichera ici au fur et à mesure que les agents seront réaffectés, mis à niveau ou désenregistrés.",
"xpack.fleet.agentActivityFlyout.noActivityText": "Aucune activité à afficher",
"xpack.fleet.agentActivityFlyout.reviewErrorLogs": "Vérifier les logs d'erreur",
"xpack.fleet.agentActivityFlyout.scheduledDescription": "Planifié pour ",
"xpack.fleet.agentActivityFlyout.title": "Activité des agents",
"xpack.fleet.agentActivityFlyout.todayTitle": "Aujourd'hui",
Expand Down
1 change: 0 additions & 1 deletion x-pack/plugins/translations/translations/ja-JP.json
Original file line number Diff line number Diff line change
Expand Up @@ -17114,7 +17114,6 @@
"xpack.fleet.agentActivityFlyout.inProgressTitle": "進行中",
"xpack.fleet.agentActivityFlyout.noActivityDescription": "エージェントが再割り当て、アップグレード、または登録解除されたときに、アクティビティフィードがここに表示されます。",
"xpack.fleet.agentActivityFlyout.noActivityText": "表示するアクティビティがありません",
"xpack.fleet.agentActivityFlyout.reviewErrorLogs": "エラーログを確認",
"xpack.fleet.agentActivityFlyout.scheduledDescription": "スケジュール済み ",
"xpack.fleet.agentActivityFlyout.title": "エージェントアクティビティ",
"xpack.fleet.agentActivityFlyout.todayTitle": "今日",
Expand Down
1 change: 0 additions & 1 deletion x-pack/plugins/translations/translations/zh-CN.json
Original file line number Diff line number Diff line change
Expand Up @@ -17114,7 +17114,6 @@
"xpack.fleet.agentActivityFlyout.inProgressTitle": "进行中",
"xpack.fleet.agentActivityFlyout.noActivityDescription": "重新分配、升级或取消注册代理时,活动源将在此处显示。",
"xpack.fleet.agentActivityFlyout.noActivityText": "没有可显示的活动",
"xpack.fleet.agentActivityFlyout.reviewErrorLogs": "查看错误日志",
"xpack.fleet.agentActivityFlyout.scheduledDescription": "计划进行 ",
"xpack.fleet.agentActivityFlyout.title": "代理活动",
"xpack.fleet.agentActivityFlyout.todayTitle": "今日",
Expand Down