]> granicus.if.org Git - icinga2/blob - doc/13-language-reference.md
a252f3aef0c5c144331b806b13c55aec093f3e95
[icinga2] / doc / 13-language-reference.md
1 # <a id="language-reference"></a> Language Reference
2
3 ## <a id="object-definition"></a> Object Definition
4
5 Icinga 2 features an object-based configuration format. You can define new
6 objects using the `object` keyword:
7
8     object Host "host1.example.org" {
9       display_name = "host1"
10
11       address = "192.168.0.1"
12       address6 = "::1"
13     }
14
15 In general you need to write each statement on a new line. Expressions started
16 with `{`, `(` and `[` extend until the matching closing character and can be broken
17 up into multiple lines.
18
19 Alternatively you can write multiple statements on a single line by separating
20 them with a semicolon:
21
22     object Host "host1.example.org" {
23       display_name = "host1"
24
25       address = "192.168.0.1"; address6 = "::1"
26     }
27
28 Each object is uniquely identified by its type (`Host`) and name
29 (`host1.example.org`). Some types have composite names, e.g. the
30 `Service` type which uses the `host_name` attribute and the name
31 you specified to generate its object name.
32
33 Exclamation marks (!) are not permitted in object names.
34
35 Objects can contain a comma-separated list of property
36 declarations. Instead of commas semicolons may also be used.
37 The following data types are available for property values:
38
39 ## Expressions
40
41 The following expressions can be used on the right-hand side of assignments.
42
43 ### <a id="numeric-literals"></a> Numeric Literals
44
45 A floating-point number.
46
47 Example:
48
49     27.3
50
51 ### <a id="duration-literals"></a> Duration Literals
52
53 Similar to floating-point numbers except for the fact that they support
54 suffixes to help with specifying time durations.
55
56 Example:
57
58     2.5m
59
60 Supported suffixes include ms (milliseconds), s (seconds), m (minutes),
61 h (hours) and d (days).
62
63 Duration literals are converted to seconds by the config parser and
64 are treated like numeric literals.
65
66 ### <a id="string-literals"></a> String Literals
67
68 A string.
69
70 Example:
71
72     "Hello World!"
73
74 Certain characters need to be escaped. The following escape sequences
75 are supported:
76
77 Character                 | Escape sequence
78 --------------------------|------------------------------------
79 "                         | \\"
80 \\                        | \\\\
81 &lt;TAB&gt;               | \\t
82 &lt;CARRIAGE-RETURN&gt;   | \\r
83 &lt;LINE-FEED&gt;         | \\n
84 &lt;BEL&gt;               | \\b
85 &lt;FORM-FEED&gt;         | \\f
86
87 In addition to these pre-defined escape sequences you can specify
88 arbitrary ASCII characters using the backslash character (\\) followed
89 by an ASCII character in octal encoding.
90
91 ### <a id="multiline-string-literals"></a> Multi-line String Literals
92
93 Strings spanning multiple lines can be specified by enclosing them in
94 {{{ and }}}.
95
96 Example:
97
98     {{{This
99     is
100     a multi-line
101     string.}}}
102
103 Unlike in ordinary strings special characters do not have to be escaped
104 in multi-line string literals.
105
106 ### <a id="boolean-literals"></a> Boolean Literals
107
108 The keywords `true` and `false` are used to denote truth values.
109
110 ### <a id="null-value"></a> Null Value
111
112 The `null` keyword can be used to specify an empty value.
113
114 ### <a id="dictionary"></a> Dictionary
115
116 An unordered list of key-value pairs. Keys must be unique and are
117 compared in a case-sensitive manner.
118
119 Individual key-value pairs must either be comma-separated or on separate lines.
120 The comma after the last key-value pair is optional.
121
122 Example:
123
124     {
125       address = "192.168.0.1"
126       port = 443
127     }
128
129 Identifiers may not contain certain characters (e.g. space) or start
130 with certain characters (e.g. digits). If you want to use a dictionary
131 key that is not a valid identifier you can enclose the key in double
132 quotes.
133
134 ### <a id="array"></a> Array
135
136 An ordered list of values.
137
138 Individual array elements must be comma-separated.
139 The comma after the last element is optional.
140
141 Example:
142
143     [ "hello", 42 ]
144
145 An array may simultaneously contain values of different types, such as
146 strings and numbers.
147
148 ### <a id="expression-operators"></a> Operators
149
150 The following operators are supported in expressions:
151
152 Operator | Examples (Result)                             | Description
153 ---------|-----------------------------------------------|--------------------------------
154 !        | !"Hello" (false), !false (true)               | Logical negation of the operand
155 ~        | ~true (false)                                 | Bitwise negation of the operand
156 +        | 1 + 3 (4), "hello " + "world" ("hello world") | Adds two numbers; concatenates strings
157 +        | +3                                            | Unary plus
158 -        | 3 - 1 (2)                                     | Subtracts two numbers
159 -        | -3                                            | Unary minus
160 *        | 5m * 10 (3000)                                | Multiplies two numbers
161 /        | 5m / 5 (60)                                   | Divides two numbers
162 %        | 17 % 12 (5)                                   | Remainder after division
163 ^        | 17 ^ 12 (29)                                  | Bitwise XOR
164 &        | 7 & 3 (3)                                     | Binary AND
165 &#124;   | 2 &#124; 3 (3)                                | Binary OR
166 &&       | true && false (false)                         | Logical AND
167 &#124;&#124; | true &#124;&#124; false (true)            | Logical OR
168 <        | 3 < 5 (true)                                  | Less than
169 >        | 3 > 5 (false)                                 | Greater than
170 <=       | 3 <= 3 (true)                                 | Less than or equal
171 >=       | 3 >= 3 (true)                                 | Greater than or equal
172 <<       | 4 << 8 (1024)                                 | Left shift
173 >>       | 1024 >> 4 (64)                                | Right shift
174 ==       | "hello" == "hello" (true), 3 == 5 (false)     | Equal to
175 !=       | "hello" != "world" (true), 3 != 3 (false)     | Not equal to
176 in       | "foo" in [ "foo", "bar" ] (true)              | Element contained in array
177 !in      | "foo" !in [ "bar", "baz" ] (true)             | Element not contained in array
178 ()       | (3 + 3) * 5                                   | Groups sub-expressions
179 ()       | Math.random()                                 | Calls a function
180
181 ### <a id="function-calls"></a> Function Calls
182
183 Functions can be called using the `()` operator:
184
185     const MyGroups = [ "test1", "test" ]
186
187     {
188       check_interval = len(MyGroups) * 1m
189     }
190
191 A list of available functions is available in the [Library Reference](14-library-reference.md#library-reference) chapter.
192
193 ## <a id="dictionary-operators"></a> Assignments
194
195 In addition to the `=` operator shown above a number of other operators
196 to manipulate attributes are supported. Here's a list of all
197 available operators:
198
199 ### <a id="operator-assignment"></a> Operator =
200
201 Sets an attribute to the specified value.
202
203 Example:
204
205     {
206       a = 5
207       a = 7
208     }
209
210 In this example `a` has the value `7` after both instructions are executed.
211
212 ### <a id="operator-additive-assignment"></a> Operator +=
213
214 The += operator is a shortcut. The following expression:
215
216     {
217       a = [ "hello" ]
218       a += [ "world" ]
219     }
220
221 is equivalent to:
222
223     {
224       a = [ "hello" ]
225       a = a + [ "world" ]
226     }
227
228 ### <a id="operator-substractive-assignment"></a> Operator -=
229
230 The -= operator is a shortcut. The following expression:
231
232     {
233       a = 10
234       a -= 5
235     }
236
237 is equivalent to:
238
239     {
240       a = 10
241       a = a - 5
242     }
243
244 ### <a id="operator-multiply-assignment"></a> Operator \*=
245
246 The *= operator is a shortcut. The following expression:
247
248     {
249       a = 60
250       a *= 5
251     }
252
253 is equivalent to:
254
255     {
256       a = 60
257       a = a * 5
258     }
259
260 ### <a id="operator-dividing-assignment"></a> Operator /=
261
262 The /= operator is a shortcut. The following expression:
263
264     {
265       a = 300
266       a /= 5
267     }
268
269 is equivalent to:
270
271     {
272       a = 300
273       a = a / 5
274     }
275
276 ## <a id="indexer"></a> Indexer
277
278 The indexer syntax provides a convenient way to set dictionary elements.
279
280 Example:
281
282     {
283       hello.key = "world"
284     }
285
286 Example (alternative syntax):
287
288     {
289       hello["key"] = "world"
290     }
291
292 This is equivalent to writing:
293
294     {
295       hello += {
296         key = "world"
297       }
298     }
299
300 If the `hello` attribute does not already have a value it is automatically initialized to an empty dictionary.
301
302 ## <a id="template-imports"></a> Template Imports
303
304 Objects can import attributes from other objects.
305
306 Example:
307
308     template Host "default-host" {
309       vars.colour = "red"
310     }
311
312     template Host "test-host" {
313       import "default-host"
314
315       vars.colour = "blue"
316     }
317
318     object Host "localhost" {
319       import "test-host"
320
321       address = "127.0.0.1"
322       address6 = "::1"
323     }
324
325 The `default-host` and `test-host` objects are marked as templates
326 using the `template` keyword. Unlike ordinary objects templates are not
327 instantiated at run-time. Parent objects do not necessarily have to be
328 templates, however in general they are.
329
330 The `vars` dictionary for the `localhost` object contains all three
331 custom attributes and the custom attribute `colour` has the value `"blue"`.
332
333 Parent objects are resolved in the order they're specified using the
334 `import` keyword.
335
336 ## <a id="constants"></a> Constants
337
338 Global constants can be set using the `const` keyword:
339
340     const VarName = "some value"
341
342 Once defined a constant can be accessed from any file. Constants cannot be changed
343 once they are set.
344
345 Icinga 2 provides a number of special global constants. Some of them can be overridden using the `--define` command line parameter:
346
347 Variable            |Description
348 --------------------|-------------------
349 PrefixDir           |**Read-only.** Contains the installation prefix that was specified with cmake -DCMAKE_INSTALL_PREFIX. Defaults to "/usr/local".
350 SysconfDir          |**Read-only.** Contains the path of the sysconf directory. Defaults to PrefixDir + "/etc".
351 ZonesDir            |**Read-only.** Contains the path of the zones.d directory. Defaults to SysconfDir + "/zones.d".
352 LocalStateDir       |**Read-only.** Contains the path of the local state directory. Defaults to PrefixDir + "/var".
353 RunDir              |**Read-only.** Contains the path of the run directory. Defaults to LocalStateDir + "/run".
354 PkgDataDir          |**Read-only.** Contains the path of the package data directory. Defaults to PrefixDir + "/share/icinga2".
355 StatePath           |**Read-write.** Contains the path of the Icinga 2 state file. Defaults to LocalStateDir + "/lib/icinga2/icinga2.state".
356 ObjectsPath         |**Read-write.** Contains the path of the Icinga 2 objects file. Defaults to LocalStateDir + "/cache/icinga2/icinga2.debug".
357 PidPath             |**Read-write.** Contains the path of the Icinga 2 PID file. Defaults to RunDir + "/icinga2/icinga2.pid".
358 Vars                |**Read-write.** Contains a dictionary with global custom attributes. Not set by default.
359 NodeName            |**Read-write.** Contains the cluster node name. Set to the local hostname by default.
360 ApplicationType     |**Read-write.** Contains the name of the Application type. Defaults to "icinga/IcingaApplication".
361 EnableNotifications |**Read-write.** Whether notifications are globally enabled. Defaults to true.
362 EnableEventHandlers |**Read-write.** Whether event handlers are globally enabled. Defaults to true.
363 EnableFlapping      |**Read-write.** Whether flap detection is globally enabled. Defaults to true.
364 EnableHostChecks    |**Read-write.** Whether active host checks are globally enabled. Defaults to true.
365 EnableServiceChecks |**Read-write.** Whether active service checks are globally enabled. Defaults to true.
366 EnablePerfdata      |**Read-write.** Whether performance data processing is globally enabled. Defaults to true.
367 UseVfork            |**Read-write.** Whether to use vfork(). Only available on *NIX. Defaults to true.
368 RunAsUser               |**Read-write.** Defines the user the Icinga 2 daemon is running as. Used in the `init.conf` configuration file.
369 RunAsGroup              |**Read-write.** Defines the group the Icinga 2 daemon is running as. Used in the `init.conf` configuration file.
370
371 ## <a id="apply"></a> Apply
372
373 The `apply` keyword can be used to create new objects which are associated with
374 another group of objects.
375
376     apply Service "ping" to Host {
377       import "generic-service"
378
379       check_command = "ping4"
380
381       assign where host.name == "localhost"
382     }
383
384 In this example the `assign where` condition is a boolean expression which is
385 evaluated for all objects of type `Host` and a new service with name "ping"
386 is created for each matching host. [Expression operators](13-language-reference.md#expression-operators)
387 may be used in `assign where` conditions.
388
389 The `to` keyword and the target type may be omitted if there is only one target
390 type, e.g. for the `Service` type.
391
392 Depending on the object type used in the `apply` expression additional local
393 variables may be available for use in the `where` condition:
394
395 Source Type       | Target Type | Variables
396 ------------------|-------------|--------------
397 Service           | Host        | host
398 Dependency        | Host        | host
399 Dependency        | Service     | host, service
400 Notification      | Host        | host
401 Notification      | Service     | host, service
402 ScheduledDowntime | Host        | host
403 ScheduledDowntime | Service     | host, service
404
405 Any valid config attribute can be accessed using the `host` and `service`
406 variables. For example, `host.address` would return the value of the host's
407 "address" attribute - or null if that attribute isn't set.
408
409 ## <a id="group-assign"></a> Group Assign
410
411 Group objects can be assigned to specific member objects using the `assign where`
412 and `ignore where` conditions.
413
414     object HostGroup "linux-servers" {
415       display_name = "Linux Servers"
416
417       assign where host.vars.os == "Linux"
418     }
419
420 In this example the `assign where` condition is a boolean expression which is evaluated
421 for all objects of the type `Host`. Each matching host is added as member to the host group
422 with the name "linux-servers". Membership exclusion can be controlled using the `ignore where`
423 condition. [Expression operators](13-language-reference.md#expression-operators) may be used in `assign where` and
424 `ignore where` conditions.
425
426 Source Type       | Variables
427 ------------------|--------------
428 HostGroup         | host
429 ServiceGroup      | host, service
430 UserGroup         | user
431
432
433 ## <a id="boolean-values"></a> Boolean Values
434
435 The `assign where` and `ignore where` statements, the `!`, `&&` and `||`
436 operators as well as the `bool()` function convert their arguments to a
437 boolean value based on the following rules:
438
439 Description          | Example Value     | Boolean Value
440 ---------------------|-------------------|--------------
441 Empty value          | null              | false
442 Zero                 | 0                 | false
443 Non-zero integer     | -23945            | true
444 Empty string         | ""                | false
445 Non-empty string     | "Hello"           | true
446 Empty array          | []                | false
447 Non-empty array      | [ "Hello" ]       | true
448 Empty dictionary     | {}                | false
449 Non-empty dictionary | { key = "value" } | true
450
451 For a list of supported expression operators for `assign where` and `ignore where`
452 statements, see [expression operators](13-language-reference.md#expression-operators).
453
454 ## <a id="comments"></a> Comments
455
456 The Icinga 2 configuration format supports C/C++-style and shell-style comments.
457
458 Example:
459
460     /*
461      This is a comment.
462      */
463     object Host "localhost" {
464       check_interval = 30 // this is also a comment.
465       retry_interval = 15 # yet another comment
466     }
467
468 ## <a id="includes"></a> Includes
469
470 Other configuration files can be included using the `include` directive.
471 Paths must be relative to the configuration file that contains the
472 `include` directive.
473
474 Example:
475
476     include "some/other/file.conf"
477     include "conf.d/*.conf"
478
479 Wildcard includes are not recursive.
480
481 Icinga also supports include search paths similar to how they work in a
482 C/C++ compiler:
483
484     include <itl>
485
486 Note the use of angle brackets instead of double quotes. This causes the
487 config compiler to search the include search paths for the specified
488 file. By default $PREFIX/share/icinga2/include is included in the list of search
489 paths. Additional include search paths can be added using
490 [command-line options](6-cli-commands.md#config-include-path).
491
492 Wildcards are not permitted when using angle brackets.
493
494 ## <a id="recursive-includes"></a> Recursive Includes
495
496 The `include_recursive` directive can be used to recursively include all
497 files in a directory which match a certain pattern.
498
499 Example:
500
501     include_recursive "conf.d", "*.conf"
502     include_recursive "templates"
503
504 The first parameter specifies the directory from which files should be
505 recursively included.
506
507 The file names need to match the pattern given in the second parameter.
508 When no pattern is specified the default pattern "*.conf" is used.
509
510 ## <a id="library"></a> Library directive
511
512 The `library` directive can be used to manually load additional
513 libraries. Libraries can be used to provide additional object types and
514 functions.
515
516 Example:
517
518     library "snmphelper"
519
520 ## <a id="functions"></a> Functions
521
522 Functions can be defined using the `function` keyword.
523
524 Example:
525
526     function multiply(a, b) {
527           return a * b
528         }
529
530 When encountering the `return` keyword further execution of the function is terminated and
531 the specified value is supplied to the caller of the function:
532
533     log(multiply(3, 5))
534
535 In this example the `multiply` function we declared earlier is invoked with two arguments (3 and 5).
536 The function computes the product of those arguments and makes the result available to the
537 function's caller.
538
539 When no value is supplied for the `return` statement the function returns `null`.
540
541 Functions which do not have a `return` statement have their return value set to the value of the
542 last expression which was performed by the function. For example, we could have also written our
543 `multiply` function like this:
544
545     function multiply(a, b) {
546           a * b
547         }
548
549 Anonymous functions can be created by omitting the name in the function definition. The
550 resulting function object can be used like any other value:
551
552     var fn = function() { 3 }
553         
554         fn() /* Returns 3 */
555
556 ## <a id="lambdas"></a> Lambda Expressions
557
558 Functions can also be declared using the alternative lambda syntax.
559
560 Example:
561
562     f = (x) => x * x
563
564 Multiple statements can be used by putting the function body into braces:
565
566     f = (x) => {
567           log("Lambda called")
568           x * x
569     }
570
571 Just like with ordinary functions the return value is the value of the last statement.
572
573 For lambdas which take exactly one argument the braces around the arguments can be omitted:
574
575     f = x => x * x
576
577 ## <a id="variable-scopes"></a> Variable Scopes
578
579 When setting a variable Icinga checks the following scopes in this order whether the variable
580 already exists there:
581
582 * Local Scope
583 * `this` Scope
584 * Global Scope
585
586 The local scope contains variables which only exist during the invocation of the current function,
587 object or apply statement. Local variables can be declared using the `var` keyword:
588
589     function multiply(a, b) {
590           var temp = a * b
591           return temp
592         }
593
594 Each time the `multiply` function is invoked a new `temp` variable is used which is in no way
595 related to previous invocations of the function.
596
597 When setting a variable which has not previously been declared as local using the `var` keyword
598 the `this` scope is used.
599
600 The `this` scope refers to the current object which the function or object/apply statement
601 operates on.
602
603     object Host "localhost" {
604           check_interval = 5m
605     }
606
607 In this example the `this` scope refers to the "localhost" object. The `check_interval` attribute
608 is set for this particular host.
609
610 You can explicitly access the `this` scope using the `this` keyword:
611
612     object Host "localhost" {
613           var check_interval = 5m
614   
615       /* This explicitly specifies that the attribute should be set
616        * for the host, if we had omitted `this.` the (poorly named)
617        * local variable `check_interval` would have been modified instead.
618        */
619       this.check_interval = 1m 
620   }
621
622 Similarly the keywords `locals` and `globals` are available to access the local and global scope.
623
624 Functions also have a `this` scope. However unlike for object/apply statements the `this` scope for
625 a function is set to whichever object was used to invoke the function. Here's an example:
626
627      hm = {
628            h_word = null
629                  
630            function init(word) {
631              h_word = word
632            }
633          }
634          
635          /* Let's invoke the init() function */
636          hm.init("hello")
637
638 We're using `hm.init` to invoke the function which causes the value of `hm` to become the `this`
639 scope for this function call.
640
641 ## <a id="conditional-statements"></a> Conditional Statements
642
643 Sometimes it can be desirable to only evaluate statements when certain conditions are met. The if/else
644 construct can be used to accomplish this.
645
646 Example:
647
648     a = 3
649
650         if (a < 5) {
651       a *= 7
652         } else {
653           a *= 2
654         }
655
656 An if/else construct can also be used in place of any other value. The value of an if/else statement
657 is the value of the last statement which was evaluated for the branch which was taken:
658
659     a = if (true) {
660           log("Taking the 'true' branch")
661           7 * 3
662         } else {
663           log("Taking the 'false' branch")
664           9
665         }
666
667 This example prints the log message "Taking the 'true' branch" and the `a` variable is set to 21 (7 * 3).
668
669 The value of an if/else construct is null if the condition evaluates to false and no else branch is given.
670
671 ## <a id="for-loops"></a> For Loops
672
673 The `for` statement can be used to iterate over arrays and dictionaries.
674
675 Example:
676
677     var list = [ "a", "b", "c" ]
678         
679         for (item in list) {
680           log("Item: " + item)
681         }
682
683 The loop body is evaluated once for each item in the array. The variable `item` is declared as a local
684 variable just as if the `var` keyword had been used.
685
686 Iterating over dictionaries can be accomplished in a similar manner:
687
688     var dict = { a = 3, b = 7 }
689         
690         for (key => value in dict) {
691           log("Key: " + key + ", Value: " + value)
692     }
693
694 ## <a id="types"></a> Types
695
696 All values have a static type. The `typeof` function can be used to determine the type of a value:
697
698     typeof(3) /* Returns an object which represents the type for numbers */
699
700 The following built-in types are available:
701
702 Type       | Examples          | Description
703 -----------|-------------------|------------------------
704 Number     | 3.7               | A numerical value.
705 Boolean    | true, false       | A boolean value.
706 String     | "hello"           | A string.
707 Array      | [ "a", "b" ]      | An array.
708 Dictionary | { a = 3 }         | A dictionary.
709
710 Depending on which libraries are loaded additional types may become available. The `icinga`
711 library implements a whole bunch of other types, e.g. Host, Service, CheckCommand, etc.
712
713 Each type has an associated type object which describes the type's semantics. These
714 type objects are made available using global variables which match the type's name:
715
716     /* This logs 'true' */
717     log(typeof(3) == Number)
718
719 The type object's `prototype` property can be used to find out which methods a certain type
720 supports:
721
722         /* This returns: ["find","len","lower","replace","split","substr","to_string","upper"] */
723     keys(String.prototype)
724
725 ## <a id="reserved-keywords"></a> Reserved Keywords
726
727 These keywords are reserved and must not be used as constants or custom attributes.
728
729     object
730     template
731     include
732     include_recursive
733     library
734     null
735     true
736     false
737     const
738     var
739     this
740     use
741     apply
742     to
743     where
744     import
745     assign
746     ignore
747     function
748     return
749     for
750     if
751     else
752     in
753
754 You can escape reserved keywords using the `@` character. The following example
755 tries to set `vars.include` which references a reserved keyword and generates
756 an error:
757
758     [2014-09-15 17:24:00 +0200] critical/config: Location:
759     /etc/icinga2/conf.d/hosts/localhost.conf(13):   vars.sla = "24x7"
760     /etc/icinga2/conf.d/hosts/localhost.conf(14):
761     /etc/icinga2/conf.d/hosts/localhost.conf(15):   vars.include = "some cmdb export field"
762                                                          ^^^^^^^
763     /etc/icinga2/conf.d/hosts/localhost.conf(16): }
764     /etc/icinga2/conf.d/hosts/localhost.conf(17):
765
766     Config error: in /etc/icinga2/conf.d/hosts/localhost.conf: 15:8-15:14: syntax error, unexpected include (T_INCLUDE), expecting T_IDENTIFIER
767     [2014-09-15 17:24:00 +0200] critical/config: 1 errors, 0 warnings.
768
769 You can escape the `include` keyword by prefixing it with an additional `@` character:
770
771     object Host "localhost" {
772       import "generic-host"
773
774       address = "127.0.0.1"
775       address6 = "::1"
776
777       vars.os = "Linux"
778       vars.sla = "24x7"
779
780       vars.@include = "some cmdb export field"
781     }
782