]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/perlmods/OpenILS/Utils/CStoreEditor.pm
added ability to define recv timeout at runtime
[Evergreen.git] / Open-ILS / src / perlmods / OpenILS / Utils / CStoreEditor.pm
1 use strict; use warnings;
2 package OpenILS::Utils::CStoreEditor;
3 use OpenILS::Application::AppUtils;
4 use OpenSRF::AppSession;
5 use OpenSRF::EX qw(:try);
6 use OpenILS::Utils::Fieldmapper;
7 use OpenILS::Event;
8 use Data::Dumper;
9 use OpenSRF::Utils::JSON;
10 use OpenSRF::Utils::Logger qw($logger);
11 my $U = "OpenILS::Application::AppUtils";
12 my %PERMS;
13 my $cache;
14
15 #my %PERMS = (
16 #       'biblio.record_entry'   => { update => 'UPDATE_MARC' },
17 #       'asset.copy'                            => { update => 'UPDATE_COPY'},
18 #       'asset.call_number'             => { update => 'UPDATE_VOLUME'},
19 #       'action.circulation'            => { retrieve => 'VIEW_CIRCULATIONS'},
20 #);
21
22
23
24 # -----------------------------------------------------------------------------
25 # Export some useful functions
26 # -----------------------------------------------------------------------------
27 use vars qw(@EXPORT_OK %EXPORT_TAGS);
28 use Exporter;
29 use base qw/Exporter/;
30 push @EXPORT_OK, ( 'new_editor', 'new_rstore_editor' );
31 %EXPORT_TAGS = ( funcs => [ qw/ new_editor new_rstore_editor / ] );
32
33 sub new_editor { return OpenILS::Utils::CStoreEditor->new(@_); }
34
35 sub new_rstore_editor { 
36         my $e = OpenILS::Utils::CStoreEditor->new(@_); 
37         $e->app('open-ils.reporter-store');
38         return $e;
39 }
40
41
42 # -----------------------------------------------------------------------------
43 # Log levels
44 # -----------------------------------------------------------------------------
45 use constant E => 'error';
46 use constant W => 'warn';
47 use constant I => 'info';
48 use constant D => 'debug';
49 use constant A => 'activity';
50
51
52
53 # -----------------------------------------------------------------------------
54 # Params include:
55 #       xact=><true> : creates a storage transaction
56 #       authtoken=>$token : the login session key
57 # -----------------------------------------------------------------------------
58 sub new {
59         my( $class, %params ) = @_;
60         $class = ref($class) || $class;
61         my $self = bless( \%params, $class );
62         $self->{checked_perms} = {};
63         return $self;
64 }
65
66
67 sub app {
68         my( $self, $app ) = @_;
69         $self->{app} = $app if $app;
70         $self->{app} = 'open-ils.cstore' unless $self->{app};
71         return $self->{app};
72 }
73
74
75 # -----------------------------------------------------------------------------
76 # Log the editor metadata along with the log string
77 # -----------------------------------------------------------------------------
78 sub log {
79         my( $self, $lev, $str ) = @_;
80         my $s = "editor[";
81         $s .= "0|" unless $self->{xact};
82         $s .= "1|" if $self->{xact};
83         $s .= "0" unless $self->requestor;
84         $s .= $self->requestor->id if $self->requestor;
85         $s .= "]";
86         $logger->$lev("$s $str");
87 }
88
89 # -----------------------------------------------------------------------------
90 # Verifies the auth token and fetches the requestor object
91 # -----------------------------------------------------------------------------
92 sub checkauth {
93         my $self = shift;
94         $self->log(D, "checking auth token ".$self->authtoken);
95         my ($reqr, $evt) = $U->checkses($self->authtoken);
96         $self->event($evt) if $evt;
97         return $self->{requestor} = $reqr;
98 }
99
100
101 =head test
102 sub checkauth {
103         my $self = shift;
104         $cache = OpenSRF::Utils::Cache->new('global') unless $cache;
105         $self->log(D, "checking cached auth token ".$self->authtoken);
106         my $user = $cache->get_cache("oils_auth_".$self->authtoken);
107         return $self->{requestor} = $user->{userobj} if $user;
108         $self->event(OpenILS::Event->new('NO_SESSION'));
109         return undef;
110 }
111 =cut
112
113
114 # -----------------------------------------------------------------------------
115 # Returns the last generated event
116 # -----------------------------------------------------------------------------
117 sub event {
118         my( $self, $evt ) = @_;
119         $self->{event} = $evt if $evt;
120         return $self->{event};
121 }
122
123 # -----------------------------------------------------------------------------
124 # Destroys the transaction and disconnects where necessary,
125 # then returns the last event that occurred
126 # -----------------------------------------------------------------------------
127 sub die_event {
128         my $self = shift;
129         $self->rollback;
130         return $self->event;
131 }
132
133
134 # -----------------------------------------------------------------------------
135 # Clears the last caught event
136 # -----------------------------------------------------------------------------
137 sub clear_event {
138         my $self = shift;
139         $self->{event} = undef;
140 }
141
142 sub authtoken {
143         my( $self, $auth ) = @_;
144         $self->{authtoken} = $auth if $auth;
145         return $self->{authtoken};
146 }
147
148 sub timeout {
149     my($self, $to) = @_;
150     $self->{timeout} = $to if defined $to;
151     return defined($self->{timeout}) ? $self->{timeout} : 60;
152 }
153
154 # -----------------------------------------------------------------------------
155 # fetches the session, creating if necessary.  If 'xact' is true on this
156 # object, a db session is created
157 # -----------------------------------------------------------------------------
158 sub session {
159         my( $self, $session ) = @_;
160         $self->{session} = $session if $session;
161
162         if(!$self->{session}) {
163                 $self->{session} = OpenSRF::AppSession->create($self->app);
164
165                 if( ! $self->{session} ) {
166                         my $str = "Error creating cstore session with OpenSRF::AppSession->create()!";
167                         $self->log(E, $str);
168                         throw OpenSRF::EX::ERROR ($str);
169                 }
170
171                 $self->{session}->connect if $self->{xact} or $self->{connect};
172                 $self->xact_start if $self->{xact};
173         }
174         return $self->{session};
175 }
176
177
178 # -----------------------------------------------------------------------------
179 # Starts a storage transaction
180 # -----------------------------------------------------------------------------
181 sub xact_start {
182         my $self = shift;
183         $self->log(D, "starting new db session");
184         my $stat = $self->request($self->app . '.transaction.begin');
185         $self->log(E, "error starting database transaction") unless $stat;
186         return $stat;
187 }
188
189 # -----------------------------------------------------------------------------
190 # Commits a storage transaction
191 # -----------------------------------------------------------------------------
192 sub xact_commit {
193         my $self = shift;
194         $self->log(D, "comitting db session");
195         my $stat = $self->request($self->app.'.transaction.commit');
196         $self->log(E, "error comitting database transaction") unless $stat;
197         return $stat;
198 }
199
200 # -----------------------------------------------------------------------------
201 # Rolls back a storage stransaction
202 # -----------------------------------------------------------------------------
203 sub xact_rollback {
204         my $self = shift;
205    return unless $self->{session};
206         $self->log(I, "rolling back db session");
207         return $self->request($self->app.".transaction.rollback");
208 }
209
210
211
212 # -----------------------------------------------------------------------------
213 # Rolls back the transaction and disconnects
214 # -----------------------------------------------------------------------------
215 sub rollback {
216         my $self = shift;
217         $self->xact_rollback if $self->{xact};
218    delete $self->{xact};
219         $self->disconnect;
220 }
221
222 sub disconnect {
223         my $self = shift;
224         $self->session->disconnect if $self->{session};
225    delete $self->{session};
226 }
227
228
229 # -----------------------------------------------------------------------------
230 # commits the db session and destroys the session
231 # -----------------------------------------------------------------------------
232 sub commit {
233         my $self = shift;
234         return unless $self->{xact};
235         $self->xact_commit;
236         $self->session->disconnect;
237         $self->{session} = undef;
238 }
239
240 # -----------------------------------------------------------------------------
241 # clears all object data. Does not commit the db transaction.
242 # -----------------------------------------------------------------------------
243 sub reset {
244         my $self = shift;
245         $self->disconnect;
246         $$self{$_} = undef for (keys %$self);
247 }
248
249
250 # -----------------------------------------------------------------------------
251 # commits and resets
252 # -----------------------------------------------------------------------------
253 sub finish {
254         my $self = shift;
255         $self->commit;
256         $self->reset;
257 }
258
259
260
261 # -----------------------------------------------------------------------------
262 # Does a simple storage request
263 # -----------------------------------------------------------------------------
264 sub request {
265         my( $self, $method, @params ) = @_;
266
267     my $val;
268         my $err;
269         my $argstr = __arg_to_string( (scalar(@params)) == 1 ? $params[0] : \@params);
270
271         $self->log(I, "request $method : $argstr");
272
273         if( $self->{xact} and 
274                         $self->session->state != OpenSRF::AppSession::CONNECTED() ) {
275                 $logger->error("CStoreEditor lost it's connection!!");
276                 #throw OpenSRF::EX::ERROR ("CStoreEditor lost it's connection - transaction cannot continue");
277         }
278
279
280         try {
281
282         my $req = $self->session->request($method, @params);
283
284         if($self->substream) {
285             $self->log(D,"running in substream mode");
286             $val = [];
287             while( my $resp = $req->recv(timeout => $self->timeout) ) {
288                 push(@$val, $resp->content) if $resp->content;
289             }
290
291         } else {
292             my $resp = $req->recv(timeout => $self->timeout);
293             $val = $resp->content;
294         }
295
296         $req->finish;
297
298         } catch Error with {
299                 $err = shift;
300                 $self->log(E, "request error $method : $argstr : $err");
301         };
302
303         throw $err if $err;
304         return $val;
305 }
306
307 sub substream {
308    my( $self, $bool ) = @_;
309    $self->{substream} = $bool if defined $bool;
310    return $self->{substream};
311 }
312
313
314 # -----------------------------------------------------------------------------
315 # Sets / Returns the requstor object.  This is set when checkauth succeeds.
316 # -----------------------------------------------------------------------------
317 sub requestor {
318         my($self, $requestor) = @_;
319         $self->{requestor} = $requestor if $requestor;
320         return $self->{requestor};
321 }
322
323
324
325 # -----------------------------------------------------------------------------
326 # Holds the last data received from a storage call
327 # -----------------------------------------------------------------------------
328 sub data {
329         my( $self, $data ) = @_;
330         $self->{data} = $data if defined $data;
331         return $self->{data};
332 }
333
334
335 # -----------------------------------------------------------------------------
336 # True if this perm has already been checked at this org
337 # -----------------------------------------------------------------------------
338 sub perm_checked {
339         my( $self, $perm, $org ) = @_;
340         $self->{checked_perms}->{$org} = {}
341                 unless $self->{checked_perms}->{$org};
342         my $checked = $self->{checked_perms}->{$org}->{$perm};
343         if(!$checked) {
344                 $self->{checked_perms}->{$org}->{$perm} = 1;
345                 return 0;
346         }
347         return 1;
348 }
349
350
351
352 # -----------------------------------------------------------------------------
353 # Returns true if the requested perm is allowed.  If the perm check fails,
354 # $e->event is set and undef is returned
355 # The perm user is $e->requestor->id and perm org defaults to the requestor's
356 # ws_ou
357 # If this perm at the given org has already been verified, true is returned
358 # and the perm is not re-checked
359 # -----------------------------------------------------------------------------
360 sub allowed {
361         my( $self, $perm, $org ) = @_;
362         my $uid = $self->requestor->id;
363         $org ||= $self->requestor->ws_ou;
364         $self->log(I, "checking perms user=$uid, org=$org, perm=$perm");
365         return 1 if $self->perm_checked($perm, $org); 
366         return $self->checkperm($uid, $org, $perm);
367 }
368
369 sub checkperm {
370         my($self, $userid, $org, $perm) = @_;
371         my $s = $U->storagereq(
372                 "open-ils.storage.permission.user_has_perm", $userid, $perm, $org );
373
374         if(!$s) {
375                 my $e = OpenILS::Event->new('PERM_FAILURE', ilsperm => $perm, ilspermloc => $org);
376                 $self->event($e);
377                 return undef;
378         }
379
380         return 1;
381 }
382
383
384
385 # -----------------------------------------------------------------------------
386 # checks the appropriate perm for the operation
387 # -----------------------------------------------------------------------------
388 sub _checkperm {
389         my( $self, $ptype, $action, $org ) = @_;
390         $org ||= $self->requestor->ws_ou;
391         my $perm = $PERMS{$ptype}{$action};
392         if( $perm ) {
393                 return undef if $self->perm_checked($perm, $org);
394                 return $self->event unless $self->allowed($perm, $org);
395         } else {
396                 $self->log(I, "no perm provided for $ptype.$action");
397         }
398         return undef;
399 }
400
401
402
403 # -----------------------------------------------------------------------------
404 # Logs update actions to the activity log
405 # -----------------------------------------------------------------------------
406 sub log_activity {
407         my( $self, $type, $action, $arg ) = @_;
408         my $str = "$type.$action";
409         $str .= _prop_string($arg);
410         $self->log(A, $str);
411 }
412
413
414
415 sub _prop_string {
416         my $obj = shift;
417         my @props = $obj->properties;
418         my $str = "";
419         for(@props) {
420                 my $prop = $obj->$_() || "";
421                 $prop = substr($prop, 0, 128) . "..." if length $prop > 131;
422                 $str .= " $_=$prop";
423         }
424         return $str;
425 }
426
427
428 sub __arg_to_string {
429         my $arg = shift;
430         return "" unless defined $arg;
431         if( UNIVERSAL::isa($arg, "Fieldmapper") ) {
432                 return (defined $arg->id) ? $arg->id : '<new object>';
433         }
434         return OpenSRF::Utils::JSON->perl2JSON($arg);
435         return "";
436 }
437
438
439 # -----------------------------------------------------------------------------
440 # This does the actual storage query.
441 #
442 # 'search' calls become search_where calls and $arg can be a search hash or
443 # an array-ref of storage search options.  
444 #
445 # 'retrieve' expects an id
446 # 'update' expects an object
447 # 'create' expects an object
448 # 'delete' expects an object
449 #
450 # All methods return true on success and undef on failure.  On failure, 
451 # $e->event is set to the generated event.  
452 # Note: this method assumes that updating a non-changed object and 
453 # thereby receiving a 0 from storage, is a successful update.  
454 #
455 # The method will therefore return true so the caller can just do 
456 # $e->update_blah($x) or return $e->event;
457 # The true value returned from storage for all methods will be stored in 
458 # $e->data, until the next method is called.
459 #
460 # not-found events are generated on retrieve and serach methods.
461 # action=search methods will return [] (==true) if no data is found.  If the
462 # caller is interested in the not found event, they can do:  
463 # return $e->event unless @$results; 
464 # -----------------------------------------------------------------------------
465 sub runmethod {
466         my( $self, $action, $type, $arg, $options ) = @_;
467
468    $options ||= {};
469
470         if( $action eq 'retrieve' ) {
471                 if(! defined($arg) ) {
472                         $self->log(W,"$action $type called with no ID...");
473                         $self->event(_mk_not_found($type, $arg));
474                         return undef;
475                 } elsif( ref($arg) =~ /Fieldmapper/ ) {
476                         $self->log(E,"$action $type called with an object.. attempting ID retrieval..");
477                         $arg = $arg->id;
478                 }
479         }
480
481         my @arg = ( ref($arg) eq 'ARRAY' ) ? @$arg : ($arg);
482         my $method = $self->app.".direct.$type.$action";
483
484         if( $action eq 'search' ) {
485                 $method .= '.atomic';
486
487         } elsif( $action eq 'batch_retrieve' ) {
488                 $action = 'search';
489                 @arg = ( { id => $arg } );
490                 $method =~ s/batch_retrieve/search/o;
491                 $method .= '.atomic';
492
493         } elsif( $action eq 'retrieve_all' ) {
494                 $action = 'search';
495                 $method =~ s/retrieve_all/search/o;
496                 my $tt = $type;
497                 $tt =~ s/\./::/og;
498                 my $fmobj = "Fieldmapper::$tt";
499                 @arg = ( { $fmobj->Identity => { '!=' => undef } } );
500                 $method .= '.atomic';
501         }
502
503         $method =~ s/search/id_list/o if $options->{idlist};
504
505     $method =~ s/\.atomic$//o if $self->substream($$options{substream} || 0);
506     $self->timeout($$options{timeout});
507
508         # remove any stale events
509         $self->clear_event;
510
511         if( $action eq 'update' or $action eq 'delete' or $action eq 'create' ) {
512                 if(!$self->{xact}) {
513                         $logger->error("Attempt to update DB while not in a transaction : $method");
514                         throw OpenSRF::EX::ERROR ("Attempt to update DB while not in a transaction : $method");
515                 }
516                 $self->log_activity($type, $action, $arg);
517         }
518
519         if($$options{checkperm}) {
520                 my $a = ($action eq 'search') ? 'retrieve' : $action;
521                 my $e = $self->_checkperm($type, $a, $$options{permorg});
522                 if($e) {
523                         $self->event($e);
524                         return undef;
525                 }
526         }
527
528         my $obj; 
529         my $err;
530
531         try {
532                 $obj = $self->request($method, @arg);
533         } catch Error with { $err = shift; };
534         
535
536         if(!defined $obj) {
537                 $self->log(I, "request returned no data : $method");
538
539                 if( $action eq 'retrieve' ) {
540                         $self->event(_mk_not_found($type, $arg));
541
542                 } elsif( $action eq 'update' or 
543                                 $action eq 'delete' or $action eq 'create' ) {
544                         my $evt = OpenILS::Event->new(
545                                 'DATABASE_UPDATE_FAILED', payload => $arg, debug => "$err" );
546                         $self->event($evt);
547                 }
548
549                 if( $err ) {
550                         $self->event( 
551                                 OpenILS::Event->new( 'DATABASE_QUERY_FAILED', 
552                                         payload => $arg, debug => "$err" ));
553                         return undef;
554                 }
555
556                 return undef;
557         }
558
559         if( $action eq 'create' and $obj == 0 ) {
560                 my $evt = OpenILS::Event->new(
561                         'DATABASE_UPDATE_FAILED', payload => $arg, debug => "$err" );
562                 $self->event($evt);
563                 return undef;
564         }
565
566         # If we havn't dealt with the error in a nice way, go ahead and throw it
567         if( $err ) {
568                 $self->event( 
569                         OpenILS::Event->new( 'DATABASE_QUERY_FAILED', 
570                                 payload => $arg, debug => "$err" ));
571                 return undef;
572         }
573
574         if( $action eq 'search' ) {
575                 $self->log(I, "$type.$action : returned ".scalar(@$obj). " result(s)");
576                 $self->event(_mk_not_found($type, $arg)) unless @$obj;
577         }
578
579         if( $action eq 'create' ) {
580                 $self->log(I, "created a new $type object with ID " . $obj->id);
581                 $arg->id($obj->id);
582         }
583
584         $self->data($obj); # cache the data for convenience
585
586         return ($obj) ? $obj : 1;
587 }
588
589
590 sub _mk_not_found {
591         my( $type, $arg ) = @_;
592         (my $t = $type) =~ s/\./_/og;
593         $t = uc($t);
594         return OpenILS::Event->new("${t}_NOT_FOUND", payload => $arg);
595 }
596
597
598
599 # utility method for loading
600 sub __fm2meth { 
601         my $str = shift;
602         my $sep = shift;
603         $str =~ s/Fieldmapper:://o;
604         $str =~ s/::/$sep/g;
605         return $str;
606 }
607
608
609 # -------------------------------------------------------------
610 # Load up the methods from the FM classes
611 # -------------------------------------------------------------
612 my $map = $Fieldmapper::fieldmap;
613 for my $object (keys %$map) {
614         my $obj = __fm2meth($object,'_');
615         my $type = __fm2meth($object, '.');
616
617         my $update = "update_$obj";
618         my $updatef = 
619                 "sub $update {return shift()->runmethod('update', '$type', \@_);}";
620         eval $updatef;
621
622         my $retrieve = "retrieve_$obj";
623         my $retrievef = 
624                 "sub $retrieve {return shift()->runmethod('retrieve', '$type', \@_);}";
625         eval $retrievef;
626
627         my $search = "search_$obj";
628         my $searchf = 
629                 "sub $search {return shift()->runmethod('search', '$type', \@_);}";
630         eval $searchf;
631
632         my $create = "create_$obj";
633         my $createf = 
634                 "sub $create {return shift()->runmethod('create', '$type', \@_);}";
635         eval $createf;
636
637         my $delete = "delete_$obj";
638         my $deletef = 
639                 "sub $delete {return shift()->runmethod('delete', '$type', \@_);}";
640         eval $deletef;
641
642         my $bretrieve = "batch_retrieve_$obj";
643         my $bretrievef = 
644                 "sub $bretrieve {return shift()->runmethod('batch_retrieve', '$type', \@_);}";
645         eval $bretrievef;
646
647         my $retrieveall = "retrieve_all_$obj";
648         my $retrieveallf = 
649                 "sub $retrieveall {return shift()->runmethod('retrieve_all', '$type', \@_);}";
650         eval $retrieveallf;
651 }
652
653 sub json_query {
654     my( $self, $arg, $options ) = @_;
655     $options ||= {};
656         my @arg = ( ref($arg) eq 'ARRAY' ) ? @$arg : ($arg);
657     my $method = $self->app.'.json_query.atomic';
658     $method =~ s/\.atomic$//o if $self->substream($$options{substream} || 0);
659         $self->clear_event;
660     my $obj;
661     my $err;
662     
663     try {
664         $obj = $self->request($method, @arg);
665     } catch Error with { $err = shift; };
666
667     if( $err ) {
668         $self->event(
669             OpenILS::Event->new( 'DATABASE_QUERY_FAILED',
670             payload => $arg, debug => "$err" ));
671         return undef;
672     }
673
674     $self->log(I, "json_query : returned ".scalar(@$obj). " result(s)");
675     return $obj;
676 }
677
678
679
680 1;
681
682