Skip to content

Commit

Permalink
feat: add Invocable scripts API (#119)
Browse files Browse the repository at this point in the history
  • Loading branch information
bednar authored Mar 29, 2022
1 parent d5abfd8 commit 013ad87
Show file tree
Hide file tree
Showing 18 changed files with 4,116 additions and 21 deletions.
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
## 2.7.0 [unreleased]

### Features
1. [#119](https://github.com/influxdata/influxdb-client-php/pull/119): Add `InvocableScriptsApi` to create, update, list, delete and invoke scripts by seamless way

### CI
1. [#118](https://github.com/influxdata/influxdb-client-php/pull/118): Use new Codecov uploader for reporting code coverage

Expand Down
28 changes: 14 additions & 14 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
![PHP from Packagist](https://img.shields.io/packagist/php-v/influxdata/influxdb-client-php)
[![Slack Status](https://img.shields.io/badge/slack-join_chat-white.svg?logo=slack&style=social)](https://www.influxdata.com/slack)

This repository contains the reference PHP client for the InfluxDB 2.0.
This repository contains the reference PHP client for the InfluxDB 2.x.

#### Note: Use this client library with InfluxDB 2.x and InfluxDB 1.8+ ([see details](#influxdb-18-api-compatibility)). For connecting to InfluxDB 1.7 or earlier instances, use the [influxdb-php](https://github.com/influxdata/influxdb-php) client library.

Expand All @@ -23,7 +23,7 @@ This repository contains the reference PHP client for the InfluxDB 2.0.
- [Advanced Usage](#advanced-usage)
- [Check the server status](#check-the-server-status)
- [InfluxDB 1.8 API compatibility](#influxdb-18-api-compatibility)
- [InfluxDB 2.0 management API](#influxdb-20-management-api)
- [InfluxDB 2.x management API](#influxdb-2x-management-api)
- [Writing via UDP](#writing-via-udp)
- [Delete data](#delete-data)
- [Proxy and redirects](#proxy-and-redirects)
Expand All @@ -34,7 +34,7 @@ This repository contains the reference PHP client for the InfluxDB 2.0.

This section contains links to the client library documentation.

* [Product documentation](https://docs.influxdata.com/influxdb/v2.0/tools/client-libraries/), [Getting Started](#usage)
* [Product documentation](https://docs.influxdata.com/influxdb/latest/tools/client-libraries/), [Getting Started](#usage)
* [Examples](examples)
* [API Reference](https://influxdata.github.io/influxdb-client-php/)
* [Changelog](CHANGELOG.md)
Expand Down Expand Up @@ -231,7 +231,7 @@ $client->close();
### Writing data

The [WriteApi](https://github.com/influxdata/influxdb-client-php/blob/master/src/InfluxDB2/WriteApi.php) supports
synchronous and batching writes into InfluxDB 2.0. In default api uses synchronous write. To enable batching you
synchronous and batching writes into InfluxDB 2.x. In default api uses synchronous write. To enable batching you
can use WriteOption.

```php
Expand Down Expand Up @@ -406,25 +406,25 @@ $this->writeApi->write($point);

### Check the server status

Server availability can be checked using the `$client->ping();` method. That is equivalent of the [influx ping](https://v2.docs.influxdata.com/v2.0/reference/cli/influx/ping/).
Server availability can be checked using the `$client->ping();` method. That is equivalent of the [influx ping](https://docs.influxdata.com/influxdb/latest/reference/cli/influx/ping/).

### InfluxDB 1.8 API compatibility

[InfluxDB 1.8.0 introduced forward compatibility APIs](https://docs.influxdata.com/influxdb/v1.8/tools/api/#influxdb-2-0-api-compatibility-endpoints) for InfluxDB 2.0. This allow you to easily move from InfluxDB 1.x to InfluxDB 2.0 Cloud or open source.
[InfluxDB 1.8.0 introduced forward compatibility APIs](https://docs.influxdata.com/influxdb/v1.8/tools/api/#influxdb-2-0-api-compatibility-endpoints) for InfluxDB 2.x. This allow you to easily move from InfluxDB 1.x to InfluxDB 2.x Cloud or open source.

The following forward compatible APIs are available:

| API | Endpoint | Description |
|:----------|:----------|:----------|
| [QueryApi.php](src/InfluxDB2/QueryApi.php) | [/api/v2/query](https://docs.influxdata.com/influxdb/latest/tools/api/#api-v2-query-http-endpoint) | Query data in InfluxDB 1.8.0+ using the InfluxDB 2.0 API and [Flux](https://docs.influxdata.com/flux/latest/) _(endpoint should be enabled by [`flux-enabled` option](https://docs.influxdata.com/influxdb/latest/administration/config/#flux-enabled-false))_ |
| [WriteApi.php](src/InfluxDB2/WriteApi.php) | [/api/v2/write](https://docs.influxdata.com/influxdb/latest/tools/api/#api-v2-write-http-endpoint) | Write data to InfluxDB 1.8.0+ using the InfluxDB 2.0 API |
| [HealthApi.php](src/InfluxDB2/HealthApi.php) | [/health](https://docs.influxdata.com/influxdb/latest/tools/api/#health-http-endpoint) | Check the health of your InfluxDB instance |
| API | Endpoint | Description |
|:----------|:----------|:---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| [QueryApi.php](src/InfluxDB2/QueryApi.php) | [/api/v2/query](https://docs.influxdata.com/influxdb/latest/tools/api/#api-v2-query-http-endpoint) | Query data in InfluxDB 1.8.0+ using the InfluxDB 2.x API and [Flux](https://docs.influxdata.com/flux/latest/) _(endpoint should be enabled by [`flux-enabled` option](https://docs.influxdata.com/influxdb/latest/administration/config/#flux-enabled-false))_ |
| [WriteApi.php](src/InfluxDB2/WriteApi.php) | [/api/v2/write](https://docs.influxdata.com/influxdb/latest/tools/api/#api-v2-write-http-endpoint) | Write data to InfluxDB 1.8.0+ using the InfluxDB 2.x API |
| [HealthApi.php](src/InfluxDB2/HealthApi.php) | [/health](https://docs.influxdata.com/influxdb/latest/tools/api/#health-http-endpoint) | Check the health of your InfluxDB instance |

For detail info see [InfluxDB 1.8 example](examples/InfluxDB_18_Example.php).

### InfluxDB 2.0 management API
### InfluxDB 2.x management API

InfluxDB 2.0 API client is generated using [`influxdb-clients-apigen`](https://github.com/bonitoo-io/influxdb-clients-apigen). Sources are in `InfluxDB2\Service\` and `InfluxDB2\Model\` packages.
InfluxDB 2.x API client is generated using [`influxdb-clients-apigen`](https://github.com/bonitoo-io/influxdb-clients-apigen). Sources are in `InfluxDB2\Service\` and `InfluxDB2\Model\` packages.

The following example shows how to use `OrganizationService` and `BucketService` to create a new bucket.

Expand Down Expand Up @@ -509,7 +509,7 @@ $writer->close();

### Delete data

The [DefaultService.php](/src/InfluxDB2/Service/DefaultService.php) supports deletes [points](https://v2.docs.influxdata.com/v2.0/reference/glossary/#point) from an InfluxDB bucket.
The [DefaultService.php](/src/InfluxDB2/Service/DefaultService.php) supports deletes [points](https://docs.influxdata.com/influxdb/latest/reference/syntax/line-protocol/) from an InfluxDB bucket.

```php
<?php
Expand Down
118 changes: 118 additions & 0 deletions examples/InvocableScripts.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
<?php
/**
* Show to use Invocable scripts Cloud API to create custom endpoints that query data
*
* Invocable Scripts are supported only in InfluxDB Cloud, currently there is no support in InfluxDB OSS.
*/

require __DIR__ . '/../vendor/autoload.php';

use InfluxDB2\Client;
use InfluxDB2\Model\ScriptCreateRequest;
use InfluxDB2\Model\ScriptUpdateRequest;
use InfluxDB2\Point;

$organization = 'my-org';
$bucket = 'my-bucket';
$token = 'my-token';

//
// Creating client
//
$client = new Client([
"url" => "https://us-west-2-1.aws.cloud2.influxdata.com",
"token" => $token,
"bucket" => $bucket,
"org" => $organization,
"precision" => InfluxDB2\Model\WritePrecision::S
]);

//
// Prepare data
//
$point1 = Point::measurement("my_measurement")
->addTag("location", "Prague")
->addField("temperature", 25.3);
$point2 = Point::measurement("my_measurement")
->addTag("location", "New York")
->addField("temperature", 24.3);
$client->createWriteApi()->write([$point1, $point2]);

//
// Creating InvocableScripts Api
//
$scriptsApi = $client->createInvocableScriptsApi();

//
// Create Invocable Script
//
print "\n------- Create -------\n";
$scriptQuery = 'from(bucket: params.bucket_name) |> range(start: -30d) |> limit(n:2)';
$createRequest = new ScriptCreateRequest([
'name' => "my_script_" . microtime(),
'description' => "my first try",
'script' => $scriptQuery,
'language' => InfluxDB2\Model\ScriptLanguage::FLUX,
]);
$createdScript = $scriptsApi->createScript($createRequest);
print $createdScript;

//
// Update Invocable Script
//
print "\n------- Update -------\n";
$updateRequest = new ScriptUpdateRequest([
'description' => "my updated description"
]);
$createdScript = $scriptsApi->updateScript($createdScript->getId(), $updateRequest);
print $createdScript;

//
// Invoke a script
//
print "\n------- Invoke to FluxTables -------\n";
$tables = $scriptsApi->invokeScript($createdScript->getId(), ["bucket_name" => $bucket]);
foreach ($tables as $table) {
foreach ($table->records as $record) {
print "\n${record['time']} ${record['location']}: ${record['_field']} ${record['_value']}";
}
}

//
// Stream of FluxRecords
//
print "\n";
print "\n------- Invoke to Stream of FluxRecords -------\n";
$records = $scriptsApi->invokeScriptStream($createdScript->getId(), ["bucket_name" => $bucket]);
foreach ($records->each() as $record) {
print "\n${record['time']} ${record['location']}: ${record['_field']} ${record['_value']}";
}

//
// RAW
//
print "\n";
print "\n------- Invoke to Raw-------\n";
$raw = $scriptsApi->invokeScriptRaw($createdScript->getId(), ["bucket_name" => $bucket]);
print "RAW output:\n\n ${raw}";

//
// List scripts
//
print "\n------- List -------\n";
$scripts = $scriptsApi->findScripts();
foreach ($scripts as $script) {
$scriptId = $script->getId();
$scriptName = $script->getName();
$scriptDescription = $script->getDescription();
print " ---\n ID: $scriptId\n Name: $scriptName\n Description: $scriptDescription";
}

//
// Delete previously created Script
//
print "\n------- Delete -------\n";
$scriptsApi->deleteScript($createdScript->getId());
print "Successfully deleted script: '" . $createdScript->getName();

$client->close();
3 changes: 2 additions & 1 deletion examples/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,4 +18,5 @@

## Others
- [InfluxDB_18_Example.php](InfluxDB_18_Example.php) - How to use forward compatibility APIs from InfluxDB 1.8
- [DeleteDataExample.php](DeleteDataExample.php) - How to delete data from InfluxDB by client
- [DeleteDataExample.php](DeleteDataExample.php) - How to delete data from InfluxDB by client
- [InvocableScripts.php](InvocableScripts.php) - How to use Invocable scripts Cloud API to create custom endpoints that query data
2 changes: 1 addition & 1 deletion scripts/influxdb-onboarding.sh
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@

set -e

echo "Wait to start InfluxDB 2.0"
echo "Wait to start InfluxDB 2.x"
wget -S --spider --tries=20 --retry-connrefused --waitretry=5 http://localhost:8086/metrics

echo
Expand Down
13 changes: 13 additions & 0 deletions src/InfluxDB2/Client.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace InfluxDB2;

use InfluxDB2\Model\HealthCheck;
use InfluxDB2\Service\InvocableScriptsService;
use InfluxDB2\Service\PingService;
use ReflectionClass;
use RuntimeException;
Expand Down Expand Up @@ -99,6 +100,18 @@ public function createQueryApi(): QueryApi
return new QueryApi($this->options);
}

/**
* Create an InvocableScripts API instance.
*
* @return InvocableScriptsApi
*/
public function createInvocableScriptsApi(): InvocableScriptsApi
{
/** @var InvocableScriptsService $service */
$service = $this->createService(InvocableScriptsService::class);
return new InvocableScriptsApi($this->options, $service);
}

/**
* Get the health of an instance.
*
Expand Down
12 changes: 10 additions & 2 deletions src/InfluxDB2/FluxCsvParser.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ class FluxCsvParser

private $response;
private $stream;
private $responseMode;
private $resource;

/* @var $variable int */
Expand All @@ -41,12 +42,14 @@ class FluxCsvParser
* FluxCsvParser constructor.
* @param $response mixed response to by parsed
* @param $stream bool use streaming
* @param $responseMode string metadata expected in response ('full', 'only_names')
*/
public function __construct($response, $stream = false)
public function __construct($response, bool $stream = false, string $responseMode = "full")
{
$this->response = is_string($response) ? null : $response;
$this->resource = is_string($response) ? $this->stringToStream($response) : $response->detach();
$this->stream = $stream;
$this->responseMode = $responseMode;
$this->tableIndex = 0;
if (!$stream) {
$this->tables = [];
Expand Down Expand Up @@ -109,7 +112,8 @@ private function parseLine(array $csv)
{
$token = $csv[0];
# start new table
if (in_array($token, self::ANNOTATIONS) && !$this->startNewTable) {
if ((in_array($token, self::ANNOTATIONS) && !$this->startNewTable)
|| ($this->responseMode == "only_names" && is_null($this->table))) {
# Return already parsed DataFrame
$this->startNewTable = true;
$this->table = new FluxTable();
Expand Down Expand Up @@ -190,6 +194,10 @@ private function parseValues(array $csv)
{
# parse column names
if ($this->startNewTable) {
if ($this->responseMode == 'only_names' && empty($this->table->columns)) {
$this->addDataTypes($this->table, array_fill(0, sizeof($csv), 'string'));
$this->groups = array_fill(0, sizeof($csv), 'false');
}
$this->addGroups($this->table, $this->groups);
$this->addColumnNamesAndTags($this->table, $csv);
$this->startNewTable = false;
Expand Down
Loading

0 comments on commit 013ad87

Please sign in to comment.