<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Joe Freeman&#039;s Weblog &#187; Erlang</title>
	<atom:link href="http://joefreeman.co.uk/blog/category/erlang/feed/" rel="self" type="application/rss+xml" />
	<link>http://joefreeman.co.uk/blog</link>
	<description>Musings on Software Development, etc</description>
	<lastBuildDate>Sat, 27 Mar 2010 15:16:35 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.1</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Handling Multipart Uploads with MochiWeb</title>
		<link>http://joefreeman.co.uk/blog/2009/12/handling-multipart-uploads-with-mochiweb/</link>
		<comments>http://joefreeman.co.uk/blog/2009/12/handling-multipart-uploads-with-mochiweb/#comments</comments>
		<pubDate>Sat, 12 Dec 2009 00:02:40 +0000</pubDate>
		<dc:creator>Joe</dc:creator>
				<category><![CDATA[Erlang]]></category>
		<category><![CDATA[MochiWeb]]></category>

		<guid isPermaLink="false">http://joefreeman.co.uk/blog/?p=262</guid>
		<description><![CDATA[An explanation of how to handle file uploads with the MochiWeb Erlang library. The article includes a brief introduction to setting up MochiWeb and an explanation of how to handle file uploads and save them to the /tmp directory. I've also put together a very simple photo gallery system to show how to make use of this feature.]]></description>
			<content:encoded><![CDATA[<p>I was getting along fairly well with my own custom-built, lightweight Erlang web server, until I needed to handle file uploading. At this point, I decided it was time to stop trying to re-invent the wheel (or take the lazy approach—whichever way you choose to look at it), and take another look at MochiWeb, which implements this feature.</p>
<p>However, MochiWeb&#8217;s documentation is non-existent (unless I&#8217;m missing something—<em>please</em> let me know if I am). I came across <a href="http://jimmyg.org/blog/2007/multipart-post-with-erlang-and-mochiweb.html">James Gardner&#8217;s post</a> on handling file uploads, which helped me out. But after digging through the MochiWeb source-code I discovered a slightly easier way of handling file uploads. It may be that this method has been added since James&#8217; post in 2007, or maybe it&#8217;s just less appropriate to James&#8217; requirements.</p>
<p>I&#8217;m going to quickly run over how to setup MochiWeb. I know this has been covered quite a lot by other people, but it&#8217;s something a found a little daunting when I started out, so I want to emphasise that it&#8217;s a lot easier to setup than maybe first appears. Then I&#8217;ll post and explain a short chunk of code for handling uploads, and saving them to <code>/tmp</code>. Finally, I&#8217;ll provide an example of using this technique to provide a <em>very</em> simple photo gallery system.</p>
<h2>Setting up MochiWeb</h2>
<p>There&#8217;s a pretty good tutorial <a href="http://beebole.com/en/blog/erlang/how-to-quickly-set-up-ubuntu-804-loaded-with-erlang-mochiweb-and-nginx/">on the BeeBole blog</a>, but I&#8217;ll cover the basics here.</p>
<p>First step is to check out the code from the Google Code repository. Make sure you have subversion installed, and then:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #c20cb9; font-weight: bold;">svn</span> checkout http:<span style="color: #000000; font-weight: bold;">//</span>mochiweb.googlecode.com<span style="color: #000000; font-weight: bold;">/</span>svn<span style="color: #000000; font-weight: bold;">/</span>trunk<span style="color: #000000; font-weight: bold;">/</span> mochiweb</pre></div></div>

<p>Now, make sure that you have Erlang installed, and:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #7a0874; font-weight: bold;">cd</span> mochiweb
<span style="color: #c20cb9; font-weight: bold;">make</span>
<span style="color: #c20cb9; font-weight: bold;">chmod</span> +x scripts<span style="color: #000000; font-weight: bold;">/</span>new_mochiweb.erl
.<span style="color: #000000; font-weight: bold;">/</span>scripts<span style="color: #000000; font-weight: bold;">/</span>new_mochiweb.erl mochiweb_uploads ..<span style="color: #000000; font-weight: bold;">/</span>.</pre></div></div>

<p>This will build the MochiWeb system and then create a new MochiWeb project. You can repeat this process whenever you&#8217;re starting a new project. Note that <code>mochiweb_uploads</code> is the project&#8217;s name. MochiWeb is a bit picky about project names: they must be valid module names, so (it seems) you can&#8217;t use hyphens.</p>
<p>Next, we should make sure that the project builds and runs before we start coding:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #7a0874; font-weight: bold;">cd</span> ..<span style="color: #000000; font-weight: bold;">/</span>mochiweb_uploads
<span style="color: #c20cb9; font-weight: bold;">make</span>
.<span style="color: #000000; font-weight: bold;">/</span>start-dev.sh</pre></div></div>

<p>By default, your MochiWeb project is setup as a lightweight web server that serves files from the <code>priv/www</code> directory on port 8000. All being well, you should now be able to point your browser at <code>http://localhost:8000/</code> and see the &#8216;MochiWeb is running.&#8217; message.</p>
<p>If you have any problems, you&#8217;ll need to wade through the progress reports on the console to try and figure out where things are going wrong. The clues will be in any &#8216;crash reports&#8217;.</p>
<p>You can stop the server with Ctrl+C, then entering &#8216;a&#8217;, and hitting return. Or you can just hit Ctrl+C twice.</p>
<h2>Handling File Uploads</h2>
<p>First of all, we need to put together a page that we can test our uploading with. We&#8217;ll just replace the <code>index.html</code> file in <code>priv/www</code> with something straight-forward:</p>

<div class="wp_syntax"><div class="code"><pre class="html4strict" style="font-family:monospace;"><span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">html</span>&gt;</span>
<span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">head</span>&gt;</span>
<span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">title</span>&gt;</span>MochiWeb Upload Test<span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">title</span>&gt;</span>
<span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">head</span>&gt;</span>
<span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">body</span>&gt;</span>
<span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">form</span> <span style="color: #000066;">action</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;upload_photo&quot;</span> <span style="color: #000066;">method</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;post&quot;</span> <span style="color: #000066;">enctype</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;multipart/form-data&quot;</span>&gt;</span>
    <span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">input</span> <span style="color: #000066;">type</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;file&quot;</span> <span style="color: #000066;">name</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;photo&quot;</span> <span style="color: #66cc66;">/</span>&gt;</span>
    <span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">input</span> <span style="color: #000066;">type</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;submit&quot;</span> <span style="color: #000066;">value</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;Upload&quot;</span> <span style="color: #66cc66;">/</span>&gt;</span>
<span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">form</span>&gt;</span>
<span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">body</span>&gt;</span>
<span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">html</span>&gt;</span></pre></div></div>

<h3>Routing the Request</h3>
<p>The code for starting the web server is in <code>src/mochiweb_uploads_web.erl</code>. Open up this file and take a look at the <code>loop/2</code> function. The function is split up into two parts by the outer <code>case</code> construct: the first part is for HTTP GET (and HEAD) requests, the second is for POST requests. We&#8217;re going to be handling the file uploads in the POST clause. Like so:</p>

<div class="wp_syntax"><div class="code"><pre class="erlang" style="font-family:monospace;"><span style="">'POST'</span> <span style="color: #6bb810;">-&gt;</span>
    <span style="color: #186895;">case</span> <span style="color: #45b3e6;">Path</span> <span style="color: #186895;">of</span>
        <span style="color: #ff7800;">&quot;upload_photo&quot;</span> <span style="color: #6bb810;">-&gt;</span>
            <span style="color: #ff3c00;">upload_photo</span><span style="color: #109ab8;">&#40;</span><span style="color: #45b3e6;">Req</span><span style="color: #109ab8;">&#41;</span><span style="color: #6bb810;">;</span>
        <span style="color: #45b3e6;">_</span> <span style="color: #6bb810;">-&gt;</span>
            <span style="color: #45b3e6;">Req</span>:<span style="color: #ff3c00;">not_found</span><span style="color: #109ab8;">&#40;</span><span style="color: #109ab8;">&#41;</span>
    <span style="color: #186895;">end</span><span style="color: #6bb810;">;</span></pre></div></div>

<p>All we are doing here, is delegating responsibility for handling the &#8216;upload_photo&#8217; request to a function called &#8216;upload_photo&#8217;, which we can add to the bottom of <code>mochiweb_uploads_web.erl</code>:</p>

<div class="wp_syntax"><div class="code"><pre class="erlang" style="font-family:monospace;"><span style="color: #ff3c00;">upload_photo</span><span style="color: #109ab8;">&#40;</span><span style="color: #45b3e6;">Req</span><span style="color: #109ab8;">&#41;</span> <span style="color: #6bb810;">-&gt;</span>
    <span style="color: #45b3e6;">Req</span>:<span style="color: #ff3c00;">ok</span><span style="color: #109ab8;">&#40;</span><span style="color: #109ab8;">&#123;</span><span style="color: #ff7800;">&quot;text/html&quot;</span><span style="color: #6bb810;">,</span> <span style="color: #109ab8;">&#91;</span><span style="color: #109ab8;">&#93;</span><span style="color: #6bb810;">,</span> <span style="color: #ff7800;">&quot;&lt;p&gt;Hello, world!&lt;/p&gt;&quot;</span><span style="color: #109ab8;">&#125;</span><span style="color: #109ab8;">&#41;</span><span style="color: #6bb810;">.</span></pre></div></div>

<p>That&#8217;s going to just return a &#8216;Hello, world!&#8217; message so we can check the request is getting routed correctly. If we try out the system (<code>make</code>, <code>./start-dev.sh</code>, go to <code>localhost:8000</code>), we should initially see the form, then after submitting the form our message should appear.</p>
<h3>Handling the POSTed multipart data</h3>
<p>Now onto actually handling the POSTed multipart data. We&#8217;ll replace our <code>upload_photo/1</code> function with this:</p>

<div class="wp_syntax"><div class="code"><pre class="erlang" style="font-family:monospace;"><span style="color: #ff3c00;">upload_photo</span><span style="color: #109ab8;">&#40;</span><span style="color: #45b3e6;">Req</span><span style="color: #109ab8;">&#41;</span> <span style="color: #6bb810;">-&gt;</span>
    <span style="color: #45b3e6;">FileHandler</span> <span style="color: #014ea4;">=</span> <span style="color: #ff3c00;">fun</span><span style="color: #109ab8;">&#40;</span><span style="color: #45b3e6;">Filename</span><span style="color: #6bb810;">,</span> <span style="color: #45b3e6;">ContentType</span><span style="color: #109ab8;">&#41;</span> <span style="color: #6bb810;">-&gt;</span> <span style="color: #ff3c00;">handle_file</span><span style="color: #109ab8;">&#40;</span><span style="color: #45b3e6;">Filename</span><span style="color: #6bb810;">,</span> <span style="color: #45b3e6;">ContentType</span><span style="color: #109ab8;">&#41;</span> <span style="color: #186895;">end</span><span style="color: #6bb810;">,</span>
    <span style="color: #45b3e6;">Files</span> <span style="color: #014ea4;">=</span> mochiweb_multipart:<span style="color: #ff3c00;">parse_form</span><span style="color: #109ab8;">&#40;</span><span style="color: #45b3e6;">Req</span><span style="color: #6bb810;">,</span> <span style="color: #45b3e6;">FileHandler</span><span style="color: #109ab8;">&#41;</span><span style="color: #6bb810;">,</span>
    <span style="color: #45b3e6;">Photo</span> <span style="color: #014ea4;">=</span> <span style="color: #ff4e18;">proplists</span>:<span style="color: #ff3c00;">get_value</span><span style="color: #109ab8;">&#40;</span><span style="color: #ff7800;">&quot;photo&quot;</span><span style="color: #6bb810;">,</span> <span style="color: #45b3e6;">Files</span><span style="color: #109ab8;">&#41;</span><span style="color: #6bb810;">,</span>
    <span style="color: #666666; font-style: italic;">% TODO: handle the photo here</span>
    <span style="color: #45b3e6;">Req</span>:<span style="color: #ff3c00;">ok</span><span style="color: #109ab8;">&#40;</span><span style="color: #109ab8;">&#123;</span><span style="color: #ff7800;">&quot;text/html&quot;</span><span style="color: #6bb810;">,</span> <span style="color: #109ab8;">&#91;</span><span style="color: #109ab8;">&#93;</span><span style="color: #6bb810;">,</span> <span style="color: #ff7800;">&quot;&lt;p&gt;Thank you. &lt;a href=<span style="color: #000099; font-weight: bold;">\&quot;</span>index.html<span style="color: #000099; font-weight: bold;">\&quot;</span>&gt;Upload another?&lt;/a&gt;&lt;/p&gt;&quot;</span><span style="color: #109ab8;">&#125;</span><span style="color: #109ab8;">&#41;</span><span style="color: #6bb810;">.</span></pre></div></div>

<p>Let&#8217;s examine this line-by-line.</p>
<p>First of all, we&#8217;re specifying a function that we pass to the <code>mochiweb_multipart:parse_form/2</code> function. The function that we&#8217;re passing will get called <strong>once for every file that is present in the POST data</strong> (i.e., that is in the form)—don&#8217;t forget that multiple files may be being uploaded.</p>
<p>The file will be split into &#8216;chunks&#8217;. So it&#8217;s the job of this &#8216;FileHandler&#8217; function to return <em>another</em> function that will be used to consume each chunk of the file (and then, finally, the &#8216;eof&#8217; atom). We&#8217;ll come back to this in a moment.</p>
<p>The <code>parse_form/2</code> function will then return a list (in fact, a <a href="http://www.erlang.org/doc/man/proplists.html">property list</a>) of all the files. There will be a mapping from the name of the input to the value finally returned from our file handler.</p>
<p>Let&#8217;s take a look at the <code>handle_file/2</code> function:</p>

<div class="wp_syntax"><div class="code"><pre class="erlang" style="font-family:monospace;"><span style="color: #ff3c00;">handle_file</span><span style="color: #109ab8;">&#40;</span><span style="color: #45b3e6;">Filename</span><span style="color: #6bb810;">,</span> <span style="color: #45b3e6;">ContentType</span><span style="color: #109ab8;">&#41;</span> <span style="color: #6bb810;">-&gt;</span>
    <span style="color: #45b3e6;">TempFilename</span> <span style="color: #014ea4;">=</span> <span style="color: #ff7800;">&quot;/tmp/&quot;</span> <span style="color: #014ea4;">++</span> <span style="color: #ff3c00;">atom_to_list</span><span style="color: #109ab8;">&#40;</span>?<span style="color: #6941fd;">MODULE</span><span style="color: #109ab8;">&#41;</span> <span style="color: #014ea4;">++</span> <span style="color: #ff3c00;">integer_to_list</span><span style="color: #109ab8;">&#40;</span><span style="color: #ff4e18;">erlang</span>:<span style="color: #ff3c00;">phash2</span><span style="color: #109ab8;">&#40;</span><span style="color: #ff3c00;">make_ref</span><span style="color: #109ab8;">&#40;</span><span style="color: #109ab8;">&#41;</span><span style="color: #109ab8;">&#41;</span><span style="color: #109ab8;">&#41;</span><span style="color: #6bb810;">,</span>
    <span style="color: #109ab8;">&#123;</span>ok<span style="color: #6bb810;">,</span> <span style="color: #45b3e6;">File</span><span style="color: #109ab8;">&#125;</span> <span style="color: #014ea4;">=</span> <span style="color: #ff4e18;">file</span>:<span style="color: #ff3c00;">open</span><span style="color: #109ab8;">&#40;</span><span style="color: #45b3e6;">TempFilename</span><span style="color: #6bb810;">,</span> <span style="color: #109ab8;">&#91;</span>raw<span style="color: #6bb810;">,</span> write<span style="color: #109ab8;">&#93;</span><span style="color: #109ab8;">&#41;</span><span style="color: #6bb810;">,</span>
    <span style="color: #ff3c00;">chunk_handler</span><span style="color: #109ab8;">&#40;</span><span style="color: #45b3e6;">Filename</span><span style="color: #6bb810;">,</span> <span style="color: #45b3e6;">ContentType</span><span style="color: #6bb810;">,</span> <span style="color: #45b3e6;">TempFilename</span><span style="color: #6bb810;">,</span> <span style="color: #45b3e6;">File</span><span style="color: #109ab8;">&#41;</span><span style="color: #6bb810;">.</span></pre></div></div>

<p>We use <a href="http://www.erlang.org/doc/man/erlang.html#erlang:phash2-2"><code>erlang:phash2/2</code></a> and <a href="http://www.erlang.org/doc/man/erlang.html#make_ref-0"><code>make_ref/0</code></a> together with a (hopefully) application-specific prefix to construct a random filename which will reside in &#8216;/tmp&#8217;. A couple of points to make here: collisions aren&#8217;t impossible and this is platform-dependent. We could get the <a href="http://en.wikipedia.org/wiki/Temporary_folder">temporary directory</a> from the operating system, and we could generate <a href="http://stackoverflow.com/questions/1222084/how-do-i-create-a-temp-filename-in-erlang">better filenames</a>.</p>
<p>We open a file for writing to and pass it to our &#8216;chunk handler&#8217; ready for consuming the first chunk. Note that <code>chunk_handler/4</code> is <strong>a function that returns a function</strong>. We return this generated function back to the MochiWeb code, which will use it to handle the first chunk.</p>
<p>Before I go on to explain the &#8216;chunk_handler&#8217;, I should point out that in theory we could use this opportunity to filter the input. If (for some reason) we wanted to handle different types of file in different ways, we could do this based on the <code>ContentType</code>. Annoyingly, there&#8217;s no way to inspect the name of the field (i.e., the name of the HTML input) that we&#8217;re handling at this stage.</p>
<p>As I mentioned, the <code>chunk_handler/4</code> function simply returns another function (which will accept one parameter) that MochiWeb will call once it has fetched a chunk. I&#8217;m using the term &#8216;chunk&#8217; casually: it can be <em>either</em> a raw chunk of data from the socket, <em>or</em> the <code>eof</code> atom. <strong>If the chunk being passed is not the <code>eof</code> atom, the function must return another function which will be used to handle the next chunk.</strong> However, if the function is passed the <code>eof</code> atom, we will return a value that we want to associate with this part of the multipart data. The value returned here will be the value that is stored in the property list we mentioned earlier (in <code>upload_photo/1</code>).</p>
<p>Here&#8217;s our <code>chunk_handler/4</code>:</p>

<div class="wp_syntax"><div class="code"><pre class="erlang" style="font-family:monospace;"><span style="color: #ff3c00;">chunk_handler</span><span style="color: #109ab8;">&#40;</span><span style="color: #45b3e6;">Filename</span><span style="color: #6bb810;">,</span> <span style="color: #45b3e6;">ContentType</span><span style="color: #6bb810;">,</span> <span style="color: #45b3e6;">TempFilename</span><span style="color: #6bb810;">,</span> <span style="color: #45b3e6;">File</span><span style="color: #109ab8;">&#41;</span> <span style="color: #6bb810;">-&gt;</span>
    <span style="color: #ff3c00;">fun</span><span style="color: #109ab8;">&#40;</span><span style="color: #45b3e6;">Next</span><span style="color: #109ab8;">&#41;</span> <span style="color: #6bb810;">-&gt;</span>
        <span style="color: #186895;">case</span> <span style="color: #45b3e6;">Next</span> <span style="color: #186895;">of</span>
            eof <span style="color: #6bb810;">-&gt;</span>
                <span style="color: #ff4e18;">file</span>:<span style="color: #ff3c00;">close</span><span style="color: #109ab8;">&#40;</span><span style="color: #45b3e6;">File</span><span style="color: #109ab8;">&#41;</span><span style="color: #6bb810;">,</span>
                <span style="color: #109ab8;">&#123;</span><span style="color: #45b3e6;">Filename</span><span style="color: #6bb810;">,</span> <span style="color: #45b3e6;">ContentType</span><span style="color: #6bb810;">,</span> <span style="color: #45b3e6;">TempFilename</span><span style="color: #109ab8;">&#125;</span><span style="color: #6bb810;">;</span>
            <span style="color: #45b3e6;">Data</span> <span style="color: #6bb810;">-&gt;</span>
                <span style="color: #ff4e18;">file</span>:<span style="color: #ff3c00;">write</span><span style="color: #109ab8;">&#40;</span><span style="color: #45b3e6;">File</span><span style="color: #6bb810;">,</span> <span style="color: #45b3e6;">Data</span><span style="color: #109ab8;">&#41;</span><span style="color: #6bb810;">,</span>
                <span style="color: #ff3c00;">chunk_handler</span><span style="color: #109ab8;">&#40;</span><span style="color: #45b3e6;">Filename</span><span style="color: #6bb810;">,</span> <span style="color: #45b3e6;">ContentType</span><span style="color: #6bb810;">,</span> <span style="color: #45b3e6;">TempFilename</span><span style="color: #6bb810;">,</span> <span style="color: #45b3e6;">File</span><span style="color: #109ab8;">&#41;</span>
        <span style="color: #186895;">end</span>
    <span style="color: #186895;">end</span><span style="color: #6bb810;">.</span></pre></div></div>

<p>So, don&#8217;t forget we&#8217;re returning a function here, which will get executed later on. There are two cases, as we&#8217;ve discussed:</p>
<ul>
<li>The <code>eof</code> case involves closing the file, and returning a tuple containing the original filename, the content-type and the temporary filename. We could return this in record form, or we may choose just to return the temporary filename if we didn&#8217;t care about the other parameters.</li>
<li>The non-<code>eof</code> case involves writing the chunk of data to the file, and then returning a function to handle the next chunk of data.</li>
</ul>
<p>This concludes the data-handling code. At this point you may wish to refer back to the <code>upload_photo/1</code>—this is where you would then be able to reference each of the uploaded files in the property list by it&#8217;s HTML input&#8217;s name. The value in the property list would be the <code>{Filename, ContentType, TempFilename}</code> tuple being returned by <code>chunk_handler/4</code>.</p>
<h2>A Semi-practical Example</h2>
<p>To turn this into something &#8216;useful&#8217;, I&#8217;ve put together a rudimentary photo gallery system.</p>
<p>We will adapt our <code>upload_photo/1</code> function to take another two parameters (the directory for the photos and a list of valid file extensions; the function will hence become <code>upload_photo/3</code>).</p>
<p>The total of our security features will be to check that the extension of the file corresponds to a recognised image type. Anyone will be able to upload files.</p>
<p>Here&#8217;s our function:</p>

<div class="wp_syntax"><div class="code"><pre class="erlang" style="font-family:monospace;"><span style="color: #ff3c00;">upload_photo</span><span style="color: #109ab8;">&#40;</span><span style="color: #45b3e6;">Req</span><span style="color: #6bb810;">,</span> <span style="color: #45b3e6;">PhotoDir</span><span style="color: #6bb810;">,</span> <span style="color: #45b3e6;">ValidExtensions</span><span style="color: #109ab8;">&#41;</span> <span style="color: #6bb810;">-&gt;</span>
    <span style="color: #45b3e6;">FileHandler</span> <span style="color: #014ea4;">=</span> <span style="color: #ff3c00;">fun</span><span style="color: #109ab8;">&#40;</span><span style="color: #45b3e6;">Filename</span><span style="color: #6bb810;">,</span> <span style="color: #45b3e6;">ContentType</span><span style="color: #109ab8;">&#41;</span> <span style="color: #6bb810;">-&gt;</span> <span style="color: #ff3c00;">handle_file</span><span style="color: #109ab8;">&#40;</span><span style="color: #45b3e6;">Filename</span><span style="color: #6bb810;">,</span> <span style="color: #45b3e6;">ContentType</span><span style="color: #109ab8;">&#41;</span> <span style="color: #186895;">end</span><span style="color: #6bb810;">,</span>
    <span style="color: #45b3e6;">Files</span> <span style="color: #014ea4;">=</span> mochiweb_multipart:<span style="color: #ff3c00;">parse_form</span><span style="color: #109ab8;">&#40;</span><span style="color: #45b3e6;">Req</span><span style="color: #6bb810;">,</span> <span style="color: #45b3e6;">FileHandler</span><span style="color: #109ab8;">&#41;</span><span style="color: #6bb810;">,</span>
    <span style="color: #109ab8;">&#123;</span><span style="color: #45b3e6;">OriginalFilename</span><span style="color: #6bb810;">,</span> <span style="color: #45b3e6;">_</span><span style="color: #6bb810;">,</span> <span style="color: #45b3e6;">TempFilename</span><span style="color: #109ab8;">&#125;</span> <span style="color: #014ea4;">=</span> <span style="color: #ff4e18;">proplists</span>:<span style="color: #ff3c00;">get_value</span><span style="color: #109ab8;">&#40;</span><span style="color: #ff7800;">&quot;photo&quot;</span><span style="color: #6bb810;">,</span> <span style="color: #45b3e6;">Files</span><span style="color: #109ab8;">&#41;</span><span style="color: #6bb810;">,</span>
    <span style="color: #186895;">case</span> <span style="color: #ff4e18;">lists</span>:<span style="color: #ff3c00;">member</span><span style="color: #109ab8;">&#40;</span><span style="color: #ff4e18;">filename</span>:<span style="color: #ff3c00;">extension</span><span style="color: #109ab8;">&#40;</span><span style="color: #45b3e6;">OriginalFilename</span><span style="color: #109ab8;">&#41;</span><span style="color: #6bb810;">,</span> <span style="color: #45b3e6;">ValidExtensions</span><span style="color: #109ab8;">&#41;</span> <span style="color: #186895;">of</span>
        true <span style="color: #6bb810;">-&gt;</span>
            <span style="color: #45b3e6;">Destination</span> <span style="color: #014ea4;">=</span> <span style="color: #45b3e6;">PhotoDir</span> <span style="color: #014ea4;">++</span> <span style="color: #45b3e6;">OriginalFilename</span><span style="color: #6bb810;">,</span>
            <span style="color: #186895;">case</span> <span style="color: #ff4e18;">file</span>:<span style="color: #ff3c00;">rename</span><span style="color: #109ab8;">&#40;</span><span style="color: #45b3e6;">TempFilename</span><span style="color: #6bb810;">,</span> <span style="color: #45b3e6;">Destination</span><span style="color: #109ab8;">&#41;</span> <span style="color: #186895;">of</span>
                ok <span style="color: #6bb810;">-&gt;</span>
                    <span style="color: #45b3e6;">Url</span> <span style="color: #014ea4;">=</span> <span style="color: #ff7800;">&quot;/&quot;</span><span style="color: #6bb810;">,</span>
                    <span style="color: #45b3e6;">Req</span>:<span style="color: #ff3c00;">respond</span><span style="color: #109ab8;">&#40;</span><span style="color: #109ab8;">&#123;</span><span style="color: #ff9600;">302</span><span style="color: #6bb810;">,</span> <span style="color: #109ab8;">&#91;</span><span style="color: #109ab8;">&#123;</span><span style="color: #ff7800;">&quot;Location&quot;</span><span style="color: #6bb810;">,</span> <span style="color: #45b3e6;">Url</span><span style="color: #109ab8;">&#125;</span><span style="color: #109ab8;">&#93;</span><span style="color: #6bb810;">,</span> <span style="color: #ff7800;">&quot;Redirecting to &quot;</span> <span style="color: #014ea4;">++</span> <span style="color: #45b3e6;">Url</span><span style="color: #109ab8;">&#125;</span><span style="color: #109ab8;">&#41;</span><span style="color: #6bb810;">;</span>
                <span style="color: #109ab8;">&#123;</span>error<span style="color: #6bb810;">,</span> <span style="color: #45b3e6;">Reason</span><span style="color: #109ab8;">&#125;</span> <span style="color: #6bb810;">-&gt;</span>
                    <span style="color: #ff4e18;">file</span>:<span style="color: #ff3c00;">delete</span><span style="color: #109ab8;">&#40;</span><span style="color: #45b3e6;">TempFilename</span><span style="color: #109ab8;">&#41;</span><span style="color: #6bb810;">,</span>
                    <span style="color: #ff3c00;">html_response</span><span style="color: #109ab8;">&#40;</span><span style="color: #45b3e6;">Req</span><span style="color: #6bb810;">,</span> <span style="color: #ff7800;">&quot;An error occured whilst trying to move your file: &quot;</span> <span style="color: #014ea4;">++</span> <span style="color: #ff3c00;">atom_to_list</span><span style="color: #109ab8;">&#40;</span><span style="color: #45b3e6;">Reason</span><span style="color: #109ab8;">&#41;</span> <span style="color: #014ea4;">++</span> <span style="color: #ff7800;">&quot;. Does the destination directory exist?&quot;</span><span style="color: #109ab8;">&#41;</span>
            <span style="color: #186895;">end</span><span style="color: #6bb810;">;</span>
        false <span style="color: #6bb810;">-&gt;</span>
            <span style="color: #ff4e18;">file</span>:<span style="color: #ff3c00;">delete</span><span style="color: #109ab8;">&#40;</span><span style="color: #45b3e6;">TempFilename</span><span style="color: #109ab8;">&#41;</span><span style="color: #6bb810;">,</span>
            <span style="color: #ff3c00;">html_response</span><span style="color: #109ab8;">&#40;</span><span style="color: #45b3e6;">Req</span><span style="color: #6bb810;">,</span> <span style="color: #ff7800;">&quot;Invalid file type. File extension must be one of: &quot;</span> <span style="color: #014ea4;">++</span> <span style="color: #ff4e18;">string</span>:<span style="color: #ff3c00;">join</span><span style="color: #109ab8;">&#40;</span><span style="color: #45b3e6;">ValidExtensions</span><span style="color: #6bb810;">,</span> <span style="color: #ff7800;">&quot;, &quot;</span><span style="color: #109ab8;">&#41;</span> <span style="color: #014ea4;">++</span> <span style="color: #ff7800;">&quot;. &lt;a href=<span style="color: #000099; font-weight: bold;">\&quot;</span>/<span style="color: #000099; font-weight: bold;">\&quot;</span>&gt;Try again?&lt;/a&gt;&quot;</span><span style="color: #109ab8;">&#41;</span>
    <span style="color: #186895;">end</span><span style="color: #6bb810;">.</span></pre></div></div>

<p>You can <a href="http://joefreeman.co.uk/blog/wp-content/uploads/2009/12/mochiweb_uploads.zip">download</a> the rest of the code. It&#8217;s not very elegant, but I was keen to put together something for you to take home.</p>
<p>Obviously this isn&#8217;t the sort of thing you should consider making available to the world wide web, but hopefully it&#8217;ll be useful in explaining how to handle file uploads.</p>
]]></content:encoded>
			<wfw:commentRss>http://joefreeman.co.uk/blog/2009/12/handling-multipart-uploads-with-mochiweb/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Deploying an Erlang Appliance with SUSE Studio</title>
		<link>http://joefreeman.co.uk/blog/2009/08/deploying-an-erlang-appliance-with-suse-studio/</link>
		<comments>http://joefreeman.co.uk/blog/2009/08/deploying-an-erlang-appliance-with-suse-studio/#comments</comments>
		<pubDate>Tue, 04 Aug 2009 08:27:54 +0000</pubDate>
		<dc:creator>Joe</dc:creator>
				<category><![CDATA[Erlang]]></category>
		<category><![CDATA[Linux]]></category>

		<guid isPermaLink="false">http://joefreeman.co.uk/blog/?p=123</guid>
		<description><![CDATA[An introduction to the newly released SUSE Studio, and method for setting up an Erlang application to run on an appliance. The process involves using an Erlang script to automatically setup a release file and boot script with the appropriate application dependencies and version numbers.]]></description>
			<content:encoded><![CDATA[<p>Having read Nat Friedman&#8217;s <a href="http://nat.org/blog/2009/07/suse-studio-10/">blog post</a> about the release of <a href="http://susestudio.com/">SUSE Studio</a>, I thought I&#8217;d take a look at it. I was also interested to find out how easy it is to create an appliance for a simple Erlang application.</p>
<p><img src="http://joefreeman.co.uk/blog/wp-content/uploads/2009/08/suse-studio.png" alt="suse-studio" title="suse-studio" width="500" height="388" class="aligncenter size-full wp-image-127" /></p>
<h2>An Introduction to SUSE Studio</h2>
<p>I&#8217;m very impressed with SUSE Studio. It allows you to completely customise a Linux distribution and actually <strong>try it out</strong> (in the browser!) before you download it. This is, in my opinion, a pretty novel concept. At least at this scale.</p>
<p>Being able to have this control before you download the distribution obviously saves you from downloading a load of components that you don&#8217;t want. But the benefits don&#8217;t stop there:</p>
<ul>
<li><strong>Performing the administrative tasks of setting up the system can be performed <em>before</em> installation.</strong> This means a system can be deployed many times with minimum effort. Products like <a href="http://www.xen.org/">Xen</a> and <a href="http://www.vmware.com/">VMware</a> provide cost-effective ways to host several different systems together and keep them isolated from each other. If one of your applications breaks, the others are (potentially) isolated from the problem.</li>
<li><strong>Applications can be deployed and run in a pre-specified environment.</strong> This means their behaviour will be more predictable, and it will be easier to provide support for them. If a client is reporting problems, it will be much easier to replicate them yourself in a test environment.</li>
</ul>
<h2>My Experiences with SUSE Studio</h2>
<p>The service is currently by invite only. But having filled out the form, I got an invite the next day:</p>
<blockquote><p>Thank you for your interest in SUSE Studio, a new service that makes it quick and easy to create and test software appliances from your web browser.  We are pleased to invite you to try SUSE Studio.</p></blockquote>
<p>Sign in is via OpenID, which is nice.</p>
<p>The interface is very smooth and pleasant to use. Helpful messages appear in the left-hand column, which let you know where you&#8217;ve gone wrong, or give you tips as you go, and there&#8217;s a helpful &#8216;undo&#8217; feature. The site is also scattered with a selection of pleasing cartoons.</p>
<p>The &#8216;test drive&#8217; feature is <strong>awesome</strong>. Once you&#8217;ve finished configuring the system you need to build it, which takes a little time. When this is completed, just click on &#8216;Testdrive&#8217;, and a flash applet lets you watch the machine and interact with it (via VNC). Nat has an <a href="http://nat.org/blog/2009/07/linux-in-the-browser/">article</a> about some of the implementation details.</p>
<p>By enabling networking in test drive, you can also connect to the machine via SSH, or with your web browser if there&#8217;s a web server running.</p>
<p>Whilst Test Drive is running, you can even see a list of the files that have been modified, view <code>diff</code>s and download the modified files.</p>
<p>A impressive number of configuration parameters are at your disposal. You can even personalise the system by changing the logo and background image.</p>
<p>I noted a minor problem with the interface so I sent some feedback to the developers to check they were aware of it. I was impressed that they replied to me about ten minutes later (to say they were aware of the problem, thanks).</p>
<h2>Setting up an Appliance with Erlang</h2>
<p>The steps involved in setting up a basic appliance are very simple. I&#8217;ll skim over these steps and instead focus on those involved in setting up Erlang, and adding your application to the appliance. The aim is to have an Erlang application boot automatically when the appliance is started.</p>
<p>I started off with the openSUSE 11.1 &#8216;just enough&#8217; base template, which, for reference, has the following packages installed:</p>
<blockquote><p>aaa_base, branding-openSUSE, dhcpcd, grub, hwinfo, insserv, kbd, kernel-default, licenses, mkinitrd, module-init-tools, netcfg, openssh, openSUSE-build-key, openSUSE-release, PolicyKit, polkit-default-privs, procps, pwdutils, rpcbind, rpm, sysconfig, syslog-ng, vim</p></blockquote>
<p>The next step is to add a repository that contains the Erlang package. Select &#8216;Add repositories&#8230;&#8217; from the Software page, search for &#8216;erlang&#8217; and then add the suggested &#8216;devel:languages:erlang 11.1&#8242; repository. At time of writing, this will install Erlang release R12B-5.</p>
<p>Then, from the software page, search for &#8216;erlang&#8217;, and select the &#8216;erlang&#8217; package to be added.</p>
<p>Then make a few more configuration changes as required—for example, selecting the keyboard layout and time zone, and adding users (with default passwords that should obviously be changed following installation).</p>
<p>The next step is to add the Erlang application. I won&#8217;t go into details of setting up OTP applications, but I will explain how to <em>automatically</em> generate a bootable release file.</p>
<p>The release file needs to be setup to work with the installed version of Erlang, and the boot script needs to be generated in the same system environment (so we know we&#8217;ve got the correct versions of applications). To achieve this, I have written an Erlang script to be run when the appliance is first booted, which will generate a release file and accompanying boot script.</p>
<p>The main function that generates the release file is:</p>

<div class="wp_syntax"><div class="code"><pre class="erlang" style="font-family:monospace;"><span style="color: #ff3c00;">generate_release</span><span style="color: #109ab8;">&#40;</span><span style="color: #45b3e6;">Name</span><span style="color: #6bb810;">,</span> <span style="color: #45b3e6;">Version</span><span style="color: #6bb810;">,</span> <span style="color: #45b3e6;">Apps</span><span style="color: #109ab8;">&#41;</span> <span style="color: #6bb810;">-&gt;</span>
    <span style="color: #45b3e6;">ErtsVsn</span> <span style="color: #014ea4;">=</span> <span style="color: #ff4e18;">erlang</span>:<span style="color: #ff3c00;">system_info</span><span style="color: #109ab8;">&#40;</span>version<span style="color: #109ab8;">&#41;</span><span style="color: #6bb810;">,</span>
    <span style="color: #ff4e18;">lists</span>:<span style="color: #ff3c00;">foreach</span><span style="color: #109ab8;">&#40;</span><span style="color: #ff3c00;">fun</span><span style="color: #109ab8;">&#40;</span><span style="color: #45b3e6;">App</span><span style="color: #109ab8;">&#41;</span> <span style="color: #6bb810;">-&gt;</span> <span style="color: #ff4e18;">application</span>:<span style="color: #ff3c00;">load</span><span style="color: #109ab8;">&#40;</span><span style="color: #45b3e6;">App</span><span style="color: #109ab8;">&#41;</span> <span style="color: #186895;">end</span><span style="color: #6bb810;">,</span> <span style="color: #45b3e6;">Apps</span><span style="color: #109ab8;">&#41;</span><span style="color: #6bb810;">,</span>
    <span style="color: #45b3e6;">AppsVsns</span> <span style="color: #014ea4;">=</span> <span style="color: #ff4e18;">lists</span>:<span style="color: #ff3c00;">map</span><span style="color: #109ab8;">&#40;</span><span style="color: #ff3c00;">fun</span><span style="color: #109ab8;">&#40;</span><span style="color: #45b3e6;">App</span><span style="color: #109ab8;">&#41;</span> <span style="color: #6bb810;">-&gt;</span> <span style="color: #109ab8;">&#123;</span><span style="color: #45b3e6;">App</span><span style="color: #6bb810;">,</span> <span style="color: #ff3c00;">get_app_vsn</span><span style="color: #109ab8;">&#40;</span><span style="color: #45b3e6;">App</span><span style="color: #109ab8;">&#41;</span><span style="color: #109ab8;">&#125;</span> <span style="color: #186895;">end</span><span style="color: #6bb810;">,</span> <span style="color: #45b3e6;">Apps</span><span style="color: #109ab8;">&#41;</span><span style="color: #6bb810;">,</span>
    <span style="color: #109ab8;">&#123;</span>release<span style="color: #6bb810;">,</span> <span style="color: #109ab8;">&#123;</span><span style="color: #45b3e6;">Name</span><span style="color: #6bb810;">,</span> <span style="color: #45b3e6;">Version</span><span style="color: #109ab8;">&#125;</span><span style="color: #6bb810;">,</span> <span style="color: #109ab8;">&#123;</span>erts<span style="color: #6bb810;">,</span> <span style="color: #45b3e6;">ErtsVsn</span><span style="color: #109ab8;">&#125;</span><span style="color: #6bb810;">,</span> <span style="color: #45b3e6;">AppsVsns</span><span style="color: #109ab8;">&#125;</span><span style="color: #6bb810;">.</span></pre></div></div>

<p>Download the <a href="http://joefreeman.co.uk/blog/wp-content/uploads/2009/08/make_release.erl">complete script</a> to try it out.</p>
<p>The application I am deploying is a simple echo server, but I won&#8217;t go into details here.</p>
<p>You need to package up your application (possibly including the compiled <code>make_release.erl</code> script), then upload it under the &#8216;Overlay files&#8217; section, and specify a directory to extract the files to. I put the application into <code>/usr/local/</code>, and use the following directory structure:</p>
<p><img src="http://joefreeman.co.uk/blog/wp-content/uploads/2009/08/directory-structure.png" alt="directory-structure" title="directory-structure" width="228" height="264" class="aligncenter size-full wp-image-132" /></p>
<p>(Note that the <code>echo-1.0.*</code> files wouldn&#8217;t be there when uploaded as they get generated by the script.)</p>
<p>If you&#8217;d like the application to be started when the system boots, you may wish to add this to a boot script. Boot scripts can be configured under the &#8216;Configuration&#8217; section. The following boot script will generate the release file when the system is booted for the first time. Following this, and on subsequent boots, the the Erlang application will be started.</p>
<p>My boot script looks like this:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">if</span> <span style="color: #7a0874; font-weight: bold;">&#91;</span> <span style="color: #660033;">-f</span> <span style="color: #000000; font-weight: bold;">/</span>etc<span style="color: #000000; font-weight: bold;">/</span>init.d<span style="color: #000000; font-weight: bold;">/</span>suse_studio_firstboot <span style="color: #7a0874; font-weight: bold;">&#93;</span>
<span style="color: #000000; font-weight: bold;">then</span>
  <span style="color: #666666; font-style: italic;"># Generate release for Echo Server</span>
  <span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #ff0000;">&quot;Generating release for Echo Server...&quot;</span>
  erl <span style="color: #660033;">-noshell</span> <span style="color: #660033;">-s</span> make_release <span style="color: #660033;">-pa</span> <span style="color: #000000; font-weight: bold;">/</span>usr<span style="color: #000000; font-weight: bold;">/</span>local<span style="color: #000000; font-weight: bold;">/</span>Echo-<span style="color: #000000;">1.0</span><span style="color: #000000; font-weight: bold;">/</span>ebin<span style="color: #000000; font-weight: bold;">/</span>
<span style="color: #000000; font-weight: bold;">fi</span>
&nbsp;
<span style="color: #666666; font-style: italic;"># Start the echo server</span>
<span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #ff0000;">&quot;Starting Echo Server...&quot;</span>
erl <span style="color: #660033;">-boot</span> echo-<span style="color: #000000;">1.0</span> <span style="color: #660033;">-pa</span> <span style="color: #000000; font-weight: bold;">/</span>usr<span style="color: #000000; font-weight: bold;">/</span>local<span style="color: #000000; font-weight: bold;">/</span>Echo-<span style="color: #000000;">1.0</span> <span style="color: #660033;">-detached</span></pre></div></div>

<p>If you&#8217;re wondering, it looks like this script gets installed to: <code>/etc/init.d/suse_studio_custom</code></p>
<p>I installed the &#8216;open-vm-tools&#8217; package, as suggested (since I had specified that I wanted to generate a VMware virtual machine), and then set the machine to be built.</p>
<p>The appliance took a few minutes to build.</p>
<p>(Having requested a few more builds, it turns out that there&#8217;s a queueing system, so you may get lucky, or you may be in for a wait&#8230;)</p>
<p>Once the build was complete I was able to try it out in the browser:</p>
<p><img src="http://joefreeman.co.uk/blog/wp-content/uploads/2009/08/test-drive.png" alt="test-drive" title="test-drive" width="500" height="371" class="aligncenter size-full wp-image-128" /></p>
<p>After downloading it, double-clicking the .vmx file booted the machine in VMware:</p>
<p><img src="http://joefreeman.co.uk/blog/wp-content/uploads/2009/08/vmware.png" alt="vmware" title="vmware" width="500" height="411" class="aligncenter size-full wp-image-149" /></p>
<p>I was then able to test out the Erlang application by connecting with telnet:</p>
<p><img src="http://joefreeman.co.uk/blog/wp-content/uploads/2009/08/echo.png" alt="echo" title="echo" width="500" height="262" class="aligncenter size-full wp-image-148" /></p>
<h2>Alternative Approaches</h2>
<p>An alternative to actually installing your application is to just setup an appliance that has Erlang installed. This would still ease the setup process of the system and would just require you to add your Erlang application in after installation.</p>
<p>If you wanted the latest version of the Erlang system, it might be possible to upload the latest Erlang release as an &#8216;overlay file&#8217;, as opposed to fetching it from the repository. The benefit of using the repository is that it could be set to update automatically.</p>
]]></content:encoded>
			<wfw:commentRss>http://joefreeman.co.uk/blog/2009/08/deploying-an-erlang-appliance-with-suse-studio/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Estimating Pi with Monte Carlo Methods</title>
		<link>http://joefreeman.co.uk/blog/2009/07/estimating-pi-with-monte-carlo-methods/</link>
		<comments>http://joefreeman.co.uk/blog/2009/07/estimating-pi-with-monte-carlo-methods/#comments</comments>
		<pubDate>Thu, 16 Jul 2009 12:58:16 +0000</pubDate>
		<dc:creator>Joe</dc:creator>
				<category><![CDATA[Erlang]]></category>

		<guid isPermaLink="false">http://joefreeman.co.uk/blog/?p=77</guid>
		<description><![CDATA[This article demonstrates how to use a Monte Carlo simulation to calculate a value for Pi. An example program is given, written in Erlang, which can be run in a parallel environment. As well as the theory behind the method, we will look at how random numbers can be generated in Erlang and how to time Erlang programs. We will also perform an informal analysis of the results.]]></description>
			<content:encoded><![CDATA[<p>This article demonstrates how to use a Monte Carlo simulation to calculate a value for Pi. An example program is given, written in Erlang, which can be run in a parallel environment. As well as the theory behind the method, we will look at how random numbers can be generated in Erlang and how to time Erlang programs. We will also perform an informal analysis of the results.</p>
<h2>Monte Carlo Simulations</h2>
<p>A Monte Carlo method is the general name of an algorithm that uses a stochastic process to perform repeated random sampling on a problem. A statistical approach is used such that the numerical result to the problem can then be given by considering the number of &#8216;hits&#8217; that are achieved with the sampling.</p>
<p>The accuracy of the result, and the confidence in it, will increase as the number of samples we take increases.</p>
<p>More details about Monte Carlo methods can be found on the <a href="http://en.wikipedia.org/wiki/Monte_Carlo_method">Wikipedia article</a> and in the article <a href="http://library.lanl.gov/cgi-bin/getfile?00326866.pdf"><i>The Beginning of the Monte Carlo Method</i></a>.</p>
<h2>Estimating Pi</h2>
<p>A nice example of the use of Monte Carlo methods involves estimating a value for Pi. Let us consider a circle (with a radius of one) which is within a square (with edges of length two). Refer to the following diagram:</p>
<p><img src="http://joefreeman.co.uk/blog/wp-content/uploads/2009/07/diagram.gif" alt="Diagram" title="Diagram" width="350" height="301" class="aligncenter size-full wp-image-88" /></p>
<p>Now, by choosing random points within the square, we are able to calculate whether or not each point is within the circle or not. We can consider the analogy of throwing darts &#8216;randomly&#8217; at a dart board.</p>
<p>Since we know the area of a circle with radius <em>r</em> is given by:</p>
<p><img src="http://joefreeman.co.uk/blog/wp-content/uploads/2009/07/pirsquared.gif" alt="Area of a circle" title="Area of a circle" width="57" height="20" class="aligncenter size-full wp-image-80" /></p>
<p>And the area of a square with sides of length <em>x</em> is given by:</p>
<p><img src="http://joefreeman.co.uk/blog/wp-content/uploads/2009/07/xsquared.gif" alt="Area of a square" title="Area of a square" width="45" height="20" class="aligncenter size-full wp-image-83" /></p>
<p>And in our example, <em>r</em>=1 and <em>x</em>=2 and we know that the ratio, <em>R</em>, of the area of the circle to the total area of the square is:</p>
<p><img src="http://joefreeman.co.uk/blog/wp-content/uploads/2009/07/ratio.gif" alt="Ratio of areas" title="Ratio of areas" width="96" height="40" class="aligncenter size-full wp-image-82" /></p>
<p>Therefore, if we can come up with this ratio by experimentation, we can use it to derive a value for Pi:</p>
<p><img src="http://joefreeman.co.uk/blog/wp-content/uploads/2009/07/r4.gif" alt="Estimation of Pi" title="Estimation of Pi" width="51" height="20" class="aligncenter size-full wp-image-81" /></p>
<h2>Generating Random Numbers in Erlang</h2>
<p>Our method requires that we generate pairs of random numbers to identify the x- and y-co-ordinates of random points within the square. We need to make sure that these numbers have a uniform distribution—so that there is an equal chance of hitting any point on the dart board.</p>
<p>Fortunately, Erlang has just such a function: <code>random:uniform/0</code>. It is essentially as simple as calling <code>random:uniform()</code> to generate a random float between 0.0 and 1.0. Details can be found in the <a href="http://erlang.org/doc/man/random.html">manual page</a>.</p>
<h2>Seeding</h2>
<p>A note at the bottom of the manual page states:</p>
<blockquote><p>If a process calls <code>uniform/0</code> or <code>uniform/1</code> without setting a seed first, <code>seed/0</code> is called automatically.</p></blockquote>
<p>Interestingly, if a number of processes are spawned together, they will all produce the same list of &#8216;random&#8217; numbers. This is because each process is seeding the random number generator with the same default values.</p>
<p>To avoid this, we can seed the random number generator ourselves. The manual recommends using the built-in-function <code>now/0</code>. We can achieve this by calling the following line from the newly spawned process:</p>

<div class="wp_syntax"><div class="code"><pre class="erlang" style="font-family:monospace;"><span style="color: #ff3c00;">apply</span><span style="color: #109ab8;">&#40;</span>random<span style="color: #6bb810;">,</span> seed<span style="color: #6bb810;">,</span> <span style="color: #ff3c00;">tuple_to_list</span><span style="color: #109ab8;">&#40;</span><span style="color: #ff3c00;">now</span><span style="color: #109ab8;">&#40;</span><span style="color: #109ab8;">&#41;</span><span style="color: #109ab8;">&#41;</span><span style="color: #109ab8;">&#41;</span></pre></div></div>

<p>The function <code>now/0</code> will always return a unique value, so we can be confident that each process has a uniquely seeded random number generator. Incidentally, I am led to believe that <code>now/0</code> will actually move ahead of the system time if called frequently enough.</p>
<h2>Code Listing</h2>

<div class="wp_syntax"><div class="code"><pre class="erlang" style="font-family:monospace;"><span style="color: #014ea4;">-</span><span style="color: #5400b3;">module</span><span style="color: #109ab8;">&#40;</span>pi<span style="color: #109ab8;">&#41;</span><span style="color: #6bb810;">.</span>
&nbsp;
<span style="color: #014ea4;">-</span><span style="color: #5400b3;">export</span><span style="color: #109ab8;">&#40;</span><span style="color: #109ab8;">&#91;</span>start<span style="color: #014ea4;">/</span><span style="color: #ff9600;">2</span><span style="color: #109ab8;">&#93;</span><span style="color: #109ab8;">&#41;</span><span style="color: #6bb810;">.</span>
&nbsp;
<span style="color: #666666; font-style: italic;">%% Start processing on the specified number of processes for the specified</span>
<span style="color: #666666; font-style: italic;">%% number of points. The number of points will be split equally amongst the</span>
<span style="color: #666666; font-style: italic;">%% number of processes.</span>
&nbsp;
<span style="color: #ff3c00;">start</span><span style="color: #109ab8;">&#40;</span><span style="color: #45b3e6;">Processes</span><span style="color: #6bb810;">,</span> <span style="color: #45b3e6;">Points</span><span style="color: #109ab8;">&#41;</span> <span style="color: #6bb810;">-&gt;</span>
	<span style="color: #45b3e6;">PointsPerProcess</span> <span style="color: #014ea4;">=</span> <span style="color: #45b3e6;">Points</span> <span style="color: #014ea4;">div</span> <span style="color: #45b3e6;">Processes</span><span style="color: #6bb810;">,</span>
	<span style="color: #ff3c00;">start_processes</span><span style="color: #109ab8;">&#40;</span><span style="color: #45b3e6;">Processes</span><span style="color: #6bb810;">,</span> <span style="color: #45b3e6;">PointsPerProcess</span><span style="color: #109ab8;">&#41;</span><span style="color: #6bb810;">,</span>
	<span style="color: #ff3c00;">wait_for_results</span><span style="color: #109ab8;">&#40;</span><span style="color: #45b3e6;">Processes</span><span style="color: #6bb810;">,</span> <span style="color: #45b3e6;">Points</span><span style="color: #109ab8;">&#41;</span><span style="color: #6bb810;">.</span>
&nbsp;
&nbsp;
<span style="color: #666666; font-style: italic;">%% Spawn the required number of processes. Each process is passed the Pid of</span>
<span style="color: #666666; font-style: italic;">%% the current process so that it can send the result back.</span>
&nbsp;
<span style="color: #ff3c00;">start_processes</span><span style="color: #109ab8;">&#40;</span><span style="color: #ff9600;">0</span><span style="color: #6bb810;">,</span> <span style="color: #45b3e6;">_PointsPerProcess</span><span style="color: #109ab8;">&#41;</span> <span style="color: #6bb810;">-&gt;</span>
	<span style="color: #ff4e18;">io</span>:<span style="color: #ff3c00;">format</span><span style="color: #109ab8;">&#40;</span><span style="color: #ff7800;">&quot;Started all processes.~n&quot;</span><span style="color: #109ab8;">&#41;</span><span style="color: #6bb810;">;</span>
&nbsp;
<span style="color: #ff3c00;">start_processes</span><span style="color: #109ab8;">&#40;</span><span style="color: #45b3e6;">Processes</span><span style="color: #6bb810;">,</span> <span style="color: #45b3e6;">PointsPerProcess</span><span style="color: #109ab8;">&#41;</span> <span style="color: #6bb810;">-&gt;</span>
	<span style="color: #45b3e6;">Pid</span> <span style="color: #014ea4;">=</span> <span style="color: #ff3c00;">self</span><span style="color: #109ab8;">&#40;</span><span style="color: #109ab8;">&#41;</span><span style="color: #6bb810;">,</span>
	<span style="color: #ff3c00;">spawn</span><span style="color: #109ab8;">&#40;</span><span style="color: #ff3c00;">fun</span><span style="color: #109ab8;">&#40;</span><span style="color: #109ab8;">&#41;</span> <span style="color: #6bb810;">-&gt;</span> <span style="color: #ff3c00;">process_points</span><span style="color: #109ab8;">&#40;</span><span style="color: #45b3e6;">PointsPerProcess</span><span style="color: #6bb810;">,</span> <span style="color: #45b3e6;">Pid</span><span style="color: #109ab8;">&#41;</span> <span style="color: #186895;">end</span><span style="color: #109ab8;">&#41;</span><span style="color: #6bb810;">,</span>
	<span style="color: #ff3c00;">start_processes</span><span style="color: #109ab8;">&#40;</span><span style="color: #45b3e6;">Processes</span> <span style="color: #014ea4;">-</span> <span style="color: #ff9600;">1</span><span style="color: #6bb810;">,</span> <span style="color: #45b3e6;">PointsPerProcess</span><span style="color: #109ab8;">&#41;</span><span style="color: #6bb810;">.</span>
&nbsp;
&nbsp;
<span style="color: #666666; font-style: italic;">%% Wait for the results to come back from each of the processeses. The result</span>
<span style="color: #666666; font-style: italic;">%% from each process comes back containing the count of 'hits'. A total sum</span>
<span style="color: #666666; font-style: italic;">%% of hits is calculated, and then when all the results have come back, we</span>
<span style="color: #666666; font-style: italic;">%% give a calculated value for Pi.</span>
<span style="color: #666666; font-style: italic;">%% </span>
<span style="color: #666666; font-style: italic;">%% Note: this is heavily reliant on the spawned processes not crashing, and</span>
<span style="color: #666666; font-style: italic;">%% returning their respective counts. (Otherwise we will be waiting forever).</span>
&nbsp;
<span style="color: #ff3c00;">wait_for_results</span><span style="color: #109ab8;">&#40;</span><span style="color: #45b3e6;">Processes</span><span style="color: #6bb810;">,</span> <span style="color: #45b3e6;">Points</span><span style="color: #109ab8;">&#41;</span> <span style="color: #6bb810;">-&gt;</span>
	<span style="color: #ff3c00;">wait_for_results</span><span style="color: #109ab8;">&#40;</span><span style="color: #45b3e6;">Processes</span><span style="color: #6bb810;">,</span> <span style="color: #45b3e6;">Points</span><span style="color: #6bb810;">,</span> <span style="color: #ff9600;">0</span><span style="color: #109ab8;">&#41;</span><span style="color: #6bb810;">.</span>
&nbsp;
<span style="color: #ff3c00;">wait_for_results</span><span style="color: #109ab8;">&#40;</span><span style="color: #ff9600;">0</span><span style="color: #6bb810;">,</span> <span style="color: #45b3e6;">Points</span><span style="color: #6bb810;">,</span> <span style="color: #45b3e6;">Sum</span><span style="color: #109ab8;">&#41;</span> <span style="color: #6bb810;">-&gt;</span>
	<span style="color: #45b3e6;">Pi</span> <span style="color: #014ea4;">=</span> <span style="color: #109ab8;">&#40;</span><span style="color: #45b3e6;">Sum</span> <span style="color: #014ea4;">/</span> <span style="color: #45b3e6;">Points</span><span style="color: #109ab8;">&#41;</span> <span style="color: #014ea4;">*</span> <span style="color: #ff9600;">4</span><span style="color: #6bb810;">,</span>
	<span style="color: #ff4e18;">io</span>:<span style="color: #ff3c00;">format</span><span style="color: #109ab8;">&#40;</span><span style="color: #ff7800;">&quot;Pi: ~w~n&quot;</span><span style="color: #6bb810;">,</span> <span style="color: #109ab8;">&#91;</span><span style="color: #45b3e6;">Pi</span><span style="color: #109ab8;">&#93;</span><span style="color: #109ab8;">&#41;</span><span style="color: #6bb810;">;</span>
&nbsp;
<span style="color: #ff3c00;">wait_for_results</span><span style="color: #109ab8;">&#40;</span><span style="color: #45b3e6;">Processes</span><span style="color: #6bb810;">,</span> <span style="color: #45b3e6;">Points</span><span style="color: #6bb810;">,</span> <span style="color: #45b3e6;">Sum</span><span style="color: #109ab8;">&#41;</span> <span style="color: #6bb810;">-&gt;</span>
	<span style="color: #186895;">receive</span>
		<span style="color: #109ab8;">&#123;</span>result<span style="color: #6bb810;">,</span> <span style="color: #45b3e6;">Count</span><span style="color: #109ab8;">&#125;</span> <span style="color: #6bb810;">-&gt;</span>
			<span style="color: #ff3c00;">wait_for_results</span><span style="color: #109ab8;">&#40;</span><span style="color: #45b3e6;">Processes</span> <span style="color: #014ea4;">-</span> <span style="color: #ff9600;">1</span><span style="color: #6bb810;">,</span> <span style="color: #45b3e6;">Points</span><span style="color: #6bb810;">,</span> <span style="color: #45b3e6;">Sum</span> <span style="color: #014ea4;">+</span> <span style="color: #45b3e6;">Count</span><span style="color: #109ab8;">&#41;</span>
	<span style="color: #186895;">end</span><span style="color: #6bb810;">.</span>
&nbsp;
&nbsp;
<span style="color: #666666; font-style: italic;">%% Setup processing of the points. We seed the random number generator, count</span>
<span style="color: #666666; font-style: italic;">%% the number of 'hits' in the simulation, and then send the result back to</span>
<span style="color: #666666; font-style: italic;">%% the parent process.</span>
&nbsp;
<span style="color: #ff3c00;">process_points</span><span style="color: #109ab8;">&#40;</span><span style="color: #45b3e6;">Points</span><span style="color: #6bb810;">,</span> <span style="color: #45b3e6;">Pid</span><span style="color: #109ab8;">&#41;</span> <span style="color: #6bb810;">-&gt;</span>
	<span style="color: #ff3c00;">apply</span><span style="color: #109ab8;">&#40;</span>random<span style="color: #6bb810;">,</span> seed<span style="color: #6bb810;">,</span> <span style="color: #ff3c00;">tuple_to_list</span><span style="color: #109ab8;">&#40;</span><span style="color: #ff3c00;">now</span><span style="color: #109ab8;">&#40;</span><span style="color: #109ab8;">&#41;</span><span style="color: #109ab8;">&#41;</span><span style="color: #109ab8;">&#41;</span><span style="color: #6bb810;">,</span>
	<span style="color: #45b3e6;">Count</span> <span style="color: #014ea4;">=</span> <span style="color: #ff3c00;">test_points</span><span style="color: #109ab8;">&#40;</span><span style="color: #45b3e6;">Points</span><span style="color: #6bb810;">,</span> <span style="color: #ff9600;">0</span><span style="color: #109ab8;">&#41;</span><span style="color: #6bb810;">,</span>
	<span style="color: #45b3e6;">Pid</span> <span style="color: #014ea4;">!</span> <span style="color: #109ab8;">&#123;</span>result<span style="color: #6bb810;">,</span> <span style="color: #45b3e6;">Count</span><span style="color: #109ab8;">&#125;</span><span style="color: #6bb810;">.</span>
&nbsp;
&nbsp;
<span style="color: #666666; font-style: italic;">%% Each point is chosen randomly and then tested to see whether it is within</span>
<span style="color: #666666; font-style: italic;">%% the circle. If it is, it is added to the count. Finally, the count is</span>
<span style="color: #666666; font-style: italic;">%% returned.</span>
&nbsp;
<span style="color: #ff3c00;">test_points</span><span style="color: #109ab8;">&#40;</span><span style="color: #ff9600;">0</span><span style="color: #6bb810;">,</span> <span style="color: #45b3e6;">Count</span><span style="color: #109ab8;">&#41;</span> <span style="color: #6bb810;">-&gt;</span> <span style="color: #45b3e6;">Count</span><span style="color: #6bb810;">;</span>
&nbsp;
<span style="color: #ff3c00;">test_points</span><span style="color: #109ab8;">&#40;</span><span style="color: #45b3e6;">Points</span><span style="color: #6bb810;">,</span> <span style="color: #45b3e6;">Count</span><span style="color: #109ab8;">&#41;</span> <span style="color: #6bb810;">-&gt;</span>
	<span style="color: #45b3e6;">X</span> <span style="color: #014ea4;">=</span> <span style="color: #109ab8;">&#40;</span><span style="color: #ff4e18;">random</span>:<span style="color: #ff3c00;">uniform</span><span style="color: #109ab8;">&#40;</span><span style="color: #109ab8;">&#41;</span> <span style="color: #014ea4;">*</span> <span style="color: #ff9600;">2</span><span style="color: #109ab8;">&#41;</span> <span style="color: #014ea4;">-</span> <span style="color: #ff9600;">1</span><span style="color: #6bb810;">,</span>
	<span style="color: #45b3e6;">Y</span> <span style="color: #014ea4;">=</span> <span style="color: #109ab8;">&#40;</span><span style="color: #ff4e18;">random</span>:<span style="color: #ff3c00;">uniform</span><span style="color: #109ab8;">&#40;</span><span style="color: #109ab8;">&#41;</span> <span style="color: #014ea4;">*</span> <span style="color: #ff9600;">2</span><span style="color: #109ab8;">&#41;</span> <span style="color: #014ea4;">-</span> <span style="color: #ff9600;">1</span><span style="color: #6bb810;">,</span>
	<span style="color: #45b3e6;">I</span> <span style="color: #014ea4;">=</span> <span style="color: #45b3e6;">X</span><span style="color: #014ea4;">*</span><span style="color: #45b3e6;">X</span> <span style="color: #014ea4;">+</span> <span style="color: #45b3e6;">Y</span><span style="color: #014ea4;">*</span><span style="color: #45b3e6;">Y</span><span style="color: #6bb810;">,</span>
	<span style="color: #186895;">if</span>
		<span style="color: #45b3e6;">I</span> <span style="color: #014ea4;">&lt;</span> <span style="color: #ff9600;">1</span> <span style="color: #6bb810;">-&gt;</span>
			<span style="color: #ff3c00;">test_points</span><span style="color: #109ab8;">&#40;</span><span style="color: #45b3e6;">Points</span> <span style="color: #014ea4;">-</span> <span style="color: #ff9600;">1</span><span style="color: #6bb810;">,</span> <span style="color: #45b3e6;">Count</span> <span style="color: #014ea4;">+</span> <span style="color: #ff9600;">1</span><span style="color: #109ab8;">&#41;</span><span style="color: #6bb810;">;</span>
		true <span style="color: #6bb810;">-&gt;</span>
			<span style="color: #ff3c00;">test_points</span><span style="color: #109ab8;">&#40;</span><span style="color: #45b3e6;">Points</span> <span style="color: #014ea4;">-</span> <span style="color: #ff9600;">1</span><span style="color: #6bb810;">,</span> <span style="color: #45b3e6;">Count</span><span style="color: #109ab8;">&#41;</span>
	<span style="color: #186895;">end</span><span style="color: #6bb810;">.</span></pre></div></div>

<p><b>Note</b>: I&#8217;ve only just started learning Erlang. Any feedback on my (simple) code will be welcomed.</p>
<h2>Timing an Erlang Program</h2>
<p>In order to experiment with running the program on multiple processors, it would be useful to be able to time the execution of the program. There is a module in Erlang for just this purpose. The function to use is: <code>timer:tc/3</code>. The three parameters that it takes are the module, the function and a list of arguments (these three parameters are commonly referred to as the MFA—module, function, arguments).</p>
<p>The following two lines allow us to time the program for ten thousand points running on one process and two processes, respectively:</p>

<div class="wp_syntax"><div class="code"><pre class="erlang" style="font-family:monospace;"><span style="color: #ff4e18;">timer</span>:<span style="color: #ff3c00;">tc</span><span style="color: #109ab8;">&#40;</span>pi<span style="color: #6bb810;">,</span> start<span style="color: #6bb810;">,</span> <span style="color: #109ab8;">&#91;</span><span style="color: #ff9600;">1</span><span style="color: #6bb810;">,</span> <span style="color: #ff9600;">10000</span><span style="color: #109ab8;">&#93;</span><span style="color: #109ab8;">&#41;</span><span style="color: #6bb810;">.</span>
<span style="color: #ff4e18;">timer</span>:<span style="color: #ff3c00;">tc</span><span style="color: #109ab8;">&#40;</span>pi<span style="color: #6bb810;">,</span> start<span style="color: #6bb810;">,</span> <span style="color: #109ab8;">&#91;</span><span style="color: #ff9600;">2</span><span style="color: #6bb810;">,</span> <span style="color: #ff9600;">10000</span><span style="color: #109ab8;">&#93;</span><span style="color: #109ab8;">&#41;</span><span style="color: #6bb810;">.</span></pre></div></div>

<p>The <code>timer:tc/3</code> function returns the tuple <code>{Time, Value}</code>, where <code>Time</code> is the time that the function took to execute, in <i>microseconds</i>, and <code>Value</code> is the return value from the function we are timing.</p>
<h2>Analysis of Results</h2>
<p>I&#8217;m currently running this code on my MacBook, so as a result of having two CPU cores, running with any more than two processes doesn&#8217;t give any speed benefits. It is nice to see, however, that running with two processes does give a significant speed increase over just a single process:</p>
<table>
<tr>
<th></th>
<th>One Processor</th>
<th>Two Processors</th>
<th>Speed-up</th>
</tr>
<tr>
<th>1 000 000 points</th>
<td>1.371</td>
<td>0.6980</td>
<td>1.964</td>
</tr>
<tr>
<th>10 000 000 points</th>
<td>13.44</td>
<td>6.854</td>
<td>1.961</td>
</tr>
</table>
<p>Times above (and below) are averaged from three runs of each scenario and given in seconds.</p>
<p>Let&#8217;s now look at the estimations given for Pi:</p>
<table>
<tr>
<th>Number of Points</th>
<th>Time taken (seconds)</th>
<th>Estimation for Pi</th>
</tr>
<tr>
<td>1 000 000</td>
<td>0.69800</td>
<td>3.14225733</td>
</tr>
<tr>
<td>10 000 000</td>
<td>6.8543</td>
<td>3.1418392</td>
</tr>
<tr>
<td>100 000 000</td>
<td>68.452</td>
<td>3.14162744</td>
</tr>
<tr>
<td>1 000 000 000</td>
<td>843.74</td>
<td>3.14161595</td>
</tr>
</table>
<p>We can observe the convergence to the true value of Pi on a graph:</p>
<p><img src="http://joefreeman.co.uk/blog/wp-content/uploads/2009/07/convergence.gif" alt="Convergence to Pi" title="Convergence to Pi" width="500" height="339" class="aligncenter size-full wp-image-103" /></p>
<p>The blue line shows our estimation of Pi, and the red line shows the true value of Pi. Note that the x-axis has a logarithmic scale.</p>
<h2>Extensions</h2>
<p>A nice extension to my program would be to be able to leave it running, and be able to call a function to see what the current progress is. For example, the number of points tested, and the current estimation of Pi would be given.</p>
<p>It would also be interesting to see how the program behaved on more than two processors. Specifically, when the processors are distributed over a network. I don&#8217;t currently have any other machines set up to try this out on.</p>
]]></content:encoded>
			<wfw:commentRss>http://joefreeman.co.uk/blog/2009/07/estimating-pi-with-monte-carlo-methods/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
