-
Notifications
You must be signed in to change notification settings - Fork 8.3k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[licensing] add license fetcher cache #170006
Merged
Merged
Changes from 10 commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
b83bb70
add license fetcher cache
pgayvallet 495063d
add tests
pgayvallet ad406c7
Merge remote-tracking branch 'upstream/main' into kbn-xxx-licensing-c…
pgayvallet ba7583f
[CI] Auto-commit changed files from 'node scripts/lint_ts_projects --…
kibanamachine 41660c7
add debounce time for manual refreshes
pgayvallet a067f59
fix unit tests
pgayvallet de59e94
Merge remote-tracking branch 'upstream/main' into kbn-xxx-licensing-c…
pgayvallet e3ada35
debounce wasn't it
pgayvallet 61c99ff
using throttle with leading and trailing
pgayvallet 3cf2735
Merge remote-tracking branch 'upstream/main' into kbn-xxx-licensing-c…
pgayvallet 26daccb
remove explicit default
pgayvallet File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
172 changes: 172 additions & 0 deletions
172
x-pack/plugins/licensing/server/license_fetcher.test.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,172 @@ | ||
/* | ||
* 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 type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; | ||
import { getLicenseFetcher } from './license_fetcher'; | ||
import { loggerMock, type MockedLogger } from '@kbn/logging-mocks'; | ||
import { elasticsearchServiceMock } from '@kbn/core/server/mocks'; | ||
|
||
type EsLicense = estypes.XpackInfoMinimalLicenseInformation; | ||
|
||
const delay = (ms: number) => new Promise((res) => setTimeout(res, ms)); | ||
|
||
function buildRawLicense(options: Partial<EsLicense> = {}): EsLicense { | ||
return { | ||
uid: 'uid-000000001234', | ||
status: 'active', | ||
type: 'basic', | ||
mode: 'basic', | ||
expiry_date_in_millis: 1000, | ||
...options, | ||
}; | ||
} | ||
|
||
describe('LicenseFetcher', () => { | ||
let logger: MockedLogger; | ||
let clusterClient: ReturnType<typeof elasticsearchServiceMock.createClusterClient>; | ||
|
||
beforeEach(() => { | ||
logger = loggerMock.create(); | ||
clusterClient = elasticsearchServiceMock.createClusterClient(); | ||
}); | ||
|
||
it('returns the license for successful calls', async () => { | ||
clusterClient.asInternalUser.xpack.info.mockResponse({ | ||
license: buildRawLicense({ | ||
uid: 'license-1', | ||
}), | ||
features: {}, | ||
} as any); | ||
|
||
const fetcher = getLicenseFetcher({ | ||
logger, | ||
clusterClient, | ||
cacheDurationMs: 50_000, | ||
}); | ||
|
||
const license = await fetcher(); | ||
expect(license.uid).toEqual('license-1'); | ||
}); | ||
|
||
it('returns the latest license for successful calls', async () => { | ||
clusterClient.asInternalUser.xpack.info | ||
.mockResponseOnce({ | ||
license: buildRawLicense({ | ||
uid: 'license-1', | ||
}), | ||
features: {}, | ||
} as any) | ||
.mockResponseOnce({ | ||
license: buildRawLicense({ | ||
uid: 'license-2', | ||
}), | ||
features: {}, | ||
} as any); | ||
|
||
const fetcher = getLicenseFetcher({ | ||
logger, | ||
clusterClient, | ||
cacheDurationMs: 50_000, | ||
}); | ||
|
||
let license = await fetcher(); | ||
expect(license.uid).toEqual('license-1'); | ||
|
||
license = await fetcher(); | ||
expect(license.uid).toEqual('license-2'); | ||
}); | ||
|
||
it('returns an error license in case of error', async () => { | ||
clusterClient.asInternalUser.xpack.info.mockResponseImplementation(() => { | ||
throw new Error('woups'); | ||
}); | ||
|
||
const fetcher = getLicenseFetcher({ | ||
logger, | ||
clusterClient, | ||
cacheDurationMs: 50_000, | ||
}); | ||
|
||
const license = await fetcher(); | ||
expect(license.error).toEqual('woups'); | ||
}); | ||
|
||
it('returns a license successfully fetched after an error', async () => { | ||
clusterClient.asInternalUser.xpack.info | ||
.mockResponseImplementationOnce(() => { | ||
throw new Error('woups'); | ||
}) | ||
.mockResponseOnce({ | ||
license: buildRawLicense({ | ||
uid: 'license-1', | ||
}), | ||
features: {}, | ||
} as any); | ||
|
||
const fetcher = getLicenseFetcher({ | ||
logger, | ||
clusterClient, | ||
cacheDurationMs: 50_000, | ||
}); | ||
|
||
let license = await fetcher(); | ||
expect(license.error).toEqual('woups'); | ||
license = await fetcher(); | ||
expect(license.uid).toEqual('license-1'); | ||
}); | ||
|
||
it('returns the latest fetched license after an error within the cache duration period', async () => { | ||
clusterClient.asInternalUser.xpack.info | ||
.mockResponseOnce({ | ||
license: buildRawLicense({ | ||
uid: 'license-1', | ||
}), | ||
features: {}, | ||
} as any) | ||
.mockResponseImplementationOnce(() => { | ||
throw new Error('woups'); | ||
}); | ||
|
||
const fetcher = getLicenseFetcher({ | ||
logger, | ||
clusterClient, | ||
cacheDurationMs: 50_000, | ||
}); | ||
|
||
let license = await fetcher(); | ||
expect(license.uid).toEqual('license-1'); | ||
license = await fetcher(); | ||
expect(license.uid).toEqual('license-1'); | ||
}); | ||
|
||
it('returns an error license after an error exceeding the cache duration period', async () => { | ||
clusterClient.asInternalUser.xpack.info | ||
.mockResponseOnce({ | ||
license: buildRawLicense({ | ||
uid: 'license-1', | ||
}), | ||
features: {}, | ||
} as any) | ||
.mockResponseImplementationOnce(() => { | ||
throw new Error('woups'); | ||
}); | ||
|
||
const fetcher = getLicenseFetcher({ | ||
logger, | ||
clusterClient, | ||
cacheDurationMs: 1, | ||
}); | ||
|
||
let license = await fetcher(); | ||
expect(license.uid).toEqual('license-1'); | ||
|
||
await delay(50); | ||
|
||
license = await fetcher(); | ||
expect(license.error).toEqual('woups'); | ||
}); | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,133 @@ | ||
/* | ||
* 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 type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; | ||
import { createHash } from 'crypto'; | ||
import stringify from 'json-stable-stringify'; | ||
import type { MaybePromise } from '@kbn/utility-types'; | ||
import { isPromise } from '@kbn/std'; | ||
import type { IClusterClient, Logger } from '@kbn/core/server'; | ||
import type { | ||
ILicense, | ||
PublicLicense, | ||
PublicFeatures, | ||
LicenseType, | ||
LicenseStatus, | ||
} from '../common/types'; | ||
import { License } from '../common/license'; | ||
import type { ElasticsearchError, LicenseFetcher } from './types'; | ||
|
||
export const getLicenseFetcher = ({ | ||
clusterClient, | ||
logger, | ||
cacheDurationMs, | ||
}: { | ||
clusterClient: MaybePromise<IClusterClient>; | ||
logger: Logger; | ||
cacheDurationMs: number; | ||
}): LicenseFetcher => { | ||
let currentLicense: ILicense | undefined; | ||
let lastSuccessfulFetchTime: number | undefined; | ||
|
||
return async () => { | ||
const client = isPromise(clusterClient) ? await clusterClient : clusterClient; | ||
try { | ||
const response = await client.asInternalUser.xpack.info(undefined, { maxRetries: 3 }); | ||
const normalizedLicense = | ||
response.license && response.license.type !== 'missing' | ||
? normalizeServerLicense(response.license) | ||
: undefined; | ||
const normalizedFeatures = response.features | ||
? normalizeFeatures(response.features) | ||
: undefined; | ||
|
||
const signature = sign({ | ||
license: normalizedLicense, | ||
features: normalizedFeatures, | ||
error: '', | ||
}); | ||
|
||
currentLicense = new License({ | ||
license: normalizedLicense, | ||
features: normalizedFeatures, | ||
signature, | ||
}); | ||
lastSuccessfulFetchTime = Date.now(); | ||
|
||
return currentLicense; | ||
} catch (error) { | ||
logger.warn( | ||
`License information could not be obtained from Elasticsearch due to ${error} error` | ||
); | ||
|
||
if (lastSuccessfulFetchTime && lastSuccessfulFetchTime + cacheDurationMs > Date.now()) { | ||
return currentLicense!; | ||
} else { | ||
const errorMessage = getErrorMessage(error); | ||
const signature = sign({ error: errorMessage }); | ||
|
||
return new License({ | ||
error: getErrorMessage(error), | ||
signature, | ||
}); | ||
} | ||
} | ||
}; | ||
}; | ||
|
||
function normalizeServerLicense( | ||
license: estypes.XpackInfoMinimalLicenseInformation | ||
): PublicLicense { | ||
return { | ||
uid: license.uid, | ||
type: license.type as LicenseType, | ||
mode: license.mode as LicenseType, | ||
expiryDateInMillis: | ||
typeof license.expiry_date_in_millis === 'string' | ||
? parseInt(license.expiry_date_in_millis, 10) | ||
: license.expiry_date_in_millis, | ||
status: license.status as LicenseStatus, | ||
}; | ||
} | ||
|
||
function normalizeFeatures(rawFeatures: estypes.XpackInfoFeatures) { | ||
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'); | ||
} | ||
|
||
function getErrorMessage(error: ElasticsearchError): string { | ||
if (error.status === 400) { | ||
return 'X-Pack plugin is not installed on the Elasticsearch cluster.'; | ||
} | ||
return error.message; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Just noticed
maxRetries: 3
wasn't part of the old code, so IIUC we're now askingelasticsearch-js
to retry 3 times in a row before actually reporting error 👍🏼That's already an improvement, but I wonder if we could have a more resilient strategy using exponential backoff and perhaps a few more retries (5?). That would probably cover https://github.com/elastic/sdh-kibana/issues/4194 already.
Don't want to block the PR on this, it can be tackled with a separate issue.
I also agree that ES probably shouldn't report itself as available if the
GET /_xpack
API is not.We can investigate/confirm if that's the case.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
It's actually the default value of the option. I'm not sure why I added it tbh, I think I wanted it to be more explicit. I should just remove it for now.