Q/ReliableFIFO/CLI.pm untested

filter: Statementstmt 0.0% 0 / 245 Branchbran 0.0% 0 / 108 Conditioncond 0.0% 0 / 38 MC/DCmcdc 0.0% 0 / 23 Subroutinesub 0.0% 0 / 22 Podpod 0.0% 0 / 13 totaltotal 0.0% 0 / 449 CC 55 SCAR 54.4
CC
55
Cov
0%
run
650.0
mv
56.0
newpath
42.0
CRAP 229.7
1 #!/usr/bin/env perl
2 package Queue::Q::ReliableFIFO::CLI;
3 use strict;
4 use Redis;
5 use Term::ReadLine;
6 use Data::Dumper;
7 use JSON::XS;
8 use File::Slurp;
9 use Carp qw(croak);
10  
11 use Queue::Q::ReliableFIFO::Redis;
12 use Class::XSAccessor {
13 constructor => 'new',
14 getters => [qw(conn prompt path redis server port db)],
15 setters => {
16 set_conn => 'conn',
17 set_prompt => 'prompt',
18 set_path => 'path',
19 set_redis => 'redis',
20 set_server => 'server',
21 set_port => 'port',
22 set_db => 'db',
23 },
24 };
25  
26 # The path property has the following meaning:
27 #
28 # $path== undef -> not connected
29 # @$path==0 -> /
30 # @$path==1 -> /queue
31 # @$path==2 -> /queue/type
32  
33 my @all_types = (qw(main busy failed));
34 my %type = map { $_ => undef } @all_types;
35  
36 sub open {
37 my ($self, %params) = @_;
38 $params{server} || die "missing server\n";
39 $params{port} ||= 6379;
40 $params{db} ||= 0;
41 $self->set_conn( Redis->new(
42 reconnect => 60,
43 server => $params{server} . ':' . $params{port}));
44 $self->conn->select($params{db})
45 if $self->conn && exists $params{db} && $params{db};
46 $self->set_server($params{server});
47 $self->set_port($params{port});
48 $self->set_db($params{db});
49 $self->set_path($self->conn ? [] : undef);
50 }
51 sub close {
52 my $self = shift;
53 $self->set_conn(undef);
54 $self->set_path(undef);
55 }
56 sub newpath {
57 my ($self, $arg) = @_;
58 my @args = defined $arg ? split(/\//, $arg) : ();
59 if (! defined $self->path) {
60 croak("not connected");
61 }
62 my @path;
63 if (substr($arg,0,1) eq '/') {
64 @path = @args;
65 shift @path;
66 }
67 else {
68 @path = @{$self->path};
69 while (my $v = shift @args) {
70 if ($v eq '..') {
71 pop @path;
72 }
73 elsif ($v ne '.') {
74 push @path, $v;
75 }
76 }
77 }
78 return @path;
79 }
80 sub ls {
81 my $self = shift;
82 my $arg = shift;
83 my @path = $self->newpath($arg);
84 my $level= @path;
85 my ($queue, $type) = @path;
86  
87 if ($level == 0) {
88 my %q = map { $_ => undef }
89 map { s/_(?:main|busy|failed|time)$//; $_ }
90 grep{ /_/ }
91 map { $self->conn->keys('*' . '_' . $_) }
92 @all_types;
93 my @q = sort keys %q;
94 return @q;
95 }
96 elsif ($level == 1) {
97 return
98 map { sprintf "%7s: %d items",
99 $_, int($self->conn->llen($queue . '_' . $_))
100 }
101 @all_types;
102 }
103 elsif ($level == 2) {
104 # show 10 items at the consumer side of the queue
105 my $start = -10;
106 my $n = 9;
107 return reverse $self->conn->lrange(
108 $queue . "_$type", $start, $start + $n);
109 }
110 else {
111 print Dumper(\@path);
112 croak("never thought of this...");
113 }
114 }
115 sub cd {
116 my $self = shift;
117 my $arg = shift;
118 my @path = $self->newpath($arg);
119 my @oldpath = @{$self->path};
120  
121 if (defined $path[0] && $path[0] ne $oldpath[0]) {
122 $self->set_redis(Queue::Q::ReliableFIFO::Redis->new(
123 redis_conn => $self->conn,
124 server => $self->server,
125 port => $self->port,
126 queue_name => $path[0]));
127 }
128 $self->set_path(\@path);
129 }
130 sub change_db {
131 my ($self, $db) = @_;
132 $db = int($db);
133 my $ret = $self->conn->select($db);
134 if ($ret) {
135 $self->set_db($db);
136 $self->set_path([]);
137 }
138 }
139 sub mv {
140 my ($self, $from, $to, $limit) = @_;
141 my @from = $self->newpath($from);
142 my @to = $self->newpath($to);
143 die "$from[1]? expected main|busy|time|failed\n" if !exists $type{$from[1]};
144 die "$to[1]? expected main|busy|time|failed\n" if !exists $type{$to[1]};
145 die "Path length should be 2: " . join('/',@from) . "\n" if @from != 2;
146 die "Path length should be 2: " . join('/',@to) . "\n" if @to != 2;
147 die "from and to are the same\n" if join('',@from) eq join('',@to);
148  
149 my $conn = $self->conn;
150 my $count = 0;
151 my $redis_from = join('_', @from);
152 my $redis_to = join('_', @to);
153 while ($conn->rpoplpush($redis_from, $redis_to)) {
154 $count++;
155 last if ($limit && $count >= $limit);
156 }
157 return $count;
158 }
159 sub cp {
160 my ($self, $from, $to, $limit) = @_;
161 my @from = $self->newpath($from);
162 my @to = $self->newpath($to);
163 die "$from[1]? expected main|busy|time|failed\n" if !exists $type{$from[1]};
164 die "$to[1]? expected main|busy|time|failed\n" if !exists $type{$to[1]};
165 die "Path length should be 2: " . join('/',@from) . "\n" if @from != 2;
166 die "Path length should be 2: " . join('/',@to) . "\n" if @to != 2;
167 my $conn = $self->conn;
168 my $redis_from = join('_', @from);
169 my $redis_to = join('_', @to);
170  
171 my $length= $conn->llen($redis_from);
172 my @elements = $conn->lrange($redis_from, 0, ($limit || $length ) - 1 );
173 $conn->rpush($redis_to, @elements) if @elements;
174 return scalar @elements;
175 }
176  
177 sub rm {
178 my ($self, $dir, $limit) = @_;
179 my @dir = $self->newpath($dir);
180 die "not a complete path\n" if (@dir != 2);
181 my $redisname = join '_', @dir;
182 my $conn = $self->conn;
183 my $count = 0;
184 if ($limit) {
185 while ($conn->rpop($redisname)) {
186 $count++;
187 last if ($count >= $limit);
188 }
189 }
190 else {
191 $self->conn->multi;
192 $self->conn->llen($redisname);
193 $self->conn->del($redisname);
194 ($count) = $self->conn->exec;
195 }
196 return $count;
197 }
198 sub who {
199 my $self = shift;
200 return $self->conn->client_list();
201 }
202 sub cleanup {
203 my ($self, $timeout, $action) = @_;
204 die "not connected\n" if !defined $self->path;
205 die "command not available here\n" if @{$self->path} < 1;
206 my @items = $self->{redis}->handle_expired_items($timeout, $action);
207 return scalar @items;
208 }
209 sub show_prompt {
210 my $self = shift;
211 my $s = $self->server;
212 my $p = $self->port;
213 my $d = $self->db;
214 my $path = $self->path;
215 my $pathstr = defined $path ? '/' . join('/', @$path) : '';
216 my $prompt;
217 if (! defined $path) { $prompt = ''; }
218 else { $prompt = "$s:$p (db=$d) \[ $pathstr \]" }
219  
220 return sprintf '%s:%s-> ', FIFO => $prompt;
221 }
222  
223 sub run {
224 my ($self, %params) = @_;
225 $| = 1;
226  
227 my @history;
228  
229 # take settings from previous session
230 my $conf_file = "$ENV{HOME}/.reliablefifo";
231 my %conf;
232 if (!$params{ignore_config_file} and -f $conf_file) {
233 %conf = %{decode_json(read_file($conf_file))};
234 $self->open(server => $conf{server}, port => $conf{port})
235 if exists $conf{server} && exists $conf{port};
236 push(@history, @{$conf{history}}) if exists $conf{history};
237 my ($queue, $type) = @{$conf{path}||[]};
238 $self->cd($queue) if $queue;
239 $self->cd($type) if $type;
240 }
241 my $quit = sub {
242 print "\n";
243 # save setting for next session
244 my %conf = ();
245 if (defined $self->path) {
246 $conf{server} = $self->server;
247 $conf{port} = $self->port;
248 $conf{db} = $self->db;
249 $conf{path} = $self->path;
250 }
251 $conf{history} = \@history;
252 write_file($conf_file, encode_json(\%conf));
253  
254 exit 0;
255 };
256  
257 my %commands = map { $_ => undef } (qw(
258 open
259 ls
260 cd
261 close
262 db
263 mv
264 cp
265 rm
266 who
267 quit
268 exit
269 hist
270 cleanup
271 ?
272 ));
273 my %help = (
274 0 => ["open <server> [<port> [<db>]]"],
275 1 => [
276 "ls [<path>]",
277 "cd <path>",
278 "mv <path-from> <path-to> [<limit>]",
279 "cp <path-from> <path-to> [<limit>]",
280 "cleanup <timeout> <(requeue|fail|drop)>",
281 'rm <path> [<limit>]',
282 'db <db>',
283 'close',
284 ],
285 );
286 push(@{$help{$_}}, ("?", "who", "hist", "quit")) for (0 .. 3);
287  
288 my $ver = join ".", map {ord} split(//, $^V);
289 my $term = Term::ReadLine->new("perl $ver");
290 $term->addhistory($_) for map {chomp; $_} @history;
291 $term->ornaments( join ',' => qw/ md me /, undef, undef );
292  
293 print { $term->OUT } "Type '?' for help\n";
294  
295 while(1) {
296 my $line = $term->readline($self->show_prompt);
297 last if not defined $line;
298 chomp $line;
299  
300 $line and push @history, $line;
301  
302 # deal with the command
303 my ($cmd, @args) = split /\s+/, $line;
304 if ($cmd) {
305 if (exists $commands{$cmd}) {
306 eval {
307 if ($cmd eq "open") {
308 $self->open(server => $args[0],
309 port => $args[1],
310 db => $args[2]);
311 }
312 elsif ($cmd eq "cd") {
313 $self->cd(@args);
314 }
315 elsif ($cmd eq "db") {
316 $self->change_db(@args);
317 }
318 elsif ($cmd eq "rm") {
319 printf { $term->OUT } "%d items removed\n", $self->rm(@args);
320 }
321 elsif ($cmd eq "mv") {
322 printf { $term->OUT } "%d items moved\n", $self->mv(@args);
323 }
324 elsif ($cmd eq "cp") {
325 printf { $term->OUT } "%d items copied\n", $self->cp(@args);
326 }
327 elsif ($cmd eq 'ls') {
328 print { $term->OUT } join("\n", $self->ls(@args)), "\n";
329 }
330 elsif ($cmd eq 'who') {
331 print { $term->OUT } join("\n", $self->who(@args)), "\n";
332 }
333 elsif ($cmd eq 'cleanup') {
334 my $n = $self->cleanup(@args);
335 printf { $term->OUT } "%d items affected\n", $n;
336 print { $term->OUT } "Try again after <timeout> seconds\n" if ($n ==0);
337 }
338 elsif ($cmd eq 'close') {
339 $self->close(), "\n";
340 }
341 elsif ($cmd eq 'quit' || $cmd eq 'exit') {
342 $quit->();
343 }
344 elsif ($cmd eq 'hist') {
345 print { $term->OUT } "\t", join("\n\t", @history), "\n";
346 }
347 elsif ($cmd eq '?') {
348 my $connected = defined $self->path ? 1 : 0;
349 print { $term->OUT } "available commands at this level:\n\t",
350 join("\n\t", @{$help{$connected}}), "\n";
351 }
352 1;
353 }
354 or do {
355 print { $term->OUT } $@;
356 }
357 }
358 else {
359 print { $term->OUT } "unknown command $cmd\n";
360 }
361 }
362 }
363 $quit->();
364 }
365  
366 1;
367  
368 __END__