Skip to content

Commit 7352203

Browse files
jagpreetsinghsasanpetermetz
authored andcommitted
feat(besu): add prometheus exporter
Primary Change -------------- 1. The besu 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. IPluginLedgerConnectorBesuOptions interface in PluginLedgerConnectorBesu class now has a prometheusExporter optional field 5. The PluginLedgerConnectorBesu class has relevant functions and codes to incorporate prometheus exporter 6. Added Readme.md on the prometheus exporter usage Fixes #533 Signed-off-by: Jagpreet Singh Sasan <[email protected]>
1 parent 55d6587 commit 7352203

File tree

12 files changed

+391
-5
lines changed

12 files changed

+391
-5
lines changed

packages/cactus-plugin-ledger-connector-besu/README.md

+41-3
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ This plugin provides `Cactus` a way to interact with Besu networks. Using this w
88

99
- [Getting Started](#getting-started)
1010
- [Usage](#usage)
11+
- [Prometheus Exporter](#prometheus-exporter)
1112
- [Runing the tests](#running-the-tests)
1213
- [Built With](#built-with)
1314
- [Contributing](#contributing)
@@ -33,8 +34,6 @@ In the project root folder, run this command to compile the plugin and create th
3334
npm run tsc
3435
```
3536

36-
## Usage
37-
3837
To use this import public-api and create new **PluginFactoryLedgerConnector**. Then use it to create a connector.
3938
```typescript
4039
const factory = new PluginFactoryLedgerConnector({
@@ -80,6 +79,45 @@ enum Web3SigningCredentialType {
8079
```
8180
> Extensive documentation and examples in the [readthedocs](https://readthedocs.org/projects/hyperledger-cactus/) (WIP)
8281
82+
## Prometheus Exporter
83+
84+
This class creates a prometheus exporter, which scrapes the transactions (total transaction count) for the use cases incorporating the use of Besu connector plugin.
85+
86+
### Usage
87+
The prometheus exporter object is initialized in the `PluginLedgerConnectorBesu` class constructor itself, so instantiating the object of the `PluginLedgerConnectorBesu` class, gives access to the exporter object.
88+
You can also initialize the prometheus exporter object seperately and then pass it to the `IPluginLedgerConnectorBesuOptions` interface for `PluginLedgerConnectoBesu` constructor.
89+
90+
`getPrometheusExporterMetricsV1` function returns the prometheus exporter metrics, currently displaying the total transaction count, which currently increments everytime the `transact()` method of the `PluginLedgerConnectorBesu` class is called.
91+
92+
### Prometheus Integration
93+
To use Prometheus with this exporter make sure to install [Prometheus main component](https://prometheus.io/download/).
94+
Once Prometheus is setup, the corresponding scrape_config needs to be added to the prometheus.yml
95+
96+
```(yaml)
97+
- job_name: 'besu_ledger_connector_exporter'
98+
metrics_path: api/v1/plugins/@hyperledger/cactus-plugin-ledger-connector-besu/get-prometheus-exporter-metrics
99+
scrape_interval: 5s
100+
static_configs:
101+
- targets: ['{host}:{port}']
102+
```
103+
104+
Here the `host:port` is where the prometheus exporter metrics are exposed. The test cases (For example, packages/cactus-plugin-ledger-connector-besu/src/test/typescript/integration/plugin-ledger-connector-besu/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)
105+
`Metrics URL: http://0.0.0.0:42379/api/v1/plugins/@hyperledger/cactus-plugin-ledger-connector-besu/get-prometheus-exporter-metrics`
106+
107+
Once edited, you can start the prometheus service by referencing the above edited prometheus.yml file.
108+
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_besu_total_tx_count** and click **execute**
109+
110+
### Helper code
111+
112+
###### response.type.ts
113+
This file contains the various responses of the metrics.
114+
115+
###### data-fetcher.ts
116+
This file contains functions encasing the logic to process the data points
117+
118+
###### metrics.ts
119+
This file lists all the prometheus metrics and what they are used for.
120+
83121
## Running the tests
84122

85123
To check that all has been installed correctly and that the pugin has no errors run the tests:
@@ -99,4 +137,4 @@ Please review [CONTIRBUTING.md](../../CONTRIBUTING.md) to get started.
99137

100138
This distribution is published under the Apache License Version 2.0 found in the [LICENSE](../../LICENSE) file.
101139

102-
## Acknowledgments
140+
## Acknowledgments

packages/cactus-plugin-ledger-connector-besu/package-lock.json

+21
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

packages/cactus-plugin-ledger-connector-besu/package.json

+5-1
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,10 @@
3333
"ignore": [
3434
"src/**/generated/*"
3535
],
36-
"extensions": ["ts", "json"],
36+
"extensions": [
37+
"ts",
38+
"json"
39+
],
3740
"quiet": true,
3841
"verbose": false,
3942
"runOnChangeOnly": true
@@ -87,6 +90,7 @@
8790
"express": "4.17.1",
8891
"joi": "14.3.1",
8992
"openapi-types": "7.0.1",
93+
"prom-client": "13.1.0",
9094
"typescript-optional": "2.0.1",
9195
"web3": "1.2.7",
9296
"web3-eea": "0.10.0"

packages/cactus-plugin-ledger-connector-besu/src/main/json/openapi.json

+29
Original file line numberDiff line numberDiff line change
@@ -675,6 +675,10 @@
675675
"nullable": false
676676
}
677677
}
678+
},
679+
"PrometheusExporterMetricsResponse": {
680+
"type": "string",
681+
"nullable": false
678682
}
679683
}
680684
},
@@ -853,6 +857,31 @@
853857
}
854858
}
855859
}
860+
},
861+
"/api/v1/plugins/@hyperledger/cactus-plugin-ledger-connector-besu/get-prometheus-exporter-metrics": {
862+
"get": {
863+
"x-hyperledger-cactus": {
864+
"http": {
865+
"verbLowerCase": "get",
866+
"path": "/api/v1/plugins/@hyperledger/cactus-plugin-ledger-connector-besu/get-prometheus-exporter-metrics"
867+
}
868+
},
869+
"operationId": "getPrometheusExporterMetricsV1",
870+
"summary": "Get the Prometheus Metrics",
871+
"parameters": [],
872+
"responses": {
873+
"200": {
874+
"description": "OK",
875+
"content": {
876+
"text/plain": {
877+
"schema": {
878+
"$ref": "#/components/schemas/PrometheusExporterMetricsResponse"
879+
}
880+
}
881+
}
882+
}
883+
}
884+
}
856885
}
857886
}
858887
}

packages/cactus-plugin-ledger-connector-besu/src/main/typescript/generated/openapi/typescript-axios/api.ts

+69
Original file line numberDiff line numberDiff line change
@@ -819,6 +819,42 @@ export const DefaultApiAxiosParamCreator = function (configuration?: Configurati
819819
options: localVarRequestOptions,
820820
};
821821
},
822+
/**
823+
*
824+
* @summary Get the Prometheus Metrics
825+
* @param {*} [options] Override http request option.
826+
* @throws {RequiredError}
827+
*/
828+
getPrometheusExporterMetricsV1: async (options: any = {}): Promise<RequestArgs> => {
829+
const localVarPath = `/api/v1/plugins/@hyperledger/cactus-plugin-ledger-connector-besu/get-prometheus-exporter-metrics`;
830+
// use dummy base URL string because the URL constructor only accepts absolute URLs.
831+
const localVarUrlObj = new URL(localVarPath, 'https://example.com');
832+
let baseOptions;
833+
if (configuration) {
834+
baseOptions = configuration.baseOptions;
835+
}
836+
const localVarRequestOptions = { method: 'GET', ...baseOptions, ...options};
837+
const localVarHeaderParameter = {} as any;
838+
const localVarQueryParameter = {} as any;
839+
840+
841+
842+
const query = new URLSearchParams(localVarUrlObj.search);
843+
for (const key in localVarQueryParameter) {
844+
query.set(key, localVarQueryParameter[key]);
845+
}
846+
for (const key in options.query) {
847+
query.set(key, options.query[key]);
848+
}
849+
localVarUrlObj.search = (new URLSearchParams(query)).toString();
850+
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
851+
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
852+
853+
return {
854+
url: localVarUrlObj.pathname + localVarUrlObj.search + localVarUrlObj.hash,
855+
options: localVarRequestOptions,
856+
};
857+
},
822858
/**
823859
* Obtain signatures of ledger from the corresponding transaction hash.
824860
* @summary Obtain signatures of ledger from the corresponding transaction hash.
@@ -929,6 +965,19 @@ export const DefaultApiFp = function(configuration?: Configuration) {
929965
return axios.request(axiosRequestArgs);
930966
};
931967
},
968+
/**
969+
*
970+
* @summary Get the Prometheus Metrics
971+
* @param {*} [options] Override http request option.
972+
* @throws {RequiredError}
973+
*/
974+
async getPrometheusExporterMetricsV1(options?: any): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<string>> {
975+
const localVarAxiosArgs = await DefaultApiAxiosParamCreator(configuration).getPrometheusExporterMetricsV1(options);
976+
return (axios: AxiosInstance = globalAxios, basePath: string = BASE_PATH) => {
977+
const axiosRequestArgs = {...localVarAxiosArgs.options, url: basePath + localVarAxiosArgs.url};
978+
return axios.request(axiosRequestArgs);
979+
};
980+
},
932981
/**
933982
* Obtain signatures of ledger from the corresponding transaction hash.
934983
* @summary Obtain signatures of ledger from the corresponding transaction hash.
@@ -992,6 +1041,15 @@ export const DefaultApiFactory = function (configuration?: Configuration, basePa
9921041
apiV2BesuInvokeContract(invokeContractV2Request?: InvokeContractV2Request, options?: any): AxiosPromise<InvokeContractV2Response> {
9931042
return DefaultApiFp(configuration).apiV2BesuInvokeContract(invokeContractV2Request, options).then((request) => request(axios, basePath));
9941043
},
1044+
/**
1045+
*
1046+
* @summary Get the Prometheus Metrics
1047+
* @param {*} [options] Override http request option.
1048+
* @throws {RequiredError}
1049+
*/
1050+
getPrometheusExporterMetricsV1(options?: any): AxiosPromise<string> {
1051+
return DefaultApiFp(configuration).getPrometheusExporterMetricsV1(options).then((request) => request(axios, basePath));
1052+
},
9951053
/**
9961054
* Obtain signatures of ledger from the corresponding transaction hash.
9971055
* @summary Obtain signatures of ledger from the corresponding transaction hash.
@@ -1060,6 +1118,17 @@ export class DefaultApi extends BaseAPI {
10601118
return DefaultApiFp(this.configuration).apiV2BesuInvokeContract(invokeContractV2Request, options).then((request) => request(this.axios, this.basePath));
10611119
}
10621120

1121+
/**
1122+
*
1123+
* @summary Get the Prometheus Metrics
1124+
* @param {*} [options] Override http request option.
1125+
* @throws {RequiredError}
1126+
* @memberof DefaultApi
1127+
*/
1128+
public getPrometheusExporterMetricsV1(options?: any) {
1129+
return DefaultApiFp(this.configuration).getPrometheusExporterMetricsV1(options).then((request) => request(this.axios, this.basePath));
1130+
}
1131+
10631132
/**
10641133
* Obtain signatures of ledger from the corresponding transaction hash.
10651134
* @summary Obtain signatures of ledger from the corresponding transaction hash.

packages/cactus-plugin-ledger-connector-besu/src/main/typescript/plugin-ledger-connector-besu.ts

+36
Original file line numberDiff line numberDiff line change
@@ -61,13 +61,19 @@ import { InvokeContractEndpoint } from "./web-services/invoke-contract-endpoint"
6161
import { InvokeContractEndpointV2 } from "./web-services/invoke-contract-endpoint-v2";
6262
import { isWeb3SigningCredentialNone } from "./model-type-guards";
6363
import { BesuSignTransactionEndpointV1 } from "./web-services/sign-transaction-endpoint-v1";
64+
import { PrometheusExporter } from "./prometheus-exporter/prometheus-exporter";
65+
import {
66+
GetPrometheusExporterMetricsEndpointV1,
67+
IGetPrometheusExporterMetricsEndpointV1Options,
68+
} from "./web-services/get-prometheus-exporter-metrics-endpoint-v1";
6469

6570
export const E_KEYCHAIN_NOT_FOUND = "cactus.connector.besu.keychain_not_found";
6671

6772
export interface IPluginLedgerConnectorBesuOptions
6873
extends ICactusPluginOptions {
6974
rpcApiHttpHost: string;
7075
pluginRegistry: PluginRegistry;
76+
prometheusExporter?: PrometheusExporter;
7177
logLevel?: LogLevelDesc;
7278
contractsPath?: string;
7379
}
@@ -83,6 +89,7 @@ export class PluginLedgerConnectorBesu
8389
ICactusPlugin,
8490
IPluginWebService {
8591
private readonly instanceId: string;
92+
public prometheusExporter: PrometheusExporter;
8693
private readonly log: Logger;
8794
private readonly web3: Web3;
8895
private readonly pluginRegistry: PluginRegistry;
@@ -116,6 +123,25 @@ export class PluginLedgerConnectorBesu
116123
this.instanceId = options.instanceId;
117124
this.pluginRegistry = options.pluginRegistry;
118125
this.contractsPath = options.contractsPath;
126+
this.prometheusExporter =
127+
options.prometheusExporter ||
128+
new PrometheusExporter({ pollingIntervalInMin: 1 });
129+
Checks.truthy(
130+
this.prometheusExporter,
131+
`${fnTag} options.prometheusExporter`,
132+
);
133+
134+
this.prometheusExporter.startMetricsCollection();
135+
}
136+
137+
public getPrometheusExporter(): PrometheusExporter {
138+
return this.prometheusExporter;
139+
}
140+
141+
public async getPrometheusExporterMetrics(): Promise<string> {
142+
const res: string = await this.prometheusExporter.getPrometheusMetrics();
143+
this.log.debug(`getPrometheusExporterMetrics() response: %o`, res);
144+
return res;
119145
}
120146

121147
public getInstanceId(): string {
@@ -178,6 +204,15 @@ export class PluginLedgerConnectorBesu
178204
endpoint.registerExpress(expressApp);
179205
endpoints.push(endpoint);
180206
}
207+
{
208+
const opts: IGetPrometheusExporterMetricsEndpointV1Options = {
209+
connector: this,
210+
logLevel: this.options.logLevel,
211+
};
212+
const endpoint = new GetPrometheusExporterMetricsEndpointV1(opts);
213+
endpoint.registerExpress(expressApp);
214+
endpoints.push(endpoint);
215+
}
181216
return endpoints;
182217
}
183218

@@ -388,6 +423,7 @@ export class PluginLedgerConnectorBesu
388423
this.log.debug(`${fnTag} sendSignedTransaction failed`, txPoolReceipt);
389424
throw txPoolReceipt;
390425
}
426+
this.prometheusExporter.addCurrentTransaction();
391427

392428
if (
393429
req.consistencyStrategy.receiptType === ReceiptType.NODETXPOOLACK &&
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
import { Transactions } from "./response.type";
2+
3+
import { totalTxCount, K_CACTUS_BESU_TOTAL_TX_COUNT } from "./metrics";
4+
5+
export async function collectMetrics(transactions: Transactions) {
6+
transactions.counter++;
7+
totalTxCount.labels(K_CACTUS_BESU_TOTAL_TX_COUNT).set(transactions.counter);
8+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
import { Gauge } from "prom-client";
2+
3+
export const K_CACTUS_BESU_TOTAL_TX_COUNT = "cactus_besu_total_tx_count";
4+
5+
export const totalTxCount = new Gauge({
6+
name: "cactus_besu_total_tx_count",
7+
help: "Total transactions executed",
8+
labelNames: ["type"],
9+
});

0 commit comments

Comments
 (0)