| 1 | package MYDan::Sync; | ||
| 2 | use strict; | ||
| 3 | use warnings; | ||
| 4 | use Carp; | ||
| 5 | use YAML::XS; | ||
| 6 | |||
| 7 | my $LEN = 65; | ||
| 8 | |||
| 9 | sub new | ||
| 10 | { | ||
| 11 | my ( $class, %this ) = @_; | ||
| 12 | map{ confess "$_ undef" unless $this{$_} }qw( conf code ); | ||
| 13 | bless \%this, ref $class || $class; | ||
| 14 | } | ||
| 15 | |||
| 16 | sub run | ||
| 17 | { | ||
| 18 | my $this = shift; | ||
| 19 | |||
| 20 | $this->{'stat'} = +{}; | ||
| 21 | $this->{'jobs'} = my $conf = eval{ YAML::XS::LoadFile $this->{conf} }; | ||
| 22 | if( $@ ){ print "[ERROR] load conf fail: $@\n"; return $this; } | ||
| 23 | |||
| 24 | ( grep{!$_}map{$this->do(0,$_)}sort keys %$conf ) | ||
| 25 | ? warn "FAIL\n" : warn "OK\n"; | ||
| 26 | |||
| 27 | print "#" x $LEN, "\n"; | ||
| 28 | return $this; | ||
| 29 | } | ||
| 30 | |||
| 31 | sub do | ||
| 32 | { | ||
| 33 | my ( $this, $deep, $name ) = @_; | ||
| 34 | |||
| 35 | my $dd = sprintf " " x (4*$deep); | ||
| 36 | print $dd,"=" x (($LEN-4*$deep)>0?($LEN-4*$deep):0), "\n"; | ||
| 37 | printf "%ssync: $name\n", $dd; | ||
| 38 | |||
| 39 | return $this->say( $dd, "stat", $name, $this->{'stat'}{$name} ) | ||
| 40 | if defined $this->{'stat'}{$name}; | ||
| 41 | |||
| 42 | my $conf = $this->{jobs}{$name}; | ||
| 43 | return $this->say( $dd, "load conf", $name, 0 ) | ||
| 44 | unless $conf && ref $conf eq 'HASH'; | ||
| 45 | |||
| 46 | my ( $sync, $code, $param ) | ||
| 47 | = @$conf{qw( sync code param )}; | ||
| 48 | |||
| 49 | map{ | ||
| 50 | return $this->say( $dd, "son", $name, 0 ) | ||
| 51 | unless $this->do( $deep +1, $_ ) | ||
| 52 | }@$sync if $sync && ref $sync eq 'ARRAY'; | ||
| 53 | |||
| 54 | my $jobs = do "$this->{code}/$code" if $code; | ||
| 55 | return say( $dd, "load code", 0 ) | ||
| 56 | unless ref $jobs eq 'CODE'; | ||
| 57 | |||
| 58 | my %param = ( | ||
| 59 | param => $param, | ||
| 60 | say => sub{ printf "${dd}%s.\n", shift; } | ||
| 61 | ); | ||
| 62 | |||
| 63 | map{ | ||
| 64 | return 1 if $this->say($dd,$_,$name,&$jobs(%param,task =>$_)) | ||
| 65 | }qw( check sync ); | ||
| 66 | return 0; | ||
| 67 | } | ||
| 68 | |||
| 69 | sub say | ||
| 70 | { | ||
| 71 | my ( $this, $dd , $info, $name, $stat ) = @_; | ||
| 72 | printf "${dd}$info %s.\n", $stat ? 'ok' : 'fail'; | ||
| 73 | return $this->{'stat'}{$name} = $stat; | ||
| 74 | } | ||
| 75 | |||
| 76 | 1; |