Skip to content

Commit

Permalink
Merge branch 'master' into lens/formula-performance
Browse files Browse the repository at this point in the history
  • Loading branch information
kibanamachine authored Jun 15, 2021
2 parents 9d1b40d + c151426 commit c3fe29d
Show file tree
Hide file tree
Showing 65 changed files with 2,310 additions and 1,069 deletions.
Binary file not shown.
Binary file not shown.
Original file line number Diff line number Diff line change
Expand Up @@ -21,13 +21,37 @@ import { Root } from '../../../root';

const kibanaVersion = Env.createDefault(REPO_ROOT, getEnvOptions()).packageInfo.version;

const logFilePath = Path.join(__dirname, 'migration_test_kibana.log');
const logFilePath = Path.join(__dirname, 'migration_test_kibana_from_v1.log');

const asyncUnlink = Util.promisify(Fs.unlink);
async function removeLogFile() {
// ignore errors if it doesn't exist
await asyncUnlink(logFilePath).catch(() => void 0);
}
const assertMigratedDocuments = (arr: any[], target: any[]) => target.every((v) => arr.includes(v));

function sortByTypeAndId(a: { type: string; id: string }, b: { type: string; id: string }) {
return a.type.localeCompare(b.type) || a.id.localeCompare(b.id);
}

async function fetchDocuments(esClient: ElasticsearchClient, index: string) {
const { body } = await esClient.search<any>({
index,
body: {
query: {
match_all: {},
},
_source: ['type', 'id'],
},
});

return body.hits.hits
.map((h) => ({
...h._source,
id: h._id,
}))
.sort(sortByTypeAndId);
}

describe('migration v2', () => {
let esServer: kbnTestServer.TestElasticsearchUtils;
Expand All @@ -40,7 +64,7 @@ describe('migration v2', () => {
adjustTimeout: (t: number) => jest.setTimeout(t),
settings: {
es: {
license: 'trial',
license: 'basic',
dataArchive,
},
},
Expand All @@ -51,8 +75,8 @@ describe('migration v2', () => {
migrations: {
skip: false,
enableV2: true,
// There are 53 docs in fixtures. Batch size configured to enforce 3 migration steps.
batchSize: 20,
// There are 40 docs in fixtures. Batch size configured to enforce 3 migration steps.
batchSize: 15,
},
logging: {
appenders: {
Expand Down Expand Up @@ -85,8 +109,7 @@ describe('migration v2', () => {
coreStart = start;
esClient = coreStart.elasticsearch.client.asInternalUser;
});

await Promise.all([startEsPromise, startKibanaPromise]);
return await Promise.all([startEsPromise, startKibanaPromise]);
};

const getExpectedVersionPerType = () =>
Expand Down Expand Up @@ -192,15 +215,19 @@ describe('migration v2', () => {
});
});

// FLAKY: https://github.com/elastic/kibana/issues/91107
describe.skip('migrating from the same Kibana version', () => {
describe('migrating from the same Kibana version that used v1 migrations', () => {
const originalIndex = `.kibana_1`; // v1 migrations index
const migratedIndex = `.kibana_${kibanaVersion}_001`;

beforeAll(async () => {
await removeLogFile();
await startServers({
oss: true,
dataArchive: Path.join(__dirname, 'archives', '8.0.0_oss_sample_saved_objects.zip'),
oss: false,
dataArchive: Path.join(
__dirname,
'archives',
'8.0.0_v1_migrations_sample_data_saved_objects.zip'
),
});
});

Expand All @@ -215,7 +242,6 @@ describe('migration v2', () => {
},
{ ignore: [404] }
);

const response = body[migratedIndex];

expect(response).toBeDefined();
Expand All @@ -225,17 +251,23 @@ describe('migration v2', () => {
]);
});

it('copies all the document of the previous index to the new one', async () => {
it('copies the documents from the previous index to the new one', async () => {
// original assertion on document count comparison (how atteched are we to this assertion?)
const migratedIndexResponse = await esClient.count({
index: migratedIndex,
});
const oldIndexResponse = await esClient.count({
index: '.kibana_1',
index: originalIndex,
});

// Use a >= comparison since once Kibana has started it might create new
// documents like telemetry tasks
expect(migratedIndexResponse.body.count).toBeGreaterThanOrEqual(oldIndexResponse.body.count);

// new assertion against a document array comparison
const originalDocs = await fetchDocuments(esClient, originalIndex);
const migratedDocs = await fetchDocuments(esClient, migratedIndex);
expect(assertMigratedDocuments(migratedDocs, originalDocs));
});

it('migrates the documents to the highest version', async () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ const DEFAULT_OPTIONS = {
stripEmptyFields: true,
};

interface UseFormReturn<T extends FormData, I extends FormData> {
export interface UseFormReturn<T extends FormData, I extends FormData> {
form: FormHook<T, I>;
}

Expand Down
26 changes: 26 additions & 0 deletions src/plugins/presentation_util/public/mocks.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
/*
* 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 { CoreStart } from 'kibana/public';
import { PresentationUtilPluginStart } from './types';
import { pluginServices } from './services';
import { registry } from './services/kibana';

const createStartContract = (coreStart: CoreStart): PresentationUtilPluginStart => {
pluginServices.setRegistry(registry.start({ coreStart, startPlugins: {} as any }));

const startContract: PresentationUtilPluginStart = {
ContextProvider: pluginServices.getContextProvider(),
labsService: pluginServices.getServices().labs,
};
return startContract;
};

export const presentationUtilPluginMock = {
createStartContract,
};
30 changes: 29 additions & 1 deletion x-pack/examples/embedded_lens_example/public/app.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import {
TypedLensByValueInput,
PersistedIndexPatternLayer,
XYState,
LensEmbeddableInput,
} from '../../../plugins/lens/public';
import { StartDependencies } from './plugin';

Expand Down Expand Up @@ -112,12 +113,15 @@ export const App = (props: {
}) => {
const [color, setColor] = useState('green');
const [isLoading, setIsLoading] = useState(false);
const [isSaveModalVisible, setIsSaveModalVisible] = useState(false);
const LensComponent = props.plugins.lens.EmbeddableComponent;
const LensSaveModalComponent = props.plugins.lens.SaveModalComponent;

const [time, setTime] = useState({
from: 'now-5d',
to: 'now',
});

return (
<EuiPage>
<EuiPageBody style={{ maxWidth: 1200, margin: '0 auto' }}>
Expand Down Expand Up @@ -172,7 +176,18 @@ export const App = (props: {
setColor(newColor);
}}
>
Edit
Edit in Lens
</EuiButton>
</EuiFlexItem>
<EuiFlexItem grow={false}>
<EuiButton
aria-label="Save visualization into library or embed directly into any dashboard"
isDisabled={!getLensAttributes(props.defaultIndexPattern, color)}
onClick={() => {
setIsSaveModalVisible(true);
}}
>
Save Visualization
</EuiButton>
</EuiFlexItem>
</EuiFlexGroup>
Expand All @@ -197,6 +212,19 @@ export const App = (props: {
// call back event for on table row click event
}}
/>
{isSaveModalVisible && (
<LensSaveModalComponent
initialInput={
(getLensAttributes(
props.defaultIndexPattern,
color
) as unknown) as LensEmbeddableInput
}
isVisible={isSaveModalVisible}
onSave={() => {}}
onClose={() => setIsSaveModalVisible(false)}
/>
)}
</>
) : (
<p>This demo only works if your default index pattern is set and time based</p>
Expand Down
8 changes: 7 additions & 1 deletion x-pack/examples/embedded_lens_example/public/mount.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,13 @@ export const mount = (coreSetup: CoreSetup<StartDependencies>) => async ({

const defaultIndexPattern = await plugins.data.indexPatterns.getDefault();

const reactElement = <App {...deps} defaultIndexPattern={defaultIndexPattern} />;
const i18nCore = core.i18n;

const reactElement = (
<i18nCore.Context>
<App {...deps} defaultIndexPattern={defaultIndexPattern} />
</i18nCore.Context>
);
render(reactElement, element);
return () => unmountComponentAtNode(element);
};
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ import {
} from '@elastic/charts';
import { EuiTitle } from '@elastic/eui';
import d3 from 'd3';
import React from 'react';
import React, { Suspense, useState } from 'react';
import { RULE_ID } from '@kbn/rule-data-utils/target/technical_field_names';
import { useApmServiceContext } from '../../../../context/apm_service/use_apm_service_context';
import { APIReturnType } from '../../../../services/rest/createCallApmApi';
Expand All @@ -27,6 +27,7 @@ import { useTheme } from '../../../../hooks/use_theme';
import { AlertType } from '../../../../../common/alert_types';
import { getAlertAnnotations } from '../../../shared/charts/helper/get_alert_annotations';
import { useApmPluginContext } from '../../../../context/apm_plugin/use_apm_plugin_context';
import { LazyAlertsFlyout } from '../../../../../../observability/public';

type ErrorDistributionAPIResponse = APIReturnType<'GET /api/apm/services/{serviceName}/errors/distribution'>;

Expand Down Expand Up @@ -68,6 +69,9 @@ export function ErrorDistribution({ distribution, title }: Props) {
const { observabilityRuleTypeRegistry } = useApmPluginContext();
const { alerts } = useApmServiceContext();
const { getFormatter } = observabilityRuleTypeRegistry;
const [selectedAlertId, setSelectedAlertId] = useState<string | undefined>(
undefined
);

const tooltipProps: SettingsSpec['tooltip'] = {
headerFormatter: (tooltip: TooltipValue) => {
Expand Down Expand Up @@ -122,8 +126,21 @@ export function ErrorDistribution({ distribution, title }: Props) {
),
chartStartTime: buckets[0].x0,
getFormatter,
selectedAlertId,
setSelectedAlertId,
theme,
})}
<Suspense fallback={null}>
<LazyAlertsFlyout
alerts={alerts}
isInApp={true}
observabilityRuleTypeRegistry={observabilityRuleTypeRegistry}
onClose={() => {
setSelectedAlertId(undefined);
}}
selectedAlertId={selectedAlertId}
/>
</Suspense>
</Chart>
</div>
</div>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,12 +49,21 @@ const getFormatter: ObservabilityRuleTypeRegistry['getFormatter'] = () => () =>
link: '/',
reason: 'a good reason',
});
const selectedAlertId = undefined;
const setSelectedAlertId = jest.fn();

describe('getAlertAnnotations', () => {
describe('with no alerts', () => {
it('returns an empty array', () => {
expect(
getAlertAnnotations({ alerts: [], chartStartTime, getFormatter, theme })
getAlertAnnotations({
alerts: [],
chartStartTime,
getFormatter,
selectedAlertId,
setSelectedAlertId,
theme,
})
).toEqual([]);
});
});
Expand All @@ -66,6 +75,8 @@ describe('getAlertAnnotations', () => {
alerts: [alert],
chartStartTime,
getFormatter,
selectedAlertId,
setSelectedAlertId,
theme,
})![0].props.style.line.stroke
).toEqual(euiColorDanger);
Expand All @@ -77,6 +88,8 @@ describe('getAlertAnnotations', () => {
alerts: [alert],
chartStartTime,
getFormatter,
selectedAlertId,
setSelectedAlertId,
theme,
})![0].props.dataValues[0].header
).toEqual('Alert');
Expand All @@ -88,6 +101,8 @@ describe('getAlertAnnotations', () => {
alerts: [alert],
chartStartTime,
getFormatter,
selectedAlertId,
setSelectedAlertId,
theme,
})![0].props.dataValues[0].details
).toEqual('a good reason');
Expand All @@ -103,6 +118,8 @@ describe('getAlertAnnotations', () => {
alerts: [alert],
chartStartTime,
getFormatter: getNoFormatter,
selectedAlertId,
setSelectedAlertId,
theme,
})![0].props.dataValues[0].details
).toEqual(alert['rule.name']![0]);
Expand All @@ -118,6 +135,8 @@ describe('getAlertAnnotations', () => {
alerts: [alert],
chartStartTime: beforeChartStartTime,
getFormatter,
selectedAlertId,
setSelectedAlertId,
theme,
})![0].props.dataValues[0].dataValue
).toEqual(beforeChartStartTime);
Expand All @@ -137,6 +156,8 @@ describe('getAlertAnnotations', () => {
alerts: [warningAlert],
chartStartTime,
getFormatter,
selectedAlertId,
setSelectedAlertId,
theme,
})![0].props.style.line.stroke
).toEqual(euiColorWarning);
Expand All @@ -148,6 +169,8 @@ describe('getAlertAnnotations', () => {
alerts: [warningAlert],
chartStartTime,
getFormatter,
selectedAlertId,
setSelectedAlertId,
theme,
})![0].props.dataValues[0].header
).toEqual('Warning Alert');
Expand All @@ -166,6 +189,8 @@ describe('getAlertAnnotations', () => {
alerts: [criticalAlert],
chartStartTime,
getFormatter,
selectedAlertId,
setSelectedAlertId,
theme,
})![0].props.style.line.stroke
).toEqual(euiColorDanger);
Expand All @@ -177,6 +202,8 @@ describe('getAlertAnnotations', () => {
alerts: [criticalAlert],
chartStartTime,
getFormatter,
selectedAlertId,
setSelectedAlertId,
theme,
})![0].props.dataValues[0].header
).toEqual('Critical Alert');
Expand Down
Loading

0 comments on commit c3fe29d

Please sign in to comment.