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