-
Notifications
You must be signed in to change notification settings - Fork 8.3k
/
plugin.ts
180 lines (155 loc) · 5.62 KB
/
plugin.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
/*
* 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 {
map,
Observable,
Subject,
Subscription,
switchMap,
takeUntil,
filter,
throttleTime,
distinctUntilChanged,
ReplaySubject,
timer,
firstValueFrom,
} from 'rxjs';
import moment from 'moment';
import type { MaybePromise } from '@kbn/utility-types';
import {
CoreSetup,
Logger,
Plugin,
PluginInitializerContext,
IClusterClient,
ServiceStatusLevels,
} from '@kbn/core/server';
import { registerAnalyticsContextProvider } from '../common/register_analytics_context_provider';
import type { ILicense } from '../common/types';
import type { LicensingPluginSetup, LicensingPluginStart } from './types';
import { createLicenseUpdate } from '../common/license_update';
import { registerRoutes } from './routes';
import { FeatureUsageService } from './services';
import type { LicenseConfigType } from './licensing_config';
import { createRouteHandlerContext } from './licensing_route_handler_context';
import { createOnPreResponseHandler } from './on_pre_response_handler';
import { getPluginStatus$ } from './plugin_status';
import { getLicenseFetcher } from './license_fetcher';
/**
* @public
* A plugin for fetching, refreshing, and receiving information about the license for the
* current Kibana instance.
*/
export class LicensingPlugin implements Plugin<LicensingPluginSetup, LicensingPluginStart, {}, {}> {
private stop$: Subject<void> = new ReplaySubject<void>(1);
private readonly isElasticsearchAvailable$ = new ReplaySubject<boolean>(1);
private readonly logger: Logger;
private readonly config: LicenseConfigType;
private loggingSubscription?: Subscription;
private featureUsage = new FeatureUsageService();
private refresh?: () => Promise<ILicense>;
private license$?: Observable<ILicense>;
constructor(private readonly context: PluginInitializerContext) {
this.logger = this.context.logger.get();
this.config = this.context.config.get<LicenseConfigType>();
}
public setup(core: CoreSetup<{}, LicensingPluginStart>) {
this.logger.debug('Setting up Licensing plugin');
const pollingFrequency = this.config.api_polling_frequency;
const clientPromise = core.getStartServices().then(([{ elasticsearch }]) => {
return elasticsearch.client;
});
core.status.core$
.pipe(map(({ elasticsearch }) => elasticsearch.level === ServiceStatusLevels.available))
.subscribe(this.isElasticsearchAvailable$);
const { refresh, license$ } = this.createLicensePoller(
clientPromise,
pollingFrequency.asMilliseconds()
);
registerAnalyticsContextProvider(core.analytics, license$);
core.status.set(getPluginStatus$(license$, this.stop$.asObservable()));
core.http.registerRouteHandlerContext(
'licensing',
createRouteHandlerContext(license$, core.getStartServices)
);
const featureUsageSetup = this.featureUsage.setup();
registerRoutes(core.http.createRouter(), featureUsageSetup, core.getStartServices);
core.http.registerOnPreResponse(createOnPreResponseHandler(refresh, license$));
this.refresh = refresh;
this.license$ = license$;
return {
refresh,
license$,
featureUsage: featureUsageSetup,
};
}
private createLicensePoller(
clusterClient: MaybePromise<IClusterClient>,
pollingFrequency: number
) {
this.logger.debug(`Polling Elasticsearch License API with frequency ${pollingFrequency}ms.`);
const isElasticsearchNotAvailable$ = this.isElasticsearchAvailable$.pipe(
filter((isElasticsearchAvailable) => !isElasticsearchAvailable)
);
// Trigger whenever the timer ticks or ES becomes available
const intervalRefresh$ = this.isElasticsearchAvailable$.pipe(
distinctUntilChanged(),
filter((isElasticsearchAvailable) => isElasticsearchAvailable),
switchMap(() => timer(0, pollingFrequency).pipe(takeUntil(isElasticsearchNotAvailable$))),
throttleTime(pollingFrequency) // avoid triggering too often
);
const licenseFetcher = getLicenseFetcher({
clusterClient,
logger: this.logger,
cacheDurationMs: this.config.license_cache_duration.asMilliseconds(),
maxRetryDelay: pollingFrequency,
});
const { license$, refreshManually } = createLicenseUpdate(
intervalRefresh$,
this.stop$,
licenseFetcher
);
this.loggingSubscription = license$.subscribe((license) =>
this.logger.debug(
() =>
'Imported license information from Elasticsearch:' +
[
`type: ${license.type}`,
`status: ${license.status}`,
`expiry date: ${moment(license.expiryDateInMillis, 'x').format()}`,
].join(' | ')
)
);
return {
refresh: async () => {
this.logger.debug('Requesting Elasticsearch licensing API');
return await refreshManually();
},
license$,
};
}
public start() {
if (!this.refresh || !this.license$) {
throw new Error('Setup has not been completed');
}
return {
refresh: this.refresh,
getLicense: async () => await firstValueFrom(this.license$!),
license$: this.license$,
featureUsage: this.featureUsage.start(),
createLicensePoller: this.createLicensePoller.bind(this),
};
}
public stop() {
this.stop$.next();
this.stop$.complete();
if (this.loggingSubscription !== undefined) {
this.loggingSubscription.unsubscribe();
this.loggingSubscription = undefined;
}
}
}