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] Add search bar and KQL support to agents and agent events table #47764

Merged
Merged
Show file tree
Hide file tree
Changes from all 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 @@ -5,7 +5,7 @@
*/

export const INDEX_NAMES = {
FLEET: '.kibana-fleet',
FLEET: '.kibana',
};

export const POLICY_NAMES = {};
107 changes: 107 additions & 0 deletions x-pack/legacy/plugins/fleet/public/components/search_bar.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/

import React, { SFC, useState, useEffect } from 'react';
import {
// @ts-ignore
EuiSuggest,
} from '@elastic/eui';
import { FrontendLibs } from '../lib/types';
import { ElasticsearchLib } from '../lib/elasticsearch';
import { useDebounce } from '../hooks/use_debounce';

const DEBOUNCE_SEARCH_MS = 150;

interface Suggestion {
label: string;
description: string;
value: string;
type: {
color: string;
iconType: string;
};
start: number;
end: number;
}

interface Props {
libs: FrontendLibs;
value: string;
fieldPrefix: string;
onChange: (newValue: string) => void;
}

export const SearchBar: SFC<Props> = ({ libs, value, fieldPrefix, onChange }) => {
const { suggestions } = useSuggestions(libs.elasticsearch, fieldPrefix, value);

const onAutocompleteClick = (suggestion: Suggestion) => {
onChange(
[value.slice(0, suggestion.start), suggestion.value, value.slice(suggestion.end, -1)].join('')
);
};
const onChangeSearch = (s: string) => {
onChange(s);
};

return (
<EuiSuggest
value={value}
icon={'search'}
placeholder={'Search'}
onInputChange={onChangeSearch}
suggestions={suggestions}
onItemClick={onAutocompleteClick}
/>
);
};

function transformSuggestionType(type: string): { iconType: string; color: string } {
switch (type) {
case 'field':
return { iconType: 'kqlField', color: 'tint4' };
case 'value':
return { iconType: 'kqlValue', color: 'tint0' };
case 'conjunction':
return { iconType: 'kqlSelector', color: 'tint3' };
case 'operator':
return { iconType: 'kqlOperand', color: 'tint1' };
default:
return { iconType: 'kqlOther', color: 'tint1' };
}
}

function useSuggestions(elasticsearch: ElasticsearchLib, fieldPrefix: string, search: string) {
const debouncedSearch = useDebounce(search, DEBOUNCE_SEARCH_MS);
const [suggestions, setSuggestions] = useState<Suggestion[]>([]);

const fetchSuggestions = async () => {
try {
const esSuggestions = (await elasticsearch.getSuggestions(
debouncedSearch,
debouncedSearch.length,
fieldPrefix
)).map(suggestion => ({
label: suggestion.text,
description: suggestion.description || '',
type: transformSuggestionType(suggestion.type),
start: suggestion.start,
end: suggestion.end,
value: suggestion.text,
}));
setSuggestions(esSuggestions);
} catch (err) {
setSuggestions([]);
}
};

useEffect(() => {
fetchSuggestions();
}, [debouncedSearch]);

return {
suggestions,
};
}
23 changes: 23 additions & 0 deletions x-pack/legacy/plugins/fleet/public/hooks/use_debounce.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/

import { useState, useEffect } from 'react';

export function useDebounce<T>(value: T, delay: number) {
const [debouncedValue, setDebouncedValue] = useState(value);

useEffect(() => {
const handler = setTimeout(() => {
setDebouncedValue(value);
}, delay);

return () => {
clearTimeout(handler);
};
}, [value, delay]);

return debouncedValue;
}
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,9 @@ export class AgentAdapter {

public async getAgentEvents(
id: string,
search: string,
page: number,
perPage: number
perPage: number,
kuery?: string
): Promise<{
total: number;
list: AgentEvent[];
Expand All @@ -41,7 +41,7 @@ export class AgentAdapter {
return true;
}

public async getAll(page: number, perPage: number) {
public async getAll(page: number, perPage: number, kuery?: string) {
const list = this.memoryDB.map<Agent>((beat: any) => omit(beat, ['access_token']));
return { list, success: true, page, perPage, total: list.length };
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,16 +25,16 @@ export class RestAgentAdapter extends AgentAdapter {

public async getAgentEvents(
id: string,
search: string,
page: number,
perPage: number
perPage: number,
kuery?: string
): Promise<{
total: number;
list: AgentEvent[];
}> {
const { total, list } = await this.REST.get<ReturnTypeList<AgentEvent>>(
`/api/fleet/agents/${id}/events`,
{ page, per_page: perPage, search: search === '' ? undefined : search }
{ page, per_page: perPage, kuery: kuery !== '' ? kuery : undefined }
);

return {
Expand All @@ -53,11 +53,16 @@ export class RestAgentAdapter extends AgentAdapter {
}
}

public async getAll(page: number, perPage: number): Promise<ReturnTypeList<Agent>> {
public async getAll(
page: number,
perPage: number,
kuery?: string
): Promise<ReturnTypeList<Agent>> {
try {
return await this.REST.get<ReturnTypeList<Agent>>('/api/fleet/agents', {
page,
perPage,
kuery: kuery !== '' ? kuery : undefined,
});
} catch (e) {
return {
Expand Down
20 changes: 5 additions & 15 deletions x-pack/legacy/plugins/fleet/public/lib/agent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,9 @@
import { ReturnTypeList } from '../../common/return_types';
import { Agent, AgentEvent } from '../../common/types/domain_data';
import { AgentAdapter } from './adapters/agent/memory_agent_adapter';
import { ElasticsearchLib } from './elasticsearch';

export class AgentsLib {
constructor(
private readonly adapter: AgentAdapter,
private readonly elasticsearch: ElasticsearchLib
) {}
constructor(private readonly adapter: AgentAdapter) {}

/**
* Get an agent by id
Expand All @@ -30,11 +26,11 @@ export class AgentsLib {
*/
public async getAgentEvents(
id: string,
search: string,
page: number,
perPage: number
perPage: number,
kuery?: string
): Promise<{ total: number; list: AgentEvent[] }> {
return await this.adapter.getAgentEvents(id, search, page, perPage);
return await this.adapter.getAgentEvents(id, page, perPage, kuery);
}

/** Get a single agent using the token it was enrolled in for lookup */
Expand All @@ -55,13 +51,7 @@ export class AgentsLib {
perPage: number,
kuery?: string
): Promise<ReturnTypeList<Agent>> => {
// @ts-ignore
let ESQuery;
if (kuery) {
ESQuery = await this.elasticsearch.convertKueryToEsQuery(kuery);
}
// TODO: add back param to getAll() when endpoint supports query
return await this.adapter.getAll(page, perPage);
return await this.adapter.getAll(page, perPage, kuery);
};

/** Update a given agent via it's ID */
Expand Down
2 changes: 1 addition & 1 deletion x-pack/legacy/plugins/fleet/public/lib/compose/kibana.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ export function compose(): FrontendLibs {
const api = new AxiosRestAPIAdapter(chrome.getXsrfToken(), chrome.getBasePath());
const esAdapter = new RestElasticsearchAdapter(api, INDEX_NAMES.FLEET);
const elasticsearchLib = new ElasticsearchLib(esAdapter);
const agents = new AgentsLib(new RestAgentAdapter(api), elasticsearchLib);
const agents = new AgentsLib(new RestAgentAdapter(api));

const framework = new FrameworkLib(
new KibanaFrameworkAdapter(
Expand Down
2 changes: 1 addition & 1 deletion x-pack/legacy/plugins/fleet/public/lib/compose/memory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ export function compose(
);
const elasticsearchLib = new ElasticsearchLib(esAdapter);

const agents = new AgentsLib(new MemoryAgentAdapter([]), elasticsearchLib);
const agents = new AgentsLib(new MemoryAgentAdapter([]));

const pluginUIModule = uiModules.get('app/fleet');

Expand Down
2 changes: 1 addition & 1 deletion x-pack/legacy/plugins/fleet/public/lib/compose/scripts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ export function compose(basePath: string): FrontendLibs {
const esAdapter = new MemoryElasticsearchAdapter(() => true, () => '', []);
const elasticsearchLib = new ElasticsearchLib(esAdapter);

const agents = new AgentsLib(new RestAgentAdapter(api), elasticsearchLib);
const agents = new AgentsLib(new RestAgentAdapter(api));

const framework = new FrameworkLib(
new TestingFrameworkAdapter(
Expand Down
52 changes: 17 additions & 35 deletions x-pack/legacy/plugins/fleet/public/lib/elasticsearch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,29 +7,14 @@
import { AutocompleteSuggestion } from '../../../../../../src/plugins/data/public';
import { ElasticsearchAdapter } from './adapters/elasticsearch/adapter_types';

interface HiddenFields {
op: 'is' | 'startsWith' | 'withoutPrefix';
value: string;
}
const HIDDEN_FIELDS = ['agents.actions'];

export class ElasticsearchLib {
private readonly hiddenFields: HiddenFields[] = [
{ op: 'startsWith', value: 'enrollment_token' },
{ op: 'is', value: 'beat.active' },
{ op: 'is', value: 'beat.enrollment_token' },
{ op: 'is', value: 'beat.access_token' },
{ op: 'is', value: 'beat.ephemeral_id' },
{ op: 'is', value: 'beat.verified_on' },
];

constructor(private readonly adapter: ElasticsearchAdapter) {}

public isKueryValid(kuery: string): boolean {
return this.adapter.isKueryValid(kuery);
}
public async convertKueryToEsQuery(kuery: string): Promise<string> {
return await this.adapter.convertKueryToEsQuery(kuery);
}

public async getSuggestions(
kuery: string,
Expand All @@ -39,29 +24,26 @@ export class ElasticsearchLib {
const suggestions = await this.adapter.getSuggestions(kuery, selectionStart);

const filteredSuggestions = suggestions.filter(suggestion => {
const hiddenFieldsCheck = this.hiddenFields;

if (fieldPrefix) {
hiddenFieldsCheck.push({
op: 'withoutPrefix',
value: `${fieldPrefix}.`,
});
if (suggestion.type === 'conjunction') {
return true;
}
if (suggestion.type === 'value') {
return true;
}
if (suggestion.type === 'operator') {
return true;
}

return hiddenFieldsCheck.reduce((isvalid: boolean, field) => {
if (!isvalid) {
return false;
if (fieldPrefix && suggestion.text.startsWith(fieldPrefix)) {
for (const hiddenField of HIDDEN_FIELDS) {
if (suggestion.text.startsWith(hiddenField)) {
return false;
}
}
return true;
}

switch (field.op) {
case 'startsWith':
return !suggestion.text.startsWith(field.value);
case 'is':
return suggestion.text.trim() !== field.value;
case 'withoutPrefix':
return suggestion.text.startsWith(field.value);
}
}, true);
return false;
});

return filteredSuggestions;
Expand Down
Loading