blib/lib/Yote/Server.pm untested

filter: Statementstmt 0.0% 0 / 573 Branchbran 0.0% 0 / 162 Conditioncond 0.0% 0 / 97 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 67 Podpod 0.0% 0 / 42 totaltotal 0.0% 0 / 941 CC 82 SCAR 46.3
CC
82
Cov
0%
_process_request
552.0
_xform_in
72.0
_create_listener_socket
42.0
CRAP 102.0
1 package Yote::Server;
2  
3 use strict;
4 use warnings;
5  
6 no warnings 'uninitialized';
7 no warnings 'numeric';
8  
9 use Lock::Server;
10 use Yote;
11  
12 use JSON;
13 use Time::HiRes qw(time);
14 use URI::Escape;
15  
16 use vars qw($VERSION);
17  
18 $VERSION = '1.03';
19  
20 my $DEBUG = 0;
21  
22 sub new {
23 my( $pkg, $args ) = @_;
24 my $class = ref( $pkg ) || $pkg;
25 bless {
26 args => $args || {},
27  
28 # the following are the args currently used
29 yote_root_dir => $args->{yote_root_dir},
30 yote_host => $args->{yote_host} || '127.0.0.1',
31 yote_port => $args->{yote_port} || 8881,
32 pids => [],
33 _locker => new Lock::Server( {
34 port => $args->{lock_port},
35 host => $args->{lock_host} || '127.0.0.1',
36 lock_attempt_timeout => $args->{lock_attempt_timeout},
37 lock_timeout => $args->{lock_timeout},
38 } ),
39 STORE => Yote::ServerStore->_new( { root => $args->{yote_root_dir} } ),
40 }, $class;
41 } #new
42  
43 sub start {
44 my $self = shift;
45  
46 $self->{STORE}{_locker} = $self->{_locker};
47 $self->{_locker}->start;
48  
49 # $self->{SERVER_ROOT} = $self->{STORE}->fetch_server_root;
50  
51 # use Devel::SimpleProfiler;Devel::SimpleProfiler::start;
52 # child process
53  
54 my $listener_socket = $self->_create_listener_socket;
55 die "Unable to open socket " unless $listener_socket;
56  
57 if( my $pid = fork ) {
58 # parent
59 $self->{server_pid} = $pid;
60 return $pid;
61 }
62  
63 # in child
64 $0 = "YoteServer process";
65 $self->_run_loop( $listener_socket );
66  
67 } #start
68  
69 sub stop {
70 my $self = shift;
71 if( my $pid = $self->{server_pid} ) {
72 $self->{error} = "Sending INT signal to lock server of pid '$pid'";
73 kill 'INT', $pid;
74 return 1;
75 }
76 $self->{error} = "No Yote server running";
77 return 0;
78 }
79  
80  
81  
82 =head2 run
83  
84 Runs the lock server.
85  
86 =cut
87 sub run {
88 my $self = shift;
89 my $listener_socket = $self->_create_listener_socket;
90 die "Unable to open socket " unless $listener_socket;
91 $self->_run_loop( $listener_socket );
92 }
93  
94 sub _create_listener_socket {
95 my $self = shift;
96  
97 unless( $self->{STORE}{_locker} ) {
98 $self->{STORE}{_locker} = $self->{_locker};
99 $self->{_locker}->start;
100 }
101  
102 my $listener_socket;
103 my $count = 0;
104 while( ! $listener_socket && ++$count < 10 ) {
105 $listener_socket = new IO::Socket::INET(
106 Listen => 10,
107 LocalAddr => "$self->{yote_host}:$self->{yote_port}",
108 );
109 last if $listener_socket;
110
111 print STDERR "Unable to open the yote socket. Retry $count of 10\n";
112 sleep 5 * $count;
113 }
114 unless( $listener_socket ) {
115 $self->{error} = "Unable to open yote socket on port '$self->{yote_port}' : $! $@\n";
116 $self->{_locker}->stop;
117 _log( "unable to start yote server : $@ $!." );
118 return 0;
119 }
120 print STDERR "Starting yote server\n";
121  
122 unless( $self->{yote_root_dir} ) {
123 eval('use Yote::ConfigData');
124 $self->{yote_root_dir} = $@ ? '/opt/yote' : Yote::ConfigData->config( 'yote_root' );
125 undef $@;
126 }
127  
128 # if this is cancelled, make sure all child procs are killed too
129 $SIG{INT} = sub {
130 _log( "got INT signal. Shutting down." );
131 $listener_socket && $listener_socket->close;
132 for my $pid ( @{ $self->{_pids} } ) {
133 kill 'HUP', $pid;
134 }
135 $self->{_locker}->stop;
136 exit;
137 };
138  
139 $SIG{CHLD} = 'IGNORE';
140  
141 return $listener_socket;
142 } #_create_listener_socket
143  
144 sub _run_loop {
145 my( $self, $listener_socket ) = @_;
146 while( my $connection = $listener_socket->accept ) {
147 $self->_process_request( $connection );
148 }
149 }
150  
151 sub _log {
152 my $msg = shift;
153 print STDERR "Yote::Server : $msg\n" if $DEBUG;
154 }
155  
156 sub __transform_params {
157 #
158 # Recursively transforms incoming parameters into values, yote objects, or non yote containers.
159 # This checks to make sure that the parameters are allowed by the given token.
160 # Throws execptions if the parametsr are not allowed, or if a reference that is not a hash or array
161 # is encountered.
162 #
163 my( $self, $param, $token, $server_root ) = @_;
164  
165 if( ref( $param ) eq 'HASH' ) {
166 return { map { $_ => $self->__transform_params($param->{$_}, $token, $server_root) } keys %$param };
167 }
168 elsif( ref( $param ) eq 'ARRAY' ) {
169 return [ map { $self->__transform_params($_, $token, $server_root) } @$param ];
170 } elsif( ref( $param ) ) {
171 die "Transforming Params: got weird ref '" . ref( $param ) . "'";
172 }
173 if( index( $param, 'v' ) == 0 ) {
174 if( $server_root->_getMay( $param, $token ) ) {
175 return $self->{STORE}->_xform_out( $param );
176 }
177 die( "Bad Req Param, server says no : $param" );
178 }
179 return $self->{STORE}->fetch($param); #oops!
180 } #__transform_params
181  
182 sub _find_ids_in_data {
183 my $data = shift;
184 my $r = ref( $data );
185 if( $r eq 'ARRAY' ) {
186 return grep { $_ && index($_,'v')!=0 } map { ref( $_ ) ? _find_ids_in_data($_) : $_ } @$data;
187 }
188 elsif( $r eq 'HASH' ) {
189 return grep { $_ && index($_,'v')!=0} map { ref( $_ ) ? _find_ids_in_data($_) : $_ } values %$data;
190 }
191 elsif( $r ) {
192 die "_find_ids_in_data encountered a non ARRAY or HASH reference";
193 }
194 } #_find_ids_in_data
195  
196 sub _process_request {
197 #
198 # Reads incomming request from the socket, parses it, performs it and
199 # prints the result back to the socket.
200 #
201 my( $self, $sock ) = @_;
202  
203  
204 if ( my $pid = fork ) {
205 # parent
206 push @{$self->{_pids}},$pid;
207 } else {
208 # use Devel::SimpleProfiler;Devel::SimpleProfiler::start;
209 my( $self, $sock ) = @_;
210 #child
211 $0 = "YoteServer processing request";
212 $SIG{INT} = sub {
213 _log( " process $$ got INT signal. Shutting down." );
214 $sock->close;
215 exit;
216 };
217
218
219 my $req = <$sock>;
220 $ENV{REMOTE_HOST} = $sock->peerhost;
221 my %headers;
222 while( my $hdr = <$sock> ) {
223 $hdr =~ s/\s*$//s;
224 last if $hdr !~ /[a-zA-Z]/;
225 my( $key, $val ) = ( $hdr =~ /^([^:]+):(.*)/ );
226 $headers{$key} = $val;
227 }
228 my $store = $self->{STORE};
229  
230 _log( "\n--> : $req" );
231  
232 #
233 # read certain length from socket ( as many bytes as content length )
234 #
235 my $content_length = $headers{'Content-Length'};
236 my $data;
237 if ( $content_length > 0 && ! eof $sock) {
238 read $sock, $data, $content_length;
239 }
240 my( $verb, $path ) = split( /\s+/, $req );
241  
242 # escape for serving up web pages
243 # the thought is that this should be able to be a stand alone webserver
244 # for testing and to provide the javascript
245 if ( $path =~ m!/__/! ) {
246 # TODO - make sure install script makes the directories properly
247 my $filename = "$self->{yote_root_dir}/html/" . substr( $path, 4 );
248 if ( -e $filename ) {
249 _log( "'$filename' exists" );
250 my @stat = stat $filename;
251  
252 my @headers = (
253 'Content-Type: text/html; charset=utf-8',
254 'Server: Yote',
255 "Content-Length: $stat[7]",
256 );
257  
258  
259 open( IN, "<$filename" );
260  
261 $sock->print( "HTTP/1.1 200 OK\n" . join ("\n", @headers). "\n\n" );
262  
263 while ( $data = <IN> ) {
264 $sock->print( $data );
265 }
266 close IN;
267 } else {
268 _log( "404 file '$filename' not found" );
269 $sock->print( "HTTP/1.1 404 FILE NOT FOUND\n\n" );
270 }
271 $sock->close;
272 exit;
273 }
274
275  
276 # data has the input parmas in JSON format.
277 # GET /obj/action/params
278 # POST /obj/action (params in POST data)
279  
280 # root is /_/
281 my( $obj_id, $token, $action, $params );
282  
283 if ( $verb eq 'GET' ) {
284 ( $obj_id, $token, $action, my @params ) = split( '/', substr( $path, 1 ) );
285  
286 $params = [ map { URI::Escape::uri_unescape($_) } @params ];
287
288 } elsif ( $verb eq 'POST' ) {
289 ( $obj_id, $token, $action ) = split( '/', substr( $path, 1 ) );
290  
291 $params = $data ? from_json( $data ) : []; # this has to be checked against is valid, yes
292 }
293 _log( "\n (params)--> : ".Data::Dumper->Dump([$params]) );
294  
295 if ( substr( $action, 0, 1 ) eq '_' ) {
296 _log( "Bad action (underscore) : '$action'" );
297 $sock->print( "HTTP/1.1 400 BAD REQUEST\n\n" );
298 $sock->close;
299 exit;
300 }
301  
302 my $server_root = $self->{STORE}->fetch_server_root;
303 my $server_root_id = $server_root->{ID};
304 unless( $obj_id eq '_' ||
305 $obj_id eq $server_root_id ||
306 ( $obj_id > 0 &&
307 $server_root->_valid_token( $token, $ENV{REMOTE_HOST} ) &&
308 $server_root->_getMay( $obj_id, $token ) ) ) {
309  
310 # tried to do an action on an object it wasn't handed. do a 404
311 _log( "Bad Path : '$path'" );
312 $sock->print( "HTTP/1.1 400 BAD REQUEST\n\n" );
313 $sock->close;
314 exit;
315 }
316  
317 if ( $params && ref( $params ) ne 'ARRAY' ) {
318 _log( "Bad Req Param Not Array : $params" );
319 $sock->print( "HTTP/1.1 400 BAD REQUEST\n\n" );
320 $sock->close;
321 exit;
322 }
323  
324 # now things are getting a bit more complicated. The params passed in
325 # are always a list, but they may contain other containers that are not
326 # yote objects. So, transform the incomming parameter list and check all
327 # yote objects inside for may. Use a recursive helper function for this.
328 my $in_params;
329 eval {
330 $in_params = $self->__transform_params( $params, $token, $server_root );
331 };
332 if( $@ ) {
333 _log( $@ );
334 $sock->print( "HTTP/1.1 400 BAD REQUEST\n\n" );
335 $sock->close;
336 exit;
337 }
338  
339 my $obj = $obj_id eq '_' ? $server_root :
340 $store->fetch( $obj_id );
341 unless( $obj->can( $action ) ) {
342 _log( "Bad Req : invalid method :'$action'" );
343 $sock->print( "HTTP/1.1 400 BAD REQUEST\n\n" );
344 $sock->close;
345 exit;
346 }
347  
348 my( @res );
349 eval {
350 if ( $action eq 'fetch' && $obj == $server_root ) {
351 # fetch is a special action that can return any
352 # object in the system. It must check the token
353 # to see if that particular object is allowed/available
354 # to the caller
355 unshift( @$in_params, $token );
356 }
357 (@res) = ($obj->$action( @$in_params ));
358 if( $action eq 'init_root' ) {
359 my $token = $server_root->create_token;
360 push @res, $token;
361 }
362 };
363  
364 if ( $@ ) {
365 _log( "INTERNAL SERVER ERROR '$@'" );
366 $sock->print( "HTTP/1.1 500 INTERNAL SERVER ERROR\n\n" );
367 $sock->close;
368 exit; #end forked process
369 }
370  
371 my $out_res = $store->_xform_in( \@res, 'allow datastructures' );
372  
373  
374 my @has = _find_ids_in_data( $out_res );
375 my @mays = @has, $store->_find_ids_referenced( @has );
376  
377 my $ids_to_update;
378 if ( ( $action eq 'fetch_root' || $action eq 'init_root' ) && ( $obj_id eq '_' || $obj_id eq $server_root_id ) ) {
379 # if there is a token, make it known that the token
380 # has received server root data
381 $ids_to_update = [ $server_root_id ];
382 if ( $token > 1 ) {
383 unless( $store->_last_updated( $server_root_id ) ) {
384 $store->{OBJ_UPDATE_DB}->put_record( $server_root_id, [ Time::HiRes::time ] );
385 }
386 push @has, $server_root_id;
387 }
388 } else {
389 $ids_to_update = $server_root->_updates_needed( $token, \@has );
390 }
391
392 my( @updates, %methods );
393 for my $obj_id (@$ids_to_update) {
394 my $obj = $store->fetch( $obj_id );
395 my $ref = ref( $obj );
396  
397 my( $data );
398 if ( $ref eq 'ARRAY' ) {
399 $data = [
400 map { my $d = $store->_xform_in( $_ );
401 push @mays, $d;
402 $d }
403 @$obj ];
404 } elsif ( $ref eq 'HASH' ) {
405 $data = {
406 map { my $d = $store->_xform_in( $obj->{$_} );
407 push @mays, $d;
408 $_ => $d }
409 keys %$obj };
410 } else {
411 my $obj_data = $obj->{DATA};
412  
413 $data = {
414 map { my $d = $obj_data->{$_};
415 push @mays, $d;
416 $_ => $d }
417 grep { $_ !~ /^_/ }
418 keys %$obj_data };
419 $methods{$ref} ||= $obj->_callable_methods;
420 }
421 push @has, $obj_id;
422 my $update = {
423 id => $obj_id,
424 cls => $ref,
425 data => $data,
426 };
427 push @updates, $update;
428 } #each obj_id to update
429  
430 $server_root->_setHasAndMay( \@has, \@mays, $token );
431  
432 my $out_json = to_json( { result => $out_res,
433 updates => \@updates,
434 methods => \%methods,
435 } );
436 my @headers = (
437 'Content-Type: text/json; charset=utf-8',
438 'Server: Yote',
439 'Access-Control-Allow-Headers: accept, content-type, cookie, origin, connection, cache-control',
440 'Access-Control-Allow-Origin: *', #TODO - have this configurable
441 'Content-Length: ' . length( $out_json ),
442 );
443 _log( "<-- 200 OK ( " . join( ",", @headers ) . " ) ( $out_json )\n" );
444 $sock->print( "HTTP/1.1 200 OK\n" . join ("\n", @headers). "\n\n$out_json\n" );
445  
446 $sock->close;
447 $self->{STORE}->stow_all;
448 exit;
449 } #child
450 } #_process_request
451  
452 # ------- END Yote::Server
453  
454 package Yote::ServerStore;
455  
456 use strict;
457 use warnings;
458 no warnings 'uninitialized';
459  
460 use DB::DataStore;
461  
462 use base 'Yote::ObjStore';
463  
464 sub _new { #Yote::ServerStore
465 my( $pkg, $args ) = @_;
466 $args->{store} = "$args->{root}/DATA_STORE";
467 my $self = $pkg->SUPER::_new( $args );
468  
469 # keeps track of when any object had been last updated.
470 # use like $self->{OBJ_UPDATE_DB}->put_record( $obj_id, [ time ] );
471 # or my( $time ) = @{ $self->{OBJ_UPDATE_DB}->get_record( $obj_id ) };
472 $self->{OBJ_UPDATE_DB} = DB::DataStore::FixedStore->open( "L", "$args->{root}/OBJ_META" );
473 $self;
474 } #_new
475  
476 sub _dirty {
477 my( $self, $ref, $id ) = @_;
478 $self->SUPER::_dirty( $ref, $id );
479 $self->{OBJ_UPDATE_DB}->ensure_entry_count( $id );
480 $self->{OBJ_UPDATE_DB}->put_record( $id, [ Time::HiRes::time ] );
481 }
482  
483 sub stow_all {
484 my $self = $_[0];
485 for my $obj (values %{$self->{_DIRTY}} ) {
486 my $obj_id = $self->_get_id( $obj );
487 $self->{OBJ_UPDATE_DB}->ensure_entry_count( $obj_id );
488 $self->{OBJ_UPDATE_DB}->put_record( $obj_id, [ Time::HiRes::time ] );
489 }
490 $self->SUPER::stow_all;
491 } #stow_all
492  
493 sub _stow {
494 my( $self, $obj ) = @_;
495 $self->SUPER::_stow( $obj );
496  
497 my $obj_id = $self->_get_id( $obj );
498 $self->{OBJ_UPDATE_DB}->put_record( $obj_id, [ Time::HiRes::time ] );
499 }
500  
501 sub _last_updated {
502 my( $self, $obj_id ) = @_;
503 my( $time ) = @{ $self->{OBJ_UPDATE_DB}->get_record( $obj_id ) };
504 $time;
505 }
506  
507 sub _log {
508 Yote::Server::_log(shift);
509 }
510  
511 #
512 # Unlike the superclass version of this, this provides an arguemnt to
513 # allow non-yote datastructures to be returned. The contents of those
514 # data structures will all recursively be xformed in.
515 #
516 sub _xform_in {
517 my( $self, $val, $allow_datastructures ) = @_;
518  
519 my $r = ref $val;
520 if( $r ) {
521 if( $allow_datastructures) {
522 # check if this is a yote object
523 if( ref( $val ) eq 'ARRAY' && ! tied @$val ) {
524 return [ map { ref $_ ? $self->_xform_in( $_, $allow_datastructures ) : "v$_" } @$val ];
525 }
526 elsif( ref( $val ) eq 'HASH' && ! tied %$val ) {
527 return { map { $_ => ( ref( $val->{$_} ) ? $self->_xform_in( $val->{$_}, $allow_datastructures ) : "v$_" ) } keys %$val };
528 }
529 }
530 return $self->_get_id( $val );
531 }
532  
533 return defined $val ? "v$val" : undef;
534 } #_xform_in
535  
536  
537 sub _find_ids_referenced {
538 my( $self, @ids ) = @_;
539 my( @refd );
540 for my $obj (map { $self->_xform_out( $_ ) } @ids ) {
541 if( ref $obj eq 'ARRAY' ) {
542 push @refd, grep { index($_,'v')!=0 } map { $self->_xform_in( $_ ) } @$obj;
543 } elsif( ref $obj eq 'HASH' ) {
544 push @refd, grep { index($_,'v')!=0 } map { $self->_xform_in( $_ ) } values %$obj;
545 } else {
546 push @refd, grep { index($_,'v')!=0 } map { $self->_xform_in( $_ ) } map { $obj->{DATA}{$_} } grep { index($_,'_') != 0 } keys %{$obj->{DATA}};
547 }
548 }
549 }
550  
551 sub newobj {
552 my( $self, $data, $class ) = @_;
553 $class ||= 'Yote::ServerObj';
554 $class->_new( $self, $data );
555 } #newobj
556  
557 sub fetch_server_root {
558 my $self = shift;
559  
560 return $self->{SERVER_ROOT} if $self->{SERVER_ROOT};
561  
562 my $system_root = $self->fetch_root;
563 my $server_root = $system_root->get_server_root;
564 unless( $server_root ) {
565 $server_root = Yote::ServerRoot->_new( $self );
566 $system_root->set_server_root( $server_root );
567 $self->stow_all;
568 }
569  
570 # some setup here? accounts/webapps/etc?
571 # or make it simple. if the webapp has an account, then pass that account
572 # with the rest of the arguments
573  
574 # verify the token - ip match in the server root object
575
576 # then verify if the command can run on the app object with those args
577 # or even : $myapp->run( 'command', @args );
578  
579 $self->{SERVER_ROOT} ||= $server_root;
580  
581 $server_root;
582
583 } #fetch_server_root
584  
585 sub lock {
586 my( $self, $key ) = @_;
587 $self->{_lockerClient} ||= $self->{_locker}->client( $$ );
588 $self->{_lockerClient}->lock( $key );
589 }
590  
591 sub unlock {
592 my( $self, $key ) = @_;
593 $self->{_lockerClient}->unlock( $key );
594 }
595  
596  
597 # ------- END Yote::ServerStore
598  
599 package Yote::ServerObj;
600  
601 use base 'Yote::Obj';
602  
603 sub _log {
604 Yote::Server::_log(shift);
605 }
606  
607 $Yote::ServerObj::PKG2METHS = {};
608 sub __discover_methods {
609 my $pkg = shift;
610 my $meths = $Yote::ServerObj::PKG2METHS->{$pkg};
611 if( $meths ) {
612 return $meths;
613 }
614  
615 no strict 'refs';
616 my @m = grep { $_ !~ /::/ } keys %{"${pkg}\::"};
617 if( $pkg eq 'Yote::ServerObj' ) { #the base, presumably
618 return [ grep { $_ !~ /^(_|[gs]et_|(can|[sg]et|AUTOLOAD|DESTROY|CARP_TRACE|BEGIN|isa|PKG2METHS|ISA)$)/ } @m ];
619 }
620  
621 my %hasm = map { $_ => 1 } @m;
622 for my $class ( @{"${pkg}\::ISA" } ) {
623 next if $class eq 'Yote::ServerObj' || $class eq 'Yote::Obj';
624 my $pm = __discover_methods( $class );
625 push @m, @$pm;
626 }
627
628 my $base_meths = __discover_methods( 'Yote::ServerObj' );
629 my( %base ) = map { $_ => 1 } 'AUTOLOAD', @$base_meths;
630 $meths = [ grep { $_ !~ /^(_|[gs]et_|(can|[sg]et|AUTOLOAD|DESTROY|BEGIN|isa|PKG2METHS|ISA)$)/ && ! $base{$_} } @m ];
631 $Yote::ServerObj::PKG2METHS->{$pkg} = $meths;
632
633 $meths;
634 } #__discover_methods
635  
636 # when sending objects across, the format is like
637 # id : { data : { }, methods : [] }
638 # the methods exclude all the methods of Yote::Obj
639 sub _callable_methods {
640 my $self = shift;
641 my $pkg = ref( $self );
642 __discover_methods( $pkg );
643 } # _callable_methods
644  
645 sub get {
646 my( $self, $fld, $default ) = @_;
647 if( index( $fld, '_' ) == 0 ) {
648 die "Cannot get private field $fld";
649 }
650 $self->_get( $fld, $default );
651 } #get
652  
653  
654 sub _get {
655 my( $self, $fld, $default ) = @_;
656 if( ! defined( $self->{DATA}{$fld} ) && defined($default) ) {
657 if( ref( $default ) ) {
658 $self->{STORE}->_dirty( $default, $self->{STORE}->_get_id( $default ) );
659 }
660 $self->{STORE}->_dirty( $self, $self->{ID} );
661 $self->{DATA}{$fld} = $self->{STORE}->_xform_in( $default );
662 }
663 $self->{STORE}->_xform_out( $self->{DATA}{$fld} );
664 } #_get
665  
666  
667 sub set {
668 my( $self, $fld, $val ) = @_;
669 if( index( $fld, '_' ) == 0 ) {
670 die "Cannot set private field";
671 }
672 my $inval = $self->{STORE}->_xform_in( $val );
673 $self->{STORE}->_dirty( $self, $self->{ID} ) if $self->{DATA}{$fld} ne $inval;
674 $self->{DATA}{$fld} = $inval;
675
676 $self->{STORE}->_xform_out( $self->{DATA}{$fld} );
677 } #set
678  
679  
680 # ------- END Yote::ServerObj
681  
682 package Yote::ServerRoot;
683  
684 use strict;
685 use warnings;
686 no warnings 'uninitialized';
687  
688 use base 'Yote::ServerObj';
689  
690 sub _init {
691 my $self = shift;
692 $self->set__token2ip({});
693 $self->set__doesHave_Token2objs({});
694 $self->set__mayHave_Token2objs({});
695 $self->set__apps({});
696 $self->set__appOnOff({});
697 $self->set__token_timeslots([]);
698 $self->set__token_timeslots_metadata([]);
699 $self->set__token_mutex([]);
700 }
701  
702 sub _log {
703 Yote::Server::_log(shift);
704 }
705  
706 sub _valid_token {
707 my( $self, $token, $ip ) = @_;
708 my $slots = $self->get__token_timeslots();
709 for( my $i=0; $i<@$slots; $i++ ) {
710 if( $slots->[$i]{$token} eq $ip ) {
711 if( $i < $#$slots ) {
712 # refresh its time
713 $slots->[0]{ $token } = $ip;
714 }
715 return 1;
716 }
717 }
718 0;
719 }
720  
721  
722 sub _resetHasAndMay {
723 my( $self, $tokens ) = @_;
724  
725 $self->{STORE}->lock( "_has_and_may_Token2objs" );
726 for ( qw( doesHave mayHave ) ) {
727 my $item = "_${_}_Token2objs";
728 my $token2objs = $self->_get( $item );
729 for my $token (@$tokens) {
730 delete $token2objs->{ $token };
731 }
732 }
733 $self->{STORE}->unlock( "_has_and_may_Token2objs" );
734  
735 } #_resetHasAndMay
736  
737 sub _setHasAndMay {
738 my( $self, $has, $may, $token ) = @_;
739  
740 $self->{STORE}->lock( "_has_and_may_Token2objs" );
741  
742 # has
743 my $obj_data = $self->get__doesHave_Token2objs;
744 for my $id (@$has) {
745 next if index( $id, 'v' ) == 0 || $token eq '_';
746 $obj_data->{$token}{$id} = Time::HiRes::time;
747 }
748 $self->{STORE}->_stow( $obj_data );
749
750 # may
751 $obj_data = $self->get__mayHave_Token2objs;
752 for my $id (@$may) {
753 next if index( $id, 'v' ) == 0 || $token eq '_';
754 $obj_data->{$token}{$id} = Time::HiRes::time;
755 }
756 $self->{STORE}->_stow( $obj_data );
757
758 $self->{STORE}->unlock( "_has_and_may_Token2objs" );
759 } #_setHasAndMay
760  
761  
762 sub _getMay {
763 my( $self, $id, $token ) = @_;
764 return 1 if index( $id, 'v' ) == 0;
765 return 0 if $token eq '_';
766 my $obj_data = $self->get__mayHave_Token2objs;
767 $obj_data->{$token} && $obj_data->{$token}{$id};
768 }
769  
770  
771  
772 sub _updates_needed {
773 my( $self, $token, $outRes ) = @_;
774 return [] if $token eq '_';
775  
776 my $obj_data = $self->get__doesHave_Token2objs()->{$token};
777 my $store = $self->{STORE};
778 my( @updates );
779 for my $obj_id (@$outRes, keys %$obj_data ) {
780 next if index( $obj_id, 'v' ) == 0;
781 my $last_update_sent = $obj_data->{$obj_id};
782 my $last_updated = $store->_last_updated( $obj_id );
783 if( $last_update_sent <= $last_updated || $last_updated == 0 ) {
784 unless( $last_updated ) {
785 $store->{OBJ_UPDATE_DB}->put_record( $obj_id, [ Time::HiRes::time ] );
786 }
787 push @updates, $obj_id;
788 }
789 }
790 \@updates;
791 } #_updates_needed
792  
793  
794 sub create_token {
795 my $self = shift;
796 my $tries = shift;
797  
798 if( $tries > 3 ) {
799 die "Error creating token. Got the same random number 4 times in a row";
800 }
801  
802 my $randpart = int( rand( 1_000_000_000 ) ); #TODO - find max this can be for long int
803 my $ip = $ENV{REMOTE_HOST};
804
805 # make the token boat. tokens last at least 10 mins, so quantize
806 # 10 minutes via time 10 min = 600 seconds = 600
807 # or easy, so that 1000 seconds ( ~ 16 mins )
808 # todo - make some sort of quantize function here
809 my $current_time_chunk = int( time / 100 );
810 my $earliest_valid_time_chunk = $current_time_chunk - 7;
811  
812 $self->{STORE}->lock( 'token_mutex' );
813  
814  
815 #
816 # A list of slot 'boats' which store token -> ip
817 #
818 my $slots = $self->get__token_timeslots();
819  
820 #
821 # a list of times. the list index of these times corresponds
822 # to the slot 'boats'
823 #
824 my $slot_data = $self->get__token_timeslots_metadata();
825
826 #
827 # Check if the token is already used ( very unlikely ).
828 # If already used, try this again :/
829 #
830 for( my $i=0; $i<@$slot_data; $i++ ) {
831 return $self->create_token( ++$tries ) if $slots->[ $i ]{ $randpart };
832 }
833  
834 #
835 # See if this belongs on the most recent boat. If not, then
836 # create a new most recent boat.
837 #
838 if( $slot_data->[ 0 ] == $current_time_chunk ) {
839 $slots->[ 0 ]{ $randpart } = $ip;
840 } else {
841 unshift @$slot_data, $current_time_chunk;
842 unshift @$slots, { $randpart => $ip };
843 }
844  
845 #
846 # remove this token from old boats so it doesn't get purged
847 # when in a valid boat.
848 #
849 for( my $i=1; $i<@$slot_data; $i++ ) {
850 delete $slots->[$i]{ $randpart };
851 }
852  
853 #
854 # Purge tokens in expired boats.
855 #
856 my @to_remove;
857 while( @$slot_data ) {
858 if( $slot_data->[$#$slot_data] < $earliest_valid_time_chunk ) {
859 pop @$slot_data;
860 my $old = pop @$slots;
861 push @to_remove, keys %$old;
862 } else {
863 last;
864 }
865 }
866  
867 if( @to_remove ) {
868 $self->_resetHasAndMay( \@to_remove );
869 }
870
871 $self->{STORE}->unlock( 'token_mutex' );
872 # print STDERR Data::Dumper->Dump([$slot_data,$slots,"MADE TOKEN $randpart"]);
873 #
874 # $VAR1 = [
875 # '14575528'
876 # ];
877 # $VAR2 = [
878 # {
879 # '913149795' => '127.0.0.1'
880 # }
881 # ];
882 #
883 #
884
885 return $randpart;
886  
887 } #create_token
888  
889 #
890 # what things will the server root provide?
891 # logins? apps?
892 #
893 # fetch_app? It's just an object.
894 #
895  
896 sub fetch_app {
897 my( $self, $app_name, @args ) = @_;
898 my $apps = $self->get__apps;
899 my $app = $apps->{$app_name};
900 unless( $app ) {
901 eval("require $app_name");
902 if( $@ ) {
903 # TODO - have/use a good logging system with clarity and stuff
904 # warnings, errors, etc
905 _log( "App '$app_name' not found $@" );
906 return undef;
907 }
908 _log( "Loading app '$app_name'" );
909 $app = $app_name->_new( $self->{STORE} );
910 $apps->{$app_name} = $app;
911 }
912 my $appIsOn = $self->get__appOnOff->{$app_name};
913 if( $appIsOn eq 'off' ) {
914 _log( "App '$app_name' not found" );
915 return undef;
916 }
917 return $app->_can_access( @args ) ? $app : undef;
918 } #fetch_app
919  
920 sub fetch_root {
921 return shift;
922 }
923  
924 sub init_root {
925 return shift;
926 }
927  
928 sub fetch {
929 my( $self, $token, @ids ) = @_;
930 my $mays = $self->get__mayHave_Token2objs;
931 my $may = $self->get__mayHave_Token2objs()->{$token};
932 my $store = $self->{STORE};
933  
934 my @ret = map { $store->fetch($_) }
935 grep { ! ref($_) && $may->{$_} }
936 @ids;
937 die "Invalid id(s) ".join(",",grep { !ref($_) && !$may->{$_} } @ids) unless @ret == @ids;
938 @ret;
939 } #fetch
940  
941 # while this is a non-op, it will cause any updated contents to be
942 # transfered to the caller automatically
943 sub update {
944  
945 }
946  
947 # ------- END Yote::ServerRoot
948  
949 package Yote::ServerApp;
950  
951  
952 use strict;
953 use warnings;
954 no warnings 'uninitialized';
955  
956 use base 'Yote::ServerObj';
957  
958 sub _can_access {
959 1;
960 }
961  
962 # ------- END Yote::ServerApp
963  
964 1;
965  
966 __END__