Skip to content

Commit

Permalink
feat(quorum): add prometheus exporter
Browse files Browse the repository at this point in the history
	Primary Change
	--------------

	1. The quorum ledger connector plugin now includes the prometheus metrics exporter integration
	2. OpenAPI spec now has api endpoint for the getting the prometheus metrics

	Refactorings that were also necessary to accomodate 1) and 2)
	------------------------------------------------------------

	3. GetPrometheusMetricsV1 class is created to handle the corresponding api endpoint
	4. IPluginLedgerConnectorQuorumOptions interface in PluginLedgerConnectorQuorum class now has a prometheusExporter optional field
	5. The PluginLedgerConnectorQuorum class has relevant functions and codes to incorporate prometheus exporter
	6. deploy-contract-from-json.test.ts is changed to incorporate the prometheus exporter
	7. Added Readme.md on the prometheus exporter usage

	Fixes hyperledger-cacti#534

Signed-off-by: Jagpreet Singh Sasan <jagpreet.singh.sasan@accenture.com>
  • Loading branch information
jagpreetsinghsasan committed Mar 10, 2021
1 parent aa070ad commit 8be6aab
Show file tree
Hide file tree
Showing 12 changed files with 394 additions and 2 deletions.
48 changes: 48 additions & 0 deletions packages/cactus-plugin-ledger-connector-quorum/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ This plugin provides `Cactus` a way to interact with Quorum networks. Using this

- [Getting Started](#getting-started)
- [Usage](#usage)
- [Prometheus Exporter](#prometheus-exporter)
- [Runing the tests](#running-the-tests)
- [Contributing](#contributing)
- [License](#license)
Expand Down Expand Up @@ -81,6 +82,53 @@ enum Web3SigningCredentialType {

To check that all has been installed correctly and that the pugin has no errors, there are two options to run the tests:

* Run this command at the project's root:
```sh
npm run test:plugin-ledger-connector-quorum
```
## Prometheus Exporter

This class creates a prometheus exporter, which scraps the transactions (total transaction count) for the use cases incorporating the use of Quorum connector plugin.

### Prometheus Exporter Usage
The prometheus exporter object is initialized in the `PluginLedgerConnectorQuorum` class constructor itself, so instantiating the object of the `PluginLedgerConnectorQuorum` class, gives access to the exporter object.
You can also initialize the prometheus exporter object seperately and then pass it to the `IPluginLedgerConnectorQuorumOptions` interface for `PluginLedgerConnectoQuorum` constructor.

`getPrometheusExporterMetricsEndpointV1` function returns the prometheus exporter metrics, currently displaying the total transaction count, which currently increments everytime the `transact()` method of the `PluginLedgerConnectorQuorum` class is called.

### Prometheus Integration
To use Prometheus with this exporter make sure to install [Prometheus main component](https://prometheus.io/download/).
Once Prometheus is setup, the corresponding scrape_config needs to be added to the prometheus.yml

```(yaml)
- job_name: 'quorum_ledger_connector_exporter'
metrics_path: api/v1/plugins/@hyperledger/cactus-plugin-ledger-connector-quorum/get-prometheus-exporter-metrics
scrape_interval: 5s
static_configs:
- targets: ['{host}:{port}']
```

Here the `host:port` is where the prometheus exporter metrics are exposed. The test cases (For example, packages/cactus-plugin-ledger-connector-quorum/src/test/typescript/integration/plugin-ledger-connector-quorum/deploy-contract/deploy-contract-from-json.test.ts) exposes it over `0.0.0.0` and a random port(). The random port can be found in the running logs of the test case and looks like (42379 in the below mentioned URL)
`Metrics URL: http://0.0.0.0:42379/api/v1/plugins/@hyperledger/cactus-plugin-ledger-connector-quorum/get-prometheus-exporter-metrics`

Once edited, you can start the prometheus service by referencing the above edited prometheus.yml file.
On the prometheus graphical interface (defaulted to http://localhost:9090), choose **Graph** from the menu bar, then select the **Console** tab. From the **Insert metric at cursor** drop down, select **cactus_quorum_total_tx_count** and click **execute**

### Helper code

###### response.type.ts
This file contains the various responses of the metrics.

###### data-fetcher.ts
This file contains functions encasing the logic to process the data points

###### metrics.ts
This file lists all the prometheus metrics and what they are used for.

## Running the tests

To check that all has been installed correctly and that the pugin has no errors, there are two options to run the tests:

* Run this command at the project's root:
```sh
npm run test:plugin-ledger-connector-quorum
Expand Down
21 changes: 21 additions & 0 deletions packages/cactus-plugin-ledger-connector-quorum/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 5 additions & 1 deletion packages/cactus-plugin-ledger-connector-quorum/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,10 @@
"ignore": [
"src/**/generated/*"
],
"extensions": ["ts", "json"],
"extensions": [
"ts",
"json"
],
"quiet": true,
"verbose": false,
"runOnChangeOnly": true
Expand Down Expand Up @@ -87,6 +90,7 @@
"express": "4.17.1",
"joi": "14.3.1",
"openapi-types": "7.0.1",
"prom-client": "13.1.0",
"typescript-optional": "2.0.1",
"web3": "1.2.7",
"web3-core-method": "1.3.0",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -537,6 +537,10 @@
},
"callOutput": {}
}
},
"PrometheusExporterMetricsResponse": {
"type": "string",
"nullable": false
}
}
},
Expand Down Expand Up @@ -642,6 +646,31 @@
}
}
}
},
"/api/v1/plugins/@hyperledger/cactus-plugin-ledger-connector-quorum/get-prometheus-exporter-metrics": {
"get": {
"x-hyperledger-cactus": {
"http": {
"verbLowerCase": "get",
"path": "/api/v1/plugins/@hyperledger/cactus-plugin-ledger-connector-quorum/get-prometheus-exporter-metrics"
}
},
"operationId": "getPrometheusExporterMetricsV1",
"summary": "Get the Prometheus Metrics",
"parameters": [],
"responses": {
"200": {
"description": "OK",
"content": {
"text/plain": {
"schema": {
"$ref": "#/components/schemas/PrometheusExporterMetricsResponse"
}
}
}
}
}
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -621,6 +621,42 @@ export const DefaultApiAxiosParamCreator = function (configuration?: Configurati
const needsSerialization = (typeof runTransactionRequest !== "string") || localVarRequestOptions.headers['Content-Type'] === 'application/json';
localVarRequestOptions.data = needsSerialization ? JSON.stringify(runTransactionRequest !== undefined ? runTransactionRequest : {}) : (runTransactionRequest || "");

return {
url: localVarUrlObj.pathname + localVarUrlObj.search + localVarUrlObj.hash,
options: localVarRequestOptions,
};
},
/**
*
* @summary Get the Prometheus Metrics
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
getPrometheusExporterMetricsV1: async (options: any = {}): Promise<RequestArgs> => {
const localVarPath = `/api/v1/plugins/@hyperledger/cactus-plugin-ledger-connector-quorum/get-prometheus-exporter-metrics`;
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, 'https://example.com');
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'GET', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;



const query = new URLSearchParams(localVarUrlObj.search);
for (const key in localVarQueryParameter) {
query.set(key, localVarQueryParameter[key]);
}
for (const key in options.query) {
query.set(key, options.query[key]);
}
localVarUrlObj.search = (new URLSearchParams(query)).toString();
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};

return {
url: localVarUrlObj.pathname + localVarUrlObj.search + localVarUrlObj.hash,
options: localVarRequestOptions,
Expand Down Expand Up @@ -677,6 +713,19 @@ export const DefaultApiFp = function(configuration?: Configuration) {
return axios.request(axiosRequestArgs);
};
},
/**
*
* @summary Get the Prometheus Metrics
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async getPrometheusExporterMetricsV1(options?: any): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<string>> {
const localVarAxiosArgs = await DefaultApiAxiosParamCreator(configuration).getPrometheusExporterMetricsV1(options);
return (axios: AxiosInstance = globalAxios, basePath: string = BASE_PATH) => {
const axiosRequestArgs = {...localVarAxiosArgs.options, url: basePath + localVarAxiosArgs.url};
return axios.request(axiosRequestArgs);
};
},
}
};

Expand Down Expand Up @@ -716,6 +765,15 @@ export const DefaultApiFactory = function (configuration?: Configuration, basePa
apiV1QuorumRunTransaction(runTransactionRequest?: RunTransactionRequest, options?: any): AxiosPromise<RunTransactionResponse> {
return DefaultApiFp(configuration).apiV1QuorumRunTransaction(runTransactionRequest, options).then((request) => request(axios, basePath));
},
/**
*
* @summary Get the Prometheus Metrics
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
getPrometheusExporterMetricsV1(options?: any): AxiosPromise<string> {
return DefaultApiFp(configuration).getPrometheusExporterMetricsV1(options).then((request) => request(axios, basePath));
},
};
};

Expand Down Expand Up @@ -761,6 +819,17 @@ export class DefaultApi extends BaseAPI {
public apiV1QuorumRunTransaction(runTransactionRequest?: RunTransactionRequest, options?: any) {
return DefaultApiFp(this.configuration).apiV1QuorumRunTransaction(runTransactionRequest, options).then((request) => request(this.axios, this.basePath));
}

/**
*
* @summary Get the Prometheus Metrics
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof DefaultApi
*/
public getPrometheusExporterMetricsV1(options?: any) {
return DefaultApiFp(this.configuration).getPrometheusExporterMetricsV1(options).then((request) => request(this.axios, this.basePath));
}
}


Original file line number Diff line number Diff line change
Expand Up @@ -49,10 +49,17 @@ import { RunTransactionEndpoint } from "./web-services/run-transaction-endpoint"
import { InvokeContractEndpoint } from "./web-services/invoke-contract-endpoint";
import { isWeb3SigningCredentialNone } from "./model-type-guards";

import { PrometheusExporter } from "./prometheus-exporter/prometheus-exporter";
import {
GetPrometheusExporterMetricsEndpointV1,
IGetPrometheusExporterMetricsEndpointV1Options,
} from "./web-services/get-prometheus-exporter-metrics-endpoint-v1";

export interface IPluginLedgerConnectorQuorumOptions
extends ICactusPluginOptions {
rpcApiHttpHost: string;
logLevel?: LogLevelDesc;
prometheusExporter?: PrometheusExporter;
pluginRegistry: PluginRegistry;
}

Expand All @@ -67,6 +74,7 @@ export class PluginLedgerConnectorQuorum
ICactusPlugin,
IPluginWebService {
private readonly pluginRegistry: PluginRegistry;
public prometheusExporter: PrometheusExporter;
private readonly instanceId: string;
private readonly log: Logger;
private readonly web3: Web3;
Expand Down Expand Up @@ -95,6 +103,26 @@ export class PluginLedgerConnectorQuorum
this.web3 = new Web3(web3Provider);
this.instanceId = options.instanceId;
this.pluginRegistry = options.pluginRegistry;

this.prometheusExporter =
options.prometheusExporter ||
new PrometheusExporter({ pollingIntervalInMin: 1 });
Checks.truthy(
this.prometheusExporter,
`${fnTag} options.prometheusExporter`,
);

this.prometheusExporter.startMetricsCollection();
}

public getPrometheusExporter(): PrometheusExporter {
return this.prometheusExporter;
}

public async getPrometheusExporterMetrics(): Promise<string> {
const res: string = await this.prometheusExporter.getPrometheusMetrics();
this.log.debug(`getPrometheusExporterMetrics() response: %o`, res);
return res;
}

public getInstanceId(): string {
Expand Down Expand Up @@ -141,6 +169,15 @@ export class PluginLedgerConnectorQuorum
endpoint.registerExpress(expressApp);
endpoints.push(endpoint);
}
{
const opts: IGetPrometheusExporterMetricsEndpointV1Options = {
connector: this,
logLevel: this.options.logLevel,
};
const endpoint = new GetPrometheusExporterMetricsEndpointV1(opts);
endpoint.registerExpress(expressApp);
endpoints.push(endpoint);
}
return endpoints;
}

Expand Down Expand Up @@ -259,6 +296,7 @@ export class PluginLedgerConnectorQuorum
this.log.debug(`${fnTag} Web3 sendSignedTransaction failed`, receipt);
throw receipt;
} else {
this.prometheusExporter.addCurrentTransaction();
return { transactionReceipt: receipt };
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { Transactions } from "./response.type";

import { totalTxCount } from "./metrics";

export async function collectMetrics(transactions: Transactions) {
totalTxCount.labels("cactus_quorum_total_tx_count").set(transactions.counter);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { Gauge } from "prom-client";

export const totalTxCount = new Gauge({
name: "cactus_quorum_total_tx_count",
help: "Total transactions executed",
labelNames: ["type"],
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import promClient from "prom-client";
import { Transactions } from "./response.type";
import { totalTxCount } from "./metrics";

export const K_CACTUS_QUORUM_TOTAL_TX_COUNT = "cactus_quorum_total_tx_count";

export interface IPrometheusExporterOptions {
pollingIntervalInMin?: number;
}

export class PrometheusExporter {
public readonly metricsPollingIntervalInMin: number;
public readonly transactions: Transactions = { counter: 0 };

constructor(
public readonly prometheusExporterOptions: IPrometheusExporterOptions,
) {
this.metricsPollingIntervalInMin =
prometheusExporterOptions.pollingIntervalInMin || 1;
}

public addCurrentTransaction(): void {
this.transactions.counter++;
totalTxCount
.labels(K_CACTUS_QUORUM_TOTAL_TX_COUNT)
.set(this.transactions.counter);
}

public async getPrometheusMetrics(): Promise<string> {
const result = await promClient.register.getSingleMetricAsString(
K_CACTUS_QUORUM_TOTAL_TX_COUNT,
);
return result;
}

public startMetricsCollection(): void {
const Registry = promClient.Registry;
const register = new Registry();
promClient.collectDefaultMetrics({ register });
}
}
Loading

0 comments on commit 8be6aab

Please sign in to comment.