Unify documentation code formatting

This unifies the documentation code formatting to use only backticks.
This commit is contained in:
Michael Insel 2019-03-07 19:56:49 +01:00 committed by Michael Friedrich
parent f4e9028543
commit 081d88436f
17 changed files with 4570 additions and 3431 deletions

View File

@ -77,12 +77,14 @@ If you prefer to organize your own local object tree, you can also remove
Create a new configuration directory, e.g. `objects.d` and include it Create a new configuration directory, e.g. `objects.d` and include it
in your icinga2.conf file. in your icinga2.conf file.
```
[root@icinga2-master1.localdomain /]# mkdir -p /etc/icinga2/objects.d [root@icinga2-master1.localdomain /]# mkdir -p /etc/icinga2/objects.d
[root@icinga2-master1.localdomain /]# vim /etc/icinga2/icinga2.conf [root@icinga2-master1.localdomain /]# vim /etc/icinga2/icinga2.conf
/* Local object configuration on our master instance. */ /* Local object configuration on our master instance. */
include_recursive "objects.d" include_recursive "objects.d"
```
This approach is used by the [Icinga 2 Puppet module](https://github.com/Icinga/puppet-icinga2). This approach is used by the [Icinga 2 Puppet module](https://github.com/Icinga/puppet-icinga2).
@ -97,6 +99,7 @@ An example configuration file is installed for you in `/etc/icinga2/icinga2.conf
Here's a brief description of the example configuration: Here's a brief description of the example configuration:
```
/** /**
* Icinga 2 configuration file * Icinga 2 configuration file
* -- this is where you define settings for the Icinga application including * -- this is where you define settings for the Icinga application including
@ -105,6 +108,7 @@ Here's a brief description of the example configuration:
* For an overview of all available configuration options please refer * For an overview of all available configuration options please refer
* to the documentation that is distributed as part of Icinga 2. * to the documentation that is distributed as part of Icinga 2.
*/ */
```
Icinga 2 supports [C/C++-style comments](17-language-reference.md#comments). Icinga 2 supports [C/C++-style comments](17-language-reference.md#comments).
@ -115,15 +119,18 @@ Icinga 2 supports [C/C++-style comments](17-language-reference.md#comments).
The `include` directive can be used to include other files. The `include` directive can be used to include other files.
```
/** /**
* The zones.conf defines zones for a cluster setup. * The zones.conf defines zones for a cluster setup.
* Not required for single instance setups. * Not required for single instance setups.
*/ */
include "zones.conf" include "zones.conf"
```
The [Icinga Template Library](10-icinga-template-library.md#icinga-template-library) provides a set of common templates The [Icinga Template Library](10-icinga-template-library.md#icinga-template-library) provides a set of common templates
and [CheckCommand](03-monitoring-basics.md#check-commands) definitions. and [CheckCommand](03-monitoring-basics.md#check-commands) definitions.
```
/** /**
* The Icinga Template Library (ITL) provides a number of useful templates * The Icinga Template Library (ITL) provides a number of useful templates
* and command definitions. * and command definitions.
@ -154,17 +161,20 @@ and [CheckCommand](03-monitoring-basics.md#check-commands) definitions.
* the features-enabled directory. * the features-enabled directory.
*/ */
include "features-enabled/*.conf" include "features-enabled/*.conf"
```
This `include` directive takes care of including the configuration files for all This `include` directive takes care of including the configuration files for all
the features which have been enabled with `icinga2 feature enable`. See the features which have been enabled with `icinga2 feature enable`. See
[Enabling/Disabling Features](11-cli-commands.md#enable-features) for more details. [Enabling/Disabling Features](11-cli-commands.md#enable-features) for more details.
```
/** /**
* Although in theory you could define all your objects in this file * Although in theory you could define all your objects in this file
* the preferred way is to create separate directories and files in the conf.d * the preferred way is to create separate directories and files in the conf.d
* directory. Each of these files must have the file extension ".conf". * directory. Each of these files must have the file extension ".conf".
*/ */
include_recursive "conf.d" include_recursive "conf.d"
```
You can put your own configuration files in the [conf.d](04-configuring-icinga-2.md#conf-d) directory. This You can put your own configuration files in the [conf.d](04-configuring-icinga-2.md#conf-d) directory. This
directive makes sure that all of your own configuration files are included. directive makes sure that all of your own configuration files are included.
@ -184,6 +194,7 @@ cluster setup.
Example: Example:
```
/* The directory which contains the plugins from the Monitoring Plugins project. */ /* The directory which contains the plugins from the Monitoring Plugins project. */
const PluginDir = "/usr/lib64/nagios/plugins" const PluginDir = "/usr/lib64/nagios/plugins"
@ -202,6 +213,7 @@ Example:
/* Secret key for remote node tickets */ /* Secret key for remote node tickets */
const TicketSalt = "" const TicketSalt = ""
```
The `ZoneName` and `TicketSalt` constants are required for remote client The `ZoneName` and `TicketSalt` constants are required for remote client
and distributed setups only. and distributed setups only.
@ -286,6 +298,7 @@ rules in [services.conf](04-configuring-icinga-2.md#services-conf) will automati
generate a new service checking the `/icingaweb2` URI using the `http` generate a new service checking the `/icingaweb2` URI using the `http`
check. check.
```
/* /*
* Host definitions with object attributes * Host definitions with object attributes
* used for apply rules for Service, Notification, * used for apply rules for Service, Notification,
@ -337,6 +350,7 @@ check.
groups = [ "icingaadmins" ] groups = [ "icingaadmins" ]
} }
} }
```
This is only the host object definition. Now we'll need to make sure that this This is only the host object definition. Now we'll need to make sure that this
host and your additional hosts are getting [services](04-configuring-icinga-2.md#services-conf) applied. host and your additional hosts are getting [services](04-configuring-icinga-2.md#services-conf) applied.
@ -376,6 +390,7 @@ which we enabled earlier by including the `itl` and `plugins` configuration file
Example `load` service apply rule: Example `load` service apply rule:
```
apply Service "load" { apply Service "load" {
import "generic-service" import "generic-service"
@ -386,6 +401,7 @@ Example `load` service apply rule:
assign where host.name == NodeName assign where host.name == NodeName
} }
```
The `apply` keyword can be used to create new objects which are associated with The `apply` keyword can be used to create new objects which are associated with
another group of objects. You can `import` existing templates, define (custom) another group of objects. You can `import` existing templates, define (custom)
@ -403,6 +419,7 @@ may be used in `assign where` conditions.
Multiple `assign where` condition can be combined with `AND` using the `&&` operator Multiple `assign where` condition can be combined with `AND` using the `&&` operator
as shown in the `ssh` example: as shown in the `ssh` example:
```
apply Service "ssh" { apply Service "ssh" {
import "generic-service" import "generic-service"
@ -410,6 +427,7 @@ as shown in the `ssh` example:
assign where host.address && host.vars.os == "Linux" assign where host.address && host.vars.os == "Linux"
} }
```
In this example, the service `ssh` is applied to all hosts having the `address` In this example, the service `ssh` is applied to all hosts having the `address`
attribute defined `AND` having the custom attribute `os` set to the string attribute defined `AND` having the custom attribute `os` set to the string
@ -429,6 +447,7 @@ The idea is simple: Your host in [hosts.conf](04-configuring-icinga-2.md#hosts-c
Remember the example from [hosts.conf](04-configuring-icinga-2.md#hosts-conf): Remember the example from [hosts.conf](04-configuring-icinga-2.md#hosts-conf):
```
... ...
/* Define disks and attributes for service apply rules in `services.conf`. */ /* Define disks and attributes for service apply rules in `services.conf`. */
vars.disks["disk"] = { vars.disks["disk"] = {
@ -438,7 +457,7 @@ Remember the example from [hosts.conf](04-configuring-icinga-2.md#hosts-conf):
disk_partition = "/" disk_partition = "/"
} }
... ...
```
This dictionary contains multiple service names we want to monitor. `disk` This dictionary contains multiple service names we want to monitor. `disk`
should just check all available disks, while `disk /` will pass an additional should just check all available disks, while `disk /` will pass an additional
@ -466,6 +485,7 @@ generated service
Configuration example: Configuration example:
```
apply Service for (disk => config in host.vars.disks) { apply Service for (disk => config in host.vars.disks) {
import "generic-service" import "generic-service"
@ -473,6 +493,7 @@ Configuration example:
vars += config vars += config
} }
```
A similar example is used for the `http` services. That way you can make your A similar example is used for the `http` services. That way you can make your
host the information provider for all apply rules. Define them once, and only host the information provider for all apply rules. Define them once, and only
@ -494,6 +515,7 @@ Defines the `icingaadmin` User and the `icingaadmins` UserGroup. The latter is u
[hosts.conf](04-configuring-icinga-2.md#hosts-conf) for defining a custom host attribute later used in [hosts.conf](04-configuring-icinga-2.md#hosts-conf) for defining a custom host attribute later used in
[notifications.conf](04-configuring-icinga-2.md#notifications-conf) for notification apply rules. [notifications.conf](04-configuring-icinga-2.md#notifications-conf) for notification apply rules.
```
object User "icingaadmin" { object User "icingaadmin" {
import "generic-user" import "generic-user"
@ -506,7 +528,7 @@ Defines the `icingaadmin` User and the `icingaadmins` UserGroup. The latter is u
object UserGroup "icingaadmins" { object UserGroup "icingaadmins" {
display_name = "Icinga 2 Admin Group" display_name = "Icinga 2 Admin Group"
} }
```
#### notifications.conf <a id="notifications-conf"></a> #### notifications.conf <a id="notifications-conf"></a>
@ -527,6 +549,7 @@ By setting the `user_groups` to the value provided by the
respective [host.vars.notification.mail](04-configuring-icinga-2.md#hosts-conf) attribute we'll respective [host.vars.notification.mail](04-configuring-icinga-2.md#hosts-conf) attribute we'll
implicitely use the `icingaadmins` UserGroup defined in [users.conf](04-configuring-icinga-2.md#users-conf). implicitely use the `icingaadmins` UserGroup defined in [users.conf](04-configuring-icinga-2.md#users-conf).
```
apply Notification "mail-icingaadmin" to Host { apply Notification "mail-icingaadmin" to Host {
import "mail-host-notification" import "mail-host-notification"
@ -544,6 +567,7 @@ implicitely use the `icingaadmins` UserGroup defined in [users.conf](04-configur
assign where host.vars.notification.mail assign where host.vars.notification.mail
} }
```
More details on defining notifications and their additional attributes such as More details on defining notifications and their additional attributes such as
filters can be read in [this chapter](03-monitoring-basics.md#alert-notifications). filters can be read in [this chapter](03-monitoring-basics.md#alert-notifications).
@ -565,6 +589,7 @@ a member of the host group `linux-servers`.
This is done by using the [group assign](17-language-reference.md#group-assign) expressions similar This is done by using the [group assign](17-language-reference.md#group-assign) expressions similar
to previously seen [apply rules](03-monitoring-basics.md#using-apply). to previously seen [apply rules](03-monitoring-basics.md#using-apply).
```
object HostGroup "linux-servers" { object HostGroup "linux-servers" {
display_name = "Linux Servers" display_name = "Linux Servers"
@ -576,11 +601,13 @@ to previously seen [apply rules](03-monitoring-basics.md#using-apply).
assign where host.vars.os == "Windows" assign where host.vars.os == "Windows"
} }
```
Service groups can be grouped together by similar pattern matches. Service groups can be grouped together by similar pattern matches.
The [match function](18-library-reference.md#global-functions-match) expects a wildcard match string The [match function](18-library-reference.md#global-functions-match) expects a wildcard match string
and the attribute string to match with. and the attribute string to match with.
```
object ServiceGroup "ping" { object ServiceGroup "ping" {
display_name = "Ping Checks" display_name = "Ping Checks"
@ -598,13 +625,14 @@ and the attribute string to match with.
assign where match("disk*", service.check_command) assign where match("disk*", service.check_command)
} }
```
#### templates.conf <a id="templates-conf"></a> #### templates.conf <a id="templates-conf"></a>
Most of the example configuration objects use generic global templates by Most of the example configuration objects use generic global templates by
default: default:
```
template Host "generic-host" { template Host "generic-host" {
max_check_attempts = 5 max_check_attempts = 5
check_interval = 1m check_interval = 1m
@ -618,11 +646,12 @@ default:
check_interval = 1m check_interval = 1m
retry_interval = 30s retry_interval = 30s
} }
```
The `hostalive` check command is part of the The `hostalive` check command is part of the
[Plugin Check Commands](10-icinga-template-library.md#icinga-template-library). [Plugin Check Commands](10-icinga-template-library.md#icinga-template-library).
```
template Notification "mail-host-notification" { template Notification "mail-host-notification" {
command = "mail-host-notification" command = "mail-host-notification"
@ -644,6 +673,7 @@ The `hostalive` check command is part of the
period = "24x7" period = "24x7"
} }
```
More details on `Notification` object attributes can be found [here](09-object-types.md#objecttype-notification). More details on `Notification` object attributes can be found [here](09-object-types.md#objecttype-notification).
@ -658,6 +688,7 @@ for the time ranges required for recurring downtime slots.
Learn more about downtimes in [this chapter](08-advanced-topics.md#downtimes). Learn more about downtimes in [this chapter](08-advanced-topics.md#downtimes).
```
apply ScheduledDowntime "backup-downtime" to Service { apply ScheduledDowntime "backup-downtime" to Service {
author = "icingaadmin" author = "icingaadmin"
comment = "Scheduled downtime for backup" comment = "Scheduled downtime for backup"
@ -674,7 +705,7 @@ Learn more about downtimes in [this chapter](08-advanced-topics.md#downtimes).
assign where service.vars.backup_downtime != "" assign where service.vars.backup_downtime != ""
} }
```
#### timeperiods.conf <a id="timeperiods-conf"></a> #### timeperiods.conf <a id="timeperiods-conf"></a>

View File

@ -15,6 +15,7 @@ The recommended way of setting up these plugins is to copy them to a common dire
and create a new global constant, e.g. `CustomPluginDir` in your [constants.conf](04-configuring-icinga-2.md#constants-conf) and create a new global constant, e.g. `CustomPluginDir` in your [constants.conf](04-configuring-icinga-2.md#constants-conf)
configuration file: configuration file:
```
# cp check_snmp_int.pl /opt/monitoring/plugins # cp check_snmp_int.pl /opt/monitoring/plugins
# chmod +x /opt/monitoring/plugins/check_snmp_int.pl # chmod +x /opt/monitoring/plugins/check_snmp_int.pl
@ -27,12 +28,15 @@ configuration file:
const PluginDir = "/usr/lib/nagios/plugins" const PluginDir = "/usr/lib/nagios/plugins"
const CustomPluginDir = "/opt/monitoring/plugins" const CustomPluginDir = "/opt/monitoring/plugins"
```
Prior to using the check plugin with Icinga 2 you should ensure that it is working properly Prior to using the check plugin with Icinga 2 you should ensure that it is working properly
by trying to run it on the console using whichever user Icinga 2 is running as: by trying to run it on the console using whichever user Icinga 2 is running as:
```
# su - icinga -s /bin/bash # su - icinga -s /bin/bash
$ /opt/monitoring/plugins/check_snmp_int.pl --help $ /opt/monitoring/plugins/check_snmp_int.pl --help
```
Additional libraries may be required for some plugins. Please consult the plugin Additional libraries may be required for some plugins. Please consult the plugin
documentation and/or the included README file for installation instructions. documentation and/or the included README file for installation instructions.
@ -64,6 +68,7 @@ set them on host/service level and you'll always know which command they control
This is an example for a custom `my-snmp-int` check command: This is an example for a custom `my-snmp-int` check command:
```
object CheckCommand "my-snmp-int" { object CheckCommand "my-snmp-int" {
command = [ CustomPluginDir + "/check_snmp_int.pl" ] command = [ CustomPluginDir + "/check_snmp_int.pl" ]
@ -87,7 +92,7 @@ This is an example for a custom `my-snmp-int` check command:
vars.snmp_warn = "300,400" vars.snmp_warn = "300,400"
vars.snmp_crit = "0,600" vars.snmp_crit = "0,600"
} }
```
For further information on your monitoring configuration read the For further information on your monitoring configuration read the
[Monitoring Basics](03-monitoring-basics.md#monitoring-basics) chapter. [Monitoring Basics](03-monitoring-basics.md#monitoring-basics) chapter.
@ -127,6 +132,7 @@ Common best practices when creating a new plugin are for example:
Example skeleton: Example skeleton:
```
# 1. include optional libraries # 1. include optional libraries
# 2. global variables # 2. global variables
# 3. helper functions and/or classes # 3. helper functions and/or classes
@ -149,6 +155,7 @@ Example skeleton:
else else
print "OK - ... | 'time'=0.2 'myperfdatavalue'=1.0 print "OK - ... | 'time'=0.2 'myperfdatavalue'=1.0
endif endif
```
There are various plugin libraries available which will help There are various plugin libraries available which will help
with plugin execution and output formatting too, for example with plugin execution and output formatting too, for example

File diff suppressed because it is too large Load Diff

View File

@ -15,6 +15,7 @@ The following example uses the [SNMP ITL](10-icinga-template-library.md#plugin-c
overrides the `snmp_oid` custom attribute. A service is created for all hosts which overrides the `snmp_oid` custom attribute. A service is created for all hosts which
have the `snmp-community` custom attribute. have the `snmp-community` custom attribute.
```
apply Service "uptime" { apply Service "uptime" {
import "generic-service" import "generic-service"
@ -24,6 +25,7 @@ have the `snmp-community` custom attribute.
assign where host.vars.snmp_community != "" assign where host.vars.snmp_community != ""
} }
```
Additional SNMP plugins are available using the [Manubulon SNMP Plugins](10-icinga-template-library.md#snmp-manubulon-plugin-check-commands). Additional SNMP plugins are available using the [Manubulon SNMP Plugins](10-icinga-template-library.md#snmp-manubulon-plugin-check-commands).
@ -37,6 +39,7 @@ Calling a plugin using the SSH protocol to execute a plugin on the remote server
its return code and output. The `by_ssh` command object is part of the built-in templates and its return code and output. The `by_ssh` command object is part of the built-in templates and
requires the `check_by_ssh` check plugin which is available in the [Monitoring Plugins package](02-getting-started.md#setting-up-check-plugins). requires the `check_by_ssh` check plugin which is available in the [Monitoring Plugins package](02-getting-started.md#setting-up-check-plugins).
```
object CheckCommand "by_ssh_swap" { object CheckCommand "by_ssh_swap" {
import "by_ssh" import "by_ssh"
@ -54,6 +57,7 @@ requires the `check_by_ssh` check plugin which is available in the [Monitoring P
vars.by_ssh_logname = "icinga" vars.by_ssh_logname = "icinga"
} }
```
## NSClient++ <a id="agent-based-checks-nsclient"></a> ## NSClient++ <a id="agent-based-checks-nsclient"></a>
@ -67,6 +71,7 @@ Icinga 2 provides the [nscp check command](10-icinga-template-library.md#plugin-
Example: Example:
```
object Service "disk" { object Service "disk" {
import "generic-service" import "generic-service"
@ -79,6 +84,7 @@ Example:
vars.nscp_warn = 70 vars.nscp_warn = 70
vars.nscp_crit = 80 vars.nscp_crit = 80
} }
```
For details on the `NSClient++` configuration please refer to the [official documentation](https://docs.nsclient.org/). For details on the `NSClient++` configuration please refer to the [official documentation](https://docs.nsclient.org/).
@ -116,6 +122,7 @@ Icinga 2 provides the [nrpe check command](10-icinga-template-library.md#plugin-
Example: Example:
```
object Service "users" { object Service "users" {
import "generic-service" import "generic-service"
@ -124,10 +131,13 @@ Example:
check_command = "nrpe" check_command = "nrpe"
vars.nrpe_command = "check_users" vars.nrpe_command = "check_users"
} }
```
nrpe.cfg: nrpe.cfg:
```
command[check_users]=/usr/local/icinga/libexec/check_users -w 5 -c 10 command[check_users]=/usr/local/icinga/libexec/check_users -w 5 -c 10
```
If you are planning to pass arguments to NRPE using the `-a` If you are planning to pass arguments to NRPE using the `-a`
command line parameter, make sure that your NRPE daemon has them command line parameter, make sure that your NRPE daemon has them
@ -144,6 +154,7 @@ attribute which expects either a single value or an array of values.
Example: Example:
```
object Service "nrpe-disk-/" { object Service "nrpe-disk-/" {
import "generic-service" import "generic-service"
@ -153,10 +164,13 @@ Example:
vars.nrpe_command = "check_disk" vars.nrpe_command = "check_disk"
vars.nrpe_arguments = [ "20%", "10%", "/" ] vars.nrpe_arguments = [ "20%", "10%", "/" ]
} }
```
Icinga 2 will execute the nrpe plugin like this: Icinga 2 will execute the nrpe plugin like this:
```
/usr/lib/nagios/plugins/check_nrpe -H <remote-nrpe-host> -c 'check_disk' -a '20%' '10%' '/' /usr/lib/nagios/plugins/check_nrpe -H <remote-nrpe-host> -c 'check_disk' -a '20%' '10%' '/'
```
NRPE expects all additional arguments in an ordered fashion NRPE expects all additional arguments in an ordered fashion
and interprets the first value as `$ARG1$` macro, the second and interprets the first value as `$ARG1$` macro, the second
@ -164,12 +178,16 @@ value as `$ARG2$`, and so on.
nrpe.cfg: nrpe.cfg:
```
command[check_disk]=/usr/local/icinga/libexec/check_disk -w $ARG1$ -c $ARG2$ -p $ARG3$ command[check_disk]=/usr/local/icinga/libexec/check_disk -w $ARG1$ -c $ARG2$ -p $ARG3$
```
Using the above example with `nrpe_arguments` the command Using the above example with `nrpe_arguments` the command
executed by the NRPE daemon looks similar to that: executed by the NRPE daemon looks similar to that:
```
/usr/local/icinga/libexec/check_disk -w 20% -c 10% -p / /usr/local/icinga/libexec/check_disk -w 20% -c 10% -p /
```
You can pass arguments in a similar manner to [NSClient++](07-agent-based-monitoring.md#agent-based-checks-nsclient) You can pass arguments in a similar manner to [NSClient++](07-agent-based-monitoring.md#agent-based-checks-nsclient)
when using its NRPE supported check method. when using its NRPE supported check method.
@ -193,6 +211,7 @@ state or from a missed reset event.
Add a directive in `snmptt.conf` Add a directive in `snmptt.conf`
```
EVENT coldStart .1.3.6.1.6.3.1.1.5.1 "Status Events" Normal EVENT coldStart .1.3.6.1.6.3.1.1.5.1 "Status Events" Normal
FORMAT Device reinitialized (coldStart) FORMAT Device reinitialized (coldStart)
EXEC echo "[$@] PROCESS_SERVICE_CHECK_RESULT;$A;Coldstart;2;The snmp agent has reinitialized." >> /var/run/icinga2/cmd/icinga2.cmd EXEC echo "[$@] PROCESS_SERVICE_CHECK_RESULT;$A;Coldstart;2;The snmp agent has reinitialized." >> /var/run/icinga2/cmd/icinga2.cmd
@ -201,6 +220,7 @@ Add a directive in `snmptt.conf`
in an agent role, is reinitializing itself and that its in an agent role, is reinitializing itself and that its
configuration may have been altered. configuration may have been altered.
EDESC EDESC
```
1. Define the `EVENT` as per your need. 1. Define the `EVENT` as per your need.
2. Construct the `EXEC` statement with the service name matching your template 2. Construct the `EXEC` statement with the service name matching your template
@ -210,6 +230,7 @@ match your Icinga convention.
Add an `EventCommand` configuration object for the passive service auto reset event. Add an `EventCommand` configuration object for the passive service auto reset event.
```
object EventCommand "coldstart-reset-event" { object EventCommand "coldstart-reset-event" {
command = [ ConfigDir + "/conf.d/custom/scripts/coldstart_reset_event.sh" ] command = [ ConfigDir + "/conf.d/custom/scripts/coldstart_reset_event.sh" ]
@ -219,11 +240,13 @@ Add an `EventCommand` configuration object for the passive service auto reset ev
"-s" = "$service.name$" "-s" = "$service.name$"
} }
} }
```
Create the `coldstart_reset_event.sh` shell script to pass the expanded variable Create the `coldstart_reset_event.sh` shell script to pass the expanded variable
data in. The `$service.state_id$` is important in order to prevent an endless loop data in. The `$service.state_id$` is important in order to prevent an endless loop
of event firing after the service has been reset. of event firing after the service has been reset.
```
#!/bin/bash #!/bin/bash
SERVICE_STATE_ID="" SERVICE_STATE_ID=""
@ -286,9 +309,11 @@ of event firing after the service has been reset.
if [ "$SERVICE_STATE_ID" -gt 0 ]; then if [ "$SERVICE_STATE_ID" -gt 0 ]; then
echo "[`date +%s`] PROCESS_SERVICE_CHECK_RESULT;$HOST_NAME;$SERVICE_NAME;0;Auto-reset (`date +"%m-%d-%Y %T"`)." >> /var/run/icinga2/cmd/icinga2.cmd echo "[`date +%s`] PROCESS_SERVICE_CHECK_RESULT;$HOST_NAME;$SERVICE_NAME;0;Auto-reset (`date +"%m-%d-%Y %T"`)." >> /var/run/icinga2/cmd/icinga2.cmd
fi fi
```
Finally create the `Service` and assign it: Finally create the `Service` and assign it:
```
apply Service "Coldstart" { apply Service "Coldstart" {
import "generic-service-custom" import "generic-service-custom"
@ -309,6 +334,7 @@ Finally create the `Service` and assign it:
assign where (host.vars.os == "Linux" || host.vars.os == "Windows") assign where (host.vars.os == "Linux" || host.vars.os == "Windows")
} }
```
### Complex SNMP Traps <a id="complex-traps"></a> ### Complex SNMP Traps <a id="complex-traps"></a>
@ -321,6 +347,7 @@ As long as the most recent passive update has occurred, the active check is bypa
Add a directive in `snmptt.conf` Add a directive in `snmptt.conf`
```
EVENT enterpriseSpecific <YOUR OID> "Status Events" Normal EVENT enterpriseSpecific <YOUR OID> "Status Events" Normal
FORMAT Enterprise specific trap FORMAT Enterprise specific trap
EXEC echo "[$@] PROCESS_SERVICE_CHECK_RESULT;$A;$1;$2;$3" >> /var/run/icinga2/cmd/icinga2.cmd EXEC echo "[$@] PROCESS_SERVICE_CHECK_RESULT;$A;$1;$2;$3" >> /var/run/icinga2/cmd/icinga2.cmd
@ -328,6 +355,7 @@ Add a directive in `snmptt.conf`
An enterprise specific trap. An enterprise specific trap.
The varbinds in order denote the Icinga service name, state and text. The varbinds in order denote the Icinga service name, state and text.
EDESC EDESC
```
1. Define the `EVENT` as per your need using your actual oid. 1. Define the `EVENT` as per your need using your actual oid.
2. The service name, state and text are extracted from the first three varbinds. 2. The service name, state and text are extracted from the first three varbinds.
@ -337,6 +365,7 @@ Create a `Service` for the specific use case associated to the host. If the host
matches and the first varbind value is `Backup`, SNMPTT will submit the corresponding matches and the first varbind value is `Backup`, SNMPTT will submit the corresponding
passive update with the state and text from the second and third varbind: passive update with the state and text from the second and third varbind:
```
object Service "Backup" { object Service "Backup" {
import "generic-service-custom" import "generic-service-custom"
@ -356,3 +385,4 @@ passive update with the state and text from the second and third varbind:
vars.dummy_state = 2 vars.dummy_state = 2
vars.dummy_text = "No passive check result received." vars.dummy_text = "No passive check result received."
} }
```

View File

@ -387,12 +387,16 @@ In Icinga 2 active check freshness is enabled by default. It is determined by th
The threshold is calculated based on the last check execution time for actively executed checks: The threshold is calculated based on the last check execution time for actively executed checks:
```
(last check execution time + check interval) > current time (last check execution time + check interval) > current time
```
If this host/service receives check results from an [external source](08-advanced-topics.md#external-check-results), If this host/service receives check results from an [external source](08-advanced-topics.md#external-check-results),
the threshold is based on the last time a check result was received: the threshold is based on the last time a check result was received:
```
(last check result time + check interval) > current time (last check result time + check interval) > current time
```
> **Tip** > **Tip**
> >
@ -579,6 +583,7 @@ In addition to that you can optionally define the `ssl` attribute which enables
Host definition: Host definition:
```
object Host "webserver01" { object Host "webserver01" {
import "generic-host" import "generic-host"
address = "192.168.56.200" address = "192.168.56.200"
@ -602,9 +607,11 @@ Host definition:
} }
} }
} }
```
Service apply for definitions: Service apply for definitions:
```
apply Service "webserver_ping" for (instance => config in host.vars.webserver.instance) { apply Service "webserver_ping" for (instance => config in host.vars.webserver.instance) {
display_name = "webserver_" + instance display_name = "webserver_" + instance
check_command = "ping4" check_command = "ping4"
@ -638,6 +645,7 @@ Service apply for definitions:
assign where config.url != "" assign where config.url != ""
} }
```
The variables defined in the host dictionary are not using the typical custom attribute The variables defined in the host dictionary are not using the typical custom attribute
prefix recommended for CheckCommand parameters. Instead they are re-used for multiple prefix recommended for CheckCommand parameters. Instead they are re-used for multiple
@ -756,6 +764,7 @@ slightly unexpected way. The following example shows how to assign values
depending on group membership. All hosts in the `slow-lan` host group use 300 depending on group membership. All hosts in the `slow-lan` host group use 300
as value for `ping_wrta`, all other hosts use 100. as value for `ping_wrta`, all other hosts use 100.
```
globals.group_specific_value = function(group, group_value, non_group_value) { globals.group_specific_value = function(group, group_value, non_group_value) {
return function() use (group, group_value, non_group_value) { return function() use (group, group_value, non_group_value) {
if (group in host.groups) { if (group in host.groups) {
@ -775,6 +784,7 @@ as value for `ping_wrta`, all other hosts use 100.
assign where true assign where true
} }
```
#### Use Functions in Assign Where Expressions <a id="use-functions-assign-where"></a> #### Use Functions in Assign Where Expressions <a id="use-functions-assign-where"></a>
@ -790,6 +800,7 @@ The following example requires the host `myprinter` being added
to the host group `printers-lexmark` but only if the host uses to the host group `printers-lexmark` but only if the host uses
a template matching the name `lexmark*`. a template matching the name `lexmark*`.
```
template Host "lexmark-printer-host" { template Host "lexmark-printer-host" {
vars.printer_type = "Lexmark" vars.printer_type = "Lexmark"
} }
@ -819,7 +830,7 @@ a template matching the name `lexmark*`.
/* call the global function and pass the arguments */ /* call the global function and pass the arguments */
assign where check_host_templates(host, "lexmark*") assign where check_host_templates(host, "lexmark*")
} }
```
Take a different more complex example: All hosts with the Take a different more complex example: All hosts with the
custom attribute `vars_app` as nested dictionary should be custom attribute `vars_app` as nested dictionary should be
@ -828,12 +839,15 @@ added to the host group `ABAP-app-server`. But only if the
It could read as wildcard match for nested dictionaries: It could read as wildcard match for nested dictionaries:
```
where host.vars.vars_app["*"].app_type == "ABAP" where host.vars.vars_app["*"].app_type == "ABAP"
```
The solution for this problem is to register a global The solution for this problem is to register a global
function which checks the `app_type` for all hosts function which checks the `app_type` for all hosts
with the `vars_app` dictionary. with the `vars_app` dictionary.
```
object Host "appserver01" { object Host "appserver01" {
check_command = "dummy" check_command = "dummy"
vars.vars_app["ABC"] = { app_type = "ABAP" } vars.vars_app["ABC"] = { app_type = "ABAP" }
@ -864,7 +878,7 @@ with the `vars_app` dictionary.
object HostGroup "ABAP-app-server" { object HostGroup "ABAP-app-server" {
assign where check_app_type(host, "ABAP") assign where check_app_type(host, "ABAP")
} }
```
#### Use Functions in Command Arguments set_if <a id="use-functions-command-arguments-setif"></a> #### Use Functions in Command Arguments set_if <a id="use-functions-command-arguments-setif"></a>
@ -879,6 +893,7 @@ multiple conditions and attributes.
The following example was found on the community support channels. The user had defined a host The following example was found on the community support channels. The user had defined a host
dictionary named `compellent` with the key `disks`. This was then used inside service apply for rules. dictionary named `compellent` with the key `disks`. This was then used inside service apply for rules.
```
object Host "dict-host" { object Host "dict-host" {
check_command = "check_compellent" check_command = "check_compellent"
vars.compellent["disks"] = { vars.compellent["disks"] = {
@ -886,6 +901,7 @@ dictionary named `compellent` with the key `disks`. This was then used inside se
checks = ["disks"] checks = ["disks"]
} }
} }
```
The more significant problem was to only add the command parameter `--disk` to the plugin call The more significant problem was to only add the command parameter `--disk` to the plugin call
when the dictionary `compellent` contains the key `disks`, and omit it if not found. when the dictionary `compellent` contains the key `disks`, and omit it if not found.
@ -894,6 +910,7 @@ By defining `set_if` as [abbreviated lambda function](17-language-reference.md#n
and evaluating the host custom attribute `compellent` containing the `disks` this problem was and evaluating the host custom attribute `compellent` containing the `disks` this problem was
solved like this: solved like this:
```
object CheckCommand "check_compellent" { object CheckCommand "check_compellent" {
command = [ "/usr/bin/check_compellent" ] command = [ "/usr/bin/check_compellent" ]
arguments = { arguments = {
@ -908,6 +925,7 @@ solved like this:
} }
} }
} }
```
This implementation uses the dictionary type method [contains](18-library-reference.md#dictionary-contains) This implementation uses the dictionary type method [contains](18-library-reference.md#dictionary-contains)
and will fail if `host.vars.compellent` is not of the type `Dictionary`. and will fail if `host.vars.compellent` is not of the type `Dictionary`.
@ -915,6 +933,7 @@ Therefore you can extend the checks using the [typeof](17-language-reference.md#
You can test the types using the `icinga2 console`: You can test the types using the `icinga2 console`:
```
# icinga2 console # icinga2 console
Icinga (version: v2.3.0-193-g3eb55ad) Icinga (version: v2.3.0-193-g3eb55ad)
<1> => srv_vars.compellent["check_a"] = { file="outfile_a.json", checks = [ "disks", "fans" ] } <1> => srv_vars.compellent["check_a"] = { file="outfile_a.json", checks = [ "disks", "fans" ] }
@ -924,9 +943,11 @@ You can test the types using the `icinga2 console`:
<3> => typeof(srv_vars.compellent) <3> => typeof(srv_vars.compellent)
type 'Dictionary' type 'Dictionary'
<4> => <4> =>
```
The more programmatic approach for `set_if` could look like this: The more programmatic approach for `set_if` could look like this:
```
"--disks" = { "--disks" = {
set_if = {{ set_if = {{
var srv_vars = service.vars var srv_vars = service.vars
@ -943,7 +964,7 @@ The more programmatic approach for `set_if` could look like this:
} }
}} }}
} }
```
#### Use Functions as Command Attribute <a id="use-functions-command-attribute"></a> #### Use Functions as Command Attribute <a id="use-functions-command-attribute"></a>
@ -955,6 +976,7 @@ The following example was taken from the community support channels. The require
specify a custom attribute inside the notification apply rule and decide which notification specify a custom attribute inside the notification apply rule and decide which notification
script to call based on that. script to call based on that.
```
object User "short-dummy" { object User "short-dummy" {
} }
@ -969,6 +991,7 @@ script to call based on that.
vars.short = true vars.short = true
assign where host.vars.notification.mail assign where host.vars.notification.mail
} }
```
The solution is fairly simple: The `command` attribute is implemented as function returning The solution is fairly simple: The `command` attribute is implemented as function returning
an array required by the caller Icinga 2. an array required by the caller Icinga 2.
@ -980,6 +1003,7 @@ returned.
You can omit the `log()` calls, they only help debugging. You can omit the `log()` calls, they only help debugging.
```
object NotificationCommand "mail-host-notification-test" { object NotificationCommand "mail-host-notification-test" {
command = {{ command = {{
log("command as function") log("command as function")
@ -998,7 +1022,7 @@ You can omit the `log()` calls, they only help debugging.
env = { env = {
} }
} }
```
### Access Object Attributes at Runtime <a id="access-object-attributes-at-runtime"></a> ### Access Object Attributes at Runtime <a id="access-object-attributes-at-runtime"></a>

View File

@ -396,12 +396,14 @@ Configuration Attributes:
Available state filters: Available state filters:
```
OK OK
Warning Warning
Critical Critical
Unknown Unknown
Up Up
Down Down
```
When using [apply rules](03-monitoring-basics.md#using-apply) for dependencies, you can leave out certain attributes which will be When using [apply rules](03-monitoring-basics.md#using-apply) for dependencies, you can leave out certain attributes which will be
automatically determined by Icinga 2. automatically determined by Icinga 2.
@ -1154,18 +1156,23 @@ Configuration Attributes:
Available notification state filters for Service: Available notification state filters for Service:
```
OK OK
Warning Warning
Critical Critical
Unknown Unknown
```
Available notification state filters for Host: Available notification state filters for Host:
```
Up Up
Down Down
```
Available notification type filters: Available notification type filters:
```
DowntimeStart DowntimeStart
DowntimeEnd DowntimeEnd
DowntimeRemoved DowntimeRemoved
@ -1175,6 +1182,7 @@ Available notification type filters:
Recovery Recovery
FlappingStart FlappingStart
FlappingEnd FlappingEnd
```
Runtime Attributes: Runtime Attributes:
@ -1687,15 +1695,18 @@ object User "icingaadmin" {
Available notification state filters: Available notification state filters:
```
OK OK
Warning Warning
Critical Critical
Unknown Unknown
Up Up
Down Down
```
Available notification type filters: Available notification type filters:
```
DowntimeStart DowntimeStart
DowntimeEnd DowntimeEnd
DowntimeRemoved DowntimeRemoved
@ -1705,6 +1716,7 @@ Available notification type filters:
Recovery Recovery
FlappingStart FlappingStart
FlappingEnd FlappingEnd
```
Configuration Attributes: Configuration Attributes:

View File

@ -25,7 +25,9 @@ You are advised to create your own CheckCommand definitions in
By default the generic templates are included in the [icinga2.conf](04-configuring-icinga-2.md#icinga2-conf) configuration file: By default the generic templates are included in the [icinga2.conf](04-configuring-icinga-2.md#icinga2-conf) configuration file:
```
include <itl> include <itl>
```
These templates are imported by the provided example configuration. These templates are imported by the provided example configuration.

View File

@ -7,11 +7,15 @@ You can run the CLI command `icinga2 api setup` to enable the
certificates as well as a new API user `root` with an auto-generated password in the certificates as well as a new API user `root` with an auto-generated password in the
`/etc/icinga2/conf.d/api-users.conf` configuration file: `/etc/icinga2/conf.d/api-users.conf` configuration file:
```
# icinga2 api setup # icinga2 api setup
```
Make sure to restart Icinga 2 to enable the changes you just made: Make sure to restart Icinga 2 to enable the changes you just made:
```
# service icinga2 restart # service icinga2 restart
```
If you prefer to set up the API manually, you will have to perform the following steps: If you prefer to set up the API manually, you will have to perform the following steps:
@ -60,7 +64,9 @@ Supported request methods:
All requests apart from `GET` require that the following `Accept` header is set: All requests apart from `GET` require that the following `Accept` header is set:
```
Accept: application/json Accept: application/json
```
Each URL is prefixed with the API version (currently "/v1"). Each URL is prefixed with the API version (currently "/v1").
@ -74,7 +80,7 @@ list. Depending on the number of affected objects in your request, the
The output will be sent back as a JSON object: The output will be sent back as a JSON object:
```
{ {
"results": [ "results": [
{ {
@ -83,6 +89,7 @@ The output will be sent back as a JSON object:
} }
] ]
} }
```
> **Tip** > **Tip**
> >
@ -132,34 +139,42 @@ In order to configure a new API user you'll need to add a new [ApiUser](09-objec
configuration object. In this example `root` will be the basic auth username configuration object. In this example `root` will be the basic auth username
and the `password` attribute contains the basic auth password. and the `password` attribute contains the basic auth password.
```
# vim /etc/icinga2/conf.d/api-users.conf # vim /etc/icinga2/conf.d/api-users.conf
object ApiUser "root" { object ApiUser "root" {
password = "icinga" password = "icinga"
} }
```
Alternatively you can use X.509 client certificates by specifying the `client_cn` Alternatively you can use X.509 client certificates by specifying the `client_cn`
the API should trust. The X.509 certificate has to be signed by the CA certificate the API should trust. The X.509 certificate has to be signed by the CA certificate
that is configured in the [ApiListener](09-object-types.md#objecttype-apilistener) object. that is configured in the [ApiListener](09-object-types.md#objecttype-apilistener) object.
```
# vim /etc/icinga2/conf.d/api-users.conf # vim /etc/icinga2/conf.d/api-users.conf
object ApiUser "root" { object ApiUser "root" {
client_cn = "CertificateCommonName" client_cn = "CertificateCommonName"
} }
```
An `ApiUser` object can have both authentication methods configured. An `ApiUser` object can have both authentication methods configured.
You can test authentication by sending a GET request to the API: You can test authentication by sending a GET request to the API:
```
$ curl -k -s -u root:icinga 'https://localhost:5665/v1' $ curl -k -s -u root:icinga 'https://localhost:5665/v1'
```
In case you get an error message make sure to check the API user credentials. In case you get an error message make sure to check the API user credentials.
When using client certificates for authentication you'll need to pass your client certificate When using client certificates for authentication you'll need to pass your client certificate
and private key to the curl call: and private key to the curl call:
```
$ curl -k --cert example.localdomain.crt --key example.localdomain.key 'https://example.localdomain:5665/v1/status' $ curl -k --cert example.localdomain.crt --key example.localdomain.key 'https://example.localdomain:5665/v1/status'
```
In case of an error make sure to verify the client certificate and CA. In case of an error make sure to verify the client certificate and CA.
@ -167,7 +182,9 @@ The curl parameter `-k` disables certificate verification and should therefore
only be used for testing. In order to securely check each connection you'll need to only be used for testing. In order to securely check each connection you'll need to
specify the trusted CA certificate using the curl parameter`--cacert`: specify the trusted CA certificate using the curl parameter`--cacert`:
```
$ curl -u root:icinga --cacert ca.crt 'icinga2.node1.localdomain:5665/v1' $ curl -u root:icinga --cacert ca.crt 'icinga2.node1.localdomain:5665/v1'
```
Read the next chapter on [API permissions](12-icinga2-api.md#icinga2-api-permissions) Read the next chapter on [API permissions](12-icinga2-api.md#icinga2-api-permissions)
in order to configure authorization settings for your newly created API user. in order to configure authorization settings for your newly created API user.
@ -185,12 +202,16 @@ The permission system mainly relies on the url scheme of the API endpoints (See
Example for an API user with all permissions: Example for an API user with all permissions:
```
permissions = [ "*" ] permissions = [ "*" ]
```
Note that you can use wildcards to include all possible hierarchically lower items. Here's another example that only allows the user Note that you can use wildcards to include all possible hierarchically lower items. Here's another example that only allows the user
to perform read-only object queries for hosts and services: to perform read-only object queries for hosts and services:
```
permissions = [ "objects/query/Host", "objects/query/Service" ] permissions = [ "objects/query/Host", "objects/query/Service" ]
```
You can also further restrict permissions by specifying a filter expression. The You can also further restrict permissions by specifying a filter expression. The
filter expression has to be a [lambda function](17-language-reference.md#nullary-lambdas) filter expression has to be a [lambda function](17-language-reference.md#nullary-lambdas)
@ -200,6 +221,7 @@ The following example allows the API user to query all hosts and services which
custom attribute `os` that matches the regular expression `^Linux`. custom attribute `os` that matches the regular expression `^Linux`.
The [regex function](18-library-reference.md#global-functions-regex) is available as global function. The [regex function](18-library-reference.md#global-functions-regex) is available as global function.
```
permissions = [ permissions = [
{ {
permission = "objects/query/Host" permission = "objects/query/Host"
@ -210,6 +232,7 @@ The [regex function](18-library-reference.md#global-functions-regex) is availabl
filter = {{ regex("^Linux", service.vars.os) }} filter = {{ regex("^Linux", service.vars.os) }}
} }
] ]
```
More information about filters can be found in the [filters](12-icinga2-api.md#icinga2-api-filters) chapter. More information about filters can be found in the [filters](12-icinga2-api.md#icinga2-api-filters) chapter.
@ -248,11 +271,15 @@ as query string, e.g. a space character becomes `%20`.
Example for a URL-encoded query string: Example for a URL-encoded query string:
```
/v1/objects/hosts?filter=match(%22example.localdomain*%22,host.name)&attrs=name&attrs=state /v1/objects/hosts?filter=match(%22example.localdomain*%22,host.name)&attrs=name&attrs=state
```
Here are the exact same query parameters as a JSON object: Here are the exact same query parameters as a JSON object:
```
{ "filter": "match(\"example.localdomain*\",host.name)", "attrs": [ "host.name", "host.state" ] } { "filter": "match(\"example.localdomain*\",host.name)", "attrs": [ "host.name", "host.state" ] }
```
The [match function](18-library-reference.md#global-functions-match) is available as global function The [match function](18-library-reference.md#global-functions-match) is available as global function
in Icinga 2. in Icinga 2.
@ -286,11 +313,15 @@ header. This comes in handy when you are using HTTP proxies disallowing `PUT` or
Query an existing object by sending a `POST` request with `X-HTTP-Method-Override: GET` as request header: Query an existing object by sending a `POST` request with `X-HTTP-Method-Override: GET` as request header:
```
$ curl -k -s -u 'root:icinga' -H 'Accept: application/json' -X POST -H 'X-HTTP-Method-Override: GET' 'https://localhost:5665/v1/objects/hosts' $ curl -k -s -u 'root:icinga' -H 'Accept: application/json' -X POST -H 'X-HTTP-Method-Override: GET' 'https://localhost:5665/v1/objects/hosts'
```
Delete an existing object by sending a `POST` request with `X-HTTP-Method-Override: DELETE` as request header: Delete an existing object by sending a `POST` request with `X-HTTP-Method-Override: DELETE` as request header:
```
$ curl -k -s -u 'root:icinga' -H 'Accept: application/json' -X POST -H 'X-HTTP-Method-Override: DELETE' 'https://localhost:5665/v1/objects/hosts/example.localdomain' $ curl -k -s -u 'root:icinga' -H 'Accept: application/json' -X POST -H 'X-HTTP-Method-Override: DELETE' 'https://localhost:5665/v1/objects/hosts/example.localdomain'
```
### Filters <a id="icinga2-api-filters"></a> ### Filters <a id="icinga2-api-filters"></a>
@ -299,11 +330,15 @@ Delete an existing object by sending a `POST` request with `X-HTTP-Method-Overri
By default actions and queries operate on all objects unless further restricted by the user. For By default actions and queries operate on all objects unless further restricted by the user. For
example, the following query returns all `Host` objects: example, the following query returns all `Host` objects:
```
https://localhost:5665/v1/objects/hosts https://localhost:5665/v1/objects/hosts
```
If you're only interested in a single object, you can limit the output to that object by specifying its name: If you're only interested in a single object, you can limit the output to that object by specifying its name:
```
https://localhost:5665/v1/objects/hosts?host=localhost https://localhost:5665/v1/objects/hosts?host=localhost
```
**The name of the URL parameter is the lower-case version of the type the query applies to.** For **The name of the URL parameter is the lower-case version of the type the query applies to.** For
example, for `Host` objects the URL parameter therefore is `host`, for `Service` objects it is example, for `Host` objects the URL parameter therefore is `host`, for `Service` objects it is
@ -311,14 +346,18 @@ example, for `Host` objects the URL parameter therefore is `host`, for `Service`
You can also specify multiple objects: You can also specify multiple objects:
```
https://localhost:5665/v1/objects/hosts?hosts=first-host&hosts=second-host https://localhost:5665/v1/objects/hosts?hosts=first-host&hosts=second-host
```
Again -- like in the previous example -- the name of the URL parameter is the lower-case version of the type. However, because we're specifying multiple objects here the **plural form** of the type is used. Again -- like in the previous example -- the name of the URL parameter is the lower-case version of the type. However, because we're specifying multiple objects here the **plural form** of the type is used.
When specifying names for objects which have composite names like for example services the When specifying names for objects which have composite names like for example services the
full name has to be used: full name has to be used:
```
https://localhost:5665/v1/objects/services?service=localhost!ping6 https://localhost:5665/v1/objects/services?service=localhost!ping6
```
The full name of an object can be obtained by looking at the `__name` attribute. The full name of an object can be obtained by looking at the `__name` attribute.
@ -336,15 +375,20 @@ Advanced filters allow users to filter objects using lambda expressions. The syn
Example matching all services in NOT-OK state: Example matching all services in NOT-OK state:
```
https://localhost:5665/v1/objects/services?filter=service.state!=ServiceOK https://localhost:5665/v1/objects/services?filter=service.state!=ServiceOK
```
Example [matching](18-library-reference.md#global-functions-match) all hosts by a name string pattern: Example [matching](18-library-reference.md#global-functions-match) all hosts by a name string pattern:
```
https://localhost:5665/v1/objects/hosts?filter=match("example.localdomain*",host.name) https://localhost:5665/v1/objects/hosts?filter=match("example.localdomain*",host.name)
```
Example for all hosts which are in the host group `linux-servers`: Example for all hosts which are in the host group `linux-servers`:
```
https://localhost:5665/v1/objects/hosts?filter="linux-servers" in host.groups https://localhost:5665/v1/objects/hosts?filter="linux-servers" in host.groups
```
User-specified filters are run in a sandbox environment which ensures that filters cannot User-specified filters are run in a sandbox environment which ensures that filters cannot
modify Icinga's state, for example object attributes or global variables. modify Icinga's state, for example object attributes or global variables.
@ -366,8 +410,10 @@ Some queries can be performed for more than just one object type. One example is
action which can be used for both hosts and services. When using advanced filters you will also have to specify the action which can be used for both hosts and services. When using advanced filters you will also have to specify the
type using the `type` parameter: type using the `type` parameter:
```
$ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/actions/reschedule-check' \ $ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/actions/reschedule-check' \
-d '{ "type": "Service", "filter": "service.name==\"ping6\"", "pretty": true }' -d '{ "type": "Service", "filter": "service.name==\"ping6\"", "pretty": true }'
```
When building filters you have to ensure that values such as When building filters you have to ensure that values such as
`"linux-servers"` are escaped properly according to the rules of the Icinga 2 configuration `"linux-servers"` are escaped properly according to the rules of the Icinga 2 configuration
@ -377,8 +423,10 @@ To make using the API in scripts easier you can use the `filter_vars` attribute
variables which should be made available to your filter expression. This way you don't have variables which should be made available to your filter expression. This way you don't have
to worry about escaping values: to worry about escaping values:
```
$ curl -k -s -u 'root:icinga' -H 'Accept: application/json' -H 'X-HTTP-Method-Override: GET' -X POST 'https://localhost:5665/v1/objects/hosts' \ $ curl -k -s -u 'root:icinga' -H 'Accept: application/json' -H 'X-HTTP-Method-Override: GET' -X POST 'https://localhost:5665/v1/objects/hosts' \
-d '{ "filter": "host.vars.os == os", "filter_vars": { "os": "Linux" }, "pretty": true }' -d '{ "filter": "host.vars.os == os", "filter_vars": { "os": "Linux" }, "pretty": true }'
```
We're using [X-HTTP-Method-Override](12-icinga2-api.md#icinga2-api-requests-method-override) here because We're using [X-HTTP-Method-Override](12-icinga2-api.md#icinga2-api-requests-method-override) here because
the HTTP specification does not allow message bodies for GET requests. the HTTP specification does not allow message bodies for GET requests.
@ -421,7 +469,9 @@ a `GET` query to the `/v1/objects/<type>` URL endpoint. `<type` has
to be replaced with the plural name of the object type you are interested to be replaced with the plural name of the object type you are interested
in: in:
```
$ curl -k -s -u root:icinga 'https://localhost:5665/v1/objects/hosts' $ curl -k -s -u root:icinga 'https://localhost:5665/v1/objects/hosts'
```
A list of all available configuration types is available in the A list of all available configuration types is available in the
[object types](09-object-types.md#object-types) chapter. [object types](09-object-types.md#object-types) chapter.
@ -440,10 +490,13 @@ Instead of using a filter you can optionally specify the object name in the
URL path when querying a single object. For objects with composite names URL path when querying a single object. For objects with composite names
(e.g. services) the full name (e.g. `example.localdomain!http`) must be specified: (e.g. services) the full name (e.g. `example.localdomain!http`) must be specified:
```
$ curl -k -s -u root:icinga 'https://localhost:5665/v1/objects/services/example.localdomain!http' $ curl -k -s -u root:icinga 'https://localhost:5665/v1/objects/services/example.localdomain!http'
```
You can limit the output to specific attributes using the `attrs` URL parameter: You can limit the output to specific attributes using the `attrs` URL parameter:
```
$ curl -k -s -u root:icinga 'https://localhost:5665/v1/objects/hosts/example.localdomain?attrs=name&attrs=address&pretty=1' $ curl -k -s -u root:icinga 'https://localhost:5665/v1/objects/hosts/example.localdomain?attrs=name&attrs=address&pretty=1'
{ {
"results": [ "results": [
@ -459,6 +512,7 @@ You can limit the output to specific attributes using the `attrs` URL parameter:
} }
] ]
} }
```
#### Object Queries Result <a id="icinga2-api-config-objects-query-result"></a> #### Object Queries Result <a id="icinga2-api-config-objects-query-result"></a>
@ -479,17 +533,23 @@ information about the host when querying service objects.
The following query retrieves all host attributes: The following query retrieves all host attributes:
```
https://localhost:5665/v1/objects/services?joins=host https://localhost:5665/v1/objects/services?joins=host
```
Instead of requesting all host attributes you can also limit the output to specific Instead of requesting all host attributes you can also limit the output to specific
attributes: attributes:
```
https://localhost:5665/v1/objects/services?joins=host.name&joins=host.address https://localhost:5665/v1/objects/services?joins=host.name&joins=host.address
```
You can request that all available joins are returned in the result set by using You can request that all available joins are returned in the result set by using
the `all_joins` query parameter. the `all_joins` query parameter.
```
https://localhost:5665/v1/objects/services?all_joins=1 https://localhost:5665/v1/objects/services?all_joins=1
```
> **Note** > **Note**
> >
@ -512,6 +572,7 @@ custom attribute set to `Linux`. The result set contains the `display_name` and
attributes for the service. The query also returns the host's `name` and `address` attribute attributes for the service. The query also returns the host's `name` and `address` attribute
via a join: via a join:
```
$ curl -k -s -u root:icinga 'https://localhost:5665/v1/objects/services?attrs=display_name&attrs=check_command&joins=host.name&joins=host.address&filter=host.vars.os==%22Linux%22&pretty=1' $ curl -k -s -u root:icinga 'https://localhost:5665/v1/objects/services?attrs=display_name&attrs=check_command&joins=host.name&joins=host.address&filter=host.vars.os==%22Linux%22&pretty=1'
{ {
@ -548,17 +609,21 @@ via a join:
} }
] ]
} }
```
In case you want to fetch all [comments](09-object-types.md#objecttype-comment) In case you want to fetch all [comments](09-object-types.md#objecttype-comment)
for hosts and services, you can use the following query URL (similar example for hosts and services, you can use the following query URL (similar example
for downtimes): for downtimes):
```
https://localhost:5665/v1/objects/comments?joins=host&joins=service https://localhost:5665/v1/objects/comments?joins=host&joins=service
```
This is another example for listing all service objects which are unhandled problems (state is not OK This is another example for listing all service objects which are unhandled problems (state is not OK
and no downtime or acknowledgement set). We're using [X-HTTP-Method-Override](12-icinga2-api.md#icinga2-api-requests-method-override) and no downtime or acknowledgement set). We're using [X-HTTP-Method-Override](12-icinga2-api.md#icinga2-api-requests-method-override)
here because we want to pass all query attributes in the request body. here because we want to pass all query attributes in the request body.
```
$ curl -k -s -u root:icinga -H 'Accept: application/json' -H 'X-HTTP-Method-Override: GET' -X POST 'https://127.0.0.1:5665/v1/objects/services' \ $ curl -k -s -u root:icinga -H 'Accept: application/json' -H 'X-HTTP-Method-Override: GET' -X POST 'https://127.0.0.1:5665/v1/objects/services' \
-d '{ "joins": [ "host.name", "host.address" ], "attrs": [ "name", "state", "downtime_depth", "acknowledgement" ], "filter": "service.state != ServiceOK && service.downtime_depth == 0.0 && service.acknowledgement == 0.0", "pretty": true }' -d '{ "joins": [ "host.name", "host.address" ], "attrs": [ "name", "state", "downtime_depth", "acknowledgement" ], "filter": "service.state != ServiceOK && service.downtime_depth == 0.0 && service.acknowledgement == 0.0", "pretty": true }'
@ -583,11 +648,13 @@ here because we want to pass all query attributes in the request body.
} }
] ]
} }
```
In order to list all acknowledgements without expire time, you query the `/v1/objects/comments` In order to list all acknowledgements without expire time, you query the `/v1/objects/comments`
URL endpoint with `joins` and `filter` request parameters using the [X-HTTP-Method-Override](12-icinga2-api.md#icinga2-api-requests-method-override) URL endpoint with `joins` and `filter` request parameters using the [X-HTTP-Method-Override](12-icinga2-api.md#icinga2-api-requests-method-override)
method: method:
```
$ curl -k -s -u root:icinga -H 'Accept: application/json' -H 'X-HTTP-Method-Override: GET' -X POST 'https://localhost:5665/v1/objects/comments' \ $ curl -k -s -u root:icinga -H 'Accept: application/json' -H 'X-HTTP-Method-Override: GET' -X POST 'https://localhost:5665/v1/objects/comments' \
-d '{ "joins": [ "service.name", "service.acknowledgement", "service.acknowledgement_expiry" ], "attrs": [ "author", "text" ], "filter": "service.acknowledgement!=0 && service.acknowledgement_expiry==0", "pretty": true }' -d '{ "joins": [ "service.name", "service.acknowledgement", "service.acknowledgement_expiry" ], "attrs": [ "author", "text" ], "filter": "service.acknowledgement!=0 && service.acknowledgement_expiry==0", "pretty": true }'
@ -611,6 +678,7 @@ method:
} }
] ]
} }
```
### Creating Config Objects <a id="icinga2-api-config-objects-create"></a> ### Creating Config Objects <a id="icinga2-api-config-objects-create"></a>
@ -628,10 +696,13 @@ the full name (e.g. `example.localdomain!http`) must be specified.
If attributes are of the Dictionary type, you can also use the indexer format. This might be necessary to only override specific custom variables and keep all other existing custom variables (e.g. from templates): If attributes are of the Dictionary type, you can also use the indexer format. This might be necessary to only override specific custom variables and keep all other existing custom variables (e.g. from templates):
```
"attrs": { "vars.os": "Linux" } "attrs": { "vars.os": "Linux" }
```
Example for creating the new host object `example.localdomain`: Example for creating the new host object `example.localdomain`:
```
$ curl -k -s -u root:icinga -H 'Accept: application/json' -X PUT 'https://localhost:5665/v1/objects/hosts/example.localdomain' \ $ curl -k -s -u root:icinga -H 'Accept: application/json' -X PUT 'https://localhost:5665/v1/objects/hosts/example.localdomain' \
-d '{ "templates": [ "generic-host" ], "attrs": { "address": "192.168.1.1", "check_command": "hostalive", "vars.os" : "Linux" }, "pretty": true }' -d '{ "templates": [ "generic-host" ], "attrs": { "address": "192.168.1.1", "check_command": "hostalive", "vars.os" : "Linux" }, "pretty": true }'
{ {
@ -642,11 +713,13 @@ Example for creating the new host object `example.localdomain`:
} }
] ]
} }
```
If the configuration validation fails, the new object will not be created and the response body If the configuration validation fails, the new object will not be created and the response body
contains a detailed error message. The following example is missing the `check_command` attribute contains a detailed error message. The following example is missing the `check_command` attribute
which is required for host objects: which is required for host objects:
```
$ curl -k -s -u root:icinga -H 'Accept: application/json' -X PUT 'https://localhost:5665/v1/objects/hosts/example.localdomain' \ $ curl -k -s -u root:icinga -H 'Accept: application/json' -X PUT 'https://localhost:5665/v1/objects/hosts/example.localdomain' \
-d '{ "attrs": { "address": "192.168.1.1", "vars.os" : "Linux" }, "pretty": true }' -d '{ "attrs": { "address": "192.168.1.1", "vars.os" : "Linux" }, "pretty": true }'
{ {
@ -660,18 +733,21 @@ which is required for host objects:
} }
] ]
} }
```
Service objects must be created using their full name ("hostname!servicename") referencing an existing host object: Service objects must be created using their full name ("hostname!servicename") referencing an existing host object:
```
$ curl -k -s -u root:icinga -H 'Accept: application/json' -X PUT 'https://localhost:5665/v1/objects/services/example.localdomain!realtime-load' \ $ curl -k -s -u root:icinga -H 'Accept: application/json' -X PUT 'https://localhost:5665/v1/objects/services/example.localdomain!realtime-load' \
-d '{ "templates": [ "generic-service" ], "attrs": { "check_command": "load", "check_interval": 1,"retry_interval": 1 } }' -d '{ "templates": [ "generic-service" ], "attrs": { "check_command": "load", "check_interval": 1,"retry_interval": 1 } }'
```
Example for a new CheckCommand object: Example for a new CheckCommand object:
```
$ curl -k -s -u root:icinga -H 'Accept: application/json' -X PUT 'https://localhost:5665/v1/objects/checkcommands/mytest' \ $ curl -k -s -u root:icinga -H 'Accept: application/json' -X PUT 'https://localhost:5665/v1/objects/checkcommands/mytest' \
-d '{ "templates": [ "plugin-check-command" ], "attrs": { "command": [ "/usr/local/sbin/check_http" ], "arguments": { "-I": "$mytest_iparam$" } } }' -d '{ "templates": [ "plugin-check-command" ], "attrs": { "command": [ "/usr/local/sbin/check_http" ], "arguments": { "-I": "$mytest_iparam$" } } }'
```
### Modifying Objects <a id="icinga2-api-config-objects-modify"></a> ### Modifying Objects <a id="icinga2-api-config-objects-modify"></a>
@ -697,10 +773,13 @@ In addition to these parameters a [filter](12-icinga2-api.md#icinga2-api-filters
If attributes are of the Dictionary type, you can also use the indexer format: If attributes are of the Dictionary type, you can also use the indexer format:
```
"attrs": { "vars.os": "Linux" } "attrs": { "vars.os": "Linux" }
```
The following example updates the `address` attribute and the custom attribute `os` for the `example.localdomain` host: The following example updates the `address` attribute and the custom attribute `os` for the `example.localdomain` host:
```
$ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/objects/hosts/example.localdomain' \ $ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/objects/hosts/example.localdomain' \
-d '{ "attrs": { "address": "192.168.1.2", "vars.os" : "Windows" }, "pretty": true }' -d '{ "attrs": { "address": "192.168.1.2", "vars.os" : "Windows" }, "pretty": true }'
{ {
@ -713,7 +792,7 @@ The following example updates the `address` attribute and the custom attribute `
} }
] ]
} }
```
### Deleting Objects <a id="icinga2-api-config-objects-delete"></a> ### Deleting Objects <a id="icinga2-api-config-objects-delete"></a>
@ -728,6 +807,7 @@ In addition to these parameters a [filter](12-icinga2-api.md#icinga2-api-filters
Example for deleting the host object `example.localdomain`: Example for deleting the host object `example.localdomain`:
```
$ curl -k -s -u root:icinga -H 'Accept: application/json' -X DELETE 'https://localhost:5665/v1/objects/hosts/example.localdomain?cascade=1&pretty=1' $ curl -k -s -u root:icinga -H 'Accept: application/json' -X DELETE 'https://localhost:5665/v1/objects/hosts/example.localdomain?cascade=1&pretty=1'
{ {
"results": [ "results": [
@ -739,6 +819,7 @@ Example for deleting the host object `example.localdomain`:
} }
] ]
} }
```
## Config Templates <a id="icinga2-api-config-templates"></a> ## Config Templates <a id="icinga2-api-config-templates"></a>
@ -755,7 +836,9 @@ a `GET` query to the `/v1/templates/<type>` URL endpoint. `<type` has
to be replaced with the plural name of the object type you are interested to be replaced with the plural name of the object type you are interested
in: in:
```
$ curl -k -s -u root:icinga 'https://localhost:5665/v1/templates/hosts' $ curl -k -s -u root:icinga 'https://localhost:5665/v1/templates/hosts'
```
A list of all available configuration types is available in the A list of all available configuration types is available in the
[object types](09-object-types.md#object-types) chapter. [object types](09-object-types.md#object-types) chapter.
@ -767,13 +850,17 @@ check a wildcard string pattern against `tmpl.name`.
The `filter` attribute is passed inside the request body thus requiring to use [X-HTTP-Method-Override](12-icinga2-api.md#icinga2-api-requests-method-override) The `filter` attribute is passed inside the request body thus requiring to use [X-HTTP-Method-Override](12-icinga2-api.md#icinga2-api-requests-method-override)
here. here.
```
$ curl -k -s -u root:icinga -H 'Accept: application/json' -H 'X-HTTP-Method-Override: GET' -X POST 'https://localhost:5661/v1/templates/hosts' \ $ curl -k -s -u root:icinga -H 'Accept: application/json' -H 'X-HTTP-Method-Override: GET' -X POST 'https://localhost:5661/v1/templates/hosts' \
-d '{ "filter": "match(\"g*\", tmpl.name)" }' -d '{ "filter": "match(\"g*\", tmpl.name)" }'
```
Instead of using a filter you can optionally specify the template name in the Instead of using a filter you can optionally specify the template name in the
URL path when querying a single object: URL path when querying a single object:
```
$ curl -k -s -u root:icinga 'https://localhost:5665/v1/templates/hosts/generic-host' $ curl -k -s -u root:icinga 'https://localhost:5665/v1/templates/hosts/generic-host'
```
The result set contains the type, name as well as the location of the template. The result set contains the type, name as well as the location of the template.
@ -788,20 +875,26 @@ Provides methods to manage global variables:
You can request information about global variables by sending You can request information about global variables by sending
a `GET` query to the `/v1/variables/` URL endpoint: a `GET` query to the `/v1/variables/` URL endpoint:
```
$ curl -k -s -u root:icinga 'https://localhost:5665/v1/variables' $ curl -k -s -u root:icinga 'https://localhost:5665/v1/variables'
```
A [filter](12-icinga2-api.md#icinga2-api-filters) may be provided for this query type. The A [filter](12-icinga2-api.md#icinga2-api-filters) may be provided for this query type. The
variable information object can be accessed in the filter using the `variable` variable. variable information object can be accessed in the filter using the `variable` variable.
The `filter` attribute is passed inside the request body thus requiring to use [X-HTTP-Method-Override](12-icinga2-api.md#icinga2-api-requests-method-override) The `filter` attribute is passed inside the request body thus requiring to use [X-HTTP-Method-Override](12-icinga2-api.md#icinga2-api-requests-method-override)
here. here.
```
$ curl -k -s -u root:icinga -H 'Accept: application/json' -H 'X-HTTP-Method-Override: GET' -X POST 'https://localhost:5661/v1/variables' \ $ curl -k -s -u root:icinga -H 'Accept: application/json' -H 'X-HTTP-Method-Override: GET' -X POST 'https://localhost:5661/v1/variables' \
-d '{ "filter": "variable.type in [ \"String\", \"Number\" ]" }' -d '{ "filter": "variable.type in [ \"String\", \"Number\" ]" }'
```
Instead of using a filter you can optionally specify the variable name in the Instead of using a filter you can optionally specify the variable name in the
URL path when querying a single variable: URL path when querying a single variable:
```
$ curl -k -s -u root:icinga 'https://localhost:5665/v1/variables/PrefixDir' $ curl -k -s -u root:icinga 'https://localhost:5665/v1/variables/PrefixDir'
```
The result set contains the type, name and value of the global variable. The result set contains the type, name and value of the global variable.
@ -823,7 +916,9 @@ notification on a program-wide basis must be applied by updating the
[IcingaApplication object](12-icinga2-api.md#icinga2-api-config-objects) [IcingaApplication object](12-icinga2-api.md#icinga2-api-config-objects)
called `app`. called `app`.
```
$ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/objects/icingaapplications/app' -d '{ "attrs": { "enable_notifications": false } }' $ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/objects/icingaapplications/app' -d '{ "attrs": { "enable_notifications": false } }'
```
### process-check-result <a id="icinga2-api-actions-process-check-result"></a> ### process-check-result <a id="icinga2-api-actions-process-check-result"></a>
@ -846,6 +941,7 @@ In addition to these parameters a [filter](12-icinga2-api.md#icinga2-api-filters
Example for the service `passive-ping6`: Example for the service `passive-ping6`:
```
$ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/actions/process-check-result?service=example.localdomain!passive-ping6' \ $ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/actions/process-check-result?service=example.localdomain!passive-ping6' \
-d '{ "exit_status": 2, "plugin_output": "PING CRITICAL - Packet loss = 100%", "performance_data": [ "rta=5000.000000ms;3000.000000;5000.000000;0.000000", "pl=100%;80;100;0" ], "check_source": "example.localdomain", "pretty": true }' -d '{ "exit_status": 2, "plugin_output": "PING CRITICAL - Packet loss = 100%", "performance_data": [ "rta=5000.000000ms;3000.000000;5000.000000;0.000000", "pl=100%;80;100;0" ], "check_source": "example.localdomain", "pretty": true }'
@ -857,11 +953,14 @@ Example for the service `passive-ping6`:
} }
] ]
} }
```
Example for using the `Host` type and filter by the host name: Example for using the `Host` type and filter by the host name:
```
$ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/actions/process-check-result' \ $ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/actions/process-check-result' \
-d '{ "filter": "host.name==\"example.localdomain\"", "type": "Host", "exit_status": 1, "plugin_output": "Host is not available." }' -d '{ "filter": "host.name==\"example.localdomain\"", "type": "Host", "exit_status": 1, "plugin_output": "Host is not available." }'
```
You can avoid URL encoding of white spaces in object names by using the `filter` attribute in the request body. You can avoid URL encoding of white spaces in object names by using the `filter` attribute in the request body.
@ -888,6 +987,7 @@ The example reschedules all services with the name "ping6" to immediately perfor
(`next_check` default), ignoring any time periods or whether active checks are (`next_check` default), ignoring any time periods or whether active checks are
allowed for the service (`force=true`). allowed for the service (`force=true`).
```
$ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/actions/reschedule-check' \ $ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/actions/reschedule-check' \
-d '{ "type": "Service", "filter": "service.name==\"ping6\"", "force": true, "pretty": true }' -d '{ "type": "Service", "filter": "service.name==\"ping6\"", "force": true, "pretty": true }'
@ -899,7 +999,7 @@ allowed for the service (`force=true`).
} }
] ]
} }
```
### send-custom-notification <a id="icinga2-api-actions-send-custom-notification"></a> ### send-custom-notification <a id="icinga2-api-actions-send-custom-notification"></a>
@ -919,6 +1019,7 @@ In addition to these parameters a [filter](12-icinga2-api.md#icinga2-api-filters
Example for a custom host notification announcing a global maintenance to Example for a custom host notification announcing a global maintenance to
host owners: host owners:
```
$ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/actions/send-custom-notification' \ $ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/actions/send-custom-notification' \
-d '{ "type": "Host", "author": "icingaadmin", "comment": "System is going down for maintenance", "force": true, "pretty": true }' -d '{ "type": "Host", "author": "icingaadmin", "comment": "System is going down for maintenance", "force": true, "pretty": true }'
@ -933,6 +1034,7 @@ host owners:
"status": "Successfully sent custom notification for object 'host1'." "status": "Successfully sent custom notification for object 'host1'."
} }
} }
```
### delay-notification <a id="icinga2-api-actions-delay-notification"></a> ### delay-notification <a id="icinga2-api-actions-delay-notification"></a>
@ -951,6 +1053,7 @@ In addition to these parameters a [filter](12-icinga2-api.md#icinga2-api-filters
Example: Example:
```
$ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/actions/delay-notification' \ $ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/actions/delay-notification' \
-d '{ "type": "Service", "timestamp": 1446389894, "pretty": true }' -d '{ "type": "Service", "timestamp": 1446389894, "pretty": true }'
@ -965,6 +1068,7 @@ Example:
"status": "Successfully delayed notifications for object 'host1!service1'." "status": "Successfully delayed notifications for object 'host1!service1'."
} }
} }
```
### acknowledge-problem <a id="icinga2-api-actions-acknowledge-problem"></a> ### acknowledge-problem <a id="icinga2-api-actions-acknowledge-problem"></a>
@ -988,6 +1092,7 @@ In addition to these parameters a [filter](12-icinga2-api.md#icinga2-api-filters
The following example acknowledges all services which are in a hard critical state and sends out The following example acknowledges all services which are in a hard critical state and sends out
a notification for them: a notification for them:
```
$ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/actions/acknowledge-problem?type=Service&filter=service.state==2&service.state_type=1' \ $ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/actions/acknowledge-problem?type=Service&filter=service.state==2&service.state_type=1' \
-d '{ "author": "icingaadmin", "comment": "Global outage. Working on it.", "notify": true, "pretty": true }' -d '{ "author": "icingaadmin", "comment": "Global outage. Working on it.", "notify": true, "pretty": true }'
@ -1002,7 +1107,7 @@ a notification for them:
"status": "Successfully acknowledged problem for object 'example.localdomain!ping4'." "status": "Successfully acknowledged problem for object 'example.localdomain!ping4'."
} }
} }
```
### remove-acknowledgement <a id="icinga2-api-actions-remove-acknowledgement"></a> ### remove-acknowledgement <a id="icinga2-api-actions-remove-acknowledgement"></a>
@ -1015,6 +1120,7 @@ A [filter](12-icinga2-api.md#icinga2-api-filters) must be provided. The valid ty
The example removes all service acknowledgements: The example removes all service acknowledgements:
```
$ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/actions/remove-acknowledgement?type=Service&pretty=1' $ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/actions/remove-acknowledgement?type=Service&pretty=1'
{ {
@ -1028,6 +1134,7 @@ The example removes all service acknowledgements:
"status": "Successfully removed acknowledgement for object 'example2.localdomain!aws-health'." "status": "Successfully removed acknowledgement for object 'example2.localdomain!aws-health'."
} }
} }
```
### add-comment <a id="icinga2-api-actions-add-comment"></a> ### add-comment <a id="icinga2-api-actions-add-comment"></a>
@ -1044,6 +1151,7 @@ In addition to these parameters a [filter](12-icinga2-api.md#icinga2-api-filters
The following example adds a comment for all `ping4` services: The following example adds a comment for all `ping4` services:
```
$ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/actions/add-comment?type=Service&filter=service.name==%22ping4%22' -d '{ "author": "icingaadmin", "comment": "Troubleticket #123456789 opened.", "pretty": true }' $ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/actions/add-comment?type=Service&filter=service.name==%22ping4%22' -d '{ "author": "icingaadmin", "comment": "Troubleticket #123456789 opened.", "pretty": true }'
{ {
"results": [ "results": [
@ -1061,6 +1169,7 @@ The following example adds a comment for all `ping4` services:
} }
] ]
} }
```
### remove-comment <a id="icinga2-api-actions-remove-comment"></a> ### remove-comment <a id="icinga2-api-actions-remove-comment"></a>
@ -1075,6 +1184,7 @@ A [filter](12-icinga2-api.md#icinga2-api-filters) must be provided. The valid ty
Example for a simple filter using the `comment` URL parameter: Example for a simple filter using the `comment` URL parameter:
```
$ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/actions/remove-comment?comment=example2.localdomain!ping4!mbmif.local-1446986367-0&pretty=1' $ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/actions/remove-comment?comment=example2.localdomain!ping4!mbmif.local-1446986367-0&pretty=1'
{ {
"results": [ "results": [
@ -1084,9 +1194,11 @@ Example for a simple filter using the `comment` URL parameter:
} }
] ]
} }
```
Example for removing all service comments using a service name filter for `ping4`: Example for removing all service comments using a service name filter for `ping4`:
```
$ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/actions/remove-comment?filter=service.name==%22ping4%22&type=Service&pretty=1' $ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/actions/remove-comment?filter=service.name==%22ping4%22&type=Service&pretty=1'
{ {
"results": [ "results": [
@ -1100,7 +1212,7 @@ Example for removing all service comments using a service name filter for `ping4
} }
] ]
} }
```
### schedule-downtime <a id="icinga2-api-actions-schedule-downtime"></a> ### schedule-downtime <a id="icinga2-api-actions-schedule-downtime"></a>
@ -1123,6 +1235,7 @@ In addition to these parameters a [filter](12-icinga2-api.md#icinga2-api-filters
Example: Example:
```
$ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/actions/schedule-downtime?type=Service&filter=service.name==%22ping4%22' -d '{ "start_time": 1446388806, "end_time": 1446389806, "duration": 1000, "author": "icingaadmin", "comment": "IPv4 network maintenance", "pretty": true }' $ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/actions/schedule-downtime?type=Service&filter=service.name==%22ping4%22' -d '{ "start_time": 1446388806, "end_time": 1446389806, "duration": 1000, "author": "icingaadmin", "comment": "IPv4 network maintenance", "pretty": true }'
{ {
"results": [ "results": [
@ -1140,6 +1253,7 @@ Example:
} }
] ]
} }
```
### remove-downtime <a id="icinga2-api-actions-remove-downtime"></a> ### remove-downtime <a id="icinga2-api-actions-remove-downtime"></a>
@ -1154,6 +1268,7 @@ A [filter](12-icinga2-api.md#icinga2-api-filters) must be provided. The valid ty
Example for a simple filter using the `downtime` URL parameter: Example for a simple filter using the `downtime` URL parameter:
```
$ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/actions/remove-downtime?downtime=example.localdomain!ping4!mbmif.local-1446979168-6&pretty=1' $ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/actions/remove-downtime?downtime=example.localdomain!ping4!mbmif.local-1446979168-6&pretty=1'
{ {
"results": [ "results": [
@ -1163,9 +1278,11 @@ Example for a simple filter using the `downtime` URL parameter:
} }
] ]
} }
```
Example for removing all host downtimes using a host name filter for `example.localdomain`: Example for removing all host downtimes using a host name filter for `example.localdomain`:
```
$ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/actions/remove-downtime?filter=host.name==%22example.localdomain%22&type=Host&pretty=1' $ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/actions/remove-downtime?filter=host.name==%22example.localdomain%22&type=Host&pretty=1'
{ {
"results": [ "results": [
@ -1175,10 +1292,12 @@ Example for removing all host downtimes using a host name filter for `example.lo
} }
] ]
} }
```
Example for removing a downtime from a host but not the services filtered by the author name. This example uses Example for removing a downtime from a host but not the services filtered by the author name. This example uses
filter variables explained in the [advanced filters](12-icinga2-api.md#icinga2-api-advanced-filters) chapter. filter variables explained in the [advanced filters](12-icinga2-api.md#icinga2-api-advanced-filters) chapter.
```
$ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/actions/remove-downtime' \ $ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/actions/remove-downtime' \
-d $'{ -d $'{
"type": "Downtime", "type": "Downtime",
@ -1198,6 +1317,7 @@ filter variables explained in the [advanced filters](12-icinga2-api.md#icinga2-a
} }
] ]
} }
```
### shutdown-process <a id="icinga2-api-actions-shutdown-process"></a> ### shutdown-process <a id="icinga2-api-actions-shutdown-process"></a>
@ -1209,6 +1329,7 @@ This action does not support a target type or filter.
Example: Example:
```
$ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/actions/shutdown-process?pretty=1' $ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/actions/shutdown-process?pretty=1'
{ {
@ -1219,6 +1340,7 @@ Example:
} }
] ]
} }
```
### restart-process <a id="icinga2-api-actions-restart-process"></a> ### restart-process <a id="icinga2-api-actions-restart-process"></a>
@ -1230,6 +1352,7 @@ This action does not support a target type or filter.
Example: Example:
```
$ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/actions/restart-process?pretty=1' $ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/actions/restart-process?pretty=1'
{ {
@ -1240,6 +1363,7 @@ Example:
} }
] ]
} }
```
### generate-ticket <a id="icinga2-api-actions-generate-ticket"></a> ### generate-ticket <a id="icinga2-api-actions-generate-ticket"></a>
@ -1254,6 +1378,7 @@ Send a `POST` request to the URL endpoint `/v1/actions/generate-ticket`.
Example: Example:
```
$ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/actions/generate-ticket' \ $ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/actions/generate-ticket' \
-d '{ "cn": "icinga2-client1.localdomain", "pretty": true }' -d '{ "cn": "icinga2-client1.localdomain", "pretty": true }'
{ {
@ -1265,7 +1390,7 @@ Example:
} }
] ]
} }
```
## Event Streams <a id="icinga2-api-event-streams"></a> ## Event Streams <a id="icinga2-api-event-streams"></a>
@ -1301,7 +1426,9 @@ being set.
Example for all downtime events: Example for all downtime events:
```
&types=DowntimeAdded&types=DowntimeRemoved&types=DowntimeTriggered &types=DowntimeAdded&types=DowntimeRemoved&types=DowntimeTriggered
```
#### <a id="icinga2-api-event-streams-type-checkresult"></a> Event Stream Type: CheckResult #### <a id="icinga2-api-event-streams-type-checkresult"></a> Event Stream Type: CheckResult
@ -1439,13 +1566,16 @@ Event streams can be filtered by attributes using the prefix `event.`.
Example for the `CheckResult` type with the `exit_code` set to `2`: Example for the `CheckResult` type with the `exit_code` set to `2`:
```
&types=CheckResult&filter=event.check_result.exit_status==2 &types=CheckResult&filter=event.check_result.exit_status==2
```
Example for the `CheckResult` type with the service [matching](18-library-reference.md#global-functions-match) Example for the `CheckResult` type with the service [matching](18-library-reference.md#global-functions-match)
the string pattern "random\*": the string pattern "random\*":
```
&types=CheckResult&filter=match%28%22random*%22,event.service%29 &types=CheckResult&filter=match%28%22random*%22,event.service%29
```
### Event Stream Response <a id="icinga2-api-event-streams-response"></a> ### Event Stream Response <a id="icinga2-api-event-streams-response"></a>
@ -1454,12 +1584,13 @@ must support long-polling and HTTP/1.1. HTTP/1.0 is not supported.
Example: Example:
```
$ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/events?queue=michi&types=CheckResult&filter=event.check_result.exit_status==2' $ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/events?queue=michi&types=CheckResult&filter=event.check_result.exit_status==2'
{"check_result":{ ... },"host":"example.localdomain","service":"ping4","timestamp":1445421319.7226390839,"type":"CheckResult"} {"check_result":{ ... },"host":"example.localdomain","service":"ping4","timestamp":1445421319.7226390839,"type":"CheckResult"}
{"check_result":{ ... },"host":"example.localdomain","service":"ping4","timestamp":1445421324.7226390839,"type":"CheckResult"} {"check_result":{ ... },"host":"example.localdomain","service":"ping4","timestamp":1445421324.7226390839,"type":"CheckResult"}
{"check_result":{ ... },"host":"example.localdomain","service":"ping4","timestamp":1445421329.7226390839,"type":"CheckResult"} {"check_result":{ ... },"host":"example.localdomain","service":"ping4","timestamp":1445421329.7226390839,"type":"CheckResult"}
```
## Status and Statistics <a id="icinga2-api-status"></a> ## Status and Statistics <a id="icinga2-api-status"></a>
@ -1467,6 +1598,7 @@ Send a `GET` request to the URL endpoint `/v1/status` to retrieve status informa
Example: Example:
```
$ curl -k -s -u root:icinga 'https://localhost:5665/v1/status?pretty=1' $ curl -k -s -u root:icinga 'https://localhost:5665/v1/status?pretty=1'
{ {
"results": [ "results": [
@ -1484,9 +1616,11 @@ Example:
... ...
] ]
} }
```
You can limit the output by specifying a status type in the URL, e.g. `IcingaApplication`: You can limit the output by specifying a status type in the URL, e.g. `IcingaApplication`:
```
$ curl -k -s -u root:icinga 'https://localhost:5665/v1/status/IcingaApplication?pretty=1' $ curl -k -s -u root:icinga 'https://localhost:5665/v1/status/IcingaApplication?pretty=1'
{ {
"results": [ "results": [
@ -1511,7 +1645,7 @@ You can limit the output by specifying a status type in the URL, e.g. `IcingaApp
} }
] ]
} }
```
## Configuration Management <a id="icinga2-api-config-management"></a> ## Configuration Management <a id="icinga2-api-config-management"></a>
@ -1529,6 +1663,7 @@ can be fetched in a separated request.
Send a `POST` request to a new config package called `example-cmdb` in this example. This Send a `POST` request to a new config package called `example-cmdb` in this example. This
will create a new empty configuration package. will create a new empty configuration package.
```
$ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST \ $ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST \
'https://localhost:5665/v1/config/packages/example-cmdb?pretty=1' 'https://localhost:5665/v1/config/packages/example-cmdb?pretty=1'
{ {
@ -1540,6 +1675,7 @@ will create a new empty configuration package.
} }
] ]
} }
```
Package names starting with an underscore are reserved for internal packages and must not be used. Package names starting with an underscore are reserved for internal packages and must not be used.
@ -1563,17 +1699,22 @@ The file path requires one of these two directories inside its path:
Example for a local configuration in the `conf.d` directory: Example for a local configuration in the `conf.d` directory:
```
"files": { "conf.d/host1.conf": "object Host \"local-host\" { address = \"127.0.0.1\", check_command = \"hostalive\" }" } "files": { "conf.d/host1.conf": "object Host \"local-host\" { address = \"127.0.0.1\", check_command = \"hostalive\" }" }
```
Example for a host configuration inside the `satellite` zone in the `zones.d` directory: Example for a host configuration inside the `satellite` zone in the `zones.d` directory:
```
"files": { "zones.d/satellite/host2.conf": "object Host \"satellite-host\" { address = \"192.168.1.100\", check_command = \"hostalive\" }" } "files": { "zones.d/satellite/host2.conf": "object Host \"satellite-host\" { address = \"192.168.1.100\", check_command = \"hostalive\" }" }
```
The example below will create a new file called `test.conf` in the `conf.d` The example below will create a new file called `test.conf` in the `conf.d`
directory. Note: This example contains an error (`chec_command`). This is directory. Note: This example contains an error (`chec_command`). This is
intentional. intentional.
```
$ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST \ $ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST \
-d '{ "files": { "conf.d/test.conf": "object Host \"cmdb-host\" { chec_command = \"dummy\" }" }, "pretty": true }' \ -d '{ "files": { "conf.d/test.conf": "object Host \"cmdb-host\" { chec_command = \"dummy\" }" }, "pretty": true }' \
'https://localhost:5665/v1/config/stages/example-cmdb' 'https://localhost:5665/v1/config/stages/example-cmdb'
@ -1587,6 +1728,7 @@ intentional.
} }
] ]
} }
```
The Icinga 2 API returns the `package` name this stage was created for, and also The Icinga 2 API returns the `package` name this stage was created for, and also
generates a unique name for the `stage` attribute you'll need for later requests. generates a unique name for the `stage` attribute you'll need for later requests.
@ -1619,6 +1761,7 @@ A list of packages and their stages can be retrieved by sending a `GET` request
The following example contains one configuration package `example-cmdb`. The package does not currently The following example contains one configuration package `example-cmdb`. The package does not currently
have an active stage. have an active stage.
```
$ curl -k -s -u root:icinga 'https://localhost:5665/v1/config/packages?pretty=1' $ curl -k -s -u root:icinga 'https://localhost:5665/v1/config/packages?pretty=1'
{ {
"results": [ "results": [
@ -1631,7 +1774,7 @@ have an active stage.
} }
] ]
} }
```
### List Configuration Package Stage Files <a id="icinga2-api-config-management-list-config-package-stage-files"></a> ### List Configuration Package Stage Files <a id="icinga2-api-config-management-list-config-package-stage-files"></a>
@ -1639,6 +1782,7 @@ In order to retrieve a list of files for a stage you can send a `GET` request to
the URL endpoint `/v1/config/stages`. You need to include the URL endpoint `/v1/config/stages`. You need to include
the package name (`example-cmdb`) and stage name (`example.localdomain-1441625839-0`) in the URL: the package name (`example-cmdb`) and stage name (`example.localdomain-1441625839-0`) in the URL:
```
$ curl -k -s -u root:icinga 'https://localhost:5665/v1/config/stages/example-cmdb/example.localdomain-1441625839-0?pretty=1' $ curl -k -s -u root:icinga 'https://localhost:5665/v1/config/stages/example-cmdb/example.localdomain-1441625839-0?pretty=1'
{ {
"results": [ "results": [
@ -1665,6 +1809,7 @@ the package name (`example-cmdb`) and stage name (`example.localdomain-144162583
} }
] ]
} }
```
### Fetch Configuration Package Stage Files <a id="icinga2-api-config-management-fetch-config-package-stage-files"></a> ### Fetch Configuration Package Stage Files <a id="icinga2-api-config-management-fetch-config-package-stage-files"></a>
@ -1677,9 +1822,11 @@ the package name, the stage name and the relative path to the file to the URL pa
The following example fetches the configuration file `conf.d/test.conf`: The following example fetches the configuration file `conf.d/test.conf`:
```
$ curl -k -s -u root:icinga 'https://localhost:5665/v1/config/files/example-cmdb/example.localdomain-1441625839-0/conf.d/test.conf' $ curl -k -s -u root:icinga 'https://localhost:5665/v1/config/files/example-cmdb/example.localdomain-1441625839-0/conf.d/test.conf'
object Host "cmdb-host" { chec_command = "dummy" } object Host "cmdb-host" { chec_command = "dummy" }
```
You can fetch a [list of existing files](12-icinga2-api.md#icinga2-api-config-management-list-config-package-stage-files) You can fetch a [list of existing files](12-icinga2-api.md#icinga2-api-config-management-list-config-package-stage-files)
in a configuration stage and then specifically request their content. in a configuration stage and then specifically request their content.
@ -1693,6 +1840,7 @@ In order to check for validation errors you can fetch the `startup.log` file
by sending a `GET` request to the URL endpoint `/v1/config/files`. You must include by sending a `GET` request to the URL endpoint `/v1/config/files`. You must include
the package name, stage name and the `startup.log` in the URL path. the package name, stage name and the `startup.log` in the URL path.
```
$ curl -k -s -u root:icinga 'https://localhost:5665/v1/config/files/example-cmdb/example.localdomain-1441133065-1/startup.log' $ curl -k -s -u root:icinga 'https://localhost:5665/v1/config/files/example-cmdb/example.localdomain-1441133065-1/startup.log'
... ...
@ -1702,6 +1850,7 @@ the package name, stage name and the `startup.log` in the URL path.
^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^
critical/config: 1 error critical/config: 1 error
```
The output is similar to the manual [configuration validation](11-cli-commands.md#config-validation). The output is similar to the manual [configuration validation](11-cli-commands.md#config-validation).
@ -1719,6 +1868,7 @@ stage name inside the URL path.
The following example removes the failed configuration stage `example.localdomain-1441133065-1` The following example removes the failed configuration stage `example.localdomain-1441133065-1`
in the `example-cmdb` configuration package: in the `example-cmdb` configuration package:
```
$ curl -k -s -u root:icinga -H 'Accept: application/json' -X DELETE \ $ curl -k -s -u root:icinga -H 'Accept: application/json' -X DELETE \
'https://localhost:5665/v1/config/stages/example-cmdb/example.localdomain-1441133065-1?pretty=1' 'https://localhost:5665/v1/config/stages/example-cmdb/example.localdomain-1441133065-1?pretty=1'
{ {
@ -1729,7 +1879,7 @@ in the `example-cmdb` configuration package:
} }
] ]
} }
```
### Deleting Configuration Package <a id="icinga2-api-config-management-delete-config-package"></a> ### Deleting Configuration Package <a id="icinga2-api-config-management-delete-config-package"></a>
@ -1739,6 +1889,7 @@ with the package name in the URL path.
This example entirely deletes the configuration package `example-cmdb`: This example entirely deletes the configuration package `example-cmdb`:
```
$ curl -k -s -u root:icinga -H 'Accept: application/json' -X DELETE \ $ curl -k -s -u root:icinga -H 'Accept: application/json' -X DELETE \
'https://localhost:5665/v1/config/packages/example-cmdb?pretty=1' 'https://localhost:5665/v1/config/packages/example-cmdb?pretty=1'
{ {
@ -1750,7 +1901,7 @@ This example entirely deletes the configuration package `example-cmdb`:
} }
] ]
} }
```
## Types <a id="icinga2-api-types"></a> ## Types <a id="icinga2-api-types"></a>
@ -1770,6 +1921,7 @@ Each response entry in the results array contains the following attributes:
In order to view a specific configuration object type specify its name inside the URL path: In order to view a specific configuration object type specify its name inside the URL path:
```
$ curl -k -s -u root:icinga 'https://localhost:5665/v1/types/Object?pretty=1' $ curl -k -s -u root:icinga 'https://localhost:5665/v1/types/Object?pretty=1'
{ {
"results": [ "results": [
@ -1800,7 +1952,7 @@ In order to view a specific configuration object type specify its name inside th
} }
] ]
} }
```
## Console <a id="icinga2-api-console"></a> ## Console <a id="icinga2-api-console"></a>
@ -1827,6 +1979,7 @@ If you specify a session identifier, the same script context can be reused for m
Example for fetching the command line from the local host's last check result: Example for fetching the command line from the local host's last check result:
```
$ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/console/execute-script?command=get_host(NodeName).last_check_result.command&sandboxed=0&session=bb75fd7c-c686-407d-9688-582c04227756&pretty=1' $ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/console/execute-script?command=get_host(NodeName).last_check_result.command&sandboxed=0&session=bb75fd7c-c686-407d-9688-582c04227756&pretty=1'
{ {
"results": [ "results": [
@ -1845,10 +1998,12 @@ Example for fetching the command line from the local host's last check result:
} }
] ]
} }
```
Example for fetching auto-completion suggestions for the `Host.` type. This works in a Example for fetching auto-completion suggestions for the `Host.` type. This works in a
similar fashion when pressing TAB inside the [console CLI command](11-cli-commands.md#cli-command-console): similar fashion when pressing TAB inside the [console CLI command](11-cli-commands.md#cli-command-console):
```
$ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/console/auto-complete-script?command=Host.&sandboxed=0&session=bb75fd7c-c686-407d-9688-582c04227756&pretty=1' $ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/console/auto-complete-script?command=Host.&sandboxed=0&session=bb75fd7c-c686-407d-9688-582c04227756&pretty=1'
{ {
"results": [ "results": [
@ -1868,7 +2023,7 @@ similar fashion when pressing TAB inside the [console CLI command](11-cli-comman
} }
] ]
} }
```
## API Clients <a id="icinga2-api-clients"></a> ## API Clients <a id="icinga2-api-clients"></a>
@ -1910,6 +2065,7 @@ on all services with `ping` in their name.
The following example uses **Python** and the `requests` and `json` module: The following example uses **Python** and the `requests` and `json` module:
```
# pip install requests # pip install requests
# pip install json # pip install json
@ -1948,12 +2104,13 @@ The following example uses **Python** and the `requests` and `json` module:
r.raise_for_status() r.raise_for_status()
$ python icinga2-api-example.py $ python icinga2-api-example.py
```
#### Example API Client in Ruby <a id="icinga2-api-clients-programmatic-examples-ruby"></a> #### Example API Client in Ruby <a id="icinga2-api-clients-programmatic-examples-ruby"></a>
The following example uses **Ruby** and the `rest_client` gem: The following example uses **Ruby** and the `rest_client` gem:
```
# gem install rest_client # gem install rest_client
$ vim icinga2-api-example.rb $ vim icinga2-api-example.rb
@ -1996,6 +2153,7 @@ The following example uses **Ruby** and the `rest_client` gem:
end end
$ ruby icinga2-api-example.rb $ ruby icinga2-api-example.rb
```
A more detailed example can be found in the [Dashing demo](https://github.com/Icinga/dashing-icinga2). A more detailed example can be found in the [Dashing demo](https://github.com/Icinga/dashing-icinga2).
@ -2003,6 +2161,7 @@ A more detailed example can be found in the [Dashing demo](https://github.com/Ic
The following example uses **PHP** and its `curl` library: The following example uses **PHP** and its `curl` library:
```
$ vim icinga2-api-example.php $ vim icinga2-api-example.php
#!/usr/bin/env php #!/usr/bin/env php
@ -2049,11 +2208,13 @@ The following example uses **PHP** and its `curl` library:
?> ?>
$ php icinga2-api-example.php $ php icinga2-api-example.php
```
#### Example API Client in Perl <a id="icinga2-api-clients-programmatic-examples-perl"></a> #### Example API Client in Perl <a id="icinga2-api-clients-programmatic-examples-perl"></a>
The following example uses **Perl** and the `Rest::Client` module: The following example uses **Perl** and the `Rest::Client` module:
```
# perl -MCPAN -e 'install REST::Client' # perl -MCPAN -e 'install REST::Client'
# perl -MCPAN -e 'install JSON' # perl -MCPAN -e 'install JSON'
# perl -MCPAN -e 'install MIME::Base64' # perl -MCPAN -e 'install MIME::Base64'
@ -2099,4 +2260,4 @@ The following example uses **Perl** and the `Rest::Client` module:
} }
$ perl icinga2-api-example.pl $ perl icinga2-api-example.pl
```

View File

@ -19,7 +19,9 @@ You need to install Graphite first, then proceed with configuring it in Icinga 2
Use the [GraphiteWriter](14-features.md#graphite-carbon-cache-writer) feature Use the [GraphiteWriter](14-features.md#graphite-carbon-cache-writer) feature
for sending real-time metrics from Icinga 2 to Graphite. for sending real-time metrics from Icinga 2 to Graphite.
```
# icinga2 feature enable graphite # icinga2 feature enable graphite
```
A popular alternative frontend for Graphite is for example [Grafana](https://grafana.org). A popular alternative frontend for Graphite is for example [Grafana](https://grafana.org).
@ -36,7 +38,9 @@ Its written in Go and has no external dependencies.
Use the [InfluxdbWriter](14-features.md#influxdb-writer) feature Use the [InfluxdbWriter](14-features.md#influxdb-writer) feature
for sending real-time metrics from Icinga 2 to InfluxDB. for sending real-time metrics from Icinga 2 to InfluxDB.
```
# icinga2 feature enable influxdb # icinga2 feature enable influxdb
```
A popular frontend for InfluxDB is for example [Grafana](https://grafana.org). A popular frontend for InfluxDB is for example [Grafana](https://grafana.org).
@ -61,11 +65,15 @@ data files which Icinga 2 generates.
Enable performance data writer in icinga 2 Enable performance data writer in icinga 2
```
# icinga2 feature enable perfdata # icinga2 feature enable perfdata
```
Configure npcd to use the performance data created by Icinga 2: Configure npcd to use the performance data created by Icinga 2:
```
vim /etc/pnp4nagios/npcd.cfg vim /etc/pnp4nagios/npcd.cfg
```
Set `perfdata_spool_dir = /var/spool/icinga2/perfdata` and restart the `npcd` daemon. Set `perfdata_spool_dir = /var/spool/icinga2/perfdata` and restart the `npcd` daemon.
@ -120,9 +128,11 @@ based on your monitoring configuration and status data using [NagVis](https://ww
The configuration in nagvis.ini.php should look like this for Livestatus for example: The configuration in nagvis.ini.php should look like this for Livestatus for example:
```
[backend_live_1] [backend_live_1]
backendtype="mklivestatus" backendtype="mklivestatus"
socket="unix:/var/run/icinga2/cmd/livestatus" socket="unix:/var/run/icinga2/cmd/livestatus"
```
If you are planning an integration into Icinga Web 2, look at [this module](https://github.com/Icinga/icingaweb2-module-nagvis). If you are planning an integration into Icinga Web 2, look at [this module](https://github.com/Icinga/icingaweb2-module-nagvis).
@ -190,6 +200,7 @@ These tools are currently in development and require feedback and tests:
They work in a similar fashion for Icinga 2 and are used for 1.x web interfaces (Icinga Web 2 doesn't require They work in a similar fashion for Icinga 2 and are used for 1.x web interfaces (Icinga Web 2 doesn't require
the action url attribute in its own module). the action url attribute in its own module).
```
template Host "pnp-hst" { template Host "pnp-hst" {
action_url = "/pnp4nagios/graph?host=$HOSTNAME$" action_url = "/pnp4nagios/graph?host=$HOSTNAME$"
} }
@ -197,6 +208,7 @@ the action url attribute in its own module).
template Service "pnp-svc" { template Service "pnp-svc" {
action_url = "/pnp4nagios/graph?host=$HOSTNAME$&srv=$SERVICEDESC$" action_url = "/pnp4nagios/graph?host=$HOSTNAME$&srv=$SERVICEDESC$"
} }
```
### PNP Custom Templates with Icinga 2 <a id="addons-graphing-pnp-custom-templates"></a> ### PNP Custom Templates with Icinga 2 <a id="addons-graphing-pnp-custom-templates"></a>
@ -213,6 +225,7 @@ and use that inside the formatting templates as `SERVICECHECKCOMMAND` for instan
Example for services: Example for services:
```
# vim /etc/icinga2/features-enabled/perfdata.conf # vim /etc/icinga2/features-enabled/perfdata.conf
service_format_template = "DATATYPE::SERVICEPERFDATA\tTIMET::$icinga.timet$\tHOSTNAME::$host.name$\tSERVICEDESC::$service.name$\tSERVICEPERFDATA::$service.perfdata$\tSERVICECHECKCOMMAND::$service.check_command$$pnp_check_arg1$\tHOSTSTATE::$host.state$\tHOSTSTATETYPE::$host.state_type$\tSERVICESTATE::$service.state$\tSERVICESTATETYPE::$service.state_type$" service_format_template = "DATATYPE::SERVICEPERFDATA\tTIMET::$icinga.timet$\tHOSTNAME::$host.name$\tSERVICEDESC::$service.name$\tSERVICEPERFDATA::$service.perfdata$\tSERVICECHECKCOMMAND::$service.check_command$$pnp_check_arg1$\tHOSTSTATE::$host.state$\tHOSTSTATETYPE::$host.state_type$\tSERVICESTATE::$service.state$\tSERVICESTATETYPE::$service.state_type$"
@ -231,6 +244,7 @@ Example for services:
vars.pnp_check_arg1 = "!$nrpe_command$" vars.pnp_check_arg1 = "!$nrpe_command$"
} }
```
If there are warnings about unresolved macros, make sure to specify a default value for `vars.pnp_check_arg1` inside the If there are warnings about unresolved macros, make sure to specify a default value for `vars.pnp_check_arg1` inside the

View File

@ -172,7 +172,9 @@ through the web interface).
In order to enable the `ExternalCommandListener` configuration use the In order to enable the `ExternalCommandListener` configuration use the
following command and restart Icinga 2 afterwards: following command and restart Icinga 2 afterwards:
```
# icinga2 feature enable command # icinga2 feature enable command
```
Icinga 2 creates the command pipe file as `/var/run/icinga2/cmd/icinga2.cmd` Icinga 2 creates the command pipe file as `/var/run/icinga2/cmd/icinga2.cmd`
using the default configuration. using the default configuration.
@ -181,12 +183,14 @@ Web interfaces and other Icinga addons are able to send commands to
Icinga 2 through the external command pipe, for example for rescheduling Icinga 2 through the external command pipe, for example for rescheduling
a forced service check: a forced service check:
```
# /bin/echo "[`date +%s`] SCHEDULE_FORCED_SVC_CHECK;localhost;ping4;`date +%s`" >> /var/run/icinga2/cmd/icinga2.cmd # /bin/echo "[`date +%s`] SCHEDULE_FORCED_SVC_CHECK;localhost;ping4;`date +%s`" >> /var/run/icinga2/cmd/icinga2.cmd
# tail -f /var/log/messages # tail -f /var/log/messages
Oct 17 15:01:25 icinga-server icinga2: Executing external command: [1382014885] SCHEDULE_FORCED_SVC_CHECK;localhost;ping4;1382014885 Oct 17 15:01:25 icinga-server icinga2: Executing external command: [1382014885] SCHEDULE_FORCED_SVC_CHECK;localhost;ping4;1382014885
Oct 17 15:01:25 icinga-server icinga2: Rescheduling next check for service 'ping4' Oct 17 15:01:25 icinga-server icinga2: Rescheduling next check for service 'ping4'
```
A list of currently supported external commands can be found [here](24-appendix.md#external-commands-list-detail). A list of currently supported external commands can be found [here](24-appendix.md#external-commands-list-detail).
@ -216,13 +220,17 @@ Therefore the Icinga 2 [PerfdataWriter](09-object-types.md#objecttype-perfdatawr
feature allows you to define the output template format for host and services helped feature allows you to define the output template format for host and services helped
with Icinga 2 runtime vars. with Icinga 2 runtime vars.
```
host_format_template = "DATATYPE::HOSTPERFDATA\tTIMET::$icinga.timet$\tHOSTNAME::$host.name$\tHOSTPERFDATA::$host.perfdata$\tHOSTCHECKCOMMAND::$host.check_command$\tHOSTSTATE::$host.state$\tHOSTSTATETYPE::$host.state_type$" host_format_template = "DATATYPE::HOSTPERFDATA\tTIMET::$icinga.timet$\tHOSTNAME::$host.name$\tHOSTPERFDATA::$host.perfdata$\tHOSTCHECKCOMMAND::$host.check_command$\tHOSTSTATE::$host.state$\tHOSTSTATETYPE::$host.state_type$"
service_format_template = "DATATYPE::SERVICEPERFDATA\tTIMET::$icinga.timet$\tHOSTNAME::$host.name$\tSERVICEDESC::$service.name$\tSERVICEPERFDATA::$service.perfdata$\tSERVICECHECKCOMMAND::$service.check_command$\tHOSTSTATE::$host.state$\tHOSTSTATETYPE::$host.state_type$\tSERVICESTATE::$service.state$\tSERVICESTATETYPE::$service.state_type$" service_format_template = "DATATYPE::SERVICEPERFDATA\tTIMET::$icinga.timet$\tHOSTNAME::$host.name$\tSERVICEDESC::$service.name$\tSERVICEPERFDATA::$service.perfdata$\tSERVICECHECKCOMMAND::$service.check_command$\tHOSTSTATE::$host.state$\tHOSTSTATETYPE::$host.state_type$\tSERVICESTATE::$service.state$\tSERVICESTATETYPE::$service.state_type$"
```
The default templates are already provided with the Icinga 2 feature configuration The default templates are already provided with the Icinga 2 feature configuration
which can be enabled using which can be enabled using
```
# icinga2 feature enable perfdata # icinga2 feature enable perfdata
```
By default all performance data files are rotated in a 15 seconds interval into By default all performance data files are rotated in a 15 seconds interval into
the `/var/spool/icinga2/perfdata/` directory as `host-perfdata.<timestamp>` and the `/var/spool/icinga2/perfdata/` directory as `host-perfdata.<timestamp>` and
@ -240,7 +248,9 @@ write them to the defined Graphite Carbon daemon tcp socket.
You can enable the feature using You can enable the feature using
```
# icinga2 feature enable graphite # icinga2 feature enable graphite
```
By default the [GraphiteWriter](09-object-types.md#objecttype-graphitewriter) feature By default the [GraphiteWriter](09-object-types.md#objecttype-graphitewriter) feature
expects the Graphite Carbon Cache to listen at `127.0.0.1` on TCP port `2003`. expects the Graphite Carbon Cache to listen at `127.0.0.1` on TCP port `2003`.
@ -253,8 +263,10 @@ depends on this schema.
The default prefix for hosts and services is configured using The default prefix for hosts and services is configured using
[runtime macros](03-monitoring-basics.md#runtime-macros)like this: [runtime macros](03-monitoring-basics.md#runtime-macros)like this:
```
icinga2.$host.name$.host.$host.check_command$ icinga2.$host.name$.host.$host.check_command$
icinga2.$host.name$.services.$service.name$.$service.check_command$ icinga2.$host.name$.services.$service.name$.$service.check_command$
```
You can customize the prefix name by using the `host_name_template` and You can customize the prefix name by using the `host_name_template` and
`service_name_template` configuration attributes. `service_name_template` configuration attributes.
@ -274,7 +286,9 @@ The following characters are escaped in prefix labels:
Metric values are stored like this: Metric values are stored like this:
```
<prefix>.perfdata.<perfdata-label>.value <prefix>.perfdata.<perfdata-label>.value
```
The following characters are escaped in perfdata labels: The following characters are escaped in perfdata labels:
@ -292,13 +306,16 @@ and is therefore replaced by `.`.
By enabling `enable_send_thresholds` Icinga 2 automatically adds the following threshold metrics: By enabling `enable_send_thresholds` Icinga 2 automatically adds the following threshold metrics:
```
<prefix>.perfdata.<perfdata-label>.min <prefix>.perfdata.<perfdata-label>.min
<prefix>.perfdata.<perfdata-label>.max <prefix>.perfdata.<perfdata-label>.max
<prefix>.perfdata.<perfdata-label>.warn <prefix>.perfdata.<perfdata-label>.warn
<prefix>.perfdata.<perfdata-label>.crit <prefix>.perfdata.<perfdata-label>.crit
```
By enabling `enable_send_metadata` Icinga 2 automatically adds the following metadata metrics: By enabling `enable_send_metadata` Icinga 2 automatically adds the following metadata metrics:
```
<prefix>.metadata.current_attempt <prefix>.metadata.current_attempt
<prefix>.metadata.downtime_depth <prefix>.metadata.downtime_depth
<prefix>.metadata.acknowledgement <prefix>.metadata.acknowledgement
@ -308,6 +325,7 @@ By enabling `enable_send_metadata` Icinga 2 automatically adds the following met
<prefix>.metadata.reachable <prefix>.metadata.reachable
<prefix>.metadata.state <prefix>.metadata.state
<prefix>.metadata.state_type <prefix>.metadata.state_type
```
Metadata metric overview: Metadata metric overview:
@ -326,10 +344,12 @@ Metadata metric overview:
The following example illustrates how to configure the storage schemas for Graphite Carbon The following example illustrates how to configure the storage schemas for Graphite Carbon
Cache. Cache.
```
[icinga2_default] [icinga2_default]
# intervals like PNP4Nagios uses them per default # intervals like PNP4Nagios uses them per default
pattern = ^icinga2\. pattern = ^icinga2\.
retentions = 1m:2d,5m:10d,30m:90d,360m:4y retentions = 1m:2d,5m:10d,30m:90d,360m:4y
```
### InfluxDB Writer <a id="influxdb-writer"></a> ### InfluxDB Writer <a id="influxdb-writer"></a>
@ -339,7 +359,9 @@ defined InfluxDB HTTP API.
You can enable the feature using You can enable the feature using
```
# icinga2 feature enable influxdb # icinga2 feature enable influxdb
```
By default the [InfluxdbWriter](09-object-types.md#objecttype-influxdbwriter) feature By default the [InfluxdbWriter](09-object-types.md#objecttype-influxdbwriter) feature
expects the InfluxDB daemon to listen at `127.0.0.1` on port `8086`. expects the InfluxDB daemon to listen at `127.0.0.1` on port `8086`.
@ -456,7 +478,9 @@ attribute.
Metric values are stored like this: Metric values are stored like this:
```
check_result.perfdata.<perfdata-label>.value check_result.perfdata.<perfdata-label>.value
```
The following characters are escaped in perfdata labels: The following characters are escaped in perfdata labels:
@ -475,10 +499,12 @@ and is therefore replaced by `.`.
Icinga 2 automatically adds the following threshold metrics Icinga 2 automatically adds the following threshold metrics
if existing: if existing:
```
check_result.perfdata.<perfdata-label>.min check_result.perfdata.<perfdata-label>.min
check_result.perfdata.<perfdata-label>.max check_result.perfdata.<perfdata-label>.max
check_result.perfdata.<perfdata-label>.warn check_result.perfdata.<perfdata-label>.warn
check_result.perfdata.<perfdata-label>.crit check_result.perfdata.<perfdata-label>.crit
```
### Graylog Integration <a id="graylog-integration"></a> ### Graylog Integration <a id="graylog-integration"></a>
@ -494,7 +520,9 @@ While it has been specified by the [Graylog](https://www.graylog.org) project as
You can enable the feature using You can enable the feature using
```
# icinga2 feature enable gelf # icinga2 feature enable gelf
```
By default the `GelfWriter` object expects the GELF receiver to listen at `127.0.0.1` on TCP port `12201`. By default the `GelfWriter` object expects the GELF receiver to listen at `127.0.0.1` on TCP port `12201`.
The default `source` attribute is set to `icinga2`. You can customize that for your needs if required. The default `source` attribute is set to `icinga2`. You can customize that for your needs if required.
@ -514,27 +542,35 @@ write them to the defined TSDB TCP socket.
You can enable the feature using You can enable the feature using
```
# icinga2 feature enable opentsdb # icinga2 feature enable opentsdb
```
By default the `OpenTsdbWriter` object expects the TSD to listen at By default the `OpenTsdbWriter` object expects the TSD to listen at
`127.0.0.1` on port `4242`. `127.0.0.1` on port `4242`.
The current naming schema is The current naming schema is
```
icinga.host.<metricname> icinga.host.<metricname>
icinga.service.<servicename>.<metricname> icinga.service.<servicename>.<metricname>
```
for host and service checks. The tag host is always applied. for host and service checks. The tag host is always applied.
To make sure Icinga 2 writes a valid metric into OpenTSDB some characters are replaced To make sure Icinga 2 writes a valid metric into OpenTSDB some characters are replaced
with `_` in the target name: with `_` in the target name:
```
\ (and space) \ (and space)
```
The resulting name in OpenTSDB might look like: The resulting name in OpenTSDB might look like:
```
www-01 / http-cert / response time www-01 / http-cert / response time
icinga.http_cert.response_time icinga.http_cert.response_time
```
In addition to the performance data retrieved from the check plugin, Icinga 2 sends In addition to the performance data retrieved from the check plugin, Icinga 2 sends
internal check statistic data to OpenTSDB: internal check statistic data to OpenTSDB:
@ -554,7 +590,9 @@ internal check statistic data to OpenTSDB:
While reachable, state and state_type are metrics for the host or service the While reachable, state and state_type are metrics for the host or service the
other metrics follow the current naming schema other metrics follow the current naming schema
```
icinga.check.<metricname> icinga.check.<metricname>
```
with the following tags with the following tags
@ -592,18 +630,24 @@ in the [Livestatus Schema](24-appendix.md#schema-livestatus) section.
You can enable Livestatus using icinga2 feature enable: You can enable Livestatus using icinga2 feature enable:
```
# icinga2 feature enable livestatus # icinga2 feature enable livestatus
```
After that you will have to restart Icinga 2: After that you will have to restart Icinga 2:
```
# systemctl restart icinga2 # systemctl restart icinga2
```
By default the Livestatus socket is available in `/var/run/icinga2/cmd/livestatus`. By default the Livestatus socket is available in `/var/run/icinga2/cmd/livestatus`.
In order for queries and commands to work you will need to add your query user In order for queries and commands to work you will need to add your query user
(e.g. your web server) to the `icingacmd` group: (e.g. your web server) to the `icingacmd` group:
```
# usermod -a -G icingacmd www-data # usermod -a -G icingacmd www-data
```
The Debian packages use `nagios` as the user and group name. Make sure to change `icingacmd` to The Debian packages use `nagios` as the user and group name. Make sure to change `icingacmd` to
`nagios` if you're using Debian. `nagios` if you're using Debian.
@ -615,8 +659,9 @@ In order to use the historical tables provided by the livestatus feature (for ex
are expected to be in `/var/log/icinga2/compat`. A different path can be set using the are expected to be in `/var/log/icinga2/compat`. A different path can be set using the
`compat_log_path` configuration attribute. `compat_log_path` configuration attribute.
```
# icinga2 feature enable compatlog # icinga2 feature enable compatlog
```
### Livestatus Sockets <a id="livestatus-sockets"></a> ### Livestatus Sockets <a id="livestatus-sockets"></a>
@ -642,6 +687,7 @@ programmatically: [Monitoring::Livestatus](http://search.cpan.org/~nierlein/Moni
Example using the unix socket: Example using the unix socket:
```
# echo -e "GET services\n" | /usr/bin/nc -U /var/run/icinga2/cmd/livestatus # echo -e "GET services\n" | /usr/bin/nc -U /var/run/icinga2/cmd/livestatus
Example using the tcp socket listening on port `6558`: Example using the tcp socket listening on port `6558`:
@ -654,14 +700,15 @@ Example using the tcp socket listening on port `6558`:
EOF EOF
(cat servicegroups; sleep 1) | netcat 127.0.0.1 6558 (cat servicegroups; sleep 1) | netcat 127.0.0.1 6558
```
### Livestatus COMMAND Queries <a id="livestatus-command-queries"></a> ### Livestatus COMMAND Queries <a id="livestatus-command-queries"></a>
A list of available external commands and their parameters can be found [here](24-appendix.md#external-commands-list-detail) A list of available external commands and their parameters can be found [here](24-appendix.md#external-commands-list-detail)
```
$ echo -e 'COMMAND <externalcommandstring>' | netcat 127.0.0.1 6558 $ echo -e 'COMMAND <externalcommandstring>' | netcat 127.0.0.1 6558
```
### Livestatus Filters <a id="livestatus-filters"></a> ### Livestatus Filters <a id="livestatus-filters"></a>
@ -696,6 +743,7 @@ Schema: "Stats: aggregatefunction aggregateattribute"
Example: Example:
```
GET hosts GET hosts
Filter: has_been_checked = 1 Filter: has_been_checked = 1
Filter: check_type = 0 Filter: check_type = 0
@ -710,6 +758,7 @@ Example:
Stats: max percent_state_change Stats: max percent_state_change
OutputFormat: json OutputFormat: json
ResponseHeader: fixed16 ResponseHeader: fixed16
```
### Livestatus Output <a id="livestatus-output"></a> ### Livestatus Output <a id="livestatus-output"></a>
@ -721,7 +770,9 @@ is a pipe (2nd level).
Separators can be set using ASCII codes like: Separators can be set using ASCII codes like:
```
Separators: 10 59 44 124 Separators: 10 59 44 124
```
* JSON * JSON
@ -773,7 +824,9 @@ interval to its `objects.cache` and `status.dat` files. Icinga 2 provides
the `StatusDataWriter` object which dumps all configuration objects and the `StatusDataWriter` object which dumps all configuration objects and
status updates in a regular interval. status updates in a regular interval.
```
# icinga2 feature enable statusdata # icinga2 feature enable statusdata
```
If you are not using any web interface or addon which uses these files, If you are not using any web interface or addon which uses these files,
you can safely disable this feature. you can safely disable this feature.
@ -795,7 +848,9 @@ for answering queries to historical tables.
The `CompatLogger` object can be enabled with The `CompatLogger` object can be enabled with
```
# icinga2 feature enable compatlog # icinga2 feature enable compatlog
```
By default, the Icinga 1.x log file called `icinga.log` is located By default, the Icinga 1.x log file called `icinga.log` is located
in `/var/log/icinga2/compat`. Rotated log files are moved into in `/var/log/icinga2/compat`. Rotated log files are moved into
@ -820,7 +875,8 @@ environments, Icinga 2 supports the `CheckResultReader` object.
There is no feature configuration available, but it must be defined There is no feature configuration available, but it must be defined
on-demand in your Icinga 2 objects configuration. on-demand in your Icinga 2 objects configuration.
```
object CheckResultReader "reader" { object CheckResultReader "reader" {
spool_dir = "/data/check-results" spool_dir = "/data/check-results"
} }
```

View File

@ -547,15 +547,19 @@ settings of the Icinga 2 systemd service by creating
`/etc/systemd/system/icinga2.service.d/override.conf` with the following `/etc/systemd/system/icinga2.service.d/override.conf` with the following
content: content:
```
[Service] [Service]
Restart=always Restart=always
RestartSec=1 RestartSec=1
StartLimitInterval=10 StartLimitInterval=10
StartLimitBurst=3 StartLimitBurst=3
```
Using the watchdog can also help with monitoring Icinga 2, to activate and use it add the following to the override: Using the watchdog can also help with monitoring Icinga 2, to activate and use it add the following to the override:
```
WatchdogSec=30s WatchdogSec=30s
```
This way systemd will kill Icinga 2 if does not notify for over 30 seconds, a timout of less than 10 seconds is not This way systemd will kill Icinga 2 if does not notify for over 30 seconds, a timout of less than 10 seconds is not
recommended. When the watchdog is activated, `Restart=` can be set to `watchdog` to restart Icinga 2 in the case of a recommended. When the watchdog is activated, `Restart=` can be set to `watchdog` to restart Icinga 2 in the case of a

View File

@ -5,12 +5,14 @@
Icinga 2 features an object-based configuration format. You can define new Icinga 2 features an object-based configuration format. You can define new
objects using the `object` keyword: objects using the `object` keyword:
```
object Host "host1.example.org" { object Host "host1.example.org" {
display_name = "host1" display_name = "host1"
address = "192.168.0.1" address = "192.168.0.1"
address6 = "2001:db8:1234::42" address6 = "2001:db8:1234::42"
} }
```
In general you need to write each statement on a new line. Expressions started In general you need to write each statement on a new line. Expressions started
with `{`, `(` and `[` extend until the matching closing character and can be broken with `{`, `(` and `[` extend until the matching closing character and can be broken
@ -19,11 +21,13 @@ up into multiple lines.
Alternatively you can write multiple statements on a single line by separating Alternatively you can write multiple statements on a single line by separating
them with a semicolon: them with a semicolon:
```
object Host "host1.example.org" { object Host "host1.example.org" {
display_name = "host1" display_name = "host1"
address = "192.168.0.1"; address6 = "2001:db8:1234::42" address = "192.168.0.1"; address6 = "2001:db8:1234::42"
} }
```
Each object is uniquely identified by its type (`Host`) and name Each object is uniquely identified by its type (`Host`) and name
(`host1.example.org`). Some types have composite names, e.g. the (`host1.example.org`). Some types have composite names, e.g. the
@ -53,7 +57,9 @@ A floating-point number.
Example: Example:
```
27.3 27.3
```
### Duration Literals <a id="duration-literals"></a> ### Duration Literals <a id="duration-literals"></a>
@ -62,7 +68,9 @@ suffixes to help with specifying time durations.
Example: Example:
```
2.5m 2.5m
```
Supported suffixes include ms (milliseconds), s (seconds), m (minutes), Supported suffixes include ms (milliseconds), s (seconds), m (minutes),
h (hours) and d (days). h (hours) and d (days).
@ -76,7 +84,9 @@ A string.
Example: Example:
```
"Hello World!" "Hello World!"
```
#### String Literals Escape Sequences <a id="string-literals-escape-sequences"></a> #### String Literals Escape Sequences <a id="string-literals-escape-sequences"></a>
@ -104,10 +114,12 @@ Strings spanning multiple lines can be specified by enclosing them in
Example: Example:
```
{{{This {{{This
is is
a multi-line a multi-line
string.}}} string.}}}
```
Unlike in ordinary strings special characters do not have to be escaped Unlike in ordinary strings special characters do not have to be escaped
in multi-line string literals. in multi-line string literals.
@ -130,10 +142,12 @@ The comma after the last key-value pair is optional.
Example: Example:
```
{ {
address = "192.168.0.1" address = "192.168.0.1"
port = 443 port = 443
} }
```
Identifiers may not contain certain characters (e.g. space) or start Identifiers may not contain certain characters (e.g. space) or start
with certain characters (e.g. digits). If you want to use a dictionary with certain characters (e.g. digits). If you want to use a dictionary
@ -149,7 +163,9 @@ The comma after the last element is optional.
Example: Example:
```
[ "hello", 42 ] [ "hello", 42 ]
```
An array may simultaneously contain values of different types, such as An array may simultaneously contain values of different types, such as
strings and numbers. strings and numbers.
@ -198,36 +214,46 @@ Operator | Precedence | Examples (Result) | Descript
A reference to a value can be obtained using the `&` operator. The `*` operator can be used A reference to a value can be obtained using the `&` operator. The `*` operator can be used
to dereference a reference: to dereference a reference:
```
var value = "Hello!" var value = "Hello!"
var p = &value /* p refers to value */ var p = &value /* p refers to value */
*p = "Hi!" *p = "Hi!"
log(value) // Prints "Hi!" because the variable was changed log(value) // Prints "Hi!" because the variable was changed
```
### Namespaces <a id="namespaces"></a> ### Namespaces <a id="namespaces"></a>
Namespaces can be used to organize variables and functions. They are used to avoid name conflicts. The `namespace` Namespaces can be used to organize variables and functions. They are used to avoid name conflicts. The `namespace`
keyword is used to create a new namespace: keyword is used to create a new namespace:
```
namespace Utils { namespace Utils {
function calculate() { function calculate() {
return 2 + 2 return 2 + 2
} }
} }
```
The namespace is made available as a global variable which has the namespace's name (e.g. `Utils`): The namespace is made available as a global variable which has the namespace's name (e.g. `Utils`):
```
Utils.calculate() Utils.calculate()
```
The `using` keyword can be used to make all attributes in a namespace available to a script without having to The `using` keyword can be used to make all attributes in a namespace available to a script without having to
explicitly specify the namespace's name for each access: explicitly specify the namespace's name for each access:
```
using Utils using Utils
calculate() calculate()
```
The `using` keyword only has an effect for the current file and only for code that follows the keyword: The `using` keyword only has an effect for the current file and only for code that follows the keyword:
```
calculate() // This will not work. calculate() // This will not work.
using Utils using Utils
```
The following namespaces are automatically imported as if by using the `using` keyword: The following namespaces are automatically imported as if by using the `using` keyword:
@ -240,11 +266,13 @@ The following namespaces are automatically imported as if by using the `using` k
Functions can be called using the `()` operator: Functions can be called using the `()` operator:
```
const MyGroups = [ "test1", "test" ] const MyGroups = [ "test1", "test" ]
{ {
check_interval = len(MyGroups) * 1m check_interval = len(MyGroups) * 1m
} }
```
A list of available functions is available in the [Library Reference](18-library-reference.md#library-reference) chapter. A list of available functions is available in the [Library Reference](18-library-reference.md#library-reference) chapter.
@ -260,10 +288,12 @@ Sets an attribute to the specified value.
Example: Example:
```
{ {
a = 5 a = 5
a = 7 a = 7
} }
```
In this example `a` has the value `7` after both instructions are executed. In this example `a` has the value `7` after both instructions are executed.
@ -271,65 +301,81 @@ In this example `a` has the value `7` after both instructions are executed.
The += operator is a shortcut. The following expression: The += operator is a shortcut. The following expression:
```
{ {
a = [ "hello" ] a = [ "hello" ]
a += [ "world" ] a += [ "world" ]
} }
```
is equivalent to: is equivalent to:
```
{ {
a = [ "hello" ] a = [ "hello" ]
a = a + [ "world" ] a = a + [ "world" ]
} }
```
### Operator -= <a id="operator-substractive-assignment"></a> ### Operator -= <a id="operator-substractive-assignment"></a>
The -= operator is a shortcut. The following expression: The -= operator is a shortcut. The following expression:
```
{ {
a = 10 a = 10
a -= 5 a -= 5
} }
```
is equivalent to: is equivalent to:
```
{ {
a = 10 a = 10
a = a - 5 a = a - 5
} }
```
### Operator \*= <a id="operator-multiply-assignment"></a> ### Operator \*= <a id="operator-multiply-assignment"></a>
The *= operator is a shortcut. The following expression: The *= operator is a shortcut. The following expression:
```
{ {
a = 60 a = 60
a *= 5 a *= 5
} }
```
is equivalent to: is equivalent to:
```
{ {
a = 60 a = 60
a = a * 5 a = a * 5
} }
```
### Operator /= <a id="operator-dividing-assignment"></a> ### Operator /= <a id="operator-dividing-assignment"></a>
The /= operator is a shortcut. The following expression: The /= operator is a shortcut. The following expression:
```
{ {
a = 300 a = 300
a /= 5 a /= 5
} }
```
is equivalent to: is equivalent to:
```
{ {
a = 300 a = 300
a = a / 5 a = a / 5
} }
```
## Indexer <a id="indexer"></a> ## Indexer <a id="indexer"></a>
@ -337,23 +383,29 @@ The indexer syntax provides a convenient way to set dictionary elements.
Example: Example:
```
{ {
hello.key = "world" hello.key = "world"
} }
```
Example (alternative syntax): Example (alternative syntax):
```
{ {
hello["key"] = "world" hello["key"] = "world"
} }
```
This is equivalent to writing: This is equivalent to writing:
```
{ {
hello += { hello += {
key = "world" key = "world"
} }
} }
```
If the `hello` attribute does not already have a value, it is automatically initialized to an empty dictionary. If the `hello` attribute does not already have a value, it is automatically initialized to an empty dictionary.
@ -363,6 +415,7 @@ Objects can import attributes from other objects.
Example: Example:
```
template Host "default-host" { template Host "default-host" {
vars.colour = "red" vars.colour = "red"
} }
@ -379,6 +432,7 @@ Example:
address = "127.0.0.1" address = "127.0.0.1"
address6 = "::1" address6 = "::1"
} }
```
The `default-host` and `test-host` objects are marked as templates The `default-host` and `test-host` objects are marked as templates
using the `template` keyword. Unlike ordinary objects templates are not using the `template` keyword. Unlike ordinary objects templates are not
@ -394,9 +448,11 @@ Parent objects are resolved in the order they're specified using the
Default templates which are automatically imported into all object definitions Default templates which are automatically imported into all object definitions
can be specified using the `default` keyword: can be specified using the `default` keyword:
```
template CheckCommand "plugin-check-command" default { template CheckCommand "plugin-check-command" default {
// ... // ...
} }
```
Default templates are imported before any other user-specified statement in an Default templates are imported before any other user-specified statement in an
object definition is evaluated. object definition is evaluated.
@ -408,7 +464,9 @@ is unspecified.
Global constants can be set using the `const` keyword: Global constants can be set using the `const` keyword:
```
const VarName = "some value" const VarName = "some value"
```
Once defined a constant can be accessed from any file. Constants cannot be changed Once defined a constant can be accessed from any file. Constants cannot be changed
once they are set. once they are set.
@ -503,6 +561,7 @@ ICINGA2\_RLIMIT\_STACK |**Read-write.** Defines the resource limit for RLIMI
The `apply` keyword can be used to create new objects which are associated with The `apply` keyword can be used to create new objects which are associated with
another group of objects. another group of objects.
```
apply Service "ping" to Host { apply Service "ping" to Host {
import "generic-service" import "generic-service"
@ -510,6 +569,7 @@ another group of objects.
assign where host.name == "localhost" assign where host.name == "localhost"
} }
```
In this example the `assign where` condition is a boolean expression which is In this example the `assign where` condition is a boolean expression which is
evaluated for all objects of type `Host` and a new service with name "ping" evaluated for all objects of type `Host` and a new service with name "ping"
@ -544,13 +604,14 @@ chapter.
[Apply](17-language-reference.md#apply) rules can be extended with the [Apply](17-language-reference.md#apply) rules can be extended with the
[for loop](17-language-reference.md#for-loops) keyword. [for loop](17-language-reference.md#for-loops) keyword.
```
apply Service "prefix-" for (key => value in host.vars.dictionary) to Host { apply Service "prefix-" for (key => value in host.vars.dictionary) to Host {
import "generic-service" import "generic-service"
check_command = "ping4" check_command = "ping4"
vars.host_value = value vars.host_value = value
} }
```
Any valid config attribute can be accessed using the `host` and `service` Any valid config attribute can be accessed using the `host` and `service`
variables. The attribute must be of the Array or Dictionary type. In this example variables. The attribute must be of the Array or Dictionary type. In this example
@ -577,11 +638,13 @@ chapter.
Group objects can be assigned to specific member objects using the `assign where` Group objects can be assigned to specific member objects using the `assign where`
and `ignore where` conditions. and `ignore where` conditions.
```
object HostGroup "linux-servers" { object HostGroup "linux-servers" {
display_name = "Linux Servers" display_name = "Linux Servers"
assign where host.vars.os == "Linux" assign where host.vars.os == "Linux"
} }
```
In this example the `assign where` condition is a boolean expression which is evaluated In this example the `assign where` condition is a boolean expression which is evaluated
for all objects of the type `Host`. Each matching host is added as member to the host group for all objects of the type `Host`. Each matching host is added as member to the host group
@ -623,6 +686,7 @@ The Icinga 2 configuration format supports C/C++-style and shell-style comments.
Example: Example:
```
/* /*
This is a comment. This is a comment.
*/ */
@ -630,6 +694,7 @@ Example:
check_interval = 30 // this is also a comment. check_interval = 30 // this is also a comment.
retry_interval = 15 # yet another comment retry_interval = 15 # yet another comment
} }
```
## Includes <a id="includes"></a> ## Includes <a id="includes"></a>
@ -639,15 +704,19 @@ Paths must be relative to the configuration file that contains the
Example: Example:
```
include "some/other/file.conf" include "some/other/file.conf"
include "conf.d/*.conf" include "conf.d/*.conf"
```
Wildcard includes are not recursive. Wildcard includes are not recursive.
Icinga also supports include search paths similar to how they work in a Icinga also supports include search paths similar to how they work in a
C/C++ compiler: C/C++ compiler:
```
include <itl> include <itl>
```
Note the use of angle brackets instead of double quotes. This causes the Note the use of angle brackets instead of double quotes. This causes the
config compiler to search the include search paths for the specified config compiler to search the include search paths for the specified
@ -664,8 +733,10 @@ files in a directory which match a certain pattern.
Example: Example:
```
include_recursive "conf.d", "*.conf" include_recursive "conf.d", "*.conf"
include_recursive "templates" include_recursive "templates"
```
The first parameter specifies the directory from which files should be The first parameter specifies the directory from which files should be
recursively included. recursively included.
@ -683,8 +754,10 @@ in these subdirectories to the name of the subdirectory.
Example: Example:
```
include_zones "etc", "zones.d", "*.conf" include_zones "etc", "zones.d", "*.conf"
include_zones "puppet", "puppet-zones" include_zones "puppet", "puppet-zones"
```
The first parameter specifies a tag name for this directive. Each `include_zones` The first parameter specifies a tag name for this directive. Each `include_zones`
invocation should use a unique tag name. When copying the zones' configuration invocation should use a unique tag name. When copying the zones' configuration
@ -708,14 +781,18 @@ Functions can be defined using the `function` keyword.
Example: Example:
```
function multiply(a, b) { function multiply(a, b) {
return a * b return a * b
} }
```
When encountering the `return` keyword further execution of the function is terminated and When encountering the `return` keyword further execution of the function is terminated and
the specified value is supplied to the caller of the function: the specified value is supplied to the caller of the function:
```
log(multiply(3, 5)) log(multiply(3, 5))
```
In this example the `multiply` function we declared earlier is invoked with two arguments (3 and 5). In this example the `multiply` function we declared earlier is invoked with two arguments (3 and 5).
The function computes the product of those arguments and makes the result available to the The function computes the product of those arguments and makes the result available to the
@ -727,16 +804,20 @@ Functions which do not have a `return` statement have their return value set to
last expression which was performed by the function. For example, we could have also written our last expression which was performed by the function. For example, we could have also written our
`multiply` function like this: `multiply` function like this:
```
function multiply(a, b) { function multiply(a, b) {
a * b a * b
} }
```
Anonymous functions can be created by omitting the name in the function definition. The Anonymous functions can be created by omitting the name in the function definition. The
resulting function object can be used like any other value: resulting function object can be used like any other value:
```
var fn = function() { 3 } var fn = function() { 3 }
fn() /* Returns 3 */ fn() /* Returns 3 */
```
## Lambda Expressions <a id="lambdas"></a> ## Lambda Expressions <a id="lambdas"></a>
@ -744,20 +825,26 @@ Functions can also be declared using the alternative lambda syntax.
Example: Example:
```
f = (x) => x * x f = (x) => x * x
```
Multiple statements can be used by putting the function body into braces: Multiple statements can be used by putting the function body into braces:
```
f = (x) => { f = (x) => {
log("Lambda called") log("Lambda called")
x * x x * x
} }
```
Just like with ordinary functions the return value is the value of the last statement. Just like with ordinary functions the return value is the value of the last statement.
For lambdas which take exactly one argument the braces around the arguments can be omitted: For lambdas which take exactly one argument the braces around the arguments can be omitted:
```
f = x => x * x f = x => x * x
```
## Abbreviated Lambda Syntax <a id="nullary-lambdas"></a> ## Abbreviated Lambda Syntax <a id="nullary-lambdas"></a>
@ -765,7 +852,9 @@ Lambdas which take no arguments can also be written using the abbreviated lambda
Example: Example:
```
f = {{ 3 }} f = {{ 3 }}
```
This creates a new function which returns the value 3. This creates a new function which returns the value 3.
@ -781,10 +870,12 @@ already exists there:
The local scope contains variables which only exist during the invocation of the current function, The local scope contains variables which only exist during the invocation of the current function,
object or apply statement. Local variables can be declared using the `var` keyword: object or apply statement. Local variables can be declared using the `var` keyword:
```
function multiply(a, b) { function multiply(a, b) {
var temp = a * b var temp = a * b
return temp return temp
} }
```
Each time the `multiply` function is invoked a new `temp` variable is used which is in no way Each time the `multiply` function is invoked a new `temp` variable is used which is in no way
related to previous invocations of the function. related to previous invocations of the function.
@ -795,15 +886,18 @@ the `this` scope is used.
The `this` scope refers to the current object which the function or object/apply statement The `this` scope refers to the current object which the function or object/apply statement
operates on. operates on.
```
object Host "localhost" { object Host "localhost" {
check_interval = 5m check_interval = 5m
} }
```
In this example the `this` scope refers to the "localhost" object. The `check_interval` attribute In this example the `this` scope refers to the "localhost" object. The `check_interval` attribute
is set for this particular host. is set for this particular host.
You can explicitly access the `this` scope using the `this` keyword: You can explicitly access the `this` scope using the `this` keyword:
```
object Host "localhost" { object Host "localhost" {
var check_interval = 5m var check_interval = 5m
@ -813,12 +907,13 @@ You can explicitly access the `this` scope using the `this` keyword:
*/ */
this.check_interval = 1m this.check_interval = 1m
} }
```
Similarly the keywords `locals` and `globals` are available to access the local and global scope. Similarly the keywords `locals` and `globals` are available to access the local and global scope.
Functions also have a `this` scope. However unlike for object/apply statements the `this` scope for Functions also have a `this` scope. However unlike for object/apply statements the `this` scope for
a function is set to whichever object was used to invoke the function. Here's an example: a function is set to whichever object was used to invoke the function. Here's an example:
```
hm = { hm = {
h_word = null h_word = null
@ -829,6 +924,7 @@ a function is set to whichever object was used to invoke the function. Here's an
/* Let's invoke the init() function */ /* Let's invoke the init() function */
hm.init("hello") hm.init("hello")
```
We're using `hm.init` to invoke the function which causes the value of `hm` to become the `this` We're using `hm.init` to invoke the function which causes the value of `hm` to become the `this`
scope for this function call. scope for this function call.
@ -840,22 +936,26 @@ outside of their scope (except for global variables).
In order to access variables which are defined in the outer scope the `use` keyword can be used: In order to access variables which are defined in the outer scope the `use` keyword can be used:
```
function MakeHelloFunction(name) { function MakeHelloFunction(name) {
return function() use(name) { return function() use(name) {
log("Hello, " + name) log("Hello, " + name)
} }
} }
```
In this case a new variable `name` is created inside the inner function's scope which has the In this case a new variable `name` is created inside the inner function's scope which has the
value of the `name` function argument. value of the `name` function argument.
Alternatively a different value for the inner variable can be specified: Alternatively a different value for the inner variable can be specified:
```
function MakeHelloFunction(name) { function MakeHelloFunction(name) {
return function() use (greeting = "Hello, " + name) { return function() use (greeting = "Hello, " + name) {
log(greeting) log(greeting)
} }
} }
```
## Conditional Statements <a id="conditional-statements"></a> ## Conditional Statements <a id="conditional-statements"></a>
@ -864,6 +964,7 @@ construct can be used to accomplish this.
Example: Example:
```
a = 3 a = 3
if (a < 5) { if (a < 5) {
@ -873,10 +974,12 @@ Example:
} else { } else {
a *= 2 a *= 2
} }
```
An if/else construct can also be used in place of any other value. The value of an if/else statement An if/else construct can also be used in place of any other value. The value of an if/else statement
is the value of the last statement which was evaluated for the branch which was taken: is the value of the last statement which was evaluated for the branch which was taken:
```
a = if (true) { a = if (true) {
log("Taking the 'true' branch") log("Taking the 'true' branch")
7 * 3 7 * 3
@ -884,6 +987,7 @@ is the value of the last statement which was evaluated for the branch which was
log("Taking the 'false' branch") log("Taking the 'false' branch")
9 9
} }
```
This example prints the log message "Taking the 'true' branch" and the `a` variable is set to 21 (7 * 3). This example prints the log message "Taking the 'true' branch" and the `a` variable is set to 21 (7 * 3).
@ -896,12 +1000,14 @@ This is repeated until the condition is no longer true.
Example: Example:
```
var num = 5 var num = 5
while (num > 5) { while (num > 5) {
log("Test") log("Test")
num -= 1 num -= 1
} }
```
The `continue` and `break` keywords can be used to control how the loop is executed: The `continue` keyword The `continue` and `break` keywords can be used to control how the loop is executed: The `continue` keyword
skips over the remaining expressions for the loop body and begins the next loop evaluation. The `break` keyword skips over the remaining expressions for the loop body and begins the next loop evaluation. The `break` keyword
@ -913,22 +1019,26 @@ The `for` statement can be used to iterate over arrays and dictionaries.
Example: Example:
```
var list = [ "a", "b", "c" ] var list = [ "a", "b", "c" ]
for (var item in list) { for (var item in list) {
log("Item: " + item) log("Item: " + item)
} }
```
The loop body is evaluated once for each item in the array. The variable `item` is declared as a local The loop body is evaluated once for each item in the array. The variable `item` is declared as a local
variable just as if the `var` keyword had been used. variable just as if the `var` keyword had been used.
Iterating over dictionaries can be accomplished in a similar manner: Iterating over dictionaries can be accomplished in a similar manner:
```
var dict = { a = 3, b = 7 } var dict = { a = 3, b = 7 }
for (var key => var value in dict) { for (var key => var value in dict) {
log("Key: " + key + ", Value: " + value) log("Key: " + key + ", Value: " + value)
} }
```
The `continue` and `break` keywords can be used to control how the loop is executed: The `continue` keyword The `continue` and `break` keywords can be used to control how the loop is executed: The `continue` keyword
skips over the remaining expressions for the loop body and begins the next loop evaluation. The `break` keyword skips over the remaining expressions for the loop body and begins the next loop evaluation. The `break` keyword
@ -943,15 +1053,19 @@ In order to create a new value of a specific type constructor calls may be used.
Example: Example:
```
var pd = PerfdataValue() var pd = PerfdataValue()
pd.label = "test" pd.label = "test"
pd.value = 10 pd.value = 10
```
You can also try to convert an existing value to another type by specifying it as an argument for the constructor call. You can also try to convert an existing value to another type by specifying it as an argument for the constructor call.
Example: Example:
```
var s = String(3) /* Sets s to "3". */ var s = String(3) /* Sets s to "3". */
```
## Throwing Exceptions <a id="throw"></a> ## Throwing Exceptions <a id="throw"></a>
@ -960,7 +1074,9 @@ using the `throw` keyword.
Example: Example:
```
throw "An error occurred." throw "An error occurred."
```
## Handling Exceptions <a id="try-except"></a> ## Handling Exceptions <a id="try-except"></a>
@ -969,6 +1085,7 @@ Exceptions can be handled using the `try` and `except` keywords. When an excepti
Example: Example:
```
try { try {
throw "Test" throw "Test"
@ -976,6 +1093,7 @@ Example:
} except { } except {
log("An error occurred in the try clause.") log("An error occurred in the try clause.")
} }
```
## Breakpoints <a id="breakpoints"></a> ## Breakpoints <a id="breakpoints"></a>
@ -987,7 +1105,9 @@ By default breakpoints have no effect unless Icinga is started with the `--scrip
All values have a static type. The `typeof` function can be used to determine the type of a value: All values have a static type. The `typeof` function can be used to determine the type of a value:
```
typeof(3) /* Returns an object which represents the type for numbers */ typeof(3) /* Returns an object which represents the type for numbers */
```
The following built-in types are available: The following built-in types are available:
@ -1006,14 +1126,18 @@ e.g. Host, Service, CheckCommand, etc.
Each type has an associated type object which describes the type's semantics. These Each type has an associated type object which describes the type's semantics. These
type objects are made available using global variables which match the type's name: type objects are made available using global variables which match the type's name:
```
/* This logs 'true' */ /* This logs 'true' */
log(typeof(3) == Number) log(typeof(3) == Number)
```
The type object's `prototype` property can be used to find out which methods a certain type The type object's `prototype` property can be used to find out which methods a certain type
supports: supports:
```
/* This returns: ["contains","find","len","lower","replace","reverse","split","substr","to_string","trim","upper"] */ /* This returns: ["contains","find","len","lower","replace","reverse","split","substr","to_string","trim","upper"] */
keys(String.prototype) keys(String.prototype)
```
Additional documentation on type methods is available in the Additional documentation on type methods is available in the
[library reference](18-library-reference.md#library-reference). [library reference](18-library-reference.md#library-reference).
@ -1025,12 +1149,15 @@ The location of the currently executing script can be obtained using the
Example: Example:
```
log("Hello from '" + current_filename + "' in line " + current_line) log("Hello from '" + current_filename + "' in line " + current_line)
```
## Reserved Keywords <a id="reserved-keywords"></a> ## Reserved Keywords <a id="reserved-keywords"></a>
These keywords are reserved and must not be used as constants or custom attributes. These keywords are reserved and must not be used as constants or custom attributes.
```
object object
template template
include include
@ -1070,11 +1197,12 @@ These keywords are reserved and must not be used as constants or custom attribut
in in
using using
namespace namespace
```
You can escape reserved keywords using the `@` character. The following example You can escape reserved keywords using the `@` character. The following example
tries to set `vars.include` which references a reserved keyword and generates tries to set `vars.include` which references a reserved keyword and generates
an error: an error:
```
[2014-09-15 17:24:00 +0200] critical/config: Location: [2014-09-15 17:24:00 +0200] critical/config: Location:
/etc/icinga2/conf.d/hosts/localhost.conf(13): vars.sla = "24x7" /etc/icinga2/conf.d/hosts/localhost.conf(13): vars.sla = "24x7"
/etc/icinga2/conf.d/hosts/localhost.conf(14): /etc/icinga2/conf.d/hosts/localhost.conf(14):
@ -1085,9 +1213,11 @@ an error:
Config error: in /etc/icinga2/conf.d/hosts/localhost.conf: 15:8-15:14: syntax error, unexpected include (T_INCLUDE), expecting T_IDENTIFIER Config error: in /etc/icinga2/conf.d/hosts/localhost.conf: 15:8-15:14: syntax error, unexpected include (T_INCLUDE), expecting T_IDENTIFIER
[2014-09-15 17:24:00 +0200] critical/config: 1 errors, 0 warnings. [2014-09-15 17:24:00 +0200] critical/config: 1 errors, 0 warnings.
```
You can escape the `include` keyword by prefixing it with an additional `@` character: You can escape the `include` keyword by prefixing it with an additional `@` character:
```
object Host "localhost" { object Host "localhost" {
import "generic-host" import "generic-host"
@ -1099,3 +1229,4 @@ You can escape the `include` keyword by prefixing it with an additional `@` char
vars.@include = "some cmdb export field" vars.@include = "some cmdb export field"
} }
```

File diff suppressed because it is too large Load Diff

View File

@ -3,7 +3,9 @@
You can run the Icinga 2 daemon with the `-X` (`--script-debugger`) You can run the Icinga 2 daemon with the `-X` (`--script-debugger`)
parameter to enable the script debugger: parameter to enable the script debugger:
```
# icinga2 daemon -X # icinga2 daemon -X
```
When an exception occurs or the [debugger](17-language-reference.md#breakpoints) When an exception occurs or the [debugger](17-language-reference.md#breakpoints)
keyword is encountered in a user script, Icinga 2 launches a console that keyword is encountered in a user script, Icinga 2 launches a console that
@ -11,7 +13,9 @@ allows the user to debug the script.
You can also attach the script debugger to the [configuration validation](11-cli-commands.md#config-validation): You can also attach the script debugger to the [configuration validation](11-cli-commands.md#config-validation):
```
# icinga2 daemon -C -X # icinga2 daemon -C -X
```
Here is a list of common errors which can be diagnosed with the script debugger: Here is a list of common errors which can be diagnosed with the script debugger:
@ -24,6 +28,7 @@ The following example illustrates the problem of a service [apply rule](03-monit
which expects a dictionary value for `config`, but the host custom attribute only which expects a dictionary value for `config`, but the host custom attribute only
provides a string value: provides a string value:
```
object Host "script-debugger-host" { object Host "script-debugger-host" {
check_command = "icinga" check_command = "icinga"
@ -37,12 +42,14 @@ provides a string value:
check_command = "http" check_command = "http"
} }
```
The error message on config validation will warn about the wrong value type, The error message on config validation will warn about the wrong value type,
but does not provide any context which objects are affected. but does not provide any context which objects are affected.
Enable the script debugger and run the config validation: Enable the script debugger and run the config validation:
```
# icinga2 daemon -C -X # icinga2 daemon -C -X
Breakpoint encountered in /etc/icinga2/conf.d/services.conf: 59:67-65:1 Breakpoint encountered in /etc/icinga2/conf.d/services.conf: 59:67-65:1
@ -57,15 +64,18 @@ Enable the script debugger and run the config validation:
You can inspect expressions (such as variables) by entering them at the prompt. You can inspect expressions (such as variables) by entering them at the prompt.
To leave the debugger and continue the program use "$continue". To leave the debugger and continue the program use "$continue".
<1> => <1> =>
```
You can print the variables `vars` and `config` to get an idea about You can print the variables `vars` and `config` to get an idea about
their values: their values:
```
<1> => vars <1> => vars
null null
<2> => config <2> => config
"192.168.1.100" "192.168.1.100"
<3> => <3> =>
```
The `vars` attribute has to be a dictionary. Trying to set this attribute to a string caused The `vars` attribute has to be a dictionary. Trying to set this attribute to a string caused
the error in our configuration example. the error in our configuration example.
@ -73,10 +83,12 @@ the error in our configuration example.
In order to determine the name of the host where the value of the `config` variable came from In order to determine the name of the host where the value of the `config` variable came from
you can inspect attributes of the service object: you can inspect attributes of the service object:
```
<3> => host_name <3> => host_name
"script-debugger-host-01" "script-debugger-host-01"
<4> => name <4> => name
"http" "http"
```
Additionally you can view the service object attributes by printing the value of `this`. Additionally you can view the service object attributes by printing the value of `this`.
@ -84,6 +96,7 @@ Additionally you can view the service object attributes by printing the value of
In order to halt execution in a script you can use the `debugger` keyword: In order to halt execution in a script you can use the `debugger` keyword:
```
object Host "script-debugger-host-02" { object Host "script-debugger-host-02" {
check_command = "dummy" check_command = "dummy"
check_interval = 5s check_interval = 5s
@ -94,9 +107,11 @@ In order to halt execution in a script you can use the `debugger` keyword:
return text return text
}} }}
} }
```
Icinga 2 will spawn a debugger console every time the function is executed: Icinga 2 will spawn a debugger console every time the function is executed:
```
# icinga2 daemon -X # icinga2 daemon -X
... ...
Breakpoint encountered in /etc/icinga2/tests/script-debugger.conf: 7:5-7:12 Breakpoint encountered in /etc/icinga2/tests/script-debugger.conf: 7:5-7:12
@ -105,7 +120,7 @@ Icinga 2 will spawn a debugger console every time the function is executed:
<1> => text <1> => text
"Hello from script-debugger-host-02" "Hello from script-debugger-host-02"
<2> => $continue <2> => $continue
```
## Debugging API Filters <a id="script-debugger-api-filters"></a> ## Debugging API Filters <a id="script-debugger-api-filters"></a>

View File

@ -213,6 +213,7 @@ If you want to delete all breakpoints, use `d` and select `yes`.
Breakpoint Example: Breakpoint Example:
```
(gdb) b __cxa_throw (gdb) b __cxa_throw
(gdb) r (gdb) r
(gdb) up (gdb) up
@ -239,6 +240,7 @@ Breakpoint Example:
m_Data = "/etc/icinga2/conf.d/satellite.conf"}, {static NPos = 18446744073709551615, m_Data = "/etc/icinga2/conf.d/services.conf"}, {static NPos = 18446744073709551615, m_Data = "/etc/icinga2/conf.d/satellite.conf"}, {static NPos = 18446744073709551615, m_Data = "/etc/icinga2/conf.d/services.conf"}, {static NPos = 18446744073709551615,
m_Data = "/etc/icinga2/conf.d/templates.conf"}, {static NPos = 18446744073709551615, m_Data = "/etc/icinga2/conf.d/test.conf"}, {static NPos = 18446744073709551615, m_Data = "/etc/icinga2/conf.d/templates.conf"}, {static NPos = 18446744073709551615, m_Data = "/etc/icinga2/conf.d/test.conf"}, {static NPos = 18446744073709551615,
m_Data = "/etc/icinga2/conf.d/timeperiods.conf"}, {static NPos = 18446744073709551615, m_Data = "/etc/icinga2/conf.d/users.conf"}} m_Data = "/etc/icinga2/conf.d/timeperiods.conf"}, {static NPos = 18446744073709551615, m_Data = "/etc/icinga2/conf.d/users.conf"}}
```
### Core Dump <a id="development-debug-core-dump"></a> ### Core Dump <a id="development-debug-core-dump"></a>
@ -1580,30 +1582,39 @@ Please check `appveyor.yml` for instructions.
Install the `boost`, `python` and `icinga2` pretty printers. Absolute paths are required, Install the `boost`, `python` and `icinga2` pretty printers. Absolute paths are required,
so please make sure to update the installation paths accordingly (`pwd`). so please make sure to update the installation paths accordingly (`pwd`).
```
$ mkdir -p ~/.gdb_printers && cd ~/.gdb_printers $ mkdir -p ~/.gdb_printers && cd ~/.gdb_printers
```
Boost Pretty Printers compatible with Python 3: Boost Pretty Printers compatible with Python 3:
```
$ git clone https://github.com/mateidavid/Boost-Pretty-Printer.git && cd Boost-Pretty-Printer $ git clone https://github.com/mateidavid/Boost-Pretty-Printer.git && cd Boost-Pretty-Printer
$ git checkout python-3 $ git checkout python-3
$ pwd $ pwd
/home/michi/.gdb_printers/Boost-Pretty-Printer /home/michi/.gdb_printers/Boost-Pretty-Printer
```
Python Pretty Printers: Python Pretty Printers:
```
$ cd ~/.gdb_printers $ cd ~/.gdb_printers
$ svn co svn://gcc.gnu.org/svn/gcc/trunk/libstdc++-v3/python $ svn co svn://gcc.gnu.org/svn/gcc/trunk/libstdc++-v3/python
```
Icinga 2 Pretty Printers: Icinga 2 Pretty Printers:
```
$ mkdir -p ~/.gdb_printers/icinga2 && cd ~/.gdb_printers/icinga2 $ mkdir -p ~/.gdb_printers/icinga2 && cd ~/.gdb_printers/icinga2
$ wget https://raw.githubusercontent.com/Icinga/icinga2/master/tools/debug/gdb/icingadbg.py $ wget https://raw.githubusercontent.com/Icinga/icinga2/master/tools/debug/gdb/icingadbg.py
```
Now you'll need to modify/setup your `~/.gdbinit` configuration file. Now you'll need to modify/setup your `~/.gdbinit` configuration file.
You can download the one from Icinga 2 and modify all paths. You can download the one from Icinga 2 and modify all paths.
Example on Fedora 22: Example on Fedora 22:
```
$ wget https://raw.githubusercontent.com/Icinga/icinga2/master/tools/debug/gdb/gdbinit -O ~/.gdbinit $ wget https://raw.githubusercontent.com/Icinga/icinga2/master/tools/debug/gdb/gdbinit -O ~/.gdbinit
$ vim ~/.gdbinit $ vim ~/.gdbinit
@ -1632,14 +1643,15 @@ Example on Fedora 22:
import boost_print import boost_print
boost_print.register_printers() boost_print.register_printers()
end end
```
If you are getting the following error when running gdb, the `libstdcxx` If you are getting the following error when running gdb, the `libstdcxx`
printers are already preloaded in your environment and you can remove printers are already preloaded in your environment and you can remove
the duplicate import in your `~/.gdbinit` file. the duplicate import in your `~/.gdbinit` file.
```
RuntimeError: pretty-printer already registered: libstdc++-v6 RuntimeError: pretty-printer already registered: libstdc++-v6
```
## Development Tests <a id="development-tests"></a> ## Development Tests <a id="development-tests"></a>

View File

@ -18,6 +18,7 @@ There are two ways of installing the SELinux Policy for Icinga 2 on Enterprise L
If the system runs in enforcing mode and you encounter problems you can set Icinga 2's domain to permissive mode. If the system runs in enforcing mode and you encounter problems you can set Icinga 2's domain to permissive mode.
```
# sestatus # sestatus
SELinux status: enabled SELinux status: enabled
SELinuxfs mount: /sys/fs/selinux SELinuxfs mount: /sys/fs/selinux
@ -28,6 +29,7 @@ If the system runs in enforcing mode and you encounter problems you can set Icin
Policy MLS status: enabled Policy MLS status: enabled
Policy deny_unknown status: allowed Policy deny_unknown status: allowed
Max kernel policy version: 28 Max kernel policy version: 28
```
You can change the configured mode by editing `/etc/selinux/config` and the current mode by executing `setenforce 0`. You can change the configured mode by editing `/etc/selinux/config` and the current mode by executing `setenforce 0`.
@ -35,13 +37,17 @@ You can change the configured mode by editing `/etc/selinux/config` and the curr
Simply add the `icinga2-selinux` package to your installation. Simply add the `icinga2-selinux` package to your installation.
```
# yum install icinga2-selinux # yum install icinga2-selinux
```
Ensure that the `icinga2` process is running in its own `icinga2_t` domain after installing the policy package: Ensure that the `icinga2` process is running in its own `icinga2_t` domain after installing the policy package:
```
# systemctl restart icinga2.service # systemctl restart icinga2.service
# ps -eZ | grep icinga2 # ps -eZ | grep icinga2
system_u:system_r:icinga2_t:s0 2825 ? 00:00:00 icinga2 system_u:system_r:icinga2_t:s0 2825 ? 00:00:00 icinga2
```
#### Manual installation <a id="selinux-policy-installation-manual"></a> #### Manual installation <a id="selinux-policy-installation-manual"></a>
@ -49,24 +55,32 @@ This section describes the installation to support development and testing. It a
As a prerequisite install the `git`, `selinux-policy-devel` and `audit` packages. Enable and start the audit daemon afterwards: As a prerequisite install the `git`, `selinux-policy-devel` and `audit` packages. Enable and start the audit daemon afterwards:
```
# yum install git selinux-policy-devel audit # yum install git selinux-policy-devel audit
# systemctl enable auditd.service # systemctl enable auditd.service
# systemctl start auditd.service # systemctl start auditd.service
```
After that clone the icinga2 git repository: After that clone the icinga2 git repository:
```
# git clone https://github.com/icinga/icinga2 # git clone https://github.com/icinga/icinga2
```
To create and install the policy package run the installation script which also labels the resources. (The script assumes Icinga 2 was started once after system startup, the labeling of the port will only happen once and fail later on.) To create and install the policy package run the installation script which also labels the resources. (The script assumes Icinga 2 was started once after system startup, the labeling of the port will only happen once and fail later on.)
```
# cd tools/selinux/ # cd tools/selinux/
# ./icinga.sh # ./icinga.sh
```
After that restart Icinga 2 and verify it running in its own domain `icinga2_t`. After that restart Icinga 2 and verify it running in its own domain `icinga2_t`.
```
# systemctl restart icinga2.service # systemctl restart icinga2.service
# ps -eZ | grep icinga2 # ps -eZ | grep icinga2
system_u:system_r:icinga2_t:s0 2825 ? 00:00:00 icinga2 system_u:system_r:icinga2_t:s0 2825 ? 00:00:00 icinga2
```
### General <a id="selinux-policy-general"></a> ### General <a id="selinux-policy-general"></a>
@ -126,23 +140,29 @@ Make sure to report the bugs in the policy afterwards.
Download and install a plugin, for example check_mysql_health. Download and install a plugin, for example check_mysql_health.
```
# wget https://labs.consol.de/download/shinken-nagios-plugins/check_mysql_health-2.1.9.2.tar.gz # wget https://labs.consol.de/download/shinken-nagios-plugins/check_mysql_health-2.1.9.2.tar.gz
# tar xvzf check_mysql_health-2.1.9.2.tar.gz # tar xvzf check_mysql_health-2.1.9.2.tar.gz
# cd check_mysql_health-2.1.9.2/ # cd check_mysql_health-2.1.9.2/
# ./configure --libexecdir /usr/lib64/nagios/plugins # ./configure --libexecdir /usr/lib64/nagios/plugins
# make # make
# make install # make install
```
It is labeled `nagios_unconfined_plugins_exec_t` by default, so it runs without restrictions. It is labeled `nagios_unconfined_plugins_exec_t` by default, so it runs without restrictions.
```
# ls -lZ /usr/lib64/nagios/plugins/check_mysql_health # ls -lZ /usr/lib64/nagios/plugins/check_mysql_health
-rwxr-xr-x. root root system_u:object_r:nagios_unconfined_plugin_exec_t:s0 /usr/lib64/nagios/plugins/check_mysql_health -rwxr-xr-x. root root system_u:object_r:nagios_unconfined_plugin_exec_t:s0 /usr/lib64/nagios/plugins/check_mysql_health
```
In this case the plugin is monitoring a service, so it should be labeled `nagios_services_plugin_exec_t` to restrict its permissions. In this case the plugin is monitoring a service, so it should be labeled `nagios_services_plugin_exec_t` to restrict its permissions.
```
# chcon -t nagios_services_plugin_exec_t /usr/lib64/nagios/plugins/check_mysql_health # chcon -t nagios_services_plugin_exec_t /usr/lib64/nagios/plugins/check_mysql_health
# ls -lZ /usr/lib64/nagios/plugins/check_mysql_health # ls -lZ /usr/lib64/nagios/plugins/check_mysql_health
-rwxr-xr-x. root root system_u:object_r:nagios_services_plugin_exec_t:s0 /usr/lib64/nagios/plugins/check_mysql_health -rwxr-xr-x. root root system_u:object_r:nagios_services_plugin_exec_t:s0 /usr/lib64/nagios/plugins/check_mysql_health
```
The plugin still runs fine but if someone changes the script to do weird stuff it will fail to do so. The plugin still runs fine but if someone changes the script to do weird stuff it will fail to do so.
@ -152,6 +172,7 @@ You are running graphite on a different port than `2003` and want `icinga2` to c
Change the port value for the graphite feature according to your graphite installation before enabling it. Change the port value for the graphite feature according to your graphite installation before enabling it.
```
# cat /etc/icinga2/features-enabled/graphite.conf # cat /etc/icinga2/features-enabled/graphite.conf
/** /**
* The GraphiteWriter type writes check result metrics and * The GraphiteWriter type writes check result metrics and
@ -166,11 +187,14 @@ Change the port value for the graphite feature according to your graphite instal
port = 2004 port = 2004
} }
# icinga2 feature enable graphite # icinga2 feature enable graphite
```
Before you restart the icinga2 service allow it to connect to all ports by enabling the boolean ´icinga2_can_connect_all` (now and permanent). Before you restart the icinga2 service allow it to connect to all ports by enabling the boolean ´icinga2_can_connect_all` (now and permanent).
```
# setsebool icinga2_can_connect_all true # setsebool icinga2_can_connect_all true
# setsebool -P icinga2_can_connect_all true # setsebool -P icinga2_can_connect_all true
```
If you restart the daemon now it will successfully connect to graphite. If you restart the daemon now it will successfully connect to graphite.
@ -181,20 +205,27 @@ this user. This is completly optional!
Start by adding the Icinga 2 administrator role `icinga2adm_r` to the administrative SELinux user `staff_u`. Start by adding the Icinga 2 administrator role `icinga2adm_r` to the administrative SELinux user `staff_u`.
```
# semanage user -m -R "staff_r sysadm_r system_r unconfined_r icinga2adm_r" staff_u # semanage user -m -R "staff_r sysadm_r system_r unconfined_r icinga2adm_r" staff_u
```
Confine your user login and create a sudo rule. Confine your user login and create a sudo rule.
```
# semanage login -a dirk -s staff_u # semanage login -a dirk -s staff_u
# echo "dirk ALL=(ALL) NOPASSWD: ALL" > /etc/sudoers.d/dirk # echo "dirk ALL=(ALL) NOPASSWD: ALL" > /etc/sudoers.d/dirk
```
Login to the system using ssh and verify your id. Login to the system using ssh and verify your id.
```
$ id -Z $ id -Z
staff_u:staff_r:staff_t:s0-s0:c0.c1023 staff_u:staff_r:staff_t:s0-s0:c0.c1023
```
Try to execute some commands as root using sudo. Try to execute some commands as root using sudo.
```
$ sudo id -Z $ sudo id -Z
staff_u:staff_r:staff_t:s0-s0:c0.c1023 staff_u:staff_r:staff_t:s0-s0:c0.c1023
$ sudo vi /etc/icinga2/icinga2.conf $ sudo vi /etc/icinga2/icinga2.conf
@ -203,9 +234,11 @@ Try to execute some commands as root using sudo.
cat: /var/log/icinga2/icinga2.log: Keine Berechtigung cat: /var/log/icinga2/icinga2.log: Keine Berechtigung
$ sudo systemctl reload icinga2.service $ sudo systemctl reload icinga2.service
Failed to get D-Bus connection: No connection to service manager. Failed to get D-Bus connection: No connection to service manager.
```
Those commands fail because you only switch to root but do not change your SELinux role. Try again but tell sudo also to switch the SELinux role and type. Those commands fail because you only switch to root but do not change your SELinux role. Try again but tell sudo also to switch the SELinux role and type.
```
$ sudo -r icinga2adm_r -t icinga2adm_t id -Z $ sudo -r icinga2adm_r -t icinga2adm_t id -Z
staff_u:icinga2adm_r:icinga2adm_t:s0-s0:c0.c1023 staff_u:icinga2adm_r:icinga2adm_t:s0-s0:c0.c1023
$ sudo -r icinga2adm_r -t icinga2adm_t vi /etc/icinga2/icinga2.conf $ sudo -r icinga2adm_r -t icinga2adm_t vi /etc/icinga2/icinga2.conf
@ -213,17 +246,22 @@ Those commands fail because you only switch to root but do not change your SELin
$ sudo -r icinga2adm_r -t icinga2adm_t cat /var/log/icinga2/icinga2.log $ sudo -r icinga2adm_r -t icinga2adm_t cat /var/log/icinga2/icinga2.log
[2015-03-26 20:48:14 +0000] information/DynamicObject: Dumping program state to file '/var/lib/icinga2/icinga2.state' [2015-03-26 20:48:14 +0000] information/DynamicObject: Dumping program state to file '/var/lib/icinga2/icinga2.state'
$ sudo -r icinga2adm_r -t icinga2adm_t systemctl reload icinga2.service $ sudo -r icinga2adm_r -t icinga2adm_t systemctl reload icinga2.service
```
Now the commands will work, but you have always to remember to add the arguments, so change the sudo rule to set it by default. Now the commands will work, but you have always to remember to add the arguments, so change the sudo rule to set it by default.
```
# echo "dirk ALL=(ALL) ROLE=icinga2adm_r TYPE=icinga2adm_t NOPASSWD: ALL" > /etc/sudoers.d/dirk # echo "dirk ALL=(ALL) ROLE=icinga2adm_r TYPE=icinga2adm_t NOPASSWD: ALL" > /etc/sudoers.d/dirk
```
Now try the commands again without providing the role and type and they will work, but if you try to read apache logs or restart apache for example it will still fail. Now try the commands again without providing the role and type and they will work, but if you try to read apache logs or restart apache for example it will still fail.
```
$ sudo cat /var/log/httpd/error_log $ sudo cat /var/log/httpd/error_log
/bin/cat: /var/log/httpd/error_log: Keine Berechtigung /bin/cat: /var/log/httpd/error_log: Keine Berechtigung
$ sudo systemctl reload httpd.service $ sudo systemctl reload httpd.service
Failed to issue method call: Access denied Failed to issue method call: Access denied
```
## Bugreports <a id="selinux-bugreports"></a> ## Bugreports <a id="selinux-bugreports"></a>

View File

@ -33,6 +33,7 @@ all existing Icinga 1.x `*_interval` attributes require an additional `m` durati
Icinga 1.x: Icinga 1.x:
```
define service { define service {
service_description service1 service_description service1
host_name localhost1 host_name localhost1
@ -41,9 +42,11 @@ Icinga 1.x:
check_interval 5 check_interval 5
retry_interval 1 retry_interval 1
} }
```
Icinga 2: Icinga 2:
```
object Service "service1" { object Service "service1" {
import "generic-service" import "generic-service"
host_name = "localhost1" host_name = "localhost1"
@ -51,6 +54,7 @@ Icinga 2:
check_interval = 5m check_interval = 5m
retry_interval = 1m retry_interval = 1m
} }
```
#### Manual Config Migration Hints for Services <a id="manual-config-migration-hints-services"></a> #### Manual Config Migration Hints for Services <a id="manual-config-migration-hints-services"></a>
@ -59,34 +63,41 @@ belongs to, you can migrate this to the [apply rules](03-monitoring-basics.md#us
Icinga 1.x: Icinga 1.x:
```
define service { define service {
service_description service1 service_description service1
host_name localhost1,localhost2 host_name localhost1,localhost2
check_command test_check check_command test_check
use generic-service use generic-service
} }
```
Icinga 2: Icinga 2:
```
apply Service "service1" { apply Service "service1" {
import "generic-service" import "generic-service"
check_command = "test_check" check_command = "test_check"
assign where host.name in [ "localhost1", "localhost2" ] assign where host.name in [ "localhost1", "localhost2" ]
} }
```
In Icinga 1.x you would have organized your services with hostgroups using the `hostgroup_name` attribute In Icinga 1.x you would have organized your services with hostgroups using the `hostgroup_name` attribute
like the following example: like the following example:
```
define service { define service {
service_description servicewithhostgroups service_description servicewithhostgroups
hostgroup_name hostgroup1,hostgroup3 hostgroup_name hostgroup1,hostgroup3
check_command test_check check_command test_check
use generic-service use generic-service
} }
```
Using Icinga 2 you can migrate this to the [apply rules](03-monitoring-basics.md#using-apply) syntax: Using Icinga 2 you can migrate this to the [apply rules](03-monitoring-basics.md#using-apply) syntax:
```
apply Service "servicewithhostgroups" { apply Service "servicewithhostgroups" {
import "generic-service" import "generic-service"
check_command = "test_check" check_command = "test_check"
@ -94,12 +105,14 @@ Using Icinga 2 you can migrate this to the [apply rules](03-monitoring-basics.md
assign where "hostgroup1" in host.groups assign where "hostgroup1" in host.groups
assign where "hostgroup3" in host.groups assign where "hostgroup3" in host.groups
} }
```
#### Manual Config Migration Hints for Group Members <a id="manual-config-migration-hints-group-members"></a> #### Manual Config Migration Hints for Group Members <a id="manual-config-migration-hints-group-members"></a>
The Icinga 1.x hostgroup `hg1` has two members `host1` and `host2`. The hostgroup `hg2` has `host3` as The Icinga 1.x hostgroup `hg1` has two members `host1` and `host2`. The hostgroup `hg2` has `host3` as
a member and includes all members of the `hg1` hostgroup. a member and includes all members of the `hg1` hostgroup.
```
define hostgroup { define hostgroup {
hostgroup_name hg1 hostgroup_name hg1
members host1,host2 members host1,host2
@ -110,11 +123,12 @@ a member and includes all members of the `hg1` hostgroup.
members host3 members host3
hostgroup_members hg1 hostgroup_members hg1
} }
```
This can be migrated to Icinga 2 and [using group assign](17-language-reference.md#group-assign). The additional nested hostgroup This can be migrated to Icinga 2 and [using group assign](17-language-reference.md#group-assign). The additional nested hostgroup
`hg1` is included into `hg2` with the `groups` attribute. `hg1` is included into `hg2` with the `groups` attribute.
```
object HostGroup "hg1" { object HostGroup "hg1" {
groups = [ "hg2" ] groups = [ "hg2" ]
assign where host.name in [ "host1", "host2" ] assign where host.name in [ "host1", "host2" ]
@ -123,6 +137,7 @@ This can be migrated to Icinga 2 and [using group assign](17-language-reference.
object HostGroup "hg2" { object HostGroup "hg2" {
assign where host.name == "host3" assign where host.name == "host3"
} }
```
These assign rules can be applied for all groups: `HostGroup`, `ServiceGroup` and `UserGroup` These assign rules can be applied for all groups: `HostGroup`, `ServiceGroup` and `UserGroup`
(requires renaming from `contactgroup`). (requires renaming from `contactgroup`).
@ -138,6 +153,7 @@ These assign rules can be applied for all groups: `HostGroup`, `ServiceGroup` an
Host and service check command arguments are separated by a `!` in Icinga 1.x. Their order is important and they Host and service check command arguments are separated by a `!` in Icinga 1.x. Their order is important and they
are referenced as `$ARGn$` where `n` is the argument counter. are referenced as `$ARGn$` where `n` is the argument counter.
```
define command { define command {
command_name my-ping command_name my-ping
command_line $USER1$/check_ping -H $HOSTADDRESS$ -w $ARG1$ -c $ARG2$ -p 5 command_line $USER1$/check_ping -H $HOSTADDRESS$ -w $ARG1$ -c $ARG2$ -p 5
@ -149,9 +165,11 @@ are referenced as `$ARGn$` where `n` is the argument counter.
service_description my-ping service_description my-ping
check_command my-ping-check!100.0,20%!500.0,60% check_command my-ping-check!100.0,20%!500.0,60%
} }
```
While you could manually migrate this like (please note the new generic command arguments and default argument values!): While you could manually migrate this like (please note the new generic command arguments and default argument values!):
```
object CheckCommand "my-ping-check" { object CheckCommand "my-ping-check" {
command = [ command = [
PluginDir + "/check_ping", "-4" PluginDir + "/check_ping", "-4"
@ -182,6 +200,7 @@ While you could manually migrate this like (please note the new generic command
vars.ping_crta = 500 vars.ping_crta = 500
vars.ping_cpl = 60 vars.ping_cpl = 60
} }
```
#### Manual Config Migration Hints for Runtime Macros <a id="manual-config-migration-hints-runtime-macros"></a> #### Manual Config Migration Hints for Runtime Macros <a id="manual-config-migration-hints-runtime-macros"></a>
@ -189,25 +208,33 @@ Runtime macros have been renamed. A detailed comparison table can be found [here
For example, accessing the service check output looks like the following in Icinga 1.x: For example, accessing the service check output looks like the following in Icinga 1.x:
```
$SERVICEOUTPUT$ $SERVICEOUTPUT$
```
In Icinga 2 you will need to write: In Icinga 2 you will need to write:
```
$service.output$ $service.output$
```
Another example referencing the host's address attribute in Icinga 1.x: Another example referencing the host's address attribute in Icinga 1.x:
```
$HOSTADDRESS$ $HOSTADDRESS$
```
In Icinga 2 you'd just use the following macro to access all `address` attributes (even overridden from the service objects): In Icinga 2 you'd just use the following macro to access all `address` attributes (even overridden from the service objects):
```
$address$ $address$
```
#### Manual Config Migration Hints for Runtime Custom Attributes <a id="manual-config-migration-hints-runtime-custom-attributes"></a> #### Manual Config Migration Hints for Runtime Custom Attributes <a id="manual-config-migration-hints-runtime-custom-attributes"></a>
Custom variables from Icinga 1.x are available as Icinga 2 custom attributes. Custom variables from Icinga 1.x are available as Icinga 2 custom attributes.
```
define command { define command {
command_name test_customvar command_name test_customvar
command_line echo "Host CV: $_HOSTCVTEST$ Service CV: $_SERVICECVTEST$\n" command_line echo "Host CV: $_HOSTCVTEST$ Service CV: $_SERVICECVTEST$\n"
@ -227,9 +254,11 @@ Custom variables from Icinga 1.x are available as Icinga 2 custom attributes.
use generic-service use generic-service
_CVTEST service cv value _CVTEST service cv value
} }
```
Can be written as the following in Icinga 2: Can be written as the following in Icinga 2:
```
object CheckCommand "test_customvar" { object CheckCommand "test_customvar" {
command = "echo "Host CV: $host.vars.CVTEST$ Service CV: $service.vars.CVTEST$\n"" command = "echo "Host CV: $host.vars.CVTEST$ Service CV: $service.vars.CVTEST$\n""
} }
@ -245,6 +274,7 @@ Can be written as the following in Icinga 2:
check_command = "test_customvar" check_command = "test_customvar"
vars.CVTEST = "service cv value" vars.CVTEST = "service cv value"
} }
```
If you are just defining `$CVTEST$` in your command definition, its value depends on the If you are just defining `$CVTEST$` in your command definition, its value depends on the
execution scope -- the host check command will fetch the host attribute value of `vars.CVTEST` execution scope -- the host check command will fetch the host attribute value of `vars.CVTEST`
@ -259,6 +289,7 @@ while the service check command resolves its value to the service attribute attr
Contacts in Icinga 1.x act as users in Icinga 2, but do not have any notification commands specified. Contacts in Icinga 1.x act as users in Icinga 2, but do not have any notification commands specified.
This migration part is explained in the [next chapter](23-migrating-from-icinga-1x.md#manual-config-migration-hints-notifications). This migration part is explained in the [next chapter](23-migrating-from-icinga-1x.md#manual-config-migration-hints-notifications).
```
define contact{ define contact{
contact_name testconfig-user contact_name testconfig-user
use generic-user use generic-user
@ -266,16 +297,19 @@ This migration part is explained in the [next chapter](23-migrating-from-icinga-
service_notification_options c,f,s,u service_notification_options c,f,s,u
email icinga@localhost email icinga@localhost
} }
```
The `service_notification_options` can be [mapped](23-migrating-from-icinga-1x.md#manual-config-migration-hints-notification-filters) The `service_notification_options` can be [mapped](23-migrating-from-icinga-1x.md#manual-config-migration-hints-notification-filters)
into generic `state` and `type` filters, if additional notification filtering is required. `alias` gets into generic `state` and `type` filters, if additional notification filtering is required. `alias` gets
renamed to `display_name`. renamed to `display_name`.
```
object User "testconfig-user" { object User "testconfig-user" {
import "generic-user" import "generic-user"
display_name = "Icinga Test User" display_name = "Icinga Test User"
email = "icinga@localhost" email = "icinga@localhost"
} }
```
This user can be put into usergroups (former contactgroups) or referenced in newly migration notification This user can be put into usergroups (former contactgroups) or referenced in newly migration notification
objects. objects.
@ -312,23 +346,28 @@ the host and service notification commands involved.
Generate a new notification object based on these values. Import the generic template based on the type (`host` or `service`). Generate a new notification object based on these values. Import the generic template based on the type (`host` or `service`).
Assign it to the host or service and set the newly generated notification command name as `command` attribute. Assign it to the host or service and set the newly generated notification command name as `command` attribute.
```
object Notification "<notificationname>" { object Notification "<notificationname>" {
import "mail-host-notification" import "mail-host-notification"
host_name = "<thishostname>" host_name = "<thishostname>"
command = "<notificationcommandname>" command = "<notificationcommandname>"
```
Convert the `notification_options` attribute from Icinga 1.x to Icinga 2 `states` and `types`. Details Convert the `notification_options` attribute from Icinga 1.x to Icinga 2 `states` and `types`. Details
[here](23-migrating-from-icinga-1x.md#manual-config-migration-hints-notification-filters). Add the notification period. [here](23-migrating-from-icinga-1x.md#manual-config-migration-hints-notification-filters). Add the notification period.
```
states = [ OK, Warning, Critical ] states = [ OK, Warning, Critical ]
types = [ Recovery, Problem, Custom ] types = [ Recovery, Problem, Custom ]
period = "24x7" period = "24x7"
```
The current contact acts as `users` attribute. The current contact acts as `users` attribute.
```
users = [ "<contactwithnotificationcommand>" ] users = [ "<contactwithnotificationcommand>" ]
} }
```
Do this in a loop for all notification commands (depending if host or service contact). Once done, dump the Do this in a loop for all notification commands (depending if host or service contact). Once done, dump the
collected notification commands. collected notification commands.
@ -374,6 +413,7 @@ hostgroup. The default `notification_interval` is set to `10` minutes notifying
After 20 minutes (`10*2`, notification_interval * first_notification) the notification is escalated to the After 20 minutes (`10*2`, notification_interval * first_notification) the notification is escalated to the
`cg_ops` contactgroup until 60 minutes (`10*6`) have passed. `cg_ops` contactgroup until 60 minutes (`10*6`) have passed.
```
define service { define service {
service_description dep_svc01 service_description dep_svc01
host_name dep_hostsvc01,dep_hostsvc03 host_name dep_hostsvc01,dep_hostsvc03
@ -396,10 +436,12 @@ After 20 minutes (`10*2`, notification_interval * first_notification) the notifi
last_notification 6 last_notification 6
contact_groups cg_ops contact_groups cg_ops
} }
```
In Icinga 2 the service and hostgroup definition will look quite the same. Save the `notification_interval` In Icinga 2 the service and hostgroup definition will look quite the same. Save the `notification_interval`
and `contact_groups` attribute for an additional notification. and `contact_groups` attribute for an additional notification.
```
apply Service "dep_svc01" { apply Service "dep_svc01" {
import "generic-service" import "generic-service"
@ -421,6 +463,7 @@ and `contact_groups` attribute for an additional notification.
assign where service.name == "dep_svc01" && (host.name == "dep_hostsvc01" || host.name == "dep_hostsvc03") assign where service.name == "dep_svc01" && (host.name == "dep_hostsvc01" || host.name == "dep_hostsvc03")
} }
```
Calculate the begin and end time for the newly created escalation notification: Calculate the begin and end time for the newly created escalation notification:
@ -429,6 +472,7 @@ Calculate the begin and end time for the newly created escalation notification:
Assign the notification escalation to the service `dep_svc01` on all hosts in the hostgroup `hg_svcdep2`. Assign the notification escalation to the service `dep_svc01` on all hosts in the hostgroup `hg_svcdep2`.
```
apply Notification "email-escalation" to Service { apply Notification "email-escalation" to Service {
import "service-mail-notification" import "service-mail-notification"
@ -442,6 +486,7 @@ Assign the notification escalation to the service `dep_svc01` on all hosts in th
assign where service.name == "dep_svc01" && "hg_svcdep2" in host.groups assign where service.name == "dep_svc01" && "hg_svcdep2" in host.groups
} }
```
The assign rule could be made more generic and the notification be applied to more than The assign rule could be made more generic and the notification be applied to more than
just this service belonging to hosts in the matched hostgroup. just this service belonging to hosts in the matched hostgroup.
@ -469,6 +514,7 @@ If the state filter matches, you can define whether to disable checks and notifi
The following example describes service dependencies. If you migrate from Icinga 1.x, you will only The following example describes service dependencies. If you migrate from Icinga 1.x, you will only
want to use the classic `Host-to-Host` and `Service-to-Service` dependency relationships. want to use the classic `Host-to-Host` and `Service-to-Service` dependency relationships.
```
define service { define service {
service_description dep_svc01 service_description dep_svc01
hostgroup_name hg_svcdep1 hostgroup_name hg_svcdep1
@ -504,6 +550,7 @@ want to use the classic `Host-to-Host` and `Service-to-Service` dependency relat
notification_failure_criteria w,u,c notification_failure_criteria w,u,c
inherits_parent 1 inherits_parent 1
} }
```
Map the dependency attributes accordingly. Map the dependency attributes accordingly.
@ -517,6 +564,7 @@ Map the dependency attributes accordingly.
And migrate the host and services. And migrate the host and services.
```
object Host "host1" { object Host "host1" {
import "linux-server-template" import "linux-server-template"
address = "192.168.1.10" address = "192.168.1.10"
@ -539,12 +587,14 @@ And migrate the host and services.
assign where "hp_svcdep2" in host.groups assign where "hp_svcdep2" in host.groups
} }
```
When it comes to the `execution_failure_criteria` and `notification_failure_criteria` attribute migration, When it comes to the `execution_failure_criteria` and `notification_failure_criteria` attribute migration,
you will need to map the most common values, in this example `u,c` (`Unknown` and `Critical` will cause the you will need to map the most common values, in this example `u,c` (`Unknown` and `Critical` will cause the
dependency to fail). Therefore the `Dependency` should be ok on Ok and Warning. `inherits_parents` is always dependency to fail). Therefore the `Dependency` should be ok on Ok and Warning. `inherits_parents` is always
enabled. enabled.
```
apply Dependency "all-svc-for-hg-hg_svcdep2-on-host1-dep_svc01" to Service { apply Dependency "all-svc-for-hg-hg_svcdep2-on-host1-dep_svc01" to Service {
parent_host_name = "host1" parent_host_name = "host1"
parent_service_name = "dep_svc01" parent_service_name = "dep_svc01"
@ -555,6 +605,7 @@ enabled.
assign where "hg_svcdep2" in host.groups assign where "hg_svcdep2" in host.groups
} }
```
Host dependencies are explained in the [next chapter](23-migrating-from-icinga-1x.md#manual-config-migration-hints-host-parents). Host dependencies are explained in the [next chapter](23-migrating-from-icinga-1x.md#manual-config-migration-hints-host-parents).
@ -570,6 +621,7 @@ virtual machines `vmware-vm1` and `vmware-vm2`.
By default all hosts in the hostgroup `vmware` should get the parent assigned. This isn't really By default all hosts in the hostgroup `vmware` should get the parent assigned. This isn't really
solvable with Icinga 1.x parents, but only with host dependencies. solvable with Icinga 1.x parents, but only with host dependencies.
```
define host{ define host{
use linux-server-template use linux-server-template
host_name vmware-master host_name vmware-master
@ -592,11 +644,13 @@ solvable with Icinga 1.x parents, but only with host dependencies.
address 192.168.28.1 address 192.168.28.1
parents vmware-master parents vmware-master
} }
```
By default all hosts in the hostgroup `vmware` should get the parent assigned (but not the `vmware-master` By default all hosts in the hostgroup `vmware` should get the parent assigned (but not the `vmware-master`
host itself). This isn't really solvable with Icinga 1.x parents, but only with host dependencies as shown host itself). This isn't really solvable with Icinga 1.x parents, but only with host dependencies as shown
below: below:
```
define hostdependency { define hostdependency {
dependent_hostgroup_name vmware dependent_hostgroup_name vmware
dependent_host_name !vmware-master dependent_host_name !vmware-master
@ -606,6 +660,7 @@ below:
execution_failure_criteria d,u execution_failure_criteria d,u
dependency_period testconfig-24x7 dependency_period testconfig-24x7
} }
```
When migrating to Icinga 2, the parents must be changed to a newly created host dependency. When migrating to Icinga 2, the parents must be changed to a newly created host dependency.
@ -620,7 +675,7 @@ Map the following attributes
The Icinga 2 configuration looks like this: The Icinga 2 configuration looks like this:
```
object Host "vmware-master" { object Host "vmware-master" {
import "linux-server-template" import "linux-server-template"
groups += [ "vmware" ] groups += [ "vmware" ]
@ -647,6 +702,7 @@ The Icinga 2 configuration looks like this:
ignore where host.vars.is_vmware_master ignore where host.vars.is_vmware_master
ignore where host.name == "vmware-master" ignore where host.name == "vmware-master"
} }
```
For easier identification you could add the `vars.is_vmware_master` attribute to the `vmware-master` For easier identification you could add the `vars.is_vmware_master` attribute to the `vmware-master`
host and let the dependency ignore that instead of the hardcoded host name. That's different host and let the dependency ignore that instead of the hardcoded host name. That's different
@ -655,6 +711,7 @@ to the Icinga 1.x example and a best practice hint only.
Another way to express the same configuration would be something like: Another way to express the same configuration would be something like:
```
object Host "vmware-master" { object Host "vmware-master" {
import "linux-server-template" import "linux-server-template"
groups += [ "vmware" ] groups += [ "vmware" ]
@ -678,6 +735,7 @@ Another way to express the same configuration would be something like:
apply Dependency "host-to-parent-" for (parent in host.vars.parents) to Host { apply Dependency "host-to-parent-" for (parent in host.vars.parents) to Host {
parent_host_name = parent parent_host_name = parent
} }
```
This example allows finer grained host-to-host dependency, as well as multiple dependency support. This example allows finer grained host-to-host dependency, as well as multiple dependency support.
@ -707,24 +765,30 @@ the Icinga daemon at startup.
icinga.cfg: icinga.cfg:
```
enable_notifications=1 enable_notifications=1
```
objects.cfg: objects.cfg:
```
define service { define service {
notifications_enabled 0 notifications_enabled 0
} }
```
Icinga 2 supports objects and (global) variables, but does not make a difference Icinga 2 supports objects and (global) variables, but does not make a difference
between the main configuration file or any other included file. between the main configuration file or any other included file.
icinga2.conf: icinga2.conf:
```
const EnableNotifications = true const EnableNotifications = true
object Service "test" { object Service "test" {
enable_notifications = false enable_notifications = false
} }
```
#### Sample Configuration and ITL <a id="differences-1x-2-sample-configuration-itl"></a> #### Sample Configuration and ITL <a id="differences-1x-2-sample-configuration-itl"></a>
@ -765,25 +829,33 @@ suffix in the given directory. Only absolute paths may be used. The `cfg_file`
and `cfg_dir` directives can include the same file twice which leads to and `cfg_dir` directives can include the same file twice which leads to
configuration errors in Icinga 1.x. configuration errors in Icinga 1.x.
```
cfg_file=/etc/icinga/objects/commands.cfg cfg_file=/etc/icinga/objects/commands.cfg
cfg_dir=/etc/icinga/objects cfg_dir=/etc/icinga/objects
```
Icinga 2 supports wildcard includes and relative paths, e.g. for including Icinga 2 supports wildcard includes and relative paths, e.g. for including
`conf.d/*.conf` in the same directory. `conf.d/*.conf` in the same directory.
```
include "conf.d/*.conf" include "conf.d/*.conf"
```
If you want to include files and directories recursively, you need to define If you want to include files and directories recursively, you need to define
a separate option and add the directory and an optional pattern. a separate option and add the directory and an optional pattern.
```
include_recursive "conf.d" include_recursive "conf.d"
```
A global search path for includes is available for advanced features like A global search path for includes is available for advanced features like
the Icinga Template Library (ITL) or additional monitoring plugins check the Icinga Template Library (ITL) or additional monitoring plugins check
command configuration. command configuration.
```
include <itl> include <itl>
include <plugins> include <plugins>
```
By convention the `.conf` suffix is used for Icinga 2 configuration files. By convention the `.conf` suffix is used for Icinga 2 configuration files.
@ -796,6 +868,7 @@ set in the `resource.cfg` configuration file in Icinga 1.x. By convention the
Icinga 2 uses global constants instead. In the default config these are Icinga 2 uses global constants instead. In the default config these are
set in the `constants.conf` configuration file: set in the `constants.conf` configuration file:
```
/** /**
* This file defines global constants which can be used in * This file defines global constants which can be used in
* the other configuration files. At a minimum the * the other configuration files. At a minimum the
@ -803,6 +876,7 @@ set in the `constants.conf` configuration file:
*/ */
const PluginDir = "/usr/lib/nagios/plugins" const PluginDir = "/usr/lib/nagios/plugins"
```
[Global macros](17-language-reference.md#constants) can only be defined once. Trying to modify a [Global macros](17-language-reference.md#constants) can only be defined once. Trying to modify a
global constant will result in an error. global constant will result in an error.
@ -825,6 +899,7 @@ Icinga Web 2 for example).
Object names are not specified using attributes (e.g. `service_description` for Object names are not specified using attributes (e.g. `service_description` for
services) like in Icinga 1.x but directly after their type definition. services) like in Icinga 1.x but directly after their type definition.
```
define service { define service {
host_name localhost host_name localhost
service_description ping4 service_description ping4
@ -833,17 +908,21 @@ services) like in Icinga 1.x but directly after their type definition.
object Service "ping4" { object Service "ping4" {
host_name = "localhost" host_name = "localhost"
} }
```
### Templates <a id="differences-1x-2-templates"></a> ### Templates <a id="differences-1x-2-templates"></a>
In Icinga 1.x templates are identified using the `register 0` setting. Icinga 2 In Icinga 1.x templates are identified using the `register 0` setting. Icinga 2
uses the `template` identifier: uses the `template` identifier:
```
template Service "ping4-template" { } template Service "ping4-template" { }
```
Icinga 1.x objects inherit from templates using the `use` attribute. Icinga 1.x objects inherit from templates using the `use` attribute.
Icinga 2 uses the keyword `import` with template names in double quotes. Icinga 2 uses the keyword `import` with template names in double quotes.
```
define service { define service {
service_description testservice service_description testservice
use tmpl1,tmpl2,tmpl3 use tmpl1,tmpl2,tmpl3
@ -854,6 +933,7 @@ Icinga 2 uses the keyword `import` with template names in double quotes.
import "tmpl2" import "tmpl2"
import "tmpl3" import "tmpl3"
} }
```
The last template overrides previously set values. The last template overrides previously set values.
@ -862,6 +942,7 @@ The last template overrides previously set values.
Icinga 1.x separates attribute and value pairs with whitespaces/tabs. Icinga 2 Icinga 1.x separates attribute and value pairs with whitespaces/tabs. Icinga 2
requires an equal sign (=) between them. requires an equal sign (=) between them.
```
define service { define service {
check_interval 5 check_interval 5
} }
@ -869,6 +950,7 @@ requires an equal sign (=) between them.
object Service "test" { object Service "test" {
check_interval = 5m check_interval = 5m
} }
```
Please note that the default time value is seconds if no duration literal Please note that the default time value is seconds if no duration literal
is given. `check_interval = 5` behaves the same as `check_interval = 5s`. is given. `check_interval = 5` behaves the same as `check_interval = 5s`.
@ -899,8 +981,10 @@ attributes for host and service objects are still available in Icinga 2.
Icinga 1.x custom variable attributes must be prefixed using an underscore (`_`). Icinga 1.x custom variable attributes must be prefixed using an underscore (`_`).
In Icinga 2 these attributes must be added to the `vars` dictionary as custom attributes. In Icinga 2 these attributes must be added to the `vars` dictionary as custom attributes.
```
vars.dn = "cn=icinga2-dev-host,ou=icinga,ou=main,ou=IcingaConfig,ou=LConf,dc=icinga,dc=org" vars.dn = "cn=icinga2-dev-host,ou=icinga,ou=main,ou=IcingaConfig,ou=LConf,dc=icinga,dc=org"
vars.cv = "my custom cmdb description" vars.cv = "my custom cmdb description"
```
These custom attributes are also used as [command parameters](03-monitoring-basics.md#command-passing-parameters). These custom attributes are also used as [command parameters](03-monitoring-basics.md#command-passing-parameters).
@ -1110,6 +1194,7 @@ Changes to global statistic macros:
The following external commands are not supported: The following external commands are not supported:
```
CHANGE_*MODATTR CHANGE_*MODATTR
CHANGE_CONTACT_HOST_NOTIFICATION_TIMEPERIOD CHANGE_CONTACT_HOST_NOTIFICATION_TIMEPERIOD
CHANGE_HOST_NOTIFICATION_TIMEPERIOD CHANGE_HOST_NOTIFICATION_TIMEPERIOD
@ -1151,6 +1236,7 @@ The following external commands are not supported:
STOP_OBSESSING_OVER_HOST_CHECKS STOP_OBSESSING_OVER_HOST_CHECKS
STOP_OBSESSING_OVER_SVC STOP_OBSESSING_OVER_SVC
STOP_OBSESSING_OVER_SVC_CHECKS STOP_OBSESSING_OVER_SVC_CHECKS
```
### Asynchronous Event Execution <a id="differences-1x-2-async-event-execution"></a> ### Asynchronous Event Execution <a id="differences-1x-2-async-event-execution"></a>
@ -1222,6 +1308,7 @@ attribute in the object. The old way of listing all group members in the group's
`members` attribute is available through `assign where` and `ignore where` `members` attribute is available through `assign where` and `ignore where`
expressions by using [group assign](03-monitoring-basics.md#group-assign-intro). expressions by using [group assign](03-monitoring-basics.md#group-assign-intro).
```
object Host "web-dev" { object Host "web-dev" {
import "generic-host" import "generic-host"
} }
@ -1230,12 +1317,14 @@ expressions by using [group assign](03-monitoring-basics.md#group-assign-intro).
display_name = "Dev Hosts" display_name = "Dev Hosts"
assign where match("*-dev", host.name) assign where match("*-dev", host.name)
} }
```
#### Add Service to Hostgroup where Host is Member <a id="differences-1x-2-service-hostgroup-host"></a> #### Add Service to Hostgroup where Host is Member <a id="differences-1x-2-service-hostgroup-host"></a>
In order to associate a service with all hosts in a host group the [apply](03-monitoring-basics.md#using-apply) In order to associate a service with all hosts in a host group the [apply](03-monitoring-basics.md#using-apply)
keyword can be used: keyword can be used:
```
apply Service "ping4" { apply Service "ping4" {
import "generic-service" import "generic-service"
@ -1243,6 +1332,7 @@ keyword can be used:
assign where "dev-hosts" in host.groups assign where "dev-hosts" in host.groups
} }
```
### Notifications <a id="differences-1x-2-notifications"></a> ### Notifications <a id="differences-1x-2-notifications"></a>
@ -1282,12 +1372,16 @@ Icinga 2 attempts to solve that problem in this way
Previously in Icinga 1.x it looked like this: Previously in Icinga 1.x it looked like this:
```
service -> (contact, contactgroup) -> notification command service -> (contact, contactgroup) -> notification command
```
In Icinga 2 it will look like this: In Icinga 2 it will look like this:
```
Service -> Notification -> NotificationCommand Service -> Notification -> NotificationCommand
-> User, UserGroup -> User, UserGroup
```
#### Escalations <a id="differences-1x-2-escalations"></a> #### Escalations <a id="differences-1x-2-escalations"></a>
@ -1295,8 +1389,10 @@ Escalations in Icinga 1.x require a separated object matching on existing
objects. Escalations happen between a defined start and end time which is objects. Escalations happen between a defined start and end time which is
calculated from the notification_interval: calculated from the notification_interval:
```
start = notification start + (notification_interval * first_notification) start = notification start + (notification_interval * first_notification)
end = notification start + (notification_interval * last_notification) end = notification start + (notification_interval * last_notification)
```
In theory first_notification and last_notification can be set to readable In theory first_notification and last_notification can be set to readable
numbers. In practice users are manipulating those attributes in combination numbers. In practice users are manipulating those attributes in combination
@ -1319,10 +1415,12 @@ Unlike Icinga 1.x with the 'notification_options' attribute with comma-separated
state and type filters, Icinga 2 uses two configuration attributes for that. state and type filters, Icinga 2 uses two configuration attributes for that.
All state and type filter use long names OR'd with a pipe together All state and type filter use long names OR'd with a pipe together
```
notification_options w,u,c,r,f,s notification_options w,u,c,r,f,s
states = [ Warning, Unknown, Critical ] states = [ Warning, Unknown, Critical ]
types = [ Problem, Recovery, FlappingStart, FlappingEnd, DowntimeStart, DowntimeEnd, DowntimeRemoved ] types = [ Problem, Recovery, FlappingStart, FlappingEnd, DowntimeStart, DowntimeEnd, DowntimeRemoved ]
```
Icinga 2 adds more fine-grained type filters for acknowledgements, downtime, Icinga 2 adds more fine-grained type filters for acknowledgements, downtime,
and flapping type (start, end, ...). and flapping type (start, end, ...).
@ -1358,7 +1456,9 @@ The Icinga 1.x flapping detection uses the last 21 states of a service. This
value is hardcoded and cannot be changed. The algorithm on determining a flapping state value is hardcoded and cannot be changed. The algorithm on determining a flapping state
is as follows: is as follows:
```
flapping value = (number of actual state changes / number of possible state changes) flapping value = (number of actual state changes / number of possible state changes)
```
The flapping value is then compared to the low and high flapping thresholds. The flapping value is then compared to the low and high flapping thresholds.