source: src-qt4/life-preserver/lp-gui/LPMain.cpp

Last change on this file was b258df0, checked in by Ken Moore <ken@…>, 5 weeks ago

Quick fix for the "lpreserver status" parsing in the Life Preserver GUI, and add one more line of debugging output.

  • Property mode set to 100644
File size: 33.0 KB
Line 
1#include "LPMain.h"
2#include "ui_LPMain.h"
3#include <unistd.h>
4
5LPMain::LPMain(QWidget *parent) : QMainWindow(parent), ui(new Ui::LPMain){
6  ui->setupUi(this); //load the Qt-designer UI file
7  //Initialize the auto-refresh timer
8  timer = new QTimer(this);
9        timer->setSingleShot(true);
10        timer->setInterval(60000); // 1 minute timer
11        connect(timer, SIGNAL(timeout()), this, SLOT(updateTabs()) );
12  //Initialize the system watcher
13  watcher = new QFileSystemWatcher(this);
14    //Make sure the lpreserver log directory exists and watch it
15    if(!QFile::exists("/var/log/lpreserver")){
16      qDebug() << "Creating the lpreserver log directory (/var/log/lpreserver)";
17      QDir dir;
18      dir.mkpath("/var/log/lpreserver");
19    }
20    watcher->addPath("/var/log/lpreserver/");
21  //Initialize the waitbox pointer
22  waitBox = 0;
23  //Initialize the classic dialog pointer
24  classicDLG = 0;
25  //Create the basic/advanced view options
26  viewBasic = new QRadioButton(tr("Basic"), ui->menuView);
27        QWidgetAction *WABasic = new QWidgetAction(this); WABasic->setDefaultWidget(viewBasic);
28        ui->menuView->addAction(WABasic);
29  viewAdvanced = new QRadioButton(tr("Advanced"), ui->menuView);
30        QWidgetAction *WAAdv = new QWidgetAction(this); WAAdv->setDefaultWidget(viewAdvanced);
31        ui->menuView->addAction(WAAdv);
32  connect(viewBasic, SIGNAL(toggled(bool)), this, SLOT(viewChanged()) );
33  //Now set the default view type
34  settings = new QSettings(QSettings::UserScope, "PC-BSD", "Life-Preserver-GUI", this);
35  bool basicMode = settings->value("viewmode", true).toBool(); //basic by default
36  if(basicMode){ viewBasic->setChecked(true); } //will automatically call the "viewChanged" function
37  else{ viewAdvanced->setChecked(true); } //will automatically call the "viewChanged" function
38  //Create the filesystem model and tie it to the treewidget
39  fsModel = new QFileSystemModel(this);
40        fsModel->setReadOnly(true);
41        ui->treeView->setModel(fsModel);
42  //Connect the UI to all the functions
43  connect(ui->tool_refresh, SIGNAL(clicked()), this, SLOT(updatePoolList()) );
44  connect(ui->combo_pools, SIGNAL(currentIndexChanged(int)), this, SLOT(updateTabs()) );
45  connect(ui->combo_datasets, SIGNAL(currentIndexChanged(int)), this, SLOT(updateDataset()) );
46  connect(ui->slider_snapshots, SIGNAL(valueChanged(int)), this, SLOT(updateSnapshot()) );
47  connect(ui->push_prevsnap, SIGNAL(clicked()), this, SLOT(prevSnapshot()) );
48  connect(ui->push_nextsnap, SIGNAL(clicked()), this, SLOT(nextSnapshot()) );
49  connect(ui->check_hidden, SIGNAL(stateChanged(int)), this, SLOT(setFileVisibility()) );
50  connect(ui->push_restore, SIGNAL(clicked()), this, SLOT(restoreFiles()) );
51  connect(ui->push_configure, SIGNAL(clicked()), this, SLOT(openConfigGUI()) );
52  //Connect the Menu buttons
53  connect(ui->menuManage_Pool, SIGNAL(triggered(QAction*)), this, SLOT(menuAddPool(QAction*)) );
54  connect(ui->menuUnmanage_Pool, SIGNAL(triggered(QAction*)), this, SLOT(menuRemovePool(QAction*)) );
55  connect(ui->action_SaveKeyToUSB, SIGNAL(triggered()), this, SLOT(menuSaveSSHKey()) );
56  connect(ui->actionClose_Window, SIGNAL(triggered()), this, SLOT(menuCloseWindow()) );
57  connect(ui->menuCompress_Home_Dir, SIGNAL(triggered(QAction*)), this, SLOT(menuCompressHomeDir(QAction*)) );
58  connect(ui->actionExtract_Home_Dir, SIGNAL(triggered()), this, SLOT(menuExtractHomeDir()) );
59  connect(ui->actionAdd_Disk, SIGNAL(triggered()), this, SLOT(menuAddDisk()) );
60  connect(ui->menuRemove_Disk, SIGNAL(triggered(QAction*)), this, SLOT(menuRemoveDisk(QAction*)) );
61  connect(ui->menuSet_Disk_Offline, SIGNAL(triggered(QAction*)), this, SLOT(menuOfflineDisk(QAction*)) );
62  connect(ui->menuSet_Disk_Online, SIGNAL(triggered(QAction*)), this, SLOT(menuOnlineDisk(QAction*)) );
63  connect(ui->action_startScrub, SIGNAL(triggered()), this, SLOT(menuStartScrub()) );
64  connect(ui->action_stopScrub, SIGNAL(triggered()), this, SLOT(menuStopScrub()) );
65  connect(ui->action_newSnapshot, SIGNAL(triggered()), this, SLOT(menuNewSnapshot()) );
66  connect(ui->menuDelete_Snapshot, SIGNAL(triggered(QAction*)), this, SLOT(menuRemoveSnapshot(QAction*)) );
67  //Update the interface
68  QTimer::singleShot(0,this,SLOT(updatePoolList()) );
69 
70  //Make sure the status tab is shown initially
71  ui->tabWidget->setCurrentWidget(ui->tab_status);
72  //Now connect the watcher to the update slot
73  connect(watcher, SIGNAL(directoryChanged(QString)), this, SLOT(autoRefresh()) );
74}
75
76LPMain::~LPMain(){
77       
78}
79
80// ==============
81//      PUBLIC SLOTS
82// ==============
83void LPMain::slotSingleInstance(){
84  this->raise();
85  this->show();
86}
87
88// ==============
89//          PRIVATE
90// ==============
91void LPMain::showErrorDialog(QString title, QString message, QString errors){
92  QMessageBox MB(QMessageBox::Warning, title, message, QMessageBox::Ok, this);
93    MB.setDetailedText(errors);
94    MB.exec();
95}
96
97void LPMain::showWaitBox(QString message){
98  if(waitBox == 0){
99    qDebug() << "New Wait Box";
100    waitBox = new QMessageBox(QMessageBox::NoIcon, tr("Please Wait"), message, QMessageBox::NoButton, this);
101    waitBox->setStandardButtons(QMessageBox::NoButton);
102    waitBox->setWindowModality(Qt::WindowModal);
103  }else{
104    qDebug() << "Update Wait Box:" << message;
105    try{
106      waitBox->setText(message);
107    }catch(...){
108      waitBox = 0; //reset flag if necessary
109      showWaitBox(message);
110      return;
111    }
112  }
113  if(!waitBox->isVisible()){ waitBox->show(); waitBox->raise(); }
114  QCoreApplication::processEvents();
115}
116
117void LPMain::hideWaitBox(){
118  if(waitBox != 0){
119    if(waitBox->isVisible()){ waitBox->hide(); }
120  }
121       
122}
123
124// ==============
125//     PRIVATE SLOTS
126// ==============
127void LPMain::updatePoolList(){
128  //Get the currently selected pool (if there is one)
129  qDebug() << "Update Pool List";
130  QString cPool;
131  if(ui->combo_pools->currentIndex() != -1){ cPool = ui->combo_pools->currentText(); }
132  //Get the list of managed pools
133  qDebug() << "[DEBUG] Fetching list of pools";
134  QStringList pools = LPBackend::listDatasets();
135  QStringList poolsAvail = LPBackend::listPossibleDatasets();
136  //Now put the lists into the UI
137  ui->combo_pools->clear();
138  if(!pools.isEmpty()){ ui->combo_pools->addItems(pools); }
139  //Now set the currently selected pools
140  qDebug() << "[DEBUG] Pool list:" << pools;
141  if(pools.length() > 0){
142    poolSelected=true;   
143    int index = pools.indexOf(cPool);
144    if(index < 0){ ui->combo_pools->setCurrentIndex(0); }
145    else{ ui->combo_pools->setCurrentIndex(index); }
146  }else{
147    //No managed pools
148    poolSelected=false;
149    ui->combo_pools->addItem("No Managed Pools!");
150    ui->combo_pools->setCurrentIndex(0);
151    //Reset to Basic View
152    viewBasic->setChecked(true);
153  }
154  qDebug() << "[DEBUG] Update pool menu options";
155  //Now update the add/remove pool menu's
156  ui->menuManage_Pool->clear();
157  for( int i=0; i<poolsAvail.length(); i++){
158    if(pools.contains(poolsAvail[i])){ continue; } //already managed
159    ui->menuManage_Pool->addAction(poolsAvail[i]);
160  }
161  ui->menuManage_Pool->setEnabled( !ui->menuManage_Pool->isEmpty() );
162  ui->menuUnmanage_Pool->clear();
163  for( int i=0; i<pools.length(); i++){
164    ui->menuUnmanage_Pool->addAction(pools[i]);
165  }
166  ui->menuUnmanage_Pool->setEnabled( !ui->menuUnmanage_Pool->isEmpty() );
167  qDebug() << "[DEBUG] Update user menus";
168  //Now update the user's that are available for home-dir packaging
169  QDir hdir("/usr/home");
170  QStringList users = hdir.entryList(QDir::Dirs | QDir::NoDotAndDotDot, QDir::Name);
171  ui->menuCompress_Home_Dir->clear();
172  for(int i=0; i<users.length(); i++){
173    ui->menuCompress_Home_Dir->addAction(users[i]);
174  }
175  //Now update the interface appropriately
176  ui->combo_pools->setEnabled(poolSelected);
177  qDebug() << "[DEBUG] Finished updatePoolList()";
178  updateTabs();
179}
180
181void LPMain::viewChanged(){
182  ui->menuView->hide();
183  ui->menubar->clear();
184  settings->setValue("viewmode", viewBasic->isChecked()); //save value for later
185  if(viewBasic->isChecked()){
186    ui->menubar->addMenu(ui->menuFile);
187    ui->menubar->addMenu(ui->menuView);
188    ui->menubar->addMenu(ui->menuClassic_Backups);
189  }else{
190    ui->menubar->addMenu(ui->menuFile);
191    ui->menubar->addMenu(ui->menuView);
192    ui->menubar->addMenu(ui->menuClassic_Backups);
193    ui->menubar->addMenu(ui->menuSnapshots);
194    ui->menubar->addMenu(ui->menuDisks);
195  }
196}
197
198void LPMain::updateTabs(){
199  //qDebug() << "Update Tabs" << poolSelected;
200  qDebug() << "[DEBUG] start updateTabs():" << poolSelected;
201  viewChanged();
202  ui->tabWidget->setEnabled(poolSelected);
203  ui->menuView->setEnabled(poolSelected);       
204  ui->menuDisks->setEnabled(poolSelected); 
205  ui->menuSnapshots->setEnabled(poolSelected);
206  ui->push_configure->setVisible(poolSelected);
207  ui->action_SaveKeyToUSB->setEnabled(poolSelected);
208  if(poolSelected){
209    showWaitBox(tr("Loading zpool information"));
210    qDebug() << "[DEBUG] loadPoolData:" << ui->combo_pools->currentText();
211    POOLDATA = LPGUtils::loadPoolData(ui->combo_pools->currentText());
212    qDebug() << "[DEBUG] loaded data";
213    hideWaitBox();
214    //Now list the status information
215    ui->label_status->setText(POOLDATA.poolStatus);
216    ui->label_numdisks->setText( QString::number(POOLDATA.harddisks.length()) );
217    ui->label_latestsnapshot->setText(POOLDATA.latestSnapshot);
218    qDebug() << "[DEBUG] Latest Snapshot:" << POOLDATA.latestSnapshot;
219    if(POOLDATA.finishedStatus.isEmpty()){ ui->label_finishedstat->setVisible(false); }
220    else{
221      ui->label_finishedstat->setText(POOLDATA.finishedStatus);
222      ui->label_finishedstat->setVisible(true);
223    }
224    if(POOLDATA.runningStatus.isEmpty()){ 
225      ui->label_runningstat->setVisible(false);
226      ui->action_startScrub->setEnabled(true);
227      ui->action_stopScrub->setEnabled(false);
228    }else{
229      ui->label_runningstat->setText(POOLDATA.runningStatus);
230      ui->label_runningstat->setVisible(true);
231      ui->action_startScrub->setEnabled(false); //Something already running
232      ui->action_stopScrub->setEnabled(POOLDATA.runningStatus.contains("scrub", Qt::CaseInsensitive));
233    }       
234    if(POOLDATA.errorStatus.isEmpty()){ ui->label_errorstat->setVisible(false); }
235    else{
236      ui->label_errorstat->setText(POOLDATA.errorStatus);
237      ui->label_errorstat->setVisible(true);
238    }       
239    //Now list the data restore options
240    QString cds = ui->combo_datasets->currentText();
241    ui->combo_datasets->clear();
242    QStringList dslist = POOLDATA.subsets();
243    dslist.sort();
244    //Now move the home directories to the top of the list
245    int moved = 0;
246    for(int i=0; i<dslist.length(); i++){  //make sure it stays in alphabetical order
247      if(dslist[i].startsWith("/usr/home/")){
248        dslist.move(i,moved);
249        moved++; 
250        i--; //make sure to not miss any items from moving
251      }
252    }
253    ui->combo_datasets->addItems(dslist);
254    int dsin = dslist.indexOf(cds);
255    if(dsin >= 0){ ui->combo_datasets->setCurrentIndex(dsin); }
256    else if( !dslist.isEmpty() ){ ui->combo_datasets->setCurrentIndex(0); }
257    else{ ui->combo_datasets->addItem(tr("No datasets available")); }
258    //NOTE: this automatically calls the "updateDataset()" function in a new thread
259   
260    //Now update the snapshot removal menu list
261    //QStringList snapComments;
262    QStringList snaps = POOLDATA.allSnapshots(); //LPBackend::listLPSnapshots(ui->combo_pools->currentText(), snapComments);
263    ui->menuDelete_Snapshot->clear();
264    for(int i=0; i<snaps.length(); i++){
265       QString comment = POOLDATA.snapshotComment(snaps[i]).simplified();
266        if(comment.isEmpty()){ ui->menuDelete_Snapshot->addAction(snaps[i]); }
267        else{ ui->menuDelete_Snapshot->addAction(snaps[i] + " (" + comment + ")" ); }
268    }
269    ui->menuDelete_Snapshot->setEnabled( !ui->menuDelete_Snapshot->isEmpty() );
270    //Now update the disk menu items
271    ui->menuRemove_Disk->clear();
272    ui->menuSet_Disk_Offline->clear();
273    ui->menuSet_Disk_Online->clear();
274    for(int i=0; i<POOLDATA.harddisks.length(); i++){
275      ui->menuRemove_Disk->addAction(POOLDATA.harddisks[i]);
276      if(POOLDATA.harddiskStatus[i] == "OFFLINE"){
277        ui->menuSet_Disk_Online->addAction(POOLDATA.harddisks[i]);
278      }else{
279        ui->menuSet_Disk_Offline->addAction(POOLDATA.harddisks[i]);     
280      }
281    }
282    ui->menuRemove_Disk->setEnabled(!ui->menuRemove_Disk->isEmpty());
283    ui->menuSet_Disk_Offline->setEnabled(!ui->menuSet_Disk_Offline->isEmpty());
284    ui->menuSet_Disk_Online->setEnabled(!ui->menuSet_Disk_Online->isEmpty());
285  }else{
286    //No Pool selected
287    ui->label_numdisks->clear();
288    ui->label_latestsnapshot->clear();
289    ui->label_status->clear();
290          ui->label_errorstat->setVisible(false);
291          ui->label_runningstat->setVisible(false);
292          ui->label_finishedstat->setVisible(false);
293  }
294
295}
296
297void LPMain::updateDataset(){
298  //Update the snapshots for the currently selected dataset
299  QString cds = ui->combo_datasets->currentText();
300  if(POOLDATA.subsets().indexOf(cds) >= 0){
301    QStringList snaps = POOLDATA.snapshots(cds);
302      qDebug() << "Update Dataset";
303      ui->slider_snapshots->setEnabled(true);
304      ui->slider_snapshots->setMinimum(0);
305      int max = snaps.length() -1;
306      if(max < 0){ max = 0; ui->slider_snapshots->setEnabled(false); }
307      ui->slider_snapshots->setMaximum(max);
308      ui->slider_snapshots->setValue(max); //most recent snapshot
309      int interval = 1; //one tick per snapshot
310      if( max > 20 ){ interval = max / 20; } //show 20 ticks
311      ui->slider_snapshots->setTickInterval(interval);
312
313      updateSnapshot();
314  }else{
315    ui->slider_snapshots->setEnabled(false);
316    ui->label_snapshot->clear();
317    ui->push_nextsnap->setEnabled(false);
318    ui->push_prevsnap->setEnabled(false);
319  }
320       
321}
322
323void LPMain::updateSnapshot(){
324  int sval = ui->slider_snapshots->value();
325  QStringList snaps = POOLDATA.snapshots(ui->combo_datasets->currentText());
326  //qDebug() << "Update Snapshot";
327  //Update the previous/next buttons
328  if(sval == ui->slider_snapshots->minimum() ){ ui->push_prevsnap->setEnabled(false); }
329  else{ ui->push_prevsnap->setEnabled(true); }
330  if(sval == ui->slider_snapshots->maximum() ){ ui->push_nextsnap->setEnabled(false); }
331  else{ ui->push_nextsnap->setEnabled(true); }
332  //Now update the snapshot viewer
333  if(snaps.isEmpty()){ ui->label_snapshot->clear(); ui->slider_snapshots->setEnabled(false); }
334  else{
335    QString snap = snaps.at(sval);
336    QString path = ui->combo_datasets->currentText() + "/.zfs/snapshot/"+snap;
337    //qDebug() << "Snapshot path:" << path;
338    QString comment = POOLDATA.snapshotComment(snap).simplified();
339    if(comment.isEmpty()){ ui->label_snapshot->setText(snap); }
340    else{ ui->label_snapshot->setText(snap+" ("+comment+")"); }
341    //Now update the snapshot view
342    ui->treeView->setRootIndex( fsModel->setRootPath(path) );
343   
344  }
345}
346
347void LPMain::nextSnapshot(){
348  ui->slider_snapshots->setValue( ui->slider_snapshots->value()+1 );
349}
350
351void LPMain::prevSnapshot(){
352  ui->slider_snapshots->setValue( ui->slider_snapshots->value()-1 );
353}
354
355void LPMain::setFileVisibility(){
356  if(ui->check_hidden->isChecked()){
357    fsModel->setFilter(QDir::AllDirs | QDir::Files | QDir::NoDotAndDotDot | QDir::Hidden );
358  }else{
359    fsModel->setFilter(QDir::AllDirs | QDir::Files | QDir::NoDotAndDotDot );
360  }
361}
362
363void LPMain::restoreFiles(){
364  QString filePath = fsModel->filePath( ui->treeView->currentIndex() );
365  qDebug() << " Restore file(s):" << filePath;
366  QFileInfo info(filePath);     
367  QString destDir = filePath;
368        destDir.remove("/.zfs/snapshot/"+ui->label_snapshot->text().section("(",0,0).simplified());
369        destDir.chop( filePath.section("/",-1).size()+1 ); //get rid of the filename at the end
370        while(!QFile::exists(destDir)){ destDir.chop( destDir.section("/",-1).size() +1); }
371  QString newFilePath = destDir+"/"+LPGUtils::generateReversionFileName(filePath, destDir);
372  //qDebug() << "Destination:" << newFilePath;
373  //Perform the reversion(s)
374  QStringList errors;
375  if( info.isDir() ){
376    //Is a directory
377    showWaitBox( QString(tr("Restoring Directory: %1")).arg(newFilePath) );
378    errors = LPGUtils::revertDir(filePath, newFilePath);
379    hideWaitBox();
380    if(!errors.isEmpty()){
381      qDebug() << "Failed Reversions:" << errors;
382      errors.prepend(tr("File destination(s) that could not be restored:")+"\n");
383      showErrorDialog(tr("Reversion Error"), tr("Some files could not be restored from the snapshot."), errors.join("\n") );
384    }else{
385      qDebug() << "Reversion successful";           
386      QMessageBox::information(this,tr("Restore Successful"),QString(tr("The following directory was succesfully restored: %1")).arg(newFilePath) );
387    }
388  }else{
389    //Just a single file
390    showWaitBox( QString(tr("Restoring file: %1")).arg(newFilePath) );
391    bool ok = LPGUtils::revertFile(filePath, newFilePath);
392    hideWaitBox();
393    if( !ok ){
394      qDebug() << "Failed Reversion:" << newFilePath;
395      errors << QString(tr("Snapshot file: %1")).arg(filePath);
396      errors << QString(tr("Destination: %1")).arg(newFilePath);
397      errors << tr("Please check that the destination directory exists and is writable");
398      showErrorDialog(tr("Reversion Error"), tr("The file could not be restored from the snapshot."), errors.join("\n") );
399    }else{
400      qDebug() << "Reversion successful";
401      QMessageBox::information(this,tr("Restore Successful"),QString(tr("The following file was succesfully restored: %1")).arg(newFilePath) );
402    }
403  }       
404       
405}
406
407void LPMain::openConfigGUI(){
408  qDebug() << "Open Configuration UI";
409  QString ds = ui->combo_pools->currentText();
410  if(ds.isEmpty()){ return; }
411  LPConfig CFG(this);
412  CFG.loadDataset(ds, LPBackend::listReplicationTargets().contains(ds));
413  CFG.exec();
414  //Now check for return values and update appropriately
415  bool change = false;
416  if(CFG.localChanged){
417    ui->statusbar->showMessage(QString(tr("Configuring dataset: %1")).arg(ds),0);
418    qDebug() << "Settings up local snapshots:" << ds << "Frequency:" << CFG.localSchedule;
419    LPBackend::setupDataset(ds, CFG.localSchedule, CFG.localSnapshots);
420    ui->statusbar->clearMessage();
421    change = true;
422  }
423  if(CFG.remoteChanged){
424    change = true;
425    if(CFG.isReplicated){
426      ui->statusbar->showMessage(QString(tr("Configuring replication: %1")).arg(ds),0);
427      qDebug() << "Setting up Replication:" << ds << " Frequency:" << CFG.remoteFreq;
428      LPBackend::setupReplication(ds, CFG.remoteHost, CFG.remoteUser, CFG.remotePort, CFG.remoteDataset, CFG.remoteFreq);
429      QMessageBox::information(this,tr("Reminder"),tr("Don't forget to save your SSH key to a USB stick so that you can restore your system from the remote host later!!"));
430    }else{
431      ui->statusbar->showMessage(QString(tr("Removing replication: %1")).arg(ds),0);
432      qDebug() << "Removing Replication:" << ds;
433      LPBackend::removeReplication(ds);
434    }
435    ui->statusbar->clearMessage();
436  }
437  //Now update the UI if appropriate
438  if(change){
439    updateTabs();
440  }     
441}
442
443void LPMain::autoRefresh(){
444  //This slot makes sure that the GUI is not refreshed too frequently
445  if(!timer->isActive()){
446    timer->start(); //start countdown to GUI refresh
447  }       
448}
449
450// -----------------------------------------------
451//   MENU SLOTS
452// -----------------------------------------------
453// ==== File Menu ====
454void LPMain::menuAddPool(QAction *act){
455  QString dataset = act->text();
456  qDebug() << "Start Wizard for new managing pool:" << dataset;
457  LPWizard wiz(this);
458  wiz.setDataset(dataset);
459  wiz.exec();
460  //See if the wizard was cancelled or not
461  if(!wiz.cancelled){
462    ui->statusbar->showMessage(QString(tr("Enabling dataset management: %1")).arg(dataset),0);
463    //run the proper commands to get the dataset enabled
464    qDebug() << "Setup Snapshots:" << dataset << " Frequency:" << wiz.localTime;
465    if( LPBackend::setupDataset(dataset, wiz.localTime, wiz.totalSnapshots) ){
466      if(wiz.enableReplication){
467         qDebug() << "Setting up replication:" << dataset << " Frequency:" << wiz.remoteTime;
468         LPBackend::setupReplication(dataset, wiz.remoteHost, wiz.remoteUser, wiz.remotePort, wiz.remoteDataset, wiz.remoteTime);     
469         QMessageBox::information(this,tr("Reminder"),tr("Don't forget to save your SSH key to a USB stick so that you can restore your system from the remote host later!!"));
470      }
471    }
472    ui->statusbar->clearMessage();
473    //Now update the list of pools
474    updatePoolList();
475  }     
476}
477
478void LPMain::menuRemovePool(QAction *act){
479  QString ds = act->text();
480  qDebug() << "Remove Pool:" << ds;
481  if(!ds.isEmpty()){
482    //Verify the removal of the dataset
483    if( QMessageBox::Yes == QMessageBox::question(this,tr("Verify Dataset Backup Removal"),tr("Are you sure that you wish to cancel automated snapshots and/or replication of the following dataset?")+"\n\n"+ds,QMessageBox::Yes | QMessageBox::No, QMessageBox::No) ){           
484      //verify the removal of all the snapshots for this dataset
485      QStringList snapComments;
486      QStringList snaps = LPBackend::listLPSnapshots(ds, snapComments);
487      if(!snaps.isEmpty()){
488        if( QMessageBox::Yes == QMessageBox::question(this,tr("Verify Snapshot Deletion"),tr("Do you wish to remove the local snapshots for this dataset?")+"\n"+tr("WARNING: This is a permanant change that cannot be reversed"),QMessageBox::Yes | QMessageBox::No, QMessageBox::No) ){
489          //Remove all the snapshots
490          ui->statusbar->showMessage(QString(tr("%1: Removing snapshots")).arg(ds),0);
491          showWaitBox(tr("Removing snapshots"));
492          for(int i=0; i<snaps.length(); i++){
493            LPBackend::removeSnapshot(ds,snaps[i]);
494          }
495          ui->statusbar->clearMessage();
496        }
497      }
498      //Remove the dataset from life-preserver management
499      if(LPBackend::listReplicationTargets().contains(ds)){ 
500        ui->statusbar->showMessage(QString(tr("%1: Disabling Replication")).arg(ds),0);
501        showWaitBox(tr("Disabling Replication"));
502        LPBackend::removeReplication(ds); 
503        ui->statusbar->clearMessage();     
504      }
505      ui->statusbar->showMessage(QString(tr("%1: Disabling Life-Preserver Management")).arg(ds),0);
506      showWaitBox(tr("Removing Life Preserver Schedules"));
507      LPBackend::removeDataset(ds);
508      ui->statusbar->clearMessage();
509      updatePoolList();
510      hideWaitBox();
511    }
512  } //end check for empty ds
513
514}
515
516void LPMain::menuSaveSSHKey(){
517  QString ds = ui->combo_pools->currentText(); 
518  qDebug() << "Save SSH Key:" << ds;
519  if(ds.isEmpty()){ return; }
520  //Get the local hostname
521  char host[1023] = "\0";
522  gethostname(host,1023);
523  QString localHost = QString(host).simplified();
524  qDebug() << " - hostname:" << localHost;
525  //Scan for mounted USB devices
526  QStringList devs = LPBackend::findValidUSBDevices();
527  qDebug() << " - devs:" << devs;
528  if(devs.isEmpty()){
529    QMessageBox::warning(this,tr("No Valid USB Devices"), tr("No valid USB devices could be found. Please mount a FAT32 formatted USB stick and try again."));
530    return;
531  }
532  //Ask the user which one to save the file to
533  bool ok;
534  QString dev = QInputDialog::getItem(this, tr("Select USB Device"), tr("Available USB Devices:"), devs,0,false,&ok);   
535  if(!ok or dev.isEmpty()){ return; } //cancelled
536  QString devPath = dev.section("(",0,0).simplified();
537  //Now copy the file over
538  ok = LPBackend::copySSHKey(devPath, localHost);
539  if(ok){
540    QMessageBox::information(this,tr("Success"), tr("The public SSH key file was successfully copied onto the USB device."));
541  }else{
542    QMessageBox::information(this,tr("Failure"), tr("The public SSH key file could not be copied onto the USB device."));
543  }
544}
545
546void LPMain::menuCloseWindow(){
547  this->close();
548}
549
550// ==== Classic Backups Menu ====
551void LPMain::menuCompressHomeDir(QAction* act){
552  QString user = act->text();
553  qDebug() << "Compress Home Dir:" << user;
554  //Start up the Classic Dialog
555  bool recreate = false;
556  if(classicDLG == 0){ recreate = true; }
557  if(recreate){
558    classicDLG = new LPClassic(this);
559    classicDLG->setHomeDir("/usr/home/"+user);
560    classicDLG->show();
561  }else if(!classicDLG->running){
562    classicDLG->setHomeDir("/usr/home/"+user); //move to the alternate user dir
563  }
564  classicDLG->raise();
565  classicDLG->show();
566  /*
567  //Prompt for the package name
568  QString pkgName = user+"-"+QDateTime::currentDateTime().toString("yyyyMMdd-hhmm");
569  bool ok;
570  pkgName = QInputDialog::getText(this, tr("Package Name"), tr("Name of the package to create:"), QLineEdit::Normal, pkgName, &ok);
571  if(!ok || pkgName.isEmpty() ){ return; } //cancelled
572  //Now create the package
573  showWaitBox(tr("Packaging home directory"));
574  QString pkgPath = LPGUtils::packageHomeDir(user, pkgName);
575  hideWaitBox();
576  //Now inform the user of the result
577  if(pkgPath.isEmpty()){
578    qDebug() << "No Package created";
579    QMessageBox::warning(this,tr("Package Failure"), tr("The home directory package could not be created."));
580  }else{
581    qDebug() << "Package created at:" << pkgPath;
582    QMessageBox::information(this,tr("Package Success"), tr("The home directory package was successfully created.")+"\n\n"+pkgPath);
583  }
584  */
585}
586
587void LPMain::menuExtractHomeDir(){
588  qDebug() << "Extract Home Dir";
589  //Get the file path from the user
590  QString filePath = QFileDialog::getOpenFileName(this,tr("Find Home Dir Package"), "/usr/home", tr("Home Dir Package (*.home.tar.gz)") );
591  if(filePath.isEmpty() || !QFile::exists(filePath)){ return; } //cancelled
592  //Now check if the user in the package is also on the system
593  QString username;
594  bool ok = LPGUtils::checkPackageUserPath(filePath, &username);
595  if(!ok){
596    QMessageBox::warning(this,tr("User Missing"),QString(tr("The user (%1) does not exist on this system. Please create this user first and then try again.")).arg(username) );
597    return;
598  }
599  //Now extract the package
600  showWaitBox(tr("Extracting Home Directory"));
601  ok = LPGUtils::extractHomeDirPackage(filePath);
602  hideWaitBox();
603  //Now report the results
604  if(ok){
605    QMessageBox::information(this,tr("Package Extracted"), QString(tr("The package was successfully extracted within %1")).arg("/usr/home/"+username) );
606  }else{
607    QMessageBox::warning(this, tr("Package Failure"), QString(tr("The package could not be extracted within %1")).arg("/usr/home/"+username) );
608  }
609 
610}
611
612// ==== Disks Menu ====
613void LPMain::menuAddDisk(){
614  QString pool = ui->combo_pools->currentText();
615  //Get the available disks and remove the current disks
616  QStringList adisks = LPGUtils::listAvailableHardDisks();
617  for(int i=0; i<POOLDATA.harddisks.length(); i++){
618    adisks.removeAll( POOLDATA.harddisks[i].section("s",0,0,QString::SectionSkipEmpty) );
619  }
620  if(adisks.isEmpty()){
621    QMessageBox::information(this,tr("Attach New Disk"), tr("No available disks could be found"));
622    return;
623  }
624  //Find a disk that can be added to the system
625  bool ok=false;
626  QString disk = QInputDialog::getItem(this, tr("Attach New Disk"),tr("Detected Disks:"), adisks,0,false, &ok);
627  if( !ok || disk.isEmpty() ){ return; }
628  qDebug() << "Add Disk:" << disk << pool;
629  showWaitBox(tr("Attaching disk"));
630  ok = LPBackend::attachDisk(pool, disk);
631  hideWaitBox();
632  if(ok){
633    QMessageBox::information(this,tr("Disk Attached"),QString(tr("Success: %1 was added to %2")).arg(disk,pool) );
634    QTimer::singleShot(0,this,SLOT(updateTabs()) );
635  }else{
636    QMessageBox::warning(this,tr("Disk Attach Error"),QString(tr("Failure: %1 could not be attached to %2.")).arg(disk,pool) );
637  }     
638}
639
640void LPMain::menuRemoveDisk(QAction *act){
641  QString disk = act->text();
642  QString pool = ui->combo_pools->currentText();
643  //Verify action
644  if(QMessageBox::Yes != QMessageBox::question(this,tr("Verify Disk Removal"),QString(tr("Are you sure that you want to remove %1 from %2?")).arg(disk,pool) + "\n\n" + tr("CAUTION: This disk can only be re-attached later as a brand new disk"), QMessageBox::Yes | QMessageBox::No, QMessageBox::No) ){
645    return; //cancelled
646  }
647  qDebug() << "Remove Disk:" << disk << pool;
648  showWaitBox(tr("Detaching disk"));
649  bool ok = LPBackend::detachDisk(pool, disk);
650  hideWaitBox();
651  if(ok){
652    QMessageBox::information(this,tr("Disk Removal Success"),QString(tr("Success: %1 was removed from %2")).arg(disk, pool) );
653    QTimer::singleShot(0,this,SLOT(updateTabs()) );
654  }else{
655    QMessageBox::warning(this,tr("Disk Removal Failure"),QString(tr("Failure: %1 could not be removed from %2 at this time.")).arg(disk, pool) );
656  }
657}
658
659void LPMain::menuOfflineDisk(QAction *act){
660  QString disk = act->text();
661  QString pool = ui->combo_pools->currentText();
662  //Verify action
663  if(QMessageBox::Yes != QMessageBox::question(this,tr("Verify Disk Offline"),QString(tr("Are you sure you wish to set %1 offline?")).arg(disk), QMessageBox::Yes | QMessageBox::No, QMessageBox::No) ){
664    return; //cancelled
665  }
666  qDebug() << "Offline Disk:" << disk << pool;
667  showWaitBox(tr("Setting disk offline"));
668  bool ok = LPBackend::setDiskOffline(pool, disk);
669  hideWaitBox();
670  if(ok){
671    QMessageBox::information(this,tr("Disk Offline Success"),QString(tr("Success: %1 has been taken offline.")).arg(disk) );
672    QTimer::singleShot(0,this,SLOT(updateTabs()) );
673  }else{
674    QMessageBox::warning(this,tr("Disk Offline Failure"),QString(tr("Failure: %1 could not be taken offline at this time.")).arg(disk) );
675  }
676}
677
678void LPMain::menuOnlineDisk(QAction *act){
679  QString disk = act->text();
680  QString pool = ui->combo_pools->currentText();
681  //Verify action
682  if(QMessageBox::Yes != QMessageBox::question(this,tr("Verify Disk Online"),QString(tr("Are you sure you wish to set %1 online?")).arg(disk), QMessageBox::Yes | QMessageBox::No, QMessageBox::No) ){
683    return; //cancelled
684  }
685  qDebug() << "Online Disk:" << disk << pool;
686  showWaitBox(tr("Setting disk online"));
687  bool ok = LPBackend::setDiskOnline(pool, disk);
688  hideWaitBox();
689  if(ok){
690    QMessageBox::information(this,tr("Disk Online Success"),QString(tr("Success: %1 has been set online.")).arg(disk) );
691    QTimer::singleShot(0,this,SLOT(updateTabs()) );
692  }else{
693    QMessageBox::warning(this,tr("Disk Online Failure"),QString(tr("Failure: %1 could not be set online at this time.")).arg(disk) );
694  }
695}
696
697void LPMain::menuStartScrub(){
698  QString pool = ui->combo_pools->currentText();
699  //Verify starting a scrub
700  if( QMessageBox::Yes != QMessageBox::question(this,tr("Verify Scrub"),QString(tr("Are you sure you want to start a scrub on %1?")).arg(pool) + "\n"+tr("NOTE: This may take quite a while to complete"), QMessageBox::Yes | QMessageBox::No, QMessageBox::No) ){
701    return; //cancelled   
702  }
703  qDebug() << "Start Scrub:" << pool;
704  QString cmd = "zpool scrub "+pool;
705  showWaitBox(tr("Trying to start a scrub"));
706  int ret = system(cmd.toUtf8());
707  hideWaitBox();
708  if(ret == 0){
709    //Now let te user know that one has been triggered
710    QMessageBox::information(this,tr("Scrub Started"),QString(tr("A scrub has just been started on %1")).arg(pool));
711    QTimer::singleShot(0,this,SLOT(updateTabs()) );
712  }else{
713    QMessageBox::warning(this,tr("Scrub Not Started"), QString(tr("A scrub on %1 could not be started at this time.")).arg(pool) + "\n"+tr("Please wait until any current resilvering or scrubs are finished before trying again.") );
714  }
715}
716
717void LPMain::menuStopScrub(){
718  QString pool = ui->combo_pools->currentText();
719  //Verify stopping a scrub
720  if( QMessageBox::Yes != QMessageBox::question(this,tr("Verify Scrub"),QString(tr("Are you sure you want to stop the scrub on %1?")).arg(pool), QMessageBox::Yes | QMessageBox::No, QMessageBox::No) ){
721    return; //cancelled   
722  }
723  qDebug() << "Stop Scrub:" << pool;
724  QString cmd = "zpool scrub -s "+pool;
725  showWaitBox(tr("Trying to stop scrub"));
726  int ret = system(cmd.toUtf8());
727  hideWaitBox();
728  if(ret == 0){
729    //Now let te user know that one has been triggered
730    QMessageBox::information(this,tr("Scrub Stopped"),QString(tr("The scrub on %1 has been stopped.")).arg(pool));
731    QTimer::singleShot(0,this,SLOT(updateTabs()) );
732  }else{
733    QMessageBox::warning(this,tr("Scrub Not Running"), QString(tr("There was no scrub running on %1.")).arg(pool) );
734  }     
735}
736
737// ==== Snapshots Menu ====
738void LPMain::menuNewSnapshot(){
739  qDebug() << "New Snapshot";
740  QString ds = ui->combo_pools->currentText();
741  if(ds.isEmpty()){return; }
742  //Get the new snapshot name from the user
743  bool ok;
744  QString name = QInputDialog::getText(this,tr("New Snapshot Name"), tr("Snapshot Name:"), QLineEdit::Normal, tr("Name"), &ok, 0, Qt::ImhUppercaseOnly | Qt::ImhLowercaseOnly | Qt::ImhDigitsOnly );
745  if(!ok || name.isEmpty()){ return; } //cancelled
746  //Now get the comment
747   QString comment = QInputDialog::getText (this, QObject::tr("Snapshot comment"), QObject::tr("Snapshot comment"), QLineEdit::Normal, tr("GUI Snapshot"), &ok);
748   if (!ok){ comment = tr("GUI Snapshot"); }
749  qDebug() << "Creating a new snapshot:" << ds << name << comment;
750  //Now create the new snapshot
751  LPBackend::newSnapshot(ds,name, comment);
752  QMessageBox::information(this,tr("Snapshot Pending"), tr("The new snapshot creation has been added to the queue"));
753  updateTabs();
754}
755
756void LPMain::menuRemoveSnapshot(QAction *act){
757  QString snapshot = act->text().section(" ", 0, 0);
758  QString comment = act->text().section(" ", 1, -1);
759  QString pool = ui->combo_pools->currentText();
760  qDebug() << "Remove Snapshot:" << snapshot;
761  //verify snapshot removal
762  if( QMessageBox::Yes == QMessageBox::question(this,tr("Verify Snapshot Deletion"),QString(tr("Do you wish to delete this snapshot? %1 (%2)")).arg(pool+"/"+snapshot, comment)+"\n"+tr("WARNING: This is a permanant change that cannot be reversed"),QMessageBox::Yes | QMessageBox::No, QMessageBox::No) ){
763    bool ok = LPBackend::removeSnapshot(ui->combo_pools->currentText(), snapshot);
764    if(ok){
765      QMessageBox::information(this,tr("Snapshot Removed"),tr("The snapshot was successfully deleted"));
766    }else{
767      QMessageBox::information(this,tr("Snapshot Removal Failure"),tr("The snapshot removal experienced an error and it not be completed at this time."));
768    }
769    updateTabs();
770  }
771}
Note: See TracBrowser for help on using the repository browser.