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

Last change on this file since 1071 was 1071, checked in by nanardon, 12 years ago
  • rename options() to config() to clarify its role
  • Property svn:keywords set to Id Rev
File size: 11.7 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 checkpoint 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    1;
368}
369
370=head2 write_status
371
372Write savepoint file
373
374=cut
375
376sub write_status {
377    my ($self) = @_;
378    if (my $file = $self->GetFileName) {
379        open(my $handle, '>', $file) or do {
380            la_log(LA_ERR, "Cannot open status file %s for writing: %s",
381                $file, $!);
382            return;
383        };
384        my $oldfh = select($handle);
385        $self->OutputConfig();
386        select($oldfh);
387        close($handle); 
388        return 1;
389    }
390
391    return 0;
392}
393
394=head2 run_pre_synchro
395
396Run task done before synchronisation
397
398=cut
399
400sub run_pre_synchro {
401    my ($self, $env) = @_;
402
403    $env ||= {};
404    $env->{HOOK_TYPE} = 'PRE';
405
406    foreach my $base ($self->to) {
407        if ($base->config('presynchro')) {
408            la_log LA_DEBUG, "Executing base pre synchro `%s' for %s",
409                $base->config('presynchro'), $base->label;
410            exec_command(
411                $base->config('presynchro'),
412                {
413                    BASE => $base->label,
414                    BASETYPE => $base->type,
415                    %{ $env },
416                }
417            );
418        }
419    }
420
421    $self->{options}{pre} or return 1;
422
423    la_log(LA_DEBUG, "Running post synchro `%s'", $self->{options}{pre});
424
425    exec_command($self->{options}{post}, $env);
426}
427
428=head2 run_post_synchro
429
430Run task done after synchronisation
431
432=cut
433
434sub run_post_synchro {
435    my ($self, $env) = @_;
436   
437    $env ||= {};
438    $env->{HOOK_TYPE} = 'PRE';
439
440    foreach my $base ($self->to) {
441        if ($base->config('postsynchro')) {
442            la_log LA_DEBUG, "Executing base post synchro `%s' for %s",
443                $base->config('postsynchro'), $base->label;
444            exec_command(
445                $base->config('postsynchro'),
446                {
447                    BASE => $base->label,
448                    BASETYPE => $base->type,
449                    %{ $env },
450                }
451            );
452        }
453    }
454
455    $self->{options}{post} or return 1;
456
457    la_log(LA_DEBUG, "Running post synchro `%s'", $self->{options}{post});
458   
459    exec_command($self->{options}{post}, $env);
460}
461
462
4631;
464
465__END__
466# Below is stub documentation for your module. You'd better edit it!
467
468=head1 SEE ALSO
469
470Mention other useful documentation such as the documentation of
471related modules or operating system documentation (such as man pages
472in UNIX), or any relevant external documentation such as RFCs or
473standards.
474
475If you have a mailing list set up for your module, mention it here.
476
477If you have a web site set up for your module, mention it here.
478
479=head1 AUTHOR
480
481Thauvin Olivier, E<lt>olivier.thauvin@latmosipsl.frE<gt>
482
483=head1 COPYRIGHT AND LICENSE
484
485Copyright (C) 2009 by Thauvin Olivier
486
487This library is free software; you can redistribute it and/or modify
488it under the same terms as Perl itself, either Perl version 5.10.0 or,
489at your option, any later version of Perl 5 you may have available.
490
491
492=cut
Note: See TracBrowser for help on using the repository browser.