script/mq.pl untested

filter: Statementstmt 0.0% 0 / 173 Branchbran 0.0% 0 / 46 Conditioncond 0.0% 0 / 17 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 22 Podpod 0.0% 0 / 3 totaltotal 0.0% 0 / 261 CC 5 SCAR 16.2
CC
5
Cov
0%
parse_size
20.0
usage
6.0
version
2.0
CRAP 5.1
1 #!/usr/local/bin/perl
2 use POE;
3 use POE::Component::Logger;
4 use POE::Component::MessageQueue;
5 use POE::Component::MessageQueue::Storage::Default;
6 use POE::Component::MessageQueue::Storage::Memory;
7 use POE::Component::MessageQueue::Storage::BigMemory;
8 use POE::Component::MessageQueue::Storage::DBI;
9 use POE::Component::MessageQueue::Storage::Throttled;
10 use Getopt::Long;
11 use Devel::StackTrace;
12 use IO::File;
13 use Carp;
14 use POSIX qw(setsid strftime);
15 use strict;
16  
17 my $DATA_DIR = '/var/lib/perl_mq';
18 my $CONF_DIR = '/etc/perl_mq';
19 my $CONF_LOG = "$CONF_DIR/log.conf";
20  
21 my $port = 61613;
22 my $hostname = undef;
23 my $timeout = 4;
24 my $granularity;
25 my $throttle_max = 2;
26 my $pump_frequency;
27 my $background = 0;
28 my $debug_shell = 0;
29 my $pidfile;
30 my $show_version = 0;
31 my $show_usage = 0;
32 my $statistics = 0;
33 my $uuids = 1;
34 my $stat_interval = 10;
35 my $front_store = 'memory';
36 my $front_max;
37 my $storage = 'default';
38 my $crash_cmd = undef;
39 my $dbi_dsn = undef;
40 my $dbi_username = undef;
41 my $dbi_password = undef;
42 my $mq_id = '';
43  
44 GetOptions(
45 "port|p=i" => \$port,
46 "hostname|h=s" => \$hostname,
47 "timeout|i=i" => \$timeout,
48 "granularity=i" => \$granularity,
49 "storage=s" => \$storage,
50 "front-store|f=s" => \$front_store,
51 "front-max=s" => \$front_max,
52 "throttle|T=i" => \$throttle_max,
53 "pump-freq|Q=i" => \$pump_frequency,
54 "data-dir=s" => \$DATA_DIR,
55 "log-conf=s" => \$CONF_LOG,
56 "stats!" => \$statistics,
57 "uuids!" => \$uuids,
58 "dbi-dsn=s" => \$dbi_dsn,
59 "dbi-username=s" => \$dbi_username,
60 "dbi-password=s" => \$dbi_password,
61 "mq-id=s" => \$mq_id,
62 "stats-interval=i" => \$stat_interval,
63 "background|b" => \$background,
64 "debug-shell" => \$debug_shell,
65 "pidfile|p=s" => \$pidfile,
66 "crash-cmd=s" => \$crash_cmd,
67 "version|v" => \$show_version,
68 "help|h" => \$show_usage,
69 ) or usage(1);
70  
71 # byte kilo mega giga tera peta exa zetta yotta
72 my @size_units = qw(b k m g t p e z y);
73 my $size_pattern = '((?:\d*\.)?\d+)(['.join('',@size_units).']?)$';
74 my $size_regex = qr/$size_pattern/i;
75 sub parse_size
76 {
77 my $string = shift;
78 if ($string =~ $size_regex)
79 {
80 my ($number, $unit) = ($1, lc($2));
81 return $number unless $unit;
82 for(my $i = 0; $i < @size_units; $i++)
83 {
84 if ($unit eq $size_units[$i])
85 {
86 return $number * (1024**$i);
87 }
88 }
89 }
90 die "Unable to parse size: $string";
91 }
92  
93 sub version
94 {
95 print "POE::Component::MessageQueue version $POE::Component::MessageQueue::VERSION\n";
96 print "Copyright 2007-2011 David Snopek (http://www.hackyourlife.org)\n";
97 print "Copyright 2007, 2008 Paul Driver <frodwith\@gmail.com>\n";
98 print "Copyright 2007 Daisuke Maki <daisuke\@endeworks.jp>\n";
99 }
100  
101 sub usage
102 {
103 my $exit_level = shift;
104 my $X = ' ' x (length $0);
105 print <<"ENDUSAGE";
106 $0 [--port|-p <num>] [--hostname|-h <host>]
107 $X [--storage <str>]
108 $X [--front-store <str>] [--front-max <size>]
109 $X [--granularity <seconds>] [--nouuids]
110 $X [--timeout|-i <seconds>] [--throttle|-T <count>]
111 $X [--dbi-dsn <str>] [--mq-id <str>]
112 $X [--dbi-username <str>] [--dbi-password <str>]
113 $X [--pump-freq|-Q <seconds>]
114 $X [--data-dir <path_to_dir>] [--log-conf <path_to_file>]
115 $X [--stats-interval|-i <seconds>] [--stats]
116 $X [--pidfile|-p <path_to_file>] [--background|-b]
117 $X [--crash-cmd <path_to_script>]
118 $X [--debug-shell] [--version|-v] [--help|-h]
119  
120 SERVER OPTIONS:
121 --port -p <num> The port number to listen on (Default: 61613)
122 --hostname -h <host> The hostname of the interface to listen on
123 (Default: localhost)
124  
125 STORAGE OPTIONS:
126 --storage <str> Specify which overall storage engine to use. This
127 affects what other options are value. (can be
128 default or dbi)
129 --front-store -f <str> Specify which in-memory storage engine to use for
130 the front-store (can be memory or bigmemory).
131 --front-max <size> How much message body the front-store should cache.
132 This size is specified in "human-readable" format
133 as per the -h option of ls, du, etc. (ex. 2.5M)
134 --timeout -i <secs> The number of seconds to keep messages in the
135 front-store (Default: 4)
136 --pump-freq -Q <secs> How often (in seconds) to automatically pump each
137 queue. Set to zero to disable this timer entirely
138 (Default: 0)
139 --granularity <secs> How often (in seconds) Complex should check for
140 messages that have passed the timeout.
141 --[no]uuids Use (or do not use) UUIDs instead of incrementing
142 integers for message IDs. (Default: uuids)
143 --throttle -T <count> The number of messages that can be stored at once
144 before throttling (Default: 2)
145 --data-dir <path> The path to the directory to store data
146 (Default: /var/lib/perl_mq)
147 --log-conf <path> The path to the log configuration file
148 (Default: /etc/perl_mq/log.conf)
149  
150 --dbi-dsn <str> The database DSN when using --storage dbi
151 --dbi-username <str> The database username when using --storage dbi
152 --dbi-password <str> The database password when using --storage dbi
153 --mq-id <str> A string uniquely identifying this MQ when more
154 than one MQ use the DBI database for storage
155  
156 STATISTICS OPTIONS:
157 --stats If specified the, statistics information will be
158 written to \$DATA_DIR/stats.yml
159 --stats-interval <secs> Specifies the number of seconds to wait before
160 dumping statistics (Default: 10)
161  
162 DAEMON OPTIONS:
163 --background -b If specified the script will daemonize and run in the
164 background
165 --pidfile -p <path> The path to a file to store the PID of the process
166  
167 --crash-cmd <path> The path to a script to call when crashing.
168 A stacktrace will be printed to the script's STDIN.
169 (ex. 'mail root\@localhost')
170  
171 OTHER OPTIONS:
172 --debug-shell Run with POE::Component::DebugShell
173 --version -v Show the current version.
174 --help -h Show this usage message
175  
176 ENDUSAGE
177
178 exit($exit_level) if (defined $exit_level);
179 }
180  
181 if ( $show_version )
182 {
183 version;
184 exit 0;
185 }
186  
187 if ( $show_usage )
188 {
189 version;
190 print "\n";
191 usage(0);
192 }
193  
194 if ( not -d $DATA_DIR )
195 {
196 mkdir $DATA_DIR;
197  
198 if ( not -d $DATA_DIR )
199 {
200 die "Unable to create the data dir: $DATA_DIR";
201 }
202 }
203  
204 if ( $background )
205 {
206 # the simplest daemonize, ever.
207 defined(fork() && exit 0) or "Can't fork: $!";
208 setsid or die "Can't start a new session: $!";
209 open STDIN, '/dev/null' or die "Can't redirect STDIN from /dev/null: $!";
210 open STDOUT, '>/dev/null' or die "Can't redirect STDOUT to /dev/null: $!";
211 open STDERR, '>/dev/null' or die "Can't redirect STDERR to /dev/null: $!";
212 }
213  
214 if ( $pidfile )
215 {
216 my $fd = IO::File->new(">$pidfile")
217 || die "Unable to open pidfile: $pidfile: $!";
218 $fd->write("$$");
219 $fd->close();
220 }
221  
222 my $logger_alias;
223 if ( -e $CONF_LOG )
224 {
225 $logger_alias = 'mq_logger';
226  
227 # we create a logger, because a production message queue would
228 # really need one.
229 POE::Component::Logger->spawn(
230 ConfigFile => $CONF_LOG,
231 Alias => $logger_alias
232 );
233 }
234 else
235 {
236 print STDERR "LOGGER: Unable to find configuration: $CONF_LOG\n";
237 print STDERR "LOGGER: Will send all messages to STDERR\n";
238 }
239  
240 if ($storage eq 'default') {
241 if ($front_store eq 'memory')
242 {
243 $front_store = POE::Component::MessageQueue::Storage::Memory->new();
244 }
245 elsif ($front_store eq 'bigmemory')
246 {
247 $front_store = POE::Component::MessageQueue::Storage::BigMemory->new();
248 }
249 else
250 {
251 die "Unknown front-store specified: $front_store";
252 }
253  
254 $storage = POE::Component::MessageQueue::Storage::Default->new(
255 data_dir => $DATA_DIR,
256 timeout => $timeout,
257 throttle_max => $throttle_max,
258 front => $front_store,
259 front_max => $front_max ? parse_size($front_max) : undef,
260 granularity => $granularity,
261 );
262 }
263 else {
264 if ($storage eq 'dbi')
265 {
266 $storage = POE::Component::MessageQueue::Storage::DBI->new(
267 dsn => $dbi_dsn,
268 username => $dbi_username,
269 password => $dbi_password,
270 mq_id => $mq_id,
271 );
272 }
273 else
274 {
275 die "Unknown storage specified: $storage";
276 }
277  
278 if ($throttle_max > 0) {
279 $storage = POE::Component::MessageQueue::Storage::Throttled->new(
280 back => $storage,
281 throttle_max => $throttle_max
282 );
283 }
284 }
285  
286 my $idgen;
287 if ($uuids)
288 {
289 use POE::Component::MessageQueue::IDGenerator::UUID;
290 $idgen = POE::Component::MessageQueue::IDGenerator::UUID->new();
291 }
292 else
293 {
294 use POE::Component::MessageQueue::IDGenerator::SimpleInt;
295 $idgen = POE::Component::MessageQueue::IDGenerator::SimpleInt->new(
296 filename => "$DATA_DIR/last_id.mq",
297 );
298 }
299  
300 my %args = (
301 port => $port,
302 hostname => $hostname,
303  
304 storage => $storage,
305  
306 pump_frequency => $pump_frequency,
307 idgen => $idgen,
308 logger_alias => $logger_alias,
309 );
310  
311 if ($statistics) {
312 require POE::Component::MessageQueue::Statistics;
313 require POE::Component::MessageQueue::Statistics::Publish::YAML;
314 my $stat = POE::Component::MessageQueue::Statistics->new();
315 my $publish = POE::Component::MessageQueue::Statistics::Publish::YAML->spawn(
316 statistics => $stat,
317 output => "$DATA_DIR/stats.yml",
318 interval => $stat_interval,
319 );
320 $args{observers} = [ $stat ];
321 }
322 my $mq = POE::Component::MessageQueue->new(%args);
323  
324 # install the debug shell if requested
325 if ( $debug_shell )
326 {
327 require POE::Component::DebugShell;
328 POE::Component::DebugShell->spawn();
329 }
330  
331 # install a die handler so we can catch crashes and log them
332 $SIG{__DIE__} = sub {
333 my $trace = Devel::StackTrace->new()->as_string();
334 my $banner = sprintf("\n%s\n", '=' x 30);
335 my $diemsg = sprintf("$banner MQ Crashed: %s $banner\n$trace",
336 strftime('%Y-%m-%d %H:%M:%S', localtime(time())));
337  
338 # Print it first, cause don't know if the other stuff is gonna work.
339 print STDERR $diemsg;
340  
341 # This will probably work, but we should say so if it doesn't.
342 my $fn = "$DATA_DIR/crashed.log";
343 if(open DIEFILE, ">>", $fn)
344 {
345 print DIEFILE $diemsg;
346 close DIEFILE;
347 }
348 else
349 {
350 print STDERR "Couldn't open crashlog '$fn': $!\n";
351 }
352  
353 # Only bother if one was specified.
354 if ($crash_cmd)
355 {
356 if (open DIEPIPE, '|-', $crash_cmd)
357 {
358 print DIEPIPE $diemsg;
359 close DIEPIPE;
360 }
361 else
362 {
363 print STDERR "Couldn't send crashlog to $crash_cmd: $!\n";
364 }
365 }
366 };
367  
368 POE::Kernel->run();
369 exit;
370