YARP
Yet Another Robot Platform
 
Loading...
Searching...
No Matches
PortCoreOutputUnit.cpp
Go to the documentation of this file.
1/*
2 * SPDX-FileCopyrightText: 2006-2021 Istituto Italiano di Tecnologia (IIT)
3 * SPDX-FileCopyrightText: 2006-2010 RobotCub Consortium
4 * SPDX-License-Identifier: BSD-3-Clause
5 */
6
8
9#include <yarp/os/Name.h>
10#include <yarp/os/PortInfo.h>
11#include <yarp/os/PortReport.h>
12#include <yarp/os/Portable.h>
13#include <yarp/os/Time.h>
17
18namespace {
19YARP_OS_LOG_COMPONENT(PORTCOREOUTPUTUNIT, "yarp.os.impl.PortCoreOutputUnit")
20} // namespace
21
22using namespace yarp::os::impl;
23using namespace yarp::os;
24
26 PortCoreUnit(owner, index),
27 op(op), // shared_ptr takes ownership of the raw pointer
28 closing(false),
29 finished(false),
30 running(false),
31 threaded(false),
32 sending(false),
33 name(owner.getName()),
34 phase(1),
35 activate(0),
36 trackerMutex(),
37 cachedWriter(nullptr),
38 cachedReader(nullptr),
39 cachedCallback(nullptr),
40 cachedTracker(nullptr)
41{
42 yCIAssert(PORTCOREOUTPUTUNIT, getName(), op != nullptr);
43}
44
49
50
52{
53 phase.wait();
54
55 if (!threaded) {
56 running = false;
57 sending = false;
59 phase.post();
60 return true;
61 }
62
63 bool result = PortCoreUnit::start();
64 if (result) {
65 phase.wait();
66 phase.post();
67 } else {
68 phase.post();
69 }
70
71 return result;
72}
73
74
76{
77 running = true;
78 sending = false;
79
80 // By default, we don't start up a thread for outputs.
81
82 if (!threaded) {
84 phase.post();
85 } else {
86 phase.post();
87 Route r = getRoute();
88 while (!closing) {
89 yCIDebug(PORTCOREOUTPUTUNIT, getName(), "waiting");
90 activate.wait();
92 if (!closing) {
93 if (sending) {
94 yCIDebug(PORTCOREOUTPUTUNIT, getName(), "write something in background");
95 sendHelper();
96 yCIDebug(PORTCOREOUTPUTUNIT, getName(), "wrote something in background");
97 trackerMutex.lock();
98 if (cachedTracker != nullptr) {
99 void* t = cachedTracker;
100 cachedTracker = nullptr;
101 sending = false;
103 } else {
104 sending = false;
105 }
106 trackerMutex.unlock();
107 }
108 }
109 yCIDebug(PORTCOREOUTPUTUNIT, getName(), "wrote something in background");
110 }
111 yCIDebug(PORTCOREOUTPUTUNIT, getName(), "thread closing");
112 sending = false;
113 }
114}
115
116
118{
119 // Local copy: guarantees the object stays alive for the duration of
120 // this function, independent of concurrent modifications to `op`.
121 std::shared_ptr<OutputProtocol> localOp = op;
122
123 if (localOp) {
124 Route route = localOp->getRoute();
125 setMode();
126 getOwner().reportUnit(this, true);
127
128 std::string msg = std::string("Sending output from ") + route.getFromName() + " to " + route.getToName() + " using " + route.getCarrierName();
129 if (Name(route.getToName()).isRooted()) {
130 if (Name(route.getFromName()).isRooted()) {
131 yCIInfo(PORTCOREOUTPUTUNIT, getName(), "%s", msg.c_str());
132 }
133 }
134
135 // Report the new connection
137 info.message = msg;
139 info.incoming = false;
140 info.created = true;
141 info.sourceName = route.getFromName();
142 info.targetName = route.getToName();
143 info.portName = info.sourceName;
144 info.carrierName = route.getCarrierName();
146 }
147
148 // no thread component
149 running = false;
150}
151
152void PortCoreOutputUnit::closeBasic()
153{
154 bool waitForOther = false;
155
156 // Take a local, private, strong reference. This keeps the pointed-to
157 // OutputProtocol alive for the whole function, even if another thread
158 // concurrently resets the shared `op` member (see closeMain()).
159 std::shared_ptr<OutputProtocol> localOp = op;
160
161 if (localOp) {
162 localOp->getConnection().prepareDisconnect();
163 Route route = localOp->getRoute();
164 if (localOp->getConnection().isConnectionless() || localOp->getConnection().isBroadcast()) {
165 yCIInfo(PORTCOREOUTPUTUNIT, getName(), "output for route %s asking other side to close by out-of-band means",
166 route.toString().c_str());
168 route.getFromName(),
169 true);
170 } else {
171 if (localOp->getConnection().canEscape()) {
172 BufferedConnectionWriter buf(localOp->getConnection().isTextMode(),
173 localOp->getConnection().isBareMode());
174 PortCommand pc('\0', std::string("q"));
175 pc.write(buf);
176 //printf("Asked for %s to close...\n",
177 // op->getRoute().toString().c_str());
178 waitForOther = localOp->write(buf);
179 }
180 }
181
182 std::string msg = std::string("Removing output from ") + route.getFromName() + " to " + route.getToName();
183
184 if (Name(route.getToName()).isRooted()) {
185 if (Name(route.getFromName()).isRooted()) {
186 yCIInfo(PORTCOREOUTPUTUNIT, getName(), "%s", msg.c_str());
187 }
188 }
189
190 getOwner().reportUnit(this, false);
191
192 // Report the disappearing connection
194 info.message = msg;
196 info.incoming = false;
197 info.created = false;
198 info.sourceName = route.getFromName();
199 info.targetName = route.getToName();
200 info.portName = info.sourceName;
201 info.carrierName = route.getCarrierName();
203 }
204
205
206 if (localOp) {
207 if (waitForOther) {
208 // quit is only acknowledged in certain conditions
209 if (localOp->getConnection().isTextMode() && localOp->getConnection().supportReply()) {
210 InputStream& is = localOp->getInputStream();
211 ManagedBytes dummy(1);
212 is.read(dummy.bytes());
213 }
214 }
215 localOp->close();
216
217 // Release our copy and clear the shared member. The underlying
218 // OutputProtocol is only actually destroyed once every other
219 // outstanding shared_ptr copy (e.g. localOp here, or one held
220 // briefly by another thread in closeMain()/getRoute()) has also
221 // gone out of scope. No explicit delete or additional locking is
222 // needed: shared_ptr's atomic refcounting handles this safely.
223 op.reset();
224 }
225}
226
227void PortCoreOutputUnit::closeMain()
228{
229 if (finished) {
230 return;
231 }
232
233 yCIDebug(PORTCOREOUTPUTUNIT, getName(), "closing");
234
235 if (running) {
236 // give a kick (unfortunately unavoidable)
237
238 // Local copy so that even if another thread concurrently clears
239 // `op` inside closeBasic(), the object we call interrupt() on
240 // (if any) remains valid for the duration of this call.
241 std::shared_ptr<OutputProtocol> localOp = op;
242 if (localOp) {
244 }
245
246 closing = true;
247 phase.post();
248 activate.post();
249 join();
250 }
251
252 yCIDebug(PORTCOREOUTPUTUNIT, getName(), "internal join");
253
254 closeBasic();
255 running = false;
256 closing = false;
257 finished = true;
258
259 yCIDebug(PORTCOREOUTPUTUNIT, getName(), "closed");
260}
261
262
264{
265 std::shared_ptr<OutputProtocol> localOp = op;
266 if (localOp) {
267 Route r = localOp->getRoute();
268 localOp->beginWrite();
269 return r;
270 }
271 return PortCoreUnit::getRoute();
272}
273
274bool PortCoreOutputUnit::sendHelper()
275{
276 bool replied = false;
277
278 // Local copy for the whole helper, for the same reason as elsewhere.
279 std::shared_ptr<OutputProtocol> localOp = op;
280
281 if (localOp) {
282 bool done = false;
283 BufferedConnectionWriter buf(localOp->getConnection().isTextMode(),
284 localOp->getConnection().isBareMode());
285 if (cachedReader != nullptr) {
286 buf.setReplyHandler(*cachedReader);
287 }
288
289 if (localOp->getSender().modifiesOutgoingData()) {
290 if (localOp->getSender().acceptOutgoingData(*cachedWriter)) {
291 cachedWriter = &localOp->getSender().modifyOutgoingData(*cachedWriter);
292 } else {
293 return (done = true);
294 }
295 }
296
297 if (localOp->getConnection().isLocal()) {
298 // WARNING Cast away const qualifier.
299 // This may actually cause bugs when using the local carrier
300 // with something that is actually const (i.e. that is using
301 // some parts of memory that cannot be written.
302 auto* pw = const_cast<yarp::os::PortWriter*>(cachedWriter);
303 auto* p = dynamic_cast<yarp::os::Portable*>(pw);
304 if (p == nullptr) {
305 yCIError(PORTCOREOUTPUTUNIT, getName(), "cast failed.");
306 return false;
307 }
308 buf.setReference(p);
309 } else {
310 yCIAssert(PORTCOREOUTPUTUNIT, getName(), cachedWriter != nullptr);
311 bool ok = cachedWriter->write(buf);
312 if (!ok) {
313 done = true;
314 }
315
316 bool suppressReply = (buf.getReplyHandler() == nullptr);
317
318 if (!done) {
319 if (!localOp->getConnection().canEscape()) {
320 if (!cachedEnvelope.empty()) {
321 localOp->getConnection().handleEnvelope(cachedEnvelope);
322 }
323 } else {
324 buf.addToHeader();
325
326 if (!cachedEnvelope.empty()) {
327 if (cachedEnvelope == "__ADMIN") {
328 PortCommand pc('a', "");
329 pc.write(buf);
330 } else {
331 PortCommand pc('\0', std::string(suppressReply ? "D " : "d ") + cachedEnvelope);
332 pc.write(buf);
333 }
334 } else {
335 PortCommand pc(suppressReply ? 'D' : 'd', "");
336 pc.write(buf);
337 }
338 }
339 }
340 }
341
342 if (!done) {
343 if (localOp->getConnection().isActive()) {
344 replied = localOp->write(buf);
345 if (replied && localOp->getSender().modifiesReply() && cachedReader != nullptr) {
346 cachedReader = &localOp->getSender().modifyReply(*cachedReader);
347 }
348 }
349 if (!localOp->isOk()) {
350 done = true;
351 }
352 }
353
354 if (buf.dropRequested()) {
355 done = true;
356 }
357 if (done) {
358 closeBasic();
359 closing = true;
360 finished = true;
361 setDoomed();
362 }
363 }
364
365
366 return replied;
367}
368
370 yarp::os::PortReader* reader,
371 const yarp::os::PortWriter* callback,
372 void* tracker,
373 const std::string& envelopeString,
374 bool waitAfter,
375 bool waitBefore,
376 bool* gotReply)
377{
378 bool replied = false;
379
380 {
381 std::shared_ptr<OutputProtocol> localOp = op;
382 if (localOp) {
383 if (!localOp->getConnection().isActive()) {
384 return tracker;
385 }
386 }
387 }
388
389 if (!waitBefore || !waitAfter) {
390 if (!running) {
391 // we must have a thread if we're going to be skipping waits
392 threaded = true;
393 yCIDebug(PORTCOREOUTPUTUNIT, getName(), "starting a thread for output");
394 start();
395 yCIDebug(PORTCOREOUTPUTUNIT, getName(), "started a thread for output");
396 }
397 }
398
399 if ((!waitBefore) && waitAfter) {
400 yCIError(PORTCOREOUTPUTUNIT, getName(), "chosen port wait combination not yet implemented");
401 }
402 if (!sending) {
403 cachedWriter = &writer;
404 cachedReader = reader;
405 cachedCallback = callback;
406 cachedEnvelope = envelopeString;
407
408 sending = true;
409 if (waitAfter) {
410 replied = sendHelper();
411 sending = false;
412 } else {
413 trackerMutex.lock();
414 void* nextTracker = tracker;
415 tracker = cachedTracker;
416 cachedTracker = nextTracker;
417 activate.post();
418 trackerMutex.unlock();
419 }
420 } else {
421 yCIDebug(PORTCOREOUTPUTUNIT, getName(), "skipping connection tagged as sending something");
422 }
423
424 if (waitAfter) {
425 if (gotReply != nullptr) {
426 *gotReply = replied;
427 }
428 }
429
430 // return tracker that we no longer need
431 return tracker;
432}
433
434
436{
437 void* tracker = nullptr;
438 trackerMutex.lock();
439 if (!sending) {
440 tracker = cachedTracker;
441 cachedTracker = nullptr;
442 }
443 trackerMutex.unlock();
444 return tracker;
445}
446
448{
449 return sending;
450}
451
453{
454 std::shared_ptr<OutputProtocol> localOp = op;
455 if (localOp) {
456 localOp->getConnection().setCarrierParams(params);
457 }
458}
459
461{
462 std::shared_ptr<OutputProtocol> localOp = op;
463 if (localOp) {
464 localOp->getConnection().getCarrierParams(params);
465 }
466}
467
469{
470 // Callers (e.g. PortCore::getTypeOfService()) treat this as a
471 // transient, "use immediately" raw pointer; they do not store it
472 // long-term. Returning op.get() preserves the existing API/ABI while
473 // the shared_ptr keeps the object's lifetime managed safely elsewhere.
474 return op.get();
475}
A mini-server for performing network communication in the background.
void close() override
Stop port activity.
void interrupt() override
Interrupt any current reads or writes attached to the port.
void write(bool forceStrict=false)
Write the current object being returned by BufferedPort::prepare.
Simple specification of the minimum functions needed from input streams.
Definition InputStream.h:25
virtual int read()
Read and return a single byte.
An abstraction for a block of bytes, with optional responsibility for allocating/destroying that bloc...
Simple abstraction for a YARP port name.
Definition Name.h:18
bool isRooted() const
Check if port name begins with "/".
Definition Name.cpp:16
static int disconnectInput(const std::string &src, const std::string &dest, bool silent=false)
Sends a disconnection command to the specified port.
Definition Network.cpp:1636
The output side of an active connection between two ports.
Information about a port connection or event.
Definition PortInfo.h:25
std::string message
A human-readable description of contents.
Definition PortInfo.h:68
@ PORTINFO_CONNECTION
Information about an incoming or outgoing connection.
Definition PortInfo.h:39
Interface implemented by all objects that can read themselves from the network, such as Bottle object...
Definition PortReader.h:24
Interface implemented by all objects that can write themselves to the network, such as Bottle objects...
Definition PortWriter.h:23
This is a base class for objects that can be both read from and be written to the YARP network.
Definition Portable.h:25
A class for storing options and configuration information.
Definition Property.h:33
Information about a connection between two ports.
Definition Route.h:28
const std::string & getToName() const
Get the destination of the route.
Definition Route.cpp:103
const std::string & getCarrierName() const
Get the carrier type of the route.
Definition Route.cpp:123
std::string toString() const
Render a text form of the route, "source->carrier->dest".
Definition Route.cpp:138
const std::string & getFromName() const
Get the source of the route.
Definition Route.cpp:93
void wait()
Decrement the counter, even if we must wait to do that.
Definition Semaphore.cpp:96
void post()
Increment the counter.
A helper for creating cached object descriptions.
Simple Readable and Writable object representing a command to a YARP port.
Definition PortCommand.h:24
void getCarrierParams(yarp::os::Property &params) override
void * takeTracker() override
Reacquire a tracker previously passed via send().
void setCarrierParams(const yarp::os::Property &params) override
Set arbitrary parameters for this connection.
void * send(const yarp::os::PortWriter &writer, yarp::os::PortReader *reader, const yarp::os::PortWriter *callback, void *tracker, const std::string &envelopeString, bool waitAfter, bool waitBefore, bool *gotReply) override
Send a message on the connection.
PortCoreOutputUnit(PortCore &owner, int index, OutputProtocol *op)
Constructor.
bool start() override
Prepare to serve this output.
void run() override
The body of a thread managing background sends.
virtual void runSingleThreaded()
Perform send operations without a separate thread.
This manages a single threaded resource related to a single input or output connection.
void setMode()
Check the carrier used for the connection, and see if it has a "log" modifier.
void setDoomed()
Request that this connection be shut down as soon as possible.
void notifyCompletion(void *tracker)
Call the right onCompletion() after sending message.
void report(const yarp::os::PortInfo &info)
Handle a port event (connection, disconnection, etc) Generate a description of the connections associ...
void reportUnit(PortCoreUnit *unit, bool active)
Called by a connection handler with active=true just after it is fully configured,...
int join(double seconds=-1)
#define yCIAssert(component, id, x)
#define yCIError(component, id,...)
#define yCIInfo(component, id,...)
#define yCIDebug(component, id,...)
#define YARP_OS_LOG_COMPONENT(name, name_string)
The components from which ports and connections are built.
An interface to the operating system, including Port based communication.
Definition OSTestMsg.cpp:13