Search Postgresql Archives

Re: Example of a pg_gethostname() function. Feedback?

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



On Fri, Dec 23, 2011 at 8:22 PM, Craig Ringer <ringerc@xxxxxxxxxxxxx> wrote:
> Only that it might be less hassle to wrap gethostname from pl/perl or
> pl/python rather than adding a new C function, particularly if this is only
> for DB testing and is not performance critical.
>
> --
> Craig Ringer

Hi Craig,

That was my first thought. However, in two of our servers, Perl is
mis-configured in some way that it causes the db to abort and crash
when a simple plperlu function is run. I reported a test case a few
months ago and that was Tom's conclusion and I didn't have the time or
inclination to pursue it. We rarely use any pl language other than
plpgsql, so I deemed it safer in this instance to avoid using plperlu
altogether.


Cheers,

Bricklen


Note, my coworker revised the C function slightly:
- Used HOST_NAME_MAX from limits.h, which is portable.
- Return an empty string on failure instead of "UNKNOWN" because that
makes more sense and allows for the host name "UNKNOWN".
- Fixed the comments.


/*
	A PostgreSQL function for getting the hostname.

	To compile...  (make sure pg_config is in your PATH)
	gcc  -I$(pg_config --includedir-server) -fpic -c pg_gethostname.c
-L$(pg_config --libdir)
	gcc --shared -o pg_gethostname.so pg_gethostname.o
	
	To create the funciton in PostgreSQL...
	CREATE OR REPLACE FUNCTION pg_gethostname() RETURNS text
		AS 'pg_gethostname'
		LANGUAGE C IMMUTABLE STRICT;
		
*/
#include "postgres.h"
#include <limits.h>
#include <unistd.h>
#include <string.h>
#include "fmgr.h"

#include "utils/palloc.h"
#include "utils/elog.h"
#include "storage/bufpage.h"

#ifdef PG_MODULE_MAGIC
PG_MODULE_MAGIC;
#endif




PG_FUNCTION_INFO_V1( pg_gethostname );

Datum pg_gethostname( PG_FUNCTION_ARGS );

Datum pg_gethostname( PG_FUNCTION_ARGS )
{
	text *t;
	char server_hostname[HOST_NAME_MAX];
	size_t length;
	
	if ( gethostname( server_hostname, HOST_NAME_MAX ) != 0 )
	{
		// returning an empty string for the hostname if it fails makes
		// sense because if it succeeded, we would have a name
		server_hostname[0] = '\0';
	}

	length = strnlen( server_hostname, HOST_NAME_MAX );
	t = (text *) palloc(VARHDRSZ + length );
	SET_VARSIZE( t, VARHDRSZ + length );
	memcpy( VARDATA(t), server_hostname, length );

	PG_RETURN_TEXT_P( t );
}

-- 
Sent via pgsql-general mailing list (pgsql-general@xxxxxxxxxxxxxx)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-general


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
[Index of Archives]     [Postgresql Jobs]     [Postgresql Admin]     [Postgresql Performance]     [Linux Clusters]     [PHP Home]     [PHP on Windows]     [Kernel Newbies]     [PHP Classes]     [PHP Books]     [PHP Databases]     [Postgresql & PHP]     [Yosemite]
  Powered by Linux