Suitability of Apache NiFi as a metrics collection tool
Tags: programming
Published: 2022-02-01 11:51:14

> *“If you can’t measure it, you can’t manage it”*

*Peter Drucker, father of management thinking*

[Metrics](https://maddevs.io/insights/blog/software-development-metrics/?utm_source=devto) are essential for a successful company. As a metric, we understand a set of measures used for assessing and comparing a company's performance. They are usually used to build a dashboard that's regularly reviewed by management or analysts.

There are several uses where a good metrics program is almost crucial:

* Problem analysis - metrics help identify the reasons why your company is failing to meet its ultimate business goal;
* Process improvement - metrics show what is working and what is not working and need adjustments;
* Recognition - metrics identify the processes and employees that are truly impacting  for high performance;  
* Goal settings - metrics process have impact on specific goal settings, key performance indicators, and milestones;
* Budgeting - metrics can be used to justify continuing or increasing funding.
* Trend development - good for developing trends that influence the dynamics of a company's process.  

Many metrics are located in different systems, databases, records. So how to determine, collect and monitor them? This article aims to explore the capabilities of Apache NiFi as a means of implementing a metrics collection system.
[![Red flags](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rxx199492g757mst7oiz.png)](https://maddevs.io/customer-university/red-flags-in-software-development/?utm_source=devto)
## Tool overview

[Apache Nifi](https://github.com/apache/nifi) (hereinafter “NiFi”) is a system that implements [ETL](https://ru.wikipedia.org/wiki/ETL) (Extract, Transform, Load) processes. The system is distributed under the shareware [Apache 2.0](https://github.com/apache/nifi/blob/main/LICENSE) license (owned by the Apache Software Foundation). The system allows collecting data from various sources, transforming it “on the fly” and sending it to the receiving system. The system has a wide range of integration capabilities. The source/recipient of data can be:

* systems with an HTTP interface (including REST API, gRPC, and WebSocket);
* queue managers (RabbitMQ, Apache Kafka);
* document-oriented systems (MongoDB, Cassandra);
* relational DBMS (MySQL, PostgreSQL, SQL Server, Oracle, and others if there is an appropriate driver);
* external utilities.

To describe the processes, NiFi offers a web-based designer interface that allows describing the process of receiving, transforming, and sending data in the form of blocks and links between them. Accordingly, NiFi implements the [FBP](https://en.wikipedia.org/wiki/Flow-based_programming) concept. The interface looks like this:
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7ol34xfh6z6y2mofemw1.png)
To describe the processes NiFi proposes to use the following components:

* **FlowFile** - a data packet capable of containing content and metadata to it in the form of attributes.

* **Processor** - a handler capable of generating, redirecting, converting stream files, or performing other actions. The current version at the time of this writing contained 288 types of handlers. It is worth noting the following separately:

* it is possible to run external utilities for processing;
* it is possible to create programmable processors using Python, Lua, ECMAScript, Clojure, Groovy, Ruby;
* it is possible to implement proprietary processors in Java (see [here](https://bryanbende.com/development/2015/02/04/custom-processors-for-apache-nifi) and [here](https://medium.com/hashmapinc/creating-custom-processors-and-controllers-in-apache-nifi-e14148740ea))
* **Connection** - transferring stream files between processors.

* **Process Group** - a group of processors that form a single process.

* **Input Port / Output Port** -  to delegate data input between different project teams.

Each individual block of the process group, like the process groups themselves, can be stopped and started, thus controlling the work process. The installation type is “on-premise” and supports clustering (using [Apache ZooKeeper](https://nifi.apache.org/docs/nifi-docs/html/administration-guide.html#clustering)) for fault tolerance and horizontal scalability. Change versioning is supported using the [Apache NiFi Registry](https://nifi.apache.org/registry.html). Thus, it is possible to save and rollback process description models in NiFi.

## Practical task
As part of the development of a metrics collection system, Mad Devs team was tasked with integrating with different systems: [Jira](https://maddevs.io/insights/blog/project-management-using-jira/), GitLab and SonarQube. Each of them has a REST-based HTTP interface. For Jira, there is already an article [“Automating Jira Analytics with Apache NiFi”](https://habr.com/ru/post/527624/), so we decided to consider integration with GitLab on a publicly accessible repository. For a practical task, the following requirements were determined:

* get pipeline data;
* remove redundant data from packets;
* send the data to the receiving system (in the subsequent stages it will be replaced by a bunch of PostgreSQL and Grafana).

## Implementation of a practical task
### Conventions
To interact with GitLab, we will take as a basis [GitLab Pipelines API v4](https://docs.gitlab.com/ee/api/pipelines.html) and the current Apache NiFi 1.14.0 version in the form of a Docker container. We will use [“AutowareAuto”](https://gitlab.com/autowarefoundation/autoware.auto/AutowareAuto) as a publicly available GitLab project.
### Installation
Installation and launch:
![Suitability of Apache NiFi](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yx8d0q7bf9bmlmvafnmb.png)
The system will be available at [https://localhost:8443/nifi](https://localhost:8443/nifi) (it may take about a couple of minutes for the container to fully start) and will ask for authorization.

Login and password are generated when the system is first started. To find them out, run the following command:

`docker exec -ti nifi /bin/bash`

Once in the container shell, run **grep** on the **"Generated"** phrase on the **logs/nifi-app.log file**:

`grep Generated logs/nifi-app.log`

We get:

`Generated Username [username]
Generated Password [password]`

To exit the shell, execute the command:
`exit`

We enter the data **without brackets** when requesting authorization at the local address [https://localhost:8443/nifi/login](https://localhost: 8443/nifi/login).

### Process description
The first step is to add a new process group and name it “Build Status Metric”:
![Suitability of Apache NiFi](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/j4qv0kwbwa22dypbm60h.png)
Double-click on the process group to switch to its local context. To access the GitLab API Pipelines, we need to generate the following URL:

`https://gitlab.com/api/v4/projects/{PROJECT_ID}/pipelines?page={CURRENT_PAGE}&per_page={PER_PAGE}`

Where: 

* **PROJECT_ID** - identifier of the GitLab project;
* **CURRENT_PAGE** - current page (default 1);
* **PER_PAGE** - number of items per page (default 20).

In order to start a process in NiFi, an initiating trigger must be defined. For this, the **"GenerateFlowFile"** processor is suitable, which generates a stream file on a timer. Let's place the **“GenerateFlowFile”** processor and define its following properties:

• Name *“Trigger: dispatch GitLab project ID”*.

• Scheduled start “60 seconds” - can be adjusted arbitrarily so that stream files are not generated too often.

• In the properties add the attribute *“PROJECT_ID”* with the value *“8229519”* (ID of the selected GitLab project).
![Trigger](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9quwvyuinzmnic0dpbr9.png)
![Configure processor](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/c4t9zi2bnz4bwedjvyv5.png)
![Configure processor2](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/n2j9t1wqkmvaoj4y3mop.png)
We have defined an initiating trigger that generates a stream file with the project ID as a metadata attribute. Let's add a processor that additionally sets pagination attributes, since it is not possible to get all the data in one request. To do this, place the **"UpdateAttribute"** processor and define the following settings for it:

* Name _“Set pagination attributes”_.
* Add the following attributes to the properties:

**"CURRENT_PAGE"** with value **“1”** (start page).
**"PER_PAGE"** with value **“5”** (arbitrary number of elements per page).
![Pagination attributes](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/v6bknfa8j8pyui8eo275.png)
![Configure processor3](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4wlsq5vlg7hzbhp5ss8e.png)
![Configure processor4](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pcb3cq6c05gpevtere30.png)
Let's connect the processors with the **“success”** link (stretching the arrow icon from the first to the second, respectively):
![Trigger](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9rldi7kq4k4je9ce2g19.png)
At this stage, we have all the data to make an HTTP request to the GitLab API. In NiFi, the most functional processor for this is the **“InvokeHTTP”**. Let's place this processor and define its following settings:

* Name _“Get pipeline data from GitLab”_.
* Configure automatic termination of sending stream files in the states _“Failure”, “No Retry”, “Original”, “Retry”_.
* In the properties, configure the following existing attributes:
For **"HTTP Method"** set the value **"GET"**.
For **“Remote URL”**, set a value using the [built-in expression language instructions](https://nifi.apache.org/docs/nifi-docs/html/expression-language-guide.html) for substituting data from attributes:

`https://gitlab.com/api/v4/projects/${PROJECT_ID}/pipelines?page=${CURRENT_PAGE}&per_page=${PER_PAGE}`

Make sure that **“Ignore response's content”** is set to **“false”**.
![Configure processor6](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xywn71v1g1ezsvaw46pi.png)
![Configure processor5](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/97hmx4qag1q7ohxn3zhi.png)
Connect the processors with the **“success”** link:
![Connect the processor](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/s6b4yeqclxbk2e18zjgj.png)
GitLab API, if there are elements to be returned, will return them as an array in JSON. If there are no elements, an empty array will be returned - in this case, no further action is required. It is possible to calculate the length of an array with elements using the **”EvaluateJsonPath”** processor. Let's place this processor and define its following settings:

* The name _“Estimate amount of array elements”_.
* Configure automatic termination of sending stream files in the states _“failure”, “unmatched”_.
* In the properties, configure the following existing attributes:
For **“Destination”**, set the value **“flowfile-attribute”** (ie, write it as a metadata attribute, not as content).
Add the following attributes to the properties:
**”array_len”** with the value `$ .length ()`.
![Estimate amount of array](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cfzdwsakt5pvzxyhtkiy.png)
![Configure processor](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5f6hooudh7rrzmulmm1v.png)
![Configure processor](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ywqrz2xmacbrv0xit8yj.png)

After we connect the processors with the **“Response”** link:
![Configure Proccesor](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/q7gux8cqsiyf0nbkps93.png)
Now we redirect the stream files, provided that the length of the array is greater than or equal to zero. Let's place the **“RouteOnAttribute”** processor and define the following settings for it:

* Name _“Route: empty or filled array”_.
* In the properties, configure the following existing attributes:
For **“Routing Strategy”** set the value **“Route to Property name”**.
* Add the following attributes to the properties:
**“empty”** with the value `$ {array_len: equals (0)}`.
**“filled”** with the value `$ {array_len: gt (0)}`.
Configure automatic termination of sending stream files in the _“empty”, “unmatched” _states.
![Suitability of Apache NiFi](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mu0qh8yvexxlgf4cgg7f.png)
![Suitability of Apache NiFi](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/r0kdf54vkk1ez74v5dmt.png)
![Suitability of Apache NiFi](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3ypxn7b7cazrdchsn75w.png)
Then we connect the processors with a **“matched”** link:
![Suitability of Apache NiFi](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lqihe5vrz8dgrthm1ik3.png)
If the array passes empty then the **“empty”** rule will stop transferring files from the stream. If the length of the array is positive, then you need to do 2 types of actions:

* enlarge the page and restart fetching data from GitLab;
* process the current data.

First of all, we will loop receiving data using one more **“UpdateAttribute”** processor. We place the processor and define the following settings for it:

* The name is _“Update pagination attributes”_.
* Add the following attributes to the properties:
**"CURRENT_PAGE"** with the value `$ {CURRENT_PAGE: plus (1)}` (next page).

We will also connect the processors of redirecting, updating pagination and receiving data from GitLab in the manner shown in the screenshot below:
![Suitability of Apache NiFi](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/69hczwq0e9s642j4e7ca.png)
![Suitability of Apache NiFi](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vktpj81m1dyn4jpbeulw.png)
![Suitability of Apache NiFi](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hi5qxabr05jgn27jjb0m.png)
Now we continue working on the existing data. The array of data returned by the GitLab API contains several elements that have the following structure:
![Suitability of Apache NiFi](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8yj7la2uw7sa49cy00ol.png)
We see that there is more data than required. To clean up data from redundant data, first split the stream file with the array into small stream files with its elements. Let's do it using the **“SplitJson”** processor. We place the processor and define the following settings for it:

* Name _“Split array to standalone elements”_.
* Configure automatic termination of sending stream files in the states _“failure”, “original”_.
* In the properties, configure the following existing attributes:
**“JsonPath Expression”** with the value `$.*`.
![Suitability of Apache NiFi](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/svy6vazqo7dswax1l111.png)
![Suitability of Apache NiFi](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/eie2zjycfar4fufdsuvr.png)
![Suitability of Apache NiFi](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/34f4uwl5en6oddflobw3.png)
Connect the processors with the **“filled”** link (as with the pagination attribute update processor):


![Suitability of Apache NiFi](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6g5e9lo8pmc5lnr3nzy8.png)

Now several stream files will be generated, and each of them will contain a separate pipeline data object. Let's finish cleaning up the redundancy using the **“JoltTransformJSON”** processor. It will allow the Jolt transformation notation to be applied to the data of stream files ([sandbox](https://jolt-demo.appspot.com/)). Let's place the processor and define the following settings for it:

* Name _“Transform data: preserve only required”_.
* Configure automatic termination of sending stream files in case of _“failure”_ state.
* In the properties, configure the following existing attributes:
“Jolt Specification” with meaning:

![Suitability of Apache NiFi](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9jxoeblroqb4f98uxnne.png)
![Suitability of Apache NiFi](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/u3dxz6cfycupc6ctrgtc.png)
![Suitability of Apache NiFi](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/30xo8uyieh88dez38yv5.png)
![Suitability of Apache NiFi](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/s4ykcpz3qk1z3l77xvhp.png)

So we connect the processors with a **“split”** link:

![Suitability of Apache NiFi](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/v9119mhqymdeshlg7ehd.png)

At this stage, it remains to send the converted data to the receiving system. For simplicity of experiment, let's implement a simple web server on the NodeJS platform and the ExpressJS framework:

* Create a new directory and execute the command in it:

`npm init`
* Update the **package.json** manifest file as follows:

![Suitability of Apache NiFi](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/m2hrs450i3cp1fxeg2uz.png)

* Install dependencies using the command:

`npm install`
*  Create an index.js file with the following content:

![Suitability of Apache NiFi](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/60irg0gpyx8vlgpv0uj3.png)
*  Start the server using the command:
`node index.js`

Add one more processor **“InvokeHTTP”** to NiFi and define the following settings for it:

* Name _“Put data to storage”_.
* Configure automatic termination of sending stream files in the states _“Failure”, “No Retry”, “Original”, “Retry”, “Response”_.
* In the properties, configure the following existing attributes:
**“HTTP Method”** with the value **“POST”**.
 **“Remote URL”** with a value that corresponds to the server address being routed from the NiFi container. In our case, it was the address [http://172.17.0.1:3000/](http://172.17.0.1:3000/).
**“Send Message Body”** with the value **“true”**.
**“Ignore response's content”** with the value **“true”**.
* Add the following attributes to the properties:
**“HEADER_CURRENT_PAGE”** with the value `$ {CURRENT_PAGE}`.
**“HEADER_CURRENT_PROJECT”** with the value `$ {PROJECT_ID}`.

![Suitability of Apache NiFi](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/n731tw0i8yk7q3no584o.png)
![Suitability of Apache NiFi](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/q6swze92di2gzd05wt5r.png)
![Suitability of Apache NiFi](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jdld9g4uzyb6yaw44jce.png)

![Suitability of Apache NiFi](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/guvquii22v79kbo83hek.png)
Connect the processors with the **“success”** link:

![Suitability of Apache NiFi](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2jl8yyafq8yr1byptpqo.png)
Open the context menu on an empty space in the workspace by right-clicking

![Suitability of Apache NiFi](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/v7ogdc0rmojq94snq1nx.png)

Items **“Start”/“Stop”** should lead to the start and stop of data transfer. The item **“Empty all queues”** should empty the queues that could have accumulated during stops. The item **“Download flow definition”** will save the current process as a JSON file. It can be loaded when adding a process group:

![Suitability of Apache NiFi](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gz0omf86c4iisblt80nl.png)

## Configurator competencies and qualities
Consider the competencies and qualities required by the user, who will subsequently be responsible for configuring and maintaining the system:

**Key features:**

* Knowledge of network communication protocols (HTTP, TCP, UDP).
* Knowledge of application programming interfaces for data exchange (REST API).
* Knowledge of data transfer formats and methods of working with them (JSON, XML).
* General skills in working with relational databases (RDBMS). * Knowledge of SQL (DDL, DML).
* Analytical mindset.
* Decomposition skills.

**Optional features:**

* Experience with GitLab, knowledge of the GitLab API.
* Experience with Jira, knowledge of Jira API and JQL.
* Knowledge of APIs other than REST, such as GraphQL.
* Knowledge of JsonPath.
* Knowledge of Jolt.
* Experience and knowledge of one of the programming languages Python, Lua, ECMAScript, Clojure, Groovy, Ruby for the implementation of programmable processors, or Java for the implementation of proprietary processors.
* Experience and knowledge of principles of working with message brokers such as RabbitMQ or Apache Kafka.

## Conclusion
When your company is already swimming in data, metric collection helps you focus on only useful data for improving processes and achieving business goals. For this purpose, the Apache NiFi system is considered. The generated process definition illustrates the possibilities when used as a tool for a metrics collection system. The system is suitable because it has the necessary functionality and characteristics for the implementation of these processes.

[![CTA](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wu9dznmknn0uvfmr2q1i.png)](https://maddevs.io/services/?utm_source=devto)

Previously published at [maddevs.io/blog](https://maddevs.io/blog/apache-nifi-as-metric-collection-tool/?utm_source=devto).