23c86015a5a81f67ced8def5be25ec44420d0074
[senf.git] / senf / Utils / Console / Mainpage.dox
1 // $Id$
2 //
3 // Copyright (C) 2008
4 // Fraunhofer Institute for Open Communication Systems (FOKUS)
5 // Competence Center NETwork research (NET), St. Augustin, GERMANY
6 //     Stefan Bund <g0dil@berlios.de>
7 //
8 // This program is free software; you can redistribute it and/or modify
9 // it under the terms of the GNU General Public License as published by
10 // the Free Software Foundation; either version 2 of the License, or
11 // (at your option) any later version.
12 //
13 // This program is distributed in the hope that it will be useful,
14 // but WITHOUT ANY WARRANTY; without even the implied warranty of
15 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 // GNU General Public License for more details.
17 //
18 // You should have received a copy of the GNU General Public License
19 // along with this program; if not, write to the
20 // Free Software Foundation, Inc.,
21 // 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
22
23 /** \mainpage The Configuration and Runtime Control Library
24
25     The Console library implements a runtime interactive (network) console which allows to
26     configure, control and manipulate a running application in any way. Additionally this library
27     provides support for configuration files and command line parsing which can be used with or
28     without the network console.
29
30     \autotoc
31
32
33     \section console_intro Introduction
34
35     There are three parts to the Config/console library:
36
37     The Config/Console library is built around several components
38
39     \li The \link node_tree Node tree\endlink represents all configuration options and commands
40         organized in a filesystem like structure.
41     \li \link console_commands Actions\endlink are added to the node tree in the form of command
42         nodes.
43     \li There exist several interfaces to \link console_access access\endlink entries in the node
44         tree: interactive console, reading configuration files etc.
45
46     The node tree works like a directory structure. Commands are entered into this directory
47     structure and can be called passing arbitrary arguments. Configuration parameters are just
48     commands which set their respective parameter, however the library allows commands to do much
49     more than just that.
50
51
52     \section console_example Example
53
54     The following example shows a \e very short summary on how to integrate the config/console
55     library. See above links for more:
56
57     \code
58     #include <senf/Console.hh>
59
60     // Define callback function.
61     void mycommand(std::ostream & os, int foo, int bar)
62     {
63         // ...
64         os << "!! Important message ...\n";
65     }
66
67     namespace kw = senf::console::kw;
68     namespace fty = senf::console::factory;
69
70     int main(int argc, char** argv)
71     {
72         // Provide global documentation
73         senf::console::root()
74             .doc("This is someServer server");
75
76         // Add a command
77         senf::console::root().add("mycommand", fty::Command(&mycommand)
78             .doc("If <bar> is given, flurgle the <foo>, otherwise burgle it")
79             .arg("foo")
80             .arg(kw::name = "bar", kw::default_value = 0) );
81
82        // Parse command line parameters
83        senf::console::parseOptions(argc,argv);
84
85         // Start the interactive console server
86         senf::console::Server::start(senf::INet4SocketAddress(senf::INet4Address::None, 23232u))
87             .name("someServer");
88
89         // Run the scheduler
90        senf::scheduler::process();
91     }
92     \endcode
93
94     after this registration, we can call the command from the command-line using
95
96     <pre>
97     $ someServer --mycommand="1 2"
98     </pre>
99
100     the console can be accessed easily via telnet:
101
102     <pre>
103     $ telnet localhost 23232
104     Trying 127.0.0.1...
105     Connected to localhost.
106     Escape character is '^]'
107     xxxx-xx-xx xx:xx:xx.xxxxxx-0000 [NOTICE][senf::console::Server] Registered new client 0xxxxxxx
108     someServer:/# ls
109     mycommand
110     someServer:/# mycommand
111     !! Important message  ...
112     someServer:/# exit
113     xxxx-xx-xx xx:xx:xx.xxxxxx-0000 [NOTICE][senf::console::Server] Disposing client 0xxxxxxx
114     Connection closed by foreign host.
115     $
116     </pre>
117
118     \see \ref console_testserver for a complete example application
119
120
121     \section intro_usage Using the Console: Configuration files, Network console
122     \seechapter \ref console_access
123
124     There are several ways to access the node tree:
125     \li By parsing configuration files
126     \li By parsing command line parameters
127     \li By providing interactive or non-interactive network console access
128
129
130     \section intro_nodes The node tree
131     \seechapter \ref node_tree
132
133     The basic idea is, that the console/config library manages a directory structure of parameters
134     and auxiliary commands. Parameters are just commands which set a parameter value so everything
135     is either a directory entry (senf::console::DirectoryNode) or a command
136     (senf::console::CommandNode).
137
138
139     \section intro_commands Implementing console/config commands
140     \seechapter \ref console_commands \n
141     \seechapter \ref senf::console::factory
142
143     The console/config language does not define, how arguments are passed to the commands, it just
144     tokenizes the input and passes the tokens to the commands which then handle the
145     conversion.
146
147     Since parsing the tokens into something usable is quite tedious and error prone, the library
148     implements automatic argument parsing where the argument tokens are automatically parsed
149     depending on argument types. This enables you to register a command taking an integer argument
150     which will be called with an already parsed integer value (or throw a
151     senf::console::SyntaxErrorException if the conversion fails). This will be the most often used
152     command.
153  */
154
155 /** \defgroup console_access Accessing the Console/Config tree
156
157     The Console/Config library provides several ways to use the node tree to configure and control
158     an application.
159
160     \autotoc
161
162
163     \section console_access_config Configuration support
164
165     The configuration support of the Console/Config library revolves around the ConfigSource
166     concept. Each ConfigSource will somehow provide commands which will then be executed against the
167     node tree.
168
169     To simplify the usage, there will always be three interfaces to a specific config source:
170     \li A constructor to build a bare config source which is then added to a
171         senf::console::ConfigBundle (see \ref console_access_multiple)
172     \li A class parsing and executing a single config source. The visible interface of this class is
173         a combination of the constructor and the senf::console::ConfigBundle interfaces.
174     \li A helper function which will do the complete parsing of a single source with default
175         parameters.
176
177     When parsing these configuration sources, it is always possible to optionally change the root
178     node used during parsing and it is also possible to restrict parsing to a command subset. See
179     \ref console_access_partial.
180
181
182     \subsection console_access_file Configuration files
183
184     <table class="senf fixedwidth">
185     <tr><td><b>Constructor</b></td> <td>senf::console::FileConfig()</td></tr>
186     <tr><td><b>Class</b></td>       <td>senf::console::ConfigFile</td></tr>
187     <tr><td><b>Helper</b></td>      <td>senf::console::parseFile()</td></tr>
188     </table>
189
190     In it's simplest form, parsing a configuration file consists of calling
191     senf::console::parseFile() with the name of the respective config file as argument.
192
193     \code
194     senf::console::parseFile("some.conf");
195     \endcode
196
197     To get more flexible, instantiate a senf::console::ConfigFile instance at use that to parse the
198     file
199
200     \code
201     senf::console::ConfigFile cf ("some.conf");
202     // The following line is optional: Call to ignore mussing files
203     cf.ignoreMissing();
204     cf.parse();
205     \endcode
206
207     If the application supports other configuration sources besides a single configuration file
208     (like command line options) or if it supports multiple configuration files (e.g. a system-wide
209     and a user specific configuration file) see \ref console_access_multiple and add one (or more)
210     senf::console::FileConfig() source to a senf::console::ConfigBundle.
211
212
213     \subsubsection console_access_file_syntax Configuration file syntax
214
215     Configuration files are written in a simple configuration language. This language is almost
216     declarative (e.g. it does not have any control-flow statements) but is processed imperatively
217     from top to bottom. This is very simple and flexible.
218
219     Commands are referenced by their path in the node tree. To simplify working with deeply nested
220     directory structures, the current directory may be changed persistently or temporarily for some
221     commands.
222     \code
223     /server/port 1234;
224
225     /logger/targets/console {
226         accept senf::log::Debug IMPORTANT;
227         accept server::ServerLog CRITICAL;
228     }
229     \endcode
230
231     \see \ref console_parser
232
233
234     \subsection console_access_options Command line options
235
236     <table class="senf fixedwidth">
237     <tr><td><b>Constructor</b></td> <td>senf::console::OptionsConfig()</td></tr>
238     <tr><td><b>Class</b></td>       <td>senf::console::ProgramOptions</td></tr>
239     <tr><td><b>Helper</b></td>      <td>senf::console::parseOptions()</td></tr>
240     </table>
241
242     Command line options can either be parsed by calling the senf::console::parseOptions() helper
243
244     \code
245     senf::console::parseOptions(argc, argv)
246     \endcode
247
248     or more flexibly by instantiating a senf::console::ProgramOptions class
249
250     \code
251     std::vector<std::string> args;
252     senf::console::ProgramOptions opts (argc, argv);
253     opts
254         .nonOptions(args)
255         .alias('c', "--mycommand",true)
256         .alias('C', "--mycommand=2 3");
257     opts.parse();
258     \endcode
259
260     This registeres two short options and accumulates all non-option arguments in \c args.
261
262     If the application supports other configuration sources besides the command line options (like
263     configuration files) see \ref console_access_multiple and add a senf::console::OptionsConfig()
264     source to a senf::console::ConfigBundle.
265
266     See \ref senf::console::ProgramOptions for the source specific additional parameters. These
267     apply to senf::console::ProgramOptions and to the senf::console::OptionsConfig() source.
268
269
270     \subsubsection console_access_options_syntax Options syntax
271
272     Command line options are primarily parsed as long-options. Long options start with '--'. Further
273     '-' characters serve as directory separators if required (that is, they are \e only interpreted
274     as directory separator is there is no entry in the current (sub-) directory matching more than a
275     single name component). This still allows using hyphens in node names.
276
277     Options can be abbreviated at each directory boundary: A command <tt>/foo/bar/do</tt> can be
278     called as <tt>--f-b-d</tt> as long as this name is unique.
279
280     Everything after the first '=' character is passed as arguments to the command. The exact
281     interpretation depends on the command:
282     \li If the command only takes a single token as argument (e.g. a single string or numeric
283         value), everything after the '=' sign is parsed into a single token (e.g. see rows 2 and 3
284         of the following table).
285     \li In all other cases, the string after the '=' sign is parsed into argument tokens using the
286         config/console parser. In this case, quoted strings need to be quoted twice, once for the
287         shell and once for the config/console parser (e.g. see rows 4 and 5 of the following table).
288     \li If the option has no '=' character, the list of argument tokens will be empty (e.g. see row
289         1 of the following table)
290
291     Without these rules, multi-word string arguments would \e always have to be quoted twice (for
292     the shell and the config/console parser).
293
294     <table style="font-size:80%" class="senf">
295     <tr><th>Command</th><th>File syntax</th><th>Option syntax</th></tr>
296
297     <tr>
298       <td><tt>void doo()</tt></td>
299       <td><tt>/path/to/doo;</tt></td>
300       <td><tt>--path-to-doo</tt></td>
301     </tr>
302
303     <tr>
304       <td><tt>void doo(std::string const &)</tt></td>
305       <td><tt>/path/to/doo john.doe@everywhere.org;</tt></td>
306       <td><tt>--path-to-doo="john.doe@everywhere.org"</tt></td>
307     </tr>
308
309     <tr>
310       <td><tt>void doo(std::string const &)</tt></td>
311       <td><tt>/path/to/doo "some text";</tt></td>
312       <td><tt>--path-to-doo="some text"</tt></td>
313     </tr>
314
315     <tr>
316       <td><tt>void doo(std::string const &, int)</tt></td>
317       <td><tt>/path/to/doo take 1;</tt></td>
318       <td><tt>--path-to-doo="take 1"</tt></td>
319     </tr>
320
321     <tr>
322       <td><tt>void doo(std::string const &, int)</tt></td>
323       <td><tt>/path/to/doo "take two" 1;</tt></td>
324       <td><tt>--path-to-doo='"take two" 1'</tt></td>
325     </tr>
326     </table>
327
328     Short options are registered as aliases for long options. They can be registered with or without
329     an implied parameter and can optionally take a parameter. so after
330
331     \code
332     opts
333         .alias('c', "--mycommand",true)
334         .alias('C', "--mycommand=2 3");
335     \endcode
336
337     we can call
338
339     <pre>
340     $ program -C -c "4 5"
341     $ program -Cc"4 5"
342     </pre>
343
344     which is the same as
345
346     <pre>
347     $ program --mycommand="2 3" --mycommand="4 5"
348     </pre>
349
350     (Beware, that the second argument to \c alias() must \e not be shell quoted).
351
352
353     \subsection console_access_root Changing the root node
354
355     When used in it's default state, parsing will always interpret all commands relative to the
356     senf::console::root() node and will parse a file completely.
357
358     The first possibility to control this is to change the root node. This is done by
359     \li passing that root node to the helper class or to the parse helper as an additional argument
360         (see the respective documentation).
361     \li passing it to the senf::console::ConfigBundle constructor when parsing multiple sources.
362
363     for example:
364
365     \code
366     senf::console::parseFile("/etc/myserver.conf", senf::console::root()['config']);
367     \endcode
368
369     This functionality is even more powerful by combining it with \c link nodes: This allows to
370     selectively choose commands from the node tree which are to be made accessible for
371     configuration. See \ref node_tree.
372
373
374     \subsection console_access_partial Partial / incremental configuration
375
376     Another feature provided by senf::console::ConfigBundle and all helper classes is partial
377     parsing.
378
379     \code
380     // Create a console/config aware object and place it (that is it's directory node) into the node
381     // tree
382     FooObject foo;
383     senf::console::root().add("foo", foo.dir);
384
385     // Open configuration file
386     senf::console::ConfigFile cf ("/etc/myserver.conf");
387
388     // Parse only commands in the configuration file which are in the foo.dir directory
389     cf.parse(foo.dir);
390
391     ...
392
393     // Anywhere later, parse the rest of the configuration file
394     cf.parse();
395     \endcode
396
397     This feature allows to parse parts of one or more configuration sources before the
398     console/config tree has been fully established. Partial parsing can be applied any number of
399     times to arbitrary nodes. Any command already parsed will be skipped automatically.
400
401     When combining partial parsing with \c chroot() and \c link's, it is important to realize, that
402     <em>partial parsing always applies to the \e real target and ignores links</em>. This is very
403     important: It allows a subsystem to parse it's configuration parameters irrespective of any
404     links pointing to nodes of that subsystem.
405
406
407     \subsection console_access_multiple Multiple sources
408
409     Most of the time, an application will utilize multiple configuration sources: A global
410     configuration file, maybe a user specific local configuration file, command line options ...
411
412     When parsing configuration commands, especially using partial / incremental parsing, all parse
413     commands should be applied to each configuration source in turn. This is the responsibility of
414     senf::console::ConfigBundle.
415
416     \code
417     senf::console::ScopedDirectory<> config;
418     senf::console::root().add("config", config);
419
420     // Let's enable all logger commands for configuration
421     config.link("logger", senf::console::root()["logger"]);
422
423     // Create bundle and add sources
424     std::vector<std::string> args;
425     senf::console::ConfigBundle conf (senf::console::root()["config"]);
426     conf.add( senf::console::FileConfig("/etc/myserver.conf") );
427     conf.add( senf::console::FileConfig(".myserver.conf")->ignoreMissing() );
428     conf.add( senf::console::OptionsConfig(senf::Daemon::instance().argc(),
429                                            senf::Daemon::instance().argv()) )
430         .nonOptions(args)
431         .alias('c', "--mycommand",true)
432         .alias('C', "--mycommand=2 3");
433
434     // Parse the logger subsystem commands in '/logger'
435     conf.parse(senf::console::root()['logger']);
436
437     ...
438
439     // Parse all other configuration commands. All necessary commands and links in '/config' must by
440     // now have been created.
441     conf.parse();
442     \endcode
443
444     This example parses three configuration sources: Two configuration files and additional
445     parameters specified on the command line. All the configuration commands are placed into the
446     <tt>/config</tt> directory (directly or via links). The configuration sources are parsed in the
447     order they are specified, so in this case, the command line options will override any options
448     specified in one of the configuration files.
449
450
451     \section console_access_console The network console
452
453     To make the network console accessible, it must be initialized when the program is started:
454     \code
455     #include <senf/Console.hh>
456
457     int main(int argc, char * argv [])
458     {
459         // Configure console nodes, add commands ...
460
461         // Start console server
462         senf::console::start(senf::INet4SocketAddress(12345u))
463            .name("myserver");
464
465         // You need to enter the scheduler main-loop for the server to work
466         senf::scheduler::process();
467
468         // Alternatively enter the main-loop via the PPI
469         // senf::ppi::run();
470     }
471     \endcode
472
473     This will start the server on IPv4 port 12345. The servers name (as displayed in the interactive
474     console prompt) is set to 'myserver'.
475
476     After launching the application, the server can be accessed at the given port:
477     \htmlonly
478     <pre>
479     bash$ telnet localhost 12345
480     Trying 127.0.0.1...
481     Connected to localhost.
482     Escape character is '^]'.
483
484     myserver:/$ exit
485     Connection closed by foreign host.
486     bash$
487     </pre>
488     \endhtmlonly
489
490     It is possible to start multiple server consoles by calling \c start() multiple times with
491     different ports/addresses. Each server can be configured separately (e.g. root node, mode ...).q
492
493
494     \subsection console_serverclient Server and Client objects
495
496     The senf::console::Server and senf::console::Client objects offer further API calls. To access
497     the server instance you need to store away the senf::console::Server reference returned when
498     starting the server so you can later refer to it:
499     \code
500     int main(int, char**)
501     {
502         senf::console::Server & server ( senf::console::start( ... ) );
503
504         // Do something ...
505
506         server.stop()
507     }
508     \endcode
509
510     The client instance can be accessed via the \c std::ostream arg of any command callback
511     \code
512     void someCallback(std::ostream & os, ... )
513     {
514         senf::console::Client & client (senf::console::Client::get(os));
515
516         // Use the client's log target
517         client.route<senf::log::Debug, senf::Log::IMPORTANT>();
518     }
519     \endcode
520
521     \see
522         senf::console::Server for the Server API \n
523         <a href="classsenf_1_1console_1_1Client-members.html">senf::console::Client / List of all
524         members</a> for the Client API
525
526
527     \subsection console_shell The interactive console shell
528
529     The interactive shell implements a fully function line editor on capable terminals. This support
530     is available when using a full featured telnet client on a fully supported terminal (like vt100
531     or xterm).
532
533     The shell supports auto-cd and auto-completion: If you enter the name of a directory at the
534     prompt, the console will change to that directory. With auto-completion, any unique beginning of
535     a path component will be completed automatically and transparently to the corresponding full
536     name.
537
538
539     \subsection console_noninteractive Non-interactive network console
540
541     After a new connection is established, the console server waits a short time for data to arrive.
542     Only if nothing happens in the first 500ms, an interactive session is initialized.
543
544     By sending data immediately after opening the connection, the console is switched into
545     non-interactive mode. In this mode, no prompt is displayed. In this mode, commands are \e not
546     terminated automatically by end-of-line (CR). This allows, to easily cat an arbitrary
547     configuration file into the network console using netcat:
548
549     <pre>
550     $ nc -q1 localhost 23232 < some.conf
551     </pre>
552
553     The argument <tt>-q1</tt> makes netcat close the sending end of the connection on EOF and wait
554     up to 1 second for the console to terminate. Even better, use \c netcat6, which has full TCP
555     half-close support.
556
557     <pre>
558     $ echo "ls" | nc6 --half-close localhost 23232 2>/dev/null
559     console/
560     server/
561     test/
562     $
563     </pre>
564
565     Commands are executed as soon as the terminating character (';', '{' or '}') is received or when
566     the sending end of the connection is closed.
567
568     \section console_udp Non-interactive UDP console
569
570     The UDP console allows to script the console tree via UDP packets. Every UDP packet must be a
571     complete command (or sequence of commands). The combined reply of all these commands will be
572     returned in a single UDP packet. This reply can be disabled or directed to a different address.
573
574     To start a UDP server, just create an instance of the senf::console::UDPServer class
575     \code
576     senf::console::UDPServer server (senf::INet4SocketAddress("127.0.0.1:23232"));
577     \endcode
578     (Remember to enter the scheduler main-loop for processing)
579
580     Commands may then be sent to this UDP console e.g. using netcat
581     <pre>
582     $ echo "cd sys; ls" | nc -uq0 localhost 23232 2>/dev/null
583     </pre>
584
585     \see senf::console::UDPServer
586  */
587
588 /** \defgroup console_commands Supported command types
589
590     The Console/config library supports quite a number of different command types. All these types
591     of command are registered by passing an appropriate factory instance to DirectoryNode::add()
592
593     \autotoc
594
595
596     \section console_cmdadd Adding commands and setting attributes
597
598     Basically, all commands are added using senf::console::DirectoryNode::add().
599     \code
600     namespace fty = senf::console::factory;
601     dir.add("name", fty::Command(callback));
602     \endcode
603     will add the command 'name' which will execute 'callback' when called.
604
605     The add call always returns (something which can be used as) a reference to the command node
606     added:
607     \code
608     senf::console::CommandNode & node ( dir.add( ... ) );
609     \endcode
610
611     Depending on the object added, you can also bind to a more specific node type
612     (e.g. senf::console::SimpleCommand) if you know the type of node returned.
613
614     Nodes are always added using a factory from the senf::console::factory namespace. The factory
615     has additional (type specific) attributes. These attributes are set by calling member functions
616     called 'attributors' on the temporary factory instance. It is \e not guaranteed, you can call
617     these members on the node reference returned by the \c add() call.
618     \code
619     namespace fty = senf::console::factory;
620     dir.add("name", fty::Command(callback) .doc("The documentation") );
621     \endcode
622     sets the \e doc attribute (if that is available, otherwise this will fail to compile).
623     \see senf::console::factory for a list of all node factories.
624
625
626     \section console_manualparse Manually parsing command arguments
627
628     This is the most primitive type of command. It will be called with an output stream and with a
629     senf::console::ParseCommandInfo reference which holds information about the command parsed.
630
631     From this information the command callback gets a list of arguments or tokens which then can be
632     interpreted in an arbitrary way.
633     \code
634     void fun1(std::ostream & os, senf::console::ParseCommandInfo const & command)
635     {
636         // Here we declare variables for the arguments
637         std::string value;
638
639         {
640             // We parse the arguments using the CheckedArgumentIteratorWrapper. This wrapper
641             // will throw a SyntaxErrorException if we access a nonexistent argument or if we
642             // do not parse all arguments.
643             senf::console::CheckedArgumentIteratorWrapper args (command.arguments());
644
645             // Extract the first argument. This is again a token range.
646             senf::console::ParseCommandInfo::TokensRange arg1Tokens ( *(args++) );
647             if (arg1Tokens.size() != 1)
648                 raise senf::console::SyntaxErrorException("argument syntax error");
649             value = arg1Tokens[0].value();
650         }
651
652         os << value << std::endl;
653     }
654     \endcode
655
656     Registering this callback is done by simply adding it. To provide online help, pass it to
657     'doc()':
658     \code
659     namespace fty = senf::console::factory;
660     senf::console::root().add("test1", fty::Command(&fun1)
661         .doc("Usage:\n"
662              "    test1 arg\n"
663              "\n"
664              "Echo 'arg' to the console") );
665     \endcode
666
667     The callback may now be called interactively on the console by it's registered name:
668     \htmlonly
669     <pre>
670     server:/$ test1
671     invalid number of arguments
672     server:/$ test1 stefan@j32.de
673     stefan@j32.de
674     server:/$ test1 (echo me)
675     argument syntax error
676     server:/$ help test1
677     Usage:
678         test1 arg
679
680     Echo 'arg' to the console
681     server:/$
682     </pre>
683     \endhtmlonly
684
685     As you can see above, the arguments and tokens are returned as <a
686     href="http://www.boost.org/doc/libs/release/libs/range/doc/html/range/reference/utilities/iterator_range.html">
687     boost::iterator_range</a> instances. These behave much like containers: They have \c begin() and
688     \c end() and some other useful members.
689
690     The parser will have divided the argument tokens into arguments already. This simplifies further
691     parsing. If however you want to access the list of argument tokens as a single list, you can do
692     so using senf::console::ParseCommandInfo::tokens().
693
694     Parsing arguments is quite simple but can get very tedious. To simplify this task, the parsing
695     can be delegated to the Console/config library. See the next section.
696
697     This type of command has only a single attribute, \e doc to set the commands documentation.
698
699
700     \section console_autoparse Automatic argument parsing
701
702     To greatly simplify parsing complex commands, we turn to automatic argument parsing.
703
704
705     \subsection console_autoadd Adding
706
707     Automatically parsed commands are registered by just adding a callback which has the correct
708     arguments and return-value defined:
709     \code
710     std::string fun2(std::string const & arg)
711     {
712         return arg;
713     }
714     \endcode
715
716     This extremely simple callback may be registered by adding it to a senf::console::DirectoryNode.
717     \code
718     namespace fty = senf::console::factory;
719     senf::console::root().add("test2", fty::Command(&fun2));
720     \endcode
721     The functionality is now identical to \c test1:
722     \htmlonly
723     <pre>
724     server:/$ test2
725     invalid number of arguments
726     server:/$ test2 stefan@j32.de
727     stefan@j32.de
728     server:/$ test2 (echo me)
729     argument syntax error
730     server:/$ help test2
731     Usage:
732         test2 arg11:string
733     server:/$
734     </pre>
735     \endhtmlonly
736
737
738     \subsection command_ostream Accessing the console stream
739
740     Commands may have an optional first argument of type <tt>std::ostream &</tt>. This argument is
741     not considered part of the real interface. When the command is executed, the callback will be
742     passed the current consoles output stream object in this argument. With this, the callback can
743     output arbitrary messages to the network console.
744     \code
745     namespace fty = senf::console::factory;
746
747     void fun3(std::ostream & os, unsigned n, std::string text)
748     {
749         while (n-- > 0) os << text << std::endl;
750     }
751
752     senf::console::root().add("test3", fty::Command(&fun3));
753     \endcode
754
755     This simple command can now be used thus:
756     \htmlonly
757     <pre>
758     server:/$ test3
759     invalid number of arguments
760     server:/$ test3 stefan@j32.de
761     invalid number of arguments
762     server:/$ test3 2 ok
763     ok
764     ok
765     server:/$ help test3
766     Usage:
767         test3 arg11:int arg12:string
768     server:/$
769     </pre>
770     \endhtmlonly
771
772
773     \subsection command_overload Overloading
774
775     Automatically parsed commands can be overloaded: You can register multiple commands under the
776     same name. Each overload is tried in turn until no SyntaxErrorException is raised.
777     \code
778     namespace fty = senf::console::factory;
779
780     senf::console::root().add("test4", fty::Command(&fun3));
781     senf::console::root().add("test4", fty::Command(&fun2));
782     \endcode
783     And now, we can call \c test4 with one or two args:
784     <pre>
785     server:/$ test4
786     invalid number of arguments
787     server:/$ test4 stefan@j32.de
788     stefan@j32.de
789     server:/$ test4 2 ok
790     ok
791     ok
792     server:/$ help test4
793     Usage:
794         1- test4 arg11:int arg12:string
795         2- test4 arg21:string
796     server:/$
797     </pre>
798
799     One note: When taking the address of an overloaded function (member or non-member), the C++
800     language forces you to cast that address to one of the possible types so the compiler knows,
801     which overload is requested. So to add a function which is overloaded in C++, each overload
802     needs to be added explicitly, casting to the correct type. There are some macros in
803     Utils/membind.hh to simplify this:
804
805     \code
806     namespace fty = senf::console::factory;
807
808     void over(int);
809     void over(int,int);
810
811     senf::console::root().add("over", fty::Command(SENF_FNP(void, over, (int))));
812     senf::console::root().add("over", fty::Command(SENF_FNP(void, over, (int,int)));
813
814     class SomeModule {
815       senf::console::ScopedDirectory<SomeModule> dir;
816
817       unsigned int overlodedMethod() const {....};
818       void overlodedMethod(unsigned int)   {....};
819
820       void addConsoleCommands() {
821         dir.node()
822             .add("overlodedMethod", fty::Command(
823                      SENF_MEMBINDFNP(unsigned int, SomeModule, overlodedMethod, () const)));
824         dir.node()
825             .add("overlodedMethod", fty::Command(
826                      SENF_MEMBINDFNP(unsigned int, SomeModule, overlodedMethod, (unsigned int))));
827       }
828     }
829     \endcode
830
831
832     \subsection console_attributes Attributes
833
834     As have seen so far, some documentation is automatically provided. We can add more info, by
835     setting additional attributes.
836     \code
837     namespace fty = senf::console::factory;
838
839     senf::console::root().add("test5", fty::Command(&fun3)
840         .doc("Echo text to the console")
841         .overloadDoc("Repeat {arg12} for {arg11} lines") );
842     senf::console::root().add("test4", fty::Command(&fun2)
843         .overloadDoc("Echo the {arg21} argument") );
844     \endcode
845
846     This additional info is used to provide more documentation:
847     \htmlonly
848     <pre>
849     server:/$ help test5
850     Usage:
851         1- test5 arg11:int arg12:string
852         2- test5 arg21:string
853
854     Echo text to the console
855
856     Variant 1:
857     Repeat {arg12} for {arg11} lines
858
859     Variant 2:
860     Echo the {arg21} argument
861     senf:/$
862     </pre>
863     \endhtmlonly
864
865
866     \subsection console_argattributes Argument attributes
867
868     Additional attributes can be set for each parameter. They are all passed to the
869     senf::console::ParsedArgumentAttributor::arg() attribute.
870
871     \code
872     namespace kw = senf::console::kw;
873     namespace fty = senf::console::factory;
874
875     senf::console::root().add("test6", fty::Command(&fun3)
876         .doc("Echo text to the console")
877         .overloadDoc("Repeat {text} for {n} lines");
878         .arg( kw::name = "n", kw::description="Number of repetitions" )
879         .arg( kw::name = "text", kw::description="Text to output" ) );
880     senf::console::root().add("test6", fty::Command(&fun2)
881         .overloadDoc("Echo the {text} argument")
882         .arg( kw::name = "text" ) );
883     \endcode
884
885     (Sadly, there is no way to automatically find out the \e name of an argument, just it's type.)
886     Every callback argument corresponds with a call of the \c arg() attribute. Argument attributes
887     are set using keywords from the \ref senf::console::kw namespace. You will probably either use
888     this namespace via a namespace alias (as above) or via a <tt>using namespace
889     senf::console::kw</tt> declaration (but beware of name collisions).
890
891     You don't need to specify any information for an argument: To skip an argument, just call \c
892     arg() without attributes for this argument.
893
894     After adding this information, the online help is much more readable
895       \htmlonly
896     <pre>
897     server:/$ help test6
898     Usage:
899         1- test6 n:int text:string
900         2- test6 text:string
901
902     With:
903         n         Number of repetitions
904         text      Text to output
905
906     Echo text to the console
907
908     Variant 1:
909     Repeat {text} for {n} lines
910
911     Variant 2:
912     Echo the {text} argument
913     senf:/$
914     </pre>
915     \endhtmlonly
916
917     Since most of the time, we only need to set the name and possibly a description for arguments,
918     there is a shortcut: name and description can be specified as positional arguments in this
919     order. So the following will give the exactly same result as above:
920     \code
921     namespace kw = senf::console::kw;
922     namespace fty = senf::console::factory;
923
924     senf::console::root().add("test6", fty::Command(&fun3)
925         .doc("Echo text to the console")
926         .overloadDoc("Repeat <text> for <n> lines");
927         .arg("n",    "Number of repetitions")
928         .arg("text", "Text to output") );
929     senf::console::root().add("test6", fty::Command(&fun2)
930         .overloadDoc("Echo the <text> argument") );
931         .arg("text");
932     \endcode
933
934     Keyword arguments should always be used if additional attributes are set. You can however mix
935     positional and keyword arguments.
936
937
938     \subsection console_defaults Default values
939
940     Another information which can not be automatically gathered from the type system is default
941     values. These have to be declared explicitly:
942     \code
943     namespace kw = senf::console::kw;
944     namespace fty = senf::console::factory;
945
946     senf::console::root().add("test7", fty::Command(&fun3)
947         .doc("Echo {text} to the console, repeating {text} for {n} lines")
948         .arg("n",    "Number of repetitions", kw::default_value=1)
949         .arg("text", "Text to output") );
950     \endcode
951
952     Default values can be used together with overloading. Default (optional) value support is quite
953     flexible, it is not mandatory, for default values to be specified only for the trailing
954     arguments. For the exact definition, how parsed argument values are assigned to overload
955     arguments in the presence of default values, see \ref senf::console::kw::default_value.
956
957     \htmlonly
958     <pre>
959     server:/$ test7 echo
960     echo
961     server:/$ test7 4 ok
962     ok
963     ok
964     ok
965     ok
966     server:/$ help test7
967     Usage:
968         test4 [n:unsigned] text:string
969
970     With:
971         n         Number of repetitions
972             default: 1
973         text      Text to output
974
975     Echo {text} to the console, repeating {text} for {n} lines
976     server:/$
977     </pre>
978     \endhtmlonly
979
980
981     \subsection console_boostfn Non-function-pointer commands
982
983     It is possible to add other callable objects besides function (and member-function)
984     pointers. However, since it is not possible to automatically deduce the argument and return
985     types in this case, the signature has to be specified explicitly:
986     \code
987     namespace fty = senf::console::factory;
988
989     senf::console::root()
990         .add("test8",fty::Command<void (std::ostream &, std::string const &)>(
991                          boost::bind(&fun3, _1, 4u, _2)));
992     \endcode
993
994     This works with any callable object where argument types cannot be deduced automatically:
995     Boost.Bind expressions, Boost.Lambda expressions, functors and so on.
996
997     \htmlonly
998     <pre>
999     server:/$ test8 ok
1000     ok
1001     ok
1002     ok
1003     ok
1004     server:/$ help test8
1005     Usage:
1006         test8 arg11:string
1007     server:/$
1008     </pre>
1009     \endhtmlonly
1010
1011
1012     \subsection console_attr_summary Attribute summary
1013
1014     Here a summary of the most common attributes
1015
1016     <table class="senf fixedwidth">
1017
1018     <tr><td style="width:14em">\link senf::console::ParsedArgumentAttributorBase::doc() .doc\endlink
1019     ( \e doc )</td><td>Set documentation for all overloads</td></tr>
1020
1021     <tr><td>\link senf::console::ParsedArgumentAttributorBase::overloadDoc()
1022     .overloadDoc\endlink ( \e doc )</td><td>Set documentation for a specific overload</td></tr>
1023
1024     <tr><td>\link senf::console::ParsedArgumentAttributor::arg() .arg\endlink ( \e argument \e
1025     attributes )</td><td>Set argument attributes (see below)</td></tr>
1026
1027     </table>
1028
1029     The most important argument attributes (all defined in the senf::console::kw namespace) are:
1030
1031     <table class="senf fixed width">
1032
1033     <tr><td style="width:14em">\link senf::console::kw::name kw::name\endlink</td><td>Parameter
1034     name</td></tr>
1035
1036     <tr><td>\link senf::console::kw::description kw::description\endlink</td><td>One-line
1037     description of the argument</td></tr>
1038
1039     <tr><td>\link senf::console::kw::default_value kw::default_value\endlink</td><td>Arguments
1040     default value</td></tr>
1041
1042     </table>
1043
1044     \see <a
1045         href="classsenf_1_1console_1_1ParsedArgumentAttributor-members.html">senf::console::ParsedArgumentAttributor
1046         / List of all members</a> for the complete attribute interface \n
1047         \ref senf::console::kw for a list of all argument attribute keywords
1048
1049
1050     \section console_memberfn Member functions
1051
1052     Non-static member functions are supported like non-member functions (static member functions are
1053     identical to non-members). They must however be added through a senf::console::ScopedDirectory
1054     instance to bind them to their instance.
1055     \code
1056     namespace fty = senf::console::factory;
1057
1058     class Test1
1059     {
1060     public:
1061         senf::console::ScopedDirectory<Test1> dir;
1062
1063         Test1(std::string label) : dir(this), label_ (label)
1064             { dir.add("test", fty::Command(&Test::test1, this));
1065               dir.add("test", fty::Command(&Test::test2, this)); }
1066
1067         std::string test1(std::string const & text)
1068             { return label_ + ": " + text; }
1069
1070         void test2(std::ostream & os, unsigned n, std::string const & text)
1071             { while (n-- > 0) os << label << ": " << text << std::endl; }
1072
1073     private:
1074         std::string label_;
1075     };
1076
1077     // ...
1078
1079     Test1 test1ob ("test");
1080     senf::console::root().add("test1ob", test1ob.dir);
1081     \endcode
1082
1083     Binding via senf::console::ScopedDirectory ensures, that the commands are automatically removed
1084     from the tree when the object is destroyed.
1085
1086
1087     \section console_variables Variables
1088
1089     \subsection console_varadd Adding
1090
1091     The console/config library supports the direct registration of variables as commands. A
1092     variable command consists of two overloads, one to query the current value and one to change the
1093     value.
1094     \code
1095     namespace fty = senf::console::factory;
1096
1097     class Test2
1098     {
1099     public:
1100         senf::console::ScopedDirectory<Test2> dir;
1101
1102         Test2() : dir(this), var_(0)
1103             { dir.add("var", fty::Variable(var_) ); }
1104
1105     private:
1106         int var_;
1107     };
1108
1109     Test2 test2ob;
1110     senf::console::root().add("test2ob", test2ob.dir);
1111     \endcode
1112     This shows the most common scenario: A member variable is added to a ScopedDirectory of the same
1113     class. This ensures, that the variable command node is removed from the tree when the instance
1114     (and thereby the variable) are destroyed. The variable can now be used like any other command:
1115     \htmlonly
1116     <pre>
1117     server:/$ test2ob/var
1118     0
1119     server:/$ test2ob/var 10
1120     server:/$ test2ob/var
1121     10
1122     server:/$ help test2ob
1123     Usage:
1124         1- var new_value:int
1125         2- var
1126     server:/$
1127     </pre>
1128     \endhtmlonly
1129
1130
1131     \subsection console_varro Read-only variables
1132
1133     The library also supports read-only variables. To make a variable read-only, just wrap it in \c
1134     boost::cref() (where \c cref stands for \c const reference)
1135     \code
1136     namespace fty = senf::console::factory;
1137
1138     int var (0);
1139
1140     senf::console::root().add("var1", fty::Variable(boost::cref(var)));
1141     \endcode
1142     A read-only variable only has a single overload:
1143     \htmlonly
1144     <pre>
1145     server:/$ var1
1146     0
1147     server:/$ help var1
1148     Usage:
1149         var1
1150     server:/$
1151     </pre>
1152     \endhtmlonly
1153
1154
1155     \subsection console_varattr Attributes
1156
1157     The most important Variable command attributes are
1158
1159     <table class="senf fixedwidth">
1160
1161     <tr><td style="width:14em">\link senf::console::VariableAttributor::doc() .doc\endlink
1162     ( \e doc )</td><td>Set variable documentation</td></tr>
1163
1164     <tr><td>\link senf::console::VariableAttributor::onChange() .onChange\endlink
1165     ( \e handler )</td><td>Set change handler</td></tr>
1166
1167     </table>
1168
1169     \see senf::console::VariableAttributor for the complete attribute interface
1170
1171
1172     \subsection console_varchange Change notification
1173
1174     A \e handler can be set to be called, whenever the variable is changed. It will be called with a
1175     reference to the old value. The handler is called, after the value has been changed
1176
1177     \code
1178     namespace fty = senf::console::factory;
1179
1180     int var (0);
1181
1182     // Since this is int, it would make sense to declare the argument pass-by-value (int old)
1183     // but for more complex args, use a const & here
1184     void varChanged(int const & old)
1185     {
1186         // ...
1187     }
1188
1189     senf::console::root().add("var2", fty::Variable(var)
1190         .onChange(&varChanged) );
1191     \endcode
1192
1193     After this setup, \c varChanged will be called, whenever the value has changed.
1194
1195
1196     \section console_args Console library supported types
1197
1198     By default, types which can be read and written using \c iostreams are automatically supported.
1199     This includes all the C++ built-in types as well as user defined streamable types.
1200
1201     An exception is made for all \c char types: These types are by default parsed as \e numeric
1202     values not single-character data. To interpret \c char values as single-char strings, use \ref
1203     senf::console::CharAsString.
1204
1205     \subsection console_args_stl STL container support
1206
1207     The %console library contains support for the STL container types: \c std::vector, \c
1208     std::list, \c std::set, \c std::multiset, \c std::map and \c std::multimap.
1209
1210     All container types are parsed as parenthesized list of elements. Each element is parsed as
1211     defined for the element type:
1212
1213     \c vector, \c list or \c set of integers:
1214     <pre>
1215     (1 2 3)
1216     </pre>
1217
1218     \c vector, \c list or \c set of strings:
1219     <pre>
1220     ("String 1" "String 2" "String 3")
1221     </pre>
1222
1223     \c vector, \c list or \c set of <tt>pair<int,string></tt>:
1224     <pre>
1225     ((1 "String 1") (2 "String 2") (3 "String 3"))
1226     </pre>
1227
1228     Empty collection:
1229     <pre>
1230     ()
1231     </pre>
1232
1233     Collection's with only one element may skip the parenthesis <em>if and only if</em> the element
1234     type does not need additional parenthesis
1235
1236     A \c vector, \c list or \c set of integer with one element may be written with or without
1237     parenthesis:
1238     <pre>
1239     (1)
1240     1
1241     </pre>
1242
1243     \e but a single element \c vector, \c list or \c set of <tt>pair<int,string></tt> may \e only be
1244     written:
1245     <pre>
1246     ((1 "String 1"))
1247     </pre>
1248
1249     In mapping containers, the key and value are separated by \c =:
1250     <pre>
1251     (foo=1 bar=2 "foo bar"=3)
1252     </pre>
1253
1254
1255     \subsection console_args_bool Boolean arguments and return values
1256
1257     The console library by default formats boolean values using the strings \c true and \c false for
1258     their representation. When parsing a boolean value, most sensible representations will be
1259     accepted:
1260
1261     <table class="senf">
1262     <tr><td>\c true</td>    <td>\c false</td>    <td>\ref senf::console::formatTrueFalse</td></tr>
1263     <tr><td>\c on</td>      <td>\c off</td>      <td>\ref senf::console::formatOnOff</td></tr>
1264     <tr><td>\c enabled</td> <td>\c disabled</td> <td>\ref senf::console::formatEnabledDisabled</td></tr>
1265     <tr><td>\c yes</td>     <td>\c no</td>       <td>\ref senf::console::formatYesNo</td></tr>
1266     <tr><td><em>non-zero integer</em></td><td>\c 0</td><td>\ref senf::console::formatOneZero</td></tr>
1267     </table>
1268
1269     The boolean parser will accept these values in any (mixed) case and accepts any unique initial
1270     substring (e.g. \c Y / \c N).
1271
1272     The last column lists explicit formatters which can be set to customize the return value
1273     formatting of a registered overload accordingly.
1274
1275
1276     \subsection console_args_enum Registering enum types
1277
1278     Enum types are a special case, since it is not possible, to find a string representation for the
1279     enumerator values automatically. Therefore, enum types need to be registered manually.
1280     \code
1281     namespace fty = senf::console::factory;
1282
1283     enum MyEnum { Sit, Run, Jump };
1284     SENF_CONSOLE_REGISTER_ENUM( MyEnum, (Sit)(Run)(Jump) );
1285
1286     MyEnum fun4(MyEnum v) { return v }
1287
1288     senf::console::root().add("test9", fty::Command(&fun4));
1289     \endcode
1290
1291     After an enum type is registered, it can be used like any other type for arguments or
1292     return-values:
1293
1294     \htmlonly
1295     <pre>
1296     server:/$ test9 Sit
1297     Sit
1298     server:/$ test9 Crawl
1299     argument syntax error: invalid enum value
1300     server:/$ help test9
1301     Usage:
1302         test9 arg11:MyEnum
1303     server:/$
1304     </pre>
1305     \endhtmlonly
1306
1307     \ref SENF_CONSOLE_REGISTER_ENUM() can only be used, to register enums at namespace scope. To
1308     register enums defined within some class, use \ref SENF_CONSOLE_REGISTER_ENUM_MEMBER()
1309
1310     \code
1311     namespace fty = senf::console::factory;
1312
1313     class Test3
1314     {
1315     public:
1316         enum Color { Red, Green, Blue };
1317
1318         senf::console::ScopedDirectory<Test3> dir;
1319
1320         Test3();
1321
1322         Color mem3(Color c) { return c }
1323     };
1324     SENF_CONSOLE_REGISTER_ENUM_MEMBER( Test3, Color, (Red)(Green)(Blue) );
1325
1326     Test3::Test3() : dir(this)
1327         { dir.add("test", fty::Command(&Test3::mem3, this)); }
1328
1329     Test3 test3ob;
1330     senf::console::root().add("test3ob", test3ob.dir);
1331     \endcode
1332
1333     Using this command/type is identical
1334     \htmlonly
1335     <pre>
1336     server:/$ test3ob/test Red
1337     Red
1338     server:/$ test3ob/test White
1339     argument syntax error: invalid enum value
1340     server:/$ help test3ob/test
1341     Usage:
1342         test arg11:Color
1343     </pre>
1344     \endhtmlonly
1345
1346
1347     \subsection console_args_convert Handling argument types by conversion
1348
1349     Sometimes an argument type is best handled by just pretending it to be of some other type. The
1350     basic idea is, to provide an explicit signature with different (but compatible) types to the
1351     factory:
1352
1353     \code
1354     namespace fty = senf::console::factory;
1355
1356     int fun4(int value)
1357     {
1358         return value;
1359     }
1360
1361     senf::console::root()
1362         .add("test8", fty::Command<bool (bool)>(&fun4));
1363     \endcode
1364
1365     Here, the type signature passed to fty::Command is different from the real type signature but it
1366     is compatible, the conversion is handled automatically. Since the console library now sees the
1367     argument and return value of type \c bool, the values will be parsed and formatted as boolean
1368     values.
1369
1370
1371     \subsection console_args_special Special Console types
1372
1373     The %console library defines some special types to be used as arguments and/or return values.
1374     Some of these are wrappers around basic types which provide custom formatting. Those are used
1375     via argument type conversion (see previous section).
1376
1377     \see \ref senf_console_utilities
1378
1379
1380     \subsection console_args_custom Extending the library to support additional types
1381
1382     To support or customize parsing/formatting of other types, they need to be registered. In it's
1383     simplest case, this works, by just providing an appropriate overload for
1384     senf_console_parse_argument() and senf_console_format_value():
1385     \code
1386     struct Coordinate
1387     {
1388         Coordinate() : x(0), y(0) {}
1389         Coordinate(int x_, int y_) : x(x_), y(y_) {}
1390
1391         int x, y;
1392     }
1393
1394     void senf_console_parse_argument(senf::console::ParseCommandInfo::TokensRange const & tokens,
1395                                      Coordinate & out)
1396     {
1397         senf::console::CheckedArgumentIteratorWrapper arg (tokens);
1398         senf::console::parse( *(arg++), out.x );
1399         senf::console::parse( *(arg++), out.y );
1400     }
1401
1402     void senf_console_format_value(Coordinate const & value, std::ostream & os)
1403     {
1404         os << '(' << value.x << ' ' << value.y << ')';
1405     }
1406     \endcode
1407
1408     The parser will accept an argument with two tokens which are each forwarded to the integer
1409     parser. The senf::console::CheckedArgumentIteratorWrapper ensures two things: That all input
1410     tokens are parsed and no extra trailing tokens are left unparsed and it checks, that all
1411     referenced tokens really exist.
1412
1413     The formatter writes out the value as a parenthesized pair.
1414
1415     \code
1416     namespace fty = senf::console::factory;
1417
1418     Coordinate fun5(Coordinate const & p) { return Coordinate(2*p.x, 2*p.y) }
1419
1420     namespace kw = senf::console::kw;
1421
1422     senf::console::root()
1423         .add("test10", fty::Command(&fun5))
1424         .arg("x","coordinate to double",
1425              kw::default_value = Coordinate())
1426     \endcode
1427     We can now call \c test10 with a coordinate argument:
1428     \htmlonly
1429     <pre>
1430     server:/$ test10 (2 7)
1431     (4 14)
1432     server:/$ help test10
1433     Usage:
1434         test10 [x:Coordinate]
1435
1436     With:
1437         x         Coordinate to double
1438             default: (0 0)
1439     server:/$
1440     </pre>
1441     \endhtmlonly
1442
1443     If you want to customize the formatting of default values differently from the formating of
1444     return-values or if you want to change the displayed name of a type, you will need to specialize
1445     the senf::console::ArgumentTraits class instead of implementing
1446     senf_console_parse_argument(). See senf::console::ArgumentTraits and
1447     senf::console::ReturnValueTraits for more.
1448  */
1449
1450 \f
1451 // Local Variables:
1452 // mode: c++
1453 // fill-column: 100
1454 // comment-column: 40
1455 // c-file-style: "senf"
1456 // indent-tabs-mode: nil
1457 // ispell-local-dictionary: "american"
1458 // compile-command: "scons -u test"
1459 // mode: auto-fill
1460 // End: