SlideShare une entreprise Scribd logo
1  sur  144
Télécharger pour lire hors ligne
Erlang/OTP in Riak
Twitter: @Sargun
Chief Solutions Architect, Basho
Erlang/OTP
History
“To provide a better way of programming
telephony applications”
The Mission
Birthplace:
Ericsson Computer
Science Lab
Requirements
• Handling a very large number of concurrent activities
• Actions to be performed at a certain point of time or within a certain time
• Systems distributed over several computers
• Interaction with hardware must be abstracted
• Very large software systems
• Complex functionality such as feature interaction
• Continuous operation over several years
• Software maintenance (reconfiguration, etc.) without stopping the system
• Stringent quality and reliability requirements
• Fault tolerance both to hardware failures and software errors
Relation of Erlang to existing languages.
"A History of Erlang”
COP: Concurrency Oriented
Programming
• Systems are built from processes.
• Process share nothing.
• Processes interact by asynchronous message
passing.
• Processes are isolated.
AXD301: Success
• Came out in 1998
• ATM switch, control-plane written in Erlang
• 2.6 Million lines of Erlang code
• Nine-nines of uptime: 99.99999999%
• Built highly reliable systems from unreliable
components
• Scale-out
Erlang
• Only accessible to the community since December
1998
• Designed for telephony control planes
• Actor Model
• Functional
Universal Server
Universal Server
1>	
  UniversalServer	
  =	
  
1>	
  fun	
  US()	
  -­‐>	
  
1>	
  	
  	
  receive	
  {become,	
  F}	
  -­‐>	
  
1>	
  	
  	
  	
  	
  F()	
  
1>	
  	
  	
  end	
  
1>	
  end.	
  
#Fun<erl_eval.44.90072148>	
  
Named Funs (Lambda)
1>	
  UniversalServer	
  =	
  
1>	
  fun	
  US()	
  -­‐>	
  
1>	
  	
  	
  receive	
  {become,	
  F}	
  -­‐>	
  
1>	
  	
  	
  	
  	
  F()	
  
1>	
  	
  	
  end	
  
1>	
  end.	
  
#Fun<erl_eval.44.90072148>	
  
Message Passing
1>	
  UniversalServer	
  =	
  
1>	
  fun	
  US()	
  -­‐>	
  
1>	
  	
  	
  receive	
  {become,	
  F}	
  -­‐>	
  
1>	
  	
  	
  	
  	
  F()	
  
1>	
  	
  	
  end	
  
1>	
  end.	
  
#Fun<erl_eval.44.90072148>	
  
Lightweight Processes
2>	
  Server	
  =	
  spawn(UniversalServer).	
  
<0.45.0>	
  
Detour:
Calculating Factorials
Recurrence Relation
Calculating Factorials
5>	
  FC	
  =	
  fun	
  
5>	
  	
  	
  Factorial(0)	
  -­‐>	
  1;	
  
5>	
  	
  	
  Factorial(N)	
  -­‐>	
  N	
  *	
  Factorial(N-­‐1)	
  
5>	
  end.	
  
#Fun<erl_eval.30.90072148>	
  
It Works!
8>	
  FC(10).	
  
3628800	
  
Turning It Into A Server
9>	
  FServer	
  =	
  
9>	
  fun	
  FactorialServer()	
  -­‐>	
  
9>	
  	
  	
  	
  	
  receive	
  
9>	
  	
  	
  	
  	
  	
  	
  	
  {From,	
  N}	
  -­‐>	
  
9>	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  From	
  !	
  FC(N),	
  
9>	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  FactorialServer()	
  
9>	
  	
  	
  	
  	
  end	
  	
  
9>	
  end.	
  
#Fun<erl_eval.44.90072148>	
  
Converting the Server
10>	
  Server	
  !	
  {become,	
  FServer}.	
  
{become,#Fun<erl_eval.44.90072148>}
Testing It Out
11>	
  Server	
  !	
  {self(),	
  10}.	
  
{<0.42.0>,10}	
  
12>	
  flush().	
  
Shell	
  got	
  3628800	
  
As A Module
As A Module
-­‐module(factorial_server).	
  
-­‐export([start_link/0,	
  calc/2,	
  server/0]).	
  
start_link()	
  -­‐>	
  
	
  	
  spawn_link(?MODULE,	
  server,	
  []).	
  	
  
calc(X,	
  Pid)	
  -­‐>	
  
	
  	
  Pid	
  !	
  {self(),	
  X},	
  
	
  	
  receive	
  N	
  -­‐>	
  N	
  end.	
  
server()	
  -­‐>	
  
	
  	
  receive	
  
	
  	
  	
  	
  {From,	
  N}	
  -­‐>	
  
	
  	
  	
  	
  	
  	
  From	
  !	
  factorial(N),	
  
	
  	
  	
  	
  	
  	
  server()	
  
	
  	
  end.	
  
factorial(0)	
  -­‐>	
  1;	
  
factorial(N)	
  -­‐>	
  N	
  *	
  factorial(N-­‐1).	
  
Module name
-­‐module(factorial_server).	
  
-­‐export([start_link/0,	
  calc/2,	
  server/0]).	
  
start_link()	
  -­‐>	
  
	
  	
  spawn_link(?MODULE,	
  server,	
  []).	
  	
  
calc(X,	
  Pid)	
  -­‐>	
  
	
  	
  Pid	
  !	
  {self(),	
  X},	
  
	
  	
  receive	
  N	
  -­‐>	
  N	
  end.	
  
server()	
  -­‐>	
  
	
  	
  receive	
  
	
  	
  	
  	
  {From,	
  N}	
  -­‐>	
  
	
  	
  	
  	
  	
  	
  From	
  !	
  factorial(N),	
  
	
  	
  	
  	
  	
  	
  server()	
  
	
  	
  end.	
  
factorial(0)	
  -­‐>	
  1;	
  
factorial(N)	
  -­‐>	
  N	
  *	
  factorial(N-­‐1).	
  
Exports
-­‐module(factorial_server).	
  
-­‐export([start_link/0,	
  calc/2,	
  server/0]).	
  
start_link()	
  -­‐>	
  
	
  	
  spawn_link(?MODULE,	
  server,	
  []).	
  	
  
calc(X,	
  Pid)	
  -­‐>	
  
	
  	
  Pid	
  !	
  {self(),	
  X},	
  
	
  	
  receive	
  N	
  -­‐>	
  N	
  end.	
  
server()	
  -­‐>	
  
	
  	
  receive	
  
	
  	
  	
  	
  {From,	
  N}	
  -­‐>	
  
	
  	
  	
  	
  	
  	
  From	
  !	
  factorial(N),	
  
	
  	
  	
  	
  	
  	
  server()	
  
	
  	
  end.	
  
factorial(0)	
  -­‐>	
  1;	
  
factorial(N)	
  -­‐>	
  N	
  *	
  factorial(N-­‐1).	
  
Start Module
-­‐module(factorial_server).	
  
-­‐export([start_link/0,	
  calc/2,	
  server/0]).	
  
start_link()	
  -­‐>	
  
	
  	
  spawn_link(?MODULE,	
  server,	
  []).	
  	
  
calc(X,	
  Pid)	
  -­‐>	
  
	
  	
  Pid	
  !	
  {self(),	
  X},	
  
	
  	
  receive	
  N	
  -­‐>	
  N	
  end.	
  
server()	
  -­‐>	
  
	
  	
  receive	
  
	
  	
  	
  	
  {From,	
  N}	
  -­‐>	
  
	
  	
  	
  	
  	
  	
  From	
  !	
  factorial(N),	
  
	
  	
  	
  	
  	
  	
  server()	
  
	
  	
  end.	
  
factorial(0)	
  -­‐>	
  1;	
  
factorial(N)	
  -­‐>	
  N	
  *	
  factorial(N-­‐1).	
  
Client Interface
-­‐module(factorial_server).	
  
-­‐export([start_link/0,	
  calc/2,	
  server/0]).	
  
start_link()	
  -­‐>	
  
	
  	
  spawn_link(?MODULE,	
  server,	
  []).	
  	
  
calc(X,	
  Pid)	
  -­‐>	
  
	
  	
  Pid	
  !	
  {self(),	
  X},	
  
	
  	
  receive	
  N	
  -­‐>	
  N	
  end.	
  
server()	
  -­‐>	
  
	
  	
  receive	
  
	
  	
  	
  	
  {From,	
  N}	
  -­‐>	
  
	
  	
  	
  	
  	
  	
  From	
  !	
  factorial(N),	
  
	
  	
  	
  	
  	
  	
  server()	
  
	
  	
  end.	
  
factorial(0)	
  -­‐>	
  1;	
  
factorial(N)	
  -­‐>	
  N	
  *	
  factorial(N-­‐1).	
  
Server Loop
-­‐module(factorial_server).	
  
-­‐export([start_link/0,	
  calc/2,	
  server/0]).	
  
start_link()	
  -­‐>	
  
	
  	
  spawn_link(?MODULE,	
  server,	
  []).	
  	
  
calc(X,	
  Pid)	
  -­‐>	
  
	
  	
  Pid	
  !	
  {self(),	
  X},	
  
	
  	
  receive	
  N	
  -­‐>	
  N	
  end.	
  
server()	
  -­‐>	
  
	
  	
  receive	
  
	
  	
  	
  	
  {From,	
  N}	
  -­‐>	
  
	
  	
  	
  	
  	
  	
  From	
  !	
  factorial(N),	
  
	
  	
  	
  	
  	
  	
  server()	
  
	
  	
  end.	
  
factorial(0)	
  -­‐>	
  1;	
  
factorial(N)	
  -­‐>	
  N	
  *	
  factorial(N-­‐1).	
  
Calculator
-­‐module(factorial_server).	
  
-­‐export([start_link/0,	
  calc/2,	
  server/0]).	
  
start_link()	
  -­‐>	
  
	
  	
  spawn_link(?MODULE,	
  server,	
  []).	
  	
  
calc(X,	
  Pid)	
  -­‐>	
  
	
  	
  Pid	
  !	
  {self(),	
  X},	
  
	
  	
  receive	
  N	
  -­‐>	
  N	
  end.	
  
server()	
  -­‐>	
  
	
  	
  receive	
  
	
  	
  	
  	
  {From,	
  N}	
  -­‐>	
  
	
  	
  	
  	
  	
  	
  From	
  !	
  factorial(N),	
  
	
  	
  	
  	
  	
  	
  server()	
  
	
  	
  end.	
  
factorial(0)	
  -­‐>	
  1;	
  
factorial(N)	
  -­‐>	
  N	
  *	
  factorial(N-­‐1).	
  
Using The Module
8>	
  Pid	
  =	
  factorial_server:start_link().	
  
<0.72.0>	
  
9>	
  factorial_server:calc(10,	
  Pid).	
  
3628800	
  
Error Handling
Introduce A Bug
factorial(0)	
  -­‐>	
  1;	
  
factorial(10)	
  -­‐>	
  1=2;	
  
factorial(N)	
  -­‐>	
  N	
  *	
  factorial(N-­‐1).	
  
Trigger The Bug
9>	
  factorial_server:calc(10,	
  Pid).	
  
	
  	
  
=ERROR	
  REPORT====	
  5-­‐Apr-­‐2015::06:04:40	
  ===	
  
Error	
  in	
  process	
  <0.59.0>	
  with	
  exit	
  value:	
  {{badmatch,2},
[{factorial_server,factorial,1,[{file,"factorial_server.erl"},{line,
15}]},{factorial_server,server,0,[{file,"factorial_server.erl"},{line,
11}]}]}	
  
	
  	
  
**	
  exception	
  exit:	
  {badmatch,2}	
  
	
  	
  	
  	
  	
  in	
  function	
  	
  factorial_server:factorial/1	
  (factorial_server.erl,	
  
line	
  15)	
  
	
  	
  	
  	
  	
  in	
  call	
  from	
  factorial_server:server/0	
  (factorial_server.erl,	
  line	
  
11)	
  
Ping The Server Again?
10>	
  	
  
10>	
  factorial_server:calc(10,	
  Pid).	
  
...Hangs	
  Forever	
  
OTP
Behaviours
Behaviours are formalizations of common
patterns. The idea is to divide the code for
a process in a generic part (a behaviour
module) and a specific part (a callback
module).
Gen_Server
A behaviour module for
implementing the server
of a client-server relation.
As An OTP Module
-­‐module(factorial_server_otp).	
  
-­‐behaviour(gen_server).	
  
-­‐export([start_link/0,	
  init/1,	
  handle_call/3,	
  	
  
terminate/2,	
  code_change/3]).	
  
start_link()	
  -­‐>	
  gen_server:start_link({local,	
  ?MODULE},	
  ?MODULE,	
  [],	
  []).	
  
init([])	
  -­‐>	
  {ok,	
  state}.	
  
handle_call(X,	
  _From,	
  state)	
  -­‐>	
  
	
  	
  {reply,	
  factorial(X),	
  state}.	
  
	
  	
  
factorial(0)	
  -­‐>	
  1;	
  
factorial(N)	
  -­‐>	
  N	
  *	
  factorial(N-­‐1).	
  
	
  	
  
terminate(shutdown,	
  state)	
  -­‐>	
  ok.	
  
code_change(_OldVsn,	
  state,	
  _Extra)	
  -­‐>	
  {ok,	
  state}.	
  
Behaviour Definition
-­‐module(factorial_server_otp).	
  
-­‐behaviour(gen_server).	
  
-­‐export([start_link/0,	
  init/1,	
  handle_call/3,	
  	
  
terminate/2,	
  code_change/3]).	
  
start_link()	
  -­‐>	
  gen_server:start_link({local,	
  ?MODULE},	
  ?MODULE,	
  [],	
  []).	
  
init([])	
  -­‐>	
  {ok,	
  state}.	
  
handle_call(X,	
  _From,	
  state)	
  -­‐>	
  
	
  	
  {reply,	
  factorial(X),	
  state}.	
  
	
  	
  
factorial(0)	
  -­‐>	
  1;	
  
factorial(N)	
  -­‐>	
  N	
  *	
  factorial(N-­‐1).	
  
	
  	
  
terminate(shutdown,	
  state)	
  -­‐>	
  ok.	
  
code_change(_OldVsn,	
  state,	
  _Extra)	
  -­‐>	
  {ok,	
  state}.	
  
Start Gen_Server
-­‐module(factorial_server_otp).	
  
-­‐behaviour(gen_server).	
  
-­‐export([start_link/0,	
  init/1,	
  handle_call/3,	
  	
  
terminate/2,	
  code_change/3]).	
  
start_link()	
  -­‐>	
  gen_server:start_link({local,	
  ?MODULE},	
  ?MODULE,	
  [],	
  []).	
  
init([])	
  -­‐>	
  {ok,	
  state}.	
  
handle_call(X,	
  _From,	
  state)	
  -­‐>	
  
	
  	
  {reply,	
  factorial(X),	
  state}.	
  
	
  	
  
factorial(0)	
  -­‐>	
  1;	
  
factorial(N)	
  -­‐>	
  N	
  *	
  factorial(N-­‐1).	
  
	
  	
  
terminate(shutdown,	
  state)	
  -­‐>	
  ok.	
  
code_change(_OldVsn,	
  state,	
  _Extra)	
  -­‐>	
  {ok,	
  state}.	
  
Setup Server
-­‐module(factorial_server_otp).	
  
-­‐behaviour(gen_server).	
  
-­‐export([start_link/0,	
  init/1,	
  handle_call/3,	
  	
  
terminate/2,	
  code_change/3]).	
  
start_link()	
  -­‐>	
  gen_server:start_link({local,	
  ?MODULE},	
  ?MODULE,	
  [],	
  []).	
  
init([])	
  -­‐>	
  {ok,	
  state}.	
  
handle_call(X,	
  _From,	
  state)	
  -­‐>	
  
	
  	
  {reply,	
  factorial(X),	
  state}.	
  
	
  	
  
factorial(0)	
  -­‐>	
  1;	
  
factorial(N)	
  -­‐>	
  N	
  *	
  factorial(N-­‐1).	
  
	
  	
  
terminate(shutdown,	
  state)	
  -­‐>	
  ok.	
  
code_change(_OldVsn,	
  state,	
  _Extra)	
  -­‐>	
  {ok,	
  state}.	
  
Server Reply Handler
-­‐module(factorial_server_otp).	
  
-­‐behaviour(gen_server).	
  
-­‐export([start_link/0,	
  init/1,	
  handle_call/3,	
  	
  
terminate/2,	
  code_change/3]).	
  
start_link()	
  -­‐>	
  gen_server:start_link({local,	
  ?MODULE},	
  ?MODULE,	
  [],	
  []).	
  
init([])	
  -­‐>	
  {ok,	
  state}.	
  
handle_call(X,	
  _From,	
  state)	
  -­‐>	
  
	
  	
  {reply,	
  factorial(X),	
  state}.	
  
	
  	
  
factorial(0)	
  -­‐>	
  1;	
  
factorial(N)	
  -­‐>	
  N	
  *	
  factorial(N-­‐1).	
  
	
  	
  
terminate(shutdown,	
  state)	
  -­‐>	
  ok.	
  
code_change(_OldVsn,	
  state,	
  _Extra)	
  -­‐>	
  {ok,	
  state}.	
  
Internal Callbacks
-­‐module(factorial_server_otp).	
  
-­‐behaviour(gen_server).	
  
-­‐export([start_link/0,	
  init/1,	
  handle_call/3,	
  	
  
terminate/2,	
  code_change/3]).	
  
start_link()	
  -­‐>	
  gen_server:start_link({local,	
  ?MODULE},	
  ?MODULE,	
  [],	
  []).	
  
init([])	
  -­‐>	
  {ok,	
  state}.	
  
handle_call(X,	
  _From,	
  state)	
  -­‐>	
  
	
  	
  {reply,	
  factorial(X),	
  state}.	
  
	
  	
  
factorial(0)	
  -­‐>	
  1;	
  
factorial(N)	
  -­‐>	
  N	
  *	
  factorial(N-­‐1).	
  
	
  	
  
terminate(shutdown,	
  state)	
  -­‐>	
  ok.	
  
code_change(_OldVsn,	
  state,	
  _Extra)	
  -­‐>	
  {ok,	
  state}.	
  
Using The OTP Module
1>	
  factorial_server_otp:start_link().	
  
{ok,<0.34.0>}	
  
2>	
  gen_server:call(factorial_server_otp,	
  9).	
  
362880	
  
Triggering The Bug
5>	
  gen_server:call(factorial_server_otp,	
  10).	
  
	
  	
  
=ERROR	
  REPORT====	
  5-­‐Apr-­‐2015::06:03:43	
  ===	
  
**	
  Generic	
  server	
  factorial_server_otp	
  
terminating	
  	
  
**	
  Last	
  message	
  in	
  was	
  10	
  
**	
  When	
  Server	
  state	
  ==	
  state	
  
**	
  Reason	
  for	
  termination	
  ==	
  	
  
…
Subsequent Calls
6>	
  gen_server:call(factorial_server_otp,	
  10).	
  
**	
  exception	
  exit:	
  {noproc,{gen_server,call,
[factorial_server_otp,10]}}	
  
	
  	
  	
  	
  	
  in	
  function	
  	
  gen_server:call/2	
  
(gen_server.erl,	
  line	
  180)	
  
Detour:
Links,
Supervisors,
&
Applications
Links
Begin
spawn_link()
Bidirectional Link Forms
Process Dies
Cohort is Terminated
Supervisors
A behaviour module for
implementing a supervisor, a
process which supervises other
processes called child processes.
Factorial Supervisor
-­‐module(factorial_server_sup).	
  
-­‐behaviour(supervisor).	
  
	
  	
  
-­‐export([start_link/0]).	
  
-­‐export([init/1]).	
  
	
  	
  
start_link()	
  -­‐>	
  
	
  	
  supervisor:start_link({local,	
  factorial_server_sup},	
  ?MODULE,	
  []).	
  
	
  	
  
init(_Args)	
  -­‐>	
  
	
  	
  {ok,	
  {{one_for_one,	
  1,	
  60},	
  
	
  	
  	
  	
  [{factorial_server_otp,	
  {factorial_server_otp,	
  start_link,	
  []},	
  
	
  	
  	
  	
  permanent,	
  brutal_kill,	
  worker,	
  dynamic}]}}.	
  
Child Specs
-­‐module(factorial_server_sup).	
  
-­‐behaviour(supervisor).	
  
	
  	
  
-­‐export([start_link/0]).	
  
-­‐export([init/1]).	
  
	
  	
  
start_link()	
  -­‐>	
  
	
  	
  supervisor:start_link({local,	
  factorial_server_sup},	
  ?MODULE,	
  []).	
  
	
  	
  
init(_Args)	
  -­‐>	
  
	
  	
  {ok,	
  {{one_for_one,	
  1,	
  60},	
  
	
  	
  	
  	
  [{factorial_server_otp,	
  {factorial_server_otp,	
  start_link,	
  []},	
  
	
  	
  	
  	
  permanent,	
  brutal_kill,	
  worker,	
  dynamic}]}}.	
  
Applications
In OTP, application denotes a component
implementing some specific functionality,
that can be started and stopped as a unit,
and which can be re-used in other systems
as well.
Application Resource File
{application,	
  factorial_server,	
  
	
  [{description,	
  "Factorial	
  Calculator"},	
  
	
  	
  {vsn,	
  "1"},	
  
	
  	
  {modules,	
  [factorial_server_otp,	
  
	
  	
  	
  	
  factorial_server_app,	
  
	
  	
  	
  	
  factorial_server_sup]},	
  
	
  	
  {registered,	
  []},	
  
	
  	
  {applications,	
  [kernel,	
  stdlib,	
  sasl]},	
  
	
  	
  {mod,	
  {factorial_server_app,[]}}	
  
	
  ]}.	
  
Dependencies
{application,	
  factorial_server,	
  
	
  [{description,	
  "Factorial	
  Calculator"},	
  
	
  	
  {vsn,	
  "1"},	
  
	
  	
  {modules,	
  [factorial_server_otp,	
  
	
  	
  	
  	
  factorial_server_app,	
  
	
  	
  	
  	
  factorial_server_sup]},	
  
	
  	
  {registered,	
  []},	
  
	
  	
  {applications,	
  [kernel,	
  stdlib,	
  sasl]},	
  
	
  	
  {mod,	
  {factorial_server_app,[]}}	
  
	
  ]}.	
  
Modules
{application,	
  factorial_server,	
  
	
  [{description,	
  "Factorial	
  Calculator"},	
  
	
  	
  {vsn,	
  "1"},	
  
	
  	
  {modules,	
  [factorial_server_otp,	
  
	
  	
  	
  	
  factorial_server_app,	
  
	
  	
  	
  	
  factorial_server_sup]},	
  
	
  	
  {registered,	
  []},	
  
	
  	
  {applications,	
  [kernel,	
  stdlib,	
  sasl]},	
  
	
  	
  {mod,	
  {factorial_server_app,[]}}	
  
	
  ]}.	
  
Callback Module
{application,	
  factorial_server,	
  
	
  [{description,	
  "Factorial	
  Calculator"},	
  
	
  	
  {vsn,	
  "1"},	
  
	
  	
  {modules,	
  [factorial_server_otp,	
  
	
  	
  	
  	
  factorial_server_app,	
  
	
  	
  	
  	
  factorial_server_sup]},	
  
	
  	
  {registered,	
  []},	
  
	
  	
  {applications,	
  [kernel,	
  stdlib,	
  sasl]},	
  
	
  	
  {mod,	
  {factorial_server_app,[]}}	
  
	
  ]}.	
  
Application Callback
Module
-­‐module(factorial_server_app).	
  
-­‐behaviour(application).	
  
	
  	
  
-­‐export([start/2,	
  stop/1]).	
  
	
  	
  
start(_Type,	
  _Args)	
  -­‐>	
  
	
  	
  factorial_server_sup:start_link().	
  
	
  	
  
stop(_State)	
  -­‐>	
  
	
  	
  ok.	
  
Using It
3>	
  application:ensure_all_started(factorial_server).	
  
{ok,[]}	
  
Observer
Observer, is a graphical tool for observing the
characteristics of erlang systems. Observer displays
system information, application supervisor trees, process
information, ets or mnesia tables and contains a frontend
for erlang tracing.
Observer: Factorial Server
Introspecting Program State
Review
• Factorial Server is now OTP Application
• gen_server
• supervisor
• application
• Factorial Server has a bug where it crashes at
numbers >10.
• Gen_server crashes handled by supervision tree
Try Again
8>	
  gen_server:call(factorial_server_otp,	
  10).	
  
	
  	
  
=ERROR	
  REPORT====	
  5-­‐Apr-­‐2015::07:45:00	
  ===	
  
**	
  Generic	
  server	
  factorial_server_otp	
  terminating	
  	
  
**	
  Last	
  message	
  in	
  was	
  10	
  
**	
  When	
  Server	
  state	
  ==	
  state	
  
**	
  Reason	
  for	
  termination	
  ==	
  	
  
...	
  
New Behaviour
9>	
  gen_server:call(factorial_server_otp,	
  9).	
  	
  
362880	
  
Live Code Patch
17>	
  c(factorial_server_otp).	
  
{ok,factorial_server_otp}
Now
18>	
  gen_server:call(factorial_server_otp,	
  12).	
  
479001600	
  
Erlang/OTP
• OTP provides framework for simplifying actor
model
• Error handling semantics through crashing
• Provides model for DRY code
Distributed
“You cannot build a fault-
tolerant system if you
only have one computer”
A History of Erlang
EPMD
This daemon acts as a name
server on all hosts involved in
distributed Erlang computations.
Intra-System
Distributed Erlang
EPMD Acts as Broker
EPMD Responds
BEAM: Initial Contact
Bidirectional Communication
Inter-System
Inter-System
Initial Contact
Responds With Host List
BEAM: Initial Contact
Bidirectional Communication
In Practice
Node 1: Foo
3c075477e55e:talk	
  sdhillon	
  erl	
  -­‐sname	
  foo	
  
Erlang	
  R16B03-­‐1	
  (erts-­‐5.10.4)	
  [source]	
  [64-­‐bit]	
  [smp:8:8]	
  [async-­‐threads:
10]	
  [hipe]	
  [kernel-­‐poll:false]	
  
	
  	
  
Eshell	
  V5.10.4	
  	
  (abort	
  with	
  ^G)	
  
(foo@3c075477e55e)1>	
  application:ensure_all_started(factorial_server).	
  
{ok,[sasl,factorial_server]}	
  
(foo@3c075477e55e)2>	
  	
  
Node Name
3c075477e55e:talk	
  sdhillon	
  erl	
  -­‐sname	
  foo	
  
Erlang	
  R16B03-­‐1	
  (erts-­‐5.10.4)	
  [source]	
  [64-­‐bit]	
  [smp:8:8]	
  [async-­‐threads:
10]	
  [hipe]	
  [kernel-­‐poll:false]	
  
	
  	
  
Eshell	
  V5.10.4	
  	
  (abort	
  with	
  ^G)	
  
(foo@3c075477e55e)1>	
  application:ensure_all_started(factorial_server).	
  
{ok,[sasl,factorial_server]}	
  
(foo@3c075477e55e)2>	
  	
  
Node 1: Bar
3c075477e55e:talk	
  sdhillon	
  erl	
  -­‐sname	
  bar	
  
Erlang	
  R16B03-­‐1	
  (erts-­‐5.10.4)	
  [source]	
  [64-­‐bit]	
  [smp:8:8]	
  [async-­‐threads:
10]	
  [hipe]	
  [kernel-­‐poll:false]	
  
	
  	
  
Eshell	
  V5.10.4	
  	
  (abort	
  with	
  ^G)	
  
(bar@3c075477e55e)1>	
  net_adm:ping('foo@3c075477e55e').	
  
pong	
  
(bar@3c075477e55e)2>	
  gen_server:call({factorial_server_otp,	
  
'foo@3c075477e55e'},	
  10).	
  
3628800	
  
Contact
3c075477e55e:talk	
  sdhillon	
  erl	
  -­‐sname	
  bar	
  
Erlang	
  R16B03-­‐1	
  (erts-­‐5.10.4)	
  [source]	
  [64-­‐bit]	
  [smp:8:8]	
  [async-­‐threads:
10]	
  [hipe]	
  [kernel-­‐poll:false]	
  
	
  	
  
Eshell	
  V5.10.4	
  	
  (abort	
  with	
  ^G)	
  
(bar@3c075477e55e)1>	
  net_adm:ping('foo@3c075477e55e').	
  
pong	
  
(bar@3c075477e55e)2>	
  gen_server:call({factorial_server_otp,	
  
'foo@3c075477e55e'},	
  10).	
  
3628800	
  
Remote Execution
3c075477e55e:talk	
  sdhillon	
  erl	
  -­‐sname	
  bar	
  
Erlang	
  R16B03-­‐1	
  (erts-­‐5.10.4)	
  [source]	
  [64-­‐bit]	
  [smp:8:8]	
  [async-­‐threads:
10]	
  [hipe]	
  [kernel-­‐poll:false]	
  
	
  	
  
Eshell	
  V5.10.4	
  	
  (abort	
  with	
  ^G)	
  
(bar@3c075477e55e)1>	
  net_adm:ping('foo@3c075477e55e').	
  
pong	
  
(bar@3c075477e55e)2>	
  gen_server:call({factorial_server_otp,	
  
'foo@3c075477e55e'},	
  10).	
  
3628800	
  
Monitoring Nodes
(bar@3c075477e55e)1>	
  net_adm:ping('foo@3c075477e55e').	
  
pong	
  
(bar@3c075477e55e)2>	
  net_kernel:monitor_nodes(true).	
  	
  	
  
ok	
  
(bar@3c075477e55e)3>	
  flush().	
  
Shell	
  got	
  {nodedown,foo@3c075477e55e}	
  
ok	
  
Distributed Erlang
• Useful for building highly reliable applications
• Useful for building applications that scale out
• The underlying system of nearly all Riak requests
• Authentication through cookies
Dialyzer
Types
Erlang:
Dynamically Typed
Typespec
Typespec
-­‐spec	
  handle_call(non_neg_integer(),	
  {pid(),	
  any()},	
  state)	
  -­‐
>	
  {reply,	
  non_neg_integer(),	
  state}.	
  
handle_call(X,	
  _From,	
  state)	
  -­‐>	
  
	
  	
  {reply,	
  factorial(X),	
  state}.	
  
-­‐spec	
  factorial(non_neg_integer())	
  -­‐>	
  non_neg_integer().	
  
factorial(1)	
  -­‐>	
  -­‐1;	
  
factorial(N)	
  -­‐>	
  N	
  *	
  factorial(N-­‐1).	
  
Tying it Together
Checking whether the PLT out.plt is up-to-date... yes
Proceeding with analysis...
factorial_server_otp.erl:6: Invalid type specification for function
factorial_server_otp:handle_call/3. The success typing is
(pos_integer(),_,'state') -> {'reply',neg_integer(),'state'}
factorial_server_otp.erl:9: Invalid type specification for function
factorial_server_otp:factorial/1. The success typing is
(pos_integer()) -> neg_integer()
done in 0m0.79s
done (warnings were emitted)
Fixed
-­‐spec	
  handle_call(non_neg_integer(),	
  {pid(),	
  any()},	
  state)	
  -­‐
>	
  {reply,	
  non_neg_integer(),	
  state}.	
  
handle_call(X,	
  _From,	
  state)	
  -­‐>	
  
	
  	
  {reply,	
  factorial(X),	
  state}.	
  
-­‐spec	
  factorial(non_neg_integer())	
  -­‐>	
  non_neg_integer().	
  
factorial(1)	
  -­‐>	
  1;	
  
factorial(N)	
  -­‐>	
  N	
  *	
  factorial(N-­‐1).	
  
Tying it Together
3c075477e55e:talk sdhillon$ dialyzer --plt out.plt
factorial_server_otp.erl
Checking whether the PLT out.plt is up-to-date... yes
Proceeding with analysis... done in 0m0.89s
done (passed successfully)
Dialyzer
• Utilizes typespec
• Static, offline analysis
• Utilizes PLTs (Persistent Lookup Table)
Garbage Collection
Memory
• Process Heaps
• ETS Tables
• Atom Table
• Large Binary Space
Memory
• Process Heaps
• ETS Tables
• Atom Table
• Large Binary Space
Per-Process Heap
Only for items <64B
GC:
Copying Collector
Large Binary Space
GC:
Generational Collector
GC:
Synchronization Free
Benefit:
Fewer Unpredictable
Pauses
Memory Model
• Split memory model
• Useful for building high performance systems
• Predictability is key
• Garbage collected
• Shared heap only GC’d under memory pressure
Tying it back to Riak
Applications
Core Applications
• Riak_KV
• Riak_Core
• Riak_API
Riak_API
This OTP application encapsulates
services for presenting Riak's
public-facing interfaces.
~1.5KLoC
2 Supervisors
5 Servers
Riak_Core
Riak Core is the distributed systems framework
that forms the basis of how Riak distributes
data and scales. More generally, it can be
thought of as a toolkit for building distributed,
scalable, fault-tolerant applications.
~25KLoC
11 Supervisors
30 Servers
Riak_KV
~30KLoC
9 Supervisors
12 Servers
Ancillary Applications
• Lager: Logging
• Storage Layer:
• Bitcask
• Leveldb
• Mochiweb: HTTP Interface
• Riak_pipe: Distributed map-reduce
• Riak_Ensemble: Consensus layer
It Works
Demos
Troubles In Paradise
• Distributed Erlang can be problematic due to head-
of-line blocking
• NIFs (external code) can be problematic due to
performance and debugging
• BEAM needs a JIT compiler
• Work being done here!
Erlang/OTP & Riak
@Sargun

Contenu connexe

Tendances

Austin Bingham. Transducers in Python. PyCon Belarus
Austin Bingham. Transducers in Python. PyCon BelarusAustin Bingham. Transducers in Python. PyCon Belarus
Austin Bingham. Transducers in Python. PyCon BelarusAlina Dolgikh
 
Higher Order Components and Render Props
Higher Order Components and Render PropsHigher Order Components and Render Props
Higher Order Components and Render PropsNitish Phanse
 
Angular Pipes Workshop
Angular Pipes WorkshopAngular Pipes Workshop
Angular Pipes WorkshopNir Kaufman
 
Using Redux-Saga for Handling Side Effects
Using Redux-Saga for Handling Side EffectsUsing Redux-Saga for Handling Side Effects
Using Redux-Saga for Handling Side EffectsGlobalLogic Ukraine
 
The Ring programming language version 1.7 book - Part 93 of 196
The Ring programming language version 1.7 book - Part 93 of 196The Ring programming language version 1.7 book - Part 93 of 196
The Ring programming language version 1.7 book - Part 93 of 196Mahmoud Samir Fayed
 
The Ring programming language version 1.8 book - Part 84 of 202
The Ring programming language version 1.8 book - Part 84 of 202The Ring programming language version 1.8 book - Part 84 of 202
The Ring programming language version 1.8 book - Part 84 of 202Mahmoud Samir Fayed
 
The Ring programming language version 1.9 book - Part 101 of 210
The Ring programming language version 1.9 book - Part 101 of 210The Ring programming language version 1.9 book - Part 101 of 210
The Ring programming language version 1.9 book - Part 101 of 210Mahmoud Samir Fayed
 
The Ring programming language version 1.6 book - Part 23 of 189
The Ring programming language version 1.6 book - Part 23 of 189The Ring programming language version 1.6 book - Part 23 of 189
The Ring programming language version 1.6 book - Part 23 of 189Mahmoud Samir Fayed
 
2018 05-16 Evolving Technologies: React, Babel & Webpack
2018 05-16 Evolving Technologies: React, Babel & Webpack2018 05-16 Evolving Technologies: React, Babel & Webpack
2018 05-16 Evolving Technologies: React, Babel & WebpackCodifly
 
Formal Verification of Web Service Interaction Contracts
Formal Verification of Web Service Interaction ContractsFormal Verification of Web Service Interaction Contracts
Formal Verification of Web Service Interaction ContractsGera Shegalov
 
Redux saga: managing your side effects. Also: generators in es6
Redux saga: managing your side effects. Also: generators in es6Redux saga: managing your side effects. Also: generators in es6
Redux saga: managing your side effects. Also: generators in es6Ignacio Martín
 
Redux Sagas - React Alicante
Redux Sagas - React AlicanteRedux Sagas - React Alicante
Redux Sagas - React AlicanteIgnacio Martín
 
The Ring programming language version 1.5 book - Part 4 of 31
The Ring programming language version 1.5 book - Part 4 of 31The Ring programming language version 1.5 book - Part 4 of 31
The Ring programming language version 1.5 book - Part 4 of 31Mahmoud Samir Fayed
 
Is java8 a true functional programming language
Is java8 a true functional programming languageIs java8 a true functional programming language
Is java8 a true functional programming languageSQLI
 
Is java8a truefunctionallanguage
Is java8a truefunctionallanguageIs java8a truefunctionallanguage
Is java8a truefunctionallanguageSamir Chekkal
 

Tendances (20)

Introducing to Asynchronous Programming
Introducing to Asynchronous  ProgrammingIntroducing to Asynchronous  Programming
Introducing to Asynchronous Programming
 
Austin Bingham. Transducers in Python. PyCon Belarus
Austin Bingham. Transducers in Python. PyCon BelarusAustin Bingham. Transducers in Python. PyCon Belarus
Austin Bingham. Transducers in Python. PyCon Belarus
 
Higher Order Components and Render Props
Higher Order Components and Render PropsHigher Order Components and Render Props
Higher Order Components and Render Props
 
Angular Pipes Workshop
Angular Pipes WorkshopAngular Pipes Workshop
Angular Pipes Workshop
 
Using Redux-Saga for Handling Side Effects
Using Redux-Saga for Handling Side EffectsUsing Redux-Saga for Handling Side Effects
Using Redux-Saga for Handling Side Effects
 
Function
FunctionFunction
Function
 
functions of C++
functions of C++functions of C++
functions of C++
 
The Ring programming language version 1.7 book - Part 93 of 196
The Ring programming language version 1.7 book - Part 93 of 196The Ring programming language version 1.7 book - Part 93 of 196
The Ring programming language version 1.7 book - Part 93 of 196
 
The Ring programming language version 1.8 book - Part 84 of 202
The Ring programming language version 1.8 book - Part 84 of 202The Ring programming language version 1.8 book - Part 84 of 202
The Ring programming language version 1.8 book - Part 84 of 202
 
The Ring programming language version 1.9 book - Part 101 of 210
The Ring programming language version 1.9 book - Part 101 of 210The Ring programming language version 1.9 book - Part 101 of 210
The Ring programming language version 1.9 book - Part 101 of 210
 
The Ring programming language version 1.6 book - Part 23 of 189
The Ring programming language version 1.6 book - Part 23 of 189The Ring programming language version 1.6 book - Part 23 of 189
The Ring programming language version 1.6 book - Part 23 of 189
 
2018 05-16 Evolving Technologies: React, Babel & Webpack
2018 05-16 Evolving Technologies: React, Babel & Webpack2018 05-16 Evolving Technologies: React, Babel & Webpack
2018 05-16 Evolving Technologies: React, Babel & Webpack
 
Formal Verification of Web Service Interaction Contracts
Formal Verification of Web Service Interaction ContractsFormal Verification of Web Service Interaction Contracts
Formal Verification of Web Service Interaction Contracts
 
Friendly Functional Programming
Friendly Functional ProgrammingFriendly Functional Programming
Friendly Functional Programming
 
Redux saga: managing your side effects. Also: generators in es6
Redux saga: managing your side effects. Also: generators in es6Redux saga: managing your side effects. Also: generators in es6
Redux saga: managing your side effects. Also: generators in es6
 
Redux Sagas - React Alicante
Redux Sagas - React AlicanteRedux Sagas - React Alicante
Redux Sagas - React Alicante
 
The Ring programming language version 1.5 book - Part 4 of 31
The Ring programming language version 1.5 book - Part 4 of 31The Ring programming language version 1.5 book - Part 4 of 31
The Ring programming language version 1.5 book - Part 4 of 31
 
Durable Functions
Durable FunctionsDurable Functions
Durable Functions
 
Is java8 a true functional programming language
Is java8 a true functional programming languageIs java8 a true functional programming language
Is java8 a true functional programming language
 
Is java8a truefunctionallanguage
Is java8a truefunctionallanguageIs java8a truefunctionallanguage
Is java8a truefunctionallanguage
 

En vedette

Why Distributed Databases?
Why Distributed Databases?Why Distributed Databases?
Why Distributed Databases?Sargun Dhillon
 
Papers We Love Too, June 2015: Haystack
Papers We Love Too, June 2015: Haystack Papers We Love Too, June 2015: Haystack
Papers We Love Too, June 2015: Haystack Sargun Dhillon
 
DC/OS 1.8 Container Networking
DC/OS 1.8 Container NetworkingDC/OS 1.8 Container Networking
DC/OS 1.8 Container NetworkingSargun Dhillon
 
Erlang User Conference 2016: Container Networking: A Field Report
Erlang User Conference 2016: Container Networking: A Field ReportErlang User Conference 2016: Container Networking: A Field Report
Erlang User Conference 2016: Container Networking: A Field ReportSargun Dhillon
 
Building the Glue for Service Discovery & Load Balancing Microservices
Building the Glue for Service Discovery & Load Balancing MicroservicesBuilding the Glue for Service Discovery & Load Balancing Microservices
Building the Glue for Service Discovery & Load Balancing MicroservicesSargun Dhillon
 
Lying, Cheating, and Winning with Containers in Networking
Lying, Cheating, and Winning with Containers in NetworkingLying, Cheating, and Winning with Containers in Networking
Lying, Cheating, and Winning with Containers in NetworkingSargun Dhillon
 
Concurrency in Elixir with OTP
Concurrency in Elixir with OTPConcurrency in Elixir with OTP
Concurrency in Elixir with OTPJustin Reese
 
Let It Crash (@pavlobaron)
Let It Crash (@pavlobaron)Let It Crash (@pavlobaron)
Let It Crash (@pavlobaron)Pavlo Baron
 
Elixir Elevated: The Ups and Downs of OTP at ElixirConf2014
Elixir Elevated: The Ups and Downs of OTP at ElixirConf2014Elixir Elevated: The Ups and Downs of OTP at ElixirConf2014
Elixir Elevated: The Ups and Downs of OTP at ElixirConf2014Greg Vaughn
 
Berbisnis ONLINE
Berbisnis ONLINEBerbisnis ONLINE
Berbisnis ONLINEMaxMedia
 
keterampilan berbahasa Indonesia-metode Membaca
keterampilan berbahasa Indonesia-metode Membacaketerampilan berbahasa Indonesia-metode Membaca
keterampilan berbahasa Indonesia-metode MembacaPotpotya Fitri
 
Beneficios de las redes educativas
Beneficios de las redes educativas Beneficios de las redes educativas
Beneficios de las redes educativas Vale Ayala
 

En vedette (20)

Why Distributed Databases?
Why Distributed Databases?Why Distributed Databases?
Why Distributed Databases?
 
Papers We Love Too, June 2015: Haystack
Papers We Love Too, June 2015: Haystack Papers We Love Too, June 2015: Haystack
Papers We Love Too, June 2015: Haystack
 
DC/OS 1.8 Container Networking
DC/OS 1.8 Container NetworkingDC/OS 1.8 Container Networking
DC/OS 1.8 Container Networking
 
Erlang User Conference 2016: Container Networking: A Field Report
Erlang User Conference 2016: Container Networking: A Field ReportErlang User Conference 2016: Container Networking: A Field Report
Erlang User Conference 2016: Container Networking: A Field Report
 
Building the Glue for Service Discovery & Load Balancing Microservices
Building the Glue for Service Discovery & Load Balancing MicroservicesBuilding the Glue for Service Discovery & Load Balancing Microservices
Building the Glue for Service Discovery & Load Balancing Microservices
 
Lying, Cheating, and Winning with Containers in Networking
Lying, Cheating, and Winning with Containers in NetworkingLying, Cheating, and Winning with Containers in Networking
Lying, Cheating, and Winning with Containers in Networking
 
Erlang containers
Erlang containersErlang containers
Erlang containers
 
Intro to Databases
Intro to DatabasesIntro to Databases
Intro to Databases
 
Riak TS
Riak TSRiak TS
Riak TS
 
Concurrency in Elixir with OTP
Concurrency in Elixir with OTPConcurrency in Elixir with OTP
Concurrency in Elixir with OTP
 
Let It Crash (@pavlobaron)
Let It Crash (@pavlobaron)Let It Crash (@pavlobaron)
Let It Crash (@pavlobaron)
 
Elixir Elevated: The Ups and Downs of OTP at ElixirConf2014
Elixir Elevated: The Ups and Downs of OTP at ElixirConf2014Elixir Elevated: The Ups and Downs of OTP at ElixirConf2014
Elixir Elevated: The Ups and Downs of OTP at ElixirConf2014
 
Elixir and OTP
Elixir and OTPElixir and OTP
Elixir and OTP
 
Berbisnis ONLINE
Berbisnis ONLINEBerbisnis ONLINE
Berbisnis ONLINE
 
keterampilan berbahasa Indonesia-metode Membaca
keterampilan berbahasa Indonesia-metode Membacaketerampilan berbahasa Indonesia-metode Membaca
keterampilan berbahasa Indonesia-metode Membaca
 
Custom kitchen remodels
Custom kitchen remodelsCustom kitchen remodels
Custom kitchen remodels
 
Mc luhan copy 2
Mc luhan copy 2Mc luhan copy 2
Mc luhan copy 2
 
τα ζώα μου
τα ζώα μουτα ζώα μου
τα ζώα μου
 
Beneficios de las redes educativas
Beneficios de las redes educativas Beneficios de las redes educativas
Beneficios de las redes educativas
 
Zero barrier showers
Zero barrier showersZero barrier showers
Zero barrier showers
 

Similaire à Erlang/OTP in Riak

Introduction to Erlang Part 2
Introduction to Erlang Part 2Introduction to Erlang Part 2
Introduction to Erlang Part 2Dmitry Zinoviev
 
Programming Sideways: Asynchronous Techniques for Android
Programming Sideways: Asynchronous Techniques for AndroidProgramming Sideways: Asynchronous Techniques for Android
Programming Sideways: Asynchronous Techniques for AndroidEmanuele Di Saverio
 
Integration-Monday-Stateful-Programming-Models-Serverless-Functions
Integration-Monday-Stateful-Programming-Models-Serverless-FunctionsIntegration-Monday-Stateful-Programming-Models-Serverless-Functions
Integration-Monday-Stateful-Programming-Models-Serverless-FunctionsBizTalk360
 
Emerging Languages: A Tour of the Horizon
Emerging Languages: A Tour of the HorizonEmerging Languages: A Tour of the Horizon
Emerging Languages: A Tour of the HorizonAlex Payne
 
A deep dive into PEP-3156 and the new asyncio module
A deep dive into PEP-3156 and the new asyncio moduleA deep dive into PEP-3156 and the new asyncio module
A deep dive into PEP-3156 and the new asyncio moduleSaúl Ibarra Corretgé
 
Implementasi Pemodelan Sistem Ke TeeChart 2
Implementasi Pemodelan Sistem Ke TeeChart  2Implementasi Pemodelan Sistem Ke TeeChart  2
Implementasi Pemodelan Sistem Ke TeeChart 2Lusiana Diyan
 
Architecture for scalable Angular applications (with introduction and extende...
Architecture for scalable Angular applications (with introduction and extende...Architecture for scalable Angular applications (with introduction and extende...
Architecture for scalable Angular applications (with introduction and extende...Paweł Żurowski
 
Advanced patterns in asynchronous programming
Advanced patterns in asynchronous programmingAdvanced patterns in asynchronous programming
Advanced patterns in asynchronous programmingMichael Arenzon
 
Simple callcenter platform with PHP
Simple callcenter platform with PHPSimple callcenter platform with PHP
Simple callcenter platform with PHPMorten Amundsen
 
Better Open Source Enterprise C++ Web Services
Better Open Source Enterprise C++ Web ServicesBetter Open Source Enterprise C++ Web Services
Better Open Source Enterprise C++ Web ServicesWSO2
 
Parallel R in snow (english after 2nd slide)
Parallel R in snow (english after 2nd slide)Parallel R in snow (english after 2nd slide)
Parallel R in snow (english after 2nd slide)Cdiscount
 
Introduction to-mongo db-execution-plan-optimizer-final
Introduction to-mongo db-execution-plan-optimizer-finalIntroduction to-mongo db-execution-plan-optimizer-final
Introduction to-mongo db-execution-plan-optimizer-finalM Malai
 
Introduction to Mongodb execution plan and optimizer
Introduction to Mongodb execution plan and optimizerIntroduction to Mongodb execution plan and optimizer
Introduction to Mongodb execution plan and optimizerMydbops
 
Job Queue in Golang
Job Queue in GolangJob Queue in Golang
Job Queue in GolangBo-Yi Wu
 
Building Cloud Castles - LRUG
Building Cloud Castles - LRUGBuilding Cloud Castles - LRUG
Building Cloud Castles - LRUGBen Scofield
 
Lecture#6 functions in c++
Lecture#6 functions in c++Lecture#6 functions in c++
Lecture#6 functions in c++NUST Stuff
 

Similaire à Erlang/OTP in Riak (20)

Appsec obfuscator reloaded
Appsec obfuscator reloadedAppsec obfuscator reloaded
Appsec obfuscator reloaded
 
Introduction to Erlang Part 2
Introduction to Erlang Part 2Introduction to Erlang Part 2
Introduction to Erlang Part 2
 
Programming Sideways: Asynchronous Techniques for Android
Programming Sideways: Asynchronous Techniques for AndroidProgramming Sideways: Asynchronous Techniques for Android
Programming Sideways: Asynchronous Techniques for Android
 
Integration-Monday-Stateful-Programming-Models-Serverless-Functions
Integration-Monday-Stateful-Programming-Models-Serverless-FunctionsIntegration-Monday-Stateful-Programming-Models-Serverless-Functions
Integration-Monday-Stateful-Programming-Models-Serverless-Functions
 
Emerging Languages: A Tour of the Horizon
Emerging Languages: A Tour of the HorizonEmerging Languages: A Tour of the Horizon
Emerging Languages: A Tour of the Horizon
 
A deep dive into PEP-3156 and the new asyncio module
A deep dive into PEP-3156 and the new asyncio moduleA deep dive into PEP-3156 and the new asyncio module
A deep dive into PEP-3156 and the new asyncio module
 
Implementasi Pemodelan Sistem Ke TeeChart 2
Implementasi Pemodelan Sistem Ke TeeChart  2Implementasi Pemodelan Sistem Ke TeeChart  2
Implementasi Pemodelan Sistem Ke TeeChart 2
 
Architecture for scalable Angular applications (with introduction and extende...
Architecture for scalable Angular applications (with introduction and extende...Architecture for scalable Angular applications (with introduction and extende...
Architecture for scalable Angular applications (with introduction and extende...
 
Advanced patterns in asynchronous programming
Advanced patterns in asynchronous programmingAdvanced patterns in asynchronous programming
Advanced patterns in asynchronous programming
 
Simple callcenter platform with PHP
Simple callcenter platform with PHPSimple callcenter platform with PHP
Simple callcenter platform with PHP
 
Better Open Source Enterprise C++ Web Services
Better Open Source Enterprise C++ Web ServicesBetter Open Source Enterprise C++ Web Services
Better Open Source Enterprise C++ Web Services
 
C++20 features
C++20 features C++20 features
C++20 features
 
Celery with python
Celery with pythonCelery with python
Celery with python
 
Parallel R in snow (english after 2nd slide)
Parallel R in snow (english after 2nd slide)Parallel R in snow (english after 2nd slide)
Parallel R in snow (english after 2nd slide)
 
Introduction to-mongo db-execution-plan-optimizer-final
Introduction to-mongo db-execution-plan-optimizer-finalIntroduction to-mongo db-execution-plan-optimizer-final
Introduction to-mongo db-execution-plan-optimizer-final
 
Introduction to Mongodb execution plan and optimizer
Introduction to Mongodb execution plan and optimizerIntroduction to Mongodb execution plan and optimizer
Introduction to Mongodb execution plan and optimizer
 
Job Queue in Golang
Job Queue in GolangJob Queue in Golang
Job Queue in Golang
 
chapter 4
chapter 4chapter 4
chapter 4
 
Building Cloud Castles - LRUG
Building Cloud Castles - LRUGBuilding Cloud Castles - LRUG
Building Cloud Castles - LRUG
 
Lecture#6 functions in c++
Lecture#6 functions in c++Lecture#6 functions in c++
Lecture#6 functions in c++
 

Dernier

Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about usDynamic Netsoft
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyFrank van der Linden
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number SystemsJheuzeDellosa
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...aditisharan08
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 

Dernier (20)

Exploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the ProcessExploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the Process
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about us
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The Ugly
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number Systems
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 

Erlang/OTP in Riak

  • 1. Erlang/OTP in Riak Twitter: @Sargun Chief Solutions Architect, Basho
  • 4. “To provide a better way of programming telephony applications” The Mission
  • 6. Requirements • Handling a very large number of concurrent activities • Actions to be performed at a certain point of time or within a certain time • Systems distributed over several computers • Interaction with hardware must be abstracted • Very large software systems • Complex functionality such as feature interaction • Continuous operation over several years • Software maintenance (reconfiguration, etc.) without stopping the system • Stringent quality and reliability requirements • Fault tolerance both to hardware failures and software errors
  • 7. Relation of Erlang to existing languages. "A History of Erlang”
  • 8. COP: Concurrency Oriented Programming • Systems are built from processes. • Process share nothing. • Processes interact by asynchronous message passing. • Processes are isolated.
  • 9. AXD301: Success • Came out in 1998 • ATM switch, control-plane written in Erlang • 2.6 Million lines of Erlang code • Nine-nines of uptime: 99.99999999% • Built highly reliable systems from unreliable components • Scale-out
  • 10. Erlang • Only accessible to the community since December 1998 • Designed for telephony control planes • Actor Model • Functional
  • 12. Universal Server 1>  UniversalServer  =   1>  fun  US()  -­‐>   1>      receive  {become,  F}  -­‐>   1>          F()   1>      end   1>  end.   #Fun<erl_eval.44.90072148>  
  • 13. Named Funs (Lambda) 1>  UniversalServer  =   1>  fun  US()  -­‐>   1>      receive  {become,  F}  -­‐>   1>          F()   1>      end   1>  end.   #Fun<erl_eval.44.90072148>  
  • 14. Message Passing 1>  UniversalServer  =   1>  fun  US()  -­‐>   1>      receive  {become,  F}  -­‐>   1>          F()   1>      end   1>  end.   #Fun<erl_eval.44.90072148>  
  • 15. Lightweight Processes 2>  Server  =  spawn(UniversalServer).   <0.45.0>  
  • 18. Calculating Factorials 5>  FC  =  fun   5>      Factorial(0)  -­‐>  1;   5>      Factorial(N)  -­‐>  N  *  Factorial(N-­‐1)   5>  end.   #Fun<erl_eval.30.90072148>  
  • 19. It Works! 8>  FC(10).   3628800  
  • 20. Turning It Into A Server 9>  FServer  =   9>  fun  FactorialServer()  -­‐>   9>          receive   9>                {From,  N}  -­‐>   9>                        From  !  FC(N),   9>                        FactorialServer()   9>          end     9>  end.   #Fun<erl_eval.44.90072148>  
  • 21. Converting the Server 10>  Server  !  {become,  FServer}.   {become,#Fun<erl_eval.44.90072148>}
  • 22. Testing It Out 11>  Server  !  {self(),  10}.   {<0.42.0>,10}   12>  flush().   Shell  got  3628800  
  • 24. As A Module -­‐module(factorial_server).   -­‐export([start_link/0,  calc/2,  server/0]).   start_link()  -­‐>      spawn_link(?MODULE,  server,  []).     calc(X,  Pid)  -­‐>      Pid  !  {self(),  X},      receive  N  -­‐>  N  end.   server()  -­‐>      receive          {From,  N}  -­‐>              From  !  factorial(N),              server()      end.   factorial(0)  -­‐>  1;   factorial(N)  -­‐>  N  *  factorial(N-­‐1).  
  • 25. Module name -­‐module(factorial_server).   -­‐export([start_link/0,  calc/2,  server/0]).   start_link()  -­‐>      spawn_link(?MODULE,  server,  []).     calc(X,  Pid)  -­‐>      Pid  !  {self(),  X},      receive  N  -­‐>  N  end.   server()  -­‐>      receive          {From,  N}  -­‐>              From  !  factorial(N),              server()      end.   factorial(0)  -­‐>  1;   factorial(N)  -­‐>  N  *  factorial(N-­‐1).  
  • 26. Exports -­‐module(factorial_server).   -­‐export([start_link/0,  calc/2,  server/0]).   start_link()  -­‐>      spawn_link(?MODULE,  server,  []).     calc(X,  Pid)  -­‐>      Pid  !  {self(),  X},      receive  N  -­‐>  N  end.   server()  -­‐>      receive          {From,  N}  -­‐>              From  !  factorial(N),              server()      end.   factorial(0)  -­‐>  1;   factorial(N)  -­‐>  N  *  factorial(N-­‐1).  
  • 27. Start Module -­‐module(factorial_server).   -­‐export([start_link/0,  calc/2,  server/0]).   start_link()  -­‐>      spawn_link(?MODULE,  server,  []).     calc(X,  Pid)  -­‐>      Pid  !  {self(),  X},      receive  N  -­‐>  N  end.   server()  -­‐>      receive          {From,  N}  -­‐>              From  !  factorial(N),              server()      end.   factorial(0)  -­‐>  1;   factorial(N)  -­‐>  N  *  factorial(N-­‐1).  
  • 28. Client Interface -­‐module(factorial_server).   -­‐export([start_link/0,  calc/2,  server/0]).   start_link()  -­‐>      spawn_link(?MODULE,  server,  []).     calc(X,  Pid)  -­‐>      Pid  !  {self(),  X},      receive  N  -­‐>  N  end.   server()  -­‐>      receive          {From,  N}  -­‐>              From  !  factorial(N),              server()      end.   factorial(0)  -­‐>  1;   factorial(N)  -­‐>  N  *  factorial(N-­‐1).  
  • 29. Server Loop -­‐module(factorial_server).   -­‐export([start_link/0,  calc/2,  server/0]).   start_link()  -­‐>      spawn_link(?MODULE,  server,  []).     calc(X,  Pid)  -­‐>      Pid  !  {self(),  X},      receive  N  -­‐>  N  end.   server()  -­‐>      receive          {From,  N}  -­‐>              From  !  factorial(N),              server()      end.   factorial(0)  -­‐>  1;   factorial(N)  -­‐>  N  *  factorial(N-­‐1).  
  • 30. Calculator -­‐module(factorial_server).   -­‐export([start_link/0,  calc/2,  server/0]).   start_link()  -­‐>      spawn_link(?MODULE,  server,  []).     calc(X,  Pid)  -­‐>      Pid  !  {self(),  X},      receive  N  -­‐>  N  end.   server()  -­‐>      receive          {From,  N}  -­‐>              From  !  factorial(N),              server()      end.   factorial(0)  -­‐>  1;   factorial(N)  -­‐>  N  *  factorial(N-­‐1).  
  • 31. Using The Module 8>  Pid  =  factorial_server:start_link().   <0.72.0>   9>  factorial_server:calc(10,  Pid).   3628800  
  • 33. Introduce A Bug factorial(0)  -­‐>  1;   factorial(10)  -­‐>  1=2;   factorial(N)  -­‐>  N  *  factorial(N-­‐1).  
  • 34. Trigger The Bug 9>  factorial_server:calc(10,  Pid).       =ERROR  REPORT====  5-­‐Apr-­‐2015::06:04:40  ===   Error  in  process  <0.59.0>  with  exit  value:  {{badmatch,2}, [{factorial_server,factorial,1,[{file,"factorial_server.erl"},{line, 15}]},{factorial_server,server,0,[{file,"factorial_server.erl"},{line, 11}]}]}       **  exception  exit:  {badmatch,2}            in  function    factorial_server:factorial/1  (factorial_server.erl,   line  15)            in  call  from  factorial_server:server/0  (factorial_server.erl,  line   11)  
  • 35. Ping The Server Again? 10>     10>  factorial_server:calc(10,  Pid).   ...Hangs  Forever  
  • 36. OTP
  • 38. Behaviours are formalizations of common patterns. The idea is to divide the code for a process in a generic part (a behaviour module) and a specific part (a callback module).
  • 40. A behaviour module for implementing the server of a client-server relation.
  • 41. As An OTP Module -­‐module(factorial_server_otp).   -­‐behaviour(gen_server).   -­‐export([start_link/0,  init/1,  handle_call/3,     terminate/2,  code_change/3]).   start_link()  -­‐>  gen_server:start_link({local,  ?MODULE},  ?MODULE,  [],  []).   init([])  -­‐>  {ok,  state}.   handle_call(X,  _From,  state)  -­‐>      {reply,  factorial(X),  state}.       factorial(0)  -­‐>  1;   factorial(N)  -­‐>  N  *  factorial(N-­‐1).       terminate(shutdown,  state)  -­‐>  ok.   code_change(_OldVsn,  state,  _Extra)  -­‐>  {ok,  state}.  
  • 42. Behaviour Definition -­‐module(factorial_server_otp).   -­‐behaviour(gen_server).   -­‐export([start_link/0,  init/1,  handle_call/3,     terminate/2,  code_change/3]).   start_link()  -­‐>  gen_server:start_link({local,  ?MODULE},  ?MODULE,  [],  []).   init([])  -­‐>  {ok,  state}.   handle_call(X,  _From,  state)  -­‐>      {reply,  factorial(X),  state}.       factorial(0)  -­‐>  1;   factorial(N)  -­‐>  N  *  factorial(N-­‐1).       terminate(shutdown,  state)  -­‐>  ok.   code_change(_OldVsn,  state,  _Extra)  -­‐>  {ok,  state}.  
  • 43. Start Gen_Server -­‐module(factorial_server_otp).   -­‐behaviour(gen_server).   -­‐export([start_link/0,  init/1,  handle_call/3,     terminate/2,  code_change/3]).   start_link()  -­‐>  gen_server:start_link({local,  ?MODULE},  ?MODULE,  [],  []).   init([])  -­‐>  {ok,  state}.   handle_call(X,  _From,  state)  -­‐>      {reply,  factorial(X),  state}.       factorial(0)  -­‐>  1;   factorial(N)  -­‐>  N  *  factorial(N-­‐1).       terminate(shutdown,  state)  -­‐>  ok.   code_change(_OldVsn,  state,  _Extra)  -­‐>  {ok,  state}.  
  • 44. Setup Server -­‐module(factorial_server_otp).   -­‐behaviour(gen_server).   -­‐export([start_link/0,  init/1,  handle_call/3,     terminate/2,  code_change/3]).   start_link()  -­‐>  gen_server:start_link({local,  ?MODULE},  ?MODULE,  [],  []).   init([])  -­‐>  {ok,  state}.   handle_call(X,  _From,  state)  -­‐>      {reply,  factorial(X),  state}.       factorial(0)  -­‐>  1;   factorial(N)  -­‐>  N  *  factorial(N-­‐1).       terminate(shutdown,  state)  -­‐>  ok.   code_change(_OldVsn,  state,  _Extra)  -­‐>  {ok,  state}.  
  • 45. Server Reply Handler -­‐module(factorial_server_otp).   -­‐behaviour(gen_server).   -­‐export([start_link/0,  init/1,  handle_call/3,     terminate/2,  code_change/3]).   start_link()  -­‐>  gen_server:start_link({local,  ?MODULE},  ?MODULE,  [],  []).   init([])  -­‐>  {ok,  state}.   handle_call(X,  _From,  state)  -­‐>      {reply,  factorial(X),  state}.       factorial(0)  -­‐>  1;   factorial(N)  -­‐>  N  *  factorial(N-­‐1).       terminate(shutdown,  state)  -­‐>  ok.   code_change(_OldVsn,  state,  _Extra)  -­‐>  {ok,  state}.  
  • 46. Internal Callbacks -­‐module(factorial_server_otp).   -­‐behaviour(gen_server).   -­‐export([start_link/0,  init/1,  handle_call/3,     terminate/2,  code_change/3]).   start_link()  -­‐>  gen_server:start_link({local,  ?MODULE},  ?MODULE,  [],  []).   init([])  -­‐>  {ok,  state}.   handle_call(X,  _From,  state)  -­‐>      {reply,  factorial(X),  state}.       factorial(0)  -­‐>  1;   factorial(N)  -­‐>  N  *  factorial(N-­‐1).       terminate(shutdown,  state)  -­‐>  ok.   code_change(_OldVsn,  state,  _Extra)  -­‐>  {ok,  state}.  
  • 47. Using The OTP Module 1>  factorial_server_otp:start_link().   {ok,<0.34.0>}   2>  gen_server:call(factorial_server_otp,  9).   362880  
  • 48. Triggering The Bug 5>  gen_server:call(factorial_server_otp,  10).       =ERROR  REPORT====  5-­‐Apr-­‐2015::06:03:43  ===   **  Generic  server  factorial_server_otp   terminating     **  Last  message  in  was  10   **  When  Server  state  ==  state   **  Reason  for  termination  ==     …
  • 49. Subsequent Calls 6>  gen_server:call(factorial_server_otp,  10).   **  exception  exit:  {noproc,{gen_server,call, [factorial_server_otp,10]}}            in  function    gen_server:call/2   (gen_server.erl,  line  180)  
  • 51. Links
  • 52. Begin
  • 58. A behaviour module for implementing a supervisor, a process which supervises other processes called child processes.
  • 59. Factorial Supervisor -­‐module(factorial_server_sup).   -­‐behaviour(supervisor).       -­‐export([start_link/0]).   -­‐export([init/1]).       start_link()  -­‐>      supervisor:start_link({local,  factorial_server_sup},  ?MODULE,  []).       init(_Args)  -­‐>      {ok,  {{one_for_one,  1,  60},          [{factorial_server_otp,  {factorial_server_otp,  start_link,  []},          permanent,  brutal_kill,  worker,  dynamic}]}}.  
  • 60. Child Specs -­‐module(factorial_server_sup).   -­‐behaviour(supervisor).       -­‐export([start_link/0]).   -­‐export([init/1]).       start_link()  -­‐>      supervisor:start_link({local,  factorial_server_sup},  ?MODULE,  []).       init(_Args)  -­‐>      {ok,  {{one_for_one,  1,  60},          [{factorial_server_otp,  {factorial_server_otp,  start_link,  []},          permanent,  brutal_kill,  worker,  dynamic}]}}.  
  • 62. In OTP, application denotes a component implementing some specific functionality, that can be started and stopped as a unit, and which can be re-used in other systems as well.
  • 63. Application Resource File {application,  factorial_server,    [{description,  "Factorial  Calculator"},      {vsn,  "1"},      {modules,  [factorial_server_otp,          factorial_server_app,          factorial_server_sup]},      {registered,  []},      {applications,  [kernel,  stdlib,  sasl]},      {mod,  {factorial_server_app,[]}}    ]}.  
  • 64. Dependencies {application,  factorial_server,    [{description,  "Factorial  Calculator"},      {vsn,  "1"},      {modules,  [factorial_server_otp,          factorial_server_app,          factorial_server_sup]},      {registered,  []},      {applications,  [kernel,  stdlib,  sasl]},      {mod,  {factorial_server_app,[]}}    ]}.  
  • 65. Modules {application,  factorial_server,    [{description,  "Factorial  Calculator"},      {vsn,  "1"},      {modules,  [factorial_server_otp,          factorial_server_app,          factorial_server_sup]},      {registered,  []},      {applications,  [kernel,  stdlib,  sasl]},      {mod,  {factorial_server_app,[]}}    ]}.  
  • 66. Callback Module {application,  factorial_server,    [{description,  "Factorial  Calculator"},      {vsn,  "1"},      {modules,  [factorial_server_otp,          factorial_server_app,          factorial_server_sup]},      {registered,  []},      {applications,  [kernel,  stdlib,  sasl]},      {mod,  {factorial_server_app,[]}}    ]}.  
  • 67. Application Callback Module -­‐module(factorial_server_app).   -­‐behaviour(application).       -­‐export([start/2,  stop/1]).       start(_Type,  _Args)  -­‐>      factorial_server_sup:start_link().       stop(_State)  -­‐>      ok.  
  • 70. Observer, is a graphical tool for observing the characteristics of erlang systems. Observer displays system information, application supervisor trees, process information, ets or mnesia tables and contains a frontend for erlang tracing.
  • 73. Review • Factorial Server is now OTP Application • gen_server • supervisor • application • Factorial Server has a bug where it crashes at numbers >10. • Gen_server crashes handled by supervision tree
  • 74. Try Again 8>  gen_server:call(factorial_server_otp,  10).       =ERROR  REPORT====  5-­‐Apr-­‐2015::07:45:00  ===   **  Generic  server  factorial_server_otp  terminating     **  Last  message  in  was  10   **  When  Server  state  ==  state   **  Reason  for  termination  ==     ...  
  • 76. Live Code Patch 17>  c(factorial_server_otp).   {ok,factorial_server_otp}
  • 78. Erlang/OTP • OTP provides framework for simplifying actor model • Error handling semantics through crashing • Provides model for DRY code
  • 80. “You cannot build a fault- tolerant system if you only have one computer” A History of Erlang
  • 81. EPMD
  • 82. This daemon acts as a name server on all hosts involved in distributed Erlang computations.
  • 85. EPMD Acts as Broker
  • 96. Node 1: Foo 3c075477e55e:talk  sdhillon  erl  -­‐sname  foo   Erlang  R16B03-­‐1  (erts-­‐5.10.4)  [source]  [64-­‐bit]  [smp:8:8]  [async-­‐threads: 10]  [hipe]  [kernel-­‐poll:false]       Eshell  V5.10.4    (abort  with  ^G)   (foo@3c075477e55e)1>  application:ensure_all_started(factorial_server).   {ok,[sasl,factorial_server]}   (foo@3c075477e55e)2>    
  • 97. Node Name 3c075477e55e:talk  sdhillon  erl  -­‐sname  foo   Erlang  R16B03-­‐1  (erts-­‐5.10.4)  [source]  [64-­‐bit]  [smp:8:8]  [async-­‐threads: 10]  [hipe]  [kernel-­‐poll:false]       Eshell  V5.10.4    (abort  with  ^G)   (foo@3c075477e55e)1>  application:ensure_all_started(factorial_server).   {ok,[sasl,factorial_server]}   (foo@3c075477e55e)2>    
  • 98. Node 1: Bar 3c075477e55e:talk  sdhillon  erl  -­‐sname  bar   Erlang  R16B03-­‐1  (erts-­‐5.10.4)  [source]  [64-­‐bit]  [smp:8:8]  [async-­‐threads: 10]  [hipe]  [kernel-­‐poll:false]       Eshell  V5.10.4    (abort  with  ^G)   (bar@3c075477e55e)1>  net_adm:ping('foo@3c075477e55e').   pong   (bar@3c075477e55e)2>  gen_server:call({factorial_server_otp,   'foo@3c075477e55e'},  10).   3628800  
  • 99. Contact 3c075477e55e:talk  sdhillon  erl  -­‐sname  bar   Erlang  R16B03-­‐1  (erts-­‐5.10.4)  [source]  [64-­‐bit]  [smp:8:8]  [async-­‐threads: 10]  [hipe]  [kernel-­‐poll:false]       Eshell  V5.10.4    (abort  with  ^G)   (bar@3c075477e55e)1>  net_adm:ping('foo@3c075477e55e').   pong   (bar@3c075477e55e)2>  gen_server:call({factorial_server_otp,   'foo@3c075477e55e'},  10).   3628800  
  • 100. Remote Execution 3c075477e55e:talk  sdhillon  erl  -­‐sname  bar   Erlang  R16B03-­‐1  (erts-­‐5.10.4)  [source]  [64-­‐bit]  [smp:8:8]  [async-­‐threads: 10]  [hipe]  [kernel-­‐poll:false]       Eshell  V5.10.4    (abort  with  ^G)   (bar@3c075477e55e)1>  net_adm:ping('foo@3c075477e55e').   pong   (bar@3c075477e55e)2>  gen_server:call({factorial_server_otp,   'foo@3c075477e55e'},  10).   3628800  
  • 101. Monitoring Nodes (bar@3c075477e55e)1>  net_adm:ping('foo@3c075477e55e').   pong   (bar@3c075477e55e)2>  net_kernel:monitor_nodes(true).       ok   (bar@3c075477e55e)3>  flush().   Shell  got  {nodedown,foo@3c075477e55e}   ok  
  • 102. Distributed Erlang • Useful for building highly reliable applications • Useful for building applications that scale out • The underlying system of nearly all Riak requests • Authentication through cookies
  • 104. Types
  • 107. Typespec -­‐spec  handle_call(non_neg_integer(),  {pid(),  any()},  state)  -­‐ >  {reply,  non_neg_integer(),  state}.   handle_call(X,  _From,  state)  -­‐>      {reply,  factorial(X),  state}.   -­‐spec  factorial(non_neg_integer())  -­‐>  non_neg_integer().   factorial(1)  -­‐>  -­‐1;   factorial(N)  -­‐>  N  *  factorial(N-­‐1).  
  • 108. Tying it Together Checking whether the PLT out.plt is up-to-date... yes Proceeding with analysis... factorial_server_otp.erl:6: Invalid type specification for function factorial_server_otp:handle_call/3. The success typing is (pos_integer(),_,'state') -> {'reply',neg_integer(),'state'} factorial_server_otp.erl:9: Invalid type specification for function factorial_server_otp:factorial/1. The success typing is (pos_integer()) -> neg_integer() done in 0m0.79s done (warnings were emitted)
  • 109. Fixed -­‐spec  handle_call(non_neg_integer(),  {pid(),  any()},  state)  -­‐ >  {reply,  non_neg_integer(),  state}.   handle_call(X,  _From,  state)  -­‐>      {reply,  factorial(X),  state}.   -­‐spec  factorial(non_neg_integer())  -­‐>  non_neg_integer().   factorial(1)  -­‐>  1;   factorial(N)  -­‐>  N  *  factorial(N-­‐1).  
  • 110. Tying it Together 3c075477e55e:talk sdhillon$ dialyzer --plt out.plt factorial_server_otp.erl Checking whether the PLT out.plt is up-to-date... yes Proceeding with analysis... done in 0m0.89s done (passed successfully)
  • 111. Dialyzer • Utilizes typespec • Static, offline analysis • Utilizes PLTs (Persistent Lookup Table)
  • 113. Memory • Process Heaps • ETS Tables • Atom Table • Large Binary Space
  • 114. Memory • Process Heaps • ETS Tables • Atom Table • Large Binary Space
  • 116. Only for items <64B
  • 122. Memory Model • Split memory model • Useful for building high performance systems • Predictability is key • Garbage collected • Shared heap only GC’d under memory pressure
  • 123. Tying it back to Riak
  • 125. Core Applications • Riak_KV • Riak_Core • Riak_API
  • 127. This OTP application encapsulates services for presenting Riak's public-facing interfaces.
  • 132. Riak Core is the distributed systems framework that forms the basis of how Riak distributes data and scales. More generally, it can be thought of as a toolkit for building distributed, scalable, fault-tolerant applications.
  • 140. Ancillary Applications • Lager: Logging • Storage Layer: • Bitcask • Leveldb • Mochiweb: HTTP Interface • Riak_pipe: Distributed map-reduce • Riak_Ensemble: Consensus layer
  • 142. Demos
  • 143. Troubles In Paradise • Distributed Erlang can be problematic due to head- of-line blocking • NIFs (external code) can be problematic due to performance and debugging • BEAM needs a JIT compiler • Work being done here!