influxdb-cxx

repository·master·Indexed 40 days ago

https://github.com/offa/influxdb-cxx

A C++20 client library for InfluxDB supporting batch writing, data exploration via queries, and multiple transport protocols including HTTP, TCP, UDP, and Unix sockets. It provides a fluent interface for configuring transports, supports InfluxDB Line Protocol formatting, and offers authentication via basic auth or API tokens.

Tokens
3.4K
Snippets
17
Records
20
Agent score
49%

What's inside influxdb-cxx

  1. Include influxdb-cxx in a CMake project

    master

    The library exports the target InfluxData::InfluxDB. You can include it either via find_package or by adding the source as a subdirectory.

    Using find_package:

    project(example)
    
    find_package(InfluxDB)
    
    add_executable(example-influx main.cpp)
    target_link_libraries(example-influx PRIVATE InfluxData::InfluxDB)

    Using add_subdirectory:

    project(example)
    add_subdirectory(influxdb-cxx)
    add_executable(example-influx main.cpp)
    target_link_libraries(example-influx PRIVATE InfluxData::InfluxDB)
  2. Install influxdb-cxx

    master

    To install the library from source, ensure you have CMake 3.12+ and a C++20 compatible compiler. You must have cpr installed (which requires CMake support). boost 1.90+ is optional and only required if you intend to use TCP, UDP, or Unix socket transports.

    Run the following commands to build and install:

    mkdir build && cd build
    cmake ..
    sudo make install
  3. Perform batch writes to InfluxDB

    master

    To improve performance, you can enable batching using batchOf(size). This buffers points and writes them in chunks of the specified size.

    Important: When batch writing is enabled, you must call flushBatch() to ensure all pending points are written to the server, especially before the client object is destroyed.

    auto influxdb = influxdb::InfluxDBFactory::Get("http://localhost:8086?db=test");
    // Write batches of 100 points
    influxdb->batchOf(100);
    
    for (;;) {
      influxdb->write(influxdb::Point{"test"}.addField("value", 10));
    }
    
    // Ensure all points are written
    influxdb->flushBatch();
  4. Perform a basic write to InfluxDB

    master

    Use influxdb::InfluxDBFactory::Get with a complete URI to create a client, then use the write method with an influxdb::Point object to send data.

    // Provide complete URI
    auto influxdb = influxdb::InfluxDBFactory::Get("http://localhost:8086?db=test");
    influxdb->write(influxdb::Point{"test"}
      .addField("value", 10)
      .addTag("host", "localhost")
    );
  5. Query data from InfluxDB

    master

    Queries are available over HTTP only. Use the query method and pass an IFQL string to receive a std::vector<influxdb::Point>.

    // Available over HTTP only
    auto influxdb = influxdb::InfluxDBFactory::Get("http://localhost:8086?db=test");
    /// Pass an IFQL to get list of points
    std::vector<influxdb::Point> points = influxdb->query("SELECT * FROM test");
  6. Execute commands in InfluxDB

    master

    Use the execute method to run commands (like SHOW DATABASES) and receive the response.

    auto influxdb = influxdb::InfluxDBFactory::Get("http://localhost:8086?db=test");
    
    // Execute a command and receive it's response
    const auto response = influxdb->execute("SHOW DATABASES");
  7. Configure additional HTTP transport options

    master

    For advanced HTTP configuration, use the InfluxDBBuilder::http fluent interface instead of the factory. This allows setting timeouts and authentication tokens.

    auto influxdb = InfluxDBBuilder::http("http://localhost:8086?db=test")
                        .setTimeout(std::chrono::seconds{20})
                        .setAuthToken("<token>")
                        .connect();
  8. Configure InfluxDB transports and URIs

    master

    The transport type is determined by the protocol in the URI. Note that boost is required for TCP, UDP, and Unix socket transports, and is also required to support queries when using those transports.

    NameDependencyURI protocolSample URI
    HTTPcprhttp/httpshttp://localhost:8086?db=<db>
    TCPboosttcptcp://localhost:8094
    UDPboostudpudp://localhost:8094
    Unix socketboostunixunix:///tmp/telegraf.sock

    URI Formats:

    • Standard: [protocol]://[username:password@]host:port[?db=database]
    • Auth token: [protocol]://[token@]host:port[?db=database]
  9. Configure authentication for the HTTP transport

    master

    The HTTP transport supports two primary authentication methods for InfluxDB:

    1. Basic Authentication: Use setBasicAuthentication(user, pass) to provide a username and password.
    2. API Token: Use setAuthToken(token) to provide a Bearer token for authentication.

    Both methods are used to authorize requests sent by the transport.

    // Using Basic Auth
    transport.setBasicAuthentication("my_user", "my_password");
    
    // Using API Token
    transport.setAuthToken("my_secret_token");
  10. Use the HTTP transport for InfluxDB communication

    master

    The influxdb::transports::HTTP class is the primary implementation for communicating with InfluxDB via HTTP. It provides methods for sending data in Line Protocol format, executing queries, and managing authentication. It inherits from the Transport base class.

    Key capabilities include:

    • Data Writing: Use send() to transmit Line Protocol strings via HTTP POST.
    • Querying: Use query() to execute queries and receive string results.
    • Command Execution: Use execute() to run administrative commands.
    • Database Management: Use createDatabase() to ensure the database at the provided URL exists.
    • Connectivity: Use ping() to check if the server is reachable.
    #include <InfluxDB/HTTP.h>
    
    // Initialize the transport with the InfluxDB URL
    influxdb::transports::HTTP transport("http://localhost:8086");
    
    // Send data
    transport.send("measurement,tag=value field=1.0");
    
    // Query data
    std::string result = transport.query("SELECT * FROM measurement");
  11. Use the TCP transport for InfluxDB communication

    master

    The influxdb::transports::TCP class provides a transport implementation for sending data to InfluxDB over a TCP connection. It requires a hostname and a port to initialize the connection.

    Key methods:

    • send(std::string&& message): Sends a raw message (blob) via the established TCP connection.
    • is_connected(): Returns true if the socket is currently connected.
    • reconnect(): Attempts to reconnect the socket to the endpoint.
    #include <influxdb/transports/TCP.h>
    
    // Initialize TCP transport with hostname and port
    influxdb::transports::TCP transport("localhost", 8086);
    
    // Send a message
    transport.send("your_influxdb_line_protocol_data");
    
    // Check connection status
    if (transport.is_connected()) {
        // ...
    }
    
    // Reconnect if necessary
    transport.reconnect();