]> granicus.if.org Git - icinga2/blob - doc/12-icinga2-api.md
Fix heading level in development chapter
[icinga2] / doc / 12-icinga2-api.md
1 # Icinga 2 API <a id="icinga2-api"></a>
2
3 ## Setting up the API <a id="icinga2-api-setup"></a>
4
5 You can run the CLI command `icinga2 api setup` to enable the
6 `api` [feature](11-cli-commands.md#enable-features) and set up
7 certificates as well as a new API user `root` with an auto-generated password in the
8 `/etc/icinga2/conf.d/api-users.conf` configuration file:
9
10     # icinga2 api setup
11
12 Make sure to restart Icinga 2 to enable the changes you just made:
13
14     # service icinga2 restart
15
16 If you prefer to set up the API manually, you will have to perform the following steps:
17
18 * Set up X.509 certificates for Icinga 2
19 * Enable the `api` feature (`icinga2 feature enable api`)
20 * Create an `ApiUser` object for authentication
21
22 The next chapter provides a quick overview of how you can use the API.
23
24 ## Introduction <a id="icinga2-api-introduction"></a>
25
26 The Icinga 2 API allows you to manage configuration objects
27 and resources in a simple, programmatic way using HTTP requests.
28
29 The URL endpoints are logically separated allowing you to easily
30 make calls to
31
32 * query, create, modify and delete [config objects](12-icinga2-api.md#icinga2-api-config-objects)
33 * perform [actions](12-icinga2-api.md#icinga2-api-actions) (reschedule checks, etc.)
34 * subscribe to [event streams](12-icinga2-api.md#icinga2-api-event-streams)
35 * [manage configuration packages](12-icinga2-api.md#icinga2-api-config-management)
36 * evaluate [script expressions](12-icinga2-api.md#icinga2-api-console)
37
38 ### Requests <a id="icinga2-api-requests"></a>
39
40 Any tool capable of making HTTP requests can communicate with
41 the API, for example [curl](https://curl.haxx.se/).
42
43 Requests are only allowed to use the HTTPS protocol so that
44 traffic remains encrypted.
45
46 By default the Icinga 2 API listens on port `5665` which is shared with
47 the cluster stack. The port can be changed by setting the `bind_port` attribute
48 for the [ApiListener](09-object-types.md#objecttype-apilistener)
49 object in the `/etc/icinga2/features-available/api.conf`
50 configuration file.
51
52 Supported request methods:
53
54   Method | Usage
55   -------|--------
56   GET    | Retrieve information about configuration objects. Any request using the GET method is read-only and does not affect any objects.
57   POST   | Update attributes of a specified configuration object.
58   PUT    | Create a new object. The PUT request must include all attributes required to create a new object.
59   DELETE | Remove an object created by the API. The DELETE method is idempotent and does not require any check if the object actually exists.
60
61 All requests apart from `GET` require that the following `Accept` header is set:
62
63     Accept: application/json
64
65 Each URL is prefixed with the API version (currently "/v1").
66
67 HTTP header size is limited to 8KB.
68
69 ### Responses <a id="icinga2-api-responses"></a>
70
71 Successful requests will send back a response body containing a `results`
72 list. Depending on the number of affected objects in your request, the
73 `results` list may contain more than one entry.
74
75 The output will be sent back as a JSON object:
76
77
78     {
79         "results": [
80             {
81                 "code": 200.0,
82                 "status": "Object was created."
83             }
84         ]
85     }
86
87 > **Tip**
88 >
89 > You can use the [pretty](12-icinga2-api.md#icinga2-api-parameters-global) parameter to beautify the JSON response with Icinga v2.9+.
90
91 You can also use [jq](https://stedolan.github.io/jq/) or `python -m json.tool`
92 in combination with curl on the CLI.
93
94 ```
95 curl ... | python -m json.tool
96 ```
97
98 > **Note**
99 >
100 > Future versions of Icinga 2 might set additional fields. Your application
101 > should gracefully handle fields it is not familiar with, for example by
102 > ignoring them.
103
104 ### HTTP Statuses <a id="icinga2-api-http-statuses"></a>
105
106 The API will return standard [HTTP statuses](https://www.ietf.org/rfc/rfc2616.txt)
107 including error codes.
108
109 When an error occurs, the response body will contain additional information
110 about the problem and its source. Set `verbose` to true to retrieve more
111 insights into what may be causing the error.
112
113 A status code between 200 and 299 generally means that the request was
114 successful.
115
116 Return codes within the 400 range indicate that there was a problem with the
117 request. Either you did not authenticate correctly, you are missing the authorization
118 for your requested action, the requested object does not exist or the request
119 was malformed.
120
121 A status in the range of 500 generally means that there was a server-side problem
122 and Icinga 2 is unable to process your request.
123
124 ### Authentication <a id="icinga2-api-authentication"></a>
125
126 There are two different ways for authenticating against the Icinga 2 API:
127
128 * username and password using HTTP basic auth
129 * X.509 certificate
130
131 In order to configure a new API user you'll need to add a new [ApiUser](09-object-types.md#objecttype-apiuser)
132 configuration object. In this example `root` will be the basic auth username
133 and the `password` attribute contains the basic auth password.
134
135     # vim /etc/icinga2/conf.d/api-users.conf
136
137     object ApiUser "root" {
138       password = "icinga"
139     }
140
141 Alternatively you can use X.509 client certificates by specifying the `client_cn`
142 the API should trust. The X.509 certificate has to be signed by the CA certificate
143 that is configured in the [ApiListener](09-object-types.md#objecttype-apilistener) object.
144
145     # vim /etc/icinga2/conf.d/api-users.conf
146
147     object ApiUser "root" {
148       client_cn = "CertificateCommonName"
149     }
150
151 An `ApiUser` object can have both authentication methods configured.
152
153 You can test authentication by sending a GET request to the API:
154
155     $ curl -k -s -u root:icinga 'https://localhost:5665/v1'
156
157 In case you get an error message make sure to check the API user credentials.
158
159 When using client certificates for authentication you'll need to pass your client certificate
160 and private key to the curl call:
161
162     $ curl -k --cert example.localdomain.crt --key example.localdomain.key 'https://example.localdomain:5665/v1/status'
163
164 In case of an error make sure to verify the client certificate and CA.
165
166 The curl parameter `-k` disables certificate verification and should therefore
167 only be used for testing. In order to securely check each connection you'll need to
168 specify the trusted CA certificate using the curl parameter`--cacert`:
169
170     $ curl -u root:icinga --cacert ca.crt 'icinga2.node1.localdomain:5665/v1'
171
172 Read the next chapter on [API permissions](12-icinga2-api.md#icinga2-api-permissions)
173 in order to configure authorization settings for your newly created API user.
174
175 ### Permissions <a id="icinga2-api-permissions"></a>
176
177 By default an API user does not have any permissions to perform
178 actions on the URL endpoints.
179
180 Permissions for API users must be specified in the `permissions` attribute
181 as array. The array items can be a list of permission strings with wildcard
182 matches. Please notice, that the permission system that is used by the API differs from the permission system used by the Icinga Web 2 frontend or other parts of Icinga 2.
183
184 The permission system mainly relies on the url scheme of the API endpoints (See listing below).
185
186 Example for an API user with all permissions:
187
188     permissions = [ "*" ]
189
190 Note that you can use wildcards to include all possible hierarchically lower items. Here's another example that only allows the user
191 to perform read-only object queries for hosts and services:
192
193     permissions = [ "objects/query/Host", "objects/query/Service" ]
194
195 You can also further restrict permissions by specifying a filter expression. The
196 filter expression has to be a [lambda function](17-language-reference.md#nullary-lambdas)
197 which must return a boolean value.
198
199 The following example allows the API user to query all hosts and services which have a
200 custom attribute `os` that matches the regular expression `^Linux`.
201 The [regex function](18-library-reference.md#global-functions-regex) is available as global function.
202
203     permissions = [
204       {
205         permission = "objects/query/Host"
206         filter = {{ regex("^Linux", host.vars.os) }}
207       },
208       {
209         permission = "objects/query/Service"
210         filter = {{ regex("^Linux", service.vars.os) }}
211       }
212     ]
213
214 More information about filters can be found in the [filters](12-icinga2-api.md#icinga2-api-filters) chapter.
215
216 Permissions are tied to a maximum HTTP request size to prevent abuse, responses sent by Icinga are not limited.
217 An API user with all permissions ("\*") may send up to 512 MB regardless of the endpoint.
218
219 Available permissions for specific URL endpoints:
220
221   Permissions                   | URL Endpoint  | Supports filters  | Max body size in MB
222   ------------------------------|---------------|-------------------|---------------------
223   actions/&lt;action&gt;        | /v1/actions   | Yes               | 1
224   config/query                  | /v1/config    | No                | 1
225   config/modify                 | /v1/config    | No                | 512
226   console                       | /v1/console   | No                | 1
227   events/&lt;type&gt;           | /v1/events    | No                | 1
228   objects/query/&lt;type&gt;    | /v1/objects   | Yes               | 1
229   objects/create/&lt;type&gt;   | /v1/objects   | No                | 1
230   objects/modify/&lt;type&gt;   | /v1/objects   | Yes               | 1
231   objects/delete/&lt;type&gt;   | /v1/objects   | Yes               | 1
232   status/query                  | /v1/status    | Yes               | 1
233   templates/&lt;type&gt;        | /v1/templates | Yes               | 1
234   types                         | /v1/types     | Yes               | 1
235   variables                     | /v1/variables | Yes               | 1
236
237 The required actions or types can be replaced by using a wildcard match ("\*").
238
239 ### Parameters <a id="icinga2-api-parameters"></a>
240
241 Depending on the request method there are two ways of passing parameters to the request:
242
243 * JSON object as request body (all request methods other than `GET`)
244 * Query string as URL parameter (all request methods)
245
246 Reserved characters by the HTTP protocol must be [URL-encoded](https://en.wikipedia.org/wiki/Percent-encoding)
247 as query string, e.g. a space character becomes `%20`.
248
249 Example for a URL-encoded query string:
250
251     /v1/objects/hosts?filter=match(%22example.localdomain*%22,host.name)&attrs=name&attrs=state
252
253 Here are the exact same query parameters as a JSON object:
254
255     { "filter": "match(\"example.localdomain*\",host.name)", "attrs": [ "host.name", "host.state" ] }
256
257 The [match function](18-library-reference.md#global-functions-match) is available as global function
258 in Icinga 2.
259
260 ### Global Parameters <a id="icinga2-api-parameters-global"></a>
261
262 Name            | Description
263 ----------------|--------------------
264 pretty          | Pretty-print the JSON response.
265 verbose         | Add verbose debug information inside the `diagnostic_information` key into the response if available. This helps with troubleshooting failing requests.
266
267 Example as URL parameter:
268
269 ```
270 /v1/objects/hosts?pretty=1
271 ```
272
273 Example as JSON object:
274
275 ```
276 { "pretty": true }
277 ```
278
279 Both parameters have been added in Icinga 2 v2.9.
280
281 ### Request Method Override <a id="icinga2-api-requests-method-override"></a>
282
283 `GET` requests do not allow you to send a request body. In case you cannot pass everything as URL
284 parameters (e.g. complex filters or JSON-encoded dictionaries) you can use the `X-HTTP-Method-Override`
285 header. This comes in handy when you are using HTTP proxies disallowing `PUT` or `DELETE` requests too.
286
287 Query an existing object by sending a `POST` request with `X-HTTP-Method-Override: GET` as request header:
288
289     $ curl -k -s -u 'root:icinga' -H 'Accept: application/json' -X POST -H 'X-HTTP-Method-Override: GET' 'https://localhost:5665/v1/objects/hosts'
290
291 Delete an existing object by sending a `POST` request with `X-HTTP-Method-Override: DELETE` as request header:
292
293     $ 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'
294
295 ### Filters <a id="icinga2-api-filters"></a>
296
297 #### Simple Filters <a id="icinga2-api-simple-filters"></a>
298
299 By default actions and queries operate on all objects unless further restricted by the user. For
300 example, the following query returns all `Host` objects:
301
302     https://localhost:5665/v1/objects/hosts
303
304 If you're only interested in a single object, you can limit the output to that object by specifying its name:
305
306     https://localhost:5665/v1/objects/hosts?host=localhost
307
308 **The name of the URL parameter is the lower-case version of the type the query applies to.** For
309 example, for `Host` objects the URL parameter therefore is `host`, for `Service` objects it is
310 `service` and so on.
311
312 You can also specify multiple objects:
313
314     https://localhost:5665/v1/objects/hosts?hosts=first-host&hosts=second-host
315
316 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.
317
318 When specifying names for objects which have composite names like for example services the
319 full name has to be used:
320
321     https://localhost:5665/v1/objects/services?service=localhost!ping6
322
323 The full name of an object can be obtained by looking at the `__name` attribute.
324
325 #### Advanced Filters <a id="icinga2-api-advanced-filters"></a>
326
327 Most of the information provided in this chapter applies to both permission filters (as used when
328 configuring `ApiUser` objects) and filters specified in queries.
329
330 Advanced filters allow users to filter objects using lambda expressions. The syntax for these filters is the same like for [apply rule expressions](03-monitoring-basics.md#using-apply-expressions).
331
332 > **Note**
333 >
334 > Filters used as URL parameter must be URL-encoded. The following examples
335 > are **not URL-encoded** for better readability.
336
337 Example matching all services in NOT-OK state:
338
339     https://localhost:5665/v1/objects/services?filter=service.state!=ServiceOK
340
341 Example [matching](18-library-reference.md#global-functions-match) all hosts by a name string pattern:
342
343     https://localhost:5665/v1/objects/hosts?filter=match("example.localdomain*",host.name)
344
345 Example for all hosts which are in the host group `linux-servers`:
346
347     https://localhost:5665/v1/objects/hosts?filter="linux-servers" in host.groups
348
349 User-specified filters are run in a sandbox environment which ensures that filters cannot
350 modify Icinga's state, for example object attributes or global variables.
351
352 When querying objects of a specific type the filter expression is evaluated for each object
353 of that type. The object is made available to the filter expression as a variable whose name
354 is the lower-case version of the object's type name.
355
356 For example when querying objects of type `Host` the variable in the filter expression is named
357 `host`. Additionally related objects such as the host's check command are also made available
358 (e.g., via the `check_command` variable). The variable names are the exact same as for the `joins`
359 query parameter; see [object query joins](12-icinga2-api.md#icinga2-api-config-objects-query-joins)
360 for details.
361
362 The object is also made available via the `obj` variable. This makes it easier to build
363 filters which can be used for more than one object type (e.g., for permissions).
364
365 Some queries can be performed for more than just one object type. One example is the 'reschedule-check'
366 action which can be used for both hosts and services. When using advanced filters you will also have to specify the
367 type using the `type` parameter:
368
369     $ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/actions/reschedule-check' \
370     -d '{ "type": "Service", "filter": "service.name==\"ping6\"", "pretty": true }'
371
372 When building filters you have to ensure that values such as
373 `"linux-servers"` are escaped properly according to the rules of the Icinga 2 configuration
374 language.
375
376 To make using the API in scripts easier you can use the `filter_vars` attribute to specify
377 variables which should be made available to your filter expression. This way you don't have
378 to worry about escaping values:
379
380     $ curl -k -s -u 'root:icinga' -H 'Accept: application/json' -H 'X-HTTP-Method-Override: GET' -X POST 'https://localhost:5665/v1/objects/hosts' \
381     -d '{ "filter": "host.vars.os == os", "filter_vars": { "os": "Linux" }, "pretty": true }'
382
383 We're using [X-HTTP-Method-Override](12-icinga2-api.md#icinga2-api-requests-method-override) here because
384 the HTTP specification does not allow message bodies for GET requests.
385
386 The `filters_vars` attribute can only be used inside the request body, but not as
387 a URL parameter because there is no way to specify a dictionary in a URL.
388
389 ## Config Objects <a id="icinga2-api-config-objects"></a>
390
391 Provides methods to manage configuration objects:
392
393 * [creating objects](12-icinga2-api.md#icinga2-api-config-objects-create)
394 * [querying objects](12-icinga2-api.md#icinga2-api-config-objects-query)
395 * [modifying objects](12-icinga2-api.md#icinga2-api-config-objects-modify)
396 * [deleting objects](12-icinga2-api.md#icinga2-api-config-objects-delete)
397
398 ### API Objects and Cluster Config Sync <a id="icinga2-api-config-objects-cluster-sync"></a>
399
400 Newly created or updated objects can be synced throughout your
401 Icinga 2 cluster. Set the `zone` attribute to the zone this object
402 belongs to and let the API and cluster handle the rest.
403
404 Objects without a zone attribute are only synced in the same zone the Icinga instance belongs to.
405
406 > **Note**
407 >
408 > Cluster nodes must accept configuration for creating, modifying
409 > and deleting objects. Ensure that `accept_config` is set to `true`
410 > in the [ApiListener](09-object-types.md#objecttype-apilistener) object
411 > on each node.
412
413 If you add a new cluster instance, or reconnect an instance which has been offline
414 for a while, Icinga 2 takes care of the initial object sync for all objects
415 created by the API.
416
417 ### Querying Objects <a id="icinga2-api-config-objects-query"></a>
418
419 You can request information about configuration objects by sending
420 a `GET` query to the `/v1/objects/<type>` URL endpoint. `<type` has
421 to be replaced with the plural name of the object type you are interested
422 in:
423
424     $ curl -k -s -u root:icinga 'https://localhost:5665/v1/objects/hosts'
425
426 A list of all available configuration types is available in the
427 [object types](09-object-types.md#object-types) chapter.
428
429 The following URL parameters are available:
430
431   Parameters | Type         | Description
432   -----------|--------------|----------------------------
433   attrs      | Array        | **Optional.** Limited attribute list in the output.
434   joins      | Array        | **Optional.** Join related object types and their attributes specified as list (`?joins=host` for the entire set, or selectively by `?joins=host.name`).
435   meta       | Array        | **Optional.** Enable meta information using `?meta=used_by` (references from other objects) and/or `?meta=location` (location information) specified as list. Defaults to disabled.
436
437 In addition to these parameters a [filter](12-icinga2-api.md#icinga2-api-filters) may be provided.
438
439 Instead of using a filter you can optionally specify the object name in the
440 URL path when querying a single object. For objects with composite names
441 (e.g. services) the full name (e.g. `example.localdomain!http`) must be specified:
442
443     $ curl -k -s -u root:icinga 'https://localhost:5665/v1/objects/services/example.localdomain!http'
444
445 You can limit the output to specific attributes using the `attrs` URL parameter:
446
447     $ curl -k -s -u root:icinga 'https://localhost:5665/v1/objects/hosts/example.localdomain?attrs=name&attrs=address&pretty=1'
448     {
449         "results": [
450             {
451                 "attrs": {
452                     "name": "example.localdomain"
453                     "address": "192.168.1.1"
454                 },
455                 "joins": {},
456                 "meta": {},
457                 "name": "example.localdomain",
458                 "type": "Host"
459             }
460         ]
461     }
462
463 #### Object Queries Result <a id="icinga2-api-config-objects-query-result"></a>
464
465 Each response entry in the results array contains the following attributes:
466
467   Attribute  | Type       | Description
468   -----------|------------|--------------
469   name       | String     | Full object name.
470   type       | String     | Object type.
471   attrs      | Dictionary | Object attributes (can be filtered using the URL parameter `attrs`).
472   joins      | Dictionary | [Joined object types](12-icinga2-api.md#icinga2-api-config-objects-query-joins) as key, attributes as nested dictionary. Disabled by default.
473   meta       | Dictionary | Contains `used_by` object references. Disabled by default, enable it using `?meta=used_by` as URL parameter.
474
475 #### Object Query Joins <a id="icinga2-api-config-objects-query-joins"></a>
476
477 Icinga 2 knows about object relations. For example it can optionally return
478 information about the host when querying service objects.
479
480 The following query retrieves all host attributes:
481
482     https://localhost:5665/v1/objects/services?joins=host
483
484 Instead of requesting all host attributes you can also limit the output to specific
485 attributes:
486
487     https://localhost:5665/v1/objects/services?joins=host.name&joins=host.address
488
489 You can request that all available joins are returned in the result set by using
490 the `all_joins` query parameter.
491
492     https://localhost:5665/v1/objects/services?all_joins=1
493
494 > **Note**
495 >
496 > For performance reasons you should only request attributes which your application
497 > requires.
498
499 The following joins are available:
500
501   Object Type  | Object Relations (`joins` prefix name)
502   -------------|------------------------------------------
503   Service      | host, check\_command, check\_period, event\_command, command\_endpoint
504   Host         | check\_command, check\_period, event\_command, command\_endpoint
505   Notification | host, service, command, period
506   Dependency   | child\_host, child\_service, parent\_host, parent\_service, period
507   User         | period
508   Zones        | parent
509
510 Here's an example that retrieves all service objects for hosts which have had their `os`
511 custom attribute set to `Linux`. The result set contains the `display_name` and `check_command`
512 attributes for the service. The query also returns the host's `name` and `address` attribute
513 via a join:
514
515     $ 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'
516
517     {
518         "results": [
519             {
520                 "attrs": {
521                     "check_command": "ping4",
522                     "display_name": "ping4"
523                 },
524                 "joins": {
525                     "host": {
526                         "address": "192.168.1.1",
527                         "name": "example.localdomain"
528                     }
529                 },
530                 "meta": {},
531                 "name": "example.localdomain!ping4",
532                 "type": "Service"
533             },
534             {
535                 "attrs": {
536                     "check_command": "ssh",
537                     "display_name": "ssh"
538                 },
539                 "joins": {
540                     "host": {
541                         "address": "192.168.1.1",
542                         "name": "example.localdomain"
543                     }
544                 },
545                 "meta": {},
546                 "name": "example.localdomain!ssh",
547                 "type": "Service"
548             }
549         ]
550     }
551
552 In case you want to fetch all [comments](09-object-types.md#objecttype-comment)
553 for hosts and services, you can use the following query URL (similar example
554 for downtimes):
555
556     https://localhost:5665/v1/objects/comments?joins=host&joins=service
557
558 This is another example for listing all service objects which are unhandled problems (state is not OK
559 and no downtime or acknowledgement set). We're using [X-HTTP-Method-Override](12-icinga2-api.md#icinga2-api-requests-method-override)
560 here because we want to pass all query attributes in the request body.
561
562     $ 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' \
563     -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 }'
564
565     {
566         "results": [
567             {
568                 "attrs": {
569                     "acknowledgement": 0.0,
570                     "downtime_depth": 0.0,
571                     "name": "10807-service",
572                     "state": 3.0
573                 },
574                 "joins": {
575                     "host": {
576                         "address": "",
577                         "name": "10807-host"
578                     }
579                 },
580                 "meta": {},
581                 "name": "10807-host!10807-service",
582                 "type": "Service"
583             }
584         ]
585     }
586
587 In order to list all acknowledgements without expire time, you query the `/v1/objects/comments`
588 URL endpoint with `joins` and `filter` request parameters using the [X-HTTP-Method-Override](12-icinga2-api.md#icinga2-api-requests-method-override)
589 method:
590
591     $ curl -k -s -u root:icinga -H 'Accept: application/json' -H 'X-HTTP-Method-Override: GET' -X POST 'https://localhost:5665/v1/objects/comments' \
592     -d '{ "joins": [ "service.name", "service.acknowledgement", "service.acknowledgement_expiry" ], "attrs": [ "author", "text" ], "filter": "service.acknowledgement!=0 && service.acknowledgement_expiry==0", "pretty": true }'
593
594     {
595         "results": [
596             {
597                 "attrs": {
598                     "author": "icingaadmin",
599                     "text": "maintenance work"
600                 },
601                 "joins": {
602                     "service": {
603                         "__name": "example.localdomain!disk /",
604                         "acknowledgement": 1.0,
605                         "acknowledgement_expiry": 0.0
606                     }
607                 },
608                 "meta": {},
609                 "name": "example.localdomain!disk /!example.localdomain-1495457222-0",
610                 "type": "Comment"
611             }
612         ]
613     }
614
615 ### Creating Config Objects <a id="icinga2-api-config-objects-create"></a>
616
617 New objects must be created by sending a PUT request. The following
618 parameters need to be passed inside the JSON body:
619
620   Parameters        | Type         | Description
621   ------------------|--------------|--------------------------
622   templates         | Array        | **Optional.** Import existing configuration templates for this object type. Note: These templates must either be statically configured or provided in [config packages](12-icinga2-api.md#icinga2-api-config-management)-
623   attrs             | Dictionary   | **Required.** Set specific object attributes for this [object type](09-object-types.md#object-types).
624   ignore\_on\_error | Boolean      | **Optional.** Ignore object creation errors and return an HTTP 200 status instead.
625
626 The object name must be specified as part of the URL path. For objects with composite names (e.g. services)
627 the full name (e.g. `example.localdomain!http`) must be specified.
628
629 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):
630
631     "attrs": { "vars.os": "Linux" }
632
633 Example for creating the new host object `example.localdomain`:
634
635     $ curl -k -s -u root:icinga -H 'Accept: application/json' -X PUT 'https://localhost:5665/v1/objects/hosts/example.localdomain' \
636     -d '{ "templates": [ "generic-host" ], "attrs": { "address": "192.168.1.1", "check_command": "hostalive", "vars.os" : "Linux" }, "pretty": true }'
637     {
638         "results": [
639             {
640                 "code": 200.0,
641                 "status": "Object was created."
642             }
643         ]
644     }
645
646 If the configuration validation fails, the new object will not be created and the response body
647 contains a detailed error message. The following example is missing the `check_command` attribute
648 which is required for host objects:
649
650     $ curl -k -s -u root:icinga -H 'Accept: application/json' -X PUT 'https://localhost:5665/v1/objects/hosts/example.localdomain' \
651     -d '{ "attrs": { "address": "192.168.1.1", "vars.os" : "Linux" }, "pretty": true }'
652     {
653         "results": [
654             {
655                 "code": 500.0,
656                 "errors": [
657                     "Error: Validation failed for object 'example.localdomain' of type 'Host'; Attribute 'check_command': Attribute must not be empty."
658                 ],
659                 "status": "Object could not be created."
660             }
661         ]
662     }
663
664 Service objects must be created using their full name ("hostname!servicename") referencing an existing host object:
665
666     $ curl -k -s -u root:icinga -H 'Accept: application/json' -X PUT 'https://localhost:5665/v1/objects/services/example.localdomain!realtime-load' \
667     -d '{ "templates": [ "generic-service" ], "attrs": { "check_command": "load", "check_interval": 1,"retry_interval": 1 } }'
668
669
670 Example for a new CheckCommand object:
671
672     $ curl -k -s -u root:icinga -H 'Accept: application/json' -X PUT 'https://localhost:5665/v1/objects/checkcommands/mytest' \
673     -d '{ "templates": [ "plugin-check-command" ], "attrs": { "command": [ "/usr/local/sbin/check_http" ], "arguments": { "-I": "$mytest_iparam$" } } }'
674
675
676 ### Modifying Objects <a id="icinga2-api-config-objects-modify"></a>
677
678 Existing objects must be modified by sending a `POST` request. The following
679 parameters need to be passed inside the JSON body:
680
681   Parameters | Type       | Description
682   -----------|------------|---------------------------
683   attrs      | Dictionary | **Required.** Set specific object attributes for this [object type](09-object-types.md#object-types).
684
685 In addition to these parameters a [filter](12-icinga2-api.md#icinga2-api-filters) should be provided.
686
687 > **Note**:
688 >
689 > Modified attributes do not trigger a re-evaluation of existing
690 > static [apply rules](03-monitoring-basics.md#using-apply) and [group assignments](03-monitoring-basics.md#group-assign-intro).
691 > Delete and re-create the objects if you require such changes.
692 >
693 > Furthermore you cannot modify templates which have already been resolved
694 > during [object creation](12-icinga2-api.md#icinga2-api-config-objects-create).
695 > There are attributes which can only be set for [PUT requests](12-icinga2-api.md#icinga2-api-config-objects-create) such as `groups`
696 > or `zone`. A complete list of `no_user_modify` attributes can be fetched from the [types](12-icinga2-api.md#icinga2-api-types) URL endpoint.
697
698 If attributes are of the Dictionary type, you can also use the indexer format:
699
700     "attrs": { "vars.os": "Linux" }
701
702 The following example updates the `address` attribute and the custom attribute `os` for the `example.localdomain` host:
703
704     $ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/objects/hosts/example.localdomain' \
705     -d '{ "attrs": { "address": "192.168.1.2", "vars.os" : "Windows" }, "pretty": true }'
706     {
707         "results": [
708             {
709                 "code": 200.0,
710                 "name": "example.localdomain",
711                 "status": "Attributes updated.",
712                 "type": "Host"
713             }
714         ]
715     }
716
717
718 ### Deleting Objects <a id="icinga2-api-config-objects-delete"></a>
719
720 You can delete objects created using the API by sending a `DELETE`
721 request.
722
723   Parameters | Type    | Description
724   -----------|---------|---------------
725   cascade    | Boolean |  **Optional.** Delete objects depending on the deleted objects (e.g. services on a host).
726
727 In addition to these parameters a [filter](12-icinga2-api.md#icinga2-api-filters) should be provided.
728
729 Example for deleting the host object `example.localdomain`:
730
731     $ curl -k -s -u root:icinga -H 'Accept: application/json' -X DELETE 'https://localhost:5665/v1/objects/hosts/example.localdomain?cascade=1&pretty=1'
732     {
733         "results": [
734             {
735                 "code": 200.0,
736                 "name": "example.localdomain",
737                 "status": "Object was deleted.",
738                 "type": "Host"
739             }
740         ]
741     }
742
743 ## Config Templates <a id="icinga2-api-config-templates"></a>
744
745 Provides methods to manage configuration templates:
746
747 * [querying templates](12-icinga2-api.md#icinga2-api-config-templates-query)
748
749 Creation, modification and deletion of templates at runtime is not supported.
750
751 ### Querying Templates <a id="icinga2-api-config-templates-query"></a>
752
753 You can request information about configuration templates by sending
754 a `GET` query to the `/v1/templates/<type>` URL endpoint. `<type` has
755 to be replaced with the plural name of the object type you are interested
756 in:
757
758     $ curl -k -s -u root:icinga 'https://localhost:5665/v1/templates/hosts'
759
760 A list of all available configuration types is available in the
761 [object types](09-object-types.md#object-types) chapter.
762
763 A [filter](12-icinga2-api.md#icinga2-api-filters) may be provided for this query type. The
764 template object can be accessed in the filter using the `tmpl` variable. In this
765 example the [match function](18-library-reference.md#global-functions-match) is used to
766 check a wildcard string pattern against `tmpl.name`.
767 The `filter` attribute is passed inside the request body thus requiring to use [X-HTTP-Method-Override](12-icinga2-api.md#icinga2-api-requests-method-override)
768 here.
769
770     $ curl -k -s -u root:icinga -H 'Accept: application/json' -H 'X-HTTP-Method-Override: GET' -X POST 'https://localhost:5661/v1/templates/hosts' \
771     -d '{ "filter": "match(\"g*\", tmpl.name)" }'
772
773 Instead of using a filter you can optionally specify the template name in the
774 URL path when querying a single object:
775
776     $ curl -k -s -u root:icinga 'https://localhost:5665/v1/templates/hosts/generic-host'
777
778 The result set contains the type, name as well as the location of the template.
779
780 ## Variables <a id="icinga2-api-variables"></a>
781
782 Provides methods to manage global variables:
783
784 * [querying variables](12-icinga2-api.md#icinga2-api-variables-query)
785
786 ### Querying Variables <a id="icinga2-api-variables-query"></a>
787
788 You can request information about global variables by sending
789 a `GET` query to the `/v1/variables/` URL endpoint:
790
791     $ curl -k -s -u root:icinga 'https://localhost:5665/v1/variables'
792
793 A [filter](12-icinga2-api.md#icinga2-api-filters) may be provided for this query type. The
794 variable information object can be accessed in the filter using the `variable` variable.
795 The `filter` attribute is passed inside the request body thus requiring to use [X-HTTP-Method-Override](12-icinga2-api.md#icinga2-api-requests-method-override)
796 here.
797
798     $ curl -k -s -u root:icinga -H 'Accept: application/json' -H 'X-HTTP-Method-Override: GET' -X POST 'https://localhost:5661/v1/variables' \
799     -d '{ "filter": "variable.type in [ \"String\", \"Number\" ]" }'
800
801 Instead of using a filter you can optionally specify the variable name in the
802 URL path when querying a single variable:
803
804     $ curl -k -s -u root:icinga 'https://localhost:5665/v1/variables/PrefixDir'
805
806 The result set contains the type, name and value of the global variable.
807
808 ## Actions <a id="icinga2-api-actions"></a>
809
810 There are several actions available for Icinga 2 provided by the `/v1/actions`
811 URL endpoint. You can run actions by sending a `POST` request.
812
813 In case you have been using the [external commands](14-features.md#external-commands)
814 in the past, the API actions provide a similar interface with filter
815 capabilities for some of the more common targets which do not directly change
816 the configuration.
817
818 All actions return a 200 `OK` or an appropriate error code for each
819 action performed on each object matching the supplied filter.
820
821 Actions which affect the Icinga Application itself such as disabling
822 notification on a program-wide basis must be applied by updating the
823 [IcingaApplication object](12-icinga2-api.md#icinga2-api-config-objects)
824 called `app`.
825
826     $ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/objects/icingaapplications/app' -d '{ "attrs": { "enable_notifications": false } }'
827
828 ### process-check-result <a id="icinga2-api-actions-process-check-result"></a>
829
830 Process a check result for a host or a service.
831
832 Send a `POST` request to the URL endpoint `/v1/actions/process-check-result`.
833
834   Parameter          | Type                           | Description
835   ------------------ | --------------                 | --------------
836   exit\_status       | Number                         | **Required.** For services: 0=OK, 1=WARNING, 2=CRITICAL, 3=UNKNOWN, for hosts: 0=OK, 1=CRITICAL.
837   plugin\_output     | String                         | **Required.** One or more lines of the plugin main output. Does **not** contain the performance data.
838   performance\_data  | Array<code>&#124;</code>String | **Optional.** The performance data as array of strings. The raw performance data string can be used too.
839   check\_command     | Array                          | **Optional.** The first entry should be the check commands path, then one entry for each command line option followed by an entry for each of its argument.
840   check\_source      | String                         | **Optional.** Usually the name of the `command_endpoint`
841   execution\_start   | Timestamp                      | **Optional.** The timestamp where a script/process started its execution.
842   execution\_end     | Timestamp                      | **Optional.** The timestamp where a script/process ended its execution. This timestamp is used in features to determine e.g. the metric timestamp.
843   ttl                | Number                         | **Optional.** Time-to-live duration in seconds for this check result. The next expected check result is `now + ttl` where freshness checks are executed.
844
845 In addition to these parameters a [filter](12-icinga2-api.md#icinga2-api-filters) must be provided. The valid types for this action are `Host` and `Service`.
846
847 Example for the service `passive-ping6`:
848
849     $ 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' \
850     -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 }'
851
852     {
853         "results": [
854             {
855                 "code": 200.0,
856                 "status": "Successfully processed check result for object 'localdomain!passive-ping6'."
857             }
858         ]
859     }
860
861 Example for using the `Host` type and filter by the host name:
862
863     $ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/actions/process-check-result' \
864     -d '{ "filter": "host.name==\"example.localdomain\"", "type": "Host", "exit_status": 1, "plugin_output": "Host is not available." }'
865
866 You can avoid URL encoding of white spaces in object names by using the `filter` attribute in the request body.
867
868 > **Note**
869 >
870 > Multi-line plugin output requires the following format: The first line is treated as `short` plugin output corresponding
871 > to the first line of the plugin output. Subsequent lines are treated as `long` plugin output. Please note that the
872 > performance data is separated from the plugin output and has to be passed as `performance_data` attribute.
873
874 ### reschedule-check <a id="icinga2-api-actions-reschedule-check"></a>
875
876 Reschedule a check for hosts and services. The check can be forced if required.
877
878 Send a `POST` request to the URL endpoint `/v1/actions/reschedule-check`.
879
880   Parameter    | Type      | Description
881   -------------|-----------|--------------
882   next\_check  | Timestamp | **Optional.** The next check will be run at this time. If omitted, the current time is used.
883   force        | Boolean   | **Optional.** Defaults to `false`. If enabled, the checks are executed regardless of time period restrictions and checks being disabled per object or on a global basis.
884
885 In addition to these parameters a [filter](12-icinga2-api.md#icinga2-api-filters) must be provided. The valid types for this action are `Host` and `Service`.
886
887 The example reschedules all services with the name "ping6" to immediately perform a check
888 (`next_check` default), ignoring any time periods or whether active checks are
889 allowed for the service (`force=true`).
890
891     $ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/actions/reschedule-check' \
892     -d '{ "type": "Service", "filter": "service.name==\"ping6\"", "force": true, "pretty": true }'
893
894     {
895         "results": [
896             {
897                 "code": 200.0,
898                 "status": "Successfully rescheduled check for object 'example.localdomain!ping6'."
899             }
900         ]
901     }
902
903
904 ### send-custom-notification <a id="icinga2-api-actions-send-custom-notification"></a>
905
906 Send a custom notification for hosts and services. This notification
907 type can be forced being sent to all users.
908
909 Send a `POST` request to the URL endpoint `/v1/actions/send-custom-notification`.
910
911   Parameter | Type    | Description
912   ----------|---------|--------------
913   author    | String  | **Required.** Name of the author, may be empty.
914   comment   | String  | **Required.** Comment text, may be empty.
915   force     | Boolean | **Optional.** Default: false. If true, the notification is sent regardless of downtimes or whether notifications are enabled or not.
916
917 In addition to these parameters a [filter](12-icinga2-api.md#icinga2-api-filters) must be provided. The valid types for this action are `Host` and `Service`.
918
919 Example for a custom host notification announcing a global maintenance to
920 host owners:
921
922     $ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/actions/send-custom-notification' \
923     -d '{ "type": "Host", "author": "icingaadmin", "comment": "System is going down for maintenance", "force": true, "pretty": true }'
924
925     {
926         "results": [
927             {
928                 "code": 200.0,
929                 "status": "Successfully sent custom notification for object 'host0'."
930             },
931             {
932                 "code": 200.0,
933                 "status": "Successfully sent custom notification for object 'host1'."
934             }
935     }
936
937 ### delay-notification <a id="icinga2-api-actions-delay-notification"></a>
938
939 Delay notifications for a host or a service.
940 Note that this will only have an effect if the service stays in the same problem
941 state that it is currently in. If the service changes to another state, a new
942 notification may go out before the time you specify in the `timestamp` argument.
943
944 Send a `POST` request to the URL endpoint `/v1/actions/delay-notification`.
945
946   Parameter | Type      | Description
947   ----------|-----------|--------------
948   timestamp | Timestamp | **Required.** Delay notifications until this timestamp.
949
950 In addition to these parameters a [filter](12-icinga2-api.md#icinga2-api-filters) must be provided. The valid types for this action are `Host` and `Service`.
951
952 Example:
953
954     $ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/actions/delay-notification' \
955     -d '{ "type": "Service", "timestamp": 1446389894, "pretty": true }'
956
957     {
958         "results": [
959             {
960                 "code": 200.0,
961                 "status": "Successfully delayed notifications for object 'host0!service0'."
962             },
963             {
964                 "code": 200.0,
965                 "status": "Successfully delayed notifications for object 'host1!service1'."
966             }
967     }
968
969 ### acknowledge-problem <a id="icinga2-api-actions-acknowledge-problem"></a>
970
971 Allows you to acknowledge the current problem for hosts or services. By
972 acknowledging the current problem, future notifications (for the same state if `sticky` is set to `false`)
973 are disabled.
974
975 Send a `POST` request to the URL endpoint `/v1/actions/acknowledge-problem`.
976
977   Parameter            | Type      | Description
978   ---------------------|-----------|--------------
979   author               | String    | **Required.** Name of the author, may be empty.
980   comment              | String    | **Required.** Comment text, may be empty.
981   expiry               | Timestamp | **Optional.** Whether the acknowledgement will be removed at the timestamp.
982   sticky               | Boolean   | **Optional.** Whether the acknowledgement will be set until the service or host fully recovers. Defaults to `false`.
983   notify               | Boolean   | **Optional.** Whether a notification of the `Acknowledgement` type will be sent. Defaults to `false`.
984   persistent           | Boolean   | **Optional.** When the comment is of type `Acknowledgement` and this is set to `true`, the comment will remain after the acknowledgement recovers or expires. Defaults to `false`.
985
986 In addition to these parameters a [filter](12-icinga2-api.md#icinga2-api-filters) must be provided. The valid types for this action are `Host` and `Service`.
987
988 The following example acknowledges all services which are in a hard critical state and sends out
989 a notification for them:
990
991     $ 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' \
992     -d '{ "author": "icingaadmin", "comment": "Global outage. Working on it.", "notify": true, "pretty": true }'
993
994     {
995         "results": [
996             {
997                 "code": 200.0,
998                 "status": "Successfully acknowledged problem for object 'example2.localdomain!ping4'."
999             },
1000             {
1001                 "code": 200.0,
1002                 "status": "Successfully acknowledged problem for object 'example.localdomain!ping4'."
1003             }
1004     }
1005
1006
1007 ### remove-acknowledgement <a id="icinga2-api-actions-remove-acknowledgement"></a>
1008
1009 Removes the acknowledgements for services or hosts. Once the acknowledgement has
1010 been removed notifications will be sent out again.
1011
1012 Send a `POST` request to the URL endpoint `/v1/actions/remove-acknowledgement`.
1013
1014 A [filter](12-icinga2-api.md#icinga2-api-filters) must be provided. The valid types for this action are `Host` and `Service`.
1015
1016 The example removes all service acknowledgements:
1017
1018     $ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/actions/remove-acknowledgement?type=Service&pretty=1'
1019
1020     {
1021         "results": [
1022             {
1023                 "code": 200.0,
1024                 "status": "Successfully removed acknowledgement for object 'host0!service0'."
1025             },
1026             {
1027                 "code": 200.0,
1028                 "status": "Successfully removed acknowledgement for object 'example2.localdomain!aws-health'."
1029             }
1030     }
1031
1032 ### add-comment <a id="icinga2-api-actions-add-comment"></a>
1033
1034 Adds a `comment` from an `author` to services or hosts.
1035
1036 Send a `POST` request to the URL endpoint `/v1/actions/add-comment`.
1037
1038   Parameter | Type   | Description
1039   ----------|--------|--------------
1040   author    | string | **Required.** Name of the author, may be empty.
1041   comment   | string | **Required.** Comment text, may be empty.
1042
1043 In addition to these parameters a [filter](12-icinga2-api.md#icinga2-api-filters) must be provided. The valid types for this action are `Host` and `Service`.
1044
1045 The following example adds a comment for all `ping4` services:
1046
1047     $ 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 }'
1048     {
1049         "results": [
1050             {
1051                 "code": 200.0,
1052                 "legacy_id": 26.0,
1053                 "name": "example.localdomain!ping4!example.localdomain-1446824161-0",
1054                 "status": "Successfully added comment 'example.localdomain!ping4!example.localdomain-1446824161-0' for object 'example.localdomain!ping4'."
1055             },
1056             {
1057                 "code": 200.0,
1058                 "legacy_id": 27.0,
1059                 "name": "example2.localdomain!ping4!example.localdomain-1446824161-1",
1060                 "status": "Successfully added comment 'example2.localdomain!ping4!example.localdomain-1446824161-1' for object 'example2.localdomain!ping4'."
1061             }
1062         ]
1063     }
1064
1065 ### remove-comment <a id="icinga2-api-actions-remove-comment"></a>
1066
1067 Remove the comment using its `name` attribute , returns `OK` if the
1068 comment did not exist.
1069 **Note**: This is **not** the legacy ID but the comment name returned by
1070 Icinga 2 when [adding a comment](12-icinga2-api.md#icinga2-api-actions-add-comment).
1071
1072 Send a `POST` request to the URL endpoint `/v1/actions/remove-comment`.
1073
1074 A [filter](12-icinga2-api.md#icinga2-api-filters) must be provided. The valid types for this action are `Host`, `Service` and `Comment`.
1075
1076 Example for a simple filter using the `comment` URL parameter:
1077
1078     $ 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'
1079     {
1080         "results": [
1081             {
1082                 "code": 200.0,
1083                 "status": "Successfully removed comment 'example2.localdomain!ping4!mbmif.local-1446986367-0'."
1084             }
1085         ]
1086     }
1087
1088 Example for removing all service comments using a service name filter for `ping4`:
1089
1090     $ 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'
1091     {
1092         "results": [
1093             {
1094                 "code": 200.0,
1095                 "status": "Successfully removed all comments for object 'example2.localdomain!ping4'."
1096             },
1097             {
1098                 "code": 200.0,
1099                 "status": "Successfully removed all comments for object 'example.localdomain!ping4'."
1100             }
1101         ]
1102     }
1103
1104
1105 ### schedule-downtime <a id="icinga2-api-actions-schedule-downtime"></a>
1106
1107 Schedule a downtime for hosts and services.
1108
1109 Send a `POST` request to the URL endpoint `/v1/actions/schedule-downtime`.
1110
1111   Parameter     | Type      | Description
1112   --------------|-----------|--------------
1113   author        | String    | **Required.** Name of the author.
1114   comment       | String    | **Required.** Comment text.
1115   start\_time   | Timestamp | **Required.** Timestamp marking the beginning of the downtime.
1116   end\_time     | Timestamp | **Required.** Timestamp marking the end of the downtime.
1117   fixed         | Boolean   | **Optional.** Defaults to `true`. If true, the downtime is `fixed` otherwise `flexible`. See [downtimes](08-advanced-topics.md#downtimes) for more information.
1118   duration      | Number    | **Required for flexible downtimes.** Duration of the downtime in seconds if `fixed` is set to false.
1119   trigger\_name | String    | **Optional.** Sets the trigger for a triggered downtime. See [downtimes](08-advanced-topics.md#downtimes) for more information on triggered downtimes.
1120   child\_options| String    | **Optional.** Schedule child downtimes. `DowntimeNoChildren` does not do anything, `DowntimeTriggeredChildren` schedules child downtimes triggered by this downtime, `DowntimeNonTriggeredChildren` schedules non-triggered downtimes. Defaults to `DowntimeNoChildren`.
1121
1122 In addition to these parameters a [filter](12-icinga2-api.md#icinga2-api-filters) must be provided. The valid types for this action are `Host` and `Service`.
1123
1124 Example:
1125
1126     $ 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 }'
1127     {
1128         "results": [
1129             {
1130                 "code": 200.0,
1131                 "legacy_id": 2.0,
1132                 "name": "example2.localdomain!ping4!example.localdomain-1446822004-0",
1133                 "status": "Successfully scheduled downtime 'example2.localdomain!ping4!example.localdomain-1446822004-0' for object 'example2.localdomain!ping4'."
1134             },
1135             {
1136                 "code": 200.0,
1137                 "legacy_id": 3.0,
1138                 "name": "example.localdomain!ping4!example.localdomain-1446822004-1",
1139                 "status": "Successfully scheduled downtime 'example.localdomain!ping4!example.localdomain-1446822004-1' for object 'example.localdomain!ping4'."
1140             }
1141         ]
1142     }
1143
1144 ### remove-downtime <a id="icinga2-api-actions-remove-downtime"></a>
1145
1146 Remove the downtime using its `name` attribute , returns `OK` if the
1147 downtime did not exist.
1148 **Note**: This is **not** the legacy ID but the downtime name returned by
1149 Icinga 2 when [scheduling a downtime](12-icinga2-api.md#icinga2-api-actions-schedule-downtime).
1150
1151 Send a `POST` request to the URL endpoint `/v1/actions/remove-downtime`.
1152
1153 A [filter](12-icinga2-api.md#icinga2-api-filters) must be provided. The valid types for this action are `Host`, `Service` and `Downtime`.
1154
1155 Example for a simple filter using the `downtime` URL parameter:
1156
1157     $ 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'
1158     {
1159         "results": [
1160             {
1161                 "code": 200.0,
1162                 "status": "Successfully removed downtime 'example.localdomain!ping4!mbmif.local-1446979168-6'."
1163             }
1164         ]
1165     }
1166
1167 Example for removing all host downtimes using a host name filter for `example.localdomain`:
1168
1169     $ 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'
1170     {
1171         "results": [
1172             {
1173                 "code": 200.0,
1174                 "status": "Successfully removed all downtimes for object 'example.localdomain'."
1175             }
1176         ]
1177     }
1178
1179 Example for removing a downtime from a host but not the services filtered by the author name. This example uses
1180 filter variables explained in the [advanced filters](12-icinga2-api.md#icinga2-api-advanced-filters) chapter.
1181
1182     $ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/actions/remove-downtime' \
1183             -d $'{
1184       "type": "Downtime",
1185       "filter": "host.name == filterHost && !service && downtime.author == filterAuthor",
1186       "filter_vars": {
1187         "filterHost": "example.localdomain",
1188         "filterAuthor": "icingaadmin"
1189       },
1190       "pretty": true
1191     }'
1192
1193     {
1194         "results": [
1195             {
1196                 "code": 200.0,
1197                 "status": "Successfully removed downtime 'example.localdomain!mbmif.local-1463043129-3'."
1198             }
1199         ]
1200     }
1201
1202 ### shutdown-process <a id="icinga2-api-actions-shutdown-process"></a>
1203
1204 Shuts down Icinga2. May or may not return.
1205
1206 Send a `POST` request to the URL endpoint `/v1/actions/shutdown-process`.
1207
1208 This action does not support a target type or filter.
1209
1210 Example:
1211
1212     $ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/actions/shutdown-process?pretty=1'
1213
1214     {
1215         "results": [
1216             {
1217                 "code": 200.0,
1218                 "status": "Shutting down Icinga 2."
1219             }
1220         ]
1221     }
1222
1223 ### restart-process <a id="icinga2-api-actions-restart-process"></a>
1224
1225 Restarts Icinga2. May or may not return.
1226
1227 Send a `POST` request to the URL endpoint `/v1/actions/restart-process`.
1228
1229 This action does not support a target type or filter.
1230
1231 Example:
1232
1233     $ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/actions/restart-process?pretty=1'
1234
1235     {
1236         "results": [
1237             {
1238                 "code": 200.0,
1239                 "status": "Restarting Icinga 2."
1240             }
1241         ]
1242     }
1243
1244 ### generate-ticket <a id="icinga2-api-actions-generate-ticket"></a>
1245
1246 Generates a PKI ticket for [CSR auto-signing](06-distributed-monitoring.md#distributed-monitoring-setup-csr-auto-signing).
1247 This can be used in combination with satellite/client setups requesting this ticket number.
1248
1249 Send a `POST` request to the URL endpoint `/v1/actions/generate-ticket`.
1250
1251   Parameter     | Type      | Description
1252   --------------|-----------|--------------
1253   cn            | String    | **Required.** The host's common name for which the ticket should be geenerated.
1254
1255 Example:
1256
1257     $ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/actions/generate-ticket' \
1258     -d '{ "cn": "icinga2-client1.localdomain", "pretty": true }'
1259     {
1260         "results": [
1261             {
1262                 "code": 200.0,
1263                 "status": "Generated PKI ticket '4f75d2ecd253575fe9180938ebff7cbca262f96e' for common name 'icinga2-client1.localdomain'.",
1264                 "ticket": "4f75d2ecd253575fe9180938ebff7cbca262f96e"
1265             }
1266         ]
1267     }
1268
1269
1270 ## Event Streams <a id="icinga2-api-event-streams"></a>
1271
1272 You can subscribe to event streams by sending a `POST` request to the URL endpoint `/v1/events`.
1273 The following parameters need to be specified (either as URL parameters or in a JSON-encoded message body):
1274
1275   Parameter  | Type         | Description
1276   -----------|--------------|-------------
1277   types      | Array        | **Required.** Event type(s). Multiple types as URL parameters are supported.
1278   queue      | String       | **Required.** Unique queue name. Multiple HTTP clients can use the same queue as long as they use the same event types and filter.
1279   filter     | String       | **Optional.** Filter for specific event attributes using [filter expressions](12-icinga2-api.md#icinga2-api-filters).
1280
1281 ### Event Stream Types <a id="icinga2-api-event-streams-types"></a>
1282
1283 The following event stream types are available:
1284
1285   Type                   | Description
1286   -----------------------|--------------
1287   CheckResult            | Check results for hosts and services.
1288   StateChange            | Host/service state changes.
1289   Notification           | Notification events including notified users for hosts and services.
1290   AcknowledgementSet     | Acknowledgement set on hosts and services.
1291   AcknowledgementCleared | Acknowledgement cleared on hosts and services.
1292   CommentAdded           | Comment added for hosts and services.
1293   CommentRemoved         | Comment removed for hosts and services.
1294   DowntimeAdded          | Downtime added for hosts and services.
1295   DowntimeRemoved        | Downtime removed for hosts and services.
1296   DowntimeStarted        | Downtime started for hosts and services.
1297   DowntimeTriggered      | Downtime triggered for hosts and services.
1298
1299 Note: Each type requires [API permissions](12-icinga2-api.md#icinga2-api-permissions)
1300 being set.
1301
1302 Example for all downtime events:
1303
1304     &types=DowntimeAdded&types=DowntimeRemoved&types=DowntimeTriggered
1305
1306 #### <a id="icinga2-api-event-streams-type-checkresult"></a> Event Stream Type: CheckResult
1307
1308   Name          | Type          | Description
1309   --------------|---------------|--------------------------
1310   type          | String        | Event type `CheckResult`.
1311   timestamp     | Timestamp     | Unix timestamp when the event happened.
1312   host          | String        | [Host](09-object-types.md#objecttype-host) name.
1313   service       | String        | [Service](09-object-types.md#objecttype-service) name. Optional if this is a host check result.
1314   check\_result | CheckResult   | Serialized [CheckResult](08-advanced-topics.md#advanced-value-types-checkresult) value type.
1315
1316 #### <a id="icinga2-api-event-streams-type-statechange"></a> Event Stream Type: StateChange
1317
1318   Name          | Type          | Description
1319   --------------|---------------|--------------------------
1320   type          | String        | Event type `StateChange`.
1321   timestamp     | Timestamp     | Unix timestamp when the event happened.
1322   host          | String        | [Host](09-object-types.md#objecttype-host) name.
1323   service       | String        | [Service](09-object-types.md#objecttype-service) name. Optional if this is a host state change.
1324   state         | Number        | [Host](09-object-types.md#objecttype-host) or [service](09-object-types.md#objecttype-service) state.
1325   state\_type   | Number        | [Host](09-object-types.md#objecttype-host) or [service](09-object-types.md#objecttype-service) state type.
1326   check\_result | CheckResult   | Serialized [CheckResult](08-advanced-topics.md#advanced-value-types-checkresult) value type.
1327
1328 #### <a id="icinga2-api-event-streams-type-notification"></a> Event Stream Type: Notification
1329
1330   Name          | Type          | Description
1331   --------------|---------------|--------------------------
1332   type          | String        | Event type `Notification`.
1333   timestamp     | Timestamp     | Unix timestamp when the event happened.
1334   host          | String        | [Host](09-object-types.md#objecttype-host) name.
1335   service       | String        | [Service](09-object-types.md#objecttype-service) name. Optional if this is a host notification.
1336   command       | String        | [NotificationCommand](09-object-types.md#objecttype-notificationcommand) name.
1337   users         | Array         | List of notified [user](09-object-types.md#objecttype-user) names.
1338   notification\_type | String   | [$notification.type$](03-monitoring-basics.md#notification-runtime-macros) runtime macro value.
1339   author        | String        | [$notification.author$](03-monitoring-basics.md#notification-runtime-macros) runtime macro value.
1340   text          | String        | [$notification.comment$](03-monitoring-basics.md#notification-runtime-macros) runtime macro value.
1341   check\_result | CheckResult   | Serialized [CheckResult](08-advanced-topics.md#advanced-value-types-checkresult) value type.
1342
1343 #### <a id="icinga2-api-event-streams-type-flapping"></a> Event Stream Type: Flapping
1344
1345   Name              | Type          | Description
1346   ------------------|---------------|--------------------------
1347   type              | String        | Event type `Flapping`.
1348   timestamp         | Timestamp     | Unix timestamp when the event happened.
1349   host              | String        | [Host](09-object-types.md#objecttype-host) name.
1350   service           | String        | [Service](09-object-types.md#objecttype-service) name. Optional if this is a host flapping event.
1351   state             | Number        | [Host](09-object-types.md#objecttype-host) or [service](09-object-types.md#objecttype-service) state.
1352   state\_type       | Number        | [Host](09-object-types.md#objecttype-host) or [service](09-object-types.md#objecttype-service) state type.
1353   is\_flapping      | Boolean       | Whether this object is flapping.
1354   current\_flapping | Number        | Current flapping value in percent (added in 2.8).
1355   threshold\_low    | Number        | Low threshold in percent (added in 2.8).
1356   threshold\_high   | Number        | High threshold in percent (added in 2.8).
1357
1358 #### <a id="icinga2-api-event-streams-type-acknowledgementset"></a> Event Stream Type: AcknowledgementSet
1359
1360   Name          | Type          | Description
1361   --------------|---------------|--------------------------
1362   type          | String        | Event type `AcknowledgementSet`.
1363   timestamp     | Timestamp     | Unix timestamp when the event happened.
1364   host          | String        | [Host](09-object-types.md#objecttype-host) name.
1365   service       | String        | [Service](09-object-types.md#objecttype-service) name. Optional if this is a host acknowledgement.
1366   state         | Number        | [Host](09-object-types.md#objecttype-host) or [service](09-object-types.md#objecttype-service) state.
1367   state\_type   | Number        | [Host](09-object-types.md#objecttype-host) or [service](09-object-types.md#objecttype-service) state type.
1368   author        | String        | Acknowledgement author set via [acknowledge-problem](12-icinga2-api.md#icinga2-api-actions-acknowledge-problem) action.
1369   comment       | String        | Acknowledgement comment set via [acknowledge-problem](12-icinga2-api.md#icinga2-api-actions-acknowledge-problem) action.
1370   acknowledgement\_type | Number | 0 = None, 1 = Normal, 2 = Sticky. `sticky` can be set via [acknowledge-problem](12-icinga2-api.md#icinga2-api-actions-acknowledge-problem) action.
1371   notify        | Boolean       | Notifications were enabled via [acknowledge-problem](12-icinga2-api.md#icinga2-api-actions-acknowledge-problem) action.
1372   expiry        | Timestamp     | Acknowledgement expire time set via [acknowledge-problem](12-icinga2-api.md#icinga2-api-actions-acknowledge-problem) action.
1373
1374 #### <a id="icinga2-api-event-streams-type-acknowledgementcleared"></a> Event Stream Type: AcknowledgementCleared
1375
1376   Name          | Type          | Description
1377   --------------|---------------|--------------------------
1378   type          | String        | Event type `AcknowledgementCleared`.
1379   timestamp     | Timestamp     | Unix timestamp when the event happened.
1380   host          | String        | [Host](09-object-types.md#objecttype-host) name.
1381   service       | String        | [Service](09-object-types.md#objecttype-service) name. Optional if this is a host acknowledgement.
1382   state         | Number        | [Host](09-object-types.md#objecttype-host) or [service](09-object-types.md#objecttype-service) state.
1383   state\_type   | Number        | [Host](09-object-types.md#objecttype-host) or [service](09-object-types.md#objecttype-service) state type.
1384
1385 #### <a id="icinga2-api-event-streams-type-commentadded"></a> Event Stream Type: CommentAdded
1386
1387   Name          | Type          | Description
1388   --------------|---------------|--------------------------
1389   type          | String        | Event type `CommentAdded`.
1390   timestamp     | Timestamp     | Unix timestamp when the event happened.
1391   comment       | Dictionary    | Serialized [Comment](09-object-types.md#objecttype-comment) object.
1392
1393 #### <a id="icinga2-api-event-streams-type-commentremoved"></a> Event Stream Type: CommentRemoved
1394
1395   Name          | Type          | Description
1396   --------------|---------------|--------------------------
1397   type          | String        | Event type `CommentRemoved`.
1398   timestamp     | Timestamp     | Unix timestamp when the event happened.
1399   comment       | Dictionary    | Serialized [Comment](09-object-types.md#objecttype-comment) object.
1400
1401 #### <a id="icinga2-api-event-streams-type-downtimeadded"></a> Event Stream Type: DowntimeAdded
1402
1403   Name          | Type          | Description
1404   --------------|---------------|--------------------------
1405   type          | String        | Event type `DowntimeAdded`.
1406   timestamp     | Timestamp     | Unix timestamp when the event happened.
1407   downtime      | Dictionary    | Serialized [Comment](09-object-types.md#objecttype-downtime) object.
1408
1409 #### <a id="icinga2-api-event-streams-type-downtimeremoved"></a> Event Stream Type: DowntimeRemoved
1410
1411   Name          | Type          | Description
1412   --------------|---------------|--------------------------
1413   type          | String        | Event type `DowntimeRemoved`.
1414   timestamp     | Timestamp     | Unix timestamp when the event happened.
1415   downtime      | Dictionary    | Serialized [Comment](09-object-types.md#objecttype-downtime) object.
1416
1417
1418 #### <a id="icinga2-api-event-streams-type-downtimestarted"></a> Event Stream Type: DowntimeStarted
1419
1420   Name          | Type          | Description
1421   --------------|---------------|--------------------------
1422   type          | String        | Event type `DowntimeStarted`.
1423   timestamp     | Timestamp     | Unix timestamp when the event happened.
1424   downtime      | Dictionary    | Serialized [Comment](09-object-types.md#objecttype-downtime) object.
1425
1426
1427 #### <a id="icinga2-api-event-streams-type-downtimetriggered"></a> Event Stream Type: DowntimeTriggered
1428
1429   Name          | Type          | Description
1430   --------------|---------------|--------------------------
1431   type          | String        | Event type `DowntimeTriggered`.
1432   timestamp     | Timestamp     | Unix timestamp when the event happened.
1433   downtime      | Dictionary    | Serialized [Comment](09-object-types.md#objecttype-downtime) object.
1434
1435
1436 ### Event Stream Filter <a id="icinga2-api-event-streams-filter"></a>
1437
1438 Event streams can be filtered by attributes using the prefix `event.`.
1439
1440 Example for the `CheckResult` type with the `exit_code` set to `2`:
1441
1442     &types=CheckResult&filter=event.check_result.exit_status==2
1443
1444 Example for the `CheckResult` type with the service [matching](18-library-reference.md#global-functions-match)
1445 the string pattern "random\*":
1446
1447     &types=CheckResult&filter=match%28%22random*%22,event.service%29
1448
1449
1450 ### Event Stream Response <a id="icinga2-api-event-streams-response"></a>
1451
1452 The event stream response is separated with new lines. The HTTP client
1453 must support long-polling and HTTP/1.1. HTTP/1.0 is not supported.
1454
1455 Example:
1456
1457     $ 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'
1458
1459     {"check_result":{ ... },"host":"example.localdomain","service":"ping4","timestamp":1445421319.7226390839,"type":"CheckResult"}
1460     {"check_result":{ ... },"host":"example.localdomain","service":"ping4","timestamp":1445421324.7226390839,"type":"CheckResult"}
1461     {"check_result":{ ... },"host":"example.localdomain","service":"ping4","timestamp":1445421329.7226390839,"type":"CheckResult"}
1462
1463
1464 ## Status and Statistics <a id="icinga2-api-status"></a>
1465
1466 Send a `GET` request to the URL endpoint `/v1/status` to retrieve status information and statistics for Icinga 2.
1467
1468 Example:
1469
1470     $ curl -k -s -u root:icinga 'https://localhost:5665/v1/status?pretty=1'
1471     {
1472         "results": [
1473             {
1474                 "name": "ApiListener",
1475                 "perfdata": [ ... ],
1476                 "status": [ ... ]
1477             },
1478             ...
1479             {
1480                 "name": "IcingaAplication",
1481                 "perfdata": [ ... ],
1482                 "status": [ ... ]
1483             },
1484             ...
1485         ]
1486     }
1487
1488 You can limit the output by specifying a status type in the URL, e.g. `IcingaApplication`:
1489
1490     $ curl -k -s -u root:icinga 'https://localhost:5665/v1/status/IcingaApplication?pretty=1'
1491     {
1492         "results": [
1493             {
1494                 "perfdata": [],
1495                 "status": {
1496                     "icingaapplication": {
1497                         "app": {
1498                             "enable_event_handlers": true,
1499                             "enable_flapping": true,
1500                             "enable_host_checks": true,
1501                             "enable_notifications": true,
1502                             "enable_perfdata": true,
1503                             "enable_service_checks": true,
1504                             "node_name": "example.localdomain",
1505                             "pid": 59819.0,
1506                             "program_start": 1443019345.093372,
1507                             "version": "v2.3.0-573-g380a131"
1508                         }
1509                     }
1510                 }
1511             }
1512         ]
1513     }
1514
1515
1516 ## Configuration Management <a id="icinga2-api-config-management"></a>
1517
1518 The main idea behind configuration management is to allow external applications
1519 creating configuration packages and stages based on configuration files and
1520 directory trees. This replaces any additional SSH connection and whatnot to
1521 dump configuration files to Icinga 2 directly.
1522 In case you are pushing a new configuration stage to a package, Icinga 2 will
1523 validate the configuration asynchronously and populate a status log which
1524 can be fetched in a separated request.
1525
1526
1527 ### Creating a Config Package <a id="icinga2-api-config-management-create-package"></a>
1528
1529 Send a `POST` request to a new config package called `example-cmdb` in this example. This
1530 will create a new empty configuration package.
1531
1532     $ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST \
1533     'https://localhost:5665/v1/config/packages/example-cmdb?pretty=1'
1534     {
1535         "results": [
1536             {
1537                 "code": 200.0,
1538                 "package": "example-cmdb",
1539                 "status": "Created package."
1540             }
1541         ]
1542     }
1543
1544 Package names starting with an underscore are reserved for internal packages and must not be used.
1545
1546 ### Uploading configuration for a Config Package <a id="icinga2-api-config-management-create-config-stage"></a>
1547
1548 Configuration files in packages are managed in stages.
1549 Stages provide a way to maintain multiple configuration versions for a package.
1550
1551 Send a `POST` request to the URL endpoint `/v1/config/stages` and add the name of an existing
1552 configuration package to the URL path (e.g. `example-cmdb`).
1553 The request body must contain the `files` attribute with the value being
1554 a dictionary of file targets and their content. You can also specify an optional `reload` attribute
1555 that will tell icinga2 to reload after stage config validation. By default this is set to `true`.
1556
1557 The file path requires one of these two directories inside its path:
1558
1559   Directory   | Description
1560   ------------|------------------------------------
1561   conf.d      | Local configuration directory.
1562   zones.d     | Configuration directory for cluster zones, each zone must be put into its own zone directory underneath. Supports the [cluster config sync](06-distributed-monitoring.md#distributed-monitoring-top-down-config-sync).
1563
1564 Example for a local configuration in the `conf.d` directory:
1565
1566     "files": { "conf.d/host1.conf": "object Host \"local-host\" { address = \"127.0.0.1\", check_command = \"hostalive\" }" }
1567
1568 Example for a host configuration inside the `satellite` zone in the `zones.d` directory:
1569
1570     "files": { "zones.d/satellite/host2.conf": "object Host \"satellite-host\" { address = \"192.168.1.100\", check_command = \"hostalive\" }" }
1571
1572
1573 The example below will create a new file called `test.conf` in the `conf.d`
1574 directory. Note: This example contains an error (`chec_command`). This is
1575 intentional.
1576
1577     $ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST \
1578     -d '{ "files": { "conf.d/test.conf": "object Host \"cmdb-host\" { chec_command = \"dummy\" }" }, "pretty": true }' \
1579     'https://localhost:5665/v1/config/stages/example-cmdb'
1580     {
1581         "results": [
1582             {
1583                 "code": 200.0,
1584                 "package": "example-cmdb",
1585                 "stage": "example.localdomain-1441625839-0",
1586                 "status": "Created stage. Icinga2 will reload."
1587             }
1588         ]
1589     }
1590
1591 The Icinga 2 API returns the `package` name this stage was created for, and also
1592 generates a unique name for the `stage` attribute you'll need for later requests.
1593
1594 Icinga 2 automatically restarts the daemon in order to activate the new config stage. This
1595 can be disabled by setting `reload` to `false` in the request.
1596 If the validation for the new config stage failed, the old stage
1597 and its configuration objects will remain active.
1598
1599 > **Note**
1600 >
1601 > Old stages are not purged automatically. You can [remove stages](12-icinga2-api.md#icinga2-api-config-management-delete-config-stage) that are no longer in use.
1602
1603 Icinga 2 will create the following files in the configuration package
1604 stage after configuration validation:
1605
1606   File        | Description
1607   ------------|--------------
1608   status      | Contains the [configuration validation](11-cli-commands.md#config-validation) exit code (everything else than 0 indicates an error).
1609   startup.log | Contains the [configuration validation](11-cli-commands.md#config-validation) output.
1610
1611 You can [fetch these files](12-icinga2-api.md#icinga2-api-config-management-fetch-config-package-stage-files)
1612 in order to verify that the new configuration was deployed successfully.
1613
1614
1615 ### List Configuration Packages and their Stages <a id="icinga2-api-config-management-list-config-packages"></a>
1616
1617 A list of packages and their stages can be retrieved by sending a `GET` request to the URL endpoint `/v1/config/packages`.
1618
1619 The following example contains one configuration package `example-cmdb`. The package does not currently
1620 have an active stage.
1621
1622     $ curl -k -s -u root:icinga 'https://localhost:5665/v1/config/packages?pretty=1'
1623     {
1624         "results": [
1625             {
1626                 "active-stage": "",
1627                 "name": "example-cmdb",
1628                 "stages": [
1629                     "example.localdomain-1441625839-0"
1630                 ]
1631             }
1632         ]
1633     }
1634
1635
1636 ### List Configuration Packages and their Stages <a id="icinga2-api-config-management-list-config-package-stage-files"></a>
1637
1638 In order to retrieve a list of files for a stage you can send a `GET` request to
1639 the URL endpoint `/v1/config/stages`. You need to include
1640 the package name (`example-cmdb`) and stage name (`example.localdomain-1441625839-0`) in the URL:
1641
1642     $ curl -k -s -u root:icinga 'https://localhost:5665/v1/config/stages/example-cmdb/example.localdomain-1441625839-0?pretty=1'
1643     {
1644         "results": [
1645     ...
1646             {
1647                 "name": "startup.log",
1648                 "type": "file"
1649             },
1650             {
1651                 "name": "status",
1652                 "type": "file"
1653             },
1654             {
1655                 "name": "conf.d",
1656                 "type": "directory"
1657             },
1658             {
1659                 "name": "zones.d",
1660                 "type": "directory"
1661             },
1662             {
1663                 "name": "conf.d/test.conf",
1664                 "type": "file"
1665             }
1666         ]
1667     }
1668
1669 ### Fetch Configuration Package Stage Files <a id="icinga2-api-config-management-fetch-config-package-stage-files"></a>
1670
1671 Send a `GET` request to the URL endpoint `/v1/config/files` and add
1672 the package name, the stage name and the relative path to the file to the URL path.
1673
1674 > **Note**
1675 >
1676 > The returned files are plain-text instead of JSON-encoded.
1677
1678 The following example fetches the configuration file `conf.d/test.conf`:
1679
1680     $ curl -k -s -u root:icinga 'https://localhost:5665/v1/config/files/example-cmdb/example.localdomain-1441625839-0/conf.d/test.conf'
1681
1682     object Host "cmdb-host" { chec_command = "dummy" }
1683
1684 You can fetch a [list of existing files](12-icinga2-api.md#icinga2-api-config-management-list-config-package-stage-files)
1685 in a configuration stage and then specifically request their content.
1686
1687 ### Configuration Package Stage Errors <a id="icinga2-api-config-management-config-package-stage-errors"></a>
1688
1689 Now that we don't have an active stage for `example-cmdb` yet seen [here](12-icinga2-api.md#icinga2-api-config-management-list-config-packages),
1690 there must have been an error.
1691
1692 In order to check for validation errors you can fetch the `startup.log` file
1693 by sending a `GET` request to the URL endpoint `/v1/config/files`. You must include
1694 the package name, stage name and the `startup.log` in the URL path.
1695
1696     $ curl -k -s -u root:icinga 'https://localhost:5665/v1/config/files/example-cmdb/example.localdomain-1441133065-1/startup.log'
1697     ...
1698
1699     critical/config: Error: Attribute 'chec_command' does not exist.
1700     Location:
1701     /var/lib/icinga2/api/packages/example-cmdb/example.localdomain-1441133065-1/conf.d/test.conf(1): object Host "cmdb-host" { chec_command = "dummy" }
1702                                                                                                            ^^^^^^^^^^^^^^^^^^^^^^
1703
1704     critical/config: 1 error
1705
1706 The output is similar to the manual [configuration validation](11-cli-commands.md#config-validation).
1707
1708 > **Note**
1709 >
1710 > The returned output is plain-text instead of JSON-encoded.
1711
1712
1713 ### Deleting Configuration Package Stage <a id="icinga2-api-config-management-delete-config-stage"></a>
1714
1715 You can send a `DELETE` request to the URL endpoint `/v1/config/stages`
1716 in order to purge a configuration stage. You must include the package and
1717 stage name inside the URL path.
1718
1719 The following example removes the failed configuration stage `example.localdomain-1441133065-1`
1720 in the `example-cmdb` configuration package:
1721
1722     $ curl -k -s -u root:icinga -H 'Accept: application/json' -X DELETE \
1723     'https://localhost:5665/v1/config/stages/example-cmdb/example.localdomain-1441133065-1?pretty=1'
1724     {
1725         "results": [
1726             {
1727                 "code": 200.0,
1728                 "status": "Stage deleted."
1729             }
1730         ]
1731     }
1732
1733
1734 ### Deleting Configuration Package <a id="icinga2-api-config-management-delete-config-package"></a>
1735
1736 In order to completely purge a configuration package and its stages
1737 you can send a `DELETE` request to the URL endpoint `/v1/config/packages`
1738 with the package name in the URL path.
1739
1740 This example entirely deletes the configuration package `example-cmdb`:
1741
1742     $ curl -k -s -u root:icinga -H 'Accept: application/json' -X DELETE \
1743     'https://localhost:5665/v1/config/packages/example-cmdb?pretty=1'
1744     {
1745         "results": [
1746             {
1747                 "code": 200.0,
1748                 "package": "example-cmdb",
1749                 "status": "Deleted package."
1750             }
1751         ]
1752     }
1753
1754
1755 ## Types <a id="icinga2-api-types"></a>
1756
1757 You can retrieve the configuration object types by sending a `GET` request to URL
1758 endpoint `/v1/types`.
1759
1760 Each response entry in the results array contains the following attributes:
1761
1762   Attribute       | Type         | Description
1763   ----------------|--------------|---------------------
1764   name            | String       | The type name.
1765   plural\_name    | String       | The plural type name.
1766   fields          | Dictionary   | Available fields including details on e.g. the type and attribute accessibility.
1767   abstract        | Boolean      | Whether objects can be instantiated for this type.
1768   base            | Boolean      | The base type (e.g. `Service` inherits fields and prototype methods from `Checkable`).
1769   prototype\_keys | Array        | Available prototype methods.
1770
1771 In order to view a specific configuration object type specify its name inside the URL path:
1772
1773     $ curl -k -s -u root:icinga 'https://localhost:5665/v1/types/Object?pretty=1'
1774     {
1775         "results": [
1776             {
1777                 "abstract": false,
1778                 "fields": {
1779                     "type": {
1780                         "array_rank": 0.0,
1781                         "attributes": {
1782                             "config": false,
1783                             "navigation": false,
1784                             "no_user_modify": false,
1785                             "no_user_view": false,
1786                             "required": false,
1787                             "state": false
1788                         },
1789                         "id": 0.0,
1790                         "type": "String"
1791                     }
1792                 },
1793                 "name": "Object",
1794                 "plural_name": "Objects",
1795                 "prototype_keys": [
1796                     "clone",
1797                     "notify_attribute",
1798                     "to_string"
1799                 ]
1800             }
1801         ]
1802     }
1803
1804
1805 ## Console <a id="icinga2-api-console"></a>
1806
1807 You can inspect variables and execute other expressions by sending a `POST` request to the URL endpoint `/v1/console/execute-script`.
1808 In order to receive auto-completion suggestions, send a `POST` request to the URL endpoint `/v1/console/auto-complete-script`.
1809
1810 The following parameters need to be specified (either as URL parameters or in a JSON-encoded message body):
1811
1812   Parameter  | Type         | Description
1813   -----------|--------------|-------------
1814   session    | String       | **Optional.** The session ID. Ideally this should be a GUID or some other unique identifier.
1815   command    | String       | **Required.** Command expression for execution or auto-completion.
1816   sandboxed  | Number       | **Optional.** Whether runtime changes are allowed or forbidden. Defaults to disabled.
1817
1818 The [API permission](12-icinga2-api.md#icinga2-api-permissions) `console` is required for executing
1819 expressions.
1820
1821 > **Note**
1822 >
1823 > Runtime modifications via `execute-script` calls are not validated and might cause the Icinga 2
1824 > daemon to crash or behave in an unexpected way. Use these runtime changes at your own risk.
1825
1826 If you specify a session identifier, the same script context can be reused for multiple requests. This allows you to, for example, set a local variable in a request and use that local variable in another request. Sessions automatically expire after a set period of inactivity (currently 30 minutes).
1827
1828 Example for fetching the command line from the local host's last check result:
1829
1830     $ 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'
1831     {
1832         "results": [
1833             {
1834                 "code": 200.0,
1835                 "result": [
1836                     "/usr/local/sbin/check_ping",
1837                     "-H",
1838                     "127.0.0.1",
1839                     "-c",
1840                     "5000,100%",
1841                     "-w",
1842                     "3000,80%"
1843                 ],
1844                 "status": "Executed successfully."
1845             }
1846         ]
1847     }
1848
1849 Example for fetching auto-completion suggestions for the `Host.` type. This works in a
1850 similar fashion when pressing TAB inside the [console CLI command](11-cli-commands.md#cli-command-console):
1851
1852     $ 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'
1853     {
1854         "results": [
1855             {
1856                 "code": 200.0,
1857                 "status": "Auto-completed successfully.",
1858                 "suggestions": [
1859                     "Host.type",
1860                     "Host.name",
1861                     "Host.prototype",
1862                     "Host.base",
1863                     "Host.register_attribute_handler",
1864                     "Host.clone",
1865                     "Host.notify_attribute",
1866                     "Host.to_string"
1867                 ]
1868             }
1869         ]
1870     }
1871
1872
1873 ## API Clients <a id="icinga2-api-clients"></a>
1874
1875 There are a couple of existing clients which can be used with the Icinga 2 API:
1876
1877 * [curl](https://curl.haxx.se/) or any other HTTP client really
1878 * [Icinga 2 console (CLI command)](12-icinga2-api.md#icinga2-api-clients-cli-console)
1879 * [Icinga Web 2 Director](https://icinga.com/products/icinga-web-2-modules/)
1880
1881 Demo cases:
1882
1883 * [Dashing](https://github.com/Icinga/dashing-icinga2)
1884 * [API examples](https://github.com/Icinga/icinga2-api-examples)
1885
1886 Additional [programmatic examples](12-icinga2-api.md#icinga2-api-clients-programmatic-examples)
1887 will help you getting started using the Icinga 2 API in your environment.
1888
1889 ### Icinga 2 Console <a id="icinga2-api-clients-cli-console"></a>
1890
1891 By default the [console CLI command](11-cli-commands.md#cli-command-console) evaluates
1892 expressions in a local interpreter, i.e. independently from your Icinga 2 daemon.
1893 Add the `--connect` parameter to debug and evaluate expressions via the API.
1894
1895 ### API Clients Programmatic Examples <a id="icinga2-api-clients-programmatic-examples"></a>
1896
1897 The programmatic examples use HTTP basic authentication and SSL certificate
1898 verification. The CA file is expected in `pki/icinga2-ca.crt`
1899 but you may adjust the examples for your likings.
1900
1901 The [request method](icinga2-api-requests) is `POST` using
1902 [X-HTTP-Method-Override: GET](12-icinga2-api.md#icinga2-api-requests-method-override)
1903 which allows you to send a JSON request body. The examples request
1904 specific service attributes joined with host attributes. `attrs`
1905 and `joins` are therefore specified as array.
1906 The `filter` attribute [matches](18-library-reference.md#global-functions-match)
1907 on all services with `ping` in their name.
1908
1909 #### Example API Client in Python <a id="icinga2-api-clients-programmatic-examples-python"></a>
1910
1911 The following example uses **Python** and the `requests` and `json` module:
1912
1913     # pip install requests
1914     # pip install json
1915
1916     $ vim icinga2-api-example.py
1917
1918     #!/usr/bin/env python
1919     
1920     import requests, json
1921     
1922     # Replace 'localhost' with your FQDN and certificate CN
1923     # for SSL verification
1924     request_url = "https://localhost:5665/v1/objects/services"
1925     headers = {
1926             'Accept': 'application/json',
1927             'X-HTTP-Method-Override': 'GET'
1928             }
1929     data = {
1930             "attrs": [ "name", "state", "last_check_result" ],
1931             "joins": [ "host.name", "host.state", "host.last_check_result" ],
1932             "filter": "match(\"ping*\", service.name)",
1933     }
1934     
1935     r = requests.post(request_url,
1936             headers=headers,
1937             auth=('root', 'icinga'),
1938             data=json.dumps(data),
1939             verify="pki/icinga2-ca.crt")
1940     
1941     print "Request URL: " + str(r.url)
1942     print "Status code: " + str(r.status_code)
1943     
1944     if (r.status_code == 200):
1945             print "Result: " + json.dumps(r.json())
1946     else:
1947             print r.text
1948             r.raise_for_status()
1949
1950     $ python icinga2-api-example.py
1951
1952
1953 #### Example API Client in Ruby <a id="icinga2-api-clients-programmatic-examples-ruby"></a>
1954
1955 The following example uses **Ruby** and the `rest_client` gem:
1956
1957     # gem install rest_client
1958
1959     $ vim icinga2-api-example.rb
1960
1961     #!/usr/bin/ruby
1962     
1963     require 'rest_client'
1964     
1965     # Replace 'localhost' with your FQDN and certificate CN
1966     # for SSL verification
1967     request_url = "https://localhost:5665/v1/objects/services"
1968     headers = {
1969             "Accept" => "application/json",
1970             "X-HTTP-Method-Override" => "GET"
1971     }
1972     data = {
1973             "attrs" => [ "name", "state", "last_check_result" ],
1974             "joins" => [ "host.name", "host.state", "host.last_check_result" ],
1975             "filter" => "match(\"ping*\", service.name)",
1976     }
1977     
1978     r = RestClient::Resource.new(
1979             URI.encode(request_url),
1980             :headers => headers,
1981             :user => "root",
1982             :password => "icinga",
1983             :ssl_ca_file => "pki/icinga2-ca.crt")
1984     
1985     begin
1986             response = r.post(data.to_json)
1987     rescue => e
1988             response = e.response
1989     end
1990     
1991     puts "Status: " + response.code.to_s
1992     if response.code == 200
1993             puts "Result: " + (JSON.pretty_generate JSON.parse(response.body))
1994     else
1995             puts "Error: " + response
1996     end
1997
1998     $ ruby icinga2-api-example.rb
1999
2000 A more detailed example can be found in the [Dashing demo](https://github.com/Icinga/dashing-icinga2).
2001
2002 #### Example API Client in PHP <a id="icinga2-api-clients-programmatic-examples-php"></a>
2003
2004 The following example uses **PHP** and its `curl` library:
2005
2006     $ vim icinga2-api-example.php
2007
2008     #!/usr/bin/env php
2009     <?php
2010     # Replace 'localhost' with your FQDN and certificate CN
2011     # for SSL verification
2012     $request_url = "https://localhost:5665/v1/objects/services";
2013     $username = "root";
2014     $password = "icinga";
2015     $headers = array(
2016             'Accept: application/json',
2017             'X-HTTP-Method-Override: GET'
2018     );
2019     $data = array(
2020             attrs => array('name', 'state', 'last_check_result'),
2021             joins => array('host.name', 'host.state', 'host.last_check_result'),
2022             filter => 'match("ping*", service.name)',
2023     );
2024     
2025     $ch = curl_init();
2026     curl_setopt_array($ch, array(
2027             CURLOPT_URL => $request_url,
2028             CURLOPT_HTTPHEADER => $headers,
2029             CURLOPT_USERPWD => $username . ":" . $password,
2030             CURLOPT_RETURNTRANSFER => true,
2031             CURLOPT_CAINFO => "pki/icinga2-ca.crt",
2032             CURLOPT_POST => count($data),
2033             CURLOPT_POSTFIELDS => json_encode($data)
2034     ));
2035     
2036     $response = curl_exec($ch);
2037     if ($response === false) {
2038             print "Error: " . curl_error($ch) . "(" . $response . ")\n";
2039     }
2040     
2041     $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
2042     curl_close($ch);
2043     print "Status: " . $code . "\n";
2044     
2045     if ($code == 200) {
2046             $response = json_decode($response, true);
2047             print_r($response);
2048     }
2049     ?>
2050
2051     $ php icinga2-api-example.php
2052
2053 #### Example API Client in Perl <a id="icinga2-api-clients-programmatic-examples-perl"></a>
2054
2055 The following example uses **Perl** and the `Rest::Client` module:
2056
2057     # perl -MCPAN -e 'install REST::Client'
2058     # perl -MCPAN -e 'install JSON'
2059     # perl -MCPAN -e 'install MIME::Base64'
2060     # perl -MCPAN -e 'install Data::Dumper'
2061
2062     $ vim icinga2-api-example.pl
2063
2064     #!/usr/bin/env perl
2065     
2066     use strict;
2067     use warnings;
2068     use REST::Client;
2069     use MIME::Base64;
2070     use JSON;
2071     use Data::Dumper;
2072     
2073     # Replace 'localhost' with your FQDN and certificate CN
2074     # for SSL verification
2075     my $request_host = "https://localhost:5665";
2076     my $userpass = "root:icinga";
2077     
2078     my $client = REST::Client->new();
2079     $client->setHost($request_host);
2080     $client->setCa("pki/icinga2-ca.crt");
2081     $client->addHeader("Accept", "application/json");
2082     $client->addHeader("X-HTTP-Method-Override", "GET");
2083     $client->addHeader("Authorization", "Basic " . encode_base64($userpass));
2084     my %json_data = (
2085             attrs => ['name', 'state', 'last_check_result'],
2086             joins => ['host.name', 'host.state', 'host.last_check_result'],
2087             filter => 'match("ping*", service.name)',
2088     );
2089     my $data = encode_json(\%json_data);
2090     $client->POST("/v1/objects/services", $data);
2091     
2092     my $status = $client->responseCode();
2093     print "Status: " . $status . "\n";
2094     my $response = $client->responseContent();
2095     if ($status == 200) {
2096             print "Result: " . Dumper(decode_json($response)) . "\n";
2097     } else {
2098             print "Error: " . $response . "\n";
2099     }
2100
2101     $ perl icinga2-api-example.pl
2102