-
Notifications
You must be signed in to change notification settings - Fork 8.2k
/
install.ts
1277 lines (1163 loc) · 40 KB
/
install.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
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* 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 apm from 'elastic-apm-node';
import { i18n } from '@kbn/i18n';
import semverLt from 'semver/functions/lt';
import type Boom from '@hapi/boom';
import type {
ElasticsearchClient,
SavedObject,
SavedObjectsClientContract,
Logger,
} from '@kbn/core/server';
import { SavedObjectsErrorHelpers } from '@kbn/core/server';
import { DEFAULT_SPACE_ID } from '@kbn/spaces-plugin/common/constants';
import pRetry from 'p-retry';
import type { LicenseType } from '@kbn/licensing-plugin/server';
import type { PackageDataStreamTypes, PackageInstallContext } from '../../../../common/types';
import type { HTTPAuthorizationHeader } from '../../../../common/http_authorization_header';
import { isPackagePrerelease, getNormalizedDataStreams } from '../../../../common/services';
import { FLEET_INSTALL_FORMAT_VERSION } from '../../../constants/fleet_es_assets';
import { generateESIndexPatterns } from '../elasticsearch/template/template';
import type {
ArchivePackage,
BulkInstallPackageInfo,
EpmPackageInstallStatus,
InstallablePackage,
Installation,
InstallResult,
InstallSource,
InstallType,
KibanaAssetType,
NewPackagePolicy,
PackageInfo,
PackageVerificationResult,
} from '../../../types';
import {
AUTO_UPGRADE_POLICIES_PACKAGES,
CUSTOM_INTEGRATION_PACKAGE_SPEC_VERSION,
DATASET_VAR_NAME,
GENERIC_DATASET_NAME,
} from '../../../../common/constants';
import {
FleetError,
PackageOutdatedError,
PackagePolicyValidationError,
ConcurrentInstallOperationError,
FleetUnauthorizedError,
PackageNotFoundError,
} from '../../../errors';
import { PACKAGES_SAVED_OBJECT_TYPE, MAX_TIME_COMPLETE_INSTALL } from '../../../constants';
import { dataStreamService, licenseService } from '../..';
import { appContextService } from '../../app_context';
import * as Registry from '../registry';
import {
setPackageInfo,
generatePackageInfoFromArchiveBuffer,
deleteVerificationResult,
unpackBufferToAssetsMap,
} from '../archive';
import { toAssetReference } from '../kibana/assets/install';
import type { ArchiveAsset } from '../kibana/assets/install';
import type { PackageUpdateEvent } from '../../upgrade_sender';
import { sendTelemetryEvents, UpdateEventType } from '../../upgrade_sender';
import { auditLoggingService } from '../../audit_logging';
import { getFilteredInstallPackages } from '../filtered_packages';
import { formatVerificationResultForSO } from './package_verification';
import { getInstallation, getInstallationObject } from './get';
import { removeInstallation } from './remove';
import { getInstalledPackageWithAssets, getPackageSavedObjects } from './get';
import { _installPackage } from './_install_package';
import { removeOldAssets } from './cleanup';
import { getBundledPackageByPkgKey } from './bundled_packages';
import { convertStringToTitle, generateDescription } from './custom_integrations/utils';
import { INITIAL_VERSION } from './custom_integrations/constants';
import { createAssets } from './custom_integrations';
import { generateDatastreamEntries } from './custom_integrations/assets/dataset/utils';
import { checkForNamingCollision } from './custom_integrations/validation/check_naming_collision';
import { checkDatasetsNameFormat } from './custom_integrations/validation/check_dataset_name_format';
import { addErrorToLatestFailedAttempts } from './install_errors_helpers';
import { installIndexTemplatesAndPipelines } from './install_index_template_pipeline';
import { optimisticallyAddEsAssetReferences } from './es_assets_reference';
const MAX_ENSURE_INSTALL_TIME = 60 * 1000;
export async function isPackageInstalled(options: {
savedObjectsClient: SavedObjectsClientContract;
pkgName: string;
}): Promise<boolean> {
const installedPackage = await getInstallation(options);
return installedPackage !== undefined;
}
// Error used to retry in isPackageVersionOrLaterInstalled
class CurrentlyInstallingError extends Error {}
/**
* Check if a package is currently installed,
* if the package is currently installing it will retry until MAX_ENSURE_INSTALL_TIME is reached
*/
export async function isPackageVersionOrLaterInstalled(options: {
savedObjectsClient: SavedObjectsClientContract;
pkgName: string;
pkgVersion: string;
}): Promise<{ package: Installation } | false> {
return pRetry(
async () => {
const { savedObjectsClient, pkgName, pkgVersion } = options;
const installedPackageObject = await getInstallationObject({ savedObjectsClient, pkgName });
const installedPackage = installedPackageObject?.attributes;
if (
installedPackage &&
(installedPackage.version === pkgVersion || semverLt(pkgVersion, installedPackage.version))
) {
if (installedPackage.install_status === 'installing') {
throw new CurrentlyInstallingError(
`Package ${pkgName}-${pkgVersion} is currently installing`
);
} else if (installedPackage.install_status === 'install_failed') {
return false;
}
return { package: installedPackage };
}
return false;
},
{
maxRetryTime: MAX_ENSURE_INSTALL_TIME,
onFailedAttempt: (error) => {
if (!(error instanceof CurrentlyInstallingError)) {
throw error;
}
},
}
).catch((err): false => {
if (err instanceof CurrentlyInstallingError) {
return false;
}
throw err;
});
}
export async function ensureInstalledPackage(options: {
savedObjectsClient: SavedObjectsClientContract;
pkgName: string;
esClient: ElasticsearchClient;
pkgVersion?: string;
spaceId?: string;
force?: boolean;
authorizationHeader?: HTTPAuthorizationHeader | null;
}): Promise<Installation> {
const {
savedObjectsClient,
pkgName,
esClient,
pkgVersion,
force = false,
spaceId = DEFAULT_SPACE_ID,
authorizationHeader,
} = options;
// If pkgVersion isn't specified, find the latest package version
const pkgKeyProps = pkgVersion
? { name: pkgName, version: pkgVersion }
: await Registry.fetchFindLatestPackageOrThrow(pkgName, { prerelease: true });
const installedPackageResult = await isPackageVersionOrLaterInstalled({
savedObjectsClient,
pkgName: pkgKeyProps.name,
pkgVersion: pkgKeyProps.version,
});
if (installedPackageResult) {
return installedPackageResult.package;
}
const pkgkey = Registry.pkgToPkgKey(pkgKeyProps);
const installResult = await installPackage({
installSource: 'registry',
savedObjectsClient,
pkgkey,
spaceId,
esClient,
neverIgnoreVerificationError: !force,
force: true, // Always force outdated packages to be installed if a later version isn't installed
authorizationHeader,
});
if (installResult.error) {
const errorPrefix =
installResult.installType === 'update' || installResult.installType === 'reupdate'
? i18n.translate('xpack.fleet.epm.install.packageUpdateError', {
defaultMessage: 'Error updating {pkgName} to {pkgVersion}',
values: {
pkgName: pkgKeyProps.name,
pkgVersion: pkgKeyProps.version,
},
})
: i18n.translate('xpack.fleet.epm.install.packageInstallError', {
defaultMessage: 'Error installing {pkgName} {pkgVersion}',
values: {
pkgName: pkgKeyProps.name,
pkgVersion: pkgKeyProps.version,
},
});
installResult.error.message = `${errorPrefix}: ${installResult.error.message}`;
throw installResult.error;
}
const installation = await getInstallation({ savedObjectsClient, pkgName });
if (!installation) throw new FleetError(`Could not get installation for ${pkgName}`);
return installation;
}
export async function handleInstallPackageFailure({
savedObjectsClient,
error,
pkgName,
pkgVersion,
installedPkg,
esClient,
spaceId,
authorizationHeader,
}: {
savedObjectsClient: SavedObjectsClientContract;
error: FleetError | Boom.Boom | Error;
pkgName: string;
pkgVersion: string;
installedPkg: SavedObject<Installation> | undefined;
esClient: ElasticsearchClient;
spaceId: string;
authorizationHeader?: HTTPAuthorizationHeader | null;
}) {
if (error instanceof ConcurrentInstallOperationError) {
return;
}
const logger = appContextService.getLogger();
const pkgkey = Registry.pkgToPkgKey({
name: pkgName,
version: pkgVersion,
});
const latestInstallFailedAttempts = addErrorToLatestFailedAttempts({
error,
targetVersion: pkgVersion,
createdAt: new Date().toISOString(),
latestAttempts: installedPkg?.attributes.latest_install_failed_attempts,
});
// if there is an unknown server error, uninstall any package assets or reinstall the previous version if update
try {
const installType = getInstallType({ pkgVersion, installedPkg });
if (installType === 'install') {
logger.error(`uninstalling ${pkgkey} after error installing: [${error.toString()}]`);
await removeInstallation({ savedObjectsClient, pkgName, pkgVersion, esClient });
return;
}
await updateInstallStatusToFailed({
logger,
savedObjectsClient,
pkgName,
status: 'install_failed',
latestInstallFailedAttempts,
});
if (installType === 'reinstall') {
logger.error(`Failed to reinstall ${pkgkey}: [${error.toString()}]`, { error });
}
if (installType === 'update') {
if (!installedPkg) {
logger.error(
`failed to rollback package after installation error ${error} because saved object was undefined`
);
return;
}
const prevVersion = `${pkgName}-${installedPkg.attributes.version}`;
logger.error(`rolling back to ${prevVersion} after error installing ${pkgkey}`);
await installPackage({
installSource: 'registry',
savedObjectsClient,
pkgkey: prevVersion,
esClient,
spaceId,
force: true,
authorizationHeader,
});
}
} catch (e) {
// If an error happens while removing the integration or while doing a rollback update the status to failed
await updateInstallStatusToFailed({
logger,
savedObjectsClient,
pkgName,
status: 'install_failed',
latestInstallFailedAttempts: installedPkg
? addErrorToLatestFailedAttempts({
error: e,
targetVersion: installedPkg.attributes.version,
createdAt: installedPkg.attributes.install_started_at,
latestAttempts: latestInstallFailedAttempts,
})
: [],
});
logger.error(`failed to uninstall or rollback package after installation error ${e}`);
}
}
export interface IBulkInstallPackageError {
name: string;
error: Error;
installType?: InstallType;
}
export type BulkInstallResponse = BulkInstallPackageInfo | IBulkInstallPackageError;
interface InstallRegistryPackageParams {
savedObjectsClient: SavedObjectsClientContract;
pkgkey: string;
esClient: ElasticsearchClient;
spaceId: string;
force?: boolean;
neverIgnoreVerificationError?: boolean;
ignoreConstraints?: boolean;
prerelease?: boolean;
authorizationHeader?: HTTPAuthorizationHeader | null;
ignoreMappingUpdateErrors?: boolean;
skipDataStreamRollover?: boolean;
}
export interface CustomPackageDatasetConfiguration {
name: string;
type: PackageDataStreamTypes;
}
interface InstallCustomPackageParams {
savedObjectsClient: SavedObjectsClientContract;
pkgName: string;
datasets: CustomPackageDatasetConfiguration[];
esClient: ElasticsearchClient;
spaceId: string;
force?: boolean;
authorizationHeader?: HTTPAuthorizationHeader | null;
kibanaVersion: string;
}
interface InstallUploadedArchiveParams {
savedObjectsClient: SavedObjectsClientContract;
esClient: ElasticsearchClient;
archiveBuffer: Buffer;
contentType: string;
spaceId: string;
version?: string;
authorizationHeader?: HTTPAuthorizationHeader | null;
ignoreMappingUpdateErrors?: boolean;
skipDataStreamRollover?: boolean;
isBundledPackage?: boolean;
}
function getTelemetryEvent(pkgName: string, pkgVersion: string): PackageUpdateEvent {
return {
packageName: pkgName,
currentVersion: 'unknown',
newVersion: pkgVersion,
status: 'failure',
dryRun: false,
eventType: UpdateEventType.PACKAGE_INSTALL,
installType: 'unknown',
};
}
function sendEvent(telemetryEvent: PackageUpdateEvent) {
sendTelemetryEvents(
appContextService.getLogger(),
appContextService.getTelemetryEventsSender(),
telemetryEvent
);
}
async function installPackageFromRegistry({
savedObjectsClient,
pkgkey,
esClient,
spaceId,
authorizationHeader,
force = false,
ignoreConstraints = false,
neverIgnoreVerificationError = false,
prerelease = false,
ignoreMappingUpdateErrors = false,
skipDataStreamRollover = false,
}: InstallRegistryPackageParams): Promise<InstallResult> {
const logger = appContextService.getLogger();
// TODO: change epm API to /packageName/version so we don't need to do this
const { pkgName, pkgVersion: version } = Registry.splitPkgKey(pkgkey);
let pkgVersion = version ?? '';
// if an error happens during getInstallType, report that we don't know
let installType: InstallType = 'unknown';
const installSource = 'registry';
const telemetryEvent: PackageUpdateEvent = getTelemetryEvent(pkgName, pkgVersion);
try {
// get the currently installed package
const installedPkg = await getInstallationObject({ savedObjectsClient, pkgName });
installType = getInstallType({ pkgVersion, installedPkg });
telemetryEvent.installType = installType;
telemetryEvent.currentVersion = installedPkg?.attributes.version || 'not_installed';
const queryLatest = () =>
Registry.fetchFindLatestPackageOrThrow(pkgName, {
ignoreConstraints,
prerelease: prerelease === true || isPackagePrerelease(pkgVersion), // fetching latest GA version if the package to install is GA, so that it is allowed to install
});
let latestPkg;
// fetching latest package first to set the version
if (!pkgVersion) {
latestPkg = await queryLatest();
pkgVersion = latestPkg.version;
}
// get latest package version and requested version in parallel for performance
const [latestPackage, { paths, packageInfo, assetsMap, verificationResult }] =
await Promise.all([
latestPkg ? Promise.resolve(latestPkg) : queryLatest(),
Registry.getPackage(pkgName, pkgVersion, {
ignoreUnverified: force && !neverIgnoreVerificationError,
}),
]);
const packageInstallContext: PackageInstallContext = {
packageInfo,
assetsMap,
paths,
};
// let the user install if using the force flag or needing to reinstall or install a previous version due to failed update
const installOutOfDateVersionOk =
force || ['reinstall', 'reupdate', 'rollback'].includes(installType);
// if the requested version is out-of-date of the latest package version, check if we allow it
// if we don't allow it, return an error
if (semverLt(pkgVersion, latestPackage.version)) {
if (!installOutOfDateVersionOk) {
throw new PackageOutdatedError(
`${pkgkey} is out-of-date and cannot be installed or updated`
);
}
logger.debug(
`${pkgkey} is out-of-date, installing anyway due to ${
force ? 'force flag' : `install type ${installType}`
}`
);
}
return await installPackageCommon({
pkgName,
pkgVersion,
installSource,
installedPkg,
installType,
savedObjectsClient,
esClient,
spaceId,
force,
packageInstallContext,
paths,
verificationResult,
authorizationHeader,
ignoreMappingUpdateErrors,
skipDataStreamRollover,
});
} catch (e) {
sendEvent({
...telemetryEvent,
errorMessage: e.message,
});
return {
error: e,
installType,
installSource,
};
}
}
function getElasticSubscription(packageInfo: ArchivePackage) {
const subscription = packageInfo.conditions?.elastic?.subscription as LicenseType | undefined;
// Keep packageInfo.license for backward compatibility
return subscription || packageInfo.license || 'basic';
}
async function installPackageCommon(options: {
pkgName: string;
pkgVersion: string;
installSource: InstallSource;
installedPkg?: SavedObject<Installation>;
installType: InstallType;
savedObjectsClient: SavedObjectsClientContract;
esClient: ElasticsearchClient;
spaceId: string;
force?: boolean;
packageInstallContext: PackageInstallContext;
paths: string[];
verificationResult?: PackageVerificationResult;
telemetryEvent?: PackageUpdateEvent;
authorizationHeader?: HTTPAuthorizationHeader | null;
ignoreMappingUpdateErrors?: boolean;
skipDataStreamRollover?: boolean;
}): Promise<InstallResult> {
const packageInfo = options.packageInstallContext.packageInfo;
const {
pkgName,
pkgVersion,
installSource,
installedPkg,
installType,
savedObjectsClient,
force,
esClient,
spaceId,
verificationResult,
authorizationHeader,
ignoreMappingUpdateErrors,
skipDataStreamRollover,
packageInstallContext,
} = options;
let { telemetryEvent } = options;
const logger = appContextService.getLogger();
logger.info(`Install - Starting installation of ${pkgName}@${pkgVersion} from ${installSource} `);
// Workaround apm issue with async spans: https://github.com/elastic/apm-agent-nodejs/issues/2611
await Promise.resolve();
const span = apm.startSpan(
`Install package from ${installSource} ${pkgName}@${pkgVersion}`,
'package'
);
if (!telemetryEvent) {
telemetryEvent = getTelemetryEvent(pkgName, pkgVersion);
telemetryEvent.installType = installType;
telemetryEvent.currentVersion = installedPkg?.attributes.version || 'not_installed';
}
try {
span?.addLabels({
packageName: pkgName,
packageVersion: pkgVersion,
installType,
});
const filteredPackages = getFilteredInstallPackages();
if (filteredPackages.includes(pkgName)) {
throw new FleetUnauthorizedError(`${pkgName} installation is not authorized`);
}
// if the requested version is the same as installed version, check if we allow it based on
// current installed package status and force flag, if we don't allow it,
// just return the asset references from the existing installation
if (
installedPkg?.attributes.version === pkgVersion &&
installedPkg?.attributes.install_status === 'installed'
) {
if (!force) {
logger.debug(`${pkgName}-${pkgVersion} is already installed, skipping installation`);
return {
assets: [
...installedPkg.attributes.installed_es,
...installedPkg.attributes.installed_kibana,
],
status: 'already_installed',
installType,
installSource,
};
}
}
const elasticSubscription = getElasticSubscription(packageInfo);
if (!licenseService.hasAtLeast(elasticSubscription)) {
logger.error(`Installation requires ${elasticSubscription} license`);
const err = new FleetError(`Installation requires ${elasticSubscription} license`);
sendEvent({
...telemetryEvent,
errorMessage: err.message,
});
return { error: err, installType, installSource };
}
// Saved object client need to be scopped with the package space for saved object tagging
const savedObjectClientWithSpace = appContextService.getInternalUserSOClientForSpaceId(spaceId);
const savedObjectsImporter = appContextService
.getSavedObjects()
.createImporter(savedObjectClientWithSpace, { importSizeLimit: 15_000 });
const savedObjectTagAssignmentService = appContextService
.getSavedObjectsTagging()
.createInternalAssignmentService({ client: savedObjectClientWithSpace });
const savedObjectTagClient = appContextService
.getSavedObjectsTagging()
.createTagClient({ client: savedObjectClientWithSpace });
// try installing the package, if there was an error, call error handler and rethrow
// @ts-expect-error status is string instead of InstallResult.status 'installed' | 'already_installed'
return await _installPackage({
savedObjectsClient,
savedObjectsImporter,
savedObjectTagAssignmentService,
savedObjectTagClient,
esClient,
logger,
installedPkg,
packageInstallContext,
installType,
spaceId,
verificationResult,
installSource,
authorizationHeader,
force,
ignoreMappingUpdateErrors,
skipDataStreamRollover,
})
.then(async (assets) => {
logger.debug(`Removing old assets from previous versions of ${pkgName}`);
await removeOldAssets({
soClient: savedObjectsClient,
pkgName: packageInfo.name,
currentVersion: packageInfo.version,
});
sendEvent({
...telemetryEvent!,
status: 'success',
});
return { assets, status: 'installed', installType, installSource };
})
.catch(async (err: Error) => {
logger.warn(`Failure to install package [${pkgName}]: [${err.toString()}]`, {
error: { stack_trace: err.stack },
});
await handleInstallPackageFailure({
savedObjectsClient,
error: err,
pkgName,
pkgVersion,
installedPkg,
spaceId,
esClient,
authorizationHeader,
});
sendEvent({
...telemetryEvent!,
errorMessage: err.message,
});
return { error: err, installType, installSource };
});
} catch (e) {
sendEvent({
...telemetryEvent,
errorMessage: e.message,
});
return {
error: e,
installType,
installSource,
};
} finally {
span?.end();
}
}
async function installPackageByUpload({
savedObjectsClient,
esClient,
archiveBuffer,
contentType,
spaceId,
version,
authorizationHeader,
ignoreMappingUpdateErrors,
skipDataStreamRollover,
isBundledPackage,
}: InstallUploadedArchiveParams): Promise<InstallResult> {
// if an error happens during getInstallType, report that we don't know
let installType: InstallType = 'unknown';
const installSource = isBundledPackage ? 'bundled' : 'upload';
try {
const { packageInfo } = await generatePackageInfoFromArchiveBuffer(archiveBuffer, contentType);
const pkgName = packageInfo.name;
// Allow for overriding the version in the manifest for cases where we install
// stack-aligned bundled packages to support special cases around the
// `forceAlignStackVersion` flag in `fleet_packages.json`.
const pkgVersion = version || packageInfo.version;
const installedPkg = await getInstallationObject({
savedObjectsClient,
pkgName,
});
installType = getInstallType({ pkgVersion, installedPkg });
// as we do not verify uploaded packages, we must invalidate the verification cache
deleteVerificationResult(packageInfo);
setPackageInfo({
name: packageInfo.name,
version: pkgVersion,
packageInfo,
});
const { assetsMap, paths } = await unpackBufferToAssetsMap({
name: packageInfo.name,
version: pkgVersion,
archiveBuffer,
contentType,
});
const packageInstallContext: PackageInstallContext = {
packageInfo: { ...packageInfo, version: pkgVersion },
assetsMap,
paths,
};
return await installPackageCommon({
packageInstallContext,
pkgName,
pkgVersion,
installSource,
installedPkg,
installType,
savedObjectsClient,
esClient,
spaceId,
force: true, // upload has implicit force
paths,
authorizationHeader,
ignoreMappingUpdateErrors,
skipDataStreamRollover,
});
} catch (e) {
return {
error: e,
installType,
installSource,
};
}
}
export type InstallPackageParams = {
spaceId: string;
neverIgnoreVerificationError?: boolean;
} & (
| ({ installSource: Extract<InstallSource, 'registry'> } & InstallRegistryPackageParams)
| ({ installSource: Extract<InstallSource, 'upload'> } & InstallUploadedArchiveParams)
| ({ installSource: Extract<InstallSource, 'bundled'> } & InstallUploadedArchiveParams)
| ({ installSource: Extract<InstallSource, 'custom'> } & InstallCustomPackageParams)
);
export async function installPackage(args: InstallPackageParams): Promise<InstallResult> {
if (!('installSource' in args)) {
throw new FleetError('installSource is required');
}
const logger = appContextService.getLogger();
const { savedObjectsClient, esClient } = args;
const authorizationHeader = args.authorizationHeader;
if (args.installSource === 'registry') {
const {
pkgkey,
force,
ignoreConstraints,
spaceId,
neverIgnoreVerificationError,
prerelease,
ignoreMappingUpdateErrors,
skipDataStreamRollover,
} = args;
const matchingBundledPackage = await getBundledPackageByPkgKey(pkgkey);
if (matchingBundledPackage) {
logger.debug(
`Found bundled package for requested install of ${pkgkey} - installing from bundled package archive`
);
const archiveBuffer = await matchingBundledPackage.getBuffer();
const response = await installPackageByUpload({
savedObjectsClient,
esClient,
archiveBuffer,
contentType: 'application/zip',
spaceId,
version: matchingBundledPackage.version,
authorizationHeader,
ignoreMappingUpdateErrors,
skipDataStreamRollover,
isBundledPackage: true,
});
return { ...response, installSource: 'bundled' };
}
logger.debug(`Kicking off install of ${pkgkey} from registry`);
const response = await installPackageFromRegistry({
savedObjectsClient,
pkgkey,
esClient,
spaceId,
force,
neverIgnoreVerificationError,
ignoreConstraints,
prerelease,
authorizationHeader,
ignoreMappingUpdateErrors,
skipDataStreamRollover,
});
return response;
} else if (args.installSource === 'upload') {
const {
archiveBuffer,
contentType,
spaceId,
ignoreMappingUpdateErrors,
skipDataStreamRollover,
} = args;
logger.debug(`Installing package by upload`);
const response = await installPackageByUpload({
savedObjectsClient,
esClient,
archiveBuffer,
contentType,
spaceId,
authorizationHeader,
ignoreMappingUpdateErrors,
skipDataStreamRollover,
});
return response;
} else if (args.installSource === 'custom') {
const { pkgName, force, datasets, spaceId, kibanaVersion } = args;
logger.debug(`Kicking off install of custom package ${pkgName}`);
const response = await installCustomPackage({
savedObjectsClient,
pkgName,
datasets,
esClient,
spaceId,
force,
authorizationHeader,
kibanaVersion,
});
return response;
}
throw new FleetError(`Unknown installSource: ${args.installSource}`);
}
export async function installCustomPackage(
args: InstallCustomPackageParams
): Promise<InstallResult> {
const {
savedObjectsClient,
esClient,
spaceId,
pkgName,
force,
authorizationHeader,
datasets,
kibanaVersion,
} = args;
// Validate that we can create this package, validations will throw if they don't pass
await checkForNamingCollision(savedObjectsClient, pkgName);
checkDatasetsNameFormat(datasets, pkgName);
// Compose a packageInfo
const packageInfo = {
format_version: CUSTOM_INTEGRATION_PACKAGE_SPEC_VERSION,
name: pkgName,
title: convertStringToTitle(pkgName),
description: generateDescription(datasets.map((dataset) => dataset.name)),
version: INITIAL_VERSION,
owner: { github: authorizationHeader?.username ?? 'unknown' },
type: 'integration' as const,
data_streams: generateDatastreamEntries(datasets, pkgName),
};
const assets = createAssets({
...packageInfo,
kibanaVersion,
datasets,
});
const assetsMap = assets.reduce((acc, asset) => {
acc.set(asset.path, asset.content);
return acc;
}, new Map<string, Buffer | undefined>());
const paths = [...assetsMap.keys()];
const packageInstallContext: PackageInstallContext = {
assetsMap,
paths,
packageInfo,
};
return await installPackageCommon({
packageInstallContext,
pkgName,
pkgVersion: INITIAL_VERSION,
installSource: 'custom',
installType: 'install',
savedObjectsClient,
esClient,
spaceId,
force,
paths,
authorizationHeader,
});
}
export const updateVersion = async (
savedObjectsClient: SavedObjectsClientContract,
pkgName: string,
pkgVersion: string
) => {
auditLoggingService.writeCustomSoAuditLog({
action: 'update',
id: pkgName,
savedObjectType: PACKAGES_SAVED_OBJECT_TYPE,
});
return savedObjectsClient.update(PACKAGES_SAVED_OBJECT_TYPE, pkgName, {
version: pkgVersion,
});
};
export const updateInstallStatusToFailed = async ({
logger,
savedObjectsClient,
pkgName,
status,
latestInstallFailedAttempts,
}: {
logger: Logger;
savedObjectsClient: SavedObjectsClientContract;
pkgName: string;
status: EpmPackageInstallStatus;
latestInstallFailedAttempts: any;
}) => {
auditLoggingService.writeCustomSoAuditLog({
action: 'update',
id: pkgName,
savedObjectType: PACKAGES_SAVED_OBJECT_TYPE,
});
try {
return await savedObjectsClient.update(PACKAGES_SAVED_OBJECT_TYPE, pkgName, {
install_status: status,
latest_install_failed_attempts: latestInstallFailedAttempts,
});
} catch (err) {
if (!SavedObjectsErrorHelpers.isNotFoundError(err)) {
logger.error(`failed to update package status to: install_failed ${err}`);
}
}
};
export async function restartInstallation(options: {
savedObjectsClient: SavedObjectsClientContract;
pkgName: string;
pkgVersion: string;
installSource: InstallSource;
verificationResult?: PackageVerificationResult;
}) {
const { savedObjectsClient, pkgVersion, pkgName, installSource, verificationResult } = options;
let savedObjectUpdate: Partial<Installation> = {
install_version: pkgVersion,
install_status: 'installing',
install_started_at: new Date().toISOString(),
install_source: installSource,
};
if (verificationResult) {
savedObjectUpdate = {
...savedObjectUpdate,
verification_key_id: null, // unset any previous verification key id
...formatVerificationResultForSO(verificationResult),
};
}
auditLoggingService.writeCustomSoAuditLog({
action: 'update',
id: pkgName,