OTP and Erlang in Action
August 17, 2009
Martin Logan is one of the many bright people I met at Erlang Factory Palo Alto.
Martin has been programming Erlang for more than 10 years — full time for the last five. He’s the core developer at Erlware and the primary developer of the Faxien package management system.
During one of the Erlang Factory breaks Martin patiently defined “referential transparency” for me. Fancy phrase for a fairly simple concept it turns out — an expression that always returns the same result given the same input is said to be “referentially transparent.”
Anyway, I recently purchased from Manning Publications the MEAP edition of OTP and Erlang in Action by Martin Logan, Eric Merritt, and Richard Carlson. And it’s sure to be an Erlang classic.
The cool thing about MEAP is that you pop in your credit card number and get back an instant *.pdf download of the book in progress. As the authors add content, you get e-mail notification of updates from Manning. You can order hard copy of the work, of course, but you won’t get it until the formal publication date. But, I say that OTP and Erlang in Action is too important to wait. If you’re striving for professional excellence in Erlang, order both *.pdf and hard copy today.
Joe Armstrong’s Programming Erlang is, of course, the Erlang gold standard. But OTP and Erlang in Action (OTP for short) belongs right beside it. And, arguably, you might find skimming through it before you even crack open Armstrong quite profitable. Most certainly, once you’ve digested Armstrong, you’ll want to read and re-read OTP, and enter code as you go along, until the pages fall off.
OTP and Erlang in Action first leads you through the core concepts of Erlang — processes and concurrency, process communication, fault tolerance, distributed Erlang, functional programming, higher order functions, iteration vs. recursion, single assignment, and pattern matching.
All these fancy shmancy words — sounds like a trudge. But OTP is written in lucid and lively English — just the kind of plain-talk accessible language that tells you that the writers really know their stuff.
Chapter 2 introduces language basics. It’s not nearly as thorough as the Erlang tutorials or Armstrong, but it complements them nicely and, more to the point, sets you up for some dazzling hands-on programming.
To wit, the remaining 11 chapters, guide you through solid OTP production-level code — a telnet server all packaged up as an OTP application and a distributed caching system. This is code you can build and use. Along the way you learn in great detail about OTP packaging and organization, processes and linking, building a production system, distributed Erlang, tracking and managing distributed code, packaging and deployment, hot code loading and upgrading, non-native Erlang distribution, drivers and multi language interfaces — all the good stuff that was left to your imagination in other texts.
As a newbie, I’ve got to say, this book is a real find. Can’t wait for the authors to finish it.
Erlang/OTP Callback Modules II
April 23, 2009
Hynek (Pichi) Vychodil kindly pointed me to Joe Armstrong’s thesis to help deepen my understanding of callback modules.
Starting on page 98, Joe talks about “abstracting out concurrency.”
Keeping track of many concurrent process is mentally challenging and error-prone, he says. For this reason he advocates a library of generic components, written by skilled Erlang programmers, and “plugins,” written by programmers competent in Erlang sequential programming. This component library, of course, has become OTP.
Says Joe, “The generic component should hide details of concurrency and mechanisms for fault-tolerance from the plugins. The plugins should be written using only sequential code with well-defined types.”
My quick reading did not turn up the phrase “callback module.” May be there. But I take it that “callback module” and “plugin” are synonymous.
Check out Joe’s thesis for yourself. Tons of invaluable background straight from the man himself.
One crucial point still clouds my aging brain: When you call a function in, say, a gen_server callback module and, say, it returns a tuple like {ok, yada yada}, who’s listening and expected to respond? I definitely need to think this one through before I get back to my walk-through of iserve.
Meanwhile, I’m packing up for Erlang University. Plan to spend three days learning what I can from Chris Anderson and Jan Lehnard about CouchDB.
The following two days, Thursday and Friday, promise many hours of brain food. I’m particularly looking forward to Rusty Klophaus’s Nitrogen presentation. If you haven’t been following Google Groups Nitrogen Web Framework for Erlang, drop in. Lively exchange of performance profiling data has been particularly interesting.
While rubbing shoulders with Erlang greats at Erlang University, I also hope to learn much more about Web Machine and Erlyweb.
Can’t promise, but maybe I’ll come back with a few pearls of wisdom. Maybe even a photo or two. I certainly plan to get back to my dissection of iserve.
So, be back sometime in early May just as soon as the jet lag wears off.
Erlang/OTP Callback Modules
April 22, 2009
Apologies for my April 19, 2009 post. For one thing, it’s much too dense. And worse, it’s wrong — at least seven of the last eight paragraphs.
Reading Erlang source really shouldn’t be rocket science. But I’m still struggling to follow the flow-of-control through Erlang applications.
One problem, for me, is this concept of “callback module.” I think I understand it, but the more I think about it the less confident I feel. I’ve tried to find a definition in Google, but failed. It seems to be one of those terms that everyone tosses around thinking that everyone else understands it.
But if I’m hazy, chances are there’s another Newbie or two out there scratching his/her head as well.
Problem for this Newbie is that the concept of “callback module” implies that something is going on behind the curtains. If I’m not all that clear about what’s going on back there, how can I be clear about what’s going on in the foreground?
So here’s my Newbie insight for the day. Caution: it may be wrong. If so, I beseech any passing Erlang wizard to set me straight.
Behaviours in Erlang/OTP are functional templates of oft-repeated code patterns, e.g., servers, finite-state machines, events, supervisors, and applications.
Callback modules fill in the slots in these templates to round out functionality for specific purposes. The “behaviour” is the generic, or abstract, part of the functionality. The “callback module” is the means through which the programmer tailors a behavior for specific application.
So how do we find out what’s going on behind the curtain? Erlang/OTP docs should certainly be our first stop:
Gen_Server Behaviour
“The client-server model is characterized by a central server and an arbitrary number of clients. The client-server model is generally used for resource management operations, where several different clients want to share a common resource. The server is responsible for managing this resource.”
Gen_Fsm Behaviour
“A finite state machine, FSM, can be described as a set of relations of the form:
“State(S) x Event(E) -> Actions(A), State(S’)
“These relations are interpreted as meaning:
“If we are in state S and the event E occurs, we should perform the actions A and make a transition to the state S’.”
Gen_Event Behaviour
“In OTP, an event manager is a named object to which events can be sent. An event could be, for example, an error, an alarm or some information that should be logged.”
Supervisor Behaviour
“A supervisor is responsible for starting, stopping and monitoring its child processes. The basic idea of a supervisor is that it should keep its child processes alive by restarting them when necessary.”
Applications
“When we have written code implementing some specific functionality, we might want to make the code into an application, that is a component that can be started and stopped as a unit, and which can be re-used in other systems as well.”
I’ll pick up on iserve again tomorrow; and try to view it from high overhead with these “behaviours” in mind.
Newbie Test: iserve – start-up logic
April 6, 2009
In our last two posts, March 30 and April 3, we poked into Erlang/OTP conventions, supervisor processes, and application resource files.
Yes, I know, this is supposed to be a Newbie Test. Well, it is. But the opportunity to study how iserve is set up as an Erlang/OTP application is just too good to pass up.
Newbies need to nibble down nifty knowledge at every pass.
iserve’s application resource file, iserve.app, tells us that we must poke into iserve_sup.erl to see how iserve is fired up.
As noted in our March 30 post, you can recognize iserve_sup.erl as a supervisor callback module by its name, *_sup.erl, and the -behviour(supevisor) directive near the top of the iserve_sup.erl module.
iserve_sup.erl exports two functions: start_link/0 and init/1.
Here’s start_link/0.
start_link() -/>
supervisor:start_link({local, ?MODULE}, ?MODULE, []).
supervisor:start_link/3 creates a supervisor process as part of a supervision tree and ensures that the supervisor is linked to the calling process (its supervisor).
Note that the first parameter of supervisor:start_link/3 is of the form {local,Name}.
This means that the supervisor is registered locally as Name using register/2.
register/2 expects a name, Name, and a process identity, P. It associates Name with the port or process identity P.
The second parameter is the name of the callback module, in this case, iserve_sup.erl.
The third parameter is an argument passed to init/1.
So, we fire off iserve:start_link/0. This kicks off a locally registered supervisor process with the name iserve_sup. Our new supervisor now calls init/1 to find out about restart strategy, maximum restart frequency and child processes.
In our case, init/1 starts two new child processes, a supervisors, iserve_server_sup, and a gen_server, iserve_master.
We looked at how supervisor processes are configured in our March 30 post.
Christian kindly provides source comments to help us understand the functions of these two processes:
-
%% The servers supervisor is for keeping individual servers,
%% adding and removing them dynamically
%% The master is for book keeping all running servers and
%% to hold information about them.
So what do we find when we poke into iserve_server_sup?
Well, my eyes are too blurry to find out. But I’ll try to get back to this when the dust settles. Promise.
Back anon.
Note to wizards: corrections/comments welcomed.
Newbie Test: iserve – application resource file
April 3, 2009
March 30 Poking Around Erlang touched on iserve’s application resource file, iserve.app.
If you’re an Erlang newbie, it’s worth studying this file closely. Much can be gleaned about the application you’re setting out to understand.
At risk of boring wizards beyond tears, here is iserve.ap in all it’s glory:
{application, iserve,
[{description, "Web Server"},
{vsn, "%ISERVE_VSN%"},
{modules, [ iserve_sup,
iserve_app,
iserve_server,
iserve_socket
]},
{registered, [ iserve_sup]},
{applications, [kernel, stdlib, sasl]},
{mod, {iserve_app, []}},
{env, [{port, 8080}, {callback, iserve_test}]}]}.
Why is this file important and what does it tell us?
The Erlang app man page is a good place to go for answers.
Erlang/OTP conventions call for one application resource file for each application in the system. The file should be named Application.app, where Application is the name of the application. It should be located in the application’s ebin directory.
The application resource file is read by the application controller when an application is loaded/started. It is also used by functions in systools when generating start scripts.
Note that the structure of the iserve’s resource specification is a series of comma-delimited tuples, Each tuple is prefaced with an atom, italicized below.
I’d hoped to have decoder rings made up, but the following will have to do in the interim:
application (name of the application): iserve
description (one-line description of the application): Web Server
version (version of the application): “%ISERVE_VSN%” NOTE: instantiated elsewhere
modules (all modules introduced by the application): iserve_sup, iserve_app,
iserve_server, iserve_socket
registered (all names of registered processes started in this application): iserve_sup
applications (all applications which must be started before this application is allowed to be started): kernel, stdlib, sasl
mod (application callback module and start argument): iserve_app, []
env (configuration parameters used by the application): port, 8080; callback, iserve_test
So, now we know that among all the files in the iserve directories, we must pay closest attention to iserve_server and iserve_socket to understand functionality. We must start up kernel, stdlib, and sasl before we start iserve. To start iserve, we need to call iserve_sup.
Useful overview for one short file. And the good news is that you’ll find a similar file in the ebin directory of every Erlang/OTP application.
Newbie Test: iserve – poking deeper into the code
March 30, 2009
My March 20 post pointed out how Christian Sunesson’s fork of iserve incorporates OTP system principles.
This must have seemed obvious and a tad tedious to Erlang wizards, but it’s been useful for me as a newbie to stand the rather abstract statements of principle in the official Erlang OTP docs against an actual implementation.
In my experience, you can’t have too many examples to drive an abstract idea home. If I have one generic criticism of the otherwise admirable official Erlang documentation it would be just this: too few code-level examples.
I also found the comparison of iserve source against the OTP docs useful in another way: As a newbie poking into a non-trivial Erlang system, it’s a challenge to know where to start among the plethora of directories, modules, and supporting files as one strives to understand what’s going on.
An understanding of OTP conventions whittles down the challenge considerably.
So, today I’m poking a bit deeper into the mysteries of OTP and iserve. Then, in another post or two I’ll try to lay out my understanding of how iserve works and, maybe, point out a few interesting code phases and idioms that I’ve noticed along the way.
My usual caution: I’m a newbie. If I get something wrong feel free to scold me, but better, please help us rise to better understanding with detailed what and why.
Let’s look first at two files in the iserve src directory: iserve_sup.erl and iserve_server_sup.erl.
When you dive into OTP Design Principles, the first thing you learn is that the supervision tree is a basic concept in Erlang/OTP.
Since you can read as well as I, no need to go too deeply into it here other than to identify iserve_sup.erl and iserve_server_sup.erl as examples of callback functions that tell a more generic OTP supervisor module what to supervise and how. The clue? Note the *_sup.erl module names and the -behaviour(supervisor) directives in each of the modules.
If you open iserve_sup.erl you’ll note that the init/1 function starts and supervises two worker processes, iserve_server_sup.erl and iserve_master.erl.
With guidance from the OTP docs we can further decipher what’s going on:
Here’s specification of the first worker process:
Servers = {servers_sup,
{iserve_server_sup, start_link, [Supervisor]},
permanent, 2000, worker, [iserve_server_sup]},
- servers_sup is the id of the first worker process
- iserve_server_sup, start_link tells the supervisor how start the worker
- Supervisor … frankly, this puzzle me, perhaps you can clear it up for us
- permanent says that the child function should always be restarted
- the integer 2000 is a timeout value.
-
The OTP docs tells that: “An integer timeout value means that the supervisor tells the child process to terminate by calling exit(Child, shutdown) and then waits for an exit signal back. If no exit signal is received within the specified time, the child process is unconditionally terminated using exit(Child, kill). “
- worker tells the supervising process that the child function is a worker process
- iserve_server_sup is the name of the callback module
Here’s the other child process specified in iserver_sup.erl:
Master = {master,
{iserve_master, start_link, [iserve_server_sup]},
permanent, 2000, worker, [iserve_master]},
See if you can decode it. Now open iserver_server_sup.erl and see if the code doesn’t make more sense.
Now let’s look at iserve.app and iserve_app.erl.
The key to understanding these two files may also be found in the Erlang/OTP docs.
When you check it out, you’ll find that iserve_app.erl is an application callback module which specifies how to start and stop the application and iserve.app is an application resource file which specifies which modules the application consists of and the name of the callback module.
So, between the supervision and application files we have a fine road map for understanding the rest of the application.
But, enough for today. My bride will be home soon and it’s my night to bring up dinner.
Best to all.
Tidbits: Webmachine, Ngnix, and More
March 24, 2009
Webmachine
Thanks to alert correspondent Jamaal we’ve just learned that Justin Sheehy has released version 1.0 of Webmachine.
Justin positions Webmachine as “an application layer that adds HTTP semantic awareness on top of the excellent bit-pushing and HTTP syntax-management provided by mochiweb, and provides a simple and clean way to connect that to your application’s behavior.”
He further notes “From the way that Webmachine’s decision core works, it follows that Webmachine’s HTTP behavior is transactional. Each HTTP Request is fully received, and the resulting HTTP Response is then fully constructed before being returned. This means that while Webmachine is suitable for a great many Web applications it is not a good fit for an application that will gradually or continuously stream responses back to clients inside the context of a single HTTP Request.”
Jamaal is smitten by Webmachine, finds it easy to work with. He’s promised notes on his experiences to date; we’re eagerly looking forward to them.
I’m thinking about moving Webmachine up the list as a Newbie Test candidate, but first need to finish up explorations of iserve.
Erlang and Ngnix and ???
Nick Gerakines is experimenting with a C/C++ Ngnix module as a front-end to Erlang.
JLouse says “Pre-process the data in other languages and make them into erlang terms which can be read fast by erlang.”
And adds “… don’t get bitten by the mnesia bug, please. It is almost always the case that mnesia and ETS are the wrong way to go.”
As a Newbie, one the attractions of Erlang was the impression that I didn’t have to pile heterogeneous software environments atop one another to get a job done. But these writers, and others, suggest that Erlang is not up to my hopes and expectations.
So what gives? What’s a Newbie to make of this? Is Erlang:
-
1) Immature? Give it time and it’ll deliver on the promise.
2) Incomplete? Give it time and it’ll embrace ever more functionality.
3) Specialized? It is what is; can’t be all things to all people; live with it.
4) OK as is? These guys may have a point, but by and large it’s sour grapes.
Love to hear from the gray-beard wizard contingent on this topic.
Best Practices
While we’re on the subject of Nick Gerakines, bookmark his list of Erlang Library Best Practices.
Can’t tell you how much this Newbie appreciates words of wisdom from the wise.
Formatting Dates in Erlang
Here’s another one to bookmark… a handy little function for formatting dates.
Newbie Test: iserve – the code
March 20, 2009
A newbie could do worse then spend a few days studying iserve source code.
This newbie is not wise enough to second guess Sean Hinde, Torbjörn Törnkvist, and Christian Sunesson on code quality. But taken as a whole, the iserve project provides a non-trivial model of web server construction. Of perhaps greater newbie value, it demonstrates Erlang and Erlang OTP conventions that every Erlang newbie should understand and emulate.
One could start with Sean Hinde’s original www.trapexit.org posting. But, as a first step, review of Christian Sunesson’s updated source side-by-side with the OTP system and design principles documentation may well be more productive.
Erlang OTP System Principles Section 1.5 lists the file types defined in Erlang OTP. An understanding of the form and function of these file types goes far toward understanding any Erlang OTP project.
Section 7.4 of the Erlang OTP Design Principles documentation suggests a directory structure for OTP applications. This structure makes it easier to make your way around OTP project source listings.
If you download and compile the latest version of iserve, you’ll note the Christian follows the OTP conventions.
We have an ebin directory plump with *.beam object files created during the compilation process.
Ignore the *.beam files in ebin, however, and you note the iserve.app file. This is an Application Resource File described in OTP Design Principles Section 7.3. In this file you’ll find the name of the application, a short description, version, modules, and other useful information.
In the include directory we find iserve.hrl file. See Section 7.1 of the Erlang Reference Manual for include file details. If you open iserve.hrl, you’ll find a record structure that defines a connection between a browser and a server. Sean provides more details.
For more on records, check Section 8 of the Erlang Reference Manual.
We peek now in the src directory and see a handful of *.erl Erlang source files.
But, hold the phone! There’s a second iserve.app file in src. We open it to find that it’s identical to the iserve.app file in the include directory. Why this should be and which is operative… beats me. Maybe one of our wizards can explain.
Among the *.erl files we find two supervision files, iserve_server_sup.erl and iserve_sup.erl. The structure and function of supervision files is documented in Section 5 of OTP Design Principles. Again, beats me why we need two. Is our wizard still around?
Another really really important thing to note can be found in iserve_sup.erl and iserve_server.erl. Grok in on the lines -behavior(xxxx). These lines tell you that you’re looking at callback modules that export pre-defined functions to to implement a common code pattern, in our case, supervision and server functionality.
There’s more to learn here, but the shadows are long and I’m headed out to the movies with my love.
Back soon fair winds willing.
Newbie Test: iserve
March 7, 2009
In days of yore,* circa 2007, trapexit published A fast web server demonstrating some undocumented Erlang features.
The posting, in form of a code walk-through, is terrific. Much to be learned.
The server, called iserve, promises simplicity and speed.
The author, noted only as Sean in the posting, deserves thumbs up on both counts. The author’s full name, says Torbjorn Tornkvist, is Sean Hinde.
In any event, thank you, Sean.
But there’s only one problem. Sean’s posting is just shy of sufficient detail to enable a newbie, at least this newbie, to bring up iserve and build on it.
Fortunately, Torbjorn Tornkvist took interest and put the code into a working OTP application. Then, Christian Sunessons mirrored Tobbe’s code and, as recently as February 28, 2009, has added patches and various tweaks.
See: http://frihjul.net/iserve
Torbjorn Tornkvist notes in private correspondence, “I would recommend you to use mochiweb. It is similar to iserve but much more developed and battle-proven. But for studies and experiments iserve is ok.”
And that’s what I intend to do.
I’m setting out today, in all newbie humility, to see if I can bring up Christian’s incarnation of iserve to see what I can learn from it.
Turns out, bringing up iserve is a newbie delight:
-
1) I opened a console to ~/erlang, the directory I use for messing around in erlang.
2) I entered git clone git://github.com/noss/iserve.git
3) From here, I followed the steps in the iserve/README file, which follow.
-
- cd iserve
- make test
- erl -pa ./test
application:start(sasl).
application:start(iserve).
iserve:add_server(iserve_master, 6464, iserve_test, x).
- Point your browser to http://localhost:6464/
And, by George, it works.
What a joy.
This newbie extends additional thumbs up to Tobbe and Christian. They light the way.
Now, what can I learn from here?
Stay tuned.
Random Tips for Erlang Doc Writers: 1
March 6, 2009
This from Notesgirl, a professional technical writer:
“…subject matter experts (that’s me, now) sometimes leave out steps because they’re just too darn obvious. Unfortunately, that makes for sucky documentation or training materials or presentations… “
See 12:27 PM post