Asterisk::LDAP.3pm

Langue: en

Version: 2005-12-20 (mandriva - 01/05/08)

Section: 3 (Bibliothèques de fonctions)

NAME

Asterisk::LDAP - Methods for generating Asterisk configuration from LDAP

SYNOPSIS

use Asterisk::LDAP;

$AstLDAP = new Asterisk::LDAP;

# parse command line options

         $AstLDAP->parseCmdline();
 
 

# parse /etc/ldap.conf (or ldap.conf supplied on command line)

         $AstLDAP->parseLDAPconf();
 
 

# parse /etc/asterisk/asterisk.conf to determine best location for generated # configuration files

         $AstLDAP->parseAsteriskconf();
 
 

# Generate the configuration files to temporary files
        foreach $config (@{$AstLDAP->{CONFIGS}}) {
            $tmpfile = $AstLDAP->generate($config, ``file'');
            rename($tmpfile, $AstLDAP->{CONFIGS}{$config});
        }

# Try to reload Asterisk with the new configuration data

         $AstLDAP->tryreload();
 
 

DESCRIPTION

This module should make it simple to write scripts that customize Asterisk's configuration based on data from the LDAP tree. These methods and mechanisms have been written with customization of the final product (configuration files) in mind.

LDAP COMMANDS

$AstLDAP->getLDAPconf()
Reads and parses into object variables LDAP connection options from ldap.conf

This command will read in the ldap.conf stored in $AstLDAP->ldapconf (defaults to /etc/ldap.conf) and parse the connection options into variables which can be used for a subsequent call to $AstLDAP->ldap_connect();

Example: $AstLDAP->ldapconf(``/usr/local/etc/ldap.conf''); // set ldap.conf path
         $AstLDAP->getLDAPconf();

Returns: 1 on success.

$AstLDAP->getAsteriskconf()
Reads and parses into object variables Asterisk installation information from asterisk.conf

This command will read in the asterisk.conf stored in $AstLDAP->asteriskconf (defaults to /etc/asterisk/asterisk.conf) and parse the installation options into variables which can be used fordetermining where to put the generated Asterisk configuration files.

Example: // set asterisk.conf path
         $AstLDAP->asteriskconf(``/usr/local/etc/asterisk.conf'');
         // read and parse the file
         $AstLDAP->getAsteriskconf();

Returns: 1 on success.

$AstLDAP->usage()
Print usage information

This function is only useful if using the standard Asterisk::LDAP parseCmdLine() routines. Otherwise you will need to supply your own usage statement.

Example: $AstLDAP->usage();

Returns: die()s printing usage information

$AstLDAP->parseCmdline()
Configures the Asterisk::LDAP object based on command line options

See $AstLDAP->usage() for parameter documentation

Example: $AstLDAP->parseCmdline();

Returns: 1 on success.

$AstLDAP->readConfig($config)
Reads from Asterisk configuration information from LDAP and populates the object's internal hash structures for generation.

$config is currently one of
    ``extensions''    - For extensions.conf
    ``voicemail''     - For voicemail.conf
    ``musiconhold''   - For musiconhold.conf

Examples:
            $AstLDAP->readConfig(``extensions'');

             my @configs = ("extensions", "voicemail", "musiconhold");
             $AstLDAP->readConfig(@configs);
 
 

Returns: 1 on success.

$AstLDAP->format($mode)
Reads from LDAP and exports Asterisk compatible configuration files.

This command will search through the LDAP directory tree and create Asterisk 1.0 compatible configuration files.

$config is currently one of
    ``extensions''    - For extensions.conf
    ``voicemail''     - For voicemail.conf
    ``musiconhold''   - For musiconhold.conf

$mode can be
    ``file''          - Will return a scalar containing the path to a temporary
                      file holding the generated configuration file.
    ``scalar''        - Will return a hash of scalars containing the generated file.
                      One hash key for each configuration file read.

Examples:
            $file = $AstLDAP->generate(``extensions'', ``file'');

             %configdata = $AstLDAP->generate("scalar");
             # $configdata{'extensions'} holds extensions.conf
             # $configdata{'voicemail'} holds voicemail.conf
             # $configdata{'musiconhold'} hosts musiconhold.conf
 
 

Returns: 1 on success.

$AstLDAP->generate($config, $mode)
  Compatibility wrapper for Asterisk::LDAP 0.5.x
 
 
  Calls readConfig and format
 
 
  Example: $AstLDAP->generate($config, $mode);
 =cut
 sub generate
 {
     my $self = shift(@_);
     my $mode = shift(@_);
 
 
     # Default to file-based formatting unless overridden by argument
     if (!defined($mode) || !$mode) {
         $mode = "file";
     }
 
 
     foreach my $config (@{$self->{'CONFIGS'}}) {
         $self->readConfig($config);
         $self->format($config, $mode);
     }
 }
 
 

# Take a config as an option and return a hash of old serials by # indexed by context sub _getOldSerials {
    my $self = shift(@_);
    my $config = shift;
    my %oldSerials;
    # Read in old $config.conf and save serial data
    if (open(OLDEXTENSIONS, '<',
        $self->{'ASTETCDIR'}.'/'.$config.'.conf')) {
        while (<OLDEXTENSIONS>) {
            if ($_ =~ /^\[(.*)\]\s*;\s*(\d+)/) {
                debug(3, ``Found serial number $2 for context $1'');
                $oldSerials{$1} = $2;
            } elsif ($_ =~ /^\[(.*)\].*$/) {
                &warn(``Found context with no serial number.  Assuming 0'');
                $oldSerials{$1} = 0;
            }
        }
        close(OLDEXTENSIONS);
    } else {
        &warn('Unable to read old '.$config.'.conf');
    }

     # Check for and possibly attempt to create
     # ASTETCDIR/extensions.d to hold per-context files
     if (!stat($self->{'ASTETCDIR'}.'/'.$config.'.d')) {
         debug(1, 'Creating '.$self->{'ASTETCDIR'}.'/'.$config.'.d');
         mkdir($self->{'ASTETCDIR'}.'/'.$config.'.d') or
             &die('Unable to create '.$self->{'ASTETCDIR'}.
                 '/'.$config.'.d for per-context configuration files',
                 __FILE__, __LINE__);
     }
 
 
     foreach my $context
         (keys(%{$self->{'CONFIGDATA'}{$config}})) {
         if (stat($self->{'ASTETCDIR'}.
             "/${config}.d/${config}.${context}.conf")) {
             open(OLDEXTENSIONS, '<', $self->{'ASTETCDIR'}.
                 "/${config}.d/${config}.${context}.conf");
             while (<OLDEXTENSIONS>) {
                 if ($_ =~ /^\[(.*)\]\s;\s(\d+)$/) {
                     debug(3, "Found serial number $2 for context $1");
                     $oldSerials{$1} = $2;
                 }
             }
             close(OLDEXTENSIONS);
         } else {
             debug(1, "No old configuration file found for $context");
         }
     }
 
 
     return %oldSerials;
 }
 
 

sub _getOutputHandle {
    my $self = shift(@_);
    my $mode = shift;
    my $config = shift;
    my $context = shift;
    my ($fh, $file);
    my $fileformat;

     # If a context was passed in return a backend for a file-per-context
     # If not return a filehandle for the standard file (ex. extensions.conf)
     if (!defined($context) || !$context) {
         $fileformat = $self->{'ASTETCDIR'}.'/'.$config.'-'.$$.'-XXXXXX';
     } else {
         $fileformat =
             $self->{'ASTETCDIR'}.'/'.$config.'.d/'.$context.'-'.$$.'-XXXXXX';
     }
 
 
     # Create a temporary filehandle for the context
     MODE: for ($mode) {
     /file/ && do {
         debug(3, 'Opening temporary file for writing.');
         ($fh, $file) = mkstemp($fileformat) or
             &die('Unable to open temporary file for writing!', __FILE__, __LINE__);
         last MODE;
     };
 #     # To properly support scalars as a backend need to figure out how
 #     # to handle file-per-context schema.  Maybe just concat all data?
 #     # But then we'll have to rip out the #include lines...
 #     # Really, does anyone actually *want* this feature?
 #     /scalar/ && do {
 #         debug(3, "Creating memory backed file for writing");
 #         open($fh, '>', \$self->{'OUTPUT'}) or
 #             &die( "Unable to open scalar file handle for writing!", __FILE__, __LINE__);
 #         last MODE;
 #     };
     # default case:
     &die("Invalid or unsupported output format requested");
     } # End of MODE block
 
 
     CORE::print $fh "; Generated by Asterisk::LDAP $VERSION\n";
     CORE::print $fh ";\n";
     CORE::print $fh "; !!! DO NOT EDIT !!!\n";
     CORE::print $fh ";\n";
 
 
     return ($fh, $file);
 }
 
 

sub _cleanStaleContexts {
    my $self = shift(@_);
    my $config = shift;
    my $oldSerials = shift;

     # Any key left in the oldSerials hash is a dead (removed) context
     # which should be purged from disk
     foreach my $oldcontext (keys(%{$oldSerials})) {
         my $filename = $self->{'ASTETCDIR'}."/${config}.d/".
             "${config}.${oldcontext}.conf";
 
 
         if(stat($filename)) {
             &print("Pruning old context from disk: ${oldcontext}");
             unlink($filename) or
                 &warn("Unable to remove stale context $filename");
         }
         # If the stat fails above the context was probably in extensions.conf
         # itself and was thus overwritten automatically.  No further
         # cleaning should be necessary.
     }
 }
 
 
$AstLDAP->updateVmailPIN([$voicemailbox], [$context], [$pin])
Updates a user's voice mailbox pin number

This method relies on having voicemailbox, context, and newpin either passed in or previously stored in the object. This information is then stored to the directory. See examples directory with this distribution for a script compatible with ``externpass'' option for voicemail.conf.

Example 1: $AstLDAP->updateVmailPIN(``101'', ``customerA'', ``12345'');

Example 2: $AstLDAP->voicemailbox(``101'');
            $AstLDAP->context(``customerA'');
            $AstLDAP->newpin(``12345'');
            $AstLDAP->updateVmailPIN();

Example 3: # Start script with arguments
            # --voicemailbox 101 --context customerA --newpin 12345
            $AstLDAP->parseCmdline();
            $AstLDAP->updateVmailPIN();

Returns: 1 on success.

$AstLDAP->tryreload()
Attempt to reload Asterisk following a configuration change

This method tests to see if reloading Asterisk is permissable, necessary, possible, and safe. To check permissibilty, it looks for a non-zero value in $AstLDAP->astreload(); To check necessity, it looks for a non-zero value in $AstLDAP->needreload(); To check possiblity, it looks for a path to the asterisk binary. To check safety, it looks for a zero value in $AstLDAP->warningsissued();

Example: # Generate configuration files and move them into place
            $AstLDAP->needreload(true); # Flag need
            $AstLDAP->astreload(true);  # Flag permission
            $AstLDAP->tryreload();      # Should work if there were no warnings

Returns: 1 on success.

$AstLDAP->ldap_connect(["root"])
Connect to the LDAP server with configured credentials

This method will connect to the LDAP server with options specified in the object. If the optional argument ``root'' is passed in, ldap_connect will attempt to bind with privileged credentials. If none are specified, a warning will be issued and regular credentials (or anonymous) are tried.

Example: $AstLDAP->ldap_connect();

Returns: A Net::LDAP object.

$AstLDAP->make_backups($filename, $numcopies)
Rotate $AstLDAP->savedcopies() number of backup copies

This method takes as arguments the file to be rotated and a number of copies to keep. For example, if ``extensions.conf'' is passed in, then that file will be renamed extensions.conf.1; extensions.conf.1 will be renamed to extensions.conf.2, etc. up to $numcopies. The last file will be unlinked. This permits the use of $AstLDAP->undo();

Example: $AstLDAP->make_backups(``/etc/asterisk/extensions.conf'', 3);

Returns: 1 on success, &die on failure

$AstLDAP->undo($filename)
Revert to a backup copy of $filename

This method takes as the sole argument the file to be restored. For example, if ``/etc/asterisk/extensiosn.conf'' is passed in, then that file will be renamed from <filename>.1 to <filename>

Example: $AstLDAP->undo(``/etc/asterisk/extensions.conf'');

Returns: 1 on success, &die on failure