-
Notifications
You must be signed in to change notification settings - Fork 8.3k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[Fleet] flag package policy SO to trigger agent policy bump #200536
Changes from 6 commits
c46cff2
0985863
7cd7cf5
33e2a37
65eee0f
600590a
58c89a9
409bbf7
32dc285
92a2a62
6704eb9
3409529
2878cbd
eeb2c54
9daf046
2681c7c
26e46d4
4ce6b39
d8c9711
e031878
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,51 @@ | ||
/* | ||
* 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 { loggingSystemMock } from '@kbn/core/server/mocks'; | ||
|
||
import { packagePolicyService } from '../package_policy'; | ||
import type { PackagePolicy } from '../../types'; | ||
|
||
import { _updatePackagePoliciesThatNeedBump } from './bump_agent_policies_task'; | ||
|
||
jest.mock('../app_context'); | ||
jest.mock('../agent_policy'); | ||
jest.mock('../package_policy'); | ||
|
||
const mockedPackagePolicyService = jest.mocked(packagePolicyService); | ||
|
||
describe('_updatePackagePoliciesThatNeedBump', () => { | ||
beforeEach(() => { | ||
jest.clearAllMocks(); | ||
mockedPackagePolicyService.list.mockResolvedValueOnce({ | ||
total: 1, | ||
items: [ | ||
{ | ||
id: 'packagePolicy1', | ||
} as PackagePolicy, | ||
], | ||
page: 1, | ||
perPage: 100, | ||
}); | ||
mockedPackagePolicyService.list.mockResolvedValueOnce({ | ||
total: 0, | ||
items: [], | ||
page: 1, | ||
perPage: 100, | ||
}); | ||
}); | ||
|
||
it('should update package policy if bump agent policy revision needed', async () => { | ||
const logger = loggingSystemMock.createLogger(); | ||
|
||
await _updatePackagePoliciesThatNeedBump(logger, false); | ||
|
||
expect(mockedPackagePolicyService.bulkUpdate).toHaveBeenCalledWith(undefined, undefined, [ | ||
{ bump_agent_policy_revision: false, id: 'packagePolicy1' }, | ||
]); | ||
}); | ||
}); |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,138 @@ | ||
/* | ||
* 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 type { Logger } from '@kbn/core/server'; | ||
import type { | ||
ConcreteTaskInstance, | ||
TaskManagerSetupContract, | ||
TaskManagerStartContract, | ||
} from '@kbn/task-manager-plugin/server'; | ||
import { v4 as uuidv4 } from 'uuid'; | ||
import { uniq } from 'lodash'; | ||
|
||
import { DEFAULT_SPACE_ID } from '@kbn/spaces-plugin/common'; | ||
|
||
import { agentPolicyService, appContextService } from '..'; | ||
import { runWithCache } from '../epm/packages/cache'; | ||
import { getPackagePolicySavedObjectType } from '../package_policy'; | ||
import { mapPackagePolicySavedObjectToPackagePolicy } from '../package_policies'; | ||
import type { PackagePolicy, PackagePolicySOAttributes } from '../../types'; | ||
import { normalizeKuery } from '../saved_object'; | ||
import { SO_SEARCH_LIMIT } from '../../constants'; | ||
|
||
const TASK_TYPE = 'fleet:bump_agent_policies'; | ||
|
||
export function registerBumpAgentPoliciesTask(taskManagerSetup: TaskManagerSetupContract) { | ||
taskManagerSetup.registerTaskDefinitions({ | ||
[TASK_TYPE]: { | ||
title: 'Fleet Bump policies', | ||
timeout: '5m', | ||
maxAttempts: 3, | ||
createTaskRunner: ({ taskInstance }: { taskInstance: ConcreteTaskInstance }) => { | ||
let cancelled = false; | ||
return { | ||
async run() { | ||
if (cancelled) { | ||
throw new Error('Task has been cancelled'); | ||
} | ||
|
||
await runWithCache(async () => { | ||
await _updatePackagePoliciesThatNeedBump(appContextService.getLogger(), cancelled); | ||
}); | ||
}, | ||
async cancel() { | ||
cancelled = true; | ||
}, | ||
}; | ||
}, | ||
}, | ||
}); | ||
} | ||
|
||
async function getPackagePoliciesToBump(savedObjectType: string) { | ||
const result = await appContextService | ||
.getInternalUserSOClientWithoutSpaceExtension() | ||
.find<PackagePolicySOAttributes>({ | ||
type: savedObjectType, | ||
filter: normalizeKuery(savedObjectType, `${savedObjectType}.bump_agent_policy_revision:true`), | ||
perPage: SO_SEARCH_LIMIT, | ||
namespaces: ['*'], | ||
fields: ['id', 'namespaces', 'policy_ids'], | ||
}); | ||
return { | ||
total: result.total, | ||
items: result.saved_objects.map((so) => | ||
mapPackagePolicySavedObjectToPackagePolicy(so, so.namespaces) | ||
), | ||
}; | ||
} | ||
|
||
export async function _updatePackagePoliciesThatNeedBump(logger: Logger, cancelled: boolean) { | ||
const savedObjectType = await getPackagePolicySavedObjectType(); | ||
const packagePoliciesToBump = await getPackagePoliciesToBump(savedObjectType); | ||
|
||
logger.info( | ||
`Found ${packagePoliciesToBump.total} package policies that need agent policy revision bump` | ||
); | ||
|
||
const packagePoliciesIndexedBySpace = packagePoliciesToBump.items.reduce((acc, policy) => { | ||
const spaceId = policy.spaceIds?.[0] ?? DEFAULT_SPACE_ID; | ||
if (!acc[spaceId]) { | ||
acc[spaceId] = []; | ||
} | ||
|
||
acc[spaceId].push(policy); | ||
|
||
return acc; | ||
}, {} as { [k: string]: PackagePolicy[] }); | ||
|
||
const start = Date.now(); | ||
|
||
for (const [spaceId, packagePolicies] of Object.entries(packagePoliciesIndexedBySpace)) { | ||
if (cancelled) { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Here is where you'd check |
||
throw new Error('Task has been cancelled'); | ||
} | ||
|
||
const soClient = appContextService.getInternalUserSOClientForSpaceId(spaceId); | ||
const esClient = appContextService.getInternalUserESClient(); | ||
|
||
await soClient.bulkUpdate<PackagePolicySOAttributes>( | ||
packagePolicies.map((item) => ({ | ||
type: savedObjectType, | ||
id: item.id, | ||
attributes: { | ||
bump_agent_policy_revision: false, | ||
}, | ||
})) | ||
); | ||
|
||
const updatedCount = packagePolicies.length; | ||
|
||
const agentPoliciesToBump = uniq(packagePolicies.map((item) => item.policy_ids).flat()); | ||
|
||
// TODO bump at once | ||
for (const agentPolicyId of agentPoliciesToBump) { | ||
await agentPolicyService.bumpRevision(soClient, esClient, agentPolicyId); | ||
} | ||
|
||
logger.debug( | ||
`Updated ${updatedCount} package policies in space ${spaceId} in ${ | ||
Date.now() - start | ||
}ms, bump ${agentPoliciesToBump.length} agent policies` | ||
); | ||
} | ||
} | ||
|
||
export async function scheduleBumpAgentPoliciesTask(taskManagerStart: TaskManagerStartContract) { | ||
await taskManagerStart.ensureScheduled({ | ||
id: `${TASK_TYPE}:${uuidv4()}`, | ||
scope: ['fleet'], | ||
params: {}, | ||
taskType: TASK_TYPE, | ||
runAt: new Date(Date.now() + 3 * 1000), | ||
state: {}, | ||
}); | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -28,17 +28,16 @@ import { licenseService } from '../license'; | |
import { outputService } from '../output'; | ||
import { appContextService } from '../app_context'; | ||
|
||
export const mapPackagePolicySavedObjectToPackagePolicy = ({ | ||
id, | ||
version, | ||
attributes, | ||
namespaces, | ||
}: SavedObject<PackagePolicySOAttributes>): PackagePolicy => { | ||
export const mapPackagePolicySavedObjectToPackagePolicy = ( | ||
{ id, version, attributes }: SavedObject<PackagePolicySOAttributes>, | ||
namespaces?: string[] | ||
): PackagePolicy => { | ||
const { bump_agent_policy_revision: bumpAgentPolicyRevision, ...restAttributes } = attributes; | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
|
||
return { | ||
id, | ||
version, | ||
spaceIds: namespaces, | ||
...attributes, | ||
...(namespaces ? { spaceIds: namespaces } : {}), | ||
...restAttributes, | ||
}; | ||
}; | ||
|
||
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This isn't going to work, to handle being cancelled while it's running.
cancelled
will always be false here.Here's an example of handling this correctly; continue to capture it locally, but provide a function that to test it, and pass the function to the "inner" functions rather than the value:
kibana/x-pack/plugins/security_solution/server/lib/entity_analytics/risk_score/tasks/risk_scoring_task.ts
Lines 392 to 408 in ebd3f0d