SlideShare una empresa de Scribd logo
1 de 24
Descargar para leer sin conexión
Using OTP and gen_server
effectively



January 19, 2010

Ken Pratt
http://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 packaging
gen_server    Client-server interactions
gen_fsm       Finite state machines
gen_event     Event handlers
supervisor    Process supervision trees
Levels of OTP-ification

1.   Vanilla Erlang
2.   gen_server and gen_...
3.   Supervisor trees
4.   Application packaging
5.   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 timer
    Stop stopwatch timer
    Read timer value

Server:
   Start server
   Stop server
   Maintain stopwatch timer state
   Support client operations
Stopwatch Example - Vanilla Erlang

stopwatch_client.erl
stopwatch_server.erl
http://gist.github.com/279841
Stopwatch Example - gen_server

stopwatch.erl
http://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 code
    No throw/catch hierarchies
    Instead, let the process crash and the supervisor will restart
    it
Supervisor trees

  Multiple restart strategies
  Configurable number of restart tries, intervals, etc
  Support 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.erl
http://gist.github.com/280607
Echo supervisor example

Echo supervisor:
   echo_supervisor:start_link().

echo_supervisor.erl
http://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 Principles
http://www.erlang.org/doc/design_principles/des_princ.html

Más contenido relacionado

La actualidad más candente

Open Telecomunication Platform (OTP)
Open Telecomunication Platform (OTP)Open Telecomunication Platform (OTP)
Open Telecomunication Platform (OTP)
Christophe Marchal
 
How Danga::Socket handles asynchronous processing and how to write asynchrono...
How Danga::Socket handles asynchronous processing and how to write asynchrono...How Danga::Socket handles asynchronous processing and how to write asynchrono...
How Danga::Socket handles asynchronous processing and how to write asynchrono...
Gosuke Miyashita
 

La actualidad más candente (19)

Python Programming Essentials - M27 - Logging module
Python Programming Essentials - M27 - Logging modulePython Programming Essentials - M27 - Logging module
Python Programming Essentials - M27 - Logging module
 
Open Telecomunication Platform (OTP)
Open Telecomunication Platform (OTP)Open Telecomunication Platform (OTP)
Open Telecomunication Platform (OTP)
 
Beyond Unit Testing
Beyond Unit TestingBeyond Unit Testing
Beyond Unit Testing
 
Salesforce Integration using REST SOAP and HTTP callouts
Salesforce Integration using REST SOAP and HTTP calloutsSalesforce Integration using REST SOAP and HTTP callouts
Salesforce Integration using REST SOAP and HTTP callouts
 
How Danga::Socket handles asynchronous processing and how to write asynchrono...
How Danga::Socket handles asynchronous processing and how to write asynchrono...How Danga::Socket handles asynchronous processing and how to write asynchrono...
How Danga::Socket handles asynchronous processing and how to write asynchrono...
 
Flask RESTful Flask HTTPAuth
Flask RESTful Flask HTTPAuthFlask RESTful Flask HTTPAuth
Flask RESTful Flask HTTPAuth
 
Test Driven Development with PHPUnit
Test Driven Development with PHPUnitTest Driven Development with PHPUnit
Test Driven Development with PHPUnit
 
Cell processor lab
Cell processor labCell processor lab
Cell processor lab
 
Rest API using Flask & SqlAlchemy
Rest API using Flask & SqlAlchemyRest API using Flask & SqlAlchemy
Rest API using Flask & SqlAlchemy
 
Client server part 12
Client server part 12Client server part 12
Client server part 12
 
PHPUnit
PHPUnitPHPUnit
PHPUnit
 
Code Igniter Code Sniffer
Code Igniter  Code SnifferCode Igniter  Code Sniffer
Code Igniter Code Sniffer
 
Oracle RDBMS Workshop (Part1)
Oracle RDBMS Workshop (Part1)Oracle RDBMS Workshop (Part1)
Oracle RDBMS Workshop (Part1)
 
Unit testing CourseSites Apache Filter
Unit testing CourseSites Apache FilterUnit testing CourseSites Apache Filter
Unit testing CourseSites Apache Filter
 
Yurii Bodarev - OTP, Phoenix & Ecto: Three Pillars of Elixir
Yurii Bodarev - OTP, Phoenix & Ecto: Three Pillars of ElixirYurii Bodarev - OTP, Phoenix & Ecto: Three Pillars of Elixir
Yurii Bodarev - OTP, Phoenix & Ecto: Three Pillars of Elixir
 
Laporan tugas network programming
Laporan tugas network programmingLaporan tugas network programming
Laporan tugas network programming
 
BEAMing With Joy
BEAMing With JoyBEAMing With Joy
BEAMing With Joy
 
Software Testing
Software TestingSoftware Testing
Software Testing
 
MUST CS101 Lab11
MUST CS101 Lab11 MUST CS101 Lab11
MUST CS101 Lab11
 

Similar a Using OTP and gen_server Effectively

Scalable Apache for Beginners
Scalable Apache for BeginnersScalable Apache for Beginners
Scalable Apache for Beginners
webhostingguy
 
Taming Deployment With Smart Frog
Taming Deployment With Smart FrogTaming Deployment With Smart Frog
Taming Deployment With Smart Frog
Steve Loughran
 

Similar a Using OTP and gen_server Effectively (20)

Functional Testing Swing Applications with Frankenstein
Functional Testing Swing Applications with FrankensteinFunctional Testing Swing Applications with Frankenstein
Functional Testing Swing Applications with Frankenstein
 
Practical catalyst
Practical catalystPractical catalyst
Practical catalyst
 
Hackingtomcat
HackingtomcatHackingtomcat
Hackingtomcat
 
Hacking Tomcat
Hacking TomcatHacking Tomcat
Hacking Tomcat
 
JavaOne 2007 - TS4721
JavaOne 2007 - TS4721 JavaOne 2007 - TS4721
JavaOne 2007 - TS4721
 
Power Shell for System Admins - By Kaustubh
Power Shell for System Admins - By KaustubhPower Shell for System Admins - By Kaustubh
Power Shell for System Admins - By Kaustubh
 
The 90-Day Startup with Google AppEngine for Java
The 90-Day Startup with Google AppEngine for JavaThe 90-Day Startup with Google AppEngine for Java
The 90-Day Startup with Google AppEngine for Java
 
Google App Engine for Java v0.0.2
Google App Engine for Java v0.0.2Google App Engine for Java v0.0.2
Google App Engine for Java v0.0.2
 
Understanding Framework Architecture using Eclipse
Understanding Framework Architecture using EclipseUnderstanding Framework Architecture using Eclipse
Understanding Framework Architecture using Eclipse
 
Scalable Apache for Beginners
Scalable Apache for BeginnersScalable Apache for Beginners
Scalable Apache for Beginners
 
Complex Event Processing - A brief overview
Complex Event Processing - A brief overviewComplex Event Processing - A brief overview
Complex Event Processing - A brief overview
 
JDD 2016 - Grzegorz Rozniecki - Java 8 What Could Possibly Go Wrong
JDD 2016 - Grzegorz Rozniecki - Java 8 What Could Possibly Go WrongJDD 2016 - Grzegorz Rozniecki - Java 8 What Could Possibly Go Wrong
JDD 2016 - Grzegorz Rozniecki - Java 8 What Could Possibly Go Wrong
 
Apache Deltacloud (Linuxcon 2010)
Apache Deltacloud (Linuxcon 2010)Apache Deltacloud (Linuxcon 2010)
Apache Deltacloud (Linuxcon 2010)
 
Dave Orchard - Offline Web Apps with HTML5
Dave Orchard - Offline Web Apps with HTML5Dave Orchard - Offline Web Apps with HTML5
Dave Orchard - Offline Web Apps with HTML5
 
Taming Deployment With Smart Frog
Taming Deployment With Smart FrogTaming Deployment With Smart Frog
Taming Deployment With Smart Frog
 
Spine.js
Spine.jsSpine.js
Spine.js
 
Apache Eagle: Architecture Evolvement and New Features
Apache Eagle: Architecture Evolvement and New FeaturesApache Eagle: Architecture Evolvement and New Features
Apache Eagle: Architecture Evolvement and New Features
 
When Web Services Go Bad
When Web Services Go BadWhen Web Services Go Bad
When Web Services Go Bad
 
jBPM5 in action - a quickstart for developers
jBPM5 in action - a quickstart for developersjBPM5 in action - a quickstart for developers
jBPM5 in action - a quickstart for developers
 
Implementing the Genetic Algorithm in XSLT: PoC
Implementing the Genetic Algorithm in XSLT: PoCImplementing the Genetic Algorithm in XSLT: PoC
Implementing the Genetic Algorithm in XSLT: PoC
 

Último

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Último (20)

ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 

Using OTP and gen_server Effectively

  • 1. Using OTP and gen_server effectively January 19, 2010 Ken Pratt http://kenpratt.net/
  • 2. OTP = "Open Telecom Platform" A set of Erlang libraries designed for fault tolerance and portability. Now part of the Erlang standard library.
  • 3. Behaviours A formalization of Erlang design patterns. Enforce an interface, but have some implementation too. Kind of like an abstract class in Java.
  • 4. OTP Behaviours application Erlang application packaging gen_server Client-server interactions gen_fsm Finite state machines gen_event Event handlers supervisor Process supervision trees
  • 5. Levels of OTP-ification 1. Vanilla Erlang 2. gen_server and gen_... 3. Supervisor trees 4. Application packaging 5. Releases (& boot scripts) 6. Live upgrade support
  • 6. gen_server A behaviour for client-server-like interactions. (not necessarily a strict client-server model)
  • 7. Stopwatch Example Simple stopwatch client & server Client: Start stopwatch timer Stop stopwatch timer Read timer value Server: Start server Stop server Maintain stopwatch timer state Support client operations
  • 8. Stopwatch Example - Vanilla Erlang stopwatch_client.erl stopwatch_server.erl http://gist.github.com/279841
  • 9. Stopwatch Example - gen_server stopwatch.erl http://gist.github.com/279844
  • 10. 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
  • 11. Actors "Actually I made up the term "object-oriented", and I can tell you I did not have C++ in mind." - Alan Kay
  • 12. 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).
  • 13. Actor/gen_server examples Web server: State: {Cookies} Call: process_request(Headers, Body) Cast: clear_cache() Cast: stop()
  • 14. 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()
  • 15. Actor/gen_server examples Database connection: State: {ConnectionPid} or maybe {TcpSocket} Call: execute_sql(Sql) Call: close()
  • 17. 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 code No throw/catch hierarchies Instead, let the process crash and the supervisor will restart it
  • 18. Supervisor trees Multiple restart strategies Configurable number of restart tries, intervals, etc Support for dynamic children (removing and adding children at runtime)
  • 19. 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.erl http://gist.github.com/280607
  • 20. Echo supervisor example Echo supervisor: echo_supervisor:start_link(). echo_supervisor.erl http://gist.github.com/280618
  • 21. 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.
  • 22. 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.
  • 23. 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/
  • 24. Books covering OTP Only the basics Only the basics Intermediate Erlang Design Principles http://www.erlang.org/doc/design_principles/des_princ.html