source: trunk/LATMOS-Accounts/lib/LATMOS/Accounts/Synchro.pm @ 1315

Last change on this file since 1315 was 1206, checked in by nanardon, 11 years ago

use 'savepoint' word instead checkpoint

  • Property svn:keywords set to Id Rev
File size: 12.2 KB
Line 
1package LATMOS::Accounts::Synchro;
2
3use 5.010000;
4use strict;
5use warnings;
6use base qw(Config::IniFiles);
7use LATMOS::Accounts::Bases;
8use LATMOS::Accounts::Log;
9use LATMOS::Accounts::Utils qw(exec_command);
10use Fcntl qw(:flock);
11
12=head1 NAME
13
14LATMOS::Accounts::Synchro - Perl extension for blah blah blah
15
16=head1 SYNOPSIS
17
18  use LATMOS::Accounts;
19  blah blah blah
20
21=head1 DESCRIPTION
22
23Stub documentation for LATMOS::Accounts, created by h2xs. It looks like the
24author of the extension was negligent enough to leave the stub
25unedited.
26
27Blah blah blah.
28
29=head1 FUNCTIONS
30
31=cut
32
33our $VERSION = (q$Rev$ =~ /^Rev: (\d+) /)[0];
34
35=head2 new($from, $to, %options)
36
37Create a new synchronisation where $from and $to are LATMOS::Accounts::Base
38based objects. $to can be an array ref of objects.
39
40=cut
41
42sub new {
43    my ($class, $from, $to, %options) = @_;
44
45    my $state_file = $options{state_dir}
46        ? $options{state_dir} . '/synchronisation.ini'
47        : undef;
48    if ($state_file && ! -w $state_file) {
49        # don't exists, we have to create it
50        open(my $handle, '>', $state_file) or do {
51            la_log(LA_ERR, "Cannot open status file %s", $state_file);
52            return;
53        };
54        print $handle "[_default_]\n";
55        close($handle);
56    }
57
58    my $self = Config::IniFiles->new(
59        $state_file
60        ? (-file => $state_file)
61        : (),
62    );
63
64    if ($state_file && !$self->GetFileName) {
65        $self->SetFileName($state_file);
66    }
67   
68    $self->{from} = $from or do {
69        la_log(LA_ERR, "No database source");
70        return;
71    };
72    $self->{options} = { %options };
73
74    # allow ref and array ref of, eg
75    # to = $foo and $to = [ $foo, $bar ]
76    foreach (ref($to) eq 'ARRAY' ? @{ $to || []} : ($to)) {
77        push(@{$self->{to}}, $_);
78    }
79    bless($self, $class)
80}
81
82=head2 name
83
84Return the name of this synchronisation
85
86=cut
87
88sub name {
89    $_[0]->{options}{name}
90}
91
92=head2 from
93
94Return the base object source for this synchronisation
95
96=cut
97
98sub from {
99    my ($self) = @_;
100    return $self->{from}
101}
102
103=head2 to
104
105Return the list of base destination for this synchronisation
106
107=cut
108
109sub to {
110    my ($self) = @_;
111    return @{$self->{to} || []};
112}
113
114=head2 load_dest
115
116Try to loaded all base, return the count of filtrered base which cannot
117be loaded
118
119=cut
120
121sub load_dest {
122    my ($self) = @_;
123    my @loaded;
124    my $unloaded = 0;
125    foreach ($self->to) {
126        if($_->load) {
127            push(@loaded, $_);
128        } else {
129            $unloaded++;
130            warn "Cannot load $_";
131        }
132    }
133    $self->{to} = \@loaded;
134    return $unloaded;
135}
136
137=head2 enter_synch_mode
138
139Configure base for synchronisation
140
141=cut
142
143sub enter_synch_mode {
144    my ($self) = @_;
145    $self->from->load or return;
146    # if any cannot be loaded, return,
147    # TODO we need a way to force if some still can be sync
148    $self->load_dest and return;
149    my %state = ();
150    $state{$self->from->label} = $self->from->wexported(
151        $self->{options}{unexported} ? 1 : 0
152    );
153    foreach ($self->to) {
154        $state{$_->label} = $_->wexported(1);
155    }
156    la_log(LA_DEBUG, "Entering synch mode, old state: %s", join(', ', map {
157            "$_ => $state{$_}" } sort keys %state));
158    %state
159}
160
161=head2 leave_synch_mode (%state)
162
163Retore base to previous state
164
165=cut
166
167sub leave_synch_mode {
168    my ($self, %state) = @_;
169    la_log(LA_DEBUG, "Leaving synch mode");
170    $self->from->wexported($state{$self->from->label});
171    foreach my $base (grep { $_ } $self->to) {
172        $base->commit;
173        $base->wexported($state{$base->label});
174    }
175}
176
177=head2 lock
178
179Create a lock to denied another synchronisation to run
180
181=cut
182
183sub lock {
184    my ($self) = @_;
185
186    $self->{lock}{handle} and return 1;
187    la_log(LA_DEBUG, "Trying to lock (pid $$)");
188    if ($self->{options}{state_dir}) {
189        my $lockfile = $self->{options}{state_dir} . '/synclock';
190        open(my $handle, '>>', $lockfile) or return;
191        flock($handle, LOCK_EX);
192        $self->{lock}{handle} = $handle;
193        $self->{lock}{filename} = $lockfile;
194        la_log(LA_DEBUG, "lock done (pid $$)");
195        return 1;
196    } else { return 1 }
197}
198
199=head2 unlock
200
201Remove lock
202
203=cut
204
205sub unlock {
206    my ($self) = @_;
207    if (my $handle = $self->{lock}{handle}) {
208        close($handle);
209        delete($self->{lock}{handle});
210        unlink($self->{lock}{filename});
211        delete($self->{lock}{filename});
212        return 1;
213    }
214    return;
215}
216
217=head2 sync_object ($otype, $uid, %options)
218
219Synchronise object type C<$otype> named C<$uid>
220
221=cut
222
223sub sync_object {
224    my ($self, $otype, $uid, %options) = @_;
225
226    $self->lock or return;
227
228    my %state = $self->enter_synch_mode;
229   
230    my $res = $self->_sync_object($otype, $uid, %options);
231
232    $self->leave_synch_mode(%state);
233
234    $self->unlock;
235
236    $res;
237}
238
239sub _sync_object {
240    my ($self, $otype, $uid, %options) = @_;
241    foreach ($self->to) {
242        my $res = $_->sync_object_from($self->from, $otype, $uid, %options);
243        if (defined $res) {
244            la_log(LA_NOTICE, $_->label . " $uid ($otype) $res") if ($res);
245            return 1;
246        } else {
247            la_log(LA_ERR, "error synching $uid ($otype) to " . $_->label);
248            return;
249        }
250    }
251}
252
253=head2 process
254
255Run the syncronisation
256
257=cut
258
259sub process {
260    my ($self, %options) = @_;
261
262    $self->lock or return;
263   
264    if (!(my $res = $self->run_pre_synchro({}))) {
265        la_log(LA_ERR, "Pre synchro script failed, aborting");
266        $self->unlock;
267        return;
268    }
269
270    my %state = $self->enter_synch_mode;
271
272    # tracking current base revision:
273    $self->{current_rev} = $self->from->current_rev;
274
275    my %desterror;
276    my %existings;
277    my $updated = 0;
278    foreach my $destbase ($self->to) {
279        my %objlist;
280        foreach my $otype ($self->from->list_supported_objects) {
281            $destbase->is_supported_object($otype) or next;
282
283            $existings{$otype} ||= { map { $_ => 1 }
284                $self->from->list_objects($otype) };
285
286            # deleting non existing object in dest:
287            foreach ($destbase->list_objects($otype)) {
288                if(!$existings{$otype}{$_}) {
289                    if (my $res = $destbase->sync_object_from($self->from,
290                            $otype, $_, %options)) {
291                        la_log(LA_NOTICE, "%s::%s::%s => %s %s",
292                            $self->from->label, $otype, $_, $destbase->label, $res,
293                        );
294                        if ($destbase->is_transactionnal) {
295                            $destbase->commit;
296                        }
297                        $updated = 1;
298                    } else {
299                        if ($destbase->is_transactionnal) {
300                            $destbase->rollback;
301                        }
302                    }
303                }
304            }
305
306            @{$objlist{$otype}} = $self->from->list_objects_from_rev(
307                $otype,
308                $self->val($self->from->label, $destbase->label, 0),
309            );
310        }
311        foreach my $pass (1, 0) {
312            foreach my $otype ($destbase->ordered_objects) {
313                exists($objlist{$otype}) or next;
314                foreach (@{$objlist{$otype} || []}) {
315                    my $res = $destbase->sync_object_from($self->from, $otype, $_,
316                        %options, firstpass => $pass);
317                    if (defined $res) {
318                        if ($res) {
319                            la_log(LA_NOTICE, "%s::%s::%s => %s %s",
320                                $self->from->label, $otype, $_,
321                                $destbase->label, $res,
322                            );
323                            if ($destbase->is_transactionnal) {
324                                $destbase->commit;
325                            }
326                            $updated = 1;
327                        }
328                    } else {
329                        la_log(LA_ERR, "Cannot synch %s::%s::%s => %s",
330                            $self->from->label, $otype, $_,
331                            $destbase->label,
332                        );
333                        $desterror{$destbase->label} = 1;
334                        if ($destbase->is_transactionnal) {
335                            $destbase->rollback;
336                        }
337                    }
338
339                }
340            }
341        }
342    }
343
344    $self->leave_synch_mode(%state);
345    my $res = $self->run_post_synchro(
346        {
347            UPDATED => $updated || undef,
348        }
349    );
350    if ($res) {
351        foreach my $destbase ($self->to) {
352            # don't register savepoint on error
353            if ($desterror{$destbase->label}) { next; }
354            $self->newval($self->from->label, $destbase->label, $self->{current_rev});
355        }
356
357        if(!($self->{options}{nocreate} ||
358                $self->{options}{test})) {
359            $self->write_status;
360        }
361    } else {
362        la_log(LA_ERROR, "Not updating status because post script failed");
363    }
364
365    $self->unlock;
366
367    if (!$res) { # postscript failure
368        return;
369    } elsif (grep { $desterror{$_} } keys %desterror) {
370        # There were errors :\
371        return;
372    } else {
373        return 1;
374    }
375}
376
377=head2 write_status
378
379Write savepoint file
380
381=cut
382
383sub write_status {
384    my ($self) = @_;
385    if (my $file = $self->GetFileName) {
386        open(my $handle, '>', $file) or do {
387            la_log(LA_ERR, "Cannot open status file %s for writing: %s",
388                $file, $!);
389            return;
390        };
391        my $oldfh = select($handle);
392        $self->OutputConfig();
393        select($oldfh);
394        close($handle); 
395        return 1;
396    }
397
398    return 0;
399}
400
401=head2 reset_savepoint
402
403Reset savepoint in status file to force full synchronisation
404
405=cut
406
407sub reset_savepoint {
408    my ($self) = @_;
409    foreach my $destbase ($self->to) {
410            # don't register savepoint on error
411        $self->newval($self->from->label, $destbase->label, 0);
412    }
413    $self->write_status;
414}
415
416=head2 run_pre_synchro
417
418Run task done before synchronisation
419
420=cut
421
422sub run_pre_synchro {
423    my ($self, $env) = @_;
424
425    $env ||= {};
426    $env->{HOOK_TYPE} = 'PRE';
427
428    foreach my $base ($self->to) {
429        if ($base->config('presynchro')) {
430            la_log LA_DEBUG, "Executing base pre synchro `%s' for %s",
431                $base->config('presynchro'), $base->label;
432            exec_command(
433                $base->config('presynchro'),
434                {
435                    BASE => $base->label,
436                    BASETYPE => $base->type,
437                    %{ $env },
438                }
439            );
440        }
441    }
442
443    $self->{options}{pre} or return 1;
444
445    la_log(LA_DEBUG, "Running post synchro `%s'", $self->{options}{pre});
446
447    exec_command($self->{options}{post}, $env);
448}
449
450=head2 run_post_synchro
451
452Run task done after synchronisation
453
454=cut
455
456sub run_post_synchro {
457    my ($self, $env) = @_;
458   
459    $env ||= {};
460    $env->{HOOK_TYPE} = 'PRE';
461
462    foreach my $base ($self->to) {
463        if ($base->config('postsynchro')) {
464            la_log LA_DEBUG, "Executing base post synchro `%s' for %s",
465                $base->config('postsynchro'), $base->label;
466            exec_command(
467                $base->config('postsynchro'),
468                {
469                    BASE => $base->label,
470                    BASETYPE => $base->type,
471                    %{ $env },
472                }
473            );
474        }
475    }
476
477    $self->{options}{post} or return 1;
478
479    la_log(LA_DEBUG, "Running post synchro `%s'", $self->{options}{post});
480   
481    exec_command($self->{options}{post}, $env);
482}
483
484
4851;
486
487__END__
488# Below is stub documentation for your module. You'd better edit it!
489
490=head1 SEE ALSO
491
492Mention other useful documentation such as the documentation of
493related modules or operating system documentation (such as man pages
494in UNIX), or any relevant external documentation such as RFCs or
495standards.
496
497If you have a mailing list set up for your module, mention it here.
498
499If you have a web site set up for your module, mention it here.
500
501=head1 AUTHOR
502
503Thauvin Olivier, E<lt>olivier.thauvin@latmosipsl.frE<gt>
504
505=head1 COPYRIGHT AND LICENSE
506
507Copyright (C) 2009 by Thauvin Olivier
508
509This library is free software; you can redistribute it and/or modify
510it under the same terms as Perl itself, either Perl version 5.10.0 or,
511at your option, any later version of Perl 5 you may have available.
512
513
514=cut
Note: See TracBrowser for help on using the repository browser.