pva2pva 1.4.2
Loading...
Searching...
No Matches
moncache.cpp
1
2#include <epicsAtomic.h>
3#include <errlog.h>
4
5#include <epicsMutex.h>
6#include <epicsTimer.h>
7
8#include <pv/pvAccess.h>
9
10#define epicsExportSharedSymbols
11#include "helper.h"
12#include "pva2pva.h"
13#include "chancache.h"
14
15namespace pva = epics::pvAccess;
16namespace pvd = epics::pvData;
17
18size_t MonitorCacheEntry::num_instances;
19size_t MonitorUser::num_instances;
20
21namespace {
22// fetch scalar value or default
23template<typename T>
24T getS(const pvd::PVStructurePtr& s, const char* name, T dft)
25{
26 try{
27 return s->getSubFieldT<pvd::PVScalar>(name)->getAs<T>();
28 }catch(std::runtime_error& e){
29 return dft;
30 }
31}
32}
33
34MonitorCacheEntry::MonitorCacheEntry(ChannelCacheEntry *ent, const pvd::PVStructure::shared_pointer& pvr)
35 :chan(ent)
36 ,bufferSize(getS<pvd::uint32>(pvr, "record._options.queueSize", 2)) // should be same default as pvAccess, but not required
37 ,havedata(false)
38 ,done(false)
39 ,nwakeups(0)
40 ,nevents(0)
41{
42 epicsAtomicIncrSizeT(&num_instances);
43}
44
45MonitorCacheEntry::~MonitorCacheEntry()
46{
47 pvd::Monitor::shared_pointer M;
48 M.swap(mon);
49 if(M) {
50 M->destroy();
51 }
52 epicsAtomicDecrSizeT(&num_instances);
53 const_cast<ChannelCacheEntry*&>(chan) = NULL; // spoil to fault use after free
54}
55
56void
57MonitorCacheEntry::monitorConnect(pvd::Status const & status,
58 pvd::MonitorPtr const & monitor,
59 pvd::StructureConstPtr const & structure)
60{
61 interested_t::vector_type tonotify;
62 {
63 Guard G(mutex());
64 if(typedesc) {
65 // we shouldn't have to deal with monitor type change since we
66 // destroy() Monitors on Channel disconnect.
67 std::cerr<<"monitorConnect() w/ new type. Monitor has outlived it's connection.\n";
68 monitor->stop();
69 //TODO: unlisten()
70 return;
71 }
72 typedesc = structure;
73
74 if(status.isSuccess()) {
75 startresult = monitor->start();
76 } else {
77 startresult = status;
78 }
79
80 if(startresult.isSuccess()) {
81 lastelem.reset(new pvd::MonitorElement(pvd::getPVDataCreate()->createPVStructure(structure)));
82 }
83
84 // set typedesc and startresult for futured MonitorUsers
85 // and copy snapshot of already interested MonitorUsers
86 tonotify = interested.lock_vector();
87 }
88
89 if(!startresult.isSuccess())
90 std::cout<<"upstream monitor start() fails\n";
91
92 shared_pointer self(weakref); // keeps us alive all MonitorUsers are destroy()ed
93
94 for(interested_t::vector_type::const_iterator it = tonotify.begin(),
95 end = tonotify.end(); it!=end; ++it)
96 {
97 pvd::MonitorRequester::shared_pointer req((*it)->req);
98 if(req) {
99 req->monitorConnect(startresult, *it, structure);
100 }
101 }
102}
103
104// notificaton from upstream client that its monitor queue has
105// become not empty (transition from empty to not empty)
106// will not be called again unless we completely empty the upstream queue.
107// If we don't then it is our responsibly to schedule more poll().
108// Note: this probably means this is a PVA client RX thread.
109void
110MonitorCacheEntry::monitorEvent(pvd::MonitorPtr const & monitor)
111{
112 /* PVA is being tricky, the Monitor* passed to monitorConnect()
113 * isn't the same one we see here!
114 * The original was a ChannelMonitorImpl, we now see a MonitorStrategyQueue
115 * owned by the original, which delegates deserialization and accumulation
116 * of deltas into complete events for us.
117 * However, we don't want to keep the MonitorStrategyQueue as it's
118 * destroy() method is a no-op!
119 */
120
121 epicsAtomicIncrSizeT(&nwakeups);
122
123 shared_pointer self(weakref); // keeps us alive in case all MonitorUsers are destroy()ed
124
125 pva::MonitorElementPtr update;
126
127 typedef std::vector<MonitorUser::shared_pointer> dsnotify_t;
128 dsnotify_t dsnotify;
129
130 {
131 Guard G(mutex()); // MCE and MU guarded by the same mutex
132 if(!havedata)
133 havedata = true;
134
135 //TODO: flow control, if all MU buffers are full, break before poll()==NULL
136 while((update=monitor->poll()))
137 {
138 epicsAtomicIncrSizeT(&nevents);
139
140 lastelem->pvStructurePtr->copyUnchecked(*update->pvStructurePtr,
141 *update->changedBitSet);
142 *lastelem->changedBitSet = *update->changedBitSet;
143 *lastelem->overrunBitSet = *update->overrunBitSet;
144 monitor->release(update);
145 update.reset();
146
147 interested_t::iterator IIT(interested); // recursively locks interested.mutex() (assumes this->mutex() is interestd.mutex())
148 for(interested_t::value_pointer pusr = IIT.next(); pusr; pusr = IIT.next())
149 {
150 MonitorUser *usr = pusr.get();
151
152 {
153 Guard G(usr->mutex());
154 if(usr->initial)
155 continue; // no start() yet
156 // TODO: track overflow when !running (after stop())?
157 if(!usr->running || usr->empty.empty()) {
158 usr->inoverflow = true;
159
160 /* overrun |= lastelem->overrun // upstream overflows
161 * overrun |= changed & lastelem->changed // downstream overflows
162 * changed |= lastelem->changed // accumulate changes
163 */
164
165 *usr->overflowElement->overrunBitSet |= *lastelem->overrunBitSet;
166 usr->overflowElement->overrunBitSet->or_and(*usr->overflowElement->changedBitSet,
167 *lastelem->changedBitSet);
168 *usr->overflowElement->changedBitSet |= *lastelem->changedBitSet;
169
170 usr->overflowElement->pvStructurePtr->copyUnchecked(*lastelem->pvStructurePtr,
171 *lastelem->changedBitSet);
172
173 epicsAtomicIncrSizeT(&usr->ndropped);
174 continue;
175 }
176 // we only come out of overflow when downstream release()s an element to us
177 // empty.empty() does not imply inoverflow,
178 // however inoverflow does imply empty.empty()
179 assert(!usr->inoverflow);
180
181 if(usr->filled.empty())
182 dsnotify.push_back(pusr);
183
184 pvd::MonitorElementPtr elem(usr->empty.front());
185
186 *elem->overrunBitSet = *lastelem->overrunBitSet;
187 *elem->changedBitSet = *lastelem->changedBitSet;
188 // Note: can't use changed mask to optimize this copy since we don't know
189 // the state of the free element
190 elem->pvStructurePtr->copyUnchecked(*lastelem->pvStructurePtr);
191
192 usr->filled.push_back(elem);
193 usr->empty.pop_front();
194
195 epicsAtomicIncrSizeT(&usr->nevents);
196 }
197 }
198 }
199 }
200
201 // unlock here, race w/ stop(), unlisten()?
202 //TODO: notify from worker thread
203
204 FOREACH(dsnotify_t::iterator, it,end,dsnotify) {
205 MonitorUser *usr = (*it).get();
206 pvd::MonitorRequester::shared_pointer req(usr->req.lock());
207 if(!req)
208 continue; // downstream requester has already been destroyed
209 epicsAtomicIncrSizeT(&usr->nwakeups);
210 req->monitorEvent(*it); // notify when first item added to empty queue, may call poll(), release(), and others
211 }
212}
213
214// notificaton from upstream client that no more monitor updates will come, ever
215void
216MonitorCacheEntry::unlisten(pvd::MonitorPtr const & monitor)
217{
218 pvd::Monitor::shared_pointer M;
219 interested_t::vector_type tonotify;
220 {
221 Guard G(mutex());
222 M.swap(mon);
223 tonotify = interested.lock_vector();
224 // assume that upstream won't call monitorEvent() again
225
226 // cause future downstream start() to error
227 startresult = pvd::Status(pvd::Status::STATUSTYPE_ERROR, "upstream unlisten()");
228 }
229 if(M) {
230 M->destroy();
231 }
232 FOREACH(interested_t::vector_type::iterator, it, end, tonotify) {
233 MonitorUser *usr = it->get();
234 pvd::MonitorRequester::shared_pointer req(usr->req);
235 Guard G(usr->mutex());
236 if(usr->inuse.empty()) { // TODO: what about stopped?
237 UnGuard U(G);
238 req->unlisten(*it);
239 }
240 }
241}
242
243std::string
244MonitorCacheEntry::getRequesterName()
245{
246 return "MonitorCacheEntry";
247}
248
249MonitorUser::MonitorUser(const MonitorCacheEntry::shared_pointer &e,
250 const pvd::MonitorRequester::shared_pointer &req,
251 const std::tr1::shared_ptr<GWChannel> &srvchan)
252 :entry(e)
253 ,req(req)
254 ,srvchan(srvchan)
255 ,initial(true)
256 ,running(false)
257 ,inoverflow(false)
258 ,nevents(0)
259 ,ndropped(0)
260{
261 epicsAtomicIncrSizeT(&num_instances);
262}
263
264MonitorUser::~MonitorUser()
265{
266 epicsAtomicDecrSizeT(&num_instances);
267}
268
269// downstream server closes monitor
270void
271MonitorUser::destroy()
272{
273 {
274 Guard G(mutex());
275 running = false;
276 }
277}
278
279pvd::Status
280MonitorUser::start()
281{
282 pvd::MonitorRequester::shared_pointer req(this->req.lock());
283 if(!req)
284 return pvd::Status(pvd::Status::STATUSTYPE_FATAL, "already dead");
285
286 bool doEvt = false;
287 {
288 Guard G(entry->mutex()); // MCE and MU have share a lock
289
290 if(!entry->startresult.isSuccess())
291 return entry->startresult;
292
293 pvd::PVStructurePtr lval;
294 if(entry->havedata)
295 lval = entry->lastelem->pvStructurePtr;
296 pvd::StructureConstPtr typedesc(entry->typedesc);
297
298 if(initial) {
299 initial = false;
300
301 empty.resize(entry->bufferSize);
302 pvd::PVDataCreatePtr fact(pvd::getPVDataCreate());
303 for(unsigned i=0; i<empty.size(); i++) {
304 empty[i].reset(new pvd::MonitorElement(fact->createPVStructure(typedesc)));
305 }
306
307 // extra element to accumulate updates during overflow
308 overflowElement.reset(new pvd::MonitorElement(fact->createPVStructure(typedesc)));
309 }
310
311 doEvt = filled.empty();
312
313 if(lval && !empty.empty()) {
314 //already running, notify of initial element
315
316 const pva::MonitorElementPtr& elem(empty.front());
317 elem->pvStructurePtr->copy(*lval);
318 elem->changedBitSet->set(0); // indicate all changed
319 elem->overrunBitSet->clear();
320 filled.push_back(elem);
321 empty.pop_front();
322 }
323
324 doEvt &= !filled.empty();
325 running = true;
326 }
327 if(doEvt)
328 req->monitorEvent(shared_pointer(weakref)); // TODO: worker thread?
329 return pvd::Status();
330}
331
332pvd::Status
333MonitorUser::stop()
334{
335 Guard G(mutex());
336 running = false;
337 return pvd::Status::Ok;
338}
339
340pva::MonitorElementPtr
341MonitorUser::poll()
342{
343 Guard G(mutex());
344 pva::MonitorElementPtr ret;
345 if(!filled.empty()) {
346 ret = filled.front();
347 inuse.insert(ret); // track which ones are out for client use
348 filled.pop_front();
349 //TODO: track lost buffers w/ wrapped shared_ptr?
350 }
351 return ret;
352}
353
354void
355MonitorUser::release(pva::MonitorElementPtr const & monitorElement)
356{
357 Guard G(mutex());
358 //TODO: ifdef DEBUG? (only track inuse when debugging?)
359 std::set<epics::pvData::MonitorElementPtr>::iterator it = inuse.find(monitorElement);
360 if(it!=inuse.end()) {
361 inuse.erase(it);
362
363 if(inoverflow) { // leaving overflow condition
364
365 // to avoid copy, enqueue the current overflowElement
366 // and replace it with the element being release()d
367
368 filled.push_back(overflowElement);
369 overflowElement = monitorElement;
370 overflowElement->changedBitSet->clear();
371 overflowElement->overrunBitSet->clear();
372
373 inoverflow = false;
374 } else {
375 // push_back empty element
376 empty.push_back(monitorElement);
377 }
378 } else {
379 // oh no, we've been given an element which we didn't give to downstream
380 //TODO: check empty and filled lists to see if this is one of ours, of from somewhere else
381 throw std::invalid_argument("Can't release MonitorElement not in use");
382 }
383 // TODO: pipeline window update?
384}
385
386std::string
387MonitorUser::getRequesterName()
388{
389 return "MonitorCacheEntry";
390}
Definition chancache.h:107
epics::pvData::MonitorElement::shared_pointer lastelem
Definition chancache.h:46