npm package: @rectech/pro-metrics
Description: NodeJS process metrics collector - client.
Author: M S
Latest version: 0.0.6

# pro-metrics

## Introduction

This package collects meterics about current nodejs process. The metrics includes RAM Consumption, Heap Memory, RSS, CPU (User + System), Program Arguments, Environment Variables (is exposed in config, otherwise disabled by default), NodeJS VM details, Program Path and custom objects too.


## Getting Started

All these metrics are available on a method call `metrics: (options: MetricOptions)` and an express wrapper is also present if you want to capture the health and metrics in your existing express app via method `metricsExpress: (options: MetricExpressOptions, req: any, res: any)`.

### Install

Install just like any other `npm` package using 

```
npm i -save @rectec/pro-metrics
```

### Getting metrics programatically

If you want the metrics in your program only, you can call `metrics` method and it will return all collected metric details.

eg. 

```
// import dependency
import { MetricOptions, metricsExpress } from '@rectech/pro-metrics';

// Metric options 
const metricOptions: MetricOptions = {
  exposeEnv: false, // false - hide env variables in metrics, true - expose env variables in metrics 
}

// call `metrics` method and pass the options
const metrics = metrics(metricOptions)
console.log(metrics);
```

Output:

```
{
  "processId": 5741,
  "processParentId": 5734,
  "resourceUsage": {
    "userCPUTime": 1401778,
    "systemCPUTime": 897951,
    "maxRSS": 56244,
    "sharedMemorySize": 0,
    "unsharedDataSize": 0,
    "unsharedStackSize": 0,
    "minorPageFault": 5820,
    "majorPageFault": 1,
    "swappedOut": 0,
    "fsRead": 3560,
    "fsWrite": 0,
    "ipcSent": 0,
    "ipcReceived": 0,
    "signalsCount": 0,
    "voluntaryContextSwitches": 909,
    "involuntaryContextSwitches": 23
  },
  "memoryUsage": {
    "rss": 40648704,
    "heapTotal": 7741440,
    "heapUsed": 5565928,
    "external": 1375139,
    "arrayBuffers": 26138
  },
  "uptimeSeconds": 19.124018903,
  "uptimeMilliSeconds": 19124.018903,
  "nodeJs": {
    "release": {
      "name": "node",
      "sourceUrl": "https://nodejs.org/download/release/v14.0.0/node-v14.0.0.tar.gz",
      "headersUrl": "https://nodejs.org/download/release/v14.0.0/node-v14.0.0-headers.tar.gz"
    },
    "verison": "v14.0.0",
    "cwd": "/path/of/current_working_directory",
    "arch": "x64",
    "platform": "linux",
    "argv": [
      "/path/of/nodejs_binary.../node/v14.0.0/bin/node",
      "src/index.ts"
    ]
  },
  "cpu": {
    "user": 1401985,
    "system": 898083
  },
  "etc": {},
  "actuatorVersion": "0.0.5"
}
```

### Getting metrics in ExpressJS app

If using it with express route, you just need to bind the `metricsExpress` method with whatever route path you want.

eg. 

```
import express from 'express';
import { json } from 'body-parser';

// import dependency
import { MetricExpressOptions, metricsExpress } from '@rectech/pro-metrics';

const PORT = process.env['PORT'] || 3000;

const app = express();
app.use(json());


// Metric options 
const metricOptions: MetricExpressOptions = {
  exposeEnv: false, // false - hide env variables in metrics, true - expose env variables in metrics 
  secured: false,   // if true, the binded-route will require `x-auth-pro-metric` header with value as `Basic base64Encoded(iginId:pass)`
  loginId: "auth",  // login id to secure the health/metric API, works only when `secured: true`
  loginPass: "pass" // login password to secure the health/metric API, works only when `secured: true`
}

// Bind route to `metricsExpress` method and security & validations will be handles automatically for this route
app.use('/api/health', (req, res) => {
    return metricsExpress(metricOptions, req, res)
});

app.listen(PORT, async () => console.log(`server is listening on port ${PORT}`));
```

Output:

```
curl http://localhost:3000/api/health 
```

Response: 

```
{
  "processId": 5741,
  "processParentId": 5734,
  "resourceUsage": {
    "userCPUTime": 1401778,
    "systemCPUTime": 897951,
    "maxRSS": 56244,
    "sharedMemorySize": 0,
    "unsharedDataSize": 0,
    "unsharedStackSize": 0,
    "minorPageFault": 5820,
    "majorPageFault": 1,
    "swappedOut": 0,
    "fsRead": 3560,
    "fsWrite": 0,
    "ipcSent": 0,
    "ipcReceived": 0,
    "signalsCount": 0,
    "voluntaryContextSwitches": 909,
    "involuntaryContextSwitches": 23
  },
  "memoryUsage": {
    "rss": 40648704,
    "heapTotal": 7741440,
    "heapUsed": 5565928,
    "external": 1375139,
    "arrayBuffers": 26138
  },
  "uptimeSeconds": 19.124018903,
  "uptimeMilliSeconds": 19124.018903,
  "nodeJs": {
    "release": {
      "name": "node",
      "sourceUrl": "https://nodejs.org/download/release/v14.0.0/node-v14.0.0.tar.gz",
      "headersUrl": "https://nodejs.org/download/release/v14.0.0/node-v14.0.0-headers.tar.gz"
    },
    "verison": "v14.0.0",
    "cwd": "/path/of/current_working_directory",
    "arch": "x64",
    "platform": "linux",
    "argv": [
      "/path/of/nodejs_binary.../node/v14.0.0/bin/node",
      "src/index.ts"
    ]
  },
  "cpu": {
    "user": 1401985,
    "system": 898083
  },
  "etc": {},
  "actuatorVersion": "0.0.5"
}
```

#### Using securly

If `MetricExpressOptions` object is set with `secured: true`, then the route will require `x-pro-metric-auth` header with value as `Basic base54Encoded(loginId:loginPass)`. You don't need to perform auth validation, automatically it will handle the authentication based on `MetricExpressOptions` config.

## Typing/API Details (in case you want the API structure)

```
export declare const metrics: (options: MetricOptions) => any;

export class MetricOptions{
    exposeEnv?: boolean = false;
    extras?: any;
}

export declare const metricsExpress: (options: MetricExpressOptions, req: any, res: any) => any;

export class MetricExpressOptions extends MetricOptions{
    loginId?: String;
    loginPass?: String;
    secured?: boolean = false;
}
```

## New Upcoming Features
There is a lot of possiblity to add new features, but here is a planned list of features:
- Support for visual analytics of metrics
- Support for live-log streaming
- Support for stop/restart NodeJS process via API
- Support for alerts (not well-planned, but still in the list)

Note: Since this is a side project that the author is working in his free time, there is no timeline about the upcoming features. More info will be available and contrubutions will be opened from anyone who wants to help/improve/maintain or add new features.  

## Support
Soon the support and issues acceptance will be made available on github or gitlab. 

## Authors and acknowledgment
To be updated soon.

## License
MIT 

## Project status
Active