Feed.pm untested

filter: Statementstmt 0.0% 0 / 298 Branchbran 0.0% 0 / 72 Conditioncond 0.0% 0 / 87 MC/DCmcdc 0.0% 0 / 47 Subroutinesub 0.0% 0 / 53 Podpod 0.0% 0 / 34 totaltotal 0.0% 0 / 591 CC 37 SCAR 32.5
CC
37
Cov
0%
status
110.0
new
72.0
fill
30.0
CRAP 25.7
1 package File::Feed;
2  
3 use strict;
4 use warnings;
5  
6 use File::Kvpar;
7 use File::Kit;
8 use File::Feed::Source;
9 use File::Feed::Channel;
10 use File::Feed::Context;
11 use File::Feed::Sink;
12 use File::Feed::Util;
13 use File::Path qw(mkpath);
14 use File::Copy qw(move copy);
15 use File::Basename qw(basename dirname);
16 use String::Expando;
17  
18 use vars qw($VERSION);
19  
20 $VERSION = '0.03';
21  
22 # Feed statuses
23 use constant IDLE => '@idle';
24 use constant FILLING => '@filling';
25 use constant DRAINING => '@draining';
26 use constant ERROR => '@error';
27 use constant FROZEN => '@frozen';
28  
29 sub new {
30 my ($cls, $dir) = @_;
31 my $kv = File::Kvpar->new('+<', "$dir/feed.kv");
32 open my $lsfh, '+>>', "$dir/files.list" or die "Can't open files.list: $!";
33 #seek $lsfh, 0, 0;
34 #my @ls = <$lsfh>;
35 #chomp @ls;
36 my @elems = $kv->elements;
37 my ($feed, $source, @etc);
38 ($feed, @etc) = grep { $_->{'@'} eq 'feed' } @elems; die if !defined $feed || @etc;
39 ($source, @etc) = grep { $_->{'@'} eq 'source' } @elems; die if !defined $source || @etc;
40 my @sinks = grep { $_->{'@'} eq 'sink' } @elems;
41 my @channels = grep { $_->{'@'} eq 'channel' } @elems;
42 if ($feed->{'perl-class'}) {
43 $cls = $feed->{'perl-class'};
44 eval "use $cls; 1" or die "Can't use feed class $cls: $!";
45 }
46 @channels = ({
47 '@' => 'channel',
48 '#' => 'default',
49 'path' => '.',
50 'description' => 'default channel',
51 'filter' => 'glob:*',
52 }) if !@channels;
53 my $self = bless {
54 '_dir' => $dir,
55 %$feed,
56 '_feedkv' => $kv,
57 '_fileskv' => File::Kvpar->new('+<', "$dir/files.kv"),
58 '_random_buf' => '',
59 '_lsfh' => $lsfh,
60 }, $cls;
61 $self->{'_channels'} = [ map {
62 $self->_channel_instance(
63 '_source' => ($self->{'_source'} ||= $self->_source_instance(%$source)),
64 %$_,
65 )
66 } @channels ];
67 my %sinks;
68 foreach (@sinks) {
69 my $id = $_->{'#'};
70 $id = 'default' if !defined $id;
71 die "Duplicate sinks: $id" if exists $sinks{$id};
72 $sinks{$id} = $_;
73 }
74 ($sinks{'default'}) = (values %sinks) if scalar(keys %sinks) == 1;
75 $self->{'_sinks'} = \%sinks;
76 return $self;
77 }
78  
79 sub _source_instance {
80 my $self = shift;
81 return File::Feed::Source->new(@_, '_feed' => $self);
82 }
83  
84 sub _sink_instance {
85 my $self = shift;
86 return File::Feed::Sink->new(@_, '_feed' => $self);
87 }
88  
89 sub _channel_instance {
90 my $self = shift;
91 return File::Feed::Channel->new(@_, '_feed' => $self);
92 }
93  
94 sub _file_instance {
95 my $self = shift;
96 my %arg = @_;
97 my $chan = $self->channel($arg{'channel'} || die "Can't determine file channel");
98 return File::Feed::File->new(%arg, '_channel' => $chan, '_feed' => $self);
99 }
100  
101 sub new_files {
102 my ($self, %arg) = @_;
103 # What channels should we look at?
104 my %chan = map { $_->id => 1 } $self->channels(@{ $arg{'channels'} || [] });
105 # Within those channels, what files are new?
106 my $new_dir = $self->path('new');
107 my @new;
108 _crawl($new_dir, \@new);
109 s{^$new_dir/}{} for @new;
110 my %is_new = map { $_ => 1 } @new;
111 # Instantiate all files meeting those criteria
112 return map {
113 $self->_file_instance(%$_)
114 }
115 grep {
116 $is_new{$_->{'local-path'}}
117 &&
118 $chan{$_->{'channel'}}
119 }
120 $self->files;
121 }
122  
123 sub _crawl {
124 my ($dir, $list) = @_;
125 opendir my $fh, $dir or die;
126 my @files = grep { !/^\./ } readdir($fh);
127 closedir $fh;
128 foreach my $name (@files) {
129 my $path = "$dir/$name";
130 if (-d $path) {
131 _crawl($path, $list);
132 }
133 elsif (-f _) {
134 push @$list, $path;
135 }
136 }
137 }
138  
139 sub _group_files {
140 my ($self, $stash, @files) = @_;
141 my $expando = String::Expando->new;
142 my $now = strftime('%Y%m%dT%H%M%S', localtime);
143 my ($ymd, $hms) = split 'T', $now;
144 my %group;
145 foreach my $file (@files) {
146 my $chan = $file->channel;
147 my $c = $chan->id;
148 my %ctx = (
149 %$self,
150 %$chan,
151 'date' => $ymd,
152 'time' => $hms,
153 'datetime' => $now,
154 %$stash,
155 %$file,
156 );
157 my $sink = $ctx{'sink'};
158 $sink = "file:dropoff/" if !defined $sink;
159 my $g = $expando->expand($sink, {
160 %ctx,
161 'feed' => $self,
162 'channel' => $chan,
163 'file' => $file,
164 });
165 $group{$g} ||= {
166 'files' => [],
167 };
168 push @{ $group{$g}{'files'} }, $file;
169 }
170 return values %group;
171 }
172  
173 sub fill {
174 my ($self, %arg) = @_;
175 my $source = $self->source;
176 my $root = $self->path;
177 my @new;
178 my $ok = eval {
179 # Start filling
180 $self->status(FILLING) or die "Can't set status: not a feed?";
181 my %logged = map { $_->{'path'} => $_ } $self->files;
182 $source->begin($self);
183 my @channels = $self->channels(@{ $arg{'channels'} || [] });
184 my ($tmpd, $arcd, $newd) = map { $self->path($_) } (FILLING, qw(archive new));
185 my %mkpath;
186 my $lsfh = $self->{'_lsfh'};
187 foreach my $channel (@channels) {
188 my $dir = $channel->path;
189 my $ldir = $channel->local_path;
190 for ($tmpd) {
191 my $d = "$_/$ldir";
192 mkpath $d if !$mkpath{$d}++ || !-d $d;
193 }
194 my @fetched = $source->fetch(
195 'channel' => $channel,
196 'exclude' => \%logged,
197 'destination' => $tmpd,
198 );
199 foreach my $file (@fetched) {
200 my $path = $file->{'path'};
201 print $lsfh $path, "\n";
202 my $lpath = $file->{'local-path'};
203 my $tmp_path = "$tmpd/$lpath";
204 foreach ($arcd, $newd) {
205 my $other_path = "$_/$lpath";
206 my $d = dirname($other_path);
207 mkpath $d if !$mkpath{$d}++ || !-d $d;
208 link $tmp_path, $other_path or die "Can't link $tmp_path into $d";
209 }
210 unlink "$tmpd/$lpath" or die;
211 push @new, $self->_file_instance(
212 %$file,
213 'feed' => $self->id,
214 'source' => $source->uri,
215 'channel' => $channel->id,
216 );
217 }
218 }
219 $source->end;
220 $self->{'_fileskv'}->append(@new) if @new;
221 1;
222 };
223 $self->_cleanup;
224 $self->status($ok ? IDLE : ERROR);
225 return @new;
226 }
227  
228 sub drain {
229 my ($self, %arg) = @_;
230 my @new = $self->new_files(%arg);
231 return if !@new;
232 my @files;
233 my $ok = eval {
234 # Start draining
235 $self->status(DRAINING) or die "Can't set status: not a feed?";
236 my $s = $arg{'sink'};
237 my $uri_proto = $self->{'_sinks'}{$s || 'default'} || $s || die "Can't determine sink";
238 $uri_proto = $uri_proto->{'#'} if ref $uri_proto; # XXX Hack!
239 my %uri2files;
240 foreach my $file (@new) {
241 my $channel = $file->channel;
242 my $ctx = $self->context(
243 'source' => $file->source,
244 'channel' => $channel,
245 'file' => $file,
246 );
247 my $uri = $ctx->expand($uri_proto);
248 push @{ $uri2files{$uri} ||= [] }, $file;
249 }
250 my $new_dir = $self->path('new');
251 while (my ($uri, $files) = each %uri2files) {
252 my $sink = $self->_sink_instance(
253 'uri' => $uri,
254 'from' => $new_dir,
255 );
256 $sink->begin;
257 $sink->store(@$files);
258 $sink->end;
259 push @files, @$files;
260 }
261 1;
262 };
263 $self->_cleanup;
264 $self->status($ok ? IDLE : ERROR);
265 return @files;
266 }
267  
268 sub reset {
269 my ($self) = @_;
270 $self->status(IDLE, 1);
271 }
272  
273 sub freeze {
274 my ($self) = @_;
275 $self->status(FROZEN, 0, IDLE);
276 }
277  
278 sub thaw {
279 my ($self) = @_;
280 $self->status(IDLE, 0, FROZEN);
281 }
282  
283 sub context {
284 my ($self, %arg) = @_;
285 my %ctx;
286 _ctxatom($_, $arg{$_}, \%ctx) for qw(source channel sink file);
287 return File::Feed::Context->new(%ctx);
288 }
289  
290 sub _ctxatom {
291 my ($key, $val, $h) = @_;
292 return if !defined $val;
293 if (ref $val) {
294 eval {
295 $h->{$key} = $val->{'#'} if defined $val->{'#'};
296 while (my ($k, $v) = each %$val) {
297 _ctxatom("$key.$k", $v, $h) if $k =~ /^[^[:punct:]]/;
298 }
299 1;
300 } or $h->{$key} = $val;
301 }
302 else {
303 $h->{$key} = $val;
304 }
305 }
306  
307 sub path {
308 my $self = shift;
309 return join '/', $self->dir, @_;
310 }
311  
312 sub status {
313 my ($self, $new_status, $error_ok, $old_status_must_be) = @_;
314 my $dir = $self->dir;
315 my ($old_status, @etc) = map { basename($_) } glob($self->path('@*'));
316 die "No status set for feed $self->{'@'}" if !defined $old_status;
317 die "Multiple statuses set for feed $self->{'@'}" if @etc;
318 return $old_status if !defined $new_status;
319 if (defined $old_status_must_be) {
320 die "Feed is not ".substr($old_status_must_be,1) if $old_status ne $old_status_must_be;
321 }
322 elsif ($new_status ne IDLE) {
323 die "Feed is frozen" if $old_status eq FROZEN;
324 }
325 die "Feed is in error state" if $old_status eq ERROR && !$error_ok;
326 return $new_status if $old_status eq $new_status;
327 rename $self->path($old_status), $self->path($new_status)
328 or die "Can't set status for feed $self->{'@'}: $!";
329 return $old_status;
330 }
331  
332 sub id { $_[0]->{'#'} }
333 sub host { $_[0]->source->host }
334 sub root { $_[0]->source->root }
335 sub from { $_[0]->{'from'} || $_[0]->id }
336 sub to { $_[0]->{'to'} || $_[0]->id }
337 sub description { $_[0]->{'description'} }
338 sub user { $_[0]->{'user'} }
339 sub repeat { $_[0]->{'repeat'} }
340  
341 sub dir { $_[0]->{'_dir'} }
342 sub source { $_[0]->{'_source'} }
343  
344 sub channel {
345 my ($self, $chan) = @_;
346 my ($channel) = grep { $_->id eq $chan } $self->channels;
347 die "No such channel: $chan" if !defined $channel;
348 return $channel;
349 }
350  
351 sub channels {
352 my $self = shift;
353 my @chan = @{ $self->{'_channels'} };
354 return @chan if !@_;
355 my %chan;
356 foreach my $spec (@_) {
357 my $rx = File::Feed::Util::pat2rx($spec);
358 %chan = ( %chan, map { my $c = $_->id; $c =~ $rx ? ($c => $_) : () } @chan );
359 }
360 return values %chan;
361 #return grep { $chan{$_->id} } @chan;
362 }
363  
364 sub files {
365 my ($self) = @_;
366 return $self->{'_fileskv'}->elements;
367 }
368  
369 sub _shadow {
370 my ($self, $file) = @_;
371 my $n = 4;
372 my ($rand, $shadow);
373 my $dir = $self->path('shadow');
374 -d $dir or mkdir $dir or die "Can't mkdir $dir $!";
375 while (defined($rand = $self->_random_hex(8)) && !link $file, $shadow = $self->path('shadow', "shadow.$rand")) {
376 die "Can't create shadow file $shadow for $file: $!"
377 if --$n == 0;
378 }
379 push @{ $self->{'_shadow'} ||= [] }, [ $shadow, $file ];
380 return $shadow, $file;
381 }
382  
383 sub _cleanup {
384 my ($self) = @_;
385 my $shadow = $self->{'_shadow'};
386 foreach (@$shadow) {
387 my ($shadow, $original) = @$_;
388 unlink $shadow or link($shadow, $original) or die "Can't remove shadow file $shadow or relink it to $original: $!";
389 }
390 }
391  
392 sub _fill_random_buffer {
393 my ($self) = @_;
394 my $fh;
395 open $fh, '<', '/dev/urandom' or
396 open $fh, '<', '/dev/random' or die "Can't open /dev/*random: $!";
397 sysread $fh, $self->{'_random_buf'}, 32 or die "Can't read random bytes: $!";
398 }
399  
400 sub _random_hex {
401 my ($self, $n) = @_;
402 $n ||= 8;
403 $n = 16 if $n > 16;
404 $self->_fill_random_buffer if length($self->{'_random_buf'}) < $n;
405 return lc unpack('H*', substr($self->{'_random_buf'}, 0, $n, ''));
406 }
407  
408 1;
409  
410 =pod
411  
412 =head1 NAME
413  
414 File::Feed - gather files from an FTP server or other source
415  
416 =cut