forked from FreeOpcUa/freeopcua
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathinternal_subscription.cpp
More file actions
619 lines (480 loc) · 19.6 KB
/
Copy pathinternal_subscription.cpp
File metadata and controls
619 lines (480 loc) · 19.6 KB
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
#include "internal_subscription.h"
#include <boost/thread/locks.hpp>
namespace OpcUa
{
namespace Internal
{
InternalSubscription::InternalSubscription(SubscriptionServiceInternal & service, const SubscriptionData & data, const NodeId & SessionAuthenticationToken, std::function<void (PublishResult)> callback, const Common::Logger::SharedPtr & logger)
: Service(service)
, AddressSpace(Service.GetAddressSpace())
, Data(data)
, CurrentSession(SessionAuthenticationToken)
, Callback(callback)
, io(service.GetIOService())
, Timer(io, boost::posix_time::milliseconds(static_cast<long>(data.RevisedPublishingInterval)))
, LifeTimeCount(data.RevisedLifetimeCount)
, Logger(logger)
{
LOG_DEBUG(Logger, "internal_subscription | id: {}, create", Data.SubscriptionId);
}
void InternalSubscription::Start()
{
LOG_DEBUG(Logger, "internal_subscription | id: {}, start", Data.SubscriptionId);
std::shared_ptr<InternalSubscription> self = shared_from_this();
Timer.async_wait([self](const boost::system::error_code & error) { self->PublishResults(error); });
}
InternalSubscription::~InternalSubscription()
{
//Stop();
LOG_DEBUG(Logger, "internal_subscription | id: {}, destroy", Data.SubscriptionId);
}
void InternalSubscription::Stop()
{
LOG_DEBUG(Logger, "internal_subscription | id: {}, stop", Data.SubscriptionId);
DeleteAllMonitoredItems();
Timer.cancel();
}
void InternalSubscription::DeleteAllMonitoredItems()
{
LOG_DEBUG(Logger, "internal_subscription | id: {}, DeleteAllMonitoredItems", Data.SubscriptionId);
std::vector<uint32_t> handles;
{
boost::shared_lock<boost::shared_mutex> lock(DbMutex);
for (auto pair : MonitoredDataChanges)
{
handles.push_back(pair.first);
}
}
DeleteMonitoredItemsIds(handles);
}
bool InternalSubscription::HasExpired()
{
bool expired = KeepAliveCount > LifeTimeCount ;
if (expired)
{
LOG_DEBUG(Logger, "internal_subscription | id: {} has expired: keep alive: {} > life time: {}", Data.SubscriptionId, KeepAliveCount, LifeTimeCount);
}
return expired;
}
void InternalSubscription::PublishResults(const boost::system::error_code & error)
{
if (error)
{
LOG_WARN(Logger, "internal_subscription | id: {}, PublishResults: error: stopping subscription timer", Data.SubscriptionId);
return;
}
if (HasExpired())
{
return;
}
if (HasPublishResult() && Service.PopPublishRequest(CurrentSession)) //Check we received a publishrequest before sending response
{
std::vector<PublishResult> results = PopPublishResult();
if (results.size() > 0)
{
LOG_DEBUG(Logger, "internal_subscription | id: {}, have {} results", Data.SubscriptionId, results.size());
if (Callback)
{
LOG_DEBUG(Logger, "internal_subscription | id: {}, calling callback", Data.SubscriptionId);
Callback(results[0]);
}
else
{
LOG_DEBUG(Logger, "internal_subscription | id: {}, no callback defined for this subscription", Data.SubscriptionId);
}
}
}
TimerStopped = false;
Timer.expires_at(Timer.expires_at() + boost::posix_time::milliseconds(static_cast<long>(Data.RevisedPublishingInterval)));
std::shared_ptr<InternalSubscription> self = shared_from_this();
Timer.async_wait([self](const boost::system::error_code & error) { self->PublishResults(error); });
}
bool InternalSubscription::HasPublishResult()
{
boost::unique_lock<boost::shared_mutex> lock(DbMutex);
if (Startup || !TriggeredDataChangeEvents.empty() || !TriggeredEvents.empty())
{
LOG_TRACE(Logger, "internal_subscription | id: {}, HasPublishResult: all queues empty, should send publish event", Data.SubscriptionId);
return true;
}
if (KeepAliveCount > Data.RevisedMaxKeepAliveCount) //we need to send keepalive notification
{
LOG_TRACE(Logger, "internal_subscription | id: {}, HasPublishResult: KeepAliveCount: {} > MaxKeepAliveCount: {}, should send publish event", Data.SubscriptionId, KeepAliveCount, Data.RevisedMaxKeepAliveCount);
return true;
}
LOG_TRACE(Logger, "internal_subscription | id: {}, HasPublishResult: KeepAliveCount: {}, MaxKeepAliveCount: {}", Data.SubscriptionId, KeepAliveCount, Data.RevisedMaxKeepAliveCount);
++KeepAliveCount;
return false;
}
std::vector<PublishResult> InternalSubscription::PopPublishResult()
{
boost::unique_lock<boost::shared_mutex> lock(DbMutex);
LOG_DEBUG(Logger, "internal_subscription | id: {}, PopPublishResult: {} queued items", Data.SubscriptionId, TriggeredDataChangeEvents.size());
PublishResult result;
result.SubscriptionId = Data.SubscriptionId;
result.NotificationMessage.PublishTime = DateTime::Current();
if (!TriggeredDataChangeEvents.empty())
{
NotificationData data = GetNotificationData();
result.NotificationMessage.NotificationData.push_back(data);
result.Results.push_back(StatusCode::Good);
}
if (!TriggeredEvents.empty())
{
LOG_DEBUG(Logger, "internal_subscription | id: {}, PopPublishResult: {} events to send", Data.SubscriptionId, TriggeredEvents.size());
EventNotificationList notif;
for (TriggeredEvent ev : TriggeredEvents)
{
notif.Events.push_back(ev.Data);
}
TriggeredEvents.clear();
NotificationData data(notif);
result.NotificationMessage.NotificationData.push_back(data);
result.Results.push_back(StatusCode::Good);
}
// clear TriggerCount to enable new events for next
// publishing cycle
for (auto & mdc : MonitoredDataChanges)
{
mdc.second.TriggerCount = 0;
}
// FIXME: also add statuschange notification since they can be send in same result
KeepAliveCount = 0;
Startup = false;
result.NotificationMessage.SequenceNumber = NotificationSequence;
++NotificationSequence;
result.MoreNotifications = false;
for (const PublishResult & res : NotAcknowledgedResults)
{
result.AvailableSequenceNumbers.push_back(res.NotificationMessage.SequenceNumber);
}
NotAcknowledgedResults.push_back(result);
LOG_DEBUG(Logger, "internal_subscription | id: {}, sending PublishResult with: {} notifications", Data.SubscriptionId, result.NotificationMessage.NotificationData.size());
std::vector<PublishResult> resultlist;
resultlist.push_back(result);
return resultlist;
}
RepublishResponse InternalSubscription::Republish(const RepublishParameters & params)
{
LOG_DEBUG(Logger, "internal_subscription | id: {}, Republish request for sequence: {}", Data.SubscriptionId, params.RetransmitSequenceNumber);
boost::unique_lock<boost::shared_mutex> lock(DbMutex);
RepublishResponse response;
for (const PublishResult & res : NotAcknowledgedResults)
{
if (res.NotificationMessage.SequenceNumber == params.RetransmitSequenceNumber)
{
response.NotificationMessage = res.NotificationMessage;
return response;
}
}
response.Header.ServiceResult = StatusCode::BadMessageNotAvailable;
return response;
}
ModifySubscriptionResult InternalSubscription::ModifySubscription(const ModifySubscriptionParameters & data)
{
LOG_DEBUG(Logger, "internal_subscription | id: {}, ModifySubscription", Data.SubscriptionId);
ModifySubscriptionResult result;
if (data.RequestedLifetimeCount)
{
Data.RevisedLifetimeCount = data.RequestedLifetimeCount;
}
LifeTimeCount = result.RevisedLifetimeCount = Data.RevisedLifetimeCount;
if (data.RequestedPublishingInterval)
{
Data.RevisedPublishingInterval = data.RequestedPublishingInterval;
}
result.RevisedPublishingInterval = Data.RevisedPublishingInterval;
if (data.RequestedMaxKeepAliveCount)
{
Data.RevisedMaxKeepAliveCount = data.RequestedMaxKeepAliveCount;
}
result.RevisedMaxKeepAliveCount = Data.RevisedMaxKeepAliveCount;
return result;
}
NotificationData InternalSubscription::GetNotificationData()
{
DataChangeNotification notification;
for (const TriggeredDataChange & event : TriggeredDataChangeEvents)
{
notification.Notification.push_back(event.Data);
}
TriggeredDataChangeEvents.clear();
NotificationData data(notification);
return data;
}
void InternalSubscription::NewAcknowlegment(const SubscriptionAcknowledgement & ack)
{
boost::unique_lock<boost::shared_mutex> lock(DbMutex);
NotAcknowledgedResults.remove_if([&](PublishResult res) { return ack.SequenceNumber == res.NotificationMessage.SequenceNumber; });
}
MonitoredItemCreateResult InternalSubscription::CreateMonitoredItem(const MonitoredItemCreateRequest & request)
{
LOG_DEBUG(Logger, "internal_subscription | id: {}, CreateMonitoredItem", Data.SubscriptionId);
MonitoredItemCreateResult result;
uint32_t callbackHandle = 0;
{
boost::unique_lock<boost::shared_mutex> lock(DbMutex);
result.MonitoredItemId = ++LastMonitoredItemId;
result.Status = OpcUa::StatusCode::Good;
result.RevisedSamplingInterval = Data.RevisedPublishingInterval; // Force our own rate
result.RevisedQueueSize = request.RequestedParameters.QueueSize; // We should check that value, maybe set to a default...
result.FilterResult = request.RequestedParameters.Filter; // We can omit that one if we do not change anything in filter
if (request.ItemToMonitor.AttributeId == AttributeId::EventNotifier)
{
LOG_DEBUG(Logger, "internal_subscription | id: {}, subscribe to event notifier", Data.SubscriptionId);
LOG_TRACE(Logger, "internal_subscription | id: {}, {}", Data.SubscriptionId, result.FilterResult);
// Client wants to subscribe to events
// FIXME: check attribute EVENT notifier is set for the node
MonitoredEvents[request.ItemToMonitor.NodeId] = result.MonitoredItemId;
}
}
// Do not lock this part as it (indirectly) calls a locked AddressSpaceInMemory
// function.
// AddressSpaceInMemory functions call locked InternalSubscription functions
// which will result in deadlocks when used from different threads
if (request.ItemToMonitor.AttributeId != AttributeId::EventNotifier)
{
LOG_DEBUG(Logger, "internal_subscription | id: {}, subscribe to data changes", Data.SubscriptionId);
uint32_t id = result.MonitoredItemId;
callbackHandle = AddressSpace.AddDataChangeCallback(request.ItemToMonitor.NodeId, request.ItemToMonitor.AttributeId, [this, id](const OpcUa::NodeId & nodeId, OpcUa::AttributeId attr, const DataValue & value)
{
this->DataChangeCallback(id, value);
});
}
MonitoredDataChange mdata;
{
boost::unique_lock<boost::shared_mutex> lock(DbMutex);
mdata.Parameters = result;
mdata.Mode = request.MonitoringMode;
mdata.TriggerCount = 0;
mdata.ClientHandle = request.RequestedParameters.ClientHandle;
mdata.CallbackHandle = callbackHandle;
mdata.MonitoredItemId = result.MonitoredItemId;
MonitoredDataChanges[result.MonitoredItemId] = mdata;
}
// Do not lock this part as it (indirectly) calls a locked AddressSpaceInMemory
// function.
LOG_DEBUG(Logger, "internal_subscription | id: {}, created MonitoredItem id: {}, ClientHandle: {}", Data.SubscriptionId, result.MonitoredItemId, mdata.ClientHandle);
// Forcing event
if (request.ItemToMonitor.AttributeId != AttributeId::EventNotifier)
{
TriggerDataChangeEvent(mdata, request.ItemToMonitor);
}
return result;
}
void InternalSubscription::TriggerDataChangeEvent(MonitoredDataChange monitoreditems, ReadValueId attrval)
{
LOG_DEBUG(Logger, "internal_subscription | id: {}, TriggerDataChangeEvent: ClientHandle: {}", Data.SubscriptionId, monitoreditems.ClientHandle);
ReadParameters params;
params.AttributesToRead.push_back(attrval);
std::vector<DataValue> vals = AddressSpace.Read(params);
TriggeredDataChange event;
event.MonitoredItemId = monitoreditems.MonitoredItemId;
event.Data.ClientHandle = monitoreditems.ClientHandle;
event.Data.Value = vals[0];
{
boost::unique_lock<boost::shared_mutex> lock(DbMutex);
TriggeredDataChangeEvents.push_back(event);
}
}
std::vector<StatusCode> InternalSubscription::DeleteMonitoredItemsIds(const std::vector<uint32_t> & monitoreditemsids)
{
std::vector<StatusCode> results;
for (const uint32_t & handle : monitoreditemsids)
{
LOG_DEBUG(Logger, "internal_subscription | id: {}, DeletingMonitoredItemsIds: handle: {}", Data.SubscriptionId, handle);
if (DeleteMonitoredEvent(handle))
{
results.push_back(StatusCode::Good);
continue;
}
if (DeleteMonitoredDataChange(handle))
{
results.push_back(StatusCode::Good);
continue;
}
results.push_back(StatusCode::BadMonitoredItemIdInvalid);
}
return results;
}
bool InternalSubscription::DeleteMonitoredDataChange(uint32_t handle)
{
boost::unique_lock<boost::shared_mutex> lock(DbMutex);
MonitoredDataChangeMap::iterator it = MonitoredDataChanges.find(handle);
if (it == MonitoredDataChanges.end())
{
return false;
}
else
{
if (it->second.CallbackHandle != 0) //if 0 this monitoreditem did not use callbacks
{
lock.unlock();
// break deadlock condition: InternalSubscription <-> AddressSpace
AddressSpace.DeleteDataChangeCallback(it->second.CallbackHandle);
lock.lock();
}
MonitoredDataChanges.erase(handle);
//We remove you our monitoreditem, now empty events which are already triggered
for (auto ev = TriggeredDataChangeEvents.begin(); ev != TriggeredDataChangeEvents.end();)
{
if (ev->MonitoredItemId == handle)
{
LOG_DEBUG(Logger, "internal_subscription | id: {}, remove TriggeredDataChangeEvents of MonitoredItemId: {}", Data.SubscriptionId, handle);
ev = TriggeredDataChangeEvents.erase(ev);
}
else
{
++ev;
}
}
return true;
}
}
bool InternalSubscription::DeleteMonitoredEvent(uint32_t handle)
{
boost::unique_lock<boost::shared_mutex> lock(DbMutex);
for (auto pair : MonitoredEvents)
{
if (pair.second == handle)
{
MonitoredEvents.erase(pair.first);
//We remove you our monitoreditem, now empty events which are already triggered
for (auto ev = TriggeredEvents.begin(); ev != TriggeredEvents.end();)
{
if (ev->MonitoredItemId == handle)
{
LOG_DEBUG(Logger, "internal_subscription | id: {}, remove TriggeredEvents of MonitoredItemId: {}", Data.SubscriptionId, handle);
ev = TriggeredEvents.erase(ev);
}
else
{
++ev;
}
}
return true;
}
}
return false;
}
void InternalSubscription::DataChangeCallback(const uint32_t & m_id, const DataValue & value)
{
boost::unique_lock<boost::shared_mutex> lock(DbMutex);
TriggeredDataChange event;
MonitoredDataChangeMap::iterator it_monitoreditem = MonitoredDataChanges.find(m_id);
if (it_monitoreditem == MonitoredDataChanges.end())
{
LOG_WARN(Logger, "internal_subscription | id: {}, DataChangeCallback called for unknown item: {}", Data.SubscriptionId, m_id);
return ;
}
MonitoredDataChange& monitoredDataChange = it_monitoreditem->second;
// spec says default sample interval for MonitoredItems is the same
// as Subscription publishing interval, so bail out if event has been
// triggered before
if (monitoredDataChange.TriggerCount > 0)
{
return;
}
event.MonitoredItemId = it_monitoreditem->first;
event.Data.ClientHandle = monitoredDataChange.ClientHandle;
event.Data.Value = value;
LOG_DEBUG(Logger, "internal_subscription | id: {}, enqueue TriggeredDataChange event: ClientHandle: {}", Data.SubscriptionId, event.Data.ClientHandle);
++monitoredDataChange.TriggerCount;
TriggeredDataChangeEvents.push_back(event);
}
void InternalSubscription::TriggerEvent(NodeId node, Event event)
{
boost::shared_lock<boost::shared_mutex> lock(DbMutex);
MonitoredEventsMap::iterator it = MonitoredEvents.find(node);
if (it == MonitoredEvents.end())
{
LOG_DEBUG(Logger, "internal_subscription | id: {} does not monitor NodeId: {}", Data.SubscriptionId, node);
return;
}
lock.unlock();//Enqueue vill need to set a unique lock
EnqueueEvent(it->second, event);
}
bool InternalSubscription::EnqueueEvent(uint32_t monitoredItemId, const Event & event)
{
LOG_DEBUG(Logger, "internal_subscription | id: {}, EnqueEvent: {}", Data.SubscriptionId, event);
boost::unique_lock<boost::shared_mutex> lock(DbMutex);
//Find monitoredItem
std::map<uint32_t, MonitoredDataChange>::iterator mii_it = MonitoredDataChanges.find(monitoredItemId);
if (mii_it == MonitoredDataChanges.end())
{
LOG_DEBUG(Logger, "internal_subscription | id: {}, MonitoredItemId: {} is already deleted", Data.SubscriptionId, monitoredItemId);
return false;
}
//Check filter against event data and create EventFieldList to send
//FIXME: Here we should also check event agains WhereClause of filter
EventFieldList fieldlist;
fieldlist.ClientHandle = mii_it->second.ClientHandle;
fieldlist.EventFields = GetEventFields(mii_it->second.Parameters.FilterResult.Event, event);
TriggeredEvent ev;
ev.Data = fieldlist;
ev.MonitoredItemId = monitoredItemId;
TriggeredEvents.push_back(ev);
return true;
}
std::vector<Variant> InternalSubscription::GetEventFields(const EventFilter & filter, const Event & event)
{
//Go through filter and add value og matches as in spec
std::vector<Variant> fields;
LOG_DEBUG(Logger, "internal_subscription | id: {}, GetEventFields: filter size: {}", Data.SubscriptionId, filter.SelectClauses.size());
for (SimpleAttributeOperand sattr : filter.SelectClauses)
{
LOG_DEBUG(Logger, "internal_subscription | id: {}, BrowsePath size: {}", Data.SubscriptionId, sattr.BrowsePath.size());
if (sattr.BrowsePath.size() == 0)
{
fields.push_back(event.GetValue(sattr.Attribute));
}
else
{
LOG_DEBUG(Logger, "internal_subscription | id: {}, send value for: {}", Data.SubscriptionId, sattr.BrowsePath[0]);
if (sattr.BrowsePath[0] == QualifiedName("EventId", 0))
{
fields.push_back(event.EventId);
}
else if (sattr.BrowsePath[0] == QualifiedName("EventType", 0))
{
fields.push_back(event.EventType);
}
else if (sattr.BrowsePath[0] == QualifiedName("SourceNode", 0))
{
fields.push_back(event.SourceNode);
}
else if (sattr.BrowsePath[0] == QualifiedName("SourceName", 0))
{
fields.push_back(event.SourceName);
}
else if (sattr.BrowsePath[0] == QualifiedName("Message", 0))
{
LOG_DEBUG(Logger, "internal_subscription | message is: {}", event.Message);
fields.push_back(event.Message);
}
else if (sattr.BrowsePath[0] == QualifiedName("Severity", 0))
{
fields.push_back(event.Severity);
}
else if (sattr.BrowsePath[0] == QualifiedName("LocalTime", 0))
{
fields.push_back(event.LocalTime);
}
else if (sattr.BrowsePath[0] == QualifiedName("ReceiveTime", 0))
{
fields.push_back(event.ReceiveTime);
}
else if (sattr.BrowsePath[0] == QualifiedName("Time", 0))
{
fields.push_back(event.Time);
}
else
{
fields.push_back(event.GetValue(sattr.BrowsePath));
}
}
}
return fields;
}
}
}