LeechCraft  0.6.70-10870-g558588d6ec
Modular cross-platform feature rich live environment.
consistencychecker.cpp
Go to the documentation of this file.
1 /**********************************************************************
2  * LeechCraft - modular cross-platform feature rich internet client.
3  * Copyright (C) 2006-2014 Georg Rudoy
4  *
5  * Boost Software License - Version 1.0 - August 17th, 2003
6  *
7  * Permission is hereby granted, free of charge, to any person or organization
8  * obtaining a copy of the software and accompanying documentation covered by
9  * this license (the "Software") to use, reproduce, display, distribute,
10  * execute, and transmit the Software, and to prepare derivative works of the
11  * Software, and to permit third-parties to whom the Software is furnished to
12  * do so, all subject to the following:
13  *
14  * The copyright notices in the Software and this entire statement, including
15  * the above license grant, this restriction and the following disclaimer,
16  * must be included in all copies of the Software, in whole or in part, and
17  * all derivative works of the Software, unless such copies or derivative
18  * works are solely in the form of machine-executable object code generated by
19  * a source language processor.
20  *
21  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
22  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
23  * FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
24  * SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
25  * FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
26  * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
27  * DEALINGS IN THE SOFTWARE.
28  **********************************************************************/
29 
30 #include "consistencychecker.h"
31 #include <memory>
32 #include <QFile>
33 #include <QSqlDatabase>
34 #include <QMessageBox>
35 #include <QtConcurrentRun>
36 #include <util/sll/slotclosure.h>
37 #include <util/sll/visitor.h>
38 #include <util/sys/paths.h>
39 #include <util/threads/futures.h>
40 #include <util/util.h>
41 #include "dumper.h"
42 #include "util.h"
43 
44 namespace LeechCraft
45 {
46 namespace Util
47 {
49  {
50  const std::shared_ptr<ConsistencyChecker> Checker_;
51  public:
52  FailedImpl (const std::shared_ptr<ConsistencyChecker>& checker)
53  : Checker_ { checker }
54  {
55  }
56  private:
57  QFuture<ConsistencyChecker::DumpResult_t> DumpReinit () override
58  {
59  return Checker_->DumpReinit ();
60  }
61  };
62 
63  ConsistencyChecker::ConsistencyChecker (const QString& dbPath,
64  const QString& dialogContext, QObject *parent)
65  : QObject { parent }
66  , DBPath_ { dbPath }
67  , DialogContext_ { dialogContext }
68  {
69  }
70 
71  std::shared_ptr<ConsistencyChecker> ConsistencyChecker::Create (const QString& dbPath, const QString& dialogContext)
72  {
73  return std::shared_ptr<ConsistencyChecker> { new ConsistencyChecker { dbPath, dialogContext } };
74  }
75 
77  {
78  const auto managed = shared_from_this ();
79  return QtConcurrent::run ([managed] { return managed->CheckDB (); });
80  }
81 
82  ConsistencyChecker::CheckResult_t ConsistencyChecker::CheckDB ()
83  {
84  qDebug () << Q_FUNC_INFO
85  << "checking"
86  << DBPath_;
87  const auto& connName = Util::GenConnectionName ("ConsistencyChecker_" + DBPath_);
88 
89  std::shared_ptr<QSqlDatabase> db
90  {
91  new QSqlDatabase { QSqlDatabase::addDatabase ("QSQLITE", connName) },
92  [connName] (QSqlDatabase *db)
93  {
94  delete db;
95  QSqlDatabase::removeDatabase (connName);
96  }
97  };
98 
99  db->setDatabaseName (DBPath_);
100  if (!db->open ())
101  {
102  qWarning () << Q_FUNC_INFO
103  << "cannot open the DB, but that's not the kind of errors we're solving.";
104  return Succeeded {};
105  }
106 
107  QSqlQuery pragma { *db };
108  const auto isGood = pragma.exec ("PRAGMA integrity_check;") &&
109  pragma.next () &&
110  pragma.value (0) == "ok";
111  qDebug () << Q_FUNC_INFO
112  << "done checking"
113  << DBPath_
114  << "; result is:"
115  << isGood;
116  if (isGood)
117  return Succeeded {};
118  else
119  return std::make_shared<FailedImpl> (shared_from_this ());
120  }
121 
122  QFuture<ConsistencyChecker::DumpResult_t> ConsistencyChecker::DumpReinit ()
123  {
125  iface.reportStarted ();
126 
127  DumpReinitImpl (iface);
128 
129  return iface.future ();
130  }
131 
132  namespace
133  {
135  const ConsistencyChecker::DumpResult_t& result)
136  {
137  iface.reportFinished (&result);
138  }
139  }
140 
141  void ConsistencyChecker::DumpReinitImpl (QFutureInterface<DumpResult_t> iface)
142  {
143  const QFileInfo fi { DBPath_ };
144  const auto filesize = fi.size ();
145 
146  while (true)
147  {
148  const auto available = GetSpaceInfo (DBPath_).Available_;
149 
150  qDebug () << Q_FUNC_INFO
151  << "db size:" << filesize
152  << "free space:" << available;
153  if (available >= static_cast<quint64> (filesize))
154  break;
155 
156  if (QMessageBox::question (nullptr,
157  DialogContext_,
158  tr ("Not enough available space on partition with file %1: "
159  "%2 while the restored file is expected to be around %3. "
160  "Please either free some disk space on this partition "
161  "and retry or cancel the restore process.")
162  .arg ("<em>" + DBPath_ + "</em>")
163  .arg (Util::MakePrettySize (available))
164  .arg (Util::MakePrettySize (filesize)),
165  QMessageBox::Retry | QMessageBox::Cancel) == QMessageBox::Cancel)
166  {
167  ReportResult (iface, DumpError { tr ("Not enough available disk space.") });
168  return;
169  }
170  }
171 
172  const auto& newPath = DBPath_ + ".new";
173 
174  while (true)
175  {
176  if (!QFile::exists (newPath))
177  break;
178 
179  if (QMessageBox::question (nullptr,
180  DialogContext_,
181  tr ("%1 already exists. Please either remove the file manually "
182  "and retry or cancel the restore process.")
183  .arg ("<em>" + newPath + "</em>"),
184  QMessageBox::Retry | QMessageBox::Cancel) == QMessageBox::Cancel)
185  {
186  ReportResult (iface, DumpError { tr ("Backup file already exists.") });
187  return;
188  }
189  }
190 
191  const auto dumper = new Dumper { DBPath_, newPath };
192 
193  const auto managed = shared_from_this ();
194  Util::Sequence (nullptr, dumper->GetFuture ()) >>
195  [iface, newPath, managed] (const Dumper::Result_t& result)
196  {
197  Util::Visit (result,
198  [iface] (const Dumper::Error& error)
199  {
200  ReportResult (iface,
201  DumpError { tr ("Unable to restore the database.") + " " + error.What_ });
202  },
203  [iface, newPath, managed] (const Dumper::Finished&) { managed->HandleDumperFinished (iface, newPath); });
204  };
205  }
206 
207  void ConsistencyChecker::HandleDumperFinished (QFutureInterface<DumpResult_t> iface, const QString& to)
208  {
209  const auto oldSize = QFileInfo { DBPath_ }.size ();
210  const auto newSize = QFileInfo { to }.size ();
211 
212  const auto& backup = DBPath_ + ".bak";
213  while (!QFile::rename (DBPath_, backup))
214  QMessageBox::critical (nullptr,
215  DialogContext_,
216  tr ("Unable to backup %1 to %2. Please remove %2 and hit OK.")
217  .arg (DBPath_)
218  .arg (backup));
219 
220  QFile::rename (to, DBPath_);
221 
222  ReportResult (iface, DumpFinished { oldSize, newSize });
223  }
224 }
225 }
UTIL_API QString MakePrettySize(qint64 sourceSize)
Makes a formatted size from number.
Definition: util.cpp:109
FailedImpl(const std::shared_ptr< ConsistencyChecker > &checker)
QString GenConnectionName(const QString &base)
Generates an unique thread-safe connection name.
Definition: util.cpp:106
quint64 Available_
How much space is available to the current user.
Definition: paths.h:225
QFuture< CheckResult_t > StartCheck()
boost::variant< Succeeded, Failed > CheckResult_t
boost::variant< Finished, Error > Result_t
Definition: dumper.h:62
boost::variant< DumpFinished, DumpError > DumpResult_t
auto Visit(const Either< Left, Right > &either, Args &&... args)
Definition: either.h:209
static std::shared_ptr< ConsistencyChecker > Create(const QString &dbPath, const QString &dialogContext)
SpaceInfo GetSpaceInfo(const QString &path)
Returns the disk space info of the partition containing path.
Definition: paths.cpp:176