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 our $personality = 'open-ils.cstore';
54 my( $self, $app ) = @_;
55 $personality = $app if $app;
56 init() if $app; # rewrite if we changed personalities
64 while ( my $a = shift ) {
65 if ($a eq 'personality') {
66 $class->personality( shift );
72 # Exporter doesn't like you to call it's import() directly
73 return $class->export_to_level(1, $class, @super_args);
76 sub new_editor { return OpenILS::Utils::CStoreEditor->new(@_); }
78 sub new_rstore_editor {
79 my $e = OpenILS::Utils::CStoreEditor->new(@_);
80 $e->app('open-ils.reporter-store');
85 # -----------------------------------------------------------------------------
87 # -----------------------------------------------------------------------------
88 use constant E => 'error';
89 use constant W => 'warn';
90 use constant I => 'info';
91 use constant D => 'debug';
92 use constant A => 'activity';
96 # -----------------------------------------------------------------------------
98 # xact=><true> : creates a storage transaction
99 # authtoken=>$token : the login session key
100 # -----------------------------------------------------------------------------
102 my( $class, %params ) = @_;
103 $class = ref($class) || $class;
104 my $self = bless( \%params, $class );
105 $self->{checked_perms} = {};
116 my( $self, $app ) = @_;
117 $self->{app} = $app if $app;
118 $self->{app} = $self->personality unless $self->{app};
123 # -----------------------------------------------------------------------------
124 # Log the editor metadata along with the log string
125 # -----------------------------------------------------------------------------
127 my( $self, $lev, $str ) = @_;
131 } elsif ($self->{xact}) {
136 $s .= "0" unless $self->requestor;
137 $s .= $self->requestor->id if $self->requestor;
139 $logger->$lev("$s $str");
142 # -----------------------------------------------------------------------------
143 # Verifies the auth token and fetches the requestor object
144 # -----------------------------------------------------------------------------
147 $self->log(D, "checking auth token ".$self->authtoken);
149 my $content = $U->simplereq(
151 'open-ils.auth.session.retrieve', $self->authtoken, 1);
153 if(!$content or $U->event_code($content)) {
154 $self->event( ($content) ? $content : OpenILS::Event->new('NO_SESSION'));
158 $self->{authtime} = $content->{authtime};
159 return $self->{requestor} = $content->{userobj};
166 $cache = OpenSRF::Utils::Cache->new('global') unless $cache;
167 $self->log(D, "checking cached auth token ".$self->authtoken);
168 my $user = $cache->get_cache("oils_auth_".$self->authtoken);
169 return $self->{requestor} = $user->{userobj} if $user;
170 $self->event(OpenILS::Event->new('NO_SESSION'));
177 # -----------------------------------------------------------------------------
178 # Returns the last generated event
179 # -----------------------------------------------------------------------------
181 my( $self, $evt ) = @_;
182 $self->{event} = $evt if $evt;
183 return $self->{event};
186 # -----------------------------------------------------------------------------
187 # Destroys the transaction and disconnects where necessary,
188 # then returns the last event that occurred
189 # -----------------------------------------------------------------------------
200 # -----------------------------------------------------------------------------
201 # Clears the last caught event
202 # -----------------------------------------------------------------------------
205 $self->{event} = undef;
209 my($self, $died) = @_;
210 $self->{died} = $died if defined $died;
211 return $self->{died};
215 my( $self, $auth ) = @_;
216 $self->{authtoken} = $auth if $auth;
217 return $self->{authtoken};
221 my( $self, $auth ) = @_;
222 $self->{authtime} = $auth if $auth;
223 return $self->{authtime};
228 $self->{timeout} = $to if defined $to;
229 return defined($self->{timeout}) ? $self->{timeout} : 60;
232 # -----------------------------------------------------------------------------
233 # fetches the session, creating if necessary. If 'xact' is true on this
234 # object, a db session is created
235 # -----------------------------------------------------------------------------
237 my( $self, $session ) = @_;
238 $self->{session} = $session if $session;
240 # sessions can stick around longer than a single request/transaction.
241 # kill it if our default locale was altered since the last request
242 # and it does not match the locale of the existing session.
243 delete $self->{session} if
246 $self->{session}->session_locale ne $default_locale;
248 if(!$self->{session}) {
249 $self->{session} = OpenSRF::AppSession->create($self->app);
250 $self->{session}->session_locale($default_locale) if $default_locale;
252 if( ! $self->{session} ) {
253 my $str = "Error creating cstore session with OpenSRF::AppSession->create()!";
255 throw OpenSRF::EX::ERROR ($str);
258 $self->{session}->connect if $self->{xact} or $self->{connect} or $always_xact;
259 $self->xact_begin if $self->{xact} or $always_xact;
262 $xact_ed_cache{$self->{xact_id}} = $self if $always_xact and $self->{xact_id};
263 return $self->{session};
267 # -----------------------------------------------------------------------------
268 # Starts a storage transaction
269 # -----------------------------------------------------------------------------
272 return $self->{xact_id} if $self->{xact_id};
273 $self->session->connect unless $self->session->state == OpenSRF::AppSession::CONNECTED();
274 $self->log(D, "starting new database transaction");
275 unless($self->{xact_id}) {
276 my $stat = $self->request($self->app . '.transaction.begin');
277 $self->log(E, "error starting database transaction") unless $stat;
278 $self->{xact_id} = $stat;
279 if($self->authtoken) {
280 if(!$self->requestor) {
285 if($self->requestor) {
286 $user_id = $self->requestor->id;
287 $ws_id = $self->requestor->wsid;
289 $self->request($self->app . '.set_audit_info', $self->authtoken, $user_id, $ws_id);
293 return $self->{xact_id};
296 # -----------------------------------------------------------------------------
297 # Commits a storage transaction
298 # -----------------------------------------------------------------------------
301 return unless $self->{xact_id};
302 $self->log(D, "comitting db session");
303 my $stat = $self->request($self->app.'.transaction.commit');
304 $self->log(E, "error comitting database transaction") unless $stat;
305 delete $self->{xact_id};
306 delete $self->{xact};
310 # -----------------------------------------------------------------------------
311 # Rolls back a storage stransaction
312 # -----------------------------------------------------------------------------
315 return unless $self->{session} and $self->{xact_id};
316 $self->log(I, "rolling back db session");
317 my $stat = $self->request($self->app.".transaction.rollback");
318 $self->log(E, "error rolling back database transaction") unless $stat;
319 delete $self->{xact_id};
320 delete $self->{xact};
325 # -----------------------------------------------------------------------------
326 # Savepoint functions. If no savepoint name is provided, the same name is used
327 # for each successive savepoint, in which case only the last savepoint set can
328 # be released or rolled back.
329 # -----------------------------------------------------------------------------
332 my $name = shift || 'savepoint';
333 return unless $self->{session} and $self->{xact_id};
334 $self->log(I, "setting savepoint '$name'");
335 my $stat = $self->request($self->app.".savepoint.set", $name)
336 or $self->log(E, "error setting savepoint '$name'");
340 sub release_savepoint {
342 my $name = shift || 'savepoint';
343 return unless $self->{session} and $self->{xact_id};
344 $self->log(I, "releasing savepoint '$name'");
345 my $stat = $self->request($self->app.".savepoint.release", $name)
346 or $self->log(E, "error releasing savepoint '$name'");
350 sub rollback_savepoint {
352 my $name = shift || 'savepoint';
353 return unless $self->{session} and $self->{xact_id};
354 $self->log(I, "rollback savepoint '$name'");
355 my $stat = $self->request($self->app.".savepoint.rollback", $name)
356 or $self->log(E, "error rolling back savepoint '$name'");
361 # -----------------------------------------------------------------------------
362 # Rolls back the transaction and disconnects
363 # -----------------------------------------------------------------------------
369 $self->xact_rollback;
373 $ret = $self->disconnect
375 throw $err if ($err);
381 $self->session->disconnect if
383 $self->{session}->state == OpenSRF::AppSession::CONNECTED();
384 delete $self->{session};
388 # -----------------------------------------------------------------------------
389 # commits the db session and destroys the session
390 # returns the status of the commit call
391 # -----------------------------------------------------------------------------
394 return unless $self->{xact_id};
395 my $stat = $self->xact_commit;
400 # -----------------------------------------------------------------------------
401 # clears all object data. Does not commit the db transaction.
402 # -----------------------------------------------------------------------------
406 $$self{$_} = undef for (keys %$self);
410 # -----------------------------------------------------------------------------
412 # -----------------------------------------------------------------------------
424 throw $err if ($err);
430 # -----------------------------------------------------------------------------
431 # Does a simple storage request
432 # -----------------------------------------------------------------------------
434 my( $self, $method, @params ) = @_;
438 my $argstr = __arg_to_string( (scalar(@params)) == 1 ? $params[0] : \@params);
439 my $locale = $self->session->session_locale;
441 $self->log(I, "request $locale $method $argstr");
443 if( ($self->{xact} or $always_xact) and
444 $self->session->state != OpenSRF::AppSession::CONNECTED() ) {
445 #$logger->error("CStoreEditor lost it's connection!!");
446 throw OpenSRF::EX::ERROR ($self->app." connection timed out - transaction cannot continue");
452 my $req = $self->session->request($method, @params);
454 if($self->substream) {
455 $self->log(D,"running in substream mode");
457 while( my $resp = $req->recv(timeout => $self->timeout) ) {
458 push(@$val, $resp->content) if $resp->content and not $self->discard;
462 my $resp = $req->recv(timeout => $self->timeout);
465 $self->log(E, "request error $method : $argstr : $err");
467 $val = $resp->content if $resp;
475 $self->log(E, "request error $method : $argstr : $err");
483 my( $self, $bool ) = @_;
484 $self->{substream} = $bool if defined $bool;
485 return $self->{substream};
488 # -----------------------------------------------------------------------------
489 # discard response data instead of returning it to the caller. currently only
490 # works in conjunction with substream mode.
491 # -----------------------------------------------------------------------------
493 my( $self, $bool ) = @_;
494 $self->{discard} = $bool if defined $bool;
495 return $self->{discard};
499 # -----------------------------------------------------------------------------
500 # Sets / Returns the requestor object. This is set when checkauth succeeds.
501 # -----------------------------------------------------------------------------
503 my($self, $requestor) = @_;
504 $self->{requestor} = $requestor if $requestor;
505 return $self->{requestor};
510 # -----------------------------------------------------------------------------
511 # Holds the last data received from a storage call
512 # -----------------------------------------------------------------------------
514 my( $self, $data ) = @_;
515 $self->{data} = $data if defined $data;
516 return $self->{data};
520 # -----------------------------------------------------------------------------
521 # True if this perm has already been checked at this org
522 # -----------------------------------------------------------------------------
524 my( $self, $perm, $org ) = @_;
525 $self->{checked_perms}->{$org} = {}
526 unless $self->{checked_perms}->{$org};
527 my $checked = $self->{checked_perms}->{$org}->{$perm};
529 $self->{checked_perms}->{$org}->{$perm} = 1;
537 # -----------------------------------------------------------------------------
538 # Returns true if the requested perm is allowed. If the perm check fails,
539 # $e->event is set and undef is returned
540 # The perm user is $e->requestor->id and perm org defaults to the requestor's
542 # if perm is an array of perms, method will return true at the first allowed
543 # permission. If none of the perms are allowed, the perm_failure event
544 # is created with the last perm to fail
545 # -----------------------------------------------------------------------------
549 transform => 'permission.usr_has_perm',
559 my $OBJECT_PERM_QUERY = {
562 transform => 'permission.usr_has_object_perm',
573 my( $self, $perm, $org, $object, $hint ) = @_;
574 my $uid = $self->requestor->id;
575 $org ||= $self->requestor->ws_ou;
577 my $perms = (ref($perm) eq 'ARRAY') ? $perm : [$perm];
579 for $perm (@$perms) {
580 $self->log(I, "checking perms user=$uid, org=$org, perm=$perm");
585 # determine the ID field and json_hint from the object
586 my $id_field = $object->Identity;
587 $params = [$perm, $object->json_hint, $object->$id_field];
589 # we were passed an object-id and json_hint
590 $params = [$perm, $hint, $object];
592 push(@$params, $org) if $org;
593 $OBJECT_PERM_QUERY->{select}->{au}->[0]->{params} = $params;
594 $OBJECT_PERM_QUERY->{where}->{id} = $uid;
595 return 1 if $U->is_true($self->json_query($OBJECT_PERM_QUERY)->[0]->{has_perm});
598 $PERM_QUERY->{select}->{au}->[0]->{params} = [$perm, $org];
599 $PERM_QUERY->{where}->{id} = $uid;
600 return 1 if $U->is_true($self->json_query($PERM_QUERY)->[0]->{has_perm});
604 # set the perm failure event if the permission check returned false
605 my $e = OpenILS::Event->new('PERM_FAILURE', ilsperm => $perm, ilspermloc => $org);
611 # -----------------------------------------------------------------------------
612 # Returns the list of object IDs this user has object-specific permissions for
613 # -----------------------------------------------------------------------------
614 sub objects_allowed {
615 my($self, $perm, $obj_type) = @_;
617 my $perms = (ref($perm) eq 'ARRAY') ? $perm : [$perm];
620 for $perm (@$perms) {
622 select => {puopm => ['object_id']},
625 ppl => {field => 'id',fkey => 'perm'}
629 '+puopm' => {usr => $self->requestor->id, object_type => $obj_type},
630 '+ppl' => {code => $perm}
634 my $list = $self->json_query($query);
635 push(@ids, 0+$_->{object_id}) for @$list;
639 $trim{$_} = 1 for @ids;
640 return [ keys %trim ];
644 # -----------------------------------------------------------------------------
645 # checks the appropriate perm for the operation
646 # -----------------------------------------------------------------------------
648 my( $self, $ptype, $action, $org ) = @_;
649 $org ||= $self->requestor->ws_ou;
650 my $perm = $PERMS{$ptype}{$action};
652 return undef if $self->perm_checked($perm, $org);
653 return $self->event unless $self->allowed($perm, $org);
655 $self->log(I, "no perm provided for $ptype.$action");
662 # -----------------------------------------------------------------------------
663 # Logs update actions to the activity log
664 # -----------------------------------------------------------------------------
666 my( $self, $method, $type, $action, $arg ) = @_;
667 my $str = "$type.$action";
673 if ($OpenSRF::Application::shared_conf and
674 $OpenSRF::Application::shared_conf->shared and
675 $redact = $OpenSRF::Application::shared_conf->shared->log_protect and
676 ref($redact) eq 'ARRAY' and
677 grep { $method =~ /^$_/ } @{$redact}) {
679 # when API calls are marked as log-protect, avoid
680 # dumping the param object to the activity log.
681 $str .= " **DETAILS REDACTED**";
684 $str .= _prop_string($arg);
696 my @props = $obj->properties;
699 my $prop = $obj->$_() || "";
700 $prop = substr($prop, 0, 128) . "..." if length $prop > 131;
707 sub __arg_to_string {
709 return "" unless defined $arg;
710 if( UNIVERSAL::isa($arg, "Fieldmapper") ) {
711 my $idf = $arg->Identity;
712 return (defined $arg->$idf) ? $arg->$idf : '<new object>';
714 return OpenSRF::Utils::JSON->perl2JSON($arg);
719 # -----------------------------------------------------------------------------
720 # This does the actual storage query.
722 # 'search' calls become search_where calls and $arg can be a search hash or
723 # an array-ref of storage search options.
725 # 'retrieve' expects an id
726 # 'update' expects an object
727 # 'create' expects an object
728 # 'delete' expects an object
730 # All methods return true on success and undef on failure. On failure,
731 # $e->event is set to the generated event.
732 # Note: this method assumes that updating a non-changed object and
733 # thereby receiving a 0 from storage, is a successful update.
735 # The method will therefore return true so the caller can just do
736 # $e->update_blah($x) or return $e->event;
737 # The true value returned from storage for all methods will be stored in
738 # $e->data, until the next method is called.
740 # not-found events are generated on retrieve and serach methods.
741 # action=search methods will return [] (==true) if no data is found. If the
742 # caller is interested in the not found event, they can do:
743 # return $e->event unless @$results;
744 # -----------------------------------------------------------------------------
746 my( $self, $action, $type, $hint, $arg, $options ) = @_;
750 if( $action eq 'retrieve' ) {
751 if(! defined($arg) ) {
752 $self->log(W,"$action $type called with no ID...");
753 $self->event(_mk_not_found($type, $arg));
755 } elsif( ref($arg) =~ /Fieldmapper/ ) {
756 $self->log(D,"$action $type called with an object.. attempting Identity retrieval..");
757 my $idf = $arg->Identity;
762 my @arg = ( ref($arg) eq 'ARRAY' ) ? @$arg : ($arg);
764 if ($self->personality eq 'open-ils.pcrud') {
765 $method = $self->app.".$action.$hint";
767 $method = $self->app.".direct.$type.$action";
770 if( $action eq 'search' ) {
771 $method .= '.atomic';
773 } elsif( $action eq 'batch_retrieve' ) {
775 $method =~ s/batch_retrieve/search/o;
776 $method .= '.atomic';
779 my $fmobj = "Fieldmapper::$tt";
780 my $ident_field = $fmobj->Identity;
782 if (ref $arg[0] eq 'ARRAY') {
783 # $arg looks like: ([1, 2, 3], {search_args})
784 @arg = ( { $ident_field => $arg[0] }, @arg[1 .. $#arg] );
786 # $arg looks like: [1, 2, 3]
787 @arg = ( { $ident_field => $arg } );
790 } elsif( $action eq 'retrieve_all' ) {
792 $method =~ s/retrieve_all/search/o;
795 my $fmobj = "Fieldmapper::$tt";
796 @arg = ( { $fmobj->Identity => { '!=' => undef } } );
797 $method .= '.atomic';
800 $method =~ s/search/id_list/o if $options->{idlist};
802 $method =~ s/\.atomic$//o if $self->substream($$options{substream} || 0);
803 $self->timeout($$options{timeout});
804 $self->discard($$options{discard});
806 # remove any stale events
809 if( $action eq 'update' or $action eq 'delete' or $action eq 'create' ) {
810 if(!($self->{xact} or $always_xact)) {
811 $logger->error("Attempt to update DB while not in a transaction : $method");
812 throw OpenSRF::EX::ERROR ("Attempt to update DB while not in a transaction : $method");
814 $self->log_activity($method, $type, $action, $arg);
817 # only check perms this way in non-pcrud mode
818 if($self->personality ne 'open-ils.pcrud' and $$options{checkperm}) {
819 my $a = ($action eq 'search') ? 'retrieve' : $action;
820 my $e = $self->_checkperm($type, $a, $$options{permorg});
830 # in PCRUD mode, if no authtoken is set, fall back to anonymous.
831 unshift(@arg, ($self->authtoken || 'ANONYMOUS'))
832 if ($self->personality eq 'open-ils.pcrud');
835 $obj = $self->request($method, @arg);
836 } catch Error with { $err = shift; };
840 $self->log(I, "request returned no data : $method");
842 if( $action eq 'retrieve' ) {
843 $self->event(_mk_not_found($type, $arg));
845 } elsif( $action eq 'update' or
846 $action eq 'delete' or $action eq 'create' ) {
847 my $evt = OpenILS::Event->new(
848 'DATABASE_UPDATE_FAILED', payload => $arg, debug => "$err" );
854 OpenILS::Event->new( 'DATABASE_QUERY_FAILED',
855 payload => $arg, debug => "$err" ));
862 if( $action eq 'create' and $obj == 0 ) {
863 my $evt = OpenILS::Event->new(
864 'DATABASE_UPDATE_FAILED', payload => $arg, debug => "$err" );
869 # If we havn't dealt with the error in a nice way, go ahead and throw it
872 OpenILS::Event->new( 'DATABASE_QUERY_FAILED',
873 payload => $arg, debug => "$err" ));
877 if( $action eq 'search' ) {
878 $self->log(I, "$method: returned ".scalar(@$obj). " result(s)");
879 $self->event(_mk_not_found($type, $arg)) unless @$obj;
882 if( $action eq 'create' ) {
883 my $idf = $obj->Identity;
884 $self->log(I, "created a new $type object with Identity " . $obj->$idf);
885 $arg->$idf($obj->$idf);
888 $self->data($obj); # cache the data for convenience
890 return ($obj) ? $obj : 1;
895 my( $type, $arg ) = @_;
896 (my $t = $type) =~ s/\./_/og;
898 return OpenILS::Event->new("${t}_NOT_FOUND", payload => $arg);
903 # utility method for loading
907 $str =~ s/Fieldmapper:://o;
913 # -------------------------------------------------------------
914 # Load up the methods from the FM classes
915 # -------------------------------------------------------------
918 no warnings; # Here we potentially redefine subs via eval
919 my $map = $Fieldmapper::fieldmap;
920 for my $object (keys %$map) {
921 my $obj = __fm2meth($object, '_');
922 my $type = __fm2meth($object, '.');
923 my $hint = $object->json_hint;
924 foreach my $command (qw/ update retrieve search create delete batch_retrieve retrieve_all /) {
925 eval "sub ${command}_$obj {return shift()->runmethod('$command', '$type', '$hint', \@_);}\n";
927 # TODO: performance test against concatenating a big string of all the subs and eval'ing only ONCE.
931 init(); # Add very many subs to this namespace
934 my( $self, $arg, $options ) = @_;
936 if( $self->personality eq 'open-ils.pcrud' ) {
937 $self->log(E, "json_query is not allowed when using the ".
938 "open-ils.pcrud personality of CStoreEditor: " .Dumper($arg));
942 'JSON_QUERY_NOT_ALLOWED',
943 attempted_query => $arg,
944 debug => "json_query is not allowed when using the open-ils.pcrud personality of CStoreEditor"
951 my @arg = ( ref($arg) eq 'ARRAY' ) ? @$arg : ($arg);
952 my $method = $self->app.'.json_query.atomic';
953 $method =~ s/\.atomic$//o if $self->substream($$options{substream} || 0);
955 $self->timeout($$options{timeout});
956 $self->discard($$options{discard});
962 $obj = $self->request($method, @arg);
963 } catch Error with { $err = shift; };
967 OpenILS::Event->new( 'DATABASE_QUERY_FAILED',
968 payload => $arg, debug => "$err" ));
972 $self->log(I, "json_query : returned ".scalar(@$obj). " result(s)") if (ref($obj));