blib/lib/Bio/Graphics/Browser2/Session.pm untested

filter: Statementstmt 0.0% 0 / 260 Branchbran 0.0% 0 / 118 Conditioncond 0.0% 0 / 48 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 50 Podpod 0.0% 0 / 35 totaltotal 0.0% 0 / 511 CC 60 SCAR 34.1
CC
60
Cov
0%
new
110.0
lock
110.0
flush
42.0
CRAP 30.3
1 package Bio::Graphics::Browser2::Session;
2  
3 # $Id$
4  
5 use strict;
6 use warnings;
7  
8 use CGI::Session;
9 use CGI::Cookie;
10 use Fcntl 'LOCK_EX','LOCK_SH';
11 use File::Spec;
12 use File::Path 'mkpath';
13 use Digest::MD5 'md5_hex';
14 use Carp 'carp';
15 use constant LOCK_TIMEOUT => 10;
16 eval "require Time::HiRes;";
17  
18 my $HAS_NFSLOCK;
19 my $HAS_MYSQL;
20  
21 BEGIN {
22 # Prevent CGI::Session from autoflushing. Only flush when we say to.
23 undef *CGI::Session::DESTROY;
24 $HAS_NFSLOCK = eval {require File::NFSLock;1 };
25 $HAS_MYSQL = eval {require DBI; require DBD::mysql; 1};
26 }
27  
28 use constant DEBUG => 0;
29 use constant DEBUG_LOCK => DEBUG || 0;
30  
31 sub new {
32 my $class = shift;
33 my %args = @_;
34 my ($driver,$id,$session_args,$default_source,$lockdir,$locktype,$expire_time,$mode)
35 = @args{'driver','id','args','source','lockdir','locktype','expires','mode'};
36  
37 $mode ||= 'exclusive';
38 $CGI::Session::NAME = 'gbrowse_sess'; # custom cookie
39  
40 #Probably safe to uncomment, but must test exhaustively with mysql locking
41 #to determine.
42 #$CGI::Session::Driver::file::NoFlock = 1;;
43  
44 unless ($id) {
45 my $cookie = CGI::Cookie->fetch();
46 $id = $cookie->{$CGI::Session::NAME}->value
47 if $cookie && $cookie->{$CGI::Session::NAME};
48 }
49 my $self = bless {
50 lockdir => $lockdir,
51 locktype => $locktype,
52 },$class;
53  
54 $self->session_argv($driver,$id,$session_args);
55 $self->{session} = $mode eq 'exclusive' ? $self->lock_ex($id) : $self->lock_sh($id);
56 warn "CGI::Session->new($driver,$id,$session_args)=>",$self->{session}->id if DEBUG;
57  
58 # never expire private (authenticated) sessions
59 $expire_time = 0 if $self->private;
60 $self->{session}->expire($expire_time)
61 if defined $expire_time;
62  
63 warn "[$$] session fetch for ",$self->id if DEBUG;
64 $self->source($default_source) unless defined $self->source;
65 $self->{pid} = $$;
66  
67 ## DEBUG STARTS
68 if (DEBUG_LOCK) {
69 my $state = $self->page_settings;
70 my @tracks = sort grep {$state->{features}{$_}{visible}} keys %{$state->{features}};
71 warn '[',$self->time,'] ',"[$$] READING @tracks\n";
72 }
73 ## DEBUG ENDS
74  
75 $self;
76 }
77  
78 sub load_session {
79 my $self = shift;
80 $self->session_argv(@_);
81 return CGI::Session->new($self->session_argv);
82 }
83  
84 sub session_argv {
85 my $self = shift;
86 if (@_) {
87 $self->{session_argv} = \@_;
88 } else {
89 return unless $self->{session_argv};
90 return @{$self->{session_argv}};
91 }
92 }
93  
94 sub locktime {
95 my $self = shift;
96 my $d = $self->{locktime};
97 $self->{locktime} = shift if @_;
98 return $d;
99 }
100  
101 sub locktype {
102 my $self = shift;
103 if ($self->{locktype} eq 'default') {
104 return 'flock';
105 }
106 return 'nfs' if $self->{locktype} eq 'nfs' && $HAS_NFSLOCK;
107 return 'mysql' if $self->{locktype} =~ /^(dbi:mysql|mysql):/ && $HAS_MYSQL;
108 return 'flock' if $self->{locktype} eq 'flock';
109 }
110  
111 sub lock {
112 my $self = shift;
113 my $type = shift;
114 my $id = shift;
115
116 # no id, so we have to create a session and get an id
117 # otherwise we lock before we make the session
118 unless ($id) {
119 $self->{session} ||= $self->load_session();
120 $id = $self->id;
121 }
122  
123 return if $self->lockobj; # don't double lock
124 my $locktype = $self->locktype;
125 my $start_time = $self->time();
126  
127 warn '[',$self->time,'] ',"[$$] waiting on $type session lock...\n" if DEBUG_LOCK;
128  
129 eval {
130 local $SIG{ALRM} = sub {die "timeout\n"};
131 # timeout lock to avoid some process from keeping process open
132 # you may see some lock timeouts if a process is taking too long
133 # to release its session.
134 alarm(LOCK_TIMEOUT);
135  
136 if ($locktype eq 'flock') {
137 $self->lock_flock($type,$id);
138 }
139 elsif ($locktype eq 'nfs') {
140 $self->lock_nfs($type,$id);
141 }
142 elsif ($locktype eq 'mysql') {
143 $self->lock_mysql($type,$id);
144 }
145 else {
146 die "unknown lock type $locktype";
147 }
148 };
149 alarm(0);
150 my $elapsed = sprintf("%5.3fs",$self->time()-$start_time);
151 if ($@) {
152 die $@ unless $@ eq "timeout\n";
153 warn ("[$$] session lock timed out on request after $elapsed\n",
154 CGI::request_method(),': ',
155 CGI::url(-path=>1),' ',
156 CGI::query_string());
157 } else {
158 warn '[',$self->time,'] ',"[$$] ...$type lock obtained after $elapsed (action=",CGI::param('action'),')' if DEBUG_LOCK;
159 }
160 $self->locktime($self->time());
161 return $self->{session} ||= $self->load_session();
162 }
163  
164 sub lock_flock {
165 my $self = shift;
166 my ($type,$id) = @_;
167  
168 my $mode = $type eq 'exclusive' ? LOCK_EX : LOCK_SH;
169  
170 my ($lockdir,$lockfile) = $self->lockfile($id);
171  
172 mkpath($lockdir) unless -e $lockdir;
173 my $lockpath = File::Spec->catfile($lockdir,$lockfile);
174 my $o_mode = $type eq 'exclusive' ? '>'
175 :-e $lockpath ? "<"
176 : "+>";
177  
178 open my $fh,$o_mode,$lockpath
179 or die "Couldn't open lockfile $lockpath: $!";
180 flock ($fh,$mode);
181 $self->lockobj($fh);
182 }
183  
184 sub lock_nfs {
185 my $self = shift;
186 my ($type,$id) = @_;
187 my ($lockdir,$lockfile) = $self->lockfile($id);
188 mkpath($lockdir) unless -e $lockdir;
189 my $lockpath = File::Spec->catfile($lockdir,$lockfile);
190 my $lock = File::NFSLock->new(
191 {file => $lockpath,
192 lock_type => $type eq 'exclusive' ? LOCK_EX : LOCK_SH
193 });
194 $lock or warn "[$$] ...couldn't get lock: $File::NFSLock::errstr";
195 $self->lockobj($lock);
196  
197 }
198  
199 sub lock_mysql {
200 my $self = shift;
201 my ($type,$id) = @_;
202 $SIG{PIPE} = 'IGNORE';
203 return if $type eq 'shared';
204 my $lock_name = $self->mysql_lock_name($id);
205 (my $dsn = $self->{locktype}) =~ s/^mysql://;
206 my $dbh = $self->{mysql} ||= DBI->connect($dsn)
207 or die "Session has no dbh handle!";
208 my $result = $dbh->selectrow_arrayref("SELECT GET_LOCK('$lock_name',10)");
209 warn "Could not get my lock on $id" unless $result->[0];
210 $self->lockobj($dbh);
211 }
212  
213 sub lock_sh {
214 shift->lock('shared',@_);
215 }
216 sub lock_ex {
217 shift->lock('exclusive',@_);
218 }
219  
220 sub unlock {
221 my $self = shift;
222 my $lock = $self->lockobj or return;
223 warn '[',$self->time,'] ',"[$$] session unlock" if DEBUG_LOCK;
224 if ($lock->isa('DBI::db')) {
225 my $lock_name = $self->mysql_lock_name($self->id);
226 my $result = $lock->do("SELECT RELEASE_LOCK('$lock_name')");
227 }
228 $self->lockobj(undef);
229 warn "[$$] lock released after ",sprintf("%2.1f",$self->time() - $self->locktime)," s (action=",CGI::param('action'),')' if DEBUG;
230 }
231  
232 sub lockfile {
233 my $self = shift;
234 my $id = shift;
235 my ($a) = $id =~ /^(.{2})/;
236 return (File::Spec->catfile($self->{lockdir},$a),
237 $id);
238 }
239  
240 sub mysql_lock_name {
241 my $self = shift;
242 my $id = shift;
243 return "gbrowse_session_lock.$id";
244 }
245  
246 # handle the lock when forking occurs
247 sub was_forked {
248 my $self = shift;
249 my $state = shift;
250 my $obj = $self->lockobj or return;
251 ref $obj or return;
252 if ($state eq 'child') {
253 if ($obj->isa('File::NFSLock')) {
254 undef *File::NFSLock::DESTROY;
255 }
256 elsif ($obj->isa('DBI::db')) {
257 $obj->{InactiveDestroy} = 1;
258 }
259 }
260 }
261  
262 sub delete {
263 my $self = shift;
264 $self->{session}->delete if $self->{session};
265 $self->unlock;
266 }
267  
268 sub flush {
269 my $self = shift;
270 return unless $$ == $self->{pid};
271 carp "[$$] session flush" if DEBUG;
272  
273 ## DEBUG STARTS
274 if (DEBUG_LOCK) {
275 my $state = $self->page_settings;
276 my @tracks = sort grep {$state->{features}{$_}{visible}} keys %{$state->{features}};
277 warn '[',$self->time,'] ',"[$$] WRITING @tracks\n";
278 }
279 ## DEBUG ENDS
280  
281 $self->{session}->flush if $self->{session};
282 # $self->unlock;
283 warn "[$$] SESSION FLUSH ERROR: ",$self->{session}->errstr
284 if $self->{session}->errstr;
285 }
286  
287 sub time {
288 return defined &Time::HiRes::time ? Time::HiRes::time() : time();
289 }
290  
291 sub modified {
292 my $self = shift;
293 $self->{session}->_set_status(CGI::Session::STATUS_MODIFIED());
294 }
295  
296 sub lockobj {
297 my $self = shift;
298 my $d = $self->{lockobj};
299 $self->{lockobj} = shift if @_;
300 return $d;
301 }
302  
303 sub id {
304 shift->{session}->id;
305 }
306  
307 sub session { shift->{session} }
308  
309 sub page_settings {
310 my $self = shift;
311 my $hash = $self->config_hash;
312 $hash->{page_settings} ||= {};
313 $hash->{page_settings}{userid} ||= $self->id; # store the id in our state
314 return $hash->{page_settings};
315 }
316  
317 sub snapshots {
318 my $self = shift;
319 my $hash = $self->config_hash;
320 return $hash->{snapshots} ||= {};
321 }
322  
323 sub plugin_settings {
324 my $self = shift;
325 my $plugin_base = shift;
326 my $hash = $self->config_hash;
327 return $hash->{plugins}{$plugin_base} ||= {};
328 }
329  
330 sub source {
331 my $self = shift;
332 my $source = $self->{session}->param('.source');
333 $self->{session}->param('.source' => shift()) if @_;
334 return $source;
335 }
336  
337 sub uploadsid {
338 my $self = shift;
339 $self->{session}->param('.uploadsid' => shift() ) if @_;
340 my $id = $self->{session}->param('.uploadsid');
341 unless ($id) {
342 # uploadsid used to be stored in the settings, which was wrong
343 $id = $self->page_settings->{uploadid} ||
344 Bio::Graphics::Browser2::Util->generate_id;
345 $self->{session}->param('.uploadsid' => $id);
346 }
347 return $id;
348 }
349  
350 sub private {
351 my $self = shift;
352 my $private = $self->{session}->param('.private');
353 $self->{session}->param('.private' => shift()) if @_;
354 return $private;
355 }
356  
357 sub remember_auth {
358 my $self = shift;
359 my $ra = $self->{session}->param('.remember_auth');
360 $self->{session}->param('.remember_auth' => shift()) if @_;
361 return $ra;
362 }
363  
364 sub username {
365 my $self = shift;
366 my $user = $self->{session}->param('.username');
367 $self->{session}->param('.username' => shift()) if @_;
368 return $user;
369 }
370  
371 sub using_openid {
372 my $self = shift;
373 my $using = $self->{session}->param('.using_openid');
374 $self->{session}->param('.using_openid' => shift()) if @_;
375 return $using;
376 }
377  
378 sub set_nonce {
379 my $self = shift;
380 my ($nonce,$salt,$remember) = @_;
381 warn "id=",$self->id," writing nonce = ",md5_hex($nonce,$salt) if DEBUG;
382 $self->{session}->param('.nonce' => md5_hex($nonce,$salt));
383  
384 # handle session expiration
385 if ($remember) {
386 $self->{session}->expire('.nonce' => '30d'); # remembers authorization for 30 days
387 $self->remember_auth(1);
388 } else {
389 $self->{session}->expire('.nonce' => '1d'); # force reauthorization every day
390 $self->remember_auth(0);
391 }
392 $self->private(1);
393 }
394  
395 sub match_nonce {
396 my $self = shift;
397 my ($new_nonce,$salt) = @_;
398 $self->private || return;
399 my $nonce = $self->{session}->param('.nonce');
400 warn "id=",$self->id," matching $nonce against ",$new_nonce,"|",$salt if DEBUG;
401 warn "$nonce eq ",md5_hex($new_nonce, $salt) if DEBUG;
402 return $nonce eq md5_hex($new_nonce, $salt);
403 }
404  
405 sub config_hash {
406 my $self = shift;
407 my $source = $self->source;
408 my $session = $self->{session};
409 $session->param($source=>{}) unless $session->param($source);
410 return $session->param($source);
411 }
412  
413 # problem with explicit DESTROY is that it gets called in all child
414 # processes. Better to have the unlock happen when filehandle is truly
415 # destroyed.
416 #sub DESTROY {
417 # my $self = shift;
418 # $self->flush;
419 # $self->unlock;
420 #}
421  
422 1;