SlideShare ist ein Scribd-Unternehmen logo
1 von 24
Downloaden Sie, um offline zu lesen
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

Weitere ähnliche Inhalte

Was ist angesagt?

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
 

Was ist angesagt? (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
 

Ähnlich wie 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
 

Ähnlich wie 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
 

Kürzlich hochgeladen

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
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Kürzlich hochgeladen (20)

Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
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
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
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...
 
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...
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
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
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
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
 
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
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 

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