-
Notifications
You must be signed in to change notification settings - Fork 8.6k
[Security Solution][Endpoint] Cleanup and improvements to run_endpoint_agent.js CLI tool
#155730
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
Merged
paul-tavares
merged 7 commits into
elastic:main
from
paul-tavares:task/endpoint-agent-runner-cli-tool-cleanup
Apr 27, 2023
Merged
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
63780ab
Delete `getAgentDownloadUrl()` form endpoint agent runner and use com…
paul-tavares b9b52ae
Added `useClosestVersionMatch` to `createAndEnrollEndpointHost()`
paul-tavares 6a15eec
Delete duplicate code from endpoint agent runner and replaced it with…
paul-tavares 2b8d410
Added additional methods to `SettingsStorage`
paul-tavares d94ff67
`createAndEnrollEndpointHost()` support for using agent downloads cache
paul-tavares 9ed10ca
added cleanup method to agent downloads storage
paul-tavares 7c3c31e
Extracted agent file management to its own service
paul-tavares File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
161 changes: 161 additions & 0 deletions
161
x-pack/plugins/security_solution/scripts/endpoint/common/agent_downloads_service.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,161 @@ | ||
| /* | ||
| * 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 { mkdir, readdir, stat, unlink } from 'fs/promises'; | ||
| import { join } from 'path'; | ||
| import fs from 'fs'; | ||
| import nodeFetch from 'node-fetch'; | ||
| import { finished } from 'stream/promises'; | ||
| import { SettingsStorage } from './settings_storage'; | ||
|
|
||
| export interface DownloadedAgentInfo { | ||
| filename: string; | ||
| directory: string; | ||
| fullFilePath: string; | ||
| } | ||
|
|
||
| interface AgentDownloadStorageSettings { | ||
| /** | ||
| * Last time a cleanup was ran. Date in ISO format | ||
| */ | ||
| lastCleanup: string; | ||
|
|
||
| /** | ||
| * The max file age in milliseconds. Defaults to 2 days | ||
| */ | ||
| maxFileAge: number; | ||
| } | ||
|
|
||
| /** | ||
| * Class for managing Agent Downloads on the local disk | ||
| * @private | ||
| */ | ||
| class AgentDownloadStorage extends SettingsStorage<AgentDownloadStorageSettings> { | ||
| private downloadsFolderExists = false; | ||
| private readonly downloadsDirName = 'agent_download_storage'; | ||
| private readonly downloadsDirFullPath: string; | ||
|
|
||
| constructor() { | ||
| super('agent_download_storage_settings.json', { | ||
| defaultSettings: { | ||
| maxFileAge: 1.728e8, // 2 days | ||
| lastCleanup: new Date().toISOString(), | ||
| }, | ||
| }); | ||
|
|
||
| this.downloadsDirFullPath = this.buildPath(this.downloadsDirName); | ||
| } | ||
|
|
||
| protected async ensureExists(): Promise<void> { | ||
| await super.ensureExists(); | ||
|
|
||
| if (!this.downloadsFolderExists) { | ||
| await mkdir(this.downloadsDirFullPath, { recursive: true }); | ||
| this.downloadsFolderExists = true; | ||
| } | ||
| } | ||
|
|
||
| public getPathsForUrl(agentDownloadUrl: string): DownloadedAgentInfo { | ||
| const filename = agentDownloadUrl.replace(/^https?:\/\//gi, '').replace(/\//g, '#'); | ||
| const directory = this.downloadsDirFullPath; | ||
| const fullFilePath = this.buildPath(join(this.downloadsDirName, filename)); | ||
|
|
||
| return { | ||
| filename, | ||
| directory, | ||
| fullFilePath, | ||
| }; | ||
| } | ||
|
|
||
| public async downloadAndStore(agentDownloadUrl: string): Promise<DownloadedAgentInfo> { | ||
| // TODO: should we add "retry" attempts to file downloads? | ||
|
|
||
| await this.ensureExists(); | ||
|
|
||
| const newDownloadInfo = this.getPathsForUrl(agentDownloadUrl); | ||
|
|
||
| // If download is already present on disk, then just return that info. No need to re-download it | ||
| if (fs.existsSync(newDownloadInfo.fullFilePath)) { | ||
| return newDownloadInfo; | ||
| } | ||
|
|
||
| try { | ||
| const outputStream = fs.createWriteStream(newDownloadInfo.fullFilePath); | ||
| const { body } = await nodeFetch(agentDownloadUrl); | ||
|
|
||
| await finished(body.pipe(outputStream)); | ||
| } catch (e) { | ||
| // Try to clean up download case it failed halfway through | ||
| await unlink(newDownloadInfo.fullFilePath); | ||
|
|
||
| throw e; | ||
| } | ||
|
|
||
| return newDownloadInfo; | ||
| } | ||
|
|
||
| public async cleanupDownloads(): Promise<{ deleted: string[] }> { | ||
| const settings = await this.get(); | ||
| const maxAgeDate = new Date(); | ||
| const response: { deleted: string[] } = { deleted: [] }; | ||
|
|
||
| maxAgeDate.setMilliseconds(settings.maxFileAge * -1); // `* -1` to set time back | ||
|
|
||
| // If cleanup already happen within the file age, then nothing to do. Exit. | ||
| if (settings.lastCleanup > maxAgeDate.toISOString()) { | ||
| return response; | ||
| } | ||
|
|
||
| await this.save({ | ||
| ...settings, | ||
| lastCleanup: new Date().toISOString(), | ||
| }); | ||
|
|
||
| const deleteFilePromises: Array<Promise<unknown>> = []; | ||
| const allFiles = await readdir(this.downloadsDirFullPath); | ||
|
|
||
| for (const fileName of allFiles) { | ||
| const filePath = join(this.downloadsDirFullPath, fileName); | ||
| const fileStats = await stat(filePath); | ||
|
|
||
| if (fileStats.isFile() && fileStats.birthtime < maxAgeDate) { | ||
| deleteFilePromises.push(unlink(filePath)); | ||
| response.deleted.push(filePath); | ||
| } | ||
| } | ||
|
|
||
| await Promise.allSettled(deleteFilePromises); | ||
|
|
||
| return response; | ||
| } | ||
| } | ||
|
|
||
| const agentDownloadsClient = new AgentDownloadStorage(); | ||
|
|
||
| /** | ||
| * Downloads the agent file provided via the input URL to a local folder on disk. If the file | ||
| * already exists on disk, then no download is actually done - the information about the cached | ||
| * version is returned instead | ||
| * @param agentDownloadUrl | ||
| */ | ||
| export const downloadAndStoreAgent = async ( | ||
| agentDownloadUrl: string | ||
| ): Promise<DownloadedAgentInfo & { url: string }> => { | ||
| const downloadedAgent = await agentDownloadsClient.downloadAndStore(agentDownloadUrl); | ||
|
|
||
| return { | ||
| url: agentDownloadUrl, | ||
| ...downloadedAgent, | ||
| }; | ||
| }; | ||
|
|
||
| /** | ||
| * Cleans up the old agent downloads on disk. | ||
| */ | ||
| export const cleanupDownloads = async (): ReturnType<AgentDownloadStorage['cleanupDownloads']> => { | ||
| return agentDownloadsClient.cleanupDownloads(); | ||
| }; | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
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.
How this works? Each time we run the script this is gonna take the current Date, so last cleanup will be always now right? Am I missing something?
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.
Yes and no.
This is the default value for the configuration for this tool. If you look at
super.ensureExists()you will see that it uses this only if the settings file does not yet exist.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.
Got it, thanks for the explanation!