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