1 use strict; use warnings;
2 package OpenILS::Utils::CStoreEditor;
3 use OpenILS::Application::AppUtils;
4 use OpenSRF::Application;
5 use OpenSRF::AppSession;
6 use OpenSRF::EX qw(:try);
7 use OpenILS::Utils::Fieldmapper;
10 use OpenSRF::Utils::JSON;
11 use OpenSRF::Utils::Logger qw($logger);
12 my $U = "OpenILS::Application::AppUtils";
17 # if set, we will use this locale for all new sessions
18 # if unset, we rely on the existing opensrf locale propagation
25 # 'biblio.record_entry' => { update => 'UPDATE_MARC' },
26 # 'asset.copy' => { update => 'UPDATE_COPY'},
27 # 'asset.call_number' => { update => 'UPDATE_VOLUME'},
28 # 'action.circulation' => { retrieve => 'VIEW_CIRCULATIONS'},
31 sub flush_forced_xacts {
32 for my $k ( keys %xact_ed_cache ) {
34 $xact_ed_cache{$k}->rollback;
38 delete $xact_ed_cache{$k};
42 # -----------------------------------------------------------------------------
43 # Export some useful functions
44 # -----------------------------------------------------------------------------
45 use vars qw(@EXPORT_OK %EXPORT_TAGS);
47 use base qw/Exporter/;
48 push @EXPORT_OK, ( 'new_editor', 'new_rstore_editor' );
49 %EXPORT_TAGS = ( funcs => [ qw/ new_editor new_rstore_editor / ] );
51 sub new_editor { return OpenILS::Utils::CStoreEditor->new(@_); }
53 sub new_rstore_editor {
54 my $e = OpenILS::Utils::CStoreEditor->new(@_);
55 $e->app('open-ils.reporter-store');
60 # -----------------------------------------------------------------------------
62 # -----------------------------------------------------------------------------
63 use constant E => 'error';
64 use constant W => 'warn';
65 use constant I => 'info';
66 use constant D => 'debug';
67 use constant A => 'activity';
71 # -----------------------------------------------------------------------------
73 # xact=><true> : creates a storage transaction
74 # authtoken=>$token : the login session key
75 # -----------------------------------------------------------------------------
77 my( $class, %params ) = @_;
78 $class = ref($class) || $class;
79 my $self = bless( \%params, $class );
80 $self->{checked_perms} = {};
91 my( $self, $app ) = @_;
92 $self->{app} = $app if $app;
93 $self->{app} = 'open-ils.cstore' unless $self->{app};
98 # -----------------------------------------------------------------------------
99 # Log the editor metadata along with the log string
100 # -----------------------------------------------------------------------------
102 my( $self, $lev, $str ) = @_;
106 } elsif ($self->{xact}) {
111 $s .= "0" unless $self->requestor;
112 $s .= $self->requestor->id if $self->requestor;
114 $logger->$lev("$s $str");
117 # -----------------------------------------------------------------------------
118 # Verifies the auth token and fetches the requestor object
119 # -----------------------------------------------------------------------------
122 $self->log(D, "checking auth token ".$self->authtoken);
124 my $content = $U->simplereq(
126 'open-ils.auth.session.retrieve', $self->authtoken, 1);
128 if(!$content or $U->event_code($content)) {
129 $self->event( ($content) ? $content : OpenILS::Event->new('NO_SESSION'));
133 $self->{authtime} = $content->{authtime};
134 return $self->{requestor} = $content->{userobj};
141 $cache = OpenSRF::Utils::Cache->new('global') unless $cache;
142 $self->log(D, "checking cached auth token ".$self->authtoken);
143 my $user = $cache->get_cache("oils_auth_".$self->authtoken);
144 return $self->{requestor} = $user->{userobj} if $user;
145 $self->event(OpenILS::Event->new('NO_SESSION'));
152 # -----------------------------------------------------------------------------
153 # Returns the last generated event
154 # -----------------------------------------------------------------------------
156 my( $self, $evt ) = @_;
157 $self->{event} = $evt if $evt;
158 return $self->{event};
161 # -----------------------------------------------------------------------------
162 # Destroys the transaction and disconnects where necessary,
163 # then returns the last event that occurred
164 # -----------------------------------------------------------------------------
175 # -----------------------------------------------------------------------------
176 # Clears the last caught event
177 # -----------------------------------------------------------------------------
180 $self->{event} = undef;
184 my($self, $died) = @_;
185 $self->{died} = $died if defined $died;
186 return $self->{died};
190 my( $self, $auth ) = @_;
191 $self->{authtoken} = $auth if $auth;
192 return $self->{authtoken};
196 my( $self, $auth ) = @_;
197 $self->{authtime} = $auth if $auth;
198 return $self->{authtime};
203 $self->{timeout} = $to if defined $to;
204 return defined($self->{timeout}) ? $self->{timeout} : 60;
207 # -----------------------------------------------------------------------------
208 # fetches the session, creating if necessary. If 'xact' is true on this
209 # object, a db session is created
210 # -----------------------------------------------------------------------------
212 my( $self, $session ) = @_;
213 $self->{session} = $session if $session;
215 # sessions can stick around longer than a single request/transaction.
216 # kill it if our default locale was altered since the last request
217 # and it does not match the locale of the existing session.
218 delete $self->{session} if
221 $self->{session}->session_locale ne $default_locale;
223 if(!$self->{session}) {
224 $self->{session} = OpenSRF::AppSession->create($self->app);
225 $self->{session}->session_locale($default_locale) if $default_locale;
227 if( ! $self->{session} ) {
228 my $str = "Error creating cstore session with OpenSRF::AppSession->create()!";
230 throw OpenSRF::EX::ERROR ($str);
233 $self->{session}->connect if $self->{xact} or $self->{connect} or $always_xact;
234 $self->xact_begin if $self->{xact} or $always_xact;
237 $xact_ed_cache{$self->{xact_id}} = $self if $always_xact and $self->{xact_id};
238 return $self->{session};
242 # -----------------------------------------------------------------------------
243 # Starts a storage transaction
244 # -----------------------------------------------------------------------------
247 return $self->{xact_id} if $self->{xact_id};
248 $self->session->connect unless $self->session->state == OpenSRF::AppSession::CONNECTED();
249 $self->log(D, "starting new database transaction");
250 unless($self->{xact_id}) {
251 my $stat = $self->request($self->app . '.transaction.begin');
252 $self->log(E, "error starting database transaction") unless $stat;
253 $self->{xact_id} = $stat;
254 if($self->authtoken) {
255 if(!$self->requestor) {
260 if($self->requestor) {
261 $user_id = $self->requestor->id;
262 $ws_id = $self->requestor->wsid;
264 $self->request($self->app . '.set_audit_info', $self->authtoken, $user_id, $ws_id);
268 return $self->{xact_id};
271 # -----------------------------------------------------------------------------
272 # Commits a storage transaction
273 # -----------------------------------------------------------------------------
276 return unless $self->{xact_id};
277 $self->log(D, "comitting db session");
278 my $stat = $self->request($self->app.'.transaction.commit');
279 $self->log(E, "error comitting database transaction") unless $stat;
280 delete $self->{xact_id};
281 delete $self->{xact};
285 # -----------------------------------------------------------------------------
286 # Rolls back a storage stransaction
287 # -----------------------------------------------------------------------------
290 return unless $self->{session} and $self->{xact_id};
291 $self->log(I, "rolling back db session");
292 my $stat = $self->request($self->app.".transaction.rollback");
293 $self->log(E, "error rolling back database transaction") unless $stat;
294 delete $self->{xact_id};
295 delete $self->{xact};
300 # -----------------------------------------------------------------------------
301 # Savepoint functions. If no savepoint name is provided, the same name is used
302 # for each successive savepoint, in which case only the last savepoint set can
303 # be released or rolled back.
304 # -----------------------------------------------------------------------------
307 my $name = shift || 'savepoint';
308 return unless $self->{session} and $self->{xact_id};
309 $self->log(I, "setting savepoint '$name'");
310 my $stat = $self->request($self->app.".savepoint.set", $name)
311 or $self->log(E, "error setting savepoint '$name'");
315 sub release_savepoint {
317 my $name = shift || 'savepoint';
318 return unless $self->{session} and $self->{xact_id};
319 $self->log(I, "releasing savepoint '$name'");
320 my $stat = $self->request($self->app.".savepoint.release", $name)
321 or $self->log(E, "error releasing savepoint '$name'");
325 sub rollback_savepoint {
327 my $name = shift || 'savepoint';
328 return unless $self->{session} and $self->{xact_id};
329 $self->log(I, "rollback savepoint '$name'");
330 my $stat = $self->request($self->app.".savepoint.rollback", $name)
331 or $self->log(E, "error rolling back savepoint '$name'");
336 # -----------------------------------------------------------------------------
337 # Rolls back the transaction and disconnects
338 # -----------------------------------------------------------------------------
344 $self->xact_rollback;
348 $ret = $self->disconnect
350 throw $err if ($err);
356 $self->session->disconnect if
358 $self->{session}->state == OpenSRF::AppSession::CONNECTED();
359 delete $self->{session};
363 # -----------------------------------------------------------------------------
364 # commits the db session and destroys the session
365 # returns the status of the commit call
366 # -----------------------------------------------------------------------------
369 return unless $self->{xact_id};
370 my $stat = $self->xact_commit;
375 # -----------------------------------------------------------------------------
376 # clears all object data. Does not commit the db transaction.
377 # -----------------------------------------------------------------------------
381 $$self{$_} = undef for (keys %$self);
385 # -----------------------------------------------------------------------------
387 # -----------------------------------------------------------------------------
399 throw $err if ($err);
405 # -----------------------------------------------------------------------------
406 # Does a simple storage request
407 # -----------------------------------------------------------------------------
409 my( $self, $method, @params ) = @_;
413 my $argstr = __arg_to_string( (scalar(@params)) == 1 ? $params[0] : \@params);
414 my $locale = $self->session->session_locale;
416 $self->log(I, "request $locale $method $argstr");
418 if( ($self->{xact} or $always_xact) and
419 $self->session->state != OpenSRF::AppSession::CONNECTED() ) {
420 #$logger->error("CStoreEditor lost it's connection!!");
421 throw OpenSRF::EX::ERROR ("CStore connection timed out - transaction cannot continue");
427 my $req = $self->session->request($method, @params);
429 if($self->substream) {
430 $self->log(D,"running in substream mode");
432 while( my $resp = $req->recv(timeout => $self->timeout) ) {
433 push(@$val, $resp->content) if $resp->content and not $self->discard;
437 my $resp = $req->recv(timeout => $self->timeout);
440 $self->log(E, "request error $method : $argstr : $err");
442 $val = $resp->content if $resp;
450 $self->log(E, "request error $method : $argstr : $err");
458 my( $self, $bool ) = @_;
459 $self->{substream} = $bool if defined $bool;
460 return $self->{substream};
463 # -----------------------------------------------------------------------------
464 # discard response data instead of returning it to the caller. currently only
465 # works in conjunction with substream mode.
466 # -----------------------------------------------------------------------------
468 my( $self, $bool ) = @_;
469 $self->{discard} = $bool if defined $bool;
470 return $self->{discard};
474 # -----------------------------------------------------------------------------
475 # Sets / Returns the requestor object. This is set when checkauth succeeds.
476 # -----------------------------------------------------------------------------
478 my($self, $requestor) = @_;
479 $self->{requestor} = $requestor if $requestor;
480 return $self->{requestor};
485 # -----------------------------------------------------------------------------
486 # Holds the last data received from a storage call
487 # -----------------------------------------------------------------------------
489 my( $self, $data ) = @_;
490 $self->{data} = $data if defined $data;
491 return $self->{data};
495 # -----------------------------------------------------------------------------
496 # True if this perm has already been checked at this org
497 # -----------------------------------------------------------------------------
499 my( $self, $perm, $org ) = @_;
500 $self->{checked_perms}->{$org} = {}
501 unless $self->{checked_perms}->{$org};
502 my $checked = $self->{checked_perms}->{$org}->{$perm};
504 $self->{checked_perms}->{$org}->{$perm} = 1;
512 # -----------------------------------------------------------------------------
513 # Returns true if the requested perm is allowed. If the perm check fails,
514 # $e->event is set and undef is returned
515 # The perm user is $e->requestor->id and perm org defaults to the requestor's
517 # if perm is an array of perms, method will return true at the first allowed
518 # permission. If none of the perms are allowed, the perm_failure event
519 # is created with the last perm to fail
520 # -----------------------------------------------------------------------------
524 transform => 'permission.usr_has_perm',
534 my $OBJECT_PERM_QUERY = {
537 transform => 'permission.usr_has_object_perm',
548 my( $self, $perm, $org, $object, $hint ) = @_;
549 my $uid = $self->requestor->id;
550 $org ||= $self->requestor->ws_ou;
552 my $perms = (ref($perm) eq 'ARRAY') ? $perm : [$perm];
554 for $perm (@$perms) {
555 $self->log(I, "checking perms user=$uid, org=$org, perm=$perm");
560 # determine the ID field and json_hint from the object
561 my $id_field = $object->Identity;
562 $params = [$perm, $object->json_hint, $object->$id_field];
564 # we were passed an object-id and json_hint
565 $params = [$perm, $hint, $object];
567 push(@$params, $org) if $org;
568 $OBJECT_PERM_QUERY->{select}->{au}->[0]->{params} = $params;
569 $OBJECT_PERM_QUERY->{where}->{id} = $uid;
570 return 1 if $U->is_true($self->json_query($OBJECT_PERM_QUERY)->[0]->{has_perm});
573 $PERM_QUERY->{select}->{au}->[0]->{params} = [$perm, $org];
574 $PERM_QUERY->{where}->{id} = $uid;
575 return 1 if $U->is_true($self->json_query($PERM_QUERY)->[0]->{has_perm});
579 # set the perm failure event if the permission check returned false
580 my $e = OpenILS::Event->new('PERM_FAILURE', ilsperm => $perm, ilspermloc => $org);
586 # -----------------------------------------------------------------------------
587 # Returns the list of object IDs this user has object-specific permissions for
588 # -----------------------------------------------------------------------------
589 sub objects_allowed {
590 my($self, $perm, $obj_type) = @_;
592 my $perms = (ref($perm) eq 'ARRAY') ? $perm : [$perm];
595 for $perm (@$perms) {
597 select => {puopm => ['object_id']},
600 ppl => {field => 'id',fkey => 'perm'}
604 '+puopm' => {usr => $self->requestor->id, object_type => $obj_type},
605 '+ppl' => {code => $perm}
609 my $list = $self->json_query($query);
610 push(@ids, 0+$_->{object_id}) for @$list;
614 $trim{$_} = 1 for @ids;
615 return [ keys %trim ];
619 # -----------------------------------------------------------------------------
620 # checks the appropriate perm for the operation
621 # -----------------------------------------------------------------------------
623 my( $self, $ptype, $action, $org ) = @_;
624 $org ||= $self->requestor->ws_ou;
625 my $perm = $PERMS{$ptype}{$action};
627 return undef if $self->perm_checked($perm, $org);
628 return $self->event unless $self->allowed($perm, $org);
630 $self->log(I, "no perm provided for $ptype.$action");
637 # -----------------------------------------------------------------------------
638 # Logs update actions to the activity log
639 # -----------------------------------------------------------------------------
641 my( $self, $method, $type, $action, $arg ) = @_;
642 my $str = "$type.$action";
648 if ($OpenSRF::Application::shared_conf and
649 $OpenSRF::Application::shared_conf->shared and
650 $redact = $OpenSRF::Application::shared_conf->shared->log_protect and
651 ref($redact) eq 'ARRAY' and
652 grep { $method =~ /^$_/ } @{$redact}) {
654 # when API calls are marked as log-protect, avoid
655 # dumping the param object to the activity log.
656 $str .= " **DETAILS REDACTED**";
659 $str .= _prop_string($arg);
671 my @props = $obj->properties;
674 my $prop = $obj->$_() || "";
675 $prop = substr($prop, 0, 128) . "..." if length $prop > 131;
682 sub __arg_to_string {
684 return "" unless defined $arg;
685 if( UNIVERSAL::isa($arg, "Fieldmapper") ) {
686 my $idf = $arg->Identity;
687 return (defined $arg->$idf) ? $arg->$idf : '<new object>';
689 return OpenSRF::Utils::JSON->perl2JSON($arg);
694 # -----------------------------------------------------------------------------
695 # This does the actual storage query.
697 # 'search' calls become search_where calls and $arg can be a search hash or
698 # an array-ref of storage search options.
700 # 'retrieve' expects an id
701 # 'update' expects an object
702 # 'create' expects an object
703 # 'delete' expects an object
705 # All methods return true on success and undef on failure. On failure,
706 # $e->event is set to the generated event.
707 # Note: this method assumes that updating a non-changed object and
708 # thereby receiving a 0 from storage, is a successful update.
710 # The method will therefore return true so the caller can just do
711 # $e->update_blah($x) or return $e->event;
712 # The true value returned from storage for all methods will be stored in
713 # $e->data, until the next method is called.
715 # not-found events are generated on retrieve and serach methods.
716 # action=search methods will return [] (==true) if no data is found. If the
717 # caller is interested in the not found event, they can do:
718 # return $e->event unless @$results;
719 # -----------------------------------------------------------------------------
721 my( $self, $action, $type, $arg, $options ) = @_;
725 if( $action eq 'retrieve' ) {
726 if(! defined($arg) ) {
727 $self->log(W,"$action $type called with no ID...");
728 $self->event(_mk_not_found($type, $arg));
730 } elsif( ref($arg) =~ /Fieldmapper/ ) {
731 $self->log(D,"$action $type called with an object.. attempting Identity retrieval..");
732 my $idf = $arg->Identity;
737 my @arg = ( ref($arg) eq 'ARRAY' ) ? @$arg : ($arg);
738 my $method = $self->app.".direct.$type.$action";
740 if( $action eq 'search' ) {
741 $method .= '.atomic';
743 } elsif( $action eq 'batch_retrieve' ) {
745 $method =~ s/batch_retrieve/search/o;
746 $method .= '.atomic';
749 my $fmobj = "Fieldmapper::$tt";
750 my $ident_field = $fmobj->Identity;
752 if (ref $arg[0] eq 'ARRAY') {
753 # $arg looks like: ([1, 2, 3], {search_args})
754 @arg = ( { $ident_field => $arg[0] }, @arg[1 .. $#arg] );
756 # $arg looks like: [1, 2, 3]
757 @arg = ( { $ident_field => $arg } );
760 } elsif( $action eq 'retrieve_all' ) {
762 $method =~ s/retrieve_all/search/o;
765 my $fmobj = "Fieldmapper::$tt";
766 @arg = ( { $fmobj->Identity => { '!=' => undef } } );
767 $method .= '.atomic';
770 $method =~ s/search/id_list/o if $options->{idlist};
772 $method =~ s/\.atomic$//o if $self->substream($$options{substream} || 0);
773 $self->timeout($$options{timeout});
774 $self->discard($$options{discard});
776 # remove any stale events
779 if( $action eq 'update' or $action eq 'delete' or $action eq 'create' ) {
780 if(!($self->{xact} or $always_xact)) {
781 $logger->error("Attempt to update DB while not in a transaction : $method");
782 throw OpenSRF::EX::ERROR ("Attempt to update DB while not in a transaction : $method");
784 $self->log_activity($method, $type, $action, $arg);
787 if($$options{checkperm}) {
788 my $a = ($action eq 'search') ? 'retrieve' : $action;
789 my $e = $self->_checkperm($type, $a, $$options{permorg});
800 $obj = $self->request($method, @arg);
801 } catch Error with { $err = shift; };
805 $self->log(I, "request returned no data : $method");
807 if( $action eq 'retrieve' ) {
808 $self->event(_mk_not_found($type, $arg));
810 } elsif( $action eq 'update' or
811 $action eq 'delete' or $action eq 'create' ) {
812 my $evt = OpenILS::Event->new(
813 'DATABASE_UPDATE_FAILED', payload => $arg, debug => "$err" );
819 OpenILS::Event->new( 'DATABASE_QUERY_FAILED',
820 payload => $arg, debug => "$err" ));
827 if( $action eq 'create' and $obj == 0 ) {
828 my $evt = OpenILS::Event->new(
829 'DATABASE_UPDATE_FAILED', payload => $arg, debug => "$err" );
834 # If we havn't dealt with the error in a nice way, go ahead and throw it
837 OpenILS::Event->new( 'DATABASE_QUERY_FAILED',
838 payload => $arg, debug => "$err" ));
842 if( $action eq 'search' ) {
843 $self->log(I, "$type.$action : returned ".scalar(@$obj). " result(s)");
844 $self->event(_mk_not_found($type, $arg)) unless @$obj;
847 if( $action eq 'create' ) {
848 my $idf = $obj->Identity;
849 $self->log(I, "created a new $type object with Identity " . $obj->$idf);
850 $arg->$idf($obj->$idf);
853 $self->data($obj); # cache the data for convenience
855 return ($obj) ? $obj : 1;
860 my( $type, $arg ) = @_;
861 (my $t = $type) =~ s/\./_/og;
863 return OpenILS::Event->new("${t}_NOT_FOUND", payload => $arg);
868 # utility method for loading
872 $str =~ s/Fieldmapper:://o;
878 # -------------------------------------------------------------
879 # Load up the methods from the FM classes
880 # -------------------------------------------------------------
883 no warnings; # Here we potentially redefine subs via eval
884 my $map = $Fieldmapper::fieldmap;
885 for my $object (keys %$map) {
886 my $obj = __fm2meth($object, '_');
887 my $type = __fm2meth($object, '.');
888 foreach my $command (qw/ update retrieve search create delete batch_retrieve retrieve_all /) {
889 eval "sub ${command}_$obj {return shift()->runmethod('$command', '$type', \@_);}\n";
891 # TODO: performance test against concatenating a big string of all the subs and eval'ing only ONCE.
895 init(); # Add very many subs to this namespace
898 my( $self, $arg, $options ) = @_;
900 my @arg = ( ref($arg) eq 'ARRAY' ) ? @$arg : ($arg);
901 my $method = $self->app.'.json_query.atomic';
902 $method =~ s/\.atomic$//o if $self->substream($$options{substream} || 0);
904 $self->timeout($$options{timeout});
905 $self->discard($$options{discard});
911 $obj = $self->request($method, @arg);
912 } catch Error with { $err = shift; };
916 OpenILS::Event->new( 'DATABASE_QUERY_FAILED',
917 payload => $arg, debug => "$err" ));
921 $self->log(I, "json_query : returned ".scalar(@$obj). " result(s)") if (ref($obj));