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

[Stack Monitoring] Add setup mode to react app #110670

Merged
merged 10 commits into from
Sep 3, 2021
12 changes: 10 additions & 2 deletions x-pack/plugins/monitoring/public/alerts/badge.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,12 @@ import { AlertState, CommonAlertStatus } from '../../common/types/alerts';
import { AlertSeverity } from '../../common/enums';
// @ts-ignore
import { formatDateTimeLocal } from '../../common/formatting';
import { isInSetupMode } from '../lib/setup_mode';
import { isInSetupMode as isInSetupModeOld } from '../lib/setup_mode';
import { isInSetupMode as isInSetupModeNew } from '../application/setup_mode/setup_mode';
import { SetupModeContext } from '../components/setup_mode/setup_mode_context';
import { getAlertPanelsByCategory } from './lib/get_alert_panels_by_category';
import { getAlertPanelsByNode } from './lib/get_alert_panels_by_node';
import { ExternalConfigContext } from '../application/external_config_context';

export const numberOfAlertsLabel = (count: number) => `${count} alert${count > 1 ? 's' : ''}`;
export const numberOfRulesLabel = (count: number) => `${count} rule${count > 1 ? 's' : ''}`;
Expand Down Expand Up @@ -48,7 +50,13 @@ export const AlertsBadge: React.FC<Props> = (props: Props) => {
const alertsList = Object.values(props.alerts).flat();
const alerts = alertsList.filter((alertItem) => Boolean(alertItem?.sanitizedRule));
const [showPopover, setShowPopover] = React.useState<AlertSeverity | boolean | null>(null);
const inSetupMode = isInSetupMode(React.useContext(SetupModeContext));

const externalConfigContext = React.useContext(ExternalConfigContext);
const reactMigrationEnabled = externalConfigContext.renderReactApp;

const context = React.useContext(SetupModeContext);
const inSetupMode = reactMigrationEnabled ? isInSetupModeNew(context) : isInSetupModeOld(context);

const alertCount = inSetupMode
? alerts.length
: alerts.reduce(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,19 +5,23 @@
* 2.0.
*/

import { isInSetupMode } from '../../lib/setup_mode';
import { isInSetupMode as isInSetupModeOld } from '../../lib/setup_mode';
import { isInSetupMode as isInSetupModeNew } from '../../application/setup_mode/setup_mode';
import { CommonAlertStatus } from '../../../common/types/alerts';
import { ISetupModeContext } from '../../components/setup_mode/setup_mode_context';

export function shouldShowAlertBadge(
alerts: { [alertTypeId: string]: CommonAlertStatus[] },
alertTypeIds: string[],
context?: ISetupModeContext
context?: ISetupModeContext,
reactMigrationEnabled?: boolean
) {
if (!alerts) {
return false;
}
const inSetupMode = isInSetupMode(context);

const inSetupMode = reactMigrationEnabled ? isInSetupModeNew(context) : isInSetupModeOld(context);

const alertExists = alertTypeIds.find(
(name) => alerts[name] && alerts[name].find((rule) => rule.states.length > 0)
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,11 @@ interface GlobalStateProviderProps {
children: React.ReactNode;
}

interface State {
export interface State {
cluster_uuid?: string;
ccs?: any;
inSetupMode?: boolean;
save?: () => void;
}

export const GlobalStateContext = createContext({} as State);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,15 @@ import { TabMenuItem } from '../page_template';
import { PageLoading } from '../../../components';
import { Overview } from '../../../components/cluster/overview';
import { ExternalConfigContext } from '../../external_config_context';
import { SetupModeRenderer } from '../../setup_mode/setup_mode_renderer';
import { SetupModeContext } from '../../../components/setup_mode/setup_mode_context';

const CODE_PATHS = [CODE_PATH_ALL];
interface SetupModeProps {
setupMode: any;
flyoutComponent: any;
bottomBarComponent: any;
}

export const ClusterOverview: React.FC<{}> = () => {
// TODO: check how many requests with useClusters
Expand Down Expand Up @@ -49,11 +56,20 @@ export const ClusterOverview: React.FC<{}> = () => {
return (
<PageTemplate title={title} pageTitle={pageTitle} tabs={tabs}>
{loaded ? (
<Overview
cluster={clusters[0]}
alerts={[]}
setupMode={{}}
showLicenseExpiration={externalConfig.showLicenseExpiration}
<SetupModeRenderer
render={({ setupMode, flyoutComponent, bottomBarComponent }: SetupModeProps) => (
<SetupModeContext.Provider value={{ setupModeSupported: true }}>
{flyoutComponent}
<Overview
cluster={clusters[0]}
alerts={[]}
setupMode={{}}
showLicenseExpiration={externalConfig.showLicenseExpiration}
/>
{/* <EnableAlertsModal alerts={this.alerts} /> */}
{bottomBarComponent}
</SetupModeContext.Provider>
)}
/>
) : (
<PageLoading />
Expand Down
204 changes: 204 additions & 0 deletions x-pack/plugins/monitoring/public/application/setup_mode/setup_mode.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,204 @@
/*
* 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 React from 'react';
import { render } from 'react-dom';
import { includes } from 'lodash';
// import { i18n } from '@kbn/i18n';
import { KibanaContextProvider } from '../../../../../../src/plugins/kibana_react/public';
import { Legacy } from '../../legacy_shims';
// import { ajaxErrorHandlersProvider } from './ajax_error_handler';
import { SetupModeEnterButton } from '../../components/setup_mode/enter_button';
// import { SetupModeFeature } from '../../../common/enums';
import { ISetupModeContext } from '../../components/setup_mode/setup_mode_context';
import { State as GlobalState } from '../../application/global_state_context';

function isOnPage(hash: string) {
return includes(window.location.hash, hash);
}

let globalState: GlobalState;

interface ISetupModeState {
enabled: boolean;
data: any;
callback?: (() => void) | null;
hideBottomBar: boolean;
}
const setupModeState: ISetupModeState = {
enabled: false,
data: null,
callback: null,
hideBottomBar: false,
};

export const getSetupModeState = () => setupModeState;

// export const setNewlyDiscoveredClusterUuid = (clusterUuid: string) => {
// const globalState = angularState.injector.get('globalState');
// const executor = angularState.injector.get('$executor');
// angularState.scope.$apply(() => {
// globalState.cluster_uuid = clusterUuid;
// globalState.save();
// });
// executor.run();
// };

// export const fetchCollectionData = async (uuid?: string, fetchWithoutClusterUuid = false) => {
// const http = angularState.injector.get('$http');
// const globalState = angularState.injector.get('globalState');
// const clusterUuid = globalState.cluster_uuid;
// const ccs = globalState.ccs;

// let url = '../api/monitoring/v1/setup/collection';
// if (uuid) {
// url += `/node/${uuid}`;
// } else if (!fetchWithoutClusterUuid && clusterUuid) {
// url += `/cluster/${clusterUuid}`;
// } else {
// url += '/cluster';
// }

// try {
// const response = await http.post(url, { ccs });
// return response.data;
// } catch (err) {
// // TODO: handle errors
// throw new Error(err);
// }
// };

const notifySetupModeDataChange = () => setupModeState.callback && setupModeState.callback();

// export const updateSetupModeData = async (uuid?: string, fetchWithoutClusterUuid = false) => {
// const data = await fetchCollectionData(uuid, fetchWithoutClusterUuid);
// setupModeState.data = data;
// const hasPermissions = get(data, '_meta.hasPermissions', false);
// if (!hasPermissions) {
// let text: string = '';
// if (!hasPermissions) {
// text = i18n.translate('xpack.monitoring.setupMode.notAvailablePermissions', {
// defaultMessage: 'You do not have the necessary permissions to do this.',
// });
// }

// angularState.scope.$evalAsync(() => {
// Legacy.shims.toastNotifications.addDanger({
// title: i18n.translate('xpack.monitoring.setupMode.notAvailableTitle', {
// defaultMessage: 'Setup mode is not available',
// }),
// text,
// });
// });
// return toggleSetupMode(false);
// }
// notifySetupModeDataChange();

// const globalState = angularState.injector.get('globalState');
// const clusterUuid = globalState.cluster_uuid;
// if (!clusterUuid) {
// const liveClusterUuid: string = get(data, '_meta.liveClusterUuid');
// const migratedEsNodes = Object.values(get(data, 'elasticsearch.byUuid', {})).filter(
// (node: any) => node.isPartiallyMigrated || node.isFullyMigrated
// );
// if (liveClusterUuid && migratedEsNodes.length > 0) {
// setNewlyDiscoveredClusterUuid(liveClusterUuid);
// }
// }
// };

// export const hideBottomBar = () => {
// setupModeState.hideBottomBar = true;
// notifySetupModeDataChange();
// };
// export const showBottomBar = () => {
// setupModeState.hideBottomBar = false;
// notifySetupModeDataChange();
// };

// export const disableElasticsearchInternalCollection = async () => {
// const http = angularState.injector.get('$http');
// const globalState = angularState.injector.get('globalState');
// const clusterUuid = globalState.cluster_uuid;
// const url = `../api/monitoring/v1/setup/collection/${clusterUuid}/disable_internal_collection`;
// try {
// const response = await http.post(url);
// return response.data;
// } catch (err) {
// // TODO: handle errors
// throw new Error(err);
// }
// };

export const toggleSetupMode = (inSetupMode: boolean) => {
setupModeState.enabled = inSetupMode;
globalState.inSetupMode = inSetupMode;
globalState.save?.();
setSetupModeMenuItem();
notifySetupModeDataChange();

if (inSetupMode) {
// console.log('updating the setup mode');
// Intentionally do not await this so we don't block UI operations
// updateSetupModeData();
}
};

export const setSetupModeMenuItem = () => {
if (isOnPage('no-data')) {
return;
}

const enabled = !globalState.inSetupMode;
const I18nContext = Legacy.shims.I18nContext;

render(
<KibanaContextProvider services={Legacy.shims.kibanaServices}>
<I18nContext>
<SetupModeEnterButton enabled={enabled} toggleSetupMode={toggleSetupMode} />
</I18nContext>
</KibanaContextProvider>,
document.getElementById('setupModeNav')
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why do we renter into the div here rather than put a conditional component into the PageTemplate?

Also I noticed we now have two "setup" things, so guessing we should maybe move the setupModeNav into MonitoringToolbar?

Screen Shot 2021-09-03 at 13 38 23

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is how it was done before and I don't know exactly why they did it that way.

When I added it, it just worked so I thought that changing it will take more time and it could introduce some bugs. I also think that everything related to setup mode needs to be refactored, both from a UX perspective (I'm not sure how intuitive it is for users...) and technically so we could improve everything together.

);
};

// is this used ?!?!?!
export const addSetupModeCallback = (callback: () => void) => (setupModeState.callback = callback);

export const initSetupModeState = async (state: GlobalState, callback?: () => void) => {
globalState = state;
if (callback) {
setupModeState.callback = callback;
}

if (globalState.inSetupMode) {
toggleSetupMode(true);
}
};

export const isInSetupMode = (context?: ISetupModeContext) => {
if (context?.setupModeSupported === false) {
return false;
}
if (setupModeState.enabled) {
return true;
}

return globalState.inSetupMode;
};

// export const isSetupModeFeatureEnabled = (feature: SetupModeFeature) => {
// if (!setupModeState.enabled) {
// return false;
// }
// if (feature === SetupModeFeature.MetricbeatMigration) {
// if (Legacy.shims.isCloud) {
// return false;
// }
// }
// return true;
// };
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
/*
* 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.
*/

export const SetupModeRenderer: FunctionComponent<Props>;
Loading