Skip to content

Commit

Permalink
Merge branch 'master' into os/restart-on-upgrade
Browse files Browse the repository at this point in the history
  • Loading branch information
jbudz committed Nov 2, 2020
2 parents ecb18c4 + 19dd9b4 commit 0600828
Show file tree
Hide file tree
Showing 285 changed files with 2,662 additions and 1,309 deletions.
80 changes: 77 additions & 3 deletions docs/developer/contributing/development-ci-metrics.asciidoc
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,10 @@

In addition to running our tests, CI collects metrics about the Kibana build. These metrics are sent to an external service to track changes over time, and to provide PR authors insights into the impact of their changes.

* <<ci-metric-types>>
* <<ci-metric-resolving-overages>>
* <<ci-metric-validating-limits>>


[[ci-metric-types]]
=== Metric types
Expand All @@ -16,7 +20,7 @@ These metrics help contributors know how they are impacting the size of the bund
[[ci-metric-page-load-bundle-size]] `page load bundle size` ::
The size of the entry file produced for each bundle/plugin. This file is always loaded on every page load, so it should be as small as possible. To reduce this metric you can put any code that isn't necessary on every page load behind an https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#Dynamic_Imports[`async import()`].
+
Code that is shared statically with other plugins will contribute to the `page load bundle size` of that plugin. This includes exports from the `public/index.ts` file and any file referenced by the `extraPublicDirs` manifest property.
Code that is shared statically with other plugins will contribute to the `page load bundle size` of that plugin. This includes exports from the `public/index.ts` file and any file referenced by the `extraPublicDirs` manifest property.

[[ci-metric-async-chunks-size]] `async chunks size` ::
An "async chunk" is created for the files imported by each https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#Dynamic_Imports[`async import()`] statement. This metric tracks the sum size of these chunks, in bytes, broken down by plugin/bundle id. You can think of this as the amount of code users will have to download if they access all the components/applications within a bundle.
Expand Down Expand Up @@ -44,7 +48,7 @@ The number of files included in the default distributable.
The number of files included in the OSS distributable.

[[ci-metric-distributable-size]] `distributable size` ::
The size, in bytes, of the default distributable. _(not reported on PRs)_
The size, in bytes, of the default distributable. _(not reported on PRs)_

[[ci-metric-oss-distributable-size]] `oss distributable size` ::
The size, in bytes, of the OSS distributable. _(not reported on PRs)_
Expand All @@ -62,4 +66,74 @@ The number of saved object fields broken down by saved object type.
[[ci-metric-adding-new-metrics]]
=== Adding new metrics

You can report new metrics by using the `CiStatsReporter` class provided by the `@kbn/dev-utils` package. This class is automatically configured on CI and its methods noop when running outside of CI. For more details checkout the {kib-repo}blob/{branch}/packages/kbn-dev-utils/src/ci_stats_reporter[`CiStatsReporter` readme].
You can report new metrics by using the `CiStatsReporter` class provided by the `@kbn/dev-utils` package. This class is automatically configured on CI and its methods noop when running outside of CI. For more details checkout the {kib-repo}blob/{branch}/packages/kbn-dev-utils/src/ci_stats_reporter[`CiStatsReporter` readme].

[[ci-metric-resolving-overages]]
=== Resolving `page load bundle size` overages

In order to prevent the page load bundles from growing unexpectedly large we limit the `page load asset size` metric for each plugin. When a PR increases this metric beyond the limit defined for that plugin in {kib-repo}blob/{branch}/packages/kbn-optimizer/limits.yml[`limits.yml`] a failed commit status is set and the PR author needs to decide how to resolve this issue before the PR can be merged.

In most cases the limit should be high enough that PRs shouldn't trigger overages, but when they do make sure it's clear what is cuasing the overage by trying the following:

1. Run the optimizer locally with the `--profile` flag to produce webpack `stats.json` files for bundles which can be inspected using a number of different online tools. Focus on the chunk named `{pluginId}.plugin.js`; the `*.chunk.js` chunks make up the `async chunks size` metric which is currently unlimited and is the main way that we {kib-repo}blob/{branch}/src/core/MIGRATION.md#keep-kibana-fast[reduce the size of page load chunks].
+
[source,shell]
-----------
node scripts/build_kibana_platform_plugins --focus {pluginid} --profile
# builds and creates {pluginDir}target/public/stats.json files for {pluginId} and any plugin it depends on
-----------

- Official Webpack tool: http://webpack.github.io/analyse/
- Webpack visualizer: https://chrisbateman.github.io/webpack-visualizer/

2. You might want to create stats for the upstream branch of your PR as well and then compare them side by side in Webpack visualizer to spot where the size difference is (using two browser tabs).

3. For relatively small changes you might be able to better understand the problem by sticking stats.json files from two different branches into https://www.scootersoftware.com/download.php[Beyond Compare]

4. If the number of changes in https://www.scootersoftware.com/download.php[Beyond Compare] are too large, you can reduce the stats.json file down to just a sorted list of module ids using https://github.com/stedolan/jq[jq]:
+
[source,shell]
-----------
jq -r .modules[].id {pluginDir}/target/public/stats.json | sort - > moduleids.txt
-----------
+
Produce a moduleids.txt file for both your branch and master and then pop them into Beyond Compare to get a very specific view of what's new.

5. As a last resort you might want to try comparing the bundle source directly. It's usually best to do this using the production source so that you're inspecting the actual change in bytes that CI is seeing. After building the distributable version of your bundle run it through prettier and then dropping it into Beyond Compare along with the chunk from upstream:
+
[source,shell]
-----------
node scripts/build_kibana_platform_plugins --focus {pluginId} --dist
npm install -g prettier
prettier -w {pluginDir}/target/public/{pluginId}.plugin.js
# repeat these steps for upstream and then compare the two {pluginId}.plugin.js files in Beyond Compare
-----------

6. If all else fails reach out to Operations for help.

Once you've identified the files which were added to the build you likely just need to stick them behind an async import as described in {kib-repo}blob/{branch}/src/core/MIGRATION.md#keep-kibana-fast[the MIGRATION.md docs].

In the case that the bundle size is not being bloated by anything obvious, but it's still larger than the limit, you can raise the limit in your PR. Do this either by editting the {kib-repo}blob/{branch}/packages/kbn-optimizer/limits.yml[`limits.yml` file] manually or by running the following to have the limit updated to the current size + 15kb

[source,shell]
-----------
node scripts/build_kibana_platform_plugins --focus {pluginId} --update-limits
-----------

This command has to run the optimizer in distributable mode so it will take a lot longer and spawn one worker for each CPU on your machine.

Changes to the {kib-repo}blob/{branch}/packages/kbn-optimizer/limits.yml[`limits.yml` file] will trigger review from the Operations team, who will attempt to verify that the size increase is justified. If you have findings you can share from the steps above that would be very helpful!

[[ci-metric-validating-limits]]
=== Validating `page load bundle size` limits

Once you've fixed any issues discovered while diagnosing overages you probably should just push the changes to your PR and let CI validate them.

If you have a pretty powerful dev machine, or the necessary patience/determination, you can validate the limits locally by running the following command:

[source,shell]
-----------
node scripts/build_kibana_platform_plugins --validate-limits
-----------

This command needs to apply production optimizations to get the right sizes, which means that the optimizer will take significantly longer to run and on most developmer machines will consume all of your machines resources for 20 minutes or more. If you'd like to multi-task while this is running you might need to limit the number of workers using the `--max-workers` flag.
12 changes: 5 additions & 7 deletions docs/user/alerting/action-types/index.asciidoc
Original file line number Diff line number Diff line change
Expand Up @@ -77,13 +77,11 @@ PUT test
"number_of_shards" : 1
},
"mappings" : {
"_doc" : {
"properties" : {
"alert_id" : { "type" : "text" },
"alert_name" : { "type" : "text" },
"alert_instance_id" : { "type" : "text" },
"context_message": { "type" : "text" }
}
"properties" : {
"alert_id" : { "type" : "text" },
"alert_name" : { "type" : "text" },
"alert_instance_id" : { "type" : "text" },
"context_message": { "type" : "text" }
}
}
}
Expand Down
34 changes: 20 additions & 14 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,10 @@
"url": "https://github.com/elastic/kibana.git"
},
"resolutions": {
"**/@hapi/iron": "^5.1.4",
"**/@types/hapi__boom": "^7.4.1",
"**/@types/hapi__hapi": "^18.2.6",
"**/@types/hapi__mimos": "4.1.0",
"**/@types/node": ">=10.17.17 <10.20.0",
"**/cross-fetch/node-fetch": "^2.6.1",
"**/deepmerge": "^4.2.2",
Expand Down Expand Up @@ -124,7 +128,16 @@
"@elastic/numeral": "^2.5.0",
"@elastic/request-crypto": "1.1.4",
"@elastic/safer-lodash-set": "0.0.0",
"@hapi/boom": "^7.4.11",
"@hapi/cookie": "^10.1.2",
"@hapi/good-squeeze": "5.2.1",
"@hapi/h2o2": "^8.3.2",
"@hapi/hapi": "^18.4.1",
"@hapi/hoek": "^8.5.1",
"@hapi/inert": "^5.2.2",
"@hapi/podium": "^3.4.3",
"@hapi/statehood": "^6.1.2",
"@hapi/vision": "^5.5.4",
"@hapi/wreck": "^15.0.2",
"@kbn/ace": "1.0.0",
"@kbn/analytics": "1.0.0",
Expand All @@ -147,7 +160,6 @@
"angular-elastic": "^2.5.1",
"angular-sanitize": "^1.8.0",
"bluebird": "3.5.5",
"boom": "^7.2.0",
"chalk": "^4.1.0",
"check-disk-space": "^2.1.0",
"chokidar": "^3.4.2",
Expand All @@ -167,15 +179,10 @@
"glob": "^7.1.2",
"glob-all": "^3.2.1",
"globby": "^8.0.1",
"h2o2": "^8.1.2",
"handlebars": "4.7.6",
"hapi": "^17.5.3",
"hapi-auth-cookie": "^9.0.0",
"hjson": "3.2.1",
"hoek": "^5.0.4",
"http-proxy-agent": "^2.1.0",
"https-proxy-agent": "^5.0.0",
"inert": "^5.1.0",
"inline-style": "^2.0.0",
"joi": "^13.5.2",
"js-yaml": "^3.14.0",
Expand Down Expand Up @@ -220,7 +227,6 @@
"tslib": "^2.0.0",
"type-detect": "^4.0.8",
"uuid": "3.3.2",
"vision": "^5.3.3",
"whatwg-fetch": "^3.0.0",
"yauzl": "^2.10.0"
},
Expand Down Expand Up @@ -274,7 +280,6 @@
"@types/archiver": "^3.1.0",
"@types/babel__core": "^7.1.10",
"@types/bluebird": "^3.1.1",
"@types/boom": "^7.2.0",
"@types/chance": "^1.0.0",
"@types/cheerio": "^0.22.10",
"@types/chromedriver": "^81.0.0",
Expand All @@ -294,14 +299,16 @@
"@types/glob": "^7.1.2",
"@types/globby": "^8.0.0",
"@types/graphql": "^0.13.2",
"@types/h2o2": "^8.1.1",
"@types/hapi": "^17.0.18",
"@types/hapi-auth-cookie": "^9.1.0",
"@types/hapi__boom": "^7.4.1",
"@types/hapi__cookie": "^10.1.1",
"@types/hapi__h2o2": "8.3.0",
"@types/hapi__hapi": "^18.2.6",
"@types/hapi__hoek": "^6.2.0",
"@types/hapi__inert": "^5.2.1",
"@types/hapi__podium": "^3.4.1",
"@types/has-ansi": "^3.0.0",
"@types/history": "^4.7.3",
"@types/hjson": "^2.4.2",
"@types/hoek": "^4.1.3",
"@types/inert": "^5.1.2",
"@types/jest": "^26.0.14",
"@types/jest-when": "^2.7.1",
"@types/joi": "^13.4.2",
Expand All @@ -326,7 +333,6 @@
"@types/opn": "^5.1.0",
"@types/pegjs": "^0.10.1",
"@types/pngjs": "^3.4.0",
"@types/podium": "^1.0.0",
"@types/prop-types": "^15.7.3",
"@types/reach__router": "^1.2.6",
"@types/react": "^16.9.36",
Expand Down
2 changes: 1 addition & 1 deletion src/core/public/public.api.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

import { Action } from 'history';
import { ApiResponse } from '@elastic/elasticsearch/lib/Transport';
import Boom from 'boom';
import Boom from '@hapi/boom';
import { ConfigPath } from '@kbn/config';
import { EnvironmentMode } from '@kbn/config';
import { EuiBreadcrumb } from '@elastic/eui';
Expand Down
2 changes: 1 addition & 1 deletion src/core/server/elasticsearch/legacy/errors.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
* under the License.
*/

import Boom from 'boom';
import Boom from '@hapi/boom';

import { LegacyElasticsearchErrorHelpers } from './errors';

Expand Down
2 changes: 1 addition & 1 deletion src/core/server/elasticsearch/legacy/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
* under the License.
*/

import Boom from 'boom';
import Boom from '@hapi/boom';
import { get } from 'lodash';

const code = Symbol('ElasticsearchError');
Expand Down
4 changes: 2 additions & 2 deletions src/core/server/http/base_path_proxy_server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,8 @@ import { Agent as HttpsAgent, ServerOptions as TlsOptions } from 'https';

import apm from 'elastic-apm-node';
import { ByteSizeValue } from '@kbn/config-schema';
import { Server, Request } from 'hapi';
import HapiProxy from 'h2o2';
import { Server, Request } from '@hapi/hapi';
import HapiProxy from '@hapi/h2o2';
import { sampleSize } from 'lodash';
import * as Rx from 'rxjs';
import { take } from 'rxjs/operators';
Expand Down
26 changes: 14 additions & 12 deletions src/core/server/http/cookie_session_storage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,10 @@
* under the License.
*/

import { Request, Server } from 'hapi';
import hapiAuthCookie from 'hapi-auth-cookie';
import { Request, Server } from '@hapi/hapi';
import hapiAuthCookie from '@hapi/cookie';
// @ts-expect-error no TS definitions
import Statehood from 'statehood';
import Statehood from '@hapi/statehood';

import { KibanaRequest, ensureRawRequest } from './router';
import { SessionStorageFactory, SessionStorage } from './session_storage';
Expand Down Expand Up @@ -80,7 +80,7 @@ class ScopedCookieSessionStorage<T extends Record<string, any>> implements Sessi
const session = await this.server.auth.test('security-cookie', this.request);
// A browser can send several cookies, if it's not an array, just return the session value
if (!Array.isArray(session)) {
return session as T;
return session.credentials as T;
}

// If we have an array with one value, we're good also
Expand Down Expand Up @@ -141,20 +141,22 @@ export async function createCookieSessionStorageFactory<T>(
await server.register({ plugin: hapiAuthCookie });

server.auth.strategy('security-cookie', 'cookie', {
cookie: cookieOptions.name,
password: cookieOptions.encryptionKey,
validateFunc: async (req, session: T | T[]) => {
cookie: {
name: cookieOptions.name,
password: cookieOptions.encryptionKey,
isSecure: cookieOptions.isSecure,
path: basePath === undefined ? '/' : basePath,
clearInvalid: false,
isHttpOnly: true,
isSameSite: cookieOptions.sameSite === 'None' ? false : cookieOptions.sameSite ?? false,
},
validateFunc: async (req: Request, session: T | T[]) => {
const result = cookieOptions.validate(session);
if (!result.isValid) {
clearInvalidCookie(req, result.path);
}
return { valid: result.isValid };
},
isSecure: cookieOptions.isSecure,
path: basePath,
clearInvalid: false,
isHttpOnly: true,
isSameSite: cookieOptions.sameSite === 'None' ? false : cookieOptions.sameSite ?? false,
});

// A hack to support SameSite: 'None'.
Expand Down
21 changes: 10 additions & 11 deletions src/core/server/http/http_server.mocks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@
* specific language governing permissions and limitations
* under the License.
*/
import { parse as parseUrl } from 'url';
import { Request } from 'hapi';
import { URL, format as formatUrl } from 'url';
import { Request } from '@hapi/hapi';
import { merge } from 'lodash';
import { Socket } from 'net';
import { stringify } from 'query-string';
Expand Down Expand Up @@ -73,7 +73,7 @@ function createKibanaRequestMock<P = any, Q = any, B = any>({
auth = { isAuthenticated: true },
}: RequestFixtureOptions<P, Q, B> = {}) {
const queryString = stringify(query, { sort: false });
const url = parseUrl(`${path}${queryString ? `?${queryString}` : ''}`);
const url = new URL(`${path}${queryString ? `?${queryString}` : ''}`, 'http://localhost');

return KibanaRequest.from<P, Q, B>(
createRawRequestMock({
Expand All @@ -87,6 +87,9 @@ function createKibanaRequestMock<P = any, Q = any, B = any>({
method,
url,
route: {
// @ts-expect-error According to types/hapi__hapi the following settings-fields have problems:
// - `auth` can't be a boolean, but it can according to the @hapi/hapi source (https://github.com/hapijs/hapi/blob/v18.4.2/lib/route.js#L139)
// - `app` isn't a valid property, but it is and this was fixed in the types in v19.0.1 (https://github.com/DefinitelyTyped/DefinitelyTyped/pull/41968)
settings: { tags: routeTags, auth: routeAuthRequired, app: kibanaRouteOptions },
},
raw: {
Expand Down Expand Up @@ -120,9 +123,11 @@ type DeepPartialObject<T> = { [P in keyof T]+?: DeepPartial<T[P]> };
function createRawRequestMock(customization: DeepPartial<Request> = {}) {
const pathname = customization.url?.pathname || '/';
const path = `${pathname}${customization.url?.search || ''}`;
const url = Object.assign({ pathname, path, href: path }, customization.url);
const url = new URL(
formatUrl(Object.assign({ pathname, path, href: path }, customization.url)),
'http://localhost'
);

// @ts-expect-error _core isn't supposed to be accessed - remove once we upgrade to hapi v18
return merge(
{},
{
Expand All @@ -140,12 +145,6 @@ function createRawRequestMock(customization: DeepPartial<Request> = {}) {
socket: {},
},
},
// TODO: Remove once we upgrade to hapi v18
_core: {
info: {
uri: 'http://localhost',
},
},
},
customization
) as Request;
Expand Down
11 changes: 7 additions & 4 deletions src/core/server/http/http_server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@
* specific language governing permissions and limitations
* under the License.
*/
import { Server } from 'hapi';
import HapiStaticFiles from 'inert';
import { Server } from '@hapi/hapi';
import HapiStaticFiles from '@hapi/inert';
import url from 'url';
import uuid from 'uuid';

Expand Down Expand Up @@ -245,8 +245,11 @@ export class HttpServer {
return;
}

this.log.debug('stopping http server');
await this.server.stop();
const hasStarted = this.server.info.started > 0;
if (hasStarted) {
this.log.debug('stopping http server');
await this.server.stop();
}
}

private getAuthOption(
Expand Down
Loading

0 comments on commit 0600828

Please sign in to comment.