Categories
Posts in this category
- Current State of Exceptions in Rakudo and Perl 6
- Meet DBIish, a Perl 6 Database Interface
- doc.perl6.org and p6doc
- Exceptions Grant Report for May 2012
- Exceptions Grant Report -- Final update
- Perl 6 Hackathon in Oslo: Be Prepared!
- Localization for Exception Messages
- News in the Rakudo 2012.05 release
- News in the Rakudo 2012.06 release
- Perl 6 Hackathon in Oslo: Report From The First Day
- Perl 6 Hackathon in Oslo: Report From The Second Day
- Quo Vadis Perl?
- Rakudo Hack: Dynamic Export Lists
- SQLite support for DBIish
- Stop The Rewrites!
- Upcoming Perl 6 Hackathon in Oslo, Norway
- A small regex optimization for NQP and Rakudo
- Pattern Matching and Unpacking
- Rakudo's Abstract Syntax Tree
- The REPL trick
- First day at YAPC::Europe 2013 in Kiev
- YAPC Europe 2013 Day 2
- YAPC Europe 2013 Day 3
- A new Perl 6 community server - call for funding
- New Perl 6 community server now live, accepting signups
- A new Perl 6 community server - update
- All Perl 6 modules in a box
- doc.perl6.org: some stats, future directions
- Profiling Perl 6 code on IRC
- Why is it hard to write a compiler for Perl 6?
- Writing docs helps you take the user's perspective
- Perl 6 Advent Calendar 2016 -- Call for Authors
- Perl 6 By Example: Running Rakudo
- Perl 6 By Example: Formatting a Sudoku Puzzle
- Perl 6 By Example: Testing the Say Function
- Perl 6 By Example: Testing the Timestamp Converter
- Perl 6 By Example: Datetime Conversion for the Command Line
- What is Perl 6?
- Perl 6 By Example, Another Perl 6 Book
- Perl 6 By Example: Silent Cron, a Cron Wrapper
- Perl 6 By Example: Testing Silent Cron
- Perl 6 By Example: Stateful Silent Cron
- Perl 6 By Example: Perl 6 Review
- Perl 6 By Example: Parsing INI files
- Perl 6 By Example: Improved INI Parsing with Grammars
- Perl 6 By Example: Generating Good Parse Errors from a Parser
- Perl 6 By Example: A File and Directory Usage Graph
- Perl 6 By Example: Functional Refactorings for Directory Visualization Code
- Perl 6 By Example: A Unicode Search Tool
- What's a Variable, Exactly?
- Perl 6 By Example: Plotting using Matplotlib and Inline::Python
- Perl 6 By Example: Stacked Plots with Matplotlib
- Perl 6 By Example: Idiomatic Use of Inline::Python
- Perl 6 By Example: Now "Perl 6 Fundamentals"
- Perl 6 Books Landscape in June 2017
- Living on the (b)leading edge
- The Loss of Name and Orientation
- Perl 6 Fundamentals Now Available for Purchase
- My Ten Years of Perl 6
- Perl 6 Coding Contest 2019: Seeking Task Makers
- A shiny perl6.org site
- Creating an entry point for newcomers
- An offer for software developers: free IRC logging
- Sprixel, a 6 compiler powered by JavaScript
- Announcing try.rakudo.org, an interactive Perl 6 shell in your browser
- Another perl6.org iteration
- Blackjack and Perl 6
- Why I commit Crud to the Perl 6 Test Suite
- This Week's Contribution to Perl 6 Week 5: Implement Str.trans
- This Week's Contribution to Perl 6
- This Week's Contribution to Perl 6 Week 8: Implement $*ARGFILES for Rakudo
- This Week's Contribution to Perl 6 Week 6: Improve Book markup
- This Week's Contribution to Perl 6 Week 2: Fix up a test
- This Week's Contribution to Perl 6 Week 9: Implement Hash.pick for Rakudo
- This Week's Contribution to Perl 6 Week 11: Improve an error message for Hyper Operators
- This Week's Contribution to Perl 6 - Lottery Intermission
- This Week's Contribution to Perl 6 Week 3: Write supporting code for the MAIN sub
- This Week's Contribution to Perl 6 Week 1: A website for proto
- This Week's Contribution to Perl 6 Week 4: Implement :samecase for .subst
- This Week's Contribution to Perl 6 Week 10: Implement samespace for Rakudo
- This Week's Contribution to Perl 6 Week 7: Implement try.rakudo.org
- What is the "Cool" class in Perl 6?
- Report from the Perl 6 Hackathon in Copenhagen
- Custom operators in Rakudo
- A Perl 6 Date Module
- Defined Behaviour with Undefined Values
- Dissecting the "Starry obfu"
- The case for distributed version control systems
- Perl 6: Failing Softly with Unthrown Exceptions
- Perl 6 Compiler Feature Matrix
- The first Perl 6 module on CPAN
- A Foray into Perl 5 land
- Gabor: Keep going
- First Grant Report: Structured Error Messages
- Second Grant Report: Structured Error Messages
- Third Grant Report: Structured Error Messages
- Fourth Grant Report: Structured Error Messages
- Google Summer of Code Mentor Recap
- How core is core?
- How fast is Rakudo's "nom" branch?
- Building a Huffman Tree With Rakudo
- Immutable Sigils and Context
- Is Perl 6 really Perl?
- Mini-Challenge: Write Your Prisoner's Dilemma Strategy
- List.classify
- Longest Palindrome by Regex
- Perl 6: Lost in Wonderland
- Lots of momentum in the Perl 6 community
- Monetize Perl 6?
- Musings on Rakudo's spectest chart
- My first executable from Perl 6
- My first YAPC - YAPC::EU 2010 in Pisa
- Trying to implement new operators - failed
- Programming Languages Are Not Zero Sum
- Perl 6 notes from February 2011
- Notes from the YAPC::EU 2010 Rakudo hackathon
- Let's build an object
- Perl 6 is optimized for fun
- How to get a parse tree for a Perl 6 Program
- Pascal's Triangle in Perl 6
- Perl 6 in 2009
- Perl 6 in 2010
- Perl 6 in 2011 - A Retrospection
- Perl 6 ticket life cycle
- The Perl Survey and Perl 6
- The Perl 6 Advent Calendar
- Perl 6 Questions on Perlmonks
- Physical modeling with Math::Model and Perl 6
- How to Plot a Segment of a Circle with SVG
- Results from the Prisoner's Dilemma Challenge
- Protected Attributes Make No Sense
- Publicity for Perl 6
- PVC - Perl 6 Vocabulary Coach
- Fixing Rakudo Memory Leaks
- Rakudo architectural overview
- Rakudo Rocks
- Rakudo "star" announced
- My personal "I want a PONIE" wish list for Rakudo Star
- Rakudo's rough edges
- Rats and other pets
- The Real World Strikes Back - or why you shouldn't forbid stuff just because you think it's wrong
- Releasing Rakudo made easy
- Set Phasers to Stun!
- Starry Perl 6 obfu
- Recent Perl 6 Developments August 2008
- The State of Regex Modifiers in Rakudo
- Strings and Buffers
- Subroutines vs. Methods - Differences and Commonalities
- A SVG plotting adventure
- A Syntax Highlighter for Perl 6
- Test Suite Reorganization: How to move tests
- The Happiness of Design Convergence
- Thoughts on masak's Perl 6 Coding Contest
- The Three-Fold Function of the Smart Match Operator
- Perl 6 Tidings from September and October 2008
- Perl 6 Tidings for November 2008
- Perl 6 Tidings from December 2008
- Perl 6 Tidings from January 2009
- Perl 6 Tidings from February 2009
- Perl 6 Tidings from March 2009
- Perl 6 Tidings from April 2009
- Perl 6 Tidings from May 2009
- Perl 6 Tidings from May 2009 (second iteration)
- Perl 6 Tidings from June 2009
- Perl 6 Tidings from August 2009
- Perl 6 Tidings from October 2009
- Timeline for a syntax change in Perl 6
- Visualizing match trees
- Want to write shiny SVG graphics with Perl 6? Port Scruffy!
- We write a Perl 6 book for you
- When we reach 100% we did something wrong
- Where Rakudo Lives Now
- Why Rakudo needs NQP
- Why was the Perl 6 Advent Calendar such a Success?
- What you can write in Perl 6 today
- Why you don't need the Y combinator in Perl 6
- You are good enough!
Sun, 01 Jan 2017
Perl 6 By Example: Silent Cron, a Cron Wrapper
Permanent link
This blog post is part of my ongoing project to write a book about Perl 6.
If you're interested, either in this book project or any other Perl 6 book news, please sign up for the mailing list at the bottom of the article, or here. It will be low volume (less than an email per month, on average).
On Linux and UNIX-Like systems, a program called cron periodically executes user-defined commands in the background. It is used for system maintenance tasks such as refreshing or removing caches, rotating and deleting old log files and so on.
If such a command produces any output, cron typically sends an email containing the output so that an operator can look at it and judge if some action is required.
But not all command line programs are written for usage with cron. For example they might produce output even on successful execution, and indicate failure through a non-zero exit code. Or they might hang, or otherwise misbehave.
To deal with such commands, we'll develop a small program called
silent-cron
, which wraps such commands and suppresses output when the
exit code is zero. It also allows you to specify a timeout that kills the
wrapped program if it takes too long:
$ silent-cron -- command-that-might-fail args
$ silent-cron --timeout=5 -- command-that-might-hang
Running Commands Asynchronously
When you want to run external commands, Perl 6 gives you basically two choices: run, a simple, synchronous interface, and Proc::Async, an asynchronous and slightly more complex option. Even though we will omit the timeout in the first iteration, we need to be aware that implementing the timeout is easier in the asynchronous interface, so that's what we'll use:
#!/usr/bin/env perl6
sub MAIN(*@cmd) {
my $proc = Proc::Async.new(@cmd);
my $collector = Channel.new;
for $proc.stdout, $proc.stderr -> $supply {
$supply.tap: { $collector.send($_) }
}
my $result = $proc.start.result;
$collector.close;
my $output = $collector.list.join;
my $exitcode = $result.exitcode;
if $exitcode != 0 {
say "Program @cmd[] exited with code $exitcode";
print "Output:\n", $output if $output;
}
exit $exitcode;
}
There's a big chunk of new features and concepts in here, so let's go through the code bit by bit.
sub MAIN(*@cmd) {
my $proc = Proc::Async.new(@cmd);
This collects all the command line arguments in the array variable @cmd
,
where the first element is the command to be executed, and any further
elements are arguments passed to this command.
The second line creates a new Proc::Async
instance, but doesn't yet run
the command.
We need to capture all output from the command; thus we capture the output
of the STDOUT and STDERR streams (file handles 1 and 2 on Linux), and
combine it into a single string. In the asynchronous API, STDOUT and STDERR
are modeled as objects of type Supply,
and hence are streams of events. Since supplies can emit events in parallel, we need
a thread-safe data structure for collecting the result, and Perl 6
conveniently provides a Channel
for that:
my $collector = Channel.new;
To actually get the output from the program, we need to tap into the STDOUT and STDERR streams:
for $proc.stdout, $proc.stderr -> $supply {
$supply.tap: { $collector.send($_) }
}
Each supply executes the block { $collector.send($_) }
for each string it
receives. The string can be a character, a line or something larger if the
stream is buffered. All we do with it is put the string into the
channel $collector
via the send
method.
Now that the streams are tapped, we can start the program and wait for it to finish:
my $result = $proc.start.result;
Proc::Async.start
executes the external process and returns a
Promise. A promise wraps a piece of code that
potentially runs on another thread, has a status (Planned
, Kept
or
Broken
), and once it's finished, a result. Accessing the result
automatically waits for the wrapped code to finish. Here the code is the
one that runs the external program and the result is an object of type
Proc (which happens to be the same as
the run()
function from the synchronous interface).
After this line, we can be sure that the external command has terminated,
and thus no more output will come from $proc.stdout
and $proc.stderr
.
Hence we can safely close the channel and access all its elements through
Channel.list
:
$collector.close;
my $output = $collector.list.join;
Finally it's time to check if the external command was successful -- by checking its exit code -- and to exit the wrapper with the command's exit code:
my $exitcode = $result.exitcode;
if $exitcode != 0 {
say "Program @cmd[] exited with code $exitcode";
print "Output:\n", $output if $output;
}
exit $exitcode;
Implementing Timeouts
The idiomatic way to implement timeouts in Perl 6 is to use the
Promise.anyof
combinator together with a timer:
sub MAIN(*@cmd, :$timeout) {
my $proc = Proc::Async.new(|@cmd);
my $collector = Channel.new;
for $proc.stdout, $proc.stderr -> $supply {
$supply.tap: { $collector.send($_) }
}
my $promise = $proc.start;
my $waitfor = $promise;
$waitfor = Promise.anyof(Promise.in($timeout), $promise)
if $timeout;
await $waitfor;
The initialization of $proc
hasn't changed. But instead of accessing
$proc.start.result
, we store the promise returned from $proc.start
. If
the user specified a timeout, we run this piece of code:
$waitfor = Promise.anyof(Promise.in($timeout), $promise)
Promise.in($seconds)
returns a promise that will be fulfilled in
$seconds
seconds. It's basically the same as start { sleep $seconds }
,
but the scheduler can be a bit smarter about not allocating a whole thread
just for sleeping.
Promise.anyof($p1, $p2)
returns a promise that is fulfilled as soon as
one of the arguments (which should also be promises) is fulfilled. So we
wait either until the external program finished, or until the sleep promise is
fulfilled.
With await $waitfor;
the program waits for the promise to be fulfilled
(or broken). When that is the case, we can't simply access
$promise.result
as before, because $promise
(which is the promise for
the external program) might not be fulfilled in the case of a timeout. So
we have to check the status of the promise first and only then can we
safely access $promise.result
:
if !$timeout || $promise.status ~~ Kept {
my $exitcode = $promise.result.exitcode;
if $exitcode != 0 {
say "Program @cmd[] exited with code $exitcode";
print "Output:\n", $output if $output;
}
exit $exitcode;
}
else {
...
}
In the else { ... }
branch, we need to handle the timeout case. This
might be as simple as printing a statement that a timeout has occurred, and
when silent-cron
exits immediately afterwards, that might be acceptable.
But we might want to do more in the future, so we should kill the external
program. And if the program doesn't terminate after the friendly kill
signal, it should receive a kill(9)
, which on UNIX systems forcefully
terminates the program:
else {
$proc.kill;
say "Program @cmd[] did not finish after $timeout seconds";
sleep 1 if $promise.status ~~ Planned;
$proc.kill(9);
await $promise;
exit 2;
}
await $promise
returns the result of the promise, so here a Proc
object.
Proc
has a safety feature built in that if the command returned with a
non-zero exit code, evaluating the object in void context throws an exception.
Since we explicitly handle the non-zero exit code in the code, we can suppress
the generation of this exception by assigning the return value from await
to
a dummy variable:
my $dummy = await $promise
Since we don't need the value, we can also assign it to an anonymous variable instead:
$ = await $promise
More on Promises
If you have worked with concurrent or parallel programs in other languages, you might have come across threads, locks, mutexes, and other low-level constructs. These exist in Perl 6 too, but their direct usage is discouraged.
The problem with such low-level primitives is that they don't compose well. You can have two libraries that use threads and work fine on their own, but lead to deadlocks when combined within the same program. Or different components might launch threads on their own, which can lead to too many threads and high memory consumption when several such components come together in the same process.
Perl 6 provides higher-level primitives. Instead of spawning a thread, you
use start
to run code asynchronously and the scheduler
decides which thread to run this on. If more start
calls
happen that ask for threads to schedule things on, some will run serially.
Here is a very simple example of running a computation in the background:
sub count-primes(Int $upto) {
(1..$upto).grep(&is-prime).elems;
}
my $p = start count-primes 10_000;
say $p.status;
await $p;
say $p.result;
It gives this output:
Planned
1229
You can see that the main line of execution continued after the start
call,
and $p
immediately had a value -- the promise, with status Planned
.
As we've seen before, there are combinators for promises, anyof
and
allof
. You can also chain actions to a promise using the then
method:
sub count-primes(Int $upto) {
(1..$upto).grep(&is-prime).elems;
}
my $p1 = start count-primes 10_000;
my $p2 = $p1.then({ say .result });
await $p2;
If an exception is thrown inside asynchronously executing code, the status of
the promise becomes Broken
, and calling its .result
method re-throws
the exception.
As a demonstration of the scheduler distributing tasks, let's consider a small Monte Carlo simulation to calculate an approximation for π. We generate a pair of random numbers between zero and one, and interpret them as dots in a square. A quarter circle with radius one covers the area of π/4, so the ratio of randomly placed dots within the quarter circle to the total number of dots approaches π/4, if we use enough dots.
sub pi-approx($iterations) {
my $inside = 0;
for 1..$iterations {
my $x = 1.rand;
my $y = 1.rand;
$inside++ if $x * $x + $y * $y <= 1;
}
return ($inside / $iterations) * 4;
}
my @approximations = (1..1000).map({ start pi-approx(80) });
await @approximations;
say @approximations.map({.result}).sum / @approximations;
The program starts one thousand computations asynchronously, but if you look at a system monitoring tool while it runs, you'll observe only 16 threads running. This magic number comes from the default thread scheduler, and we can override it by providing our own instance of a scheduler above the previous code:
my $*SCHEDULER = ThreadPoolScheduler.new(:max_threads(3));
For CPU bound tasks like this Monte Carlo Simulation, it is a good idea to limit the number of threads roughly to the number of (possibly virtual) CPU cores; if many threads are stuck waiting for IO, a higher number of threads can yield better performance.
Possible Extensions
If you want to play with silent-cron
, you could add a retry mechanism.
If a command fails because of an external dependency (like an API or an NFS
share), it might take time for that external dependency to recover.
Hence you should add a quadratic or exponential backoff, that is, the wait
time between retries should increase quadratically (1, 2, 4, 9, 16, ...) or
exponentially (1, 2, 4, 8, 16, 32, ...).
Summary
We've seen an asynchronous API for running external programs and how to use Promises to implement timeouts. We've also discussed how promises are distributed to threads by a scheduler, allowing you to start an arbitrary number of promises without overloading your computer.