1supervisor(3) Erlang Module Definition supervisor(3)
2
3
4
6 supervisor - Generic supervisor behavior.
7
9 This behavior module provides a supervisor, a process that supervises
10 other processes called child processes. A child process can either be
11 another supervisor or a worker process. Worker processes are normally
12 implemented using one of the gen_event, gen_server, or gen_statem be‐
13 haviors. A supervisor implemented using this module has a standard set
14 of interface functions and include functionality for tracing and error
15 reporting. Supervisors are used to build a hierarchical process struc‐
16 ture called a supervision tree, a nice way to structure a fault-toler‐
17 ant application. For more information, see Supervisor Behaviour in OTP
18 Design Principles.
19
20 A supervisor expects the definition of which child processes to super‐
21 vise to be specified in a callback module exporting a predefined set of
22 functions.
23
24 Unless otherwise stated, all functions in this module fail if the spec‐
25 ified supervisor does not exist or if bad arguments are specified.
26
28 The supervisor is responsible for starting, stopping, and monitoring
29 its child processes. The basic idea of a supervisor is that it must
30 keep its child processes alive by restarting them when necessary.
31
32 The children of a supervisor are defined as a list of child specifica‐
33 tions. When the supervisor is started, the child processes are started
34 in order from left to right according to this list. When the supervisor
35 terminates, it first terminates its child processes in reversed start
36 order, from right to left.
37
38 Supervisor flags
39 The supervisor properties are defined by the supervisor flags. The type
40 definition for the supervisor flags is as follows:
41
42 sup_flags() = #{strategy => strategy(), % optional
43 intensity => non_neg_integer(), % optional
44 period => pos_integer(), % optional
45 auto_shutdown => auto_shutdown()} % optional
46
47 Restart Strategies
48 A supervisor can have one of the following restart strategies specified
49 with the strategy key in the above map:
50
51 * one_for_one - If one child process terminates and is to be
52 restarted, only that child process is affected. This is the default
53 restart strategy.
54
55 * one_for_all - If one child process terminates and is to be
56 restarted, all other child processes are terminated and then all
57 child processes are restarted.
58
59 * rest_for_one - If one child process terminates and is to be
60 restarted, the 'rest' of the child processes (that is, the child
61 processes after the terminated child process in the start order)
62 are terminated. Then the terminated child process and all child
63 processes after it are restarted.
64
65 * simple_one_for_one - A simplified one_for_one supervisor, where all
66 child processes are dynamically added instances of the same process
67 type, that is, running the same code.
68
69 Functions delete_child/2 and restart_child/2 are invalid for sim‐
70 ple_one_for_one supervisors and return {error,simple_one_for_one}
71 if the specified supervisor uses this restart strategy.
72
73 Function terminate_child/2 can be used for children under sim‐
74 ple_one_for_one supervisors by specifying the child's pid() as the
75 second argument. If instead the child specification identifier is
76 used, terminate_child/2 return {error,simple_one_for_one}.
77
78 As a simple_one_for_one supervisor can have many children, it shuts
79 them all down asynchronously. This means that the children do their
80 cleanup in parallel, and therefore the order in which they are
81 stopped is not defined.
82
83 Restart intensity and period
84 To prevent a supervisor from getting into an infinite loop of child
85 process terminations and restarts, a maximum restart intensity is de‐
86 fined using two integer values specified with keys intensity and period
87 in the above map. Assuming the values MaxR for intensity and MaxT for
88 period, then, if more than MaxR restarts occur within MaxT seconds, the
89 supervisor terminates all child processes and then itself. The termina‐
90 tion reason for the supervisor itself in that case will be shutdown.
91 intensity defaults to 1 and period defaults to 5.
92
93 Automatic Shutdown
94 A supervisor can be configured to automatically shut itself down with
95 exit reason shutdown when significant children terminate with the
96 auto_shutdown key in the above map:
97
98 * never - Automic shutdown is disabled. This is the default setting.
99
100 With auto_shutdown set to never, child specs with the significant
101 flag set to true are considered invalid and will be rejected.
102
103 * any_significant - The supervisor will shut itself down when any
104 significant child terminates, that is, when a transient significant
105 child terminates normally or when a temporary significant child
106 terminates normally or abnormally.
107
108 * all_significant - The supervisor will shut itself down when all
109 significant children have terminated, that is, when the last active
110 significant child terminates. The same rules as for any_significant
111 apply.
112
113 For more information, see the section Automatic Shutdown in Supervisor
114 Behavior in OTP Design Principles.
115
116 Warning:
117 The automatic shutdown feature appeared in OTP 24.0, but applications
118 using this feature will also compile and run with older OTP versions.
119
120 However, such applications, when compiled with an OTP version that pre‐
121 dates the appearance of the automatic shutdown feature, will leak pro‐
122 cesses because the automatic shutdowns they rely on will not happen.
123
124 It is up to implementors to take proper precautions if they expect that
125 their applications may be compiled with older OTP versions.
126
127
128 Child specification
129 The type definition of a child specification is as follows:
130
131 child_spec() = #{id => child_id(), % mandatory
132 start => mfargs(), % mandatory
133 restart => restart(), % optional
134 significant => significant(), % optional
135 shutdown => shutdown(), % optional
136 type => worker(), % optional
137 modules => modules()} % optional
138
139 The old tuple format is kept for backwards compatibility, see
140 child_spec(), but the map is preferred.
141
142 * id is used to identify the child specification internally by the
143 supervisor.
144
145 The id key is mandatory.
146
147 Notice that this identifier on occations has been called "name". As
148 far as possible, the terms "identifier" or "id" are now used but to
149 keep backward compatibility, some occurences of "name" can still be
150 found, for example in error messages.
151
152 * start defines the function call used to start the child process. It
153 must be a module-function-arguments tuple {M,F,A} used as ap‐
154 ply(M,F,A).
155
156 The start function must create and link to the child process, and
157 must return {ok,Child} or {ok,Child,Info}, where Child is the pid
158 of the child process and Info any term that is ignored by the su‐
159 pervisor.
160
161 The start function can also return ignore if the child process for
162 some reason cannot be started, in which case the child specifica‐
163 tion is kept by the supervisor (unless it is a temporary child) but
164 the non-existing child process is ignored.
165
166 If something goes wrong, the function can also return an error tu‐
167 ple {error,Error}.
168
169 Notice that the start_link functions of the different behavior mod‐
170 ules fulfill the above requirements.
171
172 The start key is mandatory.
173
174 *
175
176
177 restart defines when a terminated child process must be restarted.
178 A permanent child process is always restarted. A temporary child
179 process is never restarted (even when the supervisor's restart
180 strategy is rest_for_one or one_for_all and a sibling's death
181 causes the temporary process to be terminated). A transient child
182 process is restarted only if it terminates abnormally, that is,
183 with another exit reason than normal, shutdown, or {shutdown,Term}.
184
185 The restart key is optional. If it is not specified, it defaults to
186 permanent.
187
188 *
189
190
191 significant defines if a child is considered significant for auto‐
192 matic self-shutdown of the supervisor.
193
194 Setting this option to true when the restart type is permanent is
195 invalid. Also, it is considered invalid to start children with this
196 option set to true in a supervisor when the auto_shutdown supervi‐
197 sor flag is set to never.
198
199 The significant key is optional. If it is not specified, it de‐
200 faults to false.
201
202 * shutdown defines how a child process must be terminated. bru‐
203 tal_kill means that the child process is unconditionally terminated
204 using exit(Child,kill). An integer time-out value means that the
205 supervisor tells the child process to terminate by calling
206 exit(Child,shutdown) and then wait for an exit signal with reason
207 shutdown back from the child process. If no exit signal is received
208 within the specified number of milliseconds, the child process is
209 unconditionally terminated using exit(Child,kill).
210
211 If the child process is another supervisor, the shutdown time must
212 be set to infinity to give the subtree ample time to shut down.
213
214 Warning:
215 Setting the shutdown time to anything other than infinity for a child
216 of type supervisor can cause a race condition where the child in
217 question unlinks its own children, but fails to terminate them before
218 it is killed.
219
220
221 It is also allowed to set it to infinity, if the child process is a
222 worker.
223
224 Warning:
225 Be careful when setting the shutdown time to infinity when the child
226 process is a worker. Because, in this situation, the termination of
227 the supervision tree depends on the child process, it must be imple‐
228 mented in a safe way and its cleanup procedure must always return.
229
230
231 Notice that all child processes implemented using the standard OTP
232 behavior modules automatically adhere to the shutdown protocol.
233
234 The shutdown key is optional. If it is not specified, it defaults
235 to 5000 if the child is of type worker and it defaults to infinity
236 if the child is of type supervisor.
237
238 * type specifies if the child process is a supervisor or a worker.
239
240 The type key is optional. If it is not specified, it defaults to
241 worker.
242
243 * modules is used by the release handler during code replacement to
244 determine which processes are using a certain module. As a rule of
245 thumb, if the child process is a supervisor, gen_server or,
246 gen_statem, this is to be a list with one element [Module], where
247 Module is the callback module. If the child process is an event
248 manager (gen_event) with a dynamic set of callback modules, value
249 dynamic must be used. For more information about release handling,
250 see Release Handling in OTP Design Principles.
251
252 The modules key is optional. If it is not specified, it defaults to
253 [M], where M comes from the child's start {M,F,A}.
254
255 * Internally, the supervisor also keeps track of the pid Child of the
256 child process, or undefined if no pid exists.
257
259 auto_shutdown() = never | any_significant | all_significant
260
261 child() = undefined | pid()
262
263 child_id() = term()
264
265 Not a pid().
266
267 child_spec() =
268 #{id := child_id(),
269 start := mfargs(),
270 restart => restart(),
271 significant => significant(),
272 shutdown => shutdown(),
273 type => worker(),
274 modules => modules()} |
275 {Id :: child_id(),
276 StartFunc :: mfargs(),
277 Restart :: restart(),
278 Shutdown :: shutdown(),
279 Type :: worker(),
280 Modules :: modules()}
281
282 The tuple format is kept for backward compatibility only. A map
283 is preferred; see more details above.
284
285 mfargs() =
286 {M :: module(), F :: atom(), A :: [term()] | undefined}
287
288 Value undefined for A (the argument list) is only to be used in‐
289 ternally in supervisor. If the restart type of the child is tem‐
290 porary, the process is never to be restarted and therefore there
291 is no need to store the real argument list. Value undefined is
292 then stored instead.
293
294 modules() = [module()] | dynamic
295
296 restart() = permanent | transient | temporary
297
298 shutdown() = brutal_kill | timeout()
299
300 significant() = boolean()
301
302 startchild_err() =
303 already_present | {already_started, Child :: child()} | term()
304
305 startchild_ret() =
306 {ok, Child :: child()} |
307 {ok, Child :: child(), Info :: term()} |
308 {error, startchild_err()}
309
310 startlink_err() =
311 {already_started, pid()} | {shutdown, term()} | term()
312
313 startlink_ret() =
314 {ok, pid()} | ignore | {error, startlink_err()}
315
316 strategy() =
317 one_for_all | one_for_one | rest_for_one | simple_one_for_one
318
319 sup_flags() =
320 #{strategy => strategy(),
321 intensity => integer() >= 0,
322 period => integer() >= 1,
323 auto_shutdown => auto_shutdown()} |
324 {RestartStrategy :: strategy(),
325 Intensity :: integer() >= 0,
326 Period :: integer() >= 1}
327
328 The tuple format is kept for backward compatibility only. A map
329 is preferred; see more details above.
330
331 sup_ref() =
332 (Name :: atom()) |
333 {Name :: atom(), Node :: node()} |
334 {global, Name :: term()} |
335 {via, Module :: module(), Name :: any()} |
336 pid()
337
338 worker() = worker | supervisor
339
341 check_childspecs(ChildSpecs) -> Result
342
343 check_childspecs(ChildSpecs, AutoShutdown) -> Result
344
345 Types:
346
347 ChildSpecs = [child_spec()]
348 AutoShutdown = undefined | auto_shutdown()
349 Result = ok | {error, Error :: term()}
350
351 Takes a list of child specification as argument and returns ok
352 if all of them are syntactically correct, otherwise {error,Er‐
353 ror}.
354
355 If the optional AutoShutdown argument is given and not unde‐
356 fined, also checks if the child specifications are allowed for
357 the given auto_shutdown option.
358
359 count_children(SupRef) -> PropListOfCounts
360
361 Types:
362
363 SupRef = sup_ref()
364 PropListOfCounts = [Count]
365 Count =
366 {specs, ChildSpecCount :: integer() >= 0} |
367 {active, ActiveProcessCount :: integer() >= 0} |
368 {supervisors, ChildSupervisorCount :: integer() >= 0} |
369 {workers, ChildWorkerCount :: integer() >= 0}
370
371 Returns a property list (see proplists) containing the counts
372 for each of the following elements of the supervisor's child
373 specifications and managed processes:
374
375 * specs - The total count of children, dead or alive.
376
377 * active - The count of all actively running child processes
378 managed by this supervisor. For a simple_one_for_one super‐
379 visors, no check is done to ensure that each child process
380 is still alive, although the result provided here is likely
381 to be very accurate unless the supervisor is heavily over‐
382 loaded.
383
384 * supervisors - The count of all children marked as child_type
385 = supervisor in the specification list, regardless if the
386 child process is still alive.
387
388 * workers - The count of all children marked as child_type =
389 worker in the specification list, regardless if the child
390 process is still alive.
391
392 For a description of SupRef, see start_child/2.
393
394 delete_child(SupRef, Id) -> Result
395
396 Types:
397
398 SupRef = sup_ref()
399 Id = child_id()
400 Result = ok | {error, Error}
401 Error = running | restarting | not_found | simple_one_for_one
402
403 Tells supervisor SupRef to delete the child specification iden‐
404 tified by Id. The corresponding child process must not be run‐
405 ning. Use terminate_child/2 to terminate it.
406
407 For a description of SupRef, see start_child/2.
408
409 If successful, the function returns ok. If the child specifica‐
410 tion identified by Id exists but the corresponding child process
411 is running or is about to be restarted, the function returns
412 {error,running} or {error,restarting}, respectively. If the
413 child specification identified by Id does not exist, the func‐
414 tion returns {error,not_found}.
415
416 get_childspec(SupRef, Id) -> Result
417
418 Types:
419
420 SupRef = sup_ref()
421 Id = pid() | child_id()
422 Result = {ok, child_spec()} | {error, Error}
423 Error = not_found
424
425 Returns the child specification map for the child identified by
426 Id under supervisor SupRef. The returned map contains all keys,
427 both mandatory and optional.
428
429 For a description of SupRef, see start_child/2.
430
431 restart_child(SupRef, Id) -> Result
432
433 Types:
434
435 SupRef = sup_ref()
436 Id = child_id()
437 Result =
438 {ok, Child :: child()} |
439 {ok, Child :: child(), Info :: term()} |
440 {error, Error}
441 Error =
442 running | restarting | not_found | simple_one_for_one |
443 term()
444
445 Tells supervisor SupRef to restart a child process corresponding
446 to the child specification identified by Id. The child specifi‐
447 cation must exist, and the corresponding child process must not
448 be running.
449
450 Notice that for temporary children, the child specification is
451 automatically deleted when the child terminates; thus, it is not
452 possible to restart such children.
453
454 For a description of SupRef, see start_child/2.
455
456 If the child specification identified by Id does not exist, the
457 function returns {error,not_found}. If the child specification
458 exists but the corresponding process is already running, the
459 function returns {error,running}.
460
461 If the child process start function returns {ok,Child} or
462 {ok,Child,Info}, the pid is added to the supervisor and the
463 function returns the same value.
464
465 If the child process start function returns ignore, the pid re‐
466 mains set to undefined and the function returns {ok,undefined}.
467
468 If the child process start function returns an error tuple or an
469 erroneous value, or if it fails, the function returns {error,Er‐
470 ror}, where Error is a term containing information about the er‐
471 ror.
472
473 start_child(SupRef, ChildSpec) -> startchild_ret()
474
475 Types:
476
477 SupRef = sup_ref()
478 ChildSpec = child_spec() | (List :: [term()])
479 startchild_ret() =
480 {ok, Child :: child()} |
481 {ok, Child :: child(), Info :: term()} |
482 {error, startchild_err()}
483 startchild_err() =
484 already_present | {already_started, Child :: child()} | term()
485
486 Dynamically adds a child specification to supervisor SupRef,
487 which starts the corresponding child process.
488
489 SupRef can be any of the following:
490
491 * The pid
492
493 * Name, if the supervisor is locally registered
494
495 * {Name,Node}, if the supervisor is locally registered at an‐
496 other node
497
498 * {global,Name}, if the supervisor is globally registered
499
500 * {via,Module,Name}, if the supervisor is registered through
501 an alternative process registry
502
503 ChildSpec must be a valid child specification (unless the super‐
504 visor is a simple_one_for_one supervisor; see below). The child
505 process is started by using the start function as defined in the
506 child specification.
507
508 For a simple_one_for_one supervisor, the child specification de‐
509 fined in Module:init/1 is used, and ChildSpec must instead be an
510 arbitrary list of terms List. The child process is then started
511 by appending List to the existing start function arguments, that
512 is, by calling apply(M, F, A++List), where {M,F,A} is the start
513 function defined in the child specification.
514
515 * If there already exists a child specification with the spec‐
516 ified identifier, ChildSpec is discarded, and the function
517 returns {error,already_present} or {error,{al‐
518 ready_started,Child}}, depending on if the corresponding
519 child process is running or not.
520
521 * If the child process start function returns {ok,Child} or
522 {ok,Child,Info}, the child specification and pid are added
523 to the supervisor and the function returns the same value.
524
525 * If the child process start function returns ignore, the
526 child specification is added to the supervisor (unless the
527 supervisor is a simple_one_for_one supervisor, see below),
528 the pid is set to undefined, and the function returns
529 {ok,undefined}.
530
531 For a simple_one_for_one supervisor, when a child process start
532 function returns ignore, the functions returns {ok,undefined}
533 and no child is added to the supervisor.
534
535 If the child process start function returns an error tuple or an
536 erroneous value, or if it fails, the child specification is dis‐
537 carded, and the function returns {error,Error}, where Error is a
538 term containing information about the error and child specifica‐
539 tion.
540
541 start_link(Module, Args) -> startlink_ret()
542
543 start_link(SupName, Module, Args) -> startlink_ret()
544
545 Types:
546
547 SupName = sup_name()
548 Module = module()
549 Args = term()
550 startlink_ret() =
551 {ok, pid()} | ignore | {error, startlink_err()}
552 startlink_err() =
553 {already_started, pid()} | {shutdown, term()} | term()
554 sup_name() =
555 {local, Name :: atom()} |
556 {global, Name :: term()} |
557 {via, Module :: module(), Name :: any()}
558
559 Creates a supervisor process as part of a supervision tree. For
560 example, the function ensures that the supervisor is linked to
561 the calling process (its supervisor).
562
563 The created supervisor process calls Module:init/1 to find out
564 about restart strategy, maximum restart intensity, and child
565 processes. To ensure a synchronized startup procedure,
566 start_link/2,3 does not return until Module:init/1 has returned
567 and all child processes have been started.
568
569 * If SupName={local,Name}, the supervisor is registered lo‐
570 cally as Name using register/2.
571
572 * If SupName={global,Name}, the supervisor is registered glob‐
573 ally as Name using global:register_name/2.
574
575 * If SupName={via,Module,Name}, the supervisor is registered
576 as Name using the registry represented by Module. The Module
577 callback must export the functions register_name/2, unregis‐
578 ter_name/1, and send/2, which must behave like the corre‐
579 sponding functions in global. Thus, {via,global,Name} is a
580 valid reference.
581
582 If no name is provided, the supervisor is not registered.
583
584 Module is the name of the callback module.
585
586 Args is any term that is passed as the argument to Mod‐
587 ule:init/1.
588
589 * If the supervisor and its child processes are successfully
590 created (that is, if all child process start functions re‐
591 turn {ok,Child}, {ok,Child,Info}, or ignore), the function
592 returns {ok,Pid}, where Pid is the pid of the supervisor.
593
594 * If there already exists a process with the specified Sup‐
595 Name, the function returns {error,{already_started,Pid}},
596 where Pid is the pid of that process.
597
598 * If Module:init/1 returns ignore, this function returns ig‐
599 nore as well, and the supervisor terminates with reason nor‐
600 mal.
601
602 * If Module:init/1 fails or returns an incorrect value, this
603 function returns {error,Term}, where Term is a term with in‐
604 formation about the error, and the supervisor terminates
605 with reason Term.
606
607 * If any child process start function fails or returns an er‐
608 ror tuple or an erroneous value, the supervisor first termi‐
609 nates all already started child processes with reason shut‐
610 down and then terminate itself and returns {error, {shut‐
611 down, Reason}}.
612
613 terminate_child(SupRef, Id) -> Result
614
615 Types:
616
617 SupRef = sup_ref()
618 Id = pid() | child_id()
619 Result = ok | {error, Error}
620 Error = not_found | simple_one_for_one
621
622 Tells supervisor SupRef to terminate the specified child.
623
624 If the supervisor is not simple_one_for_one, Id must be the
625 child specification identifier. The process, if any, is termi‐
626 nated and, unless it is a temporary child, the child specifica‐
627 tion is kept by the supervisor. The child process can later be
628 restarted by the supervisor. The child process can also be
629 restarted explicitly by calling restart_child/2. Use
630 delete_child/2 to remove the child specification.
631
632 If the child is temporary, the child specification is deleted as
633 soon as the process terminates. This means that delete_child/2
634 has no meaning and restart_child/2 cannot be used for these
635 children.
636
637 If the supervisor is simple_one_for_one, Id must be the pid() of
638 the child process. If the specified process is alive, but is not
639 a child of the specified supervisor, the function returns {er‐
640 ror,not_found}. If the child specification identifier is speci‐
641 fied instead of a pid(), the function returns {error,sim‐
642 ple_one_for_one}.
643
644 If successful, the function returns ok. If there is no child
645 specification with the specified Id, the function returns {er‐
646 ror,not_found}.
647
648 For a description of SupRef, see start_child/2.
649
650 which_children(SupRef) -> [{Id, Child, Type, Modules}]
651
652 Types:
653
654 SupRef = sup_ref()
655 Id = child_id() | undefined
656 Child = child() | restarting
657 Type = worker()
658 Modules = modules()
659
660 Returns a newly created list with information about all child
661 specifications and child processes belonging to supervisor
662 SupRef.
663
664 Notice that calling this function when supervising many children
665 under low memory conditions can cause an out of memory excep‐
666 tion.
667
668 For a description of SupRef, see start_child/2.
669
670 The following information is given for each child specifica‐
671 tion/process:
672
673 * Id - As defined in the child specification or undefined for
674 a simple_one_for_one supervisor.
675
676 * Child - The pid of the corresponding child process, the atom
677 restarting if the process is about to be restarted, or unde‐
678 fined if there is no such process.
679
680 * Type - As defined in the child specification.
681
682 * Modules - As defined in the child specification.
683
685 The following function must be exported from a supervisor callback mod‐
686 ule.
687
689 Module:init(Args) -> Result
690
691 Types:
692
693 Args = term()
694 Result = {ok,{SupFlags,[ChildSpec]}} | ignore
695 SupFlags = sup_flags()
696 ChildSpec = child_spec()
697
698 Whenever a supervisor is started using start_link/2,3, this
699 function is called by the new process to find out about restart
700 strategy, maximum restart intensity, and child specifications.
701
702 Args is the Args argument provided to the start function.
703
704 SupFlags is the supervisor flags defining the restart strategy
705 and maximum restart intensity for the supervisor. [ChildSpec] is
706 a list of valid child specifications defining which child pro‐
707 cesses the supervisor must start and monitor. See the discussion
708 in section Supervision Principles earlier.
709
710 Notice that when the restart strategy is simple_one_for_one, the
711 list of child specifications must be a list with one child spec‐
712 ification only. (The child specification identifier is ignored.)
713 No child process is then started during the initialization
714 phase, but all children are assumed to be started dynamically
715 using start_child/2.
716
717 The function can also return ignore.
718
719 Notice that this function can also be called as a part of a code
720 upgrade procedure. Therefore, the function is not to have any
721 side effects. For more information about code upgrade of super‐
722 visors, see section Changing a Supervisor in OTP Design Princi‐
723 ples.
724
726 gen_event(3), gen_statem(3), gen_server(3), sys(3)
727
728
729
730Ericsson AB stdlib 4.3.1.3 supervisor(3)