1# Redfish EventService design
2Author: AppaRao Puli
3
4Other contributors: None
5
6Created: 2019-07-24
7
8## Problem description
9Redfish in OpenBMC currently supports sending response to the clients
10which requests for data. Currently there is no service to send asynchronous
11message to the client about any events, error or state updates.
12
13The goal of this design document is to give resource overview of
14redfish event service and its implementation details in OpenBMC.
15
16## Background and references
17
18 - [Redfish specification](https://www.dmtf.org/sites/default/files/standards/documents/DSP0266_1.7.0.pdf)
19 - [DMTF Redfish school events](https://www.dmtf.org/sites/default/files/Redfish_School-Events_2018.2.pdf)
20 - [Redfish event logging](https://github.com/openbmc/docs/blob/master/redfish-logging-in-bmcweb.md)
21 - [Telemetry service](https://gerrit.openbmc.org/#/c/openbmc/docs/+/24357/)
22 - [Beast async client](https://www.boost.org/doc/libs/develop/libs/beast/example/http/client/async/)
23 - [Beast async-ssl client](https://www.boost.org/doc/libs/develop/libs/beast/example/http/client/async-ssl/)
24 - [EventService schema](https://redfish.dmtf.org/schemas/v1/EventService_v1.xml)
25 - [EventDestinationCollection schema](https://redfish.dmtf.org/schemas/v1/EventDestinationCollection_v1.xml)
26 - [EventDestination schema](https://redfish.dmtf.org/schemas/v1/EventDestination_v1.xml)
27 - [Upgrade connection for SSE](https://gerrit.openbmc.org/#/c/openbmc/bmcweb/+/13948/)
28
29## Requirements
30
31High level requirements:
32
33  - BMC shall support send asynchronous event notification to external
34    subscribed clients over network using redfish(http/https) protocol,
35    instead of regular querying mechanism.
36  - BMC shall provide mechanism to the users to configure event service
37    with specific filters and accordingly send the event notifications
38    to all the registered clients.
39  - BMC shall preserve the event service configuration across reboots, and
40    shall reset the same, when factory defaults applied.
41  - BMC shall have provision to disable the EventService.
42  - The BMC Redfish interface shall support the EventService, EventDestination
43    and EventDestinationCollection schemas.
44  - BMC can provide functionality to send out test events(SubmitTestEvent).
45  - Must allow only users having 'ConfigureManager' to create, delete or
46    updated event service configuration, subscriptions and restrict other users.
47    Must allow users with 'Login' privileges to view the EventService
48    configuration and subscription details.
49  - EventService shall be specific to Redfish Interface alone.
50    i.e No other service can add/modify/delete configuration or subscriptions.
51  - Either the client or the service can terminate the event stream at any time.
52    The service may terminate a subscription if the number of delivery error's
53    exceeds preconfigured thresholds.
54  - For Push style event subscription creation, BMC shall respond to a
55    successful subscription with HTTP status 201 and set the HTTP Location
56    header to the address of a new subscription resource. Subscriptions are
57    persistent and shall remain across event service restarts.
58  - For Push style event subscription creation, BMC shall respond to client with
59    http status as
60    - 400: If parameter in body is not supported.
61    - 404: If request body contains both RegistryPrefixes and MessageIds.
62  - SSE: BMC shall respond to GET method on URI specific in "ServerSentEventUri"
63    in EventService schema with 201(created) along with subscription
64    information. BMC shall open a new https connection and should keep
65    connection alive till subscription is valid. BMC shall respond with https
66    code 400, if filter parameters are not supported or 404 if filter
67    parameter contains invalid data. Also SSE subscription data cannot be
68    persistent across service resets/reboots.
69  - Clients shall terminate a subscription by sending an DELETE message to
70    the URI of the subscription resource.
71  - BMC may terminate a subscription by sending a special "subscription
72    terminated" event as the last message. Future requests to the associated
73    subscription resource will respond with HTTP status code 404.
74  - BMC shall accept the "Last-Event-ID" header from the client to allow a
75    client to restart the event/metric report stream in case the connection
76    is interrupted.
77  - To avoid exhausting the connection resource, BMC shall implement a
78    restriction of maximum 20 connections (Maximum of 10 SSE connections). BMC
79    shall respond with 503 Service Unavailable server error response code
80    indicating that the server is not ready to handle the request.
81  - BMC shall log an redfish event message for subscription addition, deletion
82    and modification.
83  - Services shall not send a "push" event payload of size more than 1 MB.
84
85## Proposed design
86
87Redfish event service provides a way to subscribe to specific kinds of Events,
88MetricReport and asynchronously send subscribed type of events or reports
89to client whenever it occurs.
90
91Two styles of events are supported OpenBMC EventService.
92
93  1. Push style events (https): When the service detects the need to send
94     an event, it uses an HTTP POST to push the event message to the client.
95     Clients can enable reception of events by creating a subscription entry
96     in the EventService.
97
98  2. Server-Sent Events (SSE):  Client opens an SSE connection to the service
99     by performing a GET on the URI specified by the "ServerSentEventUri" in
100     the Event Service.
101
102This document majorly focuses on OpenBMC implementation point of view. For more
103details specific to EventService can be found in ["Redfish Specification"](
104https://www.dmtf.org/sites/default/files/standards/documents/DSP0266_1.7.0.pdf)
105sections:-
106
107  - Eventing (Section 12.1)
108  - Server Sent-Events (Section 12.5)
109  - Security (Section 12 & 13.2.8)
110
111
112**BLOCK DIAGRAM**
113```
114+------------------------------------------------------------------------------------+
115|                                 CLIENT                                             |
116|                             EVENT LISTENER                                         |
117|                                                                                    |
118+-----------------------------------------------------------------^---------^--------+
119CONFIGURATION|         |SSE(GET)        NETWORK        PUSH STYLE |         |SSE
120SUBSCRIPTION |         |                                 EVENTS   |  POST   |
121+------------------------------------------------------------------------------------+
122|            |         |                                          |         |        |
123|   +--------+---------+---+  +---------------------------------------------------+  |
124|   |     REDFISH          |  |           EVENT SERVICE MANAGER   |         |     |  |
125|   |     SCHEMA           |  |   +-------------------------------+---------+--+  |  |
126|   |    RESOURCES         |  |   |          EVENT SERVICE                     |  |  |
127|   |                      |  |   |            SENDER                          |  |  |
128|   |                      |  |   +------^----------------------------+--------+  |  |
129|   |  +-------------+     |  |          |                            |           |  |
130|   |  |EVENT SERVICE|     |  |   +------+--------+            +------+--------+  |  |
131|   |  +-------------+     |  |   | METRICSREPORT |            |  EVENT LOG    |  |  |
132|   |                      |  |   | FORMATTER     |            |  FORMATTER    |  |  |
133|   |                      |  |   +------^--------+            +------^--------+  |  |
134|   |     +-------------+  |  |          |                            |           |  |
135|   |   + |SUBSCRIPTIONS+--------------------+------------------------------+     |  |
136|   | + | +-------------+  |  |          |   |                        |     |     |  |
137|   | | +--------------+   |  |   +------+---+----+            +------+-----+--+  |  |
138|   | +--------------|     |  |   | METRCISREPORT |            |  EVENT LOG    |  |  |
139|   |                      |  |   | MONITOR/AGENT |            |  MONITOR      |  |  |
140|   |                      |  |   +---------------+            +---------------+  |  |
141|   +----+-----------------+  +---------------------------------------------------+  |
142|        |                              |                             |              |
143+------------------------------------------------------------------------------------+
144         |                              |                             |
145         |                              |                             |INOTIFY
146         |                              |                             |
147+--------+----------+         +---------+----------+        +-----------------------+
148|                   |         |                    |        |  +-----------------+  |
149|    REDFISH        |         |     TELEMETRY      |        |  |     REDFISH     |  |
150|  EVENT SERVICE    |         |      SERVICE       |        |  |    EVENT LOGS   |  |
151|    CONFIG         |         |                    |        |  +-----------------+  |
152| PERSISTENT STORE  |         |                    |        |         |RSYSLOG      |
153|                   |         |                    |        |  +-----------------+  |
154|                   |         |                    |        |  |     JOURNAL     |  |
155|                   |         |                    |        |  |  CONTROL LOGS   |  |
156|                   |         |                    |        |  +-----------------+  |
157+-------------------+         +--------------------+        +-----------------------+
158
159```
160
161Push style events(HTTPS) flow diagram:
162
163```
164+-------------+   +------------+               +-------------------------------------+ +-----------------+
165|             |   |  CLIENT    |               |              BMCWEB                 | |   EVENT LOG/    |
166|   CLIENT    |   | LISTENERS  |               |RESOURCE SENDER  FORMATTER  MONITOR  | |TELEMETRY SERVICE|
167+-----+-------+   +-----+------+               +--+--------+--------+---------+------+ +-----+-----------+
168      |                 |                         |        |        |         |              |
169+----------------------------------------------------------------------------------------------------
170|SUBSCRIBE FOR EVENT|   |                         |        |        |         |              |
171+-------------------+   |                         |        |        |         |              |
172      |                 |                         |        |        |         |              |
173      |                 |                         |        |        |         |              |
174      |                 |    EVENT SUBSCRIPTION   |        |        |         |              |
175      +------------------------------------------>+        |        |         |              |
176      |                 |     PUSH STYLE EVENT    |        |        |         |              |
177      |                 |                         |-------------------------> |              |
178      |                 |                         |    SEND SUBSCRIPTION INFO |              |
179      |                 |                         |----------------------------------------->|
180      |                 |                         |    LOG REDFISH EVENT LOG  |              |
181      |                 |                         |        |        |         |              |
182+----------------------------------------------------------------------------------------------------
183|SEND EVENTS/METRICS WHEN GENERATED |             |        |        |         |              |
184+-----------------------------------+             |        |        |         |              |
185      |                 |                         |        |        |         |              |
186      |                 |                         |        |        |         |              +----+
187      |                 |                         |        |        |         |              |LOOP|
188      |                 |                         |        |        |         |              +<---+
189      |                 |                         |        |        |         +<------------>+
190      |                 |                         |        |        |         | NOTIFY EVENT/TELEMETRY
191      |                 |                         |        |        |         |       DATA   |
192      |                 |                         |        |        |         +-------------->
193      |                 |                         |        |        |         | READ DATA    |
194      |                 |                         |        |        |         +<-------------+
195      |       +-----+--------------------------------------------------------------------------+
196      |       |LOOP |   |                         |        |        |         |              | |
197      |       +-----+   |                         |        |        |         |              | |
198      |       |         |                         |        |        |         +-----------+  | |
199      |       |         |                         |        |        |         | MATCH     |  | |
200      |       |         |                         |        |        |         |SUBSCRIPTION  | |
201      |       |         |                         |        |        |         |WITH DATA  |  | |
202      |       |         |                         |        |        |         +-----------+  | |
203      |       |         |                         |        |        |         |              | |
204      |       |         |                         |        |        +<--------+              | |
205      |       |         |                         |        |        | SUBSCRIPTION           | |
206      |       |         |                         |        |        |  AND  DATA             | |
207      |       |         |                         |        |        |         |              | |
208      |       |         |                         |        +<-------+         |              | |
209      |       |         |                         |        |SUBSCRIPTION AND  |              | |
210      |       |         |                         |        |FORMATTED DATA    |              | |
211      |       |         |                         |        |        |         |              | |
212      |       |         +--------------------------------------------------------------------+-+
213      |       |         |FIRST TIME, CREATE CONNECTION |   |        |         |              | |
214      |       |         +------------------------------+   |        |         |              | |
215      |       |         <---------------------------------->        |         |              | |
216      |       |         |  ESTABLISH HTTP/HTTPS   |        +-----+  |         |              | |
217      |       |         |     CONNECTION          |        |STORE|  |         |              | |
218      |       |         |                         |        |CONN-SUBS         |              | |
219      |       |         |                         |        |MAP  |  |         |              | |
220      |       |         |                         |        |<----+  |         |              | |
221      |       |         |                         |        |        |         |              | |
222      |       |         |                         |        +----+|  |         |              | |
223      |       |         |                         |        |PUSH QUEUE        |              | |
224      |       |         |                         |        |INCOMING|         |              | |
225      |       |         |                         |        |DATA |  |         |              | |
226      |       |         |                         |        |<---+|  |         |              | |
227      |       |         |                         |        |        |         |              | |
228      |       | +------+-----------------------------------------+  |         |              | |
229      |       | |RETRY ||<---------------------------------+     |  |         |              | |
230      |       | |LOOP  ||   SEND FORMATTED DATA   |        |     |  |         |              | |
231      |       | |-+----+|                         |        |     |  |         |              | |
232      |       | | +-----------------------------------------------------------------------------
233      |       | | |SEND FAILED |                  |        |     |  |         |              | |
234      |       | | +------------+                  |        |     |  |         |              | |
235      |       | | |     |                         |        |     |  |         |              | |
236      |       | | |     <---------------------------------->     |  |         |              | |
237      |       | | |     |  ESTABLISH HTTP/HTTPS   |        +----+|  |         |              | |
238      |       | | |     |     CONNECTION          |        |REOPEN  |         |              | |
239      |       | | |     |                         |        |CONN&|  |         |              | |
240      |       | | |     |                         |        |UPDATE STORE      |              | |
241      |       | | |     |                         |        |<---+|  |         |              | |
242      |       | | +------------REPEAT SEND LOOP------------------|  |         |              | |
243      |       | | +-----------------------------------------------------------------------------
244      |       | | |SEND SUCCESS |                 |        |     |  |         |              | |
245      |       | | +-------------+                 |        |     |  |         |              | |
246      |       | |       |                         |        |---+ |  |         |              | |
247      |       | |       |                         |        |POP| |  |         |              | |
248      |       | |       |                         |        |QUEUE|  |         |              | |
249      |       | |       |                         |        |<--+ |  |         |              | |
250      |       | |       |                         |        |     |  |         |              | |
251      |       | |       |                         |        +----+|  |         |              | |
252      |       | |       |                         |        |SEND NEXT         |              | |
253      |       | |       |                         |        |QUEUEED |         |              | |
254      |       | |       |                         |        |DATA||  |         |              | |
255      |       | |       |                         |        |<---+|  |         |              | |
256      |       | |       |                         |        |     |  |         |              | |
257      |       | | +-----------------------------------------------------------------------------
258      |       | | |REACHED THRESHOLD LIMIT |      |        |     |  |         |              | |
259      |       | | +------------------------+      |        |     |  |         |              | |
260      |       | |       |                         |        |----+|  |         |              | |
261      |       | |       |                         |        |DELETE  |         |              | |
262      |       | |       |                         |        |STORE|  |         |              | |
263      |       | |       |                         |        |&QUEUE  |         |              | |
264      |       | |       |                         |        |<--+ |  |         |              | |
265      |       | |       |                         |<-------|     |  |         |              | |
266      |       | |       |                         |REMOVE RESOURCE  |         |              | |
267      |       | |       |                         +------+ |     |  |         |              | |
268      |       | |       |                         |REMOVE| |     |  |         |              | |
269      |       | |       |                         |SUBSCRIPTION  |  |         |              | |
270      |       | |       |                         |& CONNECTION  |  |         |              | |
271      |       | |       |                         |<-----+ |     |  |         |              | |
272      |       | |       |                         |-------------------------->|              | |
273      |       | |       |                         |  UPDATE SUBSCRIPTION      |              | |
274      |       | |       |                         |----------------------------------------->| |
275      |       | |       |                         |    LOG REDFISH EVENT LOG  |              | |
276      |       | |       |                         |        |     |  |         |              | |
277      |       | +-------+----------------------------------------+  |         |              | |
278      |       |         |                         |        |        |         |              | |
279      |       +--------------------------------------------------------------------------------+
280      |                 |                         |        |        |         |              |
281+--------------------------------------------------------------------------------------------------
282|DELETE EVENT SUBSCRIPTIONS |                     |        |        |         |              |
283+---------------------------+                     |        |        |         |              |
284      |                 |                         |        |        |         |              |
285      +-----------------+------------------------>+        |        |         |              |
286      |        DELETE SUBSCRIPTION                |        |        |         |              |
287      |                 |                         +------+ |        |         |              |
288      |                 |                         |REMOVE| |        |         |              |
289      |                 |                         |SUBSCRIPTION     |         |              |
290      |                 |                         <------+ |        |         |              |
291      |                 +<------------------------|        |        |         |              |
292      |                 |    CLOSE CONNECTION     |        |        |         |              |
293      |                 |                         |--------------------------->              |
294      |                 |                         |    UPDATE SUBSCRIPTION    |              |
295      |                 |                         |----------------------------------------->|
296      |                 |                         |    LOG REDFISH EVENT LOG  |              |
297      |                 |                         |        |        |         |              |
298
299```
300
301SSE flow diagram:
302
303```
304+-------------+   +------------+               +-------------------------------------+ +-----------------+
305|             |   |  CLIENT    |               |              BMCWEB                 | |   EVENT LOG/    |
306|   CLIENT    |   | LISTENERS  |               |RESOURCE SENDER  FORMATTER  MONITOR  | |TELEMETRY SERVICE|
307+-----+-------+   +-----+------+               +--+--------+--------+---------+------+ +-----+-----------+
308      |                 |                         |        |        |         |              |
309+--------------------------------------------------------------------------------------------------------
310|SUBSCRIBE FOR EVENT|   |                         |        |        |         |              |
311+-------------------+   |                         |        |        |         |              |
312      |                 |                         |        |        |         |              |
313      |                 |                         |        |        |         |              |
314      |                 |    EVENT SUBSCRIPTION   |        |        |         |              |
315      |                 |-------------------------|        |        |         |              |
316      |                 |     SSE(ON ESTABLISHED CONNECTION)        |         |              |
317      |                 |                         |        |        |         |              |
318      |                 |                         +-----+  |        |         |              |
319      |                 |                         |KEEP |  |        |         |              |
320      |                 |                         |CONN |  |        |         |              |
321      |                 |                         |HANDLE  |        |         |              |
322      |                 |                         +<----+  |        |         |              |
323      |                 |                         |        |        |         |              |
324      |                 |                         |--------------------------->              |
325      |                 |                         |    SEND SUBSCRIPTION INFO |              |
326      |                 |                         |        |        |         |              |
327+-----------------------------------------------------------------------------------------------------
328|SEND EVENTS/METRICS WHEN GENERATED |             |        |        |         |              |
329+-----------------------------------+             |        |        |         |              |
330      |                 |                         |        |        |         |              |
331      |                 |                         |        |        |         |              +----+
332      |                 |                         |        |        |         |              |LOOP|
333      |                 |                         |        |        |         |              +<---+
334      |                 |                         |        |        |         +<------------>+
335      |                 |                         |        |        |         | NOTIFY EVENT/TELEMETRY
336      |                 |                         |        |        |         |       DATA   |
337      |                 |                         |        |        |         +-------------->
338      |                 |                         |        |        |         | READ DATA    |
339      |                 |                         |        |        |         +<-------------+
340      |                 |                         |        |        |         |              |
341      |                 |                         |        |        |         +-----------+  |
342      |                 |                         |        |        |         | MATCH     |  |
343      |                 |                         |        |        |         |SUBSCRIPTION  |
344      |                 |                         |        |        |         |WITH DATA  |  |
345      |                 |                         |        |        |         +-----------+  |
346      |       +-----+--------------------------------------------------------------------------+
347      |       |LOOP |   |                         |        |        +<--------+              | |
348      |       +-----+   |                         |        |        | SUBSCRIPTION           | |
349      |       |         |                         |        |        |  AND  DATA             | |
350      |       |         |                         |        |        |         |              | |
351      |       |         |                         |        +<-------+         |              | |
352      |       |         |                         |        |SUBSCRIPTION AND  |              | |
353      |       |         |                         |        |FORMATTED DATA    |              | |
354      |       |         |                         |        |        |         |              | |
355      |       |         |                         |        +----+|  |         |              | |
356      |       |         |                         |        |PUSH QUEUE        |              | |
357      |       |         |                         |        |INCOMING|         |              | |
358      |       |         |                         |        |DATA |  |         |              | |
359      |       |         |                         |        |<---+|  |         |              | |
360      |       |         |                         |        |        |         |              | |
361      |       | +------+-----------------------------------------+  |         |              | |
362      |       | |RETRY ||<---------------------------------+     |  |         |              | |
363      |       | |LOOP  ||   SEND FORMATTED DATA   |        |     |  |         |              | |
364      |       | |+-----+|                         |        |     |  |         |              | |
365      |       | |+-------------------------------------------------------------------------------
366      |       | ||SEND FAILED |                   |        |     |  |         |              | |
367      |       | |+------------+                   |        |     |  |         |              | |
368      |       | ||      |                         |        |     |  |         |              | |
369      |       | |+-------------REPEAT SEND LOOP------------------|  |         |              | |
370      |       | |       |                         |        |     |  |         |              | |
371      |       | |+-------------------------------------------------------------------------------
372      |       | ||SEND SUCCESS |                  |        |     |  |         |              | |
373      |       | |+-------------+                  |        |     |  |         |              | |
374      |       | |       |                         |        |---+ |  |         |              | |
375      |       | |       |                         |        |POP| |  |         |              | |
376      |       | |       |                         |        |QUEUE|  |         |              | |
377      |       | |       |                         |        |<--+ |  |         |              | |
378      |       | |       |                         |        +----+|  |         |              | |
379      |       | |       |                         |        |SEND NEXT         |              | |
380      |       | |       |                         |        |QUEUEED |         |              | |
381      |       | |       |                         |        |DATA ON |         |              | |
382      |       | |       |                         |        |<---+|  |         |              | |
383      |       | |       |                         |        |     |  |         |              | |
384      |       | |+-------------------------------------------------------------------------------
385      |       | ||REACHED THRESHOLD LIMIT |       |        |     |  |         |              | |
386      |       | |+------------------------+       |        |     |  |         |              | |
387      |       | |       |                         |        |----+|  |         |              | |
388      |       | |       |                         |        |DELETE  |         |              | |
389      |       | |       |                         |        |STORE|  |         |              | |
390      |       | |       |                         |        |& QUEUE |         |              | |
391      |       | |       |                         |        |<---+|  |         |              | |
392      |       | |       |                         |<-------|     |  |         |              | |
393      |       | |       |                         |REMOVE RESOURCE  |         |              | |
394      |       | |       |                         +------+ |     |  |         |              | |
395      |       | |       |                         |REMOVE| |     |  |         |              | |
396      |       | |       |                         |SUBSCRIPTION  |  |         |              | |
397      |       | |       |                         |& CONNECTION  |  |         |              | |
398      |       | |       |                         |<-----+ |     |  |         |              | |
399      |       | |       |                         |-------------------------->|              | |
400      |       | |       |                         |  UPDATE SUBSCRIPTION      |              | |
401      |       | |       |                         |----------------------------------------->| |
402      |       | |       |                         |    LOG REDFISH EVENT LOG  |              | |
403      |       | |       |                         |        |     |  |         |              | |
404      |       | +-------+----------------------------------------+  |         |              | |
405      |       |         |                         |        |        |         |              | |
406      |       +--------------------------------------------------------------------------------+
407      |                 |                         |        |        |         |              |
408+--------------------------------------------------------------------------------------------------
409|DELETE EVENT SUBSCRIPTIONS |                     |        |        |         |              |
410+---------------------------+                     |        |        |         |              |
411      |                 |                         |        |        |         |              |
412      +-----------------+------------------------>+        |        |         |              |
413      |        DELETE SUBSCRIPTION                |        |        |         |              |
414      |                 |                         +------+ |        |         |              |
415      |                 |                         |REMOVE| |        |         |              |
416      |                 |                         |SUBSCRIPTION     |         |              |
417      |                 |                         <------+ |        |         |              |
418      |                 +<------------------------|        |        |         |              |
419      |                 |    CLOSE CONNECTION     |        |        |         |              |
420      |                 |                         |--------------------------->              |
421      |                 |                         |    UPDATE SUBSCRIPTION    |              |
422      |                 |                         |----------------------------------------->|
423      |                 |                         |    LOG REDFISH EVENT LOG  |              |
424      |                 |                         |        |        |         |              |
425+--------------------------------------------------------------------------------------------------
426|CLIENT CLOSE CONNECTION |                        |        |        |         |              |
427+------------------------+                        |        |        |         |              |
428      |                 |                         |        |        |         |              |
429      |                 |    CLIENT CLOSED        |        |        |         |              |
430      |                 |------------------------>|        |        |         |              |
431      |                 |                         +-------+|        |         |              |
432      |                 |                         |REMOVE ||        |         |              |
433      |                 |                         |SUBSCRIPTION     |         |              |
434      |                 |                         +<------+|        |         |              |
435      |                 |                         |--------------------------->              |
436      |                 |                         |    UPDATE SUBSCRIPTION    |              |
437      |                 |                         |----------------------------------------->|
438      |                 |                         |    LOG REDFISH EVENT LOG  |              |
439      |                 |                         |        |        |         |              |
440      v                 v                         v        v        v         v              v
441```
442
443
444EventService design includes below major blocks.
445
446  1. Redfish resources (Schema based)
447	  1. EventService
448	  2. Subscription Collections (EventDestination collection)
449	  3. Subscriptions (EventDestination)
450  2. Event Service Manager
451	  1. Event log monitor
452	  2. Event log formatter
453	  3. MetricReport monitor/agent
454	  4. MetricReport formatter
455	  5. Event service Sender (Common)
456  3. EventService config store ( Persistent)
457
458This document also covers the description of below modules.
459
460  1. Server-Sent Event(SSE): It covers details on what is SSE and
461     how connection open, close are handled in different cases.
462  2. Push style events(HTTP/HTTPS): It covers how to subscribe for
463     Push style events and how the http/https connections are handled
464     in bmcweb.
465  3. SubmitTestEvent: Details on submit test event action.
466
467This document doesn't cover below component design.
468
469  1. Redfish Event Logs: This is existing implementation. In OpenBMC,
470     All events will be logged to Journal control logs and RSyslog service,
471     monitors event logs associated with "REDFISH_MESSAGE_ID" and write the
472     required information to "/var/log/redfish" for persisting the event logs.
473
474     So EventService design is hooked to Redfish Event Logs majorly for below
475     two reasons.
476
477       - Get the notification whenever new event is logged to Redfish event
478         Logs.
479       - Way to read the Redfish event log information.
480
481     This document covers one example Redfish Event Log implementation covered
482     under below design. As part of it, it uses inotify for getting
483     notification about new event log and read the log information by accessing
484     the redfish event log file.
485
486     Refer below link for more information on same.
487[link](https://github.com/openbmc/docs/blob/master/redfish-logging-in-bmcweb.md)
488
489     If other OEM's has different implementation for Redfish EventLogs, they
490     can satisfy  above mentioned two requirement and can hook it to
491     EventService design specified here.
492     For example, If xyz OEM uses D-Bus based Redfish Event logs, They can
493     use 'signal' for notifying the new redfish event log and event log
494     information. They can replace 'inotify' with 'signal' and hook their
495     OEM specific Redfish event log to this Redfish EventService design.
496
497  2. Telemetry service: Redfish telemetry service is used to gather all the
498     metrics reports associated with different resources such as Power metrics,
499     thermal metrics, memory metrics, processor metrics etc... Monitoring
500     service in telemetry supports different modes along with aggregated
501     operations(Single, average, max, min, sum etc..).
502
503     Refer below link for design document of telemetry service.
504[link](https://gerrit.openbmc.org/#/c/openbmc/docs/+/24357/)
505
506
507### Redfish resource schema's
508
509Redfish will have three major resources to support EventService.
510
511  1. Event Service
512  2. Subscription Collections
513  3. Subscriptions
514
515All the configuration and subscriptions information data will be cached on
516bmcweb webserver and synced with config json file for restoring and persisting
517the data.
518
519**EventService**
520
521  Contains the attributes of the service such as Service Enabled, status,
522  delivery retry attempts, Event Types, Subscriptions, Actions URI etc.
523
524   - URI : `/redfish/v1/EventService`
525   - SCHEMA : [EventService](https://redfish.dmtf.org/schemas/v1/EventService_v1.xml)
526   - METHODS : `GET, PATCH`
527
528Refer Testing for supported properties and example.
529
530**Subscription Collections**
531  This resource is used to get collection of all subscriptions and also used
532  to configure the new subscriptions for automatic events.
533
534   - URI : `/redfish/v1/EventService/Subscriptions`
535   - SCHEMA : [EventDestinationCollection](https://redfish.dmtf.org/schemas/v1/EventDestinationCollection_v1.xml)
536   - METHODS : `GET, POST`
537
538Refer Testing section for example.
539
540**Subscriptions**
541  This resource contains the subscription details. Used to get each individual
542  get subscription information, update & Delete existing subscription
543  information.
544
545   - URI : `/redfish/v1/EventService/Subscriptions/<ID>`
546   - SCHEMA : [EventDestination](https://redfish.dmtf.org/schemas/v1/EventDestination_v1.xml)
547   - METHODS : `GET, PATCH, DELETE`
548
549Refer Testing section for supported properties and example.
550
551
552### Event service manager
553
554Event Manager is main block which does monitor the events, format the request
555body and send it to the subscribed destinations. It shall support for two types
556of event formats which are define in redfish specification.
557
558  1. Event: Resource type 'Event' is used to receive alerts in the form of
559     json body to subscribed clients when the subscription details matches
560     for those event logs.
561
562  2. MetricReport: It is used to receive alerts in the forms of json body
563     to subscribed clients when the subscription details matches for the
564     collected telemetry data by telemetry service.
565
566The "Event service sender" is common entity for both type of resources. The
567formatter and monitor entities are different for each type of resources.
568
569**Event log monitor**
570
571In OpenBMC, all the redfish event logs are currently logged to persistent area
572of BMC filesystem("/var/log/redfish"). The "Event log monitor" service under
573"Event service manager" will use **inotify** to watch on redfish event log file
574to identify the new events. Once it identifies the new events, it will read
575all logged events information from redfish event file and pass it to 'Event
576log formatter' for further processing. The last processed event data timestamp
577will be cached in bmcweb to identify the new events in redfish event log file.
578
579It monitors the live events for sending asynchronously and does not send
580the events logged before bmcweb service start.
581
582**Event log formatter**
583
584It is used to format the request body by reading event logs passed
585from 'Event log monitor' and filter the data by reading subscription
586information. It will fetch all the subscription information from "Redfish
587event service store" and filter the events by checking severity, event
588type against the user subscribed information. It formats the http
589"request body" along with CustomText, HttpHeaders and send the Events over
590network using http protocol for the filtered subscribers.
591
592Refer Tested section for example request body.
593
594**MetricReport monitor**
595
596Telemetry monitoring service ( Not covered in this document) is responsible
597for gathering metrics from D-Bus sensors and exposing them as D-Bus objects.
598Monitoring service supports different monitoring modes (periodic, on change
599and on demand) along with aggregated operations such as single, average, max
600min, sum etc... This service periodically collects the metrics report depending
601on Telemetry service configuration such as 'Metric Definitions', 'Metric
602Report Definitions' and 'Metric Triggers'.
603
604The telemetry monitor shall emit a signal when there is a collection of
605report. MetricReport monitor/agent shall implement the listener for
606telemetry signal and using the subscription information, it should match,
607filter the desired metric report to pass it on to 'MetricReport formatter'.
608Since 'MetricReport monitor' is tightly coupled with 'Telemetry monitor' which
609already does the monitoring loop, its responsibility of 'Telemetry
610monitor' to match the subscriptions rules and provide it to MetricReport
611formatter. The EventService should provide a way to communicate the
612subscriptions data whenever user creates or updates or delete subscription.
613
614**MetricReport formatter**
615
616The 'MetricReport formatter' is responsible for formatting the data which comes
617from 'MetricReport monitor/agent' by checking subscriptions information
618such as HttpHeaders, Custom text strings along with Telemetry report data.
619
620**Event service sender**
621
622The "Event service sender" is used to send the formatted request body
623which is passed from 'Event log formatter' or 'Telemetry formatter' to
624all filtered subscribers. It supports sending both https and http
625requests by using beast library. The http/https connections handling
626(open/close) differs for both subscription types such as 'Push style
627events' and 'SSE' and more detailed are covered in respective sections.
628
629Beast is a C++ header-only library serving as a foundation for writing
630interoperable networking libraries by providing low-level HTTP/1, WebSocket,
631and networking protocol vocabulary types and algorithms using the consistent
632asynchronous model of Boost.Asio.
633For more information on beast, refer
634[link](https://www.boost.org/doc/libs/develop/libs/beast/doc/html/beast/introduction.html)
635
636  1. PUSH style eventing: BMC uses the boost::beast for asynchronously sending
637     events to the subscribed clients. Here is the Beast client Examples for
638     sending the synchronous and asynchronous requests over encrypted and
639     un-encrypted channels.
640[link](https://www.boost.org/doc/libs/develop/libs/beast/example/http/client/async/)
641[link](https://www.boost.org/doc/libs/develop/libs/beast/example/http/client/async-ssl/)
642
643  2. Server-Sent Events (SSE): The EventDestination resource of the
644     subscription data shall contains the opaque of opened client
645     SSE stream connection. After receiving the formatted event associated
646     with specific subscription information, EventSender writes the formatted
647     event data on open SSE connection with specific ID so that client
648     can receive the event.
649
650In case of push style eventing, https connection will be established
651during first event. If the connection is already established with subscription
652ID, then it uses same connection handle for sending events. This connection
653handle and subscription map will be stored in event service sender. Users can
654have multiple subscriptions coming from single destination and BMC will
655have separate connection handle associated with each subscription. Event
656listeners (web servers) has capability to accept multiple connections from
657same client(BMC) and depending on routing rules, the received events will be
658parsed on event listener side.
659
660In case of SSE, connection handle will be read from resource and used by
661sender for sending events.
662
663Received formatted data will be pushed to queue maintained under sender,
664against the connection-subscription map. Upon successful sending
665of event data, formatted data entry will be pop-ed from queue and
666next formatted data will be attempted for send and so on.
667
668If send event(logs or metric reports) fails, then it will retry for
669number of attempts configured in Event Service "DeliveryRetryAttempts" with
670an interval of "DeliveryRetryIntervalSeconds". In case of Push Style Events
671if send fails due to some reasons, https connection will be
672re-established and first send will be re-attempted. If the failure persist even
673after the configured retry attempts, subscription information will be deleted
674and same will be updated to consumers(Telemetry service or event log service).
675In SSE connection, bmcweb would only retry sending events in the case of
676network failure/timeout/congestion. If there is error like connreset/badf,
677bmcweb will delete the subscription as specified above. In such scenario's,
678user can re-subscribe for events. This is requirement as per current redfish
679specification.
680
681Any temporary network failure during event notification, and the failure
682persist till threshold limit, subscription entry will be remove. This may be
683security concern as client may not know about subscription termination,
684once network comes back.
685Note: Redfish specification says, Event destination subscription should be
686terminated after reaching threshold limit. This is known security concern.
687TBD: Need to work with Redfish forum for resolution.
688
689
690### Redfish event service store
691
692Redfish event service store is used to store the all configuration
693related to EventService and subscriptions information. This does
694below operations:
695
696  - During bmcweb service start, it gets all the configuration and
697    subscriptions information from config json file and populates the
698    internal structures data.
699
700  - Redfish EventService resources will get/update this event store for any
701    user activities via redfish(Like Get/Add/Update/Delete subscriptions etc.)
702
703  - It will sync the "event config store" with configuration Json file for
704    persisting the information when there is update.
705    __Note__: Configuration json file will be updated only for Push style event
706    subscription information. SSE events subscription information
707    is volatile and will not get updated to json file.
708
709  - It will be used for getting all the subscription information to the
710    "Event service manager" for filtering event data.
711
712
713The bmcweb service will update the config store data
714including EventService configuration and subscription information to the
715json file(location: /var/lib/bmcweb/eventservice_data.json).
716This will be persistent across the bmcweb service restarts or bmc reboots
717and loads this while initializing bmcweb EventService class.
718
719Note:
720
721  1. In case of SSE, Client is initiator of connection and so SSE stream
722     connection can't be re-established when bmcweb service or BMC goes
723     for reboot. Hence subscription information related to SSE will not
724     be persistent and Client must re-subscribe for SSE events using
725     "ServerSentEventUri", whenever bmc comes out of reset.
726
727     Limitation: If bmcweb server closes abruptly due to some reasons
728     like watchdog trigger, then bmcweb can't send close connection
729     event to SSE client(For notifying SSE client to re-establishing
730     connection).
731
732
733Cache implementation includes below major blocks:
734
735  - EventServiceStore Class: It holds the map of all subscriptions with
736    unique key and methods to Create/Delete/update subscription
737    information. It also holds the high level configuration information
738    associated with EventService schema.
739
740  - Configuration structure: It holds the configuration associated with
741    EventService schema properties.
742
743  - Subscription structure: It holds the data associated with each
744    EventDestination schema properties along with established connection
745    handle.
746
747
748### Server-Sent Events (SSE):
749
750Server-Sent Events (SSE) is a server push technology enabling a browser to
751receive automatic updates from a server via HTTP connection. The Server-Sent
752Events EventSource API is standardized as part of HTML5 by the W3C.
753
754Server-Sent Events is a standard describing how servers can initiate data
755transmission towards clients once an initial client connection has been
756established. They are commonly used to send message updates or continuous
757data streams to a browser client and designed to enhance native,
758cross-browser streaming through a JavaScript API called EventSource, through
759which a client requests a particular URL in order to receive an event stream.
760
761The "EventService" resource contains a property called "ServerSentEventUri".
762If a client performs a GET on the URI specified by the "ServerSentEventUri",
763the bmcweb server keep the connection open and conform to the HTML5
764Specification until the client closes the socket. The bmcweb service
765should sent the response to GET URI with following headers.
766
767```
768'Content-Type': 'text/event-stream',
769'Cache-Control': 'no-cache',
770'Connection': 'keep-alive'
771```
772
773Events generated by the OpenBMC will be sent to the clients using the open
774connection. Response of event message should contain the "data: " prefix and
775postfix "\n" on each line. For representing the end of data, it should end
776with "\n\n". Example sending json response should look like
777```
778data: {\n
779data: "msg": "hello world",\n
780data: "id": 12345\n
781data: }\n\n
782```
783
784Open connection: When a client performs get on 'ServerSentEventUri' with
785desired filters, bmcweb create an EventDestination instance in the
786subscriptions collection. Once bmcweb receives the SSE stream request,
787the open connection will be upgraded to WebSocket by checking the request
788Content-Type header(matches to 'text/event-stream') and keep the connection
789alive till the client/server closes the connection. Please refer
790[link](https://gerrit.openbmc.org/#/c/openbmc/bmcweb/+/13948/) for
791details on how to upgrade the connection for SSE. The "Context" property
792in the EventDestination resource shall be an opaque string generated by the
793service.
794
795Note: since its GET operation on existing open connection(which is
796authenticated and authorized as normal operation), there is no special
797security breach with it. All bmcweb related security threat model applies
798here.
799
800Close connection: Either the client or the server can terminate the event
801stream at any time and close the connection. The bmcweb server can delete the
802corresponding EventDestination instance when the connection is closed.
803
804Connection can be closed by,
805
806  - Client by sending DELETE method on subscribed id URI.
807  - Server(bmcweb) can close connection and send notification to client
808    with 'event: close' request body.
809
810Since SSE is uni-directional, if client closes connection/browser abruptly,
811bmcweb service doesn't know the client connection state. This is limitation on
812SSE connection. In such scenario bmcweb service may delete a subscription, if
813the number of delivery errors exceeds preconfigured thresholds.
814
815Note:
816  - The SSE subscription data is not persistent in nature. When bmcweb
817    restarts or BMC reboots, client should re-establish the SSE connection to
818    bmcweb to listen for events.
819  - In case of SSE, client can send the "Last-Event-ID" as header. Monitor
820    service will fetch all the event or metric report stream captured after
821    that specified "Last-Event-ID" and send to client after formatting. If
822    it fails to find the specified event ID, it will start streaming only live
823    events/metric reports.
824
825The service should support using the $filter query parameter provided in the
826URI for the SSE stream by the client to reduce the amount of data returned
827to the client.
828
829Supported filters are:
830
831  - RegistryPrefix
832  - ResourceType
833  - EventFormatType
834  - MessageId
835  - OriginResource
836
837Example for subscribing SSE with filters:
838```
839MessageId based filter:
840METHOD: GET
841URi: https://<BMCIP>/redfish/v1/EventService/SSE?MessageId='Alert.1.0.LanDisconnect'
842
843RegistryPrefix based filter:
844https://sseuri?$filter=(RegistryPrefix eq Resource) or (RegistryPrefix eq
845Task)
846
847ResourceType based filter:
848https://sseuri?$filter=(ResourceType eq 'Power') or (ResourceType eq
849'Thermal')
850```
851
852### Push style events (HTTP/HTTPS)
853
854Unlike the SSE (where bmcweb act as server) push style events works in
855different way. In this case, BMC acts as HTTP client and send the data
856to webserver running on external system. In case of SSE, connection
857will be kept alive till stream closes but in push style events, connections
858are opened on need and closes immediately after pushing event/report data.
859
860By using POST method on '/redfish/v1/EventService/Subscriptions' URI with
861desired request body (mandatory fields: Destination, Protocol), user can
862subscribe for the events. The monitor and formatter resources (both Event
863log and MetricReport) uses the subscribed data for match rules, when there
864is event log or Telemetry data available. The 'Event service sender' uses
865the destination field in subscribed data for opening the connection and
866pushing data to webserver running externally.
867
868It shall support both http and https (https is not defined in Redfish
869specification) connections which will be created using the boost::beast
870library. For https connection it uses the self-signed certificates which are
871loaded in certificate store. If establishing connection fails, it retries for
872configured retry attempts (DeliveryRetryAttempts) and delete the subscription
873if it reaches threshold limit. If SSL negotiation fails, it will not retry for
874connection establishment. Users can upload new certificates. More details
875about certificate can be found at
876[link](https://github.com/openbmc/docs/blob/master/designs/redfish-tls-user-authentication.md)
877
878Example for created Push style event is documented in testing section
879of same document.
880
881### SubmitTestEvent
882  This action shall add a test event to the event service with the event
883  data specified in the action parameters. This message should then be sent
884  to any all subscribed Listener destination targets depending on subscription
885  data.
886
887   - URI: `/redfish/v1/EventService/Actions/EventService.SubmitTestEvent`
888   - SCHEMA: [EventService](https://redfish.dmtf.org/schemas/v1/EventService_v1.xml)
889   - METHODS : `POST`
890
891Note: EventService.v1_3_0 was updated to deprecate the EventType parameter in
892      SubmitTestEvent, and add the EventGroupId parameter in SubmitTestEvent.
893
894Example POST Request body:
895```
896{
897  "Message": "Test Event for validation",
898  "MessageArgs": [],
899  "EventId": "OpenBMC.0.1.TestEvent",
900  "EventGroupId" : "",
901  "Severity": "OK"
902}
903```
904
905
906## Alternatives considered
907
908**HTTP POLLING**
909
910Polling is a traditional technique where client repeatedly polls a server for
911data. The client makes a request and waits for the server to respond with data.
912BMC provides a way to pool the event logs (using Events schema). Client can
913run continuously http GET on Events LogService and get the all the events from
914BMC. But in HTTP protocol fetching data revolves around request/response which
915is greater HTTP overhead.
916
917Push style(https) eventing or SSE will avoid the http overhead of continuous
918polling and send the data/events when it happens on server side to the
919subscribed clients.
920
921**WEBSOCKET**
922
923WebSocket provides a richer protocol to perform bi-directional, full-duplex
924communication. Having a two-way channel is more attractive for some case but in
925some scenarios data doesn't need to be sent from the client(Client just need
926updates from server errors/events when it happens.)
927
928SSE provides uni-directional connection and operates over traditional HTTP. SSE
929do not require a special protocol or server implementation to get working.
930WebSocket on the other hand, require full-duplex connections and new Web Socket
931servers to handle the protocol.
932
933**IPMI PEF**
934
935Platform Event Filtering (PEF) provides a mechanism for configuring the BMC
936to take selected actions on event messages that it receives. This mechanism
937is IPMI centric which has its own limitation in terms of security, scalability
938etc. when compared with Redfish.
939
940##  Implementation design alternatives
941
942  - Direct journal logs vs Redfish event log file using inotify
943
944Considered reading direct journald logs using sd_journal_<xyz> api's but that
945seems to be in-efficient because
946
947  1. sdjournal has multiple logs currently( not just event logs) and so this
948     become very inefficient to monitor and process data to identify just for
949     redfish event logs.
950
951  2. Some hooks need to be added to sdjournal to emit signals whenever messages
952    are logged to sdjournal.
953
954To overcome above challenges currently redfish event logs are filtered and
955logged to separate file using rsyslog. Same file is used by EventService
956by monitor the file using inotify.
957
958  - D-Bus service vs Event Service config store
959
960Considered creating separate D-Bus service for storing EventService
961configuration and subscriptions data. Also considered using settings
962D-Bus service for persisting the data across the reboots. But since
963EventService is specific to redfish/bmcweb and not consumed/updated
964by any other processes in system, there is no real gain with having D-Bus
965service.
966
967## Impacts
968
969Security issue with Push style events:
970
971Push style events also support HTTP protocol which is not secured and is
972susceptible to man-in-the-middle attacks and eavesdropping which may lead to
973virus injections and leak sensitive information to attackers. The push style
974event subscription or changes to the BMC will be done over the
975secure HTTPS channel with full authentication and authorization. So, BMC side
976security is NOT compromised. Event Listener on client may get hacked data
977in-case of man-in-the-middle attacks. To avoid such attacks, it is recommended
978to use SSE event mechanism or https-based push style events.
979
980SSE works on HTTPS protocol which is encrypted and secured. SSE EventService
981subscriptions can be created or updated over HTTPS protocol along with proper
982authentication and authorization on BMC users. Please refer security details
983(section 13) in DSP0266 for more information.
984
985SSE connections:
986
987When client opens the SSE HTTPS connection, it will be on open state until
988client or server closes the connection. On Linux, there is a limit on each file
989descriptor(Of course this is very huge number > 8K). Multiple open http
990connections on bmcweb can slow down the performance.
991
992Since open SSE client connection is proxied under multiple level of BMC side
993protection (like Authentication is required, User should have proper privilege
994level to establish the SSE connection etc.), these impacts are mitigated. Also
995BMC will have support for maximum of 10 SSE subscriptions which will limit the
996number of http connections exhaust scenario. This can be compile time option.
997
998## Testing
999
1000User should cover below functionalists.
1001
1002 - View and update EventService configuration using GET and PATCH methods and
1003   validate the functionality.
1004 - Subscribe for Events (Both "Push style event" and "SSE") as described below
1005   and validate http status code for positive and negative use cases (Body
1006   parameter invalid, Invalid request, improper privilege - forbidden etc.).
1007 - Validate all subscription collections and each individual subscription.
1008 - Using delete method on subscription URI specific to ID and see connection
1009   closing properly on client side and subscription data clear on server side.
1010 - Enable and disable EventService, generate events and validate whether Events
1011   are sending properly to all subscriptions when its enabled and stopped
1012   sending when disabled.
1013 - Use SubmitTestEvent for generating Test Events. Also cover negative cases
1014   with invalid body data.
1015 - Validate the functionality of retry attempts and retry timeout with both
1016   positive and negative cases.
1017 - Client connection close: Close client connection which are listening for SSE
1018   and check server-side connection closes after configured retry attempts and
1019   clears the subscription information.
1020 - Reboot BMC or reset bmcweb service and check all "push style events"
1021   subscription is preserved and functional by generating and checking events.
1022 - Reboot BMC or reset bmcweb service and check all "SSE" subscription data
1023   is not preserved and client-side connection is closed properly.
1024 - Create user with multiple privileges and check create/delete/update
1025   subscription and configuration data are performed only for user having
1026   'ConfiguredManager' privilege and view EventService information works only
1027   for 'Login'.
1028 - Create new subscription and check is the event message logged in redfish
1029   event logs or not. Also modify, delete subscription and see Redfish events
1030   are logged or not.
1031 - Validate the authenticity of events sent to client on subscription with
1032   proper filtered data(Ex: If RegisteryPrefixes is set to "OpenBMC.0.1", it
1033   should not send events with prefixes "OpenBMC.0.2") should be validated.
1034 - For security, validate GET on URI specified in "ServerSentEventUri" with
1035   un-authorized users and see it responds with properly http status code and
1036   should not create any subscription or open any http connection.
1037 - Max limit check: Creates max supported event subscriptions and validate.
1038
1039
1040** Push style events: **
1041
1042  1) EventListner: Client should configure the web service for listening the
1043     events (Example: http://192.168.1.2/Events).
1044
1045  2) Subscription:
1046     Client can subscribe for events on BMC using below
1047```
1048URI: /redfish/v1/EventService/Subscriptions
1049METHOD: POST
1050REQUEST BODY:
1051{
1052  "Destination":"http://192.168.1.2/Events",
1053  "Context":"CustomText",
1054  "Protocol":"Redfish",
1055}
1056```
1057     On successful event subscription client will receive 201(Created) http
1058     status code along with created subscription ID. At this point onwards,
1059     client will receive events associated with subscribed data.
1060
1061     Client can use "SubmitTestEvent" (Documented above) to test the working
1062     state.
1063
1064  3) ViewSubscription: Client can get the subscriptions details using
1065```
1066URI: /redfish/v1/EventService/Subscriptions/<ID>
1067METHOD: GET
1068```
1069
1070  4) UpdateSubscription: At any point client can update the subscription
1071     information.
1072```
1073URI: /redfish/v1/EventService/Subscriptions/<ID>
1074METHOD: PATCH
1075REQUEST BODY:
1076{
1077  "Destination":"http://192.168.1.2/Events",
1078  "Context":"Changed Custom Text",
1079  "RegistryPrefix": "OpenBMC.0.2"
1080}
1081```
1082
1083  5) DeleteSubscription: Client can unsubscribe and stop receiving events
1084     by deleting the subscription.
1085```
1086URI: /redfish/v1/EventService/Subscriptions/<ID>
1087METHOD: DELETE
1088```
1089
1090** Server-Sent events subscription: **
1091
1092  1) EventListner and Subscription: Client can open latest browser (chrome)
1093     and fire GET URI on "ServerSentEventUri" along with filters.
1094```
1095URI: /redfish/v1/EventService/SSE?RegistryPrefix='OpenBMC.0.2'&MessageId='OpenBMC.0.2.xyz"
1096METHOD: GET
1097```
1098     On successful event subscription client will receive 200(Created) http
1099     status code, subscription id along with below response headers for
1100     streaming.
1101```
1102'Content-Type': 'text/event-stream',
1103'Cache-Control': 'no-cache',
1104'Connection': 'keep-alive'
1105```
1106     At this point onwards, client browser will receive events associated with
1107     subscribed data.
1108
1109     Client can use "SubmitTestEvent" (Documented above) to test the working
1110     state.
1111
1112  2) ViewSubscription: Client can get the subscriptions details using
1113```
1114URI: /redfish/v1/EventService/Subscriptions/<ID>
1115METHOD: GET
1116```
1117
1118  3) UpdateSubscription: At any point client can update the subscription
1119     information.
1120     Note Client can't change the destination as that is opaque associated with
1121     opened SSE connection.
1122```
1123URI: /redfish/v1/EventService/Subscriptions/<ID>
1124METHOD: PATCH
1125REQUEST BODY:
1126{
1127  "Context":"Changed Custom Text",
1128  "RegistryPrefix": "OpenBMC.0.2"
1129}
1130```
1131
1132  4) DeleteSubscription: There are two ways to close the connection from client.
1133     - Client can close the browser directly which will close the SSE http
1134       connection and so bmcweb service can close and delete the subscription
1135       data.
1136     - Client can also unsubscribe and stop receiving events
1137       by deleting the subscription.
1138```
1139URI: /redfish/v1/EventService/Subscriptions/<ID>
1140METHOD: DELETE
1141```
1142
1143** EventListner **
1144
1145Push style Events:
1146
1147To listen the push style events, client can have web server running on any
1148external system and subscribe to BMC with the subscription details along with
1149destination URI.
1150
1151There are multiple EventListners exist and here is simple node js server, which
1152can be run using "node server.js".
1153```
1154// server.js
1155const http = require("http");
1156var displayResponse;
1157
1158http.createServer((request, response) => {
1159    console.log("Requested url: " + request.url);
1160    const { headers, method, url } = request;
1161
1162    if ((method.toLowerCase() == "post") && (url.toLowerCase() === "/events")) {
1163        let body = [];
1164        request.on('error', (err) => {
1165          console.error(err);
1166        }).on('data', (chunk) => {
1167          body.push(chunk);
1168        }).on('end', () => {
1169          body = Buffer.concat(body).toString();
1170
1171          console.log(body);
1172          displayResponse.write(body);
1173          displayResponse.write("\n\n");
1174
1175          response.statusCode = 200;
1176          response.end();
1177        })
1178    } else if ((method.toLowerCase() == "get") && (url.toLowerCase() === "/display_events")) {
1179      response.writeHead(200, {
1180        Connection: "keep-alive",
1181        "Content-Type": "text/event-stream",
1182        "Cache-Control": "no-cache",
1183        "Access-Control-Allow-Origin": "*"
1184      });
1185
1186      displayResponse = response;
1187    } else {
1188      response.writeHead(404);
1189      response.end();
1190    }
1191  }).listen(5000, () => {
1192    console.log("Use 'http://<IP>:5000/events' as destination to subscribe for BMC events");
1193    console.log("Open 'http://<IP>:5000/display_events' URL on browser\n");
1194  });
1195```
1196
1197
1198Server-Sent Events (SSE):
1199
1200Client can open an SSE connection to the service by performing a GET
1201on the URI specified by the "ServerSentEventUri" in the Event Service
1202along with filters. Browser automatically prompt for credentials and
1203upon successful completion of authentication and authorization, client
1204connection will be established for listening events.
1205
1206You can also refer below link for details on Server-Sent events.
1207(https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events)
1208
1209Another simple python script for testing SSE using EventSource.
1210Run it using "python sse-client.py".
1211```
1212// sse-client.py
1213import requests, json, sys, time, re, os
1214import sseclient
1215from requests.packages.urllib3.exceptions import InsecureRequestWarning
1216requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
1217from sseclient import SSEClient
1218
1219try:
1220  bmc_ip = sys.argv[1]
1221  username = sys.argv[2]
1222  password = sys.argv[3]
1223
1224except:
1225  print "FAIL: Usage: <ScriptName> <BMC_IP> <Username> <Password>"
1226  print "Example: python sseClient.py 10.223.244.145 root root\n"
1227  sys.exit()
1228
1229
1230url = 'https://%s/redfish/v1/EventService/SSE?<filters>' %bmc_ip
1231
1232try:
1233  messages = SSEClient(url, verify=False, auth=(username, password))
1234
1235  for msg in messages:
1236    print(json.dumps(msg.data))
1237
1238except Exception as exc:
1239  print("\nERROR: Error in subscribing the SSE events\n")
1240```
1241
1242**EventService**
1243
1244Supported properties:
1245
1246
1247| PROPERTY NAME              | TYPE        | DESCRIPTION                       |
1248|----------------------------|-------------|-----------------------------------|
1249| ServiceEnabled | Boolean | This indicates whether event service is enabled. Default: True |
1250| DeliveryRetryAttempts | Integer | This is the number of attempts an event posting is retried before the subscription is terminated. Default: 3 |
1251| DeliveryRetryIntervalSeconds | Integer | This represents the number of seconds between retry attempts for sending any given Event. Default: 30        |
1252| EventFormatTypes | Array(string) |Indicates the content types of the message that this service can send to the event destination. ** Event: ** Resource types of 'Event' sent to subscribed destination. This is default value if nothing is specified. ** MetricReport: ** Resource types of 'MetricReport' only sent to subscribed destination.       |
1253| RegistryPrefixes | Array(string) | A list of the Prefixes of the Message Registries that can be used for the RegistryPrefix property on a subscription. If this property is absent or contains an empty array, the service does not support RegistryPrefix-based subscriptions. |
1254| ResourceTypes | Array(string) | A list of the Prefixes of the message registries that can be used for the RegistryPrefix property on a subscription. If this property is absent or contains an empty array, the service does not support RegistryPrefix-based subscriptions |
1255| ServerSentEventUri | String | The value of this property shall be a URI that specifies an HTML5 Server-Sent Event conformant endpoint. URI: /redfish/v1/EventService/SSE |
1256| Subscriptions | Object | The value of this property shall contain the link to a collection of type EventDestinationCollection. |
1257| Actions | Object | This action shall add a test event to the event service with the event data specified in the action parameters. More details on TestEvents captured below. |
1258
1259
1260Note: EventService.v1_3_0 was created to deprecate the EventTypesForSubscription
1261      and SSEFilterPropertiesSupported\EventType properties.
1262
1263Example GET Response:
1264```
1265{
1266  "@odata.context": "/redfish/v1/$metadata#EventService.EventService",
1267  "@odata.id": "/redfish/v1/EventService",
1268  "@odata.type": "#EventService.v1_3_0.EventService",
1269  "Actions": {
1270    "#EventService.SubmitTestEvent": {
1271      "target": "/redfish/v1/EventService/Actions/EventService.SubmitTestEvent"
1272    }
1273  },
1274  "DeliveryRetryAttempts": 3,
1275  "DeliveryRetryIntervalSeconds": 30,
1276  "EventFormatTypes": [
1277    "Event"
1278  ],
1279  "Id": "EventService",
1280  "Name": "Event Service",
1281  "RegistryPrefixes": [
1282    "Base",
1283    "OpenBMC"
1284  ],
1285  "ServerSentEventUri": "/redfish/v1/EventService/SSE",
1286  "ServiceEnabled": true,
1287  "Subscriptions": {
1288    "@odata.id": "/redfish/v1/EventService/Subscriptions"
1289  }
1290}
1291```
1292
1293**Subscription Collections**
1294
1295Example GET output:
1296```
1297{
1298  "@odata.type":"#EventDestinationCollection.EventDestinationCollection",
1299  "@odata.context":"/redfish/v1/$metadata#EventDestinationCollection.EventDestinationCollection",
1300  "@odata.id":"/redfish/v1/EventService/Subscriptions"
1301  "Id":"Event Subscription Collection",
1302  "Name":"Event Subscriptions Collection",
1303  "Members@odata.count": 2,
1304  "Members": [
1305    {
1306      "@odata.id":"/redfish/v1/EventService/Subscriptions/1",
1307      "@odata.id":"/redfish/v1/EventService/Subscriptions/2"
1308    }
1309  ],
1310}
1311```
1312
1313**Subscriptions**
1314
1315Supported properties:
1316
1317| PROPERTY NAME              | TYPE        | DESCRIPTION                       |
1318|----------------------------|-------------|-----------------------------------|
1319| Destination | String | The URI of the destination Event Service. |
1320| Context | String | A client-supplied string that is stored with the event destination subscription. Default: null |
1321| Protocol | Enum | The protocol type of the event connection. Default: redfish |
1322| HttpHeaders | array(string) | This is for setting HTTP headers, such as authorization information. Default: null |
1323| RegistryPrefixes | String | A list of the Prefixes for the Message Registries that contain the MessageIds that will be sent to this event destination. Default: null |
1324| ResourceTypes  | Array(String) | A list of Resource Type values (Schema names) that correspond to the OriginOfCondition. The version and full namespace should not be specified. Default: null |
1325| EventFormatType | String | Indicates the content types of the message that will be sent to the EventDestination. Supported types are 'Event' and 'MetricReport'. Default: Event |
1326
1327Example GET Request:
1328```
1329{
1330  "@odata.context": "/redfish/v1/$metadata#EventDestination.EventDestination",
1331  "@odata.id": "/redfish/v1/EventService/Subscriptions/1",
1332  "@odata.type": "#EventDestination.v1_5_0.EventDestination",
1333  "Context": "143TestString",
1334  "Destination": "http://test3.domain.com/EventListener",
1335  "EventFormatTypes": [
1336    "Event"
1337  ],
1338  "HttpHeaders": [
1339    "X-Auth-Token:XYZABCDEDF"
1340  ],
1341  "Id": "1",
1342  "MessageIds": [
1343    "InventoryAdded",
1344    "InventoryRemoved"
1345  ],
1346  "Name": "EventSubscription 1",
1347  "Protocol": "Redfish",
1348  "RegistryPrefixes": [
1349    "Base",
1350    "OpenBMC"
1351  ],
1352  "SubscriptionType": "Event"
1353}
1354```
1355
1356  - Event log formatted response body looks like:
1357```
1358id: 1
1359data:{
1360data: "@odata.type": "#Event.v1_1_0.Event",
1361data: "Id": "1",
1362data: "Name": "Event Array",
1363data: "Context": "ABCDEFGH",
1364data: "Events": [
1365data: {
1366data:  "Created": "2019-08-13T06:25:31+00:00",
1367data:  "EntryType": "Event",
1368data:  "Id": "1565677531",
1369data:  "Message": "F1UL16RISER3 Board with serial number BQWK64100593 was installed.",
1370data:  "MessageArgs": [
1371data:    "F1UL16RISER3",
1372data:    "Board",
1373data:    "BQWK64100593"
1374data:  ],
1375data:  "MessageId": "OpenBMC.0.1.InventoryAdded",
1376data:  "Name": "System Event Log Entry",
1377data:  "Severity": "OK"
1378data:  "Context": "ABCDEFGH"
1379data:  }
1380data: ]
1381data:}
1382```
1383
1384  - Configuration structure pseudo code:
1385```
1386struct EventSrvConfig
1387{
1388    bool enabled;
1389    uint32_t retryAttempts;
1390    uint32_t retryTimeoutInterval;
1391};
1392```
1393
1394  - Subscription structure pseudo code:
1395```
1396struct EventSrvSubscription
1397{
1398    std::string destinationUri;
1399    std::string customText;
1400    std::string subscriptionType;
1401    std::string protocol;
1402    std::vector<std::string> httpHeaders; // key-value pair
1403    std::vector<std::string> registryMsgIds;
1404    std::vector<std::string> registryPrefixes;
1405    std::vector<std::string> eventFormatTypes;
1406};
1407```
1408