]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/perlmods/OpenILS/Utils/CStoreEditor.pm
comitting initial authoritative auto-magic transactions for cstore
[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 this perm at the given org has already been verified, true is returned
379 # and the perm is not re-checked
380 # -----------------------------------------------------------------------------
381 =head
382 sub allowed {
383         my( $self, $perm, $org ) = @_;
384         my $uid = $self->requestor->id;
385         $org ||= $self->requestor->ws_ou;
386         $self->log(I, "checking perms user=$uid, org=$org, perm=$perm");
387         return 1 if $self->perm_checked($perm, $org); 
388         return $self->checkperm($uid, $org, $perm);
389 }
390 =cut
391
392 my $PERM_QUERY = {
393     select => {
394         au => [ {
395             transform => 'permission.usr_has_perm',
396             alias => 'has_perm',
397             column => 'id',
398             params => []
399         } ]
400     },
401     from => 'au',
402     where => {},
403 };
404
405 sub allowed {
406         my( $self, $perm, $org ) = @_;
407         my $uid = $self->requestor->id;
408         $org ||= $self->requestor->ws_ou;
409         $self->log(I, "checking perms user=$uid, org=$org, perm=$perm");
410
411     # fill in the search hash
412     $PERM_QUERY->{select}->{au}->[0]->{params} = [$perm, $org];
413     $PERM_QUERY->{where}->{id} = $uid;
414
415     return 1 if $U->is_true($self->json_query($PERM_QUERY)->[0]->{has_perm});
416
417     # set the perm failure event if the permission check returned false
418         my $e = OpenILS::Event->new('PERM_FAILURE', ilsperm => $perm, ilspermloc => $org);
419         $self->event($e);
420         return undef;
421
422 }
423
424 =head
425 sub checkperm {
426         my($self, $userid, $org, $perm) = @_;
427         my $s = $U->storagereq(
428                 "open-ils.storage.permission.user_has_perm", $userid, $perm, $org );
429
430         if(!$s) {
431                 my $e = OpenILS::Event->new('PERM_FAILURE', ilsperm => $perm, ilspermloc => $org);
432                 $self->event($e);
433                 return undef;
434         }
435
436         return 1;
437 }
438 =cut
439
440
441
442 # -----------------------------------------------------------------------------
443 # checks the appropriate perm for the operation
444 # -----------------------------------------------------------------------------
445 sub _checkperm {
446         my( $self, $ptype, $action, $org ) = @_;
447         $org ||= $self->requestor->ws_ou;
448         my $perm = $PERMS{$ptype}{$action};
449         if( $perm ) {
450                 return undef if $self->perm_checked($perm, $org);
451                 return $self->event unless $self->allowed($perm, $org);
452         } else {
453                 $self->log(I, "no perm provided for $ptype.$action");
454         }
455         return undef;
456 }
457
458
459
460 # -----------------------------------------------------------------------------
461 # Logs update actions to the activity log
462 # -----------------------------------------------------------------------------
463 sub log_activity {
464         my( $self, $type, $action, $arg ) = @_;
465         my $str = "$type.$action";
466         $str .= _prop_string($arg);
467         $self->log(A, $str);
468 }
469
470
471
472 sub _prop_string {
473         my $obj = shift;
474         my @props = $obj->properties;
475         my $str = "";
476         for(@props) {
477                 my $prop = $obj->$_() || "";
478                 $prop = substr($prop, 0, 128) . "..." if length $prop > 131;
479                 $str .= " $_=$prop";
480         }
481         return $str;
482 }
483
484
485 sub __arg_to_string {
486         my $arg = shift;
487         return "" unless defined $arg;
488         if( UNIVERSAL::isa($arg, "Fieldmapper") ) {
489                 return (defined $arg->id) ? $arg->id : '<new object>';
490         }
491         return OpenSRF::Utils::JSON->perl2JSON($arg);
492         return "";
493 }
494
495
496 # -----------------------------------------------------------------------------
497 # This does the actual storage query.
498 #
499 # 'search' calls become search_where calls and $arg can be a search hash or
500 # an array-ref of storage search options.  
501 #
502 # 'retrieve' expects an id
503 # 'update' expects an object
504 # 'create' expects an object
505 # 'delete' expects an object
506 #
507 # All methods return true on success and undef on failure.  On failure, 
508 # $e->event is set to the generated event.  
509 # Note: this method assumes that updating a non-changed object and 
510 # thereby receiving a 0 from storage, is a successful update.  
511 #
512 # The method will therefore return true so the caller can just do 
513 # $e->update_blah($x) or return $e->event;
514 # The true value returned from storage for all methods will be stored in 
515 # $e->data, until the next method is called.
516 #
517 # not-found events are generated on retrieve and serach methods.
518 # action=search methods will return [] (==true) if no data is found.  If the
519 # caller is interested in the not found event, they can do:  
520 # return $e->event unless @$results; 
521 # -----------------------------------------------------------------------------
522 sub runmethod {
523         my( $self, $action, $type, $arg, $options ) = @_;
524
525    $options ||= {};
526
527         if( $action eq 'retrieve' ) {
528                 if(! defined($arg) ) {
529                         $self->log(W,"$action $type called with no ID...");
530                         $self->event(_mk_not_found($type, $arg));
531                         return undef;
532                 } elsif( ref($arg) =~ /Fieldmapper/ ) {
533                         $self->log(E,"$action $type called with an object.. attempting ID retrieval..");
534                         $arg = $arg->id;
535                 }
536         }
537
538         my @arg = ( ref($arg) eq 'ARRAY' ) ? @$arg : ($arg);
539         my $method = $self->app.".direct.$type.$action";
540
541         if( $action eq 'search' ) {
542                 $method .= '.atomic';
543
544         } elsif( $action eq 'batch_retrieve' ) {
545                 $action = 'search';
546                 @arg = ( { id => $arg } );
547                 $method =~ s/batch_retrieve/search/o;
548                 $method .= '.atomic';
549
550         } elsif( $action eq 'retrieve_all' ) {
551                 $action = 'search';
552                 $method =~ s/retrieve_all/search/o;
553                 my $tt = $type;
554                 $tt =~ s/\./::/og;
555                 my $fmobj = "Fieldmapper::$tt";
556                 @arg = ( { $fmobj->Identity => { '!=' => undef } } );
557                 $method .= '.atomic';
558         }
559
560         $method =~ s/search/id_list/o if $options->{idlist};
561
562     $method =~ s/\.atomic$//o if $self->substream($$options{substream} || 0);
563     $self->timeout($$options{timeout});
564
565         # remove any stale events
566         $self->clear_event;
567
568         if( $action eq 'update' or $action eq 'delete' or $action eq 'create' ) {
569                 if(!$self->{xact_id}) {
570                         $logger->error("Attempt to update DB while not in a transaction : $method");
571                         throw OpenSRF::EX::ERROR ("Attempt to update DB while not in a transaction : $method");
572                 }
573                 $self->log_activity($type, $action, $arg);
574         }
575
576         if($$options{checkperm}) {
577                 my $a = ($action eq 'search') ? 'retrieve' : $action;
578                 my $e = $self->_checkperm($type, $a, $$options{permorg});
579                 if($e) {
580                         $self->event($e);
581                         return undef;
582                 }
583         }
584
585         my $obj; 
586         my $err;
587
588         try {
589                 $obj = $self->request($method, @arg);
590         } catch Error with { $err = shift; };
591         
592
593         if(!defined $obj) {
594                 $self->log(I, "request returned no data : $method");
595
596                 if( $action eq 'retrieve' ) {
597                         $self->event(_mk_not_found($type, $arg));
598
599                 } elsif( $action eq 'update' or 
600                                 $action eq 'delete' or $action eq 'create' ) {
601                         my $evt = OpenILS::Event->new(
602                                 'DATABASE_UPDATE_FAILED', payload => $arg, debug => "$err" );
603                         $self->event($evt);
604                 }
605
606                 if( $err ) {
607                         $self->event( 
608                                 OpenILS::Event->new( 'DATABASE_QUERY_FAILED', 
609                                         payload => $arg, debug => "$err" ));
610                         return undef;
611                 }
612
613                 return undef;
614         }
615
616         if( $action eq 'create' and $obj == 0 ) {
617                 my $evt = OpenILS::Event->new(
618                         'DATABASE_UPDATE_FAILED', payload => $arg, debug => "$err" );
619                 $self->event($evt);
620                 return undef;
621         }
622
623         # If we havn't dealt with the error in a nice way, go ahead and throw it
624         if( $err ) {
625                 $self->event( 
626                         OpenILS::Event->new( 'DATABASE_QUERY_FAILED', 
627                                 payload => $arg, debug => "$err" ));
628                 return undef;
629         }
630
631         if( $action eq 'search' ) {
632                 $self->log(I, "$type.$action : returned ".scalar(@$obj). " result(s)");
633                 $self->event(_mk_not_found($type, $arg)) unless @$obj;
634         }
635
636         if( $action eq 'create' ) {
637                 $self->log(I, "created a new $type object with ID " . $obj->id);
638                 $arg->id($obj->id);
639         }
640
641         $self->data($obj); # cache the data for convenience
642
643         return ($obj) ? $obj : 1;
644 }
645
646
647 sub _mk_not_found {
648         my( $type, $arg ) = @_;
649         (my $t = $type) =~ s/\./_/og;
650         $t = uc($t);
651         return OpenILS::Event->new("${t}_NOT_FOUND", payload => $arg);
652 }
653
654
655
656 # utility method for loading
657 sub __fm2meth { 
658         my $str = shift;
659         my $sep = shift;
660         $str =~ s/Fieldmapper:://o;
661         $str =~ s/::/$sep/g;
662         return $str;
663 }
664
665
666 # -------------------------------------------------------------
667 # Load up the methods from the FM classes
668 # -------------------------------------------------------------
669 my $map = $Fieldmapper::fieldmap;
670 for my $object (keys %$map) {
671         my $obj = __fm2meth($object,'_');
672         my $type = __fm2meth($object, '.');
673
674         my $update = "update_$obj";
675         my $updatef = 
676                 "sub $update {return shift()->runmethod('update', '$type', \@_);}";
677         eval $updatef;
678
679         my $retrieve = "retrieve_$obj";
680         my $retrievef = 
681                 "sub $retrieve {return shift()->runmethod('retrieve', '$type', \@_);}";
682         eval $retrievef;
683
684         my $search = "search_$obj";
685         my $searchf = 
686                 "sub $search {return shift()->runmethod('search', '$type', \@_);}";
687         eval $searchf;
688
689         my $create = "create_$obj";
690         my $createf = 
691                 "sub $create {return shift()->runmethod('create', '$type', \@_);}";
692         eval $createf;
693
694         my $delete = "delete_$obj";
695         my $deletef = 
696                 "sub $delete {return shift()->runmethod('delete', '$type', \@_);}";
697         eval $deletef;
698
699         my $bretrieve = "batch_retrieve_$obj";
700         my $bretrievef = 
701                 "sub $bretrieve {return shift()->runmethod('batch_retrieve', '$type', \@_);}";
702         eval $bretrievef;
703
704         my $retrieveall = "retrieve_all_$obj";
705         my $retrieveallf = 
706                 "sub $retrieveall {return shift()->runmethod('retrieve_all', '$type', \@_);}";
707         eval $retrieveallf;
708 }
709
710 sub json_query {
711     my( $self, $arg, $options ) = @_;
712     $options ||= {};
713         my @arg = ( ref($arg) eq 'ARRAY' ) ? @$arg : ($arg);
714     my $method = $self->app.'.json_query.atomic';
715     $method =~ s/\.atomic$//o if $self->substream($$options{substream} || 0);
716         $self->clear_event;
717     my $obj;
718     my $err;
719     
720     try {
721         $obj = $self->request($method, @arg);
722     } catch Error with { $err = shift; };
723
724     if( $err ) {
725         $self->event(
726             OpenILS::Event->new( 'DATABASE_QUERY_FAILED',
727             payload => $arg, debug => "$err" ));
728         return undef;
729     }
730
731     $self->log(I, "json_query : returned ".scalar(@$obj). " result(s)");
732     return $obj;
733 }
734
735
736
737 1;
738
739