From 59b95c48bc489cc2d67884ecdf661156f1518446 Mon Sep 17 00:00:00 2001 From: Josh Pinkney Date: Tue, 1 Oct 2019 09:17:54 -0400 Subject: [PATCH] Created plugin-ext-metrics for creating metrics from language plugins --- .travis.yml | 1 + examples/browser/package.json | 1 + packages/plugin-ext-metrics/.gitignore | 25 ++ packages/plugin-ext-metrics/README.md | 38 +++ .../plugin-ext-metrics/compile.tsconfig.json | 10 + packages/plugin-ext-metrics/package.json | 48 +++ .../plugin-ext-metrics/src/browser/index.ts | 15 + .../plugin-metrics-success-output.ts | 31 ++ .../plugin-metrics-time-output.ts | 29 ++ .../src/browser/plugin-metrics-creator.ts | 216 ++++++++++++ .../browser/plugin-metrics-frontend-module.ts | 38 +++ .../src/browser/plugin-metrics-interfaces.ts | 72 ++++ .../browser/plugin-metrics-languages-main.ts | 319 ++++++++++++++++++ .../browser/plugin-metrics-output-registry.ts | 64 ++++ .../src/browser/plugin-metrics-resolver.ts | 78 +++++ .../plugin-ext-metrics/src/common/index.ts | 15 + .../src/common/metrics-protocol.ts | 27 ++ .../node/plugin-ext-metrics-backend-module.ts | 34 ++ .../src/node/plugin-metrics-handler.ts | 38 +++ .../src/node/plugin-metrics.ts | 38 +++ yarn.lock | 18 + 21 files changed, 1155 insertions(+) create mode 100644 packages/plugin-ext-metrics/.gitignore create mode 100644 packages/plugin-ext-metrics/README.md create mode 100644 packages/plugin-ext-metrics/compile.tsconfig.json create mode 100644 packages/plugin-ext-metrics/package.json create mode 100644 packages/plugin-ext-metrics/src/browser/index.ts create mode 100644 packages/plugin-ext-metrics/src/browser/metric-output/plugin-metrics-success-output.ts create mode 100644 packages/plugin-ext-metrics/src/browser/metric-output/plugin-metrics-time-output.ts create mode 100644 packages/plugin-ext-metrics/src/browser/plugin-metrics-creator.ts create mode 100644 packages/plugin-ext-metrics/src/browser/plugin-metrics-frontend-module.ts create mode 100644 packages/plugin-ext-metrics/src/browser/plugin-metrics-interfaces.ts create mode 100644 packages/plugin-ext-metrics/src/browser/plugin-metrics-languages-main.ts create mode 100644 packages/plugin-ext-metrics/src/browser/plugin-metrics-output-registry.ts create mode 100644 packages/plugin-ext-metrics/src/browser/plugin-metrics-resolver.ts create mode 100644 packages/plugin-ext-metrics/src/common/index.ts create mode 100644 packages/plugin-ext-metrics/src/common/metrics-protocol.ts create mode 100644 packages/plugin-ext-metrics/src/node/plugin-ext-metrics-backend-module.ts create mode 100644 packages/plugin-ext-metrics/src/node/plugin-metrics-handler.ts create mode 100644 packages/plugin-ext-metrics/src/node/plugin-metrics.ts diff --git a/.travis.yml b/.travis.yml index ae66617cf37ce..c579a2055e0dd 100644 --- a/.travis.yml +++ b/.travis.yml @@ -46,6 +46,7 @@ cache: - packages/outline-view/node_modules - packages/output/node_modules - packages/plugin-dev/node_modules + - packages/plugin-ext-metrics/node_modules - packages/plugin-ext-vscode/node_modules - packages/plugin-ext/node_modules - packages/plugin/node_modules diff --git a/examples/browser/package.json b/examples/browser/package.json index 52624e0e866ef..212a9ee5317a1 100644 --- a/examples/browser/package.json +++ b/examples/browser/package.json @@ -43,6 +43,7 @@ "@theia/output": "^0.11.0", "@theia/plugin-dev": "^0.11.0", "@theia/plugin-ext": "^0.11.0", + "@theia/plugin-ext-metrics": "^0.11.0", "@theia/plugin-ext-vscode": "^0.11.0", "@theia/preferences": "^0.11.0", "@theia/preview": "^0.11.0", diff --git a/packages/plugin-ext-metrics/.gitignore b/packages/plugin-ext-metrics/.gitignore new file mode 100644 index 0000000000000..ac180b8954dd6 --- /dev/null +++ b/packages/plugin-ext-metrics/.gitignore @@ -0,0 +1,25 @@ +.DS_Store +node_modules +build +lib +*.log +.idea +.metadata +*.iml +jdt.ls-java-project +lerna-debug.log +.nyc_output +coverage +errorShots +examples/*/src-gen +examples/*/webpack.config.js +.browser_modules +**/docs/api +package-backup.json +.history +.Trash-* +packages/plugin/typedoc +plugins +gh-pages +.vscode/ipch +dev-packages/electron/compile_commands.json diff --git a/packages/plugin-ext-metrics/README.md b/packages/plugin-ext-metrics/README.md new file mode 100644 index 0000000000000..09a063c3bc03a --- /dev/null +++ b/packages/plugin-ext-metrics/README.md @@ -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. Everytime a language server request is resolve 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 extracing 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 its not. This is why we currently cannot get metrics for the vscode-java extension (it uses a non-standard output format). + +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 display on /metrics endpoint. This communication is done via JSON-RPC where the PluginMetrics interface acts as as common 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) diff --git a/packages/plugin-ext-metrics/compile.tsconfig.json b/packages/plugin-ext-metrics/compile.tsconfig.json new file mode 100644 index 0000000000000..a23513b5e6b13 --- /dev/null +++ b/packages/plugin-ext-metrics/compile.tsconfig.json @@ -0,0 +1,10 @@ +{ + "extends": "../../configs/base.tsconfig", + "compilerOptions": { + "rootDir": "src", + "outDir": "lib" + }, + "include": [ + "src" + ] +} diff --git a/packages/plugin-ext-metrics/package.json b/packages/plugin-ext-metrics/package.json new file mode 100644 index 0000000000000..4aa1b6ccd587b --- /dev/null +++ b/packages/plugin-ext-metrics/package.json @@ -0,0 +1,48 @@ +{ + "name": "@theia/plugin-ext-metrics", + "version": "0.11.0", + "description": "Theia - Plugin Extension Metrics", + "dependencies": { + "@theia/core": "^0.11.0", + "@theia/languages": "^0.11.0", + "@theia/metrics": "^0.11.0", + "@theia/plugin-ext": "^0.11.0", + "vscode-languageserver-protocol": "^3.14.1", + "@theia/plugin": "^0.11.0" + }, + "publishConfig": { + "access": "public" + }, + "theiaExtensions": [ + { + "frontend": "lib/browser/plugin-metrics-frontend-module", + "backend": "lib/node/plugin-ext-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" + }, + "nyc": { + "extends": "../../configs/nyc.json" + } +} diff --git a/packages/plugin-ext-metrics/src/browser/index.ts b/packages/plugin-ext-metrics/src/browser/index.ts new file mode 100644 index 0000000000000..73f42cf64d106 --- /dev/null +++ b/packages/plugin-ext-metrics/src/browser/index.ts @@ -0,0 +1,15 @@ +/******************************************************************************** + * 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 + ********************************************************************************/ diff --git a/packages/plugin-ext-metrics/src/browser/metric-output/plugin-metrics-success-output.ts b/packages/plugin-ext-metrics/src/browser/metric-output/plugin-metrics-success-output.ts new file mode 100644 index 0000000000000..92d5b4956e7c1 --- /dev/null +++ b/packages/plugin-ext-metrics/src/browser/metric-output/plugin-metrics-success-output.ts @@ -0,0 +1,31 @@ +/******************************************************************************** + * 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 { MetricOutput, AnalyticsFromRequests } from '../plugin-metrics-interfaces'; + +export class PluginMetricSuccessOutput implements MetricOutput { + + public header = '# HELP language_server_success_metrics Percentage of successful language requests\n# TYPE language_server_success_metrics gauge\n'; + + createMetricOutput(id: string, method: string, requestAnalytics: AnalyticsFromRequests): string { + if (requestAnalytics.succesfulResponses < 0) { + requestAnalytics.succesfulResponses = 0; + } + const percentageOfSuccess = ((requestAnalytics.succesfulResponses / requestAnalytics.totalRequests) * 100); + return `language_server_success_metrics{id="${id}" method="${method}"} ${percentageOfSuccess}\n`; + } + +} diff --git a/packages/plugin-ext-metrics/src/browser/metric-output/plugin-metrics-time-output.ts b/packages/plugin-ext-metrics/src/browser/metric-output/plugin-metrics-time-output.ts new file mode 100644 index 0000000000000..5fc3e1f12996f --- /dev/null +++ b/packages/plugin-ext-metrics/src/browser/metric-output/plugin-metrics-time-output.ts @@ -0,0 +1,29 @@ +/******************************************************************************** + * 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 { MetricOutput, AnalyticsFromRequests } from '../plugin-metrics-interfaces'; + +export class PluginMetricTimeOutput implements MetricOutput { + + public header = + '# HELP language_server_time_metrics Number of milliseconds it takes on average for a language server request\n# TYPE language_server_time_metrics gauge\n'; + + createMetricOutput(id: string, method: string, requestAnalytics: AnalyticsFromRequests): string { + const avgTime = requestAnalytics.avgTimeTaken; + return `language_server_time_metrics{id="${id}" method="${method}"} ${avgTime}\n`; + } + +} diff --git a/packages/plugin-ext-metrics/src/browser/plugin-metrics-creator.ts b/packages/plugin-ext-metrics/src/browser/plugin-metrics-creator.ts new file mode 100644 index 0000000000000..e70406684f47a --- /dev/null +++ b/packages/plugin-ext-metrics/src/browser/plugin-metrics-creator.ts @@ -0,0 +1,216 @@ +/******************************************************************************** + * 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 } from './plugin-metrics-interfaces'; +import { PluginMetricSuccessOutput } from './metric-output/plugin-metrics-success-output'; +import { PluginMetricTimeOutput } from './metric-output/plugin-metrics-time-output'; + +@injectable() +export class PluginMetricsCreator { + + @inject(PluginMetrics) + private pluginMetrics: PluginMetrics; + + private _extensionIDAnalytics = new Map>(); + + private NODE_BASED_REGEX = /(?<=Request)(.*?)(?=failed)/; + + private pluginMetricsSuccessOutput: PluginMetricSuccessOutput; + private pluginMetricsTimeOutput: PluginMetricTimeOutput; + + constructor() { + this.setPluginMetrics(); + + this.pluginMetricsSuccessOutput = new PluginMetricSuccessOutput(); + this.pluginMetricsTimeOutput = new PluginMetricTimeOutput(); + } + + /** + * 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 { + 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.get(pluginID); + if (thisExtension) { + const currentAnalytics = thisExtension.get(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 { + 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); + + this.createExtensionIDAnalyticIfNotFound(requestData, defaultAnalytic); + this.createExtensionIDMethodIfNotFound(requestData, defaultAnalytic); + + const thisExtension = this._extensionIDAnalytics.get(requestData.pluginID); + if (thisExtension) { + const currentAnalytic = thisExtension.get(method); + if (currentAnalytic) { + currentAnalytic.totalRequests += 1; + if (isRequestSuccessful) { + currentAnalytic.succesfulResponses += 1; + } + currentAnalytic.avgTimeTaken = this.calculateAvgTime(currentAnalytic, 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.has(requestData.pluginID)) { + this._extensionIDAnalytics.set(requestData.pluginID, new Map().set(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.has(requestData.pluginID)) { + const methodToAnalyticMap = this._extensionIDAnalytics.get(requestData.pluginID) as Map; + if (!methodToAnalyticMap.has(method)) { + methodToAnalyticMap.set(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 { + setInterval(() => { + if (this._extensionIDAnalytics.size !== 0) { + + let metricString = this.pluginMetricsSuccessOutput.header; + this._extensionIDAnalytics.forEach((value, key) => { + value.forEach((analytic, method) => { + metricString += this.pluginMetricsSuccessOutput.createMetricOutput(key, method, analytic); + }); + }); + + metricString += this.pluginMetricsTimeOutput.header; + this._extensionIDAnalytics.forEach((value, key) => { + value.forEach((analytic, method) => { + metricString += this.pluginMetricsTimeOutput.createMetricOutput(key, method, analytic); + }); + }); + + this.pluginMetrics.setMetrics(metricString); + + } + }, METRICS_TIMEOUT); + } + + // Map of plugin extension id to method to analytic + get extensionIDAnalytics(): Map> { + 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; + } + + /** + * Calculate the average time it takes for all the requests to be made + * + * @param currentAnalytics The current analytics + * @param time the time it took for the current request to complete + */ + private calculateAvgTime(currentAnalytics: AnalyticsFromRequests, time: number): number { + return (((currentAnalytics.totalRequests - 1) * currentAnalytics.avgTimeTaken) + time) / currentAnalytics.totalRequests; + } + +} diff --git a/packages/plugin-ext-metrics/src/browser/plugin-metrics-frontend-module.ts b/packages/plugin-ext-metrics/src/browser/plugin-metrics-frontend-module.ts new file mode 100644 index 0000000000000..c652ffc636928 --- /dev/null +++ b/packages/plugin-ext-metrics/src/browser/plugin-metrics-frontend-module.ts @@ -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(metricsJsonRpcPath); + }).inSingletonScope(); +}); diff --git a/packages/plugin-ext-metrics/src/browser/plugin-metrics-interfaces.ts b/packages/plugin-ext-metrics/src/browser/plugin-metrics-interfaces.ts new file mode 100644 index 0000000000000..ce054531c2097 --- /dev/null +++ b/packages/plugin-ext-metrics/src/browser/plugin-metrics-interfaces.ts @@ -0,0 +1,72 @@ +/******************************************************************************** + * 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 + ********************************************************************************/ + +// Define common interfaces that multiple classes can use + +export interface AnalyticsFromRequests { + totalRequests: number; + succesfulResponses: number; + avgTimeTaken: number; +} + +export interface DataFromRequest { + pluginID: string; + errorContentsOrMethod: string; + timeTaken: number; +} + +export interface MetricOutput { + header: string; + createMetricOutput(pluginID: string, method: string, requestAnalytics: AnalyticsFromRequests): string; +} + +/** + * Helper functions for creating an object that corresponds to the DataFromRequest interface + */ +export function createRequestData(pluginID: string, errorContentsOrMethod: string, timeTaken: number): DataFromRequest { + return { + pluginID, + errorContentsOrMethod, + timeTaken + }; +} + +export function createDefaultRequestData(pluginID: string, errorContentsOrMethod: string): DataFromRequest { + return { + pluginID, + errorContentsOrMethod, + timeTaken: 0 + }; +} + +/** + * Helper functions for creating an object that corresponds to the AnalyticsFromRequests interface + */ +export function createAnalytics(totalRequests: number, succesfulResponses: number, avgTimeTaken: number): AnalyticsFromRequests { + return { + avgTimeTaken, + succesfulResponses, + totalRequests + }; +} + +export function createDefaultAnalytics(avgTimeTaken: number): AnalyticsFromRequests { + return { + avgTimeTaken, + succesfulResponses: 0, + totalRequests: 0 + }; +} diff --git a/packages/plugin-ext-metrics/src/browser/plugin-metrics-languages-main.ts b/packages/plugin-ext-metrics/src/browser/plugin-metrics-languages-main.ts new file mode 100644 index 0000000000000..5b2b02dfa1af6 --- /dev/null +++ b/packages/plugin-ext-metrics/src/browser/plugin-metrics-languages-main.ts @@ -0,0 +1,319 @@ +/******************************************************************************** + * 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 { Range, WorkspaceSymbolParams } from '@theia/plugin-ext/lib/common/plugin-api-rpc-model'; +import { PluginMetricsResolver } from './plugin-metrics-resolver'; +import { LanguagesMainImpl } from '@theia/plugin-ext/lib/main/browser/languages-main'; +import { SymbolInformation } from '@theia/languages/lib/browser'; +import { injectable, inject } from 'inversify'; +import * as vst from 'vscode-languageserver-protocol'; +import { PluginInfo } from '@theia/plugin-ext/lib/common/plugin-api-rpc'; +import { SerializedDocumentFilter } from '@theia/plugin-ext/lib/common/plugin-api-rpc-model'; +import * as theia from '@theia/plugin'; + +@injectable() +export class LanguagesMainPluginMetrics extends LanguagesMainImpl { + + @inject(PluginMetricsResolver) + private pluginMetricsResolver: PluginMetricsResolver; + + // Map of handle to extension id + protected handleToExtensionID = new Map(); + + protected provideCompletionItems(handle: number, model: monaco.editor.ITextModel, position: monaco.Position, + context: monaco.languages.CompletionContext, token: monaco.CancellationToken): monaco.languages.ProviderResult { + return this.pluginMetricsResolver.resolveRequest(this.handleToExtensionName(handle), + vst.CompletionRequest.type.method, + super.provideCompletionItems(handle, model, position, context, token)); + } + + protected resolveCompletionItem(handle: number, model: monaco.editor.ITextModel, position: monaco.Position, + item: monaco.languages.CompletionItem, token: monaco.CancellationToken): monaco.languages.ProviderResult { + return this.pluginMetricsResolver.resolveRequest(this.handleToExtensionName(handle), + vst.CompletionRequest.type.method, + super.resolveCompletionItem(handle, model, position, item, token)); + } + + protected provideReferences(handle: number, model: monaco.editor.ITextModel, position: monaco.Position, + context: monaco.languages.ReferenceContext, token: monaco.CancellationToken): monaco.languages.ProviderResult { + return this.pluginMetricsResolver.resolveRequest(this.handleToExtensionName(handle), + vst.ReferencesRequest.type.method, + super.provideReferences(handle, model, position, context, token)); + } + + protected provideImplementation(handle: number, model: monaco.editor.ITextModel, + position: monaco.Position, token: monaco.CancellationToken): monaco.languages.ProviderResult { + return this.pluginMetricsResolver.resolveRequest(this.handleToExtensionName(handle), + vst.ImplementationRequest.type.method, + super.provideImplementation(handle, model, position, token)); + } + + protected provideTypeDefinition(handle: number, model: monaco.editor.ITextModel, + position: monaco.Position, token: monaco.CancellationToken): monaco.languages.ProviderResult { + return this.pluginMetricsResolver.resolveRequest(this.handleToExtensionName(handle), + vst.TypeDefinitionRequest.type.method, + super.provideTypeDefinition(handle, model, position, token)); + } + + protected provideHover(handle: number, model: monaco.editor.ITextModel, position: monaco.Position, + token: monaco.CancellationToken): monaco.languages.ProviderResult { + return this.pluginMetricsResolver.resolveRequest(this.handleToExtensionName(handle), + vst.HoverRequest.type.method, + super.provideHover(handle, model, position, token)); + } + + protected provideDocumentHighlights(handle: number, model: monaco.editor.ITextModel, position: monaco.Position, + token: monaco.CancellationToken): monaco.languages.ProviderResult { + return this.pluginMetricsResolver.resolveRequest(this.handleToExtensionName(handle), + vst.DocumentHighlightRequest.type.method, + super.provideDocumentHighlights(handle, model, position, token)); + } + + protected provideWorkspaceSymbols(handle: number, params: WorkspaceSymbolParams, token: monaco.CancellationToken): Thenable { + return this.pluginMetricsResolver.resolveRequest(this.handleToExtensionName(handle), + vst.WorkspaceSymbolRequest.type.method, + super.provideWorkspaceSymbols(handle, params, token)); + } + + protected resolveWorkspaceSymbol(handle: number, symbol: SymbolInformation, token: monaco.CancellationToken): Thenable { + return this.pluginMetricsResolver.resolveRequest(this.handleToExtensionName(handle), + vst.WorkspaceSymbolRequest.type.method, + super.resolveWorkspaceSymbol(handle, symbol, token)); + } + + protected async provideLinks(handle: number, model: monaco.editor.ITextModel, + token: monaco.CancellationToken): Promise> { + return this.pluginMetricsResolver.resolveRequest(this.handleToExtensionName(handle), + vst.DocumentLinkRequest.type.method, + super.provideLinks(handle, model, token)); + } + + protected async resolveLink(handle: number, link: monaco.languages.ILink, + token: monaco.CancellationToken): Promise> { + return this.pluginMetricsResolver.resolveRequest(this.handleToExtensionName(handle), + vst.DocumentLinkRequest.type.method, + super.resolveLink(handle, link, token)); + } + + protected async provideCodeLenses(handle: number, model: monaco.editor.ITextModel, + token: monaco.CancellationToken): Promise> { + return this.pluginMetricsResolver.resolveRequest(this.handleToExtensionName(handle), + vst.CodeLensRequest.type.method, + super.provideCodeLenses(handle, model, token)); + } + + protected resolveCodeLens(handle: number, model: monaco.editor.ITextModel, + codeLens: monaco.languages.CodeLens, token: monaco.CancellationToken): monaco.languages.ProviderResult { + return this.pluginMetricsResolver.resolveRequest(this.handleToExtensionName(handle), + vst.CodeLensResolveRequest.type.method, + super.resolveCodeLens(handle, model, codeLens, token)); + } + + protected provideDocumentSymbols(handle: number, model: monaco.editor.ITextModel, + token: monaco.CancellationToken): monaco.languages.ProviderResult { + return this.pluginMetricsResolver.resolveRequest(this.handleToExtensionName(handle), + vst.DocumentSymbolRequest.type.method, + super.provideDocumentSymbols(handle, model, token)); + } + + protected provideDefinition(handle: number, model: monaco.editor.ITextModel, + position: monaco.Position, token: monaco.CancellationToken): monaco.languages.ProviderResult { + return this.pluginMetricsResolver.resolveRequest(this.handleToExtensionName(handle), + vst.DefinitionRequest.type.method, + super.provideDefinition(handle, model, position, token)); + } + + protected async provideSignatureHelp(handle: number, model: monaco.editor.ITextModel, + position: monaco.Position, token: monaco.CancellationToken, + context: monaco.languages.SignatureHelpContext): Promise> { + return this.pluginMetricsResolver.resolveRequest(this.handleToExtensionName(handle), + vst.SignatureHelpRequest.type.method, + super.provideSignatureHelp(handle, model, position, token, context)); + } + + protected provideDocumentFormattingEdits(handle: number, model: monaco.editor.ITextModel, + options: monaco.languages.FormattingOptions, token: monaco.CancellationToken): monaco.languages.ProviderResult { + return this.pluginMetricsResolver.resolveRequest(this.handleToExtensionName(handle), + vst.DocumentFormattingRequest.type.method, + super.provideDocumentFormattingEdits(handle, model, options, token)); + } + + protected provideDocumentRangeFormattingEdits(handle: number, model: monaco.editor.ITextModel, + range: Range, options: monaco.languages.FormattingOptions, token: monaco.CancellationToken): monaco.languages.ProviderResult { + return this.pluginMetricsResolver.resolveRequest(this.handleToExtensionName(handle), + vst.DocumentRangeFormattingRequest.type.method, + super.provideDocumentRangeFormattingEdits(handle, model, range, options, token)); + } + + protected provideOnTypeFormattingEdits(handle: number, model: monaco.editor.ITextModel, position: monaco.Position, + ch: string, options: monaco.languages.FormattingOptions, token: monaco.CancellationToken): monaco.languages.ProviderResult { + return this.pluginMetricsResolver.resolveRequest(this.handleToExtensionName(handle), + vst.DocumentOnTypeFormattingRequest.type.method, + super.provideOnTypeFormattingEdits(handle, model, position, ch, options, token)); + } + + protected provideFoldingRanges(handle: number, model: monaco.editor.ITextModel, + context: monaco.languages.FoldingContext, token: monaco.CancellationToken): monaco.languages.ProviderResult { + return this.pluginMetricsResolver.resolveRequest(this.handleToExtensionName(handle), + vst.FoldingRangeRequest.type.method, + super.provideFoldingRanges(handle, model, context, token)); + } + + protected provideDocumentColors(handle: number, model: monaco.editor.ITextModel, + token: monaco.CancellationToken): monaco.languages.ProviderResult { + return this.pluginMetricsResolver.resolveRequest(this.handleToExtensionName(handle), + vst.DocumentColorRequest.type.method, + super.provideDocumentColors(handle, model, token)); + } + + protected provideColorPresentations(handle: number, model: monaco.editor.ITextModel, + colorInfo: monaco.languages.IColorInformation, token: monaco.CancellationToken): monaco.languages.ProviderResult { + return this.pluginMetricsResolver.resolveRequest(this.handleToExtensionName(handle), + vst.ColorPresentationRequest.type.method, + super.provideColorPresentations(handle, model, colorInfo, token)); + } + + protected async provideCodeActions(handle: number, model: monaco.editor.ITextModel, + rangeOrSelection: Range, context: monaco.languages.CodeActionContext, + token: monaco.CancellationToken): Promise> { + return this.pluginMetricsResolver.resolveRequest(this.handleToExtensionName(handle), + vst.CodeActionRequest.type.method, + super.provideCodeActions(handle, model, rangeOrSelection, context, token)); + } + + protected provideRenameEdits(handle: number, model: monaco.editor.ITextModel, + position: monaco.Position, newName: string, token: monaco.CancellationToken): monaco.languages.ProviderResult { + return this.pluginMetricsResolver.resolveRequest(this.handleToExtensionName(handle), + vst.RenameRequest.type.method, + super.provideRenameEdits(handle, model, position, newName, token)); + } + + protected resolveRenameLocation(handle: number, model: monaco.editor.ITextModel, + position: monaco.Position, token: monaco.CancellationToken): monaco.languages.ProviderResult { + return this.pluginMetricsResolver.resolveRequest(this.handleToExtensionName(handle), + vst.RenameRequest.type.method, + super.resolveRenameLocation(handle, model, position, token)); + } + + $registerCompletionSupport(handle: number, pluginInfo: PluginInfo, + selector: SerializedDocumentFilter[], triggerCharacters: string[], supportsResolveDetails: boolean): void { + this.registerPluginWithFeatureHandle(handle, pluginInfo.id); + super.$registerCompletionSupport(handle, pluginInfo, selector, triggerCharacters, supportsResolveDetails); + } + + $registerDefinitionProvider(handle: number, pluginInfo: PluginInfo, selector: SerializedDocumentFilter[]): void { + this.registerPluginWithFeatureHandle(handle, pluginInfo.id); + super.$registerDefinitionProvider(handle, pluginInfo, selector); + } + + $registerDeclarationProvider(handle: number, pluginInfo: PluginInfo, selector: SerializedDocumentFilter[]): void { + this.registerPluginWithFeatureHandle(handle, pluginInfo.id); + super.$registerDeclarationProvider(handle, pluginInfo, selector); + } + + $registerReferenceProvider(handle: number, pluginInfo: PluginInfo, selector: SerializedDocumentFilter[]): void { + this.registerPluginWithFeatureHandle(handle, pluginInfo.id); + super.$registerReferenceProvider(handle, pluginInfo, selector); + } + + $registerSignatureHelpProvider(handle: number, pluginInfo: PluginInfo, selector: SerializedDocumentFilter[], metadata: theia.SignatureHelpProviderMetadata): void { + this.registerPluginWithFeatureHandle(handle, pluginInfo.id); + super.$registerSignatureHelpProvider(handle, pluginInfo, selector, metadata); + } + + $registerImplementationProvider(handle: number, pluginInfo: PluginInfo, selector: SerializedDocumentFilter[]): void { + this.registerPluginWithFeatureHandle(handle, pluginInfo.id); + super.$registerImplementationProvider(handle, pluginInfo, selector); + } + + $registerTypeDefinitionProvider(handle: number, pluginInfo: PluginInfo, selector: SerializedDocumentFilter[]): void { + this.registerPluginWithFeatureHandle(handle, pluginInfo.id); + super.$registerTypeDefinitionProvider(handle, pluginInfo, selector); + } + + $registerHoverProvider(handle: number, pluginInfo: PluginInfo, selector: SerializedDocumentFilter[]): void { + this.registerPluginWithFeatureHandle(handle, pluginInfo.id); + super.$registerHoverProvider(handle, pluginInfo, selector); + } + + $registerDocumentHighlightProvider(handle: number, pluginInfo: PluginInfo, selector: SerializedDocumentFilter[]): void { + this.registerPluginWithFeatureHandle(handle, pluginInfo.id); + super.$registerDocumentHighlightProvider(handle, pluginInfo, selector); + } + + $registerWorkspaceSymbolProvider(handle: number, pluginInfo: PluginInfo): void { + this.registerPluginWithFeatureHandle(handle, pluginInfo.id); + super.$registerWorkspaceSymbolProvider(handle, pluginInfo); + } + + $registerDocumentLinkProvider(handle: number, pluginInfo: PluginInfo, selector: SerializedDocumentFilter[]): void { + this.registerPluginWithFeatureHandle(handle, pluginInfo.id); + super.$registerDocumentLinkProvider(handle, pluginInfo, selector); + } + + $registerCodeLensSupport(handle: number, pluginInfo: PluginInfo, selector: SerializedDocumentFilter[], eventHandle: number): void { + this.registerPluginWithFeatureHandle(handle, pluginInfo.id); + super.$registerCodeLensSupport(handle, pluginInfo, selector, eventHandle); + } + + $registerOutlineSupport(handle: number, pluginInfo: PluginInfo, selector: SerializedDocumentFilter[]): void { + this.registerPluginWithFeatureHandle(handle, pluginInfo.id); + super.$registerOutlineSupport(handle, pluginInfo, selector); + } + + $registerDocumentFormattingSupport(handle: number, pluginInfo: PluginInfo, selector: SerializedDocumentFilter[]): void { + this.registerPluginWithFeatureHandle(handle, pluginInfo.id); + super.$registerDocumentFormattingSupport(handle, pluginInfo, selector); + } + + $registerRangeFormattingProvider(handle: number, pluginInfo: PluginInfo, selector: SerializedDocumentFilter[]): void { + this.registerPluginWithFeatureHandle(handle, pluginInfo.id); + super.$registerRangeFormattingProvider(handle, pluginInfo, selector); + } + + $registerOnTypeFormattingProvider(handle: number, pluginInfo: PluginInfo, selector: SerializedDocumentFilter[], autoFormatTriggerCharacters: string[]): void { + this.registerPluginWithFeatureHandle(handle, pluginInfo.id); + super.$registerOnTypeFormattingProvider(handle, pluginInfo, selector, autoFormatTriggerCharacters); + } + + $registerFoldingRangeProvider(handle: number, pluginInfo: PluginInfo, selector: SerializedDocumentFilter[]): void { + this.registerPluginWithFeatureHandle(handle, pluginInfo.id); + super.$registerFoldingRangeProvider(handle, pluginInfo, selector); + } + + $registerDocumentColorProvider(handle: number, pluginInfo: PluginInfo, selector: SerializedDocumentFilter[]): void { + this.registerPluginWithFeatureHandle(handle, pluginInfo.id); + super.$registerDocumentColorProvider(handle, pluginInfo, selector); + } + + $registerQuickFixProvider(handle: number, pluginInfo: PluginInfo, selector: SerializedDocumentFilter[], codeActionKinds?: string[]): void { + this.registerPluginWithFeatureHandle(handle, pluginInfo.id); + super.$registerQuickFixProvider(handle, pluginInfo, selector); + } + + $registerRenameProvider(handle: number, pluginInfo: PluginInfo, selector: SerializedDocumentFilter[], supportsResolveLocation: boolean): void { + this.registerPluginWithFeatureHandle(handle, pluginInfo.id); + super.$registerRenameProvider(handle, pluginInfo, selector, supportsResolveLocation); + } + + private registerPluginWithFeatureHandle(handle: number, pluginID: string): void { + this.handleToExtensionID.set(handle, pluginID); + } + + private handleToExtensionName(handle: number): string { + return this.handleToExtensionID.get(handle) as string; + } +} diff --git a/packages/plugin-ext-metrics/src/browser/plugin-metrics-output-registry.ts b/packages/plugin-ext-metrics/src/browser/plugin-metrics-output-registry.ts new file mode 100644 index 0000000000000..2a562edf3fc2e --- /dev/null +++ b/packages/plugin-ext-metrics/src/browser/plugin-metrics-output-registry.ts @@ -0,0 +1,64 @@ +/******************************************************************************** + * 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 { injectable, inject } from 'inversify'; +import { OutputChannelRegistryMainImpl } from '@theia/plugin-ext/lib/main/browser/output-channel-registry-main'; +import { PluginMetricsCreator } from './plugin-metrics-creator'; +import { createDefaultRequestData } from './plugin-metrics-interfaces'; + +@injectable() +export class PluginMetricsOutputChannelRegistry extends OutputChannelRegistryMainImpl { + + @inject(PluginMetricsCreator) + protected readonly pluginMetricsCreator: PluginMetricsCreator; + + // This is a map of output channel names to plugin ids + private supportedExtOutputChannelToID = new Map(); + + constructor() { + super(); + this.supportedExtOutputChannelToID.set('YAML Support', 'redhat.vscode-yaml'); + this.supportedExtOutputChannelToID.set('XML Support', 'redhat.vscode-xml'); + this.supportedExtOutputChannelToID.set('Language Support for Apache Camel', 'redhat.vscode-apache-camel'); + this.supportedExtOutputChannelToID.set('intelephense', 'bmewburn.vscode-intelephense-client'); + this.supportedExtOutputChannelToID.set('Python', 'ms-python.python'); + this.supportedExtOutputChannelToID.set('Python Language Server', 'ms-python.python'); + this.supportedExtOutputChannelToID.set('TypeScript', 'vscode.typescript-language-features'); + this.supportedExtOutputChannelToID.set('Omnisharp Log', 'theia.omnisharp-theia-plugin'); + this.supportedExtOutputChannelToID.set('Clang Language Server', 'eclipse-cdt.cdt-vscode'); + } + + $append(channelName: string, errorOrValue: string): PromiseLike { + if (errorOrValue.startsWith('[Error')) { + + if (this.supportedExtOutputChannelToID.has(channelName)) { + + const createdMetric = createDefaultRequestData(this.supportedExtOutputChannelToID.get(channelName) as string, errorOrValue); + this.pluginMetricsCreator.createErrorMetric(createdMetric); + + } else if (this.pluginMetricsCreator.extensionIDAnalytics.has(channelName)) { + + const createdMetric = createDefaultRequestData(channelName, errorOrValue); + this.pluginMetricsCreator.createErrorMetric(createdMetric); + + } else { + console.log('Could not find the correct vscode extension for this error'); + } + } + return super.$append(channelName, errorOrValue); + } + +} diff --git a/packages/plugin-ext-metrics/src/browser/plugin-metrics-resolver.ts b/packages/plugin-ext-metrics/src/browser/plugin-metrics-resolver.ts new file mode 100644 index 0000000000000..0a525aa939dc1 --- /dev/null +++ b/packages/plugin-ext-metrics/src/browser/plugin-metrics-resolver.ts @@ -0,0 +1,78 @@ +/******************************************************************************** + * 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 + ********************************************************************************/ + +// tslint:disable:no-any + +import { injectable, inject } from 'inversify'; +import { PluginMetricsCreator } from './plugin-metrics-creator'; +import { createRequestData } from './plugin-metrics-interfaces'; + +/** + * This class helps resolve language server requests into successess or failures + * and sends the data to the metricsExtractor + */ +@injectable() +export class PluginMetricsResolver { + + @inject(PluginMetricsCreator) + private metricsCreator: PluginMetricsCreator; + + /** + * Resolve a request for pluginID and create a metric based on whether or not + * the language server errored. + * + * @param pluginID the ID of the plugin that made the request + * @param method the method that was request + * @param request the result of the language server request + */ + async resolveRequest(pluginID: string, method: string, request: PromiseLike | Promise | Thenable | any): Promise { + const currentTime = performance.now(); + if (isPromise(request)) { + return request.catch(error => { + this.createAndSetMetric(pluginID, method, performance.now() - currentTime, false); + return Promise.reject(error); + }).then(value => { + this.createAndSetMetric(pluginID, method, performance.now() - currentTime, true); + return value; + }); + } else if (isPromiseLike(request)) { + return request.then(value => { + this.createAndSetMetric(pluginID, method, performance.now() - currentTime, true); + return value; + }, + error => { + this.createAndSetMetric(pluginID, method, performance.now() - currentTime, false); + return Promise.reject(error); + }); + } else { + this.createAndSetMetric(pluginID, method, performance.now() - currentTime, true); + return request; + } + } + + private createAndSetMetric(pluginID: string, method: string, time: number, successful: boolean): void { + const createdSuccessMetric = createRequestData(pluginID, method, time); + this.metricsCreator.createMetric(createdSuccessMetric, successful); + } +} + +function isPromise(potentialPromise: any): potentialPromise is Promise { + return (>potentialPromise).then !== undefined; +} + +function isPromiseLike(potentialPromiseLike: any): potentialPromiseLike is PromiseLike { + return (>potentialPromiseLike).then !== undefined; +} diff --git a/packages/plugin-ext-metrics/src/common/index.ts b/packages/plugin-ext-metrics/src/common/index.ts new file mode 100644 index 0000000000000..73f42cf64d106 --- /dev/null +++ b/packages/plugin-ext-metrics/src/common/index.ts @@ -0,0 +1,15 @@ +/******************************************************************************** + * 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 + ********************************************************************************/ diff --git a/packages/plugin-ext-metrics/src/common/metrics-protocol.ts b/packages/plugin-ext-metrics/src/common/metrics-protocol.ts new file mode 100644 index 0000000000000..737dbe934c6af --- /dev/null +++ b/packages/plugin-ext-metrics/src/common/metrics-protocol.ts @@ -0,0 +1,27 @@ +/******************************************************************************** + * 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 + ********************************************************************************/ + +/** + * The JSON-RPC workspace interface for plugin metrics + */ +export const metricsJsonRpcPath = '/services/plugin-ext/metrics'; +export const PluginMetrics = Symbol('PluginMetrics'); +export interface PluginMetrics { + setMetrics(metrics: string): void; + getMetrics(): string; +} + +export const METRICS_TIMEOUT = 5000; diff --git a/packages/plugin-ext-metrics/src/node/plugin-ext-metrics-backend-module.ts b/packages/plugin-ext-metrics/src/node/plugin-ext-metrics-backend-module.ts new file mode 100644 index 0000000000000..86cb324052bb0 --- /dev/null +++ b/packages/plugin-ext-metrics/src/node/plugin-ext-metrics-backend-module.ts @@ -0,0 +1,34 @@ +/******************************************************************************** + * 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 { MetricsContribution } from '@theia/metrics/lib/node/metrics-contribution'; +import { PluginMetricsContribution } from './plugin-metrics'; +import { PluginMetrics, metricsJsonRpcPath } from '../common/metrics-protocol'; +import { PluginMetricsHandler } from './plugin-metrics-handler'; +import { ConnectionHandler } from '@theia/core/lib/common/messaging/handler'; +import { JsonRpcConnectionHandler } from '@theia/core'; +import { ContainerModule } from 'inversify'; + +export default new ContainerModule((bind, unbind, isBound, rebind) => { + bind(PluginMetrics).to(PluginMetricsHandler).inSingletonScope(); + bind(ConnectionHandler).toDynamicValue(ctx => + new JsonRpcConnectionHandler(metricsJsonRpcPath, () => + ctx.container.get(PluginMetrics) + ) + ).inSingletonScope(); + + bind(MetricsContribution).to(PluginMetricsContribution).inSingletonScope(); +}); diff --git a/packages/plugin-ext-metrics/src/node/plugin-metrics-handler.ts b/packages/plugin-ext-metrics/src/node/plugin-metrics-handler.ts new file mode 100644 index 0000000000000..501fd7675fc72 --- /dev/null +++ b/packages/plugin-ext-metrics/src/node/plugin-metrics-handler.ts @@ -0,0 +1,38 @@ +/******************************************************************************** + * 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 { injectable } from 'inversify'; +import { PluginMetrics } from '../common/metrics-protocol'; + +@injectable() +export class PluginMetricsHandler implements PluginMetrics { + + private metrics: string = ''; + + // tslint:disable-next-line:typedef + setMetrics(metrics: string) { + this.metrics = metrics; + } + + /** + * This sends all the information about metrics inside of the plugins to the backend + * where it is served on the /metrics endpoint + */ + getMetrics(): string { + return this.metrics; + } + +} diff --git a/packages/plugin-ext-metrics/src/node/plugin-metrics.ts b/packages/plugin-ext-metrics/src/node/plugin-metrics.ts new file mode 100644 index 0000000000000..1a7929d5ede9f --- /dev/null +++ b/packages/plugin-ext-metrics/src/node/plugin-metrics.ts @@ -0,0 +1,38 @@ +/******************************************************************************** + * 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 { injectable, inject } from 'inversify'; +import { MetricsContribution } from '@theia/metrics/lib/node/metrics-contribution'; +import { PluginMetrics, METRICS_TIMEOUT } from '../common/metrics-protocol'; + +@injectable() +export class PluginMetricsContribution implements MetricsContribution { + + @inject(PluginMetrics) + protected readonly pluginMetrics: PluginMetrics; + + private metrics: string; + + getMetrics(): string { + return this.metrics; + } + + startCollecting(): void { + setInterval(() => { + this.metrics = this.pluginMetrics.getMetrics(); + }, METRICS_TIMEOUT); + } +} diff --git a/yarn.lock b/yarn.lock index 7a8e33f9ec63f..a3b4ae6135dc6 100644 --- a/yarn.lock +++ b/yarn.lock @@ -10989,6 +10989,11 @@ vscode-json-languageservice@^3.3.0: vscode-nls "^4.1.1" vscode-uri "^2.0.3" +vscode-jsonrpc@^4.0.0: + version "4.0.0" + resolved "https://registry.yarnpkg.com/vscode-jsonrpc/-/vscode-jsonrpc-4.0.0.tgz#a7bf74ef3254d0a0c272fab15c82128e378b3be9" + integrity sha512-perEnXQdQOJMTDFNv+UF3h1Y0z4iSiaN9jIlb0OqIYgosPCZGYh/MCUlkFtV2668PL69lRDO32hmvL2yiidUYg== + vscode-jsonrpc@^4.1.0-next, vscode-jsonrpc@^4.1.0-next.3: version "4.1.0-next.3" resolved "https://registry.yarnpkg.com/vscode-jsonrpc/-/vscode-jsonrpc-4.1.0-next.3.tgz#05fe742959a2726020d4d0bfbc3d3c97873c7fde" @@ -11002,6 +11007,14 @@ vscode-languageclient@^5.3.0-next: semver "^5.5.0" vscode-languageserver-protocol "^3.15.0-next.6" +vscode-languageserver-protocol@^3.14.1: + version "3.14.1" + resolved "https://registry.yarnpkg.com/vscode-languageserver-protocol/-/vscode-languageserver-protocol-3.14.1.tgz#b8aab6afae2849c84a8983d39a1cf742417afe2f" + integrity sha512-IL66BLb2g20uIKog5Y2dQ0IiigW0XKrvmWiOvc0yXw80z3tMEzEnHjaGAb3ENuU7MnQqgnYJ1Cl2l9RvNgDi4g== + dependencies: + vscode-jsonrpc "^4.0.0" + vscode-languageserver-types "3.14.0" + vscode-languageserver-protocol@^3.15.0-next.6, vscode-languageserver-protocol@^3.15.0-next.8: version "3.15.0-next.8" resolved "https://registry.yarnpkg.com/vscode-languageserver-protocol/-/vscode-languageserver-protocol-3.15.0-next.8.tgz#5e3cc0ae143fe3364820249e32f6019ce974fa9e" @@ -11010,6 +11023,11 @@ vscode-languageserver-protocol@^3.15.0-next.6, vscode-languageserver-protocol@^3 vscode-jsonrpc "^4.1.0-next.3" vscode-languageserver-types "^3.15.0-next.4" +vscode-languageserver-types@3.14.0: + version "3.14.0" + resolved "https://registry.yarnpkg.com/vscode-languageserver-types/-/vscode-languageserver-types-3.14.0.tgz#d3b5952246d30e5241592b6dde8280e03942e743" + integrity sha512-lTmS6AlAlMHOvPQemVwo3CezxBp0sNB95KNPkqp3Nxd5VFEnuG1ByM0zlRWos0zjO3ZWtkvhal0COgiV1xIA4A== + vscode-languageserver-types@^3.15.0-next, vscode-languageserver-types@^3.15.0-next.2, vscode-languageserver-types@^3.15.0-next.4: version "3.15.0-next.4" resolved "https://registry.yarnpkg.com/vscode-languageserver-types/-/vscode-languageserver-types-3.15.0-next.4.tgz#9aae49844ef826ae656382facecc20664113c060"