File: bupjob.cpp

package info (click to toggle)
kup-backup 0.10.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,576 kB
  • sloc: cpp: 8,422; xml: 311; makefile: 6; sh: 3
file content (354 lines) | stat: -rw-r--r-- 14,970 bytes parent folder | download
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
// SPDX-FileCopyrightText: 2020 Simon Persson <simon.persson@mykolab.com>
//
// SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL

#include "bupjob.h"
#include "kupdaemon_debug.h"

#include <KLocalizedString>

#include <QFileInfo>
#include <QThread>

#include <csignal>

BupJob::BupJob(BackupPlan &pBackupPlan, const QString &pDestinationPath, const QString &pLogFilePath, KupDaemon *pKupDaemon)
    : BackupJob(pBackupPlan, pDestinationPath, pLogFilePath, pKupDaemon)
{
    mFsckProcess.setOutputChannelMode(KProcess::SeparateChannels);
    mIndexProcess.setOutputChannelMode(KProcess::SeparateChannels);
    mSaveProcess.setOutputChannelMode(KProcess::SeparateChannels);
    mPar2Process.setOutputChannelMode(KProcess::SeparateChannels);
    setCapabilities(KJob::Suspendable);
    mHarmlessErrorCount = 0;
    mAllErrorsHarmless = false;
    mLineBreaksRegExp = QRegularExpression(QStringLiteral("\n|\r"));
    mLineBreaksRegExp.optimize();
    mNonsenseRegExp = QRegularExpression(QStringLiteral("^(?:Reading index|bloom|midx)"));
    mNonsenseRegExp.optimize();
    mFileGoneRegExp = QRegularExpression(QStringLiteral("\\[Errno 2\\]"));
    mFileGoneRegExp.optimize();
    mProgressRegExp = QRegularExpression(QStringLiteral("(\\d+)/(\\d+)k, (\\d+)/(\\d+) files\\) \\S* (?:(\\d+)k/s|)"));
    mProgressRegExp.optimize();
    mErrorCountRegExp = QRegularExpression(QStringLiteral("^WARNING: (\\d+) errors encountered while saving."));
    mErrorCountRegExp.optimize();
    mFileInfoRegExp = QRegularExpression(QStringLiteral("^(?: |A|M) \\/"));
    mFileInfoRegExp.optimize();
}

void BupJob::performJob()
{
    KProcess lPar2Process;
    lPar2Process.setOutputChannelMode(KProcess::SeparateChannels);
    lPar2Process << QStringLiteral("bup") << QStringLiteral("fsck") << QStringLiteral("--par2-ok");
    int lExitCode = lPar2Process.execute();
    if (lExitCode < 0) {
        jobFinishedError(ErrorWithoutLog,
                         xi18nc("@info notification",
                                "The <application>bup</application> program is "
                                "needed but could not be found, maybe it is not installed?"));
        return;
    }
    if (mBackupPlan.mGenerateRecoveryInfo && lExitCode != 0) {
        jobFinishedError(ErrorWithoutLog,
                         xi18nc("@info notification",
                                "The <application>par2</application> program is "
                                "needed but could not be found, maybe it is not installed?"));
        return;
    }

    mLogStream << QStringLiteral("Kup is starting bup backup job at ") << QLocale().toString(QDateTime::currentDateTime()) << Qt::endl << Qt::endl;

    KProcess lInitProcess;
    lInitProcess.setOutputChannelMode(KProcess::SeparateChannels);
    lInitProcess << QStringLiteral("bup");
    lInitProcess << QStringLiteral("-d") << mDestinationPath;
    lInitProcess << QStringLiteral("init");
    mLogStream << quoteArgs(lInitProcess.program()) << Qt::endl;
    if (lInitProcess.execute() != 0) {
        mLogStream << QString::fromUtf8(lInitProcess.readAllStandardError()) << Qt::endl;
        mLogStream << QStringLiteral(
            "Kup did not successfully complete the bup backup job: "
            "failed to initialize backup destination.")
                   << Qt::endl;
        jobFinishedError(ErrorWithLog,
                         xi18nc("@info notification",
                                "Backup destination could not be initialised. "
                                "See log file for more details."));
        return;
    }

    if (mBackupPlan.mCheckBackups) {
        mFsckProcess << QStringLiteral("bup");
        mFsckProcess << QStringLiteral("-d") << mDestinationPath;
        mFsckProcess << QStringLiteral("fsck") << QStringLiteral("--quick");
        mFsckProcess << QStringLiteral("-j") << QString::number(qMin(4, QThread::idealThreadCount()));

        connect(&mFsckProcess, qOverload<int, QProcess::ExitStatus>(&QProcess::finished), this, &BupJob::slotCheckingDone);
        connect(&mFsckProcess, &KProcess::started, this, &BupJob::slotCheckingStarted);
        mLogStream << quoteArgs(mFsckProcess.program()) << Qt::endl;
        mFsckProcess.start();
        mInfoRateLimiter.start();
    } else {
        startIndexing();
    }
}

void BupJob::slotCheckingStarted()
{
    makeNice(mFsckProcess.processId());
    emit description(this, i18n("Checking backup integrity"));
}

void BupJob::slotCheckingDone(int pExitCode, QProcess::ExitStatus pExitStatus)
{
    QString lErrors = QString::fromUtf8(mFsckProcess.readAllStandardError());
    if (!lErrors.isEmpty()) {
        mLogStream << lErrors << Qt::endl;
    }
    mLogStream << "Exit code: " << pExitCode << Qt::endl;
    if (pExitStatus != QProcess::NormalExit || pExitCode != 0) {
        mLogStream << QStringLiteral(
            "Kup did not successfully complete the bup backup job: "
            "failed integrity check. Your backups could be "
            "corrupted! See above for details.")
                   << Qt::endl;
        if (mBackupPlan.mGenerateRecoveryInfo) {
            jobFinishedError(ErrorSuggestRepair,
                             xi18nc("@info notification",
                                    "Failed backup integrity check. Your backups could be corrupted! "
                                    "See log file for more details. Do you want to try repairing the backup files?"));
        } else {
            jobFinishedError(ErrorWithLog,
                             xi18nc("@info notification",
                                    "Failed backup integrity check. Your backups could be corrupted! "
                                    "See log file for more details."));
        }
        return;
    }
    startIndexing();
}

void BupJob::startIndexing()
{
    mIndexProcess << QStringLiteral("bup");
    mIndexProcess << QStringLiteral("-d") << mDestinationPath;
    mIndexProcess << QStringLiteral("index") << QStringLiteral("-u");

    foreach (QString lExclude, mBackupPlan.mPathsExcluded) {
        mIndexProcess << QStringLiteral("--exclude");
        mIndexProcess << lExclude;
    }
    QString lExcludesPath = mBackupPlan.absoluteExcludesFilePath();
    if (mBackupPlan.mExcludePatterns && QFileInfo::exists(lExcludesPath)) {
        mIndexProcess << QStringLiteral("--exclude-rx-from") << lExcludesPath;
    }
    mIndexProcess << mBackupPlan.mPathsIncluded;

    connect(&mIndexProcess, qOverload<int, QProcess::ExitStatus>(&QProcess::finished), this, &BupJob::slotIndexingDone);
    connect(&mIndexProcess, &KProcess::started, this, &BupJob::slotIndexingStarted);
    mLogStream << quoteArgs(mIndexProcess.program()) << Qt::endl;
    mIndexProcess.start();
}

void BupJob::slotIndexingStarted()
{
    makeNice(mIndexProcess.processId());
    emit description(this, i18n("Checking what to copy"));
}

void BupJob::slotIndexingDone(int pExitCode, QProcess::ExitStatus pExitStatus)
{
    QString lErrors = QString::fromUtf8(mIndexProcess.readAllStandardError());
    if (!lErrors.isEmpty()) {
        mLogStream << lErrors << Qt::endl;
    }
    mLogStream << "Exit code: " << pExitCode << Qt::endl;
    if (pExitStatus != QProcess::NormalExit || pExitCode != 0) {
        mLogStream << QStringLiteral("Kup did not successfully complete the bup backup job: failed to index everything.") << Qt::endl;
        jobFinishedError(ErrorWithLog,
                         xi18nc("@info notification",
                                "Failed to analyze files. "
                                "See log file for more details."));
        return;
    }
    mSaveProcess << QStringLiteral("bup");
    mSaveProcess << QStringLiteral("-d") << mDestinationPath;
    mSaveProcess << QStringLiteral("save");
    mSaveProcess << QStringLiteral("-n") << QStringLiteral("kup") << QStringLiteral("-vv");
    mSaveProcess << mBackupPlan.mPathsIncluded;
    mLogStream << quoteArgs(mSaveProcess.program()) << Qt::endl;

    connect(&mSaveProcess, qOverload<int, QProcess::ExitStatus>(&QProcess::finished), this, &BupJob::slotSavingDone);
    connect(&mSaveProcess, &KProcess::started, this, &BupJob::slotSavingStarted);
    connect(&mSaveProcess, &KProcess::readyReadStandardError, this, &BupJob::slotReadBupErrors);

    mSaveProcess.setEnv(QStringLiteral("BUP_FORCE_TTY"), QStringLiteral("2"));
    mSaveProcess.start();
}

void BupJob::slotSavingStarted()
{
    makeNice(mSaveProcess.processId());
    emit description(this, i18n("Saving backup"));
}

void BupJob::slotSavingDone(int pExitCode, QProcess::ExitStatus pExitStatus)
{
    slotReadBupErrors();
    mLogStream << "Exit code: " << pExitCode << Qt::endl;
    if (pExitStatus != QProcess::NormalExit || pExitCode != 0) {
        if (mAllErrorsHarmless) {
            mLogStream << QStringLiteral("Only harmless errors detected by Kup.") << Qt::endl;
        } else {
            mLogStream << QStringLiteral(
                "Kup did not successfully complete the bup backup job: "
                "failed to save everything.")
                       << Qt::endl;
            jobFinishedError(ErrorWithLog,
                             xi18nc("@info notification",
                                    "Failed to save backup. "
                                    "See log file for more details."));
            return;
        }
    }
    if (mBackupPlan.mGenerateRecoveryInfo) {
        mPar2Process << QStringLiteral("bup");
        mPar2Process << QStringLiteral("-d") << mDestinationPath;
        mPar2Process << QStringLiteral("fsck") << QStringLiteral("-g");
        mPar2Process << QStringLiteral("-j") << QString::number(qMin(4, QThread::idealThreadCount()));

        connect(&mPar2Process, qOverload<int, QProcess::ExitStatus>(&QProcess::finished), this, &BupJob::slotRecoveryInfoDone);
        connect(&mPar2Process, &KProcess::started, this, &BupJob::slotRecoveryInfoStarted);
        mLogStream << quoteArgs(mPar2Process.program()) << Qt::endl;
        mPar2Process.start();
    } else {
        mLogStream << QStringLiteral("Kup successfully completed the bup backup job at ") << QLocale().toString(QDateTime::currentDateTime()) << Qt::endl;
        jobFinishedSuccess();
    }
}

void BupJob::slotRecoveryInfoStarted()
{
    makeNice(mPar2Process.processId());
    emit description(this, i18n("Generating recovery information"));
}

void BupJob::slotRecoveryInfoDone(int pExitCode, QProcess::ExitStatus pExitStatus)
{
    QString lErrors = QString::fromUtf8(mPar2Process.readAllStandardError());
    if (!lErrors.isEmpty()) {
        mLogStream << lErrors << Qt::endl;
    }
    mLogStream << "Exit code: " << pExitCode << Qt::endl;
    if (pExitStatus != QProcess::NormalExit || pExitCode != 0) {
        mLogStream << QStringLiteral(
            "Kup did not successfully complete the bup backup job: "
            "failed to generate recovery info.")
                   << Qt::endl;
        jobFinishedError(ErrorWithLog,
                         xi18nc("@info notification",
                                "Failed to generate recovery info for the backup. "
                                "See log file for more details."));
    } else {
        mLogStream << QStringLiteral("Kup successfully completed the bup backup job.") << Qt::endl;
        jobFinishedSuccess();
    }
}

void BupJob::slotReadBupErrors()
{
    qulonglong lCopiedKBytes = 0, lTotalKBytes = 0, lCopiedFiles = 0, lTotalFiles = 0;
    ulong lSpeedKBps = 0, lPercent = 0;
    QString lFileName;
    const auto lInput = QString::fromUtf8(mSaveProcess.readAllStandardError());
#if QT_VERSION < QT_VERSION_CHECK(5, 14, 0)
    const auto lLines = lInput.split(mLineBreaksRegExp, QString::SkipEmptyParts);
#else
    const auto lLines = lInput.split(mLineBreaksRegExp, Qt::SkipEmptyParts);
#endif
    for (const QString &lLine : lLines) {
        qCDebug(KUPDAEMON) << lLine;
        if (mNonsenseRegExp.match(lLine).hasMatch()) {
            continue;
        }
        if (mFileGoneRegExp.match(lLine).hasMatch()) {
            mHarmlessErrorCount++;
            mLogStream << lLine << Qt::endl;
            continue;
        }
        const auto lCountMatch = mErrorCountRegExp.match(lLine);
        if (lCountMatch.hasMatch()) {
            mAllErrorsHarmless = lCountMatch.captured(1).toInt() == mHarmlessErrorCount;
            mLogStream << lLine << Qt::endl;
            continue;
        }
        const auto lProgressMatch = mProgressRegExp.match(lLine);
        if (lProgressMatch.hasMatch()) {
            lCopiedKBytes = lProgressMatch.captured(1).toULongLong();
            lTotalKBytes = lProgressMatch.captured(2).toULongLong();
            lCopiedFiles = lProgressMatch.captured(3).toULongLong();
            lTotalFiles = lProgressMatch.captured(4).toULongLong();
            lSpeedKBps = lProgressMatch.captured(5).toULong();
            if (lTotalKBytes != 0) {
                lPercent = qMax(100 * lCopiedKBytes / lTotalKBytes, static_cast<qulonglong>(1));
            }
            continue;
        }
        if (mFileInfoRegExp.match(lLine).hasMatch()) {
            lFileName = lLine.mid(2);
            continue;
        }
        if (!lLine.startsWith(QStringLiteral("D /"))) {
            mLogStream << lLine << Qt::endl;
        }
    }
    if (mInfoRateLimiter.hasExpired(200)) {
        if (lTotalFiles != 0) {
            setPercent(lPercent);
            setTotalAmount(KJob::Bytes, lTotalKBytes * 1024);
            setTotalAmount(KJob::Files, lTotalFiles);
            setProcessedAmount(KJob::Bytes, lCopiedKBytes * 1024);
            setProcessedAmount(KJob::Files, lCopiedFiles);
            emitSpeed(lSpeedKBps * 1024);
        }
        if (!lFileName.isEmpty()) {
            emit description(this, i18n("Saving backup"), qMakePair(i18nc("Label for file currently being copied", "File"), lFileName));
        }
        mInfoRateLimiter.start();
    }
}

bool BupJob::doSuspend()
{
    if (mFsckProcess.state() == KProcess::Running) {
        return 0 == ::kill(mFsckProcess.processId(), SIGSTOP);
    }
    if (mIndexProcess.state() == KProcess::Running) {
        return 0 == ::kill(mIndexProcess.processId(), SIGSTOP);
    }
    if (mSaveProcess.state() == KProcess::Running) {
        return 0 == ::kill(mSaveProcess.processId(), SIGSTOP);
    }
    if (mPar2Process.state() == KProcess::Running) {
        return 0 == ::kill(mPar2Process.processId(), SIGSTOP);
    }
    return false;
}

bool BupJob::doResume()
{
    if (mFsckProcess.state() == KProcess::Running) {
        return 0 == ::kill(mFsckProcess.processId(), SIGCONT);
    }
    if (mIndexProcess.state() == KProcess::Running) {
        return 0 == ::kill(mIndexProcess.processId(), SIGCONT);
    }
    if (mSaveProcess.state() == KProcess::Running) {
        return 0 == ::kill(mSaveProcess.processId(), SIGCONT);
    }
    if (mPar2Process.state() == KProcess::Running) {
        return 0 == ::kill(mPar2Process.processId(), SIGCONT);
    }
    return false;
}