aboutsummaryrefslogtreecommitdiffstats
path: root/system/doc/design_principles/des_princ.xml
blob: e21f2a7f4e250b99c0764e4189b95e5b1dd82b34 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE chapter SYSTEM "chapter.dtd">

<chapter>
  <header>
    <copyright>
      <year>1997</year><year>2017</year>
      <holder>Ericsson AB. All Rights Reserved.</holder>
    </copyright>
    <legalnotice>
      Licensed under the Apache License, Version 2.0 (the "License");
      you may not use this file except in compliance with the License.
      You may obtain a copy of the License at
 
          http://www.apache.org/licenses/LICENSE-2.0

      Unless required by applicable law or agreed to in writing, software
      distributed under the License is distributed on an "AS IS" BASIS,
      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
      See the License for the specific language governing permissions and
      limitations under the License.
    
    </legalnotice>

    <title>Overview</title>
    <prepared></prepared>
    <docno></docno>
    <date></date>
    <rev></rev>
    <file>des_princ.xml</file>
  </header>
  <marker id="otp design principles"></marker>
  <p>The <em>OTP design principles</em> define how to
    structure Erlang code in terms of processes, modules,
    and directories.</p>

  <section>
    <title>Supervision Trees</title>
    <p>A basic concept in Erlang/OTP is the <em>supervision tree</em>.
      This is a process structuring model based on the idea of
      <em>workers</em> and <em>supervisors</em>:</p>
    <list type="bulleted">
      <item>Workers are processes that perform computations, that is,
       they do the actual work.</item>
      <item>Supervisors are processes that monitor the behaviour of
       workers. A supervisor can restart a worker if something goes
       wrong.</item>
      <item>The supervision tree is a hierarchical arrangement of
       code into supervisors and workers, which makes it possible to
       design and program fault-tolerant software.</item>
    </list>
    <p>In the following figure, square boxes represents supervisors and
      circles represent workers:</p>
    <marker id="sup6"></marker>
    <image file="../design_principles/sup6.gif">
      <icaption>Supervision Tree</icaption>
    </image>
  </section>

  <section>
    <title>Behaviours</title>
    <p>In a supervision tree, many of the processes have similar
      structures, they follow similar patterns. For example,
      the supervisors are similar in structure. The only difference
      between them is which child processes they supervise. Many
      of the workers are servers in a server-client relation,
      finite-state machines, or event handlers such as error loggers.</p>
    <p><em>Behaviours</em> are formalizations of these common patterns.
      The idea is to divide the code for a process in a generic part
      (a behaviour module) and a specific part (a
      <em>callback module</em>).</p>
    <p>The behaviour module is part of Erlang/OTP. To implement a
      process such as a supervisor, the user only has to implement
      the callback module which is to export a pre-defined set of
      functions, the <em>callback functions</em>.</p>
    <p>The following example illustrate how code can be divided into a
      generic and a specific part. Consider the following code (written in
      plain Erlang) for a simple server, which keeps track of a number
      of "channels". Other processes can allocate and free the channels
      by calling the functions <c>alloc/0</c> and <c>free/1</c>,
      respectively.</p>
    <marker id="ch1"></marker>
    <code type="none">
-module(ch1).
-export([start/0]).
-export([alloc/0, free/1]).
-export([init/0]).

start() ->
    spawn(ch1, init, []).

alloc() ->
    ch1 ! {self(), alloc},
    receive
        {ch1, Res} ->
            Res
    end.

free(Ch) ->
    ch1 ! {free, Ch},
    ok.

init() ->
    register(ch1, self()),
    Chs = channels(),
    loop(Chs).

loop(Chs) ->
    receive
        {From, alloc} ->
            {Ch, Chs2} = alloc(Chs),
            From ! {ch1, Ch},
            loop(Chs2);
        {free, Ch} ->
            Chs2 = free(Ch, Chs),
            loop(Chs2)
    end.</code>
    <p>The code for the server can be rewritten into a generic part
      <c>server.erl</c>:</p>
    <code type="none">
-module(server).
-export([start/1]).
-export([call/2, cast/2]).
-export([init/1]).

start(Mod) ->
    spawn(server, init, [Mod]).

call(Name, Req) ->
    Name ! {call, self(), Req},
    receive
        {Name, Res} ->
            Res
    end.

cast(Name, Req) ->
    Name ! {cast, Req},
    ok.

init(Mod) ->
    register(Mod, self()),
    State = Mod:init(),
    loop(Mod, State).

loop(Mod, State) ->
    receive
        {call, From, Req} ->
            {Res, State2} = Mod:handle_call(Req, State),
            From ! {Mod, Res},
            loop(Mod, State2);
        {cast, Req} ->
            State2 = Mod:handle_cast(Req, State),
            loop(Mod, State2)
    end.</code>
    <p>And a callback module <c>ch2.erl</c>:</p>
    <code type="none">
-module(ch2).
-export([start/0]).
-export([alloc/0, free/1]).
-export([init/0, handle_call/2, handle_cast/2]).

start() ->
    server:start(ch2).

alloc() ->
    server:call(ch2, alloc).

free(Ch) ->
    server:cast(ch2, {free, Ch}).

init() ->
    channels().

handle_call(alloc, Chs) ->
    alloc(Chs). % => {Ch,Chs2}

handle_cast({free, Ch}, Chs) ->
    free(Ch, Chs). % => Chs2</code>
    <p>Notice the following:</p>
    <list type="bulleted">
      <item>The code in <c>server</c> can be reused to build many
       different servers.</item>
      <item>The server name, in this example the atom
      <c>ch2</c>, is hidden from the users of the client functions. This
       means that the name can be changed without affecting them.</item>
      <item>The protocol (messages sent to and received from the server)
       is also hidden. This is good programming practice and allows
       one to change the protocol without changing the code using
       the interface functions.</item>
      <item>The functionality of <c>server</c> can be extended without
       having to change <c>ch2</c> or any other callback module.</item>
    </list>
    <p>In <c>ch1.erl</c> and <c>ch2.erl</c> above, the implementation
      of <c>channels/0</c>, <c>alloc/1</c>, and <c>free/2</c> has been
      intentionally left out, as it is not relevant to the example.
      For completeness, one way to write these functions are given
      below. This is an example only, a realistic
      implementation must be able to handle situations like running out
      of channels to allocate, and so on.</p>
    <code type="none">
channels() ->
   {_Allocated = [], _Free = lists:seq(1,100)}.

alloc({Allocated, [H|T] = _Free}) ->
   {H, {[H|Allocated], T}}.

free(Ch, {Alloc, Free} = Channels) ->
   case lists:member(Ch, Alloc) of
      true ->
         {lists:delete(Ch, Alloc), [Ch|Free]};
      false ->
         Channels
   end.        </code>
    <p>Code written without using behaviours can be more
      efficient, but the increased efficiency is at the expense of
      generality. The ability to manage all applications in the system
      in a consistent manner is important.</p>
    <p>Using behaviours also makes it easier to read and understand
      code written by other programmers. Improvised programming structures,
      while possibly more efficient, are always more difficult to
      understand.</p>
    <p>The <c>server</c> module corresponds, greatly simplified,
      to the Erlang/OTP behaviour <c>gen_server</c>.</p>
    <p>The standard Erlang/OTP behaviours are:</p>
    <list type="bulleted">
      <item><p><seealso marker="gen_server_concepts">gen_server</seealso></p>
      <p>For implementing the server of a client-server relation</p></item>
      <item><p><seealso marker="statem">gen_statem</seealso></p>
      <p>For implementing state machines</p></item>
      <item><p><seealso marker="events">gen_event</seealso></p>
      <p>For implementing event handling functionality</p></item>
      <item><p><seealso marker="sup_princ">supervisor</seealso></p>
      <p>For implementing a supervisor in a supervision tree</p></item>
      </list>
    <p>The compiler understands the module attribute
      <c>-behaviour(Behaviour)</c> and issues warnings about
      missing callback functions, for example:</p>
    <code type="none">
-module(chs3).
-behaviour(gen_server).
...

3> c(chs3).
./chs3.erl:10: Warning: undefined call-back function handle_call/3
{ok,chs3}</code>
  </section>

  <section>
    <title>Applications</title>
    <p>Erlang/OTP comes with a number of components, each implementing
      some specific functionality. Components are with Erlang/OTP
      terminology called <em>applications</em>. Examples of Erlang/OTP
      applications are Mnesia, which has everything needed for
      programming database services, and Debugger, which is used
      to debug Erlang programs. The minimal system based on Erlang/OTP
      consists of the following two applications:</p>
      <list type="bulleted">
	<item>Kernel - Functionality necessary to run Erlang</item>
	<item>STDLIB - Erlang standard libraries</item>
      </list>
    <p>The application concept applies both to program structure
      (processes) and directory structure (modules).</p>
    <p>The simplest applications do not have any processes,
      but consist of a collection of functional modules. Such an
      application is called a <em>library application</em>. An example
      of a library application is STDLIB.</p>
    <p>An application with processes is easiest implemented as a
      supervision tree using the standard behaviours.</p>
    <p>How to program applications is described in
      <seealso marker="applications">Applications</seealso>.</p>
  </section>

  <section>
    <title>Releases</title>
    <p>A <em>release</em> is a complete system made out from a subset of
      Erlang/OTP applications and a set of user-specific applications.</p>
    <p>How to program releases is described in
      <seealso marker="release_structure">Releases</seealso>.</p>
    <p>How to install a release in a target environment is described
      in the section about target systems in Section 2 System Principles.</p>
  </section>

  <section>
    <title>Release Handling</title>
    <p><em>Release handling</em> is upgrading and downgrading between
      different versions of a release, in a (possibly) running system.
      How to do this is described in
      <seealso marker="release_handling">Release Handling</seealso>.</p>
  </section>
</chapter>