philiplb/phpprom

PHPProm is a library to measure some performance relevant metrics and expose them for Prometheus

0.1.0 2016-11-20 22:30 UTC

This package is not auto-updated.

Last update: 2024-12-07 21:11:57 UTC


README

PHPProm is a library to measure some performance relevant metrics and expose them for Prometheus.

Its goal is to offer a simple, drop in solution to start measuring but without limiting customization.

As the measurements are regulary collected by Prometheus visiting a specific endpoint, they need to be stored. PHPProm offeres support for various backends like Redis or Memcached.

Grafana Sample

Documentation

Package

PHPProm uses SemVer for versioning. Currently, the API changes quickly due to be < 1.0.0, so take care about notes in the changelog when upgrading.

Stable

"require": {
    "philiplb/phpprom": "0.1.0"
}

Bleeding Edge

"require": {
    "philiplb/phpprom": "0.2.x-dev"
}

Getting Started

Here is an example about how to quickly get started measuring a Silex application using Redis as Storage:

Prerequisites

You need to have the PHP redis extension installed.

And you need to have a Redis server up and running. Here we just assume "localhost" as host and "supersecret" as authentication password.

Require PHPProm

The PHPProm package is integrated via composer:

composer require "philiplb/phpprom"

Setup the Silex Application

The first step is to create a storage object:

$storage = new PHPProm\Storage\Redis('localhost', 'supersecret');

With this, the Silex setup can be called. It returns a function to be used as metrics route which can be scraped by Prometheus:

$silexPrometheusSetup = new PHPProm\Integration\SilexSetup();
$metricsAction = $silexPrometheusSetup->setupAndGetMetricsRoute($app, $storage);
$app->get('/metrics', $metricsAction);

Integrations

Integrating some Prometheus scrapable metrics should be as easy as possible. So some setup steps of frameworks are abstracted away into integrations in order to make PHPProm a drop in solution.

More integrations are to come. If you have a specific request, just drop me a line. Or make a pull request. :)

Silex

The Silex integration measures the following metrics:

  • Time spent per route as gauge
  • Consumed memory per route as gauge
  • How often each route has been called as counter

Each metric has the route as label "name". Wheras the slashes are replaced by underscores and the route method is prefixed. So a route like this

$app->get('my/great/{route}', function($route) {
	// ...
});

gets the label "GET_my_great_{route}".

This integration requires the package "silex/silex".

It is represented by the class PHPProm\Integration\SilexSetup with it's usage explained in the "Getting Started" section.

Adding more metrics is easy via the function addAvailableMetric of the storage instance. See the subchapter for custom integrations for a detailed explanation of the parameters.

The actual measurements are added via the according storage instance functions (see again the custom integrations subchapter). All data automatically appears within the metrics endpoint.

Custom Integration

Writing a custom integration consists of three parts. First, the metrics have to be setup, second measurements needs to happen and third, a Prometheus scrapable metrics endpoint has to be offered.

First, the metrics to measure have to be added to the storage instance via the method addAvailableMetric:

$storage->addAvailableMetric(
	$metric, // the Prometheus metric name itself
	$label, // the name of the one Prometheus label to categorize the values
	$help, // a small, meaningful help text for the metric
	$type, // the Prometheus type of the metric like "gauge" or "counter"
	$defaultValue // the default value to be taken if no measurement happened yet for the metric/label combination, "Nan" for example or "0"
);

Now, the measurements have to happen. The storage object offers two methods for this:

  • storeMeasurement($metric, $key, $value): to store a raw value for a metric under the given key
  • incrementMeasurement($metric, $key): increments a counter for the metric under the given key, starts with 1 if it didn't exist before

There is a little helper class to measure time, the PHPProm\StopWatch. To start the measurement, call its function start() and to stop and store the measurement, call the function stop($metric, $key). The parameters have the same meaning as the storage function parameters.

The third part is to offer an endpoint delivering the metrics. To get the content, the class PHPProm\PrometheusExport exists. It has a single public function getExport(AbstractStorage $storage, $keys) where the storage instance is handed in along with all expected keys. The function returns a string with all the Prometheus data to be used as response in the endpoint. It should be delivered with the "Content-Type: text/plain; version=0.0.4".

Storage Implementations

There are several storage implementations available for the measurements so the metrics endpoint can deliver them. It is also easy to write an own one if the existing ones don't cover the use case. They are all in the namespace PHPProm\Storage.

Redis

The Redis storage needs to have the PHP redis extension installed. Its constructor takes the following parameters:

  • string $host: the connection host
  • null|string $password: the password for authentication, null to ignore
  • int $port: the connection port, default 6379
  • string $prefix: the global key prefix to use, default 'PHPProm:'
  • null|string $dbIndex: the Redis DB index to use, null to ignore

It is very fast and offers persistence, so this one is the recommended storage implementation.

Memcached

The Memcached storage implementation needs to have the PHP memcached extension installed. Its constructor takes the following parameters:

  • string $host: the connection host
  • int $port: the connection port, default 11211
  • string $prefix: the global key prefix to use, default 'PHPProm:'

This storage implementation is even faster then Redis, but offers no persistence and so is not recommended if there are counters measured over time for example which should not be lost.

DBAL

The DBAL storage implementation needs to have the package "doctrine/dbal" and the prerequisites of the used driver must be fullfilled. Currently, the MySQL, PostgreSQL and SQLite drivers have been tested. But the SQL statements have been kept simple in order to be compatible with many of the DBAL supported databases. Give me a shout if you find something not working.

Its constructor takes the following parameters:

  • \Doctrine\DBAL\Connection $connection: the DBAL connection
  • string $table: the table to use

The MySQL scheme of the table is:

 CREATE TABLE `phpprom` (
     `key` varchar(255) NOT NULL,
     `value` double NOT NULL,
     PRIMARY KEY (`key`)
 ) ENGINE=InnoDB DEFAULT CHARSET=utf8;

The SQLite scheme of the table is:

CREATE TABLE `phpprom` (
	`key`	TEXT NOT NULL UNIQUE,
	`value`	REAL NOT NULL,
	PRIMARY KEY(`key`)
);

The PostgreSQL scheme of the table is:

CREATE TABLE public.phpprom (
    key VARCHAR(255) PRIMARY KEY NOT NULL,
    value DOUBLE PRECISION NOT NULL
);
CREATE UNIQUE INDEX phpprom_key_uindex ON public.phpprom (key);

This one is possibly the slowest one, but offers a secure data storage and is mostly available in existing stacks.

MongoDB

The MongoDB storage needs to have the PHP MongoDB driver installed. Its constructor takes the following parameters:

  • string $host: a mongodb:// connection URI
  • string $database: the database to use, defaults to "phppromdb"
  • string $collection: the collection to use, defaults to "measurements"
  • array $options: connection string options, defaults to []
  • array $driverOptions: any driver-specific options not included in MongoDB connection spec, defaults to []

This storage should be reasonable fast, offers persistence but should maybe only taken if Redis, MySQL or PostgreSQL is not available.

Custom

In case you want to store the measurements in a different backend, you can inherit your implementation from PHPProm\Storage\AbstractStorage and implement the abstract methods:

  • abstract public function storeMeasurement($metric, $key, $value): Stores a measurement.
  • abstract public function incrementMeasurement($metric, $key): Increments a measurement, starting with 1 if it doesn't exist yet.
  • abstract public function getMeasurements($metric, array $keys, $defaultValue = 'Nan'): Gets all measurements.

New storage implementations would make a good pull request again. :)

Status

Build Status Coverage Status

SensioLabsInsight Scrutinizer Code Quality

Total Downloads Latest Stable Version Latest Unstable Version License