Threaded/Listener.pm untested

filter: Statementstmt 0.0% 0 / 133 Branchbran 0.0% 0 / 40 Conditioncond 0.0% 0 / 9 MC/DCmcdc 0.0% 0 / 6 Subroutinesub 0.0% 0 / 25 Podpod 0.0% 0 / 12 totaltotal 0.0% 0 / 225 CC 21 SCAR 36.7
CC
21
Cov
0%
new
132.0
close
30.0
run
20.0
CRAP 39.3
1 =pod
2  
3 =begin classdoc
4  
5 Web network listener: accepts network connections, and routes
6 them to WebClient objects to handle the web requests. Creates and maintains
7 a pool of WebClient objects.
8 <p>
9 A threads::shared array is shared between this object and the WebClient
10 objects so that WebClients can return themselves to the free list quickly;
11 a future release may convert the freelist to a full object, in the event
12 the allocate/free methods require a more complex process.
13 <p>
14 Copyright&copy 2006-2008, Dean Arnold, Presicient Corp., USA<br>
15 All rights reserved.
16 <p>
17 Licensed under the Academic Free License version 3.0, as specified in the
18 at <a href='http://www.opensource.org/licenses/afl-3.0.php'>OpenSource.org</a>.
19  
20 @author D. Arnold
21 @since 2006-08-21
22 @self $self
23  
24  
25  
26 =end classdoc
27  
28 =cut
29 package HTTP::Daemon::Threaded::Listener;
30  
31 use Socket;
32 use Sys::Hostname;
33 use threads;
34 use threads::shared;
35 use HTTP::Daemon::Threaded::Socket;
36 use HTTP::Daemon::Threaded::WebClient;
37 use HTTP::Daemon::Threaded::IOSelector;
38 use HTTP::Daemon::Threaded::Logable;
39 use Thread::Apartment::MuxServer;
40  
41 use base qw(HTTP::Daemon::Threaded::Logable Thread::Apartment::MuxServer);
42  
43 use strict;
44 use warnings;
45  
46 our $VERSION = '0.91';
47  
48 use constant HTTPD_INTERVAL => 0.5;
49  
50 =pod
51  
52 =begin classdoc
53  
54 Constructor. Opens the HTTPD listener socket and creates
55 its selector. Creates a pool of HTTP::Daemon::Threaded::WebClient
56 apartment threaded objects, based on the specified MaxClient
57 parameter.
58 <p>
59 Note that the following parameters are recognized by
60 HTTP::Daemon::Threaded and/or HTTP::Daemon::Threaded::WebClient, but
61 applications may supply additional parameter key/value pairs
62 which will be provided to the constructor for any specified
63 HTTP::Daemon::Threaded::ContentParams class.
64  
65 @param AptTimeout <i>(optional)</i> Thread::Apartment proxy return timeout
66 @param Port <i>(optional)</i> TCP listen port; default 80.
67 @param MaxClients <i>(optional)</i> max number of client handlers to spawn;
68 default 5
69 @param LogLevel <i>(optional)</i> logging level; 1 => errors only; 2 => errors and warnings only; 3 => errors, warnings,
70 and info messages; default 1
71 @param EventLogger <i>(optional)</i> Instance of a HTTP::Daemon::Threaded::Logger to receive
72 event notifications (except for web requests)
73 @param WebLogger <i>(optional)</i> Instance of a HTTP::Daemon::Threaded::Logger to receive
74 web request notifications
75 @param Handlers <i>(required)</i> URI handler map; arrayref mapping URI regex's to handler package names
76 @param UserAuth <i>(optional)</i> instance of a subclass of HTTP::Daemon::Threaded::Auth <i>(not yet supported)</i>
77 @param SessionCache <i>(optional)</i> instance of a subclass of HTTP::Daemon::Threaded::SessionCache
78 to be used to create/manage sessions
79 @param InactivityTimer <i>(optional)</i> number of seconds a WebClient waits before disconnecting
80 an idle connection; default 10 minutes
81 @param ContentParams <i>(optional)</i> name of concrete implementation of HTTP::Daemon::Threaded::ContentParams
82 @param DocRoot <i>(optional)</i> root directory for default file based content handler
83 @param ProductTokens <i>(optional)</i> product token string to return to client; default
84 is 'HTTP::Daemon::Threaded/<version>'
85 @param MediaTypes <i>(optional)</i> hashref mapping 'Content-Type' specifications to
86 file qualifier strings. Values may be either a single string literal, or
87 @param SelectInterval <i>(optional)</i> seconds to wait in select()'s on sockets. May be fractional; default 0.5
88  
89 @return HTTP::Daemon::Threaded object
90  
91  
92 =end classdoc
93  
94 =cut
95 sub new {
96 my ($class, %args) = @_;
97  
98 $args{SelectInterval} = HTTPD_INTERVAL
99 unless $args{SelectInterval};
100  
101 my $self = { %args, _status => 'starting' };
102 bless $self, $class;
103 #
104 # setup our proxy version
105 #
106 $self->set_client(delete $self->{AptTAC});
107 #
108 # open our listener
109 #
110 $self->{Port} = $args{Port} = 80
111 unless exists $args{Port};
112 $self->{_fd} = HTTP::Daemon::Threaded::Socket->new(
113 LocalPort => $args{Port},
114 Proto => 'tcp',
115 Listen => 10);
116 $self->logError("Cannot get listener for Web Server: $!"),
117 $@ = "Cannot get listener for Web Server: $!",
118 return undef
119 unless $self->{_fd};
120 #
121 # register ourselves with it
122 # (for single threaded mode)
123 #
124 $self->{_fd}->setContext($self);
125  
126 $self->logInfo("Created listener\n");
127 #
128 # create a selector
129 #
130  
131 $self->{_sktsel} = HTTP::Daemon::Threaded::IOSelector->new($args{SelectInterval});
132 $self->{_sktsel}->addNoWrite($self->{_fd});
133 #
134 # create request handler pool
135 #
136 my @avail_clients : shared = ();
137 $self->{_avail_clients} = \@avail_clients;
138 my @webclients = (undef);
139 $self->{_clients} = \@webclients;
140 #
141 # update the args
142 #
143 $self->{LogLevel} = $args{LogLevel} = 1
144 unless exists $args{LogLevel};
145 delete $args{MaxClients};
146 #
147 # normalize docroot if needed
148 #
149 $args{DocRoot} .= '/'
150 if (defined $args{DocRoot}) && (substr($args{DocRoot}, -1, 1) ne '/');
151  
152 my $url = "http://";
153 my $addr = $self->{_fd}->sockaddr;
154 $url .= (!$addr || $addr eq INADDR_ANY) ?
155 lc Sys::Hostname::hostname() :
156 (gethostbyaddr($addr, AF_INET) || inet_ntoa($addr));
157 my $port = $self->{_fd}->sockport;
158 $url .= ":$args{Port}"
159 unless ($args{Port} == 80);
160 $args{URL} = $url . '/';
161 delete $args{Port};
162  
163 $args{ProductTokens} = "HTTP::Daemon::Threaded/$VERSION"
164 unless $args{ProductTokens};
165  
166 $args{HTTPD} = $self->get_client();
167 $args{AptClass} = 'HTTP::Daemon::Threaded::WebClient';
168 $args{FreeList} = \@avail_clients;
169 #
170 # note that this inactivity timer may be overridden by
171 # any Session object's timeout
172 #
173 $self->{InactivityTimer} = $args{InactivityTimer} = 10 * 60
174 unless exists $args{InactivityTimer};
175  
176 foreach (1..$self->{MaxClients}) {
177 $args{ID} = $_;
178 push @webclients, Thread::Apartment->new(%args);
179  
180 pop @webclients,
181 $@ = 'Unable to create a WebClient instance.',
182 $self->logWarning('Unable to create a WebClient instance.'),
183 return undef
184 unless $webclients[-1];
185 push @{$self->{_avail_clients}}, $_;
186 $self->logInfo("Created WebClient\n");
187 }
188  
189 $self->{_status} = 'running';
190 return $self;
191 }
192  
193 =pod
194  
195 =begin classdoc
196  
197 Thread::Apartment::MuxServer::run() implementation.
198  
199 @return 1
200  
201  
202 =end classdoc
203  
204 =cut
205 sub run {
206 my $self = shift;
207  
208 while (1) {
209 if ($self->{_sktsel}) {
210 #
211 # HTTP::Daemon::Threaded::IOSelector does the heavy lifting
212 #
213 my $elapsed = $self->{_sktsel}->select();
214 print STDERR "Long select!!! $elapsed\n"
215 if ($elapsed >= 1);
216 }
217 else {
218 select(undef, undef, undef, 0.1);
219 }
220  
221 return undef
222 unless $self->handle_method_requests();
223 #
224 # shutdown may remove our selector
225 #
226 # last unless $self->{_sktsel};
227 }
228  
229 return undef;
230 }
231  
232 sub status {
233 #print "Returning status ", $_[0]->{_status}, "\n";
234 return $_[0]->{_status};
235 }
236  
237 =pod
238  
239 =begin classdoc
240  
241 Overrides Thread::Apartment::Server::get_simplex_methods()
242  
243 @return hashref of simplex method names
244  
245  
246 =end classdoc
247  
248 =cut
249 sub get_simplex_methods {
250 return {
251 close => 1,
252 setLogLevel => 1,
253 setListenInterval => 1,
254 };
255 }
256  
257 =pod
258  
259 =begin classdoc
260  
261 Closes the listen socket and stops all the WebClient
262 threads.
263  
264 @simplex
265 @return 1
266  
267  
268 =end classdoc
269  
270 =cut
271 sub close {
272 my $self = shift;
273  
274 $self->logInfo("shutdown requested\n");
275  
276 delete $self->{_sktsel};
277  
278 $self->{_fd}->close(),
279 delete $self->{_fd}
280 if $self->{_fd};
281 #
282 # queue stops first, then join
283 #
284 if ($self->{_clients}) {
285 map { $_->stop() if $_; } @{$self->{_clients}};
286 map { $_->join() if $_; } @{$self->{_clients}};
287 }
288 $self->{_status} = 'stopped';
289 return 1;
290 }
291  
292 =pod
293  
294 =begin classdoc
295  
296 Return the listener socket.
297  
298 @return HTTP::Daemon::Threaded::Socket listen socket object
299  
300  
301 =end classdoc
302  
303 =cut
304 sub getSocket { return shift->{_fd}; }
305 =pod
306  
307 =begin classdoc
308  
309 Handle listen socket events. Accepts a new connection request,
310 allocates a WebClient to handle it, and passes the new socket
311 to the WebClient
312  
313 @return 1
314  
315  
316 =end classdoc
317  
318 =cut
319 sub handleSocketEvent {
320 my $self = shift;
321  
322 $self->logInfo('Got web connection request.');
323 #
324 # client must accept(): must make this duplex, so we don't keep
325 # pinging the listener
326 #
327 my $skt = $self->{_fd}->accept();
328 return 1 unless $skt;
329  
330 my $client = $self->_get_client();
331 $skt->close(),
332 return 1
333 unless $client;
334 #
335 # this waits for client...
336 #
337 $client->acceptConnection($skt->fileno());
338  
339 return 1;
340 }
341 #
342 # do we need to close the file here ?
343 # maybe we should just let the clients accept() ?
344 #
345 =pod
346  
347 =begin classdoc
348  
349 Handle socket errors.
350  
351 @deprecated
352 @return undef
353  
354  
355 =end classdoc
356  
357 =cut
358 sub handleSocketError {
359 my $self = shift;
360  
361 $self->logWarn("Problem with web listener.");
362 warn "Problem with web listener, exitting...\n";
363 return undef;
364 }
365  
366 sub _get_client {
367 my $self = shift;
368 my $client;
369 {
370 lock(@{$self->{_avail_clients}});
371 $client = pop @{$self->{_avail_clients}};
372 }
373 return $client ? $self->{_clients}[$client] : undef;
374 }
375  
376 =pod
377  
378 =begin classdoc
379  
380 Set log level. Called from WebClient when loglevel
381 update is requested.
382  
383 @simplex
384 @param $level new log level
385  
386 @return 1
387  
388  
389 =end classdoc
390  
391 =cut
392 sub setLogLevel {
393 my ($self, $level) = @_;
394  
395 $_->setLogLevel($level)
396 foreach (@{$self->{_clients}});
397 $self->{LogLevel} = $level;
398 return 1;
399 }
400 =pod
401  
402 =begin classdoc
403  
404 Set IO::Select() interval. Called when
405 HTTP::Daemon::Threaded select interval is updated.
406  
407 @simplex
408 @param $interval new interval; fractional number of seconds
409  
410 @return 1
411  
412  
413 =end classdoc
414  
415 =cut
416 sub setListenInterval {
417 $_[0]->{_sktsel}->setTimeout($_[1]);
418 }
419 =pod
420  
421 =begin classdoc
422  
423 Get IO::Select() interval. Called when HTTP::Daemon::Threaded
424 config info is requested.
425  
426 @return current listener interval
427  
428  
429 =end classdoc
430  
431 =cut
432 sub getListenInterval {
433 return $_[0]->{_sktsel}->getTimeout();
434 }
435  
436 1;
437