LeechCraft  0.6.70-13729-g7046a9d2a7
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 LC
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 QString checkQuery = qgetenv ("LC_THOROUGH_SQLITE_CHECK") == "1" ?
109  "PRAGMA integrity_check;" :
110  "PRAGMA quick_check;";
111  const auto isGood = pragma.exec (checkQuery) &&
112  pragma.next () &&
113  pragma.value (0) == "ok";
114  qDebug () << Q_FUNC_INFO
115  << "done checking"
116  << DBPath_
117  << "; result is:"
118  << isGood;
119  if (isGood)
120  return Succeeded {};
121  else
122  return std::make_shared<FailedImpl> (shared_from_this ());
123  }
124 
125  QFuture<ConsistencyChecker::DumpResult_t> ConsistencyChecker::DumpReinit ()
126  {
128  iface.reportStarted ();
129 
130  DumpReinitImpl (iface);
131 
132  return iface.future ();
133  }
134 
135  namespace
136  {
138  const ConsistencyChecker::DumpResult_t& result)
139  {
140  iface.reportFinished (&result);
141  }
142  }
143 
144  void ConsistencyChecker::DumpReinitImpl (QFutureInterface<DumpResult_t> iface)
145  {
146  const QFileInfo fi { DBPath_ };
147  const auto filesize = fi.size ();
148 
149  while (true)
150  {
151  const auto available = GetSpaceInfo (DBPath_).Available_;
152 
153  qDebug () << Q_FUNC_INFO
154  << "db size:" << filesize
155  << "free space:" << available;
156  if (available >= static_cast<quint64> (filesize))
157  break;
158 
159  if (QMessageBox::question (nullptr,
160  DialogContext_,
161  tr ("Not enough available space on partition with file %1: "
162  "%2 while the restored file is expected to be around %3. "
163  "Please either free some disk space on this partition "
164  "and retry or cancel the restore process.")
165  .arg ("<em>" + DBPath_ + "</em>")
166  .arg (Util::MakePrettySize (available))
167  .arg (Util::MakePrettySize (filesize)),
168  QMessageBox::Retry | QMessageBox::Cancel) == QMessageBox::Cancel)
169  {
170  ReportResult (iface, DumpError { tr ("Not enough available disk space.") });
171  return;
172  }
173  }
174 
175  const auto& newPath = DBPath_ + ".new";
176 
177  while (true)
178  {
179  if (!QFile::exists (newPath))
180  break;
181 
182  if (QMessageBox::question (nullptr,
183  DialogContext_,
184  tr ("%1 already exists. Please either remove the file manually "
185  "and retry or cancel the restore process.")
186  .arg ("<em>" + newPath + "</em>"),
187  QMessageBox::Retry | QMessageBox::Cancel) == QMessageBox::Cancel)
188  {
189  ReportResult (iface, DumpError { tr ("Backup file already exists.") });
190  return;
191  }
192  }
193 
194  const auto dumper = new Dumper { DBPath_, newPath };
195 
196  const auto managed = shared_from_this ();
197  Util::Sequence (nullptr, dumper->GetFuture ()) >>
198  [iface, newPath, managed] (const Dumper::Result_t& result)
199  {
200  Util::Visit (result,
201  [iface] (const Dumper::Error& error)
202  {
203  ReportResult (iface,
204  DumpError { tr ("Unable to restore the database.") + " " + error.What_ });
205  },
206  [iface, newPath, managed] (const Dumper::Finished&) { managed->HandleDumperFinished (iface, newPath); });
207  };
208  }
209 
210  void ConsistencyChecker::HandleDumperFinished (QFutureInterface<DumpResult_t> iface, const QString& to)
211  {
212  const auto oldSize = QFileInfo { DBPath_ }.size ();
213  const auto newSize = QFileInfo { to }.size ();
214 
215  const auto& backup = DBPath_ + ".bak";
216  while (!QFile::rename (DBPath_, backup))
217  QMessageBox::critical (nullptr,
218  DialogContext_,
219  tr ("Unable to backup %1 to %2. Please remove %2 and hit OK.")
220  .arg (DBPath_)
221  .arg (backup));
222 
223  QFile::rename (to, DBPath_);
224 
225  ReportResult (iface, DumpFinished { oldSize, newSize });
226  }
227 }
228 }
SpaceInfo GetSpaceInfo(const QString &path)
Returns the disk space info of the partition containing path.
Definition: paths.cpp:176
static std::shared_ptr< ConsistencyChecker > Create(const QString &dbPath, const QString &dialogContext)
std::variant< Succeeded, Failed > CheckResult_t
auto Visit(const Either< Left, Right > &either, Args &&... args)
Definition: either.h:224
FailedImpl(const std::shared_ptr< ConsistencyChecker > &checker)
std::variant< Finished, Error > Result_t
Definition: dumper.h:62
QFuture< CheckResult_t > StartCheck()
UTIL_API QString MakePrettySize(qint64 sourceSize)
Makes a formatted size from number.
Definition: util.cpp:109
quint64 Available_
How much space is available to the current user.
Definition: paths.h:225
std::variant< DumpFinished, DumpError > DumpResult_t
Definition: constants.h:35
QString GenConnectionName(const QString &base)
Generates an unique thread-safe connection name.
Definition: util.cpp:103