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