Using OTP and gen_server Effectively

Preview:

DESCRIPTION

(Given to the Vancouver Erlang Meetup group on January 19, 2010.)Wondering how to model things in Erlang, and what the Actor model is all about? This talk will cover the best of Erlang OTP, delve into using gen_server to model systems in Erlang, and demonstrate the use of supervisor trees to ensure your application stays alive and well. Those new to Erlang might want to look over an intro first, but should still gleam some insights from this talk either way.Speaker Bio:Ken Pratt has been working with Erlang full time since the beginning of 2009, which makes him slightly less of an Erlang noob than he was previously. Ken holds a B.Sc. in Computer Science from UBC, and is currently hard at work developing a social networking game at Pug Pharm Productions.

Citation preview

Using OTP and gen_servereffectively

January 19, 2010

Ken Pratthttp://kenpratt.net/

OTP = "Open Telecom Platform"

A set of Erlang libraries designed for fault tolerance and portability.

Now part of the Erlang standard library.

Behaviours

A formalization of Erlang design patterns.

Enforce an interface, but have some implementation too.

Kind of like an abstract class in Java.

OTP Behaviours

application Erlang application packaginggen_server Client-server interactionsgen_fsm Finite state machinesgen_event Event handlerssupervisor Process supervision trees

Levels of OTP-ification

1. Vanilla Erlang2. gen_server and gen_...3. Supervisor trees4. Application packaging5. Releases (& boot scripts)6. Live upgrade support

gen_server

A behaviour for client-server-like interactions.

(not necessarily a strict client-server model)

Stopwatch Example

Simple stopwatch client & server

Client:Start stopwatch timerStop stopwatch timerRead timer value

Server:Start serverStop serverMaintain stopwatch timer stateSupport client operations

Stopwatch Example - Vanilla Erlang

stopwatch_client.erlstopwatch_server.erlhttp://gist.github.com/279841

Stopwatch Example - gen_server

stopwatch.erlhttp://gist.github.com/279844

Actors

"OOP to me means only messaging, local retention and protection and hiding of state-process, and extreme late-binding of all things. It can be done in Smalltalk and in LISP. There are possibly other systems in which this is possible, but I'm not aware of them." - Alan Kay, father of Smalltalk

Actors

"Actually I made up the term "object-oriented", and I can tell you I did not have C++ in mind." - Alan Kay

Actors

You can model systems using gen_server much like you would model in an OOP.

Since gen_server synchronizes access to its' internal state, an entire class of programming errors is sidestepped.

(That said, you can still have race conditions between different gen_server modules or clients of those).

Actor/gen_server examples

Web server:State: {Cookies}Call: process_request(Headers, Body)Cast: clear_cache()Cast: stop()

Actor/gen_server examples

Chat room:State: {ActiveUsers, ChatLog}Call: enter_room(Handle)Call: leave_room(Handle)Cast: say(Handle, Message)Call: view_log()Cast: stop()

Actor/gen_server examples

Database connection:State: {ConnectionPid} or maybe {TcpSocket}Call: execute_sql(Sql)Call: close()

Supervisor trees

Supervisor trees

Supervisors monitor their children, and attempt to restart them if they die unexpectedly.

Erlang philosophy is to "let it crash":No huge amounts of error handling codeNo throw/catch hierarchiesInstead, let the process crash and the supervisor will restart it

Supervisor trees

Multiple restart strategiesConfigurable number of restart tries, intervals, etcSupport for dynamic children (removing and adding children at runtime)

Echo server example

Echo server:echo_server:start_link(dog, "Woof!", 3000).echo_server:echo(dog).echo_server:stop(dog).echo_server:assassinate(dog).

echo_server.erlhttp://gist.github.com/280607

Echo supervisor example

Echo supervisor:echo_supervisor:start_link().

echo_supervisor.erlhttp://gist.github.com/280618

gen_fsm

gen_fsm is sort of a super-gen_server.

You define all the states and events, and then the transitions.

Can do async events and sync events.

Earlier stopwatch example would probably be better off as a state machine if it had more features.

gen_event

gen_event can be used to set up chains of event handling for things like alarms, statistics, and debug traces.

But in reality, it is mostly just used for logging.

Other tips

Automatic code reloader (handy for development):http://code.google.com/p/mochiweb/source/browse/trunk/src/reloader.erl

Log4erl (if you want a more standard logger):http://github.com/dilshod/log4erl

Appmon - built-in application monitor/viewer

AJAX-y docs - http://erldocs.com/

Books covering OTP

Only the basics Only the basics Intermediate

Erlang Design Principleshttp://www.erlang.org/doc/design_principles/des_princ.html