From 40452d2e816be5fd38ea41201a6a84718e2bb9b6 Mon Sep 17 00:00:00 2001 From: MichaelKatsoulis Date: Tue, 15 Mar 2022 10:13:34 +0200 Subject: [PATCH 01/12] Update agent addition instructions in fleet managed mode --- .../plugins/fleet/common/constants/routes.ts | 7 + .../plugins/fleet/common/services/routes.ts | 9 + .../common/types/rest_spec/agent_policy.ts | 4 + .../agent_enrollment_flyout/index.tsx | 33 ++- .../managed_instructions.tsx | 19 +- .../standalone_instructions.tsx | 4 +- .../agent_enrollment_flyout/steps.tsx | 161 +++++++++++-- .../agent_enrollment_flyout/types.ts | 4 + .../enrollment_instructions/manual/index.tsx | 24 +- .../fleet/public/hooks/use_request/k8s.ts | 20 ++ .../server/routes/agent_policy/handlers.ts | 163 +++++++++---- .../fleet/server/routes/agent_policy/index.ts | 28 ++- .../fleet/server/services/agent_policy.ts | 26 ++- .../server/services/elastic_agent_manifest.ts | 220 +++++++++++++++++- .../server/types/rest_spec/agent_policy.ts | 8 + .../translations/translations/ja-JP.json | 26 +-- .../translations/translations/zh-CN.json | 26 +-- 17 files changed, 670 insertions(+), 112 deletions(-) create mode 100644 x-pack/plugins/fleet/public/hooks/use_request/k8s.ts diff --git a/x-pack/plugins/fleet/common/constants/routes.ts b/x-pack/plugins/fleet/common/constants/routes.ts index 61df3b78282ca..3c0b9c323d380 100644 --- a/x-pack/plugins/fleet/common/constants/routes.ts +++ b/x-pack/plugins/fleet/common/constants/routes.ts @@ -14,6 +14,7 @@ export const EPM_API_ROOT = `${API_ROOT}/epm`; export const DATA_STREAM_API_ROOT = `${API_ROOT}/data_streams`; export const PACKAGE_POLICY_API_ROOT = `${API_ROOT}/package_policies`; export const AGENT_POLICY_API_ROOT = `${API_ROOT}/agent_policies`; +export const K8S_API_ROOT = `${API_ROOT}/kubernetes`; export const LIMITED_CONCURRENCY_ROUTE_TAG = 'ingest:limited-concurrency'; @@ -67,6 +68,12 @@ export const AGENT_POLICY_API_ROUTES = { FULL_INFO_DOWNLOAD_PATTERN: `${AGENT_POLICY_API_ROOT}/{agentPolicyId}/download`, }; +// Kubernetes Manifest API routes +export const K8S_API_ROUTES = { + K8S_DOWNLOAD_PATTERN: `${K8S_API_ROOT}/download`, + K8S_INFO_PATTERN: `${K8S_API_ROOT}`, +} + // Output API routes export const OUTPUT_API_ROUTES = { LIST_PATTERN: `${API_ROOT}/outputs`, diff --git a/x-pack/plugins/fleet/common/services/routes.ts b/x-pack/plugins/fleet/common/services/routes.ts index b3a53cd05da4e..91c5e46268d33 100644 --- a/x-pack/plugins/fleet/common/services/routes.ts +++ b/x-pack/plugins/fleet/common/services/routes.ts @@ -18,6 +18,7 @@ import { OUTPUT_API_ROUTES, SETTINGS_API_ROUTES, APP_API_ROUTES, + K8S_API_ROUTES, } from '../constants'; export const epmRouteService = { @@ -137,6 +138,14 @@ export const agentPolicyRouteService = { agentPolicyId ); }, + + getK8sInfoPath: () => { + return K8S_API_ROUTES.K8S_INFO_PATTERN; + }, + + getK8sFullDownloadPath: () => { + return K8S_API_ROUTES.K8S_DOWNLOAD_PATTERN; + }, }; export const dataStreamRouteService = { diff --git a/x-pack/plugins/fleet/common/types/rest_spec/agent_policy.ts b/x-pack/plugins/fleet/common/types/rest_spec/agent_policy.ts index cbf3c9806d388..d53da769c754b 100644 --- a/x-pack/plugins/fleet/common/types/rest_spec/agent_policy.ts +++ b/x-pack/plugins/fleet/common/types/rest_spec/agent_policy.ts @@ -77,3 +77,7 @@ export interface GetFullAgentPolicyResponse { export interface GetFullAgentConfigMapResponse { item: string; } + +export interface GetFullAgentManifestResponse { + item: string; +} diff --git a/x-pack/plugins/fleet/public/components/agent_enrollment_flyout/index.tsx b/x-pack/plugins/fleet/public/components/agent_enrollment_flyout/index.tsx index 4be8eb8a03cd4..d4ac4524d577e 100644 --- a/x-pack/plugins/fleet/public/components/agent_enrollment_flyout/index.tsx +++ b/x-pack/plugins/fleet/public/components/agent_enrollment_flyout/index.tsx @@ -28,7 +28,7 @@ import { useFleetStatus, useAgentEnrollmentFlyoutData, } from '../../hooks'; -import { FLEET_SERVER_PACKAGE } from '../../constants'; +import {FLEET_SERVER_PACKAGE, SO_SEARCH_LIMIT} from '../../constants'; import type { PackagePolicy } from '../../types'; import { Loading } from '..'; @@ -37,6 +37,7 @@ import { ManagedInstructions } from './managed_instructions'; import { StandaloneInstructions } from './standalone_instructions'; import { MissingFleetServerHostCallout } from './missing_fleet_server_host_callout'; import type { BaseProps } from './types'; +import {FLEET_KUBERNETES_PACKAGE} from "../../../common"; type FlyoutMode = 'managed' | 'standalone'; @@ -93,6 +94,34 @@ export const AgentEnrollmentFlyout: React.FunctionComponent = ({ checkPolicyIsFleetServer(); }, [policyId]); + + const [isK8s, setIsK8s] = useState<'IS_LOADING' | 'IS_KUBERNETES' | 'IS_NOT_KUBERNETES'>( + 'IS_LOADING' + ); + useEffect(() => { + async function checkifK8s() { + if (!policyId) { + setIsK8s('IS_LOADING'); + return; + } + const agentPolicyRequest = await sendGetOneAgentPolicy(policyId); + const agentPol = agentPolicyRequest.data ? agentPolicyRequest.data.item : null; + + if (!agentPol) { + setIsK8s('IS_NOT_KUBERNETES'); + return; + } + const k8s = (pkg: PackagePolicy) => pkg.package?.name === FLEET_KUBERNETES_PACKAGE; + setIsK8s( + (agentPol.package_policies as PackagePolicy[]).some(k8s) + ? 'IS_KUBERNETES' + : 'IS_NOT_KUBERNETES' + ); + } + checkifK8s(); + }, [policyId]); + + const isLoadingInitialRequest = settings.isLoading && settings.isInitialRequest; return ( @@ -154,10 +183,12 @@ export const AgentEnrollmentFlyout: React.FunctionComponent = ({ diff --git a/x-pack/plugins/fleet/public/components/agent_enrollment_flyout/managed_instructions.tsx b/x-pack/plugins/fleet/public/components/agent_enrollment_flyout/managed_instructions.tsx index ba0da6c7ec83a..555d4d4be0dac 100644 --- a/x-pack/plugins/fleet/public/components/agent_enrollment_flyout/managed_instructions.tsx +++ b/x-pack/plugins/fleet/public/components/agent_enrollment_flyout/managed_instructions.tsx @@ -63,15 +63,15 @@ export const ManagedInstructions = React.memo( agentPolicies, viewDataStep, setSelectedPolicyId, + policyId, isFleetServerPolicySelected, + isK8s, settings, refreshAgentPolicies, isLoadingAgentPolicies, }) => { const fleetStatus = useFleetStatus(); - const [selectedApiKeyId, setSelectedAPIKeyId] = useState(); - const apiKey = useGetOneEnrollmentAPIKey(selectedApiKeyId); const fleetServerInstructions = useFleetServerInstructions(apiKey?.data?.item?.policy_id); @@ -111,6 +111,11 @@ export const ManagedInstructions = React.memo( ]; }, [fleetServerInstructions]); + const enrolToken = + apiKey.data + ? apiKey.data.item.api_key: + '' + const steps = useMemo(() => { const fleetServerHosts = settings?.fleet_server_hosts || []; const baseSteps: EuiContainedStepProps[] = [ @@ -123,7 +128,7 @@ export const ManagedInstructions = React.memo( refreshAgentPolicies, }) : AgentEnrollmentKeySelectionStep({ agentPolicy, selectedApiKeyId, setSelectedAPIKeyId }), - DownloadStep(isFleetServerPolicySelected || false), + DownloadStep(isFleetServerPolicySelected || false, isK8s || '', enrolToken || ''), ]; if (isFleetServerPolicySelected) { baseSteps.push(...fleetServerSteps); @@ -133,7 +138,12 @@ export const ManagedInstructions = React.memo( defaultMessage: 'Enroll and start the Elastic Agent', }), children: selectedApiKeyId && apiKey.data && ( - + ), }); } @@ -155,6 +165,7 @@ export const ManagedInstructions = React.memo( isFleetServerPolicySelected, settings?.fleet_server_hosts, viewDataStep, + enrolToken, ]); if (fleetStatus.isReady && settings?.fleet_server_hosts.length === 0) { diff --git a/x-pack/plugins/fleet/public/components/agent_enrollment_flyout/standalone_instructions.tsx b/x-pack/plugins/fleet/public/components/agent_enrollment_flyout/standalone_instructions.tsx index fa039a73e206e..7cf0bbd0782b7 100644 --- a/x-pack/plugins/fleet/public/components/agent_enrollment_flyout/standalone_instructions.tsx +++ b/x-pack/plugins/fleet/public/components/agent_enrollment_flyout/standalone_instructions.tsx @@ -159,7 +159,7 @@ export const StandaloneInstructions = React.memo( downloadLink = isK8s === 'IS_KUBERNETES' ? core.http.basePath.prepend( - `${agentPolicyRouteService.getInfoFullDownloadPath(selectedPolicyId)}?kubernetes=true` + `${agentPolicyRouteService.getInfoFullDownloadPath(selectedPolicyId)}?kubernetes=true&standalone=true` ) : core.http.basePath.prepend( `${agentPolicyRouteService.getInfoFullDownloadPath(selectedPolicyId)}?standalone=true` @@ -188,7 +188,7 @@ export const StandaloneInstructions = React.memo( refreshAgentPolicies, }) : undefined, - DownloadStep(false), + DownloadStep(false, ''), { title: i18n.translate('xpack.fleet.agentEnrollment.stepConfigureAgentTitle', { defaultMessage: 'Configure the agent', diff --git a/x-pack/plugins/fleet/public/components/agent_enrollment_flyout/steps.tsx b/x-pack/plugins/fleet/public/components/agent_enrollment_flyout/steps.tsx index 31a56056c0bcc..ed21203016c2b 100644 --- a/x-pack/plugins/fleet/public/components/agent_enrollment_flyout/steps.tsx +++ b/x-pack/plugins/fleet/public/components/agent_enrollment_flyout/steps.tsx @@ -5,8 +5,8 @@ * 2.0. */ -import React, { useCallback, useMemo, useState } from 'react'; -import { EuiText, EuiButton, EuiSpacer } from '@elastic/eui'; +import React, {useCallback, useEffect, useMemo, useState} from 'react'; +import {EuiText, EuiButton, EuiSpacer, EuiCode, EuiFlexGroup, EuiFlexItem, EuiCopy, EuiCodeBlock} from '@elastic/eui'; import { FormattedMessage } from '@kbn/i18n-react'; import { i18n } from '@kbn/i18n'; import semverMajor from 'semver/functions/major'; @@ -14,29 +14,78 @@ import semverMinor from 'semver/functions/minor'; import semverPatch from 'semver/functions/patch'; import type { AgentPolicy } from '../../types'; -import { useKibanaVersion } from '../../hooks'; +import {useGetSettings, useKibanaVersion, useStartServices} from '../../hooks'; import { AdvancedAgentAuthenticationSettings } from './advanced_agent_authentication_settings'; import { SelectCreateAgentPolicy } from './agent_policy_select_create'; +import {agentPolicyRouteService} from "../../../common"; +import {sendGetK8sManifest} from "../../hooks/use_request/k8s"; -export const DownloadStep = (hasFleetServer: boolean) => { +export const DownloadStep = (hasFleetServer: boolean, isK8s: string, enrollmentAPIKey: string) => { const kibanaVersion = useKibanaVersion(); + const core = useStartServices(); + const settings = useGetSettings(); const kibanaVersionURLString = useMemo( () => `${semverMajor(kibanaVersion)}-${semverMinor(kibanaVersion)}-${semverPatch(kibanaVersion)}`, [kibanaVersion] ); + + const [yaml, setYaml] = useState(); + const [fleetServer, setFleetServer] = useState(); + useEffect(() => { + async function fetchK8sManifest() { + try { + if (isK8s !== 'IS_KUBERNETES') { + return; + } + const fleetServerHosts = settings.data?.item.fleet_server_hosts; + let host = ''; + if (fleetServerHosts !== undefined){ + setFleetServer(fleetServerHosts[0]); + host = fleetServerHosts[0]; + } + const query = { fleetServer: host, enrolToken: enrollmentAPIKey }; + const res = await sendGetK8sManifest(query); + if (res.error) { + throw res.error; + } + + if (!res.data) { + throw new Error('No data while fetching agent manifest'); + } + + setYaml(res.data.item); + } catch (error) { + throw new Error('No data while fetching agent manifest'); + } + } + fetchK8sManifest(); + }, [isK8s, enrollmentAPIKey]); + + const altTitle = + isK8s === 'IS_KUBERNETES' + ? i18n.translate('xpack.fleet.agentEnrollment.stepDownloadAgentForK8sTitle', { + defaultMessage: 'Download the Elastic Agent Manifest', + }) + : i18n.translate('xpack.fleet.agentEnrollment.stepDownloadAgentTitle', { + defaultMessage: 'Download the Elastic Agent to your host', + }); const title = hasFleetServer ? i18n.translate('xpack.fleet.agentEnrollment.stepDownloadAgentForFleetServerTitle', { defaultMessage: 'Download the Fleet Server to a centralized host', }) - : i18n.translate('xpack.fleet.agentEnrollment.stepDownloadAgentTitle', { - defaultMessage: 'Download the Elastic Agent to your host', - }); - const downloadDescription = hasFleetServer ? ( + : altTitle; + + const altDownloadDescription = + isK8s === 'IS_KUBERNETES' ? ( FLEET_URL, + FleetTokenVariable: FLEET_ENROLLMENT_TOKEN, + }} /> ) : ( { defaultMessage="Install the Elastic Agent on the hosts you wish to monitor. Do not install this agent policy on a host containing Fleet Server. You can download the Elastic Agent binaries and verification signatures from Elastic’s download page." /> ); + + const downloadDescription = hasFleetServer ? ( + + ) : altDownloadDescription; + + const linuxUsers = + isK8s !== 'IS_KUBERNETES' ? ( + + ) : ( + "" + ) + const k8sCopyYaml = + isK8s === 'IS_KUBERNETES' ? ( + + {(copy) => ( + + + + )} + + ) : ( + "" + ) + const k8sYaml = + isK8s === 'IS_KUBERNETES' ? ( + + {yaml} + + ) : ( + "" + ) + + const downloadLink = + isK8s === 'IS_KUBERNETES' + ? core.http.basePath.prepend( + `${agentPolicyRouteService.getK8sFullDownloadPath()}?fleetServer=${fleetServer}&enrolToken=${enrollmentAPIKey}` + ) : (`https://www.elastic.co/downloads/past-releases/elastic-agent-${kibanaVersionURLString}`); + + const downloadMsg = + isK8s === 'IS_KUBERNETES' ? ( + + ) : ( + + ); + return { title, children: ( @@ -51,23 +160,25 @@ export const DownloadStep = (hasFleetServer: boolean) => { {downloadDescription} - + <>{linuxUsers} + <>{k8sYaml} - - - + + + + <>{downloadMsg} + + + + <>{k8sCopyYaml} + + ), }; diff --git a/x-pack/plugins/fleet/public/components/agent_enrollment_flyout/types.ts b/x-pack/plugins/fleet/public/components/agent_enrollment_flyout/types.ts index 0c447ad0870ff..edb34e876e7c8 100644 --- a/x-pack/plugins/fleet/public/components/agent_enrollment_flyout/types.ts +++ b/x-pack/plugins/fleet/public/components/agent_enrollment_flyout/types.ts @@ -25,7 +25,11 @@ export interface BaseProps { setSelectedPolicyId?: (policyId?: string) => void; + policyId?: string; + isFleetServerPolicySelected?: boolean; + + isK8s?: string; } export interface InstructionProps extends BaseProps { diff --git a/x-pack/plugins/fleet/public/components/enrollment_instructions/manual/index.tsx b/x-pack/plugins/fleet/public/components/enrollment_instructions/manual/index.tsx index 16ed53020a313..f7c742c7e3740 100644 --- a/x-pack/plugins/fleet/public/components/enrollment_instructions/manual/index.tsx +++ b/x-pack/plugins/fleet/public/components/enrollment_instructions/manual/index.tsx @@ -6,8 +6,7 @@ */ import React from 'react'; - -import { useStartServices } from '../../../hooks'; +import { useStartServices, useKibanaVersion } from '../../../hooks'; import type { EnrollmentAPIKey } from '../../../types'; import { PlatformSelector } from './platform_selector'; @@ -15,6 +14,8 @@ import { PlatformSelector } from './platform_selector'; interface Props { fleetServerHosts: string[]; apiKey: EnrollmentAPIKey; + policyId: string | undefined; + isK8s: string | undefined; } function getfleetServerHostsEnrollArgs(apiKey: EnrollmentAPIKey, fleetServerHosts: string[]) { @@ -22,23 +23,32 @@ function getfleetServerHostsEnrollArgs(apiKey: EnrollmentAPIKey, fleetServerHost } export const ManualInstructions: React.FunctionComponent = ({ - apiKey, - fleetServerHosts, -}) => { + apiKey, + fleetServerHosts, + policyId, + isK8s + }) => { + + const { docLinks } = useStartServices(); const enrollArgs = getfleetServerHostsEnrollArgs(apiKey, fleetServerHosts); - const linuxMacCommand = `sudo ./elastic-agent install ${enrollArgs}`; + const linuxMacCommand = + isK8s === 'IS_KUBERNETES' + ? `kubectl apply -f elastic-agent-managed-kubernetes.yaml` + :`sudo ./elastic-agent install ${enrollArgs}`; + const windowsCommand = `.\\elastic-agent.exe install ${enrollArgs}`; + return ( ); }; diff --git a/x-pack/plugins/fleet/public/hooks/use_request/k8s.ts b/x-pack/plugins/fleet/public/hooks/use_request/k8s.ts new file mode 100644 index 0000000000000..b7d538eda8d65 --- /dev/null +++ b/x-pack/plugins/fleet/public/hooks/use_request/k8s.ts @@ -0,0 +1,20 @@ +/* + * 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 { agentPolicyRouteService } from '../../services'; +import { sendRequest } from './use_request'; +import {GetFullAgentManifestResponse} from "../../../common"; + +export const sendGetK8sManifest = ( + query: { fleetServer?: string; enrolToken?: string } = {} + ) => { + return sendRequest({ + path: agentPolicyRouteService.getK8sInfoPath(), + method: 'get', + query + }); +}; diff --git a/x-pack/plugins/fleet/server/routes/agent_policy/handlers.ts b/x-pack/plugins/fleet/server/routes/agent_policy/handlers.ts index 4016d4ea690c4..152d4fe5da955 100644 --- a/x-pack/plugins/fleet/server/routes/agent_policy/handlers.ts +++ b/x-pack/plugins/fleet/server/routes/agent_policy/handlers.ts @@ -35,9 +35,11 @@ import type { DeleteAgentPolicyResponse, GetFullAgentPolicyResponse, GetFullAgentConfigMapResponse, + GetFullAgentManifestResponse, } from '../../../common'; import { defaultIngestErrorHandler } from '../../errors'; import { createAgentPolicyWithPackages } from '../../services/agent_policy_create'; +import {GetK8sManifestRequestSchema} from "../../types"; export const getAgentPoliciesHandler: FleetRequestHandler< undefined, @@ -217,28 +219,50 @@ export const getFullAgentPolicy: FleetRequestHandler< const soClient = context.fleet.epm.internalSoClient; if (request.query.kubernetes === true) { - try { - const fullAgentConfigMap = await agentPolicyService.getFullAgentConfigMap( - soClient, - request.params.agentPolicyId, - { standalone: request.query.standalone === true } - ); - if (fullAgentConfigMap) { - const body: GetFullAgentConfigMapResponse = { - item: fullAgentConfigMap, - }; - return response.ok({ - body, - }); - } else { - return response.customError({ - statusCode: 404, - body: { message: 'Agent config map not found' }, - }); + if (request.query.standalone === true) { + try { + const fullAgentConfigMap = await agentPolicyService.getFullAgentConfigMap( + soClient, + request.params.agentPolicyId, + { standalone: request.query.standalone } + ); + if (fullAgentConfigMap) { + const body: GetFullAgentConfigMapResponse = { + item: fullAgentConfigMap, + }; + return response.ok({ + body, + }); + } else { + return response.customError({ + statusCode: 404, + body: { message: 'Agent config map not found' }, + }); + } + } catch (error) { + return defaultIngestErrorHandler({ error, response }); + } + } else { + try { + const fullAgentManifest = await agentPolicyService.getFullAgentManifest("", ""); + if (fullAgentManifest) { + const body: GetFullAgentManifestResponse = { + item: fullAgentManifest, + }; + return response.ok({ + body, + }); + } else { + return response.customError({ + statusCode: 404, + body: { message: 'Agent manifest not found' }, + }); + } + } catch (error) { + return defaultIngestErrorHandler({ error, response }); } - } catch (error) { - return defaultIngestErrorHandler({ error, response }); } + } else { try { const fullAgentPolicy = await agentPolicyService.getFullAgentPolicy( @@ -275,30 +299,32 @@ export const downloadFullAgentPolicy: FleetRequestHandler< } = request; if (request.query.kubernetes === true) { - try { - const fullAgentConfigMap = await agentPolicyService.getFullAgentConfigMap( - soClient, - request.params.agentPolicyId, - { standalone: request.query.standalone === true } - ); - if (fullAgentConfigMap) { - const body = fullAgentConfigMap; - const headers: ResponseHeaders = { - 'content-type': 'text/x-yaml', - 'content-disposition': `attachment; filename="elastic-agent-standalone-kubernetes.yaml"`, - }; - return response.ok({ - body, - headers, - }); - } else { - return response.customError({ - statusCode: 404, - body: { message: 'Agent config map not found' }, - }); + if (request.query.standalone === true) { + try { + const fullAgentConfigMap = await agentPolicyService.getFullAgentConfigMap( + soClient, + request.params.agentPolicyId, + {standalone: request.query.standalone } + ); + if (fullAgentConfigMap) { + const body = fullAgentConfigMap; + const headers: ResponseHeaders = { + 'content-type': 'text/x-yaml', + 'content-disposition': `attachment; filename="elastic-agent-standalone-kubernetes.yaml"`, + }; + return response.ok({ + body, + headers, + }); + } else { + return response.customError({ + statusCode: 404, + body: {message: 'Agent config map not found'}, + }); + } + } catch (error) { + return defaultIngestErrorHandler({error, response}); } - } catch (error) { - return defaultIngestErrorHandler({ error, response }); } } else { try { @@ -326,3 +352,54 @@ export const downloadFullAgentPolicy: FleetRequestHandler< } } }; + +export const getK8sManifest: FleetRequestHandler< + TypeOf + > = async (context, request, response) => { + + try { + const fullAgentManifest = await agentPolicyService.getFullAgentManifest(request.query.fleetServer, request.query.enrolToken); + if (fullAgentManifest) { + const body: GetFullAgentManifestResponse = { + item: fullAgentManifest, + }; + return response.ok({ + body, + }); + } else { + return response.customError({ + statusCode: 404, + body: { message: 'Agent manifest not found' }, + }); + } + } catch (error) { + return defaultIngestErrorHandler({ error, response }); + } +}; + +export const downloadK8sManifest: FleetRequestHandler< + TypeOf + > = async (context, request, response) => { + + try { + const fullAgentManifest = await agentPolicyService.getFullAgentManifest(request.query.fleetServer, request.query.enrolToken); + if (fullAgentManifest) { + const body = fullAgentManifest; + const headers: ResponseHeaders = { + 'content-type': 'text/x-yaml', + 'content-disposition': `attachment; filename="elastic-agent-managed-kubernetes.yaml"`, + }; + return response.ok({ + body, + headers, + }); + } else { + return response.customError({ + statusCode: 404, + body: {message: 'Agent manifest not found'}, + }); + } + } catch (error) { + return defaultIngestErrorHandler({error, response}); + } +}; diff --git a/x-pack/plugins/fleet/server/routes/agent_policy/index.ts b/x-pack/plugins/fleet/server/routes/agent_policy/index.ts index 3819b009f2763..2510939d26d27 100644 --- a/x-pack/plugins/fleet/server/routes/agent_policy/index.ts +++ b/x-pack/plugins/fleet/server/routes/agent_policy/index.ts @@ -14,6 +14,7 @@ import { CopyAgentPolicyRequestSchema, DeleteAgentPolicyRequestSchema, GetFullAgentPolicyRequestSchema, + GetK8sManifestRequestSchema, } from '../../types'; import type { FleetAuthzRouter } from '../security'; @@ -25,8 +26,9 @@ import { copyAgentPolicyHandler, deleteAgentPoliciesHandler, getFullAgentPolicy, - downloadFullAgentPolicy, + downloadFullAgentPolicy, downloadK8sManifest, getK8sManifest, } from './handlers'; +import {K8S_API_ROUTES} from "../../../common"; export const registerRoutes = (router: FleetAuthzRouter) => { // List - Fleet Server needs access to run setup @@ -124,4 +126,28 @@ export const registerRoutes = (router: FleetAuthzRouter) => { }, downloadFullAgentPolicy ); + + // Get agent manifest + router.get( + { + path: K8S_API_ROUTES.K8S_INFO_PATTERN, + validate: GetK8sManifestRequestSchema, + fleetAuthz: { + fleet: { all: true }, + }, + }, + getK8sManifest + ); + + // Download agent manifest + router.get( + { + path: K8S_API_ROUTES.K8S_DOWNLOAD_PATTERN, + validate: GetK8sManifestRequestSchema, + fleetAuthz: { + fleet: { all: true }, + }, + }, + downloadK8sManifest + ); }; diff --git a/x-pack/plugins/fleet/server/services/agent_policy.ts b/x-pack/plugins/fleet/server/services/agent_policy.ts index 6a191863fc2f7..0fcf18c1300f4 100644 --- a/x-pack/plugins/fleet/server/services/agent_policy.ts +++ b/x-pack/plugins/fleet/server/services/agent_policy.ts @@ -52,7 +52,7 @@ import type { FullAgentConfigMap } from '../../common/types/models/agent_cm'; import { fullAgentConfigMapToYaml } from '../../common/services/agent_cm_to_yaml'; -import { elasticAgentManifest } from './elastic_agent_manifest'; +import { elasticAgentStandaloneManifest, elasticAgentManagedManifest } from './elastic_agent_manifest'; import { getPackageInfo } from './epm/packages'; import { getAgentsByKuery } from './agents'; @@ -709,7 +709,7 @@ class AgentPolicyService { }; const configMapYaml = fullAgentConfigMapToYaml(fullAgentConfigMap, safeDump); - const updateManifestVersion = elasticAgentManifest.replace( + const updateManifestVersion = elasticAgentStandaloneManifest.replace( 'VERSION', appContextService.getKibanaVersion() ); @@ -720,6 +720,28 @@ class AgentPolicyService { } } + public async getFullAgentManifest(fleetServer: string, enrolToken: string): Promise { + const updateManifestVersion = elasticAgentManagedManifest.replace( + 'VERSION', + appContextService.getKibanaVersion() + ); + let updateManifest = updateManifestVersion; + if (fleetServer !== '') { + updateManifest = updateManifest.replace( + 'https://fleet-server:8220', + fleetServer + ); + } + if (enrolToken !== '') { + updateManifest = updateManifest.replace( + 'token-id', + enrolToken + ); + } + + return updateManifest; + } + public async getFullAgentPolicy( soClient: SavedObjectsClientContract, id: string, diff --git a/x-pack/plugins/fleet/server/services/elastic_agent_manifest.ts b/x-pack/plugins/fleet/server/services/elastic_agent_manifest.ts index 392ee170d02ad..4ce39483f09a3 100644 --- a/x-pack/plugins/fleet/server/services/elastic_agent_manifest.ts +++ b/x-pack/plugins/fleet/server/services/elastic_agent_manifest.ts @@ -5,7 +5,7 @@ * 2.0. */ -export const elasticAgentManifest = ` +export const elasticAgentStandaloneManifest = ` --- apiVersion: apps/v1 kind: DaemonSet @@ -168,6 +168,7 @@ rules: - apiGroups: ["batch"] resources: - jobs + - cronjobs verbs: ["get", "list", "watch"] - apiGroups: - "" @@ -220,3 +221,220 @@ metadata: k8s-app: elastic-agent --- `; + +export const elasticAgentManagedManifest = ` +apiVersion: apps/v1 +kind: DaemonSet +metadata: + name: elastic-agent + namespace: kube-system + labels: + app: elastic-agent +spec: + selector: + matchLabels: + app: elastic-agent + template: + metadata: + labels: + app: elastic-agent + spec: + tolerations: + - key: node-role.kubernetes.io/master + effect: NoSchedule + serviceAccountName: elastic-agent + hostNetwork: true + dnsPolicy: ClusterFirstWithHostNet + containers: + - name: elastic-agent + image: docker.elastic.co/beats/elastic-agent:VERSION + env: + - name: FLEET_ENROLL + value: "1" + # Set to true in case of insecure or unverified HTTP + - name: FLEET_INSECURE + value: "true" + # The ip:port pair of fleet server + - name: FLEET_URL + value: "https://fleet-server:8220" + # If left empty KIBANA_HOST, KIBANA_FLEET_USERNAME, KIBANA_FLEET_PASSWORD are needed + - name: FLEET_ENROLLMENT_TOKEN + value: "token-id" + - name: KIBANA_HOST + value: "http://kibana:5601" + - name: KIBANA_FLEET_USERNAME + value: "elastic" + - name: KIBANA_FLEET_PASSWORD + value: "changeme" + - name: NODE_NAME + valueFrom: + fieldRef: + fieldPath: spec.nodeName + - name: POD_NAME + valueFrom: + fieldRef: + fieldPath: metadata.name + securityContext: + runAsUser: 0 + resources: + limits: + memory: 500Mi + requests: + cpu: 100m + memory: 200Mi + volumeMounts: + - name: proc + mountPath: /hostfs/proc + readOnly: true + - name: cgroup + mountPath: /hostfs/sys/fs/cgroup + readOnly: true + - name: varlibdockercontainers + mountPath: /var/lib/docker/containers + readOnly: true + - name: varlog + mountPath: /var/log + readOnly: true + volumes: + - name: proc + hostPath: + path: /proc + - name: cgroup + hostPath: + path: /sys/fs/cgroup + - name: varlibdockercontainers + hostPath: + path: /var/lib/docker/containers + - name: varlog + hostPath: + path: /var/log +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRoleBinding +metadata: + name: elastic-agent +subjects: + - kind: ServiceAccount + name: elastic-agent + namespace: kube-system +roleRef: + kind: ClusterRole + name: elastic-agent + apiGroup: rbac.authorization.k8s.io +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: RoleBinding +metadata: + namespace: kube-system + name: elastic-agent +subjects: + - kind: ServiceAccount + name: elastic-agent + namespace: kube-system +roleRef: + kind: Role + name: elastic-agent + apiGroup: rbac.authorization.k8s.io +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: RoleBinding +metadata: + name: elastic-agent-kubeadm-config + namespace: kube-system +subjects: + - kind: ServiceAccount + name: elastic-agent + namespace: kube-system +roleRef: + kind: Role + name: elastic-agent-kubeadm-config + apiGroup: rbac.authorization.k8s.io +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRole +metadata: + name: elastic-agent + labels: + k8s-app: elastic-agent +rules: + - apiGroups: [""] + resources: + - nodes + - namespaces + - events + - pods + - services + - configmaps + verbs: ["get", "list", "watch"] + # Enable this rule only if planing to use kubernetes_secrets provider + #- apiGroups: [""] + # resources: + # - secrets + # verbs: ["get"] + - apiGroups: ["extensions"] + resources: + - replicasets + verbs: ["get", "list", "watch"] + - apiGroups: ["apps"] + resources: + - statefulsets + - deployments + - replicasets + verbs: ["get", "list", "watch"] + - apiGroups: + - "" + resources: + - nodes/stats + verbs: + - get + - apiGroups: [ "batch" ] + resources: + - jobs + - cronjobs + verbs: [ "get", "list", "watch" ] + # required for apiserver + - nonResourceURLs: + - "/metrics" + verbs: + - get +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: Role +metadata: + name: elastic-agent + # should be the namespace where elastic-agent is running + namespace: kube-system + labels: + k8s-app: elastic-agent +rules: + - apiGroups: + - coordination.k8s.io + resources: + - leases + verbs: ["get", "create", "update"] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: Role +metadata: + name: elastic-agent-kubeadm-config + namespace: kube-system + labels: + k8s-app: elastic-agent +rules: + - apiGroups: [""] + resources: + - configmaps + resourceNames: + - kubeadm-config + verbs: ["get"] +--- +apiVersion: v1 +kind: ServiceAccount +metadata: + name: elastic-agent + namespace: kube-system + labels: + k8s-app: elastic-agent +--- + +`; diff --git a/x-pack/plugins/fleet/server/types/rest_spec/agent_policy.ts b/x-pack/plugins/fleet/server/types/rest_spec/agent_policy.ts index 64d142f150bfd..956103627557b 100644 --- a/x-pack/plugins/fleet/server/types/rest_spec/agent_policy.ts +++ b/x-pack/plugins/fleet/server/types/rest_spec/agent_policy.ts @@ -59,3 +59,11 @@ export const GetFullAgentPolicyRequestSchema = { kubernetes: schema.maybe(schema.boolean()), }), }; + +export const GetK8sManifestRequestSchema = { + query: schema.object({ + download: schema.maybe(schema.boolean()), + fleetServer: schema.maybe(schema.string()), + enrolToken: schema.maybe(schema.string()), + }), +}; diff --git a/x-pack/plugins/translations/translations/ja-JP.json b/x-pack/plugins/translations/translations/ja-JP.json index 59dd27f94d1e5..ac6372bb0d7bd 100644 --- a/x-pack/plugins/translations/translations/ja-JP.json +++ b/x-pack/plugins/translations/translations/ja-JP.json @@ -6266,6 +6266,19 @@ "visTypeVislib.advancedSettings.visualization.heatmap.maxBucketsText": "1つのデータソースが返せるバケットの最大数です。値が大きいとブラウザのレンダリング速度が下がる可能性があります。", "visTypeVislib.advancedSettings.visualization.heatmap.maxBucketsTitle": "ヒートマップの最大バケット数", "visTypeVislib.aggResponse.allDocsTitle": "すべてのドキュメント", + "visTypeVislib.functions.pie.help": "パイビジュアライゼーション", + "visTypeVislib.functions.vislib.help": "Vislib ビジュアライゼーション", + "visTypeVislib.vislib.errors.noResultsFoundTitle": "結果が見つかりませんでした", + "visTypeVislib.vislib.heatmap.maxBucketsText": "定義された数列が多すぎます({nr})。構成されている最大値は {max} です。", + "visTypeVislib.vislib.legend.filterForValueButtonAriaLabel": "値 {legendDataLabel} でフィルタリング", + "visTypeVislib.vislib.legend.filterOptionsLegend": "{legendDataLabel}、フィルターオプション", + "visTypeVislib.vislib.legend.filterOutValueButtonAriaLabel": "値 {legendDataLabel} を除外", + "visTypeVislib.vislib.legend.loadingLabel": "読み込み中…", + "visTypeVislib.vislib.legend.toggleLegendButtonAriaLabel": "凡例を切り替える", + "visTypeVislib.vislib.legend.toggleLegendButtonTitle": "凡例を切り替える", + "visTypeVislib.vislib.legend.toggleOptionsButtonAriaLabel": "{legendDataLabel}、トグルオプション", + "visTypeVislib.vislib.tooltip.fieldLabel": "フィールド", + "visTypeVislib.vislib.tooltip.valueLabel": "値", "visTypeGauge.controls.gaugeOptions.alignmentLabel": "アラインメント", "visTypeGauge.controls.gaugeOptions.autoExtendRangeLabel": "範囲を自動拡張", "visTypeGauge.controls.gaugeOptions.extendRangeTooltip": "範囲をデータの最高値に広げます。", @@ -6278,8 +6291,6 @@ "visTypeGauge.controls.gaugeOptions.showScaleLabel": "縮尺を表示", "visTypeGauge.controls.gaugeOptions.styleTitle": "スタイル", "visTypeGauge.controls.gaugeOptions.subTextLabel": "サブラベル", - "visTypeVislib.functions.pie.help": "パイビジュアライゼーション", - "visTypeVislib.functions.vislib.help": "Vislib ビジュアライゼーション", "visTypeGauge.gauge.alignmentAutomaticTitle": "自動", "visTypeGauge.gauge.alignmentHorizontalTitle": "横", "visTypeGauge.gauge.alignmentVerticalTitle": "縦", @@ -6293,17 +6304,6 @@ "visTypeGauge.goal.goalTitle": "ゴール", "visTypeGauge.goal.groupTitle": "グループを分割", "visTypeGauge.goal.metricTitle": "メトリック", - "visTypeVislib.vislib.errors.noResultsFoundTitle": "結果が見つかりませんでした", - "visTypeVislib.vislib.heatmap.maxBucketsText": "定義された数列が多すぎます({nr})。構成されている最大値は {max} です。", - "visTypeVislib.vislib.legend.filterForValueButtonAriaLabel": "値 {legendDataLabel} でフィルタリング", - "visTypeVislib.vislib.legend.filterOptionsLegend": "{legendDataLabel}、フィルターオプション", - "visTypeVislib.vislib.legend.filterOutValueButtonAriaLabel": "値 {legendDataLabel} を除外", - "visTypeVislib.vislib.legend.loadingLabel": "読み込み中…", - "visTypeVislib.vislib.legend.toggleLegendButtonAriaLabel": "凡例を切り替える", - "visTypeVislib.vislib.legend.toggleLegendButtonTitle": "凡例を切り替える", - "visTypeVislib.vislib.legend.toggleOptionsButtonAriaLabel": "{legendDataLabel}、トグルオプション", - "visTypeVislib.vislib.tooltip.fieldLabel": "フィールド", - "visTypeVislib.vislib.tooltip.valueLabel": "値", "visTypeXy.aggResponse.allDocsTitle": "すべてのドキュメント", "visTypeXy.area.areaDescription": "軸と線の間のデータを強調します。", "visTypeXy.area.areaTitle": "エリア", diff --git a/x-pack/plugins/translations/translations/zh-CN.json b/x-pack/plugins/translations/translations/zh-CN.json index 5af6782572cda..d4b48dd5866ee 100644 --- a/x-pack/plugins/translations/translations/zh-CN.json +++ b/x-pack/plugins/translations/translations/zh-CN.json @@ -6277,6 +6277,19 @@ "visTypeVislib.advancedSettings.visualization.heatmap.maxBucketsText": "单个数据源可以返回的最大存储桶数目。较高的数目可能对浏览器呈现性能有负面影响", "visTypeVislib.advancedSettings.visualization.heatmap.maxBucketsTitle": "热图最大存储桶数", "visTypeVislib.aggResponse.allDocsTitle": "所有文档", + "visTypeVislib.functions.pie.help": "饼图可视化", + "visTypeVislib.functions.vislib.help": "Vislib 可视化", + "visTypeVislib.vislib.errors.noResultsFoundTitle": "找不到结果", + "visTypeVislib.vislib.heatmap.maxBucketsText": "定义了过多的序列 ({nr})。配置的最大值为 {max}。", + "visTypeVislib.vislib.legend.filterForValueButtonAriaLabel": "筛留值 {legendDataLabel}", + "visTypeVislib.vislib.legend.filterOptionsLegend": "{legendDataLabel}, 筛选选项", + "visTypeVislib.vislib.legend.filterOutValueButtonAriaLabel": "筛除值 {legendDataLabel}", + "visTypeVislib.vislib.legend.loadingLabel": "正在加载……", + "visTypeVislib.vislib.legend.toggleLegendButtonAriaLabel": "切换图例", + "visTypeVislib.vislib.legend.toggleLegendButtonTitle": "切换图例", + "visTypeVislib.vislib.legend.toggleOptionsButtonAriaLabel": "{legendDataLabel}, 切换选项", + "visTypeVislib.vislib.tooltip.fieldLabel": "字段", + "visTypeVislib.vislib.tooltip.valueLabel": "值", "visTypeGauge.controls.gaugeOptions.alignmentLabel": "对齐方式", "visTypeGauge.controls.gaugeOptions.autoExtendRangeLabel": "自动扩展范围", "visTypeGauge.controls.gaugeOptions.extendRangeTooltip": "将数据范围扩展到数据中的最大值。", @@ -6289,8 +6302,6 @@ "visTypeGauge.controls.gaugeOptions.showScaleLabel": "显示比例", "visTypeGauge.controls.gaugeOptions.styleTitle": "样式", "visTypeGauge.controls.gaugeOptions.subTextLabel": "子标签", - "visTypeVislib.functions.pie.help": "饼图可视化", - "visTypeVislib.functions.vislib.help": "Vislib 可视化", "visTypeGauge.gauge.alignmentAutomaticTitle": "自动", "visTypeGauge.gauge.alignmentHorizontalTitle": "水平", "visTypeGauge.gauge.alignmentVerticalTitle": "垂直", @@ -6304,17 +6315,6 @@ "visTypeGauge.goal.goalTitle": "目标图", "visTypeGauge.goal.groupTitle": "拆分组", "visTypeGauge.goal.metricTitle": "指标", - "visTypeVislib.vislib.errors.noResultsFoundTitle": "找不到结果", - "visTypeVislib.vislib.heatmap.maxBucketsText": "定义了过多的序列 ({nr})。配置的最大值为 {max}。", - "visTypeVislib.vislib.legend.filterForValueButtonAriaLabel": "筛留值 {legendDataLabel}", - "visTypeVislib.vislib.legend.filterOptionsLegend": "{legendDataLabel}, 筛选选项", - "visTypeVislib.vislib.legend.filterOutValueButtonAriaLabel": "筛除值 {legendDataLabel}", - "visTypeVislib.vislib.legend.loadingLabel": "正在加载……", - "visTypeVislib.vislib.legend.toggleLegendButtonAriaLabel": "切换图例", - "visTypeVislib.vislib.legend.toggleLegendButtonTitle": "切换图例", - "visTypeVislib.vislib.legend.toggleOptionsButtonAriaLabel": "{legendDataLabel}, 切换选项", - "visTypeVislib.vislib.tooltip.fieldLabel": "字段", - "visTypeVislib.vislib.tooltip.valueLabel": "值", "visTypeXy.aggResponse.allDocsTitle": "所有文档", "visTypeXy.area.areaDescription": "突出轴与线之间的数据。", "visTypeXy.area.areaTitle": "面积图", From 09aba53f6aa4f0b1738b4b9cee37ede6275ce73e Mon Sep 17 00:00:00 2001 From: MichaelKatsoulis Date: Tue, 15 Mar 2022 12:20:02 +0200 Subject: [PATCH 02/12] lint --- .../plugins/fleet/common/constants/routes.ts | 2 +- .../agent_enrollment_flyout/index.tsx | 7 +- .../managed_instructions.tsx | 5 +- .../standalone_instructions.tsx | 4 +- .../agent_enrollment_flyout/steps.tsx | 113 ++++++++++-------- .../enrollment_instructions/manual/index.tsx | 19 ++- .../fleet/public/hooks/use_request/k8s.ts | 12 +- .../server/routes/agent_policy/handlers.ts | 31 ++--- .../fleet/server/routes/agent_policy/index.ts | 7 +- .../fleet/server/services/agent_policy.ts | 36 +++--- 10 files changed, 123 insertions(+), 113 deletions(-) diff --git a/x-pack/plugins/fleet/common/constants/routes.ts b/x-pack/plugins/fleet/common/constants/routes.ts index 3c0b9c323d380..f13502008bfe8 100644 --- a/x-pack/plugins/fleet/common/constants/routes.ts +++ b/x-pack/plugins/fleet/common/constants/routes.ts @@ -72,7 +72,7 @@ export const AGENT_POLICY_API_ROUTES = { export const K8S_API_ROUTES = { K8S_DOWNLOAD_PATTERN: `${K8S_API_ROOT}/download`, K8S_INFO_PATTERN: `${K8S_API_ROOT}`, -} +}; // Output API routes export const OUTPUT_API_ROUTES = { diff --git a/x-pack/plugins/fleet/public/components/agent_enrollment_flyout/index.tsx b/x-pack/plugins/fleet/public/components/agent_enrollment_flyout/index.tsx index d4ac4524d577e..c8f34da996e3a 100644 --- a/x-pack/plugins/fleet/public/components/agent_enrollment_flyout/index.tsx +++ b/x-pack/plugins/fleet/public/components/agent_enrollment_flyout/index.tsx @@ -28,16 +28,17 @@ import { useFleetStatus, useAgentEnrollmentFlyoutData, } from '../../hooks'; -import {FLEET_SERVER_PACKAGE, SO_SEARCH_LIMIT} from '../../constants'; +import { FLEET_SERVER_PACKAGE, SO_SEARCH_LIMIT } from '../../constants'; import type { PackagePolicy } from '../../types'; import { Loading } from '..'; +import { FLEET_KUBERNETES_PACKAGE } from '../../../common'; + import { ManagedInstructions } from './managed_instructions'; import { StandaloneInstructions } from './standalone_instructions'; import { MissingFleetServerHostCallout } from './missing_fleet_server_host_callout'; import type { BaseProps } from './types'; -import {FLEET_KUBERNETES_PACKAGE} from "../../../common"; type FlyoutMode = 'managed' | 'standalone'; @@ -94,7 +95,6 @@ export const AgentEnrollmentFlyout: React.FunctionComponent = ({ checkPolicyIsFleetServer(); }, [policyId]); - const [isK8s, setIsK8s] = useState<'IS_LOADING' | 'IS_KUBERNETES' | 'IS_NOT_KUBERNETES'>( 'IS_LOADING' ); @@ -121,7 +121,6 @@ export const AgentEnrollmentFlyout: React.FunctionComponent = ({ checkifK8s(); }, [policyId]); - const isLoadingInitialRequest = settings.isLoading && settings.isInitialRequest; return ( diff --git a/x-pack/plugins/fleet/public/components/agent_enrollment_flyout/managed_instructions.tsx b/x-pack/plugins/fleet/public/components/agent_enrollment_flyout/managed_instructions.tsx index 555d4d4be0dac..50da51a868a59 100644 --- a/x-pack/plugins/fleet/public/components/agent_enrollment_flyout/managed_instructions.tsx +++ b/x-pack/plugins/fleet/public/components/agent_enrollment_flyout/managed_instructions.tsx @@ -111,10 +111,7 @@ export const ManagedInstructions = React.memo( ]; }, [fleetServerInstructions]); - const enrolToken = - apiKey.data - ? apiKey.data.item.api_key: - '' + const enrolToken = apiKey.data ? apiKey.data.item.api_key : ''; const steps = useMemo(() => { const fleetServerHosts = settings?.fleet_server_hosts || []; diff --git a/x-pack/plugins/fleet/public/components/agent_enrollment_flyout/standalone_instructions.tsx b/x-pack/plugins/fleet/public/components/agent_enrollment_flyout/standalone_instructions.tsx index 7cf0bbd0782b7..a2bb3c8d31d98 100644 --- a/x-pack/plugins/fleet/public/components/agent_enrollment_flyout/standalone_instructions.tsx +++ b/x-pack/plugins/fleet/public/components/agent_enrollment_flyout/standalone_instructions.tsx @@ -159,7 +159,9 @@ export const StandaloneInstructions = React.memo( downloadLink = isK8s === 'IS_KUBERNETES' ? core.http.basePath.prepend( - `${agentPolicyRouteService.getInfoFullDownloadPath(selectedPolicyId)}?kubernetes=true&standalone=true` + `${agentPolicyRouteService.getInfoFullDownloadPath( + selectedPolicyId + )}?kubernetes=true&standalone=true` ) : core.http.basePath.prepend( `${agentPolicyRouteService.getInfoFullDownloadPath(selectedPolicyId)}?standalone=true` diff --git a/x-pack/plugins/fleet/public/components/agent_enrollment_flyout/steps.tsx b/x-pack/plugins/fleet/public/components/agent_enrollment_flyout/steps.tsx index ed21203016c2b..20e31e3f44700 100644 --- a/x-pack/plugins/fleet/public/components/agent_enrollment_flyout/steps.tsx +++ b/x-pack/plugins/fleet/public/components/agent_enrollment_flyout/steps.tsx @@ -5,8 +5,17 @@ * 2.0. */ -import React, {useCallback, useEffect, useMemo, useState} from 'react'; -import {EuiText, EuiButton, EuiSpacer, EuiCode, EuiFlexGroup, EuiFlexItem, EuiCopy, EuiCodeBlock} from '@elastic/eui'; +import React, { useCallback, useEffect, useMemo, useState } from 'react'; +import { + EuiText, + EuiButton, + EuiSpacer, + EuiCode, + EuiFlexGroup, + EuiFlexItem, + EuiCopy, + EuiCodeBlock, +} from '@elastic/eui'; import { FormattedMessage } from '@kbn/i18n-react'; import { i18n } from '@kbn/i18n'; import semverMajor from 'semver/functions/major'; @@ -14,12 +23,14 @@ import semverMinor from 'semver/functions/minor'; import semverPatch from 'semver/functions/patch'; import type { AgentPolicy } from '../../types'; -import {useGetSettings, useKibanaVersion, useStartServices} from '../../hooks'; +import { useGetSettings, useKibanaVersion, useStartServices } from '../../hooks'; + +import { agentPolicyRouteService } from '../../../common'; + +import { sendGetK8sManifest } from '../../hooks/use_request/k8s'; import { AdvancedAgentAuthenticationSettings } from './advanced_agent_authentication_settings'; import { SelectCreateAgentPolicy } from './agent_policy_select_create'; -import {agentPolicyRouteService} from "../../../common"; -import {sendGetK8sManifest} from "../../hooks/use_request/k8s"; export const DownloadStep = (hasFleetServer: boolean, isK8s: string, enrollmentAPIKey: string) => { const kibanaVersion = useKibanaVersion(); @@ -41,7 +52,7 @@ export const DownloadStep = (hasFleetServer: boolean, isK8s: string, enrollmentA } const fleetServerHosts = settings.data?.item.fleet_server_hosts; let host = ''; - if (fleetServerHosts !== undefined){ + if (fleetServerHosts !== undefined) { setFleetServer(fleetServerHosts[0]); host = fleetServerHosts[0]; } @@ -57,20 +68,20 @@ export const DownloadStep = (hasFleetServer: boolean, isK8s: string, enrollmentA setYaml(res.data.item); } catch (error) { - throw new Error('No data while fetching agent manifest'); + throw new Error('No data while fetching agent manifest'); } } - fetchK8sManifest(); + fetchK8sManifest(); }, [isK8s, enrollmentAPIKey]); const altTitle = isK8s === 'IS_KUBERNETES' - ? i18n.translate('xpack.fleet.agentEnrollment.stepDownloadAgentForK8sTitle', { - defaultMessage: 'Download the Elastic Agent Manifest', - }) + ? i18n.translate('xpack.fleet.agentEnrollment.stepDownloadAgentForK8sTitle', { + defaultMessage: 'Download the Elastic Agent Manifest', + }) : i18n.translate('xpack.fleet.agentEnrollment.stepDownloadAgentTitle', { - defaultMessage: 'Download the Elastic Agent to your host', - }); + defaultMessage: 'Download the Elastic Agent to your host', + }); const title = hasFleetServer ? i18n.translate('xpack.fleet.agentEnrollment.stepDownloadAgentForFleetServerTitle', { defaultMessage: 'Download the Fleet Server to a centralized host', @@ -79,27 +90,29 @@ export const DownloadStep = (hasFleetServer: boolean, isK8s: string, enrollmentA const altDownloadDescription = isK8s === 'IS_KUBERNETES' ? ( - FLEET_URL, - FleetTokenVariable: FLEET_ENROLLMENT_TOKEN, - }} - /> - ) : ( - - ); + FLEET_URL, + FleetTokenVariable: FLEET_ENROLLMENT_TOKEN, + }} + /> + ) : ( + + ); const downloadDescription = hasFleetServer ? ( - ) : altDownloadDescription; + ) : ( + altDownloadDescription + ); const linuxUsers = isK8s !== 'IS_KUBERNETES' ? ( @@ -108,37 +121,38 @@ export const DownloadStep = (hasFleetServer: boolean, isK8s: string, enrollmentA defaultMessage="Linux users: We recommend the installer (TAR) over system packages (RPM/DEB) because it lets you upgrade your agent in Fleet." /> ) : ( - "" - ) + '' + ); const k8sCopyYaml = isK8s === 'IS_KUBERNETES' ? ( - - {(copy) => ( - - - - )} - + + {(copy) => ( + + + + )} + ) : ( - "" - ) + '' + ); const k8sYaml = isK8s === 'IS_KUBERNETES' ? ( {yaml} ) : ( - "" - ) + '' + ); const downloadLink = isK8s === 'IS_KUBERNETES' ? core.http.basePath.prepend( - `${agentPolicyRouteService.getK8sFullDownloadPath()}?fleetServer=${fleetServer}&enrolToken=${enrollmentAPIKey}` - ) : (`https://www.elastic.co/downloads/past-releases/elastic-agent-${kibanaVersionURLString}`); + `${agentPolicyRouteService.getK8sFullDownloadPath()}?fleetServer=${fleetServer}&enrolToken=${enrollmentAPIKey}` + ) + : `https://www.elastic.co/downloads/past-releases/elastic-agent-${kibanaVersionURLString}`; const downloadMsg = isK8s === 'IS_KUBERNETES' ? ( @@ -166,12 +180,7 @@ export const DownloadStep = (hasFleetServer: boolean, isK8s: string, enrollmentA - + <>{downloadMsg} diff --git a/x-pack/plugins/fleet/public/components/enrollment_instructions/manual/index.tsx b/x-pack/plugins/fleet/public/components/enrollment_instructions/manual/index.tsx index f7c742c7e3740..195bc48e02ce3 100644 --- a/x-pack/plugins/fleet/public/components/enrollment_instructions/manual/index.tsx +++ b/x-pack/plugins/fleet/public/components/enrollment_instructions/manual/index.tsx @@ -6,6 +6,7 @@ */ import React from 'react'; + import { useStartServices, useKibanaVersion } from '../../../hooks'; import type { EnrollmentAPIKey } from '../../../types'; @@ -23,25 +24,21 @@ function getfleetServerHostsEnrollArgs(apiKey: EnrollmentAPIKey, fleetServerHost } export const ManualInstructions: React.FunctionComponent = ({ - apiKey, - fleetServerHosts, - policyId, - isK8s - }) => { - - + apiKey, + fleetServerHosts, + policyId, + isK8s, +}) => { const { docLinks } = useStartServices(); const enrollArgs = getfleetServerHostsEnrollArgs(apiKey, fleetServerHosts); const linuxMacCommand = isK8s === 'IS_KUBERNETES' - ? `kubectl apply -f elastic-agent-managed-kubernetes.yaml` - :`sudo ./elastic-agent install ${enrollArgs}`; - + ? `kubectl apply -f elastic-agent-managed-kubernetes.yaml` + : `sudo ./elastic-agent install ${enrollArgs}`; const windowsCommand = `.\\elastic-agent.exe install ${enrollArgs}`; - return ( { +import type { GetFullAgentManifestResponse } from '../../../common'; + +import { sendRequest } from './use_request'; + +export const sendGetK8sManifest = (query: { fleetServer?: string; enrolToken?: string } = {}) => { return sendRequest({ path: agentPolicyRouteService.getK8sInfoPath(), method: 'get', - query + query, }); }; diff --git a/x-pack/plugins/fleet/server/routes/agent_policy/handlers.ts b/x-pack/plugins/fleet/server/routes/agent_policy/handlers.ts index 152d4fe5da955..6f1f7a1457fde 100644 --- a/x-pack/plugins/fleet/server/routes/agent_policy/handlers.ts +++ b/x-pack/plugins/fleet/server/routes/agent_policy/handlers.ts @@ -39,7 +39,7 @@ import type { } from '../../../common'; import { defaultIngestErrorHandler } from '../../errors'; import { createAgentPolicyWithPackages } from '../../services/agent_policy_create'; -import {GetK8sManifestRequestSchema} from "../../types"; +import type { GetK8sManifestRequestSchema } from '../../types'; export const getAgentPoliciesHandler: FleetRequestHandler< undefined, @@ -244,7 +244,7 @@ export const getFullAgentPolicy: FleetRequestHandler< } } else { try { - const fullAgentManifest = await agentPolicyService.getFullAgentManifest("", ""); + const fullAgentManifest = await agentPolicyService.getFullAgentManifest('', ''); if (fullAgentManifest) { const body: GetFullAgentManifestResponse = { item: fullAgentManifest, @@ -262,7 +262,6 @@ export const getFullAgentPolicy: FleetRequestHandler< return defaultIngestErrorHandler({ error, response }); } } - } else { try { const fullAgentPolicy = await agentPolicyService.getFullAgentPolicy( @@ -304,7 +303,7 @@ export const downloadFullAgentPolicy: FleetRequestHandler< const fullAgentConfigMap = await agentPolicyService.getFullAgentConfigMap( soClient, request.params.agentPolicyId, - {standalone: request.query.standalone } + { standalone: request.query.standalone } ); if (fullAgentConfigMap) { const body = fullAgentConfigMap; @@ -319,11 +318,11 @@ export const downloadFullAgentPolicy: FleetRequestHandler< } else { return response.customError({ statusCode: 404, - body: {message: 'Agent config map not found'}, + body: { message: 'Agent config map not found' }, }); } } catch (error) { - return defaultIngestErrorHandler({error, response}); + return defaultIngestErrorHandler({ error, response }); } } } else { @@ -355,10 +354,12 @@ export const downloadFullAgentPolicy: FleetRequestHandler< export const getK8sManifest: FleetRequestHandler< TypeOf - > = async (context, request, response) => { - +> = async (context, request, response) => { try { - const fullAgentManifest = await agentPolicyService.getFullAgentManifest(request.query.fleetServer, request.query.enrolToken); + const fullAgentManifest = await agentPolicyService.getFullAgentManifest( + request.query.fleetServer, + request.query.enrolToken + ); if (fullAgentManifest) { const body: GetFullAgentManifestResponse = { item: fullAgentManifest, @@ -379,10 +380,12 @@ export const getK8sManifest: FleetRequestHandler< export const downloadK8sManifest: FleetRequestHandler< TypeOf - > = async (context, request, response) => { - +> = async (context, request, response) => { try { - const fullAgentManifest = await agentPolicyService.getFullAgentManifest(request.query.fleetServer, request.query.enrolToken); + const fullAgentManifest = await agentPolicyService.getFullAgentManifest( + request.query.fleetServer, + request.query.enrolToken + ); if (fullAgentManifest) { const body = fullAgentManifest; const headers: ResponseHeaders = { @@ -396,10 +399,10 @@ export const downloadK8sManifest: FleetRequestHandler< } else { return response.customError({ statusCode: 404, - body: {message: 'Agent manifest not found'}, + body: { message: 'Agent manifest not found' }, }); } } catch (error) { - return defaultIngestErrorHandler({error, response}); + return defaultIngestErrorHandler({ error, response }); } }; diff --git a/x-pack/plugins/fleet/server/routes/agent_policy/index.ts b/x-pack/plugins/fleet/server/routes/agent_policy/index.ts index 2510939d26d27..66540e019e5a3 100644 --- a/x-pack/plugins/fleet/server/routes/agent_policy/index.ts +++ b/x-pack/plugins/fleet/server/routes/agent_policy/index.ts @@ -18,6 +18,8 @@ import { } from '../../types'; import type { FleetAuthzRouter } from '../security'; +import { K8S_API_ROUTES } from '../../../common'; + import { getAgentPoliciesHandler, getOneAgentPolicyHandler, @@ -26,9 +28,10 @@ import { copyAgentPolicyHandler, deleteAgentPoliciesHandler, getFullAgentPolicy, - downloadFullAgentPolicy, downloadK8sManifest, getK8sManifest, + downloadFullAgentPolicy, + downloadK8sManifest, + getK8sManifest, } from './handlers'; -import {K8S_API_ROUTES} from "../../../common"; export const registerRoutes = (router: FleetAuthzRouter) => { // List - Fleet Server needs access to run setup diff --git a/x-pack/plugins/fleet/server/services/agent_policy.ts b/x-pack/plugins/fleet/server/services/agent_policy.ts index 0fcf18c1300f4..aa1f0d6fb43b5 100644 --- a/x-pack/plugins/fleet/server/services/agent_policy.ts +++ b/x-pack/plugins/fleet/server/services/agent_policy.ts @@ -52,7 +52,10 @@ import type { FullAgentConfigMap } from '../../common/types/models/agent_cm'; import { fullAgentConfigMapToYaml } from '../../common/services/agent_cm_to_yaml'; -import { elasticAgentStandaloneManifest, elasticAgentManagedManifest } from './elastic_agent_manifest'; +import { + elasticAgentStandaloneManifest, + elasticAgentManagedManifest, +} from './elastic_agent_manifest'; import { getPackageInfo } from './epm/packages'; import { getAgentsByKuery } from './agents'; @@ -720,26 +723,23 @@ class AgentPolicyService { } } - public async getFullAgentManifest(fleetServer: string, enrolToken: string): Promise { - const updateManifestVersion = elasticAgentManagedManifest.replace( - 'VERSION', - appContextService.getKibanaVersion() - ); - let updateManifest = updateManifestVersion; - if (fleetServer !== '') { - updateManifest = updateManifest.replace( - 'https://fleet-server:8220', - fleetServer - ); - } + public async getFullAgentManifest( + fleetServer: string, + enrolToken: string + ): Promise { + const updateManifestVersion = elasticAgentManagedManifest.replace( + 'VERSION', + appContextService.getKibanaVersion() + ); + let updateManifest = updateManifestVersion; + if (fleetServer !== '') { + updateManifest = updateManifest.replace('https://fleet-server:8220', fleetServer); + } if (enrolToken !== '') { - updateManifest = updateManifest.replace( - 'token-id', - enrolToken - ); + updateManifest = updateManifest.replace('token-id', enrolToken); } - return updateManifest; + return updateManifest; } public async getFullAgentPolicy( From fd7e3af8a1db2655567ac1eda2ae762c0f6aa940 Mon Sep 17 00:00:00 2001 From: MichaelKatsoulis Date: Tue, 15 Mar 2022 12:49:23 +0200 Subject: [PATCH 03/12] Linting fixes --- .../fleet/public/components/agent_enrollment_flyout/index.tsx | 2 +- .../components/agent_enrollment_flyout/managed_instructions.tsx | 2 ++ .../fleet/public/components/agent_enrollment_flyout/steps.tsx | 2 +- 3 files changed, 4 insertions(+), 2 deletions(-) diff --git a/x-pack/plugins/fleet/public/components/agent_enrollment_flyout/index.tsx b/x-pack/plugins/fleet/public/components/agent_enrollment_flyout/index.tsx index c8f34da996e3a..27746a4ab9ed0 100644 --- a/x-pack/plugins/fleet/public/components/agent_enrollment_flyout/index.tsx +++ b/x-pack/plugins/fleet/public/components/agent_enrollment_flyout/index.tsx @@ -28,7 +28,7 @@ import { useFleetStatus, useAgentEnrollmentFlyoutData, } from '../../hooks'; -import { FLEET_SERVER_PACKAGE, SO_SEARCH_LIMIT } from '../../constants'; +import { FLEET_SERVER_PACKAGE } from '../../constants'; import type { PackagePolicy } from '../../types'; import { Loading } from '..'; diff --git a/x-pack/plugins/fleet/public/components/agent_enrollment_flyout/managed_instructions.tsx b/x-pack/plugins/fleet/public/components/agent_enrollment_flyout/managed_instructions.tsx index 50da51a868a59..1e2141ea3827f 100644 --- a/x-pack/plugins/fleet/public/components/agent_enrollment_flyout/managed_instructions.tsx +++ b/x-pack/plugins/fleet/public/components/agent_enrollment_flyout/managed_instructions.tsx @@ -163,6 +163,8 @@ export const ManagedInstructions = React.memo( settings?.fleet_server_hosts, viewDataStep, enrolToken, + isK8s, + policyId, ]); if (fleetStatus.isReady && settings?.fleet_server_hosts.length === 0) { diff --git a/x-pack/plugins/fleet/public/components/agent_enrollment_flyout/steps.tsx b/x-pack/plugins/fleet/public/components/agent_enrollment_flyout/steps.tsx index 20e31e3f44700..dd267a26285ad 100644 --- a/x-pack/plugins/fleet/public/components/agent_enrollment_flyout/steps.tsx +++ b/x-pack/plugins/fleet/public/components/agent_enrollment_flyout/steps.tsx @@ -72,7 +72,7 @@ export const DownloadStep = (hasFleetServer: boolean, isK8s: string, enrollmentA } } fetchK8sManifest(); - }, [isK8s, enrollmentAPIKey]); + }, [isK8s, enrollmentAPIKey, settings.data?.item.fleet_server_hosts]); const altTitle = isK8s === 'IS_KUBERNETES' From 34eaf42100918271a7956ec7b48142cef4baa5bb Mon Sep 17 00:00:00 2001 From: MichaelKatsoulis Date: Tue, 15 Mar 2022 13:59:16 +0200 Subject: [PATCH 04/12] Types fix --- .../components/fleet_server_on_prem_instructions.tsx | 2 +- .../standalone_instructions.tsx | 2 +- .../components/agent_enrollment_flyout/steps.tsx | 9 +++++---- .../enrollment_instructions/manual/index.tsx | 2 +- .../fleet/server/routes/agent_policy/handlers.ts | 12 ++++++++---- 5 files changed, 16 insertions(+), 11 deletions(-) diff --git a/x-pack/plugins/fleet/public/applications/fleet/sections/agents/agent_requirements_page/components/fleet_server_on_prem_instructions.tsx b/x-pack/plugins/fleet/public/applications/fleet/sections/agents/agent_requirements_page/components/fleet_server_on_prem_instructions.tsx index cf023f122f21a..cb65ea48afd14 100644 --- a/x-pack/plugins/fleet/public/applications/fleet/sections/agents/agent_requirements_page/components/fleet_server_on_prem_instructions.tsx +++ b/x-pack/plugins/fleet/public/applications/fleet/sections/agents/agent_requirements_page/components/fleet_server_on_prem_instructions.tsx @@ -749,7 +749,7 @@ export const OnPremInstructions: React.FC = () => { className="eui-textLeft" steps={[ AgentPolicySelectionStep({ policyId, setPolicyId }), - DownloadStep(true), + DownloadStep(true, '', ''), deploymentModeStep({ deploymentMode, setDeploymentMode }), addFleetServerHostStep({ addFleetServerHost }), ServiceTokenStep({ diff --git a/x-pack/plugins/fleet/public/components/agent_enrollment_flyout/standalone_instructions.tsx b/x-pack/plugins/fleet/public/components/agent_enrollment_flyout/standalone_instructions.tsx index a2bb3c8d31d98..b89c4f4589876 100644 --- a/x-pack/plugins/fleet/public/components/agent_enrollment_flyout/standalone_instructions.tsx +++ b/x-pack/plugins/fleet/public/components/agent_enrollment_flyout/standalone_instructions.tsx @@ -190,7 +190,7 @@ export const StandaloneInstructions = React.memo( refreshAgentPolicies, }) : undefined, - DownloadStep(false, ''), + DownloadStep(false, '', ''), { title: i18n.translate('xpack.fleet.agentEnrollment.stepConfigureAgentTitle', { defaultMessage: 'Configure the agent', diff --git a/x-pack/plugins/fleet/public/components/agent_enrollment_flyout/steps.tsx b/x-pack/plugins/fleet/public/components/agent_enrollment_flyout/steps.tsx index dd267a26285ad..f37f296405903 100644 --- a/x-pack/plugins/fleet/public/components/agent_enrollment_flyout/steps.tsx +++ b/x-pack/plugins/fleet/public/components/agent_enrollment_flyout/steps.tsx @@ -52,7 +52,7 @@ export const DownloadStep = (hasFleetServer: boolean, isK8s: string, enrollmentA } const fleetServerHosts = settings.data?.item.fleet_server_hosts; let host = ''; - if (fleetServerHosts !== undefined) { + if (fleetServerHosts !== undefined && fleetServerHosts.length !== 0) { setFleetServer(fleetServerHosts[0]); host = fleetServerHosts[0]; } @@ -92,7 +92,7 @@ export const DownloadStep = (hasFleetServer: boolean, isK8s: string, enrollmentA isK8s === 'IS_KUBERNETES' ? ( FLEET_URL, FleetTokenVariable: FLEET_ENROLLMENT_TOKEN, @@ -176,8 +176,7 @@ export const DownloadStep = (hasFleetServer: boolean, isK8s: string, enrollmentA <>{linuxUsers} - <>{k8sYaml} - + @@ -188,6 +187,8 @@ export const DownloadStep = (hasFleetServer: boolean, isK8s: string, enrollmentA <>{k8sCopyYaml} + + <>{k8sYaml} ), }; diff --git a/x-pack/plugins/fleet/public/components/enrollment_instructions/manual/index.tsx b/x-pack/plugins/fleet/public/components/enrollment_instructions/manual/index.tsx index 195bc48e02ce3..f42425192b870 100644 --- a/x-pack/plugins/fleet/public/components/enrollment_instructions/manual/index.tsx +++ b/x-pack/plugins/fleet/public/components/enrollment_instructions/manual/index.tsx @@ -7,7 +7,7 @@ import React from 'react'; -import { useStartServices, useKibanaVersion } from '../../../hooks'; +import { useStartServices } from '../../../hooks'; import type { EnrollmentAPIKey } from '../../../types'; import { PlatformSelector } from './platform_selector'; diff --git a/x-pack/plugins/fleet/server/routes/agent_policy/handlers.ts b/x-pack/plugins/fleet/server/routes/agent_policy/handlers.ts index 6f1f7a1457fde..1327a8f088516 100644 --- a/x-pack/plugins/fleet/server/routes/agent_policy/handlers.ts +++ b/x-pack/plugins/fleet/server/routes/agent_policy/handlers.ts @@ -356,9 +356,11 @@ export const getK8sManifest: FleetRequestHandler< TypeOf > = async (context, request, response) => { try { + const fleetServer = request.query?.fleetServer ?? ''; + const token = request.query?.enrolToken ?? ''; const fullAgentManifest = await agentPolicyService.getFullAgentManifest( - request.query.fleetServer, - request.query.enrolToken + fleetServer, + token ); if (fullAgentManifest) { const body: GetFullAgentManifestResponse = { @@ -382,9 +384,11 @@ export const downloadK8sManifest: FleetRequestHandler< TypeOf > = async (context, request, response) => { try { + const fleetServer = request.query.fleetServer ?? ''; + const token = request.query.enrolToken ?? ''; const fullAgentManifest = await agentPolicyService.getFullAgentManifest( - request.query.fleetServer, - request.query.enrolToken + fleetServer, + token ); if (fullAgentManifest) { const body = fullAgentManifest; From ec24f16c054cf739d7fb13ff65af7863bc0c59d9 Mon Sep 17 00:00:00 2001 From: MichaelKatsoulis Date: Tue, 15 Mar 2022 16:04:44 +0200 Subject: [PATCH 05/12] Check types update --- .../fleet/server/routes/agent_policy/handlers.ts | 10 ++-------- 1 file changed, 2 insertions(+), 8 deletions(-) diff --git a/x-pack/plugins/fleet/server/routes/agent_policy/handlers.ts b/x-pack/plugins/fleet/server/routes/agent_policy/handlers.ts index 1327a8f088516..5618326b1534e 100644 --- a/x-pack/plugins/fleet/server/routes/agent_policy/handlers.ts +++ b/x-pack/plugins/fleet/server/routes/agent_policy/handlers.ts @@ -358,10 +358,7 @@ export const getK8sManifest: FleetRequestHandler< try { const fleetServer = request.query?.fleetServer ?? ''; const token = request.query?.enrolToken ?? ''; - const fullAgentManifest = await agentPolicyService.getFullAgentManifest( - fleetServer, - token - ); + const fullAgentManifest = await agentPolicyService.getFullAgentManifest(fleetServer, token); if (fullAgentManifest) { const body: GetFullAgentManifestResponse = { item: fullAgentManifest, @@ -386,10 +383,7 @@ export const downloadK8sManifest: FleetRequestHandler< try { const fleetServer = request.query.fleetServer ?? ''; const token = request.query.enrolToken ?? ''; - const fullAgentManifest = await agentPolicyService.getFullAgentManifest( - fleetServer, - token - ); + const fullAgentManifest = await agentPolicyService.getFullAgentManifest(fleetServer, token); if (fullAgentManifest) { const body = fullAgentManifest; const headers: ResponseHeaders = { From 08bc97705ab56c9fe8ddcb36c6fc1280ef179409 Mon Sep 17 00:00:00 2001 From: MichaelKatsoulis Date: Tue, 15 Mar 2022 17:10:19 +0200 Subject: [PATCH 06/12] Minor fix --- .../fleet/server/routes/agent_policy/handlers.ts | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/x-pack/plugins/fleet/server/routes/agent_policy/handlers.ts b/x-pack/plugins/fleet/server/routes/agent_policy/handlers.ts index 5618326b1534e..afbfeeb45924d 100644 --- a/x-pack/plugins/fleet/server/routes/agent_policy/handlers.ts +++ b/x-pack/plugins/fleet/server/routes/agent_policy/handlers.ts @@ -22,6 +22,7 @@ import type { CopyAgentPolicyRequestSchema, DeleteAgentPolicyRequestSchema, GetFullAgentPolicyRequestSchema, + GetK8sManifestRequestSchema, FleetRequestHandler, } from '../../types'; @@ -39,7 +40,6 @@ import type { } from '../../../common'; import { defaultIngestErrorHandler } from '../../errors'; import { createAgentPolicyWithPackages } from '../../services/agent_policy_create'; -import type { GetK8sManifestRequestSchema } from '../../types'; export const getAgentPoliciesHandler: FleetRequestHandler< undefined, @@ -298,12 +298,11 @@ export const downloadFullAgentPolicy: FleetRequestHandler< } = request; if (request.query.kubernetes === true) { - if (request.query.standalone === true) { try { const fullAgentConfigMap = await agentPolicyService.getFullAgentConfigMap( soClient, request.params.agentPolicyId, - { standalone: request.query.standalone } + { standalone: request.query.standalone === true } ); if (fullAgentConfigMap) { const body = fullAgentConfigMap; @@ -324,7 +323,6 @@ export const downloadFullAgentPolicy: FleetRequestHandler< } catch (error) { return defaultIngestErrorHandler({ error, response }); } - } } else { try { const fullAgentPolicy = await agentPolicyService.getFullAgentPolicy(soClient, agentPolicyId, { @@ -356,8 +354,8 @@ export const getK8sManifest: FleetRequestHandler< TypeOf > = async (context, request, response) => { try { - const fleetServer = request.query?.fleetServer ?? ''; - const token = request.query?.enrolToken ?? ''; + const fleetServer = request.query.fleetServer ?? ''; + const token = request.query.enrolToken ?? ''; const fullAgentManifest = await agentPolicyService.getFullAgentManifest(fleetServer, token); if (fullAgentManifest) { const body: GetFullAgentManifestResponse = { From b2b9a68ccf777880e3ae434b92e64fc66e2fb59e Mon Sep 17 00:00:00 2001 From: MichaelKatsoulis Date: Wed, 16 Mar 2022 16:09:13 +0200 Subject: [PATCH 07/12] Remove leftover --- .../server/routes/agent_policy/handlers.ts | 71 +++++++------------ 1 file changed, 25 insertions(+), 46 deletions(-) diff --git a/x-pack/plugins/fleet/server/routes/agent_policy/handlers.ts b/x-pack/plugins/fleet/server/routes/agent_policy/handlers.ts index afbfeeb45924d..f18cc19f6adf4 100644 --- a/x-pack/plugins/fleet/server/routes/agent_policy/handlers.ts +++ b/x-pack/plugins/fleet/server/routes/agent_policy/handlers.ts @@ -219,12 +219,11 @@ export const getFullAgentPolicy: FleetRequestHandler< const soClient = context.fleet.epm.internalSoClient; if (request.query.kubernetes === true) { - if (request.query.standalone === true) { try { const fullAgentConfigMap = await agentPolicyService.getFullAgentConfigMap( soClient, request.params.agentPolicyId, - { standalone: request.query.standalone } + { standalone: request.query.standalone === true } ); if (fullAgentConfigMap) { const body: GetFullAgentConfigMapResponse = { @@ -242,26 +241,6 @@ export const getFullAgentPolicy: FleetRequestHandler< } catch (error) { return defaultIngestErrorHandler({ error, response }); } - } else { - try { - const fullAgentManifest = await agentPolicyService.getFullAgentManifest('', ''); - if (fullAgentManifest) { - const body: GetFullAgentManifestResponse = { - item: fullAgentManifest, - }; - return response.ok({ - body, - }); - } else { - return response.customError({ - statusCode: 404, - body: { message: 'Agent manifest not found' }, - }); - } - } catch (error) { - return defaultIngestErrorHandler({ error, response }); - } - } } else { try { const fullAgentPolicy = await agentPolicyService.getFullAgentPolicy( @@ -298,31 +277,31 @@ export const downloadFullAgentPolicy: FleetRequestHandler< } = request; if (request.query.kubernetes === true) { - try { - const fullAgentConfigMap = await agentPolicyService.getFullAgentConfigMap( - soClient, - request.params.agentPolicyId, - { standalone: request.query.standalone === true } - ); - if (fullAgentConfigMap) { - const body = fullAgentConfigMap; - const headers: ResponseHeaders = { - 'content-type': 'text/x-yaml', - 'content-disposition': `attachment; filename="elastic-agent-standalone-kubernetes.yaml"`, - }; - return response.ok({ - body, - headers, - }); - } else { - return response.customError({ - statusCode: 404, - body: { message: 'Agent config map not found' }, - }); - } - } catch (error) { - return defaultIngestErrorHandler({ error, response }); + try { + const fullAgentConfigMap = await agentPolicyService.getFullAgentConfigMap( + soClient, + request.params.agentPolicyId, + { standalone: request.query.standalone === true } + ); + if (fullAgentConfigMap) { + const body = fullAgentConfigMap; + const headers: ResponseHeaders = { + 'content-type': 'text/x-yaml', + 'content-disposition': `attachment; filename="elastic-agent-standalone-kubernetes.yaml"`, + }; + return response.ok({ + body, + headers, + }); + } else { + return response.customError({ + statusCode: 404, + body: { message: 'Agent config map not found' }, + }); } + } catch (error) { + return defaultIngestErrorHandler({ error, response }); + } } else { try { const fullAgentPolicy = await agentPolicyService.getFullAgentPolicy(soClient, agentPolicyId, { From 31436d09379efcf4a2a55855e1b6a40faaa371d6 Mon Sep 17 00:00:00 2001 From: MichaelKatsoulis Date: Thu, 17 Mar 2022 11:55:26 +0200 Subject: [PATCH 08/12] Fix CI --- .../fleet_server_on_prem_instructions.tsx | 2 +- .../standalone_instructions.tsx | 2 +- .../agent_enrollment_flyout/steps.tsx | 2 +- .../server/routes/agent_policy/handlers.ts | 44 ++++++++++--------- 4 files changed, 26 insertions(+), 24 deletions(-) diff --git a/x-pack/plugins/fleet/public/applications/fleet/sections/agents/agent_requirements_page/components/fleet_server_on_prem_instructions.tsx b/x-pack/plugins/fleet/public/applications/fleet/sections/agents/agent_requirements_page/components/fleet_server_on_prem_instructions.tsx index cb65ea48afd14..cf023f122f21a 100644 --- a/x-pack/plugins/fleet/public/applications/fleet/sections/agents/agent_requirements_page/components/fleet_server_on_prem_instructions.tsx +++ b/x-pack/plugins/fleet/public/applications/fleet/sections/agents/agent_requirements_page/components/fleet_server_on_prem_instructions.tsx @@ -749,7 +749,7 @@ export const OnPremInstructions: React.FC = () => { className="eui-textLeft" steps={[ AgentPolicySelectionStep({ policyId, setPolicyId }), - DownloadStep(true, '', ''), + DownloadStep(true), deploymentModeStep({ deploymentMode, setDeploymentMode }), addFleetServerHostStep({ addFleetServerHost }), ServiceTokenStep({ diff --git a/x-pack/plugins/fleet/public/components/agent_enrollment_flyout/standalone_instructions.tsx b/x-pack/plugins/fleet/public/components/agent_enrollment_flyout/standalone_instructions.tsx index b89c4f4589876..a56653646be1d 100644 --- a/x-pack/plugins/fleet/public/components/agent_enrollment_flyout/standalone_instructions.tsx +++ b/x-pack/plugins/fleet/public/components/agent_enrollment_flyout/standalone_instructions.tsx @@ -190,7 +190,7 @@ export const StandaloneInstructions = React.memo( refreshAgentPolicies, }) : undefined, - DownloadStep(false, '', ''), + DownloadStep(false), { title: i18n.translate('xpack.fleet.agentEnrollment.stepConfigureAgentTitle', { defaultMessage: 'Configure the agent', diff --git a/x-pack/plugins/fleet/public/components/agent_enrollment_flyout/steps.tsx b/x-pack/plugins/fleet/public/components/agent_enrollment_flyout/steps.tsx index f37f296405903..75d1992b1b32e 100644 --- a/x-pack/plugins/fleet/public/components/agent_enrollment_flyout/steps.tsx +++ b/x-pack/plugins/fleet/public/components/agent_enrollment_flyout/steps.tsx @@ -32,7 +32,7 @@ import { sendGetK8sManifest } from '../../hooks/use_request/k8s'; import { AdvancedAgentAuthenticationSettings } from './advanced_agent_authentication_settings'; import { SelectCreateAgentPolicy } from './agent_policy_select_create'; -export const DownloadStep = (hasFleetServer: boolean, isK8s: string, enrollmentAPIKey: string) => { +export const DownloadStep = (hasFleetServer: boolean, isK8s?: string, enrollmentAPIKey?: string) => { const kibanaVersion = useKibanaVersion(); const core = useStartServices(); const settings = useGetSettings(); diff --git a/x-pack/plugins/fleet/server/routes/agent_policy/handlers.ts b/x-pack/plugins/fleet/server/routes/agent_policy/handlers.ts index f18cc19f6adf4..a98717c9b6fb2 100644 --- a/x-pack/plugins/fleet/server/routes/agent_policy/handlers.ts +++ b/x-pack/plugins/fleet/server/routes/agent_policy/handlers.ts @@ -219,28 +219,28 @@ export const getFullAgentPolicy: FleetRequestHandler< const soClient = context.fleet.epm.internalSoClient; if (request.query.kubernetes === true) { - try { - const fullAgentConfigMap = await agentPolicyService.getFullAgentConfigMap( - soClient, - request.params.agentPolicyId, - { standalone: request.query.standalone === true } - ); - if (fullAgentConfigMap) { - const body: GetFullAgentConfigMapResponse = { - item: fullAgentConfigMap, - }; - return response.ok({ - body, - }); - } else { - return response.customError({ - statusCode: 404, - body: { message: 'Agent config map not found' }, - }); - } - } catch (error) { - return defaultIngestErrorHandler({ error, response }); + try { + const fullAgentConfigMap = await agentPolicyService.getFullAgentConfigMap( + soClient, + request.params.agentPolicyId, + { standalone: request.query.standalone === true } + ); + if (fullAgentConfigMap) { + const body: GetFullAgentConfigMapResponse = { + item: fullAgentConfigMap, + }; + return response.ok({ + body, + }); + } else { + return response.customError({ + statusCode: 404, + body: { message: 'Agent config map not found' }, + }); } + } catch (error) { + return defaultIngestErrorHandler({ error, response }); + } } else { try { const fullAgentPolicy = await agentPolicyService.getFullAgentPolicy( @@ -330,6 +330,7 @@ export const downloadFullAgentPolicy: FleetRequestHandler< }; export const getK8sManifest: FleetRequestHandler< + undefined, TypeOf > = async (context, request, response) => { try { @@ -355,6 +356,7 @@ export const getK8sManifest: FleetRequestHandler< }; export const downloadK8sManifest: FleetRequestHandler< + undefined, TypeOf > = async (context, request, response) => { try { From c04e283e58505dc8a1c1fcb03937cdefbd2c46af Mon Sep 17 00:00:00 2001 From: MichaelKatsoulis Date: Thu, 17 Mar 2022 12:14:04 +0200 Subject: [PATCH 09/12] Eslint fixes --- .../public/components/agent_enrollment_flyout/steps.tsx | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/x-pack/plugins/fleet/public/components/agent_enrollment_flyout/steps.tsx b/x-pack/plugins/fleet/public/components/agent_enrollment_flyout/steps.tsx index 75d1992b1b32e..a4eb8a52b9856 100644 --- a/x-pack/plugins/fleet/public/components/agent_enrollment_flyout/steps.tsx +++ b/x-pack/plugins/fleet/public/components/agent_enrollment_flyout/steps.tsx @@ -32,7 +32,11 @@ import { sendGetK8sManifest } from '../../hooks/use_request/k8s'; import { AdvancedAgentAuthenticationSettings } from './advanced_agent_authentication_settings'; import { SelectCreateAgentPolicy } from './agent_policy_select_create'; -export const DownloadStep = (hasFleetServer: boolean, isK8s?: string, enrollmentAPIKey?: string) => { +export const DownloadStep = ( + hasFleetServer: boolean, + isK8s?: string, + enrollmentAPIKey?: string +) => { const kibanaVersion = useKibanaVersion(); const core = useStartServices(); const settings = useGetSettings(); From d731d0bb297ee9e427eb7d956ef8f201322387e3 Mon Sep 17 00:00:00 2001 From: Nicolas Chaulet Date: Tue, 29 Mar 2022 11:53:51 -0400 Subject: [PATCH 10/12] Fix merge issue --- .../enrollment_instructions/manual/platform_selector.tsx | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/x-pack/plugins/fleet/public/components/enrollment_instructions/manual/platform_selector.tsx b/x-pack/plugins/fleet/public/components/enrollment_instructions/manual/platform_selector.tsx index 76fbd7f712b6f..7fc1c827596e9 100644 --- a/x-pack/plugins/fleet/public/components/enrollment_instructions/manual/platform_selector.tsx +++ b/x-pack/plugins/fleet/public/components/enrollment_instructions/manual/platform_selector.tsx @@ -36,6 +36,8 @@ const CommandCode = styled.pre({ overflow: 'auto', }); +const K8S_COMMAND = `kubectl apply -f elastic-agent-managed-kubernetes.yaml`; + export const PlatformSelector: React.FunctionComponent = ({ linuxCommand, macCommand, @@ -74,9 +76,10 @@ export const PlatformSelector: React.FunctionComponent = ({ )} + {isK8s ? ( - {linuxCommand} + {K8S_COMMAND} ) : ( <> From 5a9df4cf6292b9cd453ef855517ea21b5d0cc167 Mon Sep 17 00:00:00 2001 From: Nicolas Chaulet Date: Tue, 29 Mar 2022 12:28:40 -0400 Subject: [PATCH 11/12] Refacto hooks --- .../agent_enrollment_flyout/hooks.tsx | 66 +++++++++++++++++++ .../agent_enrollment_flyout/index.tsx | 64 +++++------------- .../standalone_instructions.tsx | 36 ++-------- 3 files changed, 87 insertions(+), 79 deletions(-) create mode 100644 x-pack/plugins/fleet/public/components/agent_enrollment_flyout/hooks.tsx diff --git a/x-pack/plugins/fleet/public/components/agent_enrollment_flyout/hooks.tsx b/x-pack/plugins/fleet/public/components/agent_enrollment_flyout/hooks.tsx new file mode 100644 index 0000000000000..d7b48b5a961c2 --- /dev/null +++ b/x-pack/plugins/fleet/public/components/agent_enrollment_flyout/hooks.tsx @@ -0,0 +1,66 @@ +/* + * 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 { useState, useEffect } from 'react'; +import { i18n } from '@kbn/i18n'; + +import type { PackagePolicy, AgentPolicy } from '../../types'; +import { sendGetOneAgentPolicy, useStartServices } from '../../hooks'; +import { FLEET_KUBERNETES_PACKAGE } from '../../../common'; + +export function useAgentPolicyWithPackagePolicies(policyId?: string) { + const [agentPolicyWithPackagePolicies, setAgentPolicy] = useState(null); + const core = useStartServices(); + const { notifications } = core; + + useEffect(() => { + async function loadPolicy(policyIdToLoad?: string) { + if (!policyIdToLoad) { + return; + } + try { + const agentPolicyRequest = await sendGetOneAgentPolicy(policyIdToLoad); + + setAgentPolicy(agentPolicyRequest.data ? agentPolicyRequest.data.item : null); + } catch (err) { + notifications.toasts.addError(err, { + title: i18n.translate('xpack.fleet.agentEnrollment.loadPolicyErrorMessage', { + defaultMessage: 'An error happened while loading the policy', + }), + }); + } + } + + loadPolicy(policyId); + }, [policyId, notifications.toasts]); + + return { agentPolicyWithPackagePolicies }; +} + +export function useIsK8sPolicy(agentPolicy?: AgentPolicy) { + const [isK8s, setIsK8s] = useState<'IS_LOADING' | 'IS_KUBERNETES' | 'IS_NOT_KUBERNETES'>( + 'IS_LOADING' + ); + useEffect(() => { + async function checkifK8s() { + if (!agentPolicy) { + setIsK8s('IS_LOADING'); + return; + } + + setIsK8s( + (agentPolicy.package_policies as PackagePolicy[]).some(isK8sPackage) + ? 'IS_KUBERNETES' + : 'IS_NOT_KUBERNETES' + ); + } + checkifK8s(); + }, [agentPolicy]); + + return { isK8s }; +} + +const isK8sPackage = (pkg: PackagePolicy) => pkg.package?.name === FLEET_KUBERNETES_PACKAGE; diff --git a/x-pack/plugins/fleet/public/components/agent_enrollment_flyout/index.tsx b/x-pack/plugins/fleet/public/components/agent_enrollment_flyout/index.tsx index 27746a4ab9ed0..ed4cc15aec196 100644 --- a/x-pack/plugins/fleet/public/components/agent_enrollment_flyout/index.tsx +++ b/x-pack/plugins/fleet/public/components/agent_enrollment_flyout/index.tsx @@ -22,23 +22,17 @@ import { } from '@elastic/eui'; import { FormattedMessage } from '@kbn/i18n-react'; -import { - useGetSettings, - sendGetOneAgentPolicy, - useFleetStatus, - useAgentEnrollmentFlyoutData, -} from '../../hooks'; +import { useGetSettings, useFleetStatus, useAgentEnrollmentFlyoutData } from '../../hooks'; import { FLEET_SERVER_PACKAGE } from '../../constants'; import type { PackagePolicy } from '../../types'; import { Loading } from '..'; -import { FLEET_KUBERNETES_PACKAGE } from '../../../common'; - import { ManagedInstructions } from './managed_instructions'; import { StandaloneInstructions } from './standalone_instructions'; import { MissingFleetServerHostCallout } from './missing_fleet_server_host_callout'; import type { BaseProps } from './types'; +import { useIsK8sPolicy, useAgentPolicyWithPackagePolicies } from './hooks'; type FlyoutMode = 'managed' | 'standalone'; @@ -74,52 +68,24 @@ export const AgentEnrollmentFlyout: React.FunctionComponent = ({ isLoadingAgentPolicies, refreshAgentPolicies, } = useAgentEnrollmentFlyoutData(); - + const { agentPolicyWithPackagePolicies } = useAgentPolicyWithPackagePolicies(policyId); useEffect(() => { - async function checkPolicyIsFleetServer() { - if (policyId && setIsFleetServerPolicySelected) { - const agentPolicyRequest = await sendGetOneAgentPolicy(policyId); - if ( - agentPolicyRequest.data?.item && - (agentPolicyRequest.data.item.package_policies as PackagePolicy[]).some( - (packagePolicy) => packagePolicy.package?.name === FLEET_SERVER_PACKAGE - ) - ) { - setIsFleetServerPolicySelected(true); - } else { - setIsFleetServerPolicySelected(false); - } + if (agentPolicyWithPackagePolicies && setIsFleetServerPolicySelected) { + if ( + (agentPolicyWithPackagePolicies.package_policies as PackagePolicy[]).some( + (packagePolicy) => packagePolicy.package?.name === FLEET_SERVER_PACKAGE + ) + ) { + setIsFleetServerPolicySelected(true); + } else { + setIsFleetServerPolicySelected(false); } } + }, [agentPolicyWithPackagePolicies]); - checkPolicyIsFleetServer(); - }, [policyId]); - - const [isK8s, setIsK8s] = useState<'IS_LOADING' | 'IS_KUBERNETES' | 'IS_NOT_KUBERNETES'>( - 'IS_LOADING' + const { isK8s } = useIsK8sPolicy( + agentPolicyWithPackagePolicies ? agentPolicyWithPackagePolicies : undefined ); - useEffect(() => { - async function checkifK8s() { - if (!policyId) { - setIsK8s('IS_LOADING'); - return; - } - const agentPolicyRequest = await sendGetOneAgentPolicy(policyId); - const agentPol = agentPolicyRequest.data ? agentPolicyRequest.data.item : null; - - if (!agentPol) { - setIsK8s('IS_NOT_KUBERNETES'); - return; - } - const k8s = (pkg: PackagePolicy) => pkg.package?.name === FLEET_KUBERNETES_PACKAGE; - setIsK8s( - (agentPol.package_policies as PackagePolicy[]).some(k8s) - ? 'IS_KUBERNETES' - : 'IS_NOT_KUBERNETES' - ); - } - checkifK8s(); - }, [policyId]); const isLoadingInitialRequest = settings.isLoading && settings.isInitialRequest; diff --git a/x-pack/plugins/fleet/public/components/agent_enrollment_flyout/standalone_instructions.tsx b/x-pack/plugins/fleet/public/components/agent_enrollment_flyout/standalone_instructions.tsx index 4dc9a6c041a7e..83bc6206fec1a 100644 --- a/x-pack/plugins/fleet/public/components/agent_enrollment_flyout/standalone_instructions.tsx +++ b/x-pack/plugins/fleet/public/components/agent_enrollment_flyout/standalone_instructions.tsx @@ -27,19 +27,15 @@ import { useStartServices, useLink, sendGetOneAgentPolicyFull, - sendGetOneAgentPolicy, useKibanaVersion, } from '../../hooks'; import { fullAgentPolicyToYaml, agentPolicyRouteService } from '../../services'; -import type { PackagePolicy } from '../../../common'; - -import { FLEET_KUBERNETES_PACKAGE } from '../../../common'; - import { PlatformSelector } from '../enrollment_instructions/manual/platform_selector'; import { DownloadStep, AgentPolicySelectionStep } from './steps'; import type { InstructionProps } from './types'; +import { useIsK8sPolicy, useAgentPolicyWithPackagePolicies } from './hooks'; export const StandaloneInstructions = React.memo( ({ agentPolicy, agentPolicies, refreshAgentPolicies }) => { @@ -49,12 +45,14 @@ export const StandaloneInstructions = React.memo( const [selectedPolicyId, setSelectedPolicyId] = useState(agentPolicy?.id); const [fullAgentPolicy, setFullAgentPolicy] = useState(); - const [isK8s, setIsK8s] = useState<'IS_LOADING' | 'IS_KUBERNETES' | 'IS_NOT_KUBERNETES'>( - 'IS_LOADING' - ); const [yaml, setYaml] = useState(''); const kibanaVersion = useKibanaVersion(); + const { agentPolicyWithPackagePolicies } = useAgentPolicyWithPackagePolicies(selectedPolicyId); + const { isK8s } = useIsK8sPolicy( + agentPolicyWithPackagePolicies ? agentPolicyWithPackagePolicies : undefined + ); + const KUBERNETES_RUN_INSTRUCTIONS = 'kubectl apply -f elastic-agent-standalone-kubernetes.yaml'; const STANDALONE_RUN_INSTRUCTIONS_LINUX = `curl -L -O https://artifacts.elastic.co/downloads/beats/elastic-agent/elastic-agent-${kibanaVersion}-linux-x86_64.tar.gz @@ -84,28 +82,6 @@ sudo rpm -vi elastic-agent-${kibanaVersion}-x86_64.rpm \nsudo systemctl enable e const { docLinks } = useStartServices(); - useEffect(() => { - async function checkifK8s() { - if (!selectedPolicyId) { - return; - } - const agentPolicyRequest = await sendGetOneAgentPolicy(selectedPolicyId); - const agentPol = agentPolicyRequest.data ? agentPolicyRequest.data.item : null; - - if (!agentPol) { - setIsK8s('IS_NOT_KUBERNETES'); - return; - } - const k8s = (pkg: PackagePolicy) => pkg.package?.name === FLEET_KUBERNETES_PACKAGE; - setIsK8s( - (agentPol.package_policies as PackagePolicy[]).some(k8s) - ? 'IS_KUBERNETES' - : 'IS_NOT_KUBERNETES' - ); - } - checkifK8s(); - }, [selectedPolicyId, notifications.toasts]); - useEffect(() => { async function fetchFullPolicy() { try { From addee65a93f1dc593400e00278c474ba6eaefb06 Mon Sep 17 00:00:00 2001 From: Nicolas Chaulet Date: Tue, 29 Mar 2022 14:22:48 -0400 Subject: [PATCH 12/12] Handle error --- .../public/components/agent_enrollment_flyout/steps.tsx | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/x-pack/plugins/fleet/public/components/agent_enrollment_flyout/steps.tsx b/x-pack/plugins/fleet/public/components/agent_enrollment_flyout/steps.tsx index a4eb8a52b9856..54c449f74cc60 100644 --- a/x-pack/plugins/fleet/public/components/agent_enrollment_flyout/steps.tsx +++ b/x-pack/plugins/fleet/public/components/agent_enrollment_flyout/steps.tsx @@ -45,6 +45,7 @@ export const DownloadStep = ( `${semverMajor(kibanaVersion)}-${semverMinor(kibanaVersion)}-${semverPatch(kibanaVersion)}`, [kibanaVersion] ); + const { notifications } = core; const [yaml, setYaml] = useState(); const [fleetServer, setFleetServer] = useState(); @@ -72,11 +73,15 @@ export const DownloadStep = ( setYaml(res.data.item); } catch (error) { - throw new Error('No data while fetching agent manifest'); + notifications.toasts.addError(error, { + title: i18n.translate('xpack.fleet.agentEnrollment.loadk8sManifestErrorTitle', { + defaultMessage: 'Error while fetching agent manifest', + }), + }); } } fetchK8sManifest(); - }, [isK8s, enrollmentAPIKey, settings.data?.item.fleet_server_hosts]); + }, [isK8s, notifications.toasts, enrollmentAPIKey, settings.data?.item.fleet_server_hosts]); const altTitle = isK8s === 'IS_KUBERNETES'