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