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