-
Notifications
You must be signed in to change notification settings - Fork 8.5k
[Reporting] Restore the "csv by savedobject" endpoint for 7.17 #148030
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
Merged
tsullivan
merged 29 commits into
elastic:7.17
from
tsullivan:reporting/restore-csv-by-savedobject
Jan 11, 2023
Merged
Changes from all commits
Commits
Show all changes
29 commits
Select commit
Hold shift + click to select a range
1419dc2
partial code restoration
tsullivan a6bbbf4
fix sort
tsullivan 88605c8
fix time filter
tsullivan 01bcdd8
types and test improvement
tsullivan 5f2afb7
simplify conditionals
tsullivan 283f2f8
fix time zone
tsullivan 84caf8a
update jest snapshot
tsullivan 2f22d65
consolidate the utc default
tsullivan 4e96424
harden functional tests
tsullivan 7dfc354
unit test stubs
tsullivan 652b76b
add new saved search fixture
tsullivan a6012ff
test for terms filter
tsullivan 96c2162
harden the no-filter test
tsullivan 8ff68e7
Allow no post body in the request
tsullivan 4ee90f0
More tests
tsullivan 1c89cd8
add some jest tests
tsullivan 7a60a6c
remove oops
tsullivan 708c8e7
polish
tsullivan 5564029
fix export with no columns selected
tsullivan 6e4e8d3
add test for non-timebased view
tsullivan ab695fe
fix telemetry api test
tsullivan 8cf100d
fix telemetry attempt ii
tsullivan 45c6ccd
polish
tsullivan a617923
more tests
tsullivan 58864f4
fix usage collection snapshot
tsullivan ff8fb9e
Merge branch '7.17' into reporting/restore-csv-by-savedobject
tsullivan 5fc5af7
unit test for execute_job
tsullivan a9a6000
enable snapshot filtering based on ES version
tsullivan bb67608
export all fields if there is one column named "_source"
tsullivan File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
21 changes: 21 additions & 0 deletions
21
x-pack/plugins/reporting/common/types/export_types/csv_saved_object.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,21 @@ | ||
| /* | ||
| * 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 { BaseParams, BasePayload } from '../base'; | ||
|
|
||
| interface CsvFromSavedObjectBase { | ||
| objectType: 'saved search'; | ||
| timerange?: { | ||
| timezone?: string; | ||
| min?: string | number; | ||
| max?: string | number; | ||
| }; | ||
| savedObjectId: string; | ||
| } | ||
|
|
||
| export type JobParamsCsvFromSavedObject = CsvFromSavedObjectBase & BaseParams; | ||
| export type TaskPayloadCsvFromSavedObject = CsvFromSavedObjectBase & BasePayload; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
19 changes: 19 additions & 0 deletions
19
x-pack/plugins/reporting/server/export_types/csv_saved_object/create_job.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,19 @@ | ||
| /* | ||
| * 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 { CreateJobFn, CreateJobFnFactory } from '../../types'; | ||
| import { JobParamsCsvFromSavedObject, TaskPayloadCsvFromSavedObject } from './types'; | ||
|
|
||
| type CreateJobFnType = CreateJobFn<JobParamsCsvFromSavedObject, TaskPayloadCsvFromSavedObject>; | ||
|
|
||
| export const createJobFnFactory: CreateJobFnFactory<CreateJobFnType> = | ||
| function createJobFactoryFn() { | ||
| return async function createJob(jobParams) { | ||
| // params have been finalized in server/routes/generate_from_savedobject.ts | ||
| return jobParams; | ||
| }; | ||
| }; |
145 changes: 145 additions & 0 deletions
145
x-pack/plugins/reporting/server/export_types/csv_saved_object/execute_job.test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,145 @@ | ||
| /* | ||
| * 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. | ||
| */ | ||
|
|
||
| jest.mock('../csv_searchsource/generate_csv', () => ({ | ||
| CsvGenerator: class CsvGeneratorMock { | ||
| generateData() { | ||
| return { | ||
| size: 123, | ||
| content_type: 'text/csv', | ||
| }; | ||
| } | ||
| }, | ||
| })); | ||
|
|
||
| jest.mock('./lib/get_sharing_data', () => ({ | ||
| getSharingData: jest.fn(() => ({ columns: [], searchSource: {} })), | ||
| })); | ||
|
|
||
| import { Writable } from 'stream'; | ||
| import nodeCrypto from '@elastic/node-crypto'; | ||
| import { ReportingCore } from '../../'; | ||
| import { CancellationToken } from '../../../common'; | ||
| import { | ||
| createMockConfigSchema, | ||
| createMockLevelLogger, | ||
| createMockReportingCore, | ||
| } from '../../test_helpers'; | ||
| import { runTaskFnFactory } from './execute_job'; | ||
|
|
||
| const logger = createMockLevelLogger(); | ||
| const encryptionKey = 'tetkey'; | ||
| const headers = { sid: 'cooltestheaders' }; | ||
| let encryptedHeaders: string; | ||
| let reportingCore: ReportingCore; | ||
| let stream: jest.Mocked<Writable>; | ||
|
|
||
| beforeAll(async () => { | ||
| const crypto = nodeCrypto({ encryptionKey }); | ||
| encryptedHeaders = await crypto.encrypt(headers); | ||
| }); | ||
|
|
||
| beforeEach(async () => { | ||
| stream = {} as typeof stream; | ||
| reportingCore = await createMockReportingCore(createMockConfigSchema({ encryptionKey })); | ||
| }); | ||
|
|
||
| test('recognized saved search', async () => { | ||
| reportingCore.getSavedObjectsClient = jest.fn().mockResolvedValue({ | ||
| get: () => ({ | ||
| attributes: { | ||
| kibanaSavedObjectMeta: { | ||
| searchSourceJSON: '{"indexRefName":"kibanaSavedObjectMeta.searchSourceJSON.index"}', | ||
| }, | ||
| }, | ||
| references: [ | ||
| { | ||
| id: 'logstash-yes-*', | ||
| name: 'kibanaSavedObjectMeta.searchSourceJSON.index', | ||
| type: 'index-pattern', | ||
| }, | ||
| ], | ||
| }), | ||
| }); | ||
|
|
||
| const runTask = runTaskFnFactory(reportingCore, logger); | ||
| const payload = await runTask( | ||
| 'cool-job-id', | ||
| { | ||
| headers: encryptedHeaders, | ||
| browserTimezone: 'US/Alaska', | ||
| savedObjectId: '123-456-abc-defgh', | ||
| objectType: 'saved search', | ||
| title: 'Test Search', | ||
| version: '7.17.0', | ||
| }, | ||
| new CancellationToken(), | ||
| stream | ||
| ); | ||
|
|
||
| expect(payload).toMatchInlineSnapshot(` | ||
| Object { | ||
| "content_type": "text/csv", | ||
| "size": 123, | ||
| } | ||
| `); | ||
| }); | ||
|
|
||
| test('saved search object is missing references', async () => { | ||
| reportingCore.getSavedObjectsClient = jest.fn().mockResolvedValue({ | ||
| get: () => ({ | ||
| attributes: { | ||
| kibanaSavedObjectMeta: { | ||
| searchSourceJSON: '{"indexRefName":"kibanaSavedObjectMeta.searchSourceJSON.index"}', | ||
| }, | ||
| }, | ||
| }), | ||
| }); | ||
|
|
||
| const runTask = runTaskFnFactory(reportingCore, logger); | ||
| const runTest = async () => { | ||
| await runTask( | ||
| 'cool-job-id', | ||
| { | ||
| headers: encryptedHeaders, | ||
| browserTimezone: 'US/Alaska', | ||
| savedObjectId: '123-456-abc-defgh', | ||
| objectType: 'saved search', | ||
| title: 'Test Search', | ||
| version: '7.17.0', | ||
| }, | ||
| new CancellationToken(), | ||
| stream | ||
| ); | ||
| }; | ||
|
|
||
| await expect(runTest).rejects.toEqual( | ||
| new Error('Could not find reference for kibanaSavedObjectMeta.searchSourceJSON.index') | ||
| ); | ||
| }); | ||
|
|
||
| test('invalid saved search', async () => { | ||
| reportingCore.getSavedObjectsClient = jest.fn().mockResolvedValue({ get: jest.fn() }); | ||
| const runTask = runTaskFnFactory(reportingCore, logger); | ||
| const runTest = async () => { | ||
| await runTask( | ||
| 'cool-job-id', | ||
| { | ||
| headers: encryptedHeaders, | ||
| browserTimezone: 'US/Alaska', | ||
| savedObjectId: '123-456-abc-defgh', | ||
| objectType: 'saved search', | ||
| title: 'Test Search', | ||
| version: '7.17.0', | ||
| }, | ||
| new CancellationToken(), | ||
| stream | ||
| ); | ||
| }; | ||
|
|
||
| await expect(runTest).rejects.toEqual(new Error('Saved search object is not valid')); | ||
| }); |
109 changes: 109 additions & 0 deletions
109
x-pack/plugins/reporting/server/export_types/csv_saved_object/execute_job.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,109 @@ | ||
| /* | ||
| * 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 { SavedObject } from 'kibana/server'; | ||
| import type { SearchSourceFields } from 'src/plugins/data/common'; | ||
| import type { VisualizationSavedObjectAttributes } from 'src/plugins/visualizations/common'; | ||
| import { DeepPartial } from 'utility-types'; | ||
| import { JobParamsCSV } from '../..'; | ||
| import { injectReferences, parseSearchSourceJSON } from '../../../../../../src/plugins/data/common'; | ||
| import { CSV_JOB_TYPE } from '../../../common/constants'; | ||
| import { getFieldFormats } from '../../services'; | ||
| import type { RunTaskFn, RunTaskFnFactory } from '../../types'; | ||
| import { decryptJobHeaders } from '../common'; | ||
| import { CsvGenerator } from '../csv_searchsource/generate_csv'; | ||
| import { getSharingData } from './lib'; | ||
| import type { TaskPayloadCsvFromSavedObject } from './types'; | ||
|
|
||
| type RunTaskFnType = RunTaskFn<TaskPayloadCsvFromSavedObject>; | ||
| type SavedSearchObjectType = SavedObject< | ||
| VisualizationSavedObjectAttributes & { columns?: string[]; sort: Array<[string, string]> } | ||
| >; | ||
| type ParsedSearchSourceJSON = SearchSourceFields & { indexRefName?: string }; | ||
|
|
||
| function isSavedObject( | ||
| savedSearch: SavedSearchObjectType | unknown | ||
| ): savedSearch is SavedSearchObjectType { | ||
| return ( | ||
| (savedSearch as DeepPartial<SavedSearchObjectType> | undefined)?.attributes | ||
| ?.kibanaSavedObjectMeta?.searchSourceJSON != null | ||
| ); | ||
| } | ||
|
|
||
| export const runTaskFnFactory: RunTaskFnFactory<RunTaskFnType> = (reporting, _logger) => { | ||
| const config = reporting.getConfig(); | ||
|
|
||
| return async function runTask(jobId, job, cancellationToken, stream) { | ||
| const logger = _logger.clone([CSV_JOB_TYPE, 'execute-job', jobId]); | ||
|
|
||
| const encryptionKey = config.get('encryptionKey'); | ||
| const headers = await decryptJobHeaders(encryptionKey, job.headers, logger); | ||
| const fakeRequest = reporting.getFakeRequest({ headers }, job.spaceId, logger); | ||
| const uiSettings = await reporting.getUiSettingsClient(fakeRequest, logger); | ||
| const savedObjects = await reporting.getSavedObjectsClient(fakeRequest); | ||
| const dataPluginStart = await reporting.getDataService(); | ||
| const fieldFormatsRegistry = await getFieldFormats().fieldFormatServiceFactory(uiSettings); | ||
|
|
||
| const [es, searchSourceStart] = await Promise.all([ | ||
| (await reporting.getEsClient()).asScoped(fakeRequest), | ||
| await dataPluginStart.search.searchSource.asScoped(fakeRequest), | ||
| ]); | ||
|
|
||
| const clients = { | ||
| uiSettings, | ||
| data: dataPluginStart.search.asScoped(fakeRequest), | ||
| es, | ||
| }; | ||
| const dependencies = { | ||
| searchSourceStart, | ||
| fieldFormatsRegistry, | ||
| }; | ||
|
|
||
| // Get the Saved Search Fields object from ID | ||
| const savedSearch = await savedObjects.get('search', job.savedObjectId); | ||
|
|
||
| if (!isSavedObject(savedSearch)) { | ||
| throw new Error(`Saved search object is not valid`); | ||
| } | ||
|
|
||
| // allowed to throw an Invalid JSON error if the JSON is not parseable. | ||
| const searchSourceFields: ParsedSearchSourceJSON = parseSearchSourceJSON( | ||
| savedSearch.attributes.kibanaSavedObjectMeta.searchSourceJSON | ||
| ); | ||
|
|
||
| const indexRefName = searchSourceFields.indexRefName; | ||
| if (!indexRefName) { | ||
| throw new Error(`Saved Search data is missing a reference to an Index Pattern!`); | ||
| } | ||
|
|
||
| // Inject references into the Saved Search Fields | ||
| const searchSourceFieldsWithRefs = injectReferences( | ||
| { ...searchSourceFields, indexRefName }, | ||
| savedSearch.references ?? [] | ||
| ); | ||
|
|
||
| // Form the Saved Search attributes and SearchSource into a config that's compatible with CsvGenerator | ||
| const { columns, searchSource } = await getSharingData( | ||
| { uiSettings }, | ||
| await searchSourceStart.create(searchSourceFieldsWithRefs), | ||
| savedSearch, | ||
| job.timerange | ||
| ); | ||
|
|
||
| const jobParamsCsv: JobParamsCSV = { ...job, columns, searchSource }; | ||
| const csv = new CsvGenerator( | ||
| jobParamsCsv, | ||
| config, | ||
| clients, | ||
| dependencies, | ||
| cancellationToken, | ||
| logger, | ||
| stream | ||
| ); | ||
| return await csv.generateData(); | ||
| }; | ||
| }; | ||
40 changes: 40 additions & 0 deletions
40
x-pack/plugins/reporting/server/export_types/csv_saved_object/index.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,40 @@ | ||
| /* | ||
| * 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 { | ||
| CSV_SAVED_OBJECT_JOB_TYPE as CSV_JOB_TYPE, | ||
| LICENSE_TYPE_BASIC, | ||
| LICENSE_TYPE_ENTERPRISE, | ||
| LICENSE_TYPE_GOLD, | ||
| LICENSE_TYPE_PLATINUM, | ||
| LICENSE_TYPE_CLOUD_STANDARD, | ||
| LICENSE_TYPE_TRIAL, | ||
| } from '../../../common/constants'; | ||
| import { CreateJobFn, ExportTypeDefinition, RunTaskFn } from '../../types'; | ||
| import { createJobFnFactory } from './create_job'; | ||
| import { runTaskFnFactory } from './execute_job'; | ||
| import { JobParamsCsvFromSavedObject, TaskPayloadCsvFromSavedObject } from './types'; | ||
|
|
||
| export const getExportType = (): ExportTypeDefinition< | ||
| CreateJobFn<JobParamsCsvFromSavedObject>, | ||
| RunTaskFn<TaskPayloadCsvFromSavedObject> | ||
| > => ({ | ||
| id: CSV_JOB_TYPE, | ||
| name: CSV_JOB_TYPE, | ||
| jobType: CSV_JOB_TYPE, | ||
| jobContentExtension: 'csv', | ||
| createJobFnFactory, | ||
| runTaskFnFactory, | ||
| validLicenses: [ | ||
| LICENSE_TYPE_TRIAL, | ||
| LICENSE_TYPE_BASIC, | ||
| LICENSE_TYPE_CLOUD_STANDARD, | ||
| LICENSE_TYPE_GOLD, | ||
| LICENSE_TYPE_PLATINUM, | ||
| LICENSE_TYPE_ENTERPRISE, | ||
| ], | ||
| }); |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Think a bit ahead here. As I understand this team "owns" the "search source" object but not the "search" object?
When we have support for "down" and "on-read" migrations of saved objects we can consider pinning this object to a specific version of "search", but also a specific version of "searchsource" to ensure it is always in the shape we expect.
This is nothing to action on this PR, I'd be interested to hear what @pgayvallet or @rudolf think :)