Console: Add console logging documentation
[senf.git] / Console / Server.cc
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 /** \file
24     \brief Server non-inline non-template implementation */
25
26 #include "Server.hh"
27 #include "Server.ih"
28
29 // Custom includes
30 #include <unistd.h>
31 #include <iostream>
32 #include <boost/algorithm/string/trim.hpp>
33 #include <boost/iostreams/device/file_descriptor.hpp>
34 #include <boost/iostreams/stream.hpp>
35 #include <boost/bind.hpp>
36 #include "../Utils/senfassert.hh"
37 #include "../Utils/membind.hh"
38 #include "../Utils/Logger/SenfLog.hh"
39 #include "Readline.hh"
40
41 //#include "Server.mpp"
42 #define prefix_
43 ///////////////////////////////cc.p////////////////////////////////////////
44
45 ///////////////////////////////////////////////////////////////////////////
46 // senf::console::detail::NonBlockingSocketSink
47
48 prefix_ std::streamsize senf::console::detail::NonblockingSocketSink::write(const char * s,
49                                                                             std::streamsize n)
50 {
51     try {
52         if (client_.handle().writeable()) {
53             std::string data (s, n);
54             client_.translate(data);
55             client_.handle().write( data );
56         }
57     }
58     catch (SystemException & ex) {
59         ;
60     }
61     return n;
62 }
63
64 ///////////////////////////////////////////////////////////////////////////
65 // senf::console::Server
66
67 prefix_ senf::console::Server &
68 senf::console::Server::start(senf::INet4SocketAddress const & address)
69 {
70     senf::TCPv4ServerSocketHandle handle (address);
71     Server & server (senf::console::Server::start(handle));
72     SENF_LOG((Server::SENFLogArea)(log::NOTICE)( 
73                  "Console server started at " << address ));
74     return server;
75 }
76
77 prefix_ senf::console::Server &
78 senf::console::Server::start(senf::INet6SocketAddress const & address)
79 {
80     senf::TCPv6ServerSocketHandle handle (address);
81     Server & server (senf::console::Server::start(handle));
82     SENF_LOG((Server::SENFLogArea)(log::NOTICE)( 
83                  "Console server started at " << address ));
84     return server;
85 }
86
87 prefix_ boost::scoped_ptr<senf::console::Server> & senf::console::Server::instancePtr()
88 {
89     // We cannot make 'instance' a global or class-static variable, since it will then be destructed
90     // at an unknown time which may fail if the scheduler or the file-handle pool allocators have
91     // already been destructed.
92     static boost::scoped_ptr<senf::console::Server> instance;
93     return instance;
94 }
95
96 prefix_ senf::console::Server & senf::console::Server::start(ServerHandle handle)
97 {
98     // Uah .... ensure the scheduler is created before the instance pointer so it get's destructed
99     // AFTER it.
100     (void) senf::Scheduler::instance();
101     SENF_ASSERT( ! instancePtr() );
102     instancePtr().reset(new Server(handle));
103     return * instancePtr();
104 }
105
106 prefix_ senf::console::Server::Server(ServerHandle handle)
107     : handle_ (handle)
108 {
109     Scheduler::instance().add( handle_, senf::membind(&Server::newClient, this) );
110 }
111
112 prefix_ senf::console::Server::~Server()
113 {
114     Scheduler::instance().remove(handle_);
115 }
116
117 prefix_ void senf::console::Server::newClient(Scheduler::EventId event)
118 {
119     ServerHandle::ClientSocketHandle client (handle_.accept());
120     boost::intrusive_ptr<Client> p (new Client(*this, client, name_));
121     clients_.insert( p );
122     SENF_LOG(( "Registered new client " << p.get() ));
123 }
124
125 prefix_ void senf::console::Server::removeClient(Client & client)
126 {
127     SENF_LOG(( "Disposing client " << & client ));
128     // THIS DELETES THE CLIENT INSTANCE !!
129     clients_.erase(boost::intrusive_ptr<Client>(&client));
130 }
131
132 ///////////////////////////////////////////////////////////////////////////
133 // senf::console::detail::DumbClientReader
134
135 prefix_ senf::console::detail::DumbClientReader::DumbClientReader(Client & client)
136     : ClientReader(client), promptLen_ (0), promptActive_ (false)
137 {
138     showPrompt();
139     ReadHelper<ClientHandle>::dispatch( handle(), 16384u, ReadUntil("\n"),
140                                         senf::membind(&DumbClientReader::clientData, this) );
141 }
142
143 prefix_ void
144 senf::console::detail::DumbClientReader::clientData(senf::ReadHelper<ClientHandle>::ptr helper)
145 {
146     if (helper->error() || handle().eof()) {
147         // THIS COMMITS SUICIDE. THE INSTANCE IS GONE AFTER stopClient RETURNS
148         stopClient();
149         return;
150     }
151     
152     promptLen_ = 0;
153     promptActive_ = false;
154
155     std::string data (tail_ + helper->data());
156     tail_ = helper->tail();
157     boost::trim(data);                  // Gets rid of superfluous  \r or \n characters
158     handleInput(data);
159
160     showPrompt();
161     ReadHelper<ClientHandle>::dispatch( handle(), 16384u, ReadUntil("\n"),
162                                         senf::membind(&DumbClientReader::clientData, this) );
163
164 }
165
166 prefix_ void senf::console::detail::DumbClientReader::showPrompt()
167 {
168     std::string prompt (promptString());
169
170     stream() << std::flush;
171     handle().write(prompt);
172     promptLen_ = prompt.size();
173     promptActive_ = true;
174 }
175
176 prefix_ void senf::console::detail::DumbClientReader::v_disablePrompt()
177 {
178     if (promptActive_ && promptLen_ > 0) {
179         stream() << '\r' << std::string(' ', promptLen_) << '\r';
180         promptLen_ = 0;
181     }
182 }
183
184 prefix_ void senf::console::detail::DumbClientReader::v_enablePrompt()
185 {
186     if (promptActive_ && ! promptLen_)
187         showPrompt();
188 }
189
190 prefix_ void senf::console::detail::DumbClientReader::v_translate(std::string & data)
191 {}
192
193 ///////////////////////////////////////////////////////////////////////////
194 // senf::console::Client
195
196 prefix_ senf::console::Client::Client(Server & server, ClientHandle handle,
197                                       std::string const & name)
198     : out_t(boost::ref(*this)), senf::log::IOStreamTarget(out_t::member), server_ (server),
199       handle_ (handle), name_ (name), reader_ (new detail::SafeReadlineClientReader (*this))
200 {
201     executor_.autocd(true).autocomplete(true);
202     handle_.facet<senf::TCPSocketProtocol>().nodelay();
203     // route< senf::SenfLog, senf::log::NOTICE >();
204 }
205
206 prefix_ void senf::console::Client::translate(std::string & data)
207 {
208     reader_->translate(data);
209 }
210
211 prefix_ void senf::console::Client::handleInput(std::string data)
212 {
213     if (data.empty())
214         data = lastCommand_;
215     else
216         lastCommand_ = data;
217
218     try {
219         if (! parser_.parse(data, boost::bind<void>( boost::ref(executor_),
220                                                      boost::ref(stream()),
221                                                      _1 )) )
222             stream() << "syntax error" << std::endl;
223     }
224     catch (Executor::ExitException &) {
225         // This generates an EOF condition on the Handle. This EOF condition is expected
226         // to be handled gracefully by the ClientReader. We cannot call stop() here, since we
227         // are called from the client reader callback and that will continue executing even if we
228         // call stop here ...
229         handle_.facet<senf::TCPSocketProtocol>().shutdown(senf::TCPSocketProtocol::ShutRD);
230         return;
231     }
232     catch (std::exception & ex) {
233         stream() << ex.what() << std::endl;
234     }
235     catch (...) {
236         stream() << "unidentified error (unknown exception thrown)" << std::endl;
237     }
238 }
239
240 prefix_ void senf::console::Client::v_write(boost::posix_time::ptime timestamp,
241                                             std::string const & stream,
242                                             std::string const & area, unsigned level,
243                                             std::string const & message)
244 {
245     reader_->disablePrompt();
246     IOStreamTarget::v_write(timestamp, stream, area, level, message);
247     out_t::member << std::flush;
248     reader_->enablePrompt();
249 }
250
251 ///////////////////////////////cc.e////////////////////////////////////////
252 #undef prefix_
253 //#include "Server.mpp"
254
255 \f
256 // Local Variables:
257 // mode: c++
258 // fill-column: 100
259 // comment-column: 40
260 // c-file-style: "senf"
261 // indent-tabs-mode: nil
262 // ispell-local-dictionary: "american"
263 // compile-command: "scons -u test"
264 // End: