├── LICENSE └── README.md /LICENSE: -------------------------------------------------------------------------------- 1 | Attribution 4.0 International 2 | 3 | ======================================================================= 4 | 5 | Creative Commons Corporation ("Creative Commons") is not a law firm and 6 | does not provide legal services or legal advice. Distribution of 7 | Creative Commons public licenses does not create a lawyer-client or 8 | other relationship. Creative Commons makes its licenses and related 9 | information available on an "as-is" basis. Creative Commons gives no 10 | warranties regarding its licenses, any material licensed under their 11 | terms and conditions, or any related information. Creative Commons 12 | disclaims all liability for damages resulting from their use to the 13 | fullest extent possible. 14 | 15 | Using Creative Commons Public Licenses 16 | 17 | Creative Commons public licenses provide a standard set of terms and 18 | conditions that creators and other rights holders may use to share 19 | original works of authorship and other material subject to copyright 20 | and certain other rights specified in the public license below. The 21 | following considerations are for informational purposes only, are not 22 | exhaustive, and do not form part of our licenses. 23 | 24 | Considerations for licensors: Our public licenses are 25 | intended for use by those authorized to give the public 26 | permission to use material in ways otherwise restricted by 27 | copyright and certain other rights. Our licenses are 28 | irrevocable. Licensors should read and understand the terms 29 | and conditions of the license they choose before applying it. 30 | Licensors should also secure all rights necessary before 31 | applying our licenses so that the public can reuse the 32 | material as expected. Licensors should clearly mark any 33 | material not subject to the license. This includes other CC- 34 | licensed material, or material used under an exception or 35 | limitation to copyright. More considerations for licensors: 36 | wiki.creativecommons.org/Considerations_for_licensors 37 | 38 | Considerations for the public: By using one of our public 39 | licenses, a licensor grants the public permission to use the 40 | licensed material under specified terms and conditions. If 41 | the licensor's permission is not necessary for any reason--for 42 | example, because of any applicable exception or limitation to 43 | copyright--then that use is not regulated by the license. Our 44 | licenses grant only permissions under copyright and certain 45 | other rights that a licensor has authority to grant. Use of 46 | the licensed material may still be restricted for other 47 | reasons, including because others have copyright or other 48 | rights in the material. A licensor may make special requests, 49 | such as asking that all changes be marked or described. 50 | Although not required by our licenses, you are encouraged to 51 | respect those requests where reasonable. More_considerations 52 | for the public: 53 | wiki.creativecommons.org/Considerations_for_licensees 54 | 55 | ======================================================================= 56 | 57 | Creative Commons Attribution 4.0 International Public License 58 | 59 | By exercising the Licensed Rights (defined below), You accept and agree 60 | to be bound by the terms and conditions of this Creative Commons 61 | Attribution 4.0 International Public License ("Public License"). To the 62 | extent this Public License may be interpreted as a contract, You are 63 | granted the Licensed Rights in consideration of Your acceptance of 64 | these terms and conditions, and the Licensor grants You such rights in 65 | consideration of benefits the Licensor receives from making the 66 | Licensed Material available under these terms and conditions. 67 | 68 | 69 | Section 1 -- Definitions. 70 | 71 | a. Adapted Material means material subject to Copyright and Similar 72 | Rights that is derived from or based upon the Licensed Material 73 | and in which the Licensed Material is translated, altered, 74 | arranged, transformed, or otherwise modified in a manner requiring 75 | permission under the Copyright and Similar Rights held by the 76 | Licensor. For purposes of this Public License, where the Licensed 77 | Material is a musical work, performance, or sound recording, 78 | Adapted Material is always produced where the Licensed Material is 79 | synched in timed relation with a moving image. 80 | 81 | b. Adapter's License means the license You apply to Your Copyright 82 | and Similar Rights in Your contributions to Adapted Material in 83 | accordance with the terms and conditions of this Public License. 84 | 85 | c. Copyright and Similar Rights means copyright and/or similar rights 86 | closely related to copyright including, without limitation, 87 | performance, broadcast, sound recording, and Sui Generis Database 88 | Rights, without regard to how the rights are labeled or 89 | categorized. For purposes of this Public License, the rights 90 | specified in Section 2(b)(1)-(2) are not Copyright and Similar 91 | Rights. 92 | 93 | d. Effective Technological Measures means those measures that, in the 94 | absence of proper authority, may not be circumvented under laws 95 | fulfilling obligations under Article 11 of the WIPO Copyright 96 | Treaty adopted on December 20, 1996, and/or similar international 97 | agreements. 98 | 99 | e. Exceptions and Limitations means fair use, fair dealing, and/or 100 | any other exception or limitation to Copyright and Similar Rights 101 | that applies to Your use of the Licensed Material. 102 | 103 | f. Licensed Material means the artistic or literary work, database, 104 | or other material to which the Licensor applied this Public 105 | License. 106 | 107 | g. Licensed Rights means the rights granted to You subject to the 108 | terms and conditions of this Public License, which are limited to 109 | all Copyright and Similar Rights that apply to Your use of the 110 | Licensed Material and that the Licensor has authority to license. 111 | 112 | h. Licensor means the individual(s) or entity(ies) granting rights 113 | under this Public License. 114 | 115 | i. Share means to provide material to the public by any means or 116 | process that requires permission under the Licensed Rights, such 117 | as reproduction, public display, public performance, distribution, 118 | dissemination, communication, or importation, and to make material 119 | available to the public including in ways that members of the 120 | public may access the material from a place and at a time 121 | individually chosen by them. 122 | 123 | j. Sui Generis Database Rights means rights other than copyright 124 | resulting from Directive 96/9/EC of the European Parliament and of 125 | the Council of 11 March 1996 on the legal protection of databases, 126 | as amended and/or succeeded, as well as other essentially 127 | equivalent rights anywhere in the world. 128 | 129 | k. You means the individual or entity exercising the Licensed Rights 130 | under this Public License. Your has a corresponding meaning. 131 | 132 | 133 | Section 2 -- Scope. 134 | 135 | a. License grant. 136 | 137 | 1. Subject to the terms and conditions of this Public License, 138 | the Licensor hereby grants You a worldwide, royalty-free, 139 | non-sublicensable, non-exclusive, irrevocable license to 140 | exercise the Licensed Rights in the Licensed Material to: 141 | 142 | a. reproduce and Share the Licensed Material, in whole or 143 | in part; and 144 | 145 | b. produce, reproduce, and Share Adapted Material. 146 | 147 | 2. Exceptions and Limitations. For the avoidance of doubt, where 148 | Exceptions and Limitations apply to Your use, this Public 149 | License does not apply, and You do not need to comply with 150 | its terms and conditions. 151 | 152 | 3. Term. The term of this Public License is specified in Section 153 | 6(a). 154 | 155 | 4. Media and formats; technical modifications allowed. The 156 | Licensor authorizes You to exercise the Licensed Rights in 157 | all media and formats whether now known or hereafter created, 158 | and to make technical modifications necessary to do so. The 159 | Licensor waives and/or agrees not to assert any right or 160 | authority to forbid You from making technical modifications 161 | necessary to exercise the Licensed Rights, including 162 | technical modifications necessary to circumvent Effective 163 | Technological Measures. For purposes of this Public License, 164 | simply making modifications authorized by this Section 2(a) 165 | (4) never produces Adapted Material. 166 | 167 | 5. Downstream recipients. 168 | 169 | a. Offer from the Licensor -- Licensed Material. Every 170 | recipient of the Licensed Material automatically 171 | receives an offer from the Licensor to exercise the 172 | Licensed Rights under the terms and conditions of this 173 | Public License. 174 | 175 | b. No downstream restrictions. You may not offer or impose 176 | any additional or different terms or conditions on, or 177 | apply any Effective Technological Measures to, the 178 | Licensed Material if doing so restricts exercise of the 179 | Licensed Rights by any recipient of the Licensed 180 | Material. 181 | 182 | 6. No endorsement. Nothing in this Public License constitutes or 183 | may be construed as permission to assert or imply that You 184 | are, or that Your use of the Licensed Material is, connected 185 | with, or sponsored, endorsed, or granted official status by, 186 | the Licensor or others designated to receive attribution as 187 | provided in Section 3(a)(1)(A)(i). 188 | 189 | b. Other rights. 190 | 191 | 1. Moral rights, such as the right of integrity, are not 192 | licensed under this Public License, nor are publicity, 193 | privacy, and/or other similar personality rights; however, to 194 | the extent possible, the Licensor waives and/or agrees not to 195 | assert any such rights held by the Licensor to the limited 196 | extent necessary to allow You to exercise the Licensed 197 | Rights, but not otherwise. 198 | 199 | 2. Patent and trademark rights are not licensed under this 200 | Public License. 201 | 202 | 3. To the extent possible, the Licensor waives any right to 203 | collect royalties from You for the exercise of the Licensed 204 | Rights, whether directly or through a collecting society 205 | under any voluntary or waivable statutory or compulsory 206 | licensing scheme. In all other cases the Licensor expressly 207 | reserves any right to collect such royalties. 208 | 209 | 210 | Section 3 -- License Conditions. 211 | 212 | Your exercise of the Licensed Rights is expressly made subject to the 213 | following conditions. 214 | 215 | a. Attribution. 216 | 217 | 1. If You Share the Licensed Material (including in modified 218 | form), You must: 219 | 220 | a. retain the following if it is supplied by the Licensor 221 | with the Licensed Material: 222 | 223 | i. identification of the creator(s) of the Licensed 224 | Material and any others designated to receive 225 | attribution, in any reasonable manner requested by 226 | the Licensor (including by pseudonym if 227 | designated); 228 | 229 | ii. a copyright notice; 230 | 231 | iii. a notice that refers to this Public License; 232 | 233 | iv. a notice that refers to the disclaimer of 234 | warranties; 235 | 236 | v. a URI or hyperlink to the Licensed Material to the 237 | extent reasonably practicable; 238 | 239 | b. indicate if You modified the Licensed Material and 240 | retain an indication of any previous modifications; and 241 | 242 | c. indicate the Licensed Material is licensed under this 243 | Public License, and include the text of, or the URI or 244 | hyperlink to, this Public License. 245 | 246 | 2. You may satisfy the conditions in Section 3(a)(1) in any 247 | reasonable manner based on the medium, means, and context in 248 | which You Share the Licensed Material. For example, it may be 249 | reasonable to satisfy the conditions by providing a URI or 250 | hyperlink to a resource that includes the required 251 | information. 252 | 253 | 3. If requested by the Licensor, You must remove any of the 254 | information required by Section 3(a)(1)(A) to the extent 255 | reasonably practicable. 256 | 257 | 4. If You Share Adapted Material You produce, the Adapter's 258 | License You apply must not prevent recipients of the Adapted 259 | Material from complying with this Public License. 260 | 261 | 262 | Section 4 -- Sui Generis Database Rights. 263 | 264 | Where the Licensed Rights include Sui Generis Database Rights that 265 | apply to Your use of the Licensed Material: 266 | 267 | a. for the avoidance of doubt, Section 2(a)(1) grants You the right 268 | to extract, reuse, reproduce, and Share all or a substantial 269 | portion of the contents of the database; 270 | 271 | b. if You include all or a substantial portion of the database 272 | contents in a database in which You have Sui Generis Database 273 | Rights, then the database in which You have Sui Generis Database 274 | Rights (but not its individual contents) is Adapted Material; and 275 | 276 | c. You must comply with the conditions in Section 3(a) if You Share 277 | all or a substantial portion of the contents of the database. 278 | 279 | For the avoidance of doubt, this Section 4 supplements and does not 280 | replace Your obligations under this Public License where the Licensed 281 | Rights include other Copyright and Similar Rights. 282 | 283 | 284 | Section 5 -- Disclaimer of Warranties and Limitation of Liability. 285 | 286 | a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE 287 | EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS 288 | AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF 289 | ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS, 290 | IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION, 291 | WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR 292 | PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS, 293 | ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT 294 | KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT 295 | ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU. 296 | 297 | b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE 298 | TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION, 299 | NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT, 300 | INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES, 301 | COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR 302 | USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN 303 | ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR 304 | DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR 305 | IN PART, THIS LIMITATION MAY NOT APPLY TO YOU. 306 | 307 | c. The disclaimer of warranties and limitation of liability provided 308 | above shall be interpreted in a manner that, to the extent 309 | possible, most closely approximates an absolute disclaimer and 310 | waiver of all liability. 311 | 312 | 313 | Section 6 -- Term and Termination. 314 | 315 | a. This Public License applies for the term of the Copyright and 316 | Similar Rights licensed here. However, if You fail to comply with 317 | this Public License, then Your rights under this Public License 318 | terminate automatically. 319 | 320 | b. Where Your right to use the Licensed Material has terminated under 321 | Section 6(a), it reinstates: 322 | 323 | 1. automatically as of the date the violation is cured, provided 324 | it is cured within 30 days of Your discovery of the 325 | violation; or 326 | 327 | 2. upon express reinstatement by the Licensor. 328 | 329 | For the avoidance of doubt, this Section 6(b) does not affect any 330 | right the Licensor may have to seek remedies for Your violations 331 | of this Public License. 332 | 333 | c. For the avoidance of doubt, the Licensor may also offer the 334 | Licensed Material under separate terms or conditions or stop 335 | distributing the Licensed Material at any time; however, doing so 336 | will not terminate this Public License. 337 | 338 | d. Sections 1, 5, 6, 7, and 8 survive termination of this Public 339 | License. 340 | 341 | 342 | Section 7 -- Other Terms and Conditions. 343 | 344 | a. The Licensor shall not be bound by any additional or different 345 | terms or conditions communicated by You unless expressly agreed. 346 | 347 | b. Any arrangements, understandings, or agreements regarding the 348 | Licensed Material not stated herein are separate from and 349 | independent of the terms and conditions of this Public License. 350 | 351 | 352 | Section 8 -- Interpretation. 353 | 354 | a. For the avoidance of doubt, this Public License does not, and 355 | shall not be interpreted to, reduce, limit, restrict, or impose 356 | conditions on any use of the Licensed Material that could lawfully 357 | be made without permission under this Public License. 358 | 359 | b. To the extent possible, if any provision of this Public License is 360 | deemed unenforceable, it shall be automatically reformed to the 361 | minimum extent necessary to make it enforceable. If the provision 362 | cannot be reformed, it shall be severed from this Public License 363 | without affecting the enforceability of the remaining terms and 364 | conditions. 365 | 366 | c. No term or condition of this Public License will be waived and no 367 | failure to comply consented to unless expressly agreed to by the 368 | Licensor. 369 | 370 | d. Nothing in this Public License constitutes or may be interpreted 371 | as a limitation upon, or waiver of, any privileges and immunities 372 | that apply to the Licensor or You, including from the legal 373 | processes of any jurisdiction or authority. 374 | 375 | 376 | ======================================================================= 377 | 378 | Creative Commons is not a party to its public 379 | licenses. Notwithstanding, Creative Commons may elect to apply one of 380 | its public licenses to material it publishes and in those instances 381 | will be considered the “Licensor.” The text of the Creative Commons 382 | public licenses is dedicated to the public domain under the CC0 Public 383 | Domain Dedication. Except for the limited purpose of indicating that 384 | material is shared under a Creative Commons public license or as 385 | otherwise permitted by the Creative Commons policies published at 386 | creativecommons.org/policies, Creative Commons does not authorize the 387 | use of the trademark "Creative Commons" or any other trademark or logo 388 | of Creative Commons without its prior written consent including, 389 | without limitation, in connection with any unauthorized modifications 390 | to any of its public licenses or any other arrangements, 391 | understandings, or agreements concerning use of licensed material. For 392 | the avoidance of doubt, this paragraph does not form part of the 393 | public licenses. 394 | 395 | Creative Commons may be contacted at creativecommons.org. 396 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Originaly published on December 2012 at http://blog.bot.co.za/en/article/349/an-erlang-otp-tutorial-for-beginners 2 | 3 | # An Erlang OTP tutorial for beginners — A bot blog 4 | 5 | This is an Erlang/OTP tutorial for novice Erlang programmers. If you are familiar with Erlang's syntax, know how to compile modules and are curious to discover OTP and how to leverage its power in your own Erlang applications this tutorial is for you. To kick off we are going to create a non-OTP server and supervisor, examine their shortcomings and then turn our code into a proper OTP application. 6 | 7 | This tutorial will look at: 8 | 9 | * How to build a non-OTP server from scratch and how to automatically restart it using a non-OTP supervisor. 10 | * What the shortcomings of our implementation are and how to addresses them with OTP. 11 | * Very briefly, tools such as _rebar_ to smothen our OTP journey and OTP's folder conventions. 12 | * How to use OTP's _gen_server_ and _supervisor_ behaviour. 13 | * The OTP _application_ behaviour to tie it all together. 14 | 15 | First, however, some introductions are in order. 16 | 17 | ## About you 18 | 19 | I assume that you are familiar with Erlang's syntax, that you know what Erlang modules are and how to compile them and that you understand functional programming concepts such as recursion and single-assignment variables. You do? Great! Let's learn some OTP. It is not difficult to get started, as you will find out shortly, but first let me tell you briefly about my own Erlang experience. 20 | 21 | ## About me 22 | 23 | I am pretty much on the same page as you - except perhaps, that I've started to read Manning's Erlang & OTP in action. I am not exaggerating when I say that OTP in action is one of my favourite technical books. It contains a wealth of easy to absorb information. [Buy a copy][1] if you can. 24 | 25 | 'Scaffolding', I think, is what they called it in psychology class when peers teach peers. I am writing this as much to cement my own undertstanding of OTP as to help kickstart yours. Let's study together. Please leave a comment whenever you think I am wrong. 26 | 27 | ## About OTP 28 | 29 | OTP stands for Open Telecom Platform but in spite of its name it is not tied to telecom applications whatsoever. Think of OTP as framework to help you write robust and highly available applications on the Erlang platform. 30 | 31 | Specifially, you might like to think of OTP in terms of the following concepts: 32 | 33 | * a specification (called a 'behaviour') that dictates which functions your module should export 34 | * a concrete module that declares that it conforms to a behaviour and implements these functions 35 | * a runtime component that can execute behaviour-compliant modules within the OTP context 36 | 37 | If you are coming from on Object Oriented world such as Jave these concepts roughly translate to: 38 | 39 | * an interface or abstract class that defines a behaviour 40 | * a concrete derived implementation of that interface or abstract class 41 | * a container that knows how to instrument instances of such concrete implementations 42 | 43 | Please understand that these are, of course, only superficial similarities. They might help us understand new concepts in terms of old knowledge, but, make no mistake, we are comparing apples and oranges. 44 | 45 | ## A non OTP server 46 | 47 | With the introductions out of the way let's make sure that we really are on the same page by writing a simple server that does not use OTP. Here's the code: 48 | 49 | 50 | %%%--------------------------------------------------------------------------- 51 | %%% @doc A simple server that does not use OTP. 52 | %%% @author Hans Christian v. Stockhausen 53 | %%% @end 54 | %%%--------------------------------------------------------------------------- 55 | 56 | -module(no_otp). % module name (same as our erl filename, 57 | % i.e. no_otp.erl) 58 | 59 | %% API 60 | -export([ % the functions we export - our API 61 | start/0, % - start new server process 62 | stop/0, % - stop server 63 | say_hello/0, % - print "Hello" to stdout 64 | get_count/0 % - reply with number of times the main 65 | ]). % loop was executed 66 | 67 | %% Callbacks 68 | -export([init/0]). % exported so we can spawn it in start/0 69 | % listed as a separate export here as a 70 | % hint to clients not to use it 71 | 72 | -define(SERVER, ?MODULE). % SERVER macro is an alias for MODULE, 73 | % and expands to 'no_otp' 74 | 75 | -record(state, {count}). % record for our server state. Rather 76 | % arbitrarily we track how often the 77 | % main loop is run - see loop/1 78 | 79 | 80 | %============================================================================= 81 | % API - functions that our clients use to interact with the server 82 | %============================================================================= 83 | 84 | start() -> % spawn new process that calls init/0 85 | spawn(?MODULE, init, []). % the new process' PID is returned 86 | 87 | stop() -> % send the atom stop to the process 88 | ?SERVER ! stop, % to instruct our server to shut down 89 | ok. % and return ok to caller 90 | 91 | say_hello() -> % send the atom say_hello to the process 92 | ?SERVER ! say_hello, % to print "Hello" to sdout 93 | ok. 94 | 95 | get_count() -> % send callers Pid and the atom get_count 96 | ?SERVER ! {self(), get_count}, % to request counter value 97 | receive % wait for matching response and return 98 | {count, Value} -> Value % Value to the caller 99 | end. 100 | 101 | 102 | %============================================================================= 103 | % callback functions - not to be used by clients directly 104 | %============================================================================= 105 | 106 | init() -> % invoked by start/0 107 | register(?SERVER, self()), % register new process PID under no_otp 108 | loop(#state{count=0}). % start main server loop 109 | 110 | %============================================================================= 111 | % internal functions - note, these functions are not exported 112 | %============================================================================= 113 | 114 | loop(#state{count=Count}) -> % the main server loop 115 | receive Msg -> % when API functions send a message 116 | case Msg of % check the atom contained 117 | stop -> % if atom is 'stop' 118 | exit(normal); % exit the process 119 | say_hello -> % if atom is 'say_hello' 120 | io:format("Hello~n"); % write "Hello" to stdout 121 | {From, get_count} -> % if Msg is tuple {Pid(), get_count} 122 | From ! {count, Count} % reply with current counter value 123 | end % in tagged tupple {count, Value} 124 | end, 125 | loop(#state{count = Count + 1}). % recurse with updated state 126 | 127 | ## Let's try our server 128 | 129 | * Save the code above to a file named _no_otp.erl_. 130 | * Start the Erlang shell with erl in the same directory. 131 | * Compile the module: c(no_otp). 132 | * Start the server: no_otp:start(). 133 | * Instruct the server to print "Hello" a couple of times: no_otp:say_hello(). 134 | * Ask for the current invocation counter value: no_otp:get_count(). 135 | * Shut the server down: no_otp:stop(). 136 | 137 | Here is my session. Admittedly, one has to wonder what's the point of get_count/0. There is none, except to demonstrate how to implement a synchronous function. 138 | 139 | 140 | Eshell V5.8.5 (abort with ^G) 141 | 1> c(no_otp). 142 | {ok,no_otp} 143 | 2> no_otp:start(). 144 | <0.39.0> 145 | 3> no_otp:get_count(). 146 | 0 147 | 4> no_otp:say_hello(). 148 | Hello 149 | ok 150 | 5> no_otp:get_count(). 151 | 2 152 | 6> 153 | 154 | 155 | I initially found the term _server_ in this context a little confusing. How is this a server? On second thought, it is not at all unlike the HTTP server that served this page to your browser. It runs continously until you stop it, it speaks a protocol (not HTTP but Erlang's internal messaging protocol) and responds to inputs with side-effects or response messages. It's a server, alright. 156 | 157 | I am not going to discuss the code here in detail, since the comments already do that, I hope. However, I would like to briefly outline the structure: 158 | 159 | * Implementation details are hidden from clients by a thin API layer. The functions start/0, stop/0, etc.. decouple clients from the internal protocol (i.e. the atoms 'start', 'stop', … that these functions send) as well as from internal functions. As a result we could modify either or both without breaking client code. 160 | * There exists a function init/0 that sets up the initial state and starts the main server loop. It also registeres our server, by convention, under the module name and could perform additional initialisation steps such as opening a database connection. Note that this function is exported by our module even though it is not intended to be called by client code. Otherwise our call to spawn/3 in start/0 does not work. 161 | * There is a main loop that waits for messages, performs some actions in response, optionally updates the server state and finally calls itself. 162 | 163 | ## What's wrong with this server? 164 | 165 | Not much really. Thanks to Erlang it should run and run and run once started. This is a such a simple server, so we can be quite confident that our implementation is correct. Also, thanks to our API, we can be certain that clients don't inadvertently crash it by sending malformed data - or can we? 166 | 167 | Start up the server as before and then type no_otp ! crash. at the shell. 168 | 169 | Ouch! Since the server is registered under the name no_otp (see init/0) we can send arbitrary messages to it and because our code does not have a matching case clause for 'crash': it crashes. 170 | 171 | What to do? We could write a case clause to match any message and simply ignore it. However, that would be like a catch-all-clause when handling Exceptions, which we know is evil and likely to obscure bugs. 172 | 173 | Erlang follows a philosophy of 'let it crash'. There we go again. I am sure you've read that phrase more than once. But let's recap what that means for you, the Erlang programmer: Don't program defensively, don't try to anticipate all circumstances, focus on your specification, on what the code should do and keep it compact and succinct. If there are bugs in your code, it will crash and you can fix it. If it crashes, because of bugs in your client's code, let it crash and restart in a known good state, rather than trying to keep it alive at all costs. Don't complicate the code by trying to sort out your client's mess. It is theirs to fix. Got it? 174 | 175 | ## Supervision 176 | 177 | Fine, I'll let it crash, but how can I automatically restart the server when that happens? The answer is to code another process, that monitors our server and restarts it when it detects that it died. Such a process is a _supervisor_ and what follows is the code for our non-OTP version. 178 | 179 | ## A non-OTP supervisor 180 | 181 | Before I show you the supervisor code have a look at the annotated Erlang shell session below to see how to exercise it. The function whereis/0 returns the Pid of the process that is registered under a particular name. We can see that sup:start_server/0 must in fact have started our _no_otp_ server, since it shows up under process ID <0.40.0>. Automatic restart also seems to work as it should. 182 | 183 | 184 | Eshell V5.8.5 (abort with ^G) 185 | 1> c(sup). % compile our supervisor module 186 | {ok,sup} 187 | 2> sup:start_server(). % start the supervisor 188 | <0.39.0> % it got the process ID ..39.. 189 | 3> whereis(no_otp). % let's find our no_otp process 190 | <0.40.0> % it got ..40.. 191 | 4> no_otp:say_hello(). % let's try to use the API 192 | Hello % works 193 | ok 194 | 5> no_otp:get_count(). % works too 195 | 1 196 | 6> no_otp ! crash. % time to crash it 197 | crash 198 | 199 | =ERROR REPORT=== 200 | Error in process <0.40.0> with exit value: 201 | {{case_clause,crash},[{no_otp,loop,1}]} % as expected a case_clause error 202 | 203 | 7> no_otp:get_count(). % but a new process was started 204 | 0 % as we can see here 205 | 8> no_otp:stop(). % now let's stop it 'normally' 206 | ok 207 | 9> whereis(no_otp). % and check for a new instance 208 | undefined % but there is none. Correct! 209 | 10> 210 | 211 | 212 | Now, for the supervisor code: 213 | 214 | 215 | %%%---------------------------------------------------------------------------- 216 | %%% @doc A non-OTP supervisor 217 | %%% @author Hans Christian v. Stockhausen 218 | %%% @end 219 | %%%---------------------------------------------------------------------------- 220 | 221 | -module(sup). 222 | 223 | %% API 224 | -export([start_server/0]). 225 | 226 | %% Callbacks 227 | -export([supervise/0]). 228 | 229 | %%============================================================================= 230 | %% API 231 | %%============================================================================= 232 | 233 | start_server() -> 234 | spawn(?MODULE, supervise, []). 235 | 236 | %%============================================================================= 237 | %% Callbacks 238 | %%============================================================================= 239 | 240 | supervise() -> 241 | process_flag(trap_exit, true), % don't crash us but rather send us a 242 | % message when a linked process dies 243 | Pid = no_otp:start(), % start our server 244 | link(Pid), % and link to it 245 | receive {'EXIT', Pid, Reason} -> % wait for a message that informs us 246 | case Reason of % that our porcess shut down 247 | normal -> ok; % if the reason is 'normal' do nothing 248 | _Other -> start_server() % otherwise start all over 249 | end 250 | end. 251 | 252 | 253 | As I wrote in the introduction, I am an Erlang novice myself. I have little confidence in the supervisor code above, and **that's the point**. If we want to write applications the 'Erlang way', if we want to embrace the philosophy of 'let it crash', we have to structure our code in terms of servers, supervisors and supervisors' supervisors. That's a lot of structural code and a lot of repetitive boilerplate with amble opportunity to introduce bugs. The concept of servers and supervision hierarchies is easy enough to understand. However, is it also easy to get 100% right? 254 | 255 | ## OTP to the rescue 256 | 257 | Fortunately for us, someone else has done the hard work already. There is OTP, a framework specifically written to help us compose servers, supervisors and other components, which we will examine at a later stage. The OTP developers have given us a rock solid framework to hook our own, possibly brittle code, into a framework that is tested, battle-hardend and known to work. 258 | 259 | It is time to rewrite our server and supervisor as OTP behaviours. But firstly, let's look at two tools, to help us along the way. 260 | 261 | ## Rebar & Emacs 262 | 263 | Just because OTP saves us from having to reinvent supervision hierarchies there is, as you will see, still a fair amount of code that one has to type. A lot remains boilerplate and gets real tideous real fast. Also, you want to get into the good habit of documenting your code with _Edoc annotations_, which results in even more repetitive typing. Hence, a little tool support is in order. 264 | 265 | **Rebar** is a build tool for Erlang. Check their [github wiki page][2] for detailed instructions. I am only going to cover what we need now. 266 | 267 | Run the following commands from your nix Shell to install rebar and to create the scaffolding for our app 'hello'. 268 | 269 | 270 | $> mkdir hello 271 | $> cd hello 272 | $> wget https://raw.github.com/wiki/rebar/rebar/rebar 273 | $> chmod u+x rebar 274 | $> ./rebar create-app appid=hello 275 | 276 | 277 | If you list the contents of the newly created _src_ directory you will see that the following files have been generated: 278 | 279 | * _hello_app.erl_ \- OTP application behaviour (ignore for now) 280 | * _hello.app.src_ \- OTP application configuration template (also ignore please) 281 | * _hello_sup.erl_ \- minimal root supervisor implementation 282 | 283 | What's missing is a file to contain our server code. Let's ask _rebar_ to generate one for us. 284 | 285 | 286 | $> ./rebar create template=simplesrv srvid=hello_server 287 | 288 | 289 | If you don't want to use rebar you can, of course, create the files manually and place them into your _src_ folder. It's convention to call the folder _src_, as I will explain shortly. 290 | 291 | **Emacs** offers an Erlang mode that really speeds up your Edit-Compile-Run cycle and also comes with templates. I mostly use _vi_, for day-to-day editing tasks, but was always looking for a reason to try _emacs_. I've found one in its Erlang mode and suggest you try it too, if you haven't done so already. Try it now: 292 | * emacs src/hello_sup.erl 293 | * hit **F10** to open the menu 294 | * type **e** for Erlang 295 | * type **c** to select the **compile** option 296 | * type **c** again to compile _hello_sup.erl_ (Note the shortcut C-c C-k for future reference) 297 | * Inspect the compiler output 298 | * press **C-0** to close the compiler window 299 | * press **C-x C-c** to exit _emacs_ 300 | 301 | Powerfull stuff and we've barely scratched the surface, I am sure, but feel free to follow along with your favourite editor. 302 | 303 | Before we finally implement our OTP behaviours, we have to look at OTP folder layout. 304 | 305 | ## OTP folders 306 | 307 | To create the OTP folder structure use the following command from bash, alternatively **rebar** can create them for you. Only _src_ and _ebin_ are required. 308 | 309 | 310 | mkdir -p my_app/{doc,ebin,priv,include,src,test} 311 | 312 | 313 | * _doc_ \- for documentation which typically is generated automatically 314 | * _ebin_ \- your compiled code (.beam) 315 | * _priv_ \- resource files such as html, images etc. 316 | * _include_ \- public header files that client code may use (.hrl) 317 | * _src_ \- source code and private header files (.erl, .hrl) 318 | * _test_ \- tests (_test.erl) 319 | 320 | ## OTP gen_server 321 | 322 | As the name implies, the _gen_server_ behaviour helps us write generic servers. Here's our server rewritten as OTP behaviour. 323 | 324 | 325 | %%%---------------------------------------------------------------------------- 326 | %%% @doc An OTP gen_server example 327 | %%% @author Hans Christian v. Stockhausen 328 | %%% @end 329 | %%%---------------------------------------------------------------------------- 330 | 331 | -module(hello_server). % Nothing new in this section except for the 332 | % next line where we tell the compiler that 333 | -behaviour(gen_server). % this module implements the gen_server 334 | % behaviour. The compiler will warn us if 335 | -define(SERVER, ?MODULE). % we do not provide all callback functions 336 | % the behaviour announces. It knows what 337 | -record(state, {count}). % functions to expect by calling 338 | % gen_server:behaviour_info(callbacks). Try it. 339 | %%----------------------------------------------------------------------------- 340 | %% API Function Exports 341 | %%----------------------------------------------------------------------------- 342 | 343 | -export([ % Here we define our API functions as before 344 | start_link/0, % - starts and links the process in one step 345 | stop/0, % - stops it 346 | say_hello/0, % - prints "Hello" to stdout 347 | get_count/0]). % - returns the count state 348 | 349 | %% --------------------------------------------------------------------------- 350 | %% gen_server Function Exports 351 | %% --------------------------------------------------------------------------- 352 | 353 | -export([ % The behaviour callbacks 354 | init/1, % - initializes our process 355 | handle_call/3, % - handles synchronous calls (with response) 356 | handle_cast/2, % - handles asynchronous calls (no response) 357 | handle_info/2, % - handles out of band messages (sent with !) 358 | terminate/2, % - is called on shut-down 359 | code_change/3]). % - called to handle code changes 360 | 361 | %% --------------------------------------------------------------------------- 362 | %% API Function Definitions 363 | %% --------------------------------------------------------------------------- 364 | 365 | start_link() -> % start_link spawns and links to a new 366 | gen_server:start_link( % process in one atomic step. The parameters: 367 | {local, ?SERVER}, % - name to register the process under locally 368 | ?MODULE, % - the module to find the init/1 callback in 369 | [], % - what parameters to pass to init/1 370 | []). % - additional options to start_link 371 | 372 | stop() -> % Note that we do not use ! anymore. Instead 373 | gen_server:cast( % we use cast to send a message asynch. to 374 | ?SERVER, % the registered name. It is asynchronous 375 | stop). % because we do not expect a response. 376 | 377 | say_hello() -> % Pretty much the same as stop above except 378 | gen_server:cast( % that we send the atom say_hello instead. 379 | ?SERVER, % Again we do not expect a response but 380 | say_hello). % are only interested in the side effect. 381 | 382 | get_count() -> % Here, on the other hand, we do expect a 383 | gen_server:call( % response, which is why we use call to 384 | ?SERVER, % synchronously invoke our server. The call 385 | get_count). % blocks until we get the response. Note how 386 | % gen_server:call/2 hides the send/receive 387 | % logic from us. Nice. 388 | %% --------------------------------------------------------------------------- 389 | %% gen_server Function Definitions 390 | %% --------------------------------------------------------------------------- 391 | 392 | init([]) -> % these are the behaviour callbacks. init/1 is 393 | {ok, #state{count=0}}. % called in response to gen_server:start_link/4 394 | % and we are expected to initialize state. 395 | 396 | handle_call(get_count, _From, #state{count=Count}) -> 397 | {reply, 398 | Count, % here we synchronously respond with Count 399 | #state{count=Count+1} % and also update state 400 | }. 401 | 402 | handle_cast(stop, State) -> % this is the first handle_case clause that 403 | {stop, % deals with the stop atom. We instruct the 404 | normal, % gen_server to stop normally and return 405 | State % the current State unchanged. 406 | }; % Note: the semicolon here.... 407 | 408 | handle_cast(say_hello, State) -> % ... becuase the second clause is here to 409 | io:format("Hello~n"), % handle the say_hello atom by printing "Hello" 410 | {noreply, % again, this is asynch, so noreply and we also 411 | #state{count= 412 | State#state.count+1} 413 | }. % update our state here 414 | 415 | handle_info(Info, State) -> % handle_info deals with out-of-band msgs, ie 416 | error_logger:info_msg("~p~n", [Info]), % msgs that weren't sent via cast 417 | {noreply, State}. % or call. Here we simply log such messages. 418 | 419 | terminate(_Reason, _State) -> % terminate is invoked by the gen_server 420 | error_logger:info_msg("terminating~n"), % container on shutdown. 421 | ok. % we log it and acknowledge with ok. 422 | 423 | code_change(_OldVsn, State, _Extra) -> % called during release up/down- 424 | {ok, State}. % grade to update internal state. 425 | 426 | %% ------------------------------------------------------------------ 427 | %% Internal Function Definitions 428 | %% ------------------------------------------------------------------ 429 | 430 | % we don't have any. 431 | 432 | 433 | To compile our OTP server, change into the application directory (i.e. the one above _src_) and run ./rebar compile or, if you decided not to use _rebar_, run erlc -o ebin src/*.erl instead. _rebar_ automatically creates the _ebin_ directory, so if you use _erlc_, you need to create it manually first. 434 | 435 | Let's take our OTP server for a test ride. Here's my output: 436 | 437 | 438 | $> erl -pa ebin # start erl and -pa (path add) our ebin 439 | 1> hello_server:start_link(). % start our server. 440 | {ok,<0.34.0>} 441 | 2> hello_server:say_hello(). % try the say_hello/0 API function 442 | Hello 443 | ok 444 | 3> hello_server:get_count(). % observe how the server keeps track 445 | 1 446 | 4> hello_server:get_count(). % of state 447 | 2 448 | 5> hello_server ! stop. % let's send an out-of-band message 449 | 450 | =INFO REPORT=== % here's the output from error_logger 451 | stop 452 | stop 453 | 6> hello_server:stop(). % now let's call our stop/0 API function 454 | 455 | =INFO REPORT=== % this is the output from terminate 456 | terminating 457 | ok 458 | 7> whereis(hello_server). % and as we can see the process no longer 459 | undefined % exists. 460 | 8> 461 | 462 | 463 | So, what have we gained by turning our non-OTP version into an OTP _gen_server_? 464 | 465 | * First of all, anyone familiar with _gen_server_ can quickly understand how our code is organized, what API we expose and where to look for implementation details. This is the power of patterns. 466 | * Three distinct messaging mechanisms: synchronous, asynchronous and out-of-band. 467 | 468 | But there's more. If, as the following session shows, we start the SASL application (System Application Support Libraries) and then force a crash, we get a valuable error report, something our non-OTP version does not benefit from. 469 | 470 | 471 | 1> application:start(sasl). % let's start SASL 472 | ok 473 | 2> 474 | =PROGRESS REPORT==== % I've deleted all startup messages 475 | application: sasl % except for the last one here 476 | started_at: nonode@nohost % for brevity. SASL is up. 477 | 478 | 2> hello_server:start_link(). % let's start our server 479 | {ok,<0.44.0>} 480 | 3> whereis(hello_server). % and check that it was registered 481 | <0.44.0> 482 | 4> gen_server:cast(hello_server, crash). % now let's crash it 483 | 484 | =INFO REPORT==== 17-Dec-2012::11:00:56 === % excellent, gen_server called terminate 485 | terminating % so we could clean up, close sockets, etc. 486 | 487 | =ERROR REPORT==== 17-Dec-2012::11:00:56 === % what follows is a SASL report that we 488 | ** Generic server hello_server terminating % for free, simply by using OTP. 489 | ** Last message in was {'$gen_cast',crash} 490 | ** When Server state == {state,0} 491 | ** Reason for termination == % v--- aha - here's what went wrong 492 | ** {function_clause,[{hello_server,handle_cast,[crash,{state,0}]}, 493 | {gen_server,handle_msg,5}, 494 | {proc_lib,init_p_do_apply,3}]} 495 | 496 | =CRASH REPORT==== 17-Dec-2012::11:00:56 === % and here's even more info on the environent 497 | crasher: 498 | initial call: hello_server:init/1 499 | pid: <0.44.0> 500 | registered_name: hello_server 501 | exception exit: {function_clause, 502 | [{hello_server,handle_cast,[crash,{state,0}]}, 503 | {gen_server,handle_msg,5}, 504 | {proc_lib,init_p_do_apply,3}]} 505 | in function gen_server:terminate/6 506 | ancestors: [<0.32.0>] 507 | messages: [] 508 | links: [<0.32.0>] 509 | dictionary: [] 510 | trap_exit: false 511 | status: running 512 | heap_size: 377 513 | stack_size: 24 514 | reductions: 142 515 | neighbours: 516 | neighbour: [{pid,<0.32.0>}, 517 | {registered_name,[]}, 518 | {initial_call,{erlang,apply,2}}, 519 | {current_function,{io,wait_io_mon_reply,2}}, 520 | {ancestors,[]}, 521 | {messages,[]}, 522 | {links,[<0.26.0>,<0.44.0>]}, 523 | {dictionary,[]}, 524 | {trap_exit,false}, 525 | {status,waiting}, 526 | {heap_size,2584}, 527 | {stack_size,30}, 528 | {reductions,6595}] 529 | ** exception exit: function_clause 530 | in function hello_server:handle_cast/2 531 | called as hello_server:handle_cast(crash,{state,0}) 532 | in call from gen_server:handle_msg/5 533 | in call from proc_lib:init_p_do_apply/3 534 | 5> whereis(hello_server). % our process crashed, but at least the 535 | undefined % report above gives us an idea why. 536 | 537 | 538 | ## OTP supervisor 539 | 540 | Here's the code that _rebar_ generated for us. It is a supervisor template and not yet customized. 541 | 542 | 543 | -module(hello_sup). 544 | 545 | -behaviour(supervisor). 546 | 547 | %% API 548 | -export([start_link/0]). 549 | 550 | %% Supervisor callbacks 551 | -export([init/1]). 552 | 553 | %% Helper macro for declaring children of supervisor 554 | -define(CHILD(I, Type), {I, {I, start_link, []}, permanent, 5000, Type, [I]}). 555 | 556 | %% =================================================================== 557 | %% API functions 558 | %% =================================================================== 559 | 560 | start_link() -> 561 | supervisor:start_link({local, ?MODULE}, ?MODULE, []). 562 | 563 | %% =================================================================== 564 | %% Supervisor callbacks 565 | %% =================================================================== 566 | 567 | init([]) -> 568 | {ok, { {one_for_one, 5, 10}, []} }. 569 | 570 | 571 | Wow, that's short! Wow, what on earth does it mean? We're going to dissect it in a moment and then fill in the gap to make this template work with our _gen_server_, but even if we don't understand the details yet there's a lot we understand already. 572 | 573 | * This module implements the OTP _supervisor_ behaviour 574 | * It has one API function start_link/0 and one behaviour callback function init/1. 575 | * There is only one single function call in this entire listing (supervisor:start_link/3) 576 | * init/1, where we expect the magic to happen, only returns a tuple. 577 | 578 | Well, init/1 **is** where the magic happens. But in contrast to our non-OTP supervisor, where we had to code the logic to monitor and restart our sever, we are using a purely declarative, albeit still cryptic approach, in form of the tuple, to configure the supervisor container. 579 | 580 | What's going on with that -define(CHILD(I, Type), ...)? It is a macro, just like the familar -define(SERVER, ?MODULE). macro, except that this one takes two arguments. You use this macro by prefixing it with ? and by providing values for _I_ and _Type_. So, for example, ?CHILD(hello_server, worker) would be expanded to {hello_server, {hello_server, start_link, []}, permanent, 5000, worker, [hello_server]} at compile time. But the macro isn't used anywhere in our code yet. Where are we supposed to use it? 581 | 582 | Let's take a look at the _supervisor_ template _emacs_ generates for us. We are only interested in the init/1 function, which is why I omitted the rest. But try to use _emacs_ to generate a supervisor template yourself. To discover what goodness I'm hiding hit: F10, e, S, 0, where e stands for Erlang, S for Skeletons and 0 selects the supervisor template. Here's what I got: 583 | 584 | 585 | init([]) -> 586 | RestartStrategy = one_for_one, 587 | MaxRestarts = 1000, 588 | MaxSecondsBetweenRestarts = 3600, 589 | 590 | SupFlags = {RestartStrategy, MaxRestarts, MaxSecondsBetweenRestarts}, 591 | 592 | Restart = permanent, 593 | Shutdown = 2000, 594 | Type = worker, 595 | 596 | AChild = {'AName', {'AModule', start_link, []}, 597 | Restart, Shutdown, Type, ['AModule']}, 598 | 599 | {ok, {SupFlags, [AChild]}}. 600 | 601 | 602 | This is probably easier to understand, than what _rebar_ generated for us. Although it should, of course, at least stucturally, boil down to the same configuration tuple. Let's substitute both atoms 'AName' and 'AModule' with hello_server and resolve the last tuple fully. I am going to insert some line breaks and comments to make it easier to see what goes where. 603 | 604 | 605 | {ok, % ok, supervisor here's what we want you to do 606 | { 607 | { % Global supervisor options 608 | one_for_one, % - use the one-for-one restart strategy 609 | 1000, % - and allow a maximum of 1000 restarts 610 | 3600 % - per hour for each child process 611 | }, 612 | [ % The list of child processes you should supervise 613 | { % We only have one 614 | hello_server, % - Register it under the name hello_server 615 | { % - Here's how to find and start this child's code 616 | hello_server, % * the module is called hello_server 617 | start_link, % * the function to invoke is called start_link 618 | [] % * and here's the list of default parameters to use 619 | }, 620 | permanent, % - child should run permantenly, restart on crash 621 | 2000, % - give child 2 sec to clean up on system stop, then kill 622 | worker % - FYI, this child is a worker, not a supervisor 623 | [hello_server] % - these are the modules the process uses 624 | } 625 | ] 626 | } 627 | }. 628 | 629 | 630 | I leave it up to you to decide on the format you prefer. You can use _rebar_'s compact notation, _emac_'s verbose template or even the resolved snippet above in your supervisor's init/1. As an exercise, please implement your supervisor now and compile it. However, before we test it, let's look at the parameters we used in the snippet above. 631 | 632 | * **one_for_one**: This restart strategy instructs the supervisor to restart the crashed child process only. In our case there is only one, but if there were more supervised child processes, they would not be affected. In contrast, a restart strategy of _one_for_all_ automatically restarts all children if one crashes. For autonomous child processes use _one_for_one_. If, on the other hand, child processes form a tightly coupled subsystem it may be better to restart the entire subsystem with _one_for_all_. Consult man 3erl supervisor or this [page][3] for additional information. In particular, look at the _simple_one_for_one_ strategy which allows you to use a supervisor as a process factory. 633 | * **permanent**: This tells the supervisor that the child should always be restarted (subject to the global restart rules). Other Restart values are _temporary_ and _transient_ . _temporary_ processes are never restarted but _transient_ child processes are if they terminate abnormally (i.e. they crashed). For our use-case _permanent_ makes sense, but in the case of a process factory, _transient_ or _temporary_ may be more applicable. 634 | * **worker**: Here we want to supervise a _gen_server_ \- a worker - but it is common to build supervisor hierarchies. Setting this value to _supervisor_ instead informs the supervisor that the child is also a supervisor. This is to help it manage child processes optimally. 635 | 636 | Let's try our OTP supervisor. 637 | 638 | 639 | 1> hello_sup:start_link(). % let's start our root supervisor 640 | {ok,<0.34.0>} 641 | 2> whereis(hello_server). % and ensure that it started out child process 642 | <0.35.0> 643 | 3> hello_server:say_hello(). % now let's call the child API 644 | Hello 645 | ok 646 | 4> hello_server:get_count(). % and verify that all works as before 647 | 1 648 | 5> gen_server:cast(hello_server, crash). % time to crash the worker process 649 | 650 | =INFO REPORT==== % good, terminate is still being called 651 | terminating 652 | 653 | =ERROR REPORT==== 17-Dec-2012::13:55:51 === 654 | ** Generic server hello_server terminating 655 | ** Last message in was {'$gen_cast',crash} 656 | ** When Server state == {state,2} 657 | ** Reason for termination == % and --v-- here we see why it crashed 658 | ** {function_clause,[{hello_server,handle_cast,[crash,{state,2}]}, 659 | {gen_server,handle_msg,5}, 660 | {proc_lib,init_p_do_apply,3}]} 661 | ok 662 | 6> whereis(hello_server). % but look, a new process was already started 663 | <0.40.0> 664 | 7> hello_server:get_count(). % obviously, with a new state 665 | 0 666 | 8> hello_server:stop(). % let's call our API stop function 667 | 668 | =INFO REPORT=== 669 | terminating % looking good 670 | ok 671 | 9> whereis(hello_server). % but our supervisor started another server. 672 | <0.44.0> 673 | 10> 674 | 675 | 676 | It works as designed, although, perhaps, not as expected. The call to stop_server/0 stops our process, but the supervisor immediately starts a new instance. We could change the Restart parameter in our supervisor's Child specification to _transient_, but then we are left with a childless supervisor. I don't think this is a problem though, but rather the result of our somewhat arbitrary "Hello" scenario. Let's turn our attention therefore to **OTP applications** to learn how to start and stop applications as a whole. 677 | 678 | ## OTP application 679 | 680 | We have already seen an example of an application in this post: SASL, which we launched with application:start(sasl). Now it is time to find out how we can bundle our root supervisor and our server in an application so that we can start it in the same manner. 681 | 682 | Unlike our _gen_server_ and _supervisor_ implementation, the OTP _application_ behaviour requires two files. A configuration file, conventially named, _appname.app_ and an Erlang source file called _appname_app.erl_. In our case these are: 683 | 684 | * _ebin/hello.app_ 685 | * _src/hello_app.erl_ 686 | 687 | Note that the _hello.app_ file is placed into the _ebin_ directory. This makes sense. The _.app_ file tells Erlang how to launch our application. Since we might only ship our app's compiled _.beam_ files, not its source, this is where the _.app_ file naturally belongs. 688 | 689 | As a _rebar_ users you will notice that there exists also a _src/hello.app.src_ file, as mentioned earlier. This file serves as a template for your _ebin/hello.app_ file when you run ./rebar compile. 690 | 691 | Here is my _.erl_ and _.app_ file as generated by _rebar_. 692 | 693 | 694 | -module(hello_app). 695 | 696 | -behaviour(application). 697 | 698 | %% Application callbacks 699 | -export([start/2, stop/1]). 700 | 701 | %% =================================================================== 702 | %% Application callbacks 703 | %% =================================================================== 704 | 705 | start(_StartType, _StartArgs) -> 706 | hello_sup:start_link(). 707 | 708 | stop(_State) -> 709 | ok. 710 | 711 | 712 | This is the _hello_app.erl_ file that implements the OTP _application_ behaviour. Need I say more? 713 | 714 | 715 | {application,hello, 716 | [{description,[]}, 717 | {vsn,"1"}, 718 | {registered,[]}, 719 | {applications,[kernel,stdlib]}, 720 | {mod,{hello_app,[]}}, 721 | {env,[]}, 722 | {modules,[hello_app,hello_server,hello_sup]}]}. 723 | 724 | 725 | This is the configuration file that tells Erlang how to start our application. It's just a tuple. The first element is the atom _application_, the second the application name and the thrid a list of key-value tuples. If you are not using _rebar_ don't forget the fullstop at the end. Let's briefly look at the key-value pairs. 726 | 727 | * **description**: We should change this to "The hello OTP tutorial app" 728 | * **vsn**: Our applications version. It's common to use x.y.z, but for now, _rebar_'s default is fine. 729 | * **registered**: Is a list of names our app registeres itself under. This is typically only the root supervisors name. In our case we should add hello.sup here, but it's not required. 730 | * **applications**: Lists the applications our app depends on. Every app requires _kernel_ and _sdlib_ to be up and running. Try to add sasl if you like and see what happens when you try to start your application. 731 | * **mod**: Tells Erlang which module contains our application behaviour. 732 | * **env**: Is a list of enviromental variables you may wish to pass to your application. 733 | * **modules**: Is the list of modules our application consists of. 734 | 735 | It is time to start our application from the Erlang shell. 736 | 737 | 738 | 1> application:start(hello). 739 | ok 740 | 2> whereis(hello_sup). 741 | <0.37.0> 742 | 3> whereis(hello_server). 743 | <0.38.0> 744 | 4> hello_server:say_hello(). 745 | Hello 746 | ok 747 | 5> application:stop(hello). 748 | 749 | =INFO REPORT==== 17-Dec-2012::15:37:47 === 750 | application: hello 751 | exited: stopped 752 | type: temporary 753 | ok 754 | 6> whereis(hello_sup). 755 | undefined 756 | 7> whereis(hello_server). 757 | undefined 758 | 759 | 760 | Great, now we can start and stop our application simply by name. But there's more. Do you remember how SASL's extended reporting became automatically available when we turned our non-OTP server into a _gen_server_? Try to run the shell session above another time, but first start the Application Monitor using appmon:start(), then, once you've started the 'hello' app, click on the hello button to display the process hierarchy. Pretty nifty, don't you think? 761 | --------------------------------------------------------------------------------