YARP
Yet Another Robot Platform
 
Loading...
Searching...
No Matches
clusterWidget.cpp
Go to the documentation of this file.
1/*
2 * SPDX-FileCopyrightText: 2006-2021 Istituto Italiano di Tecnologia (IIT)
3 * SPDX-License-Identifier: LGPL-2.1-or-later
4 */
5
6#include "clusterWidget.h"
7#include "ui_clusterWidget.h"
8#include "iostream"
9#include <QLineEdit>
10#include <QCheckBox>
11#include <QBrush>
12#include <QGroupBox>
13#include <QHeaderView>
14#include <QLabel>
15#include <QPushButton>
16#include <QRadioButton>
17#include <QTreeWidget>
18#include <QVBoxLayout>
19#include <QStringList>
20
21#include <yarp/os/LogStream.h>
22#include <yarp/os/Time.h>
23
26
27#include <algorithm>
28#include <array>
29#include <cstdio>
30#include <cctype>
31#include <set>
32#include <sstream>
33
34#include <mainwindow.h>
35
36// The MSVC CRT provides popen/pclose only with a leading underscore
37#if defined(_MSC_VER)
38# define popen _popen
39# define pclose _pclose
40#endif
41
42using namespace yarp::os;
43using namespace yarp::manager;
44
45namespace {
46// To create a shell-quoted string
47std::string shellQuote(const std::string& value)
48{
49 std::string quoted = "'";
50 for (char c : value)
51 {
52 if (c == '\'')
53 {
54 quoted += "'\\''";
55 }
56 else
57 {
58 quoted += c;
59 }
60 }
61 quoted += "'";
62 return quoted;
63}
64// To divide rows separated by Tabs
65std::vector<std::string> splitTabs(const std::string& line)
66{
67 std::vector<std::string> fields;
68 std::stringstream stream(line);
69 std::string field;
70 while (std::getline(stream, field, '\t'))
71 {
72 fields.push_back(field);
73 }
74 return fields;
75}
76
77std::string sanitizedFilePart(std::string value)
78{
79 for (char& c : value)
80 {
81 if (!std::isalnum(static_cast<unsigned char>(c)))
82 {
83 c = '_';
84 }
85 }
86 return value;
87}
88
89std::string yarprunLogFile(const std::string& portName)
90{
91 return "/tmp/yarpmanager_yarprun_" + sanitizedFilePart(portName) + ".log";
92}
93
94std::string runtimeName(const yarp::manager::ClusterNode& node)
95{
96 if (!node.docker.empty()) {
97 return "docker";
98 }
99 if (!node.conda.empty()) {
100 return "conda";
101 }
102 if (!node.pixi.empty()) {
103 return "pixi";
104 }
105 return "";
106}
107
108std::string runtimeTarget(const yarp::manager::ClusterNode& node)
109{
110 if (!node.docker.empty()) {
111 return node.docker;
112 }
113 if (!node.conda.empty()) {
114 return node.conda;
115 }
116 if (!node.pixi.empty()) {
117 return node.pixi;
118 }
119 return "";
120}
121
123{
124 return (!node.docker.empty() ? 1 : 0) +
125 (!node.conda.empty() ? 1 : 0) +
126 (!node.pixi.empty() ? 1 : 0);
127}
128
129} // namespace
130
132 QWidget(parent),
133 ui(new Ui::ClusterWidget),
134 confFile(""),
135 clusLoader(nullptr),
136 checkNs(false),
137 dockerGroupBox(nullptr),
138 dockerTreeWidget(nullptr),
139 dockerRefreshBtn(nullptr),
140 dockerStartBtn(nullptr),
141 dockerStopBtn(nullptr)
142{
143
144#ifdef WIN32
145 this->setDisabled(true);
146 return;
147#endif
148 ui->setupUi(this);
149 ui->nodestreeWidget->setColumnCount(8);
150 ui->nodestreeWidget->setHeaderLabels(QStringList() << "Status" << "Name" << "Display" << "User" << "Address" << "Runtime" << "Target" << "Log");
151 ui->executeBtn->setDisabled(true);
152 ui->labelNs->setPixmap(QPixmap(":/close.svg").scaledToHeight(ui->checkRos->height()));
153 addDockerControls();
154
155 //Connections to slots
156
157 //nameserver
158 connect(ui->checkServerBtn, SIGNAL(clicked(bool)), this, SLOT(onCheckServer()));
159 connect(ui->runServerBtn, SIGNAL(clicked(bool)), this, SLOT(onRunServer()));
160 connect(ui->stopServerBtn, SIGNAL(clicked(bool)), this, SLOT(onStopServer()));
161 //yarprun
162 connect(ui->checkAllBtn, SIGNAL(clicked(bool)), this, SLOT(onCheckAll()));
163 connect(ui->runSelBtn, SIGNAL(clicked(bool)), this, SLOT(onRunSelected()));
164 connect(ui->stopSelBtn, SIGNAL(clicked(bool)), this, SLOT(onStopSelected()));
165 connect(ui->killSelBtn, SIGNAL(clicked(bool)), this, SLOT(onKillSelected()));
166 //execute
167 connect(ui->executeBtn, SIGNAL(clicked(bool)), this, SLOT(onExecute()));
168
169 connect(ui->nodestreeWidget, SIGNAL(itemSelectionChanged()), this, SLOT(onNodeSelectionChanged()));
170 connect(ui->nodestreeWidget, &QTreeWidget::itemChanged, this, [this](QTreeWidgetItem*, int column) {
171 if (column == 5) {
172 updateYarprunDockerColors();
173 }
174 });
175 connect(ui->lineEditExecute, SIGNAL(textChanged(QString)), SLOT(onExecuteTextChanged()));
176 connect(dockerTreeWidget, SIGNAL(itemSelectionChanged()), this, SLOT(updateDockerButtons()));
177
178}
179
181{
182 confFile = _confFile;
183}
184
186{
187 clusLoader = new XmlClusterLoader(confFile);
188 if (clusLoader)
189 {
190 if (!clusLoader->parseXmlFile(cluster))
191 {
192 yError()<<"ClusterWidget:Unable parse cluster-config.xml in context iCubCluster";
193 this->setDisabled(true);
194 return;
195 }
196 }
197
198 ui->lineEditUser->setText(cluster.user.c_str());
199 ui->lineEditNs->setText(cluster.nameSpace.c_str());
200
201 //check if yarpserver is running
202
203 onCheckServer();
204
206 //Adding nodes
207
208 l.push_back(cluster.nsNode.c_str());
209 int i{0};
210 for (auto& node:cluster.nodes)
211 {
212 addRow(node.name, node.displayValue, node.user, node.address, runtimeName(node), runtimeTarget(node), node.onOff, node.log, i);
213 i++;
214 if (cluster.nsNode == node.name) {
215 continue;
216 }
217 l.push_back(node.name.c_str());
218 }
219
220 // populate the execute combo box
221 ui->executeComboBox->addItems(l);
222 ui->executeComboBox->setEditable(true);
223
224 ui->nsNodeComboBox->addItems(l);
225 ui->nsNodeComboBox->setEditable(true);
226
227 onRefreshDockerContainers();
228
229 //check if all the nodes are up
230 if (checkNs)
231 {
232 onCheckAll();
233 }
234
235 ui->nodestreeWidget->header()->resizeSection(0, 50);
236
237 onNodeSelectionChanged();
238
239}
240
241void ClusterWidget::onCheckAll()
242{
243 for (int i = 0; i<ui->nodestreeWidget->topLevelItemCount(); i++)
244 {
245 QTreeWidgetItem *it = ui->nodestreeWidget->topLevelItem(i);
246 int itr = getNodeIndex(it);
247 ClusterNode node = cluster.nodes[itr];
248 if (checkNode(node.name))
249 {
250 cluster.nodes[itr].onOff=true;
251 it->setIcon(0, QIcon(":/computer-available22.svg"));
252 }
253 else
254 {
255 cluster.nodes[itr].onOff=false;
256 it->setIcon(0, QIcon(":/computer-unavailable22.svg"));
257 }
258 }
259 updateYarprunDockerColors();
260
261}
262
263void ClusterWidget::onCheckServer()
264{
265 checkNs = checkNameserver();
266 if (checkNs) {
267 ui->labelNs->setPixmap(QPixmap(":/apply.svg").scaledToHeight(ui->checkRos->height()));
268 }
269 else {
270 ui->labelNs->setPixmap(QPixmap(":/close.svg").scaledToHeight(ui->checkRos->height()));
271 }
272
273 ui->checkRos->setDisabled(checkNs);
274 ui->runServerBtn->setDisabled(checkNs);
275 ui->nsNodeComboBox->setDisabled(checkNs);
276 ui->stopServerBtn->setDisabled(!checkNs);
277}
278
279void ClusterWidget::onRunServer()
280{
281 updateServerEntries();
282
284 std::string cmdRunServer = getSSHCmd(cluster.user, cluster.nsNode, cluster.ssh_options);
285 if (ui->checkRos->isChecked())
286 {
287 cmdRunServer = cmdRunServer + " yarpserver --portdb :memory: --subdb :memory: --ros >/dev/null 2>&1 &";
288 }
289 else
290 {
291 cmdRunServer = cmdRunServer + " yarpserver --portdb :memory: --subdb :memory: >/dev/null 2>&1 &";
292 }
293 if (system(cmdRunServer.c_str()) != 0)
294 {
295 std::string err = "ClusterWidget: failed to run the server on " + cluster.nsNode;
296 logger->addError(err);
297 reportErrors();
298 }
299 else
300 {
302 onCheckServer();
303 }
304}
305
306void ClusterWidget::onStopServer()
307{
308 updateServerEntries();
309
310 auto count = std::count_if(cluster.nodes.begin(), cluster.nodes.end(),
311 [](const ClusterNode& e){ return e.onOff; });
312
313 if (count > 0) {
314
315 auto reply = QMessageBox::warning(this, "Shutting down yarpserver",
316 "You have some yarprun on execution."
317 " After shutting down yarpserver you might not be able to recover them."
318 " Are you sure?",
319 QMessageBox::Yes|QMessageBox::No);
320 if (reply== QMessageBox::No) {
321 return;
322 }
323 }
324
325 std::string cmdStopServer = getSSHCmd(cluster.user, cluster.nsNode, cluster.ssh_options);
326
327 cmdStopServer = cmdStopServer + " killall yarpserver &";
328
330
331 if (system(cmdStopServer.c_str()) != 0)
332 {
333 std::string err = "ClusterWidget: failed to stop the server on " + cluster.nsNode;
334 logger->addError(err);
335 reportErrors();
336 }
337 else
338 {
340 onCheckServer();
341 }
342
343 // if it fails to stop, kill it
344 if (checkNs)
345 {
346 onKillServer();
347 }
348 else
349 {
350 std::string info = "ClusterWidget: yarpserver successfully stopped on "+ cluster.nsNode;
351 logMessage(QString(info.c_str()));
352 }
353}
354
355void ClusterWidget::onKillServer()
356{
357 updateServerEntries();
358
359 std::string cmdKillServer = getSSHCmd(cluster.user, cluster.nsNode, cluster.ssh_options);
360
361 cmdKillServer = cmdKillServer + " killall -9 yarpserver &";
362
364 if (system(cmdKillServer.c_str()) != 0)
365 {
366 std::string err = "ClusterWidget: failed to kill the server on " + cluster.nsNode;
367 logger->addError(err);
368 reportErrors();
369 }
370 else
371 {
372 std::string info = "ClusterWidget: yarpserver successfully killed on "+ cluster.nsNode;
373 logMessage(QString(info.c_str()));
374 }
375
376
377}
378
379void ClusterWidget::onRunSelected()
380{
381 QList<QTreeWidgetItem*> selectedItems = ui->nodestreeWidget->selectedItems();
382 foreach (QTreeWidgetItem *it, selectedItems)
383 {
384 int itr = getNodeIndex(it);
385 ClusterNode node = cluster.nodes[itr];
386 node.docker.clear();
387 node.conda.clear();
388 node.pixi.clear();
389
390 std::string runtime = it->text(5).trimmed().toStdString();
391 std::string target = it->text(6).trimmed().toStdString();
392
393 if (runtime == "docker") {
394 node.docker = target;
395 } else if (runtime == "conda") {
396 node.conda = target;
397 } else if (runtime == "pixi") {
398 node.pixi = target;
399 }
400 std::string portName = node.name;
401
402 if (portName.find('/') == std::string::npos)
403 {
404 portName.insert(0, 1, '/');
405 }
406
407 if (node.onOff)
408 {
409 continue;
410 }
411
413
414 if (runtimeCount(node) > 1)
415 {
416 logger->addError("ClusterWidget: only one runtime can be specified among docker, conda and pixi.");
417 reportErrors();
418 continue;
419 }
420
421 if (!node.docker.empty() && !isDockerRunning(node, node.docker))
422 {
423 logger->addError("ClusterWidget: cannot run yarprun inside docker " + node.docker +
424 " because the container is not running. Please start the docker container first.");
425 reportErrors();
426 continue;
427 }
428
429 if (!node.pixi.empty() && !checkPixiRuntime(node))
430 {
431 reportErrors();
432 continue;
433 }
434
435 std::string cmdRunYarprun = getSSHCmd(node.user, node.address, node.ssh_options);
436 bool log = qobject_cast<QCheckBox*>(ui->nodestreeWidget->itemWidget((QTreeWidgetItem *)it, 7))->isChecked();
437 std::string logFile = yarprunLogFile(portName);
438 std::string cleanupOutput;
439 runRemoteCommand(node, "rm -f " + shellQuote(logFile), cleanupOutput);
440
441 cmdRunYarprun.append(" ").append(shellQuote(buildYarprunCommand(node, portName, log, logFile)));
442 if (system(cmdRunYarprun.c_str()) != 0)
443 {
444 std::string err = "ClusterWidget: failed to run yarprun on " + node.name;
445 logger->addError(err);
446 reportErrors();
447 }
448 else
449 {
451 if (!checkNode(node.name))
452 {
453 std::string tailOutput;
454 runRemoteCommand(node, "test -f " + shellQuote(logFile) + " && tail -n 80 " + shellQuote(logFile), tailOutput);
455 logger->addError("ClusterWidget: yarprun did not start on " + node.name + ". Remote log " + logFile + ":\n" + tailOutput);
456 reportErrors();
457 continue;
458 }
459
460 std::string info = "ClusterWidget: yarprun successfully executed on " + node.name + ". Remote log: " + logFile;
461 logMessage(QString(info.c_str()));
462 }
463 }
464
466 onCheckAll();
467}
468
469
470void ClusterWidget::onStopSelected()
471{
472 QList<QTreeWidgetItem*> selectedItems = ui->nodestreeWidget->selectedItems();
473 foreach (QTreeWidgetItem *it, selectedItems)
474 {
475 int itr = getNodeIndex(it);
476 ClusterNode node = cluster.nodes[itr];
477 if (!node.onOff)
478 {
479 continue;
480 }
481 std::string portName = node.name;
482 if (portName.find('/') == std::string::npos)
483 {
484 portName.insert(0, 1, '/');
485 }
486
487 std::string cmdStopYarprun = getSSHCmd(node.user, node.address, node.ssh_options);
488
489 cmdStopYarprun.append(" yarprun --exit --on ").append(portName).append(" &");
490
492 if (system(cmdStopYarprun.c_str()) != 0)
493 {
494 std::string err = "ClusterWidget: failed to stop yarprun on " + node.name;
495 logger->addError(err);
496 reportErrors();
497 }
498 else
499 {
500 std::string info = "ClusterWidget: yarprun successfully stopped on "+ node.name;
501 logMessage(QString(info.c_str()));
502 }
503 }
504
506 onCheckAll();
507}
508
509void ClusterWidget::onKillSelected()
510{
511 QList<QTreeWidgetItem*> selectedItems = ui->nodestreeWidget->selectedItems();
512 foreach (QTreeWidgetItem *it, selectedItems)
513 {
514 int itr = getNodeIndex(it);
515 ClusterNode node = cluster.nodes[itr];
516 if (!node.onOff)
517 {
518 continue;
519 }
520
521 std::string cmdKillYarprun = getSSHCmd(node.user, node.address, node.ssh_options);
522
523 cmdKillYarprun.append(" killall -9 yarprun &");
524
526 if (system(cmdKillYarprun.c_str()) != 0)
527 {
528 std::string err = "ClusterWidget: failed to kill yarprun on " + node.name;
529 logger->addError(err);
530 reportErrors();
531 }
532 else
533 {
534 std::string info = "ClusterWidget: yarprun successfully killed on "+ node.name;
535 logMessage(QString(info.c_str()));
536 }
537 }
539 onCheckAll();
540}
541
542void ClusterWidget::onExecute()
543{
544 if (ui->lineEditExecute->text().trimmed().size() == 0)
545 {
546 return;
547 }
548
549 auto nodeName = ui->executeComboBox->currentText();
550
551 if (nodeName.trimmed().size() == 0)
552 {
553 return;
554 }
555
556 auto nodeItr = std::find_if(cluster.nodes.begin(), cluster.nodes.end(),
557 [&nodeName](const ClusterNode& n){ return n.name == nodeName.toStdString(); });
558
559
560 if (nodeItr == cluster.nodes.end())
561 {
562 return;
563 }
564
565 auto node = *nodeItr;
566 auto command = ui->lineEditExecute->text().toStdString();
567
568 std::string cmdExecute = getSSHCmd(node.user, node.address, node.ssh_options);
569
570 cmdExecute.append(" ").append(command);
571
573 if (system(cmdExecute.c_str()) != 0)
574 {
575 std::string err = "ClusterWidget: failed to run "+ command + " on " + node.name;
576 logger->addError(err);
577 reportErrors();
578 }
579 else
580 {
581 std::string info = "ClusterWidget: command "+ command + " successfully executed on " + node.name;
582 logMessage(QString(info.c_str()));
583 }
584
585 ui->lineEditExecute->clear();
586}
587
588void ClusterWidget::onNodeSelectionChanged()
589{
590 if(ui->nodestreeWidget->selectedItems().isEmpty())
591 {
592 ui->runSelBtn->setDisabled(true);
593 ui->stopSelBtn->setDisabled(true);
594 ui->killSelBtn->setDisabled(true);
595 }
596 else
597 {
598 ui->runSelBtn->setDisabled(!checkNs);
599 ui->stopSelBtn->setDisabled(!checkNs);
600 ui->killSelBtn->setDisabled(!checkNs);
601 }
602}
603
604
605void ClusterWidget::onExecuteTextChanged()
606{
607 if (ui->lineEditExecute->text().trimmed().size() > 0) {
608 ui->executeBtn->setDisabled(false);
609 } else {
610 ui->executeBtn->setDisabled(true);
611 }
612}
613
614
615
616void ClusterWidget::addRow(const std::string& name,const std::string& display,
617 const std::string& user, const std::string& address,
618 const std::string& runtime, const std::string& target, bool onOff, bool log, int id)
619{
621 stringList << "" << QString(name.c_str()) << QString(display.c_str()) << QString(user.c_str()) << QString(address.c_str()) << QString(runtime.c_str()) << QString(target.c_str()) << "";
622 auto* it = new QTreeWidgetItem(stringList);
623 it->setData(0, Qt::UserRole, id);
624 it->setFlags(it->flags() | Qt::ItemIsEditable);
625 ui->nodestreeWidget->addTopLevelItem(it);
626 ui->nodestreeWidget->setItemWidget((QTreeWidgetItem *) it, 7, new QCheckBox(this));
627
628 //initialize checkboxes
629 qobject_cast<QCheckBox*>(ui->nodestreeWidget->itemWidget((QTreeWidgetItem *)it, 7))->setChecked(log);
630
631 //initialize icon
632 if (onOff)
633 {
634 it->setIcon(0, QIcon(":/computer-available22.svg"));
635 }
636 else
637 {
638 it->setIcon(0, QIcon(":/computer-unavailable22.svg"));
639 }
640
641}
642
643int ClusterWidget::getNodeIndex(QTreeWidgetItem* item) const
644{
645 return item->data(0, Qt::UserRole).toInt();
646}
647
648std::string ClusterWidget::buildYarprunCommand(const yarp::manager::ClusterNode& node, const std::string& portName, bool log, const std::string& logFile)
649{
650 std::string yarprunCommand;
651 if (node.display)
652 {
653 yarprunCommand.append("export DISPLAY=").append(node.displayValue).append(" && ");
654 }
655
656 yarprunCommand.append("yarprun --server ").append(portName);
657 if (log)
658 {
659 yarprunCommand.append(" --log");
660 }
661
662 if (!node.docker.empty())
663 {
664 return "docker exec " + shellQuote(node.docker) +
665 " sh -lc " + shellQuote(yarprunCommand) +
666 " > " + shellQuote(logFile) + " 2>&1";
667 }
668
669 if (!node.conda.empty())
670 {
671 return "bash -lc " + shellQuote(
672 "for conda_sh in "
673 "\"$HOME/miniforge3/etc/profile.d/conda.sh\" "
674 "\"$HOME/miniconda3/etc/profile.d/conda.sh\" "
675 "\"$HOME/anaconda3/etc/profile.d/conda.sh\" "
676 "\"/opt/conda/etc/profile.d/conda.sh\"; do "
677 "[ -f \"$conda_sh\" ] && source \"$conda_sh\" && break; "
678 "done; "
679 "if ! command -v conda >/dev/null 2>&1; then "
680 "echo \"conda command not found. Please install conda or add conda.sh to one of the standard locations.\" >&2; "
681 "exit 1; "
682 "fi; "
683 "conda activate " + shellQuote(node.conda) + " && " +
685 " > " + shellQuote(logFile) + " 2>&1";
686 }
687
688 if (!node.pixi.empty())
689 {
690 return "bash -lc " + shellQuote(
691 "export PATH=\"$HOME/.pixi/bin:$HOME/.cargo/bin:$PATH\" && "
692 "cd " + shellQuote(node.pixi) + " && "
693 "pixi run " + yarprunCommand) +
694 " > " + shellQuote(logFile) + " 2>&1";
695 }
696
697 return yarprunCommand + " > " + shellQuote(logFile) + " 2>&1";
698}
699
700bool ClusterWidget::runRemoteCommand(const yarp::manager::ClusterNode& node, const std::string& command, std::string& output)
701{
702 output.clear();
703 std::string cmd = getSSHCmd(node.user, node.address, node.ssh_options, false);
704 cmd += " ";
705 cmd += shellQuote(command);
706 cmd += " 2>&1";
707
708 std::array<char, 512> buffer{};
709 FILE* pipe = popen(cmd.c_str(), "r");
710 if (!pipe)
711 {
712 output = "unable to execute ssh command";
713 return false;
714 }
715
716 while (fgets(buffer.data(), buffer.size(), pipe) != nullptr)
717 {
718 output += buffer.data();
719 }
720
721 return pclose(pipe) == 0;
722}
723
724bool ClusterWidget::checkPixiRuntime(const yarp::manager::ClusterNode& node)
725{
726 std::string output;
727 std::string script =
728 "bash -lc " + shellQuote(
729 "export PATH=\"$HOME/.pixi/bin:$HOME/.cargo/bin:$PATH\"; "
730 "if [ ! -d " + shellQuote(node.pixi) + " ]; then "
731 "echo \"pixi project directory not found: " + node.pixi + "\"; exit 1; "
732 "fi; "
733 "if [ ! -f " + shellQuote(node.pixi + "/pixi.toml") + " ]; then "
734 "echo \"pixi.toml not found in: " + node.pixi + "\"; exit 1; "
735 "fi; "
736 "if ! command -v pixi >/dev/null 2>&1; then "
737 "echo \"pixi command not found. Install pixi or add it to PATH on host " + node.address + ".\"; exit 1; "
738 "fi; "
739 "cd " + shellQuote(node.pixi) + " && pixi info >/dev/null");
740
741 if (!runRemoteCommand(node, script, output))
742 {
743 yarp::manager::ErrorLogger::Instance()->addError("Pixi: cannot run yarprun on " + node.name + ": " + output);
744 return false;
745 }
746
747 return true;
748}
749
750bool ClusterWidget::isDockerRunning(const yarp::manager::ClusterNode& node, const std::string& dockerName)
751{
752 if (dockerName.empty())
753 {
754 return false;
755 }
756
757 std::string cmd = getSSHCmd(node.user, node.address, node.ssh_options, false);
758 cmd += " ";
759 cmd += shellQuote("docker ps --format '{{.Names}}'");
760 cmd += " 2>&1";
761
762 std::array<char, 512> buffer{};
763 FILE* pipe = popen(cmd.c_str(), "r");
764 if (!pipe)
765 {
766 yarp::manager::ErrorLogger::Instance()->addError("Docker: unable to execute docker ps on " + node.name);
767 return false;
768 }
769
770 std::string output;
771 while (fgets(buffer.data(), buffer.size(), pipe) != nullptr)
772 {
773 output += buffer.data();
774 }
775
776 int ret = pclose(pipe);
777 if (ret != 0)
778 {
779 yarp::manager::ErrorLogger::Instance()->addError("Docker: docker ps failed on " + node.name + ": " + output);
780 return false;
781 }
782
783 std::stringstream lines(output);
784 std::string line;
785 while (std::getline(lines, line))
786 {
787 if (line == dockerName)
788 {
789 return true;
790 }
791 }
792
793 return false;
794}
795
796void ClusterWidget::updateYarprunDockerColors()
797{
798 for (int i = 0; i < ui->nodestreeWidget->topLevelItemCount(); i++)
799 {
800 auto* item = ui->nodestreeWidget->topLevelItem(i);
801 int nodeIndex = getNodeIndex(item);
802 if (nodeIndex < 0 || static_cast<size_t>(nodeIndex) >= cluster.nodes.size())
803 {
804 continue;
805 }
806
807 std::string runtime = item->text(5).trimmed().toStdString();
808 std::string target = item->text(6).trimmed().toStdString();
809
810 bool green = false;
811 if (runtime == "docker" && !target.empty())
812 {
813 green = isDockerRunning(cluster.nodes[nodeIndex], target);
814 }
815
816 item->setForeground(6, green ? QBrush(Qt::darkGreen) : QBrush(Qt::black));
817 }
818}
819
820// Create the docker box
821void ClusterWidget::addDockerControls()
822{
823 dockerGroupBox = new QGroupBox("Docker containers", this);
824 auto* dockerLayout = new QVBoxLayout(dockerGroupBox);
825 auto* buttonsLayout = new QHBoxLayout();
826
827 dockerRefreshBtn = new QPushButton("Refresh", dockerGroupBox);
828 dockerStartBtn = new QPushButton("Start", dockerGroupBox);
829 dockerStopBtn = new QPushButton("Stop", dockerGroupBox);
830 dockerStartBtn->setDisabled(true);
831 dockerStopBtn->setDisabled(true);
832
833 buttonsLayout->addWidget(dockerRefreshBtn);
834 buttonsLayout->addWidget(dockerStartBtn);
835 buttonsLayout->addWidget(dockerStopBtn);
836
837 dockerTreeWidget = new QTreeWidget(dockerGroupBox);
838 dockerTreeWidget->setColumnCount(7);
839 dockerTreeWidget->setHeaderLabels(QStringList() << "Host" << "Container" << "Status" << "ID" << "Address" << "User" << "SSH options");
840 dockerTreeWidget->setSelectionMode(QAbstractItemView::ExtendedSelection);
841 dockerTreeWidget->setRootIsDecorated(false);
842 dockerTreeWidget->setAlternatingRowColors(true);
843 dockerTreeWidget->setColumnHidden(4, true);
844 dockerTreeWidget->setColumnHidden(5, true);
845 dockerTreeWidget->setColumnHidden(6, true);
846 dockerTreeWidget->header()->setStretchLastSection(false);
847 dockerTreeWidget->header()->setSectionResizeMode(0, QHeaderView::ResizeToContents);
848 dockerTreeWidget->header()->setSectionResizeMode(1, QHeaderView::ResizeToContents);
849 dockerTreeWidget->header()->setSectionResizeMode(2, QHeaderView::Stretch);
850 dockerTreeWidget->header()->setSectionResizeMode(3, QHeaderView::ResizeToContents);
851
852 dockerLayout->addLayout(buttonsLayout);
853 dockerLayout->addWidget(dockerTreeWidget);
854 ui->verticalLayout_5->addWidget(dockerGroupBox);
855
856 connect(dockerRefreshBtn, SIGNAL(clicked(bool)), this, SLOT(onRefreshDockerContainers()));
857 connect(dockerStartBtn, SIGNAL(clicked(bool)), this, SLOT(onStartSelectedDockerContainers()));
858 connect(dockerStopBtn, SIGNAL(clicked(bool)), this, SLOT(onStopSelectedDockerContainers()));
859}
860
861void ClusterWidget::updateDockerButtons()
862{
863 const bool hasSelection = dockerTreeWidget && !dockerTreeWidget->selectedItems().isEmpty();
864 dockerStartBtn->setDisabled(!hasSelection);
865 dockerStopBtn->setDisabled(!hasSelection);
866}
867
868std::vector<yarp::manager::DockerContainer> ClusterWidget::getDockerContainers(const yarp::manager::ClusterNode& node, const std::string& dockerName)
869{
870 std::vector<yarp::manager::DockerContainer> containers;
871 if (dockerName.empty())
872 {
873 return containers;
874 }
875
876 std::string cmd = getSSHCmd(node.user, node.address, node.ssh_options, false);
877 cmd += " ";
878 cmd += shellQuote("docker ps -a --filter " + shellQuote("name=^/" + dockerName + "$") + " --format '{{.ID}}\t{{.Names}}\t{{.Status}}'");
879 cmd += " 2>&1";
880
881 std::array<char, 512> buffer{};
882 FILE* pipe = popen(cmd.c_str(), "r");
883 if (!pipe)
884 {
885 yarp::manager::ErrorLogger::Instance()->addError("Docker: unable to execute docker ps on " + node.name);
886 return containers;
887 }
888
889 std::string output;
890 while (fgets(buffer.data(), buffer.size(), pipe) != nullptr)
891 {
892 output += buffer.data();
893 }
894
895 int ret = pclose(pipe);
896 if (ret != 0)
897 {
898 yarp::manager::ErrorLogger::Instance()->addError("Docker: docker ps failed on " + node.name + ": " + output);
899 return containers;
900 }
901
902 std::stringstream lines(output);
903 std::string line;
904 while (std::getline(lines, line))
905 {
906 if (line.empty())
907 {
908 continue;
909 }
910
911 auto fields = splitTabs(line);
912 if (fields.size() < 3)
913 {
914 continue;
915 }
916
918 container.id = fields[0];
919 container.name = fields[1];
920 container.status = fields[2];
921 container.host = node.address;
922 container.user = node.user;
923 container.ssh_options = node.ssh_options;
924 containers.push_back(container);
925 }
926
927 return containers;
928}
929
930bool ClusterWidget::runDockerCommand(const yarp::manager::DockerContainer& container, const std::string& command)
931{
932 std::string cmd = getSSHCmd(container.user, container.host, container.ssh_options);
933 cmd += " ";
934 cmd += shellQuote(command + " " + shellQuote(container.name));
935 return system(cmd.c_str()) == 0;
936}
937
938void ClusterWidget::onRefreshDockerContainers()
939{
940 if (!dockerTreeWidget)
941 {
942 return;
943 }
944
945 dockerTreeWidget->clear();
946 std::set<std::string> visitedContainers;
947 for (const auto& node : cluster.nodes)
948 {
949 if (node.docker.empty())
950 {
951 continue;
952 }
953
954 std::string key = node.user + "@" + node.address + " " + node.ssh_options + " " + node.docker;
955 if (!visitedContainers.insert(key).second)
956 {
957 continue;
958 }
959
960 auto containers = getDockerContainers(node, node.docker);
961 for (const auto& container : containers)
962 {
964 row << QString(container.host.c_str())
965 << QString(container.name.c_str())
966 << QString(container.status.c_str())
967 << QString(container.id.c_str())
968 << QString(container.host.c_str())
969 << QString(container.user.c_str())
970 << QString(container.ssh_options.c_str());
971 dockerTreeWidget->addTopLevelItem(new QTreeWidgetItem(row));
972 }
973 }
974
975 dockerTreeWidget->resizeColumnToContents(0);
976 dockerTreeWidget->resizeColumnToContents(1);
977 dockerTreeWidget->resizeColumnToContents(3);
978 updateDockerButtons();
979 updateYarprunDockerColors();
980 reportErrors();
981}
982
983void ClusterWidget::onStartSelectedDockerContainers()
984{
985 for (auto* item : dockerTreeWidget->selectedItems())
986 {
988 container.name = item->text(1).toStdString();
989 container.host = item->text(4).toStdString();
990 container.user = item->text(5).toStdString();
991 container.ssh_options = item->text(6).toStdString();
992
993 if (!runDockerCommand(container, "docker start"))
994 {
995 yarp::manager::ErrorLogger::Instance()->addError("Docker: failed to start " + container.name + " on " + container.host);
996 }
997 }
998 reportErrors();
999 onRefreshDockerContainers();
1000}
1001
1002void ClusterWidget::onStopSelectedDockerContainers()
1003{
1004 for (auto* item : dockerTreeWidget->selectedItems())
1005 {
1007 container.name = item->text(1).toStdString();
1008 container.host = item->text(4).toStdString();
1009 container.user = item->text(5).toStdString();
1010 container.ssh_options = item->text(6).toStdString();
1011
1012 if (!runDockerCommand(container, "docker stop"))
1013 {
1014 yarp::manager::ErrorLogger::Instance()->addError("Docker: failed to stop " + container.name + " on " + container.host);
1015 }
1016 }
1017 reportErrors();
1018 onRefreshDockerContainers();
1019}
1020
1021std::string ClusterWidget::getSSHCmd(const std::string &user, const std::string &host, const std::string &ssh_options, bool background)
1022{
1023 std::string cmd;
1024 cmd = background ? "ssh -f" : "ssh";
1025 if (!ssh_options.empty())
1026 {
1027 cmd = cmd + " " + ssh_options;
1028 }
1029 if (user.empty())
1030 {
1031 cmd = cmd + " " + host;
1032 }
1033 else
1034 {
1035 cmd = cmd + " " + user + "@" +host;
1036 }
1037
1038 return cmd;
1039}
1040
1041bool ClusterWidget::checkNameserver()
1042{
1043 std::string name = ui->lineEditNs->text().toStdString();
1044
1045 if (name.empty())
1046 {
1047 return false;
1048 }
1049
1050 if (name.find('/') == std::string::npos)
1051 {
1052 name = "/" + name;
1053 }
1054
1055
1056 if (!NetworkBase::checkNetwork(2.0))
1057 {
1058 yError()<<"ClusterWidget: yarpserver is not running";
1059 return false;
1060 }
1061
1062
1063 yarp::os::Bottle cmd, reply;
1064 cmd.addString("get");
1065 cmd.addString(name);
1066 cmd.addString("nameserver");
1067 bool ret = yarp::os::impl::NameClient::getNameClient().send(cmd, reply);
1068 if (!ret)
1069 {
1070 yError()<<"ClusterWidget: Cannot contact the NameClient";
1071 return false;
1072 }
1073 if (reply.size()==6)
1074 {
1075 if (reply.get(5).asBool())
1076 {
1077 return true;
1078 }
1079 else
1080 {
1081 return false;
1082 }
1083
1084 }
1085 else
1086 {
1087 return false;
1088 }
1089}
1090
1091bool ClusterWidget::checkNode(const std::string &name)
1092{
1093 std::string portname = name;
1094 if (portname.find('/') == std::string::npos)
1095 {
1096 portname = "/" + portname;
1097 }
1098
1099 if (!NetworkBase::checkNetwork(2.0))
1100 {
1101 yError()<<"ClusterWidget: yarpserver is not running";
1102 return false;
1103 }
1104
1107 {
1108 yError()<<"ClusterWidget: port"<<portname<<"is not responding";
1109 return false;
1110 }
1111
1112
1113 yarp::os::Bottle cmd, reply;
1114 cmd.addString("get");
1115 cmd.addString(portname);
1116 cmd.addString("yarprun");
1117 bool ret = yarp::os::impl::NameClient::getNameClient().send(cmd, reply);
1118 if (!ret)
1119 {
1120 yError()<<"ClusterWidget: Cannot contact the NameClient";
1121 return false;
1122 }
1123 if (reply.size()==6)
1124 {
1125 if (reply.get(5).asBool())
1126 {
1127 return true;
1128 }
1129 else
1130 {
1131 return false;
1132 }
1133
1134 }
1135 else
1136 {
1137 return false;
1138 }
1139
1140}
1141
1142void ClusterWidget::updateServerEntries()
1143{
1144 // remove all the whitespaces
1145 cluster.user = ui->lineEditUser->text().simplified().trimmed().toStdString();
1146 cluster.nsNode = ui->nsNodeComboBox->currentText().simplified().trimmed().toStdString();
1147}
1148
1149void ClusterWidget::reportErrors()
1150{
1152 if (logger->errorCount() || logger->warningCount())
1153 {
1154 const char* err;
1155 while((err=logger->getLastError()))
1156 {
1157 QString msg = QString("ClusterWidget: %1").arg(err);
1158 emit logError(msg);
1159 }
1160 }
1161}
1162
1164{
1165 if (clusLoader)
1166 {
1167 delete clusLoader;
1168 clusLoader = nullptr;
1169 }
1170 delete ui;
1171}
#define yError(...)
Definition Log.h:361
int SIGNAL(int pid, int signum)
void logMessage(QString)
void setConfigFile(const std::string &_confFile)
void logError(QString)
ClusterWidget(QWidget *parent=0)
Singleton class ErrorLogger.
Definition utility.h:58
const char * getLastError()
Definition utility.cpp:148
void addError(const char *szError)
Definition utility.cpp:126
static ErrorLogger * Instance()
Singleton class ErrorLogger.
Definition utility.cpp:98
bool parseXmlFile(Cluster &_cluster)
A simple collection of objects that can be described and transmitted in a portable way.
Definition Bottle.h:64
size_type size() const
Gets the number of elements in the bottle.
Definition Bottle.cpp:252
Value & get(size_type index) const
Reads a Value v from a certain part of the list.
Definition Bottle.cpp:247
void addString(const char *str)
Places a string in the bottle, at the end of the list.
Definition Bottle.cpp:176
A mini-server for performing network communication in the background.
static bool checkNetwork()
Check if the YARP Network is up and running.
Definition Network.cpp:1473
virtual bool asBool() const
Get boolean value.
Definition Value.cpp:186
static NameClient & getNameClient()
Get an instance of the name client.
static bool getPortDetails(const std::string &portName, PortDetails &info, double timeout=2.0)
Get the details (connections, owner process and machine) of a port.
Definition aboutdlg.h:11
void delay(double seconds)
Wait for a certain number of seconds.
Definition Time.cpp:111
An interface to the operating system, including Port based communication.
std::vector< ClusterNode > nodes