<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet href="http://feeds.feedburner.com/~d/styles/rss2full.xsl" type="text/xsl" media="screen"?><?xml-stylesheet href="http://feeds.feedburner.com/~d/styles/itemcontent.css" type="text/css" media="screen"?><rss 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:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0">

<channel>
	<title>spawn_link</title>
	
	<link>http://spawnlink.com</link>
	<description>Linking You to Erlang</description>
	<pubDate>Mon, 29 Sep 2008 18:09:58 +0000</pubDate>
	<generator>http://wordpress.org/?v=2.6.1</generator>
	<language>en</language>
			<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" href="http://feeds.feedburner.com/spawn_link" type="application/rss+xml" /><item>
		<title>Getting Started With EUnit</title>
		<link>http://feeds.feedburner.com/~r/spawn_link/~3/406473132/</link>
		<comments>http://spawnlink.com/articles/getting-started-with-eunit/#comments</comments>
		<pubDate>Sat, 27 Sep 2008 05:15:37 +0000</pubDate>
		<dc:creator>Mitchell</dc:creator>
		
		<category><![CDATA[Uncategorized]]></category>

		<category><![CDATA[beginner]]></category>

		<category><![CDATA[erlang]]></category>

		<category><![CDATA[eunit]]></category>

		<category><![CDATA[unit testing]]></category>

		<guid isPermaLink="false">http://spawnlink.com/?p=154</guid>
		<description><![CDATA[Up to this point, my experience with Erlang professionally has mostly been with ejabberd. I&#8217;ve created many ejabberd modules and have had to modify ejabberd core for certain projects (sometimes heavily). Now that my current client work at CitrusByte is over, I&#8217;ve been notified I will be working on a fairly customized Erlang/OTP application. Without [...]]]></description>
			<content:encoded><![CDATA[<p>Up to this point, my experience with Erlang professionally has mostly been with <a href="http://www.ejabberd.im">ejabberd</a>. I&#8217;ve created many ejabberd modules and have had to modify ejabberd core for certain projects (sometimes heavily). Now that my current client work at CitrusByte is over, I&#8217;ve been notified I will be working on a fairly customized Erlang/OTP application. Without going into too much detail, I have just began seriously looking at <a href="http://svn.process-one.net/contribs/trunk/eunit/doc/overview-summary.html">EUnit</a>. </p>
<p><span id="more-154"></span></p>
<p>In the past I have unit tested my Erlang source files by manually creating a <tt>test</tt> method and running it via a bash script. This works, but it is a bit hard to manage and you don&#8217;t get a lot of things for free; I just used pattern matching for the unit tests. Now that I&#8217;m starting a new project, I decided to start right with a proper unit testing framework. For those of you not familiar with the practice of &#8220;unit testing,&#8221; this article is not for you and you should google around, there are thousands of resources available. </p>
<h2>Getting EUnit</h2>
<p>For some reason I assumed Erlang would come shipped with EUnit, and spent a good 10 minutes &#8220;debugging&#8221; why my unit tests weren&#8217;t available! Of course I was wrong, I had to go grab EUnit myself. You can grab it by checking it out of <a href="http://svn.process-one.net/contribs/trunk/eunit/">the EUnit trunk</a> via SubVersion. I know there is a ZIP file also available on process-one&#8217;s website but the code is pretty outdated so I recommend checking out the trunk. </p>
<p>Go into the download <tt>eunit/</tt> directory and type <tt>make</tt> to compile all the Erlang source files. After doing this, make sure to copy your <tt>eunit/</tt> directory to the Erlang lib directory, which can be found by running <span class="code inline">code:lib_dir().</span></p>
<h2>Basics of EUnit</h2>
<p>There are quite a few resources for EUnit which I&#8217;ll link at the end of this article. So as not to totally reinvent the wheel I&#8217;m only going to cover a few topics here and will trust that you have the drive to read the other articles which are fantastic for getting off the ground. </p>
<p>EUnit is minimally invasive to your code. By this I mean the only real change you need to make to your source files to get it up and running is to include a header file. Here is an example of the preprocessor command I use:</p>
<div class="code">
<pre><span style="color: #f0dfaf;">-include_lib</span>(<span style="color: #cc9393;">"eunit/include/eunit.hrl"</span>).</pre>
</div>
<p>&nbsp;</p>
<p>This header file does do a small amount of magic. That is, it automatically exports a <tt>test/0</tt> method from the module if it doesn&#8217;t exist already. This test method automatically calls any methods ending in <tt>_test</tt> or <tt>_test_</tt> (a subtle but important difference).</p>
<p>The <tt>*_test</tt> methods are expected to return anything on success, or throw an exception on failure. Erlang actually has a great testing construct baked into the language: pattern matching. This is what 90% of your tests will use. The following is an example test:</p>
<div class="code">
<pre>
<span style="color: #f0dfaf;">reverse_test</span>() -&gt;
  [3, 2, 1] = lists:reverse([1, 2, 3]).</pre>
</div>
<p>&nbsp;</p>
<p>This test will pass. If instead I put <span class="code inline">[3, 1, 2]</span> it would have raised a <tt>badmatch</tt> exception and the test would have failed. Simple, isn&#8217;t it?</p>
<h2>Getting More Advanced</h2>
<p>This is just the surface of EUnit, but luckily, the rest of it isn&#8217;t much harder to understand. Unfortunately, EUnit doesn&#8217;t have mocks/stubs, which many Ruby programmers may miss (as we are all spoiled with our RSpec). I&#8217;m not going to cover any more of EUnit in this article since there are a handful of articles who do this already, and I don&#8217;t want to steal their thunder.</p>
<p>But one last thing I really liked&#8230;</p>
<h2>Hiding Your Tests In Production Systems</h2>
<p>Its great that EUnit automagically exports your test methods and runs them and all that but after the tests pass and the green icon shows, nobody really wants these in a running system. Unsurprisingly, EUnit developers already thought of this and offer an easy way out: Simply define <tt>NOTEST</tt> before you include the EUnit header file. If this is defined, nothing will happen. </p>
<p>I put NOTEST in all my files right away. Don&#8217;t worry, to run the tests you don&#8217;t have to manually remove this line. When you compile your Erlang source files for testing, add the <strong>-DTEST</strong> flag to the compiler, which will define the <tt>TEST</tt> macro. This overrides <tt>NOTEST</tt>. <img src='http://spawnlink.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> An example erlc command:</p>
<div class="code">
<pre>erlc -DTEST module.erl</pre>
</div>
<p>&nbsp;</p>
<h2>The Resources</h2>
<p>The following is a list of valuable resources I found picking up Erlang. All gain my stamp of approval (if that means anything to you).</p>
<ul>
<li><a href="http://svn.process-one.net/contribs/trunk/eunit/doc/overview-summary.html">The Official EUnit Summar Page</a></li>
<li><a href="http://salientblue.com/codenotes/">Paul Nelson&#8217;s EUnit-Based Erlang Tutorials</a></li>
<li><a href="http://pragprog.com/screencasts/v-kserl/erlang-by-example#episode-5">Kevin Smith&#8217;s Screencast on EUnit</a> - Highly recommend if you&#8217;re willing to spend a small amount of money. Its worth it.</li>
</ul>
<p>As a final note or disclaimer: I haven&#8217;t used EUnit a great amount yet in a professional environment so this is a very high-level overview of EUnit. I&#8217;m sure as time goes on and this new project goes on, I will have more to say. <img src='http://spawnlink.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /></p>
]]></content:encoded>
			<wfw:commentRss>http://spawnlink.com/articles/getting-started-with-eunit/feed/</wfw:commentRss>
		<feedburner:origLink>http://spawnlink.com/articles/getting-started-with-eunit/</feedburner:origLink></item>
		<item>
		<title>Performing Real-time Upgrades to an OTP System</title>
		<link>http://feeds.feedburner.com/~r/spawn_link/~3/401975723/</link>
		<comments>http://spawnlink.com/articles/performing-real-time-upgrades-to-an-otp-system/#comments</comments>
		<pubDate>Wed, 24 Sep 2008 17:19:17 +0000</pubDate>
		<dc:creator>Mitchell</dc:creator>
		
		<category><![CDATA[Uncategorized]]></category>

		<category><![CDATA[erlang]]></category>

		<category><![CDATA[erlybank]]></category>

		<category><![CDATA[hot code swapping]]></category>

		<category><![CDATA[otp introduction]]></category>

		<category><![CDATA[otp upgrade]]></category>

		<guid isPermaLink="false">http://spawnlink.com/?p=144</guid>
		<description><![CDATA[This is the seventh and final article of the Erlang/OTP introduction series. If you haven&#8217;t already, I recommend you read the first article which lays the foundation for the application which we&#8217;ll be upgrading in addition to teaching you the basics of Erlang/OTP before jumping into the topic of this article. If you&#8217;re a quick [...]]]></description>
			<content:encoded><![CDATA[<p>This is the seventh and final article of the Erlang/OTP introduction series. If you haven&#8217;t already, I recommend you <a href="http://spawnlink.com/articles/an-introduction-to-gen_server-erlybank/">read the first article</a> which lays the foundation for the application which we&#8217;ll be upgrading in addition to teaching you the basics of Erlang/OTP before jumping into the topic of this article. If you&#8217;re a quick learner or you wish to jump straight into this article, you may <a href="http://spawnlink.com/wp-content/uploads/2008/09/otp_part_6.zip">click here to download a ZIP</a> of all the files up to this point. </p>
<p><strong>The Scenario:</strong> ErlyBank has been running strong for a few months now and based on customer feedback, the bank wants to implement some additional features. First, they want us to implement a credit-based account. This is similar to a normal account except that withdrawals may be made to go into the negative, meaning that money is owed on the credit account. They also want us to change the ATM so that people can only use the ATM to pay bills with a credit account. And to top this all off, they want us to do these upgrades without significant downtime.</p>
<p><strong>The Result:</strong> We&#8217;ll create a credit server to easily add a credit account system and following that we&#8217;ll change the ATM. Luckily for us, once we make these changes, there is a straightforward way of upgrading the system in real-time so that ErlyBank won&#8217;t experience much, if any, downtime.</p>
<p><span id="more-144"></span></p>
<h2>Credit Based Account</h2>
<p>First things first, we need to implement the credit based account. ErlyBank wants a completely different server to handle this feature so I created eb_credit.erl as another gen_server to handle the creation and logic behind credit accounts. If you wish to challenge yourself I recommend trying to write this yourself first. The only features necessary are creating an account, withdrawing, and depositing (paying bills) since that is all we will use in this article. For fun you can also implement other features such as deleting accounts, sending events to the event manager, etc. </p>
<p>Since this article is about real-time upgrades and not more about gen_server, I&#8217;ve created the eb_credit.erl file already, <a href="http://spawnlink.com/otp-intro-7-upgrades-eb-credit/">which you can view here</a>.</p>
<h2>Changes to ATM</h2>
<p>ErlyBank also wanted changes to the ATM so that if a person logs in with a credit account, they are only allowed to deposit money to pay off a negative balance or gain a positive balance. For this, I am going to change the authorize method of eb_server to actually check the credit server too. And eb_server:authorize will return ok and tell the caller what kind of account it is. These are a lot of changes so I&#8217;ll walk you through the basics of what I did. <strong>Note:</strong> There are some very obvious problems with this approach, since it is possible that a credit account and debit account have the same name and PIN, in which case the authorize may return the wrong account. The reason I&#8217;m making these &#8220;mistakes&#8221; is to demonstrate different methods of release upgrades. After this article, if you wish, you can try and fix up the server to be a bit more realistic. </p>
<div class="code">
<pre>
<span style="color: #f0dfaf;">authorize</span>(<span style="color: #f0dfaf;">Name</span>, <span style="color: #f0dfaf;">PIN</span>) -&gt;
  <span style="color: #f0dfaf; font-weight: bold;">case</span> gen_server:call(?<span style="color: #dca3a3; font-weight: bold;">SERVER</span>, {authorize, <span style="color: #f0dfaf;">Name</span>, <span style="color: #f0dfaf;">PIN</span>}) <span style="color: #f0dfaf; font-weight: bold;">of</span>
    ok -&gt;
      {ok, debit};
    {error, <span style="color: #f0dfaf;">_Reason</span>} -&gt;
      <span style="color: #f0dfaf; font-weight: bold;">case</span> eb_credit:authorize(<span style="color: #f0dfaf;">Name</span>, <span style="color: #f0dfaf;">PIN</span>) <span style="color: #f0dfaf; font-weight: bold;">of</span>
        ok -&gt;
          {ok, credit};
        {error, <span style="color: #f0dfaf;">Reason</span>} -&gt;
          {error, <span style="color: #f0dfaf;">Reason</span>}
      <span style="color: #f0dfaf; font-weight: bold;">end</span>
  <span style="color: #f0dfaf; font-weight: bold;">end</span>.</pre>
</div>
<p>&nbsp;</p>
<p>This method should seem pretty straightforward by now. It first checks to see if there is a debit account with the name and pin, and if so, returns <span class="code inline">{ok, debit}</span>, otherwise it checks for a credit account. </p>
<p>After changing the authorize method for the server, we need to change the authorization method for the ATM to note the credit account. Remember that ErlyBank wants credit accounts to be able to deposit, but <em>not withdraw</em> money. Using Erlang&#8217;s pattern matching, implementing this change is trivial.</p>
<div class="code">
<pre>
<span style="color: #f0dfaf;">unauthorized</span>({authorize, <span style="color: #f0dfaf;">Name</span>, <span style="color: #f0dfaf;">Pin</span>}, <span style="color: #f0dfaf;">_From</span>, <span style="color: #f0dfaf;">State</span>) -&gt;
  <span style="color: #f0dfaf; font-weight: bold;">case</span> eb_server:authorize(<span style="color: #f0dfaf;">Name</span>, <span style="color: #f0dfaf;">Pin</span>) <span style="color: #f0dfaf; font-weight: bold;">of</span>
    {ok, debit} -&gt;
      {reply, ok, authorized, <span style="color: #f0dfaf;">Name</span>};
    {ok, credit} -&gt;
      {reply, ok, authorized, {credit, <span style="color: #f0dfaf;">Name</span>}};
    {error, <span style="color: #f0dfaf;">Reason</span>} -&gt;
      {reply, {error, <span style="color: #f0dfaf;">Reason</span>}, unauthorized, <span style="color: #f0dfaf;">State</span>}
  <span style="color: #f0dfaf; font-weight: bold;">end</span>;</pre>
</div>
<p>&nbsp;</p>
<p>First is to change the authorization request for the ATM. Its a simple change to test whether the response is either credit or debit. If the response is debit, we make no changes and the same code as the previous eb_atm is used. If it is a credit account, the internal state data of the ATM is set to <span class="code inline">{credit, Name}</span>. </p>
<p>Now to restrict withdrawing to only debit accounts, we can just check to make sure the state is a list (a &#8220;string&#8221; in Erlang) in the deposit method, as you can see here:</p>
<div class="code">
<pre>
<span style="color: #f0dfaf;">authorized</span>({withdraw, <span style="color: #f0dfaf;">Amount</span>}, <span style="color: #f0dfaf;">_From</span>, <span style="color: #f0dfaf;">State</span>) <span style="color: #f0dfaf; font-weight: bold;">when</span> <span style="color: #dca3a3; font-weight: bold;">is_list</span>(<span style="color: #f0dfaf;">State</span>) -&gt;</pre>
</div>
<p>&nbsp;</p>
<p>Now when a credit account attempts to withdraw, it will just give an invalid error message since it&#8217;ll skip down to the catch-all function. For the authorization methods, this is now done:</p>
<div class="code">
<pre>
<span style="color: #f0dfaf;">authorized</span>({deposit, <span style="color: #f0dfaf;">Amount</span>}, {credit, <span style="color: #f0dfaf;">Account</span>}=<span style="color: #f0dfaf;">State</span>) -&gt;
  eb_credit:deposit(<span style="color: #f0dfaf;">Account</span>, <span style="color: #f0dfaf;">Amount</span>),
  {next_state, thank_you, <span style="color: #f0dfaf;">State</span>, 5000};
<span style="color: #f0dfaf;">authorized</span>({deposit, <span style="color: #f0dfaf;">Amount</span>}, <span style="color: #f0dfaf;">State</span>) -&gt;
  eb_server:deposit(<span style="color: #f0dfaf;">State</span>, <span style="color: #f0dfaf;">Amount</span>),
  {next_state, thank_you, <span style="color: #f0dfaf;">State</span>, 5000};
<span style="color: #f0dfaf;">authorized</span>(<span style="color: #f0dfaf;">_Event</span>, <span style="color: #f0dfaf;">State</span>) -&gt;
  {next_state, authorized, <span style="color: #f0dfaf;">State</span>}.</pre>
</div>
<p>&nbsp;</p>
<p>The first function catches credit accounts and deposits its to them, the second will catch debit accounts, and the final catches invalid messages.</p>
<p>That should do it for the changes to the ATM!</p>
<h2>Release Handling Instructions</h2>
<p>Finally, to the interesting part. In Erlang/OTP an upgrade is given a set of instructions on how to transition from one version to the next. Each instruction is a tuple that is part of a list, where each instruction is executed in order of the list. There are a few instructions described as <em>high-level upgrade instructions</em>, and then there are <em>low-level upgrade instructions</em>. A brief list is given below:</p>
<ul>
<li><span class="code inline">{load_module, Module}</span> - Simply reloads a new version of the module Module. If no internal state of a module is changed and simply new code is added or changed, this command is sufficient. An example is if you have a math library and simply fix a bug and add a new method.</li>
<li><span class="code inline">{update, Module, {advanced, Extra}}</span> - If internal state is changed of a module, simply reloading a new version will not work as it will corrupt the current state for running processes. The update command calls the callback <tt>code_change</tt> passing the current state and <tt>Extra</tt>. Following this call, the module is updated to the latest version. The code_change callback function should be used to update the state to the newest format.</li>
<li><span class="code inline">{add_module/delete_module, Module}</span> - If a new module is introduced, add_module simply loads it into the address space. If a module is removed, delete_module deletes it. Any running processes from delete_module are killed.</li>
<li><span class="code inline">{apply, {M, F, A}}</span> - A low level instruction which applies the function onto the running system.</li>
</ul>
<p>There are many more but the above are the most common that I&#8217;ve used. You can view <a href="http://www.erlang.org/doc/man/appup.html">the rest here</a>.</p>
<h2>ErlyBank Upgrade Instructions</h2>
<p>Now, thinking back on the changes we made, what upgrade instructions do we need, and in what order? The following are the changes:</p>
<ul>
<li>New module, eb_credit.erl</li>
<li>Changed internal state of eb_server</li>
<li>Changed code of eb_atm</li>
<li>Added eb_credit to the supervisor</li>
</ul>
<p>For a fun challenge, you can try to think of the instructions needed to upgrade erlybank now. The following is the order and instructions I will use, accompanied with reasons:</p>
<ol>
<li><span class="code inline">{add_module, eb_credit}</span> - Adding the module won&#8217;t do much except load it into the memory space. But the other instructions are dependent on this so I do this first.</li>
<li><span class="code inline">{update, eb_sup, supervisor}</span> - Next, updating the supervisor so that eb_credit will be started.</li>
<li><span class="code inline">{load_module, eb_server}</span> - eb_server depends on eb_credit running, and now that it is we can load that up!</li>
<li><span class="code inline">{update, eb_atm, {advanced, []}}</span> - Finally we update the ATM with an advanced update since the internal state changed. We do this last since it depends on eb_server.</li>
</ol>
<p>The above instructions must go into an application upgrade file (an &#8220;appup&#8221; file), which has the following general format:</p>
<div class="code">
<pre>{NewVsn,
  [{OldVsn1, [Instructions]}],
  [{OldVsn1, [Instructions]}]
}.</pre>
</div>
<p>&nbsp;</p>
<p>The first value is the new version, followed by a list of tuples. Each tuple represents an upgrade path for a specific version, with a list of instructions to upgrade from that version. The next list is the same format as the first list but contains instructions for downgrading to that version. Following this format, the application upgrade file for ErlyBank looks like this:</p>
<div class="code">
<pre>
{"2.0",
 [{"1.0", [{add_module, eb_credit},
           {update, eb_sup, supervisor},
           {load_module, eb_server},
           {update, eb_atm, {advanced, []}},
            ]}],
  [{"1.0", [{update, eb_atm, {advanced, []}},
           {load_module, eb_server},
           {update, eb_sup, supervisor},
           {delete_module, eb_credit}]}
 ]
}.</pre>
</div>
<p>&nbsp;</p>
<p>As you can see, the instructions are the same except in the opposite order for the upgrade/downgrade paths. And we only need to be able to upgrade/downgrade from version 1 since that is the only other version! This file should be saved as <strong>erlybank.appup</strong> and should be placed in the <tt>ebin/</tt> directory with the app file.</p>
<p>Also, at this point, you should update the rel file to have the new version &#8220;2&#8243; and rename it to eb_rel-2.rel. </p>
<h2>Release Upgrade File</h2>
<p>There also needs to be a release upgrade file, or relup file, to describe how the entire release should be upgraded. Luckily for us, this doesn&#8217;t need to be manually created. Start an erlang shell in the root directory of ErlyBank and append <tt>ebin/</tt> to the code path, along with the prior version&#8217;s ebin path and path to the location of the prior version&#8217;s rel file, which you should know how to do by now. If not, the complete command for me is: <tt>erl -pz ebin/ -pz ../old/ -pz ../old/ebin</tt>. Then invoke the following command:</p>
<div class="code">
<pre>systools:make_relup("eb_rel-2", ["eb_rel-1"], ["eb_rel-1"]).</pre>
</div>
<p>&nbsp;</p>
<p>If it was able to find all the files, it should return with an <span class="code inline">ok</span>. If not, there should be a descriptive error of what happened. This command should create a &#8220;relup&#8221; file in the working directory.</p>
<h2>Packaging and Installing ErlyBank 2.0</h2>
<p>You should also know how to package the release now, it is the same as in the last article. If you&#8217;re unsure, <a href="http://spawnlink.com/articles/an-introduction-to-releases-with-erlybank/">go back and reference the previous article</a>. The first steps to installing the release are also the same as the last article, so unpack the release in the releases directory.</p>
<p>After unpacking the release, since we already have a prior release running in memory, we need to <strong>install</strong> this new release. Installing a release will run the relup file commands. To do this, invoke:</p>
<div class="code inline">
<pre>release_handler:install_release("2").</pre>
</div>
<p>&nbsp;</p>
<p>Now, although the new release is installed, the &#8220;current&#8221; code is still version 1. To make version 2 the new default, you must mark it as permanent by using the following command:</p>
<div class="code inline">
<pre>release_handler:make_permanent("2").</pre>
</div>
<p>&nsbp;</p>
<p>And that&#8217;s it! ErlyBank has been seamlessly upgraded.</p>
<h2>Final Notes</h2>
<p>In this article, I introduced real-time upgrades to an OTP system. I covered the most used release instructions and guided you through upgrading the old system. There were some upgrade instructions I forced into this article, however. For example, although the internal state of eb_atm changed, it wasn&#8217;t necessary to do the advanced update of the code since we didn&#8217;t change the structure of the old state information, just added new state information. If you&#8217;d like to learn more about application and release upgrades, I recommend reading the <a href="http://erlang.org/doc/design_principles/appup_cookbook.html">appup cookbook</a>. </p>
<p>With the conclusion of this article, the series is also concluded, almost as soon as it started. I have more posts coming up next week, but hopefully this series has helped more people become more familiar with OTP and its true power. </p>
<p>Ah, one final thing, if you want to download all the final files for this project, you can <a href="http://spawnlink.com/wp-content/uploads/2008/09/finalotp.zip">download the ZIP here.</a></p>
]]></content:encoded>
			<wfw:commentRss>http://spawnlink.com/articles/performing-real-time-upgrades-to-an-otp-system/feed/</wfw:commentRss>
		<feedburner:origLink>http://spawnlink.com/articles/performing-real-time-upgrades-to-an-otp-system/</feedburner:origLink></item>
		<item>
		<title>Where did the articles go?</title>
		<link>http://feeds.feedburner.com/~r/spawn_link/~3/400559836/</link>
		<comments>http://spawnlink.com/articles/where-did-the-articles-go/#comments</comments>
		<pubDate>Tue, 23 Sep 2008 07:35:58 +0000</pubDate>
		<dc:creator>Mitchell</dc:creator>
		
		<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://spawnlink.com/?p=142</guid>
		<description><![CDATA[Hi guys (and gals),
Sorry about postponing the final post of my Erlang/OTP series. Its in about a half-written, unedited state right now and I mean to finish it but this week I&#8217;m actually moving in to my apartment back at school at the University of Washington! I finally got internet hooked up today and am [...]]]></description>
			<content:encoded><![CDATA[<p>Hi guys (and gals),</p>
<p>Sorry about postponing the final post of my Erlang/OTP series. Its in about a half-written, unedited state right now and I mean to finish it but this week I&#8217;m actually moving in to my apartment back at school at the University of Washington! I finally got internet hooked up today and am just making final touches. </p>
<p>I have great things planned however and the feedback I&#8217;ve received on this blog has been great.</p>
<p>Thanks!</p>
]]></content:encoded>
			<wfw:commentRss>http://spawnlink.com/articles/where-did-the-articles-go/feed/</wfw:commentRss>
		<feedburner:origLink>http://spawnlink.com/articles/where-did-the-articles-go/</feedburner:origLink></item>
		<item>
		<title>An Introduction to Releases with Erlybank</title>
		<link>http://feeds.feedburner.com/~r/spawn_link/~3/395267516/</link>
		<comments>http://spawnlink.com/articles/an-introduction-to-releases-with-erlybank/#comments</comments>
		<pubDate>Wed, 17 Sep 2008 15:05:20 +0000</pubDate>
		<dc:creator>Mitchell</dc:creator>
		
		<category><![CDATA[Uncategorized]]></category>

		<category><![CDATA[erlang]]></category>

		<category><![CDATA[erlybank]]></category>

		<category><![CDATA[otp guide]]></category>

		<category><![CDATA[otp introduction]]></category>

		<category><![CDATA[otp tutorial]]></category>

		<category><![CDATA[releases]]></category>

		<guid isPermaLink="false">http://spawnlink.com/?p=132</guid>
		<description><![CDATA[This is the sixth article in the otp introduction series. If you haven&#8217;t yet, I recommend you start with the first article which talks about gen_server and lays the foundation for our bank system. If you&#8217;re a quick learner, you can download the ErlyBank sources as of the beginning of this post. 
This article will [...]]]></description>
			<content:encoded><![CDATA[<p>This is the sixth article in the <a href="http://spawnlink.com/articles/tag/otp-introduction/">otp introduction series</a>. If you haven&#8217;t yet, I recommend you <a href="http://spawnlink.com/articles/an-introduction-to-gen_server-erlybank">start with the first article</a> which talks about gen_server and lays the foundation for our bank system. If you&#8217;re a quick learner, you can <a href='http://spawnlink.com/wp-content/uploads/2008/09/erlybank-part6.zip'>download the ErlyBank sources</a> as of the beginning of this post. </p>
<p>This article will introduce release management of an Erlang application. This is not necessarily restricted to Erlang/OTP applications, and is a general tool that may be used for all your Erlang applications. </p>
<p><strong>Release Management</strong> refers to consolidating an application and its dependencies into a single package which can be easily started and stopped as a whole. Releases can be &#8220;installed&#8221; into an Erlang runtime system. Releases can also be upgraded in real-time, so when a new version of the application is created, it can be seamlessly installed into the system without bringing it down. (Note that real-time system upgrades are covered in the next article, not this one!)</p>
<p>After bundling the ErlyBank system as an application, restructuring it to be an Erlang release is very easy. But first, we&#8217;ll need to do some housecleaning to the directory structure.</p>
<p><span id="more-132"></span></p>
<h2>Release Directory Structure</h2>
<p>In general, all application releases follow a certain directory structure. This structure is not required but it is a common practice which increases in readability of application files:</p>
<div class="code">
<pre>Application-Vsn/ebin
               /include
               /priv
               /src</pre>
</div>
<p>&nbsp;</p>
<p>The <tt>src</tt> directory contains all the *.erl files, the sources for an application. The <tt>ebin</tt> directory contains all the compiled *.beam files for the sources and the application specification file. The <tt>include</tt> directory contains all the *.hrl files which may be included by the sources. And the <tt>priv</tt> directory contains any executables that are used by the application, such as port applications and Erlang drivers.</p>
<p>All these directories are under a parent directory named <tt>Application-Vsn</tt> where Application is the name of the application and Vsn is the version. </p>
<p>Reorganizing ErlyBank to follow this structure is quite easy and I will do this before moving on. Simply move all the *.erl files to the <tt>src/</tt> directory, and move erlybank.app to the <tt>ebin/</tt> directory. </p>
<p>Another important thing to remember is that when compiling Erlang sources, the resulting beam file is usually placed in the same directory as the erl file. To make it so that our sources are compiled into the <tt>ebin/</tt> directory, compilation should be done with the following command, which you may easily turn into a make command or whatever you want:</p>
<div class="code">
<pre>erlc -o ../ebin eb_app.erl eb_sup.erl eb_event_manager.erl eb_atm.erl eb_withdrawal_handler.erl eb_server.erl</pre>
</div>
<p>&nbsp;</p>
<p>The above command should be run from the <tt>src/</tt> directory and will place all beam files in the corresponding <tt>ebin/</tt> directory.</p>
<h2>Release Specification File</h2>
<p>The one thing you need to create a release is a release specification file. This file is used by the <tt>systools</tt> module to figure out how to package the Erlang application. This file format is documented very well at the <a href="http://www.erlang.org/doc/man/rel.html">release resource documentation</a>, which I recommend you glance over now. The release specification I&#8217;ve created for the ErlyBank release is:</p>
<div class="code">
<pre>{release, {"eb_rel", "1"},
          {erts, "5.6.3"},
          [{kernel, "2.12.3"},
           {stdlib, "1.15.3"},
           {sasl, "2.1.5.3"},
           {erlybank, "1.0"}]
}.</pre>
</div>
<p>&nbsp;</p>
<p>The contents of the file are saved as <strong>eb_rel-1.rel</strong>. <span class="code inline">eb_rel</span> is the name of the release with &#8220;1&#8243; being the version number. The tuple <span class="code inline">{erts, &#8220;5.6.3&#8243;}</span> specifies the version of the Erlang runtime system that the release is meant for. This can be obtained by opening the Erlang shell and seeing what version you have. Following these tuples, there is a list of more tuples which specify the applications for this release. By convention they are listed in order of dependency but <tt>systools</tt> is smart enough to figure this out on its own when you create the boot script later. </p>
<p>The versions of dependencies can be retrieved by using the <span class="code inline">application:loaded_applications/0</span> method. </p>
<p>One thing you may notice that was added was the dependency on <a href="http://www.erlang.org/doc/apps/sasl/index.html">sasl</a>, which stands for &#8220;System Architecture Support Libraries.&#8221; The sasl application is required for the <a href="http://www.erlang.org/doc/man/release_handler.html">release handler</a> module which is used to install releases into a system. </p>
<h2>Creating a Boot Script</h2>
<p>The purpose of the release specification file is create a boot script that we will use to boot up the entire release quickly and easily. To create the boot script, run the following commands:</p>
<div class="code">
<pre>Chip ~/.../6_release_management: erl -pa ./ebin
Erlang (BEAM) emulator version 5.6.3 [source] [async-threads:0] [kernel-poll:false]                                     

Eshell V5.6.3  (abort with ^G)
1> systools:make_script("eb_rel-1", [local]).
ok</pre>
</div>
<p>&nbsp;</p>
<p>The important thing is that the Erlang shell is started by appending <strong>ebin</strong> to the code path. This is what the <tt>pa</tt> flag does. This is so that the <tt>systools</tt> module can find the erlybank.app file.</p>
<p>Once the shell is open, the systools:make_script/2 method is used to create the boot script. The make_script method accepts as its first argument the name of the release spec file without the extension, and it is expected to be in the current working directory. The second argument is a list of options. The option specified here, <span class="code inline">local</span>, uses the complete path of where the dependency applications are found instead of using variables such as <tt>$ROOT</tt>. This is useful for testing in a development environment. When you&#8217;re ready to package it for true release, omit this option. </p>
<p>If the result of calling the function is <span class="code inline">ok</span>, then you should find a eb_rel-1.boot file in the current working directory. This file is used to start the Erlang system. </p>
<h2>Starting the System with the Boot File</h2>
<p>Remember how easy it was to start the ErlyBank system using <span class="code inline">application:start/1</span>? Well now its even easier by typing the following into the shell:</p>
<div class="code">
<pre>erl -boot eb_rel-1</pre>
</div>
<p>&nbsp;</p>
<p>The Erlang system will locate the boot file specified and will follow it to startup the system. You can test that it worked by using the ErlyBank server to create accounts, make deposits, etc. </p>
<p>To shut down the system, use the normal <tt>q()</tt> command in the shell. All processes will be gracefully stopped.</p>
<h2>Packaging the Release</h2>
<p>The final step is to make the system a nice single package that can be carried around different systems to ease in setup and installation. This can all be done in a single step now that we already have the correct directory structure and a compiled boot script.</p>
<div class="code">
<pre>4> systools:make_tar("eb_rel-1").
ok</pre>
</div>
<p>&nbsp;</p>
<p>In the working directory, there should now be an <strong>eb_rel-1.tar.gz</strong>. That&#8217;s all there is to it!</p>
<h2>Installing a Packaged Release</h2>
<p>To install the packaged release, we first need to copy the tar.gz package we created earlier into the <tt>$ROOT/releases</tt> directory. <tt>$ROOT</tt> can be determined by running <span class="code inline">code:root_dir().</span>. Next, start up and Erlang shell and make sure the <tt>sasl</tt> application is started so we can use the release_handler module. Also, make sure the shell is running with valid permissions to make changes to the <tt>$ROOT</tt> directory. This may require running <tt>erl</tt> with <tt>sudo</tt>. </p>
<div class="code">
<pre>3> release_handler:unpack_release("eb_rel-1").
{ok,"1"} </pre>
</div>
<p>&nbsp;</p>
<p>The unpack_release method does just what it says. It unpacks the package file, copying the libs to the <span class="code inline">code:lib_dir()</span> and created a proper release directory. Since this is the initial release, there is no need to &#8220;install&#8221; it, as its already done. </p>
<p>Now restart the Erlang shell, start sasl, and you should now be able to start erlybank with <span class="code inline">application:start(erlybank)</span> anywhere! The system has been installed!</p>
<p>Alternatively you can start the ErlyBank application with a single command:</p>
<div class="code">
<pre>erl -boot $ROOT/releases/1/start</pre>
</div>
<p>&nbsp;</p>
<p><strong>$ROOT</strong> must be replaced with the root directory of the Erlang install!</p>
<h2>Final Notes</h2>
<p>In this article I introduced creating a basic release, covering topics such as creating boot scripts, packaging a release, and installing a release. The real power of releases, however, comes at the ability to perform system upgrades to a running system, and this will be covered in the next, and final, article in the series. </p>
<p>If you wish to download all the files as of the end of this post, I have <a href="http://spawnlink.com/wp-content/uploads/2008/09/erlybank-part6-complete.zip">zipped them up here</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://spawnlink.com/articles/an-introduction-to-releases-with-erlybank/feed/</wfw:commentRss>
		<feedburner:origLink>http://spawnlink.com/articles/an-introduction-to-releases-with-erlybank/</feedburner:origLink></item>
		<item>
		<title>Bundling ErlyBank as an Application</title>
		<link>http://feeds.feedburner.com/~r/spawn_link/~3/393304430/</link>
		<comments>http://spawnlink.com/articles/bundling-erlybank-as-an-application/#comments</comments>
		<pubDate>Mon, 15 Sep 2008 15:38:42 +0000</pubDate>
		<dc:creator>Mitchell</dc:creator>
		
		<category><![CDATA[Uncategorized]]></category>

		<category><![CDATA[application]]></category>

		<category><![CDATA[erlang]]></category>

		<category><![CDATA[erlybank]]></category>

		<category><![CDATA[otp introduction]]></category>

		<guid isPermaLink="false">http://spawnlink.com/?p=111</guid>
		<description><![CDATA[This is the fifth article in the otp introduction series. If you haven&#8217;t yet, I recommend you start with the first article which talks about gen_server and lays the foundation for our bank system. If you&#8217;re a quick learner, you can read the completed erlang files so far: eb_atm.erl, eb_event_manager.erl, eb_server.erl, eb_sup.erl, and eb_withdrawal_handler.erl.
The Scenario: [...]]]></description>
			<content:encoded><![CDATA[<p>This is the fifth article in the <a href="http://spawnlink.com/articles/tag/otp-introduction/">otp introduction series</a>. If you haven&#8217;t yet, I recommend you <a href="http://spawnlink.com/articles/an-introduction-to-gen_server-erlybank">start with the first article</a> which talks about gen_server and lays the foundation for our bank system. If you&#8217;re a quick learner, you can read the completed erlang files so far: <a href="http://spawnlink.com/otp-intro-5-application-eb-atm/">eb_atm.erl</a>, <a href="http://spawnlink.com/otp-intro-5-applications-eb-event-manager-start/">eb_event_manager.erl</a>, <a href="http://spawnlink.com/otp-intro-5-applications-eb-server-start/">eb_server.erl</a>, <a href="http://spawnlink.com/otp-intro-5-application-eb-sup-start/">eb_sup.erl</a>, and <a href="http://spawnlink.com/otp-intro-5-applications-eb-withdrawal-handle/">eb_withdrawal_handler.erl</a>.</p>
<p><strong>The Scenario:</strong> The ErlyBank system is in a nice state right now with everything wrapped up under the supervisor, but ErlyBank is pressuring us to come up with a package which specifies an overall version so the system can be upgraded as a whole and can be controlled easily. They&#8217;ve commissioned us to do this task. </p>
<p><strong>The Result:</strong> Erlang/OTP has a built-in module for making a set of modules which achieve some set of functionality into an <em>application</em>. An application can be started and stopped as a unit and can easily be reused in other systems. </p>
<p><span id="more-111"></span></p>
<h2>What is an application?</h2>
<p>An application consists of a typical OTP-style callback module and an application resource file which tells the Erlang system how to handle the application. In every Erlang runtime there is an <em>application controller</em> process, which stores the information for every loaded application resource and manages the processes if they have started. Note that the application controller manager is not responsible and will not restart your applications if they terminate. It merely stores process information to know whether or not the application is running. </p>
<p>There are only two callbacks for the application callback module:</p>
<ul>
<li><strong>start/2</strong> - Called when an application is starting to initialize the processes that are part of that application. In a proper Erlang/OTP application, this will usually start a supervisor process which manages the other processes. </li>
<li><strong>stop/1</strong> - Called when an application is stopping so that the processes associated with an application can stop. This usually involves stopping the overall supervisor process for the application.</li>
</ul>
<h2>Application Callback Module</h2>
<p>A skeleton for an application module <a href="http://spawnlink.com/otp-intro-5-applications-eb-app-skeleton/">can be viewed here</a>. As you can see there are only two methods: the behavior methods. </p>
<p>So save that skeleton as eb_app.erl and let&#8217;s get it working with our ErlyBank system!</p>
<h2>The Application Start Callback</h2>
<p>Based on the skeleton, you&#8217;ll probably be able to figure out how to do this on your own, but if you need some guidance, then continue reading this paragraph. Here is the start method for eb_app:</p>
<div class="code">
<pre>
<span style="color: #f0dfaf;">start</span>(<span style="color: #f0dfaf;">_Type</span>, <span style="color: #f0dfaf;">_StartArgs</span>) -&gt;
  <span style="color: #f0dfaf; font-weight: bold;">case</span> eb_sup:start_link() <span style="color: #f0dfaf; font-weight: bold;">of</span>
    {ok, <span style="color: #f0dfaf;">Pid</span>} -&gt;<span style="color: #f0dfaf;"> </span>
      {ok, <span style="color: #f0dfaf;">Pid</span>};
    <span style="color: #f0dfaf;">Error</span> -&gt;
      <span style="color: #f0dfaf;">Error</span>
  <span style="color: #f0dfaf; font-weight: bold;">end</span>.</pre>
</div>
<p>&nbsp;</p>
<p>To start the application, all we have to do is start the supervisor. The application behavior requires us to return <span class="code inline">{ok, Pid}</span> on success so it can verify that this application is running. <span class="code inline">Type</span> is used to tell us why we&#8217;re starting, and is usually just &#8220;normal.&#8221; If we write a distributed application, then it can also signify that this application is starting due to failover and takeover, but that won&#8217;t be covered in this introductory article. </p>
<p>Also, start arguments may be specified in the application resource file, but we won&#8217;t be using them for ErlyBank so we mark the variable as unused. </p>
<h2>The Application Stop Callback</h2>
<p>The stop callback is even easier than the start! </p>
<div class="code">
<pre>
<span style="color: #f0dfaf;">stop</span>(<span style="color: #f0dfaf;">_State</span>) -&gt;
  <span style="color: #f0dfaf; font-weight: bold;">exit</span>(<span style="color: #f0dfaf; font-weight: bold;">whereis</span>(eb_sup), shutdown).</pre>
</div>
<p>&nbsp;</p>
<p>In the <a href="http://spawnlink.com/articles/using-supervisors-to-keep-erlybank-afloat/">article on supervisors </a>, I made a subtle hint to exit with <span class="code inline">kill</span> to test that the supervisors worked. The kill message is actually a brutal kill and doesn&#8217;t call any graceful termination methods. In the stop method of the applicaton, we use the <span class="code inline">shutdown</span> message which stops the supervisor gracefully.</p>
<p>There is one last piece to the application before we can actually run it, and that is to create the application resource file. But eb_app.erl is completed and <a href="http://spawnlink.com/otp-intro-5-application-eb-app-completed/">can be viewed here</a>.</p>
<h2>Application Resource File Syntax</h2>
<p>The application resource file is suffixed with <strong>.app</strong> but is actually just a file containing some erlang terms. Copied directly from the <a href="http://www.erlang.org/doc/man/app.html">application documentation</a>:</p>
<div class="code">
<pre>{application, Application,
  [{description,  Description},
   {id,           Id},
   {vsn,          Vsn},
   {modules,      Modules},
   {maxP,         MaxP},
   {maxT,         MaxT},
   {registered,   Names},
   {included_applications, Apps},
   {applications, Apps},
   {env,          Env},
   {mod,          Start},
   {start_phases, Phases}]}.

             Value                Default
             -----                -------
Application  atom()               -
Description  string()             ""
Id           string()             ""
Vsn          string()             ""
Modules      [Module]             []
MaxP         int()                infinity
MaxT         int()                infinity
Names        [Name]               []
Apps         [App]                []
Env          [{Par,Val}]          []
Start        {Module,StartArgs}   undefined
Phases       [{Phase,PhaseArgs}]  undefined
  Module = Name = App = Par = Phase = atom()
  Val = StartArgs = PhaseArgs = term()</pre>
</div>
<p>&nbsp;</p>
<p>As you can see, the application file contains an Erlang tuple which has various information about the application which the Erlang runtime will use to know how to handle the application. All the options, the tuples contained within the list, are optional, and if any are omitted, their respective default value will be used, which are listed above, also. </p>
<p>First, <span class="code inline">Application</span> is an atom representing the name of the application. This atom must be the same as the filename of the application resource file. So if they resource file is named &#8220;erlybank.app,&#8221; then the application name is &#8220;erlybank.&#8221;</p>
<p>Those are a lot of options, but the ones that are important are the options that <a href="http://www.erlang.org/doc/man/systools.html">systools</a> requires, because we will be using that module in the future to handle upgrading and packaging our system! systools requires description, vsn, modules, registered, and applications. </p>
<p><span class="code inline">Description</span> is a one line description of the application. That&#8217;s it!</p>
<p><span class="code inline">vsn</span> is the version number represented as a string. It can be anything you want! There is no standard format.</p>
<p><span class="code inline">modules</span> are all modules introduced by this application. These are the modules you wrote specifically for this application, ignoring any modules in any other applications.</p>
<p><span class="code inline">registered</span> is a list of names of all registered processes. systools will use this in the future to automatically detect any clashing process names in a system.</p>
<p><span class="code inline">applications</span> is a list of applications which must be started before this application. Include the application name of any external modules you use here so systools can create proper boot scripts in the future for the application.</p>
<h2>ErlyBank&#8217;s Application Resource File</h2>
<p>The following is the contents of the application resource file I made for ErlyBank:</p>
<div class="code">
<pre>{application, erlybank,
  [{description, "ErlyBank system."},
  {vsn, "1.0"},
  {modules, [eb_app, eb_sup, eb_server, eb_atm, eb_event_manager, eb_withdrawal_handler]},
  {registered, [eb_sup, eb_server, eb_atm, eb_event_manager]},
  {applications, [kernel, stdlib]},
  {mod, {eb_app, []}}
]}.</pre>
</div>
<p>&nbsp;</p>
<p>All the systools required options are included in addition to mod, which specifies the module that is used to start the application. </p>
<p>As application dependencies I explicitly list kernel and stdlib, but even if I left that list blank, they would be started anyways, as they&#8217;re required by the Erlang system. I just like to make everything as explicit as possible so when I come back to look at code later, I know <em>exactly</em> what is happening. </p>
<p>Save the above code as <strong>erlybank.app</strong> and we&#8217;re ready to test run it!</p>
<h2>Loading and Running the Application From the Shell</h2>
<p>First, you can use the loaded_applications method to check what applications are already loaded into the Erlang system. This is the output from my shell:</p>
<div class="code">
<pre>
<span style="color: #dfaf8f; font-weight: bold;">14&gt; </span><span style="color: #f0dfaf; font-weight: bold;">application:loaded_applications().</span>
[{kernel,"ERTS  CXC 138 10","2.12.3"},
 {stdlib,"ERTS  CXC 138 10","1.15.3"}]</pre>
</div>
<p>&nbsp;</p>
<p>As you can see, it&#8217;s not loaded yet. But actually, if you run the start method and application sees that that application spec is not loaded yet, it will attempt to load it itself. But to show you how this works, I will run it explicitly:</p>
<div class="code">
<pre>
<span style="color: #dfaf8f; font-weight: bold;">1&gt; </span><span style="color: #f0dfaf; font-weight: bold;">application:load(erlybank).</span>
ok
<span style="color: #dfaf8f; font-weight: bold;">2&gt; </span><span style="color: #f0dfaf; font-weight: bold;">application:loaded_applications().</span>
[{kernel,"ERTS  CXC 138 10","2.12.3"},
 {erlybank,"ErlyBank system.","1.0"},
 {stdlib,"ERTS  CXC 138 10","1.15.3"}]</pre>
</div>
<p>&nbsp;</p>
<p>The <span class="code inline">load</span> method finds the app file locally and loads it. It does not load any of the actual Erlang code for ErlyBank, yet. After loading the spec, I ran loaded_applications again and you can easily see that the ErlyBank application is listed.</p>
<p>To start the ErlyBank system, just run <span class="code inline">application:start(erlybank)</span> and to stop it, run the stop method with erlybank as the parameter. Play around with the bank system just to make sure it&#8217;s working. <img src='http://spawnlink.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<h2>Final Notes</h2>
<p>In this article I talked about <a href="http://www.erlang.org/doc/man/application.html">application</a>. I explained what an application is, the files that are required for an application, how to load an application, and how to start and stop an application. I breezed over the options required by systools, which we will use in a future article. </p>
<p>And that is the end of article five in the Erlang/OTP introduction series. The sixth article will be published in an another few days and will cover release management, including topics such as creating boot scripts, packaging applications, and more.</p>
]]></content:encoded>
			<wfw:commentRss>http://spawnlink.com/articles/bundling-erlybank-as-an-application/feed/</wfw:commentRss>
		<feedburner:origLink>http://spawnlink.com/articles/bundling-erlybank-as-an-application/</feedburner:origLink></item>
		<item>
		<title>Using Supervisors to Keep ErlyBank Afloat</title>
		<link>http://feeds.feedburner.com/~r/spawn_link/~3/391583966/</link>
		<comments>http://spawnlink.com/articles/using-supervisors-to-keep-erlybank-afloat/#comments</comments>
		<pubDate>Sat, 13 Sep 2008 14:46:24 +0000</pubDate>
		<dc:creator>Mitchell</dc:creator>
		
		<category><![CDATA[Uncategorized]]></category>

		<category><![CDATA[beginner]]></category>

		<category><![CDATA[erlang]]></category>

		<category><![CDATA[erlybank]]></category>

		<category><![CDATA[otp]]></category>

		<category><![CDATA[otp introduction]]></category>

		<category><![CDATA[supervisor]]></category>

		<guid isPermaLink="false">http://spawnlink.com/?p=87</guid>
		<description><![CDATA[This is the fourth article in the otp introduction series. If you haven&#8217;t yet, I recommend you start with the first article which talks about gen_server and lays the foundation for our bank system. If you are a quick learner, you can view the currently completed erlang files so far: eb_server.erl, eb_event_manager.erl, eb_withdrawal_handler.erl, and eb_atm.erl. [...]]]></description>
			<content:encoded><![CDATA[<p>This is the fourth article in the <a href="http://spawnlink.com/articles/tag/otp-introduction/">otp introduction series</a>. If you haven&#8217;t yet, I recommend you <a href="http://spawnlink.com/articles/an-introduction-to-gen_server-erlybank">start with the first article</a> which talks about gen_server and lays the foundation for our bank system. If you are a quick learner, you can view the currently completed erlang files so far: <a href="http://spawnlink.com/otp-intro-4-supervisor-eb-server/">eb_server.erl</a>, <a href="http://spawnlink.com/otp-intro-4-supervisors-eb-event-manager/">eb_event_manager.erl</a>, <a href="http://spawnlink.com/otp-intro-4-supervisor-eb-withdrawal-handler/">eb_withdrawal_handler.erl</a>, and <a href="http://spawnlink.com/otp-intro-4-supervisors-eb-atm/">eb_atm.erl</a>. </p>
<p><strong>The Scenario:</strong> The thing that makes us feel good about banks and ATMs is that they are always there. We can deposit and get money whenever want, 24 hours a day, using an ATM. Or we can go into any bank branch when they&#8217;re open, and know we have complete access to our funds. To achieve this security, we need to make sure that our system to run ErlyBank always stays working: the processes must always be running. ErlyBank has commissioned us to achieve this goal. 100% uptime! (Or as close to that as we can get) </p>
<p><strong>The Result:</strong> Using an OTP <a href="http://www.erlang.org/doc/man/supervisor.html">supervisor</a>, we will create a process whose responsibility it is to watch the running processes and make sure they stay up. </p>
<p><span id="more-87"></span></p>
<h2>What is a Supervisor?</h2>
<p>A supervisor is a process which monitors what are called <em>child</em> processes. If a child process goes down, it uses that child&#8217;s <em>restart strategy</em> to restart the process. This system can keep Erlang systems running forever.</p>
<p>The supervisor is part of what is called a <em>supervision tree</em>. A well written Erlang/OTP application starts with a root supervisor, which watches over child supervisors, which in turn watch over more supervisors or processes. The idea is that if a supervisor goes down, the parent supervisor will restart it, all the way up to the root supervisor. The Erlang runtime has a <em>heart</em> option which will watch the entire system and restart it if the root supervisor were to die. This way, the supervision tree will always be intact.</p>
<p>There is only <strong>one callback</strong> for a supervisor: <span class="code inline">init/1</span>. Its role is to return a list of child processes and restart strategies for each process, so the supervisor knows what to watch and what actions to take if something goes wrong.</p>
<h2>Decoupling eb_server and the Event Manager</h2>
<p>One of the things I did in the last article on gen_event was explicitly start the event manager process in the init method of eb_server. I did this at the time because it was the only option I really had if I wanted to easily start the server with that dependency. But now that we&#8217;re going to be implementing startup and stop using a supervisor, we can start the event manager within the supervisor tree. So let&#8217;s take out the eb_event_manager startup from the server.</p>
<p>To do this, simply remove line 84 from eb_server.erl, which is the startup for the event manager. Additionally, I added at this location the add_handler call to add eb_withdrawal_handler to the event manager. So the init method of eb_server now looks like this:</p>
<div class="code">
<pre><span style="color: #f0dfaf;">init</span>([]) -&gt;
  eb_event_manager:add_handler(eb_withdrawal_handler),
  {ok, dict:new()}.</pre>
</div>
<p>&nbsp;</p>
<p><a href="http://spawnlink.com/otp-intro-4-supervisors-eb-server-event/">Click here</a> to view eb_server.erl after this change.</p>
<h2>The Supervisor Skeleton</h2>
<p>A basic skeleton for writing a supervisor can be <a href="http://spawnlink.com/otp-intro-4-supervisors-eb-sup-skeleton/">viewed here</a>. As you can see, it has a start method and has a basic init method, which is returning a restart strategy and a fake child spec for now. Restart strategies and child specifications are covered in the next section of this article.</p>
<p>Save the skeleton as <strong>eb_sup.erl</strong>. The naming of this file is another convention. The supervisor for a certain group is always suffixed with &#8220;_sup.&#8221; Its not mandatory but its standard practice.</p>
<h2>Restart Strategies</h2>
<p>A supervisor has one restart strategy, which it uses in conjunction with the child specification, to determine what it should in case one of the supervisor&#8217;s child processes dies. The following are the possible restart strategies:</p>
<ul>
<li><span class="code inline">one_for_one</span> - When one of the child processes dies, the supervisor restarts it. Other child processes aren&#8217;t affected.</li>
<li><span class="code inline">one_for_all</span> - When one of the child processes dies, all the other child processes are terminated, and then all restarted.</li>
<li><span class="code inline">rest_for_one</span> - When one of the child processes dies, the &#8220;rest&#8221; of the child processes defined after it in the child specification list are terminated, then all restarted.</li>
</ul>
<p>When specifying the restart strategy, it takes the following format:</p>
<div class="code">
<pre>{RestartStrategy, MaxRetries, MaxTime}</pre>
</div>
<p>&nbsp;</p>
<p>This is very simple to understand after you wrap your mind around the english: If a child process is restarted more than MaxRetries times in MaxTime seconds, then the supervisor terminates all child processes and then itself. This is to avoid an infinite loop of restarting a child process. </p>
<h2>Child Specification Syntax and Concepts</h2>
<p>The init callback for the supervisor is responsible for returning a list of child specifications. These specs tell the supervisor which processes to start and how to start them. The supervisor starts the processes in order from left to right (beginning of the list to the end of the list). A restart strategy is a tuple with the following format:</p>
<div class="code">
<pre>{Id, StartFunc, Restart, Shutdown, Type, Modules}

Definitions:
Id = term()
 StartFunc = {M,F,A}
  M = F = atom()
  A = [term()]
 Restart = permanent | transient | temporary
 Shutdown = brutal_kill | int()>=0 | infinity
 Type = worker | supervisor
 Modules = [Module] | dynamic
  Module = atom()</pre>
</div>
<p>&nbsp;</p>
<p><span class="code inline">Id</span> is only used internally by the supervisor to store the child specification, but its a general convention to have the ID be the same as the module name of the child process unless you&#8217;re starting multiple instances of your module, in that case suffix the ID with the number. </p>
<p><span class="code inline">StartFunc</span> is a tuple in the format of <span class="code inline">{Module, Function, Args}</span> which specifies the function to call to start the process. <strong>REALLY IMPORTANT:</strong> The start function <em>must</em> create <em>and link</em> to the process, and should return <span class="code inline">{ok, Pid}</span>, <span class="code inline">{ok, Pid, Other}</span>, or <span class="code inline">{error, Reason}</span>. The normal OTP start_link methods follow this rule. But if you implement a module which starts its own custom processes, make sure you use <strong>spawn_link</strong> to start them (hence the blog title, if you didn&#8217;t know).</p>
<p><span class="code inline">Restart</span> is one of three atoms, defined above in the code block. If restart is &#8220;permanent&#8221; then the process is always restarted. If the value is &#8220;temporary&#8221; then the process is never restarted. And if the value is &#8220;transient&#8221; the process is only restarted if it terminated abnormally.</p>
<p><span class="code inline">Shutdown</span> tells the supervisor how to terminate child processes. The atom &#8220;brutal_kill&#8221; shuts the child process down without calling the terminate method. Any integer greater than zero represents a timeout for a graceful shutdown. And the atom &#8220;infinity&#8221; will gracefully shutdown the process and wait forever for it to stop. </p>
<p><span class="code inline">Type</span> tells the supervisor whether the child is another supervisor or any other process. If it is a supervisor, use the atom &#8220;supervisor&#8221; otherwise use the atom &#8220;worker.&#8221;</p>
<p><span class="code inline">Modules</span> is either a list of modules this process affects or the atom &#8220;dynamic.&#8221; 95% of the time, you will just use the single OTP callback module in a list for this value. You use &#8220;dynamic&#8221; if the process is a gen_event process, since the modules it affects are dynamic (multiple handlers that can&#8217;t be determined right away). This list is only used for release handling and is not important in the context of this article, but will be used in a future article about release handling.</p>
<p>Whew! That was a lot of information to soak up in so little time. It took me quite a long time to remember the format of the child specs and the different restart strategies, so don&#8217;t sweat it if you can&#8217;t remember. You can always reference this information on the <a href="http://www.erlang.org/doc/man/supervisor.html">supervisor</a> manual page. </p>
<h2>Event Manager Child Spec</h2>
<p>The first thing we want to start is the event manager, since the server depends on it. The child specification looks something like this:</p>
<div class="code">
<pre>
  <span style="color: #f0dfaf;">EventManager</span> = {eb_event_manager,{eb_event_manager, start_link,[]},
            permanent,2000,worker,dynamic}.</pre>
</div>
<p>&nbsp;</p>
<p>After reading the child specification syntax section this piece of code should be fairly straightforward. You will probably need to go back and reference the spec to see what each parameter does, and that is completely normal! Its better to go back and understand the code than nod your head and forget it in a few minutes. The one &#8220;weird&#8221; thing in the spec, I suppose, is the module list is set to &#8220;dynamic.&#8221; This is because it is a gen_event and the number of modules it uses is dynamic because of the handlers plugging into it. In other cases, you would list out all modules the process uses. </p>
<p>Here is the init method after adding this child spec:</p>
<div class="code">
<pre><span style="color: #f0dfaf;">init</span>([]) -&gt;
  <span style="color: #f0dfaf;">EventManager</span> = {eb_event_manager,{eb_event_manager, start_link,[]},
            permanent,2000,worker,dynamic},
  {ok,{{one_for_one,5,10}, [<span style="color: #f0dfaf;">EventManager</span>]}}.</pre>
</div>
<p>&nbsp;</p>
<p>I like to assign each child spec to a variable, and then use these variables for the return value, rather than putting the specs directly into the return value. One of my biggest peeves in Erlang is when a programmer nests lists and tuples so deeply that you can&#8217;t see where one ends and another begins, so I recommend you assign each to a variable too. </p>
<p>If you compile and run the supervisor now (I think you should!), after running the start_link method of the supervisor, type <span class="code inline">whereis(eb_event_manager)</span> and it should return the pid of the event manager process. Then, if you kill the supervisor, by doing <span class="code inline">exit(whereis(eb_sup), kill)</span>, and then try to get the eb_event_manager pid again, you should get the result that it is undefined, since the process has been killed. </p>
<p>Also, for fun, kill the eb_event_manager while it is running under the supervisor. Wait a couple seconds and check the process again. It should be back up!</p>
<h2>Server and ATM</h2>
<p>With the child spec reference and the example given above, you should have enough know-how to get the server and ATM up and running. So if you feel like challenging yourself, do that now. If not, I&#8217;ve posted the specs to get both up below:</p>
<div class="code">
<pre><span style="color: #f0dfaf;">Server</span> = {eb_server, {eb_server, start_link, []},
            permanent,2000,worker,[eb_server]},
  <span style="color: #f0dfaf;">ATM</span> = {eb_atm, {eb_atm, start_link, []},
         permanent,2000,worker,[eb_atm]},</pre>
</div>
<p>&nbsp;</p>
<p>After you create these specs, add them to the list returned by the init method. Make sure that you add them <em>after</em> the event manager.</p>
<p>You can view the completed eb_sup.erl by <a href="http://spawnlink.com/otp-intro-4-supervisors-eb-sup-completed/">clicking here</a>.</p>
<h2>Adding and Removing Children at Runtime</h2>
<p>Unfortunately I couldn&#8217;t think of a witty scenario to fit this into ErlyBank, but I felt that it was important to mention that you can dynamically add and remove child specs to an already running supervisor process by using the <a href="http://www.erlang.org/doc/man/supervisor.html#start_child-2">start_child</a> and <a href="http://www.erlang.org/doc/man/supervisor.html#delete_child-2">delete_child</a> methods. </p>
<p>They are pretty straightforward so I won&#8217;t repeat what the manual says here and I&#8217;ve linked the methods so you can go directly to them to check them out.</p>
<h2>Final Notes</h2>
<p>In this article about <a href="http://www.erlang.org/doc/man/supervisor.html">supervisors</a> I introduced concepts such as the supervisor tree, restart strategies, child specifications, and dynamically adding and removing children. </p>
<p>This concludes article four of the Erlang/OTP introduction series. Article five is already written and queued up for publishing in another few days and will introduce <a href="http://www.erlang.org/doc/man/application.html">applications</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://spawnlink.com/articles/using-supervisors-to-keep-erlybank-afloat/feed/</wfw:commentRss>
		<feedburner:origLink>http://spawnlink.com/articles/using-supervisors-to-keep-erlybank-afloat/</feedburner:origLink></item>
		<item>
		<title>An introduction to gen_event: Account Notifications</title>
		<link>http://feeds.feedburner.com/~r/spawn_link/~3/388734949/</link>
		<comments>http://spawnlink.com/articles/an-introduction-to-gen_event-account-notifications/#comments</comments>
		<pubDate>Wed, 10 Sep 2008 15:03:47 +0000</pubDate>
		<dc:creator>Mitchell</dc:creator>
		
		<category><![CDATA[Uncategorized]]></category>

		<category><![CDATA[beginner]]></category>

		<category><![CDATA[erlang]]></category>

		<category><![CDATA[erlybank]]></category>

		<category><![CDATA[gen_event]]></category>

		<category><![CDATA[otp introduction]]></category>

		<guid isPermaLink="false">http://spawnlink.com/?p=66</guid>
		<description><![CDATA[This is the third article in the otp introduction series. If you haven&#8217;t yet, I recommend you start with the first article which talks about gen_server and lays the foundation for our bank system. Again, if you&#8217;re a quick learner, you can look at the completed eb_atm.erl and eb_server.erl here.
The Scenario: With central server and [...]]]></description>
			<content:encoded><![CDATA[<p>This is the third article in the <a href="http://spawnlink.com/articles/tag/otp-introduction/">otp introduction series</a>. If you haven&#8217;t yet, I recommend you <a href="http://spawnlink.com/articles/an-introduction-to-gen_server-erlybank">start with the first article</a> which talks about gen_server and lays the foundation for our bank system. Again, if you&#8217;re a quick learner, you can <a href="http://spawnlink.com/otp-intro-2-gen-fsm-eb-atm-cancel/">look at the completed eb_atm.erl</a> and <a href="http://spawnlink.com/otp-intro-2-gen-fsm-eb-server-authorization/">eb_server.erl</a> here.</p>
<p><strong>The Scenario:</strong> With central server and ATM software in place, ErlyBank is started to feel good about their technological foundation. But as a security measure, one of their competitors, they&#8217;d like a system implemented which dispatches notifications when a withdrawal over a certain amount is executed. They want the ability to change the withdrawal notification amount threshold during runtime. They&#8217;ve chosen to hire us to streamline this into the current system software. </p>
<p><strong>The Result:</strong> We&#8217;ll create an event-based notification system using <a href="http://www.erlang.org/doc/man/gen_event.html">gen_event</a>. This will give us a base foundation for creating more notifications in the future, while allowing us to easily plug-in to the current server software.</p>
<p><span id="more-66"></span></p>
<h2>What is gen_event?</h2>
<p><a href="http://www.erlang.org/doc/man/gen_event.html">gen_event</a> is an Erlang/OTP behavior module for implementing event handling functionality. This works by running an event manager process, with many handler processes running along-side it. The event manager receives events from other processes, and each handler in turn is notified about the events, and can do what it pleases with them.</p>
<p>The callbacks expected for a gen_event handler module are:</p>
<ul>
<li><strong>init/1</strong> - Initializes the handler.</li>
<li><strong>handle_event/2</strong> - Handles any events sent to the notification manager it is listening to. </li>
<li><strong>handle_call/2</strong> - Handles an event which is sent as a call to the notification manager. A call in this context is the same as a gen_server call: it blocks until a response is sent.</li>
<li><strong>handle_info/2</strong> - Handles any non-event and non-call messages sent to the handler.</li>
<li><strong>terminate/2</strong> - Called when the handler is quitting so the process can clean up any open resources.</li>
<li><strong>code_change/3</strong> - Called when the module is experiencing a real-time system upgrade. This will not be covered in this article, but it will play a central role of a future article in this series.</li>
</ul>
<p>Compared to the previous two behavior modules covered in this series, there are relatively few callback methods. But gen_event has just as much use and just as much power as the other OTP modules.</p>
<h2>Creating the Event Manager</h2>
<p>First thing we need to do is create the event manager. This is a relatively simple task, since its really just starting a gen_event server and adding a few API methods on top easily add new handlers, send notifications, etc. </p>
<p>View my <a href="http://spawnlink.com/otp-intro-3-gen-event-manager-skeleton/">event manager skeleton here</a>. I will be pasting in snippets from this point on.</p>
<p>As you can see, there is nothing out of the ordinary in the file. The start-up method is the same as every other OTP behavior module. And I&#8217;ve included a basic API to add a handler to the event manager:</p>
<div class="code">
<pre><span style="color: #708070;">%%</span><span style="color: #7f9f7f;">--------------------------------------------------------------------
</span><span style="color: #708070;">%% </span><span style="color: #7f9f7f;">Function: add_handler(Module) -&gt; ok | {'EXIT',Reason} | term()
</span><span style="color: #708070;">%% </span><span style="color: #7f9f7f;">Description: Adds an event handler
</span><span style="color: #708070;">%%</span><span style="color: #7f9f7f;">--------------------------------------------------------------------
</span><span style="color: #f0dfaf;">add_handler</span>(<span style="color: #f0dfaf;">Module</span>) -&gt;
  gen_event:add_handler(?<span style="color: #dca3a3; font-weight: bold;">SERVER</span>, <span style="color: #f0dfaf;">Module</span>, []).</pre>
</div>
<p>&nbsp;</p>
<p>This just adds an event handler located at <span class="code inline">Module</span> to the event manager. And I&#8217;ve also added an easy to use notify method to send along a notification through the event manager:</p>
<div class="code">
<pre><span style="color: #708070;">%%</span><span style="color: #7f9f7f;">--------------------------------------------------------------------
</span><span style="color: #708070;">%% </span><span style="color: #7f9f7f;">Function: notify(Event) -&gt; ok | {error, Reason}
</span><span style="color: #708070;">%% </span><span style="color: #7f9f7f;">Description: Sends the Event through the event manager.
</span><span style="color: #708070;">%%</span><span style="color: #7f9f7f;">--------------------------------------------------------------------
</span><span style="color: #f0dfaf;">notify</span>(<span style="color: #f0dfaf;">Event</span>) -&gt;
  gen_event:notify(?<span style="color: #dca3a3; font-weight: bold;">SERVER</span>, <span style="color: #f0dfaf;">Event</span>).</pre>
</div>
<p>&nbsp;</p>
<p>This also should be pretty easy to understand. It just sends the event along to the event manager. <span class="code inline">gen_event:notify/2</span> is an <strong>asynchronous</strong> request, it will return immediately.</p>
<h2>Hooking the Event Manager Into the Server</h2>
<p>We want to make sure that the event manager is always up before the server starts, so for now we will be explicitly putting the start code into the server module. Later, in another article, we will use supervisor trees to do this for us. Here is my new init code for the server:</p>
<div class="code">
<pre><span style="color: #f0dfaf;">init</span>([]) -&gt;
  eb_event_manager:start_link(),
  {ok, dict:new()}.</pre>
</div>
<p>&nbsp;</p>
<p>Now that we can assume the event manager will be up during the life of the server process, we can dispatch events at certain times. Our client, ErlyBank, wants to know when a deposit over a certain amount occurs. Here is how I hooked this into the server:</p>
<div class="code">
<pre><span style="color: #f0dfaf;">handle_call</span>({withdraw, <span style="color: #f0dfaf;">Name</span>, <span style="color: #f0dfaf;">Amount</span>}, <span style="color: #f0dfaf;">_From</span>, <span style="color: #f0dfaf;">State</span>) -&gt;
  <span style="color: #f0dfaf; font-weight: bold;">case</span> dict:find(<span style="color: #f0dfaf;">Name</span>, <span style="color: #f0dfaf;">State</span>) <span style="color: #f0dfaf; font-weight: bold;">of</span>
    {ok, {<span style="color: #f0dfaf;">_PIN</span>, <span style="color: #f0dfaf;">Value</span>}} <span style="color: #f0dfaf; font-weight: bold;">when</span> <span style="color: #f0dfaf;">Value</span> &lt; <span style="color: #f0dfaf;">Amount</span> -&gt;
      {reply, {error, not_enough_funds}, <span style="color: #f0dfaf;">State</span>};
    {ok, {<span style="color: #f0dfaf;">PIN</span>, <span style="color: #f0dfaf;">Value</span>}} -&gt;
      <span style="color: #f0dfaf;">NewBalance</span> = <span style="color: #f0dfaf;">Value</span> - <span style="color: #f0dfaf;">Amount</span>,
      <span style="color: #f0dfaf;">NewState</span> = dict:store(<span style="color: #f0dfaf;">Name</span>, {<span style="color: #f0dfaf;">PIN</span>, <span style="color: #f0dfaf;">NewBalance</span>}, <span style="color: #f0dfaf;">State</span>),
      <span style="color: #708070;">% </span><span style="color: #7f9f7f;">Send notification
</span>      eb_event_manager:notify({withdraw, <span style="color: #f0dfaf;">Name</span>, <span style="color: #f0dfaf;">Amount</span>, <span style="color: #f0dfaf;">NewBalance</span>}),
      {reply, {ok, <span style="color: #f0dfaf;">NewBalance</span>}, <span style="color: #f0dfaf;">NewState</span>};
    error -&gt;
      {reply, {error, account_does_not_exist}, <span style="color: #f0dfaf;">State</span>}
  <span style="color: #f0dfaf; font-weight: bold;">end</span>;</pre>
</div>
<p>&nbsp;</p>
<p>Now whenever a withdrawal occurs, the event is raised through the event manager too. Remember that the notify method is asynchronous and the event manager and handlers all run on separate processes. This makes all this notification happen concurrently, therefore it won&#8217;t slow down the withdrawal transaction. Of course, if the cpu is being slammed, it may take more time to execute each process, but in theory, they should happen at the same time.</p>
<p>Also notice that I don&#8217;t check here whether the withdrawal is over a certain amount. ErlyBank didn&#8217;t clarify with me what amount they wanted as the threshold, and it would be rather silly to hardcode it into the server process. Its generally a good idea to keep all the logic in the handlers, and just raise the notification. And this is what we will do next!</p>
<p>The entire contents of eb_server.erl can <a href="http://spawnlink.com/otp-intro-3-gen-event-eb-server-events/">be viewed here</a>.</p>
<h2>The Handler Skeleton</h2>
<p>As with all OTP modules, I have a basic skeleton I always start with. The one for event handlers <a href="http://spawnlink.com/otp-intro-3-gen-event-eb-withdrawal-handler-skeleton/">can be viewed here</a>.</p>
<p>One thing that is different about this module is that there is no <span class="code inline">start_link</span> or start method. This is because to add an event handler we will be using the <span class="code inline">eb_event_manager:add_handler(Module)</span> method, which actually starts and spawns the process for us!</p>
<div class="code">
<pre><span style="color: #f0dfaf;">init</span>([]) -&gt;
  {ok, 500}.</pre>
</div>
<p>&nbsp;</p>
<p>The init method for a gen_event handler is similar to all other Erlang/OTP behavior modules in that it returns <span class="code inline">{ok, State}</span> where State represents the state data for the process. In this case we&#8217;ve returned 500, which we will use to signify what the warning threshold for withdrawal notifications is.</p>
<h2>Handling the Withdrawal Notification</h2>
<p>The sole purpose of this event handler is to process the withdrawal notification and do something if the amount withdrawn is over a certain threshold. The event is sent with <span class="code inline">gen_event:notify/2</span> which is an asynchronous message. Asynchronous notifications to handlers are handled in the <span class="code inline">handle_event</span> method. </p>
<div class="code">
<pre><span style="color: #f0dfaf;">handle_event</span>({withdraw, <span style="color: #f0dfaf;">Name</span>, <span style="color: #f0dfaf;">Amount</span>, <span style="color: #f0dfaf;">NewBalance</span>}, <span style="color: #f0dfaf;">State</span>) <span style="color: #f0dfaf; font-weight: bold;">when</span> <span style="color: #f0dfaf;">Amount</span> &gt;= <span style="color: #f0dfaf;">State</span> -&gt;
  io:format(<span style="color: #cc9393;">"WITHDRAWAL NOTIFICATION: ~p withdrew ~p leaving ~p left.~n"</span>, [<span style="color: #f0dfaf;">Name</span>, <span style="color: #f0dfaf;">Amount</span>, <span style="color: #f0dfaf;">NewBalance</span>]),
  {ok, <span style="color: #f0dfaf;">State</span>};
<span style="color: #f0dfaf;">handle_event</span>(<span style="color: #f0dfaf;">_Event</span>, <span style="color: #f0dfaf;">State</span>) -&gt;
  {ok, <span style="color: #f0dfaf;">State</span>}.</pre>
</div>
<p>&nbsp;</p>
<p>Handling the message is simple. We add a matcher to match the withdrawal message, and we add a guard <span class="code inline">when Amount >= State</span> to only get events when the amount withdrawn is above the threshold.</p>
<p>When the amount is above the threshold, we output it to the terminal. </p>
<p>The complete eb_withdrawal_handler.erl can <a href="http://spawnlink.com/otp-intro-3-gen-event-eb-withdrawal-events/">be viewed here</a>.</p>
<h2>Changing the Threshold During Runtime</h2>
<p>ErlyBank also mentioned that they want the ability to change the withdrawal notification amount threshold during runtime. To do this, we will add an API method to the actual handler. Here is the API method:</p>
<div class="code">
<pre><span style="color: #708070;">%%</span><span style="color: #7f9f7f;">--------------------------------------------------------------------
</span><span style="color: #708070;">%% </span><span style="color: #7f9f7f;">Function: change_threshold(Amount) -&gt; {ok, Old, NewThreshold}
</span><span style="color: #708070;">%% </span><span style="color: #7f9f7f;">| {error, Reason}
</span><span style="color: #708070;">%% </span><span style="color: #7f9f7f;">Description: Changes the withdrawal amount threshold during runtime
</span><span style="color: #708070;">%%</span><span style="color: #7f9f7f;">--------------------------------------------------------------------
</span><span style="color: #f0dfaf;">change_threshold</span>(<span style="color: #f0dfaf;">Amount</span>) -&gt;
  gen_event:call(eb_event_manager, ?<span style="color: #dca3a3; font-weight: bold;">MODULE</span>, {change_threshold, <span style="color: #f0dfaf;">Amount</span>}).</pre>
</div>
<p>&nbsp;</p>
<p>This introduces a new gen_event method, the call method. This method sends a request to a specific handler and expects a response, and therefore is <strong>synchronous</strong>. The arguments are: <span class="code inline">call(EventManager, Handler, Message)</span>. So for our arguments we put the event manager module, which that process is registered as, as the first parameter. We put the handler module as the second parameter, and we send a message to change the threshold. </p>
<p>We handle this request in a callback <span class="code inline">handle_call/2</span>:</p>
<div class="code">
<pre><span style="color: #f0dfaf;">handle_call</span>({change_threshold, <span style="color: #f0dfaf;">Amount</span>}, <span style="color: #f0dfaf;">State</span>) -&gt;
  io:format(<span style="color: #cc9393;">"NOTICE: Changing withdrawal threshold from ~p to ~p~n"</span>, [<span style="color: #f0dfaf;">State</span>, <span style="color: #f0dfaf;">Amount</span>]),
  {ok, {ok, <span style="color: #f0dfaf;">State</span>, <span style="color: #f0dfaf;">Amount</span>}, <span style="color: #f0dfaf;">Amount</span>};
<span style="color: #f0dfaf;">handle_call</span>(<span style="color: #f0dfaf;">_Request</span>, <span style="color: #f0dfaf;">State</span>) -&gt;
  <span style="color: #f0dfaf;">Reply</span> = ok,
  {ok, <span style="color: #f0dfaf;">Reply</span>, <span style="color: #f0dfaf;">State</span>}.</pre>
</div>
<p>&nbsp;</p>
<p>We first output to the terminal that the threshold is changing, and then we reply with <span class="code inline">{ok, OldThreshold, NewThreshold}</span> and set the new state data to the new threshold. Upon receiving the next withdrawal notification, the handler will begin using the new threshold! <img src='http://spawnlink.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>The complete eb_withdrawal_handler <a href="http://spawnlink.com/otp-intro-3-gen-event-eb-withdrawal-change-threshold/">can be viewed here</a>.</p>
<h2>Final Notes</h2>
<p>In this article about <a href="http://www.erlang.org/doc/man/gen_event.html">gen_event</a> I introduced writing an event manager, dispatch events, writing an event handler, processing those events, and calling an event handler. The only thing I didn&#8217;t really cover which is part of gen_event is the ability for an event handler to remove itself or swap itself with another handler. The reason for this is because I don&#8217;t have much experience with these myself in a production environment. I haven&#8217;t found a position yet where I&#8217;ve needed to use them. But if you wish to learn about them, check out the <a href="http://www.erlang.org/doc/man/gen_event.html">gen_event manual page</a>.</p>
<p>And that concludes part three of the Erlang/OTP introduction series. Article four is queued up for publishing in a few days and will cover <a href="http://www.erlang.org/doc/man/supervisor.html">supervisors</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://spawnlink.com/articles/an-introduction-to-gen_event-account-notifications/feed/</wfw:commentRss>
		<feedburner:origLink>http://spawnlink.com/articles/an-introduction-to-gen_event-account-notifications/</feedburner:origLink></item>
		<item>
		<title>An introduction to gen_fsm: ErlyBank’s ATM</title>
		<link>http://feeds.feedburner.com/~r/spawn_link/~3/386748115/</link>
		<comments>http://spawnlink.com/articles/an-introduction-to-gen_fsm-erlybanks-atm/#comments</comments>
		<pubDate>Mon, 08 Sep 2008 14:59:50 +0000</pubDate>
		<dc:creator>Mitchell</dc:creator>
		
		<category><![CDATA[Uncategorized]]></category>

		<category><![CDATA[beginner]]></category>

		<category><![CDATA[erlang]]></category>

		<category><![CDATA[erlybank]]></category>

		<category><![CDATA[gen_fsm]]></category>

		<category><![CDATA[otp introduction]]></category>

		<guid isPermaLink="false">http://spawnlink.com/?p=52</guid>
		<description><![CDATA[This is the second article in my Erlang/OTP introduction series. If you haven&#8217;t yet, I recommend you read the first article which talks about gen_server and lays the foundation for our bank system before moving onto this article. That being said, if you&#8217;re a quick learner, you can look at the completed server file and [...]]]></description>
			<content:encoded><![CDATA[<p>This is the second article in my Erlang/OTP introduction series. If you haven&#8217;t yet, I recommend you <a href="http://spawnlink.com/articles/an-introduction-to-gen_server-erlybank">read the first article</a> which talks about gen_server and lays the foundation for our bank system before moving onto this article. That being said, if you&#8217;re a quick learner, you can <a href="http://spawnlink.com/otp-intro-1-gen-server-eb-server-withdrawal/">look at the completed server file</a> and continue from there.</p>
<p><strong>The Scenario:</strong> We delivered ErlyBank&#8217;s server to them and they were very pleased. But this is the 21st century so they also need a secure and easy to use ATM system, so they&#8217;ve asked that we extend the server and also create their ATM backend. User accounts are to be protected with a four-digit PIN. From the ATM you should be able to log in to a previously existing account, and deposit or withdraw funds. There is no need to create a pretty user interface on top of the ATM backend, they have another team doing that. </p>
<p><strong>The Result:</strong> First, we&#8217;ll extend the server software to hold a PIN for accounts, and add an authorization call to it. Then, we&#8217;ll use gen_fsm to create the ATM backend. We&#8217;ll rely on the server to do all the data validation. </p>
<p>As always, click read more to get started, if you haven&#8217;t already&#8230;<br />
<span id="more-52"></span></p>
<h2>What is gen_fsm?</h2>
<p><a href="http://www.erlang.org/doc/man/gen_fsm.html">gen_fsm</a> is another Erlang/OTP behavior module, and is used for implementing <a href="http://en.wikipedia.org/wiki/Finite_state_machine">finite state machines</a>.</p>
<p>I apologize in advance, since in this article &#8220;state&#8221; will be used to reference two different things:</p>
<ul>
<li><strong>gen_fsm state</strong> - The state of a finite state machine, this is the current &#8220;mode&#8221; its in. It has nothing to do with the state you learned about with gen_server.</li>
<li><strong>state data</strong> - The state data of the server, this is the same as the state you learned about with gen_server.</li>
</ul>
<p>A bit confusing, I know, but I will do my best to only refer to them with the above terms. </p>
<p>A gen_fsm starts in a state, and any calls/casts made to it are received by a special callback method which is the named the same as the state the gen_fsm module is in. Based on an action, the module can change states. A textbook example of a finite state machine is a locked door. The door starts in the state of &#8220;locked.&#8221; It requires four digits to be unlocked. After entering a single digit, the door stores it, but it needs more digits, and waits, still &#8220;locked.&#8221; After entering four digits, if they are correct, the door changes state to &#8220;unlocked&#8221; for a period of time. If the digits are incorrect, it remains &#8220;locked&#8221; and clears its memory. You&#8217;re probably getting an idea now of how we&#8217;re going to implement an ATM using gen_fsm now <img src='http://spawnlink.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>As I did with gen_server, here is the list of callbacks we need to implement for gen_fsm. You&#8217;ll notice many of them are similar to gen_server:</p>
<ul>
<li><strong>init/1</strong> - Initializers the server. Almost identical to gen_server.</li>
<li><strong>StateName/2</strong> - In this case, StateName actually will be replaced with a state name. This is called when a message is sent to the server; an action occurs on the finite state machine. This is an <strong>asynchronous</strong> callback.</li>
<li><strong>handle_event/3</strong> - Similar to StateName/2, except that this is sent no matter what state you&#8217;re in, when the client calls gen_fsm:send_all_state_event. Again, this is asynchronous.</li>
<li><strong>StateName/3</strong> - Equivalent to StateName/2 except this is the <strong>synchronous</strong> version. The client waits for a response from the server before continuing.</li>
<li><strong>handle_sync_event/4</strong> - Equivalent to handle_event/3 except this is the synchronous version.</li>
<li><strong>handle_info/3</strong> - Equivalent to gen_server&#8217;s handle_info. This receives all messages which weren&#8217;t sending using a standard gen_fsm command. This can include timeout messages, process exit messages, or any messages sent manually with the &#8220;!&#8221; symbol to the server process.</li>
<li><strong>terminate/3</strong> - Called when the server is terminating so you can clean up any resources.</li>
<li><strong>code_change/4</strong> - Called when a real-time system upgrade of the server is occuring. We won&#8217;t deal with this in this article, but it will be used extensively in a future article.</li>
</ul>
<h2>The gen_fsm Skeleton</h2>
<p>Just like with gen_server, I start off every finite state machine with a generic skeleton. The gen_fsm skeleton can be <a href="http://spawnlink.com/otp-intro-2-gen-fsm-skeleton/">viewed here</a>. </p>
<p>There should be nothing out of the ordinary there. The start_link method looks just like the gen_server one did. <img src='http://spawnlink.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> Save that skeleton as <strong>eb_atm.erl</strong> Now we&#8217;re ready to start going!</p>
<h2>Extending eb_server to do Account Authorization</h2>
<p>This is again one of those tasks which I feel comfortable allowing you to do on your own. The following are the changes we need to make:</p>
<ol>
<li>Account creation should require a PIN now, which will be stored with the account, unencrypted.</li>
<li>Add an authorize/2 method, where the arguments are Name and PIN. The return values should be <span class="code inline">ok</span> or <span class="code inline">{error, Reason}</span>.</li>
</ol>
<p>Also, it would be a good idea to require the PIN, or some sort of authorization token with every request to deposit or withdraw money, but in order to save time, and since ErlyBank is fake (breaks my heart <img src='http://spawnlink.com/wp-includes/images/smilies/icon_sad.gif' alt=':(' class='wp-smiley' /> hah!), we will not do this. </p>
<p>To be honest, this isn&#8217;t <em>really</em> a quick-fix, but if you&#8217;re learning Erlang now on your own, you must be pretty smart <img src='http://spawnlink.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> So I think you can do it! Be sure to test your changes before moving on, or at least compare them to the answer linked below.</p>
<p>After implementing the above changes, your eb_server.erl should <a href="http://spawnlink.com/otp-intro-2-gen-fsm-eb-server-authorization/">look like this</a>. Note that the messages you send to the server may be different, and that is <em>okay</em>. Programmers think differently. The important thing is that the API outputs the same data, correctly. </p>
<h2>ATM Design Strategy</h2>
<p>I&#8217;m going to quick a take coding break to explain the plan for this ATM system. We&#8217;re going to implement it following the flow chart below:</p>
<p><img src="http://spawnlink.s3.amazonaws.com/otp-intro/gen-fsm/atm_sequence.png" alt="Sequence Diagram for ATM" /></p>
<p>The three blue boxes represent the different states the server will be in. The arrows represent what actions are necessary to switch to those states.</p>
<h2>Initializing gen_fsm</h2>
<p>To start the ATM, we use the same start_link method as a gen_server. But initialization is a little bit different.</p>
<div class="code">
<pre><span style="color: #f0dfaf;">init</span>([]) -&gt;
  {ok, unauthorized, nobody}.</pre>
</div>
<p>&nbsp;</p>
<p>The init/1 method of a gen_fsm is expected to return <span class="code inline">{ok, StateName, StateData}</span>. StateName is the initial state of the server, and state data is the initial data of the server. In the case of ErlyBank&#8217;s ATM, we start out in the unauthorized state, and the data is set to <span class="code inline">nobody</span>. The state data will be the account name we&#8217;ll be dealing with, so initially its nothing. Erlang has no null/nil/nothing data type, and a descriptive atom is usually used instead, like this one.</p>
<h2>Account Authorization</h2>
<p>We now need to implement the authorization API for the ATM. First, the API definition:</p>
<div class="code">
<pre><span style="color: #f0dfaf;">authorize</span>(<span style="color: #f0dfaf;">Name</span>, <span style="color: #f0dfaf;">PIN</span>) -&gt;
  gen_fsm:sync_send_event(?<span style="color: #dca3a3; font-weight: bold;">SERVER</span>, {authorize, <span style="color: #f0dfaf;">Name</span>, <span style="color: #f0dfaf;">PIN</span>}).</pre>
</div>
<p>The sync_send_event method is equivalent to the call method of gen_server. It sends the message, the second argument, to the current state of the server represented with the first argument. So now we have to write a handler for the message:</p>
<div class="code">
<pre><span style="color: #f0dfaf;">unauthorized</span>({authorize, <span style="color: #f0dfaf;">Name</span>, <span style="color: #f0dfaf;">Pin</span>}, <span style="color: #f0dfaf;">_From</span>, <span style="color: #f0dfaf;">State</span>) -&gt;
  <span style="color: #f0dfaf; font-weight: bold;">case</span> eb_server:authorize(<span style="color: #f0dfaf;">Name</span>, <span style="color: #f0dfaf;">Pin</span>) <span style="color: #f0dfaf; font-weight: bold;">of</span>
    ok -&gt;
      {reply, ok, authorized, <span style="color: #f0dfaf;">Name</span>};
    {error, <span style="color: #f0dfaf;">Reason</span>} -&gt;
      {reply, {error, <span style="color: #f0dfaf;">Reason</span>}, unauthorized, <span style="color: #f0dfaf;">State</span>}
  <span style="color: #f0dfaf; font-weight: bold;">end</span>;
<span style="color: #f0dfaf;">unauthorized</span>(<span style="color: #f0dfaf;">_Event</span>, <span style="color: #f0dfaf;">_From</span>, <span style="color: #f0dfaf;">State</span>) -&gt;
  <span style="color: #f0dfaf;">Reply</span> = {error, invalid_message},
  {reply, <span style="color: #f0dfaf;">Reply</span>, unauthorized, <span style="color: #f0dfaf;">State</span>}.</pre>
</div>
<p>&nbsp;</p>
<p>This should read pretty logically as well. The function is named <strong>unauthorized</strong> because that is the state we expect the message to be received at. We then write a matcher to match the tuple <span class="code inline">{authorize, Name, Pin}</span>. We then use the API methods exported by the server we wrote to authorize the user. </p>
<p>If the account and PIN are valid, we send the response <span class="code inline">ok</span> back to the client. The format of the response is <span class="code inline">{reply, Response, NewStateName, NewStateData}</span>. Following that format, we&#8217;ve changed states to <strong>authorized</strong> and for the data we store the account name.</p>
<p>If the account information was invalid, we respond with the error and reason and stay in the same state with the same state data.</p>
<p>Finally, we implement another catch-all function at the end. You should do this throughout functional programming environments but it is <em>especially important</em> here, since different states might be receiving actions meant for other states. For example, what if, for some reason, someone attempts to deposit while we&#8217;re still unauthenticated? We need a catch all to send back an invalid message error. This is what we do here.</p>
<h2>Deposits</h2>
<p>Once we&#8217;re authorized, a user is going to either deposit or withdraw from his or her bank account. We&#8217;re going to implement deposits using an <strong>asynchronous</strong> call to the server. Again, this is a bit insecure, since we&#8217;re not verifying the deposit was actually successful, but since this is a fake bank, and an ATM prototype at best, I am letting this slip. <img src='http://spawnlink.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
<p>First, the API! </p>
<div class="code">
<pre><span style="color: #708070;">%%</span><span style="color: #7f9f7f;">--------------------------------------------------------------------
</span><span style="color: #708070;">%% </span><span style="color: #7f9f7f;">Function: deposit(Amount) -&gt; ok
</span><span style="color: #708070;">%% </span><span style="color: #7f9f7f;">Description: Deposits a certain amount in the currently authorized
</span><span style="color: #708070;">%% </span><span style="color: #7f9f7f;">account.
</span><span style="color: #708070;">%%</span><span style="color: #7f9f7f;">--------------------------------------------------------------------
</span><span style="color: #f0dfaf;">deposit</span>(<span style="color: #f0dfaf;">Amount</span>) -&gt;
  gen_fsm:send_event(?<span style="color: #dca3a3; font-weight: bold;">SERVER</span>, {deposit, <span style="color: #f0dfaf;">Amount</span>}).</pre>
</div>
<p>&nbsp;</p>
<p>Simple, and this time we use the <span class="code inline">send_event/2</span> method instead of sync_send_event. This sends an asynchronous call to the server. Now the handling part&#8230;</p>
<div class="code">
<pre><span style="color: #f0dfaf;">authorized</span>({deposit, <span style="color: #f0dfaf;">Amount</span>}, <span style="color: #f0dfaf;">State</span>) -&gt;
  eb_server:deposit(<span style="color: #f0dfaf;">State</span>, <span style="color: #f0dfaf;">Amount</span>),
  {next_state, thank_you, <span style="color: #f0dfaf;">State</span>, 5000};
<span style="color: #f0dfaf;">authorized</span>(<span style="color: #f0dfaf;">_Event</span>, <span style="color: #f0dfaf;">State</span>) -&gt;
  {next_state, authorized, <span style="color: #f0dfaf;">State</span>}.</pre>
</div>
<p>&nbsp;</p>
<p>Again, very simple. The method actual just forwards the information to the eb_server deposit API we wrote, which will do all the validation. But there is something strange in the return value of the deposit method! Not only does the state change to thank_you, but there is this odd &#8220;5000&#8243; at the end there. That is actually a <em>timeout</em>. If no message is received in 5000 milliseconds (or 5 seconds), then a <span class="code inline">timeout</span> message is sent to the current state. Which leads us to our next topic&#8230;</p>
<h2>The Short &#8220;Thank You!&#8221; State</h2>
<p>Anyone (everyone?) who has gone to an ATM knows that after you&#8217;re done banking, there is a short &#8220;Thank You&#8221; screen that shows up for a little while. And although this really shouldn&#8217;t be implemented in the back end, I wanted to show off the timeout feature of gen_fsm. After 5000 milliseconds, or if any other message is received, I swap the state back over to &#8220;unauthorized&#8221; so the ATM can start over again for the next customer. Here is the code:</p>
<div class="code">
<pre><span style="color: #f0dfaf;">thank_you</span>(timeout, <span style="color: #f0dfaf;">_State</span>) -&gt;
  {next_state, unauthorized, nobody};
<span style="color: #f0dfaf;">thank_you</span>(<span style="color: #f0dfaf;">_Event</span>, <span style="color: #f0dfaf;">_State</span>) -&gt;
  {next_state, unauthorized, nobody}.</pre>
</div>
<p>&nbsp;</p>
<p><strong>Note:</strong> The trained eye will note that both methods are equal, and its unnecessary to have the first matcher. This is true, and I just included the first matcher to be explicit about catching the timeout.</p>
<p>Here is the <a href="http://spawnlink.com/otp-intro-2-gen-fsm-eb-atm-deposits/">complete eb_atm.erl up to this point</a>.</p>
<h2>Withdrawals</h2>
<p>Again, I will be leaving withdrawals as an exercise to the reader. You can implement it any way you&#8217;d like! Just make sure it actually does withdraw from the account <img src='http://spawnlink.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
<p>Here is <a href="http://spawnlink.com/otp-intro-2-gen-fsm-withdrawals/">my eb_atm.erl</a> after implementing withdrawals. Note that successful withdrawals transition to the thank_you state with the timeout in place. </p>
<h2>A Cancel-No-Matter-What Button</h2>
<p>One of my biggest gripes of many machines is that there isn&#8217;t a big &#8220;Cancel&#8221; button that cancels everything you have been doing. And though I&#8217;ve found that killing the power to a machine does this cancel functionality quite nicely, this isn&#8217;t an option for people at an ATM. So let&#8217;s implement a giant cancel method which cancels the transaction, no matter what state it is in. </p>
<p>How would you do this? Well, using only the knowledge of this article, I would guess that you&#8217;d put a cancel API method which sends a <span class="code inline">cancel</span> message to the event. Then in each event you can handle this and go back to the <span class="code inline">unauthorized</span> state.</p>
<p>Witty, but not correct, by no fault of your own! I didn&#8217;t mention (or I did extremely briefly, you probably missed it) that there is a method <span class="code inline">gen_fsm:send_all_state_event/2</span> which sends a message, regardless of what state the server is in. We will use this, to keep our code <a href="http://en.wikipedia.org/wiki/index.html?curid=4092793">DRY</a>.</p>
<p>Our API:</p>
<div class="code">
<pre><span style="color: #708070;">%%</span><span style="color: #7f9f7f;">--------------------------------------------------------------------
</span><span style="color: #708070;">%% </span><span style="color: #7f9f7f;">Function: cancel/0
</span><span style="color: #708070;">%% </span><span style="color: #7f9f7f;">Description: Cancels the ATM transaction no matter what state.
</span><span style="color: #708070;">%%</span><span style="color: #7f9f7f;">--------------------------------------------------------------------
</span><span style="color: #f0dfaf;">cancel</span>() -&gt;
  gen_fsm:send_all_state_event(?<span style="color: #dca3a3; font-weight: bold;">SERVER</span>, cancel).</pre>
</div>
<p>&nbsp;</p>
<p>This event is sent to the <span class="code inline">handle_event/3</span> method, which we extend below:</p>
<div class="code">
<pre><span style="color: #f0dfaf;">handle_event</span>(cancel, <span style="color: #f0dfaf;">_StateName</span>, <span style="color: #f0dfaf;">_State</span>) -&gt;
  {next_state, unauthorized, nobody};
<span style="color: #f0dfaf;">handle_event</span>(<span style="color: #f0dfaf;">_Event</span>, <span style="color: #f0dfaf;">StateName</span>, <span style="color: #f0dfaf;">State</span>) -&gt;
  {next_state, <span style="color: #f0dfaf;">StateName</span>, <span style="color: #f0dfaf;">State</span>}.</pre>
</div>
<p>&nbsp;</p>
<p>If we receive the cancel message, the server resets the state to unauthorized and the state data to nobody: a fresh ATM!</p>
<p>As always, the current complete state of eb_atm.erl <a href="http://spawnlink.com/otp-intro-2-gen-fsm-eb-atm-cancel/">can be viewed here</a>.</p>
<h2>Final Notes</h2>
<p>In this article, I showed you how to create a basic ATM system using <a href="http://www.erlang.org/doc/man/gen_fsm.html">gen_fsm</a>. I showed you how to handle messages in a given state, change states, change states with timeouts, and send-to-all messages, among other things.</p>
<p>There are some warts in the system though, and I leave it to you to fix them. Here are two exercises for you to do, if you wish. Trust me, you have the ability:</p>
<ol>
<li>Add error checking to deposits. Make it return <span class="code inline">{error, Reason}</span> and <span class="code inline">{ok, Balance}</span> instead of just &#8220;ok&#8221; all the time.</li>
<li>Add a &#8220;check my balance&#8221; function to the ATM. This should only be available while authorized, and should <em>not</em> end the transaction. This means that it should not send the user to the thank_you state. This is so that after seeing their balance, the user can withdraw/deposit if necessary.</li>
</ol>
<p>These two features of the exercise won&#8217;t be used in future articles, and as such I won&#8217;t post the answers here. You can test them yourself to make sure they work! <img src='http://spawnlink.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>Part two of this Erlang/OTP series is over. The third article is already in the pipeline and will be published in another few days. It will cover <a href="http://www.erlang.org/doc/man/gen_event.html">gen_event</a>. For fun, you can think what I&#8217;ll be adding to ErlyBank using this! <img src='http://spawnlink.com/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> </p>
<p>I hope you have been enjoying these introductions to Erlang/OTP as much as I&#8217;ve enjoyed writing them. Thanks for all the support, and good luck!</p>
]]></content:encoded>
			<wfw:commentRss>http://spawnlink.com/articles/an-introduction-to-gen_fsm-erlybanks-atm/feed/</wfw:commentRss>
		<feedburner:origLink>http://spawnlink.com/articles/an-introduction-to-gen_fsm-erlybanks-atm/</feedburner:origLink></item>
		<item>
		<title>An Introduction to gen_server: “ErlyBank”</title>
		<link>http://feeds.feedburner.com/~r/spawn_link/~3/385119110/</link>
		<comments>http://spawnlink.com/articles/an-introduction-to-gen_server-erlybank/#comments</comments>
		<pubDate>Sat, 06 Sep 2008 16:06:06 +0000</pubDate>
		<dc:creator>Mitchell</dc:creator>
		
		<category><![CDATA[Uncategorized]]></category>

		<category><![CDATA[bank manager]]></category>

		<category><![CDATA[beginner]]></category>

		<category><![CDATA[erlang]]></category>

		<category><![CDATA[gen_server]]></category>

		<category><![CDATA[otp introduction]]></category>

		<guid isPermaLink="false">http://spawnlink.com/?p=27</guid>
		<description><![CDATA[This is the first article in a series of articles introducing all the concepts pertaining to Erlang/OTP. In order to find all these articles later, they are tagged with a unique tag to the series: otp introduction. As promised in my initial introduction to OTP, we will be making a server to handle the fake [...]]]></description>
			<content:encoded><![CDATA[<p>This is the first article in a series of articles introducing all the concepts pertaining to Erlang/OTP. In order to find all these articles later, they are tagged with a unique tag to the series: <a href="http://spawnlink.com/articles/tag/otp-introduction/">otp introduction</a>. As promised in my <a href="http://spawnlink.com/articles/introduction-to-the-open-telecom-platform/">initial introduction to OTP</a>, we will be making a server to handle the fake bank accounts of people at &#8220;ErlyBank&#8221; (Yes, I enjoy coming up with silly names). </p>
<p><strong>The Scenario:</strong> ErlyBank is just starting and they want to start off on the right foot by creating a scalable system for managing the bank accounts of its important customer-base. Having heard about the powers of Erlang, we have been hired to do that! But to test us out, they first want a simple server to handle the creation and destruction of accounts, depositing money, and withdrawing money. They just want a prototype, not something they&#8217;ll actually be putting into production. </p>
<p><strong>The Result:</strong> We will create a simple server and client to do everything they asked using <a href="http://www.erlang.org/doc/man/gen_server.html">gen_server</a>. Since its just a prototype, we&#8217;ll store the account information in memory for now. The accounts will only be referenced by name, no other information is necessary to create an account. And of course we&#8217;ll have validation on withdrawals and deposits. </p>
<p><strong>Note:</strong> Before beginning this series, I am assuming you have a basic knowledge of the Erlang syntax. If not, I recommend reading my <a href="http://spawnlink.com/articles/compendium-of-beginner-erlang-resources/">compendium of beginner erlang resources</a> to find a place you can learn Erlang. </p>
<p>If you&#8217;re ready, click read more below to get started! (Unless you&#8217;re viewing the whole article already <img src='http://spawnlink.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> )</p>
<p><span id="more-27"></span></p>
<h2>What is gen_server?</h2>
<p><a href="http://www.erlang.org/doc/man/gen_server.html">gen_server</a> is a behavior module for implementing client-server relationships. By using this OTP module, you&#8217;re given a lot of things &#8220;for free,&#8221; as I&#8217;ll explain later. Also, later in the series, when I talk about supervisors and error reporting, this module will fit right in without many changes. </p>
<p>Since gen_server is a behavior, you&#8217;re expected to adhere to a certain number of callbacks. These callbacks, in no particular order, are:</p>
<ul>
<li><strong>init/1</strong> - Initializes the server.</li>
<li><strong>handle_call/3</strong> - Handles a call made to the server. The client who called the server is blocked until you return from this method.</li>
<li><strong>handle_cast/2</strong> - Handles a cast made to the server. A cast is similar to a call except that it is asynchronous; the client continues while this cast is running.</li>
<li><strong>handle_info/2</strong> - A sort of &#8220;catch all&#8221; method. If a message is sent to the server process that isn&#8217;t a call or a cast, it will come here. An example of such a message is an EXIT process message if your server is linked to any other process.</li>
<li><strong>terminate/2</strong> - Called while the server is stopping, so any cleanup can be done.</li>
<li><strong>code_change/3</strong> - Called when the server is being upgraded in real-time. This method will be covered in much greater detail in future articles, but you must at least put the stub of the method into your module to adhere to the behavior.</li>
</ul>
<h3>The Server Skeleton</h3>
<p>To start off <em>every</em> gen_server file, I always use a common skeleton. If you can, create a snippet or something with your text editor to paste the skeleton. The skeleton can be <a href="http://spawnlink.com/otp-intro-1-gen_server-skeleton/">viewed here</a>. Please take a quick look at it.</p>
<p>Note: To save space, I won&#8217;t ever paste the entire file here in this post, I will try to link to the whole thing when such a change occurs. But for the most part, I will just be pasting in snippets.</p>
<p>As you can see, the module is named <strong>eb_server</strong>, for &#8220;ErlyBank Server.&#8221; It implements all the callback methods I mentioned above and also adds one more: <span class="code inline">start_link/0</span>. This will be the method used to start the server. I&#8217;ve pasted this portion of the code below:</p>
<div class="code">
<pre><span style="color: #f0dfaf;">start_link</span>() -&gt;
  gen_server:start_link({local, ?<span style="color: #dca3a3; font-weight: bold;">SERVER</span>}, ?<span style="color: #dca3a3; font-weight: bold;">MODULE</span>, [], []).</pre>
</div>
<p>&nbsp;<br />
This calls the start_link/4 method of gen_server, which starts the server and registers the process to the atom defined by the macro <span class="code inline">SERVER</span>, which by default is just the module name. The remaining arguments are the module of the gen_server, in this case itself, any arguments, and finally any options. We leave the arguments blank because we don&#8217;t need any and we don&#8217;t specify any options. For more information, an in-depth description of the method is available on the <a href="http://www.erlang.org/doc/man/gen_server.html#start_link-4">gen_server manual page</a>.</p>
<h2>Initializing The ErlyBank Server</h2>
<p>Once the gen_server:start_link method is called, it calls the init method of the actual server. It is in this method you should initialize any state for the server. <strong>State</strong> can be anything you want: An atom, a list of values, a fun, anything! This state is passed around in every callback to the server. In this case, we&#8217;d like to maintain a list of all accounts and their account balance. Additionally, we&#8217;d like to look up these accounts by name. To do this, I&#8217;m going to use the <a href="http://www.erlang.org/doc/man/dict.html">dict</a> module, which stores key-value pairs in memory.</p>
<p><strong>Note to Object-Oriented Minds:</strong> If you come from an OOP language, you can think of the server state as its instance variables. In every gen_server callback, you&#8217;ll have these instance variables available, and you can change them, too. </p>
<p>So here is my final init method:</p>
<div class="code">
<pre><span style="color: #f0dfaf;">init</span>(_Args) -&gt;
  {ok, dict:new()}.</pre>
</div>
<p>&nbsp;<br />
Really, its that simple! One of the return values expected for init is <span class="code inline">{ok, State}</span> so for the ErlyBank server, I&#8217;m just returning ok, and an empty dictionary for the state. And we don&#8217;t use the arguments to init (which is an empty list anyway, remember, from start_link), so I just prepend the argument with an underscore to note that.</p>
<h2>To Call or To Cast, That is the Question</h2>
<p>Before we implement the bulk of the server, I want to quickly reiterate the difference between a call and a cast.</p>
<p>A <strong>call</strong> to the gen_server is a <strong>blocking</strong> method for the client. This means that when the client sends a message to the server, it waits for a response before moving on. You use a call when you need a response, such as if you&#8217;re asking what the balance of an account is.</p>
<p>A <strong>cast</strong> to the gen_server is a <strong>non-blocking</strong> or asynchronous method. This means that when the client sends a message to the server, it continues on, without receiving a response. Now, Erlang guarantees that all messages sent to a process are received, so unless you explicitly need a response value from the server, you should cast, as it will keep your client executing. That is to say, you don&#8217;t need to make a &#8220;call&#8221; to the server if you simply want a response to make sure the server received the message, since Erlang guarantees this.</p>
<h2>Bank Account Creation</h2>
<p>First things first, ErlyBank needs a way to create new accounts. Quickly, test yourself: If you were creating a bank account, would you <strong>cast or call</strong> to the server? Think hard&#8230; what value would you need returned? If you said <strong>call</strong> you&#8217;re correct, normally anyways. You usually want to make sure the account was created successfully without just assuming it was so. But in this case, I&#8217;m going to implement it as a cast, since we won&#8217;t be error checking for now.</p>
<p>First, I&#8217;m going to create the API method, the method outside modules will call to create an account:</p>
<div class="code">
<pre><span style="color: #708070;">%%</span><span style="color: #7f9f7f;">--------------------------------------------------------------------
</span><span style="color: #708070;">%% </span><span style="color: #7f9f7f;">Function: create_account(Name) -&gt; ok
</span><span style="color: #708070;">%% </span><span style="color: #7f9f7f;">Description: Creates a bank account for the person with name Name
</span><span style="color: #708070;">%%</span><span style="color: #7f9f7f;">--------------------------------------------------------------------
</span><span style="color: #f0dfaf;">create_account</span>(<span style="color: #f0dfaf;">Name</span>) -&gt;
  gen_server:cast(?<span style="color: #dca3a3; font-weight: bold;">SERVER</span>, {create, <span style="color: #f0dfaf;">Name</span>}).</pre>
</div>
<p>&nbsp;</p>
<p>This sends a cast to the server, which we registered as <span class="code inline">?SERVER</span> in start_link. The request is a tuple <span class="code inline">{create, Name}</span>. Since this is a cast, it returns immediately with &#8220;ok,&#8221; which is also returned from the function.</p>
<p>Now, we need to write the part to handle this cast, which is a callback for the gen_server:</p>
<div class="code">
<pre><span style="color: #f0dfaf;">handle_cast</span>({create, <span style="color: #f0dfaf;">Name</span>}, <span style="color: #f0dfaf;">State</span>) -&gt;
  {noreply, dict:store(<span style="color: #f0dfaf;">Name</span>, 0, <span style="color: #f0dfaf;">State</span>)};
<span style="color: #f0dfaf;">handle_cast</span>(<span style="color: #f0dfaf;">_Msg</span>, <span style="color: #f0dfaf;">State</span>) -&gt;
  {noreply, <span style="color: #f0dfaf;">State</span>}.</pre>
</div>
<p>&nbsp;</p>
<p>As you can see, we just add another function definition for handle_cast to capture our create request. We then store it in the dictionary, with a value of 0, representing the current account balance. The return value expected for a handle_cast is <span class="code inline">{noreply, State}</span> where State is the new state of the server. So this time, we return a new dictionary with the added account. </p>
<p>Also, notice I added a catch-all function at the end. This is not just good practice here, but for all functional programming in general. You can use this method to just absorb the message silently, or you could always raise an exception if you have to. In this case, I absorb it silently.</p>
<p>The entire <a href="http://spawnlink.com/otp-intro-1-gen-server-eb-server-create-account/">eb_server.erl at this point can be viewed here.</a></p>
<h2>Money Deposit</h2>
<p>We promised our client, ErlyBank, that we&#8217;d add an API to deposit money into a person&#8217;s account, and that we&#8217;d include basic validation. So we need to write a deposit API method, and the server also needs to verify that the account exists before depositing money, since ErlyBank doesn&#8217;t want would-be customer&#8217;s money going into a black hole. Again, test yourself: A <strong>cast or call</strong>? This one is easy: A call. We need to make sure the deposit was successful, and notify the user. </p>
<p>Just like before, I&#8217;m going to first write the API method:</p>
<div class="code">
<pre><span style="color: #708070;">%%</span><span style="color: #7f9f7f;">--------------------------------------------------------------------
</span><span style="color: #708070;">%% </span><span style="color: #7f9f7f;">Function: deposit(Name, Amount) -&gt; {ok, Balance} | {error, Reason}
</span><span style="color: #708070;">%% </span><span style="color: #7f9f7f;">Description: Deposits Amount into Name's account. Returns the
</span><span style="color: #708070;">%% </span><span style="color: #7f9f7f;">balance if successful, otherwise returns an error and reason.
</span><span style="color: #708070;">%%</span><span style="color: #7f9f7f;">--------------------------------------------------------------------
</span><span style="color: #f0dfaf;">deposit</span>(<span style="color: #f0dfaf;">Name</span>, <span style="color: #f0dfaf;">Amount</span>) -&gt;
  gen_server:call(?<span style="color: #dca3a3; font-weight: bold;">SERVER</span>, {deposit, <span style="color: #f0dfaf;">Name</span>, <span style="color: #f0dfaf;">Amount</span>}).</pre>
</div>
<p>&nbsp;</p>
<p>Nothing exciting here. We just send along a message to the server. The above should look familiar to you, as its the exact same as a cast so far. But the difference is in the server code:</p>
<div class="code">
<pre><span style="color: #f0dfaf;">handle_call</span>({deposit, <span style="color: #f0dfaf;">Name</span>, <span style="color: #f0dfaf;">Amount</span>}, <span style="color: #f0dfaf;">_From</span>, <span style="color: #f0dfaf;">State</span>) -&gt;
  <span style="color: #f0dfaf; font-weight: bold;">case</span> dict:find(<span style="color: #f0dfaf;">Name</span>, <span style="color: #f0dfaf;">State</span>) <span style="color: #f0dfaf; font-weight: bold;">of</span>
    {ok, <span style="color: #f0dfaf;">Value</span>} -&gt;
      <span style="color: #f0dfaf;">NewBalance</span> = <span style="color: #f0dfaf;">Value</span> + <span style="color: #f0dfaf;">Amount</span>,
      <span style="color: #f0dfaf;">Response</span> = {ok, <span style="color: #f0dfaf;">NewBalance</span>},
      <span style="color: #f0dfaf;">NewState</span> = dict:store(<span style="color: #f0dfaf;">Name</span>, <span style="color: #f0dfaf;">NewBalance</span>, <span style="color: #f0dfaf;">State</span>),
      {reply, <span style="color: #f0dfaf;">Response</span>, <span style="color: #f0dfaf;">NewState</span>};
    error -&gt;
      {reply, {error, account_does_not_exist}, <span style="color: #f0dfaf;">State</span>}
  <span style="color: #f0dfaf; font-weight: bold;">end</span>;
<span style="color: #f0dfaf;">handle_call</span>(<span style="color: #f0dfaf;">_Request</span>, <span style="color: #f0dfaf;">_From</span>, <span style="color: #f0dfaf;">State</span>) -&gt;
  <span style="color: #f0dfaf;">Reply</span> = ok,
  {reply, <span style="color: #f0dfaf;">Reply</span>, <span style="color: #f0dfaf;">State</span>}.</pre>
</div>
<p>&nbsp;</p>
<p>Whoa! Lots of new stuff! First, the method definition looks similar to handle_cast, except for the added <span class="code inline">From</span> argument, which we don&#8217;t use. This argument is the pid of the calling process, so we can send additional messages if needed. </p>
<p>We promised ErlyBank we&#8217;d validate the existence of accounts, and the first line is where we do it. We attempt to find a value from the state dictionary for the person trying to deposit the account. The find method of dict returns one of two values: Either <span class="code inline">{ok, Value}</span> or <span class="code inline">error</span>. </p>
<p>In the case that the account exists, Value equals the current balance in the account, so we add the deposited amount to that. We then store the new balance for the account into the dictionary and set that to a variable. I also store the response in a variable, which should look just like the comment for the deposit API said it would: <span class="code inline">{ok, Balance}</span>. Then, by returning the tuple <span class="code inline">{reply, Reply, State}</span>, the server sends the Reply back to the calling process, and stores the new state. </p>
<p>On the other hand, if the account doesn&#8217;t exist, we don&#8217;t change the state at all, but we reply with the tuple <span class="code inline">{error, account_does_not_exist}</span>, which again follows the spec in the comments of the deposit API.</p>
<p>Again, here is the <a href="http://spawnlink.com/otp-intro-1-gen-server-eb-server-deposit-api/">updated eb_server.erl source</a> after this addition. </p>
<h2>Account Destruction and Money Withdrawals</h2>
<p>I am actually going to leave it as an exercise to the reader to complete the account destruction and withdrawal APIs for the module. You have all the necessary knowledge to do these things. If you need any help with the dict module, refer to the <a href="http://www.erlang.org/doc/man/dict.html">dict module API reference</a>. For withdrawals, please validate both that the account exists and that it has enough funds for the withdrawal. You do not have to handle the case of withdrawing negative funds. </p>
<p>Once you&#8217;ve finished, or if you&#8217;ve given up (I hope not!), you can view the <a href="http://spawnlink.com/otp-intro-1-gen-server-eb-server-withdrawal/">answer here.</a></p>
<h2>Final Notes</h2>
<p>In this article, I showed you the basics of gen_server and how to create a client-server relationship. I did not cover the full capabilities of gen_server which include such things as timeouts for message receiving and stopping the server, but I feel I&#8217;ve explained a solid portion of the behavior module. </p>
<p>If you wish to learn more about the callback methods, possible return values, and more advanced usages of gen_server, <a href="http://www.erlang.org/doc/man/gen_server.html">read the manual on gen_server</a>. Read all of it, really. </p>
<p>Also, I know I did not touch and I barely mentioned the code_change/3 method, which for some reason causes the most excitement in people. Don&#8217;t worry, I have an entire article (near the end of the series) dedicated to deploying real-time upgrades to running systems, and this is where this method will come into play.</p>
<p>The next article, in a few days, will be on gen_fsm. So if this article tickled your brain, feel free to jump in on that manual and get a head start! Maybe you can guess what wacky continuation of ErlyBank I&#8217;ll be adding with gen_fsm. <img src='http://spawnlink.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /></p>
]]></content:encoded>
			<wfw:commentRss>http://spawnlink.com/articles/an-introduction-to-gen_server-erlybank/feed/</wfw:commentRss>
		<feedburner:origLink>http://spawnlink.com/articles/an-introduction-to-gen_server-erlybank/</feedburner:origLink></item>
		<item>
		<title>Introduction to the Open Telecom Platform</title>
		<link>http://feeds.feedburner.com/~r/spawn_link/~3/384389149/</link>
		<comments>http://spawnlink.com/articles/introduction-to-the-open-telecom-platform/#comments</comments>
		<pubDate>Fri, 05 Sep 2008 18:12:12 +0000</pubDate>
		<dc:creator>Mitchell</dc:creator>
		
		<category><![CDATA[Uncategorized]]></category>

		<category><![CDATA[beginner]]></category>

		<category><![CDATA[erlang]]></category>

		<category><![CDATA[guides]]></category>

		<category><![CDATA[otp]]></category>

		<guid isPermaLink="false">http://spawnlink.com/?p=24</guid>
		<description><![CDATA[Many people refer to Erlang as &#8220;Erlang/OTP.&#8221; OTP stands for Open Telecom Platform, and is more or less a set of libraries which come packaged with Erlang. They consist of Erlang behaviors (or behaviours, technically) for writing servers, finite state machines, event managers. But that is not all, OTP also encompasses the application behavior which [...]]]></description>
			<content:encoded><![CDATA[<p>Many people refer to Erlang as &#8220;Erlang/OTP.&#8221; OTP stands for <strong>Open Telecom Platform</strong>, and is more or less a set of libraries which come packaged with Erlang. They consist of Erlang behaviors (or <em>behaviours</em>, technically) for writing servers, finite state machines, event managers. But that is not all, OTP also encompasses the application behavior which allows programmers to package their Erlang code into a single &#8220;application.&#8221; And the supervisor behavior allows programmers to create a hierarchy of processes, where if one process dies, it will be restarted. </p>
<p>OTP is much too complex of a thing to explain in a single article, and I will not attempt to do so here. Instead, I will be making this a series of articles spanning a couple weeks. </p>
<h2>Why should I learn about Erlang/OTP?</h2>
<p>The platform which comes with Erlang gives you a rich and very generalized set of libraries and behaviors to easily create highly available, fault tolerant, hot code swapping ready systems. The following is a basic list of what it gives you &#8220;for free:&#8221;</p>
<ul>
<li>Generic server, finite state machine, and event manager behaviors</li>
<li>Standardized application structure</li>
<li>Hot swappable code</li>
<li>Supervisor Trees so your processes always stay up</li>
</ul>
<p>In addition to these free features, OTP is the standardized way to create systems in Erlang. The big name open source Erlang applications such as <a href="http://www.ejabberd.im/">ejabberd</a>, <a hr