]> granicus.if.org Git - icinga2/blob - doc/9-icinga2-api.md
2717e20d76e94f381ea5ceb4399b64d9c2fa4613
[icinga2] / doc / 9-icinga2-api.md
1 # <a id="icinga2-api"></a> Icinga 2 API
2
3 ## <a id="icinga2-api-introduction"></a> Introduction
4
5 The Icinga 2 API allows you to manage configuration objects
6 and resources in a simple, programmatic way using HTTP requests.
7
8 The URL endpoints are logically separated allowing you to easily
9 make calls to
10
11 * run [actions](9-icinga2-api.md#icinga2-api-actions) (reschedule checks, etc.)
12 * query, create, modify and delete [config objects](9-icinga2-api.md#icinga2-api-config-objects)
13 * [manage configuration packages](9-icinga2-api.md#icinga2-api-config-management)
14 * subscribe to [event streams](9-icinga2-api.md#icinga2-api-event-streams)
15
16 This chapter will start with a general overview followed by
17 detailed information about specific URL endpoints.
18
19 ### <a id="icinga2-api-requests"></a> Requests
20
21 Any tool capable of making HTTP requests can communicate with
22 the API, for example [curl](http://curl.haxx.se).
23
24 Requests are only allowed to use the HTTPS protocol so that
25 traffic remains encrypted.
26
27 By default the Icinga 2 API listens on port `5665` which is shared with
28 the cluster stack. The port can be changed by setting the `bind_port` attribute
29 in the [ApiListener](6-object-types.md#objecttype-apilistener)
30 configuration object in the `/etc/icinga2/features-available/api.conf`
31 file.
32
33 Supported request methods:
34
35   Method | Usage
36   -------|--------
37   GET    | Retrieve information about configuration objects. Any request using the GET method is read-only and does not affect any objects.
38   POST   | Update attributes of a specified configuration object.
39   PUT    | Create a new object. The PUT request must include all attributes required to create a new object.
40   DELETE | Remove an object created by the API. The DELETE method is idempotent and does not require any check if the object actually exists.
41
42 Each URL contains the version string as prefix (currently "/v1").
43
44 Be prepared to see additional fields being added in future versions. New fields could be added even with minor releases.
45 Modifications to existing fields are considered backward-compatibility-breaking and will only take place in new API versions.
46
47 The request and response bodies contain a JSON-encoded object.
48
49 ### <a id="icinga2-api-http-statuses"></a> HTTP Statuses
50
51 The API will return standard [HTTP statuses](https://www.ietf.org/rfc/rfc2616.txt)
52 including error codes.
53
54 When an error occurs, the response body will contain additional information
55 about the problem and its source.
56
57 A status code between 200 and 299 generally means that the request was
58 succesful.
59
60 Return codes within the 400 range indicate that there was a problem with the
61 request. Either you did not authenticate correctly, you are missing the authorization
62 for your requested action, the requested object does not exist or the request
63 was malformed.
64
65 A status in the range of 500 generally means that there was a server-side problem
66 and Icinga 2 is unable to process your request currently.
67
68
69 ### <a id="icinga2-api-responses"></a> Responses
70
71 Succesful requests will send back a response body containing a `results`
72 list. Depending on the number of affected objects in your request, the
73 results may contain one or more entries.
74
75 The [output](9-icinga2-api.md#icinga2-api-output-format) will be sent back as a JSON object:
76
77
78     {
79         "results": [
80             {
81                 "code": 200.0,
82                 "status": "Object was created."
83             }
84         ]
85     }
86
87
88 ### <a id="icinga2-api-authentication"></a> Authentication
89
90 There are two different ways for authenticating against the Icinga 2 API:
91
92 * username and password using HTTP basic auth
93 * X.509 certificate
94
95 In order to configure a new API user you'll need to add a new [ApiUser](6-object-types.md#objecttype-apiuser)
96 configuration object. In this example `root` will be the basic auth username
97 and the `password` attribute contains the basic auth password.
98
99     # vim /etc/icinga2/conf.d/api-users.conf
100
101     object ApiUser "root" {
102       password = "icinga"
103     }
104
105 Alternatively you can use X.509 client certificates by specifying the `client_cn`
106 the API should trust. The X.509 certificate has to be signed by the CA certificate
107 that is configured in the [ApiListener](6-object-types.md#objecttype-apilistener) object.
108
109     # vim /etc/icinga2/conf.d/api-users.conf
110
111     object ApiUser "api-clientcn" {
112       password = "CertificateCommonName"
113     }
114
115 An `ApiUser` object can have both methods configured. Sensitive information
116 such as the password will not be exposed through the API itself.
117
118 New installations of Icinga 2 will automatically set up a new `ApiUser`
119 named `root` with an auto-generated password in the `/etc/icinga2/conf.d/api-users.conf`
120 file.
121
122 You can manually invoke the CLI command `icinga2 api setup` which will generate
123 a new local CA, self-signed certificate and a new API user configuration.
124
125 Once the API user is configured make sure to restart Icinga 2:
126
127     # service icinga2 restart
128
129 You can test authentication by sending a GET request to the API:
130
131     $ curl -u root:icinga -k -s 'https://localhost:5665/v1'
132
133 In case you get an error message make sure to check the API user credentials.
134
135
136 ### <a id="icinga2-api-permissions"></a> Permissions
137
138 By default an API user does not have any permissions to perform
139 actions on the [URL endpoints](9-icinga2-api.md#icinga2-api-url-endpoints).
140
141 Permissions for API users must be specified in the `permissions` attribute
142 as array. The array items can be a list of permission strings with wildcard
143 matches.
144
145 Example for an API user with all permissions:
146
147     permissions = [ "*" ]
148
149 A yet more sophisticated approach is to specify additional permissions
150 and their filters. The latter must be defined as [lamdba function](20-language-reference.md#nullary-lambdas)
151 returning a boolean expression.
152
153 The `permission` attribute contains the action and the specific capitalized
154 object type name. Instead of the type name it is also possible to use a wildcard
155 match.
156
157 The following example allows the API user to query all hosts and services with
158 the custom host attribute `os` matching the regular expression `^Linux`.
159
160     permissions = [
161       {
162         permission = "objects/query/Host"
163         filter = {{ regex("^Linux", host.vars.os)  }}
164       },
165       {
166         permission = "objects/query/Service"
167         filter = {{ regex("^Linux", host.vars.os)  }}
168       },
169     ]
170
171
172 Available permissions for specific URL endpoints:
173
174   Permissions                   | URL Endpoint
175   ------------------------------|---------------
176   actions/&lt;action&gt;        | /v1/actions
177   config/query                  | /v1/config
178   config/modify                 | /v1/config
179   objects/query/&lt;type&gt;    | /v1/objects
180   objects/create/&lt;type&gt;   | /v1/objects
181   objects/modify/&lt;type&gt;   | /v1/objects
182   objects/delete/&lt;type&gt;   | /v1/objects
183   status/query                  | /v1/status
184   events/&lt;type&gt;           | /v1/events
185
186 The required actions or types can be replaced by using a wildcard match ("*").
187
188
189 ### <a id="icinga2-api-parameters"></a> Parameters
190
191 Depending on the request method there are two ways of
192 passing parameters to the request:
193
194 * JSON body (`POST`, `PUT`)
195 * Query string (`GET`, `DELETE`)
196
197 Reserved characters by the HTTP protocol must be passed url-encoded as query string, e.g. a
198 space becomes `%20`.
199
200 Example for a query string:
201
202     /v1/objects/hosts?filter=match(%22nbmif*%22,host.name)&attrs=host.name&attrs=host.state
203
204 Example for a JSON body:
205
206     { "attrs": { "address": "8.8.4.4", "vars.os" : "Windows" } }
207
208
209 #### <a id="icinga2-api-filters"></a> Filters
210
211 Uses the same syntax as apply rule expressions for filtering specific objects.
212
213 Example for a filter matching all services in NOT-OK state:
214
215     https://localhost:5665/v1/objects/services?filter=service.state!=ServiceOK
216
217 Example for a filter matching all hosts by name (**Note**: `"` are url-encoded as `%22`):
218
219     https://localhost:5665/v1/objects/hosts?filter=match(%22nbmif*%22,host.name)
220
221 ### <a id="icinga2-api-url-endpoints"></a> URL Endpoints
222
223 The Icinga 2 API provides multiple URL endpoints:
224
225   URL Endpoints | Description
226   --------------|--------------
227   /v1/actions   | Endpoint for running specific [API actions](9-icinga2-api.md#icinga2-api-actions).
228   /v1/events    | Endpoint for subscribing to [API events](9-icinga2-api.md#icinga2-api-actions).
229   /v1/status    | Endpoint for receiving the global Icinga 2 [status and statistics](9-icinga2-api.md#icinga2-api-status).
230   /v1/objects   | Endpoint for querying, creating, modifying and deleting [config objects](9-icinga2-api.md#icinga2-api-config-objects).
231   /v1/types     | Endpoint for listing Icinga 2 configuration object types and their attributes.
232   /v1/config    | Endpoint for [managing configuration modules](9-icinga2-api.md#icinga2-api-config-management).
233
234 Please check the respective sections for detailed URL information and parameters.
235
236 ## <a id="icinga2-api-actions"></a> Actions
237
238 There are several actions available for Icinga 2 provided by the `actions`
239 URL endpoint `/v1/actions`. You can run actions by sending a `POST` request.
240
241 In case you have been using the [external commands](5-advanced-topics.md#external-commands)
242 in the past, the API actions provide a similar interface with filter
243 capabilities for some of the more common targets which do not directly change
244 the configuration.
245
246 Some actions require specific target types (e.g. `type=Host`) and a
247 [filter expression](9-icinga2-api.md#icinga2-api-filters).
248 For each object matching the filter the action in question is performed once.
249
250 These parameters may either be passed as an URL query string (e.g. url/actions/action-name?list=of&parameters)
251 or as key-value pairs in a JSON-formatted payload or a mix of both.
252
253 All actions return a 200 `OK` or an appropriate error code for each
254 action performed on each object matching the supplied filter.
255
256 ### <a id="icinga2-api-actions-process-check-result"></a> process-check-result
257
258 Send a `POST` request to the URL endpoint `/v1/actions/process-check-result`.
259
260   Parameter         | Type         | Description
261   ------------------|--------------|--------------
262   type              | string       | **Required.** `Host` or `Service`.
263   filter            | string       | **Optional.** Apply the action only to objects matching the [filter](9-icinga2-api#icinga2-api-filters).
264   exit\_status      | integer      | **Required.** For services: 0=OK, 1=WARNING, 2=CRITICAL, 3=UNKNOWN, for hosts: 0=OK, 1=CRITICAL.
265   plugin\_output    | string       | **Required.** The plugins main output, i.e. the text before the `|`. Does **not** contain the perfomance data.
266   performance\_data | string array | **Optional.** One array entry per `;` separated block.
267   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.
268   check\_source     | string       | **Optional.** Usually the name of the `command_endpoint`
269
270 This is used to submit a passive check result for a service or host. Passive
271 checks need to be enabled for the check result to be processed.
272
273 Example:
274
275     $ curl -u root:icinga -k -X POST "https://localhost:5665/v1/actions/process-check-result?type=Service&filter=service.name==%22ping6%22" -d \
276     "{\"exit_status\":2,\"plugin_output\":\"IMAGINARY CHECK\",\"performance_data\":[\"This is just\", \"a drill\"],\"check_command\":[\"some/path\", \"--argument\", \"words\"]}" \
277     ;echo
278     {"results":
279       [
280         {
281           "code":200.0,"status":"Successfully processed check result for object icinga!ping6."
282         }
283       ]
284     }
285
286 ### <a id="icinga2-api-actions-reschedule-check"></a> reschedule-check
287
288 Send a `POST` request to the URL endpoint `/v1/actions/reschedule-check`.
289
290   Parameter    | Type      | Description
291   -------------|-----------|--------------
292   type         | string    | **Required.** `Host` or `Service`.
293   filter       | string    | **Optional.** Apply the action only to objects matching the [filter](9-icinga2-api#icinga2-api-filters).
294   next\_check  | timestamp | **Optional.** The next check will be run at this timestamp. Defaults to `now`.
295   force\_check | boolean   | **Optional.** Defaults to `false`. See blow for further information.
296
297 If the `forced_check` flag is set the checks are performed regardless of what
298 time it is (i.e. time period restrictions are ignored) and whether or not active
299 checks are enabled on a host/service-specific or program-wide basis.
300
301 Example:
302
303     $ curl -u root:icinga -k -X POST "https://localhost:5665/v1/actions/reschedule-check?type=Service&filter=service.name==%22ping6%22" -d \
304     "{\"force_check\":true}"
305
306     {"results":
307       [
308         {
309           "code":200.0,"status":"Successfully rescheduled check for icinga!ping6."
310         }
311       ]
312     }
313
314 This will reschedule all services with the name "ping6" to perform a check now
315 (`next_check` default), ignoring any time periods or whether active checks are
316 allowed for the service (`force_check=true`).
317
318 ### <a id="icinga2-api-actions-send-custom-notification"></a> send-custom-notification
319
320 Send a `POST` request to the URL endpoint `/v1/actions/send-custom-notification`.
321
322   Parameter | Type    | Description
323   ----------|---------|--------------
324   type      | string  | **Required.** `Host` or `Service`.
325   filter    | string  | **Optional.** Apply the action only to objects matching the [filter](9-icinga2-api#icinga2-api-filters).
326   author    | string  | **Required.** Name of the author, may be empty.
327   comment   | string  | **Required.** Comment text, may be empty.
328   force     | boolean | **Optional.** Default: false. If true, the notification is sent regardless of downtimes or whether notifications are enabled or not.
329
330 ### <a id="icinga2-api-actions-delay-notification"></a> delay-notification
331
332 Send a `POST` request to the URL endpoint `/v1/actions/delay-notification`.
333
334   Parameter | Type      | Description
335   ----------|-----------|--------------
336   type      | string    | **Required.** `Host` or `Service`.
337   filter    | string    | **Optional.** Apply the action only to objects matching the [filter](9-icinga2-api#icinga2-api-filters).
338   timestamp | timestamp | **Required.** Delay notifications until this timestamp.
339
340 Note that this will only have an effect if the service stays in the same problem
341 state that it is currently in. If the service changes to another state, a new
342 notification may go out before the time you specify in the `timestamp` argument.
343
344 ### <a id="icinga2-api-actions-acknowledge-problem"></a> acknowledge-problem
345
346 Send a `POST` request to the URL endpoint `/v1/actions/acknowledge-problem`.
347
348   Parameter | Type      | Description
349   ----------|-----------|--------------
350   type      | string     | **Required.** `Host` or `Service`.
351   filter    | string    | **Optional.** Apply the action only to objects matching the [filter](9-icinga2-api#icinga2-api-filters).
352   author    | string    | **Required.** Name of the author, may be empty.
353   comment   | string    | **Required.** Comment text, may be empty.
354   expiry    | timestamp | **Optional.** If set the acknowledgement will vanish after this timestamp.
355   sticky    | boolean   | **Optional.** If `true`, the default, the acknowledgement will remain until the service or host fully recovers.
356   notify    | boolean   | **Optional.** If `true` a notification will be sent out to contacts to indicate this problem has been acknowledged. The default is false.
357
358 Allows you to acknowledge the current problem for hosts or services. By
359 acknowledging the current problem, future notifications (for the same state)
360 are disabled.
361
362 The following example acknowledges all services which are in a hard critical state and sends out
363 a notification for them:
364
365     $ curl -u root:icinga -k -X POST "https://localhost:5665/v1/actions/acknowledge-problem?type=Service&filter=service.state==2&service.state_type=1" -d \
366     "{\"author\":\"J. D. Salinger\",\"comment\":\"I thought what I'd do was I'd pretend I was one of those deaf-mutes\",\"notify\":true }"
367
368     {"results":
369       [
370         {"code":200.0,"name":"icinga!down","status":"Attributes updated.","type":"Service"},
371         {"code":200.0,"name":"icinga!ssh","status":"Attributes updated.","type":"Service"}
372       ]
373     }
374
375 ### <a id="icinga2-api-actions-remove-acknowledgement"></a> remove-acknowledgement
376
377 Send a `POST` request to the URL endpoint `/v1/actions/remove-acknowledgement`.
378
379   parameter | type   | description
380   ----------|--------|--------------
381   type      | string | **Required.** `Host` or `Service`.
382   filter    | string | **Optional.** Apply the action only to objects matching the [filter](9-icinga2-api#icinga2-api-filters).
383
384 Remove the acknowledgements for services or hosts. Once the acknowledgement has
385 been removed notifications will be sent out again.
386
387 ### <a id="icinga2-api-actions-add-comment"></a> add-comment
388
389 Send a `POST` request to the URL endpoint `/v1/actions/add-comment`.
390
391   parameter | type   | description
392   ----------|--------|--------------
393   type      | string | **Required.** `Host` or `Service`.
394   filter    | string | **Optional.** Apply the action only to objects matching the [filter](9-icinga2-api#icinga2-api-filters).
395   author    | string | **Required.** name of the author, may be empty.
396   comment   | string | **Required.** Comment text, may be empty.
397
398 Adds a `comment` by `author` to services or hosts.
399
400 ### <a id="icinga2-api-actions-remove-all-comments"></a> remove-all-comments
401
402 Send a `POST` request to the URL endpoint `/v1/actions/remove-all-comments`.
403
404   parameter   | type    | description
405   ------------|---------|--------------
406   type        | string  | **Required.** `Host` or `Service`.
407   filter      | string  | **Optional.** Apply the action only to objects matching the [filter](9-icinga2-api#icinga2-api-filters).
408
409 Removes all comments for services or hosts.
410
411 ### <a id="icinga2-api-actions-remove-comment-by-id"></a> remove-comment-by-id
412
413 Send a `POST` request to the URL endpoint `/v1/actions/remove-comment-by-id`.
414
415   parameter   | type    | description
416   ------------|---------|--------------
417   comment\_id | integer | **Required.** ID of the comment to remove.
418
419 Does not support a target type or filters.
420
421 Tries to remove the comment with the ID `comment_id`, returns `OK` if the
422 comment did not exist.
423 **Note**: This is **not** the legacy ID but the comment ID returned by Icinga 2 itself.
424
425 ### <a id="icinga2-api-actions-schedule-downtime"></a> schedule-downtime
426
427 Send a `POST` request to the URL endpoint `/v1/actions/schedule-downtime`.
428
429   parameter   | type      | description
430   ------------|-----------|--------------
431   type        | string    | **Required.** `Host` or `Service`.
432   filter      | string    | **Optional.** Apply the action only to objects matching the [filter](9-icinga2-api#icinga2-api-filters).
433   start\_time | timestamp | **Required.** Timestamp marking the begining of the downtime.
434   end\_time   | timestamp | **Required.** Timestamp marking the end of the downtime.
435   duration    | integer   | **Required.** Duration of the downtime in seconds if `fixed` is set to false.
436   fixed       | boolean   | **Optional.** Defaults to `false`. If true the downtime is `fixed` otherwise `flexible`. See [downtimes](5-advanced-topics.md#Downtimes) for more information.
437   trigger\_id | integer   | **Optional.** Sets the trigger for a triggered downtime. See [downtimes](5-advanced-topics.md#Downtimes) for more information on triggered downtimes.
438
439 Example:
440
441     $ curl -u root:icinga -k -X POST "https://localhost:5665/v1/actions/schedule-downtime?type=Host&filter=host.name=%22icinga2b%22" -d \
442     "{\"start_time\":`date "+%s"`, \"end_time\":`date --date="next monday" "+%s"`,\"duration\":0,\"author\":\"Lazy admin\",\"comment\":\"Don't care until next monday\"}"
443
444     { "results":
445       [
446         {
447           "code":200.0,
448           "downtime_id":"icinga2b-1445861488-1",
449           "legacy_id":39.0,
450           "status":"Successfully scheduled downtime with id 39 for object icinga2b."
451         }
452       ]
453     }
454
455
456 ### <a id="icinga2-api-actions-remove-downtime"></a> remove-downtime
457
458 Send a `POST` request to the URL endpoint `/v1/actions/remove-all-downtimes`.
459
460   parameter | type   | description
461   ----------|--------|--------------
462   type      | string | **Required.** `Host` or `Service`.
463   filter    | string | **Optional.** Apply the action only to objects matching the [filter](9-icinga2-api#icinga2-api-filters).
464
465 Removes all downtimes for services or hosts.
466
467 ### <a id="icinga2-api-actions-remove-downtime-by-id"></a> remove-downtime-by-id
468
469 Send a `POST` request to the URL endpoint `/v1/actions/remove-downtime-by-id`.
470
471   parameter    | type    | description
472   -------------|---------|--------------
473   downtime\_id | integer | **Required.** ID of the downtime to remove.
474
475 Does not support a target type or filter.
476
477 Tries to remove the downtime with the ID `downtime_id`, returns `OK` if the
478 downtime did not exist.
479 **Note**: This is **not** the legacy ID but the downtime ID returned by Icinga 2 itself.
480
481 ### <a id="icinga2-api-actions-shutdown-process"></a> shutdown-process
482
483 Send a `POST` request to the URL endpoint `/v1/actions/shutdown-process`.
484
485 This action does not support a target type or filter.
486
487 Shuts down Icinga2. May or may not return.
488
489 ### <a id="icinga2-api-actions-restart-process"></a> restart-process
490
491 Send a `POST` request to the URL endpoint `/v1/actions/restart-process`.
492
493 This action does not support a target type or filter.
494
495 Restarts Icinga2. May or may not return.
496
497
498 ## <a id="icinga2-api-event-streams"></a> Event Streams
499
500 You can subscribe to event streams by sending a `POST` request to the URL endpoint `/v1/events`.
501 The following parameters need to be passed as URL parameters:
502
503   Parameters | Description
504   -----------|--------------
505   types      | **Required.** Event type(s). Multiple types as URL parameters are supported.
506   queue      | **Required.** Unique queue name. Multiple HTTP clients can use the same queue with existing filters.
507   filter     | **Optional.** Filter for specific event attributes using [filter expressions](9-icinga2-api.md#icinga2-api-filters).
508
509
510 ### <a id="icinga2-api-event-streams-types"></a> Event Stream Types
511
512 The following event stream types are available:
513
514   Type                   | Description
515   -----------------------|--------------
516   CheckResult            | Check results for hosts and services.
517   StateChange            | Host/service state changes.
518   Notification           | Notification events including notified users for hosts and services.
519   AcknowledgementSet     | Acknowledgement set on hosts and services.
520   AcknowledgementCleared | Acknowledgement cleared on hosts and services.
521   CommentAdded           | Comment added for hosts and services.
522   CommentRemoved         | Comment removed for hosts and services.
523   DowntimeAdded          | Downtime added for hosts and services.
524   DowntimeRemoved        | Downtime removed for hosts and services.
525   DowntimeTriggered      | Downtime triggered for hosts and services.
526
527 Note: Each type requires [api permissions](9-icinga2-api.md#icinga2-api-permissions)
528 being set.
529
530 Example for all downtime events:
531
532     &types=DowntimeAdded&types=DowntimeRemoved&types=DowntimeTriggered
533
534
535 ### <a id="icinga2-api-event-streams-filter"></a> Event Stream Filter
536
537 Event streams can be filtered by attributes using the prefix `event.`.
538
539 Example for the `CheckResult` type with the `exit_code` set to `2`:
540
541     &types=CheckResult&filter=event.check_result.exit_status==2
542
543 Example for the `CheckResult` type with the service matching the string "random":
544
545     &types=CheckResult&filter=match%28%22random*%22,event.service%29
546
547
548 ### <a id="icinga2-api-event-streams-response"></a> Event Stream Response
549
550 The event stream response is separated with new lines. The HTTP client
551 must support long-polling and HTTP/1.1. HTTP/1.0 is not supported.
552
553 Example:
554
555     $ curl -k -s -u root:icinga -X POST 'https://localhost:5665/v1/events?queue=michi&types=CheckResult&filter=event.check_result.exit_status==2'
556
557     {"check_result":{ ... },"host":"www.icinga.org","service":"ping4","timestamp":1445421319.7226390839,"type":"CheckResult"}
558     {"check_result":{ ... },"host":"www.icinga.org","service":"ping4","timestamp":1445421324.7226390839,"type":"CheckResult"}
559     {"check_result":{ ... },"host":"www.icinga.org","service":"ping4","timestamp":1445421329.7226390839,"type":"CheckResult"}
560
561
562 ## <a id="icinga2-api-status"></a> Status and Statistics
563
564 Send a `POST` request to the URL endpoint `/v1/status` for retrieving the
565 global status and statistics.
566
567 Contains a list of sub URL endpoints which provide the status and statistics
568 of available and enabled features. Any filters are ignored.
569
570 Example for the main URL endpoint `/v1/status`:
571
572     $ curl -k -s -u root:icinga 'https://localhost:5665/v1/status' | python -m json.tool
573     {
574         "results": [
575             {
576                 "name": "ApiListener",
577                 "perfdata": [ ... ],
578                 "status": [ ... ]
579             },
580             ...
581             {
582                 "name": "IcingaAplication",
583                 "perfdata": [ ... ],
584                 "status": [ ... ]
585             },
586             ...
587         ]
588     }
589
590 `/v1/status` is always available as virtual status URL endpoint.
591 It provides all feature status information in a collected overview.
592
593 Example for the icinga application URL endpoint `/v1/status/IcingaApplication`:
594
595     $ curl -k -s -u root:icinga 'https://localhost:5665/v1/status/IcingaApplication' | python -m json.tool
596     {
597         "results": [
598             {
599                 "perfdata": [],
600                 "status": {
601                     "icingaapplication": {
602                         "app": {
603                             "enable_event_handlers": true,
604                             "enable_flapping": true,
605                             "enable_host_checks": true,
606                             "enable_notifications": true,
607                             "enable_perfdata": true,
608                             "enable_service_checks": true,
609                             "node_name": "icinga.org",
610                             "pid": 59819.0,
611                             "program_start": 1443019345.093372,
612                             "version": "v2.3.0-573-g380a131"
613                         }
614                     }
615                 }
616             }
617         ]
618     }
619
620
621 ## <a id="icinga2-api-config-objects"></a> Config Objects
622
623 Provides functionality for all configuration object URL endpoints
624 provided by [config object types](6-object-types.md#object-types):
625
626   URL Endpoints                    | Description
627   ---------------------------------|--------------
628   /v1/objects/hosts                | Endpoint for retrieving and updating [Host](6-object-types.md#objecttype-host) objects.
629   /v1/objects/services             | Endpoint for retrieving and updating [Service](6-object-types.md#objecttype-service) objects.
630   /v1/objects/notifications        | Endpoint for retrieving and updating [Notification](6-object-types.md#objecttype-notification) objects.
631   /v1/objects/dependencies         | Endpoint for retrieving and updating [Dependency](6-object-types.md#objecttype-dependency) objects.
632   /v1/objects/users                | Endpoint for retrieving and updating [User](6-object-types.md#objecttype-user) objects.
633   /v1/objects/checkcommands        | Endpoint for retrieving and updating [CheckCommand](6-object-types.md#objecttype-checkcommand) objects.
634   /v1/objects/eventcommands        | Endpoint for retrieving and updating [EventCommand](6-object-types.md#objecttype-eventcommand) objects.
635   /v1/objects/notificationcommands | Endpoint for retrieving and updating [NotificationCommand](6-object-types.md#objecttype-notificationcommand) objects.
636   /v1/objects/hostgroups           | Endpoint for retrieving and updating [HostGroup](6-object-types.md#objecttype-hostgroup) objects.
637   /v1/objects/servicegroups        | Endpoint for retrieving and updating [ServiceGroup](6-object-types.md#objecttype-servicegroup) objects.
638   /v1/objects/usergroups           | Endpoint for retrieving and updating [UserGroup](6-object-types.md#objecttype-usergroup) objects.
639   /v1/objects/zones                | Endpoint for retrieving and updating [Zone](6-object-types.md#objecttype-zone) objects.
640   /v1/objects/endpoints            | Endpoint for retrieving and updating [Endpoint](6-object-types.md#objecttype-endpoint) objects.
641   /v1/objects/timeperiods          | Endpoint for retrieving and updating [TimePeriod](6-object-types.md#objecttype-timeperiod) objects.
642
643 All object attributes are prefixed with their respective object type.
644
645 Example:
646
647     host.address
648
649 Output listing and url parameters use the same syntax.
650
651
652 ### <a id="icinga2-api-config-objects-joins"></a> API Objects and Joins
653
654 Icinga 2 knows about object relations, i.e. when querying a service object
655 the query handler will automatically add the referenced host object and its
656 attributes to the result set. If the object reference is null (e.g. when no
657 event\_command is defined), the joined results not added to the result set.
658
659 **Note**: Select your required attributes beforehand by passing them to your
660 request. The default result set might get huge.
661
662 Each joined object will use its own attribute name as prefix for the attribute.
663 There is an exception for multiple objects used in dependencies and zones.
664
665 Objects with optional relations (e.g. host notifications without a service)
666 will not be joined.
667
668   Object Type  | Object Relations (prefix name)
669   -------------|---------------------------------
670   Service      | host, notification, check\_command, event\_command
671   Host         | notification, check\_command, event\_command
672   Notification | host, service, command, period
673   Dependency   | child\_host, child\_service, parent\_host, parent\_service, period
674   User         | period
675   Zones        | parent
676
677
678 ### <a id="icinga2-api-config-objects-cluster-sync"></a> API Objects and Cluster Config Sync
679
680 Newly created or updated objects can be synced throughout your
681 Icinga 2 cluster. Set the `zone` attribute to the zone this object
682 belongs to and let the API and cluster handle the rest.
683 Objects without zone attribute are only synced in the same (HA) zone.
684
685 > **Note**
686 >
687 > Cluster nodes must accept configuration for creating, modifying
688 > and deleting objects. Ensure that `accept_config` is set to `true`
689 > in the [ApiListener](6-object-types.md#objecttype-apilistener) object
690 > on each node.
691
692 If you add a new cluster instance, or boot an instance which has been offline
693 for a while, Icinga 2 takes care of the initial object sync for all objects
694 created by the API.
695
696 More information about distributed monitoring, cluster and its
697 configuration can be found [here](13-distributed-monitoring-ha.md#distributed-monitoring-high-availability).
698
699
700 ### <a id="icinga2-api-config-objects-list"></a> List All Objects
701
702 Send a `GET` request to `/v1/objects/hosts` to list all host objects and
703 their attributes.
704
705     $ curl -u root:icinga -k -s 'https://localhost:5665/v1/objects/hosts'
706
707 This works in a similar fashion for other [config objects](9-icinga2-api.md#icinga2-api-config-objects).
708
709
710 #### <a id="icinga2-api-objects-create"></a> Create New Config Object
711
712 New objects must be created by sending a PUT request. The following
713 parameters need to be passed inside the JSON body:
714
715   Parameters | Description
716   -----------|--------------
717   name       | **Required.** Name of the newly created config object.
718   templates  | **Optional.** Import existing configuration templates for this object type.
719   attrs      | **Required.** Set specific object attributes for this [object type](6-object-types.md#object-types).
720
721
722 If attributes are of the Dictionary type, you can also use the indexer format:
723
724     "attrs": { "vars.os": "Linux" }
725
726 Example fo creating the new host object `google.com`:
727
728     $ curl -u root:icinga -k -s 'https://localhost:5665/v1/objects/hosts/google.com' \
729     -X PUT \
730     -d '{ "templates": [ "generic-host" ], "attrs": { "address": "8.8.8.8", "check_command": "hostalive", "vars.os" : "Linux" } }' \
731     | python -m json.tool
732     {
733         "results": [
734             {
735                 "code": 200.0,
736                 "status": "Object was created."
737             }
738         ]
739     }
740
741 **Note**: Host objects require the `check_command` attribute.
742
743 If the configuration validation fails, the new object will not be created and the response body
744 contains a detailed error message. The following example omits the `check_command` attribute required
745 by the host object.
746
747     $ curl -u root:icinga -k -s 'https://localhost:5665/v1/objects/hosts/google.com' \
748     -X PUT \
749     -d '{ "attrs": { "address": "8.8.8.8", "vars.os" : "Linux" } }' \
750     | python -m json.tool
751     {
752         "results": [
753             {
754                 "code": 500.0,
755                 "errors": [
756                     "Error: Validation failed for object 'google.com' of type 'Host'; Attribute 'check_command': Attribute must not be empty."
757                 ],
758                 "status": "Object could not be created."
759             }
760         ]
761     }
762
763
764 #### <a id="icinga2-api-object-query"></a> Query Object
765
766 Send a `GET` request including the object name inside the URL.
767
768 Example for the host `google.com`:
769
770     $ curl -u root:icinga -k -s 'https://localhost:5665/v1/objects/hosts/google.com'
771
772 You can select specific attributes by adding them as url parameters using `?attrs=...`. Multiple
773 attributes must be added one by one, e.g. `?attrs=host.address&attrs=host.name`.
774
775     $ curl -u root:icinga -k -s 'https://localhost:5665/v1/objects/hosts/google.com?attrs=host.name&attrs=host.address' | python -m json.tool
776     {
777         "results": [
778             {
779                 "attrs": {
780                     "host.address": "8.8.8.8",
781                     "host.name": "google.com"
782                 }
783             }
784         ]
785     }
786
787
788 #### <a id="icinga2-api-objects-modify"></a> Modify Object
789
790 Existing objects must be modified by sending a `POST` request. The following
791 parameters need to be passed inside the JSON body:
792
793   Parameters | Description
794   -----------|--------------
795   name       | **Optional.** If not specified inside the url, this is **Required.**.
796   templates  | **Optional.** Import existing object configuration templates.
797   attrs      | **Required.** Set specific object attributes for this [object type](6-object-types.md#object-types).
798
799
800 If attributes are of the Dictionary type, you can also use the indexer format:
801
802     "attrs": { "vars.os": "Linux" }
803
804
805 Example for existing object `google.com`:
806
807     $ curl -u root:icinga -k -s 'https://localhost:5665/v1/objects/hosts/google.com' \
808     -X POST \
809     -d '{ "attrs": { "address": "8.8.4.4", "vars.os" : "Windows" } }' \
810     | python -m json.tool
811     {
812         "results": [
813             {
814                 "code": 200.0,
815                 "name": "google.com",
816                 "status": "Attributes updated.",
817                 "type": "Host"
818             }
819         ]
820     }
821
822
823 #### <a id="icinga2-api-hosts-delete"></a> Delete Host
824
825 You can delete objects created using the API by sending a `DELETE`
826 request. Specify the object name inside the url.
827
828   Parameters | Description
829   -----------|--------------
830   cascade    | **Optional.** Delete objects depending on the deleted objects (e.g. services on a host).
831
832 **Note**: Objects created by apply rules (services, notifications, etc) will implicitely require
833 to pass the `cascade` parameter on host object deletion.
834
835 Example for deleting the host object `google.com`:
836
837     $ curl -u root:icinga -k -s 'https://localhost:5665/v1/objects/hosts/google.com?cascade=1' -X DELETE | python -m json.tool
838     {
839         "results": [
840             {
841                 "code": 200.0,
842                 "name": "google.com",
843                 "status": "Object was deleted.",
844                 "type": "Host"
845             }
846         ]
847     }
848
849
850 ## <a id="icinga2-api-config-management"></a> Configuration Management
851
852 The main idea behind configuration management is to allow external applications
853 creating configuration packages and stages based on configuration files and
854 directory trees. This replaces any additional SSH connection and whatnot to
855 dump configuration files to Icinga 2 directly.
856 In case you are pushing a new configuration stage to a package, Icinga 2 will
857 validate the configuration asynchronously and populate a status log which
858 can be fetched in a separated request.
859
860
861 ### <a id="icinga2-api-config-management-create-package"></a> Create Config Package
862
863 Send a `POST` request to a new config package called `puppet` in this example. This
864 will create a new empty configuration package.
865
866     $ curl -k -s -u root:icinga -X POST https://localhost:5665/v1/config/packages/puppet | python -m json.tool
867     {
868         "results": [
869             {
870                 "code": 200.0,
871                 "package": "puppet",
872                 "status": "Created package."
873             }
874         ]
875     }
876
877
878 ### <a id="icinga2-api-config-management-create-config-stage"></a> Create Configuration to Package Stage
879
880 Send a `POST` request to the URL endpoint `/v1/config/stages` including an existing
881 configuration package, e.g. `puppet`.
882 The request body must contain the `files` attribute with the value being
883 a dictionary of file targets and their content.
884
885 The example below will create a new file called `test.conf` underneath the `conf.d`
886 directory populated by the sent configuration.
887 The Icinga 2 API returns the `package` name this stage was created for, and also
888 generates a unique name for the `package` attribute you'll need for later requests.
889
890 Note: This example contains an error (`chec_command`), do not blindly copy paste it.
891
892     $ curl -k -s -u root:icinga -X POST -d '{ "files": { "conf.d/test.conf": "object Host \"cfg-mgmt\" { chec_command = \"dummy\" }" } }' https://localhost:5665/v1/config/stages/puppet | python -m json.tool
893     {
894         "results": [
895             {
896                 "code": 200.0,
897                 "package": "puppet",
898                 "stage": "nbmif-1441625839-0",
899                 "status": "Created stage."
900             }
901         ]
902     }
903
904 If the configuration fails, the old active stage will remain active.
905 If everything is successful, the new config stage is activated and live.
906 Older stages will still be available in order to have some sort of revision
907 system in place.
908
909 Icinga 2 automatically creates the following files in the main configuration package
910 stage:
911
912   File        | Description
913   ------------|--------------
914   status      | Contains the [configuration validation](8-cli-commands.md#config-validation) exit code (everything else than 0 indicates an error).
915   startup.log | Contains the [configuration validation](8-cli-commands.md#config-validation) output.
916
917 You can [fetch these files](9-icinga2-api.md#icinga2-api-config-management-fetch-config-package-stage-files) via API call
918 after creating a new stage.
919
920
921 ### <a id="icinga2-api-config-management-list-config-packages"></a> List Configuration Packages and their Stages
922
923 List all config packages, their active stage and other stages.
924 That way you may iterate of all of them programmatically for
925 older revisions and their requests.
926
927 The following example contains one configuration package `puppet`.
928 The latter already has a stage created, but it is not active.
929
930     $ curl -k -s -u root:icinga https://localhost:5665/v1/config/packages | python -m json.tool
931     {
932         "results": [
933             {
934                 "active-stage": "",
935                 "name": "puppet",
936                 "stages": [
937                     "nbmif-1441625839-0"
938                 ]
939             }
940         ]
941     }
942
943
944 ### <a id="icinga2-api-config-management-list-config-package-stage-files"></a> List Configuration Packages and their Stages
945
946 Sent a `GET` request to the URL endpoint `/v1/config/stages` including the package
947 (`puppet`) and stage (`nbmif-1441625839-0`) name.
948
949     $ curl -k -s -u root:icinga https://localhost:5665/v1/config/stages/puppet/nbmif-1441625839-0 | python -m json.tool
950     {
951         "results": [
952     ...
953             {
954                 "name": "startup.log",
955                 "type": "file"
956             },
957             {
958                 "name": "status",
959                 "type": "file"
960             },
961             {
962                 "name": "conf.d",
963                 "type": "directory"
964             },
965             {
966                 "name": "zones.d",
967                 "type": "directory"
968             },
969             {
970                 "name": "conf.d/test.conf",
971                 "type": "file"
972             }
973         ]
974     }
975
976
977 ### <a id="icinga2-api-config-management-fetch-config-package-stage-files"></a> Fetch Configuration Package Stage Files
978
979 Send a `GET` request to the URL endpoint `/v1/config/files` including
980 the package name, the stage name and the relative path to the file.
981 Note: You cannot use dots in paths.
982
983 You can fetch a [list of existing files](9-icinga2-api.md#icinga2-api-config-management-list-config-package-stage-files)
984 in a configuration stage and then specifically request their content.
985
986 The following example fetches the faulty configuration inside `conf.d/test.conf`
987 for further analysis.
988
989     $ curl -k -s -u root:icinga https://localhost:5665/v1/config/files/puppet/nbmif-1441625839-0/conf.d/test.conf
990     object Host "cfg-mgmt" { chec_command = "dummy" }
991
992 Note: The returned files are plain-text instead of JSON-encoded.
993
994
995 ### <a id="icinga2-api-config-management-config-package-stage-errors"></a> Configuration Package Stage Errors
996
997 Now that we don’t have an active stage for `puppet` yet seen [here](9-icinga2-api.md#icinga2-api-config-management-list-config-packages),
998 there must have been an error.
999
1000 Fetch the `startup.log` file and check the config validation errors:
1001
1002     $ curl -k -s -u root:icinga https://localhost:5665/v1/config/files/puppet/imagine-1441133065-1/startup.log
1003     ...
1004
1005     critical/config: Error: Attribute 'chec_command' does not exist.
1006     Location:
1007     /var/lib/icinga2/api/packages/puppet/imagine-1441133065-1/conf.d/test.conf(1): object Host "cfg-mgmt" { chec_command = "dummy" }
1008                                                                                                            ^^^^^^^^^^^^^^^^^^^^^^
1009
1010     critical/config: 1 error
1011
1012 The output is similar to the manual [configuration validation](8-cli-commands.md#config-validation).
1013