From 87cf1306a5b0cadc00f1ef890075cc986624824a Mon Sep 17 00:00:00 2001 From: John Schulz Date: Mon, 21 Sep 2020 19:41:45 -0400 Subject: [PATCH] Remove any 7.x references to *_policy vs *_config --- .../server/routes/agent_config/handlers.ts | 57 ++-- .../server/routes/agent_policy/handlers.ts | 278 ------------------ .../server/routes/package_config/handlers.ts | 22 +- .../server/routes/package_policy/handlers.ts | 181 ------------ .../apis/agent_policy/agent_policy.ts | 115 -------- 5 files changed, 24 insertions(+), 629 deletions(-) delete mode 100644 x-pack/plugins/ingest_manager/server/routes/agent_policy/handlers.ts delete mode 100644 x-pack/plugins/ingest_manager/server/routes/package_policy/handlers.ts delete mode 100644 x-pack/test/ingest_manager_api_integration/apis/agent_policy/agent_policy.ts diff --git a/x-pack/plugins/ingest_manager/server/routes/agent_config/handlers.ts b/x-pack/plugins/ingest_manager/server/routes/agent_config/handlers.ts index 4e4653ec023ce1..a1faf8c53226a7 100644 --- a/x-pack/plugins/ingest_manager/server/routes/agent_config/handlers.ts +++ b/x-pack/plugins/ingest_manager/server/routes/agent_config/handlers.ts @@ -32,6 +32,7 @@ import { DeleteAgentConfigResponse, GetFullAgentConfigResponse, } from '../../../common'; +import { defaultIngestErrorHandler } from '../../errors'; export const getAgentConfigsHandler: RequestHandler< undefined, @@ -65,11 +66,8 @@ export const getAgentConfigsHandler: RequestHandler< ); return response.ok({ body }); - } catch (e) { - return response.customError({ - statusCode: 500, - body: { message: e.message }, - }); + } catch (error) { + return defaultIngestErrorHandler({ error, response }); } }; @@ -93,11 +91,8 @@ export const getOneAgentConfigHandler: RequestHandler -> = async (context, request, response) => { - const soClient = context.core.savedObjects.client; - const { full: withPackagePolicies = false, ...restOfQuery } = request.query; - try { - const { items, total, page, perPage } = await agentPolicyService.list(soClient, { - withPackagePolicies, - ...restOfQuery, - }); - const body: GetAgentPoliciesResponse = { - items, - total, - page, - perPage, - }; - - await bluebird.map( - items, - (agentPolicy: GetAgentPoliciesResponseItem) => - listAgents(soClient, { - showInactive: false, - perPage: 0, - page: 1, - kuery: `${AGENT_SAVED_OBJECT_TYPE}.policy_id:${agentPolicy.id}`, - }).then(({ total: agentTotal }) => (agentPolicy.agents = agentTotal)), - { concurrency: 10 } - ); - - return response.ok({ body }); - } catch (error) { - return defaultIngestErrorHandler({ error, response }); - } -}; - -export const getOneAgentPolicyHandler: RequestHandler> = async (context, request, response) => { - const soClient = context.core.savedObjects.client; - try { - const agentPolicy = await agentPolicyService.get(soClient, request.params.agentPolicyId); - if (agentPolicy) { - const body: GetOneAgentPolicyResponse = { - item: agentPolicy, - }; - return response.ok({ - body, - }); - } else { - return response.customError({ - statusCode: 404, - body: { message: 'Agent policy not found' }, - }); - } - } catch (error) { - return defaultIngestErrorHandler({ error, response }); - } -}; - -export const createAgentPolicyHandler: RequestHandler< - undefined, - TypeOf, - TypeOf -> = async (context, request, response) => { - const soClient = context.core.savedObjects.client; - const callCluster = context.core.elasticsearch.legacy.client.callAsCurrentUser; - const user = (await appContextService.getSecurity()?.authc.getCurrentUser(request)) || undefined; - const withSysMonitoring = request.query.sys_monitoring ?? false; - try { - // eslint-disable-next-line prefer-const - let [agentPolicy, newSysPackagePolicy] = await Promise.all< - AgentPolicy, - NewPackagePolicy | undefined - >([ - agentPolicyService.create(soClient, request.body, { - user, - }), - // If needed, retrieve System package information and build a new package policy for the system package - // NOTE: we ignore failures in attempting to create package policy, since agent policy might have been created - // successfully - withSysMonitoring - ? packagePolicyService - .buildPackagePolicyFromPackage(soClient, DefaultPackages.system) - .catch(() => undefined) - : undefined, - ]); - - // Create the system monitoring package policy and add it to agent policy. - if (withSysMonitoring && newSysPackagePolicy !== undefined && agentPolicy !== undefined) { - newSysPackagePolicy.policy_id = agentPolicy.id; - newSysPackagePolicy.namespace = agentPolicy.namespace; - await packagePolicyService.create(soClient, callCluster, newSysPackagePolicy, { - user, - bumpRevision: false, - }); - } - - const body: CreateAgentPolicyResponse = { - item: agentPolicy, - }; - - return response.ok({ - body, - }); - } catch (error) { - return defaultIngestErrorHandler({ error, response }); - } -}; - -export const updateAgentPolicyHandler: RequestHandler< - TypeOf, - unknown, - TypeOf -> = async (context, request, response) => { - const soClient = context.core.savedObjects.client; - const user = await appContextService.getSecurity()?.authc.getCurrentUser(request); - try { - const agentPolicy = await agentPolicyService.update( - soClient, - request.params.agentPolicyId, - request.body, - { - user: user || undefined, - } - ); - const body: UpdateAgentPolicyResponse = { item: agentPolicy }; - return response.ok({ - body, - }); - } catch (error) { - return defaultIngestErrorHandler({ error, response }); - } -}; - -export const copyAgentPolicyHandler: RequestHandler< - TypeOf, - unknown, - TypeOf -> = async (context, request, response) => { - const soClient = context.core.savedObjects.client; - const user = await appContextService.getSecurity()?.authc.getCurrentUser(request); - try { - const agentPolicy = await agentPolicyService.copy( - soClient, - request.params.agentPolicyId, - request.body, - { - user: user || undefined, - } - ); - const body: CopyAgentPolicyResponse = { item: agentPolicy }; - return response.ok({ - body, - }); - } catch (error) { - return defaultIngestErrorHandler({ error, response }); - } -}; - -export const deleteAgentPoliciesHandler: RequestHandler< - unknown, - unknown, - TypeOf -> = async (context, request, response) => { - const soClient = context.core.savedObjects.client; - try { - const body: DeleteAgentPolicyResponse = await agentPolicyService.delete( - soClient, - request.body.agentPolicyId - ); - return response.ok({ - body, - }); - } catch (error) { - return defaultIngestErrorHandler({ error, response }); - } -}; - -export const getFullAgentPolicy: RequestHandler< - TypeOf, - TypeOf -> = async (context, request, response) => { - const soClient = context.core.savedObjects.client; - - try { - const fullAgentPolicy = await agentPolicyService.getFullAgentPolicy( - soClient, - request.params.agentPolicyId, - { standalone: request.query.standalone === true } - ); - if (fullAgentPolicy) { - const body: GetFullAgentPolicyResponse = { - item: fullAgentPolicy, - }; - return response.ok({ - body, - }); - } else { - return response.customError({ - statusCode: 404, - body: { message: 'Agent policy not found' }, - }); - } - } catch (error) { - return defaultIngestErrorHandler({ error, response }); - } -}; - -export const downloadFullAgentPolicy: RequestHandler< - TypeOf, - TypeOf -> = async (context, request, response) => { - const soClient = context.core.savedObjects.client; - const { - params: { agentPolicyId }, - } = request; - - try { - const fullAgentPolicy = await agentPolicyService.getFullAgentPolicy(soClient, agentPolicyId, { - standalone: request.query.standalone === true, - }); - if (fullAgentPolicy) { - const body = fullAgentPolicyToYaml(fullAgentPolicy); - const headers: ResponseHeaders = { - 'content-type': 'text/x-yaml', - 'content-disposition': `attachment; filename="elastic-agent.yml"`, - }; - return response.ok({ - body, - headers, - }); - } else { - return response.customError({ - statusCode: 404, - body: { message: 'Agent policy not found' }, - }); - } - } catch (error) { - return defaultIngestErrorHandler({ error, response }); - } -}; diff --git a/x-pack/plugins/ingest_manager/server/routes/package_config/handlers.ts b/x-pack/plugins/ingest_manager/server/routes/package_config/handlers.ts index 6b0c2fe9c2ff7c..d8d6fa68fedac4 100644 --- a/x-pack/plugins/ingest_manager/server/routes/package_config/handlers.ts +++ b/x-pack/plugins/ingest_manager/server/routes/package_config/handlers.ts @@ -16,6 +16,7 @@ import { DeletePackageConfigsRequestSchema, NewPackageConfig, } from '../../types'; +import { defaultIngestErrorHandler } from '../../errors'; import { CreatePackageConfigResponse, DeletePackageConfigsResponse } from '../../../common'; export const getPackageConfigsHandler: RequestHandler< @@ -37,11 +38,8 @@ export const getPackageConfigsHandler: RequestHandler< success: true, }, }); - } catch (e) { - return response.customError({ - statusCode: 500, - body: { message: e.message }, - }); + } catch (error) { + return defaultIngestErrorHandler({ error, response }); } }; @@ -64,11 +62,8 @@ export const getOnePackageConfigHandler: RequestHandler -> = async (context, request, response) => { - const soClient = context.core.savedObjects.client; - try { - const { items, total, page, perPage } = await packagePolicyService.list( - soClient, - request.query - ); - return response.ok({ - body: { - items, - total, - page, - perPage, - }, - }); - } catch (error) { - return defaultIngestErrorHandler({ error, response }); - } -}; - -export const getOnePackagePolicyHandler: RequestHandler> = async (context, request, response) => { - const soClient = context.core.savedObjects.client; - const { packagePolicyId } = request.params; - const notFoundResponse = () => - response.notFound({ body: { message: `Package policy ${packagePolicyId} not found` } }); - - try { - const packagePolicy = await packagePolicyService.get(soClient, packagePolicyId); - if (packagePolicy) { - return response.ok({ - body: { - item: packagePolicy, - }, - }); - } else { - return notFoundResponse(); - } - } catch (error) { - if (SavedObjectsErrorHelpers.isNotFoundError(error)) { - return notFoundResponse(); - } else { - return defaultIngestErrorHandler({ error, response }); - } - } -}; - -export const createPackagePolicyHandler: RequestHandler< - undefined, - undefined, - TypeOf -> = async (context, request, response) => { - const soClient = context.core.savedObjects.client; - const callCluster = context.core.elasticsearch.legacy.client.callAsCurrentUser; - const user = (await appContextService.getSecurity()?.authc.getCurrentUser(request)) || undefined; - const logger = appContextService.getLogger(); - let newData = { ...request.body }; - try { - // If we have external callbacks, then process those now before creating the actual package policy - const externalCallbacks = appContextService.getExternalCallbacks('packagePolicyCreate'); - if (externalCallbacks && externalCallbacks.size > 0) { - let updatedNewData: NewPackagePolicy = newData; - - for (const callback of externalCallbacks) { - try { - // ensure that the returned value by the callback passes schema validation - updatedNewData = CreatePackagePolicyRequestSchema.body.validate( - await callback(updatedNewData) - ); - } catch (error) { - // Log the error, but keep going and process the other callbacks - logger.error( - 'An external registered [packagePolicyCreate] callback failed when executed' - ); - logger.error(error); - } - } - - newData = updatedNewData; - } - - // Create package policy - const packagePolicy = await packagePolicyService.create(soClient, callCluster, newData, { - user, - }); - const body: CreatePackagePolicyResponse = { item: packagePolicy }; - return response.ok({ - body, - }); - } catch (error) { - return defaultIngestErrorHandler({ error, response }); - } -}; - -export const updatePackagePolicyHandler: RequestHandler< - TypeOf, - unknown, - TypeOf -> = async (context, request, response) => { - const soClient = context.core.savedObjects.client; - const user = (await appContextService.getSecurity()?.authc.getCurrentUser(request)) || undefined; - try { - const packagePolicy = await packagePolicyService.get(soClient, request.params.packagePolicyId); - - if (!packagePolicy) { - throw Boom.notFound('Package policy not found'); - } - - const newData = { ...request.body }; - const pkg = newData.package || packagePolicy.package; - const inputs = newData.inputs || packagePolicy.inputs; - if (pkg && (newData.inputs || newData.package)) { - const pkgInfo = await getPackageInfo({ - savedObjectsClient: soClient, - pkgName: pkg.name, - pkgVersion: pkg.version, - }); - newData.inputs = (await packagePolicyService.assignPackageStream(pkgInfo, inputs)) as TypeOf< - typeof CreatePackagePolicyRequestSchema.body - >['inputs']; - } - - const updatedPackagePolicy = await packagePolicyService.update( - soClient, - request.params.packagePolicyId, - newData, - { user } - ); - return response.ok({ - body: { item: updatedPackagePolicy }, - }); - } catch (error) { - return defaultIngestErrorHandler({ error, response }); - } -}; - -export const deletePackagePolicyHandler: RequestHandler< - unknown, - unknown, - TypeOf -> = async (context, request, response) => { - const soClient = context.core.savedObjects.client; - const user = (await appContextService.getSecurity()?.authc.getCurrentUser(request)) || undefined; - try { - const body: DeletePackagePoliciesResponse = await packagePolicyService.delete( - soClient, - request.body.packagePolicyIds, - { user } - ); - return response.ok({ - body, - }); - } catch (error) { - return defaultIngestErrorHandler({ error, response }); - } -}; diff --git a/x-pack/test/ingest_manager_api_integration/apis/agent_policy/agent_policy.ts b/x-pack/test/ingest_manager_api_integration/apis/agent_policy/agent_policy.ts deleted file mode 100644 index 71e2bbc4e4c0a0..00000000000000 --- a/x-pack/test/ingest_manager_api_integration/apis/agent_policy/agent_policy.ts +++ /dev/null @@ -1,115 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -import expect from '@kbn/expect'; -import { FtrProviderContext } from '../../../api_integration/ftr_provider_context'; - -export default function ({ getService }: FtrProviderContext) { - const supertest = getService('supertest'); - const esArchiver = getService('esArchiver'); - - describe('ingest_manager_agent_policies', () => { - describe('POST /api/ingest_manager/agent_policies', () => { - it('should work with valid values', async () => { - await supertest - .post(`/api/ingest_manager/agent_policies`) - .set('kbn-xsrf', 'xxxx') - .send({ - name: 'TEST', - namespace: 'default', - }) - .expect(200); - }); - - it('should return a 400 with an empty namespace', async () => { - await supertest - .post(`/api/ingest_manager/agent_policies`) - .set('kbn-xsrf', 'xxxx') - .send({ - name: 'TEST', - namespace: '', - }) - .expect(400); - }); - - it('should return a 400 with an invalid namespace', async () => { - await supertest - .post(`/api/ingest_manager/agent_policies`) - .set('kbn-xsrf', 'xxxx') - .send({ - name: 'TEST', - namespace: 'InvalidNamespace', - }) - .expect(400); - }); - }); - - describe('POST /api/ingest_manager/agent_policies/{agentPolicyId}/copy', () => { - before(async () => { - await esArchiver.loadIfNeeded('fleet/agents'); - }); - after(async () => { - await esArchiver.unload('fleet/agents'); - }); - - const TEST_POLICY_ID = 'policy1'; - - it('should work with valid values', async () => { - const { - body: { item }, - } = await supertest - .post(`/api/ingest_manager/agent_policies/${TEST_POLICY_ID}/copy`) - .set('kbn-xsrf', 'xxxx') - .send({ - name: 'Copied policy', - description: 'Test', - }) - .expect(200); - // eslint-disable-next-line @typescript-eslint/naming-convention - const { id, updated_at, ...newPolicy } = item; - - expect(newPolicy).to.eql({ - name: 'Copied policy', - description: 'Test', - namespace: 'default', - monitoring_enabled: ['logs', 'metrics'], - revision: 1, - updated_by: 'elastic', - package_policies: [], - }); - }); - - it('should return a 404 with invalid source policy', async () => { - await supertest - .post(`/api/ingest_manager/agent_policies/INVALID_POLICY_ID/copy`) - .set('kbn-xsrf', 'xxxx') - .send({ - name: 'Copied policy', - description: '', - }) - .expect(404); - }); - - it('should return a 400 with invalid payload', async () => { - await supertest - .post(`/api/ingest_manager/agent_policies/${TEST_POLICY_ID}/copy`) - .set('kbn-xsrf', 'xxxx') - .send({}) - .expect(400); - }); - - it('should return a 400 with invalid name', async () => { - await supertest - .post(`/api/ingest_manager/agent_policies/${TEST_POLICY_ID}/copy`) - .set('kbn-xsrf', 'xxxx') - .send({ - name: '', - }) - .expect(400); - }); - }); - }); -}