-
Notifications
You must be signed in to change notification settings - Fork 8.2k
/
setup.ts
178 lines (151 loc) · 5.82 KB
/
setup.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
/*
* 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 { compact } from 'lodash';
import type { ElasticsearchClient, SavedObjectsClientContract } from 'src/core/server';
import { AUTO_UPDATE_PACKAGES } from '../../common';
import type { DefaultPackagesInstallationError, PreconfigurationError } from '../../common';
import { SO_SEARCH_LIMIT, DEFAULT_PACKAGES } from '../constants';
import { appContextService } from './app_context';
import { agentPolicyService } from './agent_policy';
import { ensurePreconfiguredPackagesAndPolicies } from './preconfiguration';
import { outputService } from './output';
import { generateEnrollmentAPIKey, hasEnrollementAPIKeysForPolicy } from './api_keys';
import { settingsService } from '.';
import { awaitIfPending } from './setup_utils';
import { ensureAgentActionPolicyChangeExists } from './agents';
import { awaitIfFleetServerSetupPending } from './fleet_server';
import { ensureFleetFinalPipelineIsInstalled } from './epm/elasticsearch/ingest_pipeline/install';
import { ensureDefaultComponentTemplate } from './epm/elasticsearch/template/install';
import { getInstallations, installPackage } from './epm/packages';
import { isPackageInstalled } from './epm/packages/install';
import { pkgToPkgKey } from './epm/registry';
export interface SetupStatus {
isInitialized: boolean;
nonFatalErrors: Array<PreconfigurationError | DefaultPackagesInstallationError>;
}
export async function setupIngestManager(
soClient: SavedObjectsClientContract,
esClient: ElasticsearchClient
): Promise<SetupStatus> {
return awaitIfPending(async () => createSetupSideEffects(soClient, esClient));
}
async function createSetupSideEffects(
soClient: SavedObjectsClientContract,
esClient: ElasticsearchClient
): Promise<SetupStatus> {
const [defaultOutput] = await Promise.all([
outputService.ensureDefaultOutput(soClient),
settingsService.settingsSetup(soClient),
]);
await awaitIfFleetServerSetupPending();
if (appContextService.getConfig()?.agentIdVerificationEnabled) {
await ensureFleetGlobalEsAssets(soClient, esClient);
}
const { agentPolicies: policiesOrUndefined, packages: packagesOrUndefined } =
appContextService.getConfig() ?? {};
const policies = policiesOrUndefined ?? [];
let packages = packagesOrUndefined ?? [];
// Ensure that required packages are always installed even if they're left out of the config
const preconfiguredPackageNames = new Set(packages.map((pkg) => pkg.name));
const autoUpdateablePackages = compact(
await Promise.all(
AUTO_UPDATE_PACKAGES.map((pkg) =>
isPackageInstalled({
savedObjectsClient: soClient,
pkgName: pkg.name,
}).then((installed) => (installed ? pkg : undefined))
)
)
);
packages = [
...packages,
...DEFAULT_PACKAGES.filter((pkg) => !preconfiguredPackageNames.has(pkg.name)),
...autoUpdateablePackages.filter((pkg) => !preconfiguredPackageNames.has(pkg.name)),
];
const { nonFatalErrors } = await ensurePreconfiguredPackagesAndPolicies(
soClient,
esClient,
policies,
packages,
defaultOutput
);
await ensureDefaultEnrollmentAPIKeysExists(soClient, esClient);
await ensureAgentActionPolicyChangeExists(soClient, esClient);
return {
isInitialized: true,
nonFatalErrors,
};
}
/**
* Ensure ES assets shared by all Fleet index template are installed
*/
export async function ensureFleetGlobalEsAssets(
soClient: SavedObjectsClientContract,
esClient: ElasticsearchClient
) {
const logger = appContextService.getLogger();
// Ensure Global Fleet ES assets are installed
const globalAssetsRes = await Promise.all([
ensureDefaultComponentTemplate(esClient),
ensureFleetFinalPipelineIsInstalled(esClient),
]);
if (globalAssetsRes.some((asset) => asset.isCreated)) {
// Update existing index template
const packages = await getInstallations(soClient);
await Promise.all(
packages.saved_objects.map(async ({ attributes: installation }) => {
if (installation.install_source !== 'registry') {
logger.error(
`Package needs to be manually reinstalled ${installation.name} after installing Fleet global assets`
);
return;
}
await installPackage({
installSource: installation.install_source,
savedObjectsClient: soClient,
pkgkey: pkgToPkgKey({ name: installation.name, version: installation.version }),
esClient,
// Force install the pacakge will update the index template and the datastream write indices
force: true,
}).catch((err) => {
logger.error(
`Package needs to be manually reinstalled ${installation.name} after installing Fleet global assets: ${err.message}`
);
});
})
);
}
}
export async function ensureDefaultEnrollmentAPIKeysExists(
soClient: SavedObjectsClientContract,
esClient: ElasticsearchClient,
options?: { forceRecreate?: boolean }
) {
const security = appContextService.getSecurity();
if (!security) {
return;
}
if (!(await security.authc.apiKeys.areAPIKeysEnabled())) {
return;
}
const { items: agentPolicies } = await agentPolicyService.list(soClient, {
perPage: SO_SEARCH_LIMIT,
});
await Promise.all(
agentPolicies.map(async (agentPolicy) => {
const hasKey = await hasEnrollementAPIKeysForPolicy(esClient, agentPolicy.id);
if (hasKey) {
return;
}
return generateEnrollmentAPIKey(soClient, esClient, {
name: `Default`,
agentPolicyId: agentPolicy.id,
forceRecreate: true, // Always generate a new enrollment key when Fleet is being set up
});
})
);
}