Adding a Node to a Pool

Provisioning systems can dynamically deploy applications across servers, perhaps in reaction to increased server load. This example demonstrates an application that modifies the nodes that a pool balances traffic to.

The code structure is as follows:

Instantiate a new REST Client object.

Specify the hostname and port of the REST service to which all requests are to be directed.

Add required HTTP headers for authentication and content type.

Send a GET request for the pool that the new node is added to. Check the response body, and decode from JSON into a Perl structure. This value is a hash ref.

The new node must be added to the table of existing nodes before writing the data back to the pool resource. Failing to do this results in the existing table being overwritten with a single row containing the new node. Each of the subkeys associated with the node have default values and do not need to be specified.

Re-encode the Perl structure into JSON and pass as an argument to the PUT request (using the pool name URI as the target).

In this example, the script performs a check on the response code to ensure any problems are reported back (where the response code is not 200 OK).

There is an optional portion of code at the end to iterate through the stored node table to ensure that the new node name appears.

#!/usr/bin/perl -w

 

use REST::Client;

use JSON;

use strict;

 

# Set up the connection

my $client = REST::Client->new();

$client->setHost( 'http://localhost:9070' );

$client->addHeader( 'Authorization', 'Basic YWRtaW46am9iYmll' );

$client->addHeader( 'Content-Type', 'application/json' );

 

# Our pool and new node details

my $poolName = "WebPool";

my $newNode = { "node" => "www3.pulsesecure.net:80" };

 

# Get the config for the pool in question

$client->GET( "/api/tm/8.3/config/active/pools/$poolName" );

my $poolConfig = decode_json( $client->responseContent() );

 

# Find the existing nodes table (a hashref), and add our new node

my $nodesRef = $poolConfig->{properties}->{basic}->{nodes_table};

push @$nodesRef, $newNode;

 

# Re-encode as a JSON string

my $poolStr = encode_json( $poolConfig );

 

# Now send a PUT request to the REST service

$client->PUT( "/api/tm/8.3/config/active/pools/$poolName",

$poolStr );

 

# Print out the response code if we were NOT successful

if( $client->responseCode() ne '200' ) {

die "FAILED with HTTP code: " . $client->responseCode();

}

 

# We're done! Verify that the node has been added

$client->GET( "/api/tm/8.3/config/active/pools/$poolName" );

$poolConfig = decode_json( $client->responseContent() );

print "Stored nodes for pool '$poolName':\n";

foreach my $tablerow ( @{$poolConfig->{properties}->{basic}->{nodes_table}} ) {

print "$tablerow->{node}\n";

}

The expected output of a script such as this would be:

$ ./addNode.pl

Stored nodes for pool 'WebPool':

www1.pulsesecure.net:80

www2.pulsesecure.net:80

www3.pulsesecure.net:80