Syntax-K

Know-How für Ihr Projekt

Perl Documentation

NAME

AxKit2::Config - Configuration API for AxKit2

DESCRIPTION

This module manages all configuration for AxKit2 including the API to declare, validate and retrieve parameters and parsing an external configuration file. It is meant to be extensible so that plugin authors can use different ways of obtaining their configuration, including inline XML fragments or anything else they can think of. At the other end, it makes the common task of configuring simple options extremely easy and straightforward.

END USERS

If you know an Apache configuration file, you already know AxKit2's configuration syntax. For an exact description of the format, see "CONFIGURATION FILE SYNTAX".

Core Options

Although all configuration options are declared in the modules they belong to, here is an overview of built-in options available regardless of plugins.

Plugin

The true work horse of AxKit2. Almost all functionality is implemented in plugins. They may provide infrastructure like cachecache, alter and provide important parts of all requests like uri_to_file, handle specific file types like spod5, perform only part of a document transformation/presentation pipeline like generic_transform or implement complete web applications like demo/webmail. They can be long, complex and powerful like demo/gallery or short, simple and minimal like demo/moewiki.

Writing a plugin will most probably be your first task, and it is dead easy. See AxKit2::Docs::WritingPlugins for details.

All plugins are added to a big list. Each <Server> or <Location> section has it's own list of plugins. Plugins from a parent section are enabled in subsections as well, but those of the subsection itself will take precedence over outer plugins.

PluginDir

The directory where AxKit2 will search for plugins loaded via Plugin.

ConsolePort and ConsoleAddr

These specify where the console will be accessible. They can only appear at the top level. See AxKit2::Console for details.

<Server [host]>

Server sections specify on what ports AxKit2 will listen. Through the optional host part, you can configure name-based virtual hosts, using a literal value, wildcards or even a regular expression.

Server sections can only be top-level, i.e. not inside any other section.

All Server sections must contain a Port setting. You can have multiple Server sections with different or equal port settings. If multiple servers share a port, they are distinguished by the Host:-header on client requests. This is usually known as name-based virtual hosting.

Port

The port this server should listen on. Can only appear directly below a Server section.

<Location loc>

The contained settings only apply to requests whose URI matches loc. loc can be a literal value, a wildcard or a regular expression. Note that loc matches against the encoded URL, which means that it might contain %-escapes for international characters.

Location sections can appear inside Server or other Location sections.

DocumentRoot

The base directory for web files. How exactly this is used is unspecified, although the commonly used uri_to_file plugin uses this value to find files to be served and compute path_info and other essential values.

This setting may appear anywhere.

Path

The URI path of this section. It is automatically set for Location sections that use a literal path value. The path is stripped from the request URI before filename mapping using DocumentRoot begins. This can lead to surprising results if you don't specify DocumentRoot for your Location sections.

PLUGIN/MODULE DEVELOPERS

Basic Usage

To add your own configuration parameters, add one line to your plugin:

sub conf_MySetting;

That's it!

Side note: Authors of regular perl modules need to use AxKit2::Config; first. Under the hoods, this works by adding AxKit2::Config::Helpers to your @ISA for attribute support and checking your package namespace at a later time. To avoid issues with your regular inheritance, it is probably a good idea to use AxKit2::Config; last.

Just by providing that declaration, MySetting is now a valid configuration parameter that takes a single string value. You can access it via

$self->config->my_setting

or

$self->config('my_setting')

Side note for module authors: To retrieve the value, you have to have access to a configuration object, however that is passed. If $cfg is such an object, $cfg->my_setting or $cfg->config('my_setting') will retrieve the value.

A word on spelling of configuration parameters: You are free to use CamelCase or underscore_separated style, and you may mix those styles freely. Even if you forget underscores or case, things should still work.

Advanced Options

Sometimes, a single string parameter simply isn't sufficient. Strings don't always cut it, or you need more than one. Maybe you even want to have your own <Section>. Since core parameters and sections don't get any special treatment, any plugin author can invent own options that behave exactly like core options, and even more.

Most processing options are set using perl attributes, so an advanced version of the above example could be:

sub conf_MySetting : Validate(INTEGER);

The most important aspects of processing are validation and storage. Because of that, they are explained in more detail here. You will find a reference of all possible configuration attributes below at "ATTRIBUTE REFERENCE".

Validators

Validators check the value itself and may convert strings to a different data type or structure. for example, the predefined FILE validator checks that the given value is an existing file and converts the value to an absolute path. The predefined REGEX validator parses a given value as regular expression with qr(). The advantage of this approach is that you get detailed validation of values, catching any errors at server startup. That also means that some processing of values is done only once and doesn't consume precious request time.

There are a lot of predefined validators. You will see that you'll seldom have to write own validator code, and any plugin is free to predefine new validators. See "VALIDATOR REFERENCE" for validators predefined in the core AxKit2 distribution.

Storage

The default behaviour is to simply store the validated value in the config object. If you need more complex processing or some different storage location, you can supply a function body to your config sub. The return value of that sub is stored in the configuration object.

Example:

sub conf_MySetting {
  my ($parser, $value) = @_;
  # change log level because this setting is very beta and may break things
  $parser->config('LogLevel',7);
  # our value is stored as new DirectoryIndex
  $parser->config('DirectoryIndex',$value);
  # while we just store a true value as a flag for our plugin code
  return 1;
}

AxKit2::Config API

import

You can't import anything from AxKit2::Config. This sub flags your module so that it is later searched for configuration settings. It also adds AxKit2::Config::Helpers to your @ISA for config attribute support.

_die(message)

A custom die-replacement that tries to print a more meaningful file/line location. Useful to call if you predefine new validators.

check

Does the actual namespace walking to discover new settings. Need not be called unless you load new modules containing config directives at runtime (i.e., not during BEGIN).

global

Return the global configuration object. It represents the top level of a parsed config file. Cannot be called during perl startup, since parsing happens after all core modules are loaded.

new(filename)

Parse a configuration file. Returns the configuration object object and sets it as global config. Actually returns a AxKit2::Config::Data object.

normalize_key(name)

Normalize a configuration option. This returns some normalized form which can then be compared via eq to other normalized key values. Specifically, it manages "CamelCase", "hyphenated-words" and "underscore_separated" variants of keywords.

param(name)

Retrieve configuration parameter information. The exact structure returned is subject to change, but you can assume it's a hashref containing at least the key 'key' with the normalized name of the option. All other values may change in later releases without notice.

add_param(name, storage [, validate])

Manually register a configuration setting. Arguments are the name, a storage sub, and an optional validator. See "Advanced Options" for details on validation and storage.

ATTRIBUTE REFERENCE

Push and Push(type)

Specify that this setting is list-style, i.e. new values are pushed on a list of previous values.

The optional argument type specifies how exactly the values are added to the list:

Void

If your storage sub manages all storage itself and the return value should be ignored, add Void to the attribute list.

Shared

Usually, if two plugins define the same configuration setting, AxKit2 will die at startup. This ensures plugins don't inadvertently mess with each other. Sometimes, however, two plugins will have similar functionality and may want to share a setting. Setting this attribute allows that behaviour. Both declarations should be exactly the same, since only the first definition encountered will be used, the other one is ignored!

Default(expr)

Supplies a default value for a setting. If you retrieve this config value and the config file did not contain this setting, returns expr instead.

Validate(validator [, ...])

Specify validators. Each validator may either be a sub reference or the literal name of one of the predefined validators. See "VALIDATOR REFERENCE" for more details on those.

Validators recieve one or more parameters: The first parameter is the current parser object (see "PARSER REFERENCE" for details), the remaining args are the values that were given in the configuration file. They are expected to _die(...) upon failed validation and return the validated set of (possibly preprocessed) values.

Validators are run in the order they were given. Their return values are passed to the next validator as input.

Section and Section(parser)

An option with this attribute is in fact a section used like <Section> ... </Section>. The optional argument parser selects the parser to be used for the section's contents.

Default parser is AxKit2::Config::Parser, which parses the section exactly like <Location> and <Server> including validation and storage. Apart from that, two other parsers are available: Literal and XML that parse the content into a hashref or an XML::LibXML-DOM, respectively. See "PARSER REFERENCE" for details.

If you write a custom parser, you can pass a plain parser name which is then tried as AxKit2::Config::Parser::name, or you can pass a fully qualified package name. In any case, your parsers must be a subclass of AxKit2::Config::Parser and at least support the methods parse_fh and config.

The parser is constructed just like the default parser, parse_fh is then called on the object, and finally the value (whatever it may be, there are no restrictions) is retrieved through config.

If you use the default parser, the parent section is available through the configuration setting parent, while the subsection is stored under the name of the section.

Note that this setting also works as a validator, so it makes a difference in which order you put your Section and Validate attributes. All values given in the opening tag are stored with the config object.

CONFIGURATION FILE SYNTAX

The config file is a plain text file in UTF-8 encoding with one config parameter per line. Blank lines and lines starting with # (comments) are ignored. Of the remaining lines, lines that end with a backslash are continued on the next line without any special treatment of following blank lines or comments.

Example:

# These lines are ignored, like in many file formats.
# Comments can only be full lines, however.

# The next line is treated as a single line
DocumentRoot \
  /home/www/htdocs
# but comments don't continue \
DocumentRoot /home/www \
# So this line is not a comment!

Regular settings consist of a keyword (letters, digits, underscore and hyphen are allowed), followed by white-space and one or more white-space separated values. Values must be quoted with single or double quotes if they contain white-space, and quote chars inside quotes can be escaped by a backslash, as can the backslash itself. Keywords can be given in several variants: They are (almost) case-insensitive and may contain hyphens or underscores as word separators for readability.

Example:

# All lines do the same:
DocumentRoot /home/www
DocumentRoot "/home/www"
DocumentRoot '/home/www'
document-root /home/www
document_root /home/www
DOCUMENT_ROOT /home/www
# Going all lowercase usually works, too:
documentroot /home/www
# This would be an error, because it has incorrect word separation:
Documentroot /home/www

Some parts of the configuration file may be enclosed in HTML-like tag pairs, for example <Server> ... </Server> or <Location /foo> ... </Location>. These sections inherit all configuration from their outer level. New settings in these sections usually override those of the outer level.

Example:

Plugin uri_to_file
Plugin serve_file
<Server>
    Port 8000
    # The plugins are still effective in here.
</Server>

However, some list-like settings like Plugin add to what was inherited. The final order of such values is determined by the relevant plugin. Some may keep all values in strict document order, while others (like Plugin) makes sub-settings take priority over outer values. The configuration system is quite flexible, so plugin authors probably choose the most expected behaviour.

PARSER REFERENCE

AxKit2::Config::Parser is the class that manages parsing of a configuration file. It is recursively created for subsections, and you can define own parsers for custom subsections, possibly with drastically different format.

Unless you are writing your own parser, you are not expected to do anything with this object except for calling config on it. The rest of this section targets parser authors.

Fields

AxKit2::Config::Parser has four fields:

Special config object entries

There are two special entries in each configuration object:

Methods

new([parent, section, ...])

Create a new parser. If no arguments are given, this is a top-level parser that will parse an entire file. Otherwise, parent denotes the parent parser object, section denotes the (normalized) name of the section, and all following args are the parameters of the opening tag.

propagate

Propagates values from the parent section into the current one. It is called by the default constructor for configuration inheritance. Only subsections stored in _subsections and options marked as Push(nested) are left out.

config([name [, value, ...] ])

Without arguments just returns the parseed configuration object. It can be anything you like, although the default is an AxKit2::Config::Data object.

With arguments, it should behave like AxKit2::Config::Data::config, retrieving a named setting or setting it.

handle_config(name, value, ...)

This method is called by the default parser for each line. You are expected to do somthing with this value. Sections will still have the opening < as first character of name, although the closing > is already stripped.

By default, this method calls all relevant validators and then dispatches to store_config for storage.

store_config(config, param, value, ...)

This method handles actual storage of values. It recursively handles storing values in already known subsections as well, because already parsed subsections will not get later settings through propagate.

config is the config object to receive the values. param is the option description as returned by AxKit2::Config::param, the remaining values are the arguments.

parse_fh(filehandle)

Parse configuration, reading data from the given file handle. If this parser was created for a subsection, it is expected to stop reading after a line with just the closing tag of that subsection (plus some white-space) has been read.

If you write a parser, read from the file handle until you encounter a line containing white-space and the closing tag of the current section, nothing else. Anything before that is your data, but you are expected to read and check the closing tag as well.

Alternate Parsers

Literal

This parser parses configuration directives and subsections exactly like the default parser, but it doesn't do validation, nor does it execute special storage subs or inheritance and propagation of values. In effect, you get a hash reference with (normalized) keys for each option. Each entry is an arrayref of values, either plain scalars or hashrefs for subsections.

It also doubles as base class for non-validating parsers, because the default constructor is much simpler and doesn't try to propagate values.

XML

This parser parses an embedded XML fragment and returns an XML::LibXML DOM. That's all.

CONFIGURATION OBJECT REFERENCE

AxKit2::Config::Data is the configuration object that's available in a variety of places. Plugin authors will usually encounter it in their plugin hooks, in their configuration storage subs and indirectly in configuration validators.

Fields

The object has no fixed fields. You are not allowed to access the object except through the documented methods.

Methods

new

The constructor doesn't take any arguments. It creates a plain empty configuration object.

config_clear(name)

Completely erases the given setting, resetting it to the default value.

config(name [, values, ...])

Retrieves a setting. If no value was set, the default value as set using Default is returned. In scalar context, only the first value is returned, in array context all values are returned (if more than one).

If more than one argument is given, the values will replace the current values of the setting.

This method will die if you specified an unknown configuration setting.

AUTOLOAD

Calling any other method on the config object will set/retrieve the given setting as if you used the config method.

VALIDATOR REFERENCE

Predefined validators live in package AxKit2::Config::Validators. They are plain subs that work like described in "Advanced options".

Feel free to inject new subs into this package. Providing useful predefined validators that relate to your plugin is greatly appreciated.

_die

This is not actually a validator. It is an alias for AxKit2::Config::_die, provided for convenience.

INVALID

A validator that always fails. Useful if you want to declare new config object entries but don't want them to be configured through the config file.

BOOL

A single boolean value, to the extreme. Allows "y", "yes", "1", "on" and "true" for true, "n", "no", "0", "off" and "false" for false. Returns 1 or 0.

NOARG

Dies if any values were provided.

OPTIONAL

Makes one argument optional by adding undef to the values if no argument was given.

ONEARG

Dies unless exactly one value was provided.

TWOARGS

Dies unless exactly two values were provided.

STRING

Checks that the value is a single plain non-reference scalar.

INTEGER

Checks that the value is a single integer value.

SIZE

Checks that the value is a single integer value, optionally suffixed by "K", "M" or "G".

DIRECTORY

Checks that the value is a single existing directory. Converts the path to an absolute path, if neccessary.

FILE

Checks that the value is a single existing file. Converts the path to an absolute path, if neccessary.

FILELIST

Like FILE, but accepts an arbitrary amount of values.

REGEX

Checks that the value is a single perl regular expression by compiling it. The compiled regex reference is returned.

REGEX_OR_WILDCARD_OR_SUBSTRING

Checks that the value is a single literal string, a perl regular expression, or a wildcard expression. If the value only consists of letters, digits, and any of "%/._-", then it is interpreted as literal value. With additional wildcards ("*" and "?"), it is interpreted as wildcard expression, otherwise as perl regular expression.

In any case, a compiled regex reference is returned. If a literal value was detected, a second value is returned, the literal value.

Wildcard matches are anchored at the start and at the end, literal values may match any substring.

REGEX_OR_WILDCARD_OR_PREFIX

Like REGEX_OR_WILDCARD_OR_SUBSTRING, but literal values must match as a prefix.

REGEX_OR_WILDCARD_OR_SUFFIX

Like REGEX_OR_WILDCARD_OR_SUBSTRING, but literal values must match as a suffix.

REGEX_OR_WILDCARD_OR_LITERAL

Just like REGEX_OR_WILDCARD_OR_SUBSTRING, but literal values must match the whole string.

CODE

Checks that the value is a valid perl expression by compiling it. The code reference is returned.

MODULE

Checks that the single value is a valid module by loading it.

STRINGLIST

Like STRING, but accepts an arbitrary amount of values.

GLOBAL

Checks that the value appears at top level, i.e. not within a subsection.

EMAIL

Checks that the value is a single syntactically correct email address. Needs Email::Valid to work.

EMAILLIST

Like EMAIL, but accepts an arbitrary amount of values.

LICENSE

AxKit2 is licensed under the Apache License, Version 2.0.