<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">

  <title><![CDATA[Brownsofa]]></title>
  <link href="http://brownsofa.org/atom.xml" rel="self"/>
  <link href="http://brownsofa.org/"/>
  <updated>2015-06-14T11:50:12-06:00</updated>
  <id>http://brownsofa.org/</id>
  <author>
    <name><![CDATA[Ian Truslove]]></name>
    
  </author>
  <generator uri="http://octopress.org/">Octopress</generator>

  
  <entry>
    <title type="html"><![CDATA[Clojure in production: Logging]]></title>
    <link href="http://brownsofa.org/blog/2015/06/14/clojure-in-production-logging/"/>
    <updated>2015-06-14T11:44:00-06:00</updated>
    <id>http://brownsofa.org/blog/2015/06/14/clojure-in-production-logging</id>
    <content type="html"><![CDATA[<p><img class="right" src="http://brownsofa.org/images/clojure-in-production/rabbet-plane.jpg" title="Rabbet plane" alt="Rabbet plane"></p>

<p>The first part in this series is about logging. When you&rsquo;re playing
with your at the REPL, you can immediately see what&rsquo;s going on. When
your code is running on a server in some data center, and you had a
problem 6 hours ago, it&rsquo;s too late for a REPL. You need logs.</p>

<p>Having good logs is an art, but adding logging to a Clojure project is
straightforward. So this is where we will start.</p>

<p>This article will show you how to use clojure.tools.logging, and get
it set up using the Log4j logging backend. I&rsquo;ll explain some common
logging concepts, cover how to get Log4j installed, configured and
working in a Leiningen project, and as an aside explain how to read
Clojure stack traces.  Finally I&rsquo;ll run through some code that&rsquo;s
useful for interacting with the logger configuration at run time.</p>

<!-- more -->


<h2>Logging Basics</h2>

<p>Logs are a record of what happened as your program was executing. If
something went wrong with your program&rsquo;s execution, you can&rsquo;t rewind
time to see what actually happened, but if you have a log file, you
might have log data to help you deduce what the problem was.</p>

<p>Logs are also used as a way to record &ldquo;expected&rdquo; problems and trigger
manual follow-up activities (for example, if your log contains
&ldquo;Account creation failed&rdquo; messages, you can go back and contact the
people whose accounts weren&rsquo;t created). I don&rsquo;t think you should
consider log files as a durable data store, so I strongly recommend
that you don&rsquo;t use logs for this type of thing.</p>

<p>Logging tools generally have the concept of &ldquo;log levels&rdquo;. These let
you express the severity of a particular piece of log data. This
fairly well-understood semantic lets you structure your log data, and
helps you (and others) read your log files when looking for problems.</p>

<p>Logs are frequently stored in text files on disk. Take a look at the
files in <code>/var/log/</code> on any Unix system &ndash; whilst you may not
understand the details of any given log, their structure and usage
will likely be apparent.</p>

<p>The output also need not just be a simple text file. Loggers are
frequently capable of logging to standard output (e.g. for a
Heroku-style <a href="http://12factor.net/logs">12 Factor App</a>), to syslog, or
writing structured log files aimed at ingestion into log analytics
platforms.</p>

<p>There are lots of choices available to Clojure programmers. Logback,
Log4j, commons-logging and Timbre are just a few. Largely because of
its ubiquity and the ease with which you can set it up I based this
post on logging to Log4j, but it pretty much everything applies to
these other libraries.</p>

<h2>Clojure ❤  logging</h2>

<p>OK, let&rsquo;s get this going. It&rsquo;s really simple: set up your
dependencies, configure the logger, and insert some log statements.</p>

<p>I created a new Leiningen project for this, which I&rsquo;m calling &ldquo;rabbet&rdquo;
(<code>lein new rabbet</code>).</p>

<h3>Dependencies</h3>

<p>Add clojure.tools.logging and log4j to your dependencies list in
<code>project.clj</code>:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
</pre></td><td class='code'><pre><code class='clojure'><span class='line'><span class="ss">:dependencies</span> <span class="p">[[</span><span class="nv">org.clojure/tools.logging</span> <span class="s">&quot;0.3.1&quot;</span><span class="p">]</span>
</span><span class='line'>               <span class="p">[</span><span class="nv">log4j/log4j</span> <span class="s">&quot;1.2.17&quot;</span> <span class="ss">:exclusions</span> <span class="p">[</span><span class="nv">javax.mail/mail</span>
</span><span class='line'>                                                 <span class="nv">javax.jms/jms</span>
</span><span class='line'>                                                 <span class="nv">com.sun.jmdk/jmxtools</span>
</span><span class='line'>                                                 <span class="nv">com.sun.jmx/jmxri</span><span class="p">]]</span>
</span><span class='line'>              <span class="c1">;; ...etc</span>
</span><span class='line'>              <span class="p">]</span>
</span></code></pre></td></tr></table></div></figure>


<p><em>Note: I&rsquo;m using Log4j version 1.2 here. Log4j 2 isn&rsquo;t currently
supported by clojure.tools.logging.</em></p>

<h3>Quick configuration</h3>

<p>Log4j&rsquo;s output is commonly controlled from a <code>log4j.properties</code>
file. You set up the types of logs that are created, the format of the
logs, and the verbosity of the logs.</p>

<p>Get started by creating <code>resources/log4j.properties</code> in your project containing this:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
</pre></td><td class='code'><pre><code class='text'><span class='line'>log4j.rootLogger=ERROR, file
</span><span class='line'>
</span><span class='line'>log4j.logger.rabbet.core=INFO
</span><span class='line'>
</span><span class='line'>log4j.appender.file=org.apache.log4j.RollingFileAppender
</span><span class='line'>log4j.appender.file.File=log/rabbet.log
</span><span class='line'>log4j.appender.file.MaxFileSize=1MB
</span><span class='line'>log4j.appender.file.MaxBackupIndex=10
</span><span class='line'>log4j.appender.file.layout=org.apache.log4j.PatternLayout
</span><span class='line'>log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss.SSS} | %-5p | %t | %c | %m%n
</span></code></pre></td></tr></table></div></figure>


<p>I also suggest that you add <code>log/</code> to your <code>.gitignore</code>.</p>

<h3>Using clojure.tools.logging</h3>

<p>It&rsquo;s super simple.
Add this code to <code>src/rabbet/core.clj</code>:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
<span class='line-number'>18</span>
</pre></td><td class='code'><pre><code class='clojure'><span class='line'><span class="p">(</span><span class="kd">ns </span><span class="nv">rabbet.core</span>
</span><span class='line'>  <span class="p">(</span><span class="ss">:require</span> <span class="p">[</span><span class="nv">clojure.tools.logging</span> <span class="ss">:as</span> <span class="nv">log</span><span class="p">]))</span>
</span><span class='line'>
</span><span class='line'><span class="c1">;; Output log statements at various levels:</span>
</span><span class='line'><span class="p">(</span><span class="nf">log/trace</span> <span class="s">&quot;This is the lowest (least important) log level&quot;</span><span class="p">)</span>
</span><span class='line'><span class="p">(</span><span class="nf">log/debug</span> <span class="s">&quot;For programmer info...&quot;</span><span class="p">)</span>
</span><span class='line'><span class="p">(</span><span class="nf">log/warn</span> <span class="s">&quot;Something bad might have happened.&quot;</span><span class="p">)</span>
</span><span class='line'>
</span><span class='line'><span class="c1">;; You can dump all kinds of things out to the log:</span>
</span><span class='line'><span class="p">(</span><span class="nf">log/info</span> <span class="s">&quot;this happened:&quot;</span>
</span><span class='line'>          <span class="p">{</span><span class="ss">:foo</span> <span class="mi">12</span> <span class="ss">:bar</span> <span class="ss">:quux</span><span class="p">}</span>
</span><span class='line'>          <span class="s">&quot;that was fun!&quot;</span><span class="p">)</span>
</span><span class='line'>
</span><span class='line'><span class="c1">;; Exceptions have a special arity:</span>
</span><span class='line'><span class="p">(</span><span class="nf">try</span>
</span><span class='line'>  <span class="p">(</span><span class="nb">/ </span><span class="mi">10</span> <span class="p">(</span><span class="nb">dec </span><span class="mi">1</span><span class="p">))</span> <span class="c1">;; &lt;-- dividing by zero rarely works.</span>
</span><span class='line'>  <span class="p">(</span><span class="nf">catch</span> <span class="nv">Exception</span> <span class="nv">e</span>
</span><span class='line'>    <span class="p">(</span><span class="nf">log/error</span> <span class="nv">e</span> <span class="s">&quot;Dividing failed!&quot;</span><span class="p">)))</span>
</span></code></pre></td></tr></table></div></figure>


<p>Evaluate the file and take a look at the output in the log file (<code>log/rabbet.log</code>):</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
</pre></td><td class='code'><pre><code class='text'><span class='line'>2015-06-14 14:26:48.957 | WARN  | nREPL-worker-2 | rabbet.core | Something bad might have happened.
</span><span class='line'>2015-06-14 14:26:48.960 | INFO  | nREPL-worker-2 | rabbet.core | this happened: {:foo 12, :bar :quux} that was fun!
</span><span class='line'>2015-06-14 14:26:48.963 | ERROR | nREPL-worker-2 | rabbet.core | Dividing failed!
</span><span class='line'>java.lang.ArithmeticException: Divide by zero
</span><span class='line'>  at clojure.lang.Numbers.divide(Numbers.java:158)
</span><span class='line'>  at clojure.lang.Numbers.divide(Numbers.java:3808)
</span><span class='line'>  at rabbet.core$eval12281.invoke(core.clj:16)
</span><span class='line'>  at clojure.lang.Compiler.eval(Compiler.java:6792)
</span><span class='line'>  at clojure.lang.Compiler.load(Compiler.java:7237)
</span><span class='line'>         &lt;--- snip ---&gt;
</span><span class='line'>  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
</span><span class='line'>  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
</span><span class='line'>  at java.lang.Thread.run(Thread.java:745)
</span></code></pre></td></tr></table></div></figure>


<p>You can see three interesting log lines, one for the <code>log/warn</code> call,
one for the <code>log/info</code> call, and one for the <code>log/error</code> call. Because
we passed the caught exception to the <code>log/error</code> call, the stack trace
of the exception is also printed to the log.</p>

<p>The log statements are timestamped (a good thing), indicate clearly
how bad the information they contain might be (another good thing),
and in the case of the exception you can even see where the exception
was thrown.</p>

<p>What you don&rsquo;t see is output from the <code>log/trace</code> and <code>log/debug</code>
calls. This is because we configured Log4j to output at the INFO level
for our namespace. Let&rsquo;s dig into that configuration.</p>

<h3>Configuration details</h3>

<p>Log4j is a fairly substantial library, but it has but a handful of
important concepts that can easily be explained by looking back at the
<code>log4j.properties</code> file.</p>

<h4>Log Levels</h4>

<p>Log4j defines the following levels:</p>

<ul>
<li>TRACE</li>
<li>DEBUG</li>
<li>INFO</li>
<li>WARN</li>
<li>ERROR</li>
<li>FATAL</li>
</ul>


<p>Obviously there&rsquo;s a semantic ordering here &ndash; the least bad is at the
top, the worst is at the bottom.</p>

<p>When logging some data you choose the log level that best represents
each log datum. In the example earlier, I logged a divide-by-zero
exception at the ERROR level (using the <code>log/error</code>
function). Conceptually, an ERROR is more severe than a WARNing, which
is in turn more severe than an INFO, etc. When you add log calls to
your code, add them at an appropriate level.</p>

<h4>Appenders</h4>

<p>Appenders are where log output gets written to. Log4j has a rich set
of loggers, and an API for creating your own. Some interesting
appenders are:</p>

<ul>
<li>ConsoleAppender &ndash; writes to standard out or standard error</li>
<li>FileAppender &ndash; writes to a log file</li>
<li>RollingFileAppender &ndash; writes to a log file, and also has options for
rolling the log with size-based criteria</li>
<li>DailyRollingFileAppender &ndash; writes to a log file, and rolls the log
with time-based criteria</li>
<li>SMTPAppender &ndash; sends emails</li>
<li>SyslogAppender &ndash; writes to Syslog</li>
<li>NTEventLogAppender &ndash; writes to Windows event log</li>
</ul>


<p>There are also third-party appenders, e.g. logging directly to Splunk.</p>

<p>Our <code>log4j.properties</code> defines only one appender. Interpreting lines 5
through 8 of the config, it is named <code>file</code>, and it is a
RollingFileAppender. It creates and logs to <code>log/rabbet.log</code>. It will
allow 1MB of log data to accumulate in the file before starting
writing to a new log file, and renaming the older log file(s). It will
keep a total of 10 old log files, and any older ones will get deleted
when log rolling occurs.</p>

<p>You can configure Log4j to output to multiple appenders at the same
time, each of which having a different active configuration. The most
common use case for this is having some log lines printed on standard
output, and having all log lines kept in a log file and with a more
detailed layout format.</p>

<h4>Loggers</h4>

<p>Loggers are what you make logging calls to.  They are hierarchical,
and control the threshold of the log level to output.  The hierarchy
is based on package and class naming (namespaces in Clojure). It&rsquo;s a
sparse tree, so if you don&rsquo;t define a logger for a particular
namespace, the closest ancestor in the tree will be used. Since
there&rsquo;s always a root logger, there&rsquo;s always an ancestor.</p>

<p>Line 1 of our <code>log4j.properties</code> defines the root logger as being at
level ERROR, and the logger named <code>file</code> is configured to listen at the
root logger level.</p>

<p>Line 3 defines a specialization: for the namespace <code>rabbet.core</code>, the
log threshold is set to INFO. The effect of this is that the active
log level for log statements in the <code>rabbet.core</code> namespace, or any
sub-namespace therein, will be increased to INFO. All other namespaces
are still covered by the root logger, which is logging at ERROR level.</p>

<h4>Layouts</h4>

<p>Layouts are how you specify what the formatting of the log output
is. There are a number of different layouts available (see the direct
known subclasses of the <a href="https://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/Layout.html">Layout class</a>) but I&rsquo;ll cover only
one: PatternLayout.</p>

<p>The last line in our <code>log4j.properties</code> describes the pattern we&rsquo;re
using for the <code>file</code> appender. Skipping over the justification and
padding details, <code>%d{yyyy-MM-dd HH:mm:ss.SSS} | %-5p | %t | %c | %m%n</code>
will format the log into pipe-delimited fields, with each line having
a timestamp, a log priority (level), the thread name, the class, and
the log message (followed by a newline).</p>

<p>There are other interesting things you might want in your log output,
or perhaps you&rsquo;d rather every field in the log was fixed-width. You
can find out more from the <a href="https://logging.apache.org/log4j/1.2/apidocs/index.html?org/apache/log4j/PatternLayout.html">PatternLayout API doc</a>.</p>

<h3>Logging without logging</h3>

<p>Recall the example above where the <code>(log/trace ...)</code> and <code>(log/debug
...)</code> calls resulted in no output. Looking at the log configuration
file, there are two lines are responsible for this behavior:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
</pre></td><td class='code'><pre><code class='text'><span class='line'># Set the overall log level for the `file` appender to ERROR:
</span><span class='line'>log4j.rootLogger=ERROR, file
</span><span class='line'>
</span><span class='line'># Override the log level for the `rabbet.core` namespace to INFO:
</span><span class='line'>log4j.logger.rabbet.core=INFO
</span></code></pre></td></tr></table></div></figure>


<p>So for the <code>rabbet.core</code> namespace, output for TRACE and DEBUG
messages is suppressed. This means you can add all kinds of log calls
to your source file, and then through the logger configuration set
whether those log statements are output to the log.</p>

<p>This configuration is fairly typical. ERROR logs for any namespaces
are always output to the log file, and more information is output for
the source for my project. I can leave all of the DEBUG and TRACE
calls in the code, and when I need to investigate a problem, I can
just increase the log level in log4j.properties and get lots more data
in the log.</p>

<h3>A quick aside: reading Clojure stack traces</h3>

<p>If you&rsquo;re new to stack traces, they can be a little intimidating.</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
<span class='line-number'>18</span>
<span class='line-number'>19</span>
<span class='line-number'>20</span>
<span class='line-number'>21</span>
<span class='line-number'>22</span>
<span class='line-number'>23</span>
<span class='line-number'>24</span>
<span class='line-number'>25</span>
<span class='line-number'>26</span>
<span class='line-number'>27</span>
<span class='line-number'>28</span>
</pre></td><td class='code'><pre><code class='text'><span class='line'>java.lang.ArithmeticException: Divide by zero
</span><span class='line'>  at clojure.lang.Numbers.divide(Numbers.java:158)
</span><span class='line'>  at clojure.lang.Numbers.divide(Numbers.java:3808)
</span><span class='line'>  at rabbet.core$eval12281.invoke(core.clj:16)
</span><span class='line'>  at clojure.lang.Compiler.eval(Compiler.java:6792)
</span><span class='line'>  at clojure.lang.Compiler.load(Compiler.java:7237)
</span><span class='line'>  at user$eval12257.invoke(form-init323843885648136810.clj:1)
</span><span class='line'>  at clojure.lang.Compiler.eval(Compiler.java:6792)
</span><span class='line'>  at clojure.lang.Compiler.eval(Compiler.java:6755)
</span><span class='line'>  at clojure.core$eval.invoke(core.clj:3079)
</span><span class='line'>  at clojure.main$repl$read_eval_print__7093$fn__7096.invoke(main.clj:240)
</span><span class='line'>  at clojure.main$repl$read_eval_print__7093.invoke(main.clj:240)
</span><span class='line'>  at clojure.main$repl$fn__7102.invoke(main.clj:258)
</span><span class='line'>  at clojure.main$repl.doInvoke(main.clj:258)
</span><span class='line'>  at clojure.lang.RestFn.invoke(RestFn.java:1523)
</span><span class='line'>  at clojure.tools.nrepl.middleware.interruptible_eval$evaluate$fn__1673.invoke(interruptible_eval.clj:53)
</span><span class='line'>  at clojure.lang.AFn.applyToHelper(AFn.java:152)
</span><span class='line'>  at clojure.lang.AFn.applyTo(AFn.java:144)
</span><span class='line'>  at clojure.core$apply.invoke(core.clj:628)
</span><span class='line'>  at clojure.core$with_bindings_STAR_.doInvoke(core.clj:1866)
</span><span class='line'>  at clojure.lang.RestFn.invoke(RestFn.java:425)
</span><span class='line'>  at clojure.tools.nrepl.middleware.interruptible_eval$evaluate.invoke(interruptible_eval.clj:51)
</span><span class='line'>  at clojure.tools.nrepl.middleware.interruptible_eval$interruptible_eval$fn__1715$fn__1718.invoke(interruptible_eval.clj:183)
</span><span class='line'>  at clojure.tools.nrepl.middleware.interruptible_eval$run_next$fn__1708.invoke(interruptible_eval.clj:152)
</span><span class='line'>  at clojure.lang.AFn.run(AFn.java:22)
</span><span class='line'>  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
</span><span class='line'>  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
</span><span class='line'>  at java.lang.Thread.run(Thread.java:745)
</span></code></pre></td></tr></table></div></figure>


<p>If this all looks like noise to you, here&rsquo;s how I suggest you break it
down:</p>

<ul>
<li>Read the stack trace from the top down.</li>
<li><strong>What type of exception was thrown?</strong>

<ul>
<li>Start at the top. <code>java.lang.ArithmeticException</code> &ndash; this is the
type of exception thrown. It&rsquo;s usually a good clue about the kind
of problem you&rsquo;re looking for.</li>
</ul>
</li>
<li><strong>What is the exception message?</strong>

<ul>
<li><code>Divide by zero</code> &ndash; this is the message the exception was created
with (e.g. <code>(throw (ArithmeticException. "Divide by
zero"))</code>). Sometimes this is very useful, but it&rsquo;s just a
descriptive field that a programmer can type some words into, so
you are relying on their descriptive skills.</li>
</ul>
</li>
<li><strong>Where did the exception get thrown?</strong>

<ul>
<li>The stack trace output has a standard structure &ndash; <code>at
&lt;package&gt;.&lt;packages&gt;.&lt;class&gt;.&lt;method&gt;(&lt;filename&gt;:&lt;line number&gt;)</code>,
and since the order comes from unwinding the stack, the top of the
stack trace is the &ldquo;most specific&rdquo;, or the deepest point in your
program. The bottom of the stack trace is going to be the &ldquo;lest
specific&rdquo;, the original initiating point in the code for the
execution stack (e.g. a <code>main</code> function).</li>
<li>The first line in the stack trace is where the exception was
thrown &ndash; <code>at clojure.lang.Numbers.divide(Numbers.java:158)</code>.
This first method call &ndash; <code>divide</code> in <code>clojure.lang.Numbers</code> &ndash; is
what threw the exception. At this point, we know a lot about the
problem: a divide-by-zero arithmetic exception was thrown by a
divide method call on a Number. That&rsquo;s really helpful to know what
we&rsquo;re looking for.</li>
</ul>
</li>
<li><strong>But what <em>really</em> caused the exception?</strong>

<ul>
<li>The first two lines of the stack trace are in Clojure&rsquo;s
functions. A decent heuristic is that there aren&rsquo;t bugs in core
Clojure or in Java, so if an exception is thrown the problem is
in your code. So skip over the lines for Clojure functions
and focus on those lines related to your own namespaces &ndash;
that&rsquo;s probably where the problem lies.</li>
<li>Reading downwards, the third line of the stack trace, <code>at
rabbet.core$eval12281.invoke(core.clj:16)</code> comes from one of our
source files. Since the Clojure compiler does all manner of clever
code generation things, you will see some seemingly spurious data
(in this case, we never wrote a function called <code>eval12281</code>, but
the Clojure compiler actually did).  You will quickly learn to
ignore the generated bits and see only the important
information. I squint my eyes and see <code>at rabbet.core(core.clj:16)</code>,
which tells me to go and look at line 16 in the source file that
defines the <code>rabbet.core</code> namespace, and whose name is
<code>core.clj</code>. So open up <code>src/rabbet/core.clj</code>, and see what on line
16 matches the rest of what you know about the problem.</li>
<li>In a real-world example you will need to repeat these last couple
of steps and keep working your way down the stack trace to get an
understanding of how the actual problem came about. Focus on stack
frames for namespaces you own.</li>
</ul>
</li>
</ul>


<h2>Dynamic Reconfiguration</h2>

<p>This is a coda to the main part of the article, but I sometimes find
it really useful to tweak the log configuration when I&rsquo;m getting the
project set up, and when I&rsquo;m debugging. Here are some of my use cases:</p>

<p>I like to be able to change the global log level (and without having
to restart the JVM). Sometimes it&rsquo;s when I&rsquo;ve scattered loads of trace
and debug log calls through the code and I want to increase the log
verbosity and see all of what&rsquo;s being emitted. Sometimes I want to
just see warnings and errors, so I want to decrease the verbosity.</p>

<p>Also, it&rsquo;s useful to be able to change the log level for a specific
namespace or package. The use case is similar: I&rsquo;ll scatter a load of
trace and debug calls through a namespace, and have the logger output
all of these log lines but keep the log output from other namespaces
fairly quiet.</p>

<p>The final use case I&rsquo;ll cover is reloading the logger configuration
file. I don&rsquo;t use this a lot, but if I&rsquo;m tweaking the logger patterns,
or trying out different log appenders, it&rsquo;s a big time saver to be
able to just edit the config file and call a <code>reload</code> function instead
of having to restart the JVM. It is possible to set up Log4J to do
this automatically, but I don&rsquo;t really need this under normal
circumstances, so a runtime approach is handy.</p>

<p>Before getting to the code that does this, I should note that there
are libraries that do loads of log config for you, including all of
the above and plenty more. I&rsquo;m only really interested in a subset of
their functionality, so I&rsquo;ll leave it as an exercise to the reader to
investigate these (I suggest <a href="https://github.com/malcolmsparks/clj-logging-config">clj-logging-config</a>).</p>

<h3>Source</h3>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
<span class='line-number'>18</span>
<span class='line-number'>19</span>
<span class='line-number'>20</span>
<span class='line-number'>21</span>
<span class='line-number'>22</span>
<span class='line-number'>23</span>
<span class='line-number'>24</span>
<span class='line-number'>25</span>
<span class='line-number'>26</span>
<span class='line-number'>27</span>
<span class='line-number'>28</span>
<span class='line-number'>29</span>
<span class='line-number'>30</span>
<span class='line-number'>31</span>
<span class='line-number'>32</span>
<span class='line-number'>33</span>
<span class='line-number'>34</span>
<span class='line-number'>35</span>
<span class='line-number'>36</span>
<span class='line-number'>37</span>
<span class='line-number'>38</span>
<span class='line-number'>39</span>
<span class='line-number'>40</span>
<span class='line-number'>41</span>
<span class='line-number'>42</span>
<span class='line-number'>43</span>
<span class='line-number'>44</span>
<span class='line-number'>45</span>
<span class='line-number'>46</span>
<span class='line-number'>47</span>
<span class='line-number'>48</span>
<span class='line-number'>49</span>
<span class='line-number'>50</span>
<span class='line-number'>51</span>
<span class='line-number'>52</span>
<span class='line-number'>53</span>
<span class='line-number'>54</span>
<span class='line-number'>55</span>
<span class='line-number'>56</span>
<span class='line-number'>57</span>
<span class='line-number'>58</span>
<span class='line-number'>59</span>
</pre></td><td class='code'><pre><code class='clojure'><span class='line'><span class="p">(</span><span class="kd">ns </span><span class="nv">rabbet.log</span>
</span><span class='line'>  <span class="p">(</span><span class="ss">:require</span> <span class="p">[</span><span class="nv">clojure.java.io</span> <span class="ss">:as</span> <span class="nv">io</span><span class="p">]</span>
</span><span class='line'>            <span class="p">[</span><span class="nv">clojure.set</span> <span class="ss">:as</span> <span class="nv">set</span><span class="p">])</span>
</span><span class='line'>  <span class="p">(</span><span class="ss">:import</span> <span class="p">(</span><span class="nf">org.apache.log4j</span> <span class="nv">Level</span>
</span><span class='line'>                             <span class="nv">Logger</span>
</span><span class='line'>                             <span class="nv">PropertyConfigurator</span><span class="p">)))</span>
</span><span class='line'>
</span><span class='line'><span class="p">(</span><span class="k">def </span><span class="nv">log-levels</span> <span class="p">{</span><span class="ss">:all</span> <span class="nv">Level/ALL</span>
</span><span class='line'>                 <span class="ss">:trace</span> <span class="nv">Level/TRACE</span>
</span><span class='line'>                 <span class="ss">:debug</span> <span class="nv">Level/DEBUG</span>
</span><span class='line'>                 <span class="ss">:info</span> <span class="nv">Level/INFO</span>
</span><span class='line'>                 <span class="ss">:warn</span> <span class="nv">Level/WARN</span>
</span><span class='line'>                 <span class="ss">:error</span> <span class="nv">Level/ERROR</span>
</span><span class='line'>                 <span class="ss">:fatal</span> <span class="nv">Level/FATAL</span>
</span><span class='line'>                 <span class="ss">:off</span> <span class="nv">Level/OFF</span><span class="p">})</span>
</span><span class='line'>
</span><span class='line'><span class="p">(</span><span class="kd">defn- </span><span class="nv">set-logger-level*</span>
</span><span class='line'>  <span class="p">[</span><span class="o">^</span><span class="nv">org.apache.log4j.Logger</span> <span class="nv">logger</span> <span class="nv">level</span><span class="p">]</span>
</span><span class='line'>  <span class="p">{</span><span class="ss">:pre</span> <span class="p">[(</span><span class="nf">log-levels</span> <span class="nv">level</span><span class="p">)]}</span>
</span><span class='line'>  <span class="p">(</span><span class="nf">.setLevel</span> <span class="nv">logger</span> <span class="p">(</span><span class="nf">log-levels</span> <span class="nv">level</span><span class="p">)))</span>
</span><span class='line'>
</span><span class='line'><span class="p">(</span><span class="kd">defn </span><span class="nv">set-root-logger-level!</span>
</span><span class='line'>  <span class="s">&quot;Sets the root logger to be at `level`.&quot;</span>
</span><span class='line'>  <span class="p">[</span><span class="nv">level</span><span class="p">]</span>
</span><span class='line'>  <span class="p">(</span><span class="nf">set-logger-level*</span> <span class="p">(</span><span class="nf">Logger/getRootLogger</span><span class="p">)</span>
</span><span class='line'>                     <span class="nv">level</span><span class="p">))</span>
</span><span class='line'>
</span><span class='line'><span class="p">(</span><span class="kd">defn </span><span class="nv">set-logger-level!</span>
</span><span class='line'>  <span class="s">&quot;Sets the specified `logger` to be at `level`.&quot;</span>
</span><span class='line'>  <span class="p">[</span><span class="nv">logger</span> <span class="nv">level</span><span class="p">]</span>
</span><span class='line'>  <span class="p">(</span><span class="nf">set-logger-level*</span> <span class="p">(</span><span class="nf">Logger/getLogger</span> <span class="nv">logger</span><span class="p">)</span>
</span><span class='line'>                     <span class="nv">level</span><span class="p">))</span>
</span><span class='line'>
</span><span class='line'><span class="p">(</span><span class="kd">defn </span><span class="nv">loggers-seq</span> <span class="p">[]</span>
</span><span class='line'>  <span class="p">(</span><span class="nb">-&gt; </span><span class="p">(</span><span class="nf">Logger/getRootLogger</span><span class="p">)</span>
</span><span class='line'>      <span class="nv">.getLoggerRepository</span>
</span><span class='line'>      <span class="nv">.getCurrentLoggers</span>
</span><span class='line'>      <span class="nv">enumeration-seq</span><span class="p">))</span>
</span><span class='line'>
</span><span class='line'><span class="p">(</span><span class="kd">defn </span><span class="nv">logger-levels</span> <span class="p">[</span><span class="nv">loggers</span><span class="p">]</span>
</span><span class='line'>  <span class="p">(</span><span class="nb">into </span><span class="p">{}</span>
</span><span class='line'>        <span class="p">(</span><span class="nb">for </span><span class="p">[</span><span class="nv">logger</span> <span class="nv">loggers</span><span class="p">]</span>
</span><span class='line'>          <span class="p">[(</span><span class="nf">.getName</span> <span class="nv">logger</span><span class="p">)</span> <span class="p">((</span><span class="nf">set/map-invert</span> <span class="nv">log-levels</span><span class="p">)</span> <span class="p">(</span><span class="nf">.getEffectiveLevel</span> <span class="nv">logger</span><span class="p">))])))</span>
</span><span class='line'>
</span><span class='line'><span class="p">(</span><span class="kd">defn </span><span class="nv">set-all-loggers-level!</span>
</span><span class='line'>  <span class="s">&quot;Sets the level of all configured loggers to be at `level`.&quot;</span>
</span><span class='line'>  <span class="p">[</span><span class="nv">level</span><span class="p">]</span>
</span><span class='line'>  <span class="p">(</span><span class="nb">doseq </span><span class="p">[</span><span class="nv">logger</span> <span class="p">(</span><span class="nf">loggers-seq</span><span class="p">)]</span>
</span><span class='line'>    <span class="p">(</span><span class="nf">set-logger-level*</span> <span class="nv">logger</span> <span class="nv">level</span><span class="p">)))</span>
</span><span class='line'>
</span><span class='line'><span class="p">(</span><span class="kd">defn </span><span class="nv">reload-config!</span>
</span><span class='line'>  <span class="s">&quot;Reconfigures log4j from a log4j.properties file on the classpath&quot;</span>
</span><span class='line'>  <span class="p">[]</span>
</span><span class='line'>  <span class="p">(</span><span class="nb">with-open </span><span class="p">[</span><span class="nv">config-stream</span>
</span><span class='line'>              <span class="p">(</span><span class="nb">-&gt; </span><span class="s">&quot;log4j.properties&quot;</span>
</span><span class='line'>                  <span class="nv">io/resource</span>
</span><span class='line'>                  <span class="nv">io/file</span>
</span><span class='line'>                  <span class="nv">io/input-stream</span><span class="p">)]</span>
</span><span class='line'>    <span class="p">(</span><span class="nf">PropertyConfigurator/configure</span> <span class="nv">config-stream</span><span class="p">)))</span>
</span></code></pre></td></tr></table></div></figure>


<h3>Usage</h3>

<p>Three functions are useful, and here&rsquo;s how you would use them:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
</pre></td><td class='code'><pre><code class='clojure'><span class='line'><span class="p">(</span><span class="nf">require</span> <span class="o">&#39;</span><span class="p">[</span><span class="nv">rabbet.log</span> <span class="ss">:as</span> <span class="nv">rlog</span><span class="p">])</span>
</span><span class='line'>
</span><span class='line'><span class="c1">;; Reload the config file:</span>
</span><span class='line'><span class="p">(</span><span class="nf">rlog/reload-config!</span><span class="p">)</span>
</span><span class='line'>
</span><span class='line'><span class="c1">;; Set all loggers to emit errors and worse:</span>
</span><span class='line'><span class="p">(</span><span class="nf">rlog/set-all-loggers-level!</span> <span class="ss">:all</span><span class="p">)</span>
</span><span class='line'>
</span><span class='line'><span class="c1">;; Set one specific namespace to emit all log events:</span>
</span><span class='line'><span class="p">(</span><span class="nf">rlog/set-logger-level!</span> <span class="s">&quot;rabbet.foo&quot;</span> <span class="ss">:all</span><span class="p">)</span>
</span></code></pre></td></tr></table></div></figure>


<h2>Summary</h2>

<p>Do logging! I&rsquo;ve covered how easy it is to set up
clojure.tools.logging logging to Log4j, and shown how to do some basic
logger configuration to get you up and running.</p>

<p>The hard bit is in balancing what to log, how much to log, and how
much to keep. I recommend a liberal sprinkling of log calls, but pick
appropriate levels for the calls &ndash; lots of <code>trace</code> and <code>debug</code> calls,
but hopefully not too many <code>error</code>s. If an exception is thrown,
<code>catch</code> blocks are an obvious place to drop a log call. Use this arity
of the log calls:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
</pre></td><td class='code'><pre><code class='clojure'><span class='line'><span class="p">(</span><span class="nf">try</span>
</span><span class='line'>  <span class="p">(</span><span class="nf">stuff</span> <span class="nv">...</span><span class="p">)</span>
</span><span class='line'>  <span class="p">(</span><span class="nf">catch</span> <span class="nv">Exception</span> <span class="nv">e</span>
</span><span class='line'>    <span class="p">(</span><span class="nf">log/error</span> <span class="nv">e</span> <span class="s">&quot;foobar went wrong&quot;</span><span class="p">))</span>
</span></code></pre></td></tr></table></div></figure>


<p>Add log calls, put useful data into the calls, and tune the logger
configuration to your liking. If you want more or less log output, you
can leave the code alone and just change the configuration file, or
even change the active configuration at runtime.</p>

<p>Please get in touch if you&rsquo;d like to see more on this, or if you have
any kind of feedback. <a href="https://twitter.com/iantruslove">@iantruslove</a></p>

<p><small>Image Credit: <a href="http://chestofbooks.com/home-improvement/woodworking/Cabinet-Making/">http://chestofbooks.com/home-improvement/woodworking/Cabinet-Making/</a></small></p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Clojure in production]]></title>
    <link href="http://brownsofa.org/blog/2015/05/10/clojure-in-production/"/>
    <updated>2015-05-10T12:45:00-06:00</updated>
    <id>http://brownsofa.org/blog/2015/05/10/clojure-in-production</id>
    <content type="html"><![CDATA[<p>I was chatting with <a href="https://twitter.com/danoyoung">@danoyoung</a> on IRC
the other day about embedding a nREPL server, and about using that as
the basis for a talk at our local
<a href="http://www.meetup.com/denofclojure/">Clojure meetup</a>.</p>

<p>I&rsquo;ve also been in and seen conversations about all of the effort and
knowledge that needs to go into making some Clojure code be a &ldquo;real&rdquo;
software product.</p>

<p>Along these lines of thinking, I have an idea for a series of posts
about the kinds of things one does when putting Clojure into
production. Each will build on the previous, hopefully resulting in a
nice multipart article and corresponding repo on Github to help
beginners see some patterns and ideas for building Clojure services.</p>

<p><strike>The first post will be about logging. Updates coming soon&hellip;</strike></p>

<p>Updates within&hellip;</p>

<!-- more -->


<ul>
<li>2015-06-14: added the post on <a href="http://brownsofa.org/blog/2015/06/14/clojure-in-production-logging/">Logging</a>.</li>
</ul>

]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Querying Elasticsearch from Hive]]></title>
    <link href="http://brownsofa.org/blog/2015/03/08/querying-elasticsearch-from-hive/"/>
    <updated>2015-03-08T16:56:00-06:00</updated>
    <id>http://brownsofa.org/blog/2015/03/08/querying-elasticsearch-from-hive</id>
    <content type="html"><![CDATA[<p>I wanted to query ES from Hive. They seem like really interesting, complementary tools.</p>

<h2>Setup</h2>

<p>Obviously I needed Elasticsearch and Hive to be running. The former is
fairly straightforward, the latter requires a basic Hadoop stack.</p>

<p>I have been playing with the Cloudera distribution, and for a cluster
it is great, but for this I don&rsquo;t need the (significant) overhead.</p>

<p>So I found a <a href="https://github.com/congdang/vagrant-hadoop-hive">Vagrant setup</a> that did a bunch of what I needed, fixed a
bunch of issues, added Elasticsearch, and pushed up
<a href="https://github.com/iantruslove/hadoop-hive-elasticsearch-vm">hadoop-hive-elasticsearch-vm</a> &ndash; a single-node ES and Hive cluster.</p>

<h2>What I&rsquo;m trying to accomplish</h2>

<ul>
<li>ES aggregations are cool, but I have definitely found use cases
where they don&rsquo;t do all that I need.</li>
<li>I&rsquo;m trying to do things like calculating <a href="http://en.wikipedia.org/wiki/Tf%25E2%2580%2593idf">TF-IDF</a> type statistics for
documents and groups of documents.</li>
<li>The tricky thing with aggregations was stuff like summing TFs across
a whole account.</li>
<li>These kinds of things are really easy with SQL, so it seems like
ES + Hive (or later ES + Spark) would be a very powerful
combination.</li>
</ul>


<!-- more -->


<h2>Add some data to Elasticsearch</h2>

<p>I have a host <code>hadoop-hive-elasticsearch</code> running standard
installations of Elasticsearch and Hive, as close to out of the box as
one would reasonably get.</p>

<p>Create an index in Elasticsearch:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class='sh'><span class='line'>curl -v -XPUT http://hadoop-hive-elasticsearch:9200/idx_foo
</span></code></pre></td></tr></table></div></figure>


<p>PUT the mapping:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
<span class='line-number'>18</span>
<span class='line-number'>19</span>
<span class='line-number'>20</span>
<span class='line-number'>21</span>
<span class='line-number'>22</span>
<span class='line-number'>23</span>
</pre></td><td class='code'><pre><code class='sh'><span class='line'>curl -v -XPUT <span class="s1">&#39;http://hadoop-hive-elasticsearch:9200/idx_foo/_mapping/analysis?ignore_conflicts=true&#39;</span> -d <span class="s1">&#39;{</span>
</span><span class='line'><span class="s1">  &quot;analysis&quot; : {</span>
</span><span class='line'><span class="s1">    &quot;properties&quot; : {</span>
</span><span class='line'><span class="s1">      &quot;analyserVersion&quot; : {</span>
</span><span class='line'><span class="s1">        &quot;type&quot; : &quot;string&quot;,</span>
</span><span class='line'><span class="s1">        &quot;store&quot; : &quot;true&quot;,</span>
</span><span class='line'><span class="s1">        &quot;index&quot; : &quot;not_analyzed&quot;</span>
</span><span class='line'><span class="s1">      },</span>
</span><span class='line'><span class="s1">      &quot;analysisTime&quot; : {</span>
</span><span class='line'><span class="s1">        &quot;type&quot; : &quot;date&quot;,</span>
</span><span class='line'><span class="s1">        &quot;format&quot; : &quot;date_optional_time&quot;</span>
</span><span class='line'><span class="s1">      },</span>
</span><span class='line'><span class="s1">      &quot;documentIdentifier&quot; : {</span>
</span><span class='line'><span class="s1">        &quot;type&quot; : &quot;string&quot;,</span>
</span><span class='line'><span class="s1">        &quot;store&quot; : true,</span>
</span><span class='line'><span class="s1">        &quot;index&quot; : &quot;not_analyzed&quot;</span>
</span><span class='line'><span class="s1">      },</span>
</span><span class='line'><span class="s1">      &quot;topics&quot; : {</span>
</span><span class='line'><span class="s1">        &quot;type&quot; : &quot;string&quot;</span>
</span><span class='line'><span class="s1">      }</span>
</span><span class='line'><span class="s1">    }</span>
</span><span class='line'><span class="s1">  }</span>
</span><span class='line'><span class="s1">}&#39;</span>
</span></code></pre></td></tr></table></div></figure>


<p>Use the bulk API to add some docs:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
<span class='line-number'>18</span>
<span class='line-number'>19</span>
<span class='line-number'>20</span>
</pre></td><td class='code'><pre><code class='sh'><span class='line'>curl -v -XPOST http://hadoop-hive-elasticsearch:9200/_bulk -d <span class="s1">&#39;</span>
</span><span class='line'><span class="s1">{ &quot;create&quot;: { &quot;_index&quot;: &quot;idx_foo&quot;, &quot;_type&quot;: &quot;analysis&quot; } }</span>
</span><span class='line'><span class="s1">{ &quot;analyserVersion&quot;: &quot;0.0.1&quot;, &quot;analysisTime&quot;: &quot;2015-03-07T16:12:00Z&quot;, &quot;documentIdentifier&quot;: &quot;doc1&quot;, &quot;topics&quot;: [&quot;business&quot;, &quot;collaboration&quot;, &quot;lifehacks&quot;, &quot;email&quot;] }</span>
</span><span class='line'><span class="s1">{ &quot;create&quot;: { &quot;_index&quot;: &quot;idx_foo&quot;, &quot;_type&quot;: &quot;analysis&quot; } }</span>
</span><span class='line'><span class="s1">{ &quot;analyserVersion&quot;: &quot;0.0.1&quot;, &quot;analysisTime&quot;: &quot;2015-03-07T16:12:01Z&quot;, &quot;documentIdentifier&quot;: &quot;doc2&quot;, &quot;topics&quot;: [&quot;sports&quot;, &quot;basketball&quot;] }</span>
</span><span class='line'><span class="s1">{ &quot;create&quot;: { &quot;_index&quot;: &quot;idx_foo&quot;, &quot;_type&quot;: &quot;analysis&quot; } }</span>
</span><span class='line'><span class="s1">{ &quot;analyserVersion&quot;: &quot;0.0.1&quot;, &quot;analysisTime&quot;: &quot;2015-03-07T16:12:02Z&quot;, &quot;documentIdentifier&quot;: &quot;doc3&quot;, &quot;topics&quot;: [&quot;lifehacks&quot;, &quot;wardrobe&quot;] }</span>
</span><span class='line'><span class="s1">{ &quot;create&quot;: { &quot;_index&quot;: &quot;idx_foo&quot;, &quot;_type&quot;: &quot;analysis&quot; } }</span>
</span><span class='line'><span class="s1">{ &quot;analyserVersion&quot;: &quot;0.0.1&quot;, &quot;analysisTime&quot;: &quot;2015-03-07T16:12:03Z&quot;, &quot;documentIdentifier&quot;: &quot;doc4&quot;, &quot;topics&quot;: [&quot;sports&quot;, &quot;snowboarding&quot;, &quot;mountains&quot;] }</span>
</span><span class='line'><span class="s1">{ &quot;create&quot;: { &quot;_index&quot;: &quot;idx_foo&quot;, &quot;_type&quot;: &quot;analysis&quot; } }</span>
</span><span class='line'><span class="s1">{ &quot;analyserVersion&quot;: &quot;0.0.1&quot;, &quot;analysisTime&quot;: &quot;2015-03-07T16:12:04Z&quot;, &quot;documentIdentifier&quot;: &quot;doc5&quot;, &quot;topics&quot;: [&quot;outdoors&quot;, &quot;hiking&quot;, &quot;mountains&quot;, &quot;lakes&quot;] }</span>
</span><span class='line'><span class="s1">{ &quot;create&quot;: { &quot;_index&quot;: &quot;idx_foo&quot;, &quot;_type&quot;: &quot;analysis&quot; } }</span>
</span><span class='line'><span class="s1">{ &quot;analyserVersion&quot;: &quot;0.0.1&quot;, &quot;analysisTime&quot;: &quot;2015-03-07T16:12:05Z&quot;, &quot;documentIdentifier&quot;: &quot;doc6&quot;, &quot;topics&quot;: [&quot;business&quot;, &quot;sales&quot;, &quot;cars&quot;] }</span>
</span><span class='line'><span class="s1">{ &quot;create&quot;: { &quot;_index&quot;: &quot;idx_foo&quot;, &quot;_type&quot;: &quot;analysis&quot; } }</span>
</span><span class='line'><span class="s1">{ &quot;analyserVersion&quot;: &quot;0.0.1&quot;, &quot;analysisTime&quot;: &quot;2015-03-07T16:12:06Z&quot;, &quot;documentIdentifier&quot;: &quot;doc7&quot;, &quot;topics&quot;: [&quot;jeep&quot;, &quot;cars&quot;, &quot;outdoors&quot;, &quot;off-roading&quot;] }</span>
</span><span class='line'><span class="s1">{ &quot;create&quot;: { &quot;_index&quot;: &quot;idx_foo&quot;, &quot;_type&quot;: &quot;analysis&quot; } }</span>
</span><span class='line'><span class="s1">{ &quot;analyserVersion&quot;: &quot;0.0.1&quot;, &quot;analysisTime&quot;: &quot;2015-03-07T16:12:07Z&quot;, &quot;documentIdentifier&quot;: &quot;doc8&quot;, &quot;topics&quot;: [&quot;sports&quot;, &quot;fly fishing&quot;, &quot;lakes&quot;] }</span>
</span><span class='line'><span class="s1">{ &quot;create&quot;: { &quot;_index&quot;: &quot;idx_foo&quot;, &quot;_type&quot;: &quot;analysis&quot; } }</span>
</span><span class='line'><span class="s1">{ &quot;analyserVersion&quot;: &quot;0.0.1&quot;, &quot;analysisTime&quot;: &quot;2015-03-07T16:12:08Z&quot;, &quot;documentIdentifier&quot;: &quot;doc9&quot;, &quot;topics&quot;: [&quot;programming&quot;, &quot;clojure&quot;, &quot;databases&quot;] }</span>
</span><span class='line'><span class="s1">&#39;</span>
</span></code></pre></td></tr></table></div></figure>


<p>So now the ES instance has an index called <code>idx_foo</code>, with a handful
of documents belonging to one document type.</p>

<h2>Hive Time<a id="sec-1-4"></a></h2>

<p>Create a database in Hive to use</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
</pre></td><td class='code'><pre><code class='sql'><span class='line'><span class="k">CREATE</span> <span class="k">DATABASE</span> <span class="n">es_test</span><span class="p">;</span>
</span><span class='line'><span class="n">USE</span> <span class="n">es_test</span><span class="p">;</span>
</span></code></pre></td></tr></table></div></figure>


<p>Create a table. It needs to be an external table and pull data in from
Elasticsearch.</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
</pre></td><td class='code'><pre><code class='sql'><span class='line'><span class="c1">-- DROP TABLE foo_analysis_doc_ids;</span>
</span><span class='line'>
</span><span class='line'><span class="k">CREATE</span> <span class="k">EXTERNAL</span> <span class="k">TABLE</span> <span class="n">foo_analysis_doc_ids</span> <span class="p">(</span>
</span><span class='line'>  <span class="n">analyser_version</span> <span class="n">STRING</span><span class="p">,</span>
</span><span class='line'>  <span class="n">analysis_time</span> <span class="k">TIMESTAMP</span><span class="p">,</span>
</span><span class='line'>  <span class="n">doc_id</span> <span class="n">STRING</span><span class="p">,</span>
</span><span class='line'>  <span class="n">topics</span> <span class="nb">ARRAY</span><span class="o">&lt;</span><span class="n">STRING</span><span class="o">&gt;</span>
</span><span class='line'><span class="p">)</span>
</span><span class='line'><span class="n">STORED</span> <span class="k">BY</span> <span class="s1">&#39;org.elasticsearch.hadoop.hive.EsStorageHandler&#39;</span>
</span><span class='line'><span class="n">TBLPROPERTIES</span><span class="p">(</span><span class="s1">&#39;es.resource&#39;</span> <span class="o">=</span> <span class="s1">&#39;idx_foo/analysis&#39;</span><span class="p">,</span>
</span><span class='line'>              <span class="s1">&#39;es.mapping.names&#39;</span> <span class="o">=</span> <span class="s1">&#39;doc_id:documentIdentifier, analysis_time:analysisTime, analyser_version:analyserVersion&#39;</span><span class="p">);</span>
</span></code></pre></td></tr></table></div></figure>


<p>It turned out that mapping column names is useful.</p>

<p>Querying ES from Hive:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class='sql'><span class='line'><span class="k">SELECT</span> <span class="o">*</span> <span class="k">FROM</span> <span class="n">foo_analysis_doc_ids</span><span class="p">;</span>
</span></code></pre></td></tr></table></div></figure>


<pre><code>0.0.1   2015-03-07 16:12:00     be87f0b5-faad-4513-827c-15a635844eaa    ["business","collaboration","lifehacks","email"]
0.0.1   2015-03-07 16:12:01     doc2    ["sports","basketball"]
0.0.1   2015-03-07 16:12:05     doc6    ["business","sales","cars"]
0.0.1   2015-03-07 16:12:06     doc7    ["jeep","cars","outdoors","off-roading"]
0.0.1   2015-03-07 16:12:00     b0289460-f6ef-4309-911a-d27e52155ae7    ["business","collaboration","lifehacks","email"]
0.0.1   2015-03-07 16:12:02     doc3    ["lifehacks","wardrobe"]
0.0.1   2015-03-07 16:12:07     doc8    ["sports","fly fishing","lakes"]
0.0.1   2015-03-07 16:12:03     doc4    ["sports","snowboarding","mountains"]
0.0.1   2015-03-07 16:12:08     doc9    ["programming","clojure","databases"]
0.0.1   2015-03-07 16:12:00     doc1    ["business","collaboration","lifehacks","email"]
0.0.1   2015-03-07 16:12:04     doc5    ["outdoors","hiking","mountains","lakes"]
Time taken: 0.038 seconds, Fetched: 11 row(s)
</code></pre>

<p>Great. You can even see here there are a couple of documents with UUID
identifiers that I had in ES from experiments along the way that
didn&rsquo;t quite get written up here.</p>

<p>So let&rsquo;s do some SQL-y things with Elasticsearch data: retrieve a list of unique topics.</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
</pre></td><td class='code'><pre><code class='sql'><span class='line'><span class="k">SELECT</span> <span class="k">DISTINCT</span><span class="p">(</span><span class="n">topic_list</span><span class="p">.</span><span class="n">t</span><span class="p">)</span> <span class="k">AS</span> <span class="n">topic</span>
</span><span class='line'><span class="k">FROM</span> <span class="p">(</span><span class="k">SELECT</span> <span class="n">explode</span><span class="p">(</span><span class="n">f</span><span class="p">.</span><span class="n">topics</span><span class="p">)</span> <span class="k">AS</span> <span class="n">t</span> <span class="k">FROM</span> <span class="n">foo_analysis_doc_ids</span> <span class="k">AS</span> <span class="n">f</span><span class="p">)</span> <span class="k">AS</span> <span class="n">topic_list</span>
</span><span class='line'><span class="k">ORDER</span> <span class="k">BY</span> <span class="n">topic</span><span class="p">;</span>
</span></code></pre></td></tr></table></div></figure>


<pre><code>Query ID = vagrant_20150308155959_a966862b-4aa0-489d-867f-74b880a952a1
Total jobs = 2
Launching Job 1 out of 2
Number of reduce tasks not specified. Estimated from input data size: 1
In order to change the average load for a reducer (in bytes):
  set hive.exec.reducers.bytes.per.reducer=&lt;number&gt;
In order to limit the maximum number of reducers:
  set hive.exec.reducers.max=&lt;number&gt;
In order to set a constant number of reducers:
  set mapred.reduce.tasks=&lt;number&gt;
Starting Job = job_201503081508_0007, Tracking URL = http://localhost:50030/jobdetails.jsp?jobid=job_201503081508_0007
&lt;SNIP&gt;
Stage-Stage-1: Map: 5  Reduce: 1   Cumulative CPU: 8.57 sec   HDFS Read: 190090 HDFS Write: 617 SUCCESS
Stage-Stage-2: Map: 1  Reduce: 1   Cumulative CPU: 1.86 sec   HDFS Read: 1113 HDFS Write: 181 SUCCESS
Total MapReduce CPU Time Spent: 10 seconds 430 msec
OK
basketball
business
cars
clojure
collaboration
databases
email
fly fishing
hiking
jeep
lakes
lifehacks
mountains
off-roading
outdoors
programming
sales
snowboarding
sports
wardrobe
Time taken: 41.09 seconds, Fetched: 20 row(s)
</code></pre>

<p>In doing the previous I ran into a problem that looked like the
elasticsearch-hadoop jar wasn&rsquo;t distributed to the hadoop cluster.</p>

<ul>
<li>Having the JAR in the Hive <code>lib</code> dir didn&rsquo;t work.</li>
<li>Putting the JAR into the Hadoop <code>lib</code> dir didn&rsquo;t work.</li>
<li>Using the Hive shell&rsquo;s <code>ADD JAR &lt;file-path&gt;</code> command DID WORK!</li>
<li>This is something that will need to be addressed systematically for
a real-world scenario &ndash; something like distrbuting the JAR via HDFS.</li>
</ul>


<p>Note the time taken to do that &ndash; 40 seconds. It ended up firing two
map-reduce jobs, one for the <code>explode</code>, and one for the <code>ORDER
BY</code>.</p>

<p>For local testing, there&rsquo;s a local mode to help:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class='sql'><span class='line'><span class="k">SET</span> <span class="n">mapred</span><span class="p">.</span><span class="n">job</span><span class="p">.</span><span class="n">tracker</span><span class="o">=</span><span class="k">local</span><span class="p">;</span>
</span></code></pre></td></tr></table></div></figure>


<p>The same query then takes 4 seconds.</p>

<p>Now, how about something like &ldquo;what&rsquo;s the mapping of topics to
documents?&rdquo; This has a <a href="https://cwiki.apache.org/confluence/display/Hive/Common%2BTable%2BExpression">CTE</a>, a <code>SELECT DISTINCT</code>, a <code>JOIN</code> &ndash; definitely
interesting stuff to layer on top of an Elasticsearch index.</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
</pre></td><td class='code'><pre><code class='sql'><span class='line'><span class="k">WITH</span> <span class="n">topic_explosion</span> <span class="k">AS</span> <span class="p">(</span><span class="k">SELECT</span> <span class="n">explode</span><span class="p">(</span><span class="n">f</span><span class="p">.</span><span class="n">topics</span><span class="p">)</span> <span class="k">AS</span> <span class="n">t</span> <span class="k">FROM</span> <span class="n">foo_analysis_doc_ids</span> <span class="k">AS</span> <span class="n">f</span><span class="p">),</span>
</span><span class='line'><span class="n">topics</span> <span class="k">AS</span> <span class="p">(</span><span class="k">SELECT</span> <span class="k">DISTINCT</span><span class="p">(</span><span class="n">t</span><span class="p">)</span> <span class="k">AS</span> <span class="n">topic</span> <span class="k">FROM</span> <span class="n">topic_explosion</span><span class="p">)</span>
</span><span class='line'><span class="k">SELECT</span> <span class="n">topics</span><span class="p">.</span><span class="n">topic</span><span class="p">,</span> <span class="n">f</span><span class="p">.</span><span class="n">doc_id</span>
</span><span class='line'><span class="k">FROM</span> <span class="n">foo_analysis_doc_ids</span> <span class="n">f</span><span class="p">,</span> <span class="n">topics</span>
</span><span class='line'><span class="k">WHERE</span> <span class="n">array_contains</span><span class="p">(</span><span class="n">f</span><span class="p">.</span><span class="n">topics</span><span class="p">,</span> <span class="n">topics</span><span class="p">.</span><span class="n">topic</span><span class="p">)</span>
</span><span class='line'><span class="k">ORDER</span> <span class="k">BY</span> <span class="n">topic</span><span class="p">,</span> <span class="n">doc_id</span><span class="p">;</span>
</span></code></pre></td></tr></table></div></figure>


<pre><code>Total MapReduce CPU Time Spent: 0 msec
OK
basketball      doc2
business        b0289460-f6ef-4309-911a-d27e52155ae7
business        be87f0b5-faad-4513-827c-15a635844eaa
business        doc1
business        doc6
cars    doc6
cars    doc7
clojure doc9
collaboration   b0289460-f6ef-4309-911a-d27e52155ae7
collaboration   be87f0b5-faad-4513-827c-15a635844eaa
collaboration   doc1
databases       doc9
email   b0289460-f6ef-4309-911a-d27e52155ae7
email   be87f0b5-faad-4513-827c-15a635844eaa
email   doc1
fly fishing     doc8
hiking  doc5
jeep    doc7
lakes   doc5
lakes   doc8
lifehacks       b0289460-f6ef-4309-911a-d27e52155ae7
lifehacks       be87f0b5-faad-4513-827c-15a635844eaa
lifehacks       doc1
lifehacks       doc3
mountains       doc4
mountains       doc5
off-roading     doc7
outdoors        doc5
outdoors        doc7
programming     doc9
sales   doc6
snowboarding    doc4
sports  doc2
sports  doc4
sports  doc8
wardrobe        doc3
Time taken: 5.945 seconds, Fetched: 36 row(s)
</code></pre>

<h2>Looking ahead&#x2026;</h2>

<p>I can see some interesting experiments ahead:</p>

<ul>
<li>How can I effectively work across multiple ES indexes? E.g. if
there&rsquo;s one index per account, and analyses go into that, how can
aggregate statistics be calculated across accounts?</li>
<li>Hive uses Hadoop MR to distribute work. This is slow. Would <a href="http://pig.apache.org/">Pig</a> do
any better? How about <a href="https://spark.apache.org/">Spark</a>? How would the three perform at scale?</li>
</ul>

]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Debugging in Clojure: Tools]]></title>
    <link href="http://brownsofa.org/blog/2014/08/03/debugging-in-clojure-tools/"/>
    <updated>2014-08-03T18:20:00-06:00</updated>
    <id>http://brownsofa.org/blog/2014/08/03/debugging-in-clojure-tools</id>
    <content type="html"><![CDATA[<p><img class="right" src="http://brownsofa.org/images/debugging-in-clojure/butterfly_net.jpg" title="Butterfly net" alt="Butterfly net"></p>

<p><a href="http://brownsofa.org/blog/2014/07/17/debugging-in-clojure-thoughts/">Part one</a> covered the types of things I&rsquo;m considering when talking
about &ldquo;debugging&rdquo;, and the process by which I debug code.</p>

<p>This part is about writing debuggable code, and the tools I use or
have seen to debug code: the REPL, println debugging and better,
tracing with Spyscope and clojure.tools.trace, and other assorted good
things.</p>

<!-- more -->


<p><strong>Contents:</strong></p>

<ul>
<li>Constructing comprehensible systems

<ul>
<li>Easy to exercise</li>
<li>Easily observed behavior</li>
<li>Unit tests</li>
<li>Purity and state</li>
<li>Understand your assumptions</li>
</ul>
</li>
<li>Tools and techniques

<ul>
<li>The REPL</li>
<li>println</li>
<li>Tracing with Spyscope</li>
<li>Macros for debugging let forms</li>
<li>Tracing with clojure.tools.trace</li>
<li>Fogus&rsquo;s breakpoint macro</li>
<li>Other bits</li>
</ul>
</li>
</ul>


<h1>Constructing comprehensible systems</h1>

<p>So, debugging is essentially a process for gaining a more in-depth
understanding about how one particular aspect of our system
operates. How can Clojure development in particular help with that,
and how can we make that easier when developing in Clojure?</p>

<p>In short: write code that is easy to exercise in the REPL, whose
behavior is easily observed, and with unit test coverage.</p>

<h2>Easy to exercise</h2>

<p>Make it easy to construct valid data to pass to your function.  You
will be greatly assisted by knowing exactly what constitutes valid.
Docstrings, <a href="http://blog.fogus.me/2009/12/21/clojures-pre-and-post/">pre- and post-conditions</a>, <a href="http://clojuredocs.org/clojure_core/clojure.core/assert">assertions</a>,
<a href="https://github.com/Prismatic/schema">schema</a> are all helpful.  Fewer arguments keep it simpler.  Provide
helper functions to help construct complex intermediate data
structures.</p>

<p>The usual programming practices have their usual benefits.  Write
clear, well-encapsulated, cohesive-but-not-coupled, singly-responsible
code (functions, in our case).</p>

<h2>Easily observed behavior</h2>

<p>Your functions should express a concise piece of behavior, and your
code will be easiest to understand if that behavior is simple, and the
observation is as simple as inspecting the return value.</p>

<p>If the cyclomatic complexity of the function is high, observing the
function&rsquo;s behavior might also require observing the control flow
(yuck).  If the return value of your function needs significant
parsing or decoding to determine whether it operated correctly,
consider whether the function has too many responsibilities.</p>

<h2>Unit tests</h2>

<p>I debated for a second whether tests are part of comprehensible
systems, or whether they are tools.  They are an integral part of any
code base, so here they belong.  Tests are your infallible long-term
memory, a playground for experimentation, your sanity check.  Easily
exercised, easily verified functions are easily unit tested.</p>

<h2>Purity and state</h2>

<p>Writing pure functions aids the system&rsquo;s comprehensibility enormously.
<code>f(x) = f(x)</code> when your program starts up, or when it&rsquo;s crashing, and
whether <code>f</code> is running on an EC2 node or in your REPL.  When your code
is a composition of pure functions, reasoning about the code is far
simpler.  This is probably the single biggest contributor to why one
can effectively program in Clojure without a visual debugger: with
pure functions, the state of the system is always external to the
code.</p>

<p>Reality is a little messy.  Applications are infrequently entirely a
composition of pure functions.  You have databases, user input,
network and disk I/O to contend with.  Push the non-pure aspects of
your system to the edges, encapsulate them, and stop your abstractions
from leaking too far.</p>

<p>So, why?  You need to be facile enough with your code and tools so you
can observe the conditions that cause the system to behave
&ldquo;unexpectedly&rdquo;.  If your code is structured such that it is easy to
run in the REPL (and pure functions generally are), it will be easy to
reproduce the faulty behavior in the REPL (and later in tests), and
understand what the system is doing.</p>

<p>If the corpus of code under examination is too large for immediate
comprehension (in reductionist terms, &ldquo;emergent behavior&rdquo;?), divide
and conquer. By looking at the problem into smaller and smaller chunks
(i.e. the layers of composed functions), you exclude possibilities of
where the source of the problem is, until the answer jumps out at you.</p>

<h2>Understand your assumptions</h2>

<p>With Occam&rsquo;s Razor in mind, be ready to question your assumptions.
There&rsquo;s always the possibility a bug in Clojure core is the cause of
your problem.  It&rsquo;s not very likely, so don&rsquo;t start there.  The most
likely problem is in your understanding of the problem, or in your
expression of the solution (substitute &ldquo;your&rdquo; for whomever wrote the
code), so the assumptions built in here are the first ones to
question, to check, and to verify.</p>

<h1>Tools and techniques</h1>

<p>Finally, the Clojure debugging tools easily available to you in Emacs.
They all are
typically employed in <a href="http://brownsofa.org/blog/2014/07/17/debugging-in-clojure-thoughts/#process">steps 2 and 3</a> of the debugging algorithm,
and each support one or more of the following:</p>

<ul>
<li>executing code</li>
<li>observing the result of function calls</li>
<li>observing intermediate calculations</li>
<li>observing control flow</li>
</ul>


<h2>The REPL</h2>

<p>It&rsquo;s obvious, but you need to run the code to see what it does.  Use
the REPL to do this.  In Emacs, you will likely be using
<a href="">cider-mode</a> to fire up a REPL via <a href="">Leiningen</a>.</p>

<p>A selection of cider commands for the uninitiated:</p>

<ul>
<li>Use <code>C-c M-n</code> or <code>M-x cider-repl-set-ns</code> to switch to a source
file&rsquo;s namespace.</li>
<li><code>C-c C-k</code> or <code>M-x cider-load-current-buffer</code> loads the current
source file in the REPL.</li>
<li><code>C-c C-e</code> or <code>M-x cider-eval-last-sexp</code> evaluates an S-expression
and prints the result in the mini buffer.</li>
<li><code>C-c M-p</code> or <code>M-x cider-insert-last-sexp-in-repl</code> copies a
S-expression into the REPL and switches buffers to the REPL ready for
you to hit Enter and evaluate the code.</li>
</ul>


<p>You may have different key bindings to these.</p>

<h2>println</h2>

<p>Showing result values, inspecting intermediate calculation results,
shining a light into execution paths, <code>println</code> can do it all.  Some
uses of println I&rsquo;ve seen:</p>

<p>Print out a number of values at the same time by throwing them into a
map and printing out the map:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
</pre></td><td class='code'><pre><code class='clojure'><span class='line'><span class="c1">;; instead of:</span>
</span><span class='line'><span class="p">(</span><span class="nb">println </span><span class="s">&quot;foo:&quot;</span> <span class="nv">foo</span> <span class="s">&quot;bar:&quot;</span> <span class="nv">bar</span><span class="p">)</span>
</span><span class='line'><span class="c1">;; do this:</span>
</span><span class='line'><span class="p">(</span><span class="nb">println </span><span class="s">&quot;Easy!&quot;</span> <span class="p">{</span><span class="ss">:foo</span> <span class="nv">foo</span> <span class="ss">:bar</span> <span class="nv">bar</span><span class="p">})</span>   <span class="c1">;; easy to extend</span>
</span></code></pre></td></tr></table></div></figure>


<p>Print out what values intermediate symbols in a <code>let</code> are bound to:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
</pre></td><td class='code'><pre><code class='clojure'><span class='line'><span class="p">(</span><span class="k">let </span><span class="p">[</span><span class="nv">headers</span>         <span class="p">(</span><span class="ss">:headers</span> <span class="nv">ring-request</span><span class="p">)</span>
</span><span class='line'>      <span class="nv">header-names</span>    <span class="p">(</span><span class="nb">keys </span><span class="nv">headers</span><span class="p">)</span>
</span><span class='line'>      <span class="c1">;; The following underscore is a convention for &quot;unused variable&quot;</span>
</span><span class='line'>      <span class="nv">_</span>               <span class="p">(</span><span class="nb">println </span><span class="s">&quot;Headers:&quot;</span> <span class="nv">header-names</span><span class="p">)</span>  <span class="c1">;; &lt;-- this</span>
</span><span class='line'>      <span class="nv">header-keywords</span> <span class="p">(</span><span class="nb">map keyword </span><span class="nv">header-names</span><span class="p">)]</span>
</span><span class='line'><span class="c1">;; etc</span>
</span><span class='line'><span class="p">)</span>
</span></code></pre></td></tr></table></div></figure>


<p>A variant of println is using <code>clojure.pprint/pprint</code> or <code>pr-str</code> to
print out more complex data structures in a more human-readable
format.</p>

<p>Well, this isn&rsquo;t great.  You have to modify the code to see what&rsquo;s
going on, so you might forget to remove those modifications.  You have
to duplicate code that&rsquo;s already there to inspect values &ndash; this
introduces the possibility of typo error.  <code>println</code> doesn&rsquo;t
necessarily behave how you would expect in a multithreaded context.
And yeah, it makes you itch a little too.  We can do better&hellip;</p>

<h2>Tracing with Spyscope</h2>

<p><a href="https://github.com/dgrnbrg/spyscope">Spyscope</a> is a nice improvement of println debugging. With two
simple additions to your <code>~/.lein/profiles.clj</code> it adds three reader
tags:</p>

<ul>
<li>print: <code>#spy/p</code></li>
<li>details: <code>#spy/d</code></li>
<li>trace: <code>#spy/t</code></li>
</ul>


<p>Since they are reader tags, you can just pop one of them in front of
the expression you&rsquo;re trying to inspect, and it gets printed out. This improves the example from above</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
</pre></td><td class='code'><pre><code class='clojure'><span class='line'><span class="p">(</span><span class="k">let </span><span class="p">[</span><span class="nv">headers</span>         <span class="p">(</span><span class="ss">:headers</span> <span class="nv">ring-request</span><span class="p">)</span>
</span><span class='line'>      <span class="nv">header-names</span>    <span class="o">#</span><span class="nv">spy/p</span> <span class="p">(</span><span class="nb">keys </span><span class="nv">headers</span><span class="p">)</span>       <span class="c1">;; &lt;-- print out what header-names is</span>
</span><span class='line'>      <span class="nv">header-keywords</span> <span class="p">(</span><span class="nb">map keyword </span><span class="nv">header-names</span><span class="p">)]</span>
</span><span class='line'><span class="c1">;; etc</span>
</span><span class='line'><span class="p">)</span>
</span></code></pre></td></tr></table></div></figure>


<p>If you&rsquo;re doing println debugging, I definitely recommend the upgrade to Spyscope.</p>

<h2>Macros for debugging let forms</h2>

<p>If you find yourself inspecting the values of the bindings within a
let form, I have seen a number of macros to automate the typing.</p>

<p>I have <a href="http://blog.gaz-jones.com/2012/02/04/debug_let.html">Gareth Jones&rsquo;s <code>dlet</code> macro</a> in my user namespace:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
</pre></td><td class='code'><pre><code class='clojure'><span class='line'><span class="p">(</span><span class="kd">defmacro </span><span class="nv">dlet</span> <span class="p">[</span><span class="nv">bindings</span> <span class="o">&amp;</span> <span class="nv">body</span><span class="p">]</span>
</span><span class='line'>  <span class="o">`</span><span class="p">(</span><span class="k">let </span><span class="p">[</span><span class="o">~@</span><span class="p">(</span><span class="nb">mapcat </span><span class="p">(</span><span class="k">fn </span><span class="p">[[</span><span class="nv">n</span> <span class="nv">v</span><span class="p">]]</span>
</span><span class='line'>                       <span class="p">(</span><span class="k">if </span><span class="p">(</span><span class="nb">or </span><span class="p">(</span><span class="nb">vector? </span><span class="nv">n</span><span class="p">)</span> <span class="p">(</span><span class="nb">map? </span><span class="nv">n</span><span class="p">))</span>
</span><span class='line'>                           <span class="p">[</span><span class="nv">n</span> <span class="nv">v</span><span class="p">]</span>
</span><span class='line'>                         <span class="p">[</span><span class="nv">n</span> <span class="nv">v</span> <span class="ss">&#39;_</span> <span class="o">`</span><span class="p">(</span><span class="nb">println </span><span class="p">(</span><span class="nb">name </span><span class="o">&#39;~</span><span class="nv">n</span><span class="p">)</span> <span class="s">&quot;:&quot;</span> <span class="o">~</span><span class="nv">v</span><span class="p">)]))</span>
</span><span class='line'>                   <span class="p">(</span><span class="nf">partition</span> <span class="mi">2</span> <span class="nv">bindings</span><span class="p">))]</span>
</span><span class='line'>     <span class="o">~@</span><span class="nv">body</span><span class="p">))</span>
</span></code></pre></td></tr></table></div></figure>


<p>To see the binding values within the let, just replace any old <code>let</code>
in your code with a <code>dlet</code>, and the bindings all get printed out:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
<span class='line-number'>18</span>
</pre></td><td class='code'><pre><code class='clojure'><span class='line'><span class="c1">;; Example let form to inspect.  Note use of `dlet` not `let`...</span>
</span><span class='line'><span class="p">(</span><span class="nf">dlet</span> <span class="p">[</span><span class="nv">response</span> <span class="p">(</span><span class="nf">http/get</span> <span class="s">&quot;http://localhost:8080/api&quot;</span><span class="p">)</span>
</span><span class='line'>       <span class="nv">data</span> <span class="p">(</span><span class="nf">json/parse-string</span> <span class="p">(</span><span class="ss">:body</span> <span class="nv">response</span><span class="p">)</span> <span class="nv">true</span><span class="p">)</span>
</span><span class='line'>       <span class="nv">accounts</span> <span class="p">(</span><span class="ss">:accounts</span> <span class="nv">data</span><span class="p">)]</span>
</span><span class='line'>      <span class="c1">;; ... some more stuff</span>
</span><span class='line'>      <span class="p">)</span>
</span><span class='line'>
</span><span class='line'><span class="c1">;; This is what gets printed to the REPL:</span>
</span><span class='line'><span class="nv">user&gt;</span> <span class="nv">response</span> <span class="err">:</span> <span class="p">{</span><span class="ss">:orig-content-encoding</span> <span class="nv">nil</span>, <span class="ss">:trace-redirects</span> <span class="p">[</span><span class="nv">http</span><span class="ss">://localhost:8080/api</span><span class="p">]</span>, <span class="ss">:request-time</span> <span class="mi">7</span>, <span class="ss">:status</span> <span class="mi">200</span>, <span class="ss">:headers</span> <span class="p">{</span><span class="nv">Server</span> <span class="nv">Jetty</span> <span class="p">(</span><span class="mf">7.6</span><span class="nv">.8.v20121106</span><span class="p">)</span>, <span class="nv">Connection</span> <span class="nv">close</span>, <span class="nv">Content-Type</span> <span class="nv">application/json</span><span class="c1">; charset=utf-8, Date Sun, 01 Aug 2014 12:34:56 GMT}, :body {</span>
</span><span class='line'><span class="s">&quot;accounts&quot;</span> <span class="err">:</span> <span class="p">[</span> <span class="p">{</span> <span class="s">&quot;id&quot;</span> <span class="err">:</span> <span class="s">&quot;53defe4e-5c00-49ae-b0bf-93aa7b57394b&quot;</span>,
</span><span class='line'>                 <span class="s">&quot;active&quot;</span> <span class="err">:</span> <span class="nv">true</span>
</span><span class='line'>                <span class="p">}</span>, <span class="p">{</span>
</span><span class='line'>                 <span class="s">&quot;id&quot;</span> <span class="err">:</span> <span class="s">&quot;c24e6ab9-c9f3-40d3-ab10-cf28c3bbf1e1&quot;</span>,
</span><span class='line'>                  <span class="s">&quot;active&quot;</span> <span class="err">:</span> <span class="nv">false</span>
</span><span class='line'>                <span class="p">}</span> <span class="p">]</span>
</span><span class='line'><span class="p">}}</span>
</span><span class='line'><span class="nv">data</span> <span class="err">:</span> <span class="p">{</span><span class="ss">:accounts</span> <span class="p">[{</span><span class="ss">:id</span> <span class="mi">53</span><span class="nv">defe4e-5c00-49ae-b0bf-93aa7b57394b</span>, <span class="ss">:active</span> <span class="nv">true</span><span class="p">}</span> <span class="p">{</span><span class="ss">:id</span> <span class="nv">c24e6ab9-c9f3-40d3-ab10-cf28c3bbf1e1</span>, <span class="ss">:active</span> <span class="nv">false</span><span class="p">}]}</span>
</span><span class='line'><span class="nv">accounts</span> <span class="err">:</span> <span class="p">[{</span><span class="ss">:id</span> <span class="mi">53</span><span class="nv">defe4e-5c00-49ae-b0bf-93aa7b57394b</span>, <span class="ss">:active</span> <span class="nv">true</span><span class="p">}</span> <span class="p">{</span><span class="ss">:id</span> <span class="nv">c24e6ab9-c9f3-40d3-ab10-cf28c3bbf1e1</span>, <span class="ss">:active</span> <span class="nv">false</span><span class="p">}]</span>
</span></code></pre></td></tr></table></div></figure>


<p>I have also seen a similar outcome using Fogus&rsquo;s <a href="https://github.com/tailrecursion/evalive">evalive</a> library:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
</pre></td><td class='code'><pre><code class='clojure'><span class='line'><span class="p">(</span><span class="nf">require</span> <span class="o">&#39;</span><span class="p">[</span><span class="nv">evalive.core</span><span class="p">])</span>
</span><span class='line'>
</span><span class='line'><span class="p">(</span><span class="kd">defmacro </span><span class="nv">dlet</span> <span class="p">[</span><span class="nv">bindings</span> <span class="o">&amp;</span> <span class="nv">body</span><span class="p">]</span>
</span><span class='line'>  <span class="o">`</span><span class="p">(</span><span class="k">let </span><span class="o">~</span><span class="nv">bindings</span>
</span><span class='line'>     <span class="p">(</span><span class="nf">clojure.pprint/pprint</span> <span class="p">(</span><span class="nf">evalive.core/lexical-context</span><span class="p">))</span>
</span><span class='line'>     <span class="o">~@</span><span class="nv">body</span><span class="p">))</span>
</span></code></pre></td></tr></table></div></figure>


<h2>Tracing with clojure.tools.trace</h2>

<p>The techniques so far all involve modifying the code to inspect
values. In addition to similar tools to the above,
<a href="https://github.com/clojure/tools.trace">clojure.tools.trace</a> gives you easy ways to trace the result of function
calls without any code modification.</p>

<p>From the REPL, use the <code>trace-vars</code> and <code>trace-ns</code> functions to wrap
specific functions or entire namespaces with tracing calls.  In this
example, I define and use a function to square a number, apply a trace
to it, then use it again.  You can see the invocation arguments and
return value for each call:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
<span class='line-number'>18</span>
<span class='line-number'>19</span>
<span class='line-number'>20</span>
<span class='line-number'>21</span>
<span class='line-number'>22</span>
<span class='line-number'>23</span>
<span class='line-number'>24</span>
<span class='line-number'>25</span>
<span class='line-number'>26</span>
<span class='line-number'>27</span>
<span class='line-number'>28</span>
<span class='line-number'>29</span>
<span class='line-number'>30</span>
<span class='line-number'>31</span>
<span class='line-number'>32</span>
<span class='line-number'>33</span>
<span class='line-number'>34</span>
<span class='line-number'>35</span>
<span class='line-number'>36</span>
</pre></td><td class='code'><pre><code class='clojure'><span class='line'><span class="nv">user&gt;</span> <span class="p">(</span><span class="nf">require</span> <span class="o">&#39;</span><span class="p">[</span><span class="nv">clojure.tools.trace</span><span class="p">])</span>
</span><span class='line'>
</span><span class='line'><span class="nv">user&gt;</span> <span class="p">(</span><span class="kd">defn </span><span class="nv">square</span> <span class="p">[</span><span class="nv">n</span><span class="p">]</span> <span class="p">(</span><span class="nb">* </span><span class="nv">n</span> <span class="nv">n</span><span class="p">))</span>
</span><span class='line'><span class="o">#</span><span class="ss">&#39;user/square</span>
</span><span class='line'>
</span><span class='line'><span class="nv">user&gt;</span> <span class="p">(</span><span class="nb">map </span><span class="nv">square</span> <span class="p">(</span><span class="nb">range </span><span class="mi">1</span> <span class="mi">11</span><span class="p">))</span>
</span><span class='line'><span class="p">(</span><span class="mi">1</span> <span class="mi">4</span> <span class="mi">9</span> <span class="mi">16</span> <span class="mi">25</span> <span class="mi">36</span> <span class="mi">49</span> <span class="mi">64</span> <span class="mi">81</span> <span class="mi">100</span><span class="p">)</span>
</span><span class='line'>
</span><span class='line'><span class="nv">user&gt;</span> <span class="p">(</span><span class="nf">clojure.tools.trace/trace-vars</span> <span class="nv">user/square</span><span class="p">)</span>
</span><span class='line'><span class="o">#</span><span class="ss">&#39;user/square</span>
</span><span class='line'>
</span><span class='line'><span class="nv">user&gt;</span> <span class="p">(</span><span class="nb">map </span><span class="nv">square</span> <span class="p">(</span><span class="nb">range </span><span class="mi">1</span> <span class="mi">11</span><span class="p">))</span>
</span><span class='line'><span class="p">(</span><span class="nf">TRACE</span> <span class="nv">t13642</span><span class="err">:</span> <span class="p">(</span><span class="nf">user/square</span> <span class="mi">1</span><span class="p">)</span>
</span><span class='line'>       <span class="nv">TRACE</span> <span class="nv">t13642</span><span class="err">:</span> <span class="nv">=&gt;</span> <span class="mi">1</span>
</span><span class='line'>       <span class="nv">TRACE</span> <span class="nv">t13643</span><span class="err">:</span> <span class="p">(</span><span class="nf">user/square</span> <span class="mi">2</span><span class="p">)</span>
</span><span class='line'>       <span class="nv">TRACE</span> <span class="nv">t13643</span><span class="err">:</span> <span class="nv">=&gt;</span> <span class="mi">4</span>
</span><span class='line'>       <span class="nv">TRACE</span> <span class="nv">t13644</span><span class="err">:</span> <span class="p">(</span><span class="nf">user/square</span> <span class="mi">3</span><span class="p">)</span>
</span><span class='line'>       <span class="nv">TRACE</span> <span class="nv">t13644</span><span class="err">:</span> <span class="nv">=&gt;</span> <span class="mi">9</span>
</span><span class='line'>       <span class="nv">TRACE</span> <span class="nv">t13645</span><span class="err">:</span> <span class="p">(</span><span class="nf">user/square</span> <span class="mi">4</span><span class="p">)</span>
</span><span class='line'>       <span class="nv">TRACE</span> <span class="nv">t13645</span><span class="err">:</span> <span class="nv">=&gt;</span> <span class="mi">16</span>
</span><span class='line'>       <span class="nv">TRACE</span> <span class="nv">t13646</span><span class="err">:</span> <span class="p">(</span><span class="nf">user/square</span> <span class="mi">5</span><span class="p">)</span>
</span><span class='line'>       <span class="nv">TRACE</span> <span class="nv">t13646</span><span class="err">:</span> <span class="nv">=&gt;</span> <span class="mi">25</span>
</span><span class='line'>       <span class="nv">TRACE</span> <span class="nv">t13647</span><span class="err">:</span> <span class="p">(</span><span class="nf">user/square</span> <span class="mi">6</span><span class="p">)</span>
</span><span class='line'>       <span class="nv">TRACE</span> <span class="nv">t13647</span><span class="err">:</span> <span class="nv">=&gt;</span> <span class="mi">36</span>
</span><span class='line'>       <span class="nv">TRACE</span> <span class="nv">t13648</span><span class="err">:</span> <span class="p">(</span><span class="nf">user/square</span> <span class="mi">7</span><span class="p">)</span>
</span><span class='line'>       <span class="nv">TRACE</span> <span class="nv">t13648</span><span class="err">:</span> <span class="nv">=&gt;</span> <span class="mi">49</span>
</span><span class='line'>       <span class="nv">TRACE</span> <span class="nv">t13649</span><span class="err">:</span> <span class="p">(</span><span class="nf">user/square</span> <span class="mi">8</span><span class="p">)</span>
</span><span class='line'>       <span class="nv">TRACE</span> <span class="nv">t13649</span><span class="err">:</span> <span class="nv">=&gt;</span> <span class="mi">64</span>
</span><span class='line'>       <span class="nv">TRACE</span> <span class="nv">t13650</span><span class="err">:</span> <span class="p">(</span><span class="nf">user/square</span> <span class="mi">9</span><span class="p">)</span>
</span><span class='line'>       <span class="nv">TRACE</span> <span class="nv">t13650</span><span class="err">:</span> <span class="nv">=&gt;</span> <span class="mi">81</span>
</span><span class='line'>       <span class="nv">TRACE</span> <span class="nv">t13651</span><span class="err">:</span> <span class="p">(</span><span class="nf">user/square</span> <span class="mi">10</span><span class="p">)</span>
</span><span class='line'>       <span class="nv">TRACE</span> <span class="nv">t13651</span><span class="err">:</span> <span class="nv">=&gt;</span> <span class="mi">100</span>
</span><span class='line'>       <span class="mi">1</span> <span class="mi">4</span> <span class="mi">9</span> <span class="mi">16</span> <span class="mi">25</span> <span class="mi">36</span> <span class="mi">49</span> <span class="mi">64</span> <span class="mi">81</span> <span class="mi">100</span><span class="p">)</span>
</span><span class='line'>
</span><span class='line'><span class="c1">;; Turn off all traces:</span>
</span><span class='line'><span class="nv">user&gt;</span> <span class="p">(</span><span class="nf">clojure.tools.trace/untrace-ns</span> <span class="ss">&#39;user</span><span class="p">)</span>
</span></code></pre></td></tr></table></div></figure>


<p>I like <code>clojure.tools.trace/trace-vars</code> a lot.  I used <a href="https://github.com/zcaudate/vinyasa">Vinyasa</a> to
make it really convenient to use by injecting <code>trace-vars</code> into all
namespaces in the REPL, and use it thus:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
</pre></td><td class='code'><pre><code class='clojure'><span class='line'><span class="p">(</span><span class="nb">in-ns </span><span class="ss">&#39;my.ns.one</span><span class="p">)</span>
</span><span class='line'>
</span><span class='line'><span class="c1">;; Trace some other namespace&#39;s fn</span>
</span><span class='line'><span class="p">(</span><span class="nf">&gt;trace-vars</span> <span class="nv">my.ns.two/foo</span><span class="p">)</span>
</span></code></pre></td></tr></table></div></figure>


<h2>Fogus&rsquo;s breakpoint macro</h2>

<p>The venerable <a href="http://joyofclojure.com/">Joy of Clojure</a> has the source code for a
complete Clojure breakpoint system. Reading this code was one of those
&ldquo;Clojure, wow&rdquo; moments&hellip;</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
<span class='line-number'>18</span>
<span class='line-number'>19</span>
<span class='line-number'>20</span>
</pre></td><td class='code'><pre><code class='clojure'><span class='line'><span class="p">(</span><span class="kd">defn </span><span class="nv">contextual-eval</span> <span class="p">[</span><span class="nv">ctx</span> <span class="nv">expr</span><span class="p">]</span>
</span><span class='line'>  <span class="p">(</span><span class="nf">eval</span>
</span><span class='line'>   <span class="o">`</span><span class="p">(</span><span class="k">let </span><span class="p">[</span><span class="o">~@</span><span class="p">(</span><span class="nb">mapcat </span><span class="p">(</span><span class="k">fn </span><span class="p">[[</span><span class="nv">k</span> <span class="nv">v</span><span class="p">]]</span> <span class="p">[</span><span class="nv">k</span> <span class="o">`&#39;~</span><span class="nv">v</span><span class="p">])</span> <span class="nv">ctx</span><span class="p">)]</span>
</span><span class='line'>      <span class="o">~</span><span class="nv">expr</span><span class="p">)))</span>
</span><span class='line'>
</span><span class='line'><span class="p">(</span><span class="kd">defmacro </span><span class="nv">local-context</span> <span class="p">[]</span>
</span><span class='line'>  <span class="p">(</span><span class="k">let </span><span class="p">[</span><span class="nv">symbols</span> <span class="p">(</span><span class="nb">keys </span><span class="o">&amp;</span><span class="nv">env</span><span class="p">)]</span>
</span><span class='line'>    <span class="p">(</span><span class="nb">zipmap </span><span class="p">(</span><span class="nb">map </span><span class="p">(</span><span class="k">fn </span><span class="p">[</span><span class="nv">sym</span><span class="p">]</span> <span class="o">`</span><span class="p">(</span><span class="k">quote </span><span class="o">~</span><span class="nv">sym</span><span class="p">))</span> <span class="nv">symbols</span><span class="p">)</span> <span class="nv">symbols</span><span class="p">)))</span>
</span><span class='line'>
</span><span class='line'><span class="p">(</span><span class="kd">defn </span><span class="nv">readr</span> <span class="p">[</span><span class="nv">prompt</span> <span class="nv">exit-code</span><span class="p">]</span>
</span><span class='line'>  <span class="p">(</span><span class="k">let </span><span class="p">[</span><span class="nv">input</span> <span class="p">(</span><span class="nf">clojure.main/repl-read</span> <span class="nv">prompt</span> <span class="nv">exit-code</span><span class="p">)]</span>
</span><span class='line'>    <span class="p">(</span><span class="k">if </span><span class="p">(</span><span class="nb">= </span><span class="nv">input</span> <span class="ss">::tl</span><span class="p">)</span>
</span><span class='line'>      <span class="nv">exit-code</span>
</span><span class='line'>      <span class="nv">input</span><span class="p">)))</span>
</span><span class='line'>
</span><span class='line'><span class="p">(</span><span class="kd">defmacro </span><span class="nv">break</span> <span class="p">[]</span>
</span><span class='line'>  <span class="o">`</span><span class="p">(</span><span class="nf">clojure.main/repl</span>
</span><span class='line'>    <span class="ss">:prompt</span> <span class="o">#</span><span class="p">(</span><span class="nb">print </span><span class="s">&quot;debug=&gt; &quot;</span><span class="p">)</span>
</span><span class='line'>    <span class="ss">:read</span> <span class="nv">readr</span>
</span><span class='line'>    <span class="ss">:eval</span> <span class="p">(</span><span class="nb">partial </span><span class="nv">contextual-eval</span> <span class="p">(</span><span class="nf">local-context</span><span class="p">))))</span>
</span></code></pre></td></tr></table></div></figure>


<p>Really, it&rsquo;s just a toy, but isn&rsquo;t it incredible!</p>

<h2>Other bits</h2>

<h3>ClojureScript</h3>

<p>I saw <a href="http://www.reddit.com/r/Clojure/comments/2behsz/clojurescript_debugging_tips/cj4mvok">the following ClojureScript macro</a> for defining a
traced function.  I haven&rsquo;t tried it, but it looks interesting:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
<span class='line-number'>18</span>
<span class='line-number'>19</span>
<span class='line-number'>20</span>
</pre></td><td class='code'><pre><code class='clojure'><span class='line'><span class="p">(</span><span class="kd">defmacro </span><span class="nv">defntraced</span>
</span><span class='line'>  <span class="s">&quot;Define a function with it&#39;s inputs and output logged to the console.&quot;</span>
</span><span class='line'>  <span class="p">[</span><span class="nv">sym</span> <span class="o">&amp;</span> <span class="nv">body</span><span class="p">]</span>
</span><span class='line'>  <span class="p">(</span><span class="k">let </span><span class="p">[[</span><span class="nv">_</span> <span class="nv">_</span> <span class="p">[</span><span class="nv">_</span> <span class="o">&amp;</span> <span class="nv">specs</span><span class="p">]]</span> <span class="p">(</span><span class="nb">macroexpand </span><span class="o">`</span><span class="p">(</span><span class="kd">defn </span><span class="o">~</span><span class="nv">sym</span> <span class="o">~@</span><span class="nv">body</span><span class="p">))</span>
</span><span class='line'>        <span class="nv">new-specs</span>
</span><span class='line'>        <span class="p">(</span><span class="nf">map</span>
</span><span class='line'>         <span class="p">(</span><span class="k">fn </span><span class="p">[[</span><span class="nv">args</span> <span class="nv">body</span><span class="p">]]</span>
</span><span class='line'>           <span class="p">(</span><span class="k">let </span><span class="p">[</span><span class="nv">prns</span> <span class="p">(</span><span class="nb">for </span><span class="p">[</span><span class="nv">arg</span> <span class="nv">args</span><span class="p">]</span>
</span><span class='line'>                        <span class="o">`</span><span class="p">(</span><span class="nf">js/console.log</span> <span class="p">(</span><span class="nb">str </span><span class="o">&#39;~</span><span class="nv">arg</span><span class="p">)</span> <span class="s">&quot;=&quot;</span> <span class="p">(</span><span class="nb">pr-str </span><span class="o">~</span><span class="nv">arg</span><span class="p">)))]</span>
</span><span class='line'>             <span class="p">(</span><span class="nf">list</span>
</span><span class='line'>              <span class="nv">args</span>
</span><span class='line'>              <span class="o">`</span><span class="p">(</span><span class="nf">do</span>
</span><span class='line'>                 <span class="p">(</span><span class="nf">js/console.groupCollapsed</span> <span class="p">(</span><span class="nb">str </span><span class="o">&#39;~</span><span class="nv">sym</span> <span class="s">&quot; &quot;</span> <span class="o">&#39;~</span><span class="nv">args</span><span class="p">))</span>
</span><span class='line'>                 <span class="o">~@</span><span class="nv">prns</span>
</span><span class='line'>                 <span class="p">(</span><span class="k">let </span><span class="p">[</span><span class="nv">res#</span> <span class="o">~</span><span class="nv">body</span><span class="p">]</span>
</span><span class='line'>                   <span class="p">(</span><span class="nf">js/console.log</span> <span class="s">&quot;=&gt;&quot;</span> <span class="p">(</span><span class="nb">pr-str </span><span class="nv">res#</span><span class="p">))</span>
</span><span class='line'>                   <span class="p">(</span><span class="nf">js/console.groupEnd</span><span class="p">)</span>
</span><span class='line'>                   <span class="nv">res#</span><span class="p">)))))</span>
</span><span class='line'>         <span class="nv">specs</span><span class="p">)]</span>
</span><span class='line'>    <span class="o">`</span><span class="p">(</span><span class="k">def </span><span class="o">~</span><span class="nv">sym</span> <span class="p">(</span><span class="k">fn </span><span class="o">~@</span><span class="nv">new-specs</span><span class="p">))))</span>
</span></code></pre></td></tr></table></div></figure>


<h3>Ring</h3>

<p>Ring services seem like fertile ground for debugging and inspection
problems.  My next post will cover some basic Ring concepts from a
problem-solving point of view.</p>

<h1>Sources and References</h1>

<p>In addition to the pages referenced, the following resources have been useful to me:</p>

<ul>
<li><a href="http://z.caudate.me/give-your-clojure-workflow-more-flow/">http://z.caudate.me/give-your-clojure-workflow-more-flow/</a> and <a href="http://dev.solita.fi/2014/03/18/pimp-my-repl.html">http://dev.solita.fi/2014/03/18/pimp-my-repl.html</a> (which I think draws upon the former)</li>
<li>Image credit: <a href="http://frostedgardner.blogspot.com/2010/07/summer-weekend-finds.html">http://frostedgardner.blogspot.com/2010/07/summer-weekend-finds.html</a></li>
</ul>

]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Debugging in Clojure: Thoughts]]></title>
    <link href="http://brownsofa.org/blog/2014/07/17/debugging-in-clojure-thoughts/"/>
    <updated>2014-07-17T19:03:00-06:00</updated>
    <id>http://brownsofa.org/blog/2014/07/17/debugging-in-clojure-thoughts</id>
    <content type="html"><![CDATA[<p><img class="right" src="http://brownsofa.org/images/debugging-in-clojure/bug.jpg" title="Bug" alt="Bug"> I
read a <a href="http://www.reddit.com/r/Clojure/comments/28udm4/does_clojure_have_a_breakpoint_capable_debugger/">few</a> <a href="http://www.reddit.com/r/Clojure/comments/1def3g/starter_tips_for_more_productive_clj_development/">posts</a> recently on <a href="http://www.reddit.com/r/clojure">r/clojure</a> asking about
Clojure debugging tools.  It seemed that those asking the questions
were looking for the kind of tools we have come to expect from IDEs
such as IntelliJ, Eclipse, Visual Studio and their ilk.
It&rsquo;s a familiar question since I asked it myself when I started
learning Clojure.</p>

<p>I think I have come to the same conclusion as other Clojure
programmers in that my short answer to the question is
&ldquo;there isn&rsquo;t one&rdquo;, or &ldquo;it&rsquo;s the REPL&rdquo;, and that my long answer is,
well, long.</p>

<p>This cryptic answer needs expanding upon, because it&rsquo;s not really
true.  The real answer is that, like in any other language, the best
Clojure debugger is your brain.</p>

<p>This is no less cryptic.</p>

<p>In coming up with the long answer, I found it fits best into
two parts.  This first part covers what I&rsquo;m defining as debugging, and
my overall approach &ndash; my philosophy, perhaps.  The second part will
cover building debuggable systems, and finally get into the debugging
tools themselves.</p>

<!-- more -->


<h1>Contents</h1>

<ul>
<li><a href="#scope">Scope</a></li>
<li><a href="#what">What is &ldquo;debugging&rdquo; anyway?</a></li>
<li><a href="#process">Process</a></li>
</ul>


<p><a name="scope"></a></p>

<h1>Scope</h1>

<p><img class="right" src="http://brownsofa.org/images/debugging-in-clojure/terminal.png" title="Hi-tech coding" alt="Hi-tech coding"> At
work, I am constrained to write Clojure in a terminal (we use remote
tmux) and really, using Emacs.  This is a fine set of constraints,
but my debugging solutions haven&rsquo;t considered tools like Nightcode,
Light Table, La Clojure or other IDE-like tools.  Looking at the
various product websites, point-and-click debugging has different
levels of support, and if that&rsquo;s what you <em>really</em> want, perhaps La
Clojure would be a good start.</p>

<p>I also have not yet tried out the <a href="https://github.com/pallet/ritz/tree/develop/nrepl">Ritz</a> toolchain
(<a href="http://ianeslick.com/2013/05/17/clojure-debugging-13-emacs-nrepl-and-ritz/">this article</a> has lots of tidbits that are on my
to-try list), nor have I tried <a href="https://github.com/prismofeverything/schmetterling">Schmetterling</a> (which makes
exception-triggered or breakpoint-triggered stacktrace inspection and
interactive REPLs available through a browser connected to your REPL),
or <a href="https://github.com/relevance/mycroft">Mycroft</a>.</p>

<p>This article is concerned with debugging Clojure, in Emacs, using
simple Clojure code, tools and libraries to make life a little easier.
Much of it applies equally to non-Clojure, and non-functional
programming.  Solving bugs in 100k+ LOC Java codebases isn&rsquo;t magically
made tractable by having IntelliJ&rsquo;s debugger.</p>

<p><a name="what"></a></p>

<h1>What is &ldquo;debugging&rdquo; anyway?</h1>

<p>I will define a bug as a deviation between your expectation of, and
your observation of the behavior of a system.</p>

<p>The &ldquo;system&rdquo; here comprises your code, the libraries your code uses,
the JVM, OS and all the way on down to the physical hardware (though
you can likely limit your concern to the first two &ndash; see &ldquo;Understand
your assumptions&rdquo; below).</p>

<p>Debugging is the process of investigating, verifying, isolating the
cause for, and closing the gap between your expectations and your
observations.  You are allowed to change the system; you are also
allowed to change your expectations of the system.</p>

<p><img class="right" src="http://brownsofa.org/images/debugging-in-clojure/chop.jpg" title="Chop it up" alt="Chop it up">
Debugging is a reductionist process: understanding of the whole is
achieved through understanding of the composite parts. The systems we
build are frequently too complex to really comprehensively understand
all at once, but by considering a bug from how it manifests at the
highest level of abstraction, and digging down into the layers of the
system, we can understand enough of the system to understand a bug,
then make informed decisions about how to address it.</p>

<p>Given this fairly straightforward reductionist approach, it is fairly
straightforward to sketch out an algorithm for debugging.</p>

<p><a name="process"></a></p>

<h1>Process</h1>

<p>Above I laid out the case for writing &ldquo;code that is easy to exercise
in the REPL, whose behavior is easily observed, and with unit test
coverage&rdquo;.  Here is my &ldquo;algorithm&rdquo; for debugging:</p>

<ol>
<li>Identify the area of your system expressing the bug.  You should be
able to clearly state the desired behavior.</li>
<li>Run that subset of your code and observe the behavior; the outcome
will be different to your expectation.  Ensure you can repeatably
observe that outcome is different to your expectation. If you can&rsquo;t
reproduce it, you aren&rsquo;t in a position to fix it.</li>
<li>Read the code.  Consider the inputs, and try to understand how it
generates the output.  Add temporary instrumentation to the code as
necessary.</li>
<li>If the code is too large or complex to understand, divide and
conquer.  Refactoring may be helpful, even as a temporary
measure. You must somehow break the problem down into smaller,
understandable pieces.  Go back to step 2 and repeat for each of
the smaller pieces.  Proceed when you fully understand how the code
works.</li>
<li>As long as you are always mindful of what your expectation of the
code is, the problem will at this point become clear, and you need
to devise a way to fix it.  Remember, the problem might be your
expectation.</li>
</ol>


<p>So, the debugging process can &ndash; in general &ndash; be outlined.  There are
architectural decisions you can make, and tools you can use, in order
to better pose and answer questions about the runtime behavior of your
code. The <a href="http://brownsofa.org/blog/2014/08/03/debugging-in-clojure-tools/">second part of this article</a> <strike>will
cover</strike> covers what a debuggable Clojure-based codebase
would be, and then digs into some Emacs and Clojure tools I have found
useful.</p>

<hr />

<p>Image credits:</p>

<ul>
<li><a href="http://royalbcmuseum.bc.ca/nh-collections/entomology/">http://royalbcmuseum.bc.ca/nh-collections/entomology/</a></li>
<li><a href="http://blog.envylabs.com/post/62718536773/remote-pairing-and-browser-sharing-with-tmux">http://blog.envylabs.com/post/62718536773/remote-pairing-and-browser-sharing-with-tmux</a></li>
<li><a href="http://modernfarmer.com/2013/12/chop-wood/">http://modernfarmer.com/2013/12/chop-wood/</a></li>
</ul>

]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Docker: what I learned from working out what's in it for me]]></title>
    <link href="http://brownsofa.org/blog/2014/03/19/docker-what-i-learned-from-whats-in-it-for-me/"/>
    <updated>2014-03-19T20:31:00-06:00</updated>
    <id>http://brownsofa.org/blog/2014/03/19/docker-what-i-learned-from-whats-in-it-for-me</id>
    <content type="html"><![CDATA[<p><img class="left" src="http://brownsofa.org/images/docker-what-i-learned-from-whats-in-it-for-me/docker-logo.png" title="Docker logo: from www.docker.io" alt="Docker whale logo"></p>

<p>I recently spent some time researching and using <a href="http://www.docker.io">Docker</a>, specifically
with a view of how it would help me develop a scalable SOA. I gave a
couple of <a href="http://brownsofa.org/presentations/#docker_whats_in_it_for_me">presentations</a>
on some of the basics I picked up.</p>

<p>In the spirit of the order of the talk, I concluded that Docker had
some really interesting use cases:</p>

<p><em>For developers</em>: Docker is great for pulling in application
 dependencies.  For example, starting up an ElasticSearch server is as
 simple as two commands at the shell.</p>

<p><em>For devops</em>: Docker is great for getting developers to package up
 apps with all their dependencies into a declaratively constructed,
 directly deployable, entirely repeatable artifact.</p>

<p><em>For architects</em>: Docker is entirely in line with the tenets of
 <a href="http://12factor.net/">Twelve Factor Apps</a>, and can easily be used in various
 infrastructure scenarios.</p>

<p>I didn&rsquo;t have time in the talk to cover some of the interesting
details I discovered along the way, so I&rsquo;ll cover them here instead:</p>

<ul>
<li>Structure Dockerfiles hierarchically</li>
<li>Use Versions in Tags</li>
<li>Check Dockerfiles into GitHub</li>
<li>Running in the foreground</li>
<li>Inter-container communication and web services APIs</li>
</ul>


<!-- more -->


<p></p>

<hr />

<h2>Structure Dockerfiles hierarchically</h2>

<p>It seems like premature optimization, but I found distinct
develop-build-test cycle time improvements when I paid attention to
the image tree Docker maintains.</p>

<p>My earlier attempts to iteratively build two Docker images, each from
their own Dockerfile, was unnecessarily slow.  Each of the Dockerfiles
was large and monolithic, and the commands in each of the Dockerfiles
had no real order.  Each of the images had some similarities
(Ubuntu-based, Oracle Java), and some notable differences (one runs
ElasticSearch with Supervisor, the other packages up and runs a
Clojure application from GitHub sources).  Changes in the shared code
in one were replicated in the other, and a change early in one
Dockerfile meant rebuilding the entire image, not just incremental
changes in the later &ldquo;states&rdquo; Docker manages.</p>

<p>The approach I moved to, and what I recommend, is nothing novel. Since
each docker command run within a container yields a new container with
that altered state, the best way to minimize build-time churn is to
keep the base images stable. To wit: develop a hierarchy of images
whose base layers are the most stable, and where changes occur as
close to the leaf nodes of the tree as possible.</p>

<p>For illustration, here is the hierarchy of some images I built
according to that scheme:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
<span class='line-number'>18</span>
<span class='line-number'>19</span>
<span class='line-number'>20</span>
<span class='line-number'>21</span>
<span class='line-number'>22</span>
<span class='line-number'>23</span>
<span class='line-number'>24</span>
<span class='line-number'>25</span>
<span class='line-number'>26</span>
<span class='line-number'>27</span>
<span class='line-number'>28</span>
</pre></td><td class='code'><pre><code class='sh'><span class='line'>% docker images -t
</span><span class='line'>├─511136ea3c5a Virtual Size: 0 B
</span><span class='line'>│ ├─1c7f181e78b9 Virtual Size: 0 B
</span><span class='line'>│ │ └─9f676bd305a4 Virtual Size: 178 MB Tags: ubuntu:13.10, ubuntu:saucy
</span><span class='line'>│ │   └─55048c64aafb Virtual Size: 178 MB
</span><span class='line'>│ │     └─b45b04c61d37 Virtual Size: 181.3 MB
</span><span class='line'>│ │       └─cfd0a2113031 Virtual Size: 266.1 MB Tags: iant/base:0.1.0
</span><span class='line'>│ │         └─873825ff7806 Virtual Size: 266.1 MB
</span><span class='line'>│ │           └─c5ec6d485e19 Virtual Size: 332.1 MB Tags: iant/common:0.1.0
</span><span class='line'>│ │             └─12284038f771 Virtual Size: 332.1 MB
</span><span class='line'>│ │               └─8a7772c4e933 Virtual Size: 388 MB
</span><span class='line'>│ │                 └─59dc3b6ad0a8 Virtual Size: 388 MB
</span><span class='line'>│ │                   └─f3b21f3b00fe Virtual Size: 391.4 MB
</span><span class='line'>│ │                     └─8afce624e6a1 Virtual Size: 394.2 MB
</span><span class='line'>│ │                       └─88acfebd9fa9 Virtual Size: 808.3 MB Tags: iant/java:0.1.0
</span><span class='line'>│ │                         └─f829acd28896 Virtual Size: 808.3 MB
</span><span class='line'>│ │                           └─add88843e338 Virtual Size: 808.4 MB
</span><span class='line'>│ │                             └─b29cab6d5c13 Virtual Size: 808.4 MB
</span><span class='line'>│ │                               └─f782125c3355 Virtual Size: 822.1 MB Tags: iant/clojure:0.1.0
</span><span class='line'>│ │                                 └─63cd57a9fe58 Virtual Size: 822.1 MB
</span><span class='line'>│ │                                   └─d33ab8f97b66 Virtual Size: 822.2 MB
</span><span class='line'>│ │                                     └─6dcc5827a7b3 Virtual Size: 822.2 MB
</span><span class='line'>│ │                                       └─472668b960a2 Virtual Size: 822.2 MB
</span><span class='line'>│ │                                         └─38ee3cb17dd7 Virtual Size: 851.3 MB
</span><span class='line'>│ │                                           └─909f8927c47a Virtual Size: 851.3 MB
</span><span class='line'>│ │                                             └─6d5f57d4355e Virtual Size: 851.3 MB
</span><span class='line'>│ │                                               └─7dde5563b9bc Virtual Size: 851.3 MB Tags: iant/search-clojure-archives:0.1.0
</span><span class='line'>...etc
</span></code></pre></td></tr></table></div></figure>


<p>The <code>base</code> image is simply an updated <code>ubuntu:saucy</code> image.  <code>common</code>
adds common command line tools (curl etc) to <code>base</code>.  <code>java</code> is an
image based on <code>common</code> with Oracle Java 8 installed; it has a number
more intermediate images each corresponding to all the trickery to get
Java installed
<a href="https://github.com/iantruslove/dockerfiles/blob/master/java/Dockerfile#L14">&ldquo;unattended&rdquo;</a>.
<code>clojure</code> adds basic Clojure development tools, and
<code>search-clojure-archive</code> builds on that to retrieve, build and run the
web app.</p>

<p>Your scheme will be different.  I view Java as a fairly base-level
dependency.  Yours might be Ruby, or Nginx.  The point is to push the
rapidly changing configurations to the edges of the hierarchy, and get
considerably quicker build and test times.</p>

<h2>Use Versions in Tags</h2>

<p>When building Dockerfiles into images, make consistent use of <code>docker
build -t &lt;tag&gt;</code>.  The documentation isn&rsquo;t superbly lucid, but you are
encouraged to structure the &ldquo;tag&rdquo; used here as
<code>&lt;username&gt;/&lt;image&gt;:&lt;version&gt;</code>.  The <code>version</code> identifier can be
anything, but <code>latest</code> has some semantic significance.</p>

<p>I picked a semver scheme, I would just recommend being consistent, and
keeping Dockerfile inline documentation and published image versions
consistent.</p>

<h2>Check Dockerfiles into GitHub</h2>

<p>Because why not?</p>

<p>Whilst finding ways to solve some problem or accomplish some goal, I
found looking at others&#8217; Dockerfiles very useful.  My issues were only
very slightly unique, the problems had generally all been solved by
others.</p>

<p>Quinten Krijger was kind enough to have put a bunch of Dockerfiles in
<a href="https://github.com/Krijger/docker-cookbooks">his repo</a>, they are
worth a look.</p>

<h2>Running in the foreground</h2>

<p>To package your app up into a container (or when writing pretty much
any other Dockerfile) that serves as a single purpose self-contained
application, you quickly find that you need to run your app as a
foreground process, and likely as the default command to run.</p>

<p>If the app container you&rsquo;re creating is based on your own code, this
is entirely within your control.</p>

<p>If the app container is based on a third-party daemonizing service, or
if your container must have additional services running, using
something like <a href="http://supervisord.org/">Supervisor</a> might help.  There are plenty of
examples of configuring Supervisor, including in
<a href="http://docs.docker.io/en/latest/examples/using_supervisord/">Docker&rsquo;s own documentation</a>.</p>

<p>Before adding too many services into a single image, ask yourself
whether this is really necessary &ndash; could these dependencies be
fulfilled by other independent Docker containers, with communication
over the network?</p>

<h2>Inter-container communication and web services APIs</h2>

<p>If a good Docker container is single-purpose, then how can you build a
system of containers?  Docker&rsquo;s <code>docker run --name &lt;name&gt;</code> and <code>docker
run --link &lt;name&gt;:&lt;alias&gt;</code> is designed to help you with just that.</p>

<p>Run a service container with <code>--name foo</code> and its exposed ports are
available to be mapped into client containers.  Run a client container
with <code>--link foo:bar</code>, and the &ldquo;foo&rdquo; container&rsquo;s ports are exposed via
a variety of environment variables within the client, using &ldquo;bar&rdquo; as
an identifier.</p>

<p>For example, a client application depends on an ElasticSearch service.
An ES service would typically expose its HTTP API on port 9200.  The
application within the client container can be written to expect the
ElasticSearch dependency to be fulfilled by injection of environment
variables corresponding to the alias you decide to always run it with
(&ldquo;elasticsearch&rdquo;), so specifically <code>$ELASTICSEARCH_PORT_9200_TCP_ADDR</code>
and <code>$ELASTICSEARCH_PORT_9200_TCP_PORT</code>.</p>

<p>By running the ElasticSearch container with <code>--name es</code>, and the
client with <code>--link es:elasticsearch</code>, the service is wired into the
client via the predetermined env vars, whose values are only set at
run time.  Very neat, and
<a href="http://docs.docker.io/en/latest/use/working_with_links_names/">full documentation for linking containers</a> is on Docker&rsquo;s site.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[OpenVPN for the Uninitiated: Building a secure connection to your home internet connection]]></title>
    <link href="http://brownsofa.org/blog/2013/11/12/openvpn-for-the-uninitiated/"/>
    <updated>2013-11-12T08:34:00-07:00</updated>
    <id>http://brownsofa.org/blog/2013/11/12/openvpn-for-the-uninitiated</id>
    <content type="html"><![CDATA[<p><img class="left" src="http://brownsofa.org/images/2013-11-12/rusty-padlock-on-an-old-metal-door.jpg" width="350" height="242" title="Padlock" alt="A rusty padlock">
It&rsquo;s clear that using wifi access points I don&rsquo;t own is an increasingly risky proposition,
and given I&rsquo;m going to be using others&#8217; wifi more soon,
I wanted to put together some kind of VPN to help protect my network comms.
Since I want all network comms to be routed through the VPN to a trusted access point,
popular methods using Hamachi didn&rsquo;t seem to go far enough.
A VPN would make an interesting reason to get a Raspberry Pi, but I have an older laptop laying idle.</p>

<p>A lightweight Linux distro and OpenVPN server, and the Tunnelblick OSX OpenVPN client
made setting up a VPN tunnel a fairly straightforward system to build and manage
(after working through a couple of issues that would be obvious to a networking pro).
With configuration of a DynDNS hostname, port forwarding on my home wireless router,
and a little networking black magic,
I now have give secure access to my home network and internet connection from anywhere in the world.</p>

<p>I found plenty of well-written resources online for getting OpenVPN installed and running,
but nothing quite fit my need to build a VPN to my home network internet connection.
I don&rsquo;t know that this post reflects the <em>best</em> way to do what I wanted to do,
but I hope if you are after a similar setup it will save you some time digging.</p>

<!-- more -->


<hr />

<h2>Desired Goal</h2>

<p>When I&rsquo;m working on an untrusted wireless network,
I want to be able to flick a switch on my laptop and route all network traffic
through an encrypted tunnel back to my home network connection.
I might also want to access file resources on machines at home,
but my primary goal is to secure my network comms whilst away from home.</p>

<p>To do this, I need to build a VPN,
on the server end of which needs to be a network bridge to to my home network
(and internet connection).</p>

<p>I have full access to all machines involved, and I&rsquo;m willing to securely pre-share keys.</p>

<h2>Steps</h2>

<ol>
<li>Clean build of a new server machine</li>
<li>Basic point-to-point OpenVPN</li>
<li>Configuring a network bridge</li>
<li>Hardening</li>
</ol>


<h2>Step 1. Build a clean server</h2>

<p>I installed <a href="http://lubuntu.net/">Lubuntu</a> on an older laptop (500MB RAM).
As one would expect, there were no issues during installation,
and performance once it was installed isn&rsquo;t too bad.
If I were more serious about this I would install a pure server OS without X,
but I was just after some point-and-click quick wins.</p>

<p>I installed few extra packages, only notably the SSH server,
which I then configured to only allow key-based logins.
In <em>/etc/ssh/sshd_config</em>, ensure the following config values are set:</p>

<pre><code>RSAAuthentication yes
PubkeyAuthentication yes
ChallengeResponseAuthentication no
PasswordAuthentication no
UsePAM no
</code></pre>

<h2>Step 2. Basic OpenVPN setup</h2>

<h3>OpenVPN Server</h3>

<p>Installing <a href="http://http://openvpn.net/">OpenVPN</a> on this Ubuntu-based OS was as simple as <code>apt-get install openvpn</code>,
and basic configuration is well-explained on the <a href="https://help.ubuntu.com/12.04/serverguide/openvpn.html">Ubuntu site</a>.
One small difference I encountered from the instructions was the location of the <code>easy-rsa</code> CA utilities &ndash;
they are now on <a href="https://github.com/OpenVPN/easy-rsa">GitHub</a>.</p>

<h3>OSX Client</h3>

<p><a href="https://code.google.com/p/tunnelblick/">Tunnelblick</a> is what I came across to run the client part of the VPN.
It&rsquo;s just a thin wrapper over the OpenVPN client configuration file,
and those config files are not avoidable,
but it does make starting and stopping the VPN easy.</p>

<p>Tunnelblick&rsquo;s instructions are straightforward to follow;
in fact, once installed it basically walks you through where it wants configuration files and keys copied and edited.
I just SCP&rsquo;d the client keys generated by the CA scripts back to my laptop,
dropped them into the right place,
and made the minor adjustments to config file per the Tunnelblick docs and comments in the config file itself.</p>

<h3>Router and DNS</h3>

<p>My wireless router happens to have an option for a DynDNS account.
DynDNS don&rsquo;t do a free dynamic DNS service any more,
but a little google research turned me up something useful.</p>

<p>I configured my router with the DynDNS account info,
set my VPN server to be allocated a particular IP address from the DHCP pool,
and set up UDP port 1194 (OpenVPN) and TCP port 22 (SSH) to be forwarded to the VPN machine.
After this, connecting to the machine via SSH worked right away.</p>

<p>I then reconfigured my client configuration in Tunnelblick to connect to the VPN at my new dynamic dns hostname.
That too worked without fault.</p>

<h2>Step 3. Networking</h2>

<p>Thinking I was done at this point,
a wrinkle emerged the first time I was testing away from home:
by default, only resources on the private network are routed through the VPN.
I wanted all network traffic from my laptop to go through the VPN.</p>

<p>I spotted this when I tried verifying my IP address had changed once connected to the VPN.
Reloading <a href="http://www.tracemyip.org/">TraceMyIP</a> in a browser once connected didn&rsquo;t show me any change.
Looking at the Tunnelblick configuration, there&rsquo;s a checkbox to force all traffic through the VPN
and this checkbox isn&rsquo;t checked by default.</p>

<p>Basically all I needed to do was set up IP masquerading on the VPN server.
After some lost time spent looking into setting up a network bridge,
I found that just a couple of commands got me going (albeit temporarily).
<code>sudo sysctl -w net.ipv4.ip_forward=1</code> enables IP forwarding,
and <code>sudo iptables -t nat -A POSTROUTING -s 10.8.0.0/24 -o eth0 -j MASQUERADE</code>
sets up IP masquerading on my NIC of choice.
Make sure the IP address and netmask matches what is set in <em>/etc/openvpn/server.conf</em>; I have</p>

<pre><code>server 10.8.0.0 255.255.255.0
</code></pre>

<p>I also added a configuration option to the <em>/etc/openvpn/server.conf</em> to make clients push all traffic through the VPN:</p>

<pre><code>push "redirect-gateway def1"
</code></pre>

<p>After doing these couple of steps, I was able to connect to the VPN and see my external IP address was that assigned to my home network.</p>

<h3>Persistent network configuration</h3>

<p>Now I needed to make the networking changes permanent.</p>

<p>In <em>/etc/sysctl.conf</em>, add the line</p>

<pre><code>net.ipv4.ip_forward=1
</code></pre>

<p>to enable IP forwarding.</p>

<p>Exactly per <a href="https://help.ubuntu.com/community/IptablesHowTo#Solution_.232_.2BAC8-etc.2BAC8-network.2BAC8-if-pre-up.d_and_...2BAC8-if-post-down.d">this page with iptables info</a>,
I set up a couple of simple networking startup and shutdown scripts to save any changes to the firewall configuration:</p>

<p><em>/etc/network/if-pre-up.d/iptablesload</em>:</p>

<pre><code>#!/bin/sh
iptables-restore &lt; /etc/iptables.rules
exit 0
</code></pre>

<p><em>/etc/network/if-post-down.d/iptablessave</em>:</p>

<pre><code>#!/bin/sh
iptables-save -c &gt; /etc/iptables.rules
if [ -f /etc/iptables.downrules ]; then
  iptables-restore &lt; /etc/iptables.downrules
fi
exit 0
</code></pre>

<p>Remember to make the scripts executable.</p>

<p>Since I hadn&rsquo;t restarted since making the temporary <code>iptables</code> change,
on server shutdown and restart I verified the IP masquerade settings were still in effect
(run <code>sudo iptables-save -c</code> to see the active settings),
and that they were described in <em>/etc/iptables.rules</em>.</p>

<hr />

<p>I hope my fumblings through this might help you set up your own VPN.
Let me know if you want any clarification on any of the whats or hows.</p>

<p>Image credit: <a href="http://www.colourbox.com/preview/1928550-192532-rusty-padlock-on-an-old-metal-door.jpg">http://www.colourbox.com/preview/1928550-192532-rusty-padlock-on-an-old-metal-door.jpg</a></p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Application Build Tools]]></title>
    <link href="http://brownsofa.org/blog/2012/08/28/application-build-tools/"/>
    <updated>2012-08-28T19:12:50-06:00</updated>
    <id>http://brownsofa.org/blog/2012/08/28/application-build-tools</id>
    <content type="html"><![CDATA[<p>In my experience, there’s a common set of <em>types</em> of tools that every project needs. When it’s time to start up a new project, here’s an outline of the things to consider when putting together a new tool chain, and some examples of good tools I’ve seen recently.</p>

<!-- more -->


<h2>Source Control</h2>

<p>Well, it’s not really part of the build tools, but if you’re not using <a href="http://git-scm.com/">Git</a> or <a href="http://bazaar.canonical.com/en/">Bazaar</a> or <a href="http://mercurial.selenic.com/">Mercurial</a> or <a href="http://subversion.tigris.org/">Subversion</a> or <a href="http://www.perforce.com/">Perforce</a> (or even <a href="http://www.nongnu.org/cvs/">CVS</a>, and I’d even give you it if you were using <a href="http://www.microsoft.com/visualstudio/en-us/products/2010-editions/team-foundation-server/overview">TFS</a>) or some other source code repository, you should get yourself some source control before anything else.</p>

<p>The latest tools (Git, Bazaar and Mercurial) are all Distributed Version Control Systems, wherein there is not necessarily a single centralized repository, but where any given clone of the repository contains the full history. They have powerful branching and merging capabilities, eclipsing those in SVN which in turn eclipsed those in CVS. If you are working in a team situation, particularly a distributed team, consider one of the DVCS tools.</p>

<p>Social coding sites like <a href="http://github.com">GitHub</a> (Git-based) and <a href="https://bitbucket.org/">Bitbucket</a> (Git and Mercurial) are supplanting the more traditional online repositories such as <a href="http://sourceforge.net/">SourceForge</a> because they’re slick, free to get started, have great features, and are easy to use.</p>

<p>There’s just no excuse…</p>

<h2>Unit Tests</h2>

<p>I’m just going to assume that you write unit tests for your code. In fact, I’m just going to say that everyone’s doing <a href="http://www.amazon.com/Test-Driven-Development-By-Example/dp/0321146530">TDD</a>. If you’re not doing TDD, perhaps consider it for your new project &ndash; it’s the easiest time to start. If you’re adamantly not, this should all still apply.</p>

<p>At the very least you need a set of basic assertions for your language of choice, and a way to run your app’s test harness. It’s not hard to roll your own, but you are likely reinventing a wheel.</p>

<p>More sophisticated unit test frameworks basically can give you more assertions, more structures for organizing your tests, and better integration with your platform and development environment.</p>

<p>Whether simple or complex, the most important thing when evaluating these frameworks is readability of code, and of test’s failure messages.</p>

<p>You will be generating and refactoring lots of test code, and the test frameworks can make or break whether your test code is readable. What constitutes “readable” is more personal, but read through some test code written with the framework and see how clear the <em>intent</em> of the tests are without having to trawl the API docs.</p>

<p>You will also be writing tests that are in some sense designed to fail. When they do, the error message displayed by the test runner needs to be clear and informative, and either help you verify your assumptions about the as-yet unwritten code, or to quickly find the failing test and trace back through the call stack.</p>

<p>Simple but good frameworks I’ve used include <a href="http://unittest-cpp.sourceforge.net/">UnitTest++</a> for C++, and the tools built in to the Python standard libraries (wonderfully introduced in the <a href="http://www.diveintopython.net/unit_testing/index.html">Dive Into Python</a> book).</p>

<p>The <a href="http://www.martinfowler.com/bliki/Xunit.html">xUnit</a> family of test libraries originated in a design by Kent Beck, and were made ubiquitous by <a href="http://www.junit.org/">JUnit</a> and <a href="www.nunit.org">NUnit</a>. They are well understood and <a href="http://www.amazon.com/xUnit-Test-Patterns-Refactoring-Code/dp/0131495054">well documented</a>, and are surely available in just about every language imaginable.</p>

<p>I recommend a more <a href="http://dannorth.net/introducing-bdd/">behavior-driven</a> approach. It encourages a valuable switch in focus; making your code right is made subservient to making the right code. My favorite unit test libraries adopt this style of testing: Ruby’s <a href="http://rspec.info/">RSpec</a>, <a href="https://github.com/pivotal/jasmine/wiki">Jasmine</a> for JavaScript, and the <a href="http://code.google.com/p/hamcrest/wiki/Tutorial">Hamcrest matchers</a> on the JVM all make me really happy. <a href="https://github.com/jaycfields/expectations">Expectations</a> for Clojure is both simple and behavioral.</p>

<h2>Integration/Acceptance Tests</h2>

<p>Continuing the theme of “write the right code”, it’s important to make sure the whole system meets whatever needs are set out. At some point you need to stick together your a number of the various bits of your app and make sure they at least look like the whole thing might work.</p>

<p>Acceptance tests should be written in the language of your problem domain, and ideally will be readable by your pointy-hair types. They should express what the system should be doing. See any of <a href="http://gojko.net/">Gojko Adzic</a>’s work. Since they are high level and written in terms of business needs, pick a tool that supports this. <a href="http://cukes.info/">Cucumber</a> and <a href="http://fitnesse.org/">FitNesse</a> both have implementations in many languages, and have various plugins or extensions to support development of different types of application. I currently use <a href="http://watirwebdriver.com/">Watir WebDriver</a> for web UI testing; tests are written in Ruby, and because of its WebDriver roots it’s very easy to test in multiple browsers using Selenium Grid service providers like <a href="http://saucelabs.com/">Sauce Labs</a>. Other tools include <a href="https://github.com/jnicklas/capybara">Capybara</a> (which I believe is somewhat tailored to Rails apps) and <a href="http://seleniumhq.org/">Selenium</a>.</p>

<p><em>One note regarding Selenium IDE and perhaps other similar tools: I strongly recommend avoiding the GUI test recorder. It is tempting to think it will save time and give everyone the ability to write acceptance tests; you end up with a pile of unmaintainable XPath expressions and brittle tests that none of your developers want to touch with a bargepole. This is my experience at least; YMMV. Working together as a cross-functional team is the right way to build the tests anyway.</em></p>

<p>Integration tests allow you to compose a small subset of your entire system, and ensure that the independent pieces work correctly with each other (a unit test, in comparison to integration tests, ideally should not instantiate more than one of your system’s classes. See the “I” of FIRST). I go back and forth on this one, but my current approach is to use my unit test framework to write the tests, but explicitly and intentionally separate the integration tests from the unit tests.</p>

<h2>Mock Objects</h2>

<p>Remember the <a href="http://pragprog.com/magazines/2012-01/unit-tests-are-first">FIRST</a> acronym for unit tests? “F”, “I” and I believe to some degree, “T” are dependent on being able to substitute the collaborators your code under test interacts with for some type of stand-in. Whether you only need a simple test double, or you want a full-on programmable mock, <a href="http://martinfowler.com/bliki/TestDouble.html">these test-time objects</a> are easier to make if you enlist the help of a mock object library.</p>

<p>Examples. <a href="http://lmgtfy.com/?q=mock+object+framework">So many</a> examples… <a href="http://sinonjs.org/">Sinon</a> for JavaScript rocks. <a href="http://code.google.com/p/mockito/">Mockito</a> is my go-to in Java.</p>

<p>If you haven’t used mocks before, this is one case I’d absolutely recommend you write these types of objects from scratch the first time. The frameworks will absolutely help you later on, but your knowledge of what type of test stand-in to use, when, and why, will be greatly assisted if you roll your own for a while.</p>

<h2>Static Analysis</h2>

<p>This is an interesting area, one which appeals to the metrics nerd in me. It is possible to have a program inspect your source code and perform various types of analyses. Examples I’ve used include:</p>

<ul>
<li><p>checking for basic syntactical errors (javac, gcc, g++, …)</p></li>
<li><p>more subtle syntactical and best-practice conformance (<a href="http://www.jshint.com/">JSHint</a>, <a href="http://www.jslint.com/">JSLint</a>, <a href="http://checkstyle.sourceforge.net/checks.html">Checkstyle</a>)</p></li>
<li><p>conformance with team coding conventions (<a href="http://blogs.msdn.com/b/codeanalysis/">FXCop</a>, which I think now ships with Visual Studio)</p></li>
<li><p>inclusion of appropriate license headers (<a href="http://code.google.com/p/maven-license-plugin/">maven-license-plugin</a>)</p></li>
<li><p>scanners for common web security vulnerabilities (<a href="http://sourceforge.net/projects/rips-scanner/">RIPS</a>)</p></li>
<li><p>code coverage of your unit tests (<a href="http://emma.sourceforge.net/">EMMA</a>, which strictly speaking isn’t a static analyzer)</p></li>
<li><p>calculating your code’s cyclomatic complexity (<a href="http://javancss.codehaus.org/">JavaNCSS</a>, though I haven’t used it)</p></li>
</ul>


<p>It’s possible to get an incredible amount of information about your code, some more useful than others.</p>

<h2>Documentation</h2>

<p>Agile or not, there is a need for some amount of (valuable) documentation. As a somewhat responsible software developer, I think there are a few high value, low cost artifacts that I should take responsibility for: auto-generated source code documentation, developer READMEs, and API documentation. I do most of my work on web systems, and I realize my opinions tend towards those types of products.</p>

<h3>Auto-generated source code docs</h3>

<p>By this I mean things like <a href="http://www.oracle.com/technetwork/java/javase/documentation/index-jsp-135444.html">JavaDoc</a> comments. These are simple formatting rules applied in comment blocks to mark up the content of the comment. The source code can be post-processed, documentation can be extracted and reprocessed into immediately publishable HTML, PDF, whatever. Some IDEs also use the documentation comments to enrich the context-sensitive help and autocompletion tools. There are many implementations of this type of tool, including <a href="http://www.doxygen.org">Doxygen</a> (supports a multitude of languages), <a href="http://rdoc.sourceforge.net/">RDoc</a> and <a href="http://yardoc.org/">Yard</a> for Ruby, and <a href="http://www.phpdoc.org/">PHPDocumentor</a>. These tools are often particularly powerful in strongly typed languages, since the documentation parser can easily parse the source code to determine types and hierarchies.</p>

<p>From the JavaScript community, a less-formal type of tool has emerged, exemplified by <a href="http://jashkenas.github.com/docco/">Docco</a>. In these tools, few (if any) assumptions are made about the markup content of the comments, but the output rendering of the documentation places the comments in the left column, lined up with the code they annotate in the right hand column. Docco will convert any <a href="http://daringfireball.net/projects/markdown/">Markdown</a> content to marked up HTML in the output too. The <a href="http://documentcloud.github.com/underscore/docs/underscore.html">Underscore documentation</a> is generated by Docco, and it’s useful and looks good.</p>

<p>For those who share my general distaste of commented code, it is true that the documentation will only be as good as the comments that you write; if your comments aren’t maintained as your source code changes, your documentation will be confusing at best, and horribly wrong at worst. If you’re going to do this, there’s a certain commitment that’s required.</p>

<h3>Developer READMEs</h3>

<p>Nothing groundbreaking here. Look at most projects’ home page on GitHub, and the README.md file is presented front and center. Put whatever you want in it, but make sure you cover at least the items below. Think about what a new developer getting started on the project would need (or yourself in three months time when you’ve inevitably shifted everything unnecessary out of your brain, including how <em>this</em> project works):</p>

<ul>
<li><p>What dependencies you need to install by hand</p></li>
<li><p>How to install the dependencies your project installs</p></li>
<li><p>How to build the software</p></li>
<li><p>How to run the software</p></li>
<li><p>Any special magic one needs to know in order to write new code or fix bugs</p></li>
</ul>


<p>Plain text files have a nice low barrier to entry, and Markdown adds a little sugar and options for post-processing for a low cost.</p>

<h3>API Documentation</h3>

<p>This section assumes you’re writing at least a little bit of code that someone else will re-use &ndash; whether it’s a RESTful web service or a redistributed code library.</p>

<p>Your API is a contract &ndash; by releasing an API you implicitly agree to certain reasonable conventions around that API. These include that the code does what it says it will do, and by extension, what the documentation says the code will do. You also need to provide users of your code some indication of how to use it. If you think you write perfectly understandable code that doesn’t need documentation, well, perhaps just think of the rest of us who haven’t attained your level of coding mastery.</p>

<p>First, explain <em>how</em> your code should be used. Coherent APIs have a philosophy, a way of doing things. Introduce the neophyte to that way of thinking. Succinct, complete, accurate examples go a long way.</p>

<p>Second, document the precise inputs and outputs for all components of the API, and any requirements for use that a programmer must manage themselves. This is your contract. When you are changing the code, be aware of when you are breaking the contract in a way that is not backwards-compatible; you will need to write a new contract. See Versioning for a tad more discussion.</p>

<p>Tools to generate this type of documentation vary widely. You may just mark up your source code with a little extra documentation, then generate and publish your docs from that. RESTful APIs need a little more work, and some sources would indicate that all one needs to publish are some schema and the media types. I think a little more effort allows other developers to use your API more easily, and this is surely a large reason for using REST in the first place. <a href="https://github.com/mashery/iodocs">IODocs</a> has a great approach: a terse JSON-formatted input file describes the API in a very concise way. IODocs then generates a documentation website around the API description, automatically generating tools to allow you to interact with the API in real time. Hands-on is often an effective way to learn.</p>

<h2>Dependency Management</h2>

<p>Ooh, sounds like fun, doesn’t it! Well, it’s not. It can go horribly, awfully wrong &ndash; search for DLL hell, JAR hell, Gem hell, NPM hell, pick your poison. Here’s the issue: your code depends on Library A v5, and on Library B v3. Library A depends on Library B v4. What version of Library B do you need? Gah.</p>

<p>Transitive dependency management, artifact caching, searching for and resolving artifacts. Things such as these have been taken care of by the smart people behind <a href="http://maven.apache.org/">Maven</a>, <a href="http://ant.apache.org/">Ant</a>, <a href="http://rubyforge.org/projects/rubygems/">RubyGems</a>, <a href="https://npmjs.org/">NPM</a>, and many other tools. If you’re going to be writing code any more complex than “Hello World”, you will likely benefit from one of these tools.</p>

<h2>Versioning</h2>

<p>This one’s easy: use <a href="http://semver.org/">Semver</a> and all the rules and conventions therein. Its lack of ambiguity makes it so easy to adopt.</p>

<h2>Tools to wrap it all up</h2>

<p>You need something to tie all of the above up in a neat bow. You could write some shell scripts, but there are better options. It also seems that whilst there aren’t huge numbers of tools in this area, the pace at which new tools are being released is increasing rapidly.</p>

<p>If you’re a C programmer, you’ve written a <code>makefile</code> for <a href="http://www.gnu.org/software/make/">make</a>. <code>makefile</code>s are a declarative configuration file that describes how your source code needs to be compiled, assembled and linked. Without <code>make</code>, C programs beyond one or two source files are too much effort.</p>

<p>Fast-forward 7 years after make’s inception, and <a href="http://ant.apache.org/">Ant</a> first hits the scene. Ant is a tool primarily designed to compile and build Java applications, but it can be used as a more genera-purpose tool. It uses XML files to describe how the project should be built, but again in a declarative manner.</p>

<p>Soon after Ant was released, <a href="http://maven.apache.org/">Maven</a> hit the interwebs. Maven also uses XML to describe the project configuration (typically <code>pom.xml</code>), but in exchange for its highly opinionated idea of how source code should be laid out and named, Maven allows you to forego a huge amount of boilerplate build file configuration. One common criticism of Maven, however, is that it’s really hard to get Maven to do something non-standard. Writing a plugin isn’t usually an effective solution; I’ve seen plenty of solutions where Maven calls out to an Ant task to do something hacky.</p>

<p>It’s clear that depending on what you want to do, there’s going to be differing sweet spots of declarative vs imperative solutions, and convention versus configuration.</p>

<p>Some other notable tools I’ve run into and like are <a href="https://github.com/cowboy/grunt">Grunt</a> for JavaScript, <a href="http://rubyforge.org/projects/rake/">Rake</a> for Ruby, <a href="http://www.gradle.org/">Gradle</a> for various JVM languages, and <a href="https://github.com/technomancy/leiningen">Leiningen</a> for Clojure. Each has its own set of strengths and trade-offs. There are still certain Java tasks I might use Maven for, and I might also recommend learning how to use Ant as a handy fallback for weird situations, using <a href="http://ant.apache.org/ivy/">Ivy</a> to add dependency management capabilities. My go-to replacement for Ant, however, is Rake. The configuration files (<code>rakefile</code>s) are written in Ruby, but Rake is easily applicable to any task. There’s a nice set of declarative tasks available, and at any time you can drop into vanilla Ruby to do whatever needs doing.</p>

<h2>Other Considerations</h2>

<h3>CI Integration</h3>

<p>That’s right, “Continuous Integration Integration”. How do all of these things fit into your CI system? Having your CI server run the entire build and release process is so valuable &ndash; in order to be confident enough to do this automatically you need a high degree of confidence in your tools, which implies that your tools are likely solid, powerful, and get the job done. These are all good things to have, even if you don’t <a href="http://www.amazon.com/Continuous-Delivery-Deployment-Automation-Addison-Wesley/dp/0321601912/">continuously deploy</a> your software <a href="http://code.flickr.com/#foot">a dozen times a day</a>.</p>

<p>Think about how the output from the various tools can be parsed by your CI &ndash; JUnit XML format is a common output format for test runners whether or not it has anything to do with Java.</p>

<p>Take advantage of the visualization tools and plugins for your CI. They’re fun and pretty, but sometimes surprisingly useful: I have dropped a test result history plot (i.e. largely green, trending up-and-to-the-right) into a presentation and the pointy hair types definitely grokked that.</p>

<h2>Conclusion</h2>

<p>In short: myriad options. Chasing down and using the latest cool library is often unproductive, but starting up a new project is a great time to improve your tool chain and improve your productivity or quality, increase your visibility into your code, get faster feedback on errors, improve your code in general, or just geek out on graphs and charts. Take some time to learn what’s out there, take inspiration from other great tools, and perhaps roll your own tool to rule them all.</p>

<p>Drop me a comment and let me know what awesome tools I have missed &ndash; I’ll take a look for the next project.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Leiningen for OSX 10.5.8]]></title>
    <link href="http://brownsofa.org/blog/2012/08/09/leiningen-for-osx-10-5-8/"/>
    <updated>2012-08-09T22:54:15-06:00</updated>
    <id>http://brownsofa.org/blog/2012/08/09/leiningen-for-osx-10-5-8</id>
    <content type="html"><![CDATA[<p>My old MacBook Pro (A1260/MacBookPro4,1/OS X 10.5.8 Leopard) might be getting a little ragged at the edges, might be needing some new memory, but it can still play with the cool kids after fixing a couple of small issues getting <a href="https://github.com/technomancy/leiningen/">Leiningen</a> (both 1 and 2) to work.  In short, using Java 1.6 fixed the problem.</p>

<!-- more -->


<p>Download Leiningen in the (well, my) usual manner:</p>

<pre><code>mkdir -p ~/local/bin
export PATH=~/local/bin:$PATH
# Leiningen 1 is currently "stable"
curl -k 'https://raw.github.com/technomancy/leiningen/stable/bin/lein' &gt; ~/local/bin/lein1
# Leiningen 2 is "preview"
curl -k https://raw.github.com/technomancy/leiningen/preview/bin/lein &gt; lein
chmod a+x ~/local/bin/lein*
</code></pre>

<p>Problem now is that <code>lein</code> doesn&rsquo;t work: I was getting <code>Caused by: java.lang.ClassNotFoundException: javax/tools/ToolProvider</code>.</p>

<p>It looked like I was running Java 1.5:</p>

<pre><code>$ java -version
java version "1.5.0_30"
Java(TM) 2 Runtime Environment, Standard Edition (build 1.5.0_30-b03-389-9M3425)
Java HotSpot(TM) Client VM (build 1.5.0_30-161, mixed mode, sharing)
</code></pre>

<p>Google searches turned up the info that indicated Java 1.6 was probably available, just not configured. Additionally, re-symlinking <code>/System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK</code> to 1.6 wasn&rsquo;t enough for me, I also had to update <code>Current</code>:</p>

<pre><code>$ cd /System/Library/Frameworks/JavaVM.framework/Versions
sudo rm Current
sudo ln -s 1.6 Current
</code></pre>

<p>Now, <code>java -version</code> was reporting 1.6, and <code>lein</code> was all happy.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Getting Started with Amazon AWS Command Line Basics]]></title>
    <link href="http://brownsofa.org/blog/2012/05/14/getting-started-with-amazon-aws-command-line-basics/"/>
    <updated>2012-05-14T21:10:55-06:00</updated>
    <id>http://brownsofa.org/blog/2012/05/14/getting-started-with-amazon-aws-command-line-basics</id>
    <content type="html"><![CDATA[<p>I didn&rsquo;t even realize there&rsquo;s a set of command line tools for working with Amazon&rsquo;s Web Services.  It only took a few mins to get started, but it wasn&rsquo;t immediately apparent what needed to happen.</p>

<p><em>I&rsquo;m using OSX Lion.  If you&rsquo;re using another *nix this is all fairly easy to translate. I have no idea how this could be Windows-ified&hellip;</em></p>

<!-- more -->


<h2>Download and Install</h2>

<p>I downloaded the tools as a zip archive from <a href="http://aws.amazon.com/developertools/351">http://aws.amazon.com/developertools/351</a>.  I like to keep this kind of package within a <code>~/local</code> folder, so:</p>

<pre><code>mkdir ~/local
cd Downloads
unzip ec2-api-tools.zip
mv ec2-api-tools-1.5.3.1 ~/local
</code></pre>

<p>To make upgrades easier, create a symlink to that directory:</p>

<pre><code>cd ~/local
ln -s ec2-api-tools-1.5.3.1 ec2-api-tools
</code></pre>

<h2>Security</h2>

<p>You need your username and password to get into the AWS web interface.  You&rsquo;ll still need to authenticate with the command line tools, but you have a more convenient mechanism to do this &ndash; X.509 keys.</p>

<p>Log into the AWS web page, and go to <strong>My Account</strong> > <strong>Security Credentials</strong>.  Go to the <strong>X.509 Certificates</strong> tab and hit <strong>Create A New Certificate</strong>.  Download the private key and the certificate and save them somewhere safe &ndash; since it already has appropriate permissions and contains keys, I save mine to <code>~/.ssh/pk.pem</code> and <code>~/.ssh/cert.pem</code> respectively.</p>

<h2>Configure</h2>

<p>The tools require you to set <code>JAVA_HOME</code> and <code>EC2_HOME</code> environment variables, and there are a couple of other variables that will save you a whole lot of typing. Add the following to the end your <code>~/.bash_profile</code>:</p>

<pre><code>export PATH=$HOME/local/ec2-api-tools/bin:$PATH
export JAVA_HOME=/System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK/Home
export EC2_HOME=$HOME/local/ec2-api-tools
export EC2_PRIVATE_KEY=~/.ssh/pk_ec2.pem
export EC2_CERT=~/.ssh/cert_ec2.pem
export EC2_URL=https://ec2.us-west-1.amazonaws.com
</code></pre>

<p>Be careful with the last of these.  I host my instances in the US-West-1 region &ndash; you will likely need to figure out which URL to put here based on the region your instances or volumes are at.  If you have machines in multiple regions, use the <code>--region</code> switch in the commands instead.</p>

<p>Source the file to have the changes take effect:</p>

<pre><code>. ~/.bash_profile
</code></pre>

<p>and carry on.</p>

<h2>Run</h2>

<p>Now, it&rsquo;s easy.  For example, run <code>ec2-describe-instances</code> &ndash; it should show you a list of all your EC2 instances, and a whole bunch of info about them.  I leave it to you to work out the other 280-odd commands.  Looks like you can do pretty much do any operation to manage EC2 instances, images, volumes, networking, snapshots, &hellip;</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Building NodeJS on OS X 10.5.8]]></title>
    <link href="http://brownsofa.org/blog/2011/05/25/building-nodejs-on-os-x-10-5-8/"/>
    <updated>2011-05-25T21:58:44-06:00</updated>
    <id>http://brownsofa.org/blog/2011/05/25/building-nodejs-on-os-x-10-5-8</id>
    <content type="html"><![CDATA[<p>It seems that I borked xcode, did something bad with my libssl, or just that my system&rsquo;s too out of date to trivially <a href="http://sites.google.com/site/nodejsmacosx/">install</a>, <a href="http://shapeshed.com/journal/setting-up-nodejs-and-npm-on-mac-osx/">homebrew</a> or <a href="http://www.devpatch.com/2010/02/installing-node-js-on-os-x-10-6/">build</a> <a href="http://nodejs.org/">NodeJS</a>.  I really want to install Node, so here&rsquo;s what I just did.</p>

<!-- more -->


<p>I started off downloading and extracting the latest NodeJS source tarball (0.4.2 at time of writing).  After attempting to configure and build, I was getting some complaints out of make:</p>

<p>I was getting some complaints out of <code>make</code>:</p>

<pre><code>../src/node_crypto.cc: In function ‘void node::crypto::InitCrypto(v8::Handle&lt;v8::object&gt;)’:
../src/node_crypto.cc:2917: error: ‘SSL_COMP_get_compression_methods’ was not declared in this scope
Waf: Leaving directory `/Users/Ian/node-latest-install/build'
Build failed:  -&gt; task failed (err #1): 
    {task: cxx node_crypto.cc -&gt; node_crypto_4.o}
</code></pre>

<p>After a helpful tweek from <a href="http://twitter.com/#!/tonymilne">@tonymilne</a> I looked at the output of <code>./configure</code> slightly more closely: whilst it reported it found <code>header openssl/crypto.h</code>, it said that <code>openssl</code> was not found.</p>

<p>Getting an updated version of OpenSSL was pretty easy with homebrew:</p>

<pre><code>brew create http://www.openssl.org/source/openssl-0.9.8r.tar.gz
brew install openssl
</code></pre>

<p>It didn&rsquo;t quite fully install though.  It told me &ldquo;This formula is keg-only, so it was not symlinked into /usr/local&rdquo;, and that</p>

<pre><code>If you build your own software and it requires this formula, you'll need
to add its lib &amp; include paths to your build variables:

  LDFLAGS: -L/usr/local/Cellar/openssl/0.9.8r/lib
  CPPFLAGS: -I/usr/local/Cellar/openssl/0.9.8r/include
</code></pre>

<p>Turns out that similar but different problems were solved by <a href="http://canonical.org/~kragen/compiling-node-on-macos.html">setting options</a> with configure, and running <code>./configure --help</code> in the folder with the NodeJS source shows some pertinent options.  I tried</p>

<pre><code>./configure --prefix=~/local --openssl-includes=/usr/local/Cellar/openssl/0.9.8r/include  --openssl-libpath=/usr/local/Cellar/openssl/0.9.8r/lib
</code></pre>

<p>and it seems like it was successful &ndash; <code>node --vars</code> includes <code>-DHAVESSL=1</code>.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[The Compleat ATtiny13 LED Flasher: Part 3 - Low Power Mode ]]></title>
    <link href="http://brownsofa.org/blog/2011/01/09/the-compleat-attiny13-led-flasher-part-3-low-power-mode/"/>
    <updated>2011-01-09T23:36:28-07:00</updated>
    <id>http://brownsofa.org/blog/2011/01/09/the-compleat-attiny13-led-flasher-part-3-low-power-mode</id>
    <content type="html"><![CDATA[<p><em>This is the final part of three in attempting to explain how to make the ATtiny13 flash a LED.</em></p>

<ul>
<li><p><em>Part 1: <a href="http://brownsofa.org/blog/archives/191">Setup, Hardware and A Basic Solution</a></em></p></li>
<li><p><em>Part 2: <a href="http://brownsofa.org/blog/archives/215">Using timer interrupts</a></em></p></li>
<li><p><em><strong> Part 3: Low power mode</strong></em></p></li>
</ul>


<p>In previous posts we&rsquo;ve looked at creating a simple LED flasher circuit for the ATtiny, a first-pass program for the ATtiny using delays, and a second-pass implementation exploiting timer overflows resulting in a simpler program.  In this article I will explore the power saving modes on the ATtiny13 as an example of how to minimize the power consumption of your circuit.  If your ATTtiny13-, ATtiny80-, or even ATmega-based circuit relies on battery power you will be able to significantly improve the battery life by using the chips&#8217; power saving modes.</p>

<p>In this article we will be using the same circuit developed in the <a href="http://brownsofa.org/blog/archives/191">previous</a> <a href="http://brownsofa.org/blog/archives/215">posts</a>:</p>

<p><a href="http://brownsofa.org/blog/wp-content/uploads/2011/01/LED-Flasher-Circuit.png"><img src="http://brownsofa.org/blog/wp-content/uploads/2011/01/LED-Flasher-Circuit-300x152.png" alt="" /></a><a href="http://brownsofa.org/blog/wp-content/uploads/2011/01/board.jpg"><img src="http://brownsofa.org/blog/wp-content/uploads/2011/01/board-300x225.jpg" alt="" /></a></p>

<h2><!-- more -->Overview</h2>

<p>Looking at the first page of the <a href="http://www.atmel.com/dyn/resources/prod_documents/doc8126.pdf">datasheet</a> you see it lists &ldquo;Low Power Idle, ADC Noise Reduction, and Power-down Modes&rdquo;.  Also looking at the <a href="http://www.nongnu.org/avr-libc/user-manual/modules.html">modules list</a> in the avr-libc documentation there&rsquo;s an entry for &ldquo;<a href="http://www.nongnu.org/avr-libc/user-manual/group__avr__sleep.html">&lt;avr/sleep.h>: Power Management and Sleep Modes</a>&rdquo;.  Starting with example code from the latter, putting the device to sleep doesn&rsquo;t look very hard:</p>

<pre><code>#include &lt;avr/sleep.h&gt;

    ...
      set_sleep_mode(&lt;mode&gt;);
      sleep_mode();
</code></pre>

<p>Then immediately following is this note: &ldquo;[&hellip;] unless your purpose is to completely lock the CPU (until a  hardware reset), interrupts need to be enabled before going to sleep.&rdquo;</p>

<p>So here are my questions: What are the sleep modes and what do they do?  What interrupt vector(s) are available and how do I enable them?</p>

<p>In the datasheet, §7 covers the sleep modes.  Right at the top, Table 7-1 summarizes which clocks and oscillators are active, and how the device can be awaken from each of the three supported sleep modes.  Looking at §7.1.1-3, the lowest power consumption sleep mode looks like &ldquo;Power Down Mode&rdquo; (no surprise), and once in that state it can be awoken by an external interrupt (i.e. a level change on a pin) or through the Watchdog Timer.</p>

<p>Looking at §8.4, the Watchdog timer (WDT) is a separately clocked counter/timer system, capable of generating interrupts which we can use to bring the device out of the Power Down sleep mode.  §8.5.2 details the WDT&rsquo;s register, and in particular Table 8-2 lists how to alter the length of the WDT&rsquo;s time period.</p>

<h2>Implementation</h2>

<p>We&rsquo;ve sen that there&rsquo;s a way to put the device to sleep, and a way to periodically wake it up.  Last time our LED flasher toggled its LED state each time a timer-based interrupt was generated.  Let&rsquo;s do the same thing, except put the device to sleep once the LED state has been toggled.  Hopefully this will reduce the power consumption overall, but mainly during the &ldquo;off&rdquo; part of the cycle.</p>

<p>Our last implementation using Timer/Counter0 looked like this:</p>

<pre><code>#include &lt;avr/interrupt.h&gt;

volatile int timer_overflow_count = 0;

ISR(TIM0_OVF_vect) {
   if (++timer_overflow_count &gt; 5) {   // a timer overflow occurs 4.6 times per second
      // Toggle Port B pin 4 output state
      PORTB ^= 1&lt;&lt;PB4;
      timer_overflow_count = 0;
   }
}

int main(void) {
   // Set up Port B pin 4 mode to output
    DDRB = 1&lt;&lt;DDB4;

   // prescale timer to 1/1024th the clock rate
   TCCR0B |= (1&lt;&lt;CS02) | (1&lt;&lt;CS00);

   // enable timer overflow interrupt
   TIMSK0 |=1&lt;&lt;TOIE0;
   sei();

   while(1) {
      // let ISR handle the LED forever
   }
}
</code></pre>

<p>We need to adjust the timer setup and interrupt we&rsquo;re using, and add the power mode change.  Working on the timer part first, we remove all references to Timer0, and replace them with set up for the WDT.  Having read through §8.5.2 it&rsquo;s clear that operating the WDT is very similar to Timer/Counter0.  Setting the <code>WDTIE</code> bit enables WDT interrupts, and combinations of <code>WDP3</code>, <code>WDP2</code>, <code>WDP1</code>, and <code>WDP0</code> adjust the prescaling and thus the WDT&rsquo;s period.  Looking at Table 8-2, setting <code>WDP2</code> and <code>WDP0</code> gives a 0.5s timer period.</p>

<p>To wrap up replacing the older timer code, we also need to change the interrupt vector we&rsquo;re using.  The <a href="http://www.nongnu.org/avr-libc/user-manual/group__avr__interrupts.html">documentation for interrupt.h</a> shows that this is called <code>WDT_vect</code>.</p>

<p>Finally, because we can prescale the timer this low, we can also dispense with our old overflow counter.</p>

<pre><code>#include &lt;avr/interrupt.h&gt;

ISR(WDT_vect) {
   // Toggle Port B pin 4 output state
   PORTB ^= 1&lt;&lt;PB4;
}

int main(void) {
   // Set up Port B pin 4 mode to output
    DDRB = 1&lt;&lt;DDB4;

   // prescale timer to 0.5s
   WDTCR |= (1&lt;&lt;WDP2) | (1&lt;&lt;WDP0);

   // Enable watchdog timer interrupts
   WDTCR |= (1&lt;&lt;WDTIE);

   sei(); // Enable global interrupts 

   for (;;) {
      // Waiting for interrupt...
   }
}
</code></pre>

<p>If you set up the circuit and program this into the ATtiny13, the LED should flash on and off with a period of ~1 second, as you would expect.  It might be interesting top find out what kind of power savings the sleep modes might give us, so before we add the sleep code let&rsquo;s measure current drain right now.  To make measurements a little easier slow down the flash rate by setting the prescaler to 4 seconds &ndash; <code>WDTCR |= (1&lt;&lt;WDP3);</code> &ndash; then set your multimeter to measure current and put in the main power loop somewhere.  For me the most convenient way was to break the connection between VCC on the ISP breakout and pin 8 on the ATtiny, and insert the ammeter there.  I measured 50mA on the mark (whilst the LED was on), and 2.3mA on the space.</p>

<p>To put the device to sleep, the <a href="http://www.nongnu.org/avr-libc/user-manual/group__avr__sleep.html">documentation for sleep.h</a> states that</p>

<pre><code>set_sleep_mode(&lt;mode&gt;);
sleep_mode();
</code></pre>

<p>is all there is to it. But what parameter do we pass to <code>set_sleep_mode</code> to enable Power Down Mode?  Since it&rsquo;s not in this page of the documentation, if you take a look at the <a href="http://www.nongnu.org/avr-libc/user-manual/sleep_8h_source.html">code for the header file itself</a>, at line 253 there&rsquo;s a #define for <code>SLEEP_MODE_PWR_DOWN</code> that&rsquo;s applicable to ATtiny13s.</p>

<p>We have already set up the WDT to wake the device from sleep when it raises an interrupt, so as soon as the interrupt handler is complete it is safe to go back to sleep.  Working this in, our code now looks like:</p>

<pre><code>#include &lt;avr/interrupt.h&gt;
#include &lt;avr/sleep.h&gt;

ISR(WDT_vect) {
   // Toggle Port B pin 4 output state
   PORTB ^= 1&lt;&lt;PB4;
}

int main(void) {
   // Set up Port B pin 4 mode to output
    DDRB = 1&lt;&lt;DDB4;

   // temporarily prescale timer to 4s so we can measure current
   WDTCR |= (1&lt;&lt;WDP3); // (1&lt;&lt;WDP2) | (1&lt;&lt;WDP0);

   // Enable watchdog timer interrupts
   WDTCR |= (1&lt;&lt;WDTIE);

   sei(); // Enable global interrupts 

   // Use the Power Down sleep mode
   set_sleep_mode(SLEEP_MODE_PWR_DOWN);

   for (;;) {
      sleep_mode();   // go to sleep and wait for interrupt...
   }
}
</code></pre>

<p>Plugging in the ammeter again shows 47mA on the mark and 7µA on the space.  These readings (and the previous set) are definitely within range of the typical DC characteristics shown in Table 18-1 in the datasheet.  If you were using a CR1632 lithium coin cell rated at 125mAh, using the power down mode might increase battery life from 2.4h to 2.6h.  Ok, that&rsquo;s not fantastic but the huge majority of electron juice is used by the LED.  If your circuit was a little more complex and had longer periods of inactivity, using the power down saves you a lot of power.  If our LED were on for 1/10th of the time it were off, the battery duration change goes from an increase of 8% with the sleep code to an increase of <strong>55%</strong>, which seems well worth it to me.</p>

<h2>More Reading</h2>

<p>For more ways to reduce power consumption, read §7.4 in the datasheet.</p>

<p><a href="http://jumptuck.wordpress.com">Jumptuck&rsquo;s</a> <a href="http://jumptuck.wordpress.com/2008/11/13/led-menorah-powered-by-avr-tiny13/">LED Menorah</a> is a real-world example of using the sleep modes to reduce power consumption &ndash; in that case it&rsquo;s to reduce power whilst the device is &ldquo;off&rdquo;.</p>

<p>Go back to <a href="http://brownsofa.org/blog/archives/191">part 1</a> or <a href="http://brownsofa.org/blog/archives/215">part 2</a>.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[The Compleat ATtiny13 LED Flasher: Part 2 - Using Timer Interrupts]]></title>
    <link href="http://brownsofa.org/blog/2011/01/04/the-compleat-attiny13-led-flasher-part-2-using-timer-interrupts/"/>
    <updated>2011-01-04T23:27:48-07:00</updated>
    <id>http://brownsofa.org/blog/2011/01/04/the-compleat-attiny13-led-flasher-part-2-using-timer-interrupts</id>
    <content type="html"><![CDATA[<p><em>This is the second part of three in attempting to explain how to make the ATtiny13 flash a LED.</em></p>

<ul>
<li><p><em>Part 1: <a href="http://brownsofa.org/blog/archives/191">Setup, Hardware and A Basic Solution</a></em></p></li>
<li><p><em><strong>Part 2: Using timer interrupts</strong></em></p></li>
<li><p><em>Part 3: <a href="http://brownsofa.org/blog/archives/261">Low power mode</a></em></p></li>
</ul>


<p><em><del>Post-</del>Pre-script: If you find this post useful, happen to try out the code, or have any other views or criticisms, please leave a comment.  I&rsquo;d love to hear what you think.
&ndash; Ian</em></p>

<p>So last time around, we made a LED flash.  Of course there are other, more elegant ways to do it.  In this post I&rsquo;ll explore interrupts, and specifically the timer overflow interrupt.  For this I&rsquo;ll use the same circuit setup from the first article.  If you&rsquo;re reading this one independently, here&rsquo;s a circuit diagram:</p>

<p><a href="http://brownsofa.org/blog/wp-content/uploads/2011/01/LED-Flasher-Circuit.png"><img src="http://brownsofa.org/blog/wp-content/uploads/2011/01/LED-Flasher-Circuit-300x152.png" alt="" /></a></p>

<h2><!-- more -->Interrupts</h2>

<p>The structure of programs for these microcontrollers often takes a standard form:</p>

<pre><code>#include &lt;headers&gt;

int main() {
   set_up_routine();

   while (1) {
      do_something_interesting();
   }
   return 1;
}
</code></pre>

<p>So once the code&rsquo;s on the device, after power-up it enters <code>main()</code>, runs whatever setup you want to do, then begins running in an infinite loop doing whatever it is you want the tiny guy to do.</p>

<p>In this model, say you want to get input from devices, you must <em>poll</em> them &ndash; that is, every so often your program must go out of its way to figure out whether an input pin has changed from high to low, or some other measurement.  Now this can cause problems.   For example:</p>

<pre><code>#include &lt;headers&gt;

int isSwitchPressed();      // returns 1 if switch is currently pressed down, 0 otherwise

int main() {
   set_up_routine();

   while (1) {
      if (isSwitchPressed()) {
         do_something_that_takes_a_long_time();
      }
   }
   return 1;
}
</code></pre>

<p>Let&rsquo;s say that our interesting thing was to play a fancy little light sequence on a LED.  You press the switch, the LED does its thing (or whatever else is in <code>do_something_that_takes_a_long_time</code>), that function returns and again we&rsquo;re waiting for the switch to be pressed.  This is all well and good.  If the switch is not pressed, the function returns false, the <code>if</code>&rsquo;s body is not evaluated, the <code>while</code> loop ends and restarts, and the code tests whether the switch is pressed.</p>

<p>But here&rsquo;s the rub.  Consider:</p>

<pre><code>#include &lt;headers&gt;

int isSwitchPressed();      // returns 1 if switch is currently pressed down, 0 otherwise

int main() {
   set_up_routine();

   while (1) {
      if (isSwitchPressed()) {
         do_something_that_takes_a_long_time();
      } else {
         do_something_else_that_takes_a_long_time();
      }
   }
   return 1;
}
</code></pre>

<p>If the switch is not pressed, <code>do_something_else_that_takes_a_long_time()</code> is executed.  If you push the switch during the time this function is executing, nothing will happen.  The microcontroller will not register that the switch was pressed, and you lose that event happening.</p>

<p>So what if you want a button press during <code>do_something_else_that_takes_a_long_time()</code> to run the regular <code>do_something_that_takes_a_long_time()</code> code?  You could start testing the switch state in <code>do_something_else_that_takes_a_long_time</code>.  No, just kidding.  That would suck.</p>

<p>This is where <em>interrupts</em> come into play.  They do what you might expect them to do &ndash; they interrupt the normal code execution.  Interrupts can be triggered by different types of events.  In the example above you may recognize that a hardware-based interrupt might come to the rescue.  Interrupts can also be generated by the microcontroller&rsquo;s own internal systems, or by your code itself.  These are called <em>interrupt vectors</em>.  A list of the interrupt vectors for the ATtiny13 is listed in §9.1 in the <a href="http://www.atmel.com/dyn/resources/prod_documents/doc8126.pdf">ATtiny13 datasheet</a> (p. 45).</p>

<p>When an interrupt happens, your way to instruct the µc to do something is through an interrupt handler, aka interrupt service routine, aka ISR.  It looks just like a regular function, but you don&rsquo;t call it directly from your code; it gets executed whenever an interrupt occurs.  Once your ISR has completed execution, the program counter jumps back to right where it left of from in your <code>main()</code> loop (or wherever it was when the interrupt was raised) and carries on running.</p>

<p>More pseudocode:</p>

<pre><code>#include &lt;headers&gt;

ISR(interrupt_vector_caused_by_switch_press) {
   do_something_that_takes_a_long_time();
}

int main() {
   set_up_routine();

   while (1) {
      do_something_else_that_takes_a_long_time();
   }
   return 1;
}
</code></pre>

<p>So if the button is pressed, and interrupt is raised and our ISR is called.  No matter where the program counter is when you press the button, <code>do_something_that_takes_a_long_time()</code> will get called within a few clock cycles.  If you haven&rsquo;t pressed the button then all that gets executed is <code>do_something_else_that_takes_a_long_time()</code>.</p>

<p>OK, you get it, enough theory and pseudocode.  Moving on&hellip;</p>

<p><em>A word of warning: interrupts give you ways to do all kinds of weird things.  Check out <a href="http://www.societyofrobots.com/member_tutorials/node/207">this</a> and <a href="http://greatengineering.net/Embedded-System-Engineering/Implementation/Interrupt-Race-Conditions.html">this</a> for just a hint of the perils that await you!</em></p>

<h2>Implementing Interrupts on ATtiny13 with AVR Libc</h2>

<p>_There&rsquo;s more than one way to skin a cat.  My preferred method is using the <a href="http://www.nongnu.org/avr-libc/user-manual/index.html">AVR Libc</a> code, and the avr-gcc C compiler toolchain, and that&rsquo;s exclusively what I&rsquo;ll focus on. _</p>

<p>I&rsquo;m getting down to brass tacks and jumping around the <a href="http://www.atmel.com/dyn/resources/prod_documents/doc8126.pdf">datasheet</a> a bit here.</p>

<p>The ATtiny13 datasheet §9.1 lists the <em>Timer/Counter Overflow</em> interrupt vector.  Then reading §11.7.1, you learn that in its normal mode, the counter counts upwards, and once it gets to the &ldquo;top&rdquo; (there&rsquo;s only so many bits allocated to store the counter value) it resets back to zero and the <code>TOV0</code> bit is set.  §11.9.6 says that if you enable the Timer/Counter0 Overflow Interrupt by setting the <code>TOIE0</code> bit to 1 in the <code>TIMSK0</code> register and interrupts are enabled (&ldquo;the I-bit in the Status Register is set&rdquo;), whenever the <code>TOV0</code> bit is set, the interrupt will be raised.</p>

<p>The timer is what we&rsquo;re using to generate our interrupts.  It&rsquo;s an 8-bit register, incremented once per clock tick (unless prescaled &ndash; see later).  Since it&rsquo;s only an 8-bit register its maximum value is 255, therefore once every 256 clock cycles the timer reaches its maximum value and resets back to zero.  If we set up the device properly, when this occurs the Timer/Counter0 Overflow Interrupt will be generated, and we can write a ISR to respond to this interrupt, and flash our timer.</p>

<p>&ldquo;256 clock cycles?&rdquo; I hear you ask.  &#8221;That&rsquo;s not very long.&ldquo;  We could add a counter variable and toggle the LED once the counter reaches a certain number of overflows.  That might work.  The clock runs at around 9.6MHz by default (§6.2.2) and is shipped with the clock freqeuncy divided by 8 (§6.4.2), therefore the 8-bit timer register will overflow ~4688 times per second.  Using an 8-bit variable to count those would itself overflow 18 times per second, so we&rsquo;d need to use a 16-bit variable instead.  That gets us into the human timescale, but 65536/4688 gives us a maximum flash time of ~13 seconds.  It might work, but there&rsquo;s a yet more elegant way&hellip;</p>

<p>An alternative is to prescale the timer.  This has the effect of using 1 of every <em>n</em> clock ticks to increment the timer counter (§12.1).   You can choose from a number of slowdown factors, all of them are powers of two, and all are listed in the datasheet in §11.9.2, table 11-9.  The slowest rate we can make the timer increment is at 1/1024th the rate of the main system clock (by setting <code>CS02</code> and <code>CS00</code> bits to 1 in the <code>TCCR0B</code> register).</p>

<p>If prescaling by x1024, the timer register gets incremented at 1.2MHz/1024, i.e. ~1172 times per second, and thus overflows 4.6 times per second.  We could use an 8-bit variable to count the overflows and get a maximum of just under 56 seconds for that one little <code>uint</code>.  Sounds better to me.</p>

<p>Here&rsquo;s a little pseudocode to encapsulate this so far:</p>

<pre><code>ISR(timer_overflow_vector) {
   if (timer_overflow_count &gt; 5) {   // a timer overflow occurs 4.6 times per second
      toggle_led();
      reset_timer_overflow_count();
   }
}

main() {
   initialize_io_port();
   prescale_timer();
   enable_timer_overflow_interrupt();

   while(1) {
      // let ISR handle the LED forever
   }
}
</code></pre>

<p>Some of this is gravy, so let&rsquo;s fill those in with more realistic code:</p>

<pre><code>volatile int timer_overflow_count = 0;

ISR(timer_overflow_vector) {      // TODO
   if (++timer_overflow_count &gt; 5) {   // a timer overflow occurs 4.6 times per second
      // Toggle Port B pin 4 output state
      PORTB ^= 1&lt;&lt;PB4;
      timer_overflow_count = 0;
   }
}

int main(void) {
   // Set up Port B pin 4 mode to output
    DDRB = 1&lt;&lt;DDB4;

   prescale_timer();   // TODO
   enable_timer_overflow_interrupt();   // TODO

   while(1) {
      // let ISR handle the LED forever
   }
}
</code></pre>

<p>A little insight from <a href="http://www.nongnu.org/avr-libc/user-manual/group__avr__interrupts.html">avr-libc</a> helps with the interrupts.  By including <code>avr/interrupt.h</code>, the ATtiny13&rsquo;s Timer/Counter0 Overflow is exposed through the <code>TIM0_OVF_vect</code> interrupt vector.  Thus:</p>

<pre><code>#include &lt;avr/interrupt.h&gt;

volatile int timer_overflow_count = 0;

ISR(TIM0_OVF_vect) {
   if (++timer_overflow_count &gt; 5) {   // a timer overflow occurs 4.6 times per second
      // Toggle Port B pin 4 output state
      PORTB ^= 1&lt;&lt;PB4;
      timer_overflow_count = 0;
   }
}

int main(void) {
   // Set up Port B pin 4 mode to output
    DDRB = 1&lt;&lt;DDB4;

   prescale_timer();   // TODO
   enable_timer_overflow_interrupt();   // TODO

   while(1) {
      // let ISR handle the LED forever
   }
}
</code></pre>

<p>Prescaling the timer is straightforward and straight from the datasheet: <code>TCCR0B |= (1&lt;&lt;CS02) | (1&lt;&lt;CS00)</code>.  Setting up the timer overflow interrupt was also defined in the datasheet: <code>TIMSK0 |=1&lt;&lt;TOIE0</code>, and the <code>sei</code> instruction has a helpful <code>sei()</code> macro defined in <code>avr/interrupt.h</code>.  Consolidating for our final code:</p>

<pre><code>#include &lt;avr/interrupt.h&gt;

volatile int timer_overflow_count = 0;

ISR(TIM0_OVF_vect) {
   if (++timer_overflow_count &gt; 5) {   // a timer overflow occurs 4.6 times per second
      // Toggle Port B pin 4 output state
      PORTB ^= 1&lt;&lt;PB4;
      timer_overflow_count = 0;
   }
}

int main(void) {
   // Set up Port B pin 4 mode to output
    DDRB = 1&lt;&lt;DDB4;

   // prescale timer to 1/1024th the clock rate
   TCCR0B |= (1&lt;&lt;CS02) | (1&lt;&lt;CS00);

   // enable timer overflow interrupt
   TIMSK0 |=1&lt;&lt;TOIE0;
   sei();

   while(1) {
      // let ISR handle the LED forever
   }
}
</code></pre>

<p><strong>References/Acknowledgements: </strong>I have to point out the complete awesomeness and of Dean&#8217;s <a href="http://www.avrfreaks.net/index.php?name=PNphpBB2&amp;file=viewtopic&amp;t=89843&amp;start=0&amp;postdays=0&amp;postorder=asc&amp;highlight=">Newbie&rsquo;s Guide to AVR Interrupts</a> on <a href="http://www.avrfreaks.net/">http://www.avrfreaks.net</a>.  It&rsquo;s awesome.   If you want a great explanation of interrupts, go there and read his tut.</p>

<p>Continue reading <a href="http://brownsofa.org/blog/archives/261">part 3</a> to see how to use these techniques plus sleep modes to save battery power, or review the <a href="http://brownsofa.org/blog/archives/191">previous section</a>.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[The Compleat ATtiny13 LED Flasher: Part 1 - Setup, Hardware and A Basic Solution]]></title>
    <link href="http://brownsofa.org/blog/2011/01/01/the-compleat-attiny13-led-flasher/"/>
    <updated>2011-01-01T22:17:17-07:00</updated>
    <id>http://brownsofa.org/blog/2011/01/01/the-compleat-attiny13-led-flasher</id>
    <content type="html"><![CDATA[<p><em>This is the first part of three in attempting to explain how to make the ATtiny13 flash a LED.</em></p>

<ul>
<li><p><em><strong>Part 1: Setup, Hardware and A  Basic Solution</strong></em></p></li>
<li><p><em>Part 2: <a href="http://brownsofa.org/blog/archives/215">Using Timer Interrupts</a></em></p></li>
<li><p><em>Part 3: <a href="http://brownsofa.org/blog/archives/261">Low Power Mode</a></em></p></li>
</ul>


<p>If you&rsquo;re used to the user-friendliness of Arduino, getting started with bare bones AVRs can be hard work.  I&rsquo;d like to try to go slowly through the early steps and point out some of the information sources I used.</p>

<p><a href="http://brownsofa.org/blog/wp-content/uploads/2011/01/board.jpg"><img src="http://brownsofa.org/blog/wp-content/uploads/2011/01/board-150x150.jpg" alt="" /></a>First, start at the end: here&rsquo;s the final circuit.  It has an ATtiny13, an LED and current-limiting resistor, a few wires, the programmer interface, and that&rsquo;s about it.  All it does is flash the LED on and off (very much like the classic 555 timer astable multivibrator but with the advantage of no passive components required).  That&rsquo;s it.  Not much to it.</p>

<p><a href="http://brownsofa.org/blog/wp-content/uploads/2011/01/photo.jpg"><img src="http://brownsofa.org/blog/wp-content/uploads/2011/01/photo-150x150.jpg" alt="" /></a>Also, here&rsquo;s a quick sketch of a circuit diagram too &ndash; the inputs all come directly from the ISP interface from the programmer.</p>

<p>Ok, that&rsquo;s the end result.  Next: how to get there:</p>

<ol>
<li><p> Prerequisites (hardware and software)</p></li>
<li><p> Build the circuit</p></li>
<li><p> Write code</p></li>
<li><p> Upload to microprocessor</p></li>
</ol>


<h2><!-- more --></h2>

<p><strong>Prerequisites</strong></p>

<p>You need a programmer (e.g. <a href="http://www.sparkfun.com/products/9231">Pocket Programmer</a>, Adafruit&rsquo;s <a href="http://www.adafruit.com/index.php?main_page=product_info&amp;products_id=46">USBtinyISP</a>, any number <a href="http://www.pololu.com/catalog/product/1300">of</a> <a href="http://hackaday.com/2010/05/15/minimalist-avr-programmer-is-just-fab/">others</a>, or even <a href="http://electronics.stackexchange.com/questions/33/arduino-as-avr-programmer">use</a> your <a href="http://hackaday.com/2009/07/15/avr-isp-programming-via-arduino/">arduino</a>),  a way to interface your programmer to your computer (a USB cable would be normal), and a way to interface your programmer to the ATtiny (ISP headers are normal, and here&rsquo;s a <a href="http://electronics.stackexchange.com/questions/33/arduino-as-avr-programmer/71#71">picture of the pinout </a>of the 6-pin header).</p>

<p>Software-wise, there are also myriad choices.  There are different solutions for <a href="http://www.google.com/search?q=program+avr+with+windows">Windows</a>, <a href="http://www.google.com/search?q=program+avr+with+mac">Mac </a>and <a href="http://www.google.com/search?q=program+avr+with+linux">Linux</a>.  I&rsquo;ve only tried a couple of Windows options to date.</p>

<p>Since there are so many options, I&rsquo;d recommend finding a set of hardware and software that matches your existing equipment and budget that has a decent amount of documentation for troubleshooting.  If you can&rsquo;t find much out about how to get programmer X working on your computer, try another programmer.</p>

<p>There are more detailed instructions about my tool chain for compiling and programming the chip in the <a href="http://brownsofa.org/blog/archives/50">dice post</a>.  I&rsquo;m using a <a href="http://www.sparkfun.com/products/9231">Pocket Programmer</a>, and <a href="http://winavr.sourceforge.net/">WinAVR</a>.</p>

<p><strong>Build</strong>
Plug the microprocessor into your breadboard.  There&rsquo;s a notch or a dot at one end of the package to indicate the top, or the position of pin 1 (pointed to in the photo).  Pay attention to which way round the chip is!  The rest of the pins are numbered counter-clockwise from pin 1.</p>

<p><a href="http://brownsofa.org/blog/wp-content/uploads/2011/01/1.jpg"><img src="http://brownsofa.org/blog/wp-content/uploads/2011/01/1-150x150.jpg" alt="" /></a></p>

<p>If you have a nice <a href="http://www.sparkfun.com/products/8508">breakout board</a> for your ISP connector, plug it into the breadboard, and start working from that.  Otherwise, refer to the <a href="http://electronics.stackexchange.com/questions/33/arduino-as-avr-programmer/71#71">pinout </a>for the ISP and plug wires directly into the socket.</p>

<p><a href="http://brownsofa.org/blog/wp-content/uploads/2011/01/2.jpg"><img src="http://brownsofa.org/blog/wp-content/uploads/2011/01/2-150x150.jpg" alt="" /></a></p>

<p>Connect each of the signals from the programmer to your ATtiny &ndash; each of MISO, MOSI, SCK, GND, VCC and RESET.  Look at the <a href="http://www.atmel.com/dyn/resources/prod_documents/doc8126.pdf">datasheet for the ATtiny13</a>to see the pinout  (page 2).</p>

<p>(I have a printout of tinkerlog.com&#8217;s <a href="http://tinkerlog.com/2009/06/18/microcontroller-cheat-sheet/">microcontroller cheat sheet</a> on my desk.  It has pinouts of most common ATtiny and ATmega chips, and ISP headers, and I&rsquo;m constantly referring to it.)</p>

<p><a href="http://brownsofa.org/blog/wp-content/uploads/2011/01/3.jpg"><img src="http://brownsofa.org/blog/wp-content/uploads/2011/01/3-150x150.jpg" alt="" /></a><a href="http://brownsofa.org/blog/wp-content/uploads/2011/01/4.jpg"><img src="http://brownsofa.org/blog/wp-content/uploads/2011/01/4-150x150.jpg" alt="" /></a><em><a href="http://brownsofa.org/blog/wp-content/uploads/2011/01/5.jpg"><img src="http://brownsofa.org/blog/wp-content/uploads/2011/01/5-150x150.jpg" alt="" /></a></em></p>

<p>I want to source current for the LED from the ATtiny, and sink it to ground, so connect a supply line on the edge of the breadboard to GND from the ISP.</p>

<p><a href="http://brownsofa.org/blog/wp-content/uploads/2011/01/6.jpg"><img src="http://brownsofa.org/blog/wp-content/uploads/2011/01/6-150x150.jpg" alt="" /></a></p>

<p>Connect the long lead of the LED to pin 3 of the ATtiny.   Connect the short pin to an empty row.  Into that row, connect the resistor (100 or 200 ohms should be fine) and then finally connect the other leg of the resistor to the ground channel.</p>

<p><a href="http://brownsofa.org/blog/wp-content/uploads/2011/01/7.jpg"><img src="http://brownsofa.org/blog/wp-content/uploads/2011/01/7-150x150.jpg" alt="" /></a></p>

<p><strong>Write the code</strong></p>

<p>Paste this into your code editor:</p>

<pre><code>/*
 * ATtiny13 LED Flasher
 * File: main.c
 */

#include &lt;stdlib.h&gt;
#include &lt;util/delay.h&gt;

int main(void)
{
    const int msecsDelayPost = 100;

    // Set up Port B pin 4 mode to output
    DDRB = 1&lt;&lt;DDB4;

    // Set up Port B data to be all low
    PORTB = 0;  

    while (1) {
        // Toggle Port B pin 4 output state
        PORTB ^= 1&lt;&lt;PB4;

        // Pause a little while
        _delay_ms (msecsDelayPost);
    }

    return 0;
}
</code></pre>

<p>Simple enough.  Save the file as main.c, generate or customize a makefile, and at a command prompt type <code>make all</code>.  You should see something like the following:</p>

<pre><code>D:\Projects\AVR&gt;make all

-------- begin --------
avr-gcc (WinAVR 20100110) 4.3.3
Copyright (C) 2008 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

Size before:
AVR Memory Usage
----------------
Device: attiny13

Program:      64 bytes (6.3% Full)
(.text + .data + .bootloader)

Data:          0 bytes (0.0% Full)
(.data + .bss + .noinit)

Compiling C: main.c
avr-gcc -c -mmcu=attiny13 -I. -gdwarf-2 -DF_CPU=1200000UL -Os -funsigned-char -f
unsigned-bitfields -fpack-struct -fshort-enums -Wall -Wstrict-prototypes -Wa,-ad
hlns=./main.lst  -std=gnu99 -MMD -MP -MF .dep/main.o.d main.c -o main.o

Linking: main.elf
avr-gcc -mmcu=attiny13 -I. -gdwarf-2 -DF_CPU=1200000UL -Os -funsigned-char -funs
igned-bitfields -fpack-struct -fshort-enums -Wall -Wstrict-prototypes -Wa,-adhln
s=main.o  -std=gnu99 -MMD -MP -MF .dep/main.elf.d main.o --output main.elf -Wl,-
Map=main.map,--cref     -lm

Creating load file for Flash: main.hex
avr-objcopy -O ihex -R .eeprom -R .fuse -R .lock -R .signature main.elf main.hex

Creating load file for EEPROM: main.eep
avr-objcopy -j .eeprom --set-section-flags=.eeprom="alloc,load" \
        --change-section-lma .eeprom=0 --no-change-warnings -O ihex main.elf mai
n.eep || exit 0

Creating Extended Listing: main.lss
avr-objdump -h -S -z main.elf &gt; main.lss

Creating Symbol Table: main.sym
avr-nm -n main.elf &gt; main.sym

Size after:
AVR Memory Usage
----------------
Device: attiny13

Program:      64 bytes (6.3% Full)
(.text + .data + .bootloader)

Data:          0 bytes (0.0% Full)
(.data + .bss + .noinit)

-------- end --------

D:\Projects\AVR&gt;
</code></pre>

<p><strong>Upload to microprocessor</strong></p>

<p>Now the easy bit: plug the programmer into your computer, and type <code>make program</code>at the command prompt.  With any luck, you will see something like</p>

<pre><code>D:\Projects\AVR&gt;make program
avrdude -p attiny13 -P usb     -c usbtiny    -U flash:w:main.hex

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.34s

avrdude: Device signature = 0x1e9007
avrdude: NOTE: FLASH memory has been specified, an erase cycle will be performed

         To disable this feature, specify the -D option.
avrdude: erasing chip
avrdude: reading input file "main.hex"
avrdude: input file main.hex auto detected as Intel Hex
avrdude: writing flash (64 bytes):

Writing | ################################################## | 100% 0.27s

avrdude: 64 bytes of flash written
avrdude: verifying flash memory against main.hex:
avrdude: load data flash data from input file main.hex:
avrdude: input file main.hex auto detected as Intel Hex
avrdude: input file main.hex contains 64 bytes
avrdude: reading on-chip flash data:

Reading | ################################################## | 100% 0.05s

avrdude: verifying ...
avrdude: 64 bytes of flash verified

avrdude: safemode: Fuses OK

avrdude done.  Thank you.

D:\Projects\AVR&gt;
</code></pre>

<p>&hellip;and the LED should start flashing!</p>

<p>Continue reading <a href="http://brownsofa.org/blog/archives/215">part 2</a> to see how to achieve the same results by using timer interrupts.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Arduino Game Of Life on 8x8 LED Matrix]]></title>
    <link href="http://brownsofa.org/blog/2010/12/30/arduino-8x8-game-of-life/"/>
    <updated>2010-12-30T14:48:20-07:00</updated>
    <id>http://brownsofa.org/blog/2010/12/30/arduino-8x8-game-of-life</id>
    <content type="html"><![CDATA[<p>I was messing around with some Christmas toys and threw together a <a href="http://en.wikipedia.org/wiki/Conway's_Game_of_Life">Conway&rsquo;s Game Of Life</a> implementation together on my Arduino.  I just love how quick it is to get things up and running on this platform.  It took me longer to solder a platform for the LED matrix to raise it up off the breadboard so the wires would all fit than the whole rest of the project.</p>

<p>Here&rsquo;s a <a href="http://brownsofa.org/blog/wp-content/uploads/2010/12/IMG_0965.mp4">video of Arduino Game Of Life</a> running.</p>

<p>Anyway, more pictures and full source code are below.  The code has a couple of conditionally compiled options, one for storing rand seeds to EEPROM.  With the randomization turned on, every so often I&rsquo;d see a &ldquo;game&rdquo; that progressed really nicely.  I wanted to be able to go back and watch the same game again.</p>

<p><a href="http://brownsofa.org/blog/wp-content/uploads/2010/12/IMG_0956.jpg"><img src="http://brownsofa.org/blog/wp-content/uploads/2010/12/IMG_0956-150x150.jpg" alt="" /></a> <a href="http://brownsofa.org/blog/wp-content/uploads/2010/12/IMG_0964.jpg"><img src="http://brownsofa.org/blog/wp-content/uploads/2010/12/IMG_0964-150x150.jpg" alt="" /></a></p>

<h2><!-- more --></h2>

<p>The LED matrix conveniently has a non-standard pin spacing (between the rows of pins that is), and is as wide as the full working area on a solderless breadboard.  I quickly knocked up a breakout board for it, mounting some header pins on the bottom, and the matrix on the top.  This way it plugs directly into the breadboard, leaving clearance for the wires below.</p>

<p><a href="http://brownsofa.org/blog/wp-content/uploads/2010/12/IMG_0950.jpg"><img src="http://brownsofa.org/blog/wp-content/uploads/2010/12/IMG_0950-150x150.jpg" alt="" /></a> <a href="http://brownsofa.org/blog/wp-content/uploads/2010/12/IMG_0951.jpg"><img src="http://brownsofa.org/blog/wp-content/uploads/2010/12/IMG_0951-150x150.jpg" alt="" /></a> <a href="http://brownsofa.org/blog/wp-content/uploads/2010/12/IMG_0952.jpg"><img src="http://brownsofa.org/blog/wp-content/uploads/2010/12/IMG_0952-150x150.jpg" alt="" /></a> <a href="http://brownsofa.org/blog/wp-content/uploads/2010/12/IMG_0955.jpg"><img src="http://brownsofa.org/blog/wp-content/uploads/2010/12/IMG_0955-150x150.jpg" alt="" /></a></p>

<p><strong>Source code:</strong></p>

<pre><code>#include &lt;EEPROM.h&gt;

/*
GAME OF LIFE
For an 8x8 LED matrix

Connect digital IO pins 2-13 and analog pins 0-3 to LED matrix (through current limiting resistors)
Analog pin 4 (see RANDOMIZER_ANALOG_PIN) is used to select the randomization mode.
  - connect to 5V to randomize and generate a new rand seed
  - connect to 3.3V to use the last randomized set (USE_EEPROM must be #defined)
  - connect to 0V to use the hard coded starting state
Analog pin 5 (see UNCONNECTED_ANALOG_PIN) is left unconnected and used to add a bit of true randomness to seed the RNG
 */

const int NUMROWS = 8;
const int NUMCOLS = 8;
const int MICROS = 100;

const int EEPROM_ADDRESS_1 = 34;
const int EEPROM_ADDRESS_2 = 35;

/**
 * The "rows" in my LED matrix (http://www.sparkfun.com/products/681) are the ground connections.
 * They need to either be pulled low to enable the row, or be set to high impedance (input) mode.
 */
const byte rows[NUMROWS] = { 15, 7, 6, 5, 2, 3, 4, 14 };

/**
 * I'm using only one of the colors in the LED matrix.
 */
const byte cols[NUMCOLS] = { 17, 13, 12, 11, 8, 9, 10, 16 };

const int RANDOMIZER_ANALOG_PIN = 4;
const int UNCONNECTED_ANALOG_PIN = 5;

/**
 * Conditional compilation directives
 */
//#define USE_EEPROM 1                // uncomment this line to enable eeprom storage
//#define SHOW_STARTUP_SEQUENCE 1     // uncomment this line to enable the startup sequence

boolean gameBoard[NUMROWS][NUMCOLS] = {
  { 0, 0, 0, 0, 0, 0, 0, 0 },
  { 0, 0, 1, 1, 0, 0, 0, 0 },
  { 0, 1, 1, 0, 0, 0, 0, 0 },
  { 0, 0, 1, 0, 0, 0, 0, 0 },
  { 0, 0, 0, 0, 0, 0, 0, 0 },
  { 0, 0, 0, 0, 0, 0, 0, 0 },
  { 0, 0, 0, 0, 0, 0, 0, 0 },
  { 0, 0, 0, 0, 0, 0, 0, 0 }
};

boolean newGameBoard[NUMROWS][NUMCOLS] = {
  { 0, 0, 0, 0, 0, 0, 0, 0 },
  { 0, 0, 0, 0, 0, 0, 0, 0 },
  { 0, 0, 0, 0, 0, 0, 0, 0 },
  { 0, 0, 0, 0, 0, 0, 0, 0 },
  { 0, 0, 0, 0, 0, 0, 0, 0 },
  { 0, 0, 0, 0, 0, 0, 0, 0 },
  { 0, 0, 0, 0, 0, 0, 0, 0 },
  { 0, 0, 0, 0, 0, 0, 0, 0 },
};

/////////////////////////////////

void setup() {
  Serial.begin(9600);
  Serial.println("\nBegin setup()");

#ifdef USE_EEPROM
  Serial.println("EEPROM code enabled");
#else
  Serial.println("EEPROM code disabled");
#endif // defined USE_EEPROM

  allOff();
  startupSequence();
  setUpInitialBoard();
  Serial.println("End setup()\n");
}

void loop() {
  long time = millis();

  // Display the current game board for approx. 250ms
  do {
    displayGameBoard();
  }
  while (millis() &lt; time + 250);

  // Calculate the next iteration
  calculateNewGameBoard();
  swapGameBoards();
}

///////////////////////////////////

/**
 * Turns off all LEDs, and initializes the pin modes correctly.
 */
void allOff() {
  for (int i=0; i&lt;NUMROWS; i++) {
    pinMode(rows[i], INPUT);
  }
  for (int i=0; i&lt;NUMCOLS; i++) {
    pinMode(cols[i], OUTPUT);
    digitalWrite(cols[i], LOW);
  }
}

/**
 * Does some randomizing of the initial board state.
 */
void setUpInitialBoard() {
  // Generate a new seed for the RNG
  int seed = analogRead(UNCONNECTED_ANALOG_PIN);

  // Look at how the randomizer pin is connected.
  // If it's pulled high, then generate and store a new seed.
  // If it's middle (3.3v) then read the seed from EEPROM (if that code is enabled with USE_EEPROM)
  pinMode(RANDOMIZER_ANALOG_PIN, INPUT);
  int randomizerPinValue = analogRead(RANDOMIZER_ANALOG_PIN);
  if (randomizerPinValue &gt; 900) {  // connected to +5V
#ifdef USE_EEPROM
    // Generate and store a new random seed
    Serial.println("Generating new randseed...");
    Serial.print("Storing ");
    Serial.print(seed, DEC);
    EEPROM.write(EEPROM_ADDRESS_1, lowByte(seed));
    EEPROM.write(EEPROM_ADDRESS_2, highByte(seed));
    Serial.print("... done\n");
#endif // defined USE_EEPROM

    Serial.print("Seeding RNG with ");
    Serial.print(seed, DEC);
    Serial.print("\n");

    randomSeed(seed);
    perturbInitialGameBoard();
  } else if (randomizerPinValue &gt; 300) {  // connected to +3.3V
    // Retrieve random seed from EEPROM
#ifdef USE_EEPROM
    Serial.println("Retrieving randseed...");
    int hi = EEPROM.read(EEPROM_ADDRESS_2);
    int lo = EEPROM.read(EEPROM_ADDRESS_1);
    seed = (hi &lt;&lt; 8 ) | lo;
    Serial.print("Read ");
    Serial.print(seed, DEC);
    Serial.print("\n");
#endif // defined USE_EEPROM

    Serial.print("Seeding RNG with ");
    Serial.print(seed, DEC);
    Serial.print("\n");

    randomSeed(seed);
    perturbInitialGameBoard();
  } else {
    Serial.println("Using basic board.");
  }
}

/**
 * Does a nice little animation to aid visual checks that all LEDs are correctly connected and operating.
 * Lights every LED in each row, going back and forth across the rows, from top to bottom.
 */
void startupSequence() {
#ifdef SHOW_STARTUP_SEQUENCE
  for (int row=0; row&lt;NUMROWS; row++) {
    if (row%2 == 0) {
      for (int col=0; col&lt;NUMCOLS; col++) {
        setLedOn(row, col);
        delay(25);
        setLedOff(row, col);
      }
    } else {
      for (int col=NUMCOLS-1; col&gt;=0; col--) {
        setLedOn(row, col);
        delay(25);
        setLedOff(row, col);
      }
    }
  }
#endif // defined SHOW_STARTUP_SEQUENCE
}

/**
 * Makes a small number of random changes to the game board
 */
void perturbInitialGameBoard() {
  int numChanges = random(20,100);
  for (int i=0; i&lt;numChanges; i++) {
    int row = random(0, NUMROWS);
    int col = random(0, NUMCOLS);
    gameBoard[row][col] = !gameBoard[row][col]; // toggle the led in this position
  }
}

/**
 * Loops over all game board positions, and briefly turns on any LEDs for "on" positions.
 */
void displayGameBoard() {
  for (byte row=0; row&lt;NUMROWS; row++) {
    for (byte col=0; col&lt;NUMCOLS; col++) {
      if (gameBoard[row][col]) {
        pulseLed(row, col);
      }
    }
  }
}

/**
 * Turns on the specified LED for a v. short period of time
 */
void pulseLed(byte row, byte col) {
  setLedOn(row, col);
  delayMicroseconds(MICROS);
  setLedOff(row, col);
}

/**
 * Counts the number of active cells surrounding the specified cell.
 * Cells outside the board are considered "off"
 * Returns a number in the range of 0 &lt;= n &lt; 9
 */
byte countNeighbors(byte row, byte col) {
  byte count = 0;
  for (char rowDelta=-1; rowDelta&lt;=1; rowDelta++) {
    for (char colDelta=-1; colDelta&lt;=1; colDelta++) {
      // skip the center cell
      if (!(colDelta == 0 &amp;&amp; rowDelta == 0)) {
        if (isCellAlive(rowDelta+row, colDelta+col)) {
          count++;
        }
      }
    }
  }
  return count;
}

/**
 * Returns whether or not the specified cell is on.
 * If the cell specified is outside the game board, returns false.
 */
boolean isCellAlive(char row, char col) {
  if (row &lt; 0 || col &lt; 0 || row &gt;= NUMROWS || col &gt;= NUMCOLS) {
    return false;
  }

  return (gameBoard[row][col] == 1);
}

/**
 * Encodes the core rules of Conway's Game Of Life, and generates the next iteration of the board.
 * Rules taken from wikipedia.
 */
void calculateNewGameBoard() {
  for (byte row=0; row&lt;NUMROWS; row++) {
    for (byte col=0; col&lt;NUMCOLS; col++) {
      byte numNeighbors = countNeighbors(row, col);

      if (gameBoard[row][col] &amp;&amp; numNeighbors &lt; 2) {
        // Any live cell with fewer than two live neighbours dies, as if caused by under-population.
        newGameBoard[row][col] = false;
      } else if (gameBoard[row][col] &amp;&amp; (numNeighbors == 2 || numNeighbors == 3)) {
        // Any live cell with two or three live neighbours lives on to the next generation.
        newGameBoard[row][col] = true;
      } else if (gameBoard[row][col] &amp;&amp; numNeighbors &gt; 3) {
        // Any live cell with more than three live neighbours dies, as if by overcrowding.
        newGameBoard[row][col] = false;
      } else if (!gameBoard[row][col] &amp;&amp; numNeighbors == 3) {
        // Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction.
        newGameBoard[row][col] = true;
      } else {
        // All other cells will remain off
        newGameBoard[row][col] = false;
      }
    }
  }
}

/**
 * Copies the data from the new game board into the current game board array
 */
void swapGameBoards() {
  for (byte row=0; row&lt;NUMROWS; row++) {
    for (byte col=0; col&lt;NUMCOLS; col++) {
      gameBoard[row][col] = newGameBoard[row][col];
    }
  }
}

void setLed(byte row, byte col, boolean level) {
  if (level == HIGH) {
    pinMode(rows[row], OUTPUT);
    digitalWrite(cols[col], HIGH);
  }
  else if (level == LOW) {
    pinMode(rows[row], INPUT);
    digitalWrite(cols[col], LOW);
  }
}

void setLedOn(byte row, byte col) {
  setLed(row, col, HIGH);
}
void setLedOff(byte row, byte col) {
  setLed(row, col, LOW);
}
</code></pre>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[How To Selectively Delete Photos Off iPhone?]]></title>
    <link href="http://brownsofa.org/blog/2010/07/28/how-to-selectively-delete-photos-off-iphone/"/>
    <updated>2010-07-28T20:44:14-06:00</updated>
    <id>http://brownsofa.org/blog/2010/07/28/how-to-selectively-delete-photos-off-iphone</id>
    <content type="html"><![CDATA[<p>To spread some knowledge I found really helpful, <a href="http://discussions.info.apple.com/message.jspa?messageID=7569336#7569336">this thread</a> contains the answer to the question.  The iPhoto app will let you delete all downloaded images, but I wanted to delete a select range (some big videos in particular).  The short version: quit iPhoto, launch Image Capture, click <em>Download Some&hellip;</em>, select photos to delete, and delete from the edit menu.  Done.  Thanks FloBro!</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[PHP 5.3 + XDebug + NetBeans + Mac OSX Leopard]]></title>
    <link href="http://brownsofa.org/blog/2010/07/24/php-5-3-xdebug-netbeans-mac-osx-leopard/"/>
    <updated>2010-07-24T10:50:15-06:00</updated>
    <id>http://brownsofa.org/blog/2010/07/24/php-5-3-xdebug-netbeans-mac-osx-leopard</id>
    <content type="html"><![CDATA[<p>&hellip; or how I got all the toys to play nice together &hellip;</p>

<p>If you&rsquo;re working in PHP and are <code>echo</code>ing out your variables to see what&rsquo;s going on, please stop that right now.  Graphical Debuggers are here (in fact, they&rsquo;ve been here for some decades) and now they work really nicely with free IDE tools.  Here I&rsquo;ll outline how to get graphical PHP debugging with NetBeans working.  The overview is: (1) install PHP 5.3, (2) install Xdebug, (3) install NetBeans, (4) configure publishing path, (5) test Xdebug.</p>

<p>There&rsquo;s a lot more to go through.  Click through to see all the steps&hellip;</p>

<!-- more -->


<p><strong>PHP</strong></p>

<p>OSX Leopard came installed with PHP 5.2.  You can check by opening up terminal and typing <code>php -v</code>, or looking at the output of <code>phpinfo()</code>.  I want the latest version of PHP which is currently 5.3.</p>

<p>First, you need to stop the old version of PHP from running.  Edit httpd.conf with your favorite text editor.  My choice: from the terminal, run <code>sudo /etc/apache2/httpd.conf</code>.  The sudo is necessary since it&rsquo;s a protected file.  (You may find you need to <a href="http://www.google.com/search?q=osx+sudo+password">set an account password</a>).  Find the line beginning with &ldquo;LoadModule php5_module&rdquo; and comment it out:</p>

<pre><code>&lt;span style="font-family: monospace;"&gt;#LoadModule php5_module  libexec/apache2/libphp5.so&lt;/span&gt;
</code></pre>

<p>Then, restart apache: <code>sudo apachectl restart</code></p>

<p>Next, install the later version of PHP.  Go to <a href="http://www.entropy.ch/software/macosx/php/">entropy.ch</a> and download <a href="http://www2.entropy.ch/download/Entropy%20PHP%205.3.0-3.pkg">Entropy PHP 5.3.0-3.pkg</a>.  Open the package and follow the instructions.  After this has completed, apache will be running with PHP 5.3.</p>

<p>If you care about this, your command line php interpreter will still be running an older version of PHP.  Verify by comparing the output of <code>php -i</code> on the command line with <code>phpinfo()</code> from the web server.  I found my 5.3 version of the CLI PHP at <code>/usr/local/php5/bin/php</code>. Also of note: some day you&rsquo;ll need to know with total certainty which php.ini file is being loaded.  You&rsquo;ll see this from these outputs.</p>

<p><strong>XDebug</strong></p>

<p>Roll up your sleeves. It&rsquo;s time to get a bit hacky.</p>

<p>There&rsquo;s a few ways to install xdebug &ndash; build from source, install with PEAR, or find a precompiled binary to install.  I pick the latter.  The fine folks at <a href="http://code.activestate.com/komodo/remotedebugging/">ActiveState</a> have a package with precompiled xdebug modules for lots of PHP versions.  <a href="http://downloads.activestate.com/Komodo/releases/6.0.0b2/remotedebugging/Komodo-PHPRemoteDebugging-6.0.0-beta2-53747-macosx.tar.gz">Here&rsquo;s</a> the download I grabbed.  Extract the files and copy the <code>&lt;komodo_files&gt;/5.3/xdebug.so</code> into <code>/usr/local/php5/lib/php/extensions/no-debug-non-zts-20090626</code>.  If you&rsquo;re in the terminal, cd to the extracted 5.3 folder and type in <code>sudo cp xdebug.so /usr/local/php5/lib/php/extensions/no-debug-non-zts-20090626</code>.</p>

<p>At the end of your php.ini file, add the following lines to enable and configure xdebug:</p>

<pre><code>[xdebug]
zend_extension="/usr/local/php5/lib/php/extensions/no-debug-non-zts-20090626/xdebug.so"
xdebug.remote_enable=on
xdebug.remote_handler=dbgp
xdebug.remote_mode=req
xdebug.remote_host=localhost
xdebug.remote_port=9000
xdebug.idekey="netbeans-xdebug"
xdebug.remote_log="/var/log/apache2/xdebug_remote.log"
</code></pre>

<p>Restart apache again.  Look at the output from phpinfo and at the end of the first block you should now see &ldquo;<em>with Xdebug v2.1.0beta3, Copyright &copy; 2002-2010, by Derick Rethans</em>&rdquo; in the copyright.  If you see this, Xdebug is installed.  If you can&rsquo;t see this, something didn&rsquo;t work.  Make sure you edited the correct php.ini file, and make sure you restarted apache.</p>

<p><strong>NetBeans</strong></p>

<p>Go to the <a href="http://netbeans.org/downloads/index.html">NetBeans download page</a>, and pick the most relevant version.  If you&rsquo;re doing PHP programming, start out with the PHP version.  Download and install like any other app.</p>

<p><img src="http://brownsofa.org/blog/wp-content/uploads/2010/07/newProjectUrl-150x150.png" alt="" /> Create a new &ldquo;PHP Application&rdquo; NetBeans project.  Use the defaults on the first page, and make sure that PHP 5.3 is selected on the second page.  On the third page, make the URL point to your personal local page &ndash; insert a tilde followed by your username.</p>

<p>Accept all the default options on the final dialog page and get into the editor.</p>

<p>Next, add some code to get things rolling.  I opened the default index.php and added some basic stuff in there.</p>

<pre><code>&lt;!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"&gt;
&lt;html&gt;
    &lt;head&gt;
        &lt;meta http-equiv="Content-Type" content="text/html; charset=UTF-8"&gt;
        &lt;title&gt;&lt;/title&gt;
    &lt;/head&gt;
    &lt;body&gt;
        &lt;?php
        // put your code here
        $test = 3;

        while ($test &gt; 0) {
            $output = $test . "...&lt;br&gt;";
            echo $output;
            $test--;
        }

        xdebug_break();

        echo "Go!&lt;br&gt;";

        ?&gt;
    &lt;/body&gt;
&lt;/html&gt;
</code></pre>

<p>Almost time to test it out &ndash; the only thing remaining is to get the source tree into view of apache.  For my username, the <code>/Users/Ian/Sites/</code> folder is published as <a href="http://localhost/~ian/">http://localhost/~ian/</a>.  The most direct way I&rsquo;ve found to test and develop is to symlink from this folder to your project sources folder, thus:</p>

<pre><code>cd /Users/Ian/Sites/
ln -s ~Ian/NetBeansProjects/PhpProject1 PhpProject1
</code></pre>

<p>Finally, apache is configured to not follow symlinks.  I made two changes to make to enable this: in <code>/etc/apache2/Users/Ian.conf</code> I changed the AllowOverride directive to read &ldquo;<code>AllowOverride All</code>&rdquo;. Then in <code>~/Sites/htaccess</code> I added &ldquo;<code>Options +FollowSymLinks</code>&rdquo;</p>

<p>Now go back to NetBeans and run the project (press F6, or click the <a href="http://brownsofa.org/blog/wp-content/uploads/2010/07/runProject.png"><img src="http://brownsofa.org/blog/wp-content/uploads/2010/07/runProject.png" alt="" /></a> button).  You should see the countdown in your browser.</p>

<p><a href="http://brownsofa.org/blog/wp-content/uploads/2010/07/basic.png"><img src="http://brownsofa.org/blog/wp-content/uploads/2010/07/basic-150x150.png" alt="" /></a> Finally, make sure Xdebug is all set up properly and working.  Set some breakpoints in the code: look at the screenshot and you&rsquo;ll see that on line 13 I set a breakpoint in the IDE (just by clicking the where the red square is, or by pressing Command+F8).  Also on line 18 there&rsquo;s a call to <code>xdebug_break()</code>, which will have the same effect as the IDE breakpoint.  Also to note, by default NetBeans will break on the first line of the script (you can change this behavior in the PHP / General section of the NetBeans Preferences).</p>

<p><a href="http://brownsofa.org/blog/wp-content/uploads/2010/07/dbg.png"><img src="http://brownsofa.org/blog/wp-content/uploads/2010/07/dbg-150x150.png" alt="" /></a>From the Debug menu, choose Debug Project.  A browser window will open up, and if everything is set up correctly, that window will show absolutely nothing.  What you should see in the NetBeans window is the green arrow and highlight at line 8, indicating this is the next line to execute.  From the Debug menu press Continue &ndash; the execution pointer will jump down to line 13 (where you set the breakpoint).  In the source window click on the <code>$test</code> variable name, and leave the mouse pointer over the word.  A small popup shows you the current value of the variable.  Alternatively, look at the Variables window, and see the values of the variables in scope.  Click Continue again, and notice the value of $test changes to 2, and then to 1.  Clicking Continue again will pause execution at the <code>xdebug_break()</code> call.</p>

<p>If Xdebug isn&rsquo;t working, the config settings (in php.ini) are definitely very picky.  I&rsquo;ve found different platforms and versions don&rsquo;t work exactly the same, so play around with those settings.  Make sure you restart apache each time you make a change, otherwise nothing will happen.  Make sure you&rsquo;re editing the correct php.ini &ndash; many fist-to-forehead injuries have been caused (to me) as a result of not doing this.</p>

<p>That&rsquo;s it.  Play with the Step Into and Step Out Of debugging commands to dig down into and back out of functions.  Also check out the Xdebug documentation &ndash; there&rsquo;s a great API for debugging, tracing and profiling.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[More natural BDD with PHPUnit]]></title>
    <link href="http://brownsofa.org/blog/2010/07/17/bdd-with-phpunit/"/>
    <updated>2010-07-17T23:43:14-06:00</updated>
    <id>http://brownsofa.org/blog/2010/07/17/bdd-with-phpunit</id>
    <content type="html"><![CDATA[<p>I&rsquo;ve always been a little jealous of RSpec.  Those Ruby kids and their natural language BDD testing and plain text stories&hellip;  It always just seems more awkward any other way.  Cucumber looks pretty cool but getting it to play nicely with PHP is a little over my KISS threshold today.</p>

<!-- more -->


<p>Well, PHPUnit does have an alternative in its <a href="http://www.phpunit.de/manual/3.5/en/behaviour-driven-development.html">Story extension</a>.  Look at the docs and it&rsquo;s simple enough to put into effect, and works nicely as part of a bigger set of unit tests.  But check out how those scenarios are constructed &ndash; the argument passing just doesn&rsquo;t seem elegant, and run <code>phpunit --story &lt;file&gt;</code> on the 2-arg puppies and it&rsquo;s not pretty at all.  Here&rsquo;s a simple scenario straight from the manual:</p>

<pre><code>    /**
     * @scenario
     */
    public function scoreForOneStrikeAnd3And4Is24()
    {
        $this-&gt;given('New game')
             -&gt;when('Player rolls', 10)
             -&gt;and('Player rolls', 3)
             -&gt;and('Player rolls', 4)
             -&gt;then('Score should be', 24);
    }
</code></pre>

<p>So how can we write PHPUnit scenarios to read more like natural language?   Well, first thing to go are the arguments.  I&rsquo;d rather write:</p>

<pre><code>    /**
     * @scenario
     */
    public function scoreForOneStrikeAnd3And4Is24()
    {
        $this-&gt;given('New game')
             -&gt;when('Player rolls 10')
             -&gt;and('Player rolls 3')
             -&gt;and('Player rolls 4')
             -&gt;then('Score should be 24');
    }
</code></pre>

<p>Not a huge change, but it takes a little more work to finish the plumbing.  Just looking at implementing the when clause, the original version read</p>

<pre><code>    public function runWhen(&amp;$world, $action, $arguments)
    {
        switch($action) {
            case 'Player rolls': {
                $world['game']-&gt;roll($arguments[0]);
                $world['rolls']++;
            }
            break;

            default: {
                return $this-&gt;notImplemented($action);
            }
        }
    }
</code></pre>

<p>and ends up becoming something like:</p>

<pre><code>    public function runWhen(&amp;$world, $action, $arguments)
    {
        switch(true) {
            case preg_match('/^Player rolls \d+$/', $action): {
                $world['game']-&gt;roll( preg_replace('/\D/', '', $action) );
                $world['rolls']++;
            }
            break;

            default: {
                return $this-&gt;notImplemented($action);
            }
        }
    }
</code></pre>

<p>I feel like the added complexity of the helper code is compensated by the much more natural and flexible way you can construct the scenarios.  Start adding multiple arguments to the clauses and it&rsquo;s even nicer.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[ATtiny13 Dice]]></title>
    <link href="http://brownsofa.org/blog/2010/02/09/attiny13-dice/"/>
    <updated>2010-02-09T11:26:09-07:00</updated>
    <id>http://brownsofa.org/blog/2010/02/09/attiny13-dice</id>
    <content type="html"><![CDATA[<p><a href="http://brownsofa.org/blog/wp-content/uploads/2010/02/dice.jpg"><img src="http://brownsofa.org/blog/wp-content/uploads/2010/02/dice-150x150.jpg" alt="dice" /></a> I wanted to learn how to get the handful of non-Arduino AVR chips I have working.  I wanted to learn the basics of the C API, the development toolchain, and get a sense for what can be done with the little ATtiny microprocessors.  Starting with the most limited, teeny tiny little chip (the 1k ATtiny13), I made a dice.</p>

<!-- more -->


<p><strong>Parts</strong></p>

<p>Before starting, I had a handful of tools and parts.  In addition to the bits I had in my kit already, I ordered some parts from the super-helpful folks at Sparkfun.</p>

<ul>
<li><p>Atmel AVR ATtiny13 (<a href="http://www.sparkfun.com/commerce/product_info.php?products_id=211">Sparkfun</a>, $1.94)</p></li>
<li><p>AVR programming adapter (<a href="http://www.sparkfun.com/commerce/product_info.php?products_id=8508">Sparkfun</a>, $0.95)  <em>Not strictly necessary but add some header pins and it makes prototyping this stuff much easier</em></p></li>
<li><p>Sparkfun&rsquo;s AVR Pocket Programmer (<a href="http://www.sparkfun.com/commerce/product_info.php?products_id=9231">Sparkfun</a>, $14.95)</p></li>
<li><p>A momentary contact push-button switch</p></li>
<li><p>Some LEDs</p></li>
<li><p>A couple of 10k resistors</p></li>
</ul>


<p><strong>Software Setup and Reference</strong></p>

<p>The Pocket Programmer <a href="http://www.sparkfun.com/commerce/product_info.php?products_id=9231">product page</a> at Sparkfun has some helpful links and comments for the newb.  I downloaded the Windows USB driver from there.</p>

<p><a href="http://winavr.sourceforge.net/">WinAVR</a> is the obvious choice as a programming toolchain.  I downloaded and installed this, and after a little time found that the Programmer&rsquo;s Notepad bundled works perfectly well as a source editor.  I&rsquo;m still using it.</p>

<p>I did download and try Atmel&rsquo;s <a href="http://www.atmel.com/dyn/products/tools_card.asp?tool_id=2725">AVR Studio</a> IDE, but didn&rsquo;t really use it much beyond seeing its simulator.</p>

<p><a href="http://imakeprojects.com/Projects/avr-tutorial/">This</a> was a really useful getting started guide for me, taking you through hooking up the programmer to the chip, and the very most basic steps.  I won&rsquo;t repeat too much of this kind of stuff &ndash; just check out that page.</p>

<p>The <a href="http://www.atmel.com/dyn/resources/prod_documents/doc2535.pdf">ATtiny13 datasheet</a> and the <a href="http://www.nongnu.org/avr-libc/user-manual/modules.html">AVR libc API docs</a> were open the whole time too.</p>

<p><strong>The Plan</strong></p>

<p>I wanted to push a button and have a familiar dice display show me the result.  Obviously it needs to pick a random number between 1 and 6 to display.  I wanted some kind of flashy effect to take the place of the dice roll.</p>

<p>From playing around with <a href="http://en.wikipedia.org/wiki/Charlieplexing">charlieplexing </a>on arduino I figured that would be a sensible way to get going with driving the LEDs.  The dice will need a total of 7 LEDs, so I sketched out a charlieplexed array of 6 LEDs plus a single LED all on its own.  This requires a total of 4 tri-state I/O pins.</p>

<p>The pushbutton switch will need an input pin, so I need 5 of the 6 available I/O pins on the chip.  I used a 10k pull-up resistor (R1) on the switch input pin &ndash; when the switch is pressed it pulls the pin low, and it&rsquo;s this state I watch for in the code.</p>

<p>Finally, there&rsquo;s the standard pull-up resistor (R2) to keep the RESET pin high means the following circuit:</p>

<p><img src="http://brownsofa.org/blog/wp-content/uploads/2010/02/schematic.png" alt="ATtiny13 Dice schematic" /></p>

<p>Nothing too fancy.  Right now I&rsquo;m just drawing +5V from the USB programmer &ndash; later  steps will include adding power to the circuit.</p>

<p><strong>Coding  and Testing</strong></p>

<p>Even the simplest source needs a way to be compiled, then programmed onto the chip.  Helpfully, WinAVR comes with a template makefile in the sample directory.  There were a couple of customizations to this basic template:</p>

<pre><code>MCU = attiny13
F_CPU = 1200000
AVRDUDE_PROGRAMMER = usbtiny
</code></pre>

<p>The build targets in the makefile correspond with the tools menu items in Programmer&rsquo;s Notepad &ndash; Make All, Make Clean and Program.</p>

<p>As far as writing the code, the most helpful resources were the <a href="http://www.nongnu.org/avr-libc/user-manual/modules.html">API docs</a>, and the <a href="http://www.avrfreaks.net/index.php?name=PNphpBB2&amp;file=index">AVR Freaks</a> forum.</p>

<p>When it came to testing the code on the device, I initially ran into a problem with the programmer being unable to connect to the target &ndash; a <code>rc=-1</code> type error.  It turns out that having the chip in the circuit was messing with the programmer.  By disconnecting the MISO, MOSI and SCK pins from the LEDs (these pins also function as PORTB bits) the programmer worked fine.  This is something I need to fix in the future &ndash; unplugging 3 wires to program the chip then plugging them back in gets pretty tired&hellip;</p>

<p><strong>Results</strong></p>

<p>Here&rsquo;s a pic of the breadboard circuit.  You can see the programming adapter plugged in at the top left of the board.</p>

<p><a href="http://brownsofa.org/blog/wp-content/uploads/2010/02/dice.jpg"><img src="http://brownsofa.org/blog/wp-content/uploads/2010/02/dice.jpg" alt="dice" /></a></p>

<p>Download the <a href="http://brownsofa.org/blog/wp-content/uploads/2010/02/ATtiny13-Dice.zip">Source Code</a></p>

<p><strong>Next Steps</strong></p>

<p>I&rsquo;m going to add battery power and a regulator to the circuit, build it on proto board, and enclose it.  There&rsquo;s a little tweaking of code required, and I&rsquo;d like to squeeze a better &ldquo;roll&rdquo; effect in (but I&rsquo;m pretty full up on program space already).</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Ginger beer experiment #1]]></title>
    <link href="http://brownsofa.org/blog/2009/07/27/ginger-beer-experiment-1j/"/>
    <updated>2009-07-27T21:18:35-06:00</updated>
    <id>http://brownsofa.org/blog/2009/07/27/ginger-beer-experiment-1j</id>
    <content type="html"><![CDATA[<p>I made about a gallon of homemade ginger beer.  It&rsquo;s not perfect but it&rsquo;s pretty damn good &ndash; if you like it spicy.</p>

<p>I was flicking through the Southwest Air in-flight magazine the other week and they had some cocktail recipes, so I shoved the mag in my backpack and forgot about it until last weekend, when I made a batch.  I just tasted the first glass, and it&rsquo;s hot as hell but pretty good.  It&rsquo;s gingery, lightly carbonated, not too sweet, and tastes a little too much of habanero.  I&rsquo;ll make it again but modify the recipe a little.   Here&rsquo;s what I&rsquo;ll do next time:</p>

<!-- more -->


<ul>
<li><p><em>Juice from 1lb finely grated ginger</em></p></li>
<li><p><em>Juice from 8 small lemons</em></p></li>
<li><p><em>18 oz turbinado sugar (a light brown fairly unrefined sugar)</em></p></li>
<li><p><em>80 oz water</em></p></li>
<li><p><em>2-4 habanero chillies, halved and deseeded</em></p></li>
<li><p><em>Champagne yeast</em></p></li>
</ul>


<p>Bring some of the water to boil and dissolve sugar. Add the juice from the grated ginger, lemon juice, remainder of water and habaneros. Stick it in the fridge overnight.</p>

<p>Remove habaneros, bring back to room temperature (I did it on the stove), bottle and add a little yeast to each bottle (I used 32 oz gatorade bottles, and about 1/8 teaspoon yeast per bottle). Cap tightly, shake really really well, and keep in a warm place for a day or two until the pressure in the bottle has built. Refrigerate to stop further fermentation.</p>

<p>Lessons learned from this try:</p>

<ul>
<li><p>Add yeast directly into bottles.  Despite stirring and ladling I was left with the majority of yeast I pitched into the pan of ginger beer at the bottom of the pan, not in the bottles.  And they didn&rsquo;t carbonate first time round.</p></li>
<li><p>Less habaneros &ndash; not that the hot and spicy is bad, but it tastes like chilli ginger beer.</p></li>
<li><p>Grating ginger continues to be a threat to the structural integrity of my fingertips, but squeezing the juice out of ungrated ginger is really difficult and in the long run probably more painful.</p></li>
</ul>


<p>Next steps: handful of ice, twist of lemon, splash or two of ginger beer, and a slug of Woodford Reserve&hellip;</p>
]]></content>
  </entry>
  
</feed>
