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