From: Michael Insel Date: Thu, 7 Mar 2019 18:56:49 +0000 (+0100) Subject: Unify documentation code formatting X-Git-Tag: v2.10.5~41 X-Git-Url: https://granicus.if.org/sourcecode?a=commitdiff_plain;h=59c8ce91d843c70233178c8dd18765d6cd17f20c;p=icinga2 Unify documentation code formatting This unifies the documentation code formatting to use only backticks. (cherry picked from commit 081d88436f66725152f5f5b58d07053da7ababd5) --- diff --git a/doc/04-configuring-icinga-2.md b/doc/04-configuring-icinga-2.md index 4d8770ced..434b8c9b8 100644 --- a/doc/04-configuring-icinga-2.md +++ b/doc/04-configuring-icinga-2.md @@ -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 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. */ - include_recursive "objects.d" +/* Local object configuration on our master instance. */ +include_recursive "objects.d" +``` This approach is used by the [Icinga 2 Puppet module](https://github.com/Icinga/puppet-icinga2). @@ -97,74 +99,82 @@ An example configuration file is installed for you in `/etc/icinga2/icinga2.conf Here's a brief description of the example configuration: - /** - * Icinga 2 configuration file - * -- this is where you define settings for the Icinga application including - * which hosts/services to check. - * - * For an overview of all available configuration options please refer - * to the documentation that is distributed as part of Icinga 2. - */ +``` +/** +* Icinga 2 configuration file +* -- this is where you define settings for the Icinga application including +* which hosts/services to check. +* +* For an overview of all available configuration options please refer +* to the documentation that is distributed as part of Icinga 2. +*/ +``` Icinga 2 supports [C/C++-style comments](17-language-reference.md#comments). - /** - * The constants.conf defines global constants. - */ - include "constants.conf" +/** +* The constants.conf defines global constants. +*/ +include "constants.conf" The `include` directive can be used to include other files. - /** - * The zones.conf defines zones for a cluster setup. - * Not required for single instance setups. - */ - include "zones.conf" +``` +/** +* The zones.conf defines zones for a cluster setup. +* Not required for single instance setups. +*/ +include "zones.conf" +``` 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. - /** - * The Icinga Template Library (ITL) provides a number of useful templates - * and command definitions. - * Common monitoring plugin command definitions are included separately. - */ - include - include - include - include - - /** - * This includes the Icinga 2 Windows plugins. These command definitions - * are required on a master node when a client is used as command endpoint. - */ - include - - /** - * This includes the NSClient++ check commands. These command definitions - * are required on a master node when a client is used as command endpoint. - */ - include - - /** - * The features-available directory contains a number of configuration - * files for features which can be enabled and disabled using the - * icinga2 feature enable / icinga2 feature disable CLI commands. - * These commands work by creating and removing symbolic links in - * the features-enabled directory. - */ - include "features-enabled/*.conf" +``` +/** +* The Icinga Template Library (ITL) provides a number of useful templates +* and command definitions. +* Common monitoring plugin command definitions are included separately. +*/ +include +include +include +include + +/** +* This includes the Icinga 2 Windows plugins. These command definitions +* are required on a master node when a client is used as command endpoint. +*/ +include + +/** +* This includes the NSClient++ check commands. These command definitions +* are required on a master node when a client is used as command endpoint. +*/ +include + +/** +* The features-available directory contains a number of configuration +* files for features which can be enabled and disabled using the +* icinga2 feature enable / icinga2 feature disable CLI commands. +* These commands work by creating and removing symbolic links in +* the features-enabled directory. +*/ +include "features-enabled/*.conf" +``` This `include` directive takes care of including the configuration files for all the features which have been enabled with `icinga2 feature enable`. See [Enabling/Disabling Features](11-cli-commands.md#enable-features) for more details. - /** - * 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 - * directory. Each of these files must have the file extension ".conf". - */ - include_recursive "conf.d" +``` +/** +* 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 +* directory. Each of these files must have the file extension ".conf". +*/ +include_recursive "conf.d" +``` 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. @@ -184,24 +194,26 @@ cluster setup. Example: - /* The directory which contains the plugins from the Monitoring Plugins project. */ - const PluginDir = "/usr/lib64/nagios/plugins" +``` +/* The directory which contains the plugins from the Monitoring Plugins project. */ +const PluginDir = "/usr/lib64/nagios/plugins" - /* The directory which contains the Manubulon plugins. - * Check the documentation, chapter "SNMP Manubulon Plugin Check Commands", for details. - */ - const ManubulonPluginDir = "/usr/lib64/nagios/plugins" +/* The directory which contains the Manubulon plugins. +* Check the documentation, chapter "SNMP Manubulon Plugin Check Commands", for details. +*/ +const ManubulonPluginDir = "/usr/lib64/nagios/plugins" - /* Our local instance name. By default this is the server's hostname as returned by `hostname --fqdn`. - * This should be the common name from the API certificate. - */ - //const NodeName = "localhost" +/* Our local instance name. By default this is the server's hostname as returned by `hostname --fqdn`. +* This should be the common name from the API certificate. +*/ +//const NodeName = "localhost" - /* Our local zone name. */ - const ZoneName = NodeName +/* Our local zone name. */ +const ZoneName = NodeName - /* Secret key for remote node tickets */ - const TicketSalt = "" +/* Secret key for remote node tickets */ +const TicketSalt = "" +``` The `ZoneName` and `TicketSalt` constants are required for remote client and distributed setups only. @@ -286,57 +298,59 @@ rules in [services.conf](04-configuring-icinga-2.md#services-conf) will automati generate a new service checking the `/icingaweb2` URI using the `http` check. - /* - * Host definitions with object attributes - * used for apply rules for Service, Notification, - * Dependency and ScheduledDowntime objects. - * - * Tip: Use `icinga2 object list --type Host` to - * list all host objects after running - * configuration validation (`icinga2 daemon -C`). - */ - - /* - * This is an example host based on your - * local host's FQDN. Specify the NodeName - * constant in `constants.conf` or use your - * own description, e.g. "db-host-1". - */ - - object Host NodeName { - /* Import the default host template defined in `templates.conf`. */ - import "generic-host" - - /* Specify the address attributes for checks e.g. `ssh` or `http`. */ - address = "127.0.0.1" - address6 = "::1" - - /* Set custom attribute `os` for hostgroup assignment in `groups.conf`. */ - vars.os = "Linux" - - /* Define http vhost attributes for service apply rules in `services.conf`. */ - vars.http_vhosts["http"] = { - http_uri = "/" - } - /* Uncomment if you've sucessfully installed Icinga Web 2. */ - //vars.http_vhosts["Icinga Web 2"] = { - // http_uri = "/icingaweb2" - //} - - /* Define disks and attributes for service apply rules in `services.conf`. */ - vars.disks["disk"] = { - /* No parameters. */ - } - vars.disks["disk /"] = { - disk_partitions = "/" - } - - /* Define notification mail attributes for notification apply rules in `notifications.conf`. */ - vars.notification["mail"] = { - /* The UserGroup `icingaadmins` is defined in `users.conf`. */ - groups = [ "icingaadmins" ] - } - } +``` +/* +* Host definitions with object attributes +* used for apply rules for Service, Notification, +* Dependency and ScheduledDowntime objects. +* +* Tip: Use `icinga2 object list --type Host` to +* list all host objects after running +* configuration validation (`icinga2 daemon -C`). +*/ + +/* + * This is an example host based on your + * local host's FQDN. Specify the NodeName + * constant in `constants.conf` or use your + * own description, e.g. "db-host-1". + */ + +object Host NodeName { + /* Import the default host template defined in `templates.conf`. */ + import "generic-host" + + /* Specify the address attributes for checks e.g. `ssh` or `http`. */ + address = "127.0.0.1" + address6 = "::1" + + /* Set custom attribute `os` for hostgroup assignment in `groups.conf`. */ + vars.os = "Linux" + + /* Define http vhost attributes for service apply rules in `services.conf`. */ + vars.http_vhosts["http"] = { + http_uri = "/" + } + /* Uncomment if you've sucessfully installed Icinga Web 2. */ + //vars.http_vhosts["Icinga Web 2"] = { + // http_uri = "/icingaweb2" + //} + + /* Define disks and attributes for service apply rules in `services.conf`. */ + vars.disks["disk"] = { + /* No parameters. */ + } + vars.disks["disk /"] = { + disk_partitions = "/" + } + + /* Define notification mail attributes for notification apply rules in `notifications.conf`. */ + vars.notification["mail"] = { + /* The UserGroup `icingaadmins` is defined in `users.conf`. */ + groups = [ "icingaadmins" ] + } +} +``` 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. @@ -376,16 +390,18 @@ which we enabled earlier by including the `itl` and `plugins` configuration file Example `load` service apply rule: - apply Service "load" { - import "generic-service" +``` +apply Service "load" { +import "generic-service" - check_command = "load" +check_command = "load" - /* Used by the ScheduledDowntime apply rule in `downtimes.conf`. */ - vars.backup_downtime = "02:00-03:00" +/* Used by the ScheduledDowntime apply rule in `downtimes.conf`. */ +vars.backup_downtime = "02:00-03:00" - assign where host.name == NodeName - } +assign where host.name == NodeName +} +``` 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) @@ -403,13 +419,15 @@ may be used in `assign where` conditions. Multiple `assign where` condition can be combined with `AND` using the `&&` operator as shown in the `ssh` example: - apply Service "ssh" { - import "generic-service" +``` +apply Service "ssh" { + import "generic-service" - check_command = "ssh" + check_command = "ssh" - 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` attribute defined `AND` having the custom attribute `os` set to the string @@ -429,16 +447,17 @@ 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): - ... - /* Define disks and attributes for service apply rules in `services.conf`. */ - vars.disks["disk"] = { - /* No parameters. */ - } - vars.disks["disk /"] = { - disk_partition = "/" - } - ... - +``` +... + /* Define disks and attributes for service apply rules in `services.conf`. */ + vars.disks["disk"] = { + /* No parameters. */ + } + vars.disks["disk /"] = { + disk_partition = "/" + } +... +``` This dictionary contains multiple service names we want to monitor. `disk` should just check all available disks, while `disk /` will pass an additional @@ -466,13 +485,15 @@ generated service Configuration example: - apply Service for (disk => config in host.vars.disks) { - import "generic-service" +``` +apply Service for (disk => config in host.vars.disks) { + import "generic-service" - check_command = "disk" + check_command = "disk" - vars += config - } + vars += config +} +``` 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 @@ -494,19 +515,20 @@ 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 [notifications.conf](04-configuring-icinga-2.md#notifications-conf) for notification apply rules. - object User "icingaadmin" { - import "generic-user" - - display_name = "Icinga 2 Admin" - groups = [ "icingaadmins" ] +``` +object User "icingaadmin" { + import "generic-user" - email = "icinga@localhost" - } + display_name = "Icinga 2 Admin" + groups = [ "icingaadmins" ] - object UserGroup "icingaadmins" { - display_name = "Icinga 2 Admin Group" - } + email = "icinga@localhost" +} +object UserGroup "icingaadmins" { + display_name = "Icinga 2 Admin Group" +} +``` #### notifications.conf @@ -527,23 +549,25 @@ 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 implicitely use the `icingaadmins` UserGroup defined in [users.conf](04-configuring-icinga-2.md#users-conf). - apply Notification "mail-icingaadmin" to Host { - import "mail-host-notification" +``` +apply Notification "mail-icingaadmin" to Host { + import "mail-host-notification" - user_groups = host.vars.notification.mail.groups - users = host.vars.notification.mail.users + user_groups = host.vars.notification.mail.groups + users = host.vars.notification.mail.users - assign where host.vars.notification.mail - } + assign where host.vars.notification.mail +} - apply Notification "mail-icingaadmin" to Service { - import "mail-service-notification" +apply Notification "mail-icingaadmin" to Service { + import "mail-service-notification" - user_groups = host.vars.notification.mail.groups - users = host.vars.notification.mail.users + user_groups = host.vars.notification.mail.groups + users = host.vars.notification.mail.users - assign where host.vars.notification.mail - } + assign where host.vars.notification.mail +} +``` More details on defining notifications and their additional attributes such as filters can be read in [this chapter](03-monitoring-basics.md#alert-notifications). @@ -565,85 +589,91 @@ a member of the host group `linux-servers`. 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). - object HostGroup "linux-servers" { - display_name = "Linux Servers" +``` +object HostGroup "linux-servers" { + display_name = "Linux Servers" - assign where host.vars.os == "Linux" - } + assign where host.vars.os == "Linux" +} - object HostGroup "windows-servers" { - display_name = "Windows Servers" +object HostGroup "windows-servers" { + display_name = "Windows Servers" - assign where host.vars.os == "Windows" - } + assign where host.vars.os == "Windows" +} +``` 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 and the attribute string to match with. - object ServiceGroup "ping" { - display_name = "Ping Checks" +``` +object ServiceGroup "ping" { + display_name = "Ping Checks" - assign where match("ping*", service.name) - } + assign where match("ping*", service.name) +} - object ServiceGroup "http" { - display_name = "HTTP Checks" +object ServiceGroup "http" { + display_name = "HTTP Checks" - assign where match("http*", service.check_command) - } + assign where match("http*", service.check_command) +} - object ServiceGroup "disk" { - display_name = "Disk Checks" - - assign where match("disk*", service.check_command) - } +object ServiceGroup "disk" { + display_name = "Disk Checks" + assign where match("disk*", service.check_command) +} +``` #### templates.conf Most of the example configuration objects use generic global templates by default: - template Host "generic-host" { - max_check_attempts = 5 - check_interval = 1m - retry_interval = 30s +``` +template Host "generic-host" { + max_check_attempts = 5 + check_interval = 1m + retry_interval = 30s - check_command = "hostalive" - } + check_command = "hostalive" +} - template Service "generic-service" { - max_check_attempts = 3 - check_interval = 1m - retry_interval = 30s - } +template Service "generic-service" { + max_check_attempts = 3 + check_interval = 1m + retry_interval = 30s +} +``` The `hostalive` check command is part of the [Plugin Check Commands](10-icinga-template-library.md#icinga-template-library). +``` +template Notification "mail-host-notification" { + command = "mail-host-notification" - template Notification "mail-host-notification" { - command = "mail-host-notification" - - states = [ Up, Down ] - types = [ Problem, Acknowledgement, Recovery, Custom, - FlappingStart, FlappingEnd, - DowntimeStart, DowntimeEnd, DowntimeRemoved ] + states = [ Up, Down ] + types = [ Problem, Acknowledgement, Recovery, Custom, + FlappingStart, FlappingEnd, + DowntimeStart, DowntimeEnd, DowntimeRemoved ] - period = "24x7" - } + period = "24x7" +} - template Notification "mail-service-notification" { - command = "mail-service-notification" +template Notification "mail-service-notification" { + command = "mail-service-notification" - states = [ OK, Warning, Critical, Unknown ] - types = [ Problem, Acknowledgement, Recovery, Custom, - FlappingStart, FlappingEnd, - DowntimeStart, DowntimeEnd, DowntimeRemoved ] + states = [ OK, Warning, Critical, Unknown ] + types = [ Problem, Acknowledgement, Recovery, Custom, + FlappingStart, FlappingEnd, + DowntimeStart, DowntimeEnd, DowntimeRemoved ] - period = "24x7" - } + period = "24x7" +} +``` More details on `Notification` object attributes can be found [here](09-object-types.md#objecttype-notification). @@ -658,23 +688,24 @@ for the time ranges required for recurring downtime slots. Learn more about downtimes in [this chapter](08-advanced-topics.md#downtimes). - apply ScheduledDowntime "backup-downtime" to Service { - author = "icingaadmin" - comment = "Scheduled downtime for backup" - - ranges = { - monday = service.vars.backup_downtime - tuesday = service.vars.backup_downtime - wednesday = service.vars.backup_downtime - thursday = service.vars.backup_downtime - friday = service.vars.backup_downtime - saturday = service.vars.backup_downtime - sunday = service.vars.backup_downtime - } - - assign where service.vars.backup_downtime != "" - } - +``` +apply ScheduledDowntime "backup-downtime" to Service { + author = "icingaadmin" + comment = "Scheduled downtime for backup" + + ranges = { + monday = service.vars.backup_downtime + tuesday = service.vars.backup_downtime + wednesday = service.vars.backup_downtime + thursday = service.vars.backup_downtime + friday = service.vars.backup_downtime + saturday = service.vars.backup_downtime + sunday = service.vars.backup_downtime + } + + assign where service.vars.backup_downtime != "" +} +``` #### timeperiods.conf diff --git a/doc/05-service-monitoring.md b/doc/05-service-monitoring.md index b8e7375c0..aeeeb481c 100644 --- a/doc/05-service-monitoring.md +++ b/doc/05-service-monitoring.md @@ -15,24 +15,28 @@ 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) configuration file: - # cp check_snmp_int.pl /opt/monitoring/plugins - # chmod +x /opt/monitoring/plugins/check_snmp_int.pl +``` +# cp check_snmp_int.pl /opt/monitoring/plugins +# chmod +x /opt/monitoring/plugins/check_snmp_int.pl - # cat /etc/icinga2/constants.conf - /** - * This file defines global constants which can be used in - * the other configuration files. At a minimum the - * PluginDir constant should be defined. - */ +# cat /etc/icinga2/constants.conf +/** + * This file defines global constants which can be used in + * the other configuration files. At a minimum the + * PluginDir constant should be defined. + */ - const PluginDir = "/usr/lib/nagios/plugins" - const CustomPluginDir = "/opt/monitoring/plugins" +const PluginDir = "/usr/lib/nagios/plugins" +const CustomPluginDir = "/opt/monitoring/plugins" +``` 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: - # su - icinga -s /bin/bash - $ /opt/monitoring/plugins/check_snmp_int.pl --help +``` +# su - icinga -s /bin/bash +$ /opt/monitoring/plugins/check_snmp_int.pl --help +``` Additional libraries may be required for some plugins. Please consult the plugin documentation and/or the included README file for installation instructions. @@ -64,30 +68,31 @@ 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: - object CheckCommand "my-snmp-int" { - command = [ CustomPluginDir + "/check_snmp_int.pl" ] - - arguments = { - "-H" = "$snmp_address$" - "-C" = "$snmp_community$" - "-p" = "$snmp_port$" - "-2" = { - set_if = "$snmp_v2$" - } - "-n" = "$snmp_interface$" - "-f" = { - set_if = "$snmp_perf$" - } - "-w" = "$snmp_warn$" - "-c" = "$snmp_crit$" - } - - vars.snmp_v2 = true - vars.snmp_perf = true - vars.snmp_warn = "300,400" - vars.snmp_crit = "0,600" +``` +object CheckCommand "my-snmp-int" { + command = [ CustomPluginDir + "/check_snmp_int.pl" ] + + arguments = { + "-H" = "$snmp_address$" + "-C" = "$snmp_community$" + "-p" = "$snmp_port$" + "-2" = { + set_if = "$snmp_v2$" + } + "-n" = "$snmp_interface$" + "-f" = { + set_if = "$snmp_perf$" } + "-w" = "$snmp_warn$" + "-c" = "$snmp_crit$" + } + vars.snmp_v2 = true + vars.snmp_perf = true + vars.snmp_warn = "300,400" + vars.snmp_crit = "0,600" +} +``` For further information on your monitoring configuration read the [Monitoring Basics](03-monitoring-basics.md#monitoring-basics) chapter. @@ -127,28 +132,30 @@ Common best practices when creating a new plugin are for example: Example skeleton: - # 1. include optional libraries - # 2. global variables - # 3. helper functions and/or classes - # 4. define timeout condition - - if () then - print "UNKNOWN - Timeout (...) reached | 'time'=30.0 - endif - - # 5. main method - - - - if () then - print "CRITICAL - ... | 'time'=0.1 'myperfdatavalue'=5.0 - exit(2) - else if () then - print "WARNING - ... | 'time'=0.1 'myperfdatavalue'=3.0 - exit(1) - else - print "OK - ... | 'time'=0.2 'myperfdatavalue'=1.0 - endif +``` +# 1. include optional libraries +# 2. global variables +# 3. helper functions and/or classes +# 4. define timeout condition + +if () then + print "UNKNOWN - Timeout (...) reached | 'time'=30.0 +endif + +# 5. main method + + + +if () then + print "CRITICAL - ... | 'time'=0.1 'myperfdatavalue'=5.0 + exit(2) +else if () then + print "WARNING - ... | 'time'=0.1 'myperfdatavalue'=3.0 + exit(1) +else + print "OK - ... | 'time'=0.2 'myperfdatavalue'=1.0 +endif +``` There are various plugin libraries available which will help with plugin execution and output formatting too, for example diff --git a/doc/06-distributed-monitoring.md b/doc/06-distributed-monitoring.md index 48cfd1b26..b2a00ee10 100644 --- a/doc/06-distributed-monitoring.md +++ b/doc/06-distributed-monitoring.md @@ -52,19 +52,21 @@ Zones depend on a parent-child relationship in order to trust each other. Have a look at this example for the `satellite` zones which have the `master` zone as a parent zone: - object Zone "master" { - //... - } +``` +object Zone "master" { + //... +} - object Zone "satellite region 1" { - parent = "master" - //... - } +object Zone "satellite region 1" { + parent = "master" + //... +} - object Zone "satellite region 2" { - parent = "master" - //... - } +object Zone "satellite region 2" { + parent = "master" + //... +} +``` There are certain limitations for child zones, e.g. their members are not allowed to send configuration commands to the parent zone members. Vice versa, the @@ -83,22 +85,24 @@ Nodes which are a member of a zone are so-called [Endpoint](09-object-types.md#o Here is an example configuration for two endpoints in different zones: - object Endpoint "icinga2-master1.localdomain" { - host = "192.168.56.101" - } +``` +object Endpoint "icinga2-master1.localdomain" { + host = "192.168.56.101" +} - object Endpoint "icinga2-satellite1.localdomain" { - host = "192.168.56.105" - } +object Endpoint "icinga2-satellite1.localdomain" { + host = "192.168.56.105" +} - object Zone "master" { - endpoints = [ "icinga2-master1.localdomain" ] - } +object Zone "master" { + endpoints = [ "icinga2-master1.localdomain" ] +} - object Zone "satellite" { - endpoints = [ "icinga2-satellite1.localdomain" ] - parent = "master" - } +object Zone "satellite" { + endpoints = [ "icinga2-satellite1.localdomain" ] + parent = "master" +} +``` All endpoints in the same zone work as high-availability setup. For example, if you have two nodes in the `master` zone, they will load-balance the check execution. @@ -135,7 +139,9 @@ and `accept_config` can be configured here. In order to use the `api` feature you need to enable it and restart Icinga 2. - icinga2 feature enable api +``` +icinga2 feature enable api +``` ## Conventions @@ -359,24 +365,28 @@ Required information: The following example shows how to generate a ticket on the master node `icinga2-master1.localdomain` for the client `icinga2-client1.localdomain`: - [root@icinga2-master1.localdomain /]# icinga2 pki ticket --cn icinga2-client1.localdomain +``` +[root@icinga2-master1.localdomain /]# icinga2 pki ticket --cn icinga2-client1.localdomain +``` Querying the [Icinga 2 API](12-icinga2-api.md#icinga2-api) on the master requires an [ApiUser](12-icinga2-api.md#icinga2-api-authentication) object with at least the `actions/generate-ticket` permission. - [root@icinga2-master1.localdomain /]# vim /etc/icinga2/conf.d/api-users.conf +``` +[root@icinga2-master1.localdomain /]# vim /etc/icinga2/conf.d/api-users.conf - object ApiUser "client-pki-ticket" { - password = "bea11beb7b810ea9ce6ea" //change this - permissions = [ "actions/generate-ticket" ] - } +object ApiUser "client-pki-ticket" { + password = "bea11beb7b810ea9ce6ea" //change this + permissions = [ "actions/generate-ticket" ] +} - [root@icinga2-master1.localdomain /]# systemctl restart icinga2 +[root@icinga2-master1.localdomain /]# systemctl restart icinga2 Retrieve the ticket on the master node `icinga2-master1.localdomain` with `curl`, for example: - [root@icinga2-master1.localdomain /]# curl -k -s -u client-pki-ticket:bea11beb7b810ea9ce6ea -H 'Accept: application/json' \ - -X POST 'https://localhost:5665/v1/actions/generate-ticket' -d '{ "cn": "icinga2-client1.localdomain" }' + [root@icinga2-master1.localdomain /]# curl -k -s -u client-pki-ticket:bea11beb7b810ea9ce6ea -H 'Accept: application/json' \ + -X POST 'https://localhost:5665/v1/actions/generate-ticket' -d '{ "cn": "icinga2-client1.localdomain" }' +``` Store that ticket number for the satellite/client setup below. @@ -448,8 +458,10 @@ The next step is to run the `node wizard` CLI command. In this example we're generating a ticket on the master node `icinga2-master1.localdomain` for the client `icinga2-client1.localdomain`: - [root@icinga2-master1.localdomain /]# icinga2 pki ticket --cn icinga2-client1.localdomain - 4f75d2ecd253575fe9180938ebff7cbca262f96e +``` +[root@icinga2-master1.localdomain /]# icinga2 pki ticket --cn icinga2-client1.localdomain +4f75d2ecd253575fe9180938ebff7cbca262f96e +``` Note: You don't need this step if you have chosen to use [On-Demand CSR Signing](06-distributed-monitoring.md#distributed-monitoring-setup-on-demand-csr-signing). @@ -923,15 +935,17 @@ Include the endpoint and zone configuration on **both** nodes in the file `/etc/ The endpoint configuration could look like this, for example: - [root@icinga2-client1.localdomain /]# vim /etc/icinga2/zones.conf +``` +[root@icinga2-client1.localdomain /]# vim /etc/icinga2/zones.conf - object Endpoint "icinga2-master1.localdomain" { - host = "192.168.56.101" - } +object Endpoint "icinga2-master1.localdomain" { + host = "192.168.56.101" +} - object Endpoint "icinga2-client1.localdomain" { - host = "192.168.56.111" - } +object Endpoint "icinga2-client1.localdomain" { + host = "192.168.56.111" +} +``` Next, you need to define two zones. There is no naming convention, best practice is to either use `master`, `satellite`/`client-fqdn` or to choose region names for example `Europe`, `USA` and `Asia`, though. @@ -940,17 +954,19 @@ is to use the client's FQDN for all object names. The `master` zone is a parent of the `icinga2-client1.localdomain` zone: - [root@icinga2-client1.localdomain /]# vim /etc/icinga2/zones.conf +``` +[root@icinga2-client1.localdomain /]# vim /etc/icinga2/zones.conf - object Zone "master" { - endpoints = [ "icinga2-master1.localdomain" ] //array with endpoint names - } +object Zone "master" { + endpoints = [ "icinga2-master1.localdomain" ] //array with endpoint names +} - object Zone "icinga2-client1.localdomain" { - endpoints = [ "icinga2-client1.localdomain" ] +object Zone "icinga2-client1.localdomain" { + endpoints = [ "icinga2-client1.localdomain" ] - parent = "master" //establish zone hierarchy - } + parent = "master" //establish zone hierarchy +} + ``` You don't need any local configuration on the client except for CheckCommand definitions which can be synced using the global zone @@ -974,11 +990,13 @@ on both nodes. Example on CentOS 7: - [root@icinga2-client1.localdomain /]# icinga2 daemon -C - [root@icinga2-client1.localdomain /]# systemctl restart icinga2 +``` +[root@icinga2-client1.localdomain /]# icinga2 daemon -C +[root@icinga2-client1.localdomain /]# systemctl restart icinga2 - [root@icinga2-master1.localdomain /]# icinga2 daemon -C - [root@icinga2-master1.localdomain /]# systemctl restart icinga2 +[root@icinga2-master1.localdomain /]# icinga2 daemon -C +[root@icinga2-master1.localdomain /]# systemctl restart icinga2 +``` Once the clients have successfully connected, you are ready for the next step: **execute a remote check on the client using the command endpoint**. @@ -986,7 +1004,9 @@ a remote check on the client using the command endpoint**. Include the host and service object configuration in the `master` zone -- this will help adding a secondary master for high-availability later. - [root@icinga2-master1.localdomain /]# mkdir -p /etc/icinga2/zones.d/master +``` +[root@icinga2-master1.localdomain /]# mkdir -p /etc/icinga2/zones.d/master +``` Add the host and service objects you want to monitor. There is no limitation for files and directories -- best practice is to @@ -995,46 +1015,55 @@ sort things by type. By convention a master/satellite/client host object should use the same name as the endpoint object. You can also add multiple hosts which execute checks against remote services/clients. - [root@icinga2-master1.localdomain /]# cd /etc/icinga2/zones.d/master - [root@icinga2-master1.localdomain /etc/icinga2/zones.d/master]# vim hosts.conf +``` +[root@icinga2-master1.localdomain /]# cd /etc/icinga2/zones.d/master +[root@icinga2-master1.localdomain /etc/icinga2/zones.d/master]# vim hosts.conf - object Host "icinga2-client1.localdomain" { - check_command = "hostalive" //check is executed on the master - address = "192.168.56.111" +object Host "icinga2-client1.localdomain" { + check_command = "hostalive" //check is executed on the master + address = "192.168.56.111" - vars.client_endpoint = name //follows the convention that host name == endpoint name - } + vars.client_endpoint = name //follows the convention that host name == endpoint name +} +``` Given that you are monitoring a Linux client, we'll add a remote [disk](10-icinga-template-library.md#plugin-check-command-disk) check. - [root@icinga2-master1.localdomain /etc/icinga2/zones.d/master]# vim services.conf +``` +[root@icinga2-master1.localdomain /etc/icinga2/zones.d/master]# vim services.conf - apply Service "disk" { - check_command = "disk" +apply Service "disk" { + check_command = "disk" - //specify where the check is executed - command_endpoint = host.vars.client_endpoint + //specify where the check is executed + command_endpoint = host.vars.client_endpoint - assign where host.vars.client_endpoint - } + assign where host.vars.client_endpoint +} +``` If you have your own custom `CheckCommand` definition, add it to the global zone: - [root@icinga2-master1.localdomain /]# mkdir -p /etc/icinga2/zones.d/global-templates - [root@icinga2-master1.localdomain /]# vim /etc/icinga2/zones.d/global-templates/commands.conf +``` +[root@icinga2-master1.localdomain /]# mkdir -p /etc/icinga2/zones.d/global-templates +[root@icinga2-master1.localdomain /]# vim /etc/icinga2/zones.d/global-templates/commands.conf - object CheckCommand "my-cmd" { - //... - } +object CheckCommand "my-cmd" { + //... +} +``` Save the changes and validate the configuration on the master node: - [root@icinga2-master1.localdomain /]# icinga2 daemon -C - +``` +[root@icinga2-master1.localdomain /]# icinga2 daemon -C +``` Restart the Icinga 2 daemon (example for CentOS 7): - [root@icinga2-master1.localdomain /]# systemctl restart icinga2 +``` +[root@icinga2-master1.localdomain /]# systemctl restart icinga2 +``` The following steps will happen: @@ -1084,15 +1113,17 @@ Include the endpoint and zone configuration on **both** nodes in the file `/etc/ The endpoint configuration could look like this: - [root@icinga2-client2.localdomain /]# vim /etc/icinga2/zones.conf +``` +[root@icinga2-client2.localdomain /]# vim /etc/icinga2/zones.conf - object Endpoint "icinga2-master1.localdomain" { - host = "192.168.56.101" - } +object Endpoint "icinga2-master1.localdomain" { + host = "192.168.56.101" +} - object Endpoint "icinga2-client2.localdomain" { - host = "192.168.56.112" - } +object Endpoint "icinga2-client2.localdomain" { + host = "192.168.56.112" +} +``` Next, you need to define two zones. There is no naming convention, best practice is to either use `master`, `satellite`/`client-fqdn` or to choose region names for example `Europe`, `USA` and `Asia`, though. @@ -1101,40 +1132,45 @@ is to use the client's FQDN for all object names. The `master` zone is a parent of the `icinga2-client2.localdomain` zone: - [root@icinga2-client2.localdomain /]# vim /etc/icinga2/zones.conf +``` +[root@icinga2-client2.localdomain /]# vim /etc/icinga2/zones.conf - object Zone "master" { - endpoints = [ "icinga2-master1.localdomain" ] //array with endpoint names - } +object Zone "master" { + endpoints = [ "icinga2-master1.localdomain" ] //array with endpoint names +} - object Zone "icinga2-client2.localdomain" { - endpoints = [ "icinga2-client2.localdomain" ] +object Zone "icinga2-client2.localdomain" { + endpoints = [ "icinga2-client2.localdomain" ] - parent = "master" //establish zone hierarchy - } + parent = "master" //establish zone hierarchy +} +``` Edit the `api` feature on the client `icinga2-client2.localdomain` in the `/etc/icinga2/features-enabled/api.conf` file and set `accept_config` to `true`. - [root@icinga2-client2.localdomain /]# vim /etc/icinga2/features-enabled/api.conf +``` +[root@icinga2-client2.localdomain /]# vim /etc/icinga2/features-enabled/api.conf - object ApiListener "api" { - //... - accept_config = true - } +object ApiListener "api" { + //... + accept_config = true +} +``` Now it is time to validate the configuration and to restart the Icinga 2 daemon on both nodes. Example on CentOS 7: - [root@icinga2-client2.localdomain /]# icinga2 daemon -C - [root@icinga2-client2.localdomain /]# systemctl restart icinga2 - - [root@icinga2-master1.localdomain /]# icinga2 daemon -C - [root@icinga2-master1.localdomain /]# systemctl restart icinga2 +``` +[root@icinga2-client2.localdomain /]# icinga2 daemon -C +[root@icinga2-client2.localdomain /]# systemctl restart icinga2 +[root@icinga2-master1.localdomain /]# icinga2 daemon -C +[root@icinga2-master1.localdomain /]# systemctl restart icinga2 +``` **Tip**: Best practice is to use a [global zone](06-distributed-monitoring.md#distributed-monitoring-global-zone-config-sync) for common configuration items (check commands, templates, groups, etc.). @@ -1146,7 +1182,9 @@ Navigate to `/etc/icinga2/zones.d` on your master node `icinga2-master1.localdomain` and create a new directory with the same name as your satellite/client zone name: - [root@icinga2-master1.localdomain /]# mkdir -p /etc/icinga2/zones.d/icinga2-client2.localdomain +``` +[root@icinga2-master1.localdomain /]# mkdir -p /etc/icinga2/zones.d/icinga2-client2.localdomain +``` Add the host and service objects you want to monitor. There is no limitation for files and directories -- best practice is to @@ -1155,33 +1193,41 @@ sort things by type. By convention a master/satellite/client host object should use the same name as the endpoint object. You can also add multiple hosts which execute checks against remote services/clients. - [root@icinga2-master1.localdomain /]# cd /etc/icinga2/zones.d/icinga2-client2.localdomain - [root@icinga2-master1.localdomain /etc/icinga2/zones.d/icinga2-client2.localdomain]# vim hosts.conf +``` +[root@icinga2-master1.localdomain /]# cd /etc/icinga2/zones.d/icinga2-client2.localdomain +[root@icinga2-master1.localdomain /etc/icinga2/zones.d/icinga2-client2.localdomain]# vim hosts.conf - object Host "icinga2-client2.localdomain" { - check_command = "hostalive" - address = "192.168.56.112" - zone = "master" //optional trick: sync the required host object to the client, but enforce the "master" zone to execute the check - } +object Host "icinga2-client2.localdomain" { + check_command = "hostalive" + address = "192.168.56.112" + zone = "master" //optional trick: sync the required host object to the client, but enforce the "master" zone to execute the check +} +``` Given that you are monitoring a Linux client we'll just add a local [disk](10-icinga-template-library.md#plugin-check-command-disk) check. - [root@icinga2-master1.localdomain /etc/icinga2/zones.d/icinga2-client2.localdomain]# vim services.conf +``` +[root@icinga2-master1.localdomain /etc/icinga2/zones.d/icinga2-client2.localdomain]# vim services.conf - object Service "disk" { - host_name = "icinga2-client2.localdomain" +object Service "disk" { + host_name = "icinga2-client2.localdomain" - check_command = "disk" - } + check_command = "disk" +} +``` Save the changes and validate the configuration on the master node: - [root@icinga2-master1.localdomain /]# icinga2 daemon -C +``` +[root@icinga2-master1.localdomain /]# icinga2 daemon -C +``` Restart the Icinga 2 daemon (example for CentOS 7): - [root@icinga2-master1.localdomain /]# systemctl restart icinga2 +``` +[root@icinga2-master1.localdomain /]# systemctl restart icinga2 +``` The following steps will happen: @@ -1236,39 +1282,41 @@ Setup requirements: Edit the `zones.conf` configuration file on the master: - [root@icinga2-master1.localdomain /]# vim /etc/icinga2/zones.conf +``` +[root@icinga2-master1.localdomain /]# vim /etc/icinga2/zones.conf - object Endpoint "icinga2-master1.localdomain" { - } +object Endpoint "icinga2-master1.localdomain" { +} - object Endpoint "icinga2-client1.localdomain" { - host = "192.168.56.111" //the master actively tries to connect to the client - } +object Endpoint "icinga2-client1.localdomain" { + host = "192.168.56.111" //the master actively tries to connect to the client +} - object Endpoint "icinga2-client2.localdomain" { - host = "192.168.56.112" //the master actively tries to connect to the client - } +object Endpoint "icinga2-client2.localdomain" { + host = "192.168.56.112" //the master actively tries to connect to the client +} - object Zone "master" { - endpoints = [ "icinga2-master1.localdomain" ] - } +object Zone "master" { + endpoints = [ "icinga2-master1.localdomain" ] +} - object Zone "icinga2-client1.localdomain" { - endpoints = [ "icinga2-client1.localdomain" ] +object Zone "icinga2-client1.localdomain" { + endpoints = [ "icinga2-client1.localdomain" ] - parent = "master" - } + parent = "master" +} - object Zone "icinga2-client2.localdomain" { - endpoints = [ "icinga2-client2.localdomain" ] +object Zone "icinga2-client2.localdomain" { + endpoints = [ "icinga2-client2.localdomain" ] - parent = "master" - } + parent = "master" +} - /* sync global commands */ - object Zone "global-templates" { - global = true - } +/* sync global commands */ +object Zone "global-templates" { + global = true +} +``` The two client nodes do not necessarily need to know about each other. The only important thing is that they know about the parent zone and their endpoint members (and optionally the global zone). @@ -1278,53 +1326,55 @@ the client will actively try to connect to the master node. Since we've specifie endpoint's attribute on the master node already, we don't want the clients to connect to the master. **Choose one [connection direction](06-distributed-monitoring.md#distributed-monitoring-advanced-hints-connection-direction).** - [root@icinga2-client1.localdomain /]# vim /etc/icinga2/zones.conf +``` +[root@icinga2-client1.localdomain /]# vim /etc/icinga2/zones.conf - object Endpoint "icinga2-master1.localdomain" { - //do not actively connect to the master by leaving out the 'host' attribute - } +object Endpoint "icinga2-master1.localdomain" { + //do not actively connect to the master by leaving out the 'host' attribute +} - object Endpoint "icinga2-client1.localdomain" { - } +object Endpoint "icinga2-client1.localdomain" { +} - object Zone "master" { - endpoints = [ "icinga2-master1.localdomain" ] - } +object Zone "master" { + endpoints = [ "icinga2-master1.localdomain" ] +} - object Zone "icinga2-client1.localdomain" { - endpoints = [ "icinga2-client1.localdomain" ] +object Zone "icinga2-client1.localdomain" { + endpoints = [ "icinga2-client1.localdomain" ] - parent = "master" - } + parent = "master" +} - /* sync global commands */ - object Zone "global-templates" { - global = true - } +/* sync global commands */ +object Zone "global-templates" { + global = true +} - [root@icinga2-client2.localdomain /]# vim /etc/icinga2/zones.conf +[root@icinga2-client2.localdomain /]# vim /etc/icinga2/zones.conf - object Endpoint "icinga2-master1.localdomain" { - //do not actively connect to the master by leaving out the 'host' attribute - } +object Endpoint "icinga2-master1.localdomain" { + //do not actively connect to the master by leaving out the 'host' attribute +} - object Endpoint "icinga2-client2.localdomain" { - } +object Endpoint "icinga2-client2.localdomain" { +} - object Zone "master" { - endpoints = [ "icinga2-master1.localdomain" ] - } +object Zone "master" { + endpoints = [ "icinga2-master1.localdomain" ] +} - object Zone "icinga2-client2.localdomain" { - endpoints = [ "icinga2-client2.localdomain" ] +object Zone "icinga2-client2.localdomain" { + endpoints = [ "icinga2-client2.localdomain" ] - parent = "master" - } + parent = "master" +} - /* sync global commands */ - object Zone "global-templates" { - global = true - } +/* sync global commands */ +object Zone "global-templates" { + global = true +} +``` Now it is time to define the two client hosts and apply service checks using the command endpoint execution method on them. Note: You can also use the @@ -1332,48 +1382,56 @@ config sync mode here. Create a new configuration directory on the master node: - [root@icinga2-master1.localdomain /]# mkdir -p /etc/icinga2/zones.d/master +``` +[root@icinga2-master1.localdomain /]# mkdir -p /etc/icinga2/zones.d/master +``` Add the two client nodes as host objects: - [root@icinga2-master1.localdomain /]# cd /etc/icinga2/zones.d/master - [root@icinga2-master1.localdomain /etc/icinga2/zones.d/master]# vim hosts.conf +``` +[root@icinga2-master1.localdomain /]# cd /etc/icinga2/zones.d/master +[root@icinga2-master1.localdomain /etc/icinga2/zones.d/master]# vim hosts.conf - object Host "icinga2-client1.localdomain" { - check_command = "hostalive" - address = "192.168.56.111" - vars.client_endpoint = name //follows the convention that host name == endpoint name - } +object Host "icinga2-client1.localdomain" { + check_command = "hostalive" + address = "192.168.56.111" + vars.client_endpoint = name //follows the convention that host name == endpoint name +} - object Host "icinga2-client2.localdomain" { - check_command = "hostalive" - address = "192.168.56.112" - vars.client_endpoint = name //follows the convention that host name == endpoint name - } +object Host "icinga2-client2.localdomain" { + check_command = "hostalive" + address = "192.168.56.112" + vars.client_endpoint = name //follows the convention that host name == endpoint name +} +``` Add services using command endpoint checks: - [root@icinga2-master1.localdomain /etc/icinga2/zones.d/master]# vim services.conf +``` +[root@icinga2-master1.localdomain /etc/icinga2/zones.d/master]# vim services.conf - apply Service "ping4" { - check_command = "ping4" - //check is executed on the master node - assign where host.address - } +apply Service "ping4" { + check_command = "ping4" + //check is executed on the master node + assign where host.address +} - apply Service "disk" { - check_command = "disk" +apply Service "disk" { + check_command = "disk" - //specify where the check is executed - command_endpoint = host.vars.client_endpoint + //specify where the check is executed + command_endpoint = host.vars.client_endpoint - assign where host.vars.client_endpoint - } + assign where host.vars.client_endpoint +} +``` Validate the configuration and restart Icinga 2 on the master node `icinga2-master1.localdomain`. - [root@icinga2-master1.localdomain /]# icinga2 daemon -C - [root@icinga2-master1.localdomain /]# systemctl restart icinga2 +``` +[root@icinga2-master1.localdomain /]# icinga2 daemon -C +[root@icinga2-master1.localdomain /]# systemctl restart icinga2 +``` Open Icinga Web 2 and check the two newly created client hosts with two new services -- one executed locally (`ping4`) and one using command endpoint (`disk`). @@ -1421,44 +1479,46 @@ backend, IDO database, used transports, etc.). The zone hierarchy could look like this. It involves putting the two master nodes `icinga2-master1.localdomain` and `icinga2-master2.localdomain` into the `master` zone. - [root@icinga2-master1.localdomain /]# vim /etc/icinga2/zones.conf +``` +[root@icinga2-master1.localdomain /]# vim /etc/icinga2/zones.conf - object Endpoint "icinga2-master1.localdomain" { - host = "192.168.56.101" - } +object Endpoint "icinga2-master1.localdomain" { + host = "192.168.56.101" +} - object Endpoint "icinga2-master2.localdomain" { - host = "192.168.56.102" - } +object Endpoint "icinga2-master2.localdomain" { + host = "192.168.56.102" +} - object Endpoint "icinga2-client1.localdomain" { - host = "192.168.56.111" //the master actively tries to connect to the client - } +object Endpoint "icinga2-client1.localdomain" { + host = "192.168.56.111" //the master actively tries to connect to the client +} - object Endpoint "icinga2-client2.localdomain" { - host = "192.168.56.112" //the master actively tries to connect to the client - } +object Endpoint "icinga2-client2.localdomain" { + host = "192.168.56.112" //the master actively tries to connect to the client +} - object Zone "master" { - endpoints = [ "icinga2-master1.localdomain", "icinga2-master2.localdomain" ] - } +object Zone "master" { + endpoints = [ "icinga2-master1.localdomain", "icinga2-master2.localdomain" ] +} - object Zone "icinga2-client1.localdomain" { - endpoints = [ "icinga2-client1.localdomain" ] +object Zone "icinga2-client1.localdomain" { + endpoints = [ "icinga2-client1.localdomain" ] - parent = "master" - } + parent = "master" +} - object Zone "icinga2-client2.localdomain" { - endpoints = [ "icinga2-client2.localdomain" ] +object Zone "icinga2-client2.localdomain" { + endpoints = [ "icinga2-client2.localdomain" ] - parent = "master" - } + parent = "master" +} - /* sync global commands */ - object Zone "global-templates" { - global = true - } +/* sync global commands */ +object Zone "global-templates" { + global = true +} +``` The two client nodes do not necessarily need to know about each other. The only important thing is that they know about the parent zone and their endpoint members (and optionally about the global zone). @@ -1468,61 +1528,63 @@ endpoint objects, the client will actively try to connect to the master node. Si endpoint's attribute on the master node already, we don't want the clients to connect to the master nodes. **Choose one [connection direction](06-distributed-monitoring.md#distributed-monitoring-advanced-hints-connection-direction).** - [root@icinga2-client1.localdomain /]# vim /etc/icinga2/zones.conf +``` +[root@icinga2-client1.localdomain /]# vim /etc/icinga2/zones.conf - object Endpoint "icinga2-master1.localdomain" { - //do not actively connect to the master by leaving out the 'host' attribute - } +object Endpoint "icinga2-master1.localdomain" { + //do not actively connect to the master by leaving out the 'host' attribute +} - object Endpoint "icinga2-master2.localdomain" { - //do not actively connect to the master by leaving out the 'host' attribute - } +object Endpoint "icinga2-master2.localdomain" { + //do not actively connect to the master by leaving out the 'host' attribute +} - object Endpoint "icinga2-client1.localdomain" { - } +object Endpoint "icinga2-client1.localdomain" { +} - object Zone "master" { - endpoints = [ "icinga2-master1.localdomain", "icinga2-master2.localdomain" ] - } +object Zone "master" { + endpoints = [ "icinga2-master1.localdomain", "icinga2-master2.localdomain" ] +} - object Zone "icinga2-client1.localdomain" { - endpoints = [ "icinga2-client1.localdomain" ] +object Zone "icinga2-client1.localdomain" { + endpoints = [ "icinga2-client1.localdomain" ] - parent = "master" - } + parent = "master" +} - /* sync global commands */ - object Zone "global-templates" { - global = true - } +/* sync global commands */ +object Zone "global-templates" { + global = true +} - [root@icinga2-client2.localdomain /]# vim /etc/icinga2/zones.conf +[root@icinga2-client2.localdomain /]# vim /etc/icinga2/zones.conf - object Endpoint "icinga2-master1.localdomain" { - //do not actively connect to the master by leaving out the 'host' attribute - } +object Endpoint "icinga2-master1.localdomain" { + //do not actively connect to the master by leaving out the 'host' attribute +} - object Endpoint "icinga2-master2.localdomain" { - //do not actively connect to the master by leaving out the 'host' attribute - } +object Endpoint "icinga2-master2.localdomain" { + //do not actively connect to the master by leaving out the 'host' attribute +} - object Endpoint "icinga2-client2.localdomain" { - } +object Endpoint "icinga2-client2.localdomain" { +} - object Zone "master" { - endpoints = [ "icinga2-master1.localdomain", "icinga2-master2.localdomain" ] - } +object Zone "master" { + endpoints = [ "icinga2-master1.localdomain", "icinga2-master2.localdomain" ] +} - object Zone "icinga2-client2.localdomain" { - endpoints = [ "icinga2-client2.localdomain" ] +object Zone "icinga2-client2.localdomain" { + endpoints = [ "icinga2-client2.localdomain" ] - parent = "master" - } + parent = "master" +} - /* sync global commands */ - object Zone "global-templates" { - global = true - } +/* sync global commands */ +object Zone "global-templates" { + global = true +} +``` Now it is time to define the two client hosts and apply service checks using the command endpoint execution method. Note: You can also use the @@ -1532,48 +1594,56 @@ Create a new configuration directory on the master node `icinga2-master1.localdo **Note**: The secondary master node `icinga2-master2.localdomain` receives the configuration using the [config sync mode](06-distributed-monitoring.md#distributed-monitoring-top-down-config-sync). - [root@icinga2-master1.localdomain /]# mkdir -p /etc/icinga2/zones.d/master +``` +[root@icinga2-master1.localdomain /]# mkdir -p /etc/icinga2/zones.d/master +``` Add the two client nodes as host objects: - [root@icinga2-master1.localdomain /]# cd /etc/icinga2/zones.d/master - [root@icinga2-master1.localdomain /etc/icinga2/zones.d/master]# vim hosts.conf +``` +[root@icinga2-master1.localdomain /]# cd /etc/icinga2/zones.d/master +[root@icinga2-master1.localdomain /etc/icinga2/zones.d/master]# vim hosts.conf - object Host "icinga2-client1.localdomain" { - check_command = "hostalive" - address = "192.168.56.111" - vars.client_endpoint = name //follows the convention that host name == endpoint name - } +object Host "icinga2-client1.localdomain" { + check_command = "hostalive" + address = "192.168.56.111" + vars.client_endpoint = name //follows the convention that host name == endpoint name +} - object Host "icinga2-client2.localdomain" { - check_command = "hostalive" - address = "192.168.56.112" - vars.client_endpoint = name //follows the convention that host name == endpoint name - } +object Host "icinga2-client2.localdomain" { + check_command = "hostalive" + address = "192.168.56.112" + vars.client_endpoint = name //follows the convention that host name == endpoint name +} +``` Add services using command endpoint checks: - [root@icinga2-master1.localdomain /etc/icinga2/zones.d/master]# vim services.conf +``` +[root@icinga2-master1.localdomain /etc/icinga2/zones.d/master]# vim services.conf - apply Service "ping4" { - check_command = "ping4" - //check is executed on the master node - assign where host.address - } +apply Service "ping4" { + check_command = "ping4" + //check is executed on the master node + assign where host.address +} - apply Service "disk" { - check_command = "disk" +apply Service "disk" { + check_command = "disk" - //specify where the check is executed - command_endpoint = host.vars.client_endpoint + //specify where the check is executed + command_endpoint = host.vars.client_endpoint - assign where host.vars.client_endpoint - } + assign where host.vars.client_endpoint +} +``` Validate the configuration and restart Icinga 2 on the master node `icinga2-master1.localdomain`. - [root@icinga2-master1.localdomain /]# icinga2 daemon -C - [root@icinga2-master1.localdomain /]# systemctl restart icinga2 +``` +[root@icinga2-master1.localdomain /]# icinga2 daemon -C +[root@icinga2-master1.localdomain /]# systemctl restart icinga2 +``` Open Icinga Web 2 and check the two newly created client hosts with two new services -- one executed locally (`ping4`) and one using command endpoint (`disk`). @@ -1814,32 +1884,34 @@ we must configure the client endpoint and zone objects. In order to minimize the effort, we'll sync the client zone and endpoint configuration to the satellites where the connection information is needed as well. - [root@icinga2-master1.localdomain /]# mkdir -p /etc/icinga2/zones.d/{master,satellite,global-templates} - [root@icinga2-master1.localdomain /]# cd /etc/icinga2/zones.d/satellite +``` +[root@icinga2-master1.localdomain /]# mkdir -p /etc/icinga2/zones.d/{master,satellite,global-templates} +[root@icinga2-master1.localdomain /]# cd /etc/icinga2/zones.d/satellite - [root@icinga2-master1.localdomain /etc/icinga2/zones.d/satellite]# vim icinga2-client1.localdomain.conf +[root@icinga2-master1.localdomain /etc/icinga2/zones.d/satellite]# vim icinga2-client1.localdomain.conf - object Endpoint "icinga2-client1.localdomain" { - host = "192.168.56.111" //the satellite actively tries to connect to the client - } +object Endpoint "icinga2-client1.localdomain" { + host = "192.168.56.111" //the satellite actively tries to connect to the client +} - object Zone "icinga2-client1.localdomain" { - endpoints = [ "icinga2-client1.localdomain" ] +object Zone "icinga2-client1.localdomain" { + endpoints = [ "icinga2-client1.localdomain" ] - parent = "satellite" - } + parent = "satellite" +} - [root@icinga2-master1.localdomain /etc/icinga2/zones.d/satellite]# vim icinga2-client2.localdomain.conf +[root@icinga2-master1.localdomain /etc/icinga2/zones.d/satellite]# vim icinga2-client2.localdomain.conf - object Endpoint "icinga2-client2.localdomain" { - host = "192.168.56.112" //the satellite actively tries to connect to the client - } +object Endpoint "icinga2-client2.localdomain" { + host = "192.168.56.112" //the satellite actively tries to connect to the client +} - object Zone "icinga2-client2.localdomain" { - endpoints = [ "icinga2-client2.localdomain" ] +object Zone "icinga2-client2.localdomain" { + endpoints = [ "icinga2-client2.localdomain" ] - parent = "satellite" - } + parent = "satellite" +} +``` The two client nodes do not necessarily need to know about each other, either. The only important thing is that they know about the parent zone (the satellite) and their endpoint members (and optionally the global zone). @@ -1851,73 +1923,77 @@ satellite nodes. **Choose one [connection direction](06-distributed-monitoring.m Example for `icinga2-client1.localdomain`: - [root@icinga2-client1.localdomain /]# vim /etc/icinga2/zones.conf +``` +[root@icinga2-client1.localdomain /]# vim /etc/icinga2/zones.conf - object Endpoint "icinga2-satellite1.localdomain" { - //do not actively connect to the satellite by leaving out the 'host' attribute - } +object Endpoint "icinga2-satellite1.localdomain" { + //do not actively connect to the satellite by leaving out the 'host' attribute +} - object Endpoint "icinga2-satellite2.localdomain" { - //do not actively connect to the satellite by leaving out the 'host' attribute - } +object Endpoint "icinga2-satellite2.localdomain" { + //do not actively connect to the satellite by leaving out the 'host' attribute +} - object Endpoint "icinga2-client1.localdomain" { - //that's us - } +object Endpoint "icinga2-client1.localdomain" { + //that's us +} - object Zone "satellite" { - endpoints = [ "icinga2-satellite1.localdomain", "icinga2-satellite2.localdomain" ] - } +object Zone "satellite" { + endpoints = [ "icinga2-satellite1.localdomain", "icinga2-satellite2.localdomain" ] +} - object Zone "icinga2-client1.localdomain" { - endpoints = [ "icinga2-client1.localdomain" ] +object Zone "icinga2-client1.localdomain" { + endpoints = [ "icinga2-client1.localdomain" ] - parent = "satellite" - } + parent = "satellite" +} - /* sync global commands */ - object Zone "global-templates" { - global = true - } +/* sync global commands */ +object Zone "global-templates" { + global = true +} - object Zone "director-global" { - global = true - } +object Zone "director-global" { + global = true +} +``` Example for `icinga2-client2.localdomain`: - [root@icinga2-client2.localdomain /]# vim /etc/icinga2/zones.conf +``` +[root@icinga2-client2.localdomain /]# vim /etc/icinga2/zones.conf - object Endpoint "icinga2-satellite1.localdomain" { - //do not actively connect to the satellite by leaving out the 'host' attribute - } +object Endpoint "icinga2-satellite1.localdomain" { + //do not actively connect to the satellite by leaving out the 'host' attribute +} - object Endpoint "icinga2-satellite2.localdomain" { - //do not actively connect to the satellite by leaving out the 'host' attribute - } +object Endpoint "icinga2-satellite2.localdomain" { + //do not actively connect to the satellite by leaving out the 'host' attribute +} - object Endpoint "icinga2-client2.localdomain" { - //that's us - } +object Endpoint "icinga2-client2.localdomain" { + //that's us +} - object Zone "satellite" { - endpoints = [ "icinga2-satellite1.localdomain", "icinga2-satellite2.localdomain" ] - } +object Zone "satellite" { + endpoints = [ "icinga2-satellite1.localdomain", "icinga2-satellite2.localdomain" ] +} - object Zone "icinga2-client2.localdomain" { - endpoints = [ "icinga2-client2.localdomain" ] +object Zone "icinga2-client2.localdomain" { + endpoints = [ "icinga2-client2.localdomain" ] - parent = "satellite" - } + parent = "satellite" +} - /* sync global commands */ - object Zone "global-templates" { - global = true - } +/* sync global commands */ +object Zone "global-templates" { + global = true +} - object Zone "director-global" { - global = true - } +object Zone "director-global" { + global = true +} +``` Now it is time to define the two client hosts on the master, sync them to the satellites and apply service checks using the command endpoint execution method to them. @@ -1926,57 +2002,69 @@ Add the two client nodes as host objects to the `satellite` zone. We've already created the directories in `/etc/icinga2/zones.d` including the files for the zone and endpoint configuration for the clients. - [root@icinga2-master1.localdomain /]# cd /etc/icinga2/zones.d/satellite +``` +[root@icinga2-master1.localdomain /]# cd /etc/icinga2/zones.d/satellite +``` Add the host object configuration for the `icinga2-client1.localdomain` client. You should have created the configuration file in the previous steps and it should contain the endpoint and zone object configuration already. - [root@icinga2-master1.localdomain /etc/icinga2/zones.d/satellite]# vim icinga2-client1.localdomain.conf +``` +[root@icinga2-master1.localdomain /etc/icinga2/zones.d/satellite]# vim icinga2-client1.localdomain.conf - object Host "icinga2-client1.localdomain" { - check_command = "hostalive" - address = "192.168.56.111" - vars.client_endpoint = name //follows the convention that host name == endpoint name - } +object Host "icinga2-client1.localdomain" { + check_command = "hostalive" + address = "192.168.56.111" + vars.client_endpoint = name //follows the convention that host name == endpoint name +} +``` Add the host object configuration for the `icinga2-client2.localdomain` client configuration file: - [root@icinga2-master1.localdomain /etc/icinga2/zones.d/satellite]# vim icinga2-client2.localdomain.conf +``` +[root@icinga2-master1.localdomain /etc/icinga2/zones.d/satellite]# vim icinga2-client2.localdomain.conf - object Host "icinga2-client2.localdomain" { - check_command = "hostalive" - address = "192.168.56.112" - vars.client_endpoint = name //follows the convention that host name == endpoint name - } +object Host "icinga2-client2.localdomain" { + check_command = "hostalive" + address = "192.168.56.112" + vars.client_endpoint = name //follows the convention that host name == endpoint name +} +``` Add a service object which is executed on the satellite nodes (e.g. `ping4`). Pin the apply rule to the `satellite` zone only. - [root@icinga2-master1.localdomain /etc/icinga2/zones.d/satellite]# vim services.conf +``` +[root@icinga2-master1.localdomain /etc/icinga2/zones.d/satellite]# vim services.conf - apply Service "ping4" { - check_command = "ping4" - //check is executed on the satellite node - assign where host.zone == "satellite" && host.address - } +apply Service "ping4" { + check_command = "ping4" + //check is executed on the satellite node + assign where host.zone == "satellite" && host.address +} +``` Add services using command endpoint checks. Pin the apply rules to the `satellite` zone only. - [root@icinga2-master1.localdomain /etc/icinga2/zones.d/satellite]# vim services.conf +``` +[root@icinga2-master1.localdomain /etc/icinga2/zones.d/satellite]# vim services.conf - apply Service "disk" { - check_command = "disk" +apply Service "disk" { + check_command = "disk" - //specify where the check is executed - command_endpoint = host.vars.client_endpoint + //specify where the check is executed + command_endpoint = host.vars.client_endpoint - assign where host.zone == "satellite" && host.vars.client_endpoint - } + assign where host.zone == "satellite" && host.vars.client_endpoint +} +``` Validate the configuration and restart Icinga 2 on the master node `icinga2-master1.localdomain`. - [root@icinga2-master1.localdomain /]# icinga2 daemon -C - [root@icinga2-master1.localdomain /]# systemctl restart icinga2 +``` +[root@icinga2-master1.localdomain /]# icinga2 daemon -C +[root@icinga2-master1.localdomain /]# systemctl restart icinga2 +``` Open Icinga Web 2 and check the two newly created client hosts with two new services -- one executed locally (`ping4`) and one using command endpoint (`disk`). @@ -2014,26 +2102,32 @@ zone. The configuration validation will terminate with an error. The zone object configuration must be deployed on all nodes which should receive the global configuration files: - [root@icinga2-master1.localdomain /]# vim /etc/icinga2/zones.conf +``` +[root@icinga2-master1.localdomain /]# vim /etc/icinga2/zones.conf - object Zone "global-commands" { - global = true - } +object Zone "global-commands" { + global = true +} +``` The default global zones generated by the setup wizards are called `global-templates` and `director-global`. Similar to the zone configuration sync you'll need to create a new directory in `/etc/icinga2/zones.d`: - [root@icinga2-master1.localdomain /]# mkdir -p /etc/icinga2/zones.d/global-commands +``` +[root@icinga2-master1.localdomain /]# mkdir -p /etc/icinga2/zones.d/global-commands +``` Next, add a new check command, for example: - [root@icinga2-master1.localdomain /]# vim /etc/icinga2/zones.d/global-commands/web.conf +``` +[root@icinga2-master1.localdomain /]# vim /etc/icinga2/zones.d/global-commands/web.conf - object CheckCommand "webinject" { - //... - } +object CheckCommand "webinject" { + //... +} +``` Restart the client(s) which should receive the global zone before before restarting the parent master/satellite nodes. @@ -2045,8 +2139,10 @@ into the default global zone `global-templates`. Example: - [root@icinga2-master1.localdomain /]# cd /etc/icinga2/conf.d - [root@icinga2-master1.localdomain /etc/icinga2/conf.d]# cp {commands,groups,notifications,services,templates,timeperiods,users}.conf /etc/icinga2/zones.d/global-templates +``` +[root@icinga2-master1.localdomain /]# cd /etc/icinga2/conf.d +[root@icinga2-master1.localdomain /etc/icinga2/conf.d]# cp {commands,groups,notifications,services,templates,timeperiods,users}.conf /etc/icinga2/zones.d/global-templates +``` ### Health Checks @@ -2060,69 +2156,76 @@ additional health checks. The `cluster` check, for example, will check if all endpoints in the current zone and the directly connected zones are working properly: - [root@icinga2-master1.localdomain /]# mkdir -p /etc/icinga2/zones.d/master - [root@icinga2-master1.localdomain /]# vim /etc/icinga2/zones.d/master/icinga2-master1.localdomain.conf +``` +[root@icinga2-master1.localdomain /]# mkdir -p /etc/icinga2/zones.d/master +[root@icinga2-master1.localdomain /]# vim /etc/icinga2/zones.d/master/icinga2-master1.localdomain.conf - object Host "icinga2-master1.localdomain" { - check_command = "hostalive" - address = "192.168.56.101" - } +object Host "icinga2-master1.localdomain" { + check_command = "hostalive" + address = "192.168.56.101" +} - [root@icinga2-master1.localdomain /]# vim /etc/icinga2/zones.d/master/cluster.conf +[root@icinga2-master1.localdomain /]# vim /etc/icinga2/zones.d/master/cluster.conf - object Service "cluster" { - check_command = "cluster" - check_interval = 5s - retry_interval = 1s +object Service "cluster" { + check_command = "cluster" + check_interval = 5s + retry_interval = 1s - host_name = "icinga2-master1.localdomain" - } + host_name = "icinga2-master1.localdomain" +} +``` The `cluster-zone` check will test whether the configured target zone is currently connected or not. This example adds a health check for the [ha master with clients scenario](06-distributed-monitoring.md#distributed-monitoring-scenarios-ha-master-clients). - [root@icinga2-master1.localdomain /]# vim /etc/icinga2/zones.d/master/services.conf +``` +[root@icinga2-master1.localdomain /]# vim /etc/icinga2/zones.d/master/services.conf - apply Service "cluster-health" { - check_command = "cluster-zone" +apply Service "cluster-health" { + check_command = "cluster-zone" - display_name = "cluster-health-" + host.name + display_name = "cluster-health-" + host.name - /* This follows the convention that the client zone name is the FQDN which is the same as the host object name. */ - vars.cluster_zone = host.name + /* This follows the convention that the client zone name is the FQDN which is the same as the host object name. */ + vars.cluster_zone = host.name - assign where host.vars.client_endpoint - } + assign where host.vars.client_endpoint +} +``` In case you cannot assign the `cluster_zone` attribute, add specific checks to your cluster: - [root@icinga2-master1.localdomain /]# vim /etc/icinga2/zones.d/master/cluster.conf - - object Service "cluster-zone-satellite" { - check_command = "cluster-zone" - check_interval = 5s - retry_interval = 1s - vars.cluster_zone = "satellite" +``` +[root@icinga2-master1.localdomain /]# vim /etc/icinga2/zones.d/master/cluster.conf - host_name = "icinga2-master1.localdomain" - } +object Service "cluster-zone-satellite" { + check_command = "cluster-zone" + check_interval = 5s + retry_interval = 1s + vars.cluster_zone = "satellite" + host_name = "icinga2-master1.localdomain" +} +``` If you are using top down checks with command endpoint configuration, you can add a dependency which prevents notifications for all other failing services: - [root@icinga2-master1.localdomain /]# vim /etc/icinga2/zones.d/master/dependencies.conf +``` +[root@icinga2-master1.localdomain /]# vim /etc/icinga2/zones.d/master/dependencies.conf - apply Dependency "health-check" to Service { - parent_service_name = "child-health" +apply Dependency "health-check" to Service { + parent_service_name = "child-health" - states = [ OK ] - disable_notifications = true + states = [ OK ] + disable_notifications = true - assign where host.vars.client_endpoint - ignore where service.name == "child-health" - } + assign where host.vars.client_endpoint + ignore where service.name == "child-health" +} +``` ### Pin Checks in a Zone @@ -2130,23 +2233,25 @@ In case you want to pin specific checks to their endpoints in a given zone you'l the `command_endpoint` attribute. This is reasonable if you want to execute a local disk check in the `master` Zone on a specific endpoint then. - [root@icinga2-master1.localdomain /]# mkdir -p /etc/icinga2/zones.d/master - [root@icinga2-master1.localdomain /]# vim /etc/icinga2/zones.d/master/icinga2-master1.localdomain.conf +``` +[root@icinga2-master1.localdomain /]# mkdir -p /etc/icinga2/zones.d/master +[root@icinga2-master1.localdomain /]# vim /etc/icinga2/zones.d/master/icinga2-master1.localdomain.conf - object Host "icinga2-master1.localdomain" { - check_command = "hostalive" - address = "192.168.56.101" - } +object Host "icinga2-master1.localdomain" { + check_command = "hostalive" + address = "192.168.56.101" +} - [root@icinga2-master1.localdomain /]# vim /etc/icinga2/zones.d/master/services.conf +[root@icinga2-master1.localdomain /]# vim /etc/icinga2/zones.d/master/services.conf - apply Service "disk" { - check_command = "disk" +apply Service "disk" { + check_command = "disk" - command_endpoint = host.name //requires a host object matching the endpoint object name e.g. icinga2-master1.localdomain + command_endpoint = host.name //requires a host object matching the endpoint object name e.g. icinga2-master1.localdomain - assign where host.zone == "master" && match("icinga2-master*", host.name) - } + assign where host.zone == "master" && match("icinga2-master*", host.name) +} +``` The `host.zone` attribute check inside the expression ensures that the service object is only created for host objects inside the `master` @@ -2160,21 +2265,27 @@ function ensures to only create services for the master nodes. By default ICMP requests are disabled in the Windows firewall. You can change that by [adding a new rule](https://support.microsoft.com/en-us/kb/947709). - C:\WINDOWS\system32>netsh advfirewall firewall add rule name="ICMP Allow incoming V4 echo request" protocol=icmpv4:8,any dir=in action=allow +``` +C:\WINDOWS\system32>netsh advfirewall firewall add rule name="ICMP Allow incoming V4 echo request" protocol=icmpv4:8,any dir=in action=allow +``` #### Icinga 2 If your master/satellite nodes should actively connect to the Windows client you'll also need to ensure that port `5665` is enabled. - C:\WINDOWS\system32>netsh advfirewall firewall add rule name="Open port 5665 (Icinga 2)" dir=in action=allow protocol=TCP localport=5665 +``` +C:\WINDOWS\system32>netsh advfirewall firewall add rule name="Open port 5665 (Icinga 2)" dir=in action=allow protocol=TCP localport=5665 +``` #### NSClient++ API If the [check_nscp_api](06-distributed-monitoring.md#distributed-monitoring-windows-nscp-check-api) plugin is used to query NSClient++, you need to ensure that its port is enabled. - C:\WINDOWS\system32>netsh advfirewall firewall add rule name="Open port 8443 (NSClient++ API)" dir=in action=allow protocol=TCP localport=8443 +``` +C:\WINDOWS\system32>netsh advfirewall firewall add rule name="Open port 8443 (NSClient++ API)" dir=in action=allow protocol=TCP localport=8443 +``` For security reasons, it is advised to enable the NSClient++ HTTP API for local connection from the Icinga 2 client only. Remote connections to the HTTP API @@ -2187,45 +2298,53 @@ Detailed [documentation](10-icinga-template-library.md#windows-plugins) is avail Add the following `include` statement on all your nodes (master, satellite, client): - vim /etc/icinga2/icinga2.conf +``` +vim /etc/icinga2/icinga2.conf - include +include +``` Based on the [master with clients](06-distributed-monitoring.md#distributed-monitoring-master-clients) scenario we'll now add a local disk check. First, add the client node as host object: - [root@icinga2-master1.localdomain /]# cd /etc/icinga2/zones.d/master - [root@icinga2-master1.localdomain /etc/icinga2/zones.d/master]# vim hosts.conf +``` +[root@icinga2-master1.localdomain /]# cd /etc/icinga2/zones.d/master +[root@icinga2-master1.localdomain /etc/icinga2/zones.d/master]# vim hosts.conf - object Host "icinga2-client2.localdomain" { - check_command = "hostalive" - address = "192.168.56.112" - vars.client_endpoint = name //follows the convention that host name == endpoint name - vars.os_type = "windows" - } +object Host "icinga2-client2.localdomain" { + check_command = "hostalive" + address = "192.168.56.112" + vars.client_endpoint = name //follows the convention that host name == endpoint name + vars.os_type = "windows" +} +``` Next, add the disk check using command endpoint checks (details in the [disk-windows](10-icinga-template-library.md#windows-plugins-disk-windows) documentation): - [root@icinga2-master1.localdomain /etc/icinga2/zones.d/master]# vim services.conf +``` +[root@icinga2-master1.localdomain /etc/icinga2/zones.d/master]# vim services.conf - apply Service "disk C:" { - check_command = "disk-windows" +apply Service "disk C:" { + check_command = "disk-windows" - vars.disk_win_path = "C:" + vars.disk_win_path = "C:" - //specify where the check is executed - command_endpoint = host.vars.client_endpoint + //specify where the check is executed + command_endpoint = host.vars.client_endpoint - assign where host.vars.os_type == "windows" && host.vars.client_endpoint - } + assign where host.vars.os_type == "windows" && host.vars.client_endpoint +} +``` Validate the configuration and restart Icinga 2. - [root@icinga2-master1.localdomain /]# icinga2 daemon -C - [root@icinga2-master1.localdomain /]# systemctl restart icinga2 +``` +[root@icinga2-master1.localdomain /]# icinga2 daemon -C +[root@icinga2-master1.localdomain /]# systemctl restart icinga2 +``` Open Icinga Web 2 and check your newly added Windows disk check :) @@ -2260,43 +2379,49 @@ scenario we'll now add a local nscp check which queries the NSClient++ API to ch Define a host object called `icinga2-client2.localdomain` on the master. Add the `nscp_api_password` custom attribute and specify the drives to check. - [root@icinga2-master1.localdomain /]# cd /etc/icinga2/zones.d/master - [root@icinga2-master1.localdomain /etc/icinga2/zones.d/master]# vim hosts.conf +``` +[root@icinga2-master1.localdomain /]# cd /etc/icinga2/zones.d/master +[root@icinga2-master1.localdomain /etc/icinga2/zones.d/master]# vim hosts.conf - object Host "icinga2-client1.localdomain" { - check_command = "hostalive" - address = "192.168.56.111" - vars.client_endpoint = name //follows the convention that host name == endpoint name - vars.os_type = "Windows" - vars.nscp_api_password = "icinga" - vars.drives = [ "C:", "D:" ] - } +object Host "icinga2-client1.localdomain" { +check_command = "hostalive" +address = "192.168.56.111" +vars.client_endpoint = name //follows the convention that host name == endpoint name +vars.os_type = "Windows" +vars.nscp_api_password = "icinga" +vars.drives = [ "C:", "D:" ] +} +``` The service checks are generated using an [apply for](03-monitoring-basics.md#using-apply-for) rule based on `host.vars.drives`: - [root@icinga2-master1.localdomain /etc/icinga2/zones.d/master]# vim services.conf +``` +[root@icinga2-master1.localdomain /etc/icinga2/zones.d/master]# vim services.conf - apply Service "nscp-api-" for (drive in host.vars.drives) { - import "generic-service" +apply Service "nscp-api-" for (drive in host.vars.drives) { + import "generic-service" - check_command = "nscp_api" - command_endpoint = host.vars.client_endpoint + check_command = "nscp_api" + command_endpoint = host.vars.client_endpoint - //display_name = "nscp-drive-" + drive + //display_name = "nscp-drive-" + drive - vars.nscp_api_host = "localhost" - vars.nscp_api_query = "check_drivesize" - vars.nscp_api_password = host.vars.nscp_api_password - vars.nscp_api_arguments = [ "drive=" + drive ] + vars.nscp_api_host = "localhost" + vars.nscp_api_query = "check_drivesize" + vars.nscp_api_password = host.vars.nscp_api_password + vars.nscp_api_arguments = [ "drive=" + drive ] - ignore where host.vars.os_type != "Windows" - } + ignore where host.vars.os_type != "Windows" +} +``` Validate the configuration and restart Icinga 2. - [root@icinga2-master1.localdomain /]# icinga2 daemon -C - [root@icinga2-master1.localdomain /]# systemctl restart icinga2 +``` +[root@icinga2-master1.localdomain /]# icinga2 daemon -C +[root@icinga2-master1.localdomain /]# systemctl restart icinga2 +``` Two new services ("nscp-drive-D:" and "nscp-drive-C:") will be visible in Icinga Web 2. @@ -2306,44 +2431,48 @@ Note: You can also omit the `command_endpoint` configuration to execute the command on the master. This also requires a different value for `nscp_api_host` which defaults to `host.address`. - //command_endpoint = host.vars.client_endpoint +``` + //command_endpoint = host.vars.client_endpoint - //vars.nscp_api_host = "localhost" + //vars.nscp_api_host = "localhost" +``` You can verify the check execution by looking at the `Check Source` attribute in Icinga Web 2 or the REST API. If you want to monitor specific Windows services, you could use the following example: - [root@icinga2-master1.localdomain /]# cd /etc/icinga2/zones.d/master - [root@icinga2-master1.localdomain /etc/icinga2/zones.d/master]# vim hosts.conf +``` +[root@icinga2-master1.localdomain /]# cd /etc/icinga2/zones.d/master +[root@icinga2-master1.localdomain /etc/icinga2/zones.d/master]# vim hosts.conf - object Host "icinga2-client1.localdomain" { - check_command = "hostalive" - address = "192.168.56.111" - vars.client_endpoint = name //follows the convention that host name == endpoint name - vars.os_type = "Windows" - vars.nscp_api_password = "icinga" - vars.services = [ "Windows Update", "wscsvc" ] - } +object Host "icinga2-client1.localdomain" { +check_command = "hostalive" +address = "192.168.56.111" +vars.client_endpoint = name //follows the convention that host name == endpoint name +vars.os_type = "Windows" +vars.nscp_api_password = "icinga" +vars.services = [ "Windows Update", "wscsvc" ] +} - [root@icinga2-master1.localdomain /etc/icinga2/zones.d/master]# vim services.conf +[root@icinga2-master1.localdomain /etc/icinga2/zones.d/master]# vim services.conf - apply Service "nscp-api-" for (svc in host.vars.services) { - import "generic-service" +apply Service "nscp-api-" for (svc in host.vars.services) { + import "generic-service" - check_command = "nscp_api" - command_endpoint = host.vars.client_endpoint + check_command = "nscp_api" + command_endpoint = host.vars.client_endpoint - //display_name = "nscp-service-" + svc + //display_name = "nscp-service-" + svc - vars.nscp_api_host = "localhost" - vars.nscp_api_query = "check_service" - vars.nscp_api_password = host.vars.nscp_api_password - vars.nscp_api_arguments = [ "service=" + svc ] + vars.nscp_api_host = "localhost" + vars.nscp_api_query = "check_service" + vars.nscp_api_password = host.vars.nscp_api_password + vars.nscp_api_arguments = [ "service=" + svc ] - ignore where host.vars.os_type != "Windows" - } + ignore where host.vars.os_type != "Windows" +} +``` #### NSCLient++ with nscp-local @@ -2356,9 +2485,11 @@ provided by the Icinga Template Library (ITL). Add the following `include` statement on all your nodes (master, satellite, client): - vim /etc/icinga2/icinga2.conf +``` +vim /etc/icinga2/icinga2.conf - include +include +``` The CheckCommand definitions will automatically determine the installed path to the `nscp.exe` binary. @@ -2368,39 +2499,45 @@ scenario we'll now add a local nscp check querying a given performance counter. First, add the client node as host object: - [root@icinga2-master1.localdomain /]# cd /etc/icinga2/zones.d/master - [root@icinga2-master1.localdomain /etc/icinga2/zones.d/master]# vim hosts.conf +``` +[root@icinga2-master1.localdomain /]# cd /etc/icinga2/zones.d/master +[root@icinga2-master1.localdomain /etc/icinga2/zones.d/master]# vim hosts.conf - object Host "icinga2-client1.localdomain" { - check_command = "hostalive" - address = "192.168.56.111" - vars.client_endpoint = name //follows the convention that host name == endpoint name - vars.os_type = "windows" - } +object Host "icinga2-client1.localdomain" { + check_command = "hostalive" + address = "192.168.56.111" + vars.client_endpoint = name //follows the convention that host name == endpoint name + vars.os_type = "windows" +} +``` Next, add a performance counter check using command endpoint checks (details in the [nscp-local-counter](10-icinga-template-library.md#nscp-check-local-counter) documentation): - [root@icinga2-master1.localdomain /etc/icinga2/zones.d/master]# vim services.conf +``` +[root@icinga2-master1.localdomain /etc/icinga2/zones.d/master]# vim services.conf - apply Service "nscp-local-counter-cpu" { - check_command = "nscp-local-counter" - command_endpoint = host.vars.client_endpoint +apply Service "nscp-local-counter-cpu" { + check_command = "nscp-local-counter" + command_endpoint = host.vars.client_endpoint - vars.nscp_counter_name = "\\Processor(_total)\\% Processor Time" - vars.nscp_counter_perfsyntax = "Total Processor Time" - vars.nscp_counter_warning = 1 - vars.nscp_counter_critical = 5 + vars.nscp_counter_name = "\\Processor(_total)\\% Processor Time" + vars.nscp_counter_perfsyntax = "Total Processor Time" + vars.nscp_counter_warning = 1 + vars.nscp_counter_critical = 5 - vars.nscp_counter_showall = true + vars.nscp_counter_showall = true - assign where host.vars.os_type == "windows" && host.vars.client_endpoint - } + assign where host.vars.os_type == "windows" && host.vars.client_endpoint +} +``` Validate the configuration and restart Icinga 2. - [root@icinga2-master1.localdomain /]# icinga2 daemon -C - [root@icinga2-master1.localdomain /]# systemctl restart icinga2 +``` +[root@icinga2-master1.localdomain /]# icinga2 daemon -C +[root@icinga2-master1.localdomain /]# systemctl restart icinga2 +``` Open Icinga Web 2 and check your newly added Windows NSClient++ check :) @@ -2442,7 +2579,9 @@ have the `checker` feature enabled. Example: - # icinga2 feature enable checker +``` +# icinga2 feature enable checker +``` All nodes in the same zone load-balance the check execution. If one instance shuts down, the other nodes will automatically take over the remaining checks. @@ -2454,7 +2593,9 @@ have the `notification` feature enabled. Example: - # icinga2 feature enable notification +``` +# icinga2 feature enable notification +``` Notifications are load-balanced amongst all nodes in a zone. By default this functionality is enabled. @@ -2469,7 +2610,9 @@ have the DB IDO feature enabled. Example DB IDO MySQL: - # icinga2 feature enable ido-mysql +``` +# icinga2 feature enable ido-mysql +``` By default the DB IDO feature only runs on one node. All other nodes in the same zone disable the active IDO database connection at runtime. The node with the active DB IDO connection is @@ -2490,11 +2633,13 @@ The DB IDO feature will try to determine which cluster endpoint is currently wri to the database and bail out if another endpoint is active. You can manually verify that by running the following query command: - icinga=> SELECT status_update_time, endpoint_name FROM icinga_programstatus; - status_update_time | endpoint_name - ------------------------+--------------- - 2016-08-15 15:52:26+02 | icinga2-master1.localdomain - (1 Zeile) +``` +icinga=> SELECT status_update_time, endpoint_name FROM icinga_programstatus; + status_update_time | endpoint_name +------------------------+--------------- + 2016-08-15 15:52:26+02 | icinga2-master1.localdomain +(1 Zeile) +``` This is useful when the cluster connection between endpoints breaks, and prevents data duplication in split-brain-scenarios. The failover timeout can be set for the @@ -2508,26 +2653,30 @@ configuration specifies a valid `host` attribute (FQDN or IP address). Example for the master node `icinga2-master1.localdomain` actively connecting to the client node `icinga2-client1.localdomain`: - [root@icinga2-master1.localdomain /]# vim /etc/icinga2/zones.conf +``` +[root@icinga2-master1.localdomain /]# vim /etc/icinga2/zones.conf - //... +//... - object Endpoint "icinga2-client1.localdomain" { - host = "192.168.56.111" //the master actively tries to connect to the client - log_duration = 0 - } +object Endpoint "icinga2-client1.localdomain" { + host = "192.168.56.111" //the master actively tries to connect to the client + log_duration = 0 +} +``` Example for the client node `icinga2-client1.localdomain` not actively connecting to the master node `icinga2-master1.localdomain`: - [root@icinga2-client1.localdomain /]# vim /etc/icinga2/zones.conf +``` +[root@icinga2-client1.localdomain /]# vim /etc/icinga2/zones.conf - //... +//... - object Endpoint "icinga2-master1.localdomain" { - //do not actively connect to the master by leaving out the 'host' attribute - log_duration = 0 - } +object Endpoint "icinga2-master1.localdomain" { + //do not actively connect to the master by leaving out the 'host' attribute + log_duration = 0 +} +``` It is not necessary that both the master and the client node establish two connections to each other. Icinga 2 will only use one connection @@ -2553,35 +2702,39 @@ client is not connected. Configuration on the master node `icinga2-master1.localdomain`: - [root@icinga2-master1.localdomain /]# vim /etc/icinga2/zones.conf +``` +[root@icinga2-master1.localdomain /]# vim /etc/icinga2/zones.conf - //... +//... - object Endpoint "icinga2-client1.localdomain" { - host = "192.168.56.111" //the master actively tries to connect to the client - log_duration = 0 - } +object Endpoint "icinga2-client1.localdomain" { + host = "192.168.56.111" //the master actively tries to connect to the client + log_duration = 0 +} - object Endpoint "icinga2-client2.localdomain" { - host = "192.168.56.112" //the master actively tries to connect to the client - log_duration = 0 - } +object Endpoint "icinga2-client2.localdomain" { + host = "192.168.56.112" //the master actively tries to connect to the client + log_duration = 0 +} +``` Configuration on the client `icinga2-client1.localdomain`: - [root@icinga2-client1.localdomain /]# vim /etc/icinga2/zones.conf +``` +[root@icinga2-client1.localdomain /]# vim /etc/icinga2/zones.conf - //... +//... - object Endpoint "icinga2-master1.localdomain" { - //do not actively connect to the master by leaving out the 'host' attribute - log_duration = 0 - } +object Endpoint "icinga2-master1.localdomain" { + //do not actively connect to the master by leaving out the 'host' attribute + log_duration = 0 +} - object Endpoint "icinga2-master2.localdomain" { - //do not actively connect to the master by leaving out the 'host' attribute - log_duration = 0 - } +object Endpoint "icinga2-master2.localdomain" { + //do not actively connect to the master by leaving out the 'host' attribute + log_duration = 0 +} +``` ### Manual Certificate Creation @@ -2592,7 +2745,9 @@ Choose the host which should store the certificate authority (one of the master The first step is the creation of the certificate authority (CA) by running the following command as root user: - [root@icinga2-master1.localdomain /root]# icinga2 pki new-ca +``` +[root@icinga2-master1.localdomain /root]# icinga2 pki new-ca +``` #### Create CSR and Certificate @@ -2674,7 +2829,9 @@ This will tremendously help when someone is trying to help in the [community cha If you want to install the client silently/unattended, use the `/qn` modifier. The installation should not trigger a restart, but if you want to be completely sure, you can use the `/norestart` modifier. - C:> msiexec /i C:\Icinga2-v2.5.0-x86.msi /qn /norestart +``` +C:> msiexec /i C:\Icinga2-v2.5.0-x86.msi /qn /norestart +``` Once the setup is completed you can use the `node setup` cli command too. @@ -2708,7 +2865,9 @@ Example: In case you want to bind the `ApiListener` object to a specific host/port you can specify it like this: - --listen 192.68.56.101,5665 +``` +--listen 192.68.56.101,5665 +``` In case you don't need anything in `conf.d`, use the following command line: @@ -2722,8 +2881,10 @@ In case you don't need anything in `conf.d`, use the following command line: Make sure that the `/var/lib/icinga2/certs` directory exists and is owned by the `icinga` user (or the user Icinga 2 is running as). - [root@icinga2-client1.localdomain /]# mkdir -p /var/lib/icinga2/certs - [root@icinga2-client1.localdomain /]# chown -R icinga:icinga /var/lib/icinga2/certs +``` +[root@icinga2-client1.localdomain /]# mkdir -p /var/lib/icinga2/certs +[root@icinga2-client1.localdomain /]# chown -R icinga:icinga /var/lib/icinga2/certs +``` First you'll need to generate a new local self-signed certificate. Pass the following details to the `pki new-cert` CLI command: @@ -2735,9 +2896,11 @@ Pass the following details to the `pki new-cert` CLI command: Example: - [root@icinga2-client1.localdomain /]# icinga2 pki new-cert --cn icinga2-client1.localdomain \ - --key /var/lib/icinga2/certs/icinga2-client1.localdomain.key \ - --cert /var/lib/icinga2/certs/icinga2-client1.localdomain.crt +``` +[root@icinga2-client1.localdomain /]# icinga2 pki new-cert --cn icinga2-client1.localdomain \ +--key /var/lib/icinga2/certs/icinga2-client1.localdomain.key \ +--cert /var/lib/icinga2/certs/icinga2-client1.localdomain.crt +``` Request the master certificate from the master host (`icinga2-master1.localdomain`) and store it as `trusted-master.crt`. Review it and continue. @@ -2752,10 +2915,12 @@ Pass the following details to the `pki save-cert` CLI command: Example: - [root@icinga2-client1.localdomain /]# icinga2 pki save-cert --key /var/lib/icinga2/certs/icinga2-client1.localdomain.key \ - --cert /var/lib/icinga2/certs/icinga2-client1.localdomain.crt \ - --trustedcert /var/lib/icinga2/certs/trusted-parent.crt \ - --host icinga2-master1.localdomain +``` +[root@icinga2-client1.localdomain /]# icinga2 pki save-cert --key /var/lib/icinga2/certs/icinga2-client1.localdomain.key \ +--cert /var/lib/icinga2/certs/icinga2-client1.localdomain.crt \ +--trustedcert /var/lib/icinga2/certs/trusted-parent.crt \ +--host icinga2-master1.localdomain +``` Continue with the additional node setup step. Specify a local endpoint and zone name (`icinga2-client1.localdomain`) and set the master host (`icinga2-master1.localdomain`) as parent zone configuration. Specify the path to @@ -2798,17 +2963,23 @@ Example for Icinga 2 v2.9: In case the client should connect to the master node, you'll need to modify the `--endpoint` parameter using the format `cn,host,port`: - --endpoint icinga2-master1.localdomain,192.168.56.101,5665 +``` +--endpoint icinga2-master1.localdomain,192.168.56.101,5665 +``` Specify the parent zone using the `--parent_zone` parameter. This is useful if the client connects to a satellite, not the master instance. - --parent_zone satellite +``` +--parent_zone satellite +``` In case the client should know the additional global zone `linux-templates`, you'll need to set the `--global-zones` parameter. - --global_zones linux-templates +``` +--global_zones linux-templates +``` The `--parent-host` parameter is optional since v2.9 and allows you to perform a connection-less setup. You cannot restart Icinga 2 yet, the CLI command asked to to manually copy the parent's public CA @@ -2825,46 +2996,58 @@ which holds the CA's key pair. If this client node is configured as [remote command endpoint execution](06-distributed-monitoring.md#distributed-monitoring-top-down-command-endpoint) you can safely disable the `checker` feature. The `node setup` CLI command already disabled the `notification` feature. - [root@icinga2-client1.localdomain /]# icinga2 feature disable checker +``` +[root@icinga2-client1.localdomain /]# icinga2 feature disable checker +``` Disable "conf.d" inclusion if this is a [top down](06-distributed-monitoring.md#distributed-monitoring-top-down) configured client. - [root@icinga2-client1.localdomain /]# sed -i 's/include_recursive "conf.d"/\/\/include_recursive "conf.d"/g' /etc/icinga2/icinga2.conf +``` +[root@icinga2-client1.localdomain /]# sed -i 's/include_recursive "conf.d"/\/\/include_recursive "conf.d"/g' /etc/icinga2/icinga2.conf +``` **Note**: This is the default since v2.9. **Optional**: Add an ApiUser object configuration for remote troubleshooting. - [root@icinga2-client1.localdomain /]# cat </etc/icinga2/conf.d/api-users.conf - object ApiUser "root" { - password = "clientsupersecretpassword" - permissions = ["*"] - } - EOF +``` +[root@icinga2-client1.localdomain /]# cat </etc/icinga2/conf.d/api-users.conf +object ApiUser "root" { + password = "clientsupersecretpassword" + permissions = ["*"] +} +EOF +``` In case you've previously disabled the "conf.d" directory only add the file file `conf.d/api-users.conf`: - [root@icinga2-client1.localdomain /]# echo 'include "conf.d/api-users.conf"' >> /etc/icinga2/icinga2.conf +``` +[root@icinga2-client1.localdomain /]# echo 'include "conf.d/api-users.conf"' >> /etc/icinga2/icinga2.conf +``` Finally restart Icinga 2. - [root@icinga2-client1.localdomain /]# systemctl restart icinga2 +``` +[root@icinga2-client1.localdomain /]# systemctl restart icinga2 +``` Your automation tool must then configure master node in the meantime. - # cat <>/etc/icinga2/zones.conf - object Endpoint "icinga2-client1.localdomain" { - //client connects itself - } +``` +# cat <>/etc/icinga2/zones.conf +object Endpoint "icinga2-client1.localdomain" { + //client connects itself +} - object Zone "icinga2-client1.localdomain" { - endpoints = [ "icinga2-client1.localdomain" ] - parent = "master" - } +object Zone "icinga2-client1.localdomain" { + endpoints = [ "icinga2-client1.localdomain" ] + parent = "master" +} - EOF +EOF +``` ## Using Multiple Environments diff --git a/doc/07-agent-based-monitoring.md b/doc/07-agent-based-monitoring.md index 48c0d1cf8..99e461523 100644 --- a/doc/07-agent-based-monitoring.md +++ b/doc/07-agent-based-monitoring.md @@ -15,15 +15,17 @@ 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 have the `snmp-community` custom attribute. - apply Service "uptime" { - import "generic-service" +``` +apply Service "uptime" { + import "generic-service" - check_command = "snmp" - vars.snmp_oid = "1.3.6.1.2.1.1.3.0" - vars.snmp_miblist = "DISMAN-EVENT-MIB" + check_command = "snmp" + vars.snmp_oid = "1.3.6.1.2.1.1.3.0" + vars.snmp_miblist = "DISMAN-EVENT-MIB" - 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). @@ -37,23 +39,25 @@ 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 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" { - import "by_ssh" +``` +object CheckCommand "by_ssh_swap" { + import "by_ssh" - vars.by_ssh_command = "/usr/lib/nagios/plugins/check_swap -w $by_ssh_swap_warn$ -c $by_ssh_swap_crit$" - vars.by_ssh_swap_warn = "75%" - vars.by_ssh_swap_crit = "50%" - } + vars.by_ssh_command = "/usr/lib/nagios/plugins/check_swap -w $by_ssh_swap_warn$ -c $by_ssh_swap_crit$" + vars.by_ssh_swap_warn = "75%" + vars.by_ssh_swap_crit = "50%" +} - object Service "swap" { - import "generic-service" +object Service "swap" { + import "generic-service" - host_name = "remote-ssh-host" + host_name = "remote-ssh-host" - check_command = "by_ssh_swap" + check_command = "by_ssh_swap" - vars.by_ssh_logname = "icinga" - } + vars.by_ssh_logname = "icinga" +} +``` ## NSClient++ @@ -67,18 +71,20 @@ Icinga 2 provides the [nscp check command](10-icinga-template-library.md#plugin- Example: - object Service "disk" { - import "generic-service" +``` +object Service "disk" { + import "generic-service" - host_name = "remote-windows-host" + host_name = "remote-windows-host" - check_command = "nscp" + check_command = "nscp" - vars.nscp_variable = "USEDDISKSPACE" - vars.nscp_params = "c" - vars.nscp_warn = 70 - vars.nscp_crit = 80 - } + vars.nscp_variable = "USEDDISKSPACE" + vars.nscp_params = "c" + vars.nscp_warn = 70 + vars.nscp_crit = 80 +} +``` For details on the `NSClient++` configuration please refer to the [official documentation](https://docs.nsclient.org/). @@ -116,18 +122,22 @@ Icinga 2 provides the [nrpe check command](10-icinga-template-library.md#plugin- Example: - object Service "users" { - import "generic-service" +``` +object Service "users" { + import "generic-service" - host_name = "remote-nrpe-host" + host_name = "remote-nrpe-host" - check_command = "nrpe" - vars.nrpe_command = "check_users" - } + check_command = "nrpe" + vars.nrpe_command = "check_users" +} +``` 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` command line parameter, make sure that your NRPE daemon has them @@ -144,19 +154,23 @@ attribute which expects either a single value or an array of values. Example: - object Service "nrpe-disk-/" { - import "generic-service" +``` +object Service "nrpe-disk-/" { + import "generic-service" - host_name = "remote-nrpe-host" + host_name = "remote-nrpe-host" - check_command = "nrpe" - vars.nrpe_command = "check_disk" - vars.nrpe_arguments = [ "20%", "10%", "/" ] - } + check_command = "nrpe" + vars.nrpe_command = "check_disk" + vars.nrpe_arguments = [ "20%", "10%", "/" ] +} +``` Icinga 2 will execute the nrpe plugin like this: - /usr/lib/nagios/plugins/check_nrpe -H -c 'check_disk' -a '20%' '10%' '/' +``` +/usr/lib/nagios/plugins/check_nrpe -H -c 'check_disk' -a '20%' '10%' '/' +``` NRPE expects all additional arguments in an ordered fashion and interprets the first value as `$ARG1$` macro, the second @@ -164,12 +178,16 @@ value as `$ARG2$`, and so on. 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 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) when using its NRPE supported check method. @@ -193,14 +211,16 @@ state or from a missed reset event. Add a directive in `snmptt.conf` - EVENT coldStart .1.3.6.1.6.3.1.1.5.1 "Status Events" Normal - FORMAT Device reinitialized (coldStart) - EXEC echo "[$@] PROCESS_SERVICE_CHECK_RESULT;$A;Coldstart;2;The snmp agent has reinitialized." >> /var/run/icinga2/cmd/icinga2.cmd - SDESC - A coldStart trap signifies that the SNMPv2 entity, acting - in an agent role, is reinitializing itself and that its - configuration may have been altered. - EDESC +``` +EVENT coldStart .1.3.6.1.6.3.1.1.5.1 "Status Events" Normal +FORMAT Device reinitialized (coldStart) +EXEC echo "[$@] PROCESS_SERVICE_CHECK_RESULT;$A;Coldstart;2;The snmp agent has reinitialized." >> /var/run/icinga2/cmd/icinga2.cmd +SDESC +A coldStart trap signifies that the SNMPv2 entity, acting +in an agent role, is reinitializing itself and that its +configuration may have been altered. +EDESC +``` 1. Define the `EVENT` as per your need. 2. Construct the `EXEC` statement with the service name matching your template @@ -210,105 +230,111 @@ match your Icinga convention. Add an `EventCommand` configuration object for the passive service auto reset event. - object EventCommand "coldstart-reset-event" { - command = [ ConfigDir + "/conf.d/custom/scripts/coldstart_reset_event.sh" ] +``` +object EventCommand "coldstart-reset-event" { + command = [ ConfigDir + "/conf.d/custom/scripts/coldstart_reset_event.sh" ] - arguments = { - "-i" = "$service.state_id$" - "-n" = "$host.name$" - "-s" = "$service.name$" - } - } + arguments = { + "-i" = "$service.state_id$" + "-n" = "$host.name$" + "-s" = "$service.name$" + } +} +``` 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 of event firing after the service has been reset. - #!/bin/bash - - SERVICE_STATE_ID="" - HOST_NAME="" - SERVICE_NAME="" - - show_help() - { - cat <<-EOF - Usage: ${0##*/} [-h] -n HOST_NAME -s SERVICE_NAME - Writes a coldstart reset event to the Icinga command pipe. - - -h Display this help and exit. - -i SERVICE_STATE_ID The associated service state id. - -n HOST_NAME The associated host name. - -s SERVICE_NAME The associated service name. - EOF - } - - while getopts "hi:n:s:" opt; do - case "$opt" in - h) - show_help - exit 0 - ;; - i) - SERVICE_STATE_ID=$OPTARG - ;; - n) - HOST_NAME=$OPTARG - ;; - s) - SERVICE_NAME=$OPTARG - ;; - '?') - show_help - exit 0 - ;; - esac - done - - if [ -z "$SERVICE_STATE_ID" ]; then - show_help - printf "\n Error: -i required.\n" - exit 1 - fi - - if [ -z "$HOST_NAME" ]; then - show_help - printf "\n Error: -n required.\n" - exit 1 - fi - - if [ -z "$SERVICE_NAME" ]; then - show_help - printf "\n Error: -s required.\n" - exit 1 - fi - - 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 - fi +``` +#!/bin/bash + +SERVICE_STATE_ID="" +HOST_NAME="" +SERVICE_NAME="" + +show_help() +{ +cat <<-EOF + Usage: ${0##*/} [-h] -n HOST_NAME -s SERVICE_NAME + Writes a coldstart reset event to the Icinga command pipe. + + -h Display this help and exit. + -i SERVICE_STATE_ID The associated service state id. + -n HOST_NAME The associated host name. + -s SERVICE_NAME The associated service name. +EOF +} + +while getopts "hi:n:s:" opt; do + case "$opt" in + h) + show_help + exit 0 + ;; + i) + SERVICE_STATE_ID=$OPTARG + ;; + n) + HOST_NAME=$OPTARG + ;; + s) + SERVICE_NAME=$OPTARG + ;; + '?') + show_help + exit 0 + ;; + esac +done + +if [ -z "$SERVICE_STATE_ID" ]; then + show_help + printf "\n Error: -i required.\n" + exit 1 +fi + +if [ -z "$HOST_NAME" ]; then + show_help + printf "\n Error: -n required.\n" + exit 1 +fi + +if [ -z "$SERVICE_NAME" ]; then + show_help + printf "\n Error: -s required.\n" + exit 1 +fi + +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 +fi +``` Finally create the `Service` and assign it: - apply Service "Coldstart" { - import "generic-service-custom" +``` +apply Service "Coldstart" { + import "generic-service-custom" - check_command = "dummy" - event_command = "coldstart-reset-event" + check_command = "dummy" + event_command = "coldstart-reset-event" - enable_notifications = 1 - enable_active_checks = 0 - enable_passive_checks = 1 - enable_flapping = 0 - volatile = 1 - enable_perfdata = 0 + enable_notifications = 1 + enable_active_checks = 0 + enable_passive_checks = 1 + enable_flapping = 0 + volatile = 1 + enable_perfdata = 0 - vars.dummy_state = 0 - vars.dummy_text = "Manual reset." + vars.dummy_state = 0 + vars.dummy_text = "Manual reset." - vars.sla = "24x7" + vars.sla = "24x7" - assign where (host.vars.os == "Linux" || host.vars.os == "Windows") - } + assign where (host.vars.os == "Linux" || host.vars.os == "Windows") +} +``` ### Complex SNMP Traps @@ -321,13 +347,15 @@ As long as the most recent passive update has occurred, the active check is bypa Add a directive in `snmptt.conf` - EVENT enterpriseSpecific "Status Events" Normal - FORMAT Enterprise specific trap - EXEC echo "[$@] PROCESS_SERVICE_CHECK_RESULT;$A;$1;$2;$3" >> /var/run/icinga2/cmd/icinga2.cmd - SDESC - An enterprise specific trap. - The varbinds in order denote the Icinga service name, state and text. - EDESC +``` +EVENT enterpriseSpecific "Status Events" Normal +FORMAT Enterprise specific trap +EXEC echo "[$@] PROCESS_SERVICE_CHECK_RESULT;$A;$1;$2;$3" >> /var/run/icinga2/cmd/icinga2.cmd +SDESC +An enterprise specific trap. +The varbinds in order denote the Icinga service name, state and text. +EDESC +``` 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. @@ -337,22 +365,24 @@ 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 passive update with the state and text from the second and third varbind: - object Service "Backup" { - import "generic-service-custom" - - host_name = "host.domain.com" - check_command = "dummy" - - enable_notifications = 1 - enable_active_checks = 1 - enable_passive_checks = 1 - enable_flapping = 0 - volatile = 1 - max_check_attempts = 1 - check_interval = 87000 - enable_perfdata = 0 - - vars.sla = "24x7" - vars.dummy_state = 2 - vars.dummy_text = "No passive check result received." - } +``` +object Service "Backup" { + import "generic-service-custom" + + host_name = "host.domain.com" + check_command = "dummy" + + enable_notifications = 1 + enable_active_checks = 1 + enable_passive_checks = 1 + enable_flapping = 0 + volatile = 1 + max_check_attempts = 1 + check_interval = 87000 + enable_perfdata = 0 + + vars.sla = "24x7" + vars.dummy_state = 2 + vars.dummy_text = "No passive check result received." +} +``` \ No newline at end of file diff --git a/doc/08-advanced-topics.md b/doc/08-advanced-topics.md index 858323f03..a7acb9591 100644 --- a/doc/08-advanced-topics.md +++ b/doc/08-advanced-topics.md @@ -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: - (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), 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** > @@ -579,65 +583,69 @@ In addition to that you can optionally define the `ssl` attribute which enables Host definition: - object Host "webserver01" { - import "generic-host" - address = "192.168.56.200" - vars.os = "Linux" - - vars.webserver = { - instance["status"] = { - address = "192.168.56.201" - port = "80" - url = "/status" - } - instance["tomcat"] = { - address = "192.168.56.202" - port = "8080" - } - instance["icingaweb2"] = { - address = "192.168.56.210" - port = "443" - url = "/icingaweb2" - ssl = true - } - } +``` +object Host "webserver01" { + import "generic-host" + address = "192.168.56.200" + vars.os = "Linux" + + vars.webserver = { + instance["status"] = { + address = "192.168.56.201" + port = "80" + url = "/status" } + instance["tomcat"] = { + address = "192.168.56.202" + port = "8080" + } + instance["icingaweb2"] = { + address = "192.168.56.210" + port = "443" + url = "/icingaweb2" + ssl = true + } + } +} +``` Service apply for definitions: - apply Service "webserver_ping" for (instance => config in host.vars.webserver.instance) { - display_name = "webserver_" + instance - check_command = "ping4" +``` +apply Service "webserver_ping" for (instance => config in host.vars.webserver.instance) { + display_name = "webserver_" + instance + check_command = "ping4" - vars.ping_address = config.address + vars.ping_address = config.address - assign where host.vars.webserver.instance - } + assign where host.vars.webserver.instance +} - apply Service "webserver_port" for (instance => config in host.vars.webserver.instance) { - display_name = "webserver_" + instance + "_" + config.port - check_command = "tcp" +apply Service "webserver_port" for (instance => config in host.vars.webserver.instance) { + display_name = "webserver_" + instance + "_" + config.port + check_command = "tcp" - vars.tcp_address = config.address - vars.tcp_port = config.port + vars.tcp_address = config.address + vars.tcp_port = config.port - assign where host.vars.webserver.instance - } + assign where host.vars.webserver.instance +} - apply Service "webserver_url" for (instance => config in host.vars.webserver.instance) { - display_name = "webserver_" + instance + "_" + config.url - check_command = "http" +apply Service "webserver_url" for (instance => config in host.vars.webserver.instance) { + display_name = "webserver_" + instance + "_" + config.url + check_command = "http" - vars.http_address = config.address - vars.http_port = config.port - vars.http_uri = config.url + vars.http_address = config.address + vars.http_port = config.port + vars.http_uri = config.url - if (config.ssl) { - vars.http_ssl = config.ssl - } + if (config.ssl) { + vars.http_ssl = config.ssl + } - assign where config.url != "" - } + assign where config.url != "" +} +``` 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 @@ -756,25 +764,27 @@ 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 as value for `ping_wrta`, all other hosts use 100. - globals.group_specific_value = function(group, group_value, non_group_value) { - return function() use (group, group_value, non_group_value) { - if (group in host.groups) { - return group_value - } else { - return non_group_value - } +``` +globals.group_specific_value = function(group, group_value, non_group_value) { + return function() use (group, group_value, non_group_value) { + if (group in host.groups) { + return group_value + } else { + return non_group_value } } +} - apply Service "ping4" { - import "generic-service" - check_command = "ping4" +apply Service "ping4" { + import "generic-service" + check_command = "ping4" - vars.ping_wrta = group_specific_value("slow-lan", 300, 100) - vars.ping_crta = group_specific_value("slow-lan", 500, 200) + vars.ping_wrta = group_specific_value("slow-lan", 300, 100) + vars.ping_crta = group_specific_value("slow-lan", 500, 200) - assign where true - } + assign where true +} +``` #### Use Functions in Assign Where Expressions @@ -790,36 +800,37 @@ The following example requires the host `myprinter` being added to the host group `printers-lexmark` but only if the host uses a template matching the name `lexmark*`. - template Host "lexmark-printer-host" { - vars.printer_type = "Lexmark" - } - - object Host "myprinter" { - import "generic-host" - import "lexmark-printer-host" +``` +template Host "lexmark-printer-host" { + vars.printer_type = "Lexmark" +} - address = "192.168.1.1" - } +object Host "myprinter" { + import "generic-host" + import "lexmark-printer-host" - /* register a global function for the assign where call */ - globals.check_host_templates = function(host, search) { - /* iterate over all host templates and check if the search matches */ - for (tmpl in host.templates) { - if (match(search, tmpl)) { - return true - } - } + address = "192.168.1.1" +} - /* nothing matched */ - return false +/* register a global function for the assign where call */ +globals.check_host_templates = function(host, search) { + /* iterate over all host templates and check if the search matches */ + for (tmpl in host.templates) { + if (match(search, tmpl)) { + return true } + } - object HostGroup "printers-lexmark" { - display_name = "Lexmark Printers" - /* call the global function and pass the arguments */ - assign where check_host_templates(host, "lexmark*") - } + /* nothing matched */ + return false +} +object HostGroup "printers-lexmark" { + display_name = "Lexmark Printers" + /* call the global function and pass the arguments */ + assign where check_host_templates(host, "lexmark*") +} +``` Take a different more complex example: All hosts with the custom attribute `vars_app` as nested dictionary should be @@ -828,43 +839,46 @@ added to the host group `ABAP-app-server`. But only if the It could read as wildcard match for nested dictionaries: +``` where host.vars.vars_app["*"].app_type == "ABAP" +``` The solution for this problem is to register a global function which checks the `app_type` for all hosts with the `vars_app` dictionary. - object Host "appserver01" { - check_command = "dummy" - vars.vars_app["ABC"] = { app_type = "ABAP" } - } - object Host "appserver02" { - check_command = "dummy" - vars.vars_app["DEF"] = { app_type = "ABAP" } - } - - globals.check_app_type = function(host, type) { - /* ensure that other hosts without the custom attribute do not match */ - if (typeof(host.vars.vars_app) != Dictionary) { - return false - } +``` +object Host "appserver01" { + check_command = "dummy" + vars.vars_app["ABC"] = { app_type = "ABAP" } +} +object Host "appserver02" { + check_command = "dummy" + vars.vars_app["DEF"] = { app_type = "ABAP" } +} - /* iterate over the vars_app dictionary */ - for (key => val in host.vars.vars_app) { - /* if the value is a dictionary and if contains the app_type being the requested type */ - if (typeof(val) == Dictionary && val.app_type == type) { - return true - } - } +globals.check_app_type = function(host, type) { + /* ensure that other hosts without the custom attribute do not match */ + if (typeof(host.vars.vars_app) != Dictionary) { + return false + } - /* nothing matched */ - return false + /* iterate over the vars_app dictionary */ + for (key => val in host.vars.vars_app) { + /* if the value is a dictionary and if contains the app_type being the requested type */ + if (typeof(val) == Dictionary && val.app_type == type) { + return true } + } - object HostGroup "ABAP-app-server" { - assign where check_app_type(host, "ABAP") - } + /* nothing matched */ + return false +} +object HostGroup "ABAP-app-server" { + assign where check_app_type(host, "ABAP") +} +``` #### Use Functions in Command Arguments set_if @@ -879,13 +893,15 @@ multiple conditions and attributes. 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. - object Host "dict-host" { - check_command = "check_compellent" - vars.compellent["disks"] = { - file = "/var/lib/check_compellent/san_disks.0.json", - checks = ["disks"] - } - } +``` +object Host "dict-host" { + check_command = "check_compellent" + vars.compellent["disks"] = { + file = "/var/lib/check_compellent/san_disks.0.json", + checks = ["disks"] + } +} +``` 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. @@ -894,20 +910,22 @@ 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 solved like this: - object CheckCommand "check_compellent" { - command = [ "/usr/bin/check_compellent" ] - arguments = { - "--disks" = { - set_if = {{ - var host_vars = host.vars - log(host_vars) - var compel = host_vars.compellent - log(compel) - compel.contains("disks") - }} - } - } +``` +object CheckCommand "check_compellent" { + command = [ "/usr/bin/check_compellent" ] + arguments = { + "--disks" = { + set_if = {{ + var host_vars = host.vars + log(host_vars) + var compel = host_vars.compellent + log(compel) + compel.contains("disks") + }} } + } +} +``` 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`. @@ -915,35 +933,38 @@ Therefore you can extend the checks using the [typeof](17-language-reference.md# You can test the types using the `icinga2 console`: - # icinga2 console - Icinga (version: v2.3.0-193-g3eb55ad) - <1> => srv_vars.compellent["check_a"] = { file="outfile_a.json", checks = [ "disks", "fans" ] } - null - <2> => srv_vars.compellent["check_b"] = { file="outfile_b.json", checks = [ "power", "voltages" ] } - null - <3> => typeof(srv_vars.compellent) - type 'Dictionary' - <4> => +``` +# icinga2 console +Icinga (version: v2.3.0-193-g3eb55ad) +<1> => srv_vars.compellent["check_a"] = { file="outfile_a.json", checks = [ "disks", "fans" ] } +null +<2> => srv_vars.compellent["check_b"] = { file="outfile_b.json", checks = [ "power", "voltages" ] } +null +<3> => typeof(srv_vars.compellent) +type 'Dictionary' +<4> => +``` The more programmatic approach for `set_if` could look like this: - "--disks" = { - set_if = {{ - var srv_vars = service.vars - if(len(srv_vars) > 0) { - if (typeof(srv_vars.compellent) == Dictionary) { - return srv_vars.compellent.contains("disks") - } else { - log(LogInformationen, "checkcommand set_if", "custom attribute compellent_checks is not a dictionary, ignoring it.") - return false - } - } else { - log(LogWarning, "checkcommand set_if", "empty custom attributes") - return false - } - }} +``` + "--disks" = { + set_if = {{ + var srv_vars = service.vars + if(len(srv_vars) > 0) { + if (typeof(srv_vars.compellent) == Dictionary) { + return srv_vars.compellent.contains("disks") + } else { + log(LogInformationen, "checkcommand set_if", "custom attribute compellent_checks is not a dictionary, ignoring it.") + return false + } + } else { + log(LogWarning, "checkcommand set_if", "empty custom attributes") + return false } - + }} + } +``` #### Use Functions as Command Attribute @@ -955,20 +976,22 @@ 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 script to call based on that. - object User "short-dummy" { - } +``` +object User "short-dummy" { +} - object UserGroup "short-dummy-group" { - assign where user.name == "short-dummy" - } +object UserGroup "short-dummy-group" { + assign where user.name == "short-dummy" +} - apply Notification "mail-admins-short" to Host { - import "mail-host-notification" - command = "mail-host-notification-test" - user_groups = [ "short-dummy-group" ] - vars.short = true - assign where host.vars.notification.mail - } +apply Notification "mail-admins-short" to Host { + import "mail-host-notification" + command = "mail-host-notification-test" + user_groups = [ "short-dummy-group" ] + vars.short = true + assign where host.vars.notification.mail +} +``` The solution is fairly simple: The `command` attribute is implemented as function returning an array required by the caller Icinga 2. @@ -980,25 +1003,26 @@ returned. You can omit the `log()` calls, they only help debugging. - object NotificationCommand "mail-host-notification-test" { - command = {{ - log("command as function") - var mailscript = "mail-host-notification-long.sh" - if (notification.vars.short) { - mailscript = "mail-host-notification-short.sh" - } - log("Running command") - log(mailscript) - - var cmd = [ ConfigDir + "/scripts/" + mailscript ] - log(LogCritical, "me", cmd) - return cmd - }} - - env = { - } +``` +object NotificationCommand "mail-host-notification-test" { + command = {{ + log("command as function") + var mailscript = "mail-host-notification-long.sh" + if (notification.vars.short) { + mailscript = "mail-host-notification-short.sh" } + log("Running command") + log(mailscript) + + var cmd = [ ConfigDir + "/scripts/" + mailscript ] + log(LogCritical, "me", cmd) + return cmd + }} + env = { + } +} +``` ### Access Object Attributes at Runtime diff --git a/doc/09-object-types.md b/doc/09-object-types.md index b785d1f60..b12b69691 100644 --- a/doc/09-object-types.md +++ b/doc/09-object-types.md @@ -395,12 +395,14 @@ Configuration Attributes: Available state filters: - OK - Warning - Critical - Unknown - Up - Down +``` +OK +Warning +Critical +Unknown +Up +Down +``` 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. @@ -1149,27 +1151,33 @@ Configuration Attributes: Available notification state filters for Service: - OK - Warning - Critical - Unknown +``` +OK +Warning +Critical +Unknown +``` Available notification state filters for Host: - Up - Down +``` +Up +Down +``` Available notification type filters: - DowntimeStart - DowntimeEnd - DowntimeRemoved - Custom - Acknowledgement - Problem - Recovery - FlappingStart - FlappingEnd +``` +DowntimeStart +DowntimeEnd +DowntimeRemoved +Custom +Acknowledgement +Problem +Recovery +FlappingStart +FlappingEnd +``` Runtime Attributes: @@ -1680,24 +1688,28 @@ object User "icingaadmin" { Available notification state filters: - OK - Warning - Critical - Unknown - Up - Down +``` +OK +Warning +Critical +Unknown +Up +Down +``` Available notification type filters: - DowntimeStart - DowntimeEnd - DowntimeRemoved - Custom - Acknowledgement - Problem - Recovery - FlappingStart - FlappingEnd +``` +DowntimeStart +DowntimeEnd +DowntimeRemoved +Custom +Acknowledgement +Problem +Recovery +FlappingStart +FlappingEnd +``` Configuration Attributes: diff --git a/doc/10-icinga-template-library.md b/doc/10-icinga-template-library.md index 45172ac78..fb7283f38 100644 --- a/doc/10-icinga-template-library.md +++ b/doc/10-icinga-template-library.md @@ -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: - include +``` +include +``` These templates are imported by the provided example configuration. diff --git a/doc/12-icinga2-api.md b/doc/12-icinga2-api.md index 8709438d1..1a6a54be4 100644 --- a/doc/12-icinga2-api.md +++ b/doc/12-icinga2-api.md @@ -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 `/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: - # service icinga2 restart +``` +# service icinga2 restart +``` 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: - Accept: application/json +``` +Accept: application/json +``` Each URL is prefixed with the API version (currently "/v1"). @@ -74,15 +80,16 @@ list. Depending on the number of affected objects in your request, the The output will be sent back as a JSON object: - - { - "results": [ - { - "code": 200.0, - "status": "Object was created." - } - ] - } +``` +{ + "results": [ + { + "code": 200.0, + "status": "Object was created." + } + ] +} +``` > **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 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" { - password = "icinga" - } +object ApiUser "root" { + password = "icinga" +} +``` 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 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" { - client_cn = "CertificateCommonName" - } +object ApiUser "root" { + client_cn = "CertificateCommonName" +} +``` An `ApiUser` object can have both authentication methods configured. 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. When using client certificates for authentication you'll need to pass your client certificate 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. @@ -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 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) 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: - permissions = [ "*" ] +``` +permissions = [ "*" ] +``` 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: - 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 filter expression has to be a [lambda function](17-language-reference.md#nullary-lambdas) @@ -200,16 +221,18 @@ The following example allows the API user to query all hosts and services which custom attribute `os` that matches the regular expression `^Linux`. The [regex function](18-library-reference.md#global-functions-regex) is available as global function. - permissions = [ - { - permission = "objects/query/Host" - filter = {{ regex("^Linux", host.vars.os) }} - }, - { - permission = "objects/query/Service" - filter = {{ regex("^Linux", service.vars.os) }} - } - ] +``` +permissions = [ + { + permission = "objects/query/Host" + filter = {{ regex("^Linux", host.vars.os) }} + }, + { + permission = "objects/query/Service" + filter = {{ regex("^Linux", service.vars.os) }} + } +] +``` 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: - /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: - { "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 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: - $ 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: - $ 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 @@ -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 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: - 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 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: - 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. When specifying names for objects which have composite names like for example services the 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. @@ -336,15 +375,20 @@ Advanced filters allow users to filter objects using lambda expressions. The syn 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: - 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`: - - 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 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 type using the `type` parameter: - $ 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 }' +``` +$ 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 }' +``` 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 @@ -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 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' \ - -d '{ "filter": "host.vars.os == os", "filter_vars": { "os": "Linux" }, "pretty": true }' +``` +$ 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 }' +``` 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. @@ -421,7 +469,9 @@ a `GET` query to the `/v1/objects/` URL endpoint. ` @@ -479,17 +533,23 @@ information about the host when querying service objects. 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 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 the `all_joins` query parameter. - https://localhost:5665/v1/objects/services?all_joins=1 +``` +https://localhost:5665/v1/objects/services?all_joins=1 +``` > **Note** > @@ -512,105 +572,113 @@ 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 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' - - { - "results": [ - { - "attrs": { - "check_command": "ping4", - "display_name": "ping4" - }, - "joins": { - "host": { - "address": "192.168.1.1", - "name": "example.localdomain" - } - }, - "meta": {}, - "name": "example.localdomain!ping4", - "type": "Service" +``` +$ 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' + +{ + "results": [ + { + "attrs": { + "check_command": "ping4", + "display_name": "ping4" }, - { - "attrs": { - "check_command": "ssh", - "display_name": "ssh" - }, - "joins": { - "host": { - "address": "192.168.1.1", - "name": "example.localdomain" - } - }, - "meta": {}, - "name": "example.localdomain!ssh", - "type": "Service" - } - ] - } + "joins": { + "host": { + "address": "192.168.1.1", + "name": "example.localdomain" + } + }, + "meta": {}, + "name": "example.localdomain!ping4", + "type": "Service" + }, + { + "attrs": { + "check_command": "ssh", + "display_name": "ssh" + }, + "joins": { + "host": { + "address": "192.168.1.1", + "name": "example.localdomain" + } + }, + "meta": {}, + "name": "example.localdomain!ssh", + "type": "Service" + } + ] +} +``` 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 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 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. - $ 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 }' - - { - "results": [ - { - "attrs": { - "acknowledgement": 0.0, - "downtime_depth": 0.0, - "name": "10807-service", - "state": 3.0 - }, - "joins": { - "host": { - "address": "", - "name": "10807-host" - } - }, - "meta": {}, - "name": "10807-host!10807-service", - "type": "Service" - } - ] - } +``` +$ 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 }' + +{ + "results": [ + { + "attrs": { + "acknowledgement": 0.0, + "downtime_depth": 0.0, + "name": "10807-service", + "state": 3.0 + }, + "joins": { + "host": { + "address": "", + "name": "10807-host" + } + }, + "meta": {}, + "name": "10807-host!10807-service", + "type": "Service" + } + ] +} +``` 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) 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' \ - -d '{ "joins": [ "service.name", "service.acknowledgement", "service.acknowledgement_expiry" ], "attrs": [ "author", "text" ], "filter": "service.acknowledgement!=0 && service.acknowledgement_expiry==0", "pretty": true }' - - { - "results": [ - { - "attrs": { - "author": "icingaadmin", - "text": "maintenance work" - }, - "joins": { - "service": { - "__name": "example.localdomain!disk /", - "acknowledgement": 1.0, - "acknowledgement_expiry": 0.0 - } - }, - "meta": {}, - "name": "example.localdomain!disk /!example.localdomain-1495457222-0", - "type": "Comment" - } - ] - } +``` +$ 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 }' + +{ + "results": [ + { + "attrs": { + "author": "icingaadmin", + "text": "maintenance work" + }, + "joins": { + "service": { + "__name": "example.localdomain!disk /", + "acknowledgement": 1.0, + "acknowledgement_expiry": 0.0 + } + }, + "meta": {}, + "name": "example.localdomain!disk /!example.localdomain-1495457222-0", + "type": "Comment" + } + ] +} +``` ### Creating Config Objects @@ -628,50 +696,58 @@ 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): - "attrs": { "vars.os": "Linux" } +``` +"attrs": { "vars.os": "Linux" } +``` 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' \ - -d '{ "templates": [ "generic-host" ], "attrs": { "address": "192.168.1.1", "check_command": "hostalive", "vars.os" : "Linux" }, "pretty": true }' - { - "results": [ - { - "code": 200.0, - "status": "Object was created." - } - ] - } +``` +$ 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 }' +{ + "results": [ + { + "code": 200.0, + "status": "Object was created." + } + ] +} +``` 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 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' \ - -d '{ "attrs": { "address": "192.168.1.1", "vars.os" : "Linux" }, "pretty": true }' - { - "results": [ - { - "code": 500.0, - "errors": [ - "Error: Validation failed for object 'example.localdomain' of type 'Host'; Attribute 'check_command': Attribute must not be empty." - ], - "status": "Object could not be created." - } - ] - } +``` +$ 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 }' +{ + "results": [ + { + "code": 500.0, + "errors": [ + "Error: Validation failed for object 'example.localdomain' of type 'Host'; Attribute 'check_command': Attribute must not be empty." + ], + "status": "Object could not be created." + } + ] +} +``` 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' \ - -d '{ "templates": [ "generic-service" ], "attrs": { "check_command": "load", "check_interval": 1,"retry_interval": 1 } }' - +``` +$ 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 } }' +``` 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' \ - -d '{ "templates": [ "plugin-check-command" ], "attrs": { "command": [ "/usr/local/sbin/check_http" ], "arguments": { "-I": "$mytest_iparam$" } } }' - +``` +$ 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$" } } }' +``` ### Modifying Objects @@ -697,23 +773,26 @@ 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: - "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: - $ 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 }' - { - "results": [ - { - "code": 200.0, - "name": "example.localdomain", - "status": "Attributes updated.", - "type": "Host" - } - ] - } - +``` +$ 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 }' +{ + "results": [ + { + "code": 200.0, + "name": "example.localdomain", + "status": "Attributes updated.", + "type": "Host" + } + ] +} +``` ### Deleting Objects @@ -728,17 +807,19 @@ In addition to these parameters a [filter](12-icinga2-api.md#icinga2-api-filters 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' - { - "results": [ - { - "code": 200.0, - "name": "example.localdomain", - "status": "Object was deleted.", - "type": "Host" - } - ] - } +``` +$ 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": [ + { + "code": 200.0, + "name": "example.localdomain", + "status": "Object was deleted.", + "type": "Host" + } + ] +} +``` ## Config Templates @@ -755,7 +836,9 @@ a `GET` query to the `/v1/templates/` URL endpoint. ` @@ -846,22 +941,26 @@ In addition to these parameters a [filter](12-icinga2-api.md#icinga2-api-filters 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' \ - -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 }' - - { - "results": [ - { - "code": 200.0, - "status": "Successfully processed check result for object '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 }' + +{ + "results": [ + { + "code": 200.0, + "status": "Successfully processed check result for object 'localdomain!passive-ping6'." + } + ] +} +``` 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' \ - -d '{ "filter": "host.name==\"example.localdomain\"", "type": "Host", "exit_status": 1, "plugin_output": "Host is not available." }' +``` +$ 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." }' +``` You can avoid URL encoding of white spaces in object names by using the `filter` attribute in the request body. @@ -888,18 +987,19 @@ The example reschedules all services with the name "ping6" to immediately perfor (`next_check` default), ignoring any time periods or whether active checks are 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' \ - -d '{ "type": "Service", "filter": "service.name==\"ping6\"", "force": true, "pretty": true }' - - { - "results": [ - { - "code": 200.0, - "status": "Successfully rescheduled check for object 'example.localdomain!ping6'." - } - ] - } - +``` +$ 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 }' + +{ + "results": [ + { + "code": 200.0, + "status": "Successfully rescheduled check for object 'example.localdomain!ping6'." + } + ] +} +``` ### send-custom-notification @@ -919,20 +1019,22 @@ 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 host owners: - $ 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 }' - - { - "results": [ - { - "code": 200.0, - "status": "Successfully sent custom notification for object 'host0'." - }, - { - "code": 200.0, - "status": "Successfully sent custom notification for object 'host1'." - } - } +``` +$ 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 }' + +{ + "results": [ + { + "code": 200.0, + "status": "Successfully sent custom notification for object 'host0'." + }, + { + "code": 200.0, + "status": "Successfully sent custom notification for object 'host1'." + } +} +``` ### delay-notification @@ -951,20 +1053,22 @@ In addition to these parameters a [filter](12-icinga2-api.md#icinga2-api-filters Example: - $ 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 }' - - { - "results": [ - { - "code": 200.0, - "status": "Successfully delayed notifications for object 'host0!service0'." - }, - { - "code": 200.0, - "status": "Successfully delayed notifications for object 'host1!service1'." - } - } +``` +$ 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 }' + +{ + "results": [ + { + "code": 200.0, + "status": "Successfully delayed notifications for object 'host0!service0'." + }, + { + "code": 200.0, + "status": "Successfully delayed notifications for object 'host1!service1'." + } +} +``` ### acknowledge-problem @@ -988,21 +1092,22 @@ 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 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' \ - -d '{ "author": "icingaadmin", "comment": "Global outage. Working on it.", "notify": true, "pretty": true }' - - { - "results": [ - { - "code": 200.0, - "status": "Successfully acknowledged problem for object 'example2.localdomain!ping4'." - }, - { - "code": 200.0, - "status": "Successfully acknowledged problem for object 'example.localdomain!ping4'." - } - } - +``` +$ 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 }' + +{ + "results": [ + { + "code": 200.0, + "status": "Successfully acknowledged problem for object 'example2.localdomain!ping4'." + }, + { + "code": 200.0, + "status": "Successfully acknowledged problem for object 'example.localdomain!ping4'." + } +} +``` ### remove-acknowledgement @@ -1015,19 +1120,21 @@ A [filter](12-icinga2-api.md#icinga2-api-filters) must be provided. The valid ty 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' - - { - "results": [ - { - "code": 200.0, - "status": "Successfully removed acknowledgement for object 'host0!service0'." - }, - { - "code": 200.0, - "status": "Successfully removed acknowledgement for object 'example2.localdomain!aws-health'." - } - } +``` +$ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/actions/remove-acknowledgement?type=Service&pretty=1' + +{ + "results": [ + { + "code": 200.0, + "status": "Successfully removed acknowledgement for object 'host0!service0'." + }, + { + "code": 200.0, + "status": "Successfully removed acknowledgement for object 'example2.localdomain!aws-health'." + } +} +``` ### add-comment @@ -1044,23 +1151,25 @@ In addition to these parameters a [filter](12-icinga2-api.md#icinga2-api-filters 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 }' - { - "results": [ - { - "code": 200.0, - "legacy_id": 26.0, - "name": "example.localdomain!ping4!example.localdomain-1446824161-0", - "status": "Successfully added comment 'example.localdomain!ping4!example.localdomain-1446824161-0' for object 'example.localdomain!ping4'." - }, - { - "code": 200.0, - "legacy_id": 27.0, - "name": "example2.localdomain!ping4!example.localdomain-1446824161-1", - "status": "Successfully added comment 'example2.localdomain!ping4!example.localdomain-1446824161-1' for object 'example2.localdomain!ping4'." - } - ] - } +``` +$ 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": [ + { + "code": 200.0, + "legacy_id": 26.0, + "name": "example.localdomain!ping4!example.localdomain-1446824161-0", + "status": "Successfully added comment 'example.localdomain!ping4!example.localdomain-1446824161-0' for object 'example.localdomain!ping4'." + }, + { + "code": 200.0, + "legacy_id": 27.0, + "name": "example2.localdomain!ping4!example.localdomain-1446824161-1", + "status": "Successfully added comment 'example2.localdomain!ping4!example.localdomain-1446824161-1' for object 'example2.localdomain!ping4'." + } + ] +} +``` ### remove-comment @@ -1075,32 +1184,35 @@ 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: - $ 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": [ - { - "code": 200.0, - "status": "Successfully removed comment 'example2.localdomain!ping4!mbmif.local-1446986367-0'." - } - ] - } +``` +$ 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": [ + { + "code": 200.0, + "status": "Successfully removed comment 'example2.localdomain!ping4!mbmif.local-1446986367-0'." + } + ] +} +``` 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' - { - "results": [ - { - "code": 200.0, - "status": "Successfully removed all comments for object 'example2.localdomain!ping4'." - }, - { - "code": 200.0, - "status": "Successfully removed all comments for object 'example.localdomain!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' +{ + "results": [ + { + "code": 200.0, + "status": "Successfully removed all comments for object 'example2.localdomain!ping4'." + }, + { + "code": 200.0, + "status": "Successfully removed all comments for object 'example.localdomain!ping4'." + } + ] +} +``` ### schedule-downtime @@ -1123,23 +1235,25 @@ In addition to these parameters a [filter](12-icinga2-api.md#icinga2-api-filters 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 }' - { - "results": [ - { - "code": 200.0, - "legacy_id": 2.0, - "name": "example2.localdomain!ping4!example.localdomain-1446822004-0", - "status": "Successfully scheduled downtime 'example2.localdomain!ping4!example.localdomain-1446822004-0' for object 'example2.localdomain!ping4'." - }, - { - "code": 200.0, - "legacy_id": 3.0, - "name": "example.localdomain!ping4!example.localdomain-1446822004-1", - "status": "Successfully scheduled downtime 'example.localdomain!ping4!example.localdomain-1446822004-1' for object 'example.localdomain!ping4'." - } - ] - } +``` +$ 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": [ + { + "code": 200.0, + "legacy_id": 2.0, + "name": "example2.localdomain!ping4!example.localdomain-1446822004-0", + "status": "Successfully scheduled downtime 'example2.localdomain!ping4!example.localdomain-1446822004-0' for object 'example2.localdomain!ping4'." + }, + { + "code": 200.0, + "legacy_id": 3.0, + "name": "example.localdomain!ping4!example.localdomain-1446822004-1", + "status": "Successfully scheduled downtime 'example.localdomain!ping4!example.localdomain-1446822004-1' for object 'example.localdomain!ping4'." + } + ] +} +``` ### remove-downtime @@ -1154,50 +1268,56 @@ 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: - $ 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": [ - { - "code": 200.0, - "status": "Successfully removed downtime 'example.localdomain!ping4!mbmif.local-1446979168-6'." - } - ] - } +``` +$ 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": [ + { + "code": 200.0, + "status": "Successfully removed downtime 'example.localdomain!ping4!mbmif.local-1446979168-6'." + } + ] +} +``` 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' - { - "results": [ - { - "code": 200.0, - "status": "Successfully removed all downtimes for object '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' +{ + "results": [ + { + "code": 200.0, + "status": "Successfully removed all downtimes for object 'example.localdomain'." + } + ] +} +``` 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. - $ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/actions/remove-downtime' \ - -d $'{ - "type": "Downtime", - "filter": "host.name == filterHost && !service && downtime.author == filterAuthor", - "filter_vars": { - "filterHost": "example.localdomain", - "filterAuthor": "icingaadmin" - }, - "pretty": true - }' - - { - "results": [ - { - "code": 200.0, - "status": "Successfully removed downtime 'example.localdomain!mbmif.local-1463043129-3'." - } - ] - } +``` +$ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/actions/remove-downtime' \ + -d $'{ + "type": "Downtime", + "filter": "host.name == filterHost && !service && downtime.author == filterAuthor", + "filter_vars": { + "filterHost": "example.localdomain", + "filterAuthor": "icingaadmin" + }, + "pretty": true +}' + +{ + "results": [ + { + "code": 200.0, + "status": "Successfully removed downtime 'example.localdomain!mbmif.local-1463043129-3'." + } + ] +} +``` ### shutdown-process @@ -1209,16 +1329,18 @@ This action does not support a target type or filter. Example: - $ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/actions/shutdown-process?pretty=1' - - { - "results": [ - { - "code": 200.0, - "status": "Shutting down Icinga 2." - } - ] - } +``` +$ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/actions/shutdown-process?pretty=1' + +{ + "results": [ + { + "code": 200.0, + "status": "Shutting down Icinga 2." + } + ] +} +``` ### restart-process @@ -1230,16 +1352,18 @@ This action does not support a target type or filter. Example: - $ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/actions/restart-process?pretty=1' - - { - "results": [ - { - "code": 200.0, - "status": "Restarting Icinga 2." - } - ] - } +``` +$ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/actions/restart-process?pretty=1' + +{ + "results": [ + { + "code": 200.0, + "status": "Restarting Icinga 2." + } + ] +} +``` ### generate-ticket @@ -1254,18 +1378,19 @@ Send a `POST` request to the URL endpoint `/v1/actions/generate-ticket`. Example: - $ 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 }' - { - "results": [ - { - "code": 200.0, - "status": "Generated PKI ticket '4f75d2ecd253575fe9180938ebff7cbca262f96e' for common name 'icinga2-client1.localdomain'.", - "ticket": "4f75d2ecd253575fe9180938ebff7cbca262f96e" - } - ] - } - +``` +$ 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 }' +{ + "results": [ + { + "code": 200.0, + "status": "Generated PKI ticket '4f75d2ecd253575fe9180938ebff7cbca262f96e' for common name 'icinga2-client1.localdomain'.", + "ticket": "4f75d2ecd253575fe9180938ebff7cbca262f96e" + } + ] +} +``` ## Event Streams @@ -1301,7 +1426,9 @@ being set. Example for all downtime events: - &types=DowntimeAdded&types=DowntimeRemoved&types=DowntimeTriggered +``` +&types=DowntimeAdded&types=DowntimeRemoved&types=DowntimeTriggered +``` #### Event Stream Type: CheckResult @@ -1438,13 +1565,16 @@ Event streams can be filtered by attributes using the prefix `event.`. 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) 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 @@ -1453,12 +1583,13 @@ must support long-polling and HTTP/1.1. HTTP/1.0 is not supported. 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' - - {"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":1445421329.7226390839,"type":"CheckResult"} +``` +$ 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":1445421324.7226390839,"type":"CheckResult"} +{"check_result":{ ... },"host":"example.localdomain","service":"ping4","timestamp":1445421329.7226390839,"type":"CheckResult"} +``` ## Status and Statistics @@ -1466,51 +1597,54 @@ Send a `GET` request to the URL endpoint `/v1/status` to retrieve status informa Example: - $ curl -k -s -u root:icinga 'https://localhost:5665/v1/status?pretty=1' - { - "results": [ - { - "name": "ApiListener", - "perfdata": [ ... ], - "status": [ ... ] - }, - ... - { - "name": "IcingaAplication", - "perfdata": [ ... ], - "status": [ ... ] - }, - ... - ] - } +``` +$ curl -k -s -u root:icinga 'https://localhost:5665/v1/status?pretty=1' +{ + "results": [ + { + "name": "ApiListener", + "perfdata": [ ... ], + "status": [ ... ] + }, + ... + { + "name": "IcingaAplication", + "perfdata": [ ... ], + "status": [ ... ] + }, + ... + ] +} +``` 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' - { - "results": [ - { - "perfdata": [], - "status": { - "icingaapplication": { - "app": { - "enable_event_handlers": true, - "enable_flapping": true, - "enable_host_checks": true, - "enable_notifications": true, - "enable_perfdata": true, - "enable_service_checks": true, - "node_name": "example.localdomain", - "pid": 59819.0, - "program_start": 1443019345.093372, - "version": "v2.3.0-573-g380a131" - } +``` +$ curl -k -s -u root:icinga 'https://localhost:5665/v1/status/IcingaApplication?pretty=1' +{ + "results": [ + { + "perfdata": [], + "status": { + "icingaapplication": { + "app": { + "enable_event_handlers": true, + "enable_flapping": true, + "enable_host_checks": true, + "enable_notifications": true, + "enable_perfdata": true, + "enable_service_checks": true, + "node_name": "example.localdomain", + "pid": 59819.0, + "program_start": 1443019345.093372, + "version": "v2.3.0-573-g380a131" } } } - ] - } - + } + ] +} +``` ## Configuration Management @@ -1528,17 +1662,19 @@ can be fetched in a separated request. Send a `POST` request to a new config package called `example-cmdb` in this example. This will create a new empty configuration package. - $ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST \ - 'https://localhost:5665/v1/config/packages/example-cmdb?pretty=1' - { - "results": [ - { - "code": 200.0, - "package": "example-cmdb", - "status": "Created package." - } - ] - } +``` +$ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST \ +'https://localhost:5665/v1/config/packages/example-cmdb?pretty=1' +{ + "results": [ + { + "code": 200.0, + "package": "example-cmdb", + "status": "Created package." + } + ] +} +``` Package names starting with an underscore are reserved for internal packages and must not be used. @@ -1562,30 +1698,36 @@ The file path requires one of these two directories inside its path: 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: - "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` directory. Note: This example contains an error (`chec_command`). This is intentional. - $ 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 }' \ - 'https://localhost:5665/v1/config/stages/example-cmdb' - { - "results": [ - { - "code": 200.0, - "package": "example-cmdb", - "stage": "example.localdomain-1441625839-0", - "status": "Created stage. Icinga2 will reload." - } - ] - } +``` +$ 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 }' \ +'https://localhost:5665/v1/config/stages/example-cmdb' +{ + "results": [ + { + "code": 200.0, + "package": "example-cmdb", + "stage": "example.localdomain-1441625839-0", + "status": "Created stage. Icinga2 will reload." + } + ] +} +``` 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. @@ -1618,19 +1760,20 @@ 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 have an active stage. - $ curl -k -s -u root:icinga 'https://localhost:5665/v1/config/packages?pretty=1' - { - "results": [ - { - "active-stage": "", - "name": "example-cmdb", - "stages": [ - "example.localdomain-1441625839-0" - ] - } - ] - } - +``` +$ curl -k -s -u root:icinga 'https://localhost:5665/v1/config/packages?pretty=1' +{ + "results": [ + { + "active-stage": "", + "name": "example-cmdb", + "stages": [ + "example.localdomain-1441625839-0" + ] + } + ] +} +``` ### List Configuration Packages and their Stages @@ -1638,32 +1781,34 @@ 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 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' - { - "results": [ - ... - { - "name": "startup.log", - "type": "file" - }, - { - "name": "status", - "type": "file" - }, - { - "name": "conf.d", - "type": "directory" - }, - { - "name": "zones.d", - "type": "directory" - }, - { - "name": "conf.d/test.conf", - "type": "file" - } - ] - } +``` +$ curl -k -s -u root:icinga 'https://localhost:5665/v1/config/stages/example-cmdb/example.localdomain-1441625839-0?pretty=1' +{ + "results": [ +... + { + "name": "startup.log", + "type": "file" + }, + { + "name": "status", + "type": "file" + }, + { + "name": "conf.d", + "type": "directory" + }, + { + "name": "zones.d", + "type": "directory" + }, + { + "name": "conf.d/test.conf", + "type": "file" + } + ] +} +``` ### Fetch Configuration Package Stage Files @@ -1676,9 +1821,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`: - $ 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) in a configuration stage and then specifically request their content. @@ -1692,15 +1839,17 @@ 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 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' +... - critical/config: Error: Attribute 'chec_command' does not exist. - Location: - /var/lib/icinga2/api/packages/example-cmdb/example.localdomain-1441133065-1/conf.d/test.conf(1): object Host "cmdb-host" { chec_command = "dummy" } - ^^^^^^^^^^^^^^^^^^^^^^ +critical/config: Error: Attribute 'chec_command' does not exist. +Location: +/var/lib/icinga2/api/packages/example-cmdb/example.localdomain-1441133065-1/conf.d/test.conf(1): object Host "cmdb-host" { chec_command = "dummy" } + ^^^^^^^^^^^^^^^^^^^^^^ - critical/config: 1 error +critical/config: 1 error +``` The output is similar to the manual [configuration validation](11-cli-commands.md#config-validation). @@ -1718,17 +1867,18 @@ stage name inside the URL path. The following example removes the failed configuration stage `example.localdomain-1441133065-1` in the `example-cmdb` configuration package: - $ 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' - { - "results": [ - { - "code": 200.0, - "status": "Stage deleted." - } - ] - } - +``` +$ 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' +{ + "results": [ + { + "code": 200.0, + "status": "Stage deleted." + } + ] +} +``` ### Deleting Configuration Package @@ -1738,18 +1888,19 @@ with the package name in the URL path. This example entirely deletes the configuration package `example-cmdb`: - $ curl -k -s -u root:icinga -H 'Accept: application/json' -X DELETE \ - 'https://localhost:5665/v1/config/packages/example-cmdb?pretty=1' - { - "results": [ - { - "code": 200.0, - "package": "example-cmdb", - "status": "Deleted package." - } - ] - } - +``` +$ curl -k -s -u root:icinga -H 'Accept: application/json' -X DELETE \ +'https://localhost:5665/v1/config/packages/example-cmdb?pretty=1' +{ + "results": [ + { + "code": 200.0, + "package": "example-cmdb", + "status": "Deleted package." + } + ] +} +``` ## Types @@ -1769,37 +1920,38 @@ 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: - $ curl -k -s -u root:icinga 'https://localhost:5665/v1/types/Object?pretty=1' - { - "results": [ - { - "abstract": false, - "fields": { - "type": { - "array_rank": 0.0, - "attributes": { - "config": false, - "navigation": false, - "no_user_modify": false, - "no_user_view": false, - "required": false, - "state": false - }, - "id": 0.0, - "type": "String" - } - }, - "name": "Object", - "plural_name": "Objects", - "prototype_keys": [ - "clone", - "notify_attribute", - "to_string" - ] - } - ] - } - +``` +$ curl -k -s -u root:icinga 'https://localhost:5665/v1/types/Object?pretty=1' +{ + "results": [ + { + "abstract": false, + "fields": { + "type": { + "array_rank": 0.0, + "attributes": { + "config": false, + "navigation": false, + "no_user_modify": false, + "no_user_view": false, + "required": false, + "state": false + }, + "id": 0.0, + "type": "String" + } + }, + "name": "Object", + "plural_name": "Objects", + "prototype_keys": [ + "clone", + "notify_attribute", + "to_string" + ] + } + ] +} +``` ## Console @@ -1826,48 +1978,51 @@ 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: - $ 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": [ - { - "code": 200.0, - "result": [ - "/usr/local/sbin/check_ping", - "-H", - "127.0.0.1", - "-c", - "5000,100%", - "-w", - "3000,80%" - ], - "status": "Executed successfully." - } - ] - } +``` +$ 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": [ + { + "code": 200.0, + "result": [ + "/usr/local/sbin/check_ping", + "-H", + "127.0.0.1", + "-c", + "5000,100%", + "-w", + "3000,80%" + ], + "status": "Executed successfully." + } + ] +} +``` 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): - $ 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": [ - { - "code": 200.0, - "status": "Auto-completed successfully.", - "suggestions": [ - "Host.type", - "Host.name", - "Host.prototype", - "Host.base", - "Host.register_attribute_handler", - "Host.clone", - "Host.notify_attribute", - "Host.to_string" - ] - } - ] - } - +``` +$ 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": [ + { + "code": 200.0, + "status": "Auto-completed successfully.", + "suggestions": [ + "Host.type", + "Host.name", + "Host.prototype", + "Host.base", + "Host.register_attribute_handler", + "Host.clone", + "Host.notify_attribute", + "Host.to_string" + ] + } + ] +} +``` ## API Clients @@ -1909,92 +2064,95 @@ on all services with `ping` in their name. The following example uses **Python** and the `requests` and `json` module: - # pip install requests - # pip install json - - $ vim icinga2-api-example.py - - #!/usr/bin/env python - - import requests, json - - # Replace 'localhost' with your FQDN and certificate CN - # for SSL verification - request_url = "https://localhost:5665/v1/objects/services" - headers = { - 'Accept': 'application/json', - 'X-HTTP-Method-Override': 'GET' - } - data = { - "attrs": [ "name", "state", "last_check_result" ], - "joins": [ "host.name", "host.state", "host.last_check_result" ], - "filter": "match(\"ping*\", service.name)", - } - - r = requests.post(request_url, - headers=headers, - auth=('root', 'icinga'), - data=json.dumps(data), - verify="pki/icinga2-ca.crt") - - print "Request URL: " + str(r.url) - print "Status code: " + str(r.status_code) - - if (r.status_code == 200): - print "Result: " + json.dumps(r.json()) - else: - print r.text - r.raise_for_status() - - $ python icinga2-api-example.py - +``` +# pip install requests +# pip install json + +$ vim icinga2-api-example.py + +#!/usr/bin/env python + +import requests, json + +# Replace 'localhost' with your FQDN and certificate CN +# for SSL verification +request_url = "https://localhost:5665/v1/objects/services" +headers = { + 'Accept': 'application/json', + 'X-HTTP-Method-Override': 'GET' + } +data = { + "attrs": [ "name", "state", "last_check_result" ], + "joins": [ "host.name", "host.state", "host.last_check_result" ], + "filter": "match(\"ping*\", service.name)", +} + +r = requests.post(request_url, + headers=headers, + auth=('root', 'icinga'), + data=json.dumps(data), + verify="pki/icinga2-ca.crt") + +print "Request URL: " + str(r.url) +print "Status code: " + str(r.status_code) + +if (r.status_code == 200): + print "Result: " + json.dumps(r.json()) +else: + print r.text + r.raise_for_status() + +$ python icinga2-api-example.py +``` #### Example API Client in Ruby The following example uses **Ruby** and the `rest_client` gem: - # gem install rest_client - - $ vim icinga2-api-example.rb - - #!/usr/bin/ruby - - require 'rest_client' - - # Replace 'localhost' with your FQDN and certificate CN - # for SSL verification - request_url = "https://localhost:5665/v1/objects/services" - headers = { - "Accept" => "application/json", - "X-HTTP-Method-Override" => "GET" - } - data = { - "attrs" => [ "name", "state", "last_check_result" ], - "joins" => [ "host.name", "host.state", "host.last_check_result" ], - "filter" => "match(\"ping*\", service.name)", - } - - r = RestClient::Resource.new( - URI.encode(request_url), - :headers => headers, - :user => "root", - :password => "icinga", - :ssl_ca_file => "pki/icinga2-ca.crt") - - begin - response = r.post(data.to_json) - rescue => e - response = e.response - end - - puts "Status: " + response.code.to_s - if response.code == 200 - puts "Result: " + (JSON.pretty_generate JSON.parse(response.body)) - else - puts "Error: " + response - end - - $ ruby icinga2-api-example.rb +``` +# gem install rest_client + +$ vim icinga2-api-example.rb + +#!/usr/bin/ruby + +require 'rest_client' + +# Replace 'localhost' with your FQDN and certificate CN +# for SSL verification +request_url = "https://localhost:5665/v1/objects/services" +headers = { + "Accept" => "application/json", + "X-HTTP-Method-Override" => "GET" +} +data = { + "attrs" => [ "name", "state", "last_check_result" ], + "joins" => [ "host.name", "host.state", "host.last_check_result" ], + "filter" => "match(\"ping*\", service.name)", +} + +r = RestClient::Resource.new( + URI.encode(request_url), + :headers => headers, + :user => "root", + :password => "icinga", + :ssl_ca_file => "pki/icinga2-ca.crt") + +begin + response = r.post(data.to_json) +rescue => e + response = e.response +end + +puts "Status: " + response.code.to_s +if response.code == 200 + puts "Result: " + (JSON.pretty_generate JSON.parse(response.body)) +else + puts "Error: " + response +end + +$ ruby icinga2-api-example.rb +``` A more detailed example can be found in the [Dashing demo](https://github.com/Icinga/dashing-icinga2). @@ -2002,100 +2160,103 @@ A more detailed example can be found in the [Dashing demo](https://github.com/Ic The following example uses **PHP** and its `curl` library: - $ vim icinga2-api-example.php - - #!/usr/bin/env php - array('name', 'state', 'last_check_result'), - joins => array('host.name', 'host.state', 'host.last_check_result'), - filter => 'match("ping*", service.name)', - ); - - $ch = curl_init(); - curl_setopt_array($ch, array( - CURLOPT_URL => $request_url, - CURLOPT_HTTPHEADER => $headers, - CURLOPT_USERPWD => $username . ":" . $password, - CURLOPT_RETURNTRANSFER => true, - CURLOPT_CAINFO => "pki/icinga2-ca.crt", - CURLOPT_POST => count($data), - CURLOPT_POSTFIELDS => json_encode($data) - )); - - $response = curl_exec($ch); - if ($response === false) { - print "Error: " . curl_error($ch) . "(" . $response . ")\n"; - } - - $code = curl_getinfo($ch, CURLINFO_HTTP_CODE); - curl_close($ch); - print "Status: " . $code . "\n"; - - if ($code == 200) { - $response = json_decode($response, true); - print_r($response); - } - ?> - - $ php icinga2-api-example.php +``` +$ vim icinga2-api-example.php + +#!/usr/bin/env php + array('name', 'state', 'last_check_result'), + joins => array('host.name', 'host.state', 'host.last_check_result'), + filter => 'match("ping*", service.name)', +); + +$ch = curl_init(); +curl_setopt_array($ch, array( + CURLOPT_URL => $request_url, + CURLOPT_HTTPHEADER => $headers, + CURLOPT_USERPWD => $username . ":" . $password, + CURLOPT_RETURNTRANSFER => true, + CURLOPT_CAINFO => "pki/icinga2-ca.crt", + CURLOPT_POST => count($data), + CURLOPT_POSTFIELDS => json_encode($data) +)); + +$response = curl_exec($ch); +if ($response === false) { + print "Error: " . curl_error($ch) . "(" . $response . ")\n"; +} + +$code = curl_getinfo($ch, CURLINFO_HTTP_CODE); +curl_close($ch); +print "Status: " . $code . "\n"; + +if ($code == 200) { + $response = json_decode($response, true); + print_r($response); +} +?> + +$ php icinga2-api-example.php +``` #### Example API Client in Perl The following example uses **Perl** and the `Rest::Client` module: - # perl -MCPAN -e 'install REST::Client' - # perl -MCPAN -e 'install JSON' - # perl -MCPAN -e 'install MIME::Base64' - # perl -MCPAN -e 'install Data::Dumper' - - $ vim icinga2-api-example.pl - - #!/usr/bin/env perl - - use strict; - use warnings; - use REST::Client; - use MIME::Base64; - use JSON; - use Data::Dumper; - - # Replace 'localhost' with your FQDN and certificate CN - # for SSL verification - my $request_host = "https://localhost:5665"; - my $userpass = "root:icinga"; - - my $client = REST::Client->new(); - $client->setHost($request_host); - $client->setCa("pki/icinga2-ca.crt"); - $client->addHeader("Accept", "application/json"); - $client->addHeader("X-HTTP-Method-Override", "GET"); - $client->addHeader("Authorization", "Basic " . encode_base64($userpass)); - my %json_data = ( - attrs => ['name', 'state', 'last_check_result'], - joins => ['host.name', 'host.state', 'host.last_check_result'], - filter => 'match("ping*", service.name)', - ); - my $data = encode_json(\%json_data); - $client->POST("/v1/objects/services", $data); - - my $status = $client->responseCode(); - print "Status: " . $status . "\n"; - my $response = $client->responseContent(); - if ($status == 200) { - print "Result: " . Dumper(decode_json($response)) . "\n"; - } else { - print "Error: " . $response . "\n"; - } - - $ perl icinga2-api-example.pl - +``` +# perl -MCPAN -e 'install REST::Client' +# perl -MCPAN -e 'install JSON' +# perl -MCPAN -e 'install MIME::Base64' +# perl -MCPAN -e 'install Data::Dumper' + +$ vim icinga2-api-example.pl + +#!/usr/bin/env perl + +use strict; +use warnings; +use REST::Client; +use MIME::Base64; +use JSON; +use Data::Dumper; + +# Replace 'localhost' with your FQDN and certificate CN +# for SSL verification +my $request_host = "https://localhost:5665"; +my $userpass = "root:icinga"; + +my $client = REST::Client->new(); +$client->setHost($request_host); +$client->setCa("pki/icinga2-ca.crt"); +$client->addHeader("Accept", "application/json"); +$client->addHeader("X-HTTP-Method-Override", "GET"); +$client->addHeader("Authorization", "Basic " . encode_base64($userpass)); +my %json_data = ( + attrs => ['name', 'state', 'last_check_result'], + joins => ['host.name', 'host.state', 'host.last_check_result'], + filter => 'match("ping*", service.name)', +); +my $data = encode_json(\%json_data); +$client->POST("/v1/objects/services", $data); + +my $status = $client->responseCode(); +print "Status: " . $status . "\n"; +my $response = $client->responseContent(); +if ($status == 200) { + print "Result: " . Dumper(decode_json($response)) . "\n"; +} else { + print "Error: " . $response . "\n"; +} + +$ perl icinga2-api-example.pl +``` diff --git a/doc/13-addons.md b/doc/13-addons.md index b617498cf..760fe4ccd 100644 --- a/doc/13-addons.md +++ b/doc/13-addons.md @@ -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 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). @@ -36,7 +38,9 @@ It’s written in Go and has no external dependencies. Use the [InfluxdbWriter](14-features.md#influxdb-writer) feature 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). @@ -61,11 +65,15 @@ data files which Icinga 2 generates. 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: - vim /etc/pnp4nagios/npcd.cfg +``` +vim /etc/pnp4nagios/npcd.cfg +``` 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: - [backend_live_1] - backendtype="mklivestatus" - socket="unix:/var/run/icinga2/cmd/livestatus" +``` +[backend_live_1] +backendtype="mklivestatus" +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). @@ -190,13 +200,15 @@ 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 the action url attribute in its own module). - template Host "pnp-hst" { - action_url = "/pnp4nagios/graph?host=$HOSTNAME$" - } +``` +template Host "pnp-hst" { + action_url = "/pnp4nagios/graph?host=$HOSTNAME$" +} - template Service "pnp-svc" { - action_url = "/pnp4nagios/graph?host=$HOSTNAME$&srv=$SERVICEDESC$" - } +template Service "pnp-svc" { + action_url = "/pnp4nagios/graph?host=$HOSTNAME$&srv=$SERVICEDESC$" +} +``` ### PNP Custom Templates with Icinga 2 @@ -213,24 +225,26 @@ and use that inside the formatting templates as `SERVICECHECKCOMMAND` for instan 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$" - # vim /etc/icinga2/conf.d/services.conf +# vim /etc/icinga2/conf.d/services.conf - template Service "pnp-svc" { - action_url = "/pnp4nagios/graph?host=$HOSTNAME$&srv=$SERVICEDESC$" - vars.pnp_check_arg1 = "" - } +template Service "pnp-svc" { + action_url = "/pnp4nagios/graph?host=$HOSTNAME$&srv=$SERVICEDESC$" + vars.pnp_check_arg1 = "" +} - apply Service "nrpe-check" { - import "pnp-svc" - check_command = nrpe - vars.nrpe_command = "check_disk" +apply Service "nrpe-check" { + import "pnp-svc" + check_command = nrpe + vars.nrpe_command = "check_disk" - 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 diff --git a/doc/14-features.md b/doc/14-features.md index 0ecafd62c..9b1f7615a 100644 --- a/doc/14-features.md +++ b/doc/14-features.md @@ -172,7 +172,9 @@ through the web interface). In order to enable the `ExternalCommandListener` configuration use the 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` 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 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: Rescheduling next check for service 'ping4' +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' +``` 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 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$" - 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$" +``` +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$" +``` The default templates are already provided with the Icinga 2 feature configuration 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 the `/var/spool/icinga2/perfdata/` directory as `host-perfdata.` and @@ -240,7 +248,9 @@ write them to the defined Graphite Carbon daemon tcp socket. 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 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 [runtime macros](03-monitoring-basics.md#runtime-macros)like this: - icinga2.$host.name$.host.$host.check_command$ - icinga2.$host.name$.services.$service.name$.$service.check_command$ +``` +icinga2.$host.name$.host.$host.check_command$ +icinga2.$host.name$.services.$service.name$.$service.check_command$ +``` You can customize the prefix name by using the `host_name_template` and `service_name_template` configuration attributes. @@ -274,7 +286,9 @@ The following characters are escaped in prefix labels: Metric values are stored like this: - .perfdata..value +``` +.perfdata..value +``` The following characters are escaped in perfdata labels: @@ -292,22 +306,26 @@ and is therefore replaced by `.`. By enabling `enable_send_thresholds` Icinga 2 automatically adds the following threshold metrics: - .perfdata..min - .perfdata..max - .perfdata..warn - .perfdata..crit +``` +.perfdata..min +.perfdata..max +.perfdata..warn +.perfdata..crit +``` By enabling `enable_send_metadata` Icinga 2 automatically adds the following metadata metrics: - .metadata.current_attempt - .metadata.downtime_depth - .metadata.acknowledgement - .metadata.execution_time - .metadata.latency - .metadata.max_check_attempts - .metadata.reachable - .metadata.state - .metadata.state_type +``` +.metadata.current_attempt +.metadata.downtime_depth +.metadata.acknowledgement +.metadata.execution_time +.metadata.latency +.metadata.max_check_attempts +.metadata.reachable +.metadata.state +.metadata.state_type +``` Metadata metric overview: @@ -326,10 +344,12 @@ Metadata metric overview: The following example illustrates how to configure the storage schemas for Graphite Carbon Cache. - [icinga2_default] - # intervals like PNP4Nagios uses them per default - pattern = ^icinga2\. - retentions = 1m:2d,5m:10d,30m:90d,360m:4y +``` +[icinga2_default] +# intervals like PNP4Nagios uses them per default +pattern = ^icinga2\. +retentions = 1m:2d,5m:10d,30m:90d,360m:4y +``` ### InfluxDB Writer @@ -339,7 +359,9 @@ defined InfluxDB HTTP API. 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 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: - check_result.perfdata..value +``` +check_result.perfdata..value +``` 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 if existing: - check_result.perfdata..min - check_result.perfdata..max - check_result.perfdata..warn - check_result.perfdata..crit +``` +check_result.perfdata..min +check_result.perfdata..max +check_result.perfdata..warn +check_result.perfdata..crit +``` ### Graylog Integration @@ -494,7 +520,9 @@ While it has been specified by the [Graylog](https://www.graylog.org) project as 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`. 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 - # icinga2 feature enable opentsdb +``` +# icinga2 feature enable opentsdb +``` By default the `OpenTsdbWriter` object expects the TSD to listen at `127.0.0.1` on port `4242`. The current naming schema is - icinga.host. - icinga.service.. +``` +icinga.host. +icinga.service.. +``` 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 with `_` in the target name: - \ (and space) +``` +\ (and space) +``` The resulting name in OpenTSDB might look like: - www-01 / http-cert / response time - icinga.http_cert.response_time +``` +www-01 / http-cert / response time +icinga.http_cert.response_time +``` In addition to the performance data retrieved from the check plugin, Icinga 2 sends 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 other metrics follow the current naming schema - icinga.check. +``` +icinga.check. +``` 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: - # icinga2 feature enable livestatus +``` +# icinga2 feature enable livestatus +``` 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`. 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: - # 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 `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 `compat_log_path` configuration attribute. - # icinga2 feature enable compatlog - +``` +# icinga2 feature enable compatlog +``` ### Livestatus Sockets @@ -642,26 +687,28 @@ programmatically: [Monitoring::Livestatus](http://search.cpan.org/~nierlein/Moni 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`: - # echo -e 'GET services\n' | netcat 127.0.0.1 6558 - - # cat servicegroups < A list of available external commands and their parameters can be found [here](24-appendix.md#external-commands-list-detail) - $ echo -e 'COMMAND ' | netcat 127.0.0.1 6558 - +``` +$ echo -e 'COMMAND ' | netcat 127.0.0.1 6558 +``` ### Livestatus Filters @@ -696,20 +743,22 @@ Schema: "Stats: aggregatefunction aggregateattribute" Example: - GET hosts - Filter: has_been_checked = 1 - Filter: check_type = 0 - Stats: sum execution_time - Stats: sum latency - Stats: sum percent_state_change - Stats: min execution_time - Stats: min latency - Stats: min percent_state_change - Stats: max execution_time - Stats: max latency - Stats: max percent_state_change - OutputFormat: json - ResponseHeader: fixed16 +``` +GET hosts +Filter: has_been_checked = 1 +Filter: check_type = 0 +Stats: sum execution_time +Stats: sum latency +Stats: sum percent_state_change +Stats: min execution_time +Stats: min latency +Stats: min percent_state_change +Stats: max execution_time +Stats: max latency +Stats: max percent_state_change +OutputFormat: json +ResponseHeader: fixed16 +``` ### Livestatus Output @@ -721,7 +770,9 @@ is a pipe (2nd level). Separators can be set using ASCII codes like: - Separators: 10 59 44 124 +``` +Separators: 10 59 44 124 +``` * 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 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, you can safely disable this feature. @@ -795,7 +848,9 @@ for answering queries to historical tables. 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 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 on-demand in your Icinga 2 objects configuration. - object CheckResultReader "reader" { - spool_dir = "/data/check-results" - } - +``` +object CheckResultReader "reader" { + spool_dir = "/data/check-results" +} +``` \ No newline at end of file diff --git a/doc/15-troubleshooting.md b/doc/15-troubleshooting.md index 42afa28ab..7c62d3bb4 100644 --- a/doc/15-troubleshooting.md +++ b/doc/15-troubleshooting.md @@ -547,15 +547,19 @@ settings of the Icinga 2 systemd service by creating `/etc/systemd/system/icinga2.service.d/override.conf` with the following content: - [Service] - Restart=always - RestartSec=1 - StartLimitInterval=10 - StartLimitBurst=3 +``` +[Service] +Restart=always +RestartSec=1 +StartLimitInterval=10 +StartLimitBurst=3 +``` 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 recommended. When the watchdog is activated, `Restart=` can be set to `watchdog` to restart Icinga 2 in the case of a diff --git a/doc/17-language-reference.md b/doc/17-language-reference.md index eff67a0fb..2782ef7fd 100644 --- a/doc/17-language-reference.md +++ b/doc/17-language-reference.md @@ -5,12 +5,14 @@ Icinga 2 features an object-based configuration format. You can define new objects using the `object` keyword: - object Host "host1.example.org" { - display_name = "host1" +``` +object Host "host1.example.org" { + display_name = "host1" - address = "192.168.0.1" - address6 = "2001:db8:1234::42" - } + address = "192.168.0.1" + address6 = "2001:db8:1234::42" +} +``` 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 @@ -19,11 +21,13 @@ up into multiple lines. Alternatively you can write multiple statements on a single line by separating them with a semicolon: - object Host "host1.example.org" { - display_name = "host1" +``` +object Host "host1.example.org" { + 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 (`host1.example.org`). Some types have composite names, e.g. the @@ -53,7 +57,9 @@ A floating-point number. Example: - 27.3 +``` +27.3 +``` ### Duration Literals @@ -62,7 +68,9 @@ suffixes to help with specifying time durations. Example: - 2.5m +``` +2.5m +``` Supported suffixes include ms (milliseconds), s (seconds), m (minutes), h (hours) and d (days). @@ -76,7 +84,9 @@ A string. Example: - "Hello World!" +``` +"Hello World!" +``` #### String Literals Escape Sequences @@ -104,10 +114,12 @@ Strings spanning multiple lines can be specified by enclosing them in Example: - {{{This - is - a multi-line - string.}}} +``` +{{{This +is +a multi-line +string.}}} +``` Unlike in ordinary strings special characters do not have to be escaped in multi-line string literals. @@ -130,10 +142,12 @@ The comma after the last key-value pair is optional. Example: - { - address = "192.168.0.1" - port = 443 - } +``` +{ + address = "192.168.0.1" + port = 443 +} +``` Identifiers may not contain certain characters (e.g. space) or start 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: - [ "hello", 42 ] +``` +[ "hello", 42 ] +``` An array may simultaneously contain values of different types, such as 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 to dereference a reference: - var value = "Hello!" - var p = &value /* p refers to value */ - *p = "Hi!" - log(value) // Prints "Hi!" because the variable was changed +``` +var value = "Hello!" +var p = &value /* p refers to value */ +*p = "Hi!" +log(value) // Prints "Hi!" because the variable was changed +``` ### Namespaces 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: - namespace Utils { - function calculate() { - return 2 + 2 - } +``` +namespace Utils { + function calculate() { + return 2 + 2 } +} +``` 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 explicitly specify the namespace's name for each access: - using Utils - calculate() +``` +using Utils +calculate() +``` The `using` keyword only has an effect for the current file and only for code that follows the keyword: - calculate() // This will not work. - using Utils +``` +calculate() // This will not work. +using Utils +``` 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: - 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. @@ -260,10 +288,12 @@ Sets an attribute to the specified value. Example: - { - a = 5 - a = 7 - } +``` +{ + a = 5 + a = 7 +} +``` 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: - { - a = [ "hello" ] - a += [ "world" ] - } +``` +{ + a = [ "hello" ] + a += [ "world" ] +} +``` is equivalent to: - { - a = [ "hello" ] - a = a + [ "world" ] - } +``` +{ + a = [ "hello" ] + a = a + [ "world" ] +} +``` ### Operator -= The -= operator is a shortcut. The following expression: - { - a = 10 - a -= 5 - } +``` +{ + a = 10 + a -= 5 +} +``` is equivalent to: - { - a = 10 - a = a - 5 - } +``` +{ + a = 10 + a = a - 5 +} +``` ### Operator \*= The *= operator is a shortcut. The following expression: - { - a = 60 - a *= 5 - } +``` +{ + a = 60 + a *= 5 +} +``` is equivalent to: - { - a = 60 - a = a * 5 - } +``` +{ + a = 60 + a = a * 5 +} +``` ### Operator /= The /= operator is a shortcut. The following expression: - { - a = 300 - a /= 5 - } +``` +{ + a = 300 + a /= 5 +} +``` is equivalent to: - { - a = 300 - a = a / 5 - } +``` +{ + a = 300 + a = a / 5 +} +``` ## Indexer @@ -337,23 +383,29 @@ The indexer syntax provides a convenient way to set dictionary elements. Example: - { - hello.key = "world" - } +``` +{ + hello.key = "world" +} +``` Example (alternative syntax): - { - hello["key"] = "world" - } +``` +{ + hello["key"] = "world" +} +``` This is equivalent to writing: - { - hello += { - key = "world" - } - } +``` +{ + hello += { + key = "world" + } +} +``` If the `hello` attribute does not already have a value, it is automatically initialized to an empty dictionary. @@ -363,22 +415,24 @@ Objects can import attributes from other objects. Example: - template Host "default-host" { - vars.colour = "red" - } +``` +template Host "default-host" { + vars.colour = "red" +} - template Host "test-host" { - import "default-host" +template Host "test-host" { + import "default-host" - vars.colour = "blue" - } + vars.colour = "blue" +} - object Host "localhost" { - import "test-host" +object Host "localhost" { + import "test-host" - address = "127.0.0.1" - address6 = "::1" - } + address = "127.0.0.1" + address6 = "::1" +} +``` The `default-host` and `test-host` objects are marked as templates 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 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 object definition is evaluated. @@ -408,7 +464,9 @@ is unspecified. 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 they are set. @@ -502,13 +560,15 @@ 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 another group of objects. - apply Service "ping" to Host { - import "generic-service" +``` +apply Service "ping" to Host { + import "generic-service" - check_command = "ping4" + check_command = "ping4" - assign where host.name == "localhost" - } + assign where host.name == "localhost" +} +``` 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" @@ -543,13 +603,14 @@ chapter. [Apply](17-language-reference.md#apply) rules can be extended with the [for loop](17-language-reference.md#for-loops) keyword. - apply Service "prefix-" for (key => value in host.vars.dictionary) to Host { - import "generic-service" - - check_command = "ping4" - vars.host_value = value - } +``` +apply Service "prefix-" for (key => value in host.vars.dictionary) to Host { + import "generic-service" + check_command = "ping4" + vars.host_value = value +} +``` 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 @@ -576,11 +637,13 @@ chapter. Group objects can be assigned to specific member objects using the `assign where` and `ignore where` conditions. - object HostGroup "linux-servers" { - display_name = "Linux Servers" +``` +object HostGroup "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 for all objects of the type `Host`. Each matching host is added as member to the host group @@ -622,13 +685,15 @@ The Icinga 2 configuration format supports C/C++-style and shell-style comments. Example: - /* - This is a comment. - */ - object Host "localhost" { - check_interval = 30 // this is also a comment. - retry_interval = 15 # yet another comment - } +``` +/* + This is a comment. + */ +object Host "localhost" { + check_interval = 30 // this is also a comment. + retry_interval = 15 # yet another comment +} +``` ## Includes @@ -638,15 +703,19 @@ Paths must be relative to the configuration file that contains the Example: - include "some/other/file.conf" - include "conf.d/*.conf" +``` +include "some/other/file.conf" +include "conf.d/*.conf" +``` Wildcard includes are not recursive. Icinga also supports include search paths similar to how they work in a C/C++ compiler: - include +``` +include +``` Note the use of angle brackets instead of double quotes. This causes the config compiler to search the include search paths for the specified @@ -663,8 +732,10 @@ files in a directory which match a certain pattern. Example: - include_recursive "conf.d", "*.conf" - include_recursive "templates" +``` +include_recursive "conf.d", "*.conf" +include_recursive "templates" +``` The first parameter specifies the directory from which files should be recursively included. @@ -682,8 +753,10 @@ in these subdirectories to the name of the subdirectory. Example: - include_zones "etc", "zones.d", "*.conf" - include_zones "puppet", "puppet-zones" +``` +include_zones "etc", "zones.d", "*.conf" +include_zones "puppet", "puppet-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 @@ -707,14 +780,18 @@ Functions can be defined using the `function` keyword. Example: - function multiply(a, b) { - return a * b - } +``` +function multiply(a, b) { + return a * b +} +``` When encountering the `return` keyword further execution of the function is terminated and 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). The function computes the product of those arguments and makes the result available to the @@ -726,16 +803,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 `multiply` function like this: - function multiply(a, b) { - a * b - } +``` +function multiply(a, b) { + a * b +} +``` Anonymous functions can be created by omitting the name in the function definition. The 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 @@ -743,20 +824,26 @@ Functions can also be declared using the alternative lambda syntax. Example: - f = (x) => x * x +``` +f = (x) => x * x +``` Multiple statements can be used by putting the function body into braces: - f = (x) => { - log("Lambda called") - x * x - } +``` +f = (x) => { + log("Lambda called") + x * x +} +``` 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: - f = x => x * x +``` +f = x => x * x +``` ## Abbreviated Lambda Syntax @@ -764,7 +851,9 @@ Lambdas which take no arguments can also be written using the abbreviated lambda Example: - f = {{ 3 }} +``` +f = {{ 3 }} +``` This creates a new function which returns the value 3. @@ -780,10 +869,12 @@ already exists there: 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: - function multiply(a, b) { - var temp = a * b - return temp - } +``` +function multiply(a, b) { + var temp = a * b + return temp +} +``` 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. @@ -794,40 +885,45 @@ the `this` scope is used. The `this` scope refers to the current object which the function or object/apply statement operates on. - object Host "localhost" { - check_interval = 5m - } +``` +object Host "localhost" { + check_interval = 5m +} +``` In this example the `this` scope refers to the "localhost" object. The `check_interval` attribute is set for this particular host. You can explicitly access the `this` scope using the `this` keyword: - object Host "localhost" { - var check_interval = 5m - - /* This explicitly specifies that the attribute should be set - * for the host, if we had omitted `this.` the (poorly named) - * local variable `check_interval` would have been modified instead. - */ - this.check_interval = 1m - } - +``` +object Host "localhost" { + var check_interval = 5m + + /* This explicitly specifies that the attribute should be set + * for the host, if we had omitted `this.` the (poorly named) + * local variable `check_interval` would have been modified instead. + */ + this.check_interval = 1m +} +``` 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 a function is set to whichever object was used to invoke the function. Here's an example: - hm = { - h_word = null +``` + hm = { + h_word = null - function init(word) { - h_word = word - } - } + function init(word) { + h_word = word + } + } - /* Let's invoke the init() function */ - hm.init("hello") + /* Let's invoke the init() function */ + hm.init("hello") +``` We're using `hm.init` to invoke the function which causes the value of `hm` to become the `this` scope for this function call. @@ -839,22 +935,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: - function MakeHelloFunction(name) { - return function() use(name) { - log("Hello, " + name) - } - } +``` +function MakeHelloFunction(name) { + return function() use(name) { + log("Hello, " + name) + } +} +``` In this case a new variable `name` is created inside the inner function's scope which has the value of the `name` function argument. Alternatively a different value for the inner variable can be specified: - function MakeHelloFunction(name) { - return function() use (greeting = "Hello, " + name) { - log(greeting) - } - } +``` +function MakeHelloFunction(name) { + return function() use (greeting = "Hello, " + name) { + log(greeting) + } +} +``` ## Conditional Statements @@ -863,26 +963,30 @@ construct can be used to accomplish this. Example: - a = 3 +``` +a = 3 - if (a < 5) { - a *= 7 - } else if (a > 10) { - a *= 5 - } else { - a *= 2 - } +if (a < 5) { + a *= 7 +} else if (a > 10) { + a *= 5 +} else { + a *= 2 +} +``` 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: - a = if (true) { - log("Taking the 'true' branch") - 7 * 3 - } else { - log("Taking the 'false' branch") - 9 - } +``` +a = if (true) { + log("Taking the 'true' branch") + 7 * 3 +} else { + log("Taking the 'false' branch") + 9 +} +``` This example prints the log message "Taking the 'true' branch" and the `a` variable is set to 21 (7 * 3). @@ -895,12 +999,14 @@ This is repeated until the condition is no longer true. Example: - var num = 5 +``` +var num = 5 - while (num > 5) { - log("Test") - num -= 1 - } +while (num > 5) { + log("Test") + num -= 1 +} +``` 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 @@ -912,22 +1018,26 @@ The `for` statement can be used to iterate over arrays and dictionaries. Example: - var list = [ "a", "b", "c" ] +``` +var list = [ "a", "b", "c" ] - for (var item in list) { - log("Item: " + item) - } +for (var item in list) { + log("Item: " + item) +} +``` 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. 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) { - log("Key: " + key + ", Value: " + value) - } +for (var key => var value in dict) { + log("Key: " + key + ", Value: " + value) +} +``` 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 @@ -942,15 +1052,19 @@ In order to create a new value of a specific type constructor calls may be used. Example: - var pd = PerfdataValue() - pd.label = "test" - pd.value = 10 +``` +var pd = PerfdataValue() +pd.label = "test" +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. Example: - var s = String(3) /* Sets s to "3". */ +``` +var s = String(3) /* Sets s to "3". */ +``` ## Throwing Exceptions @@ -959,7 +1073,9 @@ using the `throw` keyword. Example: - throw "An error occurred." +``` +throw "An error occurred." +``` ## Handling Exceptions @@ -968,13 +1084,15 @@ Exceptions can be handled using the `try` and `except` keywords. When an excepti Example: - try { - throw "Test" +``` +try { + throw "Test" - log("This statement won't get executed.") - } except { - log("An error occurred in the try clause.") - } + log("This statement won't get executed.") +} except { + log("An error occurred in the try clause.") +} +``` ## Breakpoints @@ -986,7 +1104,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: - 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: @@ -1005,14 +1125,18 @@ e.g. Host, Service, CheckCommand, etc. 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: - /* This logs 'true' */ - log(typeof(3) == Number) +``` +/* This logs 'true' */ +log(typeof(3) == Number) +``` The type object's `prototype` property can be used to find out which methods a certain type supports: - /* This returns: ["contains","find","len","lower","replace","reverse","split","substr","to_string","trim","upper"] */ - keys(String.prototype) +``` +/* This returns: ["contains","find","len","lower","replace","reverse","split","substr","to_string","trim","upper"] */ +keys(String.prototype) +``` Additional documentation on type methods is available in the [library reference](18-library-reference.md#library-reference). @@ -1024,77 +1148,84 @@ The location of the currently executing script can be obtained using the Example: - log("Hello from '" + current_filename + "' in line " + current_line) +``` +log("Hello from '" + current_filename + "' in line " + current_line) +``` ## Reserved Keywords These keywords are reserved and must not be used as constants or custom attributes. - object - template - include - include_recursive - include_zones - library - null - true - false - const - var - this - globals - locals - use - default - ignore_on_error - current_filename - current_line - apply - to - where - import - assign - ignore - function - return - break - continue - for - if - else - while - throw - try - except - in - using - namespace - +``` +object +template +include +include_recursive +include_zones +library +null +true +false +const +var +this +globals +locals +use +default +ignore_on_error +current_filename +current_line +apply +to +where +import +assign +ignore +function +return +break +continue +for +if +else +while +throw +try +except +in +using +namespace +``` You can escape reserved keywords using the `@` character. The following example tries to set `vars.include` which references a reserved keyword and generates an error: - [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(14): - /etc/icinga2/conf.d/hosts/localhost.conf(15): vars.include = "some cmdb export field" - ^^^^^^^ - /etc/icinga2/conf.d/hosts/localhost.conf(16): } - /etc/icinga2/conf.d/hosts/localhost.conf(17): +``` +[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(14): +/etc/icinga2/conf.d/hosts/localhost.conf(15): vars.include = "some cmdb export field" + ^^^^^^^ +/etc/icinga2/conf.d/hosts/localhost.conf(16): } +/etc/icinga2/conf.d/hosts/localhost.conf(17): - 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. +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. +``` You can escape the `include` keyword by prefixing it with an additional `@` character: - object Host "localhost" { - import "generic-host" +``` +object Host "localhost" { + import "generic-host" - address = "127.0.0.1" - address6 = "::1" + address = "127.0.0.1" + address6 = "::1" - vars.os = "Linux" - vars.sla = "24x7" + vars.os = "Linux" + vars.sla = "24x7" - vars.@include = "some cmdb export field" - } + vars.@include = "some cmdb export field" +} +``` \ No newline at end of file diff --git a/doc/18-library-reference.md b/doc/18-library-reference.md index 30277bfdf..897400c79 100644 --- a/doc/18-library-reference.md +++ b/doc/18-library-reference.md @@ -14,7 +14,9 @@ them in your scenarios. Signature: - function regex(pattern, value, mode) +``` +function regex(pattern, value, mode) +``` Returns true if the regular expression `pattern` matches the `value`, false otherwise. The `value` can be of the type [String](18-library-reference.md#string-type) or [Array](18-library-reference.md#array-type) (which @@ -28,32 +30,37 @@ The default mode is `MatchAll`. Example for string values: - $ icinga2 console - Icinga 2 (version: v2.7.0) - <1> => host.vars.os_type = "Linux/Unix" - null - <2> => regex("^Linux", host.vars.os_type) - true - <3> => regex("^Linux$", host.vars.os_type) - false +``` +$ icinga2 console +Icinga 2 (version: v2.7.0) +<1> => host.vars.os_type = "Linux/Unix" +null +<2> => regex("^Linux", host.vars.os_type) +true +<3> => regex("^Linux$", host.vars.os_type) +false +``` Example for an array of string values: - $ icinga2 console - Icinga 2 (version: v2.7.0) - <1> => host.vars.databases = [ "db-prod1", "db-prod2", "db-dev" ] - null - <2> => regex("^db-prod\\d+", host.vars.databases, MatchAny) - true - <3> => regex("^db-prod\\d+", host.vars.databases, MatchAll) - false - +``` +$ icinga2 console +Icinga 2 (version: v2.7.0) +<1> => host.vars.databases = [ "db-prod1", "db-prod2", "db-dev" ] +null +<2> => regex("^db-prod\\d+", host.vars.databases, MatchAny) +true +<3> => regex("^db-prod\\d+", host.vars.databases, MatchAll) +false +``` ### match Signature: - function match(pattern, text, mode) +``` +function match(pattern, text, mode) +``` Returns true if the wildcard (`?*`) `pattern` matches the `value`, false otherwise. The `value` can be of the type [String](18-library-reference.md#string-type) or [Array](18-library-reference.md#array-type) (which @@ -65,32 +72,37 @@ The default mode is `MatchAll`. Example for string values: - $ icinga2 console - Icinga 2 (version: v2.7.0) - <1> => var name = "db-prod-sfo-657" - null - <2> => match("*prod-sfo*", name) - true - <3> => match("*-dev-*", name) - false +``` +$ icinga2 console +Icinga 2 (version: v2.7.0) +<1> => var name = "db-prod-sfo-657" +null +<2> => match("*prod-sfo*", name) +true +<3> => match("*-dev-*", name) +false +``` Example for an array of string values: - $ icinga2 console - Icinga 2 (version: v2.7.0-28) - <1> => host.vars.application_types = [ "web-wp", "web-rt", "db-local" ] - null - <2> => match("web-*", host.vars.application_types, MatchAll) - false - <3> => match("web-*", host.vars.application_types, MatchAny) - true - +``` +$ icinga2 console +Icinga 2 (version: v2.7.0-28) +<1> => host.vars.application_types = [ "web-wp", "web-rt", "db-local" ] +null +<2> => match("web-*", host.vars.application_types, MatchAll) +false +<3> => match("web-*", host.vars.application_types, MatchAny) +true +``` ### cidr_match Signature: - function cidr_match(pattern, ip, mode) +``` +function cidr_match(pattern, ip, mode) +``` Returns true if the CIDR pattern matches the IP address, false otherwise. @@ -102,33 +114,39 @@ either `MatchAll` (in which case all elements for an array have to match) or `Ma Example for a single IP address: - $ icinga2 console - Icinga 2 (version: v2.7.0) - <1> => host.address = "192.168.56.101" - null - <2> => cidr_match("192.168.56.0/24", host.address) - true - <3> => cidr_match("192.168.56.0/26", host.address) - false +``` +$ icinga2 console +Icinga 2 (version: v2.7.0) +<1> => host.address = "192.168.56.101" +null +<2> => cidr_match("192.168.56.0/24", host.address) +true +<3> => cidr_match("192.168.56.0/26", host.address) +false +``` Example for an array of IP addresses: - $ icinga2 console - Icinga 2 (version: v2.7.0) - <1> => host.vars.vhost_ips = [ "192.168.56.101", "192.168.56.102", "10.0.10.99" ] - null - <2> => cidr_match("192.168.56.0/24", host.vars.vhost_ips, MatchAll) - false - <3> => cidr_match("192.168.56.0/24", host.vars.vhost_ips, MatchAny) - true +``` +$ icinga2 console +Icinga 2 (version: v2.7.0) +<1> => host.vars.vhost_ips = [ "192.168.56.101", "192.168.56.102", "10.0.10.99" ] +null +<2> => cidr_match("192.168.56.0/24", host.vars.vhost_ips, MatchAll) +false +<3> => cidr_match("192.168.56.0/24", host.vars.vhost_ips, MatchAny) +true +``` ### range Signature: - function range(end) - function range(start, end) - function range(start, end, increment) +``` +function range(end) +function range(start, end) +function range(start, end, increment) +``` Returns an array of numbers in the specified range. If you specify one parameter, the first element starts at `0`. @@ -142,20 +160,24 @@ as third parameter. Example: - $ icinga2 console - Icinga 2 (version: v2.7.0) - <1> => range(5) - [ 0.000000, 1.000000, 2.000000, 3.000000, 4.000000 ] - <2> => range(2,4) - [ 2.000000, 3.000000 ] - <3> => range(2,10,2) - [ 2.000000, 4.000000, 6.000000, 8.000000 ] +``` +$ icinga2 console +Icinga 2 (version: v2.7.0) +<1> => range(5) +[ 0.000000, 1.000000, 2.000000, 3.000000, 4.000000 ] +<2> => range(2,4) +[ 2.000000, 3.000000 ] +<3> => range(2,10,2) +[ 2.000000, 4.000000, 6.000000, 8.000000 ] +``` ### len Signature: - function len(value) +``` +function len(value) +``` Returns the length of the value, i.e. the number of elements for an array or dictionary, or the length of the string in bytes. @@ -166,68 +188,78 @@ prototype method: [Array#len](18-library-reference.md#array-len), [Dictionary#le Example: - $ icinga2 console - Icinga 2 (version: v2.7.0) - <1> => host.groups = [ "linux-servers", "db-servers" ] - null - <2> => host.groups.len() - 2.000000 - <3> => host.vars.disks["/"] = {} - null - <4> => host.vars.disks["/var"] = {} - null - <5> => host.vars.disks.len() - 2.000000 - <6> => host.vars.os_type = "Linux/Unix" - null - <7> => host.vars.os_type.len() - 10.000000 - +``` +$ icinga2 console +Icinga 2 (version: v2.7.0) +<1> => host.groups = [ "linux-servers", "db-servers" ] +null +<2> => host.groups.len() +2.000000 +<3> => host.vars.disks["/"] = {} +null +<4> => host.vars.disks["/var"] = {} +null +<5> => host.vars.disks.len() +2.000000 +<6> => host.vars.os_type = "Linux/Unix" +null +<7> => host.vars.os_type.len() +10.000000 +``` ### union Signature: - function union(array, array, ...) +``` +function union(array, array, ...) +``` Returns an array containing all unique elements from the specified arrays. Example: - - $ icinga2 console - Icinga 2 (version: v2.7.0) - <1> => var dev_notification_groups = [ "devs", "slack" ] - null - <2> => var host_notification_groups = [ "slack", "noc" ] - null - <3> => union(dev_notification_groups, host_notification_groups) - [ "devs", "noc", "slack" ] +``` +$ icinga2 console +Icinga 2 (version: v2.7.0) +<1> => var dev_notification_groups = [ "devs", "slack" ] +null +<2> => var host_notification_groups = [ "slack", "noc" ] +null +<3> => union(dev_notification_groups, host_notification_groups) +[ "devs", "noc", "slack" ] +``` ### intersection Signature: - function intersection(array, array, ...) +``` +function intersection(array, array, ...) +``` Returns an array containing all unique elements which are common to all specified arrays. Example: - $ icinga2 console - Icinga 2 (version: v2.7.0) - <1> => var dev_notification_groups = [ "devs", "slack" ] - null - <2> => var host_notification_groups = [ "slack", "noc" ] - null - <3> => intersection(dev_notification_groups, host_notification_groups) - [ "slack" ] +``` +$ icinga2 console +Icinga 2 (version: v2.7.0) +<1> => var dev_notification_groups = [ "devs", "slack" ] +null +<2> => var host_notification_groups = [ "slack", "noc" ] +null +<3> => intersection(dev_notification_groups, host_notification_groups) +[ "slack" ] +``` ### keys Signature: - function keys(dict) +``` +function keys(dict) +``` Returns an array containing the dictionary's keys. @@ -236,20 +268,24 @@ prototype method: [Dictionary#keys](18-library-reference.md#dictionary-keys). Example: - $ icinga2 console - Icinga 2 (version: v2.7.0) - <1> => host.vars.disks["/"] = {} - null - <2> => host.vars.disks["/var"] = {} - null - <3> => host.vars.disks.keys() - [ "/", "/var" ] +``` +$ icinga2 console +Icinga 2 (version: v2.7.0) +<1> => host.vars.disks["/"] = {} +null +<2> => host.vars.disks["/var"] = {} +null +<3> => host.vars.disks.keys() +[ "/", "/var" ] +``` ### string Signature: - function string(value) +``` +function string(value) +``` Converts the value to a string. @@ -264,81 +300,99 @@ prototype method: Example: - $ icinga2 console - Icinga 2 (version: v2.7.0) - <1> => 5.to_string() - "5" - <2> => false.to_string() - "false" - <3> => "abc".to_string() - "abc" - <4> => [ "dev", "slack" ].to_string() - "[ \"dev\", \"slack\" ]" - <5> => { "/" = {}, "/var" = {} }.to_string() - "{\n\t\"/\" = {\n\t}\n\t\"/var\" = {\n\t}\n}" - <6> => DateTime(2016, 11, 25).to_string() - "2016-11-25 00:00:00 +0100" +``` +$ icinga2 console +Icinga 2 (version: v2.7.0) +<1> => 5.to_string() +"5" +<2> => false.to_string() +"false" +<3> => "abc".to_string() +"abc" +<4> => [ "dev", "slack" ].to_string() +"[ \"dev\", \"slack\" ]" +<5> => { "/" = {}, "/var" = {} }.to_string() +"{\n\t\"/\" = {\n\t}\n\t\"/var\" = {\n\t}\n}" +<6> => DateTime(2016, 11, 25).to_string() +"2016-11-25 00:00:00 +0100" +``` ### number Signature: - function number(value) +``` +function number(value) +``` Converts the value to a number. Example: - $ icinga2 console - Icinga 2 (version: v2.7.0) - <1> => number(false) - 0.000000 - <2> => number("78") - 78.000000 +``` +$ icinga2 console +Icinga 2 (version: v2.7.0) +<1> => number(false) +0.000000 +<2> => number("78") +78.000000 +``` ### bool Signature: - function bool(value) +``` +function bool(value) +``` Converts the value to a bool. Example: - $ icinga2 console - Icinga 2 (version: v2.7.0) - <1> => bool(1) - true - <2> => bool(0) - false +``` +$ icinga2 console +Icinga 2 (version: v2.7.0) +<1> => bool(1) +true +<2> => bool(0) +false +``` ### random Signature: - function random() +``` +function random() +``` Returns a random value between 0 and RAND\_MAX (as defined in stdlib.h). - $ icinga2 console - Icinga 2 (version: v2.7.0) - <1> => random() - 1263171996.000000 - <2> => random() - 108402530.000000 +``` +$ icinga2 console +Icinga 2 (version: v2.7.0) +<1> => random() +1263171996.000000 +<2> => random() +108402530.000000 +``` ### log Signature: - function log(value) +``` +function log(value) +``` Writes a message to the log. Non-string values are converted to a JSON string. Signature: - function log(severity, facility, value) +``` +function log(severity, facility, value) +``` Writes a message to the log. `severity` can be one of `LogDebug`, `LogNotice`, `LogInformation`, `LogWarning`, and `LogCritical`. @@ -347,140 +401,168 @@ Non-string values are converted to a JSON string. Example: - $ icinga2 console - Icinga 2 (version: v2.7.0) - <1> => log(LogCritical, "Console", "First line") - critical/Console: First line - null - <2> => var groups = [ "devs", "slack" ] - null - <3> => log(LogCritical, "Console", groups) - critical/Console: ["devs","slack"] - null +``` +$ icinga2 console +Icinga 2 (version: v2.7.0) +<1> => log(LogCritical, "Console", "First line") +critical/Console: First line +null +<2> => var groups = [ "devs", "slack" ] +null +<3> => log(LogCritical, "Console", groups) +critical/Console: ["devs","slack"] +null +``` ### typeof Signature: - function typeof(value) +``` +function typeof(value) +``` Returns the [Type](18-library-reference.md#type-type) object for a value. Example: - $ icinga2 console - Icinga 2 (version: v2.7.0) - <1> => typeof(3) == Number - true - <2> => typeof("str") == String - true - <3> => typeof(true) == Boolean - true - <4> => typeof([ 1, 2, 3]) == Array - true - <5> => typeof({ a = 2, b = 3 }) == Dictionary - true +``` +$ icinga2 console +Icinga 2 (version: v2.7.0) +<1> => typeof(3) == Number +true +<2> => typeof("str") == String +true +<3> => typeof(true) == Boolean +true +<4> => typeof([ 1, 2, 3]) == Array +true +<5> => typeof({ a = 2, b = 3 }) == Dictionary +true +``` ### get_time Signature: - function get_time() +``` +function get_time() +``` Returns the current UNIX timestamp as floating point number. Example: - $ icinga2 console - Icinga 2 (version: v2.7.0) - <1> => get_time() - 1480072135.633008 - <2> => get_time() - 1480072140.401207 +``` +$ icinga2 console +Icinga 2 (version: v2.7.0) +<1> => get_time() +1480072135.633008 +<2> => get_time() +1480072140.401207 +``` ### parse_performance_data Signature: - function parse_performance_data(pd) +``` +function parse_performance_data(pd) +``` Parses a performance data string and returns an array describing the values. Example: - $ icinga2 console - Icinga 2 (version: v2.7.0) - <1> => var pd = "'time'=1480074205.197363;;;" - null - <2> => parse_performance_data(pd) - { - counter = false - crit = null - label = "time" - max = null - min = null - type = "PerfdataValue" - unit = "" - value = 1480074205.197363 - warn = null - } +``` +$ icinga2 console +Icinga 2 (version: v2.7.0) +<1> => var pd = "'time'=1480074205.197363;;;" +null +<2> => parse_performance_data(pd) +{ + counter = false + crit = null + label = "time" + max = null + min = null + type = "PerfdataValue" + unit = "" + value = 1480074205.197363 + warn = null +} +``` ### dirname Signature: - function dirname(path) +``` +function dirname(path) +``` Returns the directory portion of the specified path. Example: - $ icinga2 console - Icinga 2 (version: v2.7.0) - <1> => var path = "/etc/icinga2/scripts/xmpp-notification.pl" - null - <2> => dirname(path) - "/etc/icinga2/scripts" +``` +$ icinga2 console +Icinga 2 (version: v2.7.0) +<1> => var path = "/etc/icinga2/scripts/xmpp-notification.pl" +null +<2> => dirname(path) +"/etc/icinga2/scripts" +``` ### basename Signature: - function basename(path) +``` +function basename(path) +``` Returns the filename portion of the specified path. Example: - $ icinga2 console - Icinga 2 (version: v2.7.0) - <1> => var path = "/etc/icinga2/scripts/xmpp-notification.pl" - null - <2> => basename(path) - "xmpp-notification.pl" +``` +$ icinga2 console +Icinga 2 (version: v2.7.0) +<1> => var path = "/etc/icinga2/scripts/xmpp-notification.pl" +null +<2> => basename(path) +"xmpp-notification.pl" +``` ### path\_exists Signature: - function path_exists(path) +``` +function path_exists(path) +``` Returns true if the specified path exists, false otherwise. Example: - $ icinga2 console - Icinga 2 (version: v2.7.0) - <1> => var path = "/etc/icinga2/scripts/xmpp-notification.pl" - null - <2> => path_exists(path) - true +``` +$ icinga2 console +Icinga 2 (version: v2.7.0) +<1> => var path = "/etc/icinga2/scripts/xmpp-notification.pl" +null +<2> => path_exists(path) +true +``` ### glob Signature: - function glob(pathSpec, type) +``` +function glob(pathSpec, type) +``` Returns an array containing all paths which match the `pathSpec` argument. @@ -489,18 +571,22 @@ The `type` argument is optional and specifies which types of paths are matched. This can be a combination of the `GlobFile` and `GlobDirectory` constants. The default value is `GlobFile | GlobDirectory`. - $ icinga2 console - Icinga 2 (version: v2.7.0) - <1> => var pathSpec = "/etc/icinga2/conf.d/*.conf" - null - <2> => glob(pathSpec) - [ "/etc/icinga2/conf.d/app.conf", "/etc/icinga2/conf.d/commands.conf", ... ] +``` +$ icinga2 console +Icinga 2 (version: v2.7.0) +<1> => var pathSpec = "/etc/icinga2/conf.d/*.conf" +null +<2> => glob(pathSpec) +[ "/etc/icinga2/conf.d/app.conf", "/etc/icinga2/conf.d/commands.conf", ... ] +``` ### glob\_recursive Signature: - function glob_recursive(path, pattern, type) +``` +function glob_recursive(path, pattern, type) +``` Recursively descends into the specified directory and returns an array containing all paths which match the `pattern` argument. @@ -509,50 +595,62 @@ The `type` argument is optional and specifies which types of paths are matched. This can be a combination of the `GlobFile` and `GlobDirectory` constants. The default value is `GlobFile | GlobDirectory`. - $ icinga2 console - Icinga 2 (version: v2.7.0) - <1> => var path = "/etc/icinga2/zones.d/" - null - <2> => var pattern = "*.conf" - null - <3> => glob_recursive(path, pattern) - [ "/etc/icinga2/zones.d/global-templates/templates.conf", "/etc/icinga2/zones.d/master/hosts.conf", ... ] +``` +$ icinga2 console +Icinga 2 (version: v2.7.0) +<1> => var path = "/etc/icinga2/zones.d/" +null +<2> => var pattern = "*.conf" +null +<3> => glob_recursive(path, pattern) +[ "/etc/icinga2/zones.d/global-templates/templates.conf", "/etc/icinga2/zones.d/master/hosts.conf", ... ] +``` ### escape_shell_arg Signature: - function escape_shell_arg(text) +``` +function escape_shell_arg(text) +``` Escapes a string for use as a single shell argument. Example: - $ icinga2 console - Icinga 2 (version: v2.7.0) - <1> => escape_shell_arg("'$host.name$' '$service.name$'") - "''\\''$host.name$'\\'' '\\''$service.name$'\\'''" +``` +$ icinga2 console +Icinga 2 (version: v2.7.0) +<1> => escape_shell_arg("'$host.name$' '$service.name$'") +"''\\''$host.name$'\\'' '\\''$service.name$'\\'''" +``` ### escape_shell_cmd Signature: - function escape_shell_cmd(text) +``` +function escape_shell_cmd(text) +``` Escapes shell meta characters in a string. Example: - $ icinga2 console - Icinga 2 (version: v2.7.0) - <1> => escape_shell_cmd("/bin/echo 'shell test' $ENV") - "/bin/echo 'shell test' \\$ENV" +``` +$ icinga2 console +Icinga 2 (version: v2.7.0) +<1> => escape_shell_cmd("/bin/echo 'shell test' $ENV") +"/bin/echo 'shell test' \\$ENV" +``` ### escape_create_process_arg Signature: - function escape_create_process_arg(text) +``` +function escape_create_process_arg(text) +``` Escapes a string for use as an argument for CreateProcess(). Windows only. @@ -560,7 +658,9 @@ Escapes a string for use as an argument for CreateProcess(). Windows only. Signature: - function sleep(interval) +``` +function sleep(interval) +``` Sleeps for the specified amount of time (in seconds). @@ -614,7 +714,9 @@ These functions can be used to retrieve a reference to another object by name. Signature: - function get_check_command(name); +``` +function get_check_command(name); +``` Returns the CheckCommand object with the specified name, or `null` if no such CheckCommand object exists. @@ -622,7 +724,9 @@ Returns the CheckCommand object with the specified name, or `null` if no such Ch Signature: - function get_event_command(name); +``` +function get_event_command(name); +``` Returns the EventCommand object with the specified name, or `null` if no such EventCommand object exists. @@ -630,7 +734,9 @@ Returns the EventCommand object with the specified name, or `null` if no such Ev Signature: - function get_notification_command(name); +``` +function get_notification_command(name); +``` Returns the NotificationCommand object with the specified name, or `null` if no such NotificationCommand object exists. @@ -638,7 +744,9 @@ Returns the NotificationCommand object with the specified name, or `null` if no Signature: - function get_host(host_name); +``` +function get_host(host_name); +``` Returns the Host object with the specified name, or `null` if no such Host object exists. @@ -647,8 +755,10 @@ Returns the Host object with the specified name, or `null` if no such Host objec Signature: - function get_service(host_name, service_name); - function get_service(host, service_name); +``` +function get_service(host_name, service_name); +function get_service(host, service_name); +``` Returns the Service object with the specified host name or object and service name pair, or `null` if no such Service object exists. @@ -672,8 +782,10 @@ Icinga 2 (version: v2.7.0) Signature: - function get_services(host_name); - function get_services(host); +``` +function get_services(host_name); +function get_services(host); +``` Returns an [array](17-language-reference.md#array) of service objects for the specified host name or object, or `null` if no such host object exists. @@ -704,7 +816,9 @@ in using the [map](18-library-reference.md#array-map) functionality: Signature: - function get_user(name); +``` +function get_user(name); +``` Returns the User object with the specified name, or `null` if no such User object exists. @@ -712,7 +826,9 @@ Returns the User object with the specified name, or `null` if no such User objec Signature: - function get_host_group(name); +``` +function get_host_group(name); +``` Returns the HostGroup object with the specified name, or `null` if no such HostGroup object exists. @@ -721,7 +837,9 @@ Returns the HostGroup object with the specified name, or `null` if no such HostG Signature: - function get_service_group(name); +``` +function get_service_group(name); +``` Returns the ServiceGroup object with the specified name, or `null` if no such ServiceGroup object exists. @@ -729,7 +847,9 @@ Returns the ServiceGroup object with the specified name, or `null` if no such Se Signature: - function get_user_group(name); +``` +function get_user_group(name); +``` Returns the UserGroup object with the specified name, or `null` if no such UserGroup object exists. @@ -738,7 +858,9 @@ Returns the UserGroup object with the specified name, or `null` if no such UserG Signature: - function get_time_period(name); +``` +function get_time_period(name); +``` Returns the TimePeriod object with the specified name, or `null` if no such TimePeriod object exists. @@ -747,7 +869,9 @@ Returns the TimePeriod object with the specified name, or `null` if no such Time Signature: - function get_object(type, name); +``` +function get_object(type, name); +``` Returns the object with the specified type and name, or `null` if no such object exists. `type` must refer to a type object. @@ -757,7 +881,9 @@ to a type object. Signature: - function get_objects(type); +``` +function get_objects(type); +``` Returns an array of objects whose type matches the specified type. `type` must refer to a type object. @@ -800,7 +926,9 @@ Square root of 2. Signature: - function abs(x); +``` +function abs(x); +``` Returns the absolute value of `x`. @@ -808,7 +936,9 @@ Returns the absolute value of `x`. Signature: - function acos(x); +``` +function acos(x); +``` Returns the arccosine of `x`. @@ -816,7 +946,9 @@ Returns the arccosine of `x`. Signature: - function asin(x); +``` +function asin(x); +``` Returns the arcsine of `x`. @@ -824,7 +956,9 @@ Returns the arcsine of `x`. Signature: - function atan(x); +``` +function atan(x); +``` Returns the arctangent of `x`. @@ -832,15 +966,18 @@ Returns the arctangent of `x`. Signature: - function atan2(y, x); - +``` +function atan2(y, x); +``` Returns the arctangent of the quotient of `y` and `x`. ### Math.ceil Signature: - function ceil(x); +``` +function ceil(x); +``` Returns the smallest integer value not less than `x`. @@ -848,7 +985,9 @@ Returns the smallest integer value not less than `x`. Signature: - function cos(x); +``` +function cos(x); +``` Returns the cosine of `x`. @@ -856,7 +995,9 @@ Returns the cosine of `x`. Signature: - function exp(x); +``` +function exp(x); +``` Returns E raised to the `x`th power. @@ -864,7 +1005,9 @@ Returns E raised to the `x`th power. Signature: - function floor(x); +``` +function floor(x); +``` Returns the largest integer value not greater than `x`. @@ -872,7 +1015,9 @@ Returns the largest integer value not greater than `x`. Signature: - function isinf(x); +``` +function isinf(x); +``` Returns whether `x` is infinite. @@ -880,7 +1025,9 @@ Returns whether `x` is infinite. Signature: - function isnan(x); +``` +function isnan(x); +``` Returns whether `x` is NaN (not-a-number). @@ -888,7 +1035,9 @@ Returns whether `x` is NaN (not-a-number). Signature: - function log(x); +``` +function log(x); +``` Returns the natural logarithm of `x`. @@ -896,7 +1045,9 @@ Returns the natural logarithm of `x`. Signature: - function max(...); +``` +function max(...); +``` Returns the largest argument. A variable number of arguments can be specified. If no arguments are given, -Infinity is returned. @@ -905,7 +1056,9 @@ If no arguments are given, -Infinity is returned. Signature: - function min(...); +``` +function min(...); +``` Returns the smallest argument. A variable number of arguments can be specified. If no arguments are given, +Infinity is returned. @@ -914,7 +1067,9 @@ If no arguments are given, +Infinity is returned. Signature: - function pow(x, y); +``` +function pow(x, y); +``` Returns `x` raised to the `y`th power. @@ -922,7 +1077,9 @@ Returns `x` raised to the `y`th power. Signature: - function random(); +``` +function random(); +``` Returns a pseudo-random number between 0 and 1. @@ -930,7 +1087,9 @@ Returns a pseudo-random number between 0 and 1. Signature: - function round(x); +``` +function round(x); +``` Returns `x` rounded to the nearest integer value. @@ -938,7 +1097,9 @@ Returns `x` rounded to the nearest integer value. Signature: - function sign(x); +``` +function sign(x); +``` Returns -1 if `x` is negative, 1 if `x` is positive and 0 if `x` is 0. @@ -947,7 +1108,9 @@ and 0 if `x` is 0. Signature: - function sin(x); +``` +function sin(x); +``` Returns the sine of `x`. @@ -955,7 +1118,9 @@ Returns the sine of `x`. Signature: - function sqrt(x); +``` +function sqrt(x); +``` Returns the square root of `x`. @@ -963,7 +1128,9 @@ Returns the square root of `x`. Signature: - function tan(x); +``` +function tan(x); +``` Returns the tangent of `x`. @@ -975,7 +1142,9 @@ The global `Json` object can be used to encode and decode JSON. Signature: - function encode(x); +``` +function encode(x); +``` Encodes an arbitrary value into JSON. @@ -983,7 +1152,9 @@ Encodes an arbitrary value into JSON. Signature: - function decode(x); +``` +function decode(x); +``` Decodes a JSON string. @@ -993,14 +1164,18 @@ Decodes a JSON string. Signature: - function to_string(); +``` +function to_string(); +``` The `to_string` method returns a string representation of the number. Example: - var example = 7 +``` +var example = 7 example.to_string() /* Returns "7" */ +``` ## Boolean type @@ -1008,14 +1183,18 @@ Example: Signature: - function to_string(); +``` +function to_string(); +``` The `to_string` method returns a string representation of the boolean value. Example: - var example = true +``` +var example = true example.to_string() /* Returns "true" */ +``` ## String type @@ -1023,7 +1202,9 @@ Example: Signature: - function find(str, start); +``` +function find(str, start); +``` Returns the zero-based index at which the string `str` was found in the string. If the string was not found, -1 is returned. `start` specifies the zero-based index at which `find` should @@ -1031,13 +1212,17 @@ start looking for the string (defaults to 0 when not specified). Example: - "Hello World".find("World") /* Returns 6 */ +``` +"Hello World".find("World") /* Returns 6 */ +``` ### String#contains Signature: - function contains(str); +``` +function contains(str); +``` Returns `true` if the string `str` was found in the string. If the string was not found, `false` is returned. Use [find](18-library-reference.md#string-find) @@ -1045,50 +1230,66 @@ for getting the index instead. Example: - "Hello World".contains("World") /* Returns true */ +``` +"Hello World".contains("World") /* Returns true */ +``` ### String#len Signature - function len(); +``` +function len(); +``` Returns the length of the string in bytes. Note that depending on the encoding type of the string this is not necessarily the number of characters. Example: - "Hello World".len() /* Returns 11 */ +``` +"Hello World".len() /* Returns 11 */ +``` ### String#lower Signature: - function lower(); +``` +function lower(); +``` Returns a copy of the string with all of its characters converted to lower-case. Example: - "Hello World".lower() /* Returns "hello world" */ +``` +"Hello World".lower() /* Returns "hello world" */ +``` ### String#upper Signature: - function upper(); +``` +function upper(); +``` Returns a copy of the string with all of its characters converted to upper-case. Example: - "Hello World".upper() /* Returns "HELLO WORLD" */ +``` +"Hello World".upper() /* Returns "HELLO WORLD" */ +``` ### String#replace Signature: - function replace(search, replacement); +``` +function replace(search, replacement); +``` Returns a copy of the string with all occurences of the string specified in `search` replaced with the string specified in `replacement`. @@ -1097,33 +1298,43 @@ with the string specified in `replacement`. Signature: - function split(delimiters); +``` +function split(delimiters); +``` Splits a string into individual parts and returns them as an array. The `delimiters` argument specifies the characters which should be used as delimiters between parts. Example: - "x-7,y".split("-,") /* Returns [ "x", "7", "y" ] */ +``` +"x-7,y".split("-,") /* Returns [ "x", "7", "y" ] */ +``` ### String#substr Signature: - function substr(start, len); +``` +function substr(start, len); +``` Returns a part of a string. The `start` argument specifies the zero-based index at which the part begins. The optional `len` argument specifies the length of the part ("until the end of the string" if omitted). Example: - "Hello World".substr(6) /* Returns "World" */ +``` +"Hello World".substr(6) /* Returns "World" */ +``` ### String#to_string Signature: - function to_string(); +``` +function to_string(); +``` Returns a copy of the string. @@ -1131,7 +1342,9 @@ Returns a copy of the string. Signature: - function reverse(); +``` +function reverse(); +``` Returns a copy of the string in reverse order. @@ -1139,7 +1352,9 @@ Returns a copy of the string in reverse order. Signature: - function trim(); +``` +function trim(); +``` Removes trailing whitespaces and returns the string. @@ -1151,7 +1366,9 @@ This is the base type for all types in the Icinga application. Signature: - function clone(); +``` + function clone(); +``` Returns a copy of the object. Note that for object elements which are reference values (e.g. objects such as arrays or dictionaries) the entire @@ -1161,7 +1378,9 @@ object is recursively copied. Signature: - function to_string(); +``` +function to_string(); +``` Returns a string representation for the object. Unless overridden this returns a string of the format "Object of type ''" where is the name of the @@ -1169,19 +1388,23 @@ object's type. Example: - [ 3, true ].to_string() /* Returns "[ 3.000000, true ]" */ +``` +[ 3, true ].to_string() /* Returns "[ 3.000000, true ]" */ +``` ### Object#type Signature: - String type; +String type; Returns the object's type name. This attribute is read-only. Example: - get_host("localhost").type /* Returns "Host" */ +``` +get_host("localhost").type /* Returns "Host" */ +``` ## Type type @@ -1195,19 +1418,25 @@ All types are registered as global variables. For example, in order to obtain a Signature: - Type base; +``` +Type base; +``` Returns a reference to the type's base type. This attribute is read-only. Example: - Dictionary.base == Object /* Returns true, because the Dictionary type inherits directly from the Object type. */ +``` +Dictionary.base == Object /* Returns true, because the Dictionary type inherits directly from the Object type. */ +``` ### Type#name Signature: - String name; +``` +String name; +``` Returns the name of the type. @@ -1215,7 +1444,9 @@ Returns the name of the type. Signature: - Object prototype; +``` +Object prototype; +``` Returns the prototype object for the type. When an attribute is accessed on an object that doesn't exist the prototype object is checked to see if an attribute with the requested name exists. If it does, the attribute's value is returned. @@ -1223,7 +1454,9 @@ The prototype functionality is used to implement methods. Example: - 3.to_string() /* Even though '3' does not have a to_string property the Number type's prototype object does. */ +``` +3.to_string() /* Even though '3' does not have a to_string property the Number type's prototype object does. */ +``` ## Array type @@ -1233,7 +1466,9 @@ Inherits methods from the [Object type](18-library-reference.md#object-type). Signature: - function add(value); +``` +function add(value); +``` Adds a new value after the last element in the array. @@ -1241,13 +1476,17 @@ Adds a new value after the last element in the array. Signature: - function clear(); +``` +function clear(); +``` Removes all elements from the array. ### Array#shallow_clone - function shallow_clone(); +``` +function shallow_clone(); +``` Returns a copy of the array. Note that for elements which are reference values (e.g. objects such as arrays and dictionaries) only the references are copied. @@ -1256,7 +1495,9 @@ as arrays and dictionaries) only the references are copied. Signature: - function contains(value); +``` +function contains(value); +``` Returns true if the array contains the specified value, false otherwise. @@ -1264,7 +1505,9 @@ Returns true if the array contains the specified value, false otherwise. Signature: - function freeze() +``` +function freeze() +``` Disallows further modifications to this array. Trying to modify the array will result in an exception. @@ -1272,7 +1515,9 @@ Disallows further modifications to this array. Trying to modify the array will r Signature: - function len(); +``` +function len(); +``` Returns the number of elements contained in the array. @@ -1280,7 +1525,9 @@ Returns the number of elements contained in the array. Signature: - function remove(index); +``` +function remove(index); +``` Removes the element at the specified zero-based index. @@ -1288,7 +1535,9 @@ Removes the element at the specified zero-based index. Signature: - function set(index, value); +``` +function set(index, value); +``` Sets the element at the zero-based index to the specified value. The `index` must refer to an element which already exists in the array. @@ -1297,7 +1546,9 @@ which already exists in the array. Signature: - function get(index); +``` +function get(index); +``` Retrieves the element at the specified zero-based index. @@ -1305,7 +1556,9 @@ Retrieves the element at the specified zero-based index. Signature: - function sort(less_cmp); +``` +function sort(less_cmp); +``` Returns a copy of the array where all items are sorted. The items are compared using the `<` (less-than) operator. A custom comparator function @@ -1315,7 +1568,9 @@ can be specified with the `less_cmp` argument. Signature: - function join(separator); +``` +function join(separator); +``` Joins all elements of the array using the specified separator. @@ -1323,7 +1578,9 @@ Joins all elements of the array using the specified separator. Signature: - function reverse(); +``` +function reverse(); +``` Returns a new array with all elements of the current array in reverse order. @@ -1331,7 +1588,9 @@ Returns a new array with all elements of the current array in reverse order. Signature: - function map(func); +``` +function map(func); +``` Calls `func(element)` for each of the elements in the array and returns a new array containing the return values of these function calls. @@ -1340,7 +1599,9 @@ a new array containing the return values of these function calls. Signature: - function reduce(func); +``` +function reduce(func); +``` Reduces the elements of the array into a single value by calling the provided function `func` as `func(a, b)` repeatedly where `a` and `b` are elements of the array @@ -1350,7 +1611,9 @@ or results from previous function calls. Signature: - function filter(func); +``` +function filter(func); +``` Returns a copy of the array containing only the elements for which `func(element)` is true. @@ -1359,7 +1622,9 @@ is true. Signature: - function any(func); +``` +function any(func); +``` Returns true if the array contains at least one element for which `func(element)` is true, false otherwise. @@ -1368,7 +1633,9 @@ is true, false otherwise. Signature: - function all(func); +``` +function all(func); +``` Returns true if the array contains only elements for which `func(element)` is true, false otherwise. @@ -1377,7 +1644,9 @@ is true, false otherwise. Signature: - function unique(); +``` +function unique(); +``` Returns a copy of the array with all duplicate elements removed. The original order of the array is not preserved. @@ -1390,7 +1659,9 @@ Inherits methods from the [Object type](18-library-reference.md#object-type). Signature: - function shallow_clone(); +``` +function shallow_clone(); +``` Returns a copy of the dictionary. Note that for elements which are reference values (e.g. objects such as arrays and dictionaries) only the references are copied. @@ -1399,7 +1670,9 @@ as arrays and dictionaries) only the references are copied. Signature: - function contains(key); +``` +function contains(key); +``` Returns true if a dictionary item with the specified `key` exists, false otherwise. @@ -1407,7 +1680,9 @@ Returns true if a dictionary item with the specified `key` exists, false otherwi Signature: - function freeze() +``` +function freeze() +``` Disallows further modifications to this dictionary. Trying to modify the dictionary will result in an exception. @@ -1415,7 +1690,9 @@ Disallows further modifications to this dictionary. Trying to modify the diction Signature: - function len(); +``` +function len(); +``` Returns the number of items contained in the dictionary. @@ -1423,7 +1700,9 @@ Returns the number of items contained in the dictionary. Signature: - function remove(key); +``` +function remove(key); +``` Removes the item with the specified `key`. Trying to remove an item which does not exist is a no-op. @@ -1432,7 +1711,9 @@ is a no-op. Signature: - function clear(); +``` +function clear(); +``` Removes all items from the dictionary. @@ -1440,7 +1721,9 @@ Removes all items from the dictionary. Signature: - function set(key, value); +``` +function set(key, value); +``` Creates or updates an item with the specified `key` and `value`. @@ -1448,7 +1731,9 @@ Creates or updates an item with the specified `key` and `value`. Signature: - function get(key); +``` +function get(key); +``` Retrieves the value for the specified `key`. Returns `null` if they `key` does not exist in the dictionary. @@ -1457,7 +1742,9 @@ in the dictionary. Signature: - function keys(); +``` +function keys(); +``` Returns a list of keys for all items that are currently in the dictionary. @@ -1465,7 +1752,9 @@ Returns a list of keys for all items that are currently in the dictionary. Signature: - function values(); +``` +function values(); +``` Returns a list of values for all items that are currently in the dictionary. @@ -1477,41 +1766,49 @@ Inherits methods from the [Object type](18-library-reference.md#object-type). Signature: - function call(thisArg, ...); +``` +function call(thisArg, ...); +``` Invokes the function using an alternative `this` scope. The `thisArg` argument specifies the `this` scope for the function. All other arguments are passed directly to the function. Example: - function set_x(val) { - this.x = val - } +``` +function set_x(val) { + this.x = val +} - dict = {} +dict = {} - set_x.call(dict, 7) /* Invokes set_x using `dict` as `this` */ +set_x.call(dict, 7) /* Invokes set_x using `dict` as `this` */ +``` ### Function#callv Signature: - function callv(thisArg, args); +``` +function callv(thisArg, args); +``` Invokes the function using an alternative `this` scope. The `thisArg` argument specifies the `this` scope for the function. The items in the `args` array are passed to the function as individual arguments. Example: - function set_x(val) { - this.x = val - } +``` +function set_x(val) { + this.x = val +} - var dict = {} +var dict = {} - var args = [ 7 ] +var args = [ 7 ] - set_x.callv(dict, args) /* Invokes set_x using `dict` as `this` */ +set_x.callv(dict, args) /* Invokes set_x using `dict` as `this` */ +``` ## DateTime type @@ -1521,18 +1818,22 @@ Inherits methods from the [Object type](18-library-reference.md#object-type). Signature: - function DateTime() - function DateTime(unixTimestamp) - function DateTime(year, month, day) - function DateTime(year, month, day, hours, minutes, seconds) +``` +function DateTime() +function DateTime(unixTimestamp) +function DateTime(year, month, day) +function DateTime(year, month, day, hours, minutes, seconds) +``` Constructs a new DateTime object. When no arguments are specified for the constructor a new DateTime object representing the current time is created. Example: - var d1 = DateTime() /* current time */ - var d2 = DateTime(2016, 5, 21) /* midnight April 21st, 2016 (local time) */ +``` +var d1 = DateTime() /* current time */ +var d2 = DateTime(2016, 5, 21) /* midnight April 21st, 2016 (local time) */ +``` ### DateTime arithmetic @@ -1540,41 +1841,55 @@ Subtracting two DateTime objects yields the interval between them, in seconds. Example: - var delta = DateTime() - DateTime(2016, 5, 21) /* seconds since midnight April 21st, 2016 */ +``` +var delta = DateTime() - DateTime(2016, 5, 21) /* seconds since midnight April 21st, 2016 */ +``` Subtracting a number from a DateTime object yields a new DateTime object that is further in the past: Example: - var dt = DateTime() - 2 * 60 * 60 /* Current time minus 2 hours */ +``` +var dt = DateTime() - 2 * 60 * 60 /* Current time minus 2 hours */ +``` Adding a number to a DateTime object yields a new DateTime object that is in the future: Example: - var dt = DateTime() + 24 * 60 60 /* Current time plus 24 hours */ +``` +var dt = DateTime() + 24 * 60 60 /* Current time plus 24 hours */ +``` ### DateTime#format Signature: - function format(fmt) +``` +function format(fmt) +``` Returns a string representation for the DateTime object using the specified format string. The format string may contain format conversion placeholders as specified in strftime(3). Example: - var s = DateTime(2016, 4, 21).format("%A") /* Sets s to "Thursday". */ +``` +var s = DateTime(2016, 4, 21).format("%A") /* Sets s to "Thursday". */ +``` ### DateTime#to_string Signature: - function to_string() +``` +function to_string() +``` Returns a string representation for the DateTime object. Uses a suitable default format. Example: - var s = DateTime(2016, 4, 21).to_string() /* Sets s to "2016-04-21 00:00:00 +0200". */ +``` +var s = DateTime(2016, 4, 21).to_string() /* Sets s to "2016-04-21 00:00:00 +0200". */ +``` diff --git a/doc/20-script-debugger.md b/doc/20-script-debugger.md index 09a11e95f..711600c3b 100644 --- a/doc/20-script-debugger.md +++ b/doc/20-script-debugger.md @@ -3,7 +3,9 @@ You can run the Icinga 2 daemon with the `-X` (`--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) 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): - # icinga2 daemon -C -X +``` +# icinga2 daemon -C -X +``` Here is a list of common errors which can be diagnosed with the script debugger: @@ -24,48 +28,54 @@ 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 provides a string value: - object Host "script-debugger-host" { - check_command = "icinga" +``` +object Host "script-debugger-host" { + check_command = "icinga" - vars.http_vhosts["example.org"] = "192.168.1.100" // a string value - } + vars.http_vhosts["example.org"] = "192.168.1.100" // a string value +} - apply Service for (http_vhost => config in host.vars.http_vhosts) { - import "generic-service" +apply Service for (http_vhost => config in host.vars.http_vhosts) { + import "generic-service" - vars += config // expects a dictionary + vars += config // expects a dictionary - check_command = "http" - } + check_command = "http" +} +``` The error message on config validation will warn about the wrong value type, but does not provide any context which objects are affected. Enable the script debugger and run the config validation: - # icinga2 daemon -C -X - - Breakpoint encountered in /etc/icinga2/conf.d/services.conf: 59:67-65:1 - Exception: Error: Error while evaluating expression: Cannot convert value of type 'String' to an object. - Location: - /etc/icinga2/conf.d/services.conf(62): check_command = "http" - /etc/icinga2/conf.d/services.conf(63): - /etc/icinga2/conf.d/services.conf(64): vars += config - ^^^^^^^^^^^^^^ - /etc/icinga2/conf.d/services.conf(65): } - /etc/icinga2/conf.d/services.conf(66): - You can inspect expressions (such as variables) by entering them at the prompt. - To leave the debugger and continue the program use "$continue". - <1> => +``` +# icinga2 daemon -C -X + +Breakpoint encountered in /etc/icinga2/conf.d/services.conf: 59:67-65:1 +Exception: Error: Error while evaluating expression: Cannot convert value of type 'String' to an object. +Location: +/etc/icinga2/conf.d/services.conf(62): check_command = "http" +/etc/icinga2/conf.d/services.conf(63): +/etc/icinga2/conf.d/services.conf(64): vars += config + ^^^^^^^^^^^^^^ +/etc/icinga2/conf.d/services.conf(65): } +/etc/icinga2/conf.d/services.conf(66): +You can inspect expressions (such as variables) by entering them at the prompt. +To leave the debugger and continue the program use "$continue". +<1> => +``` You can print the variables `vars` and `config` to get an idea about their values: - <1> => vars - null - <2> => config - "192.168.1.100" - <3> => +``` +<1> => vars +null +<2> => config +"192.168.1.100" +<3> => +``` The `vars` attribute has to be a dictionary. Trying to set this attribute to a string caused 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 you can inspect attributes of the service object: - <3> => host_name - "script-debugger-host-01" - <4> => name - "http" +``` +<3> => host_name +"script-debugger-host-01" +<4> => name +"http" +``` Additionally you can view the service object attributes by printing the value of `this`. @@ -84,28 +96,31 @@ 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: - object Host "script-debugger-host-02" { - check_command = "dummy" - check_interval = 5s - - vars.dummy_text = {{ - var text = "Hello from " + macro("$name$") - debugger - return text - }} - } +``` +object Host "script-debugger-host-02" { + check_command = "dummy" + check_interval = 5s + + vars.dummy_text = {{ + var text = "Hello from " + macro("$name$") + debugger + return text + }} +} +``` Icinga 2 will spawn a debugger console every time the function is executed: - # icinga2 daemon -X - ... - Breakpoint encountered in /etc/icinga2/tests/script-debugger.conf: 7:5-7:12 - You can inspect expressions (such as variables) by entering them at the prompt. - To leave the debugger and continue the program use "$continue". - <1> => text - "Hello from script-debugger-host-02" - <2> => $continue - +``` +# icinga2 daemon -X +... +Breakpoint encountered in /etc/icinga2/tests/script-debugger.conf: 7:5-7:12 +You can inspect expressions (such as variables) by entering them at the prompt. +To leave the debugger and continue the program use "$continue". +<1> => text +"Hello from script-debugger-host-02" +<2> => $continue +``` ## Debugging API Filters diff --git a/doc/21-development.md b/doc/21-development.md index c5ea8e7cc..feccdd8a0 100644 --- a/doc/21-development.md +++ b/doc/21-development.md @@ -213,32 +213,34 @@ If you want to delete all breakpoints, use `d` and select `yes`. Breakpoint Example: - (gdb) b __cxa_throw - (gdb) r - (gdb) up - .... - (gdb) up - #11 0x00007ffff7cbf9ff in icinga::Utility::GlobRecursive(icinga::String const&, icinga::String const&, boost::function const&, int) (path=..., pattern=..., callback=..., type=1) - at /home/michi/coding/icinga/icinga2/lib/base/utility.cpp:609 - 609 callback(cpath); - (gdb) l - 604 - 605 #endif /* _WIN32 */ - 606 - 607 std::sort(files.begin(), files.end()); - 608 BOOST_FOREACH(const String& cpath, files) { - 609 callback(cpath); - 610 } - 611 - 612 std::sort(dirs.begin(), dirs.end()); - 613 BOOST_FOREACH(const String& cpath, dirs) { - (gdb) p files - $3 = std::vector of length 11, capacity 16 = {{static NPos = 18446744073709551615, m_Data = "/etc/icinga2/conf.d/agent.conf"}, {static NPos = 18446744073709551615, - m_Data = "/etc/icinga2/conf.d/commands.conf"}, {static NPos = 18446744073709551615, m_Data = "/etc/icinga2/conf.d/downtimes.conf"}, {static NPos = 18446744073709551615, - m_Data = "/etc/icinga2/conf.d/groups.conf"}, {static NPos = 18446744073709551615, m_Data = "/etc/icinga2/conf.d/notifications.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/timeperiods.conf"}, {static NPos = 18446744073709551615, m_Data = "/etc/icinga2/conf.d/users.conf"}} +``` +(gdb) b __cxa_throw +(gdb) r +(gdb) up +.... +(gdb) up +#11 0x00007ffff7cbf9ff in icinga::Utility::GlobRecursive(icinga::String const&, icinga::String const&, boost::function const&, int) (path=..., pattern=..., callback=..., type=1) + at /home/michi/coding/icinga/icinga2/lib/base/utility.cpp:609 +609 callback(cpath); +(gdb) l +604 +605 #endif /* _WIN32 */ +606 +607 std::sort(files.begin(), files.end()); +608 BOOST_FOREACH(const String& cpath, files) { +609 callback(cpath); +610 } +611 +612 std::sort(dirs.begin(), dirs.end()); +613 BOOST_FOREACH(const String& cpath, dirs) { +(gdb) p files +$3 = std::vector of length 11, capacity 16 = {{static NPos = 18446744073709551615, m_Data = "/etc/icinga2/conf.d/agent.conf"}, {static NPos = 18446744073709551615, + m_Data = "/etc/icinga2/conf.d/commands.conf"}, {static NPos = 18446744073709551615, m_Data = "/etc/icinga2/conf.d/downtimes.conf"}, {static NPos = 18446744073709551615, + m_Data = "/etc/icinga2/conf.d/groups.conf"}, {static NPos = 18446744073709551615, m_Data = "/etc/icinga2/conf.d/notifications.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/timeperiods.conf"}, {static NPos = 18446744073709551615, m_Data = "/etc/icinga2/conf.d/users.conf"}} +``` ### Core Dump @@ -1584,66 +1586,76 @@ Please check `appveyor.yml` for instructions. Install the `boost`, `python` and `icinga2` pretty printers. Absolute paths are required, 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: - $ git clone https://github.com/mateidavid/Boost-Pretty-Printer.git && cd Boost-Pretty-Printer - $ git checkout python-3 - $ pwd - /home/michi/.gdb_printers/Boost-Pretty-Printer +``` +$ git clone https://github.com/mateidavid/Boost-Pretty-Printer.git && cd Boost-Pretty-Printer +$ git checkout python-3 +$ pwd +/home/michi/.gdb_printers/Boost-Pretty-Printer +``` Python Pretty Printers: - $ cd ~/.gdb_printers - $ svn co svn://gcc.gnu.org/svn/gcc/trunk/libstdc++-v3/python +``` +$ cd ~/.gdb_printers +$ svn co svn://gcc.gnu.org/svn/gcc/trunk/libstdc++-v3/python +``` Icinga 2 Pretty Printers: - $ mkdir -p ~/.gdb_printers/icinga2 && cd ~/.gdb_printers/icinga2 - $ wget https://raw.githubusercontent.com/Icinga/icinga2/master/tools/debug/gdb/icingadbg.py +``` +$ mkdir -p ~/.gdb_printers/icinga2 && cd ~/.gdb_printers/icinga2 +$ wget https://raw.githubusercontent.com/Icinga/icinga2/master/tools/debug/gdb/icingadbg.py +``` Now you'll need to modify/setup your `~/.gdbinit` configuration file. You can download the one from Icinga 2 and modify all paths. Example on Fedora 22: - $ wget https://raw.githubusercontent.com/Icinga/icinga2/master/tools/debug/gdb/gdbinit -O ~/.gdbinit - $ vim ~/.gdbinit - - set print pretty on - - python - import sys - sys.path.insert(0, '/home/michi/.gdb_printers/icinga2') - from icingadbg import register_icinga_printers - register_icinga_printers() - end - - python - import sys - sys.path.insert(0, '/home/michi/.gdb_printers/python') - from libstdcxx.v6.printers import register_libstdcxx_printers - try: - register_libstdcxx_printers(None) - except: - pass - end - - python - import sys - sys.path.insert(0, '/home/michi/.gdb_printers/Boost-Pretty-Printer') - import boost_print - boost_print.register_printers() - end +``` +$ wget https://raw.githubusercontent.com/Icinga/icinga2/master/tools/debug/gdb/gdbinit -O ~/.gdbinit +$ vim ~/.gdbinit + +set print pretty on + +python +import sys +sys.path.insert(0, '/home/michi/.gdb_printers/icinga2') +from icingadbg import register_icinga_printers +register_icinga_printers() +end +python +import sys +sys.path.insert(0, '/home/michi/.gdb_printers/python') +from libstdcxx.v6.printers import register_libstdcxx_printers +try: + register_libstdcxx_printers(None) +except: + pass +end + +python +import sys +sys.path.insert(0, '/home/michi/.gdb_printers/Boost-Pretty-Printer') +import boost_print +boost_print.register_printers() +end +``` If you are getting the following error when running gdb, the `libstdcxx` printers are already preloaded in your environment and you can remove the duplicate import in your `~/.gdbinit` file. - RuntimeError: pretty-printer already registered: libstdc++-v6 - +``` +RuntimeError: pretty-printer already registered: libstdc++-v6 +``` ## Development Tests diff --git a/doc/22-selinux.md b/doc/22-selinux.md index 9801553cc..15f111a6e 100644 --- a/doc/22-selinux.md +++ b/doc/22-selinux.md @@ -18,16 +18,18 @@ 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. - # sestatus - SELinux status: enabled - SELinuxfs mount: /sys/fs/selinux - SELinux root directory: /etc/selinux - Loaded policy name: targeted - Current mode: enforcing - Mode from config file: enforcing - Policy MLS status: enabled - Policy deny_unknown status: allowed - Max kernel policy version: 28 +``` +# sestatus +SELinux status: enabled +SELinuxfs mount: /sys/fs/selinux +SELinux root directory: /etc/selinux +Loaded policy name: targeted +Current mode: enforcing +Mode from config file: enforcing +Policy MLS status: enabled +Policy deny_unknown status: allowed +Max kernel policy version: 28 +``` 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. - # 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: - # systemctl restart icinga2.service - # ps -eZ | grep icinga2 - system_u:system_r:icinga2_t:s0 2825 ? 00:00:00 icinga2 +``` +# systemctl restart icinga2.service +# ps -eZ | grep icinga2 +system_u:system_r:icinga2_t:s0 2825 ? 00:00:00 icinga2 +``` #### Manual installation @@ -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: - # yum install git selinux-policy-devel audit - # systemctl enable auditd.service - # systemctl start auditd.service +``` +# yum install git selinux-policy-devel audit +# systemctl enable auditd.service +# systemctl start auditd.service +``` 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.) - # cd tools/selinux/ - # ./icinga.sh +``` +# cd tools/selinux/ +# ./icinga.sh +``` After that restart Icinga 2 and verify it running in its own domain `icinga2_t`. - # systemctl restart icinga2.service - # ps -eZ | grep icinga2 - system_u:system_r:icinga2_t:s0 2825 ? 00:00:00 icinga2 +``` +# systemctl restart icinga2.service +# ps -eZ | grep icinga2 +system_u:system_r:icinga2_t:s0 2825 ? 00:00:00 icinga2 +``` ### General @@ -126,23 +140,29 @@ Make sure to report the bugs in the policy afterwards. 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 - # tar xvzf check_mysql_health-2.1.9.2.tar.gz - # cd check_mysql_health-2.1.9.2/ - # ./configure --libexecdir /usr/lib64/nagios/plugins - # make - # make install +``` +# 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 +# cd check_mysql_health-2.1.9.2/ +# ./configure --libexecdir /usr/lib64/nagios/plugins +# make +# make install +``` It is labeled `nagios_unconfined_plugins_exec_t` by default, so it runs without restrictions. - # 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 +``` +# 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 +``` 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 - # 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 +``` +# chcon -t nagios_services_plugin_exec_t /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 +``` The plugin still runs fine but if someone changes the script to do weird stuff it will fail to do so. @@ -152,25 +172,29 @@ 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. - # cat /etc/icinga2/features-enabled/graphite.conf - /** - * The GraphiteWriter type writes check result metrics and - * performance data to a graphite tcp socket. - */ +``` +# cat /etc/icinga2/features-enabled/graphite.conf +/** + * The GraphiteWriter type writes check result metrics and + * performance data to a graphite tcp socket. + */ - library "perfdata" +library "perfdata" - object GraphiteWriter "graphite" { - //host = "127.0.0.1" - //port = 2003 - port = 2004 - } - # icinga2 feature enable graphite +object GraphiteWriter "graphite" { + //host = "127.0.0.1" + //port = 2003 + port = 2004 +} +# 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). - # setsebool icinga2_can_connect_all true - # setsebool -P icinga2_can_connect_all true +``` +# setsebool icinga2_can_connect_all true +# setsebool -P icinga2_can_connect_all true +``` If you restart the daemon now it will successfully connect to graphite. @@ -181,49 +205,63 @@ this user. This is completly optional! 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. - # semanage login -a dirk -s staff_u - # echo "dirk ALL=(ALL) NOPASSWD: ALL" > /etc/sudoers.d/dirk +``` +# semanage login -a dirk -s staff_u +# echo "dirk ALL=(ALL) NOPASSWD: ALL" > /etc/sudoers.d/dirk +``` Login to the system using ssh and verify your id. - $ id -Z - staff_u:staff_r:staff_t:s0-s0:c0.c1023 +``` +$ id -Z +staff_u:staff_r:staff_t:s0-s0:c0.c1023 +``` Try to execute some commands as root using sudo. - $ sudo id -Z - staff_u:staff_r:staff_t:s0-s0:c0.c1023 - $ sudo vi /etc/icinga2/icinga2.conf - "/etc/icinga2/icinga2.conf" [Permission Denied] - $ sudo cat /var/log/icinga2/icinga2.log - cat: /var/log/icinga2/icinga2.log: Keine Berechtigung - $ sudo systemctl reload icinga2.service - Failed to get D-Bus connection: No connection to service manager. +``` +$ sudo id -Z +staff_u:staff_r:staff_t:s0-s0:c0.c1023 +$ sudo vi /etc/icinga2/icinga2.conf +"/etc/icinga2/icinga2.conf" [Permission Denied] +$ sudo cat /var/log/icinga2/icinga2.log +cat: /var/log/icinga2/icinga2.log: Keine Berechtigung +$ sudo systemctl reload icinga2.service +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. - $ sudo -r icinga2adm_r -t icinga2adm_t id -Z - staff_u:icinga2adm_r:icinga2adm_t:s0-s0:c0.c1023 - $ sudo -r icinga2adm_r -t icinga2adm_t vi /etc/icinga2/icinga2.conf - "/etc/icinga2/icinga2.conf" - $ 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' - $ sudo -r icinga2adm_r -t icinga2adm_t systemctl reload icinga2.service +``` +$ sudo -r icinga2adm_r -t icinga2adm_t id -Z +staff_u:icinga2adm_r:icinga2adm_t:s0-s0:c0.c1023 +$ sudo -r icinga2adm_r -t icinga2adm_t vi /etc/icinga2/icinga2.conf +"/etc/icinga2/icinga2.conf" +$ 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' +$ 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. - # 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. - $ sudo cat /var/log/httpd/error_log - /bin/cat: /var/log/httpd/error_log: Keine Berechtigung - $ sudo systemctl reload httpd.service - Failed to issue method call: Access denied +``` +$ sudo cat /var/log/httpd/error_log +/bin/cat: /var/log/httpd/error_log: Keine Berechtigung +$ sudo systemctl reload httpd.service +Failed to issue method call: Access denied +``` ## Bugreports diff --git a/doc/23-migrating-from-icinga-1x.md b/doc/23-migrating-from-icinga-1x.md index 4583b1606..8ae0aaa17 100644 --- a/doc/23-migrating-from-icinga-1x.md +++ b/doc/23-migrating-from-icinga-1x.md @@ -33,24 +33,28 @@ all existing Icinga 1.x `*_interval` attributes require an additional `m` durati Icinga 1.x: - define service { - service_description service1 - host_name localhost1 - check_command test_customvar - use generic-service - check_interval 5 - retry_interval 1 - } +``` +define service { + service_description service1 + host_name localhost1 + check_command test_customvar + use generic-service + check_interval 5 + retry_interval 1 +} +``` Icinga 2: - object Service "service1" { - import "generic-service" - host_name = "localhost1" - check_command = "test_customvar" - check_interval = 5m - retry_interval = 1m - } +``` +object Service "service1" { + import "generic-service" + host_name = "localhost1" + check_command = "test_customvar" + check_interval = 5m + retry_interval = 1m +} +``` #### Manual Config Migration Hints for Services @@ -59,70 +63,81 @@ belongs to, you can migrate this to the [apply rules](03-monitoring-basics.md#us Icinga 1.x: - define service { - service_description service1 - host_name localhost1,localhost2 - check_command test_check - use generic-service - } +``` +define service { + service_description service1 + host_name localhost1,localhost2 + check_command test_check + use generic-service +} +``` Icinga 2: - apply Service "service1" { - import "generic-service" - check_command = "test_check" +``` +apply Service "service1" { + import "generic-service" + 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 like the following example: - define service { - service_description servicewithhostgroups - hostgroup_name hostgroup1,hostgroup3 - check_command test_check - use generic-service - } +``` +define service { + service_description servicewithhostgroups + hostgroup_name hostgroup1,hostgroup3 + check_command test_check + use generic-service +} +``` Using Icinga 2 you can migrate this to the [apply rules](03-monitoring-basics.md#using-apply) syntax: - apply Service "servicewithhostgroups" { - import "generic-service" - check_command = "test_check" +``` +apply Service "servicewithhostgroups" { + import "generic-service" + check_command = "test_check" - assign where "hostgroup1" in host.groups - assign where "hostgroup3" in host.groups - } + assign where "hostgroup1" in host.groups + assign where "hostgroup3" in host.groups +} +``` #### Manual Config Migration Hints for Group Members 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. - define hostgroup { - hostgroup_name hg1 - members host1,host2 - } +``` +define hostgroup { + hostgroup_name hg1 + members host1,host2 +} - define hostgroup { - hostgroup_name hg2 - members host3 - hostgroup_members hg1 - } +define hostgroup { + hostgroup_name hg2 + members host3 + hostgroup_members hg1 +} +``` 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. +``` +object HostGroup "hg1" { + groups = [ "hg2" ] + assign where host.name in [ "host1", "host2" ] +} - object HostGroup "hg1" { - groups = [ "hg2" ] - assign where host.name in [ "host1", "host2" ] - } - - object HostGroup "hg2" { - assign where host.name == "host3" - } +object HostGroup "hg2" { + assign where host.name == "host3" +} +``` These assign rules can be applied for all groups: `HostGroup`, `ServiceGroup` and `UserGroup` (requires renaming from `contactgroup`). @@ -138,50 +153,54 @@ 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 are referenced as `$ARGn$` where `n` is the argument counter. - define command { - command_name my-ping - command_line $USER1$/check_ping -H $HOSTADDRESS$ -w $ARG1$ -c $ARG2$ -p 5 - } +``` +define command { + command_name my-ping + command_line $USER1$/check_ping -H $HOSTADDRESS$ -w $ARG1$ -c $ARG2$ -p 5 +} - define service { - use generic-service - host_name my-server - service_description my-ping - check_command my-ping-check!100.0,20%!500.0,60% - } +define service { + use generic-service + host_name my-server + service_description my-ping + 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!): - object CheckCommand "my-ping-check" { - command = [ - PluginDir + "/check_ping", "-4" - ] - - arguments = { - "-H" = "$ping_address$" - "-w" = "$ping_wrta$,$ping_wpl$%" - "-c" = "$ping_crta$,$ping_cpl$%" - "-p" = "$ping_packets$" - "-t" = "$ping_timeout$" - } - - vars.ping_address = "$address$" - vars.ping_wrta = 100 - vars.ping_wpl = 5 - vars.ping_crta = 200 - vars.ping_cpl = 15 - } - - object Service "my-ping" { - import "generic-service" - host_name = "my-server" - check_command = "my-ping-check" - - vars.ping_wrta = 100 - vars.ping_wpl = 20 - vars.ping_crta = 500 - vars.ping_cpl = 60 - } +``` +object CheckCommand "my-ping-check" { + command = [ + PluginDir + "/check_ping", "-4" + ] + + arguments = { + "-H" = "$ping_address$" + "-w" = "$ping_wrta$,$ping_wpl$%" + "-c" = "$ping_crta$,$ping_cpl$%" + "-p" = "$ping_packets$" + "-t" = "$ping_timeout$" + } + + vars.ping_address = "$address$" + vars.ping_wrta = 100 + vars.ping_wpl = 5 + vars.ping_crta = 200 + vars.ping_cpl = 15 +} + +object Service "my-ping" { + import "generic-service" + host_name = "my-server" + check_command = "my-ping-check" + + vars.ping_wrta = 100 + vars.ping_wpl = 20 + vars.ping_crta = 500 + vars.ping_cpl = 60 +} +``` #### Manual Config Migration Hints for Runtime Macros @@ -189,62 +208,73 @@ 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: - $SERVICEOUTPUT$ +``` +$SERVICEOUTPUT$ +``` In Icinga 2 you will need to write: - $service.output$ +``` +$service.output$ +``` 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): - $address$ - +``` +$address$ +``` #### Manual Config Migration Hints for Runtime Custom Attributes Custom variables from Icinga 1.x are available as Icinga 2 custom attributes. - define command { - command_name test_customvar - command_line echo "Host CV: $_HOSTCVTEST$ Service CV: $_SERVICECVTEST$\n" - } - - define host { - host_name localhost1 - check_command test_customvar - use generic-host - _CVTEST host cv value - } - - define service { - service_description service1 - host_name localhost1 - check_command test_customvar - use generic-service - _CVTEST service cv value - } +``` +define command { + command_name test_customvar + command_line echo "Host CV: $_HOSTCVTEST$ Service CV: $_SERVICECVTEST$\n" +} + +define host { + host_name localhost1 + check_command test_customvar + use generic-host + _CVTEST host cv value +} + +define service { + service_description service1 + host_name localhost1 + check_command test_customvar + use generic-service + _CVTEST service cv value +} +``` Can be written as the following in Icinga 2: - object CheckCommand "test_customvar" { - command = "echo "Host CV: $host.vars.CVTEST$ Service CV: $service.vars.CVTEST$\n"" - } +``` +object CheckCommand "test_customvar" { + command = "echo "Host CV: $host.vars.CVTEST$ Service CV: $service.vars.CVTEST$\n"" +} - object Host "localhost1" { - import "generic-host" - check_command = "test_customvar" - vars.CVTEST = "host cv value" - } +object Host "localhost1" { + import "generic-host" + check_command = "test_customvar" + vars.CVTEST = "host cv value" +} - object Service "service1" { - host_name = "localhost1" - check_command = "test_customvar" - vars.CVTEST = "service cv value" - } +object Service "service1" { + host_name = "localhost1" + check_command = "test_customvar" + vars.CVTEST = "service cv value" +} +``` 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` @@ -259,23 +289,27 @@ 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. This migration part is explained in the [next chapter](23-migrating-from-icinga-1x.md#manual-config-migration-hints-notifications). - define contact{ - contact_name testconfig-user - use generic-user - alias Icinga Test User - service_notification_options c,f,s,u - email icinga@localhost - } +``` +define contact{ + contact_name testconfig-user + use generic-user + alias Icinga Test User + service_notification_options c,f,s,u + email icinga@localhost +} +``` 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 renamed to `display_name`. - object User "testconfig-user" { - import "generic-user" - display_name = "Icinga Test User" - email = "icinga@localhost" - } +``` +object User "testconfig-user" { + import "generic-user" + display_name = "Icinga Test User" + email = "icinga@localhost" +} +``` This user can be put into usergroups (former contactgroups) or referenced in newly migration notification 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`). Assign it to the host or service and set the newly generated notification command name as `command` attribute. - object Notification "" { - import "mail-host-notification" - host_name = "" - command = "" - +``` +object Notification "" { + import "mail-host-notification" + host_name = "" + command = "" +``` 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. - states = [ OK, Warning, Critical ] - types = [ Recovery, Problem, Custom ] - period = "24x7" +``` + states = [ OK, Warning, Critical ] + types = [ Recovery, Problem, Custom ] + period = "24x7" +``` The current contact acts as `users` attribute. - users = [ "" ] - } +``` + users = [ "" ] +} +``` Do this in a loop for all notification commands (depending if host or service contact). Once done, dump the collected notification commands. @@ -374,53 +413,57 @@ 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 `cg_ops` contactgroup until 60 minutes (`10*6`) have passed. - define service { - service_description dep_svc01 - host_name dep_hostsvc01,dep_hostsvc03 - check_command test2 - use generic-service - notification_interval 10 - contact_groups cg_admin - } - - define hostgroup { - hostgroup_name hg_svcdep2 - members dep_hostsvc03 - } - - # with hostgroup_name and service_description - define serviceescalation { - hostgroup_name hg_svcdep2 - service_description dep_svc01 - first_notification 2 - last_notification 6 - contact_groups cg_ops - } +``` +define service { + service_description dep_svc01 + host_name dep_hostsvc01,dep_hostsvc03 + check_command test2 + use generic-service + notification_interval 10 + contact_groups cg_admin +} + +define hostgroup { + hostgroup_name hg_svcdep2 + members dep_hostsvc03 +} + +# with hostgroup_name and service_description +define serviceescalation { + hostgroup_name hg_svcdep2 + service_description dep_svc01 + first_notification 2 + last_notification 6 + contact_groups cg_ops +} +``` 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. - apply Service "dep_svc01" { - import "generic-service" +``` +apply Service "dep_svc01" { + import "generic-service" - check_command = "test2" + check_command = "test2" - assign where host.name == "dep_hostsvc01" - assign where host.name == "dep_hostsvc03" - } + assign where host.name == "dep_hostsvc01" + assign where host.name == "dep_hostsvc03" +} - object HostGroup "hg_svcdep2" { - assign where host.name == "dep_hostsvc03" - } +object HostGroup "hg_svcdep2" { + assign where host.name == "dep_hostsvc03" +} - apply Notification "email" to Service { - import "service-mail-notification" +apply Notification "email" to Service { + import "service-mail-notification" - interval = 10m - user_groups = [ "cg_admin" ] + interval = 10m + user_groups = [ "cg_admin" ] - 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: @@ -429,19 +472,21 @@ 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`. - apply Notification "email-escalation" to Service { - import "service-mail-notification" +``` +apply Notification "email-escalation" to Service { + import "service-mail-notification" - interval = 10m - user_groups = [ "cg_ops" ] + interval = 10m + user_groups = [ "cg_ops" ] - times = { - begin = 20m - end = 1h - } + times = { + begin = 20m + end = 1h + } - 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 just this service belonging to hosts in the matched hostgroup. @@ -469,41 +514,43 @@ 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 want to use the classic `Host-to-Host` and `Service-to-Service` dependency relationships. - define service { - service_description dep_svc01 - hostgroup_name hg_svcdep1 - check_command test2 - use generic-service - } - - define service { - service_description dep_svc02 - hostgroup_name hg_svcdep2 - check_command test2 - use generic-service - } - - define hostgroup { - hostgroup_name hg_svcdep2 - members host2 - } - - define host{ - use linux-server-template - host_name host1 - address 192.168.1.10 - } - - # with hostgroup_name and service_description - define servicedependency { - host_name host1 - dependent_hostgroup_name hg_svcdep2 - service_description dep_svc01 - dependent_service_description * - execution_failure_criteria u,c - notification_failure_criteria w,u,c - inherits_parent 1 - } +``` +define service { + service_description dep_svc01 + hostgroup_name hg_svcdep1 + check_command test2 + use generic-service +} + +define service { + service_description dep_svc02 + hostgroup_name hg_svcdep2 + check_command test2 + use generic-service +} + +define hostgroup { + hostgroup_name hg_svcdep2 + members host2 +} + +define host{ + use linux-server-template + host_name host1 + address 192.168.1.10 +} + +# with hostgroup_name and service_description +define servicedependency { + host_name host1 + dependent_hostgroup_name hg_svcdep2 + service_description dep_svc01 + dependent_service_description * + execution_failure_criteria u,c + notification_failure_criteria w,u,c + inherits_parent 1 +} +``` Map the dependency attributes accordingly. @@ -517,44 +564,48 @@ Map the dependency attributes accordingly. And migrate the host and services. - object Host "host1" { - import "linux-server-template" - address = "192.168.1.10" - } +``` +object Host "host1" { + import "linux-server-template" + address = "192.168.1.10" +} - object HostGroup "hg_svcdep2" { - assign where host.name == "host2" - } +object HostGroup "hg_svcdep2" { + assign where host.name == "host2" +} - apply Service "dep_svc01" { - import "generic-service" - check_command = "test2" +apply Service "dep_svc01" { + import "generic-service" + check_command = "test2" - assign where "hp_svcdep1" in host.groups - } + assign where "hp_svcdep1" in host.groups +} - apply Service "dep_svc02" { - import "generic-service" - check_command = "test2" +apply Service "dep_svc02" { + import "generic-service" + check_command = "test2" - 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, 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 enabled. - apply Dependency "all-svc-for-hg-hg_svcdep2-on-host1-dep_svc01" to Service { - parent_host_name = "host1" - parent_service_name = "dep_svc01" +``` +apply Dependency "all-svc-for-hg-hg_svcdep2-on-host1-dep_svc01" to Service { + parent_host_name = "host1" + parent_service_name = "dep_svc01" - states = [ Ok, Warning ] - disable_checks = true - disable_notifications = true + states = [ Ok, Warning ] + disable_checks = true + disable_notifications = true - 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). @@ -570,42 +621,46 @@ virtual machines `vmware-vm1` and `vmware-vm2`. 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. - define host{ - use linux-server-template - host_name vmware-master - hostgroups vmware - address 192.168.1.10 - } - - define host{ - use linux-server-template - host_name vmware-vm1 - hostgroups vmware - address 192.168.27.1 - parents vmware-master - } - - define host{ - use linux-server-template - host_name vmware-vm2 - hostgroups vmware - address 192.168.28.1 - parents vmware-master - } +``` +define host{ + use linux-server-template + host_name vmware-master + hostgroups vmware + address 192.168.1.10 +} + +define host{ + use linux-server-template + host_name vmware-vm1 + hostgroups vmware + address 192.168.27.1 + parents vmware-master +} + +define host{ + use linux-server-template + host_name vmware-vm2 + hostgroups vmware + address 192.168.28.1 + parents 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 below: - define hostdependency { - dependent_hostgroup_name vmware - dependent_host_name !vmware-master - host_name vmware-master - inherits_parent 1 - notification_failure_criteria d,u - execution_failure_criteria d,u - dependency_period testconfig-24x7 - } +``` +define hostdependency { + dependent_hostgroup_name vmware + dependent_host_name !vmware-master + host_name vmware-master + inherits_parent 1 + notification_failure_criteria d,u + execution_failure_criteria d,u + dependency_period testconfig-24x7 +} +``` When migrating to Icinga 2, the parents must be changed to a newly created host dependency. @@ -620,33 +675,34 @@ Map the following attributes The Icinga 2 configuration looks like this: - - object Host "vmware-master" { - import "linux-server-template" - groups += [ "vmware" ] - address = "192.168.1.10" - vars.is_vmware_master = true - } - - object Host "vmware-vm1" { - import "linux-server-template" - groups += [ "vmware" ] - address = "192.168.27.1" - } - - object Host "vmware-vm2" { - import "linux-server-template" - groups += [ "vmware" ] - address = "192.168.28.1" - } - - apply Dependency "vmware-master" to Host { - parent_host_name = "vmware-master" - - assign where "vmware" in host.groups - ignore where host.vars.is_vmware_master - ignore where host.name == "vmware-master" - } +``` +object Host "vmware-master" { + import "linux-server-template" + groups += [ "vmware" ] + address = "192.168.1.10" + vars.is_vmware_master = true +} + +object Host "vmware-vm1" { + import "linux-server-template" + groups += [ "vmware" ] + address = "192.168.27.1" +} + +object Host "vmware-vm2" { + import "linux-server-template" + groups += [ "vmware" ] + address = "192.168.28.1" +} + +apply Dependency "vmware-master" to Host { + parent_host_name = "vmware-master" + + assign where "vmware" in host.groups + ignore where host.vars.is_vmware_master + ignore where host.name == "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 @@ -655,29 +711,31 @@ to the Icinga 1.x example and a best practice hint only. Another way to express the same configuration would be something like: - object Host "vmware-master" { - import "linux-server-template" - groups += [ "vmware" ] - address = "192.168.1.10" - } - - object Host "vmware-vm1" { - import "linux-server-template" - groups += [ "vmware" ] - address = "192.168.27.1" - vars.parents = [ "vmware-master" ] - } - - object Host "vmware-vm2" { - import "linux-server-template" - groups += [ "vmware" ] - address = "192.168.28.1" - vars.parents = [ "vmware-master" ] - } - - apply Dependency "host-to-parent-" for (parent in host.vars.parents) to Host { - parent_host_name = parent - } +``` +object Host "vmware-master" { + import "linux-server-template" + groups += [ "vmware" ] + address = "192.168.1.10" +} + +object Host "vmware-vm1" { + import "linux-server-template" + groups += [ "vmware" ] + address = "192.168.27.1" + vars.parents = [ "vmware-master" ] +} + +object Host "vmware-vm2" { + import "linux-server-template" + groups += [ "vmware" ] + address = "192.168.28.1" + vars.parents = [ "vmware-master" ] +} + +apply Dependency "host-to-parent-" for (parent in host.vars.parents) to Host { + parent_host_name = parent +} +``` 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: - enable_notifications=1 +``` +enable_notifications=1 +``` objects.cfg: - define service { - notifications_enabled 0 - } +``` +define service { + notifications_enabled 0 +} +``` Icinga 2 supports objects and (global) variables, but does not make a difference between the main configuration file or any other included file. icinga2.conf: - const EnableNotifications = true +``` +const EnableNotifications = true - object Service "test" { - enable_notifications = false - } +object Service "test" { + enable_notifications = false +} +``` #### Sample Configuration and ITL @@ -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 configuration errors in Icinga 1.x. - cfg_file=/etc/icinga/objects/commands.cfg - cfg_dir=/etc/icinga/objects +``` +cfg_file=/etc/icinga/objects/commands.cfg +cfg_dir=/etc/icinga/objects +``` Icinga 2 supports wildcard includes and relative paths, e.g. for including `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 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 the Icinga Template Library (ITL) or additional monitoring plugins check command configuration. - include - include +``` +include +include +``` By convention the `.conf` suffix is used for Icinga 2 configuration files. @@ -796,13 +868,15 @@ 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 set in the `constants.conf` configuration file: - /** - * This file defines global constants which can be used in - * the other configuration files. At a minimum the - * PluginDir constant should be defined. - */ +``` +/** + * This file defines global constants which can be used in + * the other configuration files. At a minimum the + * PluginDir constant should be defined. + */ - 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 constant will result in an error. @@ -825,35 +899,41 @@ Icinga Web 2 for example). Object names are not specified using attributes (e.g. `service_description` for services) like in Icinga 1.x but directly after their type definition. - define service { - host_name localhost - service_description ping4 - } +``` +define service { + host_name localhost + service_description ping4 +} - object Service "ping4" { - host_name = "localhost" - } +object Service "ping4" { + host_name = "localhost" +} +``` ### Templates In Icinga 1.x templates are identified using the `register 0` setting. Icinga 2 uses the `template` identifier: - template Service "ping4-template" { } +``` +template Service "ping4-template" { } +``` Icinga 1.x objects inherit from templates using the `use` attribute. Icinga 2 uses the keyword `import` with template names in double quotes. - define service { - service_description testservice - use tmpl1,tmpl2,tmpl3 - } +``` +define service { + service_description testservice + use tmpl1,tmpl2,tmpl3 +} - object Service "testservice" { - import "tmpl1" - import "tmpl2" - import "tmpl3" - } +object Service "testservice" { + import "tmpl1" + import "tmpl2" + import "tmpl3" +} +``` The last template overrides previously set values. @@ -862,13 +942,15 @@ The last template overrides previously set values. Icinga 1.x separates attribute and value pairs with whitespaces/tabs. Icinga 2 requires an equal sign (=) between them. - define service { - check_interval 5 - } +``` +define service { + check_interval 5 +} - object Service "test" { - check_interval = 5m - } +object Service "test" { + check_interval = 5m +} +``` 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`. @@ -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 (`_`). 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.cv = "my custom cmdb description" +``` +vars.dn = "cn=icinga2-dev-host,ou=icinga,ou=main,ou=IcingaConfig,ou=LConf,dc=icinga,dc=org" +vars.cv = "my custom cmdb description" +``` These custom attributes are also used as [command parameters](03-monitoring-basics.md#command-passing-parameters). @@ -1110,47 +1194,49 @@ Changes to global statistic macros: The following external commands are not supported: - CHANGE_*MODATTR - CHANGE_CONTACT_HOST_NOTIFICATION_TIMEPERIOD - CHANGE_HOST_NOTIFICATION_TIMEPERIOD - CHANGE_SVC_NOTIFICATION_TIMEPERIOD - DEL_DOWNTIME_BY_HOSTGROUP_NAME - DEL_DOWNTIME_BY_START_TIME_COMMENT - DISABLE_ALL_NOTIFICATIONS_BEYOND_HOST - DISABLE_CONTACT_HOST_NOTIFICATIONS - DISABLE_CONTACT_SVC_NOTIFICATIONS - DISABLE_CONTACTGROUP_HOST_NOTIFICATIONS - DISABLE_CONTACTGROUP_SVC_NOTIFICATIONS - DISABLE_FAILURE_PREDICTION - DISABLE_HOST_AND_CHILD_NOTIFICATIONS - DISABLE_HOST_FRESHNESS_CHECKS - DISABLE_NOTIFICATIONS_EXPIRE_TIME - DISABLE_SERVICE_FRESHNESS_CHECKS - ENABLE_ALL_NOTIFICATIONS_BEYOND_HOST - ENABLE_CONTACT_HOST_NOTIFICATIONS - ENABLE_CONTACT_SVC_NOTIFICATIONS - ENABLE_CONTACTGROUP_HOST_NOTIFICATIONS - ENABLE_CONTACTGROUP_SVC_NOTIFICATIONS - ENABLE_FAILURE_PREDICTION - ENABLE_HOST_AND_CHILD_NOTIFICATIONS - ENABLE_HOST_FRESHNESS_CHECKS - ENABLE_SERVICE_FRESHNESS_CHECKS - READ_STATE_INFORMATION - SAVE_STATE_INFORMATION - SET_HOST_NOTIFICATION_NUMBER - SET_SVC_NOTIFICATION_NUMBER - START_ACCEPTING_PASSIVE_HOST_CHECKS - START_ACCEPTING_PASSIVE_SVC_CHECKS - START_OBSESSING_OVER_HOST - START_OBSESSING_OVER_HOST_CHECKS - START_OBSESSING_OVER_SVC - START_OBSESSING_OVER_SVC_CHECKS - STOP_ACCEPTING_PASSIVE_HOST_CHECKS - STOP_ACCEPTING_PASSIVE_SVC_CHECKS - STOP_OBSESSING_OVER_HOST - STOP_OBSESSING_OVER_HOST_CHECKS - STOP_OBSESSING_OVER_SVC - STOP_OBSESSING_OVER_SVC_CHECKS +``` +CHANGE_*MODATTR +CHANGE_CONTACT_HOST_NOTIFICATION_TIMEPERIOD +CHANGE_HOST_NOTIFICATION_TIMEPERIOD +CHANGE_SVC_NOTIFICATION_TIMEPERIOD +DEL_DOWNTIME_BY_HOSTGROUP_NAME +DEL_DOWNTIME_BY_START_TIME_COMMENT +DISABLE_ALL_NOTIFICATIONS_BEYOND_HOST +DISABLE_CONTACT_HOST_NOTIFICATIONS +DISABLE_CONTACT_SVC_NOTIFICATIONS +DISABLE_CONTACTGROUP_HOST_NOTIFICATIONS +DISABLE_CONTACTGROUP_SVC_NOTIFICATIONS +DISABLE_FAILURE_PREDICTION +DISABLE_HOST_AND_CHILD_NOTIFICATIONS +DISABLE_HOST_FRESHNESS_CHECKS +DISABLE_NOTIFICATIONS_EXPIRE_TIME +DISABLE_SERVICE_FRESHNESS_CHECKS +ENABLE_ALL_NOTIFICATIONS_BEYOND_HOST +ENABLE_CONTACT_HOST_NOTIFICATIONS +ENABLE_CONTACT_SVC_NOTIFICATIONS +ENABLE_CONTACTGROUP_HOST_NOTIFICATIONS +ENABLE_CONTACTGROUP_SVC_NOTIFICATIONS +ENABLE_FAILURE_PREDICTION +ENABLE_HOST_AND_CHILD_NOTIFICATIONS +ENABLE_HOST_FRESHNESS_CHECKS +ENABLE_SERVICE_FRESHNESS_CHECKS +READ_STATE_INFORMATION +SAVE_STATE_INFORMATION +SET_HOST_NOTIFICATION_NUMBER +SET_SVC_NOTIFICATION_NUMBER +START_ACCEPTING_PASSIVE_HOST_CHECKS +START_ACCEPTING_PASSIVE_SVC_CHECKS +START_OBSESSING_OVER_HOST +START_OBSESSING_OVER_HOST_CHECKS +START_OBSESSING_OVER_SVC +START_OBSESSING_OVER_SVC_CHECKS +STOP_ACCEPTING_PASSIVE_HOST_CHECKS +STOP_ACCEPTING_PASSIVE_SVC_CHECKS +STOP_OBSESSING_OVER_HOST +STOP_OBSESSING_OVER_HOST_CHECKS +STOP_OBSESSING_OVER_SVC +STOP_OBSESSING_OVER_SVC_CHECKS +``` ### Asynchronous Event Execution @@ -1222,27 +1308,31 @@ 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` expressions by using [group assign](03-monitoring-basics.md#group-assign-intro). - object Host "web-dev" { - import "generic-host" - } +``` +object Host "web-dev" { + import "generic-host" +} - object HostGroup "dev-hosts" { - display_name = "Dev Hosts" - assign where match("*-dev", host.name) - } +object HostGroup "dev-hosts" { + display_name = "Dev Hosts" + assign where match("*-dev", host.name) +} +``` #### Add Service to Hostgroup where Host is Member 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: - apply Service "ping4" { - import "generic-service" +``` +apply Service "ping4" { + import "generic-service" - check_command = "ping4" + check_command = "ping4" - assign where "dev-hosts" in host.groups - } + assign where "dev-hosts" in host.groups +} +``` ### Notifications @@ -1282,12 +1372,16 @@ Icinga 2 attempts to solve that problem in this way 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: - Service -> Notification -> NotificationCommand - -> User, UserGroup +``` +Service -> Notification -> NotificationCommand + -> User, UserGroup +``` #### Escalations @@ -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 calculated from the notification_interval: - start = notification start + (notification_interval * first_notification) - end = notification start + (notification_interval * last_notification) +``` +start = notification start + (notification_interval * first_notification) +end = notification start + (notification_interval * last_notification) +``` In theory first_notification and last_notification can be set to readable 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. 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 ] - types = [ Problem, Recovery, FlappingStart, FlappingEnd, DowntimeStart, DowntimeEnd, DowntimeRemoved ] +states = [ Warning, Unknown, Critical ] +types = [ Problem, Recovery, FlappingStart, FlappingEnd, DowntimeStart, DowntimeEnd, DowntimeRemoved ] +``` Icinga 2 adds more fine-grained type filters for acknowledgements, downtime, 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 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.