Plugin Creation Tutorial


This page contains a step by step guide to writing a plugin for GNUMP3d. This will be a simple one which will just display the current system load upon the server.

For this we'll only make minimal use of the servers internal API.


To follow along with this tutorial you'll need the following:

Getting started.

To write a plugin we need to decide what path will be used to call it. In this case the URL "http://server:port/load/" will be used - as that seems like an appropriate access point for the server functionality.

Adding The Plugin To The Source

With that decided we can start coding - the first thing to do is to create a new source file within the 'lib/gnump3d/plugin' directory.

We'll call our file 'load.pm', although the name doesn't matter, and we'll ensure that it is called for requests to the top level '/load/' URL.

Implementing the plugin

For our plugin we need to include some functions the main server expects.

The mandatory functions are:

The minimal implementation would be this:

# lib/gnump3d/plugins/load.pm

sub getAuthor
   return( "Steve Kemp" );

sub getVersion
   return( "1.0" );

sub wantsPath
    my ( $class, $path ) = ( @_ );

    if ( $path =~ /^\/load\/*/i )
        return 1;

    return 0;

sub handlePath
    my ( $class, $uri ) = (@_);

package main;

   my $header = &getHTTPHeader( 200, "text/plain" );
   &sendData( $data, $header );

   my $output = "We were called for the URL <b>$request</b>";

   &sendData( $data, $output );
   return 1;

# Perl modules must finish with this line...

All that code did was export the minimal functions the server required, and respond to a request upon the path '/load/', merely echoing the request it received.

Testing It

Now would be a good time to test the code. You should be able to go to the top directory, and run 'make install'.

Once that's done start the server and request the '/load/' via your browser. All being well you'll see an output page containing the response from the server.

If you receive a blank page you should investigate the contents of the server error file, (this will be printed to the console if you start the server with '--debug').

Assuming that you got this far then we can move on to actually determining the server load - and coding the rest of the plugin.

Final Stages

One of the simplest ways of testing the server load would be to look at the output of the 'uptime' command, which contains the current system load.

The following code shows how this could be done:

	    my $uptime = `uptime`;
	    chomp( $uptime );

	    if ( $uptime =~ /load average: ([^,]+),/ )
		$text .= "<b>Current Load: $1</b>\n";

The Finished Article

If you've followed along you should have code which looks this:

Comments / Questions?

Any comments or questions can be posted to the developer mailing list.