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;
9 use OpenSRF::Utils::JSON;
10 use OpenSRF::Utils::Logger qw($logger);
11 my $U = "OpenILS::Application::AppUtils";
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'},
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};
33 # -----------------------------------------------------------------------------
34 # Export some useful functions
35 # -----------------------------------------------------------------------------
36 use vars qw(@EXPORT_OK %EXPORT_TAGS);
38 use base qw/Exporter/;
39 push @EXPORT_OK, ( 'new_editor', 'new_rstore_editor' );
40 %EXPORT_TAGS = ( funcs => [ qw/ new_editor new_rstore_editor / ] );
42 sub new_editor { return OpenILS::Utils::CStoreEditor->new(@_); }
44 sub new_rstore_editor {
45 my $e = OpenILS::Utils::CStoreEditor->new(@_);
46 $e->app('open-ils.reporter-store');
51 # -----------------------------------------------------------------------------
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';
62 # -----------------------------------------------------------------------------
64 # xact=><true> : creates a storage transaction
65 # authtoken=>$token : the login session key
66 # -----------------------------------------------------------------------------
68 my( $class, %params ) = @_;
69 $class = ref($class) || $class;
70 my $self = bless( \%params, $class );
71 $self->{checked_perms} = {};
77 my( $self, $app ) = @_;
78 $self->{app} = $app if $app;
79 $self->{app} = 'open-ils.cstore' unless $self->{app};
84 # -----------------------------------------------------------------------------
85 # Log the editor metadata along with the log string
86 # -----------------------------------------------------------------------------
88 my( $self, $lev, $str ) = @_;
92 } elsif ($self->{xact}) {
97 $s .= "0" unless $self->requestor;
98 $s .= $self->requestor->id if $self->requestor;
100 $logger->$lev("$s $str");
103 # -----------------------------------------------------------------------------
104 # Verifies the auth token and fetches the requestor object
105 # -----------------------------------------------------------------------------
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;
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'));
128 # -----------------------------------------------------------------------------
129 # Returns the last generated event
130 # -----------------------------------------------------------------------------
132 my( $self, $evt ) = @_;
133 $self->{event} = $evt if $evt;
134 return $self->{event};
137 # -----------------------------------------------------------------------------
138 # Destroys the transaction and disconnects where necessary,
139 # then returns the last event that occurred
140 # -----------------------------------------------------------------------------
148 # -----------------------------------------------------------------------------
149 # Clears the last caught event
150 # -----------------------------------------------------------------------------
153 $self->{event} = undef;
157 my( $self, $auth ) = @_;
158 $self->{authtoken} = $auth if $auth;
159 return $self->{authtoken};
164 $self->{timeout} = $to if defined $to;
165 return defined($self->{timeout}) ? $self->{timeout} : 60;
168 # -----------------------------------------------------------------------------
169 # fetches the session, creating if necessary. If 'xact' is true on this
170 # object, a db session is created
171 # -----------------------------------------------------------------------------
173 my( $self, $session ) = @_;
174 $self->{session} = $session if $session;
176 if(!$self->{session}) {
177 $self->{session} = OpenSRF::AppSession->create($self->app);
179 if( ! $self->{session} ) {
180 my $str = "Error creating cstore session with OpenSRF::AppSession->create()!";
182 throw OpenSRF::EX::ERROR ($str);
185 $self->{session}->connect if $self->{xact} or $self->{connect} or $always_xact;
186 $self->xact_start if $self->{xact} or $always_xact;
189 $xact_ed_cache{$self->{xact_id}} = $self if $always_xact;
190 return $self->{session};
194 # -----------------------------------------------------------------------------
195 # Starts a storage transaction
196 # -----------------------------------------------------------------------------
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;
206 # -----------------------------------------------------------------------------
207 # Commits a storage transaction
208 # -----------------------------------------------------------------------------
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};
218 # -----------------------------------------------------------------------------
219 # Rolls back a storage stransaction
220 # -----------------------------------------------------------------------------
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};
233 # -----------------------------------------------------------------------------
234 # Rolls back the transaction and disconnects
235 # -----------------------------------------------------------------------------
238 $self->xact_rollback;
239 delete $self->{xact};
245 $self->session->disconnect if $self->{session};
246 delete $self->{session};
250 # -----------------------------------------------------------------------------
251 # commits the db session and destroys the session
252 # -----------------------------------------------------------------------------
255 return unless $self->{xact_id};
257 $self->session->disconnect;
258 $self->{session} = undef;
261 # -----------------------------------------------------------------------------
262 # clears all object data. Does not commit the db transaction.
263 # -----------------------------------------------------------------------------
267 $$self{$_} = undef for (keys %$self);
271 # -----------------------------------------------------------------------------
273 # -----------------------------------------------------------------------------
282 # -----------------------------------------------------------------------------
283 # Does a simple storage request
284 # -----------------------------------------------------------------------------
286 my( $self, $method, @params ) = @_;
290 my $argstr = __arg_to_string( (scalar(@params)) == 1 ? $params[0] : \@params);
292 $self->log(I, "request $method : $argstr");
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");
303 my $req = $self->session->request($method, @params);
305 if($self->substream) {
306 $self->log(D,"running in substream mode");
308 while( my $resp = $req->recv(timeout => $self->timeout) ) {
309 push(@$val, $resp->content) if $resp->content;
313 my $resp = $req->recv(timeout => $self->timeout);
314 $val = $resp->content;
321 $self->log(E, "request error $method : $argstr : $err");
329 my( $self, $bool ) = @_;
330 $self->{substream} = $bool if defined $bool;
331 return $self->{substream};
335 # -----------------------------------------------------------------------------
336 # Sets / Returns the requstor object. This is set when checkauth succeeds.
337 # -----------------------------------------------------------------------------
339 my($self, $requestor) = @_;
340 $self->{requestor} = $requestor if $requestor;
341 return $self->{requestor};
346 # -----------------------------------------------------------------------------
347 # Holds the last data received from a storage call
348 # -----------------------------------------------------------------------------
350 my( $self, $data ) = @_;
351 $self->{data} = $data if defined $data;
352 return $self->{data};
356 # -----------------------------------------------------------------------------
357 # True if this perm has already been checked at this org
358 # -----------------------------------------------------------------------------
360 my( $self, $perm, $org ) = @_;
361 $self->{checked_perms}->{$org} = {}
362 unless $self->{checked_perms}->{$org};
363 my $checked = $self->{checked_perms}->{$org}->{$perm};
365 $self->{checked_perms}->{$org}->{$perm} = 1;
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
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 # -----------------------------------------------------------------------------
385 transform => 'permission.usr_has_perm',
396 my( $self, $perm, $org ) = @_;
397 my $uid = $self->requestor->id;
398 $org ||= $self->requestor->ws_ou;
400 my $perms = [$perm] unless ref($perm) eq 'ARRAY';
401 for $perm (@$perms) {
402 $self->log(I, "checking perms user=$uid, org=$org, perm=$perm");
404 # fill in the search hash
405 $PERM_QUERY->{select}->{au}->[0]->{params} = [$perm, $org];
406 $PERM_QUERY->{where}->{id} = $uid;
408 return 1 if $U->is_true($self->json_query($PERM_QUERY)->[0]->{has_perm});
411 # set the perm failure event if the permission check returned false
412 my $e = OpenILS::Event->new('PERM_FAILURE', ilsperm => $perm, ilspermloc => $org);
420 my($self, $userid, $org, $perm) = @_;
421 my $s = $U->storagereq(
422 "open-ils.storage.permission.user_has_perm", $userid, $perm, $org );
425 my $e = OpenILS::Event->new('PERM_FAILURE', ilsperm => $perm, ilspermloc => $org);
436 # -----------------------------------------------------------------------------
437 # checks the appropriate perm for the operation
438 # -----------------------------------------------------------------------------
440 my( $self, $ptype, $action, $org ) = @_;
441 $org ||= $self->requestor->ws_ou;
442 my $perm = $PERMS{$ptype}{$action};
444 return undef if $self->perm_checked($perm, $org);
445 return $self->event unless $self->allowed($perm, $org);
447 $self->log(I, "no perm provided for $ptype.$action");
454 # -----------------------------------------------------------------------------
455 # Logs update actions to the activity log
456 # -----------------------------------------------------------------------------
458 my( $self, $type, $action, $arg ) = @_;
459 my $str = "$type.$action";
460 $str .= _prop_string($arg);
468 my @props = $obj->properties;
471 my $prop = $obj->$_() || "";
472 $prop = substr($prop, 0, 128) . "..." if length $prop > 131;
479 sub __arg_to_string {
481 return "" unless defined $arg;
482 if( UNIVERSAL::isa($arg, "Fieldmapper") ) {
483 return (defined $arg->id) ? $arg->id : '<new object>';
485 return OpenSRF::Utils::JSON->perl2JSON($arg);
490 # -----------------------------------------------------------------------------
491 # This does the actual storage query.
493 # 'search' calls become search_where calls and $arg can be a search hash or
494 # an array-ref of storage search options.
496 # 'retrieve' expects an id
497 # 'update' expects an object
498 # 'create' expects an object
499 # 'delete' expects an object
501 # All methods return true on success and undef on failure. On failure,
502 # $e->event is set to the generated event.
503 # Note: this method assumes that updating a non-changed object and
504 # thereby receiving a 0 from storage, is a successful update.
506 # The method will therefore return true so the caller can just do
507 # $e->update_blah($x) or return $e->event;
508 # The true value returned from storage for all methods will be stored in
509 # $e->data, until the next method is called.
511 # not-found events are generated on retrieve and serach methods.
512 # action=search methods will return [] (==true) if no data is found. If the
513 # caller is interested in the not found event, they can do:
514 # return $e->event unless @$results;
515 # -----------------------------------------------------------------------------
517 my( $self, $action, $type, $arg, $options ) = @_;
521 if( $action eq 'retrieve' ) {
522 if(! defined($arg) ) {
523 $self->log(W,"$action $type called with no ID...");
524 $self->event(_mk_not_found($type, $arg));
526 } elsif( ref($arg) =~ /Fieldmapper/ ) {
527 $self->log(E,"$action $type called with an object.. attempting ID retrieval..");
532 my @arg = ( ref($arg) eq 'ARRAY' ) ? @$arg : ($arg);
533 my $method = $self->app.".direct.$type.$action";
535 if( $action eq 'search' ) {
536 $method .= '.atomic';
538 } elsif( $action eq 'batch_retrieve' ) {
540 @arg = ( { id => $arg } );
541 $method =~ s/batch_retrieve/search/o;
542 $method .= '.atomic';
544 } elsif( $action eq 'retrieve_all' ) {
546 $method =~ s/retrieve_all/search/o;
549 my $fmobj = "Fieldmapper::$tt";
550 @arg = ( { $fmobj->Identity => { '!=' => undef } } );
551 $method .= '.atomic';
554 $method =~ s/search/id_list/o if $options->{idlist};
556 $method =~ s/\.atomic$//o if $self->substream($$options{substream} || 0);
557 $self->timeout($$options{timeout});
559 # remove any stale events
562 if( $action eq 'update' or $action eq 'delete' or $action eq 'create' ) {
563 if(!$self->{xact_id}) {
564 $logger->error("Attempt to update DB while not in a transaction : $method");
565 throw OpenSRF::EX::ERROR ("Attempt to update DB while not in a transaction : $method");
567 $self->log_activity($type, $action, $arg);
570 if($$options{checkperm}) {
571 my $a = ($action eq 'search') ? 'retrieve' : $action;
572 my $e = $self->_checkperm($type, $a, $$options{permorg});
583 $obj = $self->request($method, @arg);
584 } catch Error with { $err = shift; };
588 $self->log(I, "request returned no data : $method");
590 if( $action eq 'retrieve' ) {
591 $self->event(_mk_not_found($type, $arg));
593 } elsif( $action eq 'update' or
594 $action eq 'delete' or $action eq 'create' ) {
595 my $evt = OpenILS::Event->new(
596 'DATABASE_UPDATE_FAILED', payload => $arg, debug => "$err" );
602 OpenILS::Event->new( 'DATABASE_QUERY_FAILED',
603 payload => $arg, debug => "$err" ));
610 if( $action eq 'create' and $obj == 0 ) {
611 my $evt = OpenILS::Event->new(
612 'DATABASE_UPDATE_FAILED', payload => $arg, debug => "$err" );
617 # If we havn't dealt with the error in a nice way, go ahead and throw it
620 OpenILS::Event->new( 'DATABASE_QUERY_FAILED',
621 payload => $arg, debug => "$err" ));
625 if( $action eq 'search' ) {
626 $self->log(I, "$type.$action : returned ".scalar(@$obj). " result(s)");
627 $self->event(_mk_not_found($type, $arg)) unless @$obj;
630 if( $action eq 'create' ) {
631 $self->log(I, "created a new $type object with ID " . $obj->id);
635 $self->data($obj); # cache the data for convenience
637 return ($obj) ? $obj : 1;
642 my( $type, $arg ) = @_;
643 (my $t = $type) =~ s/\./_/og;
645 return OpenILS::Event->new("${t}_NOT_FOUND", payload => $arg);
650 # utility method for loading
654 $str =~ s/Fieldmapper:://o;
660 # -------------------------------------------------------------
661 # Load up the methods from the FM classes
662 # -------------------------------------------------------------
663 my $map = $Fieldmapper::fieldmap;
664 for my $object (keys %$map) {
665 my $obj = __fm2meth($object,'_');
666 my $type = __fm2meth($object, '.');
668 my $update = "update_$obj";
670 "sub $update {return shift()->runmethod('update', '$type', \@_);}";
673 my $retrieve = "retrieve_$obj";
675 "sub $retrieve {return shift()->runmethod('retrieve', '$type', \@_);}";
678 my $search = "search_$obj";
680 "sub $search {return shift()->runmethod('search', '$type', \@_);}";
683 my $create = "create_$obj";
685 "sub $create {return shift()->runmethod('create', '$type', \@_);}";
688 my $delete = "delete_$obj";
690 "sub $delete {return shift()->runmethod('delete', '$type', \@_);}";
693 my $bretrieve = "batch_retrieve_$obj";
695 "sub $bretrieve {return shift()->runmethod('batch_retrieve', '$type', \@_);}";
698 my $retrieveall = "retrieve_all_$obj";
700 "sub $retrieveall {return shift()->runmethod('retrieve_all', '$type', \@_);}";
705 my( $self, $arg, $options ) = @_;
707 my @arg = ( ref($arg) eq 'ARRAY' ) ? @$arg : ($arg);
708 my $method = $self->app.'.json_query.atomic';
709 $method =~ s/\.atomic$//o if $self->substream($$options{substream} || 0);
715 $obj = $self->request($method, @arg);
716 } catch Error with { $err = shift; };
720 OpenILS::Event->new( 'DATABASE_QUERY_FAILED',
721 payload => $arg, debug => "$err" ));
725 $self->log(I, "json_query : returned ".scalar(@$obj). " result(s)");