Skip to content
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

plugin-ext-metrics extension for creating metrics from language plugins #6303

Merged
merged 1 commit into from
Nov 18, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ cache:
- packages/plugin-dev/node_modules
- packages/plugin-ext-vscode/node_modules
- packages/plugin-ext/node_modules
- packages/plugin-metrics/node_modules
- packages/plugin/node_modules
- packages/preferences/node_modules
- packages/preview/node_modules
Expand Down
1 change: 1 addition & 0 deletions examples/browser/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@
"@theia/plugin-dev": "^0.12.0",
"@theia/plugin-ext": "^0.12.0",
"@theia/plugin-ext-vscode": "^0.12.0",
"@theia/plugin-metrics": "^0.12.0",
"@theia/preferences": "^0.12.0",
"@theia/preview": "^0.12.0",
"@theia/process": "^0.12.0",
Expand Down
38 changes: 38 additions & 0 deletions packages/plugin-metrics/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@

# Theia Plugin Extension Metrics
This extension provides metrics for the theia plugin extension in the prometheus format.

### What Metrics it Detects
1. Detects errors in languages that are registered directly with monaco (E.g. if an error happens here: https://github.com/microsoft/vscode-extension-samples/blob/master/completions-sample/src/extension.ts#L11 it will be reported).

2. Detects errors that are logged directly to the output channel for a specific vscode extension that uses a language server. These errors can only be reported via their id that is registered with the vscode-languageclient library. E.g. "YAML Support", "XML Support", etc

### Limitations & Drawbacks
Due to the limitations of the vscode-languageclient library (see https://github.com/microsoft/vscode-languageserver-node/issues/517) we are unable to process errors that come from the language server directly, instead we need to use the output channel. The output channel is great because it allows us to work around limitations of the vscode-languageclient library and still get metrics but it still has some drawbacks:

1. Every time a language server request is resolved it counts as a success. This is because the vscode-languageclient always sends back a resolved promise even when the promise is actually rejected. The only time you can get an error is by extracting data from the output channel using a regex and connecting it back to the successes that were counted earlier. This has a few consequences:
1. If the errors logged are not matched by the regex we have no way to know where the error occured and thus we can't link the error back to a language server method. That means that the metric we created will always show that its working 100% correctly, even though it's not.

2. You need to manually add a mapping of the output channel id to the vscode extension id, otherwise when the request is logged to the output channel it doesn't know which vscode extension it should associate itself with. There is no way around this because the output channel id is registered in the vscode-languageclient library inside of the vscode extension and not in something like the vscode-extensions package.json.

### Implementation
The browser side of this extension rebinds key parts of the plugin-ext allowing us to abstract relevant metrics at certain points.

The browser then collects all these key metrics in the plugin-metrics-creator class.

Once we have all the data we want, we need to transfer the data from the frontend to the backend so that our new metrics are displayed on /metrics endpoint. This communication is done via JSON-RPC where the PluginMetrics interface acts as a way to pass information between the frontend and the backend. To learn more see [1]

The plugin-metrics-extractor will set the plugin metrics every 5 seconds [2] via pluginMetrics.setMetrics(metrics: string).

Then, every 5 seconds [2] the backend will check the plugin metrics via pluginMetrics.getMetrics() to see what the contents of the metrics are at that time.

Then, when you load up the /metrics endpoint you will see the new language metrics.

[1] - [https://www.theia-ide.org/docs/json_rpc](https://www.theia-ide.org/docs/json_rpc)

[2] - This is configurable and lives in common/metrics-protocol.ts

## License

- [Eclipse Public License 2.0](http://www.eclipse.org/legal/epl-2.0/)
- [一 (Secondary) GNU General Public License, version 2 with the GNU Classpath Exception](https://projects.eclipse.org/license/secondary-gpl-2.0-cp)
10 changes: 10 additions & 0 deletions packages/plugin-metrics/compile.tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"extends": "../../configs/base.tsconfig",
"compilerOptions": {
"rootDir": "src",
"outDir": "lib"
},
"include": [
"src"
]
}
51 changes: 51 additions & 0 deletions packages/plugin-metrics/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
{
"name": "@theia/plugin-metrics",
"version": "0.12.0",
"description": "Theia - Plugin Metrics",
"dependencies": {
"@theia/core": "^0.12.0",
"@theia/languages": "^0.12.0",
"@theia/metrics": "^0.12.0",
"@theia/plugin-ext": "^0.12.0",
"vscode-languageserver-protocol": "^3.15.0-next.8",
"@theia/plugin": "^0.12.0"
},
"publishConfig": {
"access": "public"
},
"theiaExtensions": [
{
"frontend": "lib/browser/plugin-metrics-frontend-module",
"backend": "lib/node/plugin-metrics-backend-module"
}
],
"keywords": [
"theia-extension"
],
"license": "EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0",
"repository": {
"type": "git",
"url": "https://github.com/theia-ide/theia.git"
},
"bugs": {
"url": "https://github.com/theia-ide/theia/issues"
},
"homepage": "https://github.com/theia-ide/theia",
"files": [
"lib",
"src"
],
"scripts": {
"prepare": "yarn run clean && yarn run build",
"clean": "theiaext clean",
"build": "theiaext build",
"watch": "theiaext watch",
"test": "theiaext test"
},
"devDependencies": {
"@theia/ext-scripts": "^0.12.0"
},
"nyc": {
"extends": "../../configs/nyc.json"
}
}
190 changes: 190 additions & 0 deletions packages/plugin-metrics/src/browser/plugin-metrics-creator.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,190 @@
/********************************************************************************
* Copyright (C) 2019 Red Hat, Inc. and others.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* This Source Code may also be made available under the following Secondary
* Licenses when the conditions for such availability set forth in the Eclipse
* Public License v. 2.0 are satisfied: GNU General Public License, version 2
* with the GNU Classpath Exception which is available at
* https://www.gnu.org/software/classpath/license.html.
*
* SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
********************************************************************************/

import { inject, injectable } from 'inversify';
import { PluginMetrics, METRICS_TIMEOUT } from '../common/metrics-protocol';
import { AnalyticsFromRequests, DataFromRequest, createRequestData, createDefaultAnalytics, MetricsMap } from '../common/plugin-metrics-types';

@injectable()
export class PluginMetricsCreator {

@inject(PluginMetrics)
private pluginMetrics: PluginMetrics;

private _extensionIDAnalytics: MetricsMap;

private NODE_BASED_REGEX = /(?<=Request)(.*?)(?=failed)/;
Copy link
Member

@paul-marechal paul-marechal Nov 19, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why not /Request(.*)failed/?


constructor() {
this.setPluginMetrics();
this._extensionIDAnalytics = {};
}

/**
* Create an error metric for requestData.pluginID by attempting to extract the erroring
* language server method from the requestData.errorContentsOrMethod. If it cannot extract the
* error language server method from requestData.errorContentsOrMethod then it will not
* create a metric.
*
* @param pluginID The id of the plugin
* @param errorContents The contents that the langauge server error has produced
*/
async createErrorMetric(requestData: DataFromRequest): Promise<void> {
if (!requestData.pluginID) {
return;
}

const method = this.extractMethodFromValue(requestData.errorContentsOrMethod);

// only log the metric if we can find the method that it occured in
if (method) {
const createdMetric = createRequestData(requestData.pluginID, method, requestData.timeTaken);
this.createMetric(createdMetric, false);

this.decreaseExtensionRequests(requestData.pluginID, method);
}
}

/**
* Decreases the total requests and the successful responses for pluginID with method by 1.
*
* This is needed because an error and a successful language server request aren't currently
* associated together because of https://github.com/microsoft/vscode-languageserver-node/issues/517.
* That means that every language server request that resolves counts as a successful language server request.
* Therefore, we need to decrease the extension requests for pluginID when we know there is an error.
* Otherwise, for every language server request that errors we would count it as both a success and a failure.
*
* @param pluginID The id of the plugin that should have the decreased requests
*/
private decreaseExtensionRequests(pluginID: string, method: string): void {
const thisExtension = this._extensionIDAnalytics[pluginID];
if (thisExtension) {
const currentAnalytics = thisExtension[method];
if (currentAnalytics) {
currentAnalytics.totalRequests -= 1;
currentAnalytics.succesfulResponses -= 1;
}
}
}

/**
* Update the internal metrics structure for pluginID with method when a request is made
*
* @param requestData The data from the request that was made
* @param isRequestSuccessful If the language server request was successful or not
*/
async createMetric(requestData: DataFromRequest, isRequestSuccessful: boolean): Promise<void> {
if (!requestData.pluginID) {
return;
}

// When we are in this function we know its a method so we can make it clearer
const method = requestData.errorContentsOrMethod;
const defaultAnalytic = createDefaultAnalytics(requestData.timeTaken, isRequestSuccessful);

this.createExtensionIDAnalyticIfNotFound(requestData, defaultAnalytic);
this.createExtensionIDMethodIfNotFound(requestData, defaultAnalytic);

const thisExtension = this._extensionIDAnalytics[requestData.pluginID];
if (thisExtension) {
const currentAnalytic = thisExtension[method];
if (currentAnalytic) {
currentAnalytic.totalRequests += 1;
if (isRequestSuccessful) {
currentAnalytic.succesfulResponses += 1;
}
if (isRequestSuccessful) {
currentAnalytic.sumOfTimeForSuccess = currentAnalytic.sumOfTimeForSuccess + requestData.timeTaken;
} else {
currentAnalytic.sumOfTimeForFailure = currentAnalytic.sumOfTimeForFailure + requestData.timeTaken;
}
}
}
}

/**
* Create an entry in _extensionIDAnalytics with createdAnalytic if there does not exist one
*
* @param requestData data that we will turn into metrics
* @param createdAnalytic the analytic being created
*/
private createExtensionIDAnalyticIfNotFound(requestData: DataFromRequest, createdAnalytic: AnalyticsFromRequests): void {
const method = requestData.errorContentsOrMethod; // We know its a metric if this is being called

if (!this._extensionIDAnalytics[requestData.pluginID]) {
this._extensionIDAnalytics[requestData.pluginID] = {
[method]: createdAnalytic
};
}
}

/**
* Create an entry in _extensionIDAnalytics for requestData.pluginID with requestData.errorContentsOrMethod as the method
* if there does not exist one
*
* @param requestData data that we will turn into metrics
* @param createdAnalytic the analytic being created
*/
private createExtensionIDMethodIfNotFound(requestData: DataFromRequest, createdAnalytic: AnalyticsFromRequests): void {
const method = requestData.errorContentsOrMethod; // We know its a metric if this is being called

if (this._extensionIDAnalytics[requestData.pluginID]) {
const methodToAnalyticMap = this._extensionIDAnalytics[requestData.pluginID];
if (!methodToAnalyticMap[method]) {
methodToAnalyticMap[method] = createdAnalytic;
}
}
}

/**
* setPluginMetrics is a constant running function that sets
* pluginMetrics every {$METRICS_TIMEOUT} seconds so that it doesn't
* update /metrics on every request
*/
private setPluginMetrics(): void {
const self = this;
setInterval(() => {
if (Object.keys(self._extensionIDAnalytics).length !== 0) {
self.pluginMetrics.setMetrics(JSON.stringify(self._extensionIDAnalytics));
}
}, METRICS_TIMEOUT);
}

// Map of plugin extension id to method to analytic
get extensionIDAnalytics(): MetricsMap {
return this._extensionIDAnalytics;
}

/**
* Attempts to extract the method name from the current errorContents using the
* vscode-languageclient matching regex.
*
* If it cannot find a match in the errorContents it returns undefined
*
* @param errorContents The contents of the current error or undefined
*/
private extractMethodFromValue(errorContents: string | undefined): string | undefined {
if (!errorContents) {
return undefined;
}
const matches = errorContents.match(this.NODE_BASED_REGEX);
if (matches) {
return matches[0].trim();
}
return undefined;
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
/********************************************************************************
* Copyright (C) 2019 Red Hat and others.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* This Source Code may also be made available under the following Secondary
* Licenses when the conditions for such availability set forth in the Eclipse
* Public License v. 2.0 are satisfied: GNU General Public License, version 2
* with the GNU Classpath Exception which is available at
* https://www.gnu.org/software/classpath/license.html.
*
* SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
********************************************************************************/

import { ContainerModule } from 'inversify';
import { LanguagesMainPluginMetrics } from './plugin-metrics-languages-main';
import { PluginMetrics, metricsJsonRpcPath } from '../common/metrics-protocol';
import { WebSocketConnectionProvider } from '@theia/core/lib/browser/messaging/ws-connection-provider';
import { PluginMetricsCreator } from './plugin-metrics-creator';
import { PluginMetricsResolver } from './plugin-metrics-resolver';
import { PluginMetricsOutputChannelRegistry } from './plugin-metrics-output-registry';
import { LanguagesMainImpl } from '@theia/plugin-ext/lib/main/browser/languages-main';
import { OutputChannelRegistryMainImpl } from '@theia/plugin-ext/lib/main/browser/output-channel-registry-main';

export default new ContainerModule((bind, unbind, isBound, rebind) => {
bind(PluginMetricsResolver).toSelf().inSingletonScope();
bind(PluginMetricsCreator).toSelf().inSingletonScope();

rebind(LanguagesMainImpl).to(LanguagesMainPluginMetrics).inTransientScope();
rebind(OutputChannelRegistryMainImpl).to(PluginMetricsOutputChannelRegistry).inTransientScope();

bind(PluginMetrics).toDynamicValue(ctx => {
const connection = ctx.container.get(WebSocketConnectionProvider);
return connection.createProxy<PluginMetrics>(metricsJsonRpcPath);
}).inSingletonScope();
});
Loading