-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmainwindow.cpp
More file actions
495 lines (402 loc) · 14.1 KB
/
Copy pathmainwindow.cpp
File metadata and controls
495 lines (402 loc) · 14.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
#include "mainwindow.h"
#include "./ui_mainwindow.h"
#include "ssh_port_forward.h"
#include "job_dialog.h"
#include "password_dialog.h"
#include <iostream>
#include <QDesktopServices>
#include <QInputDialog>
#include <QRegularExpression>
#include <QRegularExpressionMatch>
#include <QRegularExpressionMatchIterator>
#include <QUrl>
#include <QUrlQuery>
struct NotebookUrlParts
{
QString protocol;
QString host;
int port;
QString path;
QString token;
};
NotebookUrlParts parseNotebookUrl(const QString &urlString)
{
NotebookUrlParts parts;
// Create QUrl object from the string
QUrl url(urlString);
// Extract basic URL components
parts.protocol = url.scheme();
parts.host = url.host();
parts.port = url.port();
parts.path = url.path();
// Parse query parameters to get the token
QUrlQuery query(url);
if (query.hasQueryItem("token"))
{
parts.token = query.queryItemValue("token");
}
return parts;
}
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent), ui(new Ui::MainWindow), m_sshClient(nullptr), m_sshPortForward(nullptr)
{
ui->setupUi(this);
m_sshClient = new SSHClient(this);
m_notebookController = NotebookController::create(m_sshClient);
// Connect signals
connect(m_sshClient, &SSHClient::connected, this, &MainWindow::onConnected);
connect(m_sshClient, &SSHClient::disconnected, this, &MainWindow::onDisconnected);
connect(m_sshClient, &SSHClient::error, this, &MainWindow::onError);
connect(m_sshClient, &SSHClient::keyboardInteractivePrompt, this, &MainWindow::onKeyboardInteractivePrompt);
connect(m_sshClient, &SSHClient::authenticationFailed, this, &MainWindow::onAuthenticationFailed);
connect(m_sshClient, &SSHClient::authenticationSucceeded, this, &MainWindow::onAuthenticationSucceeded);
connect(m_sshClient, &SSHClient::tunnelEstablished, this, &MainWindow::onTunnelEstablished);
connect(m_sshClient, &SSHClient::tunnelClosed, this, &MainWindow::onTunnelClosed);
connect(m_sshClient, &SSHClient::channelOutputReceived, this, &MainWindow::onChannelOutputReceived);
connect(m_sshClient, &SSHClient::channelOpened, this, &MainWindow::onChannelOpened);
connect(m_sshClient, &SSHClient::channelClosed, this, &MainWindow::onChannelClosed);
connect(m_sshClient, &SSHClient::channelError, this, &MainWindow::onChannelError);
connect(m_notebookController.get(), &NotebookController::jobTableUpdated, this, &MainWindow::onJobTableUpdated);
m_sshPortForward = new SSHPortForward(m_sshClient, this);
connect(m_sshPortForward, &SSHPortForward::forwardingStarted, this, &MainWindow::onForwardingStarted,
Qt::QueuedConnection);
connect(m_sshPortForward, &SSHPortForward::forwardingStopped, this, &MainWindow::onForwardingStopped,
Qt::QueuedConnection);
connect(m_sshPortForward, &SSHPortForward::error, this, &MainWindow::onForwardError, Qt::QueuedConnection);
connect(m_sshPortForward, &SSHPortForward::newConnectionEstablished, this,
&MainWindow::onNewForwardConnectionEstablished, Qt::QueuedConnection);
connect(m_sshPortForward, &SSHPortForward::connectionClosed, this, &MainWindow::onForwardConnectionClosed,
Qt::QueuedConnection);
disableControls();
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::disableControls()
{
ui->connectButton->setEnabled(true);
ui->newNotebookButton->setEnabled(false);
ui->refreshButton->setEnabled(false);
ui->closeNotebookButton->setEnabled(false);
ui->closeButton->setEnabled(false);
ui->openNotebookButton->setEnabled(false);
}
void MainWindow::enableControls()
{
ui->connectButton->setEnabled(false);
ui->newNotebookButton->setEnabled(true);
ui->refreshButton->setEnabled(true);
ui->closeNotebookButton->setEnabled(true);
ui->closeButton->setEnabled(true);
ui->openNotebookButton->setEnabled(true);
}
void MainWindow::log(const QString &message)
{
ui->logEdit->append(message);
}
void MainWindow::onConnected()
{
ui->statusBar->showMessage("Connected to host");
log("Connected to host");
}
void MainWindow::onDisconnected()
{
ui->statusBar->showMessage("Disconnected from host");
disableControls();
log("Disconnected from host");
}
void MainWindow::onError(const QString &error)
{
ui->statusBar->showMessage(error);
log("Error: " + error);
}
void MainWindow::onAuthenticationFailed()
{
ui->statusBar->showMessage("Authentication failed.");
disableControls();
log("Authentication failed");
}
void MainWindow::onAuthenticationSucceeded()
{
log("Authentication succeeded");
ui->statusBar->showMessage("Authentication succeeded.");
enableControls();
SSHClient::CommandOptions options;
options.ptyEnabled = true; // Enable PTY for interactive apps
options.columns = 120; // Set reasonable terminal size
options.rows = 40;
options.mergeOutput = true; // Merge stderr with stdout
options.outputMode = SSHClient::PtyOutputMode::StripAll;
m_sshClient->openCommandChannel(options);
if (m_sshClient->isCommandChannelOpen())
{
log("Command channel is open");
m_notebookController->initialise();
m_notebookController->job_table();
}
}
void MainWindow::onKeyboardInteractivePrompt(const QString &name, const QString &instruction,
const QStringList &prompts)
{
log("Received keyboard-interactive prompt: " + name + " - " + instruction);
QStringList responses;
for (int i = 0; i < prompts.size(); i++)
{
QInputDialog dialog;
dialog.setWindowTitle(name);
dialog.setLabelText(prompts.at(i));
if (prompts.at(i).contains("password", Qt::CaseInsensitive))
dialog.setTextEchoMode(QLineEdit::Password);
else
dialog.setTextEchoMode(QLineEdit::Normal);
dialog.exec();
responses << dialog.textValue();
}
log("Sending keyboard-interactive response: " + responses.join(", "));
m_sshClient->sendKeyboardInteractiveResponse(responses);
}
void MainWindow::onTunnelEstablished(const QString &bindAddress, uint16_t bindPort)
{
ui->statusBar->showMessage(QString("Tunnel established on %1:%2").arg(bindAddress).arg(bindPort));
}
void MainWindow::onTunnelClosed(const QString &bindAddress, uint16_t bindPort)
{
ui->statusBar->showMessage(QString("Tunnel closed on %1:%2").arg(bindAddress).arg(bindPort));
}
void MainWindow::onDataReceived(const QByteArray &data)
{
ui->textEdit->append(QString::fromUtf8(data));
}
void MainWindow::onForwardingStarted(quint16 localPort)
{
log("Forwarding started on port " + QString::number(localPort));
}
void MainWindow::onForwardingStopped()
{
log("Forwarding stopped");
}
void MainWindow::onForwardError(const QString &message)
{
log("Forwarding error: " + message);
}
void MainWindow::onNewForwardConnectionEstablished(const QString &remoteHost, quint16 remotePort)
{
log("New connection established to " + remoteHost + ":" + QString::number(remotePort));
}
void MainWindow::onForwardConnectionClosed()
{
log("Forward connection closed");
}
void MainWindow::onChannelOpened()
{
log("Command channel opened");
}
void MainWindow::onChannelClosed(int exitStatus)
{
log("Command channel closed with exit status: " + QString::number(exitStatus));
}
std::vector< QString > extractUrls(const QString &input)
{
std::vector< QString > urls;
// Regular expression pattern for URLs
// This pattern matches common URL formats including http, https, ftp
QRegularExpression urlRegex(QStringLiteral(R"((https?|ftp):\/\/)" // Protocol
R"([\w_-]+(?:(?:\.[\w_-]+)+))" // Domain name
R"(([\w.,@?^=%&:\/~+#-]*[\w@?^=%&\/~+#-])?)") // Path and query
);
// Find all matches in the input string
QRegularExpressionMatchIterator matchIterator = urlRegex.globalMatch(input);
// Extract each URL match
while (matchIterator.hasNext())
{
QRegularExpressionMatch match = matchIterator.next();
urls.push_back(match.captured(0));
}
return urls;
}
void MainWindow::onChannelOutputReceived(const QByteArray &data, bool isStderr)
{
// log("Command output received: " + QString::fromUtf8(data));
auto receivedString = QString::fromUtf8(data);
ui->textEdit->append(QString::fromUtf8(data));
log("----- Command output received ---- ");
log(receivedString);
log("----- Command output end --------- ");
m_notebookController->parseCommandOutput(receivedString);
}
void MainWindow::onChannelError(const QString &error)
{
log("Command channel error: " + error);
}
void MainWindow::onJobTableUpdated()
{
log("Updating running table");
ui->runningTable->clearContents();
auto jobs = m_notebookController->jobs();
ui->runningTable->setRowCount(jobs.size());
ui->runningTable->setColumnCount(4);
ui->runningTable->setHorizontalHeaderLabels(QStringList() << "ID"
<< "Name"
<< "Status"
<< "URL");
for (int i = 0; i < jobs.size(); i++)
{
auto jobIdItem = new QTableWidgetItem(QString::number(jobs[i].id));
jobIdItem->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
auto jobNameItem = new QTableWidgetItem(jobs[i].name);
jobNameItem->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
auto jobStatusItem = new QTableWidgetItem(jobs[i].status);
jobStatusItem->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
auto jobUrlItem = new QTableWidgetItem(jobs[i].url);
jobUrlItem->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
ui->runningTable->setItem(i, 0, jobIdItem);
ui->runningTable->setItem(i, 1, jobNameItem);
ui->runningTable->setItem(i, 2, jobStatusItem);
ui->runningTable->setItem(i, 3, jobUrlItem);
}
}
void MainWindow::on_connectButton_clicked()
{
QString server, username, password;
// server = "rocky9-vm.lunarc.lu.se";
// username = "lindemann";
server = "192.168.86.28";
username = "lindemann";
if (m_connectionSettings.useKeyboardInteractive)
{
log("Trying to authenticate with KeyboardInteractive");
m_sshClient->authenticateWithKeyboardInteractive();
log("isAuthenticated: " + QString::number(m_sshClient->isAuthenticated()));
if (!m_sshClient->isAuthenticated())
{
log("Trying to authenticate with Password");
// m_sshClient->authenticateWithPassword(ui->passwordEdit->text());
}
else
log("Already authenticated");
}
else
{
if (PasswordDialog::getConnectionInfo(this, server, username, password))
{
m_sshClient->connectToHost(server, username);
m_sshClient->authenticateWithPassword(password);
}
else
{
log("Connection cancelled");
return;
}
}
}
void MainWindow::on_disconnectButton_clicked()
{
m_sshClient->disconnect();
if (m_sshPortForward != nullptr)
{
if (m_sshPortForward->isForwarding())
m_sshPortForward->stopForwarding();
}
}
void MainWindow::on_executeButton_clicked()
{
m_sshClient->executeCommand(ui->commandEdit->text());
ui->commandEdit->clear();
}
void MainWindow::on_commandEdit_returnPressed()
{
m_sshClient->executeInChannel(ui->commandEdit->text());
ui->commandEdit->clear();
}
void MainWindow::on_connectTunnelButton_clicked()
{
}
void MainWindow::on_disconnectTunnelButton_clicked()
{
}
void MainWindow::on_newNotebookButton_clicked()
{
QString name, notebookEnv, wallTime;
int tasksPerNode;
if (JobDialog::getJobInfo(this, name, notebookEnv, wallTime, tasksPerNode))
{
m_notebookController->submit(name, notebookEnv, wallTime, tasksPerNode);
}
else
{
log("Notebook creation cancelled.");
return;
}
}
void MainWindow::on_refreshButton_clicked()
{
m_notebookController->job_table();
}
void MainWindow::on_closeButton_clicked()
{
m_sshClient->closeCommandChannel();
m_sshClient->disconnect();
if (m_sshPortForward != nullptr)
{
if (m_sshPortForward->isForwarding())
m_sshPortForward->stopForwarding();
}
disableControls();
}
void MainWindow::on_closeNotebookButton_clicked()
{
auto selectedItems = ui->runningTable->selectedItems();
if (selectedItems.size() > 0)
{
auto jobId = selectedItems[0]->text().toInt();
m_notebookController->cancel(jobId);
}
m_notebookController->job_table();
}
void MainWindow::on_openNotebookButton_clicked()
{
auto selectedItems = ui->runningTable->selectedItems();
if (selectedItems.size() > 0)
{
auto url = selectedItems[3]->text();
log("Opening URL: " + url);
auto parts = parseNotebookUrl(url);
if (parts.token.isEmpty())
{
log("No token found in URL");
return;
}
log("Protocol: " + parts.protocol);
log("Host: " + parts.host);
log("Port: " + QString::number(parts.port));
log("Path: " + parts.path);
log("Token: " + parts.token);
QUrl localUrl;
localUrl.setScheme(parts.protocol);
localUrl.setHost(parts.host);
localUrl.setPort(8888);
localUrl.setPath(parts.path);
localUrl.setQuery("token=" + parts.token);
m_sshPortForward->startForwarding(8888, "localhost", QUrl(url).port());
bool success = QDesktopServices::openUrl(localUrl);
if (!success)
{
// Handle error case
qDebug() << "Failed to open URL";
}
}
}
void MainWindow::closeEvent(QCloseEvent *event)
{
if (m_sshClient != nullptr)
{
m_sshClient->disconnect();
}
if (m_sshPortForward != nullptr)
{
if (m_sshPortForward->isForwarding())
m_sshPortForward->stopForwarding();
}
event->accept();
}