Skip to content

Commit

Permalink
Merge branch 'main' into 165812-infra-ui-rename-disk-usage-charts
Browse files Browse the repository at this point in the history
  • Loading branch information
jennypavlova authored Sep 7, 2023
2 parents 49a3898 + 62911d2 commit 8591a32
Show file tree
Hide file tree
Showing 8 changed files with 107 additions and 56 deletions.
15 changes: 9 additions & 6 deletions packages/kbn-es/src/utils/docker.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -476,15 +476,18 @@ describe('runServerlessCluster()', () => {
[baseEsPath]: {},
});
execa.mockImplementation(() => Promise.resolve({ stdout: '' }));
const info = jest.fn();
jest.requireMock('@elastic/elasticsearch').Client.mockImplementation(() => ({ info }));
const health = jest.fn();
jest
.requireMock('@elastic/elasticsearch')
.Client.mockImplementation(() => ({ cluster: { health } }));

info.mockImplementationOnce(() => Promise.reject()); // first call fails
info.mockImplementationOnce(() => Promise.resolve()); // then succeeds
health.mockImplementationOnce(() => Promise.reject()); // first call fails
health.mockImplementationOnce(() => Promise.resolve({ status: 'red' })); // second call return wrong status
health.mockImplementationOnce(() => Promise.resolve({ status: 'green' })); // then succeeds

await runServerlessCluster(log, { basePath: baseEsPath, waitForReady: true });
expect(info).toHaveBeenCalledTimes(2);
});
expect(health).toHaveBeenCalledTimes(3);
}, 10000);
});
});

Expand Down
23 changes: 3 additions & 20 deletions packages/kbn-es/src/utils/docker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ import {
ELASTIC_SERVERLESS_SUPERUSER_PASSWORD,
} from './ess_file_realm';
import { SYSTEM_INDICES_SUPERUSER } from './native_realm';
import { waitUntilClusterReady } from './wait_until_cluster_ready';

interface BaseOptions {
tag?: string;
Expand Down Expand Up @@ -560,25 +561,6 @@ function getESClient(clientOptions: ClientOptions): Client {
});
}

const delay = (ms: number) => new Promise((res) => setTimeout(res, ms));
async function waitUntilClusterReady(
clientOptions: ClientOptions,
timeoutMs = 60 * 1000
): Promise<void> {
const started = Date.now();
const client = getESClient(clientOptions);

while (started + timeoutMs > Date.now()) {
try {
await client.info();
break;
} catch (e) {
await delay(1000);
/* trap to continue */
}
}
}

/**
* Runs an ES Serverless Cluster through Docker
*/
Expand Down Expand Up @@ -636,7 +618,7 @@ export async function runServerlessCluster(log: ToolingLog, options: ServerlessO
portCmd[1].lastIndexOf(':')
)}`;

await waitUntilClusterReady({
const client = getESClient({
node: esNodeUrl,
...(options.ssl
? {
Expand All @@ -654,6 +636,7 @@ export async function runServerlessCluster(log: ToolingLog, options: ServerlessO
}
: {}),
});
await waitUntilClusterReady({ client, log });
log.success('ES is ready');
}

Expand Down
63 changes: 63 additions & 0 deletions packages/kbn-es/src/utils/wait_until_cluster_ready.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
/*
* 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 { Client } from '@elastic/elasticsearch';
import { ToolingLog } from '@kbn/tooling-log';
const DEFAULT_READY_TIMEOUT = 60 * 1000; // 1 minute

export interface WaitOptions {
client: Client;
log: ToolingLog;
readyTimeout?: number;
}

/**
* General method to wait for the ES cluster status to be green
*/
export async function waitUntilClusterReady({
client,
log,
readyTimeout = DEFAULT_READY_TIMEOUT,
}: WaitOptions) {
let attempt = 0;
const start = Date.now();

log.info('waiting for ES cluster to report a green status');

while (true) {
attempt += 1;

try {
const resp = await client.cluster.health();
if (resp.status === 'green') {
return;
}

throw new Error(`not ready, cluster health is ${resp.status}`);
} catch (error) {
const timeSinceStart = Date.now() - start;
if (timeSinceStart > readyTimeout) {
const sec = readyTimeout / 1000;
throw new Error(`ES cluster failed to come online with the ${sec} second timeout`);
}

if (error?.message?.startsWith('not ready,')) {
if (timeSinceStart > 10_000) {
log.warning(error.message);
}
} else {
log.warning(
`waiting for ES cluster to come online, attempt ${attempt} failed with: ${error?.message}`
);
}

const waitSec = attempt * 1.5;
await new Promise((resolve) => setTimeout(resolve, waitSec * 1000));
}
}
}
32 changes: 15 additions & 17 deletions packages/kbn-search-api-panels/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import React from 'react';
import { EuiFlexGroup, EuiFlexItem, EuiTitle, EuiSpacer, EuiImage, EuiText } from '@elastic/eui';
import { i18n } from '@kbn/i18n';
import { AuthenticatedUser } from '@kbn/security-plugin/common';

export * from './components/code_box';
export * from './components/github_link';
Expand All @@ -24,19 +25,14 @@ export * from './types';
export * from './utils';

export interface WelcomeBannerProps {
userProfile: {
user: {
full_name?: string;
username?: string;
};
};
user?: AuthenticatedUser;
assetBasePath?: string;
image?: string;
showDescription?: boolean;
}

export const WelcomeBanner: React.FC<WelcomeBannerProps> = ({
userProfile,
user,
assetBasePath,
image,
showDescription = true,
Expand All @@ -54,16 +50,18 @@ export const WelcomeBanner: React.FC<WelcomeBannerProps> = ({
</h1>
</EuiTitle>
</EuiFlexItem>
<EuiFlexItem grow={false}>
<EuiTitle size="xxxs">
<h2>
{i18n.translate('searchApiPanels.welcomeBanner.header.greeting.title', {
defaultMessage: 'Hi {name}!',
values: { name: userProfile?.user?.full_name || userProfile?.user?.username },
})}
</h2>
</EuiTitle>
</EuiFlexItem>
{Boolean(user) && (
<EuiFlexItem grow={false}>
<EuiTitle size="xxxs">
<h2>
{i18n.translate('searchApiPanels.welcomeBanner.header.greeting.title', {
defaultMessage: 'Hi {name}!',
values: { name: user?.full_name || user.username },
})}
</h2>
</EuiTitle>
</EuiFlexItem>
)}
</EuiFlexGroup>
<EuiSpacer />
{showDescription && (
Expand Down
3 changes: 2 additions & 1 deletion packages/kbn-search-api-panels/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
"@kbn/core-http-browser",
"@kbn/core-application-browser",
"@kbn/share-plugin",
"@kbn/i18n-react"
"@kbn/i18n-react",
"@kbn/security-plugin"
]
}
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ export const ElasticsearchOverview = () => {
const [selectedLanguage, setSelectedLanguage] =
useState<LanguageDefinition>(javascriptDefinition);
const [clientApiKey, setClientApiKey] = useState<string>(API_KEY_PLACEHOLDER);
const { application, cloud, http, userProfile, share } = useKibanaServices();
const { application, cloud, http, user, share } = useKibanaServices();

const elasticsearchURL = useMemo(() => {
return cloud?.elasticsearchUrl ?? ELASTICSEARCH_URL_PLACEHOLDER;
Expand All @@ -73,7 +73,7 @@ export const ElasticsearchOverview = () => {
<EuiPageTemplate offset={0} grow restrictWidth data-test-subj="svlSearchOverviewPage">
<EuiPageTemplate.Section alignment="top" className="serverlessSearchHeaderSection">
<EuiText color="ghost">
<WelcomeBanner userProfile={userProfile} assetBasePath={assetBasePath} />
<WelcomeBanner user={user} assetBasePath={assetBasePath} />
</EuiText>
</EuiPageTemplate.Section>
<EuiPageTemplate.Section color="subdued" bottomBorder="extended">
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,12 @@ import { CloudStart } from '@kbn/cloud-plugin/public';
import type { CoreStart } from '@kbn/core/public';
import type { SharePluginStart } from '@kbn/share-plugin/public';
import { useKibana as useKibanaBase } from '@kbn/kibana-react-plugin/public';
import { GetUserProfileResponse, UserProfileData } from '@kbn/security-plugin/common';
import { AuthenticatedUser } from '@kbn/security-plugin/common';

export interface ServerlessSearchContext {
cloud: CloudStart;
share: SharePluginStart;
userProfile: GetUserProfileResponse<UserProfileData>;
user?: AuthenticatedUser;
}

type ServerlessSearchKibanaContext = CoreStart & ServerlessSearchContext;
Expand Down
19 changes: 11 additions & 8 deletions x-pack/plugins/serverless_search/public/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import { AppMountParameters, CoreSetup, CoreStart, Plugin } from '@kbn/core/public';
import { i18n } from '@kbn/i18n';
import { appIds } from '@kbn/management-cards-navigation';
import { AuthenticatedUser } from '@kbn/security-plugin/common';
import { createServerlessSearchSideNavComponent as createComponent } from './layout/nav';
import { docLinks } from '../common/doc_links';
import {
Expand Down Expand Up @@ -41,10 +42,15 @@ export class ServerlessSearchPlugin
const [coreStart, services] = await core.getStartServices();
const { security } = services;
docLinks.setDocLinks(coreStart.docLinks.links);
let user: AuthenticatedUser | undefined;
try {
const response = await security.authc.getCurrentUser();
user = response;
} catch {
user = undefined;
}

const userProfile = await security.userProfiles.getCurrent();

return await renderApp(element, coreStart, { userProfile, ...services });
return await renderApp(element, coreStart, { user, ...services });
},
});

Expand All @@ -58,12 +64,9 @@ export class ServerlessSearchPlugin
async mount({ element }: AppMountParameters) {
const { renderApp } = await import('./application/connectors');
const [coreStart, services] = await core.getStartServices();
const { security } = services;
docLinks.setDocLinks(coreStart.docLinks.links);

const userProfile = await security.userProfiles.getCurrent();

return await renderApp(element, coreStart, { userProfile, ...services });
docLinks.setDocLinks(coreStart.docLinks.links);
return await renderApp(element, coreStart, { ...services });
},
});

Expand Down

0 comments on commit 8591a32

Please sign in to comment.