Overview of the Splunk SDK for PHP

Welcome to the Splunk® Software Development Kit (SDK) for PHP!

This overview tells you more about:

This SDK is open source and uses the Apache v2.0 license. If you want to make a code contribution, go to the Open Source page for more information.

 

What you can do with the Splunk SDK for PHP

This SDK contains library code and examples designed to enable developers to build applications using Splunk. With the Splunk SDK for PHP you can write PHP applications to programmatically interact with the Splunk engine. The SDK is built on top of the REST API, providing a wrapper over the REST API endpoints. With the PDP SDK you can:

  • Run search jobs and extract data
  • Manage search jobs
  • Log events to indexes
  • Manage Splunk configurations and objects (coming soon)
 

The Splunk SDK for PHP components

The Splunk developer platform consists of three primary components: Splunkd, the engine; Splunk Web, the app framework that sits on top of the engine; and the Splunk SDKs that interface with the REST API and extension points.

The Splunk SDK for PHP lets you target Splunkd by making calls against the engine's REST API and accessing the various Splunkd end points such as custom search commands, lookup functions, scripted inputs, and custom REST handlers.

Read more about:

 

The Splunk_Service class

The Splunk_Service class is the primary entry point for the client library. Construct an instance of the Splunk_Service class and provide any arguments that are required to connect to an available Splunk server. Once the Splunk_Service instance is created, call the login method to provide login credentials. Once connected, you can work with various entities on the server, such as saved searches and search jobs.

The following shows an example of how to create a Splunk_Service instance and connect to Splunk:

// Import Splunk.php
require_once 'Splunk.php';

// Create an instance of Splunk_Service to connect to a Splunk server
$service = new Splunk_Service(array(
    'host' => 'localhost',
    'port' => '8089',
    'username' => 'admin',
    'password' => 'changeme',
));
$service->login();
 

Entities and collections

The Splunk REST API has over 160 endpoints (resources) that provide access to almost every feature of Splunk. The Splunk SDK for PHP exposes many of these endpoints as entities and collections of entities. The base abstractions are as follows:

  • Endpoint: An abstraction that allows an endpoint to be accessed over HTTP, with shortcuts for making HTTP GET, POST, and DELETE calls.
  • Entity: An abstraction over a Splunk entity (such as a single app, saved search, job, or index), providing operations such as update, remove, read properties, and refresh.
  • Collection: An abstraction over a Splunk collection (such as all apps, all saved searches, all jobs, or all indexes), providing operations such as creating new entities and fetching specific entities.

Each collection type can be accessed on the Splunk_Service object. For example, the following example shows how to retrieve a collection from the server:

// Retrieve a collection of saved searches
$savedSearches = $service->getSavedSearches()->items();

// Retrieve a collection of jobs
$jobs = $service->getJobs()->items();

The following example shows how to retrieve a particular entity, in this case a saved search, from a collection by its name:

// Retrieve a specific saved search, "Top five sourcetypes"
$mySavedSearch = $service->getSavedSearches()->get('Top five sourcetypes');
 

Namespaces

To account for permissions to view apps, system files, and other entity resources by users throughout a Splunk installation, Splunk provides access to entity resources based on a namespace. This is similar to the app/user context that is used by the Splunk REST API when accessing entity resources using endpoints.

The namespace is defined by:

  • An owner, which is the Splunk username, such as "admin". A value of "nobody" means no specific user.
  • An app, which is the app context for this entity (such as "search").
  • A sharing mode, which indicates how the entity is shared. The sharing mode can be:
    • "user": The entity is private to a specific user, as specified by owner.
    • "app": The entity is shared through an app, as specified by app. The owner is "nobody", meaning no specific user.
    • "global": The entity is globally shared to all apps. The owner is "nobody", meaning no specific user.
    • "system": The entity is a system resource (owner is "nobody", app is "system").

If a namespace is not explicitly specified, the default namespaces is used: the current user is used for owner and the default app is used for app.

Here are the constructors for accessing entity resources in different types of namespaces:

// The default namespace--the current user and the user's default app
Splunk_Namespace::createDefault();

// Entities owned by a specific user and app
Splunk_Namespace::createUser($owner, $app);

// Entities that are shared through a specific app with no specific owner
Splunk_Namespace::createApp($app);

// Entities for a specific app that are globally shared to all apps
Splunk_Namespace::createGlobal($app);

// Entities in the System app
Splunk_Namespace::createSystem();

This example shows how to retrieve a collection of saved searches that is available to the "admin" user in the "search" app:

$savedSearches = $service->getSavedSearches()->items(array(
    'namespace' => Splunk_Namespace::createUser('admin', 'search'),
));

This example shows how to retrieve an individual entity in a namespace:

// Retrieve the saved search named "Top five sourcetypes"
$topSourcetypesSearch = $service->getSavedSearches()->get(
    'Top five sourcetypes',
    Splunk_Namespace::createApp('search'));

If you typically access lots of objects in the same namespace, you can pass a default namespace to the Splunk_Service constructor, allowing you to avoid passing an explicit namespace with every call to get or items:

$service = new Splunk_Service(array(
    ...
    'namespace' => Splunk_Namespace::createUser('admin', 'search'),
));
$service->login();

$jobs = $service->getJobs()->items();           // in the admin/search namespace
$indexes = $service->getIndexes()->items(array( // in the system namespace
    'namespace' => Splunk_Namespace::createSystem(),
));
 

Searches

One of the primary features of Splunk is running searches and retrieving search results. There are multiple ways to run a search—here are a few examples.

  • Normal: A normal search runs asynchronously and allows you to monitor its progress. This type of search is ideal for most cases, especially for searches that return a large number of results.
    // Define the search expression--the query must begin with 'search'
    $searchExpression = 'search index=_internal | head 10000';
    
    // Create a normal search job
    $job = $service->getJobs()->create($searchExpression);
    
    // Alternately, you can create a search job using the search method:
    // $job = $service->search($searchExpression);
    
    // Wait for the job to complete, then get results
    while (!$job->isDone())
    {
        printf("Progress: %03.1f%%\r\n", $job->getProgress() * 100);
        usleep(0.5 * 1000000);
        $job->refresh();
    }
    $results = $job->getResults();
    
    // Process results
    foreach ($results as $result)
    {
        if ($result instanceof Splunk_ResultsFieldOrder)
        {
            // Process the field order
            print "FIELDS: " . implode(',', $result->getFieldNames()) . "\r\n";
        }
        else if ($result instanceof Splunk_ResultsMessage)
        {
            // Process a message
            print "[{$result->getType()}] {$result->getText()}\r\n";
        }
        else if (is_array($result))
        {
            // Process a row
            print "{\r\n";
            foreach ($result as $key => $valueOrValues)
            {
                if (is_array($valueOrValues))
                {
                    $values = $valueOrValues;
                    $valuesString = implode(',', $values);
                    print "  {$key} => [{$valuesString}]\r\n";
                }
                else
                {
                    $value = $valueOrValues;
                    print "  {$key} => {$value}\r\n";
                }
            }
            print "}\r\n";
        }
        else
        {
            // Ignore unknown result type
        }
    }
    
  • Blocking: A blocking search runs synchronously and does not return a search job until the search has finished. This type of search can be used when you don't need to monitor progress, and does not work with real-time searches.
    // Define the search expression--the query must begin with 'search'
    $searchExpression = 'search index=_internal | head 1000';
    
    // Create a blocking search job, run it, then get results
    $job = $service->getJobs()->create($searchExpression, array(
        'exec_mode' => 'blocking',
    ));
    $results = $job->getResults();
    
    // Process results
    // (See the Normal search example)
    
  • Oneshot: A oneshot search is a blocking search that is scheduled to run immediately. Instead of returning a search job, this mode returns the results of the search once completed.
    // Define the search expression--the query must begin with 'search'
    $searchExpression = 'search index=_internal | head 100 | top sourcetype';
    
    // Run the search
    $resultsXmlString = $service->getJobs()->createOneshot($searchExpression);
    
    // Alternately, you can initiate a oneshot search using the oneshotSearch method:
    // $resultsXmlString = $service->oneshotSearch($searchExpression);
    
    // Get the results
    $results = new Splunk_ResultsReader($resultsXmlString);
    
    // Process results
    // (See the Normal search example)
  • Saved search: A saved search is simply a search query that was saved to be used again and can be set up to run on a regular schedule. The results from the search are not saved. This example creates a normal search job based on a saved search.
    // Retrieve the saved search named "Top five sourcetypes"
    $savedSearch = $service->getSavedSearches()->get('Top five sourcetypes');
    
    // Create a normal search job based on the saved search
    $job = $savedSearch->dispatch();
    
    // Wait for job to complete and get results
    // (See the Normal search example)
    
    // Process results
    // (See the Normal search example)
    
    

To explore core search features, see the examples included in the Splunk SDK for PHP.