-
Notifications
You must be signed in to change notification settings - Fork 8.3k
/
Copy pathplugin.ts
200 lines (171 loc) · 5.66 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
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
/*
* 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 { Observable, Subject, Subscription, timer } from 'rxjs';
import { take } from 'rxjs/operators';
import moment from 'moment';
import { createHash } from 'crypto';
import stringify from 'json-stable-stringify';
import {
CoreSetup,
CoreStart,
Logger,
Plugin,
PluginInitializerContext,
IClusterClient,
} from 'src/core/server';
import { ILicense, PublicLicense, PublicFeatures } from '../common/types';
import { LicensingPluginSetup } from './types';
import { License } from '../common/license';
import { createLicenseUpdate } from '../common/license_update';
import { ElasticsearchError, RawLicense, RawFeatures } from './types';
import { registerRoutes } from './routes';
import { LicenseConfigType } from './licensing_config';
import { createRouteHandlerContext } from './licensing_route_handler_context';
import { createOnPreResponseHandler } from './on_pre_response_handler';
function normalizeServerLicense(license: RawLicense): PublicLicense {
return {
uid: license.uid,
type: license.type,
mode: license.mode,
expiryDateInMillis: license.expiry_date_in_millis,
status: license.status,
};
}
function normalizeFeatures(rawFeatures: RawFeatures) {
const features: PublicFeatures = {};
for (const [name, feature] of Object.entries(rawFeatures)) {
features[name] = {
isAvailable: feature.available,
isEnabled: feature.enabled,
};
}
return features;
}
function sign({
license,
features,
error,
}: {
license?: PublicLicense;
features?: PublicFeatures;
error?: string;
}) {
return createHash('sha256')
.update(
stringify({
license,
features,
error,
})
)
.digest('hex');
}
/**
* @public
* A plugin for fetching, refreshing, and receiving information about the license for the
* current Kibana instance.
*/
export class LicensingPlugin implements Plugin<LicensingPluginSetup> {
private stop$ = new Subject();
private readonly logger: Logger;
private readonly config$: Observable<LicenseConfigType>;
private loggingSubscription?: Subscription;
constructor(private readonly context: PluginInitializerContext) {
this.logger = this.context.logger.get();
this.config$ = this.context.config.create<LicenseConfigType>();
}
public async setup(core: CoreSetup) {
this.logger.debug('Setting up Licensing plugin');
const config = await this.config$.pipe(take(1)).toPromise();
const pollingFrequency = config.api_polling_frequency;
const dataClient = await core.elasticsearch.dataClient;
const { refresh, license$ } = this.createLicensePoller(
dataClient,
pollingFrequency.asMilliseconds()
);
core.http.registerRouteHandlerContext('licensing', createRouteHandlerContext(license$));
registerRoutes(core.http.createRouter());
core.http.registerOnPreResponse(createOnPreResponseHandler(refresh, license$));
return {
refresh,
license$,
createLicensePoller: this.createLicensePoller.bind(this),
};
}
private createLicensePoller(clusterClient: IClusterClient, pollingFrequency: number) {
this.logger.debug(`Polling Elasticsearch License API with frequency ${pollingFrequency}ms.`);
const intervalRefresh$ = timer(0, pollingFrequency);
const { license$, refreshManually } = createLicenseUpdate(intervalRefresh$, this.stop$, () =>
this.fetchLicense(clusterClient)
);
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$,
};
}
private fetchLicense = async (clusterClient: IClusterClient): Promise<ILicense> => {
try {
const response = await clusterClient.callAsInternalUser('transport.request', {
method: 'GET',
path: '/_xpack',
});
const normalizedLicense = response.license
? normalizeServerLicense(response.license)
: undefined;
const normalizedFeatures = response.features
? normalizeFeatures(response.features)
: undefined;
const signature = sign({
license: normalizedLicense,
features: normalizedFeatures,
error: '',
});
return new License({
license: normalizedLicense,
features: normalizedFeatures,
signature,
});
} catch (error) {
this.logger.warn(
`License information could not be obtained from Elasticsearch due to ${error} error`
);
const errorMessage = this.getErrorMessage(error);
const signature = sign({ error: errorMessage });
return new License({
error: this.getErrorMessage(error),
signature,
});
}
};
private getErrorMessage(error: ElasticsearchError): string {
if (error.status === 400) {
return 'X-Pack plugin is not installed on the Elasticsearch cluster.';
}
return error.message;
}
public async start(core: CoreStart) {}
public stop() {
this.stop$.next();
this.stop$.complete();
if (this.loggingSubscription !== undefined) {
this.loggingSubscription.unsubscribe();
this.loggingSubscription = undefined;
}
}
}