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