YARP
Yet Another Robot Platform
 
Loading...
Searching...
No Matches
PortCore.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
10
11#include <yarp/os/Bottle.h>
14#include <yarp/os/Name.h>
15#include <yarp/os/Network.h>
16#include <yarp/os/PortInfo.h>
18#include <yarp/os/SystemInfo.h>
19#include <yarp/os/Time.h>
29
31
32#include <cstdio>
33#include <functional>
34#include <random>
35#include <regex>
36#include <vector>
37
38#ifdef YARP_HAS_ACE
39# include <ace/INET_Addr.h>
40# include <ace/Sched_Params.h>
41// In one the ACE headers there is a definition of "main" for WIN32
42# ifdef main
43# undef main
44# endif
45#endif
46
47#if defined(__linux__) // used for configuring scheduling properties
48# include <dirent.h>
49# include <sys/types.h>
50# include <unistd.h>
51#endif
52
53
54using namespace yarp::os::impl;
55using namespace yarp::os;
56using namespace yarp;
57
58namespace {
59YARP_OS_LOG_COMPONENT(PORTCORE, "yarp.os.impl.PortCore")
60} // namespace
61
62PortCore::PortCore() = default;
63
69
70
71bool PortCore::listen(const Contact& address, bool shouldAnnounce)
72{
73 yCIDebug(PORTCORE, getName(), "Starting listening on %s", address.toURI().c_str());
74 // If we're using ACE, we really need to have it initialized before
75 // this point.
77 yCIError(PORTCORE, getName(), "YARP not initialized; create a yarp::os::Network object before using ports");
78 return false;
79 }
80
81 yCITrace(PORTCORE, getName(), "listen");
82
83 {
84 // Critical section
85 std::lock_guard<std::mutex> lock(m_stateMutex);
86
87 // This method assumes we are not already on the network.
88 // We can assume this because it is not a user-facing class,
89 // and we carefully never call this method again without
90 // calling close().
91 yCIAssert(PORTCORE, getName(), !m_listening);
92 yCIAssert(PORTCORE, getName(), !m_running);
93 yCIAssert(PORTCORE, getName(), !m_closing.load());
94 yCIAssert(PORTCORE, getName(), !m_finished.load());
95 yCIAssert(PORTCORE, getName(), m_face == nullptr);
96
97 // Try to put the port on the network, using the user-supplied
98 // address (which may be incomplete). You can think of
99 // this as getting a server socket.
100 m_address = address;
101 setName(address.getRegName());
102 if (m_timeout > 0) {
103 m_address.setTimeout(m_timeout);
104 }
105 m_face = Carriers::listen(m_address);
106
107 // We failed, abort.
108 if (m_face == nullptr) {
109 return false;
110 }
111
112 // Update our address if it was incomplete.
113 if (m_address.getPort() <= 0) {
114 m_address = m_face->getLocalAddress();
115 if (m_address.getRegName() == "...") {
116 m_address.setName(std::string("/") + m_address.getHost() + "_" + yarp::conf::numeric::to_string(m_address.getPort()));
117 setName(m_address.getRegName());
118 }
119 }
120
121 // Move into listening phase
122 m_listening.store(true);
123 }
124
125 // Now that we are on the network, we can let the name server know this.
126 if (shouldAnnounce) {
128 std::string portName = address.getRegName();
129 Bottle cmd;
130 Bottle reply;
131 cmd.addString("announce");
132 cmd.addString(portName);
133 ContactStyle style;
134 NetworkBase::writeToNameServer(cmd, reply, style);
135 }
136 }
137
138 // Success!
139 return true;
140}
141
142
144{
145 // Don't even try to do this when the port is hot, it'll burn you
146 yCIAssert(PORTCORE, getName(), !m_running.load());
147 yCIAssert(PORTCORE, getName(), m_reader == nullptr);
148 m_reader = &reader;
149}
150
152{
153 // Don't even try to do this when the port is hot, it'll burn you
154 yCIAssert(PORTCORE, getName(), !m_running.load());
155 yCIAssert(PORTCORE, getName(), m_adminReader == nullptr);
156 m_adminReader = &reader;
157}
158
160{
161 // Don't even try to do this when the port is hot, it'll burn you
162 yCIAssert(PORTCORE, getName(), !m_running.load());
163 yCIAssert(PORTCORE, getName(), m_readableCreator == nullptr);
164 m_readableCreator = &creator;
165}
166
167
169{
170 yCITrace(PORTCORE, getName(), "run");
171
172 // This is the server thread for the port. We listen on
173 // the network and handle any incoming connections.
174 // We don't touch those connections, just shove them
175 // in a list and move on. It is important that this
176 // thread doesn't make a connecting client wait just
177 // because some other client is slow.
178
179 // We assume that listen() has succeeded and that
180 // start() has been called.
181 yCIAssert(PORTCORE, getName(), m_listening.load());
182 yCIAssert(PORTCORE, getName(), !m_running.load());
183 yCIAssert(PORTCORE, getName(), !m_closing.load());
184 yCIAssert(PORTCORE, getName(), !m_finished.load());
185 yCIAssert(PORTCORE, getName(), m_starting.load());
186
187 // Enter running phase
188 {
189 // Critical section
190 std::lock_guard<std::mutex> lock(m_stateMutex);
191 m_running.store(true);
192 m_starting.store(false);
193 }
194
195 // Notify the start() thread that the run() thread is running
196 m_stateCv.notify_one();
197
198 yCITrace(PORTCORE, getName(), "run running");
199
200 // Enter main loop, where we block on incoming connections.
201 // The loop is exited when PortCore#closing is set. One last
202 // connection will be needed to de-block this thread and ensure
203 // that it checks PortCore#closing.
204 bool shouldStop = false;
205 while (!shouldStop) {
206
207 // Block and wait for a connection
208 InputProtocol* ip = m_face->read();
209
210 {
211 // Critical section
212 std::lock_guard<std::mutex> lock(m_stateMutex);
213
214 // Attach the connection to this port and update its timeout setting
215 if (ip != nullptr) {
216 ip->attachPort(m_contactable);
217 yCIDebug(PORTCORE, getName(), "received something");
218 if (m_timeout > 0) {
219 ip->setTimeout(m_timeout);
220 }
221 }
222
223 // Check whether we should shut down
224 shouldStop |= m_closing.load();
225
226 // Increment a global count of connection events
227 m_events++;
228 }
229
230 // It we are not shutting down, spin off the connection.
231 // It starts life as an input connection (although it
232 // may later morph into an output).
233 if (!shouldStop) {
234 if (ip != nullptr) {
235 addInput(ip);
236 }
237 yCIDebug(PORTCORE, getName(), "spun off a connection");
238 ip = nullptr;
239 }
240
241 // If the connection wasn't spun off, just shut it down.
242 if (ip != nullptr) {
243 ip->close();
244 delete ip;
245 ip = nullptr;
246 }
247
248 // Remove any defunct connections.
249 reapUnits();
250
251 // Notify anyone listening for connection changes.
252 std::lock_guard<std::mutex> lock(m_stateMutex);
253 m_connectionListeners = 0;
254 m_connectionChangeCv.notify_all();
255 }
256
257 yCITrace(PORTCORE, getName(), "run closing");
258
259 // The server thread is shutting down.
260 std::lock_guard<std::mutex> lock(m_stateMutex);
261 m_connectionListeners = 0;
262 m_connectionChangeCv.notify_all();
263 m_finished.store(true);
264}
265
266
268{
269 closeMain();
270
271 m_modifier.releaseOutModifier();
272 m_modifier.releaseInModifier();
273}
274
275
277{
278 yCITrace(PORTCORE, getName(), "start");
279
280 // This wait will, on success, be matched by a post in run()
281 std::unique_lock<std::mutex> lock(m_stateMutex);
282
283 // We assume that listen() has been called.
284 yCIAssert(PORTCORE, getName(), m_listening.load());
285 yCIAssert(PORTCORE, getName(), !m_running.load());
286 yCIAssert(PORTCORE, getName(), !m_starting.load());
287 yCIAssert(PORTCORE, getName(), !m_finished.load());
288 yCIAssert(PORTCORE, getName(), !m_closing.load());
289
290 m_starting.store(true);
291
292 // Start the server thread.
293 bool started = ThreadImpl::start();
294 if (!started) {
295 // run() won't be happening
296 yAssert(false);
297
298 } else {
299 // Wait for the signal from the run thread before returning.
300 m_stateCv.wait(lock, [&]{ return m_running.load(); });
301 yCIAssert(PORTCORE, getName(), m_running.load());
302 }
303 return started;
304}
305
306
307bool PortCore::manualStart(const char* sourceName)
308{
309 yCITrace(PORTCORE, getName(), "manualStart");
310
311 // This variant of start() does not create a server thread.
312 // That is appropriate if we never expect to receive incoming
313 // connections for any reason. No incoming data, no requests
314 // for state information, no requests to change connections,
315 // nothing. We set the port's name to something fake, and
316 // act like nothing is wrong.
317 m_interruptable = false;
318 m_manual = true;
319 setName(sourceName);
320 return true;
321}
322
323
325{
326 // We are no longer interrupted.
327 m_interrupted = false;
328}
329
331{
332 yCITrace(PORTCORE, getName(), "interrupt");
333
334 // This is a no-op if there is no server thread.
335 if (!m_listening.load()) {
336 return;
337 }
338
339 // Ignore any future incoming data
340 m_interrupted = true;
341
342 // What about data that is already coming in?
343 // If interruptable is not currently set, no worries, the user
344 // did not or will not end up blocked on a read.
345 if (!m_interruptable) {
346 return;
347 }
348
349 // Since interruptable is set, it is possible that the user
350 // may be blocked on a read. We send an empty message,
351 // which is reserved for giving blocking readers a chance to
352 // update their state.
353 {
354 // Critical section
355 std::lock_guard<std::mutex> lock(m_stateMutex);
356 if (m_reader != nullptr) {
357 yCIDebug(PORTCORE, getName(), "sending update-state message to listener");
359 lockCallback();
360 m_reader->read(sbr);
362 }
363 }
364}
365
366
367void PortCore::closeMain()
368{
369 yCITrace(PORTCORE, getName(), "closeMain");
370
371 {
372 // Critical section
373 std::lock_guard<std::mutex> lock(m_stateMutex);
374
375 // We may not have anything to do.
376 if (m_finishing || !(m_running.load() || m_manual)) {
377 yCITrace(PORTCORE, getName(), "closeMain - nothing to do");
378 return;
379 }
380
381 yCITrace(PORTCORE, getName(), "closeMain - Central");
382
383 // Move into official "finishing" phase.
384 m_finishing = true;
385 yCIDebug(PORTCORE, getName(), "now preparing to shut down port");
386 }
387
388 // Start disconnecting inputs. We ask the other side of the
389 // connection to do this, so it won't come as a surprise.
390 // The details of how disconnection works vary by carrier.
391 // While we are doing this, the server thread may be still running.
392 // This is because other ports may need to talk to the server
393 // to organize details of how a connection should be broken down.
394 bool done = false;
395 std::string prevName;
396 while (!done) {
397 done = true;
398 std::string removeName;
399 {
400 // Critical section
401 std::lock_guard<std::mutex> lock(m_stateMutex);
402 for (auto* unit : m_units) {
403 if ((unit != nullptr) && unit->isInput() && !unit->isDoomed()) {
404 Route r = unit->getRoute();
405 std::string s = r.getFromName();
406 if (s.length() >= 1 && s[0] == '/' && s != getName() && s != prevName) {
407 removeName = s;
408 done = false;
409 break;
410 }
411 }
412 }
413 }
414 if (!done) {
415 yCIDebug(PORTCORE, getName(), "requesting removal of connection from %s", removeName.c_str());
417 getName(),
418 true);
419 if (!result) {
422 true);
423 }
425 }
426 }
427
428 // Start disconnecting outputs. We don't negotiate with the
429 // other side, we just break them down.
430 done = false;
431 while (!done) {
432 done = true;
434 {
435 // Critical section
436 std::lock_guard<std::mutex> lock(m_stateMutex);
437 for (auto* unit : m_units) {
438 if ((unit != nullptr) && unit->isOutput() && !unit->isFinished()) {
439 removeRoute = unit->getRoute();
440 if (removeRoute.getFromName() == getName()) {
441 done = false;
442 break;
443 }
444 }
445 }
446 }
447 if (!done) {
448 removeUnit(removeRoute, true);
449 }
450 }
451
452 bool stopRunning = m_running.load();
453
454 // If the server thread is still running, we need to bring it down.
455 if (stopRunning) {
456 // Let the server thread know we no longer need its services.
457 m_closing.store(true);
458
459 // Wake up the server thread the only way we can, by sending
460 // a message to it. Then join it, it is done.
461 if (!m_manual) {
462 OutputProtocol* op = m_face->write(m_address);
463 if (op != nullptr) {
464 op->close();
465 delete op;
466 }
467 join();
468 }
469
470 // We should be finished now.
471 yCIAssert(PORTCORE, getName(), m_finished.load());
472
473 // Clean up our connection list. We couldn't do this earlier,
474 // because the server thread was running.
475 closeUnits();
476
477 // Reset some state flags.
478 {
479 // Critical section
480 std::lock_guard<std::mutex> lock(m_stateMutex);
481 m_finished.store(false);
482 m_closing.store(false);
483 m_running.store(false);
484 }
485 }
486
487 // There should be no other threads at this point and we
488 // can stop listening on the network.
489 if (m_listening.load()) {
490 yCIAssert(PORTCORE, getName(), m_face != nullptr);
491 m_face->close();
492 delete m_face;
493 m_face = nullptr;
494 m_listening.store(false);
495 }
496
497 // Check if the client is waiting for input. If so, wake them up
498 // with the bad news. An empty message signifies a request to
499 // check the port state.
500 if (m_reader != nullptr) {
501 yCIDebug(PORTCORE, getName(), "sending end-of-port message to listener");
503 m_reader->read(sbr);
504 m_reader = nullptr;
505 }
506
507 // We may need to unregister the port with the name server.
508 if (stopRunning) {
509 std::string name = getName();
510 if (name != std::string("")) {
511 if (m_controlRegistration) {
513 }
514 }
515 }
516
517 // We are done with the finishing process.
518 m_finishing = false;
519
520 // We are fresh as a daisy.
521 yCIAssert(PORTCORE, getName(), !m_listening.load());
522 yCIAssert(PORTCORE, getName(), !m_running.load());
523 yCIAssert(PORTCORE, getName(), !m_starting.load());
524 yCIAssert(PORTCORE, getName(), !m_closing.load());
525 yCIAssert(PORTCORE, getName(), !m_finished.load());
526 yCIAssert(PORTCORE, getName(), !m_finishing);
527 yCIAssert(PORTCORE, getName(), m_face == nullptr);
528}
529
530
532{
533 // How many times has the server thread spun off a connection.
534 std::lock_guard<std::mutex> lock(m_stateMutex);
535 int ct = m_events;
536 return ct;
537}
538
539
540void PortCore::closeUnits()
541{
542 // Empty the PortCore#units list. This is only possible when
543 // the server thread is finished.
544 yCIAssert(PORTCORE, getName(), m_finished.load());
545
546 // In the "finished" phase, nobody else touches the units,
547 // so we can go ahead and shut them down and delete them.
548 for (auto& i : m_units) {
549 PortCoreUnit* unit = i;
550 if (unit != nullptr) {
551 yCIDebug(PORTCORE, getName(), "closing a unit");
552 unit->close();
553 yCIDebug(PORTCORE, getName(), "joining a unit");
554 unit->join();
555 delete unit;
556 yCIDebug(PORTCORE, getName(), "deleting a unit");
557 i = nullptr;
558 }
559 }
560
561 // Get rid of all our nulls. Done!
562 m_units.clear();
563}
564
565void PortCore::reapUnits()
566{
567 // Connections that should be shut down get tagged as "doomed"
568 // but aren't otherwise touched until it is safe to do so.
569 if (!m_finished.load()) {
570 std::lock_guard<std::mutex> lock(m_stateMutex);
571 for (auto* unit : m_units) {
572 if ((unit != nullptr) && unit->isDoomed() && !unit->isFinished()) {
573 std::string s = unit->getRoute().toString();
574 yCIDebug(PORTCORE, getName(), "Informing connection %s that it is doomed", s.c_str());
575 unit->close();
576 yCIDebug(PORTCORE, getName(), "Closed connection %s", s.c_str());
577 unit->join();
578 yCIDebug(PORTCORE, getName(), "Joined thread of connection %s", s.c_str());
579 }
580 }
581 }
582 cleanUnits();
583}
584
585void PortCore::cleanUnits(bool blocking)
586{
587 // We will remove any connections that have finished operating from
588 // the PortCore#units list.
589
590 // Depending on urgency, either wait for a safe time to do this
591 // or skip if unsafe.
592 std::unique_lock<std::mutex> lock(m_stateMutex, std::defer_lock);
593 if (blocking) {
594 lock.lock();
595 } else {
596 bool have_lock = lock.try_lock();
597 if (!have_lock) {
598 return;
599 }
600 }
601 // here we have the lock
602
603 // We will update our connection counts as a by-product.
604 int updatedInputCount = 0;
605 int updatedOutputCount = 0;
607 yCIDebug(PORTCORE, getName(), "/ routine check of connections to this port begins");
608 if (!m_finished.load()) {
609
610 // First, we delete and null out any defunct entries in the list.
611 for (auto& i : m_units) {
612 PortCoreUnit* unit = i;
613 if (unit != nullptr) {
614 yCIDebug(PORTCORE, getName(), "| checking connection %s %s", unit->getRoute().toString().c_str(), unit->getMode().c_str());
615 if (unit->isFinished()) {
616 std::string con = unit->getRoute().toString();
617 yCIDebug(PORTCORE, getName(), "| removing connection %s", con.c_str());
618 unit->close();
619 unit->join();
620 delete unit;
621 i = nullptr;
622 yCIDebug(PORTCORE, getName(), "| removed connection %s", con.c_str());
623 } else {
624 // No work to do except updating connection counts.
625 if (!unit->isDoomed()) {
626 if (unit->isOutput()) {
628 if (unit->getMode().empty()) {
630 }
631 }
632 if (unit->isInput()) {
633 if (unit->getRoute().getFromName() != "admin") {
635 }
636 }
637 }
638 }
639 }
640 }
641
642 // Now we do some awkward shuffling (list class may be from ACE
643 // or STL, if ACE it is quite limited). We move the nulls to
644 // the end of the list ...
645 size_t rem = 0;
646 for (size_t i2 = 0; i2 < m_units.size(); i2++) {
647 if (m_units[i2] != nullptr) {
648 if (rem < i2) {
649 m_units[rem] = m_units[i2];
650 m_units[i2] = nullptr;
651 }
652 rem++;
653 }
654 }
655
656 // ... Now we get rid of the null entries
657 for (size_t i3 = 0; i3 < m_units.size() - rem; i3++) {
658 m_units.pop_back();
659 }
660 }
661
662 // Finalize the connection counts.
663 m_dataOutputCount = updatedDataOutputCount;
664 lock.unlock();
665
666 m_packetMutex.lock();
667 m_inputCount = updatedInputCount;
668 m_outputCount = updatedOutputCount;
669 m_packetMutex.unlock();
670 yCIDebug(PORTCORE, getName(), "\\ routine check of connections to this port ends");
671}
672
673
674void PortCore::addInput(InputProtocol* ip)
675{
676 yCITrace(PORTCORE, getName(), "addInput");
677
678 // This method is only called by the server thread in its running phase.
679 // It wraps up a network connection as a unit and adds it to
680 // PortCore#units. The unit will have its own thread associated
681 // with it.
682
683 yCIAssert(PORTCORE, getName(), ip != nullptr);
684 std::lock_guard<std::mutex> lock(m_stateMutex);
686 getNextIndex(),
687 ip,
688 false);
689 yCIAssert(PORTCORE, getName(), unit != nullptr);
690 unit->start();
691 m_units.push_back(unit);
692 yCITrace(PORTCORE, getName(), "there are now %zu units", m_units.size());
693}
694
695
697{
698 yCITrace(PORTCORE, getName(), "addOutput");
699
700 // This method is called from threads associated with input
701 // connections.
702 // It wraps up a network connection as a unit and adds it to
703 // PortCore#units. The unit will start with its own thread
704 // associated with it, but that thread will be very short-lived
705 // if the port is not configured to do background writes.
706
707 yCIAssert(PORTCORE, getName(), op != nullptr);
708 if (!m_finished.load()) {
709 std::lock_guard<std::mutex> lock(m_stateMutex);
710 PortCoreUnit* unit = new PortCoreOutputUnit(*this, getNextIndex(), op);
711 yCIAssert(PORTCORE, getName(), unit != nullptr);
712 unit->start();
713 m_units.push_back(unit);
714 }
715}
716
717
718bool PortCore::isUnit(const Route& route, int index)
719{
720 // Check if a connection with a specified route (and optional ID) is present
721 bool needReap = false;
722 if (!m_finished.load()) {
723 for (auto* unit : m_units) {
724 if (unit != nullptr) {
725 Route alt = unit->getRoute();
726 std::string wild = "*";
727 bool ok = true;
728 if (index >= 0) {
729 ok = ok && (unit->getIndex() == index);
730 }
731 if (ok) {
732 if (route.getFromName() != wild) {
733 ok = ok && (route.getFromName() == alt.getFromName());
734 }
735 if (route.getToName() != wild) {
736 ok = ok && (route.getToName() == alt.getToName());
737 }
738 if (route.getCarrierName() != wild) {
739 ok = ok && (route.getCarrierName() == alt.getCarrierName());
740 }
741 }
742 if (ok) {
743 needReap = true;
744 break;
745 }
746 }
747 }
748 }
749 return needReap;
750}
751
752
753bool PortCore::removeUnit(const Route& route, bool synch, bool* except)
754{
755 // This is a request to remove a connection. It could arise from any
756 // input thread.
757
758 if (except != nullptr) {
759 yCIDebug(PORTCORE, getName(), "asked to remove connection in the way of %s", route.toString().c_str());
760 *except = false;
761 } else {
762 yCIDebug(PORTCORE, getName(), "asked to remove connection %s", route.toString().c_str());
763 }
764
765 // Scan for units that match the given route, and collect their IDs.
766 // Mark them as "doomed".
767 std::vector<int> removals;
768
769 bool needReap = false;
770 if (!m_finished.load()) {
771 std::lock_guard<std::mutex> lock(m_stateMutex);
772 for (auto* unit : m_units) {
773 if (unit != nullptr) {
774 Route alt = unit->getRoute();
775 std::string wild = "*";
776 bool ok = true;
777 if (route.getFromName() != wild) {
778 ok = ok && (route.getFromName() == alt.getFromName());
779 }
780 if (route.getToName() != wild) {
781 ok = ok && (route.getToName() == alt.getToName());
782 }
783 if (route.getCarrierName() != wild) {
784 if (except == nullptr) {
785 ok = ok && (route.getCarrierName() == alt.getCarrierName());
786 } else {
787 if (route.getCarrierName() == alt.getCarrierName()) {
788 *except = true;
789 ok = false;
790 }
791 }
792 }
793
794 if (ok) {
795 yCIDebug(PORTCORE, getName(), "removing connection %s", alt.toString().c_str());
796 removals.push_back(unit->getIndex());
797 unit->setDoomed();
798 needReap = true;
799 }
800 }
801 }
802 }
803
804 // If we find one or more matches, we need to do some work.
805 // We've marked those matches as "doomed" so they'll get cleared
806 // up eventually, but we can speed this up by waking up the
807 // server thread.
808 if (needReap) {
809 yCIDebug(PORTCORE, getName(), "one or more connections need prodding to die");
810
811 if (m_manual) {
812 // No server thread, no problems.
813 reapUnits();
814 } else {
815 // Send a blank message to make up server thread.
816 OutputProtocol* op = m_face->write(m_address);
817 if (op != nullptr) {
818 op->close();
819 delete op;
820 }
821 yCIDebug(PORTCORE, getName(), "sent message to prod connection death");
822
823 if (synch) {
824 // Wait for connections to be cleaned up.
825 yCIDebug(PORTCORE, getName(), "synchronizing with connection death");
826 {
827 // Critical section
828 std::unique_lock<std::mutex> lock(m_stateMutex);
829 while (std::any_of(removals.begin(), removals.end(), [&](int removal){ return isUnit(route, removal); })) {
830 m_connectionListeners++;
831 m_connectionChangeCv.wait(lock, [&]{ return m_connectionListeners == 0; });
832 }
833 }
834 }
835 }
836 }
837 return needReap;
838}
839
840
841bool PortCore::addOutput(const std::string& dest,
842 void* id,
843 OutputStream* os,
844 bool onlyIfNeeded)
845{
846 YARP_UNUSED(id);
847 yCIDebug(PORTCORE, getName(), "asked to add output to %s", dest.c_str());
848
849 // Buffer to store text describing outcome (successful connection,
850 // or a failure).
852
853 // Look up the address we'll be connecting to.
854 Contact parts = Name(dest).toAddress();
855 Contact contact = NetworkBase::queryName(parts.getRegName());
856 Contact address = contact;
857
858 // If we can't find it, say so and abort.
859 if (!address.isValid()) {
860 bw.appendLine(std::string("Do not know how to connect to ") + dest);
861 if (os != nullptr) {
862 bw.write(*os);
863 }
864 return false;
865 }
866
867 // We clean all existing connections to the desired destination,
868 // optionally stopping if we find one with the right carrier.
869 if (onlyIfNeeded) {
870 // Remove any existing connections between source and destination
871 // with a different carrier. If we find a connection already
872 // present with the correct carrier, then we are done.
873 bool except = false;
874 removeUnit(Route(getName(), address.getRegName(), address.getCarrier()), true, &except);
875 if (except) {
876 // Connection already present.
877 yCIDebug(PORTCORE, getName(), "output already present to %s", dest.c_str());
878 bw.appendLine(std::string("Desired connection already present from ") + getName() + " to " + dest);
879 if (os != nullptr) {
880 bw.write(*os);
881 }
882 return true;
883 }
884 } else {
885 // Remove any existing connections between source and destination.
886 removeUnit(Route(getName(), address.getRegName(), "*"), true);
887 }
888
889 // Set up a named route for this connection.
890 std::string aname = address.getRegName();
891 if (aname.empty()) {
892 aname = address.toURI(false);
893 }
894 Route r(getName(),
895 aname,
896 ((!parts.getCarrier().empty()) ? parts.getCarrier() : address.getCarrier()));
897 r.setToContact(contact);
898
899 // Check for any restrictions on the port. Perhaps it can only
900 // read, or write.
901 bool allowed = true;
902 std::string err;
903 std::string append;
904 unsigned int f = getFlags();
905 bool allow_output = (f & PORTCORE_IS_OUTPUT) != 0;
906 bool rpc = (f & PORTCORE_IS_RPC) != 0;
907 Name name(r.getCarrierName() + std::string("://test"));
908 std::string mode = name.getCarrierModifier("log");
909 bool is_log = (!mode.empty());
910 if (is_log) {
911 if (mode != "in") {
912 err = "Logger configured as log." + mode + ", but only log.in is supported";
913 allowed = false;
914 } else {
915 append = "; " + r.getFromName() + " will forward messages and replies (if any) to " + r.getToName();
916 }
917 }
918 if (!allow_output) {
919 if (!is_log) {
920 bool push = false;
922 if (c != nullptr) {
923 push = c->isPush();
924 }
925 if (push) {
926 err = "Outputs not allowed";
927 allowed = false;
928 }
929 }
930 } else if (rpc) {
931 if (m_dataOutputCount >= 1 && !is_log) {
932 err = "RPC output already connected";
933 allowed = false;
934 }
935 }
936
937 // If we found a relevant restriction, abort.
938 if (!allowed) {
939 bw.appendLine(err);
940 if (os != nullptr) {
941 bw.write(*os);
942 }
943 return false;
944 }
945
946 // Ok! We can go ahead and make a connection.
947 OutputProtocol* op = nullptr;
948 if (m_timeout > 0) {
949 address.setTimeout(m_timeout);
950 }
951 op = Carriers::connect(address);
952 if (op != nullptr) {
953 op->attachPort(m_contactable);
954 if (m_timeout > 0) {
955 op->setTimeout(m_timeout);
956 }
957
958 bool ok = op->open(r);
959 if (!ok) {
960 yCIDebug(PORTCORE, getName(), "open route error");
961 delete op;
962 op = nullptr;
963 }
964 }
965
966 // No connection, abort.
967 if (op == nullptr) {
968 bw.appendLine(std::string("Cannot connect to ") + dest);
969 if (os != nullptr) {
970 bw.write(*os);
971 }
972 return false;
973 }
974
975 // Ok, we have a connection, now add it to PortCore#units
976 if (op->getConnection().isPush()) {
977 // This is the normal case
978 addOutput(op);
979 } else {
980 // This is the case for connections that are initiated
981 // in the opposite direction to native YARP connections.
982 // Native YARP has push connections, initiated by the
983 // sender. HTTP and ROS have pull connections, initiated
984 // by the receiver.
985 // We invert the route, flip the protocol direction, and add.
986 r.swapNames();
987 op->rename(r);
988 InputProtocol* ip = &(op->getInput());
989 if (!m_finished.load()) {
990 std::lock_guard<std::mutex> lock(m_stateMutex);
992 getNextIndex(),
993 ip,
994 true);
995 yCIAssert(PORTCORE, getName(), unit != nullptr);
996 unit->start();
997 m_units.push_back(unit);
998 }
999 }
1000
1001 // Communicated the good news.
1002 bw.appendLine(std::string("Added connection from ") + getName() + " to " + dest + append);
1003 if (os != nullptr) {
1004 bw.write(*os);
1005 }
1006 cleanUnits();
1007 return true;
1008}
1009
1010
1011bool PortCore::removeOutput(const std::string& dest, void* id, OutputStream* os)
1012{
1013 YARP_UNUSED(id);
1014 yCIDebug(PORTCORE, getName(), "asked to remove output to %s", dest.c_str());
1015
1016 // All the real work done by removeUnit().
1018 const bool removed = removeUnit(Route("*", dest, "*"), true);
1019 if (removed) {
1020 bw.appendLine(std::string("Removed connection from ") + getName() + " to " + dest);
1021 } else {
1022 bw.appendLine(std::string("Could not find an outgoing connection to ") + dest);
1023 }
1024 if (os != nullptr) {
1025 bw.write(*os);
1026 }
1027 cleanUnits();
1028 return removed;
1029}
1030
1031bool PortCore::removeInput(const std::string& src, void* id, OutputStream* os)
1032{
1033 YARP_UNUSED(id);
1034 yCIDebug(PORTCORE, getName(), "asked to remove input to %s", src.c_str());
1035
1036 // All the real work done by removeUnit().
1038 const bool removed = removeUnit(Route(src, "*", "*"), true);
1039 if (removed) {
1040 bw.appendLine(std::string("Removing connection from ") + src + " to " + getName());
1041 } else {
1042 bw.appendLine(std::string("Could not find an incoming connection from ") + src);
1043 }
1044 if (os != nullptr) {
1045 bw.write(*os);
1046 }
1047 cleanUnits();
1048 return removed;
1049}
1050
1052{
1053 YARP_UNUSED(id);
1054 cleanUnits();
1055
1056 // Buffer to store a human-readable description of the port's
1057 // state.
1059
1060 {
1061 // Critical section
1062 std::lock_guard<std::mutex> lock(m_stateMutex);
1063
1064 // Report name and address.
1065 bw.appendLine(std::string("This is ") + m_address.getRegName() + " at " + m_address.toURI());
1066
1067 // Report outgoing connections.
1068 int oct = 0;
1069 for (auto* unit : m_units) {
1070 if ((unit != nullptr) && unit->isOutput() && !unit->isFinished()) {
1071 Route route = unit->getRoute();
1072 std::string msg = "There is an output connection from " + route.getFromName() + " to " + route.getToName() + " using " + route.getCarrierName();
1073 bw.appendLine(msg);
1074 oct++;
1075 }
1076 }
1077 if (oct < 1) {
1078 bw.appendLine("There are no outgoing connections");
1079 }
1080
1081 // Report incoming connections.
1082 int ict = 0;
1083 for (auto* unit : m_units) {
1084 if ((unit != nullptr) && unit->isInput() && !unit->isFinished()) {
1085 Route route = unit->getRoute();
1086 if (!route.getCarrierName().empty()) {
1087 std::string msg = "There is an input connection from " + route.getFromName() + " to " + route.getToName() + " using " + route.getCarrierName();
1088 bw.appendLine(msg);
1089 ict++;
1090 }
1091 }
1092 }
1093 if (ict < 1) {
1094 bw.appendLine("There are no incoming connections");
1095 }
1096 }
1097
1098 // Send description across network, or print it.
1099 if (os != nullptr) {
1100 bw.write(*os);
1101 } else {
1103 bw.write(sos);
1104 printf("%s\n", sos.toString().c_str());
1105 }
1106}
1107
1108
1110{
1111 cleanUnits();
1112
1113 std::lock_guard<std::mutex> lock(m_stateMutex);
1114
1115 // Report name and address of port.
1118 std::string portName = m_address.getRegName();
1119 baseInfo.message = std::string("This is ") + portName + " at " + m_address.toURI();
1120 reporter.report(baseInfo);
1121
1122 // Report outgoing connections.
1123 int oct = 0;
1124 for (auto* unit : m_units) {
1125 if ((unit != nullptr) && unit->isOutput() && !unit->isFinished()) {
1126 Route route = unit->getRoute();
1127 std::string msg = "There is an output connection from " + route.getFromName() + " to " + route.getToName() + " using " + route.getCarrierName();
1128 PortInfo info;
1129 info.message = msg;
1131 info.incoming = false;
1132 info.portName = portName;
1133 info.sourceName = route.getFromName();
1134 info.targetName = route.getToName();
1135 info.carrierName = route.getCarrierName();
1136 reporter.report(info);
1137 oct++;
1138 }
1139 }
1140 if (oct < 1) {
1141 PortInfo info;
1143 info.message = "There are no outgoing connections";
1144 reporter.report(info);
1145 }
1146
1147 // Report incoming connections.
1148 int ict = 0;
1149 for (auto* unit : m_units) {
1150 if ((unit != nullptr) && unit->isInput() && !unit->isFinished()) {
1151 Route route = unit->getRoute();
1152 std::string msg = "There is an input connection from " + route.getFromName() + " to " + route.getToName() + " using " + route.getCarrierName();
1153 PortInfo info;
1154 info.message = msg;
1156 info.incoming = true;
1157 info.portName = portName;
1158 info.sourceName = route.getFromName();
1159 info.targetName = route.getToName();
1160 info.carrierName = route.getCarrierName();
1161 reporter.report(info);
1162 ict++;
1163 }
1164 }
1165 if (ict < 1) {
1166 PortInfo info;
1168 info.message = "There are no incoming connections";
1169 reporter.report(info);
1170 }
1171}
1172
1173
1175{
1176 std::lock_guard<std::mutex> lock(m_stateMutex);
1177 if (reporter != nullptr) {
1178 m_eventReporter = reporter;
1179 }
1180}
1181
1183{
1184 std::lock_guard<std::mutex> lock(m_stateMutex);
1185 m_eventReporter = nullptr;
1186}
1187
1189{
1190 // We are in the context of one of the input or output threads,
1191 // so our contact with the PortCore must be absolutely minimal.
1192 //
1193 // It is safe to pick up the address of the reporter if this is
1194 // kept constant over the lifetime of the input/output threads.
1195
1196 if (m_eventReporter != nullptr) {
1197 m_eventReporter->report(info);
1198 }
1199}
1200
1201
1203{
1204 YARP_UNUSED(id);
1205 YARP_UNUSED(os);
1206 bool result = true;
1207
1208 // We are in the context of one of the input threads,
1209 // so our contact with the PortCore must be absolutely minimal.
1210 //
1211 // It is safe to pick up the address of the reader since this is
1212 // constant over the lifetime of the input threads.
1213
1214 if (m_reader != nullptr && !m_interrupted) {
1215 m_interruptable = false; // No mutex; user of interrupt() has to be careful.
1216
1217 bool haveOutputs = (m_outputCount != 0); // No mutex, but failure modes are benign.
1218
1219 if (m_logNeeded && haveOutputs) {
1220 // Normally, yarp doesn't pay attention to the content of
1221 // messages received by the client. Likewise, the content
1222 // of replies are not monitored. However it may sometimes
1223 // be useful to log this traffic.
1224
1226 recorder.init(&reader);
1227 lockCallback();
1228 result = m_reader->read(recorder);
1230 recorder.fini();
1231 // send off a log of this transaction to whoever wants it
1233 } else {
1234 // YARP is not needed as a middleman
1235 lockCallback();
1236 result = m_reader->read(reader);
1238 }
1239
1240 m_interruptable = true;
1241 } else {
1242 // Read and ignore message, there is no where to send it.
1243 yCIDebug(PORTCORE, getName(), "data received, no reader for it");
1244 Bottle b;
1245 result = b.read(reader);
1246 }
1247 return result;
1248}
1249
1250
1251bool PortCore::send(const PortWriter& writer,
1252 PortReader* reader,
1253 const PortWriter* callback)
1254{
1255 // check if there is any modifier
1256 // we need to protect this part while the modifier
1257 // plugin is loading or unloading!
1258 m_modifier.outputMutex.lock();
1259 if (m_modifier.outputModifier != nullptr) {
1260 if (!m_modifier.outputModifier->acceptOutgoingData(writer)) {
1261 m_modifier.outputMutex.unlock();
1262 return false;
1263 }
1264 m_modifier.outputModifier->modifyOutgoingData(writer);
1265 }
1266 m_modifier.outputMutex.unlock();
1267 if (!m_logNeeded) {
1268 return sendHelper(writer, PORTCORE_SEND_NORMAL, reader, callback);
1269 }
1270 // logging is desired, so we need to wrap up and log this send
1271 // (and any reply it gets) -- TODO not yet supported
1272 return sendHelper(writer, PORTCORE_SEND_NORMAL, reader, callback);
1273}
1274
1276 int mode,
1277 PortReader* reader,
1278 const PortWriter* callback)
1279{
1280 if (m_interrupted || m_finishing) {
1281 return false;
1282 }
1283
1284 bool all_ok = true;
1285 bool gotReply = false;
1286 int logCount = 0;
1287 std::string envelopeString = m_envelope;
1288
1289 // Pass a message to all output units for sending on. We could
1290 // be doing more here to cache the serialization of the message
1291 // and reuse it across output connections. However, one key
1292 // optimization is present: external blocks written by
1293 // yarp::os::ConnectionWriter::appendExternalBlock are never
1294 // copied. So for example the core image array in a yarp::sig::Image
1295 // is untouched by the port communications code.
1296
1297 yCITrace(PORTCORE, getName(), "------- send in real");
1298
1299 // Give user the chance to know that this object is about to be
1300 // written.
1301 writer.onCommencement();
1302
1303 // All user-facing parts of this port will be blocked on this
1304 // operation, so we'll want to be snappy. How long the
1305 // operation lasts will depend on these flags:
1306 // * waitAfterSend
1307 // * waitBeforeSend
1308 // set by setWaitAfterSend() and setWaitBeforeSend().
1309 std::lock_guard<std::mutex> lock(m_stateMutex);
1310
1311 // If the port is shutting down, abort.
1312 if (m_finished.load()) {
1313 return false;
1314 }
1315
1316 yCITrace(PORTCORE, getName(), "------- send in");
1317 // Prepare a "packet" for tracking a single message which
1318 // may travel by multiple outputs.
1319 m_packetMutex.lock();
1320 PortCorePacket* packet = m_packets.getFreePacket();
1321 yCIAssert(PORTCORE, getName(), packet != nullptr);
1322 packet->setContent(&writer, false, callback);
1323 m_packetMutex.unlock();
1324
1325 // Scan connections, placing message everywhere we can.
1326 for (auto* unit : m_units) {
1327 if ((unit != nullptr) && unit->isOutput() && !unit->isFinished()) {
1328 bool log = (!unit->getMode().empty());
1329 if (log) {
1330 // Some connections are for logging only.
1331 logCount++;
1332 }
1333 bool ok = (mode == PORTCORE_SEND_NORMAL) ? (!log) : (log);
1334 if (!ok) {
1335 continue;
1336 }
1337 bool waiter = m_waitAfterSend || (mode == PORTCORE_SEND_LOG);
1338 yCITrace(PORTCORE, getName(), "------- -- inc");
1339 m_packetMutex.lock();
1340 packet->inc(); // One more connection carrying message.
1341 m_packetMutex.unlock();
1342 yCITrace(PORTCORE, getName(), "------- -- pre-send");
1343 bool gotReplyOne = false;
1344 // Send the message off on this connection.
1345 void* out = unit->send(writer,
1346 reader,
1347 (callback != nullptr) ? callback : (&writer),
1348 reinterpret_cast<void*>(packet),
1350 waiter,
1351 m_waitBeforeSend,
1352 &gotReplyOne);
1354 yCITrace(PORTCORE, getName(), "------- -- send");
1355 if (out != nullptr) {
1356 // We got back a report of a message already sent.
1357 m_packetMutex.lock();
1358 (static_cast<PortCorePacket*>(out))->dec(); // Message on one fewer connections.
1359 m_packets.checkPacket(static_cast<PortCorePacket*>(out));
1360 m_packetMutex.unlock();
1361 }
1362 if (waiter) {
1363 if (unit->isFinished()) {
1364 all_ok = false;
1365 }
1366 }
1367 yCITrace(PORTCORE, getName(), "------- -- dec");
1368 }
1369 }
1370 yCITrace(PORTCORE, getName(), "------- pack check");
1371 m_packetMutex.lock();
1372
1373 // We no longer concern ourselves with the message.
1374 // It may or may not be traveling on some connections.
1375 // But that is not our problem anymore.
1376 packet->dec();
1377
1378 m_packets.checkPacket(packet);
1379 m_packetMutex.unlock();
1380 yCITrace(PORTCORE, getName(), "------- packed");
1381 yCITrace(PORTCORE, getName(), "------- send out");
1382 if (mode == PORTCORE_SEND_LOG) {
1383 if (logCount == 0) {
1384 m_logNeeded = false;
1385 }
1386 }
1387
1388 yCITrace(PORTCORE, getName(), "------- send out real");
1389
1390 if (m_waitAfterSend && reader != nullptr) {
1391 all_ok = all_ok && gotReply;
1392 }
1393
1394 return all_ok;
1395}
1396
1397
1399{
1400 bool writing = false;
1401
1402 // Check if any port is currently writing. TODO optimize
1403 // this query by counting down with notifyCompletion().
1404 if (!m_finished.load()) {
1405 std::lock_guard<std::mutex> lock(m_stateMutex);
1406 for (auto* unit : m_units) {
1407 if ((unit != nullptr) && !unit->isFinished() && unit->isBusy()) {
1408 writing = true;
1409 }
1410 }
1411 }
1412
1413 return writing;
1414}
1415
1416
1418{
1419 cleanUnits(false);
1420 m_packetMutex.lock();
1421 int result = m_inputCount;
1422 m_packetMutex.unlock();
1423 return result;
1424}
1425
1427{
1428 cleanUnits(false);
1429 m_packetMutex.lock();
1430 int result = m_outputCount;
1431 m_packetMutex.unlock();
1432 return result;
1433}
1434
1435
1437{
1438 yCITrace(PORTCORE, getName(), "starting notifyCompletion");
1439 m_packetMutex.lock();
1440 if (tracker != nullptr) {
1441 (static_cast<PortCorePacket*>(tracker))->dec();
1442 m_packets.checkPacket(static_cast<PortCorePacket*>(tracker));
1443 }
1444 m_packetMutex.unlock();
1445 yCITrace(PORTCORE, getName(), "stopping notifyCompletion");
1446}
1447
1448
1450{
1451 m_envelopeWriter.restart();
1452 bool ok = envelope.write(m_envelopeWriter);
1453 if (ok) {
1454 setEnvelope(m_envelopeWriter.toString());
1455 }
1456 return ok;
1457}
1458
1459
1460void PortCore::setEnvelope(const std::string& envelope)
1461{
1462 m_envelope = envelope;
1463 for (size_t i = 0; i < m_envelope.length(); i++) {
1464 // It looks like envelopes are constrained to be printable ASCII?
1465 // I'm not sure why this would be. TODO check.
1466 if (m_envelope[i] < 32) {
1467 m_envelope = m_envelope.substr(0, i);
1468 break;
1469 }
1470 }
1471 yCIDebug(PORTCORE, getName(), "set envelope to %s", m_envelope.c_str());
1472}
1473
1475{
1476 return m_envelope;
1477}
1478
1480{
1482 sis.add(m_envelope);
1483 sis.add("\r\n");
1485 Route route;
1486 sbr.reset(sis, nullptr, route, 0, true);
1487 return envelope.read(sbr);
1488}
1489
1490// Make an RPC connection to talk to a ROS API, send a message, get reply.
1491// NOTE: ROS support can now be moved out of here, once all documentation
1492// of older ways to interoperate with it are purged and people stop
1493// doing it.
1494static bool __pc_rpc(const Contact& c,
1495 const char* carrier,
1496 Bottle& writer,
1497 Bottle& reader,
1498 bool verbose)
1499{
1500 ContactStyle style;
1501 style.quiet = !verbose;
1502 style.timeout = 4;
1503 style.carrier = carrier;
1504 bool ok = Network::write(c, writer, reader, style);
1505 return ok;
1506}
1507
1508// ACE is sometimes confused by localhost aliases, in a ROS-incompatible
1509// way. This method does a quick sanity check if we are using ROS.
1510static bool __tcp_check(const Contact& c)
1511{
1512#ifdef YARP_HAS_ACE
1514 int result = addr.set(c.getPort(), c.getHost().c_str());
1515 if (result != 0) {
1516 yCWarning(PORTCORE, "ACE choked on %s:%d\n", c.getHost().c_str(), c.getPort());
1517 }
1518 result = addr.set(c.getPort(), "127.0.0.1");
1519 if (result != 0) {
1520 yCWarning(PORTCORE, "ACE choked on 127.0.0.1:%d\n", c.getPort());
1521 }
1522 result = addr.set(c.getPort(), "127.0.1.1");
1523 if (result != 0) {
1524 yCWarning(PORTCORE, "ACE choked on 127.0.1.1:%d\n", c.getPort());
1525 }
1526#endif
1527 return true;
1528}
1529
1531 void* id)
1532{
1533 Bottle cmd;
1534 Bottle result;
1535
1536 // We've received a message to the port that is marked as administrative.
1537 // That means that instead of passing it along as data to the user of the
1538 // port, the port itself is responsible for reading and responding to
1539 // it. So let's read the message and see what we're supposed to do.
1540 cmd.read(reader);
1541
1542 yCIDebug(PORTCORE, getName(), "Port %s received command %s", getName().c_str(), cmd.toString().c_str());
1543
1544 // Server side of the commands defined in idl/PortCoreMsgs.thrift.
1545 // NOTE: being a local class, it has the same access rights of adminBlock().
1547 {
1549 void* m_id; // the id of the unit which sent the command
1550
1551 bool attach(const std::string& portmonitor_options, bool isOutput)
1552 {
1553 std::string errMsg;
1554 if (!m_owner.attachPortMonitor(portmonitor_options, isOutput, errMsg)) {
1555 yCIError(PORTCORE, m_owner.getName(), "%s", errMsg.c_str());
1556 return false;
1557 }
1558 return true;
1559 }
1560
1562 {
1564 result.ret = true;
1565 std::lock_guard<std::mutex> lock(m_owner.m_stateMutex);
1566 for (auto* unit : m_owner.m_units) {
1567 if ((unit != nullptr) && (isInput ? unit->isInput() : unit->isOutput()) && !unit->isFinished()) {
1568 const Route route = unit->getRoute();
1569 const std::string& name = isInput ? route.getFromName() : route.getToName();
1570 if (!name.empty()) {
1571 result.connections.push_back(name);
1572 }
1573 }
1574 }
1575 return result;
1576 }
1577
1578 return_getConnectionInfo getConnectionInfo(bool isInput, const std::string& portname)
1579 {
1581 result.ret = true;
1582 std::lock_guard<std::mutex> lock(m_owner.m_stateMutex);
1583 for (auto* unit : m_owner.m_units) {
1584 if ((unit != nullptr) && (isInput ? unit->isInput() : unit->isOutput()) && !unit->isFinished()) {
1585 const Route route = unit->getRoute();
1586 if ((isInput ? route.getFromName() : route.getToName()) == portname) {
1587 result.found = true;
1588 result.from_port = route.getFromName();
1589 result.to_port = route.getToName();
1590 result.carrier = route.getCarrierName();
1592 if (carrier != nullptr) {
1593 result.connectionless = carrier->isConnectionless();
1594 result.push = carrier->isPush();
1595 delete carrier;
1596 }
1597 break;
1598 }
1599 }
1600 }
1601 return result;
1602 }
1603
1604 return_setPortmonitorParams setPortmonitorParams(const std::string& params, bool isOutput)
1605 {
1607 result.ret = true;
1608 Property property;
1609 property.fromString(params);
1610 result.success = m_owner.setParamPortMonitor(property, isOutput, result.message);
1611 return result;
1612 }
1613
1614 return_getPortmonitorParams getPortmonitorParams(bool isOutput)
1615 {
1617 result.ret = true;
1618 Property property;
1619 result.success = m_owner.getParamPortMonitor(property, isOutput, result.message);
1620 if (result.success) {
1621 result.params = property.toString();
1622 }
1623 return result;
1624 }
1625
1626 // Returns the unit of the (active) connection coming from (isInput) or
1627 // going to (!isInput) the given port, or nullptr if there is none.
1628 // NOTE: m_owner.m_stateMutex must be locked by the caller.
1629 PortCoreUnit* findConnectionUnit(bool isInput, const std::string& portname)
1630 {
1631 for (auto* unit : m_owner.m_units) {
1632 if ((unit != nullptr) && (isInput ? unit->isInput() : unit->isOutput()) && !unit->isFinished()) {
1633 const Route route = unit->getRoute();
1634 if ((isInput ? route.getFromName() : route.getToName()) == portname) {
1635 return unit;
1636 }
1637 }
1638 }
1639 return nullptr;
1640 }
1641
1642 std::string connectionNotFoundMessage(bool isInput, const std::string& portname)
1643 {
1644 return isInput ? "Could not find an incoming connection from " + portname
1645 : "Could not find an outgoing connection to " + portname;
1646 }
1647
1648 return_setConnectionParams setConnectionParams(bool isInput, const std::string& portname, const std::string& params)
1649 {
1651 result.ret = true;
1652 std::lock_guard<std::mutex> lock(m_owner.m_stateMutex);
1653 PortCoreUnit* unit = findConnectionUnit(isInput, portname);
1654 if (unit == nullptr) {
1655 result.success = false;
1656 result.message = connectionNotFoundMessage(isInput, portname);
1657 return result;
1658 }
1659 Property property;
1660 property.fromString(params);
1661 unit->setCarrierParams(property);
1662 result.success = true;
1663 result.message = (isInput ? "Configured connection from " : "Configured connection to ") + portname;
1664 return result;
1665 }
1666
1667 return_getConnectionParams getConnectionParams(bool isInput, const std::string& portname)
1668 {
1670 result.ret = true;
1671 std::lock_guard<std::mutex> lock(m_owner.m_stateMutex);
1672 PortCoreUnit* unit = findConnectionUnit(isInput, portname);
1673 if (unit == nullptr) {
1674 result.success = false;
1675 result.message = connectionNotFoundMessage(isInput, portname);
1676 return result;
1677 }
1678 Property property;
1679 unit->getCarrierParams(property);
1680 result.success = true;
1681 result.params = property.toString();
1682 return result;
1683 }
1684
1685 return_getConnectionQos getConnectionQos(bool isInput, const std::string& portname)
1686 {
1688 result.ret = true;
1689 result.qos_tos = -1;
1690 std::lock_guard<std::mutex> lock(m_owner.m_stateMutex);
1691 PortCoreUnit* unit = findConnectionUnit(isInput, portname);
1692 if (unit != nullptr) {
1693 result.found = true;
1694 result.thread.tid = static_cast<int>(unit->getTid());
1695 result.thread.priority = unit->getPriority();
1696 result.thread.policy = unit->getPolicy();
1697 result.qos_tos = m_owner.getTypeOfService(unit);
1698 }
1699 return result;
1700 }
1701
1702 return_setConnectionQos setConnectionQos(bool isInput, const std::string& portname, int priority, int policy, int tos)
1703 {
1704 // The priority and policy values on Linux are:
1705 // SCHED_OTHER : policy=0, priority=[0 .. 0]
1706 // SCHED_FIFO : policy=1, priority=[1 .. 99]
1707 // SCHED_RR : policy=2, priority=[1 .. 99]
1709 result.ret = true;
1710 std::lock_guard<std::mutex> lock(m_owner.m_stateMutex);
1711 PortCoreUnit* unit = findConnectionUnit(isInput, portname);
1712 if (unit == nullptr) {
1713 result.success = false;
1714 result.message = connectionNotFoundMessage(isInput, portname);
1715 return result;
1716 }
1717 if (unit->setPriority(priority, policy) == -1) {
1718 result.success = false;
1719 result.message = "Cannot set the scheduling parameters of the thread of the connection";
1720 return result;
1721 }
1722 // a negative tos means "leave unchanged"
1723 if (tos >= 0 && !m_owner.setTypeOfService(unit, tos)) {
1724 result.success = false;
1725 result.message = "Cannot set the type of service of the connection";
1726 return result;
1727 }
1728 result.success = true;
1729 return result;
1730 }
1731
1732 public:
1733 PortCoreMsgsServer(PortCore& owner, void* id) : m_owner(owner), m_id(id) {}
1734
1735 return_addConnection addConnection(const std::string& portname, const std::string& carrier) override
1736 {
1737 // Add an output to the port.
1738 return_addConnection result;
1739 result.ret = true;
1740 const std::string output = carrier.empty() ? portname : carrier + ":/" + portname;
1741 StringOutputStream cache;
1742 result.success = m_owner.addOutput(output, m_id, &cache, false);
1743 result.message = cache.toString();
1744 return result;
1745 }
1746
1747 return_delConnection delConnection(const std::string& portname) override
1748 {
1749 // Delete any inputs or outputs involving the named port.
1750 return_delConnection result;
1751 result.ret = true;
1752 StringOutputStream cache;
1753 const bool removedOutput = m_owner.removeOutput(portname, m_id, &cache);
1754 const std::string outputMessage = cache.toString();
1755 cache.reset();
1756 const bool removedInput = m_owner.removeInput(portname, m_id, &cache);
1757 const std::string inputMessage = cache.toString();
1758 // The operation succeeds if at least one connection was removed.
1759 // The reply contains only the message(s) of the removal(s) which
1760 // actually happened (or both failure messages, if none).
1762 if (removedOutput && !removedInput) {
1763 result.message = outputMessage;
1764 } else if (!removedOutput && removedInput) {
1765 result.message = inputMessage;
1766 } else {
1768 }
1769 return result;
1770 }
1771
1772 bool attachPortmonitorOut(const std::string& prop) override { return attach(prop, true); }
1773 bool attachPortmonitorIn(const std::string& prop) override { return attach(prop, false); }
1774 bool detachPortmonitorOut() override { return m_owner.detachPortMonitor(true); }
1775 bool detachPortmonitorIn() override { return m_owner.detachPortMonitor(false); }
1776 return_setPortmonitorParams setPortmonitorParamsOut(const std::string& params) override { return setPortmonitorParams(params, true); }
1777 return_setPortmonitorParams setPortmonitorParamsIn(const std::string& params) override { return setPortmonitorParams(params, false); }
1778 return_getPortmonitorParams getPortmonitorParamsOut() override { return getPortmonitorParams(true); }
1779 return_getPortmonitorParams getPortmonitorParamsIn() override { return getPortmonitorParams(false); }
1780 return_setConnectionParams setConnectionParamsOut(const std::string& portname, const std::string& params) override { return setConnectionParams(false, portname, params); }
1781 return_setConnectionParams setConnectionParamsIn(const std::string& portname, const std::string& params) override { return setConnectionParams(true, portname, params); }
1782 return_getConnectionParams getConnectionParamsOut(const std::string& portname) override { return getConnectionParams(false, portname); }
1783 return_getConnectionParams getConnectionParamsIn(const std::string& portname) override { return getConnectionParams(true, portname); }
1784 return_listConnections listConnectionsIn() override { return listConnections(true); }
1785 return_listConnections listConnectionsOut() override { return listConnections(false); }
1786 return_getConnectionInfo getConnectionInfoIn(const std::string& portname) override { return getConnectionInfo(true, portname); }
1787 return_getConnectionInfo getConnectionInfoOut(const std::string& portname) override { return getConnectionInfo(false, portname); }
1788
1789 return_getAdminProtocolVersion getAdminProtocolVersion() override
1790 {
1791 // Gives a version number for the administrative commands.
1792 // It is distinct from YARP library versioning.
1794 result.ret = true;
1795 result.version_major = 1;
1796 result.version_minor = 2;
1797 result.version_patch = 4;
1798 return result;
1799 }
1800
1801 return_getPortInfo getPortInfo() override
1802 {
1803 return_getPortInfo result;
1804 result.ret = true;
1805
1807 result.process = processInfo;
1808 if (processInfo.pid == -1) {
1809 result.process.name = "unknown";
1810 result.process.arguments = "unknown";
1811 }
1813
1814 result.thread.tid = static_cast<int>(m_owner.getTid());
1815 result.thread.priority = m_owner.getPriority();
1816 result.thread.policy = m_owner.getPolicy();
1817
1818 const unsigned int flags = m_owner.getFlags();
1819 result.port.is_input = (flags & PORTCORE_IS_INPUT) != 0;
1820 result.port.is_output = (flags & PORTCORE_IS_OUTPUT) != 0;
1821 result.port.is_rpc = (flags & PORTCORE_IS_RPC) != 0;
1822 result.port.type = m_owner.getType().getName();
1823 result.port.hostname = m_owner.m_address.getHost();
1824 return result;
1825 }
1826
1827 return_getConnectionQos getConnectionQosIn(const std::string& portname) override { return getConnectionQos(true, portname); }
1828 return_getConnectionQos getConnectionQosOut(const std::string& portname) override { return getConnectionQos(false, portname); }
1829 return_setConnectionQos setConnectionQosIn(const std::string& portname, const std::int32_t scheduler_priority, const std::int32_t scheduler_policy, const std::int32_t qos_tos) override { return setConnectionQos(true, portname, scheduler_priority, scheduler_policy, qos_tos); }
1830 return_setConnectionQos setConnectionQosOut(const std::string& portname, const std::int32_t scheduler_priority, const std::int32_t scheduler_policy, const std::int32_t qos_tos) override { return setConnectionQos(false, portname, scheduler_priority, scheduler_policy, qos_tos); }
1831
1832 bool setProcessScheduling(const std::int32_t priority, const std::int32_t policy) override
1833 {
1834 // set the scheduling parameters of all the threads of the process
1835 return m_owner.setProcessSchedulingParam(priority, policy);
1836 }
1837 };
1838
1839 auto handleAdminThriftCmd = [this, id](const Bottle& cmd, Bottle& result) {
1840 // Forward the (already read) command to the thrift service and
1841 // collect its reply. Returns false if the command is not one of
1842 // the commands of the service.
1843 PortCoreMsgsServer server(*this, id);
1844 DummyConnector con;
1845 cmd.write(con.getWriter());
1846 if (!server.read(con.getReader())) {
1847 return false;
1848 }
1849 result.read(con.getReader());
1850 return true;
1851 };
1852
1853 auto handleAdminUnknownCmd = [this](const Bottle& cmd) {
1854 Bottle result;
1855 bool ok = false;
1856 if (m_adminReader != nullptr) {
1857 DummyConnector con;
1858 cmd.write(con.getWriter());
1859 lockCallback();
1860 ok = m_adminReader->read(con.getReader());
1862 if (ok) {
1863 result.read(con.getReader());
1864 }
1865 }
1866 if (!ok) {
1867 result.addVocab32("fail");
1868 result.addString("send help for the list of valid commands");
1869 }
1870 return result;
1871 };
1872
1873 // All the administrative commands (including "help") are defined in the
1874 // thrift service PortCoreMsgs. Other commands are forwarded to the admin
1875 // reader (if any).
1876 if (!handleAdminThriftCmd(cmd, result)) {
1877 result = handleAdminUnknownCmd(cmd);
1878 }
1879
1880 ConnectionWriter* writer = reader.getWriter();
1881 if (writer != nullptr) {
1882 result.write(*writer);
1883 }
1884
1885 return true;
1886}
1887
1888
1889bool PortCore::setTypeOfService(PortCoreUnit* unit, int tos)
1890{
1891 if (unit == nullptr) {
1892 return false;
1893 }
1894
1895 yCIDebug(PORTCORE, getName(), "Trying to set TOS = %d", tos);
1896
1897 if (unit->isOutput()) {
1898 auto* outUnit = dynamic_cast<PortCoreOutputUnit*>(unit);
1899 if (outUnit != nullptr) {
1900 OutputProtocol* op = outUnit->getOutPutProtocol();
1901 if (op != nullptr) {
1902 yCIDebug(PORTCORE, getName(), "Trying to set TOS = %d on output unit", tos);
1903 bool ok = op->getOutputStream().setTypeOfService(tos);
1904 if (!ok) {
1905 yCIWarning(PORTCORE, getName(), "Setting TOS on output unit failed");
1906 }
1907 return ok;
1908 }
1909 }
1910 }
1911
1912 // Some of the input units may have output stream object to write back to
1913 // the connection (e.g., tcp ack and reply). Thus the QoS preferences should be
1914 // also configured for them.
1915
1916
1917 if (unit->isInput()) {
1918 auto* inUnit = dynamic_cast<PortCoreInputUnit*>(unit);
1919 if (inUnit != nullptr) {
1920 InputProtocol* ip = inUnit->getInPutProtocol();
1921 if ((ip != nullptr) && ip->getOutput().isOk()) {
1922 yCIDebug(PORTCORE, getName(), "Trying to set TOS = %d on input unit", tos);
1923 bool ok = ip->getOutput().getOutputStream().setTypeOfService(tos);
1924 if (!ok) {
1925 yCIWarning(PORTCORE, getName(), "Setting TOS on input unit failed");
1926 }
1927 return ok;
1928 }
1929 }
1930 }
1931 // if there is nothing to be set, returns true
1932 return true;
1933}
1934
1935int PortCore::getTypeOfService(PortCoreUnit* unit)
1936{
1937 if (unit == nullptr) {
1938 return -1;
1939 }
1940
1941 if (unit->isOutput()) {
1942 auto* outUnit = dynamic_cast<PortCoreOutputUnit*>(unit);
1943 if (outUnit != nullptr) {
1944 OutputProtocol* op = outUnit->getOutPutProtocol();
1945 if (op != nullptr) {
1946 return op->getOutputStream().getTypeOfService();
1947 }
1948 }
1949 }
1950
1951 // Some of the input units may have output stream object to write back to
1952 // the connection (e.g., tcp ack and reply). Thus the QoS preferences should be
1953 // also configured for them.
1954
1955
1956 if (unit->isInput()) {
1957 auto* inUnit = dynamic_cast<PortCoreInputUnit*>(unit);
1958 if (inUnit != nullptr) {
1959 InputProtocol* ip = inUnit->getInPutProtocol();
1960 if ((ip != nullptr) && ip->getOutput().isOk()) {
1961 return ip->getOutput().getOutputStream().getTypeOfService();
1962 }
1963 }
1964 }
1965 return -1;
1966}
1967
1968// attach a portmonitor plugin to the port or to a specific connection
1969bool PortCore::attachPortMonitor(const std::string& portmonitor_options, bool isOutput, std::string& errMsg)
1970{
1971 // attach to the current port
1973 if (portmonitor == nullptr) {
1974 errMsg = "Portmonitor carrier modifier cannot be find or it is not enabled in YARP!";
1975 return false;
1976 }
1977
1978 yarp::os::Property prop;
1980
1981 if (isOutput) {
1982 detachPortMonitor(true);
1983 prop.put("source", getName());
1984 prop.put("destination", "");
1985 prop.put("sender_side", 1);
1986 prop.put("receiver_side", 0);
1987 prop.put("carrier", "");
1988 m_modifier.outputMutex.lock();
1989 m_modifier.outputModifier = portmonitor;
1990 if (!m_modifier.outputModifier->configureFromProperty(prop)) {
1991 m_modifier.releaseOutModifier();
1992 errMsg = "Failed to configure the portmonitor plug-in";
1993 m_modifier.outputMutex.unlock();
1994 return false;
1995 }
1996 m_modifier.outputMutex.unlock();
1997 } else {
1998 detachPortMonitor(false);
1999 prop.put("source", "");
2000 prop.put("destination", getName());
2001 prop.put("sender_side", 0);
2002 prop.put("receiver_side", 1);
2003 prop.put("carrier", "");
2004 m_modifier.inputMutex.lock();
2005 m_modifier.inputModifier = portmonitor;
2006 if (!m_modifier.inputModifier->configureFromProperty(prop)) {
2007 m_modifier.releaseInModifier();
2008 errMsg = "Failed to configure the portmonitor plug-in";
2009 m_modifier.inputMutex.unlock();
2010 return false;
2011 }
2012 m_modifier.inputMutex.unlock();
2013 }
2014 return true;
2015}
2016
2017// detach the portmonitor from the port or specific connection
2018bool PortCore::detachPortMonitor(bool isOutput)
2019{
2020 if (isOutput) {
2021 m_modifier.outputMutex.lock();
2022 m_modifier.releaseOutModifier();
2023 m_modifier.outputMutex.unlock();
2024 } else {
2025 m_modifier.inputMutex.lock();
2026 m_modifier.releaseInModifier();
2027 m_modifier.inputMutex.unlock();
2028 }
2029 return true;
2030}
2031
2032bool PortCore::setParamPortMonitor(const yarp::os::Property& param,
2033 bool isOutput,
2034 std::string& errMsg)
2035{
2036 if (isOutput) {
2037 m_modifier.outputMutex.lock();
2038 if (m_modifier.outputModifier == nullptr) {
2039 errMsg = "No port modifier is attached to the output";
2040 m_modifier.outputMutex.unlock();
2041 return false;
2042 }
2043 m_modifier.outputModifier->setCarrierParams(param);
2044 m_modifier.outputMutex.unlock();
2045 } else {
2046 m_modifier.inputMutex.lock();
2047 if (m_modifier.inputModifier == nullptr) {
2048 errMsg = "No port modifier is attached to the input";
2049 m_modifier.inputMutex.unlock();
2050 return false;
2051 }
2052 m_modifier.inputModifier->setCarrierParams(param);
2053 m_modifier.inputMutex.unlock();
2054 }
2055 return true;
2056}
2057
2058bool PortCore::getParamPortMonitor(yarp::os::Property& param,
2059 bool isOutput,
2060 std::string& errMsg)
2061{
2062 if (isOutput) {
2063 m_modifier.outputMutex.lock();
2064 if (m_modifier.outputModifier == nullptr) {
2065 errMsg = "No port modifier is attached to the output";
2066 m_modifier.outputMutex.unlock();
2067 return false;
2068 }
2069 m_modifier.outputModifier->getCarrierParams(param);
2070 m_modifier.outputMutex.unlock();
2071 } else {
2072 m_modifier.inputMutex.lock();
2073 if (m_modifier.inputModifier == nullptr) {
2074 errMsg = "No port modifier is attached to the input";
2075 m_modifier.inputMutex.unlock();
2076 return false;
2077 }
2078 m_modifier.inputModifier->getCarrierParams(param);
2079 m_modifier.inputMutex.unlock();
2080 }
2081 return true;
2082}
2083
2085{
2086 YARP_UNUSED(active);
2087 if (unit != nullptr) {
2088 bool isLog = (!unit->getMode().empty());
2089 if (isLog) {
2090 m_logNeeded = true;
2091 }
2092 }
2093}
2094
2095bool PortCore::setProcessSchedulingParam(int priority, int policy)
2096{
2097#if defined(__linux__)
2098 // set the sched properties of all threads within the process
2099 struct sched_param sch_param;
2100 sch_param.__sched_priority = priority;
2101
2102 DIR* dir;
2103 char path[PATH_MAX];
2104 sprintf(path, "/proc/%d/task/", yarp::os::impl::getpid());
2105
2106 dir = opendir(path);
2107 if (dir == nullptr) {
2108 return false;
2109 }
2110
2111 struct dirent* d;
2112 char* end;
2113 long tid = 0;
2114 bool ret = true;
2115 while ((d = readdir(dir)) != nullptr) {
2116 if (isdigit(static_cast<unsigned char>(*d->d_name)) == 0) {
2117 continue;
2118 }
2119
2120 tid = strtol(d->d_name, &end, 10);
2121 if (d->d_name == end || ((end != nullptr) && (*end != 0))) {
2122 closedir(dir);
2123 return false;
2124 }
2125 ret &= (sched_setscheduler(static_cast<pid_t>(tid), policy, &sch_param) == 0);
2126 }
2127 closedir(dir);
2128 return ret;
2129#elif defined(YARP_HAS_ACE) // for other platforms
2130 // TODO: Check how to set the scheduling properties of all process's threads in Windows
2131 ACE_Sched_Params param(policy, (ACE_Sched_Priority)priority, ACE_SCOPE_PROCESS);
2132 int ret = ACE_OS::set_scheduling_params(param, yarp::os::impl::getpid());
2133 return (ret != -1);
2134#else
2135 return false;
2136#endif
2137}
2138
2139bool PortCore::removeIO(const Route& route, bool synch)
2140{
2141 return removeUnit(route, synch);
2142}
2143
2144void PortCore::setName(const std::string& name)
2145{
2146 m_name = name;
2147}
2148
2150{
2151 return m_name;
2152}
2153
2154int PortCore::getNextIndex()
2155{
2156 int result = m_counter;
2157 m_counter++;
2158 if (m_counter < 0) {
2159 m_counter = 1;
2160 }
2161 return result;
2162}
2163
2165{
2166 return m_address;
2167}
2168
2169void PortCore::resetPortName(const std::string& str)
2170{
2171 m_address.setName(str);
2172}
2173
2175{
2176 return m_readableCreator;
2177}
2178
2180{
2181 m_controlRegistration = flag;
2182}
2183
2185{
2186 return m_listening.load();
2187}
2188
2190{
2191 return m_manual;
2192}
2193
2195{
2196 return m_interrupted;
2197}
2198
2199void PortCore::setTimeout(float timeout)
2200{
2201 m_timeout = timeout;
2202}
2203
2204bool PortCore::setCallbackLock(std::mutex* mutex)
2205{
2207 if (mutex != nullptr) {
2208 m_mutex = mutex;
2209 m_mutexOwned = false;
2210 } else {
2211 m_mutex = new std::mutex;
2212 m_mutexOwned = true;
2213 }
2214 return true;
2215}
2216
2218{
2219 if (m_mutexOwned && (m_mutex != nullptr)) {
2220 delete m_mutex;
2221 }
2222 m_mutex = nullptr;
2223 m_mutexOwned = false;
2224 return true;
2225}
2226
2228{
2229 if (m_mutex == nullptr) {
2230 return false;
2231 }
2232 m_mutex->lock();
2233 return true;
2234}
2235
2237{
2238 if (m_mutex == nullptr) {
2239 return true;
2240 }
2241 return m_mutex->try_lock();
2242}
2243
2245{
2246 if (m_mutex == nullptr) {
2247 return;
2248 }
2249 m_mutex->unlock();
2250}
2251
2256
2258{
2259 m_typeMutex.lock();
2260 if (!m_checkedType) {
2261 if (!m_type.isValid()) {
2262 m_type = reader.getReadType();
2263 }
2264 m_checkedType = true;
2265 }
2266 m_typeMutex.unlock();
2267}
2268
2270{
2271 m_typeMutex.lock();
2272 Type t = m_type;
2273 m_typeMutex.unlock();
2274 return t;
2275}
2276
2278{
2279 m_typeMutex.lock();
2280 m_type = typ;
2281 m_typeMutex.unlock();
2282}
FeatureMode mode
#define yAssert(x)
Definition Log.h:388
static bool __tcp_check(const Contact &c)
static bool __pc_rpc(const Contact &c, const char *carrier, Bottle &writer, Bottle &reader, bool verbose)
#define PORTCORE_IS_INPUT
Definition PortCore.h:40
#define PORTCORE_SEND_LOG
Definition PortCore.h:35
#define PORTCORE_IS_RPC
Definition PortCore.h:39
#define PORTCORE_IS_OUTPUT
Definition PortCore.h:41
#define PORTCORE_SEND_NORMAL
Definition PortCore.h:34
A simple collection of objects that can be described and transmitted in a portable way.
Definition Bottle.h:64
void addVocab32(yarp::conf::vocab32_t x)
Places a 32 bit vocabulary item in the bottle, at the end of the list.
Definition Bottle.cpp:164
bool read(ConnectionReader &reader) override
Set the bottle's value based on input from a network connection.
Definition Bottle.cpp:241
bool write(ConnectionWriter &writer) const override
Output a representation of the bottle to a network connection.
Definition Bottle.cpp:231
void addString(const char *str)
Places a string in the bottle, at the end of the list.
Definition Bottle.cpp:176
std::string toString() const override
Gives a human-readable textual representation of the bottle.
Definition Bottle.cpp:212
A mini-server for performing network communication in the background.
Type getType() override
Get the type of data the port has committed to send/receive.
std::string getName() const override
Get name of port.
void close() override
Stop port activity.
T * read(bool shouldWait=true) override
Read an available object from the port.
bool addOutput(const std::string &name) override
Add an output connection to the specified port.
void write(bool forceStrict=false)
Write the current object being returned by BufferedPort::prepare.
A base class for connection types (tcp, mcast, shmem, ...) which are called carriers in YARP.
Definition Carrier.h:44
bool isConnectionless() const override=0
Check if this carrier is connectionless (like udp, mcast) or connection based (like tcp).
void getCarrierParams(Property &params) const override
Get carrier configuration and deliver it by port administrative commands.
Definition Carrier.cpp:127
virtual bool configureFromProperty(yarp::os::Property &options)
Definition Carrier.cpp:115
bool isPush() const override
Check if carrier is "push" or "pull" style.
Definition Carrier.cpp:23
bool acceptOutgoingData(const PortWriter &writer) override
Determine whether outgoing data should be accepted.
Definition Carrier.cpp:102
const PortWriter & modifyOutgoingData(const PortWriter &writer) override
Modify outgoing payload data, if appropriate.
Definition Carrier.cpp:77
void setCarrierParams(const Property &params) override
Configure carrier from port administrative commands.
Definition Carrier.cpp:122
static Face * listen(const Contact &address)
Create a "proto-carrier" interface object that waits for incoming connections prior to a carrier bein...
Definition Carriers.cpp:250
static Carrier * getCarrierTemplate(const std::string &name)
Get template for carrier.
Definition Carriers.cpp:238
static Carrier * chooseCarrier(const std::string &name)
Select a carrier by name.
Definition Carriers.cpp:233
static OutputProtocol * connect(const Contact &address)
Initiate a connection to an address.
Definition Carriers.cpp:282
An interface for reading from a network connection.
virtual ConnectionWriter * getWriter()=0
Gets a way to reply to the message, if possible.
An interface for writing to a network connection.
Preferences for how to communicate with a contact.
double timeout
Set a timeout for communication (in units of seconds, fractional seconds allowed).
bool quiet
Suppress all outputs and warnings.
std::string carrier
Request that communication be made using a particular carrier.
Represents how to reach a part of a YARP network.
Definition Contact.h:33
bool isValid() const
Checks if a Contact is tagged as valid.
Definition Contact.cpp:298
std::string getRegName() const
Get the name associated with this Contact.
Definition Contact.cpp:217
std::string toURI(bool includeCarrier=true) const
Get a representation of the Contact as a URI.
Definition Contact.cpp:313
int getPort() const
Get the port number associated with this Contact for socket communication.
Definition Contact.cpp:239
void setName(const std::string &name)
Set the name associated with this Contact.
Definition Contact.cpp:222
void setTimeout(float timeout)
Set timeout for this Contact.
Definition Contact.cpp:282
std::string getCarrier() const
Get the carrier associated with this Contact for socket communication.
Definition Contact.cpp:250
std::string getHost() const
Get the host name associated with this Contact for socket communication.
Definition Contact.cpp:228
A dummy connection to test yarp::os::Portable implementations.
ConnectionWriter & getWriter()
Get the dummy ConnectionWriter loaded with whatever was written the ConnectionWriter since it was las...
ConnectionReader & getReader(ConnectionWriter *replyWriter=nullptr)
Get the dummy ConnectionReader loaded with whatever was written the ConnectionWriter since it was las...
virtual InputProtocol * read()=0
Block and wait for someone to talk to us.
virtual Contact getLocalAddress() const
Get address after open(), if more specific that the address provided to open() - otherwise an invalid...
Definition Face.h:82
virtual OutputProtocol * write(const Contact &address)=0
Try to reach out and talk to someone.
virtual void close()=0
Stop listening.
The input side of an active connection between two ports.
virtual void close()=0
Negotiate an end to operations.
virtual bool setTimeout(double timeout)=0
Set the timeout to be used for network operations.
virtual OutputProtocol & getOutput()=0
Get an interface for doing write operations on the connection.
virtual void attachPort(Contactable *port)=0
Set the port to be associated with the connection.
Simple abstraction for a YARP port name.
Definition Name.h:18
Contact toAddress() const
Create an address from the name.
Definition Name.cpp:27
std::string getCarrierModifier(const char *mod, bool *hasModifier=nullptr)
Definition Name.cpp:44
static bool initialized()
Returns true if YARP has been fully initialized.
Definition Network.cpp:1485
static bool getLocalMode()
Get current value of flag "localMode", see setLocalMode function.
Definition Network.cpp:1142
static Contact unregisterName(const std::string &name)
Removes the registration for a name from the name server.
Definition Network.cpp:1111
static NameStore * getQueryBypass()
Definition Network.cpp:1508
static Contact queryName(const std::string &name)
Find out information about a registered name.
Definition Network.cpp:1083
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:1614
static bool writeToNameServer(PortWriter &cmd, PortReader &reply, const ContactStyle &style)
Variant write method specialized to name server.
Definition Network.cpp:2045
static bool disconnect(const std::string &src, const std::string &dest, bool quiet)
Request that an output port disconnect from an input port.
Definition Network.cpp:802
static bool write(const Contact &contact, PortWriter &cmd, PortReader &reply, bool admin=false, bool quiet=false, double timeout=-1)
Send a single command to a port and await a single response.
Definition Network.cpp:1322
The output side of an active connection between two ports.
virtual OutputStream & getOutputStream()=0
Access the output stream associated with the connection.
virtual Connection & getConnection()=0
Get the connection whose protocol operations we are managing.
virtual bool open(const Route &route)=0
Start negotiating a carrier, using the given route (this should generally match the name of the sendi...
virtual void attachPort(Contactable *port)=0
Set the port to be associated with the connection.
virtual InputProtocol & getInput()=0
Get an interface for doing read operations on the connection.
virtual void close()=0
Negotiate an end to operations.
virtual void rename(const Route &route)=0
Relabel the route after the fact (e.g.
virtual bool setTimeout(double timeout)=0
Set the timeout to be used for network operations.
Simple specification of the minimum functions needed from output streams.
Administrative commands of a YARP port, handled by PortCore::adminBlock().
Information about a port connection or event.
Definition PortInfo.h:25
std::string message
A human-readable description of contents.
Definition PortInfo.h:68
int tag
Type of information.
Definition PortInfo.h:47
@ PORTINFO_CONNECTION
Information about an incoming or outgoing connection.
Definition PortInfo.h:39
@ PORTINFO_MISC
Unspecified information.
Definition PortInfo.h:42
A creator for readers.
Interface implemented by all objects that can read themselves from the network, such as Bottle object...
Definition PortReader.h:24
virtual bool read(ConnectionReader &reader)=0
Read this object from a network connection.
virtual Type getReadType() const
A base class for objects that want information about port status changes.
Definition PortReport.h:25
virtual void report(const PortInfo &info)=0
Callback for port event/state information.
Interface implemented by all objects that can write themselves to the network, such as Bottle objects...
Definition PortWriter.h:23
virtual bool write(ConnectionWriter &writer) const =0
Write this object to a network connection.
virtual void onCommencement() const
This is called when the port is about to begin writing operations.
Holds the operating system process information.
A class for storing options and configuration information.
Definition Property.h:32
void fromString(const std::string &txt, bool wipe=true)
Interprets a string as a list of properties.
void put(const std::string &key, const std::string &value)
Associate the given key with the given string.
Definition Property.cpp:980
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 swapNames()
Swap from and to names.
Definition Route.cpp:133
void setToContact(const Contact &toContact)
Set the destination contact of the route.
Definition Route.cpp:118
An InputStream that reads from a string.
void add(const std::string &txt)
An OutputStream that produces a string.
static ProcessInfo getProcessInfo(int pid=0)
gets the operating system process information given by its PID.
static PlatformInfo getPlatformInfo()
getPlatformInfo
bool isValid() const
Definition Type.cpp:154
std::string getName() const
Definition Type.cpp:139
A helper for creating cached object descriptions.
void restart()
Tell the writer that we will be serializing a new object, but to keep any cached buffers that already...
A helper for recording entire message/reply transactions.
Manager for a single input to a port.
Manager for a single output from a port.
A single message, potentially being transmitted on multiple connections.
PortCorePacket * getFreePacket()
Get a packet that we can prepare for sending.
bool checkPacket(PortCorePacket *packet)
Move a packet to the inactive state if it has finished being sent on all connections.
This manages a single threaded resource related to a single input or output connection.
void notifyCompletion(void *tracker)
Call the right onCompletion() after sending message.
void resetPortName(const std::string &str)
std::string getEnvelope()
void setAdminReadHandler(yarp::os::PortReader &reader)
Set a callback for incoming administrative messages.
Definition PortCore.cpp:151
int getOutputCount()
Check how many output connections there are.
bool readBlock(ConnectionReader &reader, void *id, yarp::os::OutputStream *os)
Read a block of regular payload data.
void setReportCallback(yarp::os::PortReport *reporter)
Set a callback to be notified of changes in port status.
void run() override
The body of the main thread.
Definition PortCore.cpp:168
bool start() override
Begin main thread.
Definition PortCore.cpp:276
void checkType(PortReader &reader)
void resume()
Undo an interrupt()
Definition PortCore.cpp:324
void setTimeout(float timeout)
yarp::os::PortReaderCreator * getReadCreator()
Get the creator of callbacks.
void interrupt()
Prepare the port to be shut down.
Definition PortCore.cpp:330
bool removeInput(const std::string &src, void *id, yarp::os::OutputStream *os)
Remove an input connection.
bool setCallbackLock(std::mutex *mutex=nullptr)
void setEnvelope(const std::string &envelope)
Set some envelope information to pass along with a message without actually being part of the message...
bool removeIO(const Route &route, bool synch=false)
Remove any connection matching the supplied route.
void report(const yarp::os::PortInfo &info)
Handle a port event (connection, disconnection, etc) Generate a description of the connections associ...
bool listen(const Contact &address, bool shouldAnnounce=true)
Begin service at a given address.
Definition PortCore.cpp:71
bool sendHelper(const yarp::os::PortWriter &writer, int mode, yarp::os::PortReader *reader=nullptr, const yarp::os::PortWriter *callback=nullptr)
Send a message with a specific mode (normal or log).
void setControlRegistration(bool flag)
Normally the port will unregister its name with the name server when shutting down.
int getInputCount()
Check how many input connections there are.
bool manualStart(const char *sourceName)
Start up the port, but without a main thread.
Definition PortCore.cpp:307
void setReadHandler(yarp::os::PortReader &reader)
Set a callback for incoming data.
Definition PortCore.cpp:143
void reportUnit(PortCoreUnit *unit, bool active)
Called by a connection handler with active=true just after it is fully configured,...
bool removeOutput(const std::string &dest, void *id, yarp::os::OutputStream *os)
Remove an output connection.
void promiseType(const Type &typ)
int getEventCount()
A diagnostic for testing purposes.
Definition PortCore.cpp:531
void close() override
Shut down port.
Definition PortCore.cpp:267
const Contact & getAddress() const
Get the address associated with the port.
void describe(void *id, yarp::os::OutputStream *os)
Produce a text description of the port and its connections.
yarp::os::Type getType()
bool isWriting()
Check if a message is currently being sent.
bool adminBlock(ConnectionReader &reader, void *id)
Read a block of administrative data.
unsigned int getFlags()
Check current configuration of port.
Definition PortCore.h:300
bool send(const yarp::os::PortWriter &writer, yarp::os::PortReader *reader=nullptr, const yarp::os::PortWriter *callback=nullptr)
Send a normal message.
void resetReportCallback()
Reset the callback to be notified of changes in port status.
void setReadCreator(yarp::os::PortReaderCreator &creator)
Set a callback for creating callbacks for incoming data.
Definition PortCore.cpp:159
yarp::os::impl::PortDataModifier & getPortModifier()
void setName(const std::string &name)
Set the name of this port.
bool addOutput(const std::string &dest, void *id, yarp::os::OutputStream *os, bool onlyIfNeeded=false)
Add an output connection to this port.
Definition PortCore.cpp:841
This is the heart of a yarp port.
Definition PortCore.h:102
yarp::os::Carrier * outputModifier
Definition PortCore.h:135
yarp::os::Carrier * inputModifier
Definition PortCore.h:136
Lets Readable objects read from the underlying InputStream associated with the connection between two...
int join(double seconds=-1)
Reply of PortCoreMsgs::addConnection().
Reply of PortCoreMsgs::delConnection().
Reply of PortCoreMsgs::getAdminProtocolVersion().
Reply of PortCoreMsgs::getConnectionInfoIn() and PortCoreMsgs::getConnectionInfoOut().
Reply of PortCoreMsgs::getConnectionParamsIn() and PortCoreMsgs::getConnectionParamsOut().
Reply of PortCoreMsgs::getConnectionQosIn() and PortCoreMsgs::getConnectionQosOut().
Reply of PortCoreMsgs::getPortInfo().
yarp::os::ProcessInfoData process
yarp::os::ThreadInfoData thread
yarp::os::PortInfoData port
yarp::os::PlatformInfoData platform
Reply of PortCoreMsgs::getPortmonitorParamsIn() and PortCoreMsgs::getPortmonitorParamsOut().
Reply of PortCoreMsgs::listConnectionsIn() and PortCoreMsgs::listConnectionsOut().
std::vector< std::string > connections
Reply of PortCoreMsgs::setConnectionParamsIn() and PortCoreMsgs::setConnectionParamsOut().
Reply of PortCoreMsgs::setConnectionQosIn() and PortCoreMsgs::setConnectionQosOut().
Reply of PortCoreMsgs::setPortmonitorParamsIn() and PortCoreMsgs::setPortmonitorParamsOut().
#define yCIAssert(component, id, x)
#define yCWarning(component,...)
#define yCIError(component, id,...)
#define yCITrace(component, id,...)
#define yCIDebug(component, id,...)
#define yCIWarning(component, id,...)
#define YARP_OS_LOG_COMPONENT(name, name_string)
std::string to_string(IntegerType x)
Definition numeric.h:116
The components from which ports and connections are built.
An interface to the operating system, including Port based communication.
The main, catch-all namespace for YARP.
Definition dirs.h:16
#define YARP_UNUSED(var)
Definition api.h:162