-
Notifications
You must be signed in to change notification settings - Fork 8.2k
/
setup.ts
196 lines (177 loc) · 6.12 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
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
/*
* 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 url from 'url';
import uuid from 'uuid';
import { SavedObjectsClientContract } from 'src/core/server';
import { CallESAsCurrentUser } from '../types';
import { agentConfigService } from './agent_config';
import { outputService } from './output';
import { ensureInstalledDefaultPackages } from './epm/packages/install';
import { ensureDefaultIndices } from './epm/kibana/index_pattern/install';
import {
packageToConfigDatasource,
Datasource,
AgentConfig,
Installation,
Output,
DEFAULT_AGENT_CONFIGS_PACKAGES,
decodeCloudId,
} from '../../common';
import { getPackageInfo } from './epm/packages';
import { datasourceService } from './datasource';
import { generateEnrollmentAPIKey } from './api_keys';
import { settingsService } from '.';
import { appContextService } from './app_context';
const FLEET_ENROLL_USERNAME = 'fleet_enroll';
const FLEET_ENROLL_ROLE = 'fleet_enroll';
export async function setupIngestManager(
soClient: SavedObjectsClientContract,
callCluster: CallESAsCurrentUser
) {
if (appContextService.getIsInitialized()?.status === 'success') {
return;
}
try {
const [installedPackages, defaultOutput, config] = await Promise.all([
// packages installed by default
ensureInstalledDefaultPackages(soClient, callCluster),
outputService.ensureDefaultOutput(soClient),
agentConfigService.ensureDefaultAgentConfig(soClient),
ensureDefaultIndices(callCluster),
settingsService.getSettings(soClient).catch((e: any) => {
if (e.isBoom && e.output.statusCode === 404) {
const http = appContextService.getHttpSetup();
const serverInfo = http.getServerInfo();
const basePath = http.basePath;
const cloud = appContextService.getCloud();
const cloudId = cloud?.isCloudEnabled && cloud.cloudId;
const cloudUrl = cloudId && decodeCloudId(cloudId)?.kibanaUrl;
const flagsUrl = appContextService.getConfig()?.fleet?.kibana?.host;
const defaultUrl = url.format({
protocol: serverInfo.protocol,
hostname: serverInfo.host,
port: serverInfo.port,
pathname: basePath.serverBasePath,
});
return settingsService.saveSettings(soClient, {
agent_auto_upgrade: true,
package_auto_upgrade: true,
kibana_url: cloudUrl || flagsUrl || defaultUrl,
});
}
return Promise.reject(e);
}),
]);
// ensure default packages are added to the default conifg
const configWithDatasource = await agentConfigService.get(soClient, config.id, true);
if (!configWithDatasource) {
throw new Error('Config not found');
}
if (
configWithDatasource.datasources.length &&
typeof configWithDatasource.datasources[0] === 'string'
) {
throw new Error('Config not found');
}
for (const installedPackage of installedPackages) {
const packageShouldBeInstalled = DEFAULT_AGENT_CONFIGS_PACKAGES.some(
(packageName) => installedPackage.name === packageName
);
if (!packageShouldBeInstalled) {
continue;
}
const isInstalled = configWithDatasource.datasources.some((d: Datasource | string) => {
return typeof d !== 'string' && d.package?.name === installedPackage.name;
});
if (!isInstalled) {
await addPackageToConfig(soClient, installedPackage, configWithDatasource, defaultOutput);
}
}
} catch (e) {
appContextService.setIsInitialized({ status: 'error', error: e });
}
appContextService.setIsInitialized({ status: 'success' });
return;
}
export async function setupFleet(
soClient: SavedObjectsClientContract,
callCluster: CallESAsCurrentUser,
options?: { forceRecreate?: boolean }
) {
// Create fleet_enroll role
// This should be done directly in ES at some point
const res = await callCluster('transport.request', {
method: 'PUT',
path: `/_security/role/${FLEET_ENROLL_ROLE}`,
body: {
cluster: ['monitor', 'manage_api_key'],
indices: [
{
names: ['logs-*', 'metrics-*', 'events-*'],
privileges: ['write', 'create_index'],
},
],
},
});
// If the role is already created skip the rest unless you have forceRecreate set to true
if (options?.forceRecreate !== true && res.role.created === false) {
return;
}
const password = generateRandomPassword();
// Create fleet enroll user
await callCluster('transport.request', {
method: 'PUT',
path: `/_security/user/${FLEET_ENROLL_USERNAME}`,
body: {
password,
roles: [FLEET_ENROLL_ROLE],
metadata: {
updated_at: new Date().toISOString(),
},
},
});
// save fleet admin user
const defaultOutputId = await outputService.getDefaultOutputId(soClient);
if (!defaultOutputId) {
throw new Error('Default output does not exist');
}
await outputService.updateOutput(soClient, defaultOutputId, {
fleet_enroll_username: FLEET_ENROLL_USERNAME,
fleet_enroll_password: password,
});
// Generate default enrollment key
await generateEnrollmentAPIKey(soClient, {
name: 'Default',
configId: await agentConfigService.getDefaultAgentConfigId(soClient),
});
}
function generateRandomPassword() {
return Buffer.from(uuid.v4()).toString('base64');
}
async function addPackageToConfig(
soClient: SavedObjectsClientContract,
packageToInstall: Installation,
config: AgentConfig,
defaultOutput: Output
) {
const packageInfo = await getPackageInfo({
savedObjectsClient: soClient,
pkgName: packageToInstall.name,
pkgVersion: packageToInstall.version,
});
const newDatasource = packageToConfigDatasource(
packageInfo,
config.id,
defaultOutput.id,
undefined,
config.namespace
);
newDatasource.inputs = await datasourceService.assignPackageStream(
packageInfo,
newDatasource.inputs
);
await datasourceService.create(soClient, newDatasource);
}