-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
Copy pathEventManagement.cpp
970 lines (835 loc) · 36 KB
/
EventManagement.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
/**
*
* Copyright (c) 2021 Project CHIP Authors
* Copyright (c) 2015-2017 Nest Labs, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <app/EventManagement.h>
#include <app/InteractionModelEngine.h>
#include <inttypes.h>
#include <lib/core/CHIPEventLoggingConfig.h>
#include <lib/core/CHIPTLVUtilities.hpp>
#include <lib/support/CodeUtils.h>
#include <lib/support/ErrorStr.h>
#include <lib/support/logging/CHIPLogging.h>
using namespace chip::TLV;
namespace chip {
namespace app {
static EventManagement sInstance;
/**
* @brief
* A TLVReader backed by CircularEventBuffer
*/
class CircularEventReader : public TLV::TLVReader
{
public:
/**
* @brief
* Initializes a TLVReader object backed by CircularEventBuffer
*
* Reading begins in the CircularTLVBuffer belonging to this
* CircularEventBuffer. When the reader runs out of data, it begins
* to read from the previous CircularEventBuffer.
*
* @param[in] apBuf A pointer to a fully initialized CircularEventBuffer
*
*/
void Init(CircularEventBufferWrapper * apBuf);
virtual ~CircularEventReader() = default;
};
EventManagement & EventManagement::GetInstance(void)
{
return sInstance;
}
struct ReclaimEventCtx
{
CircularEventBuffer * mpEventBuffer = nullptr;
size_t mSpaceNeededForMovedEvent = 0;
};
/**
* @brief
* Internal structure for traversing event list.
*/
struct CopyAndAdjustDeltaTimeContext
{
CopyAndAdjustDeltaTimeContext(TLVWriter * aWriter, EventLoadOutContext * inContext) : mpWriter(aWriter), mpContext(inContext) {}
TLV::TLVWriter * mpWriter = nullptr;
EventLoadOutContext * mpContext = nullptr;
};
/**
* @brief
* Internal structure for traversing events.
*/
struct EventEnvelopeContext
{
EventEnvelopeContext() {}
uint16_t mFieldsToRead = 0;
/* PriorityLevel and DeltaSystemTimestamp are there if that is not first event when putting events in report*/
Timestamp mDeltaSystemTime = Timestamp::System(System::Clock::kZero);
Timestamp mDeltaUtc = Timestamp::UTC(0);
PriorityLevel mPriority = PriorityLevel::First;
NodeId mNodeId = 0;
ClusterId mClusterId = 0;
EndpointId mEndpointId = 0;
EventId mEventId = 0;
};
void EventManagement::Init(Messaging::ExchangeManager * apExchangeManager, uint32_t aNumBuffers,
CircularEventBuffer * apCircularEventBuffer, const LogStorageResources * const apLogStorageResources)
{
CircularEventBuffer * current = nullptr;
CircularEventBuffer * prev = nullptr;
CircularEventBuffer * next = nullptr;
if (aNumBuffers == 0)
{
ChipLogError(EventLogging, "Invalid aNumBuffers");
return;
}
if (mState != EventManagementStates::Shutdown)
{
ChipLogError(EventLogging, "Invalid EventManagement State");
return;
}
mpExchangeMgr = apExchangeManager;
for (uint32_t bufferIndex = 0; bufferIndex < aNumBuffers; bufferIndex++)
{
next = (bufferIndex < aNumBuffers - 1) ? &apCircularEventBuffer[bufferIndex + 1] : nullptr;
current = &apCircularEventBuffer[bufferIndex];
current->Init(apLogStorageResources[bufferIndex].mpBuffer, apLogStorageResources[bufferIndex].mBufferSize, prev, next,
apLogStorageResources[bufferIndex].mPriority);
prev = current;
current->mProcessEvictedElement = AlwaysFail;
current->mAppData = nullptr;
current->InitCounter(apLogStorageResources[bufferIndex].InitializeCounter());
}
mpEventBuffer = apCircularEventBuffer;
mState = EventManagementStates::Idle;
mBytesWritten = 0;
#if !CHIP_SYSTEM_CONFIG_NO_LOCKING
CHIP_ERROR err = chip::System::Mutex::Init(mAccessLock);
if (err != CHIP_NO_ERROR)
{
ChipLogError(EventLogging, "mutex init fails with error %s", ErrorStr(err));
}
#endif // !CHIP_SYSTEM_CONFIG_NO_LOCKING
}
CHIP_ERROR EventManagement::CopyToNextBuffer(CircularEventBuffer * apEventBuffer)
{
CircularTLVWriter writer;
CircularTLVReader reader;
CHIP_ERROR err = CHIP_NO_ERROR;
CircularEventBuffer * nextBuffer = apEventBuffer->GetNextCircularEventBuffer();
if (nextBuffer == nullptr)
{
return CHIP_ERROR_INVALID_ARGUMENT;
}
CircularEventBuffer backup = *nextBuffer;
// Set up the next buffer s.t. it fails if needs to evict an element
nextBuffer->mProcessEvictedElement = AlwaysFail;
writer.Init(*nextBuffer);
// Set up the reader s.t. it is positioned to read the head event
reader.Init(*apEventBuffer);
err = reader.Next();
SuccessOrExit(err);
err = writer.CopyElement(reader);
SuccessOrExit(err);
err = writer.Finalize();
SuccessOrExit(err);
ChipLogProgress(EventLogging, "Copy Event to next buffer with priority %u", static_cast<unsigned>(nextBuffer->GetPriority()));
exit:
if (err != CHIP_NO_ERROR)
{
*nextBuffer = backup;
}
return err;
}
CHIP_ERROR EventManagement::EnsureSpaceInCircularBuffer(size_t aRequiredSpace)
{
CHIP_ERROR err = CHIP_NO_ERROR;
size_t requiredSpace = aRequiredSpace;
CircularEventBuffer * eventBuffer = mpEventBuffer;
ReclaimEventCtx ctx;
// check whether we actually need to do anything, exit if we don't
VerifyOrExit(requiredSpace > eventBuffer->AvailableDataLength(), err = CHIP_NO_ERROR);
while (true)
{
// check that the request can ultimately be satisfied.
VerifyOrExit(requiredSpace <= eventBuffer->GetTotalDataLength(), err = CHIP_ERROR_BUFFER_TOO_SMALL);
if (requiredSpace > eventBuffer->AvailableDataLength())
{
ctx.mpEventBuffer = eventBuffer;
ctx.mSpaceNeededForMovedEvent = 0;
eventBuffer->mProcessEvictedElement = EvictEvent;
eventBuffer->mAppData = &ctx;
err = eventBuffer->EvictHead();
// one of two things happened: either the element was evicted immediately if the head's priority is same as current
// buffer(final one), or we figured out how much space we need to evict it into the next buffer, the check happens in
// EvictEvent function
if (err != CHIP_NO_ERROR)
{
VerifyOrExit(ctx.mSpaceNeededForMovedEvent != 0, /* no-op, return err */);
VerifyOrExit(eventBuffer->GetNextCircularEventBuffer() != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
if (ctx.mSpaceNeededForMovedEvent <= eventBuffer->GetNextCircularEventBuffer()->AvailableDataLength())
{
// we can copy the event outright. copy event and
// subsequently evict head s.t. evicting the head
// element always succeeds.
// Since we're calling CopyElement and we've checked
// that there is space in the next buffer, we don't expect
// this to fail.
err = CopyToNextBuffer(eventBuffer);
SuccessOrExit(err);
// success; evict head unconditionally
eventBuffer->mProcessEvictedElement = nullptr;
err = eventBuffer->EvictHead();
// if unconditional eviction failed, this
// means that we have no way of further
// clearing the buffer. fail out and let the
// caller know that we could not honor the
// request
SuccessOrExit(err);
continue;
}
// we cannot copy event outright. We remember the
// current required space in mRequiredSpaceForEvicted, we note the
// space requirements for the event in the current
// buffer and make that space in the next buffer.
eventBuffer->SetRequiredSpaceforEvicted(requiredSpace);
eventBuffer = eventBuffer->GetNextCircularEventBuffer();
// Sanity check: return error here on null event buffer. If
// eventBuffer->mpNext were null, then the `EvictBuffer`
// would have succeeded -- the event was
// already in the final buffer.
VerifyOrExit(eventBuffer != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
requiredSpace = ctx.mSpaceNeededForMovedEvent;
}
}
else
{
// this branch is only taken when we go back in the buffer chain since we have free/spare enough space in next buffer,
// and need to retry to copy event from current buffer to next buffer, and free space for current buffer
if (eventBuffer == mpEventBuffer)
break;
eventBuffer = eventBuffer->GetPreviousCircularEventBuffer();
requiredSpace = eventBuffer->GetRequiredSpaceforEvicted();
err = CHIP_NO_ERROR;
}
}
// On exit, configure the top-level s.t. it will always fail to evict an element
mpEventBuffer->mProcessEvictedElement = AlwaysFail;
mpEventBuffer->mAppData = nullptr;
exit:
return err;
}
CHIP_ERROR EventManagement::CalculateEventSize(EventLoggingDelegate * apDelegate, const EventOptions * apOptions,
uint32_t & requiredSize)
{
CHIP_ERROR err = CHIP_NO_ERROR;
System::PacketBufferTLVWriter writer;
EventLoadOutContext ctxt = EventLoadOutContext(writer, apOptions->mpEventSchema->mPriority,
GetPriorityBuffer(apOptions->mpEventSchema->mPriority)->GetLastEventNumber());
System::PacketBufferHandle buf = System::PacketBufferHandle::New(kMaxEventSizeReserve);
if (buf.IsNull())
{
return CHIP_ERROR_NO_MEMORY;
}
writer.Init(std::move(buf));
ctxt.mCurrentEventNumber = GetPriorityBuffer(apOptions->mpEventSchema->mPriority)->GetLastEventNumber();
ctxt.mCurrentSystemTime.mValue = GetPriorityBuffer(apOptions->mpEventSchema->mPriority)->GetLastEventSystemTimestamp();
err = ConstructEvent(&ctxt, apDelegate, apOptions);
if (CHIP_NO_ERROR == err)
{
requiredSize = writer.GetLengthWritten();
}
return err;
}
CHIP_ERROR EventManagement::ConstructEvent(EventLoadOutContext * apContext, EventLoggingDelegate * apDelegate,
const EventOptions * apOptions)
{
CHIP_ERROR err = CHIP_NO_ERROR;
TLVWriter checkpoint = apContext->mWriter;
TLV::TLVType dataContainerType;
EventReportIB::Builder eventReportBuilder;
EventDataIB::Builder eventDataIBBuilder;
EventPathIB::Builder eventPathBuilder;
EventStatusIB::Builder eventStatusIBBuilder;
StatusIB::Builder statusIBBuilder;
StatusIB status;
uint64_t deltatime = 0;
VerifyOrExit(apContext->mCurrentEventNumber >= apContext->mStartingEventNumber,
/* no-op: don't write event, but advance current event Number */);
VerifyOrExit(apOptions != nullptr, err = CHIP_ERROR_INVALID_ARGUMENT);
VerifyOrExit(apOptions->mTimestamp.mType != Timestamp::Type::kInvalid, err = CHIP_ERROR_INVALID_ARGUMENT);
eventReportBuilder.Init(&(apContext->mWriter));
// TODO: Update IsUrgent
// TODO: Update statusIB
eventStatusIBBuilder = eventReportBuilder.CreateEventStatus();
eventPathBuilder = eventStatusIBBuilder.CreatePath();
err = eventStatusIBBuilder.GetError();
SuccessOrExit(err);
eventPathBuilder.Node(apOptions->mpEventSchema->mNodeId)
.Endpoint(apOptions->mpEventSchema->mEndpointId)
.Cluster(apOptions->mpEventSchema->mClusterId)
.Event(apOptions->mpEventSchema->mEventId)
.IsUrgent(false)
.EndOfEventPathIB();
err = eventPathBuilder.GetError();
SuccessOrExit(err);
statusIBBuilder = eventStatusIBBuilder.CreateErrorStatus();
err = eventStatusIBBuilder.GetError();
SuccessOrExit(err);
statusIBBuilder.EncodeStatusIB(status);
eventStatusIBBuilder.EndOfEventStatusIB();
err = statusIBBuilder.GetError();
SuccessOrExit(err);
eventDataIBBuilder = eventReportBuilder.CreateEventData();
eventPathBuilder = eventDataIBBuilder.CreatePath();
err = eventDataIBBuilder.GetError();
SuccessOrExit(err);
// TODO: Revisit NodeId since the the encoding spec and the IM seem to disagree on how this stuff works
eventPathBuilder.Node(apOptions->mpEventSchema->mNodeId)
.Endpoint(apOptions->mpEventSchema->mEndpointId)
.Cluster(apOptions->mpEventSchema->mClusterId)
.Event(apOptions->mpEventSchema->mEventId)
.IsUrgent(false)
.EndOfEventPathIB();
err = eventPathBuilder.GetError();
SuccessOrExit(err);
eventDataIBBuilder.Priority(chip::to_underlying(apContext->mPriority));
// TODO: need to add utc and systen system check here
deltatime = apOptions->mTimestamp.mValue - apContext->mCurrentSystemTime.mValue;
eventDataIBBuilder.DeltaSystemTimestamp(deltatime);
err = eventDataIBBuilder.GetError();
SuccessOrExit(err);
err = apContext->mWriter.StartContainer(ContextTag(chip::to_underlying(EventDataIB::Tag::kData)), TLV::kTLVType_Structure,
dataContainerType);
SuccessOrExit(err);
// Callback to write the EventData
err = apDelegate->WriteEvent(apContext->mWriter);
SuccessOrExit(err);
err = apContext->mWriter.EndContainer(dataContainerType);
SuccessOrExit(err);
eventDataIBBuilder.EndOfEventDataIB();
SuccessOrExit(err = eventDataIBBuilder.GetError());
eventReportBuilder.EndOfEventReportIB();
SuccessOrExit(err = eventReportBuilder.GetError());
err = apContext->mWriter.Finalize();
SuccessOrExit(err);
apContext->mFirst = false;
exit:
if (err != CHIP_NO_ERROR)
{
apContext->mWriter = checkpoint;
}
else
{
// update these variables since ConstructEvent can be used to track the
// state of a set of events over multiple calls.
apContext->mCurrentEventNumber++;
if (apContext->mCurrentSystemTime.mType == Timestamp::Type::kSystem)
{
apContext->mCurrentSystemTime = apOptions->mTimestamp;
}
}
return err;
}
void EventManagement::CreateEventManagement(Messaging::ExchangeManager * apExchangeManager, uint32_t aNumBuffers,
CircularEventBuffer * apCircularEventBuffer,
const LogStorageResources * const apLogStorageResources)
{
sInstance.Init(apExchangeManager, aNumBuffers, apCircularEventBuffer, apLogStorageResources);
}
/**
* @brief Perform any actions we need to on shutdown.
*/
void EventManagement::DestroyEventManagement()
{
#if !CHIP_SYSTEM_CONFIG_NO_LOCKING
ScopedLock lock(sInstance);
#endif // !CHIP_SYSTEM_CONFIG_NO_LOCKING
sInstance.mState = EventManagementStates::Shutdown;
sInstance.mpEventBuffer = nullptr;
sInstance.mpExchangeMgr = nullptr;
}
EventNumber CircularEventBuffer::VendEventNumber()
{
CHIP_ERROR err = CHIP_NO_ERROR;
// Assign event Number to the buffer's counter's value.
mLastEventNumber = static_cast<EventNumber>(mpEventNumberCounter->GetValue());
// Now advance the counter.
err = mpEventNumberCounter->Advance();
if (err != CHIP_NO_ERROR)
{
ChipLogError(EventLogging, "%s Advance() for priority %u failed with %" CHIP_ERROR_FORMAT, __FUNCTION__,
static_cast<unsigned>(mPriority), err.Format());
}
return mLastEventNumber;
}
EventNumber EventManagement::GetLastEventNumber(PriorityLevel aPriority)
{
return GetPriorityBuffer(aPriority)->GetLastEventNumber();
}
EventNumber EventManagement::GetFirstEventNumber(PriorityLevel aPriority)
{
return GetPriorityBuffer(aPriority)->GetFirstEventNumber();
}
CircularEventBuffer * EventManagement::GetPriorityBuffer(PriorityLevel aPriority) const
{
CircularEventBuffer * buf = mpEventBuffer;
while (!buf->IsFinalDestinationForPriority(aPriority))
{
buf = buf->GetNextCircularEventBuffer();
assert(buf != nullptr);
// code guarantees that every PriorityLevel has a buffer destination.
}
return buf;
}
CHIP_ERROR EventManagement::CopyAndAdjustDeltaTime(const TLVReader & aReader, size_t aDepth, void * apContext)
{
CHIP_ERROR err;
CopyAndAdjustDeltaTimeContext * ctx = static_cast<CopyAndAdjustDeltaTimeContext *>(apContext);
TLVReader reader(aReader);
// TODO: Add UTC timestamp support
if (aReader.GetTag() == TLV::ContextTag(to_underlying(EventDataIB::Tag::kDeltaSystemTimestamp)))
{
if (ctx->mpContext->mFirst) // First event gets a timestamp, subsequent ones get a delta T
{
err = ctx->mpWriter->Put(TLV::ContextTag(to_underlying(EventDataIB::Tag::kSystemTimestamp)),
ctx->mpContext->mCurrentSystemTime.mValue);
}
else
{
err = ctx->mpWriter->Put(TLV::ContextTag(to_underlying(EventDataIB::Tag::kDeltaSystemTimestamp)),
ctx->mpContext->mCurrentSystemTime.mValue - ctx->mpContext->mPreviousSystemTime.mValue);
}
}
else
{
err = ctx->mpWriter->CopyElement(reader);
}
// First event in the sequence gets a event number neatly packaged
// right after the priority to keep tags ordered
if (aReader.GetTag() == TLV::ContextTag(to_underlying(EventDataIB::Tag::kPriority)))
{
if (ctx->mpContext->mFirst)
{
err = ctx->mpWriter->Put(TLV::ContextTag(to_underlying(EventDataIB::Tag::kEventNumber)),
ctx->mpContext->mCurrentEventNumber);
}
}
return err;
}
CHIP_ERROR EventManagement::LogEvent(EventLoggingDelegate * apDelegate, EventOptions & aEventOptions, EventNumber & aEventNumber)
{
CHIP_ERROR err = CHIP_NO_ERROR;
{
#if !CHIP_SYSTEM_CONFIG_NO_LOCKING
ScopedLock lock(sInstance);
#endif // !CHIP_SYSTEM_CONFIG_NO_LOCKING
VerifyOrExit(mState != EventManagementStates::Shutdown, err = CHIP_ERROR_INCORRECT_STATE);
VerifyOrExit(aEventOptions.mpEventSchema != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = LogEventPrivate(apDelegate, aEventOptions, aEventNumber);
}
exit:
return err;
}
CHIP_ERROR EventManagement::LogEventPrivate(EventLoggingDelegate * apDelegate, EventOptions & aEventOptions,
EventNumber & aEventNumber)
{
CircularTLVWriter writer;
CHIP_ERROR err = CHIP_NO_ERROR;
uint32_t requestSize = 0;
aEventNumber = 0;
CircularEventBuffer checkpoint = *mpEventBuffer;
CircularEventBuffer * buffer = nullptr;
EventLoadOutContext ctxt = EventLoadOutContext(writer, aEventOptions.mpEventSchema->mPriority,
GetPriorityBuffer(aEventOptions.mpEventSchema->mPriority)->GetLastEventNumber());
Timestamp timestamp(System::SystemClock().GetMonotonicTimestamp());
EventOptions opts = EventOptions(timestamp);
// Start the event container (anonymous structure) in the circular buffer
writer.Init(*mpEventBuffer);
// check whether the entry is to be logged or discarded silently
VerifyOrExit(aEventOptions.mpEventSchema->mPriority >= CHIP_CONFIG_EVENT_GLOBAL_PRIORITY, /* no-op */);
// Create all event specific data
// Timestamp; encoded as a delta time
if (aEventOptions.mTimestamp.mType == Timestamp::Type::kSystem)
{
opts.mTimestamp = aEventOptions.mTimestamp;
}
if (GetPriorityBuffer(aEventOptions.mpEventSchema->mPriority)->GetFirstEventSystemTimestamp() == 0)
{
GetPriorityBuffer(aEventOptions.mpEventSchema->mPriority)->UpdateFirstLastEventTime(opts.mTimestamp);
}
opts.mUrgent = aEventOptions.mUrgent;
opts.mpEventSchema = aEventOptions.mpEventSchema;
ctxt.mCurrentEventNumber = GetPriorityBuffer(opts.mpEventSchema->mPriority)->GetLastEventNumber();
ctxt.mCurrentSystemTime.mValue = GetPriorityBuffer(opts.mpEventSchema->mPriority)->GetLastEventSystemTimestamp();
err = CalculateEventSize(apDelegate, &opts, requestSize);
SuccessOrExit(err);
// Ensure we have space in the in-memory logging queues
err = EnsureSpaceInCircularBuffer(requestSize);
SuccessOrExit(err);
err = ConstructEvent(&ctxt, apDelegate, &opts);
SuccessOrExit(err);
// Check the number of bytes written. If the event is too large
// to be evicted from subsequent buffers, drop it now.
buffer = mpEventBuffer;
while (true)
{
VerifyOrExit(buffer->GetTotalDataLength() >= writer.GetLengthWritten(), err = CHIP_ERROR_BUFFER_TOO_SMALL);
if (buffer->IsFinalDestinationForPriority(opts.mpEventSchema->mPriority))
{
break;
}
else
{
buffer = buffer->GetNextCircularEventBuffer();
assert(buffer != nullptr);
// code guarantees that every PriorityLevel has a buffer destination.
}
}
mBytesWritten += writer.GetLengthWritten();
exit:
if (err != CHIP_NO_ERROR)
{
*mpEventBuffer = checkpoint;
}
else if (opts.mpEventSchema->mPriority >= CHIP_CONFIG_EVENT_GLOBAL_PRIORITY)
{
CircularEventBuffer * currentBuffer = GetPriorityBuffer(opts.mpEventSchema->mPriority);
aEventNumber = currentBuffer->VendEventNumber();
currentBuffer->UpdateFirstLastEventTime(opts.mTimestamp);
#if CHIP_CONFIG_EVENT_LOGGING_VERBOSE_DEBUG_LOGS
ChipLogDetail(EventLogging,
"LogEvent event number: 0x" ChipLogFormatX64 " schema priority: %u cluster id: " ChipLogFormatMEI
" event id: 0x%" PRIx32 " sys timestamp: 0x" ChipLogFormatX64,
ChipLogValueX64(aEventNumber), static_cast<unsigned>(opts.mpEventSchema->mPriority),
ChipLogValueMEI(opts.mpEventSchema->mClusterId), opts.mpEventSchema->mEventId,
ChipLogValueX64(opts.mTimestamp.mValue));
#endif // CHIP_CONFIG_EVENT_LOGGING_VERBOSE_DEBUG_LOGS
ScheduleFlushIfNeeded(opts.mUrgent);
}
return err;
}
CHIP_ERROR EventManagement::CopyEvent(const TLVReader & aReader, TLVWriter & aWriter, EventLoadOutContext * apContext)
{
TLVReader reader;
TLVType containerType;
TLVType containerType1;
TLVType containerType2;
CopyAndAdjustDeltaTimeContext context(&aWriter, apContext);
CHIP_ERROR err = CHIP_NO_ERROR;
reader.Init(aReader);
ReturnErrorOnFailure(reader.EnterContainer(containerType));
ReturnErrorOnFailure(aWriter.StartContainer(AnonymousTag, kTLVType_Structure, containerType));
ReturnErrorOnFailure(reader.Next());
ReturnErrorOnFailure(reader.EnterContainer(containerType1));
ReturnErrorOnFailure(aWriter.StartContainer(TLV::ContextTag(to_underlying(EventReportIB::Tag::kEventStatus)),
kTLVType_Structure, containerType1));
ReturnErrorOnFailure(reader.Next());
do
{
ReturnErrorOnFailure(aWriter.CopyElement(reader));
} while (CHIP_NO_ERROR == (err = reader.Next()));
if (err == CHIP_END_OF_TLV)
{
err = CHIP_NO_ERROR;
}
ReturnErrorOnFailure(err);
ReturnErrorOnFailure(reader.ExitContainer(containerType1));
ReturnErrorOnFailure(aWriter.EndContainer(containerType1));
ReturnErrorOnFailure(reader.Next());
ReturnErrorOnFailure(reader.EnterContainer(containerType2));
ReturnErrorOnFailure(
aWriter.StartContainer(TLV::ContextTag(to_underlying(EventReportIB::Tag::kEventData)), kTLVType_Structure, containerType2));
err = TLV::Utilities::Iterate(reader, CopyAndAdjustDeltaTime, &context, false /*recurse*/);
if (err == CHIP_END_OF_TLV)
{
err = CHIP_NO_ERROR;
}
ReturnErrorOnFailure(err);
ReturnErrorOnFailure(aWriter.EndContainer(containerType2));
ReturnErrorOnFailure(aWriter.EndContainer(containerType));
ReturnErrorOnFailure(aWriter.Finalize());
return CHIP_NO_ERROR;
}
static bool IsInterestedEventPaths(EventLoadOutContext * eventLoadOutContext, const EventEnvelopeContext & event)
{
ClusterInfo * interestedEventPaths = eventLoadOutContext->mpInterestedEventPaths;
if (eventLoadOutContext->mCurrentEventNumber < eventLoadOutContext->mStartingEventNumber)
{
return false;
}
while (interestedEventPaths != nullptr)
{
if (interestedEventPaths->mNodeId == event.mNodeId && interestedEventPaths->mEndpointId == event.mEndpointId &&
interestedEventPaths->mClusterId == event.mClusterId && interestedEventPaths->mEventId == event.mEventId)
{
return true;
}
interestedEventPaths = interestedEventPaths->mpNext;
}
return false;
}
CHIP_ERROR EventManagement::EventIterator(const TLVReader & aReader, size_t aDepth, EventLoadOutContext * apEventLoadOutContext)
{
CHIP_ERROR err = CHIP_NO_ERROR;
TLVReader innerReader;
TLVType tlvType;
TLVType tlvType1;
EventEnvelopeContext event;
innerReader.Init(aReader);
ReturnErrorOnFailure(innerReader.EnterContainer(tlvType));
ReturnErrorOnFailure(innerReader.Next());
// Skip EventStatus Element
ReturnErrorOnFailure(innerReader.Next());
ReturnErrorOnFailure(innerReader.EnterContainer(tlvType1));
err = TLV::Utilities::Iterate(innerReader, FetchEventParameters, &event, false /*recurse*/);
if (event.mFieldsToRead != kRequiredEventField)
{
return CHIP_ERROR_INVALID_ARGUMENT;
}
if (err == CHIP_END_OF_TLV)
{
err = CHIP_NO_ERROR;
}
ReturnErrorOnFailure(err);
if (event.mPriority == apEventLoadOutContext->mPriority)
{
apEventLoadOutContext->mCurrentSystemTime.mValue += event.mDeltaSystemTime.mValue;
if (IsInterestedEventPaths(apEventLoadOutContext, event))
{
return CHIP_EVENT_ID_FOUND;
}
}
return CHIP_NO_ERROR;
}
CHIP_ERROR EventManagement::CopyEventsSince(const TLVReader & aReader, size_t aDepth, void * apContext)
{
EventLoadOutContext * const loadOutContext = static_cast<EventLoadOutContext *>(apContext);
CHIP_ERROR err = EventIterator(aReader, aDepth, loadOutContext);
loadOutContext->mCurrentEventNumber++;
if (err == CHIP_EVENT_ID_FOUND)
{
// checkpoint the writer
TLV::TLVWriter checkpoint = loadOutContext->mWriter;
err = CopyEvent(aReader, loadOutContext->mWriter, loadOutContext);
// CHIP_NO_ERROR and CHIP_END_OF_TLV signify a
// successful copy. In all other cases, roll back the
// writer state back to the checkpoint, i.e., the state
// before we began the copy operation.
if ((err != CHIP_NO_ERROR) && (err != CHIP_END_OF_TLV))
{
loadOutContext->mWriter = checkpoint;
return err;
}
loadOutContext->mPreviousSystemTime.mValue = loadOutContext->mCurrentSystemTime.mValue;
loadOutContext->mFirst = false;
loadOutContext->mEventCount++;
}
return err;
}
CHIP_ERROR EventManagement::FetchEventsSince(TLVWriter & aWriter, ClusterInfo * apClusterInfolist, PriorityLevel aPriority,
EventNumber & aEventNumber, size_t & aEventCount)
{
// TODO: Add particular set of event Paths in FetchEventsSince so that we can filter the interested paths
CHIP_ERROR err = CHIP_NO_ERROR;
const bool recurse = false;
TLVReader reader;
CircularEventBufferWrapper bufWrapper;
EventLoadOutContext context(aWriter, aPriority, aEventNumber);
CircularEventBuffer * buf = mpEventBuffer;
#if !CHIP_SYSTEM_CONFIG_NO_LOCKING
ScopedLock lock(sInstance);
#endif // !CHIP_SYSTEM_CONFIG_NO_LOCKING
while (!buf->IsFinalDestinationForPriority(aPriority))
{
buf = buf->GetNextCircularEventBuffer();
}
context.mpInterestedEventPaths = apClusterInfolist;
context.mCurrentSystemTime.mValue = buf->GetFirstEventSystemTimestamp();
context.mCurrentEventNumber = buf->GetFirstEventNumber();
err = GetEventReader(reader, aPriority, &bufWrapper);
SuccessOrExit(err);
err = TLV::Utilities::Iterate(reader, CopyEventsSince, &context, recurse);
if (err == CHIP_END_OF_TLV)
{
err = CHIP_NO_ERROR;
}
exit:
aEventNumber = context.mCurrentEventNumber;
aEventCount += context.mEventCount;
return err;
}
CHIP_ERROR EventManagement::GetEventReader(TLVReader & aReader, PriorityLevel aPriority, CircularEventBufferWrapper * apBufWrapper)
{
CircularEventBuffer * buffer = GetPriorityBuffer(aPriority);
VerifyOrReturnError(buffer != nullptr, CHIP_ERROR_INVALID_ARGUMENT);
apBufWrapper->mpCurrent = buffer;
CircularEventReader reader;
reader.Init(apBufWrapper);
aReader.Init(reader);
return CHIP_NO_ERROR;
}
CHIP_ERROR EventManagement::FetchEventParameters(const TLVReader & aReader, size_t aDepth, void * apContext)
{
EventEnvelopeContext * const envelope = static_cast<EventEnvelopeContext *>(apContext);
TLVReader reader;
reader.Init(aReader);
if (reader.GetTag() == TLV::ContextTag(to_underlying(EventDataIB::Tag::kPath)))
{
EventPathIB::Parser path;
ReturnErrorOnFailure(path.Init(aReader));
ReturnErrorOnFailure(path.GetNode(&(envelope->mNodeId)));
ReturnErrorOnFailure(path.GetEndpoint(&(envelope->mEndpointId)));
ReturnErrorOnFailure(path.GetCluster(&(envelope->mClusterId)));
ReturnErrorOnFailure(path.GetEvent(&(envelope->mEventId)));
envelope->mFieldsToRead |= 1 << to_underlying(EventDataIB::Tag::kPath);
}
if (reader.GetTag() == TLV::ContextTag(to_underlying(EventDataIB::Tag::kPriority)))
{
uint16_t extPriority; // Note: the type here matches the type case in EventManagement::LogEvent, priority section
ReturnErrorOnFailure(reader.Get(extPriority));
envelope->mPriority = static_cast<PriorityLevel>(extPriority);
envelope->mFieldsToRead |= 1 << to_underlying(EventDataIB::Tag::kPriority);
}
if (reader.GetTag() == TLV::ContextTag(to_underlying(EventDataIB::Tag::kDeltaSystemTimestamp)))
{
ReturnErrorOnFailure(reader.Get(envelope->mDeltaSystemTime.mValue));
envelope->mFieldsToRead |= 1 << to_underlying(EventDataIB::Tag::kDeltaSystemTimestamp);
}
return CHIP_NO_ERROR;
}
CHIP_ERROR EventManagement::EvictEvent(CHIPCircularTLVBuffer & apBuffer, void * apAppData, TLVReader & aReader)
{
// pull out the delta time, pull out the priority
ReturnErrorOnFailure(aReader.Next());
TLVType containerType;
TLVType containerType1;
ReturnErrorOnFailure(aReader.EnterContainer(containerType));
ReturnErrorOnFailure(aReader.Next());
// Skip EventStatus
ReturnErrorOnFailure(aReader.Next());
ReturnErrorOnFailure(aReader.EnterContainer(containerType1));
EventEnvelopeContext context;
constexpr bool recurse = false;
CHIP_ERROR err = TLV::Utilities::Iterate(aReader, FetchEventParameters, &context, recurse);
if (err == CHIP_END_OF_TLV)
{
err = CHIP_NO_ERROR;
}
ReturnErrorOnFailure(err);
ReturnErrorOnFailure(aReader.ExitContainer(containerType1));
ReturnErrorOnFailure(aReader.ExitContainer(containerType));
const PriorityLevel imp = static_cast<PriorityLevel>(context.mPriority);
ReclaimEventCtx * const ctx = static_cast<ReclaimEventCtx *>(apAppData);
CircularEventBuffer * const eventBuffer = ctx->mpEventBuffer;
if (eventBuffer->IsFinalDestinationForPriority(imp))
{
// event is getting dropped. Increase the event number and first timestamp.
EventNumber numEventsToDrop = 1;
eventBuffer->RemoveEvent(numEventsToDrop);
eventBuffer->SetFirstEventSystemTimestamp(eventBuffer->GetFirstEventSystemTimestamp() + context.mDeltaSystemTime.mValue);
ChipLogProgress(
EventLogging,
"Dropped events from buffer with priority %u due to overflow: { event priority_level: %u, count: 0x" ChipLogFormatX64
" };",
static_cast<unsigned>(eventBuffer->GetPriority()), static_cast<unsigned>(imp), ChipLogValueX64(numEventsToDrop));
ctx->mSpaceNeededForMovedEvent = 0;
return CHIP_NO_ERROR;
}
// event is not getting dropped. Note how much space it requires, and return.
ctx->mSpaceNeededForMovedEvent = aReader.GetLengthRead();
return CHIP_END_OF_TLV;
}
CHIP_ERROR EventManagement::ScheduleFlushIfNeeded(EventOptions::Type aUrgent)
{
// TODO: Implement ScheduleFlushIfNeeded
return CHIP_NO_ERROR;
}
void EventManagement::SetScheduledEventEndpoint(EventNumber * apEventEndpoints)
{
CircularEventBuffer * eventBuffer = mpEventBuffer;
#if !CHIP_SYSTEM_CONFIG_NO_LOCKING
ScopedLock lock(sInstance);
#endif // !CHIP_SYSTEM_CONFIG_NO_LOCKING
while (eventBuffer != nullptr)
{
if (eventBuffer->GetPriority() >= PriorityLevel::First && (eventBuffer->GetPriority() <= PriorityLevel::Last))
{
apEventEndpoints[static_cast<uint8_t>(eventBuffer->GetPriority())] = eventBuffer->GetLastEventNumber();
}
eventBuffer = eventBuffer->GetNextCircularEventBuffer();
}
}
void CircularEventBuffer::Init(uint8_t * apBuffer, uint32_t aBufferLength, CircularEventBuffer * apPrev,
CircularEventBuffer * apNext, PriorityLevel aPriorityLevel)
{
CHIPCircularTLVBuffer::Init(apBuffer, aBufferLength);
mpPrev = apPrev;
mpNext = apNext;
mPriority = aPriorityLevel;
mFirstEventNumber = 1;
mLastEventNumber = 0;
mFirstEventSystemTimestamp = Timestamp::System(System::Clock::kZero);
mLastEventSystemTimestamp = Timestamp::System(System::Clock::kZero);
mpEventNumberCounter = nullptr;
}
bool CircularEventBuffer::IsFinalDestinationForPriority(PriorityLevel aPriority) const
{
return !((mpNext != nullptr) && (mpNext->mPriority <= aPriority));
}
void CircularEventBuffer::UpdateFirstLastEventTime(Timestamp aEventTimestamp)
{
if (mFirstEventSystemTimestamp.mValue == 0)
{
mFirstEventSystemTimestamp = aEventTimestamp;
mLastEventSystemTimestamp = aEventTimestamp;
}
mLastEventSystemTimestamp = aEventTimestamp;
}
void CircularEventBuffer::RemoveEvent(EventNumber aNumEvents)
{
mFirstEventNumber = mFirstEventNumber + aNumEvents;
}
void CircularEventReader::Init(CircularEventBufferWrapper * apBufWrapper)
{
CircularEventBuffer * prev;
if (apBufWrapper->mpCurrent == nullptr)
return;
TLVReader::Init(*apBufWrapper, apBufWrapper->mpCurrent->DataLength());
mMaxLen = apBufWrapper->mpCurrent->DataLength();
for (prev = apBufWrapper->mpCurrent->GetPreviousCircularEventBuffer(); prev != nullptr;
prev = prev->GetPreviousCircularEventBuffer())
{
CircularEventBufferWrapper bufWrapper;
bufWrapper.mpCurrent = prev;
mMaxLen += prev->DataLength();
}
}
CHIP_ERROR CircularEventBufferWrapper::GetNextBuffer(TLVReader & aReader, const uint8_t *& aBufStart, uint32_t & aBufLen)
{
CHIP_ERROR err = CHIP_NO_ERROR;
mpCurrent->GetNextBuffer(aReader, aBufStart, aBufLen);
SuccessOrExit(err);
if ((aBufLen == 0) && (mpCurrent->GetPreviousCircularEventBuffer() != nullptr))
{
mpCurrent = mpCurrent->GetPreviousCircularEventBuffer();
aBufStart = nullptr;
err = GetNextBuffer(aReader, aBufStart, aBufLen);
}
exit:
return err;
}
} // namespace app
} // namespace chip