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, 15 Jan 2017
Perl 6 By Example: Stateful Silent Cron
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).
In the last two installments we've looked at silent-cron
, a wrapper around
external programs that silences them in case their exit status is zero. But
to make it really practical, it should also silence occasional failures.
External APIs fail, networks become congested, and other things happen that
prevent a job from succeeding, so some kind of retry mechanism is desirable.
In case of a cron job, cron already takes care of retrying a job on a regular
basis, so silent-cron
should just suppress occasional errors. On the other
hand, if a job fails consistently, this is usually something that an operator
or developer should look into, so it's a problem worth reporting.
To implement this functionality, silent-cron
needs to store persistent
state between separate runs. It needs to record the results from the current
run and then analyze if the failure history qualifies as "occasional".
Persistent Storage
The storage backend needs to write and retrieve structured data, and protect concurrent access to the state file with locking. A good library for such a storage backend is SQLite, a zero-maintenance SQL engine that's available as a C library. It's public domain software and in use in most major browsers, operating systems and even some airliners.
Perl 6 gives you access to SQLite's functionality through
DBIish, a generic database interface with
backend drivers for SQLite, MySQL, PostgreSQL and Oracle DB. To use it, first
make sure that SQLite3 is installed, including its header files. On a Debian-based
Linux system, for example, you can achieve this with apt-get install
libsqlite3-dev
. If you are using the Rakudo Star distribution, DBIish is
already available. If not, you can use one of the module installers to
retrieve and install it: panda install DBIish
or zef install DBIish
.
To use the DBIish's SQLite backend, you first have to create a database handle by selecting the backend and supplying connection information:
use DBIish;
my $dbh = DBIish.connect('SQLite', :database('database-file.sqlite3'));
Connecting to a database file that does not yet exist creates that file.
One-off SQL statements can be executed directly on the database handle:
$dbh.do('INSERT INTO player (name) VALUES ?', 'John');
The ?
in the SQL is a placeholder that is passed out-of-band as a separate
argument to the do
method, which avoids potential errors such as SQL
injection vulnerabilities.
Queries tend to work by first preparing a statement which returns a
statement handle. You can execute a statement once or multiple times, and
retrieve result rows after each execute
call:
my $sth = $dbh.prepare('SELECT id FROM player WHERE name = ?');
my %ids;
for <John Jack> -> $name {
$sth.execute($name);
%ids{ $name } = $sth.row[0];
}
$sth.finish;
Developing the Storage Backend
We shouldn't just stuff all the storage handling code into sub MAIN
, we
should instead carefully consider the creation of a useful API for the storage backend. At
first, we need only two pieces of functionality: insert the result of a job
execution; and retrieve the most recent results.
Since silent-cron
can be used to guard multiple cron jobs on the same
machine, we might need something to distinguish the different jobs so that
one of them succeeding doesn't prevent error reporting for one that is constantly
failing. For that we introduce a job name, which can default to the
command (including arguments) being executed but which can be set explicitly
on the command line.
The API for the storage backend could look something like this:
my $repo = ExecutionResultRepository.new(
jobname => 'refresh cache',
statefile => 'silent-cron.sqlite3',
);
$repo.insert($result);
my @last-results = $repo.tail(5);
This API isn't specific to the SQLite backend at all; a storage backend that works with plain text files could have the exact same API.
Let's implement this API. First we need the class and the two attributes that should be obvious from the usage example above:
class ExecutionResultRepository {
has $.jobname is required;
has $.statefile is required;
# ... more code
To implement the insert
method, we need to connect to the database
and create the relevant table if it doesn't exist yet.
has $!db;
method !db() {
return $!db if $!db;
$!db = DBIish.connect('SQLite', :database($.statefile));
self!create-schema();
return $!db;
}
This code uses a private attribute $!db
to cache the database handle and a
private method !db
to create the handle if it doesn't exist yet.
Private methods are declared like ordinary methods, except that the name
starts with an exclamation mark. To call one, substitute the method call dot
for the exclamation mark, in other words, use self!db()
instead of self.db()
.
The !db
method also calls the next private method, !create-schema
, which
creates the storage table and some indexes:
method !create-schema() {
$!db.do(qq:to/SCHEMA/);
CREATE TABLE IF NOT EXISTS $table (
id INTEGER PRIMARY KEY,
jobname VARCHAR NOT NULL,
exitcode INTEGER NOT NULL,
timed_out INTEGER NOT NULL,
output VARCHAR NOT NULL,
executed TIMESTAMP NOT NULL DEFAULT (DATETIME('NOW'))
);
SCHEMA
$!db.do(qq:to/INDEX/);
CREATE INDEX IF NOT EXISTS {$table}_jobname_exitcode ON $table ( jobname, exitcode );
INDEX
$!db.do(qq:to/INDEX/);
CREATE INDEX IF NOT EXISTS {$table}_jobname_executed ON $table ( jobname, executed );
INDEX
}
Multi-line string literals are best written with the heredoc
syntax. qq:to/DELIMITER/
tells Perl 6 to finish parsing the current
statement so that you can still close the method call parenthesis and add the
statement-ending semicolon. The next line starts the string literal, which
goes on until Perl 6 finds the delimiter on a line on its own. Leading
whitespace is stripped from each line of the string literal by as much as the
closing delimiter is indented.
For example
print q:to/EOS/;
Not indented
Indented four spaces
EOS
Produces the output
Not indented
Indented four spaces
Now that we have a working database connection and know that the database table exists, inserting a new record becomes easy:
method insert(ExecutionResult $r) {
self!db.do(qq:to/INSERT/, $.jobname, $r.exitcode, $r.timed-out, $r.output);
INSERT INTO $table (jobname, exitcode, timed_out, output)
VALUES(?, ?, ?, ?)
INSERT
}
Selecting the most recent records is a bit more work, partially because we need to convert the table rows into objects:
method tail(Int $count) {
my $sth = self!db.prepare(qq:to/SELECT/);
SELECT exitcode, timed_out, output
FROM $table
WHERE jobname = ?
ORDER BY executed DESC
LIMIT $count
SELECT
$sth.execute($.jobname);
$sth.allrows(:array-of-hash).map: -> %h {
ExecutionResult.new(
exitcode => %h<exitcode>,
timed-out => ?%h<timed_out>,
output => %h<output>,
);
}
}
The last statement in the tail
method deserves a bit of extra attention.
$sth.allrows(:array-of-hash)
produces the database rows as a list of hashes.
This list is lazy, that is, it's generated on-demand. Lazy lists are a very
convenient feature because they allow you to use iterators and lists with the
same API. For example when reading lines from a file, you can write for
$handle.lines -> $line { ... }
, and the lines
method doesn't have to load
the whole file into memory; instead it can read a line whenever it is
accessed.
$sth.allrows(...)
is lazy, and so is the .map
call that comes after it.
map
transforms a list one element at a time by calling the code object
that's passed to it. And that is done lazily as well. So SQLite only retrieves
rows from the database file when elements of the resulting list are actually
accessed.
Using the Storage Backend
With the storage API in place, it's time to use it:
multi sub MAIN(*@cmd, :$timeout, :$jobname is copy,
:$statefile='silent-cron.sqlite3', Int :$tries = 3) {
$jobname //= @cmd.Str;
my $result = run-with-timeout(@cmd, :$timeout);
my $repo = ExecutionResultRepository.new(:$jobname, :$statefile);
$repo.insert($result);
my @runs = $repo.tail($tries);
unless $result.is-success or @runs.grep({.is-success}) {
say "The last @runs.elems() runs of @cmd[] all failed, the last execution ",
$result.timed-out ?? "ran into a timeout"
!! "exited with code $result.exitcode()";
print "Output:\n", $result.output if $result.output;
}
exit $result.exitcode // 2;
}
Now a job that succeeds a few times, and then fails up to two times in a row
doesn't produce any error output, and only the third failed execution in a row
produces output. You can override that on the command line with --tries=5
.
Summary
We've discussed DBIish
, a database API with pluggable backend, and explored
using it with SQLite to store persistent data. In the process we also came
across lazy lists and a new form of string literals called heredocs.