]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/qt-console/joblist/joblist.cpp
Distinct seems to be needed when media is included in the search. Select
[bacula/bacula] / bacula / src / qt-console / joblist / joblist.cpp
1 /*
2    Bacula® - The Network Backup Solution
3
4    Copyright (C) 2000-2007 Free Software Foundation Europe e.V.
5
6    The main author of Bacula is Kern Sibbald, with contributions from
7    many others, a complete list can be found in the file AUTHORS.
8    This program is Free Software; you can redistribute it and/or
9    modify it under the terms of version two of the GNU General Public
10    License as published by the Free Software Foundation plus additions
11    that are listed in the file LICENSE.
12
13    This program is distributed in the hope that it will be useful, but
14    WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16    General Public License for more details.
17
18    You should have received a copy of the GNU General Public License
19    along with this program; if not, write to the Free Software
20    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
21    02110-1301, USA.
22
23    Bacula® is a registered trademark of John Walker.
24    The licensor of Bacula is the Free Software Foundation Europe
25    (FSFE), Fiduciary Program, Sumatrastrasse 25, 8006 Zürich,
26    Switzerland, email:ftf@fsfeurope.org.
27 */
28 /*
29  *   Version $Id: joblist.h 4230 2007-02-21 20:07:37Z kerns $
30  *
31  *   Dirk Bartley, March 2007
32  */
33  
34 #include <QAbstractEventDispatcher>
35 #include <QTableWidgetItem>
36 #include "bat.h"
37 #include "joblist.h"
38 #include "restore.h"
39 #include "joblog/joblog.h"
40
41 /*
42  * Constructor for the class
43  */
44 JobList::JobList(QString &mediaName, QString &clientname,
45          QTreeWidgetItem *parentTreeWidgetItem)
46 {
47    setupUi(this);
48    m_name = "Clients";
49    m_mediaName = mediaName;
50    m_clientName = clientname;
51    pgInitialize(parentTreeWidgetItem);
52    m_resultCount = 0;
53    m_populated = false;
54    m_closeable = false;
55    if ((m_mediaName != "") || (m_clientName != "")) { m_closeable=true; }
56    m_checkCurrentWidget = true;
57    createConnections();
58
59    /* Set Defaults for check and spin for limits */
60    limitCheckBox->setCheckState(Qt::Checked);
61    limitSpinBox->setValue(150);
62    daysCheckBox->setCheckState(Qt::Unchecked);
63    daysSpinBox->setValue(30);
64 }
65
66 /*
67  * The Meat of the class.
68  * This function will populate the QTableWidget, mp_tablewidget, with
69  * QTableWidgetItems representing the results of a query for what jobs exist on
70  * the media name passed from the constructor stored in m_mediaName.
71  */
72 void JobList::populateTable()
73 {
74    QStringList results;
75    QString resultline;
76    QBrush blackBrush(Qt::black);
77
78    /* Can't do this in constructor because not neccesarily conected in constructor */
79    if (!m_populated) {
80       clientsComboBox->addItem("Any");
81       clientsComboBox->addItems(m_console->client_list);
82       int clientIndex = clientsComboBox->findText(m_clientName, Qt::MatchExactly);
83       if (clientIndex != -1)
84          clientsComboBox->setCurrentIndex(clientIndex);
85
86       /* Not m_console->volume_list will query database */
87       QString query("SELECT VolumeName AS Media FROM Media ORDER BY Media");
88       QStringList results, volumeList;
89       if (m_console->sql_cmd(query, results)) {
90          QString field;
91          QStringList fieldlist;
92          /* Iterate through the lines of results. */
93          foreach (QString resultline, results) {
94             fieldlist = resultline.split("\t");
95             volumeList.append(fieldlist[0]);
96          } /* foreach resultline */
97       } /* if results from query */
98       volumeComboBox->addItem("Any");
99       volumeComboBox->addItems(volumeList);
100       int volumeIndex = volumeComboBox->findText(m_mediaName, Qt::MatchExactly);
101       if (volumeIndex != -1) {
102          volumeComboBox->setCurrentIndex(volumeIndex);
103       }
104       jobComboBox->addItem("Any");
105       jobComboBox->addItems(m_console->job_list);
106       levelComboBox->addItem("Any");
107       levelComboBox->addItems( QStringList() << "F" << "D" << "I");
108       purgedComboBox->addItem("Any");
109       purgedComboBox->addItems( QStringList() << "0" << "1");
110       statusComboBox->addItem("Any");
111       QString statusQuery("SELECT JobStatusLong FROM Status");
112       QStringList statusResults, statusLongList;
113       if (m_console->sql_cmd(statusQuery, statusResults)) {
114          QString field;
115          QStringList fieldlist;
116          /* Iterate through the lines of results. */
117          foreach (QString resultline, statusResults) {
118             fieldlist = resultline.split("\t");
119             statusLongList.append(fieldlist[0]);
120          } /* foreach resultline */
121       } /* if results from statusquery */
122       statusComboBox->addItems(statusLongList);
123    }
124
125    /* Set up query */
126    QString query("");
127    int volumeIndex = volumeComboBox->currentIndex();
128    if (volumeIndex != -1)
129       m_mediaName = volumeComboBox->itemText(volumeIndex);
130    query += "SELECT DISTINCT Job.Jobid AS Id, Job.Name AS JobName, Client.Name AS Client,"
131             " Job.Starttime AS JobStart, Job.Type AS JobType,"
132             " Job.Level AS BackupLevel, Job.Jobfiles AS FileCount,"
133             " Job.JobBytes AS Bytes,"
134             " Job.JobStatus AS Status, Status.JobStatusLong AS StatusLong,"
135             " Job.PurgedFiles AS Purged"
136             " FROM Job,Client,Status";
137    if (m_mediaName != "Any") {
138       query += ",JobMedia,Media";
139    }
140    query += " WHERE Client.ClientId=Job.ClientId AND Job.JobStatus=Status.JobStatus";
141    if (m_mediaName != "Any") {
142       query += " AND JobMedia.JobId=Job.JobId AND JobMedia.MediaId=Media.MediaId"
143                " AND Media.VolumeName='" + m_mediaName + "'";
144    }
145    int clientIndex = clientsComboBox->currentIndex();
146    if (clientIndex != -1)
147       m_clientName = clientsComboBox->itemText(clientIndex);
148    if (m_clientName != "Any") {
149       query += " AND Client.Name='" + m_clientName + "'";
150    }
151    int jobIndex = jobComboBox->currentIndex();
152    if ((jobIndex != -1) && (jobComboBox->itemText(jobIndex) != "Any")) {
153       query += " AND Job.Name='" + jobComboBox->itemText(jobIndex) + "'";
154    }
155    int levelIndex = levelComboBox->currentIndex();
156    if ((levelIndex != -1) && (levelComboBox->itemText(levelIndex) != "Any")) {
157       query += " AND Job.Level='" + levelComboBox->itemText(levelIndex) + "'";
158    }
159    int statusIndex = statusComboBox->currentIndex();
160    if ((statusIndex != -1) && (statusComboBox->itemText(statusIndex) != "Any")) {
161       query += " AND Status.JobStatusLong='" + statusComboBox->itemText(statusIndex) + "'";
162    }
163    int purgedIndex = purgedComboBox->currentIndex();
164    if ((purgedIndex != -1) && (purgedComboBox->itemText(purgedIndex) != "Any")) {
165       query += " AND Job.PurgedFiles='" + purgedComboBox->itemText(purgedIndex) + "'";
166    }
167    /* If Limit check box For limit by days is checked  */
168    if (daysCheckBox->checkState() == Qt::Checked) {
169       QDateTime stamp = QDateTime::currentDateTime().addDays(-daysSpinBox->value());
170       QString since = stamp.toString(Qt::ISODate);
171       query += " AND Job.Starttime>'" + since + "'";
172    }
173    /* Descending */
174    query += " ORDER BY Job.Starttime DESC, Job.JobId DESC";
175    /* If Limit check box for limit records returned is checked  */
176    if (limitCheckBox->checkState() == Qt::Checked) {
177       QString limit;
178       limit.setNum(limitSpinBox->value());
179       query += " LIMIT " + limit;
180    }
181
182    /* Set up the Header for the table */
183    QStringList headerlist = (QStringList()
184       << "Job Id" << "Job Name" << "Client" << "Job Starttime" << "Job Type" 
185       << "Job Level" << "Job Files" << "Job Bytes" << "Job Status"  << "Purged" );
186    m_purgedIndex = headerlist.indexOf("Purged");
187    statusIndex = headerlist.indexOf("Job Status");
188
189    /* Initialize the QTableWidget */
190    m_checkCurrentWidget = false;
191    mp_tableWidget->clear();
192    m_checkCurrentWidget = true;
193    mp_tableWidget->setColumnCount(headerlist.size());
194    mp_tableWidget->setHorizontalHeaderLabels(headerlist);
195
196    /*  This could be a user preference debug message?? */
197    //printf("Query cmd : %s\n",query.toUtf8().data());
198    if (m_console->sql_cmd(query, results)) {
199       m_resultCount = results.count();
200
201       QTableWidgetItem* p_tableitem;
202       QString field;
203       QStringList fieldlist;
204       mp_tableWidget->setRowCount(results.size());
205
206       int row = 0;
207       /* Iterate through the record returned from the query */
208       foreach (resultline, results) {
209          fieldlist = resultline.split("\t");
210          int column = 0;
211          bool statusIndexDone = false;
212          QString statusCode("");
213          /* Iterate through fields in the record */
214          foreach (field, fieldlist) {
215             field = field.trimmed();  /* strip leading & trailing spaces */
216             if ((column == statusIndex) && (!statusIndexDone)){
217                statusIndexDone = true;
218                statusCode = field;
219             } else {
220                p_tableitem = new QTableWidgetItem(field,1);
221                p_tableitem->setFlags(0);
222                p_tableitem->setForeground(blackBrush);
223                mp_tableWidget->setItem(row, column, p_tableitem);
224                if (column == statusIndex)
225                   setStatusColor(p_tableitem, statusCode);
226                column++;
227             }
228          }
229          row++;
230       }
231    } 
232    /* Resize the columns */
233    mp_tableWidget->resizeColumnsToContents();
234    mp_tableWidget->resizeRowsToContents();
235    mp_tableWidget->verticalHeader()->hide();
236    if ((m_mediaName != "Any") && (m_resultCount == 0)){
237       /* for context sensitive searches, let the user know if there were no
238        * results */
239       QMessageBox::warning(this, tr("Bat"),
240           tr("The Jobs query returned no results.\n"
241          "Press OK to continue?"), QMessageBox::Ok );
242    }
243 }
244
245 void JobList::setStatusColor(QTableWidgetItem *item, QString &field)
246 {
247    QString greenchars("TCR");
248    QString redchars("BEf");
249    QString yellowchars("eDAFSMmsjdctp");
250    if (greenchars.contains(field, Qt::CaseSensitive)) {
251       item->setBackground(Qt::green);
252    } else if (redchars.contains(field, Qt::CaseSensitive)) {
253       item->setBackground(Qt::red);
254    } else if (yellowchars.contains(field, Qt::CaseSensitive)){ 
255       item->setBackground(Qt::yellow);
256    }
257 }
258
259 /*
260  * When the treeWidgetItem in the page selector tree is singleclicked, Make sure
261  * The tree has been populated.
262  */
263 void JobList::PgSeltreeWidgetClicked()
264 {
265    populateTable();
266    if (!m_populated) {
267       m_populated=true;
268    }
269 }
270
271 /*
272  *  Virtual function override of pages function which is called when this page
273  *  is visible on the stack
274  */
275 void JobList::currentStackItem()
276 {
277    if (!m_populated) {
278       populateTable();
279       m_contextActions.append(actionRefreshJobList);
280       m_populated=true;
281    }
282 }
283
284 /*
285  * Virtual Function to return the name for the medialist tree widget
286  */
287 void JobList::treeWidgetName(QString &desc)
288 {
289    if ((m_mediaName == "") && (m_clientName == "")) {
290       desc = "Jobs";
291    } else {
292       desc = "Jobs ";
293       if (m_mediaName != "" ) {
294          desc += "on Volume " + m_mediaName;
295       }
296       if (m_clientName != "" ) {
297          desc += "of Client " + m_clientName;
298       }
299    }
300 }
301
302 /*
303  * This functions much line tableItemChanged for trees like the page selector,
304  * but I will do much less here
305  */
306 void JobList::tableItemChanged(QTableWidgetItem *currentItem, QTableWidgetItem * /*previousItem*/)
307 {
308    if (m_checkCurrentWidget) {
309       int row = currentItem->row();
310       QTableWidgetItem* jobitem = mp_tableWidget->item(row, 0);
311       m_currentJob = jobitem->text();
312       jobitem = mp_tableWidget->item(row, m_purgedIndex);
313       QString purged = jobitem->text();
314       mp_tableWidget->removeAction(actionPurgeFiles);
315       if (purged == "0") {
316          mp_tableWidget->addAction(actionPurgeFiles);
317       }
318    }
319 }
320
321 /*
322  * Function to create connections for context sensitive menu for this and
323  * the page selector
324  */
325 void JobList::createConnections()
326 {
327    /* connect to the action specific to this pages class that shows up in the 
328     * page selector tree */
329    connect(actionRefreshJobList, SIGNAL(triggered()), this,
330                 SLOT(populateTable()));
331    connect(refreshButton, SIGNAL(pressed()), this, SLOT(populateTable()));
332    /* for the tableItemChanged to maintain m_currentJob */
333    connect(mp_tableWidget, SIGNAL(
334            currentItemChanged(QTableWidgetItem *, QTableWidgetItem *)),
335            this, SLOT(tableItemChanged(QTableWidgetItem *, QTableWidgetItem *)));
336
337    /* Do what is required for the local context sensitive menu */
338
339
340    /* setContextMenuPolicy is required */
341    mp_tableWidget->setContextMenuPolicy(Qt::ActionsContextMenu);
342
343    /* Add Actions */
344    mp_tableWidget->addAction(actionRefreshJobList);
345    mp_tableWidget->addAction(actionLongListJob);
346    mp_tableWidget->addAction(actionListJobid);
347    mp_tableWidget->addAction(actionListFilesOnJob);
348    mp_tableWidget->addAction(actionListJobMedia);
349    mp_tableWidget->addAction(actionListVolumes);
350    mp_tableWidget->addAction(actionDeleteJob);
351    mp_tableWidget->addAction(actionPurgeFiles);
352    mp_tableWidget->addAction(actionRestoreFromJob);
353    mp_tableWidget->addAction(actionRestoreFromTime);
354    mp_tableWidget->addAction(actionShowLogForJob);
355
356    /* Make Connections */
357    connect(actionLongListJob, SIGNAL(triggered()), this,
358                 SLOT(consoleLongListJob()));
359    connect(actionListJobid, SIGNAL(triggered()), this,
360                 SLOT(consoleListJobid()));
361    connect(actionListFilesOnJob, SIGNAL(triggered()), this,
362                 SLOT(consoleListFilesOnJob()));
363    connect(actionListJobMedia, SIGNAL(triggered()), this,
364                 SLOT(consoleListJobMedia()));
365    connect(actionListVolumes, SIGNAL(triggered()), this,
366                 SLOT(consoleListVolumes()));
367    connect(actionDeleteJob, SIGNAL(triggered()), this,
368                 SLOT(consoleDeleteJob()));
369    connect(actionPurgeFiles, SIGNAL(triggered()), this,
370                 SLOT(consolePurgeFiles()));
371    connect(actionRestoreFromJob, SIGNAL(triggered()), this,
372                 SLOT(preRestoreFromJob()));
373    connect(actionRestoreFromTime, SIGNAL(triggered()), this,
374                 SLOT(preRestoreFromTime()));
375    connect(actionShowLogForJob, SIGNAL(triggered()), this,
376                 SLOT(showLogForJob()));
377 }
378
379 /*
380  * Functions to respond to local context sensitive menu sending console commands
381  * If I could figure out how to make these one function passing a string, Yaaaaaa
382  */
383 void JobList::consoleLongListJob()
384 {
385    QString cmd("llist jobid=");
386    cmd += m_currentJob;
387    consoleCommand(cmd);
388 }
389 void JobList::consoleListJobid()
390 {
391    QString cmd("list jobid=");
392    cmd += m_currentJob;
393    consoleCommand(cmd);
394 }
395 void JobList::consoleListFilesOnJob()
396 {
397    QString cmd("list files jobid=");
398    cmd += m_currentJob;
399    consoleCommand(cmd);
400 }
401 void JobList::consoleListJobMedia()
402 {
403    QString cmd("list jobmedia jobid=");
404    cmd += m_currentJob;
405    consoleCommand(cmd);
406 }
407 void JobList::consoleListVolumes()
408 {
409    QString cmd("list volumes jobid=");
410    cmd += m_currentJob;
411    consoleCommand(cmd);
412 }
413 void JobList::consoleDeleteJob()
414 {
415    if (QMessageBox::warning(this, tr("Bat"),
416       tr("Are you sure you want to delete??  !!!.\n"
417 "This delete command is used to delete a Job record and all associated catalog"
418 " records that were created. This command operates only on the Catalog"
419 " database and has no effect on the actual data written to a Volume. This"
420 " command can be dangerous and we strongly recommend that you do not use"
421 " it unless you know what you are doing.  The Job and all its associated"
422 " records (File and JobMedia) will be deleted from the catalog."
423       "Press OK to proceed with delete operation.?"),
424       QMessageBox::Ok | QMessageBox::Cancel)
425       == QMessageBox::Cancel) { return; }
426
427    QString cmd("delete job jobid=");
428    cmd += m_currentJob;
429    consoleCommand(cmd);
430 }
431 void JobList::consolePurgeFiles()
432 {
433    if (QMessageBox::warning(this, tr("Bat"),
434       tr("Are you sure you want to purge ??  !!!.\n"
435 "The Purge command will delete associated Catalog database records from Jobs and"
436 " Volumes without considering the retention period. Purge  works only on the"
437 " Catalog database and does not affect data written to Volumes. This command can"
438 " be dangerous because you can delete catalog records associated with current"
439 " backups of files, and we recommend that you do not use it unless you know what"
440 " you are doing.\n"
441       "Press OK to proceed with the purge operation?"),
442       QMessageBox::Ok | QMessageBox::Cancel)
443       == QMessageBox::Cancel) { return; }
444
445    QString cmd("purge files jobid=");
446    cmd += m_currentJob;
447    consoleCommand(cmd);
448 }
449
450 /*
451  * Subroutine to call preRestore to restore from a select job
452  */
453 void JobList::preRestoreFromJob()
454 {
455    new prerestorePage(m_currentJob, R_JOBIDLIST);
456 }
457
458 /*
459  * Subroutine to call preRestore to restore from a select job
460  */
461 void JobList::preRestoreFromTime()
462 {
463    new prerestorePage(m_currentJob, R_JOBDATETIME);
464 }
465
466 /*
467  * Subroutine to call class to show the log in the database from that job
468  */
469 void JobList::showLogForJob()
470 {
471    QTreeWidgetItem* pageSelectorTreeWidgetItem = mainWin->getFromHash(this);
472    new JobLog(m_currentJob, pageSelectorTreeWidgetItem);
473 }